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

The following examples show how to use io.fabric8.kubernetes.api.model.ReplicationController. 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: ReplicationControllerOperationsImpl.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Override
public ReplicationController updateImage(Map<String, String> containerToImageMap) {
  ReplicationController replicationController = get();
  if (replicationController == null) {
    throw new KubernetesClientException("Existing replica set doesn't exist");
  }
  if (replicationController.getSpec().getTemplate().getSpec().getContainers().isEmpty()) {
    throw new KubernetesClientException("Pod has no containers!");
  }

  List<Container> containers = replicationController.getSpec().getTemplate().getSpec().getContainers();
  for (Container container : containers) {
    if (containerToImageMap.containsKey(container.getName())) {
      container.setImage(containerToImageMap.get(container.getName()));
    }
  }
  replicationController.getSpec().getTemplate().getSpec().setContainers(containers);
  return sendPatchedObject(get(), replicationController);
}
 
Example #2
Source File: ApplyStepExecution.java    From kubernetes-pipeline-plugin with Apache License 2.0 6 votes vote down vote up
private void addEnvironmentAnnotations(Iterable<HasMetadata> items) throws Exception {
    if (items != null) {
        for (HasMetadata item : items) {
            if (item instanceof KubernetesList) {
                KubernetesList list = (KubernetesList) item;
                addEnvironmentAnnotations(list.getItems());
            } else if (item instanceof Template) {
                Template template = (Template) item;
                addEnvironmentAnnotations(template.getObjects());
            } else if (item instanceof ReplicationController) {
                addEnvironmentAnnotations(item);
            } else if (item instanceof DeploymentConfig) {
                addEnvironmentAnnotations(item);
            }
        }
    }
}
 
Example #3
Source File: ApplyTest.java    From kubernetes-pipeline-plugin with Apache License 2.0 6 votes vote down vote up
private void testAddRegistryToImageName(String json, String registry, String expectedImageName) throws Exception {
    Set<HasMetadata> entities = new TreeSet<>(new HasMetadataComparator());
    Object dto = KubernetesHelper.loadJson(json);

    entities.addAll(KubernetesHelper.toItemList(dto));

    ApplyStepExecution execution = new ApplyStepExecution();
    execution.addRegistryToImageNameIfNotPresent(entities, registry);

    boolean matched = false;
    for (HasMetadata entity : entities) {
        if (entity instanceof ReplicationController){
            assertEquals(expectedImageName, ((ReplicationController) entity).getSpec().getTemplate().getSpec().getContainers().get(0).getImage());
            matched = true;
        }
    }
    assertTrue(matched);
}
 
Example #4
Source File: ReplicationControllerTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testGet() {
 server.expect().withPath("/api/v1/namespaces/test/replicationcontrollers/repl1").andReturn(200, new ReplicationControllerBuilder().build()).once();
 server.expect().withPath("/api/v1/namespaces/ns1/replicationcontrollers/repl2").andReturn(200, new ReplicationControllerBuilder().build()).once();

  KubernetesClient client = server.getClient();

  ReplicationController repl1 = client.replicationControllers().withName("repl1").get();
  assertNotNull(repl1);

  repl1 = client.replicationControllers().withName("repl2").get();
  assertNull(repl1);

  repl1 = client.replicationControllers().inNamespace("ns1").withName("repl2").get();
  assertNotNull(repl1);
}
 
Example #5
Source File: ReplicationControllerTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testScale() {
 server.expect().withPath("/api/v1/namespaces/test/replicationcontrollers/repl1").andReturn(200, new ReplicationControllerBuilder()
    .withNewMetadata()
    .withName("repl1")
    .withResourceVersion("1")
    .endMetadata()
    .withNewSpec()
    .withReplicas(5)
    .endSpec()
    .withNewStatus()
      .withReplicas(1)
    .endStatus()
    .build()).always();

  KubernetesClient client = server.getClient();
  ReplicationController repl = client.replicationControllers().withName("repl1").scale(5);
  assertNotNull(repl);
  assertNotNull(repl.getSpec());
  assertEquals(5, repl.getSpec().getReplicas().intValue());
  assertEquals(1, repl.getStatus().getReplicas().intValue());
}
 
Example #6
Source File: ReplicationControllerDelete.java    From fabric8-forge with Apache License 2.0 6 votes vote down vote up
@Override
public void initializeUI(UIBuilder builder) throws Exception {
    super.initializeUI(builder);

    // populate autocompletion options
    replicationControllerId.setCompleter(new UICompleter<String>() {
        @Override
        public Iterable<String> getCompletionProposals(UIContext context, InputComponent<?, String> input, String value) {
            List<String> list = new ArrayList<String>();
            ReplicationControllerList replicationControllers = getKubernetes().replicationControllers().inNamespace(getNamespace()).list();
            if (replicationControllers != null) {
                List<ReplicationController> items = replicationControllers.getItems();
                if (items != null) {
                    for (ReplicationController item : items) {
                        String id = KubernetesHelper.getName(item);
                        list.add(id);
                    }
                }
            }
            Collections.sort(list);
            return list;
        }
    });

    builder.add(replicationControllerId);
}
 
Example #7
Source File: Readiness.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
public static boolean isReady(HasMetadata item) {
  if (item instanceof Deployment) {
    return isDeploymentReady((Deployment) item);
  } else if (item instanceof ReplicaSet) {
    return isReplicaSetReady((ReplicaSet) item);
  } else if (item instanceof Pod) {
    return isPodReady((Pod) item);
  } else if (item instanceof DeploymentConfig) {
    return isDeploymentConfigReady((DeploymentConfig) item);
  } else if (item instanceof ReplicationController) {
    return isReplicationControllerReady((ReplicationController) item);
  } else if (item instanceof Endpoints) {
    return isEndpointsReady((Endpoints) item);
  } else if (item instanceof Node) {
    return isNodeReady((Node) item);
  } else if (item instanceof StatefulSet) {
    return isStatefulSetReady((StatefulSet) item);
  } else {
    throw new IllegalArgumentException("Item needs to be one of [Node, Deployment, ReplicaSet, StatefulSet, Pod, DeploymentConfig, ReplicationController], but was: [" + (item != null ? item.getKind() : "Unknown (null)") + "]");
  }
}
 
Example #8
Source File: Readiness.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
public static boolean isReplicationControllerReady(ReplicationController r) {
  Utils.checkNotNull(r, "ReplicationController can't be null.");
  ReplicationControllerSpec spec = r.getSpec();
  ReplicationControllerStatus status = r.getStatus();

  if (status == null || status.getReadyReplicas() == null) {
    return false;
  }

  //Can be true in testing, so handle it to make test writing easier.
  if (spec == null || spec.getReplicas() == null) {
    return false;
  }

  return spec.getReplicas().intValue() == status.getReadyReplicas();
}
 
Example #9
Source File: TeiidOpenShiftClient.java    From syndesis with Apache License 2.0 6 votes vote down vote up
private static Long getDeployedRevision(DeploymentConfig dc, Long defaultNumber, final OpenShiftClient client) {
    long latestVersion = dc.getStatus().getLatestVersion().longValue();
    ReplicationControllerList list = client.replicationControllers().inNamespace(dc.getMetadata().getNamespace())
            .withLabel("application", dc.getMetadata().getName()).list();

    for (ReplicationController rc : list.getItems()) {
        String version = rc.getMetadata().getAnnotations().get("openshift.io/deployment-config.latest-version");
        if (version != null && Long.parseLong(version) == latestVersion) {
            String deployedVersion = rc.getSpec().getTemplate().getMetadata().getLabels().get(DEPLOYMENT_VERSION_LABEL);
            if (deployedVersion != null) {
                try {
                    return Long.parseLong(deployedVersion);
                } catch (NumberFormatException e) {
                    LOG.error("unexpected value for deployment-version", e);
                }
            }
        }
    }
    return defaultNumber;
}
 
Example #10
Source File: ReplicationControllerTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("Should update image based in single argument")
void testRolloutUpdateSingleImage() throws InterruptedException {
  // Given
  String imageToUpdate = "nginx:latest";
  server.expect().get().withPath("/api/v1/namespaces/ns1/replicationcontrollers/replicationcontroller1")
    .andReturn(HttpURLConnection.HTTP_OK, getReplicationControllerBuilder().build()).times(3);
  server.expect().patch().withPath("/api/v1/namespaces/ns1/replicationcontrollers/replicationcontroller1")
    .andReturn(HttpURLConnection.HTTP_OK, getReplicationControllerBuilder()
      .editSpec().editTemplate().editSpec().editContainer(0)
      .withImage(imageToUpdate)
      .endContainer().endSpec().endTemplate().endSpec()
      .build()).once();
  KubernetesClient client = server.getClient();

  // When
  ReplicationController replicationController = client.replicationControllers().inNamespace("ns1").withName("replicationcontroller1")
    .rolling().updateImage(imageToUpdate);

  // Then
  assertNotNull(replicationController);
  assertEquals(imageToUpdate, replicationController.getSpec().getTemplate().getSpec().getContainers().get(0).getImage());
  RecordedRequest recordedRequest = server.getLastRequest();
  assertEquals("PATCH", recordedRequest.getMethod());
  assertTrue(recordedRequest.getBody().readUtf8().contains(imageToUpdate));
}
 
Example #11
Source File: ReplicationControllerTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("Should update image based in map based argument")
void testRolloutUpdateImage() throws InterruptedException {
  // Given
  Map<String, String> containerToImageMap = Collections.singletonMap("nginx", "nginx:latest");
  server.expect().get().withPath("/api/v1/namespaces/ns1/replicationcontrollers/replicationcontroller1")
    .andReturn(HttpURLConnection.HTTP_OK, getReplicationControllerBuilder().build()).times(3);
  server.expect().patch().withPath("/api/v1/namespaces/ns1/replicationcontrollers/replicationcontroller1")
    .andReturn(HttpURLConnection.HTTP_OK, getReplicationControllerBuilder()
      .editSpec().editTemplate().editSpec().editContainer(0)
      .withImage(containerToImageMap.get("nginx"))
      .endContainer().endSpec().endTemplate().endSpec()
      .build()).once();
  KubernetesClient client = server.getClient();

  // When
  ReplicationController replicationController = client.replicationControllers().inNamespace("ns1").withName("replicationcontroller1")
    .rolling().updateImage(containerToImageMap);

  // Then
  assertNotNull(replicationController);
  assertEquals(containerToImageMap.get("nginx"), replicationController.getSpec().getTemplate().getSpec().getContainers().get(0).getImage());
  RecordedRequest recordedRequest = server.getLastRequest();
  assertEquals("PATCH", recordedRequest.getMethod());
  assertTrue(recordedRequest.getBody().readUtf8().contains(containerToImageMap.get("nginx")));
}
 
Example #12
Source File: ReplicationControllerOperationsImpl.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
private List<PodResource<Pod, DoneablePod>> doGetLog(boolean isPretty) {
  List<PodResource<Pod, DoneablePod>> pods = new ArrayList<>();
  ReplicationController rc = fromServer().get();
  String rcUid = rc.getMetadata().getUid();

  PodOperationsImpl podOperations = new PodOperationsImpl(new PodOperationContext(context.getClient(),
    context.getConfig(), context.getPlural(), context.getNamespace(), context.getName(), null,
    "v1", context.getCascading(), context.getItem(), context.getLabels(), context.getLabelsNot(),
    context.getLabelsIn(), context.getLabelsNotIn(), context.getFields(), context.getFieldsNot(), context.getResourceVersion(),
    context.getReloadingFromServer(), context.getGracePeriodSeconds(), context.getPropagationPolicy(),
    context.getWatchRetryInitialBackoffMillis(), context.getWatchRetryBackoffMultiplier(), null, null, null, null, null,
    null, null, null, null, false, false, false, null, null,
    null, isPretty, null, null, null, null, null));
  PodList jobPodList = podOperations.withLabels(rc.getMetadata().getLabels()).list();

  for (Pod pod : jobPodList.getItems()) {
    OwnerReference ownerReference = KubernetesResourceUtil.getControllerUid(pod);
    if (ownerReference != null && ownerReference.getUid().equals(rcUid)) {
      pods.add(podOperations.withName(pod.getMetadata().getName()));
    }
  }
  return pods;
}
 
Example #13
Source File: KubernetesClientUtil.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
public static void resizeApp(KubernetesClient kubernetes, String namespace, Set<HasMetadata> entities, int replicas, KitLogger log) {
    for (HasMetadata entity : entities) {
        String name = KubernetesHelper.getName(entity);
        Scaleable<?> scalable = null;
        if (entity instanceof Deployment) {
            scalable = kubernetes.apps().deployments().inNamespace(namespace).withName(name);
        } else if (entity instanceof ReplicaSet) {
            scalable = kubernetes.apps().replicaSets().inNamespace(namespace).withName(name);
        } else if (entity instanceof ReplicationController) {
            scalable = kubernetes.replicationControllers().inNamespace(namespace).withName(name);
        } else if (entity instanceof DeploymentConfig) {
            OpenShiftClient openshiftClient = OpenshiftHelper.asOpenShiftClient(kubernetes);
            if (openshiftClient == null) {
                log.warn("Ignoring DeploymentConfig %s as not connected to an OpenShift cluster", name);
                continue;
            }
            scalable = openshiftClient.deploymentConfigs().inNamespace(namespace).withName(name);
        }
        if (scalable != null) {
            log.info("Scaling " + KubernetesHelper.getKind(entity) + " " + namespace + "/" + name + " to replicas: " + replicas);
            scalable.scale(replicas, true);
        }
    }
}
 
Example #14
Source File: PatchService.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
private static EntityPatcher<ReplicationController> rcPatcher() {
    return (KubernetesClient client, String namespace, ReplicationController newObj, ReplicationController oldObj) -> {
        if (UserConfigurationCompare.configEqual(newObj, oldObj)) {
            return oldObj;
        }

        DoneableReplicationController entity =
            client.replicationControllers()
                  .inNamespace(namespace)
                  .withName(oldObj.getMetadata().getName())
                  .edit();

        if (!UserConfigurationCompare.configEqual(newObj.getMetadata(), oldObj.getMetadata())) {
            entity.withMetadata(newObj.getMetadata());
        }

        if(!UserConfigurationCompare.configEqual(newObj.getSpec(), oldObj.getSpec())) {
                entity.withSpec(newObj.getSpec());
        }
        return entity.done();
    };
}
 
Example #15
Source File: ReplicationControllerOperationsImpl.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Override
public ReplicationController updateImage(String image) {
  ReplicationController oldRC = get();

  if (oldRC == null) {
    throw new KubernetesClientException("Existing replication controller doesn't exist");
  }
  if (oldRC.getSpec().getTemplate().getSpec().getContainers().size() > 1) {
    throw new KubernetesClientException("Image update is not supported for multicontainer pods");
  }
  if (oldRC.getSpec().getTemplate().getSpec().getContainers().isEmpty()) {
    throw new KubernetesClientException("Pod has no containers!");
  }

  Container container = oldRC.getSpec().getTemplate().getSpec().getContainers().iterator().next();
  return updateImage(Collections.singletonMap(container.getName(), image));
}
 
Example #16
Source File: ReplicationControllerTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Disabled
@Test
public void testUpdate() {
  ReplicationController repl1 = new ReplicationControllerBuilder()
    .withNewMetadata()
    .withName("repl1")
    .withNamespace("test")
    .endMetadata()
    .withNewSpec()
      .withReplicas(1)
      .withNewTemplate()
        .withNewMetadata().withLabels(new HashMap<String, String>()).endMetadata()
        .withNewSpec()
          .addNewContainer()
            .withImage("img1")
          .endContainer()
        .endSpec()
      .endTemplate()
    .endSpec()
    .withNewStatus().withReplicas(1).endStatus()
    .build();

 server.expect().withPath("/api/v1/namespaces/test/replicationcontrollers/repl1").andReturn(200, repl1).once();
 server.expect().put().withPath("/api/v1/namespaces/test/replicationcontrollers/repl1").andReturn(200, repl1).once();
 server.expect().get().withPath("/api/v1/namespaces/test/replicationcontrollers").andReturn(200, new ReplicationControllerListBuilder().withItems(repl1).build()).once();
 server.expect().post().withPath("/api/v1/namespaces/test/replicationcontrollers").andReturn(201, repl1).once();
 server.expect().withPath("/api/v1/namespaces/test/pods").andReturn(200, new KubernetesListBuilder().build()).once();
  KubernetesClient client = server.getClient();

  repl1 = client.replicationControllers().withName("repl1")
    .rolling()
    .withTimeout(5, TimeUnit.MINUTES)
    .updateImage("");
  assertNotNull(repl1);
}
 
Example #17
Source File: ReplicationControllerRollingUpdater.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
protected ReplicationController createClone(ReplicationController obj, String newName, String newDeploymentHash) {
  return new ReplicationControllerBuilder(obj)
    .editMetadata()
    .withResourceVersion(null)
    .withName(newName)
    .endMetadata()
    .editSpec()
    .withReplicas(0).addToSelector(DEPLOYMENT_KEY, newDeploymentHash)
    .editTemplate().editMetadata().addToLabels(DEPLOYMENT_KEY, newDeploymentHash).endMetadata().endTemplate()
    .endSpec()
    .build();
}
 
Example #18
Source File: ReplicationControllerTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testScaleAndWait() {
 server.expect().withPath("/api/v1/namespaces/test/replicationcontrollers/repl1").andReturn(200, new ReplicationControllerBuilder()
    .withNewMetadata()
    .withName("repl1")
    .withResourceVersion("1")
    .endMetadata()
    .withNewSpec()
    .withReplicas(5)
    .endSpec()
    .withNewStatus()
      .withReplicas(1)
    .endStatus()
    .build()).once();

  server.expect().withPath("/api/v1/namespaces/test/replicationcontrollers/repl1").andReturn(200, new ReplicationControllerBuilder()
      .withNewMetadata()
      .withName("repl1")
      .withResourceVersion("1")
      .endMetadata()
      .withNewSpec()
      .withReplicas(5)
      .endSpec()
      .withNewStatus()
      .withReplicas(5)
      .endStatus()
      .build()).always();

  KubernetesClient client = server.getClient();
  ReplicationController repl = client.replicationControllers().withName("repl1").scale(5, true);
  assertNotNull(repl);
  assertNotNull(repl.getSpec());
  assertEquals(5, repl.getSpec().getReplicas().intValue());
  assertEquals(5, repl.getStatus().getReplicas().intValue());
}
 
Example #19
Source File: ContainerSearch.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private Stream<Container> findContainers(HasMetadata o) {
  // hopefully, this covers all types of objects that can contain a container
  if (o instanceof Pod) {
    return ((Pod) o).getSpec().getContainers().stream();
  } else if (o instanceof PodTemplate) {
    return ((PodTemplate) o).getTemplate().getSpec().getContainers().stream();
  } else if (o instanceof DaemonSet) {
    return ((DaemonSet) o).getSpec().getTemplate().getSpec().getContainers().stream();
  } else if (o instanceof Deployment) {
    return ((Deployment) o).getSpec().getTemplate().getSpec().getContainers().stream();
  } else if (o instanceof Job) {
    return ((Job) o).getSpec().getTemplate().getSpec().getContainers().stream();
  } else if (o instanceof ReplicaSet) {
    return ((ReplicaSet) o).getSpec().getTemplate().getSpec().getContainers().stream();
  } else if (o instanceof ReplicationController) {
    return ((ReplicationController) o).getSpec().getTemplate().getSpec().getContainers().stream();
  } else if (o instanceof StatefulSet) {
    return ((StatefulSet) o).getSpec().getTemplate().getSpec().getContainers().stream();
  } else if (o instanceof CronJob) {
    return ((CronJob) o)
        .getSpec()
        .getJobTemplate()
        .getSpec()
        .getTemplate()
        .getSpec()
        .getContainers()
        .stream();
  } else if (o instanceof DeploymentConfig) {
    return ((DeploymentConfig) o).getSpec().getTemplate().getSpec().getContainers().stream();
  } else if (o instanceof Template) {
    return ((Template) o).getObjects().stream().flatMap(this::findContainers);
  } else {
    return Stream.empty();
  }
}
 
Example #20
Source File: ReplicationControllerHandlerTest.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void replicationControllerHandlerTest() {

    ContainerHandler containerHandler = getContainerHandler();

    PodTemplateHandler podTemplateHandler = new PodTemplateHandler(containerHandler);

    ReplicationControllerHandler replicationControllerHandler = new ReplicationControllerHandler(podTemplateHandler);

    ResourceConfig config = ResourceConfig.builder()
            .imagePullPolicy("IfNotPresent")
            .controllerName("testing")
            .serviceAccount("test-account")
            .replicas(5)
            .volumes(volumes1)
            .build();

    ReplicationController replicationController = replicationControllerHandler.getReplicationController(config,images);

    //Assertion
    assertNotNull(replicationController.getSpec());
    assertNotNull(replicationController.getMetadata());
    assertEquals(5,replicationController.getSpec().getReplicas().intValue());
    assertNotNull(replicationController.getSpec().getTemplate());
    assertEquals("testing",replicationController.getMetadata().getName());
    assertEquals("test-account",replicationController.getSpec().getTemplate()
            .getSpec().getServiceAccountName());
    assertFalse(replicationController.getSpec().getTemplate().getSpec().getVolumes().isEmpty());
    assertEquals("test",replicationController.getSpec().getTemplate().getSpec().
            getVolumes().get(0).getName());
    assertEquals("/test/path",replicationController.getSpec().getTemplate()
            .getSpec().getVolumes().get(0).getHostPath().getPath());
    assertNotNull(replicationController.getSpec().getTemplate().getSpec().getContainers());

}
 
Example #21
Source File: Readiness.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public static boolean isReadinessApplicable(Class<? extends HasMetadata> itemClass) {
  return Deployment.class.isAssignableFrom(itemClass)
    || ReplicaSet.class.isAssignableFrom(itemClass)
    || Pod.class.isAssignableFrom(itemClass)
    || DeploymentConfig.class.isAssignableFrom(itemClass)
    || ReplicationController.class.isAssignableFrom(itemClass)
    || Endpoints.class.isAssignableFrom(itemClass)
    || Node.class.isAssignableFrom(itemClass)
    || StatefulSet.class.isAssignableFrom(itemClass)
    ;
}
 
Example #22
Source File: ReplicationControllerDelete.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
@Override
public Result execute(UIExecutionContext context) throws Exception {
    String idText = replicationControllerId.getValue();
    ReplicationController replicationController = getKubernetes().replicationControllers().inNamespace(getNamespace()).withName(idText).get();
    if (replicationController == null) {
        System.out.println("No replicationController for id: " + idText);
    } else {
        executeReplicationController(replicationController);
    }
    return null;
}
 
Example #23
Source File: ReplicationControllersList.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
private void printReplicationControllers(ReplicationControllerList replicationControllers, PrintStream out) {
    TablePrinter table = new TablePrinter();
    table.columns("id", "labels", "replicas", "replica selector");
    List<ReplicationController> items = replicationControllers.getItems();
    if (items == null) {
        items = Collections.EMPTY_LIST;
    }
    Filter<ReplicationController> filter = KubernetesHelper.createReplicationControllerFilter(filterText.getValue());
    for (ReplicationController item : items) {
        if (filter.matches(item)) {
            String id = KubernetesHelper.getName(item);
            String labels = KubernetesHelper.toLabelsString(item.getMetadata().getLabels());
            Integer replicas = null;
            ReplicationControllerSpec desiredState = item.getSpec();
            ReplicationControllerStatus currentState = item.getStatus();
            String selector = null;
            if (desiredState != null) {
                selector = KubernetesHelper.toLabelsString(desiredState.getSelector());
            }
            if (currentState != null) {
                replicas = currentState.getReplicas();
            }
            table.row(id, labels, toPositiveNonZeroText(replicas), selector);
        }
    }
    table.print();
}
 
Example #24
Source File: ResourceCompareTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setup() {
  pod = new PodBuilder().withNewMetadata().withName("pod1").withNamespace("test").withLabels(Collections.singletonMap("label", "value")).and().build();
  service = new ServiceBuilder()
    .withNewMetadata().withName("service1").withNamespace("test").and()
    .build();
  final ReplicationController rc = new ReplicationControllerBuilder()
    .withNewMetadata().withName("repl1").withNamespace("test").endMetadata()
    .withNewSpec().withReplicas(1).endSpec()
    .build();

  kubeList = new KubernetesListBuilder().withItems(pod, service, rc).build();
}
 
Example #25
Source File: SparkClusterOperator.java    From spark-operator with Apache License 2.0 5 votes vote down vote up
private Map<String, Integer> getActual() {
    MixedOperation<ReplicationController, ReplicationControllerList, DoneableReplicationController, RollableScalableResource<ReplicationController, DoneableReplicationController>> aux1 =
            client.replicationControllers();
    FilterWatchListMultiDeletable<ReplicationController, ReplicationControllerList, Boolean, Watch, Watcher<ReplicationController>> aux2 =
            "*".equals(namespace) ? aux1.inAnyNamespace() : aux1.inNamespace(namespace);
    Map<String, String> labels =new HashMap<>(2);
    labels.put(prefix + OPERATOR_KIND_LABEL, entityName);
    labels.put(prefix + OPERATOR_RC_TYPE_LABEL, "worker");
    List<ReplicationController> workerRcs = aux2.withLabels(labels).list().getItems();
    Map<String, Integer> retMap = workerRcs
            .stream()
            .collect(Collectors.toMap(rc -> rc.getMetadata().getLabels().get(prefix + entityName),
                    rc -> rc.getSpec().getReplicas()));
    return retMap;
}
 
Example #26
Source File: ApplyService.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
protected void doCreateReplicationController(ReplicationController replicationController, String namespace, String sourceName) {
    log.info("Creating a ReplicationController from " + sourceName + " namespace " + namespace + " name " + getName(replicationController));
    try {
        Object answer;
        if (StringUtils.isNotBlank(namespace)) {
            answer = kubernetesClient.replicationControllers().inNamespace(namespace).create(replicationController);
        } else {
            answer =  kubernetesClient.replicationControllers().inNamespace(getNamespace()).create(replicationController);
        }
        logGeneratedEntity("Created ReplicationController: ", namespace, replicationController, answer);
    } catch (Exception e) {
        onApplyError("Failed to create ReplicationController from " + sourceName + ". " + e + ". " + replicationController, e);
    }
}
 
Example #27
Source File: ResourceCompareTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testResourceCompareEqualsFalse() throws Exception {
  final ReplicationController rc = new ReplicationControllerBuilder()
    .withNewMetadata().withName("repl1").withNamespace("test").endMetadata()
    .withNewSpec().withReplicas(2).endSpec()
    .build();
  final KubernetesList kubeList2 =
    new KubernetesListBuilder(kubeList).withItems(pod, service, rc).build();
  assertThat(ResourceCompare.equals(kubeList, kubeList2), is(false));
}
 
Example #28
Source File: ReplicationControllerHandler.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
public ReplicationController getReplicationController(ResourceConfig config,
                                                      List<ImageConfiguration> images) {
    return new ReplicationControllerBuilder()
        .withMetadata(createRcMetaData(config))
        .withSpec(createRcSpec(config, images))
        .build();
}
 
Example #29
Source File: KubernetesDeploymentHandler.java    From ephemerals with MIT License 5 votes vote down vote up
@Override
public void destroy(Deployment deployment) {

    List<ReplicationController> apps =
            kubernetesClient.replicationControllers()
                    .withLabel(DEPLOYMENT_LABEL_KEY,deployment.getId())
                    .list().getItems();

    for (ReplicationController rc : apps) {

        String deploymentId = rc.getMetadata().getName();

        logger.info("Deleting service, replication controller and pods for deployment: {}", deploymentId);

        Service svc = kubernetesClient.services().withName(deploymentId).get();
        if(svc.getSpec().getType().equals(KubernetesServiceType.LOAD_BALANCER.getValue())) {

            KubernetesLoadBalancerWaiter kubernetesLoadBalancerWaiter =
                    new KubernetesLoadBalancerWaiter(kubernetesClient, deployment);
            try {
                kubernetesLoadBalancerWaiter.start();
            } catch (TimeoutException e) {
                throw new DeploymentException(e);
            }
        }

        Boolean svcDeleted = kubernetesClient.services().withName(deploymentId).delete();
        logger.info("Deleted service for deployment: {} {}", deploymentId, svcDeleted);

        Boolean rcDeleted = kubernetesClient.replicationControllers().withName(deploymentId).delete();
        logger.info("Deleted replication controller for deployment: {} {}", deploymentId, rcDeleted);

        Map<String, String> selector = new HashMap<>();
        selector.put(DEPLOYMENT_LABEL_KEY, deploymentId);
        Boolean podDeleted = kubernetesClient.pods().withLabels(selector).delete();
        logger.info("Deleted pods for deployment: {} {}", deploymentId, podDeleted);

    }
}
 
Example #30
Source File: DefaultKubernetesClient.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public MixedOperation<ReplicationController, ReplicationControllerList, DoneableReplicationController, RollableScalableResource<ReplicationController, DoneableReplicationController>> replicationControllers() {
  return new ReplicationControllerOperationsImpl(httpClient, getConfiguration());
}