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

The following examples show how to use io.fabric8.kubernetes.api.model.HasMetadata. 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: PodIT.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void listFromServer() {
  // Wait for resources to get ready
  ReadyEntity<Pod> podReady = new ReadyEntity<>(Pod.class, client, pod1.getMetadata().getName(), currentNamespace);
  await().atMost(30, TimeUnit.SECONDS).until(podReady);

  List<HasMetadata> resources = client.resourceList(pod1).inNamespace(currentNamespace).fromServer().get();

  assertNotNull(resources);
  assertEquals(1, resources.size());
  assertNotNull(resources.get(0));

  HasMetadata fromServerPod = resources.get(0);

  assertEquals(pod1.getKind(), fromServerPod.getKind());
  assertEquals(currentNamespace, fromServerPod.getMetadata().getNamespace());
  assertEquals(pod1.getMetadata().getName(), fromServerPod.getMetadata().getName());
}
 
Example #2
Source File: KubernetesResourceUtilTest.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void readWholeDir() throws IOException {
    ResourceVersioning v = new ResourceVersioning()
            .withCoreVersion("v2")
            .withExtensionsVersion("extensions/v2");

    KubernetesListBuilder builder =
        KubernetesResourceUtil.readResourceFragmentsFrom(PlatformMode.kubernetes, v, "pong", new File(jkubeDir, "read-dir").listFiles());
    KubernetesList list = builder.build();
    assertEquals(2,list.getItems().size());
    for (HasMetadata item : list.getItems() ) {
        assertTrue("Service".equals(item.getKind()) || "ReplicationController".equals(item.getKind()));
        assertEquals("pong",item.getMetadata().getName());
        assertEquals("v2",item.getApiVersion());
    }
}
 
Example #3
Source File: BasicOpenshiftTest.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Test
public void assertGeneratedResources() throws IOException {
    Path kubernetesDir = prodModeTestResults.getBuildDir().resolve("kubernetes");
    assertThat(kubernetesDir)
            .isDirectoryContaining(p -> p.getFileName().endsWith("openshift.json"))
            .isDirectoryContaining(p -> p.getFileName().endsWith("openshift.yml"))
            .satisfies(p -> assertThat(p.toFile().listFiles()).hasSize(2));
    List<HasMetadata> openshiftList = DeserializationUtil
            .deserializeAsList(kubernetesDir.resolve("openshift.yml"));

    assertThat(openshiftList).filteredOn(h -> "DeploymentConfig".equals(h.getKind())).hasOnlyOneElementSatisfying(h -> {
        assertThat(h.getMetadata()).satisfies(m -> {
            assertThat(m.getName()).isEqualTo("basic-openshift");
            assertThat(m.getLabels().get("app.openshift.io/runtime")).isEqualTo("quarkus");
        });
        assertThat(h).extracting("spec").extracting("replicas").isEqualTo(1);
        assertThat(h).extracting("spec").extracting("template").extracting("spec").isInstanceOfSatisfying(PodSpec.class,
                podSpec -> {
                    assertThat(podSpec.getContainers()).hasOnlyOneElementSatisfying(container -> {
                        assertThat(container.getEnv()).extracting("name", "value")
                                .contains(tuple("JAVA_APP_JAR",
                                        "/deployments/basic-openshift-runner.jar"));
                    });
                });
    });
}
 
Example #4
Source File: CreateOrReplaceResourceTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testResourceCreateFromLoad() throws Exception {
  server.expect().get().withPath("/api/v1/namespaces/test/pods/nginx").andReturn(404, new StatusBuilder().build()).always();

  server.expect().post().withPath("/api/v1/namespaces/test/pods").andReturn(201, new PodBuilder()
    .withNewMetadata().withResourceVersion("12345").and().build()).once();

  KubernetesClient client = server.getClient();
  List<HasMetadata> result = client.load(getClass().getResourceAsStream("/test-pod-create-from-load.yml")).createOrReplace();
  assertNotNull(result);
  assertEquals(1, result.size());
  Pod pod = (Pod) result.get(0);
  assertEquals("12345", pod.getMetadata().getResourceVersion());

  RecordedRequest request = server.getMockServer().takeRequest();
  assertEquals("/api/v1/namespaces/test/pods/nginx", request.getPath());

  request = server.getMockServer().takeRequest();
  Pod requestPod = new ObjectMapper().readerFor(Pod.class).readValue(request.getBody().inputStream());
  assertEquals("nginx", requestPod.getMetadata().getName());
}
 
Example #5
Source File: Serialization.java    From dekorate with Apache License 2.0 6 votes vote down vote up
/**
 * Unmarshals a stream.
 * @param is    The {@link InputStream}.
 * @return
 */
public static KubernetesList unmarshalAsList(InputStream is)  {
  String content = Strings.read(is);
  String[] parts = splitDocument(content);
  List<HasMetadata> items = new ArrayList<>();
  for (String part : parts) {
    if (part.trim().isEmpty()) {
      continue;
    }
    Object resource = unmarshal(part);
    if (resource instanceof KubernetesList) {
      items.addAll(((KubernetesList) resource).getItems());
    } else if (resource instanceof HasMetadata) {
      items.add((HasMetadata) resource);
    } else if (resource instanceof HasMetadata[]) {
      Arrays.stream((HasMetadata[])resource).forEach(r -> items.add(r));
    }
  }
  return new KubernetesListBuilder().withItems(items).build();
}
 
Example #6
Source File: Sample14Test.java    From module-ballerina-kubernetes with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void compileSample() throws IOException, InterruptedException {
    Assert.assertEquals(KubernetesTestUtils.compileBallerinaFile(SOURCE_DIR_PATH, "hello_world_k8s_namespace.bal"),
            0);
    File yamlFile = KUBERNETES_TARGET_PATH.resolve("hello_world_k8s_namespace.yaml").toFile();
    Assert.assertTrue(yamlFile.exists());
    List<HasMetadata> k8sItems = KubernetesTestUtils.loadYaml(yamlFile);
    for (HasMetadata data : k8sItems) {
        switch (data.getKind()) {
            case "Deployment":
                deployment = (Deployment) data;
                break;
            case "Service":
                service = (Service) data;
                break;
            case "Ingress":
                ingress = (Ingress) data;
                break;
            default:
                break;
        }
    }
}
 
Example #7
Source File: ApplyStepExecution.java    From kubernetes-pipeline-plugin with Apache License 2.0 6 votes vote down vote up
private List<HasMetadata> loadImageStreams() throws IOException, InterruptedException {
    if (kubernetes.isAdaptable(OpenShiftClient.class)) {
        FilePath child = workspace.child("target");
        if (child.exists() && child.isDirectory()) {
            List<FilePath> paths = child.list();
            if (paths != null) {
                for (FilePath path : paths) {
                    String name = path.getName();
                    if (path.exists() && !path.isDirectory() && name.endsWith("-is.yml")) {
                        try (InputStream is = path.read()) {
                            listener.getLogger().println("Loading OpenShift ImageStreams file: " + name);
                            KubernetesResource dto = KubernetesHelper.loadYaml(is, KubernetesResource.class);
                            return KubernetesHelper.toItemList(dto);
                        }
                    }
                }
            }
        }
    }
    return Collections.emptyList();
}
 
Example #8
Source File: KubernetesJobManagerFactoryTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@Test
public void testAdditionalResourcesSize() {
	final List<HasMetadata> resultAdditionalResources = this.kubernetesJobManagerSpecification.getAccompanyingResources();
	assertEquals(3, resultAdditionalResources.size());

	final List<HasMetadata> resultServices = resultAdditionalResources
		.stream()
		.filter(x -> x instanceof Service)
		.collect(Collectors.toList());
	assertEquals(2, resultServices.size());

	final List<HasMetadata> resultConfigMaps = resultAdditionalResources
		.stream()
		.filter(x -> x instanceof ConfigMap)
		.collect(Collectors.toList());
	assertEquals(1, resultConfigMaps.size());
}
 
Example #9
Source File: Sample1Test.java    From module-ballerina-kubernetes with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void compileSample() throws IOException, InterruptedException {
    Assert.assertEquals(KubernetesTestUtils.compileBallerinaFile(SOURCE_DIR_PATH, "hello_world_k8s.bal"), 0);
    File artifactYaml = KUBERNETES_TARGET_PATH.resolve("hello_world_k8s.yaml").toFile();
    Assert.assertTrue(artifactYaml.exists());
    KubernetesClient client = new DefaultKubernetesClient();
    List<HasMetadata> k8sItems = client.load(new FileInputStream(artifactYaml)).get();
    for (HasMetadata data : k8sItems) {
        switch (data.getKind()) {
            case "Deployment":
                deployment = (Deployment) data;
                break;
            case "Service":
                service = (Service) data;
                break;
            default:
                Assert.fail("Unexpected k8s resource found: " + data.getKind());
                break;
        }
    }
}
 
Example #10
Source File: ResourceMojo.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
private void addProfiledResourcesFromSubdirectories(PlatformMode platformMode, KubernetesListBuilder builder, File resourceDir,
    EnricherManager enricherManager) throws IOException, MojoExecutionException {
    File[] profileDirs = resourceDir.listFiles(File::isDirectory);
    if (profileDirs != null) {
        for (File profileDir : profileDirs) {
            Profile foundProfile = ProfileUtil.findProfile(profileDir.getName(), resourceDir);
            ProcessorConfig enricherConfig = foundProfile.getEnricherConfig();
            File[] resourceFiles = KubernetesResourceUtil.listResourceFragments(profileDir);
            if (resourceFiles.length > 0) {
                KubernetesListBuilder profileBuilder = readResourceFragments(platformMode, resourceFiles);
                enricherManager.createDefaultResources(platformMode, enricherConfig, profileBuilder);
                enricherManager.enrich(platformMode, enricherConfig, profileBuilder);
                KubernetesList profileItems = profileBuilder.build();
                for (HasMetadata item : profileItems.getItems()) {
                    builder.addToItems(item);
                }
            }
        }
    }
}
 
Example #11
Source File: DeploymentIT.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void listFromServer() {
  ReadyEntity<Deployment> deploymentReady = new ReadyEntity<>(Deployment.class, client, "deployment1", currentNamespace);
  await().atMost(30, TimeUnit.SECONDS).until(deploymentReady);

  List<HasMetadata> resources = client.resourceList(deployment1).inNamespace(currentNamespace).fromServer().get();

  assertNotNull(resources);
  assertEquals(1, resources.size());
  assertNotNull(resources.get(0));

  HasMetadata fromServerPod = resources.get(0);

  assertEquals(deployment1.getKind(), fromServerPod.getKind());
  assertEquals(currentNamespace, fromServerPod.getMetadata().getNamespace());
  assertEquals(deployment1.getMetadata().getName(), fromServerPod.getMetadata().getName());
}
 
Example #12
Source File: DependencyEnricher.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
private void processArtifactSetResources(Set<URL> artifactSet, Function<List<HasMetadata>, Void> function) {
    for (URL url : artifactSet) {
        try {
            log.debug("Processing Kubernetes YAML in at: %s", url);
            KubernetesList resources = new ObjectMapper(new YAMLFactory()).readValue(url, KubernetesList.class);
            List<HasMetadata> items = resources.getItems();
            if (items.isEmpty() && Objects.equals("Template", resources.getKind())) {
                Template template = new ObjectMapper(new YAMLFactory()).readValue(url, Template.class);
                if (template != null) {
                    items.add(template);
                }
            }
            for (HasMetadata item : items) {
                KubernetesResourceUtil.setSourceUrlAnnotationIfNotSet(item, url.toString());
                log.debug("  found %s  %s", KubernetesHelper.getKind(item), KubernetesHelper.getName(item));
            }
            function.apply(items);
        } catch (IOException e) {
            getLog().debug("Skipping %s: %s", url, e);
        }
    }
}
 
Example #13
Source File: SpringBootWatcher.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
private String getServiceExposeUrl(KubernetesClient kubernetes, Set<HasMetadata> resources) throws InterruptedException {
    long serviceUrlWaitTimeSeconds = Configs.asInt(getConfig(Config.serviceUrlWaitTimeSeconds));
    for (HasMetadata entity : resources) {
        if (entity instanceof Service) {
            Service service = (Service) entity;
            String name = KubernetesHelper.getName(service);
            Resource<Service, DoneableService> serviceResource = kubernetes.services()
                .inNamespace(getContext().getJKubeServiceHub().getClusterAccess().getNamespace())
                .withName(name);
            String url = null;
            // lets wait a little while until there is a service URL in case the exposecontroller is running slow
            for (int i = 0; i < serviceUrlWaitTimeSeconds; i++) {
                if (i > 0) {
                    Thread.sleep(1000);
                }
                Service s = serviceResource.get();
                if (s != null) {
                    url = KubernetesHelper.getOrCreateAnnotations(s).get(JKubeAnnotations.SERVICE_EXPOSE_URL.value());
                    if (StringUtils.isNotBlank(url)) {
                        break;
                    }
                }
                if (!isExposeService(service)) {
                    break;
                }
            }

            // lets not wait for other services
            serviceUrlWaitTimeSeconds = 1;
            if (StringUtils.isNotBlank(url) && url.startsWith("http")) {
                return url;
            }
        }
    }

    log.info("No exposed service found for connecting the dev tools");
    return null;
}
 
Example #14
Source File: KubernetesDeserializer.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
private KubernetesResource fromArrayNode(JsonParser jp, JsonNode node) throws IOException {
    Iterator<JsonNode> iterator = node.elements();
    List<HasMetadata> list = new ArrayList<>();
    while (iterator.hasNext()) {
        JsonNode jsonNode = iterator.next();
        if (jsonNode.isObject()) {
            KubernetesResource resource = fromObjectNode(jp, jsonNode);
            if (resource instanceof HasMetadata) {
                list.add((HasMetadata)resource);
            }
        }
    }
    return new KubernetesListBuilder().withItems(list).build();
}
 
Example #15
Source File: KubernetesObjectUtil.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/** Adds annotation to target Kubernetes object. */
public static void putAnnotation(HasMetadata target, String key, String value) {
  ObjectMeta metadata = target.getMetadata();

  if (metadata == null) {
    target.setMetadata(metadata = new ObjectMeta());
  }

  putAnnotation(metadata, key, value);
}
 
Example #16
Source File: DockerimageComponentToWorkspaceApplierTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldProvisionSpecifiedEnvVars() throws Exception {
  // given
  ComponentImpl dockerimageComponent = new ComponentImpl();
  dockerimageComponent.setAlias("jdk");
  dockerimageComponent.setType(DOCKERIMAGE_COMPONENT_TYPE);
  dockerimageComponent.setImage("eclipse/ubuntu_jdk8:latest");
  dockerimageComponent.setMemoryLimit("1G");
  dockerimageComponent.setEnv(singletonList(new EnvImpl("envName", "envValue")));

  // when
  dockerimageComponentApplier.apply(workspaceConfig, dockerimageComponent, null);

  // then
  verify(k8sEnvProvisioner)
      .provision(
          eq(workspaceConfig),
          eq(KubernetesEnvironment.TYPE),
          objectsCaptor.capture(),
          machinesCaptor.capture());
  List<HasMetadata> objects = objectsCaptor.getValue();
  assertEquals(objects.size(), 1);
  assertTrue(objects.get(0) instanceof Deployment);
  Deployment deployment = (Deployment) objects.get(0);
  PodTemplateSpec podTemplate = deployment.getSpec().getTemplate();
  assertEquals(podTemplate.getSpec().getContainers().size(), 1);
  Container container = podTemplate.getSpec().getContainers().get(0);
  int env = container.getEnv().size();
  assertEquals(env, 1);
  EnvVar containerEnvVar = container.getEnv().get(0);
  assertEquals(containerEnvVar.getName(), "envName");
  assertEquals(containerEnvVar.getValue(), "envValue");
}
 
Example #17
Source File: InternalServiceDecoratorTest.java    From flink with Apache License 2.0 5 votes vote down vote up
@Test
public void testBuildAccompanyingKubernetesResources() throws IOException {
	final List<HasMetadata> resources = this.internalServiceDecorator.buildAccompanyingKubernetesResources();
	assertEquals(1, resources.size());

	assertEquals(
		InternalServiceDecorator.getNamespacedInternalServiceName(CLUSTER_ID, NAMESPACE),
		this.flinkConfig.getString(JobManagerOptions.ADDRESS));

	final Service internalService = (Service) resources.get(0);

	assertEquals(Constants.API_VERSION, internalService.getApiVersion());

	assertEquals(InternalServiceDecorator.getInternalServiceName(CLUSTER_ID), internalService.getMetadata().getName());

	final Map<String, String> expectedLabels = getCommonLabels();
	assertEquals(expectedLabels, internalService.getMetadata().getLabels());

	assertNull(internalService.getSpec().getType());
	assertEquals("None", internalService.getSpec().getClusterIP());

	List<ServicePort> expectedServicePorts = Arrays.asList(
		new ServicePortBuilder()
			.withName(Constants.JOB_MANAGER_RPC_PORT_NAME)
			.withPort(RPC_PORT)
			.build(),
		new ServicePortBuilder()
			.withName(Constants.BLOB_SERVER_PORT_NAME)
			.withPort(BLOB_SERVER_PORT)
			.build());
	assertEquals(expectedServicePorts, internalService.getSpec().getPorts());

	expectedLabels.put(Constants.LABEL_COMPONENT_KEY, Constants.LABEL_COMPONENT_JOB_MANAGER);
	expectedLabels.putAll(userLabels);
	assertEquals(expectedLabels, internalService.getSpec().getSelector());
}
 
Example #18
Source File: BaseOperation.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public Boolean delete(List<T> items) {
  boolean deleted = true;
  if (items != null) {
    for (T item : items) {
      updateApiVersionResource(item);

      try {
        R op;

        if (item instanceof HasMetadata
          && ((HasMetadata) item).getMetadata() != null
          && ((HasMetadata) item).getMetadata().getName() != null
          && !((HasMetadata) item).getMetadata().getName().isEmpty())  {
          op = (R) inNamespace(checkNamespace(item)).withName(((HasMetadata) item).getMetadata().getName());
        } else {
          op = (R) withItem(item);
        }

        deleted &= op.delete();
      } catch (KubernetesClientException e) {
        if (e.getCode() != HttpURLConnection.HTTP_NOT_FOUND) {
          throw e;
        }
        return false;
      }
    }
  }
  return deleted;
}
 
Example #19
Source File: DockerimageComponentToWorkspaceApplierTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldProvisionContainerWithMemoryLimitSpecified() throws Exception {
  // given
  ComponentImpl dockerimageComponent = new ComponentImpl();
  dockerimageComponent.setAlias("jdk");
  dockerimageComponent.setType(DOCKERIMAGE_COMPONENT_TYPE);
  dockerimageComponent.setImage("eclipse/ubuntu_jdk8:latest");
  dockerimageComponent.setMemoryLimit("1G");

  // when
  dockerimageComponentApplier.apply(workspaceConfig, dockerimageComponent, null);

  // then
  verify(k8sEnvProvisioner)
      .provision(
          eq(workspaceConfig),
          eq(KubernetesEnvironment.TYPE),
          objectsCaptor.capture(),
          machinesCaptor.capture());
  List<HasMetadata> objects = objectsCaptor.getValue();
  assertEquals(objects.size(), 1);
  assertTrue(objects.get(0) instanceof Deployment);
  Deployment deployment = (Deployment) objects.get(0);
  PodTemplateSpec podTemplate = deployment.getSpec().getTemplate();
  assertEquals(podTemplate.getSpec().getContainers().size(), 1);
  Container container = podTemplate.getSpec().getContainers().get(0);
  Quantity memoryLimit = container.getResources().getLimits().get("memory");
  assertEquals(memoryLimit.getAmount(), "1");
  assertEquals(memoryLimit.getFormat(), "G");
}
 
Example #20
Source File: Sample17Test.java    From module-ballerina-kubernetes with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public void compileSample() throws IOException, InterruptedException {
    Path sourcePath = SOURCE_DIR_PATH.resolve("hello_world_oc.bal");
    
    // save original source
    Stream<String> lines = Files.lines(sourcePath);
    this.originalSourceContent = lines.collect(Collectors.toList());
    
    // replace placeholders with mocks
    lines = Files.lines(sourcePath);
    List<String> replacedContent = lines.map(line -> line
            .replaceAll("<MINISHIFT_IP>", "192.168.99.131")
            .replaceAll("<MINISHIFT_DOCKER_REGISTRY_IP>", "172.30.1.1:5000"))
            .collect(Collectors.toList());
    Files.write(sourcePath, replacedContent);
    
    Assert.assertEquals(KubernetesTestUtils.compileBallerinaFile(SOURCE_DIR_PATH, "hello_world_oc.bal"), 0);
    File yamlFile = KUBERNETES_TARGET_PATH.resolve(OPENSHIFT).resolve("hello_world_oc.yaml").toFile();
    Assert.assertTrue(yamlFile.exists());
    List<HasMetadata> k8sItems = KubernetesTestUtils.loadYaml(yamlFile);
    for (HasMetadata data : k8sItems) {
        if ("BuildConfig".equals(data.getKind())) {
            buildConfig = (BuildConfig) data;
        } else if ("ImageStream".equals(data.getKind())) {
            imageStream = (ImageStream) data;
        } else if ("Route".equals(data.getKind())) {
            route = (Route) data;
        }
    }
}
 
Example #21
Source File: DependencyEnricherTest.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
private boolean checkUniqueResources(List<HasMetadata> resourceList) {
    Map<KindAndName, Integer> resourceMap = new HashMap<>();
    for(int index = 0; index < resourceList.size(); index++) {
        KindAndName aKey = new KindAndName(resourceList.get(index));
        if(resourceMap.containsKey(aKey))
            return false;
        resourceMap.put(aKey, index);
    }
    return true;
}
 
Example #22
Source File: ResourceTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateWithExplicitNamespace() {
    Pod pod1 = new PodBuilder().withNewMetadata().withName("pod1").withNamespace("test").and().build();

    server.expect().get().withPath("/api/v1/namespaces/ns1/pods/pod1").andReturn(404, "").once();
    server.expect().post().withPath("/api/v1/namespaces/ns1/pods").andReturn(201, pod1).once();

    KubernetesClient client = server.getClient();
    HasMetadata response = client.resource(pod1).inNamespace("ns1").apply();
    assertEquals(pod1, response);
}
 
Example #23
Source File: KubernetesComponentToWorkspaceApplier.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Applies changes on workspace config according to the specified kubernetes/openshift component.
 *
 * @param workspaceConfig workspace config on which changes should be applied
 * @param k8sComponent kubernetes/openshift component that should be applied
 * @param contentProvider content provider that may be used for external component resource
 *     fetching
 * @throws IllegalArgumentException if specified workspace config or plugin component is null
 * @throws IllegalArgumentException if specified component has type different from chePlugin
 * @throws DevfileException if specified content provider is null while kubernetes/openshift
 *     component required external file content
 * @throws DevfileException if external file content is empty or any error occurred during content
 *     retrieving
 */
@Override
public void apply(
    WorkspaceConfigImpl workspaceConfig,
    ComponentImpl k8sComponent,
    FileContentProvider contentProvider)
    throws DevfileException {
  checkArgument(workspaceConfig != null, "Workspace config must not be null");
  checkArgument(k8sComponent != null, "Component must not be null");
  checkArgument(
      kubernetesBasedComponentTypes.contains(k8sComponent.getType()),
      format("Plugin must have %s type", String.join(" or ", kubernetesBasedComponentTypes)));

  String componentContent = retrieveContent(k8sComponent, contentProvider);

  final List<HasMetadata> componentObjects =
      prepareComponentObjects(k8sComponent, componentContent);

  List<PodData> podsData = getPodDatas(componentObjects);
  podsData
      .stream()
      .flatMap(e -> e.getSpec().getContainers().stream())
      .forEach(c -> c.setImagePullPolicy(imagePullPolicy));

  if (Boolean.TRUE.equals(k8sComponent.getMountSources())) {
    applyProjectsVolumes(podsData, componentObjects);
  }

  if (!k8sComponent.getEnv().isEmpty()) {
    podsData.forEach(p -> envVars.apply(p, k8sComponent.getEnv()));
  }

  Map<String, MachineConfigImpl> machineConfigs = prepareMachineConfigs(podsData, k8sComponent);
  linkCommandsToMachineName(workspaceConfig, k8sComponent, machineConfigs.keySet());

  k8sEnvProvisioner.provision(workspaceConfig, environmentType, componentObjects, machineConfigs);
}
 
Example #24
Source File: OpenShiftServiceImpl.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
public <T extends HasMetadata, L extends KubernetesResourceList<T>, D extends Doneable<T>> Watch watchCR(CustomResourceDefinition crd, Class<T> resourceType, Class<L> resourceListType, Class<D> doneableResourceType, BiConsumer<Watcher.Action,T> watcher){
    return getCRDClient(crd, resourceType, resourceListType, doneableResourceType).inNamespace(config.getNamespace()).watch(new Watcher<T>() {
        @Override
        public void eventReceived(Action action, T t) {
            watcher.accept(action, t);
        }

        @Override
        public void onClose(KubernetesClientException e) {
            LOGGER.info("Closing watcher "+this+" on crd "+crd.getMetadata().getName(), e);
        }
    });
}
 
Example #25
Source File: ResourceProvidingDecorator.java    From dekorate with Apache License 2.0 5 votes vote down vote up
public Optional<ObjectMeta> getDeploymentMetadata(KubernetesListBuilder list) {
  return list.getItems()
    .stream()
    .filter(h -> DEPLOYMENT_KINDS.contains(h.getKind()))
    .map(HasMetadata::getMetadata)
    .findFirst();
}
 
Example #26
Source File: KubernetesResourceUtil.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the resource version for the entity or null if it does not have one
 *
 * @param entity entity provided
 * @return returns resource version of provided entity
 */
public static String getResourceVersion(HasMetadata entity) {
  if (entity != null) {
    ObjectMeta metadata = entity.getMetadata();
    if (metadata != null) {
      String resourceVersion = metadata.getResourceVersion();
      if (!Utils.isNullOrEmpty(resourceVersion)) {
        return resourceVersion;
      }
    }
  }
  return null;
}
 
Example #27
Source File: DeploymentConfigEnricher.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
private DeploymentConfig convertFromAppsV1Deployment(HasMetadata item) {
    Deployment resource = (Deployment) item;
    DeploymentConfigBuilder builder = new DeploymentConfigBuilder();
    builder.withMetadata(resource.getMetadata());
    DeploymentSpec spec = resource.getSpec();
    if (spec != null) {
        builder.withSpec(getDeploymentConfigSpec(spec.getReplicas(), spec.getRevisionHistoryLimit(), spec.getSelector(), spec.getTemplate(), spec.getStrategy() != null ? spec.getStrategy().getType() : null));
    }
    return builder.build();
}
 
Example #28
Source File: KubernetesHelper.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
public static Map<String, String> getOrCreateLabels(HasMetadata entity) {
    ObjectMeta metadata = getOrCreateMetadata(entity);
    Map<String, String> answer = metadata.getLabels();
    if (answer == null) {
        // use linked so the annotations can be in the FIFO order
        answer = new LinkedHashMap<>();
        metadata.setLabels(answer);
    }
    return answer;
}
 
Example #29
Source File: OperatorMetricsTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
private AbstractWatchableResourceOperator resourceOperatorWithExistingResource()    {
    return new AbstractWatchableResourceOperator(vertx, null, "TestResource") {
        @Override
        protected MixedOperation operation() {
            return null;
        }

        @Override
        public HasMetadata get(String namespace, String name) {
            return new HasMetadata() {
                @Override
                public ObjectMeta getMetadata() {
                    return null;
                }

                @Override
                public void setMetadata(ObjectMeta objectMeta) {

                }

                @Override
                public String getKind() {
                    return "TestResource";
                }

                @Override
                public String getApiVersion() {
                    return "v1";
                }

                @Override
                public void setApiVersion(String s) {

                }
            };
        }
    };
}
 
Example #30
Source File: DeploymentConfigEnricherTest.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testConversionFromAppsV1Deployment() {
    // Given
    DeploymentConfigEnricher deploymentConfigEnricher = new DeploymentConfigEnricher(context);
    io.fabric8.kubernetes.api.model.apps.Deployment appsV1Deployment = new io.fabric8.kubernetes.api.model.apps.DeploymentBuilder()
            .withNewMetadata().withName("test-app").addToLabels("app", "test-app").endMetadata()
            .withNewSpec()
            .withReplicas(3)
            .withRevisionHistoryLimit(2)
            .withNewSelector().addToMatchLabels("app", "test-app").endSelector()
            .withNewTemplate()
            .withNewMetadata().addToLabels("app", "test-app").endMetadata()
            .withNewSpec()
            .addNewContainer()
            .withName("test-container")
            .withImage("test-image:1.0.0")
            .addNewPort()
            .withContainerPort(80)
            .endPort()
            .endContainer()
            .endSpec()
            .endTemplate()
            .withNewStrategy()
            .withType("Rolling")
            .withNewRollingUpdate().withMaxSurge(new IntOrString(5)).endRollingUpdate()
            .endStrategy()
            .endSpec()
            .build();
    KubernetesListBuilder kubernetesListBuilder = new KubernetesListBuilder().addToItems(appsV1Deployment);

    // When
    deploymentConfigEnricher.create(PlatformMode.openshift, kubernetesListBuilder);

    // Then
    assertEquals(1, kubernetesListBuilder.buildItems().size());
    HasMetadata result = kubernetesListBuilder.buildFirstItem();
    assertTrue(result instanceof DeploymentConfig);
    assertDeploymentConfig((DeploymentConfig) result, "Rolling");
}