io.fabric8.kubernetes.api.model.ServiceAccount Java Examples

The following examples show how to use io.fabric8.kubernetes.api.model.ServiceAccount. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ApplyService.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Creates/updates a service account and processes it returning the processed DTOs
 */
public void applyServiceAccount(ServiceAccount serviceAccount, String sourceName) throws Exception {
    String namespace = getNamespace();
    String id = getName(serviceAccount);
    Objects.requireNonNull(id, "No name for " + serviceAccount + " " + sourceName);
    if (isServicesOnlyMode()) {
        log.debug("Only processing Services right now so ignoring ServiceAccount: " + id);
        return;
    }
    ServiceAccount old = kubernetesClient.serviceAccounts().inNamespace(namespace).withName(id).get();
    if (isRunning(old)) {
        if (UserConfigurationCompare.configEqual(serviceAccount, old)) {
            log.info("ServiceAccount has not changed so not doing anything");
        } else {
            if (isRecreateMode()) {
                kubernetesClient.serviceAccounts().inNamespace(namespace).withName(id).delete();
                doCreateServiceAccount(serviceAccount, namespace, sourceName);
            } else {
                log.info("Updating a ServiceAccount from " + sourceName);
                try {
                    Object answer = kubernetesClient.serviceAccounts().inNamespace(namespace).withName(id).replace(serviceAccount);
                    logGeneratedEntity("Updated ServiceAccount: ", namespace, serviceAccount, answer);
                } catch (Exception e) {
                    onApplyError("Failed to update ServiceAccount from " + sourceName + ". " + e + ". " + serviceAccount, e);
                }
            }
        }
    } else {
        if (!isAllowCreate()) {
            log.warn("Creation disabled so not creating a ServiceAccount from " + sourceName + " namespace " + namespace + " name " + getName(serviceAccount));
        } else {
            doCreateServiceAccount(serviceAccount, namespace, sourceName);
        }
    }
}
 
Example #2
Source File: KubernetesNamespaceTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testStopsWaitingServiceAccountEventJustAfterEventReceived() throws Exception {
  prepareCreateNamespaceRequest();
  final Resource resource = prepareNamespaceResource(NAMESPACE);
  doThrow(new KubernetesClientException("error", 403, null)).when(resource).get();
  when(serviceAccountResource.get()).thenReturn(null);
  doAnswer(
          invocation -> {
            final Watcher<ServiceAccount> watcher = invocation.getArgument(0);
            watcher.eventReceived(Action.ADDED, mock(ServiceAccount.class));
            return mock(Watch.class);
          })
      .when(serviceAccountResource)
      .watch(any());

  new KubernetesNamespace(clientFactory, executor, NAMESPACE, WORKSPACE_ID).prepare(true);

  verify(serviceAccountResource).get();
  verify(serviceAccountResource).watch(any());
}
 
Example #3
Source File: KubernetesNamespaceTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test(expectedExceptions = InfrastructureException.class)
public void testThrowsInfrastructureExceptionWhenWatcherClosed() throws Exception {
  prepareCreateNamespaceRequest();
  final Resource resource = prepareNamespaceResource(NAMESPACE);
  doThrow(new KubernetesClientException("error", 403, null)).when(resource).get();
  when(serviceAccountResource.get()).thenReturn(null);
  doAnswer(
          (Answer<Watch>)
              invocation -> {
                final Watcher<ServiceAccount> watcher = invocation.getArgument(0);
                watcher.onClose(mock(KubernetesClientException.class));
                return mock(Watch.class);
              })
      .when(serviceAccountResource)
      .watch(any());

  new KubernetesNamespace(clientFactory, executor, NAMESPACE, WORKSPACE_ID).prepare(false);
}
 
Example #4
Source File: ServiceAccountOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Override
public void createWhenExistsIsAPatch(VertxTestContext context, boolean cascade) {
    // This is overridden because SA patch is coded as a no op to avoid needless token creation.
    ServiceAccount resource = resource();
    Resource mockResource = mock(resourceType());
    when(mockResource.get()).thenReturn(resource);
    when(mockResource.cascading(cascade)).thenReturn(mockResource);

    NonNamespaceOperation mockNameable = mock(NonNamespaceOperation.class);
    when(mockNameable.withName(matches(resource.getMetadata().getName()))).thenReturn(mockResource);

    MixedOperation mockCms = mock(MixedOperation.class);
    when(mockCms.inNamespace(matches(resource.getMetadata().getNamespace()))).thenReturn(mockNameable);

    KubernetesClient mockClient = mock(clientType());
    mocker(mockClient, mockCms);

    AbstractResourceOperator<KubernetesClient, ServiceAccount, ServiceAccountList, DoneableServiceAccount, Resource<ServiceAccount, DoneableServiceAccount>> op = createResourceOperations(vertx, mockClient);

    Checkpoint async = context.checkpoint();
    op.createOrUpdate(resource)
        .onComplete(context.succeeding(rr -> {
            context.verify(() -> assertThat(rr, instanceOf(ReconcileResult.Noop.class)));
            verify(mockResource).get();
            //verify(mockResource).patch(any());
            verify(mockResource, never()).create(any());
            verify(mockResource, never()).createNew();
            verify(mockResource, never()).createOrReplace(any());
            verify(mockCms, never()).createOrReplace(any());
            async.flag();
        }));
}
 
Example #5
Source File: ServiceAccountEnricher.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
private ServiceAccount getServiceAccountFromList(KubernetesListBuilder builder, String serviceAccountName) {
    for(HasMetadata item : builder.buildItems()) {
        if(item instanceof ServiceAccount && item.getMetadata().getName().equals(serviceAccountName)) {
            return (ServiceAccount)item;
        }
    }
    return null;
}
 
Example #6
Source File: ServiceAccountEnricherTest.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
private void enrichAndAssert(KubernetesListBuilder builder) {
    final ServiceAccountEnricher saEnricher = new ServiceAccountEnricher(context);
    saEnricher.create(PlatformMode.kubernetes, builder);

    final ServiceAccount serviceAccount = (ServiceAccount) builder.buildLastItem();
    assertThat(serviceAccount).isNotNull();
    assertThat(serviceAccount.getMetadata().getName()).isEqualTo("ribbon");
}
 
Example #7
Source File: ApplyService.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
protected void doCreateServiceAccount(ServiceAccount serviceAccount, String namespace, String sourceName) {
    log.info("Creating a ServiceAccount from " + sourceName + " namespace " + namespace + " name " + getName
            (serviceAccount));
    try {
        Object answer;
        if (StringUtils.isNotBlank(namespace)) {
            answer = kubernetesClient.serviceAccounts().inNamespace(namespace).create(serviceAccount);
        } else {
            answer = kubernetesClient.serviceAccounts().inNamespace(getNamespace()).create(serviceAccount);
        }
        logGeneratedEntity("Created ServiceAccount: ", namespace, serviceAccount, answer);
    } catch (Exception e) {
        onApplyError("Failed to create ServiceAccount from " + sourceName + ". " + e + ". " + serviceAccount, e);
    }
}
 
Example #8
Source File: ServiceAccountOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Override
protected ServiceAccount resource() {
    return new ServiceAccountBuilder()
            .withNewMetadata()
                .withName(RESOURCE_NAME)
                .withNamespace(NAMESPACE)
                .withLabels(singletonMap("foo", "bar"))
            .endMetadata()
        .build();
}
 
Example #9
Source File: DemoApplicationTests.java    From dekorate with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldContainerServiceAccount() {
  KubernetesList list = Serialization.unmarshalAsList(getClass().getClassLoader().getResourceAsStream("META-INF/dekorate/kubernetes.yml"));
  assertNotNull(list);
  ServiceAccount serviceAccount = findFirst(list, ServiceAccount.class).orElseThrow(IllegalStateException::new);
  assertNotNull(serviceAccount);
  assertEquals(1, list.getItems().stream()
    .filter(i -> ServiceAccount.class.isInstance(i)).count());
  //Desrializing rbac resources is broken at the moment: https://github.com/fabric8io/kubernetes-client/issues/1531
  //RoleBinding roleBinding = findFirst(list, RoleBinding.class).orElseThrow(IllegalStateException::new);
}
 
Example #10
Source File: KubernetesAppDeployerIntegrationTests.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeploymentServiceAccountName() {
	log.info("Testing {}...", "DeploymentServiceAccountName");

	ServiceAccount deploymentServiceAccount = new ServiceAccountBuilder().withNewMetadata().withName("appsa")
			.endMetadata().build();

	this.kubernetesClient.serviceAccounts().create(deploymentServiceAccount);

	String serviceAccountName = deploymentServiceAccount.getMetadata().getName();

	KubernetesDeployerProperties deployProperties = new KubernetesDeployerProperties();
	deployProperties.setDeploymentServiceAccountName(serviceAccountName);

	ContainerFactory containerFactory = new DefaultContainerFactory(deployProperties);
	KubernetesAppDeployer appDeployer = new KubernetesAppDeployer(deployProperties, kubernetesClient,
			containerFactory);

	AppDefinition definition = new AppDefinition(randomName(), null);
	AppDeploymentRequest request = new AppDeploymentRequest(definition, testApplication());

	log.info("Deploying {}...", request.getDefinition().getName());
	String deploymentId = appDeployer.deploy(request);
	Timeout timeout = deploymentTimeout();
	assertThat(deploymentId, eventually(hasStatusThat(
			Matchers.hasProperty("state", is(deployed))), timeout.maxAttempts, timeout.pause));

	log.info("Undeploying {}...", deploymentId);
	timeout = undeploymentTimeout();
	appDeployer.undeploy(deploymentId);
	assertThat(deploymentId, eventually(hasStatusThat(
			Matchers.hasProperty("state", is(unknown))), timeout.maxAttempts, timeout.pause));

	kubernetesClient.serviceAccounts().delete(deploymentServiceAccount);
}
 
Example #11
Source File: OpenShiftProjectTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@BeforeMethod
public void setUp() throws Exception {
  lenient().when(clientFactory.create(anyString())).thenReturn(kubernetesClient);
  lenient().when(clientFactory.createOC()).thenReturn(openShiftClient);
  lenient().when(clientFactory.createOC(anyString())).thenReturn(openShiftClient);
  lenient().when(openShiftClient.adapt(OpenShiftClient.class)).thenReturn(openShiftClient);

  final MixedOperation mixedOperation = mock(MixedOperation.class);
  final NonNamespaceOperation namespaceOperation = mock(NonNamespaceOperation.class);
  lenient().doReturn(mixedOperation).when(kubernetesClient).serviceAccounts();
  lenient().when(mixedOperation.inNamespace(anyString())).thenReturn(namespaceOperation);
  lenient().when(namespaceOperation.withName(anyString())).thenReturn(serviceAccountResource);
  lenient().when(serviceAccountResource.get()).thenReturn(mock(ServiceAccount.class));

  openShiftProject =
      new OpenShiftProject(
          clientFactory,
          WORKSPACE_ID,
          PROJECT_NAME,
          deployments,
          services,
          routes,
          pvcs,
          ingresses,
          secrets,
          configsMaps);
}
 
Example #12
Source File: EntityOperator.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Override
public ServiceAccount generateServiceAccount() {
    if (!isDeployed()) {
        return null;
    }
    return super.generateServiceAccount();
}
 
Example #13
Source File: AbstractModel.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
/**
 * @return The service account.
 */
public ServiceAccount generateServiceAccount() {
    return new ServiceAccountBuilder()
            .withNewMetadata()
                .withName(getServiceAccountName())
                .withNamespace(namespace)
                .withOwnerReferences(createOwnerReference())
                .withLabels(labels.toMap())
            .endMetadata()
        .build();
}
 
Example #14
Source File: ManagedKubernetesClient.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
public MixedOperation<ServiceAccount, ServiceAccountList, DoneableServiceAccount, Resource<ServiceAccount, DoneableServiceAccount>> serviceAccounts() {
  return delegate.serviceAccounts();
}
 
Example #15
Source File: Kubernetes.java    From enmasse with Apache License 2.0 4 votes vote down vote up
public List<ServiceAccount> listServiceAccounts(Map<String, String> labels) {
    return client.serviceAccounts().inNamespace(infraNamespace).withLabels(labels).list().getItems();
}
 
Example #16
Source File: Kubernetes.java    From enmasse with Apache License 2.0 4 votes vote down vote up
public ServiceAccount getServiceAccount(String namespace, String name) {
    return client.serviceAccounts().inNamespace(namespace).withName(name).get();
}
 
Example #17
Source File: AutoAdaptableKubernetesClient.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public MixedOperation<ServiceAccount, ServiceAccountList, DoneableServiceAccount, Resource<ServiceAccount, DoneableServiceAccount>> serviceAccounts() {
  return delegate.serviceAccounts();
}
 
Example #18
Source File: DefaultKubernetesClient.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public MixedOperation<ServiceAccount, ServiceAccountList, DoneableServiceAccount, Resource<ServiceAccount, DoneableServiceAccount>> serviceAccounts() {
  return new ServiceAccountOperationsImpl(httpClient, getConfiguration());
}
 
Example #19
Source File: ServiceAccountOperator.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
@Override
protected MixedOperation<ServiceAccount, ServiceAccountList, DoneableServiceAccount, Resource<ServiceAccount, DoneableServiceAccount>> operation() {
    return client.serviceAccounts();
}
 
Example #20
Source File: UtilsTest.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Test
void testGetPluralFromKind() {
  // Given
  Map<String, Class> pluralToKubernetesResourceMap = new HashMap<>();
  pluralToKubernetesResourceMap.put("bindings", Binding.class);
  pluralToKubernetesResourceMap.put("componentstatuses", ComponentStatus.class);
  pluralToKubernetesResourceMap.put("configmaps", ConfigMap.class);
  pluralToKubernetesResourceMap.put("endpoints", Endpoints.class);
  pluralToKubernetesResourceMap.put("events", Event.class);
  pluralToKubernetesResourceMap.put("limitranges", LimitRange.class);
  pluralToKubernetesResourceMap.put("namespaces", Namespace.class);
  pluralToKubernetesResourceMap.put("nodes", Node.class);
  pluralToKubernetesResourceMap.put("persistentvolumeclaims", PersistentVolumeClaim.class);
  pluralToKubernetesResourceMap.put("persistentvolumes", PersistentVolume.class);
  pluralToKubernetesResourceMap.put("pods", Pod.class);
  pluralToKubernetesResourceMap.put("podtemplates", PodTemplate.class);
  pluralToKubernetesResourceMap.put("replicationcontrollers", ReplicationController.class);
  pluralToKubernetesResourceMap.put("resourcequotas", ResourceQuota.class);
  pluralToKubernetesResourceMap.put("secrets", Secret.class);
  pluralToKubernetesResourceMap.put("serviceaccounts", ServiceAccount.class);
  pluralToKubernetesResourceMap.put("services", Service.class);
  pluralToKubernetesResourceMap.put("mutatingwebhookconfigurations", MutatingWebhookConfiguration.class);
  pluralToKubernetesResourceMap.put("validatingwebhookconfigurations", ValidatingWebhookConfiguration.class);
  pluralToKubernetesResourceMap.put("customresourcedefinitions", CustomResourceDefinition.class);
  pluralToKubernetesResourceMap.put("controllerrevisions", ControllerRevision.class);
  pluralToKubernetesResourceMap.put("daemonsets", DaemonSet.class);
  pluralToKubernetesResourceMap.put("deployments", Deployment.class);
  pluralToKubernetesResourceMap.put("replicasets", ReplicaSet.class);
  pluralToKubernetesResourceMap.put("statefulsets", StatefulSet.class);
  pluralToKubernetesResourceMap.put("tokenreviews", TokenReview.class);
  pluralToKubernetesResourceMap.put("localsubjectaccessreviews", LocalSubjectAccessReview.class);
  pluralToKubernetesResourceMap.put("selfsubjectaccessreviews", SelfSubjectAccessReview.class);
  pluralToKubernetesResourceMap.put("selfsubjectrulesreviews", SelfSubjectRulesReview.class);
  pluralToKubernetesResourceMap.put("subjectaccessreviews", SubjectAccessReview.class);
  pluralToKubernetesResourceMap.put("horizontalpodautoscalers", HorizontalPodAutoscaler.class);
  pluralToKubernetesResourceMap.put("cronjobs", CronJob.class);
  pluralToKubernetesResourceMap.put("jobs", Job.class);
  pluralToKubernetesResourceMap.put("certificatesigningrequests", CertificateSigningRequest.class);
  pluralToKubernetesResourceMap.put("leases", Lease.class);
  pluralToKubernetesResourceMap.put("endpointslices", EndpointSlice.class);
  pluralToKubernetesResourceMap.put("ingresses", Ingress.class);
  pluralToKubernetesResourceMap.put("networkpolicies", NetworkPolicy.class);
  pluralToKubernetesResourceMap.put("poddisruptionbudgets", PodDisruptionBudget.class);
  pluralToKubernetesResourceMap.put("podsecuritypolicies", PodSecurityPolicy.class);
  pluralToKubernetesResourceMap.put("clusterrolebindings", ClusterRoleBinding.class);
  pluralToKubernetesResourceMap.put("clusterroles", ClusterRole.class);
  pluralToKubernetesResourceMap.put("rolebindings", RoleBinding.class);
  pluralToKubernetesResourceMap.put("roles", Role.class);
  pluralToKubernetesResourceMap.put("priorityclasses", PriorityClass.class);
  pluralToKubernetesResourceMap.put("csidrivers", CSIDriver.class);
  pluralToKubernetesResourceMap.put("csinodes", CSINode.class);
  pluralToKubernetesResourceMap.put("storageclasses", StorageClass.class);
  pluralToKubernetesResourceMap.put("volumeattachments", VolumeAttachment.class);

  // When & Then
  pluralToKubernetesResourceMap.forEach((plural, kubernetesResource)
    -> assertEquals(plural, Utils.getPluralFromKind(kubernetesResource.getSimpleName())));
}
 
Example #21
Source File: UtilsTest.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Test
@DisplayName("Should test whether resource is namespaced or not")
void testWhetherNamespacedOrNot() {
  assertTrue(Utils.isResourceNamespaced(Binding.class));
  assertFalse(Utils.isResourceNamespaced(ComponentStatus.class));
  assertTrue(Utils.isResourceNamespaced(ConfigMap.class));
  assertTrue(Utils.isResourceNamespaced(Endpoints.class));
  assertTrue(Utils.isResourceNamespaced(Event.class));
  assertTrue(Utils.isResourceNamespaced(LimitRange.class));
  assertFalse(Utils.isResourceNamespaced(Namespace.class));
  assertFalse(Utils.isResourceNamespaced(Node.class));
  assertTrue(Utils.isResourceNamespaced(PersistentVolumeClaim.class));
  assertFalse(Utils.isResourceNamespaced(PersistentVolume.class));
  assertTrue(Utils.isResourceNamespaced(Pod.class));
  assertTrue(Utils.isResourceNamespaced(PodTemplate.class));
  assertTrue(Utils.isResourceNamespaced(ReplicationController.class));
  assertTrue(Utils.isResourceNamespaced(ResourceQuota.class));
  assertTrue(Utils.isResourceNamespaced(Secret.class));
  assertTrue(Utils.isResourceNamespaced(ServiceAccount.class));
  assertTrue(Utils.isResourceNamespaced(Service.class));
  assertFalse(Utils.isResourceNamespaced(MutatingWebhookConfiguration.class));
  assertFalse(Utils.isResourceNamespaced(ValidatingWebhookConfiguration.class));
  assertFalse(Utils.isResourceNamespaced(CustomResourceDefinition.class));
  assertTrue(Utils.isResourceNamespaced(ControllerRevision.class));
  assertTrue(Utils.isResourceNamespaced(DaemonSet.class));
  assertTrue(Utils.isResourceNamespaced(Deployment.class));
  assertTrue(Utils.isResourceNamespaced(ReplicaSet.class));
  assertTrue(Utils.isResourceNamespaced(StatefulSet.class));
  assertTrue(Utils.isResourceNamespaced(TokenReview.class));
  assertTrue(Utils.isResourceNamespaced(LocalSubjectAccessReview.class));
  assertTrue(Utils.isResourceNamespaced(SelfSubjectAccessReview.class));
  assertTrue(Utils.isResourceNamespaced(SelfSubjectRulesReview.class));
  assertTrue(Utils.isResourceNamespaced(SubjectAccessReview.class));
  assertTrue(Utils.isResourceNamespaced(HorizontalPodAutoscaler.class));
  assertTrue(Utils.isResourceNamespaced(CronJob.class));
  assertTrue(Utils.isResourceNamespaced(Job.class));
  assertTrue(Utils.isResourceNamespaced(CertificateSigningRequest.class));
  assertTrue(Utils.isResourceNamespaced(Lease.class));
  assertTrue(Utils.isResourceNamespaced(EndpointSlice.class));
  assertTrue(Utils.isResourceNamespaced(Ingress.class));
  assertTrue(Utils.isResourceNamespaced(NetworkPolicy.class));
  assertTrue(Utils.isResourceNamespaced(PodDisruptionBudget.class));
  assertFalse(Utils.isResourceNamespaced(PodSecurityPolicy.class));
  assertFalse(Utils.isResourceNamespaced(ClusterRoleBinding.class));
  assertFalse(Utils.isResourceNamespaced(ClusterRole.class));
  assertTrue(Utils.isResourceNamespaced(RoleBinding.class));
  assertTrue(Utils.isResourceNamespaced(Role.class));
  assertFalse(Utils.isResourceNamespaced(PriorityClass.class));
  assertTrue(Utils.isResourceNamespaced(CSIDriver.class));
  assertTrue(Utils.isResourceNamespaced(CSINode.class));
  assertFalse(Utils.isResourceNamespaced(StorageClass.class));
  assertTrue(Utils.isResourceNamespaced(VolumeAttachment.class));
}
 
Example #22
Source File: DeploymentConfigExamples.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
  Config config = new ConfigBuilder().build();
  KubernetesClient kubernetesClient = new DefaultKubernetesClient(config);
  OpenShiftClient client = kubernetesClient.adapt(OpenShiftClient.class);

  try {
    ProjectRequest  projectRequest = new ProjectRequestBuilder()
        .withNewMetadata()
          .withName("thisisatest")
          .addToLabels("project", "thisisatest")
        .endMetadata()
        .build();


    log("Created project", client.projectrequests().create(projectRequest));

    ServiceAccount fabric8 = new ServiceAccountBuilder().withNewMetadata().withName("fabric8").endMetadata().build();

    client.serviceAccounts().inNamespace("thisisatest").createOrReplace(fabric8);

    log("Created deployment", client.deploymentConfigs().inNamespace("thisisatest").createOrReplaceWithNew()
      .withNewMetadata()
        .withName("nginx")
      .endMetadata()
      .withNewSpec()
        .withReplicas(1)
        .addNewTrigger()
          .withType("ConfigChange")
        .endTrigger()
        .addToSelector("app", "nginx")
        .withNewTemplate()
          .withNewMetadata()
            .addToLabels("app", "nginx")
          .endMetadata()
          .withNewSpec()
            .addNewContainer()
              .withName("nginx")
              .withImage("nginx")
              .addNewPort()
                .withContainerPort(80)
              .endPort()
            .endContainer()
          .endSpec()
        .endTemplate()
      .endSpec()
      .done());


    client.deploymentConfigs().inNamespace("thisisatest").withName("nginx").scale(2, true);
    log("Created pods:", client.pods().inNamespace("thisisatest").list().getItems());
    client.deploymentConfigs().inNamespace("thisisatest").withName("nginx").delete();
    log("Pods:", client.pods().inNamespace("thisisatest").list().getItems());
    log("Replication Controllers:", client.replicationControllers().inNamespace("thisisatest").list().getItems());

    log("Done.");
  }finally {
   // client.projects().withName("thisisatest").delete();
    client.close();
  }
}
 
Example #23
Source File: DeploymentExamples.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
  Config config = new ConfigBuilder().build();
  KubernetesClient client = new DefaultKubernetesClient(config);

  try {
    // Create a namespace for all our stuff
    Namespace ns = new NamespaceBuilder().withNewMetadata().withName("thisisatest").addToLabels("this", "rocks").endMetadata().build();
    log("Created namespace", client.namespaces().createOrReplace(ns));

    ServiceAccount fabric8 = new ServiceAccountBuilder().withNewMetadata().withName("fabric8").endMetadata().build();

    client.serviceAccounts().inNamespace("thisisatest").createOrReplace(fabric8);
    for (int i = 0; i < 2; i++) {
      System.err.println("Iteration:" + (i+1));
      Deployment deployment = new DeploymentBuilder()
        .withNewMetadata()
        .withName("nginx")
        .endMetadata()
        .withNewSpec()
        .withReplicas(1)
        .withNewTemplate()
        .withNewMetadata()
        .addToLabels("app", "nginx")
        .endMetadata()
        .withNewSpec()
        .addNewContainer()
        .withName("nginx")
        .withImage("nginx")
        .addNewPort()
        .withContainerPort(80)
        .endPort()
        .endContainer()
        .endSpec()
        .endTemplate()
        .withNewSelector()
        .addToMatchLabels("app", "nginx")
        .endSelector()
        .endSpec()
        .build();


      deployment = client.apps().deployments().inNamespace("thisisatest").create(deployment);
      log("Created deployment", deployment);

      System.err.println("Scaling up:" + deployment.getMetadata().getName());
      client.apps().deployments().inNamespace("thisisatest").withName("nginx").scale(2, true);
      log("Created replica sets:", client.apps().replicaSets().inNamespace("thisisatest").list().getItems());
      System.err.println("Deleting:" + deployment.getMetadata().getName());
      client.resource(deployment).delete();
    }
    log("Done.");

  }finally {
    client.namespaces().withName("thisisatest").delete();
    client.close();
  }
}
 
Example #24
Source File: KubeClient.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
public List<ServiceAccount> listServiceAccounts() {
    return client.serviceAccounts().inNamespace(getNamespace()).list().getItems();
}
 
Example #25
Source File: ServiceAccountOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
@Override
protected AbstractResourceOperator<KubernetesClient, ServiceAccount, ServiceAccountList, DoneableServiceAccount, Resource<ServiceAccount, DoneableServiceAccount>> createResourceOperations(Vertx vertx, KubernetesClient mockClient) {
    return new ServiceAccountOperator(vertx, mockClient);
}
 
Example #26
Source File: ServiceAccountOperator.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
@Override
protected Future<ReconcileResult<ServiceAccount>> internalPatch(String namespace, String name, ServiceAccount current, ServiceAccount desired) {
    // Patching a SA causes new tokens to be created, which we should avoid
    return Future.succeededFuture(ReconcileResult.noop(current));
}
 
Example #27
Source File: ServiceAccountEnricher.java    From jkube with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void create(PlatformMode mode, KubernetesListBuilder builder) {
    Map<String, String> deploymentToSaPair = new HashMap<>();
    List<ServiceAccount> serviceAccounts = new ArrayList<>();

    // Check XML config and see if there are any service accounts specified
    ResourceConfig xmlResourceConfig = getConfiguration().getResource();
    if(xmlResourceConfig != null && xmlResourceConfig.getServiceAccounts() != null) {
        for(ServiceAccountConfig serviceAccountConfig : xmlResourceConfig.getServiceAccounts()) {
            if(serviceAccountConfig.getName() != null) {
                serviceAccounts.add(createServiceAccount(builder, serviceAccountConfig.getName()));
            }
            if(serviceAccountConfig.getDeploymentRef() != null) {
                deploymentToSaPair.put(serviceAccountConfig.getDeploymentRef(), serviceAccountConfig.getName());
            }
        }
    }

    // If any service account is referenced in deployment spec, then
    // create sa on fly.
    builder.accept(new TypedVisitor<DeploymentBuilder>() {
       @Override
       public void visit(DeploymentBuilder deploymentBuilder) {
           String serviceAccountName = getServiceAccountNameFromSpec(deploymentBuilder);
           if(serviceAccountName != null && getServiceAccountFromList(builder, serviceAccountName) == null) {
               serviceAccounts.add(createServiceAccount(builder, serviceAccountName));
           }
           if(deploymentToSaPair.containsKey(deploymentBuilder.buildMetadata().getName())) {
               deploymentBuilder.editSpec()
                       .editTemplate()
                       .editSpec()
                       .withServiceAccountName(deploymentToSaPair.get(deploymentBuilder.buildMetadata().getName()))
                       .endSpec()
                       .endTemplate()
                       .endSpec();
           }
       }
    });

    builder.addAllToServiceAccountItems(serviceAccounts);
}
 
Example #28
Source File: KafkaMirrorMaker2AssemblyOperator.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
private Future<ReconcileResult<ServiceAccount>> mirrorMaker2ServiceAccount(String namespace, KafkaMirrorMaker2Cluster mirrorMaker2Cluster) {
    return serviceAccountOperations.reconcile(namespace,
            KafkaMirrorMaker2Resources.serviceAccountName(mirrorMaker2Cluster.getCluster()),
            mirrorMaker2Cluster.generateServiceAccount());
}
 
Example #29
Source File: KafkaConnectAssemblyOperator.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
private Future<ReconcileResult<ServiceAccount>> connectServiceAccount(String namespace, KafkaConnectCluster connect) {
    return serviceAccountOperations.reconcile(namespace,
            KafkaConnectResources.serviceAccountName(connect.getCluster()),
            connect.generateServiceAccount());
}
 
Example #30
Source File: KafkaConnectS2IAssemblyOperator.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
Future<ReconcileResult<ServiceAccount>> connectServiceAccount(String namespace, KafkaConnectCluster connect) {
    return serviceAccountOperations.reconcile(namespace,
            KafkaConnectS2IResources.serviceAccountName(connect.getCluster()),
            connect.generateServiceAccount());
}