Java Code Examples for io.fabric8.kubernetes.api.model.KubernetesList#getItems()

The following examples show how to use io.fabric8.kubernetes.api.model.KubernetesList#getItems() . 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: 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 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: 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 4
Source File: KubernetesHelper.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Loads the Kubernetes JSON and converts it to a list of entities
 *
 * @param entity Kubernetes generic resource object
 * @return list of objects of type HasMetadata
 * @throws IOException IOException if anything wrong happens
 */
@SuppressWarnings("unchecked")
public static List<HasMetadata> toItemList(Object entity) throws IOException {
    if (entity instanceof List) {
        return (List<HasMetadata>) entity;
    } else if (entity instanceof HasMetadata[]) {
        HasMetadata[] array = (HasMetadata[]) entity;
        return Arrays.asList(array);
    } else if (entity instanceof KubernetesList) {
        KubernetesList config = (KubernetesList) entity;
        return config.getItems();
    } else if (entity instanceof Template) {
        Template objects = (Template) entity;
        return objects.getObjects();
    } else {
        List<HasMetadata> answer = new ArrayList<>();
        if (entity instanceof HasMetadata) {
            answer.add((HasMetadata) entity);
        }
        return answer;
    }
}
 
Example 5
Source File: ComponentSpringBootExampleTest.java    From dekorate with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldContainComponent() {
  KubernetesList list = Serialization.unmarshalAsList(ComponentSpringBootExampleTest.class.getClassLoader().getResourceAsStream("META-INF/dekorate/halkyon.yml"));
  assertNotNull(list);
  List<HasMetadata> items = list.getItems();
  Assertions.assertEquals(1, items.size());
  Component component = (Component) items.get(0);
  Assertions.assertEquals("Component", component.getKind());
  // This doesn't work during release.
  //assertEquals("https://github.com/dekorateio/dekorate.git", component.getSpec().getBuildConfig().getUrl());
  assertEquals("docker", component.getSpec().getBuildConfig().getType());
  assertEquals("feat-229-override-annotationbased-config", component.getSpec().getBuildConfig().getModuleDirName());
  // This may be null during the release process where HEAD point to a commit instead of a branch.
  //assertNotNull("", component.getSpec().getBuildConfig().getRef());
  assertEquals(DeploymentMode.build, component.getSpec().getDeploymentMode());
  Map<String, String> labels = component.getMetadata().getLabels();
  Assertions.assertNotNull(labels.get("key1-from-properties"));
  Assertions.assertEquals("val1-from-properties", labels.get("key1-from-properties"));
  Assertions.assertEquals("hello-world", component.getMetadata().getName());
}
 
Example 6
Source File: Issue52Test.java    From dekorate with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldContainBuildConfig() {
  KubernetesList list = Serialization.unmarshalAsList(Issue52Test.class.getClassLoader().getResourceAsStream("META-INF/dekorate/halkyon.yml"));
  assertNotNull(list);
  List<HasMetadata> items = list.getItems();
  assertEquals(1, items.size());
  Component component = (Component) items.get(0);
  assertEquals("Component", component.getKind());
  //As the git repo is being changed to local, only not null value is checked
  assertNotNull(component.getSpec().getBuildConfig().getUrl(), "Git url shouldn't be null.");
  assertEquals("s2i", component.getSpec().getBuildConfig().getType());
  assertEquals("feat-52-add-build-spec", component.getSpec().getBuildConfig().getModuleDirName());
  // This may be null during the release when HEAD points to a commit rather than a branch.
  //assertNotNull(component.getSpec().getBuildConfig().getRef(), "Git ref shouldn't be null.");
}
 
Example 7
Source File: KubernetesListHandler.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public KubernetesList replace(OkHttpClient client, Config config, String namespace, KubernetesList item) {
  List<HasMetadata> replacedItems = new ArrayList<>();

  for (HasMetadata metadata : item.getItems()) {
    ResourceHandler<HasMetadata, HasMetadataVisitiableBuilder> handler = Handlers.get(item.getKind(), item.getApiVersion());
    if (handler == null) {
      LOGGER.warn("No handler found for:" + item.getKind() + ". Ignoring");
    } else {
      replacedItems.add(handler.replace(client, config, namespace, metadata));
    }
  }
  return new KubernetesListBuilder(item).withItems(replacedItems).build();
}
 
Example 8
Source File: NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
private static List<HasMetadata> processTemplate(Template template, Boolean failOnMissing)  {
  List<Parameter> parameters = template != null ? template.getParameters() : null;
  KubernetesList list = new KubernetesListBuilder()
    .withItems(template.getObjects())
    .build();

  try {
    String json = OBJECT_MAPPER.writeValueAsString(list);
    if (parameters != null && !parameters.isEmpty()) {
      // lets make a few passes in case there's expressions in values
      for (int i = 0; i < 5; i++) {
        for (Parameter parameter : parameters) {
          String name = parameter.getName();
          String regex = "${" + name + "}";
          String value;
          if (Utils.isNotNullOrEmpty(parameter.getValue())) {
            value = parameter.getValue();
          } else if (EXPRESSION.equals(parameter.getGenerate())) {
            Generex generex = new Generex(parameter.getFrom());
            value = generex.random();
          } else if (failOnMissing) {
            throw new IllegalArgumentException("No value available for parameter name: " + name);
          } else {
            value = "";
          }
          json = json.replace(regex, value);
        }
      }
    }

    list = OBJECT_MAPPER.readValue(json, KubernetesList.class);
  } catch (IOException e) {
    throw KubernetesClientException.launderThrowable(e);
  }
  return list.getItems();
}
 
Example 9
Source File: KubernetesListHandler.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public KubernetesList reload(OkHttpClient client, Config config, String namespace, KubernetesList item) {
  List<HasMetadata> replacedItems = new ArrayList<>();

  for (HasMetadata metadata : item.getItems()) {
    ResourceHandler<HasMetadata, HasMetadataVisitiableBuilder> handler = Handlers.get(item.getKind(), item.getApiVersion());
    if (handler == null) {
      LOGGER.warn("No handler found for:" + item.getKind() + ". Ignoring");
    } else {
      replacedItems.add(handler.reload(client, config, namespace, metadata));
    }
  }
  return new KubernetesListBuilder(item).withItems(replacedItems).build();
}
 
Example 10
Source File: KubernetesListOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public Boolean delete(List<KubernetesList> lists) {
  for (KubernetesList list : lists) {
    for (HasMetadata item : list.getItems()) {
      ResourceHandler<HasMetadata, HasMetadataVisitiableBuilder> handler = Handlers.get(item.getKind(), item.getApiVersion());
      if (!handler.delete(client, config, namespace, DeletionPropagation.BACKGROUND, item)) {
        return false;
      }
    }
  }
  return true;
}
 
Example 11
Source File: ComponentSpringBootExampleTest.java    From dekorate with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldContainComponent() {
  KubernetesList list = Serialization.unmarshalAsList(ComponentSpringBootExampleTest.class.getClassLoader().getResourceAsStream("META-INF/dekorate/halkyon.yml"));
  assertNotNull(list);
  List<HasMetadata> items = list.getItems();
  Assertions.assertEquals(1, items.size());
  Component component = (Component) items.get(0);
  Assertions.assertEquals("Component", component.getKind());
  assertEquals("feat-452-halkyon-requirements-with-annotations", component.getSpec().getBuildConfig().getModuleDirName());
  Capabilities capabilities = component.getSpec().getCapabilities();

  RequiredComponentCapability[] requires = capabilities.getRequires();
  assertEquals("db", requires[0].getName());
  assertEquals("postgres-db", requires[0].getBoundTo());
  assertEquals("database", requires[0].getSpec().getCategory());
  assertEquals("postgres", requires[0].getSpec().getType());
  assertTrue(requires[0].isAutoBindable());
  Parameter[] parameters = requires[0].getSpec().getParameters();
  assertEquals(1, parameters.length);
  Parameter parameter = parameters[0];
  assertEquals("postgres-name", parameter.getName());
  assertEquals("postgres-value", parameter.getValue());

  ComponentCapability[] provides = capabilities.getProvides();
  assertEquals("hello-world-endpoint", provides[0].getName());
  assertEquals("api", provides[0].getSpec().getCategory());
  assertEquals("rest-component", provides[0].getSpec().getType());
  assertEquals("1", provides[0].getSpec().getVersion());
}
 
Example 12
Source File: ComponentSpringBootExampleTest.java    From dekorate with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldContainComponent() {
  KubernetesList list = Serialization.unmarshalAsList(ComponentSpringBootExampleTest.class.getClassLoader().getResourceAsStream("META-INF/dekorate/halkyon.yml"));
  assertNotNull(list);
  List<HasMetadata> items = list.getItems();
  Assertions.assertEquals(1, items.size());
  Component component = (Component) items.get(0);
  Assertions.assertEquals("Component", component.getKind());
  assertEquals("feat-452-halkyon-requirements-annotationless-properties", component.getSpec().getBuildConfig().getModuleDirName());
  Capabilities capabilities = component.getSpec().getCapabilities();

  RequiredComponentCapability[] requires = capabilities.getRequires();
  assertEquals("db", requires[0].getName());
  assertEquals("postgres-db", requires[0].getBoundTo());
  assertEquals("database", requires[0].getSpec().getCategory());
  assertEquals("postgres", requires[0].getSpec().getType());
  assertTrue(requires[0].isAutoBindable());
  Parameter[] parameters = requires[0].getSpec().getParameters();
  assertEquals(1, parameters.length);
  Parameter parameter = parameters[0];
  assertEquals("postgres-name", parameter.getName());
  assertEquals("postgres-value", parameter.getValue());

  ComponentCapability[] provides = capabilities.getProvides();
  assertEquals("hello-world-endpoint", provides[0].getName());
  assertEquals("api", provides[0].getSpec().getCategory());
  assertEquals("rest-component", provides[0].getSpec().getType());
  assertEquals("1", provides[0].getSpec().getVersion());

  assertEquals("goodbye-world-endpoint", provides[1].getName());
  assertEquals("api", provides[1].getSpec().getCategory());
  assertEquals("rest-component", provides[1].getSpec().getType());
  assertEquals("2", provides[1].getSpec().getVersion());
}
 
Example 13
Source File: ResourceMojo.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Returns the Template if the list contains a single Template only otherwise returns null
 */
protected static Template getSingletonTemplate(KubernetesList resources) {
    // if the list contains a single Template lets unwrap it
    if (resources != null) {
        List<HasMetadata> items = resources.getItems();
        if (items != null && items.size() == 1) {
            HasMetadata singleEntity = items.get(0);
            if (singleEntity instanceof Template) {
                return (Template) singleEntity;
            }
        }
    }
    return null;
}
 
Example 14
Source File: ComponentSpringBootExampleTest.java    From dekorate with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldContainComponentWithDefaultValues() {
  KubernetesList list = Serialization.unmarshalAsList(ComponentSpringBootExampleTest.class.getClassLoader().getResourceAsStream("META-INF/dekorate/halkyon.yml"));
  assertNotNull(list);
  List<HasMetadata> items = list.getItems();
  assertEquals(1, items.size());
  Component component = (Component) items.get(0);
  assertEquals("Component", component.getKind());
  assertEquals("halkyon-example", component.getMetadata().getName());
  assertEquals(1, component.getMetadata().getLabels().size());
  assertNotNull(component.getSpec().getBuildConfig());
  assertNotNull(component.getSpec().getBuildConfig().getUrl());
}
 
Example 15
Source File: ComponentSpringBootExampleTest.java    From dekorate with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldContainComponent() {
  KubernetesList list = Serialization.unmarshalAsList(ComponentSpringBootExampleTest.class.getClassLoader().getResourceAsStream("META-INF/dekorate/halkyon.yml"));
  assertNotNull(list);
  List<HasMetadata> items = list.getItems();
  Assertions.assertEquals(1, items.size());
  Component component = (Component) items.get(0);
  Assertions.assertEquals("Component", component.getKind());
  assertEquals("docker", component.getSpec().getBuildConfig().getType());
  assertEquals("halkyon-example-annotationless-properties", component.getSpec().getBuildConfig().getModuleDirName());
  assertEquals(DeploymentMode.build, component.getSpec().getDeploymentMode());
  assertNotNull("", component.getSpec().getBuildConfig().getRef());
  // Breaks release
  //assertEquals("https://github.com/dekorateio/dekorate.git", component.getSpec().getBuildConfig().getUrl());
}
 
Example 16
Source File: ApplyService.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
public void applyList(KubernetesList list, String sourceName) throws Exception {
    List<HasMetadata> entities = list.getItems();
    if (entities != null) {
        for (Object entity : entities) {
            applyEntity(entity, sourceName);
        }
    }
}
 
Example 17
Source File: HelmMojo.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
private String findIconURL() throws MojoExecutionException {
  String answer = null;
  if (kubernetesManifest != null && kubernetesManifest.isFile()) {
    KubernetesResource dto;
    try {
      dto = ResourceUtil.load(kubernetesManifest, KubernetesResource.class);
    } catch (IOException e) {
      throw new MojoExecutionException("Failed to load kubernetes YAML " + kubernetesManifest + ". " + e, e);
    }
    if (dto instanceof HasMetadata) {
      answer = KubernetesHelper.getOrCreateAnnotations((HasMetadata) dto).get("jkube.io/iconUrl");
    }
    if (StringUtils.isBlank(answer) && dto instanceof KubernetesList) {
      KubernetesList list = (KubernetesList) dto;
      List<HasMetadata> items = list.getItems();
      if (items != null) {
        for (HasMetadata item : items) {
          answer = KubernetesHelper.getOrCreateAnnotations(item).get("jkube.io/iconUrl");
          if (StringUtils.isNotBlank(answer)) {
            break;
          }
        }
      }
    }
  } else {
    getLog().warn("No kubernetes manifest file has been generated yet by the kubernetes:resource goal at: " + kubernetesManifest);
  }
  return answer;
}
 
Example 18
Source File: ResourceMojo.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
private static void writeIndividualResources(KubernetesList resources, File targetDir,
    ResourceFileType resourceFileType, KitLogger log) throws MojoExecutionException {
    for (HasMetadata item : resources.getItems()) {
        String name = KubernetesHelper.getName(item);
        if (StringUtils.isBlank(name)) {
            log.error("No name for generated item %s", item);
            continue;
        }
        String itemFile = KubernetesResourceUtil.getNameWithSuffix(name, item.getKind());

        // Here we are writing individual file for all the resources.
        File itemTarget = new File(targetDir, itemFile);
        writeResource(itemTarget, item, resourceFileType);
    }
}
 
Example 19
Source File: ComponentSpringBootExampleTest.java    From dekorate with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldContainComponent() {
  KubernetesList list = Serialization.unmarshalAsList(ComponentSpringBootExampleTest.class.getClassLoader().getResourceAsStream("META-INF/dekorate/halkyon.yml"));
  assertNotNull(list);
  List<HasMetadata> items = list.getItems();
  assertEquals(1, items.size());
  Component component = (Component) items.get(0);
  assertEquals("Component", component.getKind());
  assertEquals("feat-452-halkyon-requirements-annotationless-yml", component.getSpec().getBuildConfig().getModuleDirName());
  Capabilities capabilities = component.getSpec().getCapabilities();

  RequiredComponentCapability[] requires = capabilities.getRequires();
  assertEquals(1, requires.length);
  final RequiredComponentCapability require = requires[0];
  assertEquals("db", require.getName());
  assertEquals("postgres-db", require.getBoundTo());
  assertEquals("database", require.getSpec().getCategory());
  assertEquals("postgres", require.getSpec().getType());
  assertTrue(require.isAutoBindable());
  Parameter[] parameters = require.getSpec().getParameters();
  assertEquals(1, parameters.length);
  Parameter parameter = parameters[0];
  assertEquals("postgres-name", parameter.getName());
  assertEquals("postgres-value", parameter.getValue());

  ComponentCapability[] provides = capabilities.getProvides();
  assertEquals(2, provides.length);
  assertEquals("hello-world-endpoint", provides[0].getName());
  assertEquals("api", provides[0].getSpec().getCategory());
  assertEquals("rest-component", provides[0].getSpec().getType());
  assertEquals("1", provides[0].getSpec().getVersion());

  assertEquals("goodbye-world-endpoint", provides[1].getName());
  assertEquals("api", provides[1].getSpec().getCategory());
  assertEquals("rest-component", provides[1].getSpec().getType());
  assertEquals("2", provides[1].getSpec().getVersion());
  parameters = provides[1].getSpec().getParameters();
  assertEquals(1, parameters.length);
  parameter = parameters[0];
  assertEquals("goodbye-name", parameter.getName());
  assertEquals("goodbye-value", parameter.getValue());
}
 
Example 20
Source File: OpenshiftSessionListener.java    From dekorate with Apache License 2.0 4 votes vote down vote up
@Override
public void onClosed() {
  Session session = getSession();
  Project project = getProject();
  // We ned to set the TTCL, becuase the KubenretesClient used in this part of
  // code, needs TTCL so that java.util.ServiceLoader can work.
  ClassLoader tccl = Thread.currentThread().getContextClassLoader();
  List<ProjectHook> hooks = new ArrayList<>();

  try {
    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
    Optional<OpenshiftConfig> optionalAppConfig = session.configurators().get(OpenshiftConfig.class);
    Optional<ImageConfiguration> optionalImageConfig = session.configurators().getImageConfig(BuildServiceFactories.supplierMatches(project));

    if (!optionalAppConfig.isPresent() || !optionalImageConfig.isPresent()) {
      return;
    }

    OpenshiftConfig openshiftConfig = optionalAppConfig.get();
    ImageConfiguration imageConfig = optionalImageConfig.get();

    String name = session.configurators().get(OpenshiftConfig.class).map(c -> c.getName())
        .orElse(getProject().getBuildInfo().getName());

    BuildService buildService = null;
    boolean s2iEnabled =  imageConfig instanceof S2iBuildConfig && ((S2iBuildConfig)imageConfig).isEnabled();
    if (imageConfig.isAutoBuildEnabled() || imageConfig.isAutoPushEnabled() || openshiftConfig.isAutoDeployEnabled()) {

      KubernetesList list = session.getGeneratedResources().get("openshift");
      List<HasMetadata> generated = list != null ? list.getItems() : Collections.emptyList();

      try {
        buildService = optionalImageConfig.map(BuildServiceFactories.create(getProject(), generated))
            .orElseThrow(() -> new IllegalStateException("No applicable BuildServiceFactory found."));
      } catch (Exception e) {
        BuildServiceFactories.log(project, session.configurators().getAll(ImageConfiguration.class));
        throw DekorateException.launderThrowable("Failed to lookup BuildService.", e);
      }

      hooks.add(new ImageBuildHook(getProject(), buildService));
    }

    if (imageConfig.isAutoPushEnabled() && !s2iEnabled) {
      hooks.add(new ImagePushHook(getProject(), buildService));
    }

    if (openshiftConfig.isAutoDeployEnabled()) {
      hooks.add(new ResourcesApplyHook(getProject(), OPENSHIFT, "oc"));
    }

  } finally {
    Thread.currentThread().setContextClassLoader(tccl);
    if (!hooks.isEmpty()) {
      OrderedHook hook = OrderedHook.create(hooks.toArray(new ProjectHook[hooks.size()]));
      hook.register();
    }
  }
}