io.kubernetes.client.openapi.models.V1PodSpec Java Examples

The following examples show how to use io.kubernetes.client.openapi.models.V1PodSpec. 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: CacheTest.java    From java with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultiIndexFuncCacheStore() {
  String testIndexFuncName = "test-idx-func";
  Cache<V1Pod> podCache = new Cache<>();
  podCache.addIndexFunc(
      testIndexFuncName,
      (V1Pod pod) -> {
        return Arrays.asList(pod.getSpec().getNodeName());
      });

  V1Pod testPod =
      new V1Pod()
          .metadata(new V1ObjectMeta().namespace("ns").name("n"))
          .spec(new V1PodSpec().nodeName("node1"));
  podCache.add(testPod);

  List<V1Pod> namespaceIndexedPods = podCache.byIndex(Caches.NAMESPACE_INDEX, "ns");
  assertEquals(1, namespaceIndexedPods.size());

  List<V1Pod> nodeNameIndexedPods = podCache.byIndex(testIndexFuncName, "node1");
  assertEquals(1, nodeNameIndexedPods.size());
}
 
Example #2
Source File: RequestObjectBuilder.java    From twister2 with Apache License 2.0 6 votes vote down vote up
public static void constructAffinity(V1PodSpec podSpec) {
  V1Affinity affinity = new V1Affinity();
  boolean affinitySet = false;
  if (KubernetesContext.workerToNodeMapping(config)) {
    setNodeAffinity(affinity);
    affinitySet = true;
  }

  String uniformMappingType = KubernetesContext.workerMappingUniform(config);
  if ("all-same-node".equalsIgnoreCase(uniformMappingType)
      || "all-separate-nodes".equalsIgnoreCase(uniformMappingType)) {
    setUniformMappingAffinity(affinity);
    affinitySet = true;
  }

  // if affinity is initialized, set it
  if (affinitySet) {
    podSpec.setAffinity(affinity);
  }
}
 
Example #3
Source File: AppsV1Controller.java    From incubator-heron with Apache License 2.0 6 votes vote down vote up
private V1PodSpec getPodSpec(List<String> executorCommand, Resource resource,
    int numberOfInstances) {
  final V1PodSpec podSpec = new V1PodSpec();

  // set the termination period to 0 so pods can be deleted quickly
  podSpec.setTerminationGracePeriodSeconds(0L);

  // set the pod tolerations so pods are rescheduled when nodes go down
  // https://kubernetes.io/docs/concepts/configuration/taint-and-toleration/#taint-based-evictions
  podSpec.setTolerations(getTolerations());

  podSpec.containers(Collections.singletonList(
      getContainer(executorCommand, resource, numberOfInstances)));

  addVolumesIfPresent(podSpec);

  return podSpec;
}
 
Example #4
Source File: FluentExample.java    From java with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException, ApiException {
  ApiClient client = Config.defaultClient();
  Configuration.setDefaultApiClient(client);

  CoreV1Api api = new CoreV1Api();

  V1Pod pod =
      new V1PodBuilder()
          .withNewMetadata()
          .withName("apod")
          .endMetadata()
          .withNewSpec()
          .addNewContainer()
          .withName("www")
          .withImage("nginx")
          .endContainer()
          .endSpec()
          .build();

  api.createNamespacedPod("default", pod, null, null, null);

  V1Pod pod2 =
      new V1Pod()
          .metadata(new V1ObjectMeta().name("anotherpod"))
          .spec(
              new V1PodSpec()
                  .containers(Arrays.asList(new V1Container().name("www").image("nginx"))));

  api.createNamespacedPod("default", pod2, null, null, null);

  V1PodList list =
      api.listNamespacedPod("default", null, null, null, null, null, null, null, null, null);
  for (V1Pod item : list.getItems()) {
    System.out.println(item.getMetadata().getName());
  }
}
 
Example #5
Source File: GenericClientExample.java    From java with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

    // The following codes demonstrates using generic client to manipulate pods
    V1Pod pod =
        new V1Pod()
            .metadata(new V1ObjectMeta().name("foo").namespace("default"))
            .spec(
                new V1PodSpec()
                    .containers(Arrays.asList(new V1Container().name("c").image("test"))));
    ApiClient apiClient = ClientBuilder.standard().build();
    GenericKubernetesApi<V1Pod, V1PodList> podClient =
        new GenericKubernetesApi<>(V1Pod.class, V1PodList.class, "", "v1", "pods", apiClient);

    KubernetesApiResponse<V1Pod> createResponse = podClient.create(pod);
    if (!createResponse.isSuccess()) {
      throw new RuntimeException(createResponse.getStatus().toString());
    }
    System.out.println("Created!");

    KubernetesApiResponse<V1Pod> patchResponse =
        podClient.patch(
            "default",
            "foo",
            V1Patch.PATCH_FORMAT_STRATEGIC_MERGE_PATCH,
            new V1Patch("{\"metadata\":{\"finalizers\":[\"example.io/foo\"]}}"));
    if (!patchResponse.isSuccess()) {
      throw new RuntimeException(patchResponse.getStatus().toString());
    }
    System.out.println("Patched!");

    KubernetesApiResponse<V1Pod> deleteResponse = podClient.delete("default", "foo");
    if (!deleteResponse.isSuccess()) {
      throw new RuntimeException(deleteResponse.getStatus().toString());
    }
    if (deleteResponse.getObject() != null) {
      System.out.println(
          "Received after-deletion status of the requested object, will be deleting in background!");
    }
    System.out.println("Deleted!");
  }
 
Example #6
Source File: V1PodTemplateSpec.java    From java with Apache License 2.0 5 votes vote down vote up
/**
 * Get spec
 * @return spec
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")

public V1PodSpec getSpec() {
  return spec;
}
 
Example #7
Source File: V1Pod.java    From java with Apache License 2.0 5 votes vote down vote up
/**
 * Get spec
 * @return spec
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")

public V1PodSpec getSpec() {
  return spec;
}
 
Example #8
Source File: PodLogsTest.java    From java with Apache License 2.0 5 votes vote down vote up
@Test
public void testNotFound() throws ApiException, IOException {
  V1Pod pod =
      new V1Pod()
          .metadata(new V1ObjectMeta().name(podName).namespace(namespace))
          .spec(
              new V1PodSpec()
                  .containers(Arrays.asList(new V1Container().name(container).image("nginx"))));

  stubFor(
      get(urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/log"))
          .willReturn(
              aResponse()
                  .withStatus(404)
                  .withHeader("Content-Type", "text/plain")
                  .withBody("Not Found")));

  PodLogs logs = new PodLogs(client);
  boolean thrown = false;
  try {
    logs.streamNamespacedPodLog(pod);
  } catch (ApiException ex) {
    assertEquals(404, ex.getCode());
    thrown = true;
  }
  assertEquals(thrown, true);
  verify(
      getRequestedFor(
              urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/log"))
          .withQueryParam("container", equalTo(container))
          .withQueryParam("follow", equalTo("true"))
          .withQueryParam("pretty", equalTo("false"))
          .withQueryParam("previous", equalTo("false"))
          .withQueryParam("timestamps", equalTo("false")));
}
 
Example #9
Source File: PodLogsTest.java    From java with Apache License 2.0 5 votes vote down vote up
@Test
public void testStream() throws ApiException, IOException {
  V1Pod pod =
      new V1Pod()
          .metadata(new V1ObjectMeta().name(podName).namespace(namespace))
          .spec(
              new V1PodSpec()
                  .containers(Arrays.asList(new V1Container().name(container).image("nginx"))));

  String content = "this is some\n content for \n various logs \n done";

  stubFor(
      get(urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/log"))
          .willReturn(
              aResponse()
                  .withStatus(200)
                  .withHeader("Content-Type", "text/plain")
                  .withBody(content)));

  PodLogs logs = new PodLogs(client);
  InputStream is = logs.streamNamespacedPodLog(pod);

  verify(
      getRequestedFor(
              urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/log"))
          .withQueryParam("container", equalTo(container))
          .withQueryParam("follow", equalTo("true"))
          .withQueryParam("pretty", equalTo("false"))
          .withQueryParam("previous", equalTo("false"))
          .withQueryParam("timestamps", equalTo("false")));

  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  ByteStreams.copy(is, bos);
  assertEquals(content, bos.toString());
}
 
Example #10
Source File: KubeApiServerIntegrator.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
private V1Pod taskInfoToPod(TaskInfoRequest taskInfoRequest) {
    Protos.TaskInfo taskInfo = taskInfoRequest.getTaskInfo();
    String taskId = taskInfo.getName();
    String nodeName = taskInfo.getSlaveId().getValue();
    Map<String, String> annotations = KubeUtil.createPodAnnotations(taskInfoRequest.getJob(), taskInfoRequest.getTask(),
            taskInfo.getData().toByteArray(), taskInfoRequest.getPassthroughAttributes(),
            mesosConfiguration.isJobDescriptorAnnotationEnabled());

    V1ObjectMeta metadata = new V1ObjectMeta()
            .name(taskId)
            .annotations(annotations);

    V1Container container = new V1Container()
            .name(taskId)
            .image("imageIsInContainerInfo")
            .resources(taskInfoToResources(taskInfo));

    V1PodSpec spec = new V1PodSpec()
            .nodeName(nodeName)
            .containers(Collections.singletonList(container))
            .terminationGracePeriodSeconds(directKubeConfiguration.getPodTerminationGracePeriodSeconds())
            .restartPolicy(NEVER_RESTART_POLICY);

    return new V1Pod()
            .metadata(metadata)
            .spec(spec);
}
 
Example #11
Source File: DefaultTaskToPodConverter.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@Override
public V1Pod apply(Job<?> job, Task task) {
    String taskId = task.getId();
    TitanProtos.ContainerInfo containerInfo = buildContainerInfo(job, task);
    Map<String, String> annotations = KubeUtil.createPodAnnotations(job, task, containerInfo.toByteArray(),
            containerInfo.getPassthroughAttributesMap(), configuration.isJobDescriptorAnnotationEnabled());

    V1ObjectMeta metadata = new V1ObjectMeta()
            .name(taskId)
            .annotations(annotations)
            .labels(ImmutableMap.of(
                    KubeConstants.POD_LABEL_JOB_ID, job.getId(),
                    KubeConstants.POD_LABEL_TASK_ID, taskId
            ));

    V1Container container = new V1Container()
            .name(taskId)
            .image("imageIsInContainerInfo")
            .resources(buildV1ResourceRequirements(job.getJobDescriptor().getContainer().getContainerResources()));

    V1PodSpec spec = new V1PodSpec()
            .schedulerName(configuration.getKubeSchedulerName())
            .containers(Collections.singletonList(container))
            .terminationGracePeriodSeconds(POD_TERMINATION_GRACE_PERIOD_SECONDS)
            .restartPolicy(NEVER_RESTART_POLICY)
            .affinity(podAffinityFactory.buildV1Affinity(job, task))
            .tolerations(taintTolerationFactory.buildV1Toleration(job, task))
            .topologySpreadConstraints(buildTopologySpreadConstraints(job));

    return new V1Pod().metadata(metadata).spec(spec);
}
 
Example #12
Source File: AppsV1Controller.java    From incubator-heron with Apache License 2.0 5 votes vote down vote up
private void addVolumesIfPresent(V1PodSpec spec) {
  final Config config = getConfiguration();
  if (KubernetesContext.hasVolume(config)) {
    final V1Volume volume = Volumes.get().create(config);
    if (volume != null) {
      LOG.fine("Adding volume: " + volume.toString());
      spec.volumes(Collections.singletonList(volume));
    }
  }
}
 
Example #13
Source File: V1PodTemplateSpec.java    From java with Apache License 2.0 4 votes vote down vote up
public void setSpec(V1PodSpec spec) {
  this.spec = spec;
}
 
Example #14
Source File: V1Pod.java    From java with Apache License 2.0 4 votes vote down vote up
public void setSpec(V1PodSpec spec) {
  this.spec = spec;
}
 
Example #15
Source File: JobMasterRequestObject.java    From twister2 with Apache License 2.0 4 votes vote down vote up
/**
 * construct pod template
 */
public static V1PodTemplateSpec constructPodTemplate() {

  V1PodTemplateSpec template = new V1PodTemplateSpec();
  V1ObjectMeta templateMetaData = new V1ObjectMeta();
  HashMap<String, String> labels = KubernetesUtils.createJobLabels(jobID);
  labels.put("t2-mp", jobID); // job master pod

  templateMetaData.setLabels(labels);
  template.setMetadata(templateMetaData);

  V1PodSpec podSpec = new V1PodSpec();
  podSpec.setTerminationGracePeriodSeconds(0L);

  ArrayList<V1Volume> volumes = new ArrayList<>();
  V1Volume memoryVolume = new V1Volume();
  memoryVolume.setName(KubernetesConstants.POD_MEMORY_VOLUME_NAME);
  V1EmptyDirVolumeSource volumeSource1 = new V1EmptyDirVolumeSource();
  volumeSource1.setMedium("Memory");
  memoryVolume.setEmptyDir(volumeSource1);
  volumes.add(memoryVolume);

  // a volatile disk based volume
  // create it if the requested disk space is positive
  if (JobMasterContext.volatileVolumeRequested(config)) {
    double vSize = JobMasterContext.volatileVolumeSize(config);
    V1Volume volatileVolume = RequestObjectBuilder.createVolatileVolume(vSize);
    volumes.add(volatileVolume);
  }

  if (JobMasterContext.persistentVolumeRequested(config)) {
    String claimName = jobID;
    V1Volume persistentVolume = RequestObjectBuilder.createPersistentVolume(claimName);
    volumes.add(persistentVolume);
  }

  podSpec.setVolumes(volumes);

  ArrayList<V1Container> containers = new ArrayList<V1Container>();
  containers.add(constructContainer());
  podSpec.setContainers(containers);

  template.setSpec(podSpec);
  return template;
}
 
Example #16
Source File: RequestObjectBuilder.java    From twister2 with Apache License 2.0 4 votes vote down vote up
/**
 * construct pod template
 */
public static V1PodTemplateSpec constructPodTemplate(ComputeResource computeResource) {

  V1PodTemplateSpec template = new V1PodTemplateSpec();
  V1ObjectMeta templateMetaData = new V1ObjectMeta();
  HashMap<String, String> labels = KubernetesUtils.createJobLabels(jobID);
  labels.put("t2-wp", jobID); // worker pod

  templateMetaData.setLabels(labels);
  template.setMetadata(templateMetaData);

  V1PodSpec podSpec = new V1PodSpec();
  podSpec.setTerminationGracePeriodSeconds(0L);

  ArrayList<V1Volume> volumes = new ArrayList<>();
  V1Volume memoryVolume = new V1Volume();
  memoryVolume.setName(KubernetesConstants.POD_MEMORY_VOLUME_NAME);
  V1EmptyDirVolumeSource volumeSource1 = new V1EmptyDirVolumeSource();
  volumeSource1.setMedium("Memory");
  memoryVolume.setEmptyDir(volumeSource1);
  volumes.add(memoryVolume);

  // a volatile disk based volume
  // create it if the requested disk space is positive
  if (computeResource.getDiskGigaBytes() > 0) {
    double volumeSize = computeResource.getDiskGigaBytes() * computeResource.getWorkersPerPod();
    V1Volume volatileVolume = createVolatileVolume(volumeSize);
    volumes.add(volatileVolume);
  }

  if (SchedulerContext.persistentVolumeRequested(config)) {
    String claimName = jobID;
    V1Volume persistentVolume = createPersistentVolume(claimName);
    volumes.add(persistentVolume);
  }

  // if openmpi is used, we initialize a Secret volume on each pod
  if (SchedulerContext.useOpenMPI(config)) {
    String secretName = KubernetesContext.secretName(config);
    V1Volume secretVolume = createSecretVolume(secretName);
    volumes.add(secretVolume);
  }

  podSpec.setVolumes(volumes);

  int containersPerPod = computeResource.getWorkersPerPod();

  // if openmpi is used, we initialize only one container for each pod
  if (SchedulerContext.useOpenMPI(config)) {
    containersPerPod = 1;
  }

  ArrayList<V1Container> containers = new ArrayList<V1Container>();
  for (int i = 0; i < containersPerPod; i++) {
    containers.add(constructContainer(computeResource, i));
  }
  podSpec.setContainers(containers);

  if (computeResource.getIndex() == 0) {
    constructAffinity(podSpec);
  }

  template.setSpec(podSpec);

  return template;
}