io.fabric8.openshift.api.model.Template Java Examples

The following examples show how to use io.fabric8.openshift.api.model.Template. 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: 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 #2
Source File: TemplateTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateWithHandler() {
  Template template = new TemplateBuilder()
    .editOrNewMetadata()
    .withName("tmpl3")
    .withNamespace("test")
    .endMetadata()
    .build();

  server.expect().withPath("/apis/template.openshift.io/v1/namespaces/test/templates").andReturn(200, template).once();
  server.expect().withPath("/apis/template.openshift.io/v1/namespaces/test/templates/tmpl3").andReturn(404, new StatusBuilder().withCode(404).build()).once();

  OpenShiftClient client = server.getOpenshiftClient();

  Template created = client.resource(template).createOrReplace();
  assertNotNull(created);
}
 
Example #3
Source File: TemplateTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testGet() {
  server.expect().withPath("/apis/template.openshift.io/v1/namespaces/test/templates/tmpl1").andReturn(200, new TemplateBuilder()
    .withNewMetadata().withName("tmpl1").endMetadata()
    .build()).once();

  server.expect().withPath("/apis/template.openshift.io/v1/namespaces/ns1/templates/tmpl2").andReturn(200, new TemplateBuilder()
    .withNewMetadata().withName("tmpl2").endMetadata()
    .build()).once();

  OpenShiftClient client = server.getOpenshiftClient();

  Template template = client.templates().withName("tmpl1").get();
  assertNotNull(template);
  assertEquals("tmpl1", template.getMetadata().getName());

  template = client.templates().withName("tmpl2").get();
  assertNull(template);

  template = client.templates().inNamespace("ns1").withName("tmpl2").get();
  assertNotNull(template);
  assertEquals("tmpl2", template.getMetadata().getName());
}
 
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: HelmService.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
private static void createTemplateParameters(HelmConfig helmConfig, File outputDir, File templatesDir) throws IOException {
  final List<HelmParameter> helmParameters = Optional.ofNullable(helmConfig.getTemplates())
      .orElse(Collections.emptyList()).stream()
      .map(Template::getParameters).flatMap(List::stream)
      .map(HelmParameter::new).collect(Collectors.toList());
  final Map<String, String> values = helmParameters.stream().collect(Collectors.toMap(
      HelmParameter::getHelmName, hp -> hp.getParameter().getValue()));

  File outputChartFile = new File(outputDir, VALUES_FILENAME);
  ResourceUtil.save(outputChartFile, values, ResourceFileType.yaml);

  // now lets replace all the parameter expressions in each template
  for (File file : listYamls(templatesDir)) {
    interpolateTemplateParameterExpressionsWithHelmExpressions(file, helmParameters);
  }
}
 
Example #6
Source File: OpenshiftHelperTest.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testProcessTemplatesLocallyNull() throws IOException {
    //Given
    Template template = new TemplateBuilder()
            .withNewMetadata().withName("redis-template").endMetadata()
            .addNewParameter()
            .withDescription("Password used for Redis authentication")
            .withFrom("[A-Z0-9]{8}")
            .withGenerate("expression")
            .withName("REDIS_PASSWORD")
            .endParameter()
            .build();
    boolean failOnMissingParameterValue = true;
    //When
    KubernetesList result = OpenshiftHelper.processTemplatesLocally(template, failOnMissingParameterValue);
    //Then
    assertNull(result);
}
 
Example #7
Source File: DependencyEnricher.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
private void enrichKubernetes(final KubernetesListBuilder builder) {
    final List<HasMetadata> kubernetesItems = new ArrayList<>();
    processArtifactSetResources(this.kubernetesDependencyArtifacts, items -> {
        kubernetesItems.addAll(Arrays.asList(items.toArray(new HasMetadata[items.size()])));
        return null;
    });
    processArtifactSetResources(this.kubernetesTemplateDependencyArtifacts, items -> {
        List<HasMetadata> templates = Arrays.asList(items.toArray(new HasMetadata[items.size()]));

        // lets remove all the plain resources (without any ${PARAM} expressions) which match objects
        // in the Templates found from the k8s-templates.yml files which still contain ${PARAM} expressions
        // to preserve the parameter expressions for dependent kubernetes resources
        for (HasMetadata resource : templates) {
            if (resource instanceof Template) {
                Template template = (Template) resource;
                List<HasMetadata> objects = template.getObjects();
                if (objects != null) {
                    removeTemplateObjects(kubernetesItems, objects);
                    kubernetesItems.addAll(objects);
                }
            }
        }
        return null;
    });
    filterAndAddItemsToBuilder(builder, kubernetesItems);
}
 
Example #8
Source File: HelmMojoTest.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void executeInternalFindTemplatesFromProvidedFile(
    @Mocked File kubernetesTemplate, @Mocked ResourceUtil resourceUtil, @Mocked Template template) throws Exception {

  // Given
  helmMojo.kubernetesTemplate = kubernetesTemplate;
  new Expectations() {{
    mavenProject.getProperties();
    result = new Properties();
    ResourceUtil.load(kubernetesTemplate, KubernetesResource.class, ResourceFileType.yaml);
    result = template;
  }};
  // When
  helmMojo.executeInternal();
  // Then
  assertThat(helmMojo.helm.getTemplates(), contains(template));
}
 
Example #9
Source File: HelmMojo.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
private List<Template> findTemplates() throws IOException {
  final List<Template> ret = new ArrayList<>();
  final File[] sourceFiles;
  if (kubernetesTemplate != null && kubernetesTemplate.isDirectory()) {
    sourceFiles = kubernetesTemplate.listFiles((dir, filename) -> filename.endsWith("-template.yml"));
  } else if (kubernetesTemplate != null) {
    sourceFiles = new File[] { kubernetesTemplate };
  } else {
    sourceFiles = new File[0];
  }
  for (File sourceFile : Objects.requireNonNull(sourceFiles, "No template files found in the provided directory")) {
    final KubernetesResource dto = ResourceUtil.load(sourceFile, KubernetesResource.class, ResourceFileType.yaml);
    if (dto instanceof  Template) {
      ret.add((Template) dto);
    } else if (dto instanceof KubernetesList) {
      Optional.ofNullable(((KubernetesList)dto).getItems())
          .map(List::stream)
          .map(items -> items.filter(Template.class::isInstance).map(item -> (Template)item).collect(Collectors.toList()))
          .ifPresent(ret::addAll);
    }
  }
  return ret;
}
 
Example #10
Source File: TemplateOperationsImpl.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Override
public KubernetesList process(Map<String, String> valuesMap) {
  Template t = get();
  try {
    List<Parameter> parameters = t.getParameters();
    if (parameters != null) {
      for (Parameter p : parameters) {
        String v = valuesMap.get(p.getName());
        if (v != null) {
          p.setGenerate(null);
          p.setValue(v);
        }
      }
    }

    RequestBody body = RequestBody.create(JSON, JSON_MAPPER.writeValueAsString(t));
    Request.Builder requestBuilder = new Request.Builder().post(body).url(getProcessUrl());
    t = handleResponse(requestBuilder);
    KubernetesList l = new KubernetesList();
    l.setItems(t.getObjects());
    return l;
  } catch (Exception e) {
    throw KubernetesClientException.launderThrowable(forOperationType("process"), e);
  }
}
 
Example #11
Source File: ResourceMojo.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
private void resolveTemplateVariablesIfAny(KubernetesList resources) throws MojoExecutionException {
    Template template = findTemplate(resources);
    if (template != null) {
        List<io.fabric8.openshift.api.model.Parameter> parameters = template.getParameters();
        if (parameters == null || parameters.isEmpty()) {
            return;
        }
        File kubernetesYaml = new File(this.targetDir, "kubernetes.yml");
        resolveTemplateVariables(parameters, kubernetesYaml);
        File kubernetesResourceDir = new File(this.targetDir, "kubernetes");
        File[] kubernetesResources = kubernetesResourceDir.listFiles((dir, filename) -> filename.endsWith(".yml"));
        if (kubernetesResources != null) {
            for (File kubernetesResource : kubernetesResources) {
                resolveTemplateVariables(parameters, kubernetesResource);
            }
        }
    }
}
 
Example #12
Source File: ResourceMojo.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
public static File writeResourcesIndividualAndComposite(KubernetesList resources, File resourceFileBase,
    ResourceFileType resourceFileType, KitLogger log) throws MojoExecutionException {

    // entity is object which will be sent to writeResource for openshift.yml
    // if generateRoute is false, this will be set to resources with new list
    // otherwise it will be set to resources with old list.
    Object entity = resources;

    // if the list contains a single Template lets unwrap it
    // in resources already new or old as per condition is set.
    // no need to worry about this for dropping Route.
    Template template = getSingletonTemplate(resources);
    if (template != null) {
        entity = template;
    }

    File file = writeResource(resourceFileBase, entity, resourceFileType);

    // write separate files, one for each resource item
    // resources passed to writeIndividualResources is also new one.
    writeIndividualResources(resources, resourceFileBase, resourceFileType, log);
    return file;
}
 
Example #13
Source File: OpenshiftHelper.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
public static KubernetesList processTemplatesLocally(Template entity, boolean failOnMissingParameterValue) throws IOException {
    List<HasMetadata> objects = null;
    if (entity != null) {
        objects = entity.getObjects();
        if (objects == null || objects.isEmpty()) {
            return null;
        }
    }
    List<Parameter> parameters = entity != null ? entity.getParameters() : null;
    if (parameters != null && !parameters.isEmpty()) {
        String json = "{\"kind\": \"List\", \"apiVersion\": \"" + DEFAULT_API_VERSION + "\",\n" +
                "  \"items\": " + ResourceUtil.toJson(objects) + " }";

        // 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 from = "${" + name + "}";
                String value = parameter.getValue();

                // TODO generate random strings for passwords etc!
                if (StringUtils.isBlank(value)) {
                    if (failOnMissingParameterValue) {
                        throw new IllegalArgumentException("No value available for parameter name: " + name);
                    } else {
                        value = "";
                    }
                }
                json = json.replace(from, value);
            }
        }
        return  OBJECT_MAPPER.readerFor(KubernetesList.class).readValue(json);
    } else {
        KubernetesList answer = new KubernetesList();
        answer.setItems(objects);
        return answer;
    }
}
 
Example #14
Source File: OpenshiftHelper.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
public static Template combineTemplates(Template firstTemplate, Template template) {
    List<HasMetadata> objects = template.getObjects();
    if (objects != null) {
        for (HasMetadata object : objects) {
            addTemplateObject(firstTemplate, object);
        }
    }
    List<Parameter> parameters = firstTemplate.getParameters();
    if (parameters == null) {
        parameters = new ArrayList<>();
        firstTemplate.setParameters(parameters);
    }
    combineParameters(parameters, template.getParameters());
    String name = KubernetesHelper.getName(template);
    if (StringUtils.isNotBlank(name)) {
        // lets merge all the jkube annotations using the template id qualifier as a postfix
        Map<String, String> annotations = KubernetesHelper.getOrCreateAnnotations(firstTemplate);
        Map<String, String> otherAnnotations = KubernetesHelper.getOrCreateAnnotations(template);
        Set<Map.Entry<String, String>> entries = otherAnnotations.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            String key = entry.getKey();
            String value = entry.getValue();
            if (!annotations.containsKey(key)) {
                annotations.put(key, value);
            }
        }
    }
    return firstTemplate;
}
 
Example #15
Source File: OpenshiftHelperTest.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testProcessTemplatesLocallyNotNull() throws IOException {
    //Given
    Template template = new TemplateBuilder()
            .withNewMetadata().withName("redis-template").endMetadata()
            .withObjects(new PodBuilder()
                    .withNewMetadata().withName("redis-master").endMetadata()
                    .withNewSpec()
                    .addNewContainer()
                    .addNewEnv()
                    .withName("REDIS_PASSWORD")
                    .withValue("${REDIS_PASSWORD}")
                    .endEnv()
                    .withImage("dockerfile/redis")
                    .withName("master")
                    .addNewPort()
                    .withProtocol("TCP")
                    .withContainerPort(6379)
                    .endPort()
                    .endContainer()
                    .endSpec()
                    .build())
            .addNewParameter()
            .withDescription("Password used for Redis authentication")
            .withFrom("[A-Z0-9]{8}")
            .withGenerate("expression")
            .withName("REDIS_PASSWORD")
            .endParameter()
            .build();

    boolean failOnMissingParameterValue = false;
    //When
    KubernetesList result = OpenshiftHelper.processTemplatesLocally(template, failOnMissingParameterValue);
    //Then
    assertEquals(1, result.getItems().size());
    assertTrue(result.getItems().get(0) instanceof Pod);
    Pod item = (Pod) result.getItems().get(0);
    assertEquals("REDIS_PASSWORD", item.getSpec().getContainers().get(0).getEnv().get(0).getName());
    assertNotEquals("${REDIS_PASSWORD}", item.getSpec().getContainers().get(0).getEnv().get(0).getValue());
}
 
Example #16
Source File: Fabric8OpenShiftServiceImpl.java    From launchpad-missioncontrol with Apache License 2.0 5 votes vote down vote up
private void applyParameterValueProperties(final OpenShiftProject project, final Template template) {
    RouteList routes = null;
    for (Parameter parameter : template.getParameters()) {
        // Find any parameters with special "fabric8-value" properties
        if (parameter.getAdditionalProperties().containsKey("fabric8-value")
                && parameter.getValue() == null) {
            String value = parameter.getAdditionalProperties().get("fabric8-value").toString();
            Matcher m = PARAM_VAR_PATTERN.matcher(value);
            StringBuffer newval = new StringBuffer();
            while (m.find()) {
                String type = m.group(1);
                String routeName = m.group(2);
                String propertyPath = m.group(3);
                String propertyValue = "";
                // We only support "route/XXX[.spec.host]" for now,
                // but we're prepared for future expansion
                if ("route".equals(type) && ".spec.host".equals(propertyPath)) {
                    // Try to find a Route with that name and use its host name
                    if (routes == null) {
                        routes = client.routes().inNamespace(project.getName()).list();
                    }
                    propertyValue = routes.getItems().stream()
                        .filter(r -> routeName.equals(r.getMetadata().getName()))
                        .map(r -> r.getSpec().getHost())
                        .filter(Objects::nonNull)
                        .findAny()
                        .orElse(propertyValue);
                }
                m.appendReplacement(newval, Matcher.quoteReplacement(propertyValue));
            }
            m.appendTail(newval);
            parameter.setValue(newval.toString());
        }
    }
}
 
Example #17
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 #18
Source File: TemplateTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoadParameterizedNumberTemplate() throws IOException {
  String json = IOHelpers.readFully(getClass().getResourceAsStream("/template-with-number-params.json"));
  server.expect().withPath("/apis/template.openshift.io/v1/namespaces/test/templates/tmpl1").andReturn(200, json).once();

  Map<String, String> map = new HashMap<>();
  map.put("PORT", "8080");

  OpenShiftClient client = server.getOpenshiftClient();
  Template template = client.templates().withParameters(map).withName("tmpl1").get();
  List<HasMetadata> list = template.getObjects();
  assertListIsServiceWithPort8080(list);
}
 
Example #19
Source File: NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
private static <T> List<HasMetadata> asHasMetadata(T item, Boolean enableProccessing) {
  List<HasMetadata> result = new ArrayList<>();
  if (item instanceof KubernetesList) {
    result.addAll(((KubernetesList) item).getItems());
  } else if (item instanceof Template) {

    if (!enableProccessing) {
      result.addAll(((Template) item).getObjects());
    } else {
      result.addAll(processTemplate((Template)item, false));
    }
  } else if (item instanceof KubernetesResourceList) {
    result.addAll(((KubernetesResourceList) item).getItems());
  } else if (item instanceof HasMetadata) {
    result.add((HasMetadata) item);
  }  else if (item instanceof String) {
    try (InputStream is = new ByteArrayInputStream(((String)item).getBytes(StandardCharsets.UTF_8))) {
      return asHasMetadata(unmarshal(is), enableProccessing);
    } catch (IOException e) {
      throw KubernetesClientException.launderThrowable(e);
    }
  } else if (item instanceof Collection) {
    for (Object o : (Collection)item) {
      if (o instanceof HasMetadata) {
        result.add((HasMetadata) o);
      }
    }
  }
  return result;
}
 
Example #20
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 #21
Source File: TemplateIT.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void load() {
  Template template = client.templates()
    .withParameters(Collections.singletonMap("REDIS_PASSWORD", "secret"))
    .inNamespace(currentNamespace)
    .load(getClass().getResourceAsStream("/test-template.yml")).get();
  assertThat(template).isNotNull();
  assertEquals(1, template.getObjects().size());
}
 
Example #22
Source File: TemplateIT.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void delete() {
  ReadyEntity<Template> template1Ready = new ReadyEntity<>(Template.class, client, "foo", this.currentNamespace);
  await().atMost(30, TimeUnit.SECONDS).until(template1Ready);
  boolean bDeleted = client.templates().inNamespace(currentNamespace).withName("foo").delete();
  assertTrue(bDeleted);
}
 
Example #23
Source File: TemplateIT.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@After
public void cleanup() throws InterruptedException {
  if (client.templates().inNamespace(currentNamespace).list().getItems().size()!= 0) {
    client.templates().inNamespace(currentNamespace).withName("foo").delete();
  }

  DeleteEntity<Template> templateDelete = new DeleteEntity<>(Template.class, client, "foo", currentNamespace);
  await().atMost(30, TimeUnit.SECONDS).until(templateDelete);
}
 
Example #24
Source File: TemplateOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public TemplateOperationsImpl(TemplateOperationContext context) {
  super(context.withApiGroupName(TEMPLATE)
    .withPlural("templates"));
  this.parameters = context.getParameters();
  this.type = Template.class;
  this.listType = TemplateList.class;
  this.doneableType = DoneableTemplate.class;
}
 
Example #25
Source File: KubernetesHelper.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
public static void resolveTemplateVariablesIfAny(KubernetesList resources, File targetDir) throws IllegalStateException {
    Template template = findTemplate(resources);
    if (template != null) {
        List<io.fabric8.openshift.api.model.Parameter> parameters = template.getParameters();
        if (parameters == null || parameters.isEmpty()) {
            return;
        }
        File kubernetesYaml = new File(targetDir, "kubernetes.yml");
        resolveTemplateVariables(parameters, kubernetesYaml);
    }
}
 
Example #26
Source File: KubernetesHelper.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
public static Set<HasMetadata> loadResources(File manifest) throws IOException {
    Object dto = ResourceUtil.load(manifest, KubernetesResource.class);
    if (dto == null) {
        throw new IllegalStateException("Cannot load kubernetes manifest " + manifest);
    }

    if (dto instanceof Template) {
        Template template = (Template) dto;
        dto = OpenshiftHelper.processTemplatesLocally(template, false);
    }

    Set<HasMetadata> entities = new TreeSet<>(new HasMetadataComparator());
    entities.addAll(KubernetesHelper.toItemList(dto));
    return entities;
}
 
Example #27
Source File: ApplyService.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
public Object processTemplate(Template entity, String sourceName) {
        try {
            return OpenshiftHelper.processTemplatesLocally(entity, false);
        } catch (IOException e) {
            onApplyError("Failed to process template " + sourceName + ". " + e + ". " + entity, e);
            return null;
        }
}
 
Example #28
Source File: ApplyService.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
protected void doCreateTemplate(Template entity, String namespace, String sourceName) {
    OpenShiftClient openShiftClient = getOpenShiftClient();
    if (openShiftClient != null) {
        log.info("Creating a Template from " + sourceName + " namespace " + namespace + " name " + getName(entity));
        try {
            Object answer = openShiftClient.templates().inNamespace(namespace).create(entity);
            logGeneratedEntity("Created Template: ", namespace, entity, answer);
        } catch (Exception e) {
            onApplyError("Failed to Template entity from " + sourceName + ". " + e + ". " + entity, e);
        }
    }
}
 
Example #29
Source File: KubernetesResourceUtil.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
public static Set<HasMetadata> loadResources(File manifest) throws IOException {
    final Set<HasMetadata> entities = new TreeSet<>(new HasMetadataComparator());
    for (KubernetesResource dto : ResourceUtil.loadList(manifest, KubernetesResource.class)) {
        if (dto == null) {
            throw new IllegalStateException("Cannot load kubernetes manifest " + manifest);
        }
        if (dto instanceof Template) {
            Template template = (Template) dto;
            dto = OpenshiftHelper.processTemplatesLocally(template, false);
        }
        entities.addAll(KubernetesHelper.toItemList(dto));
    }
    return entities;
}
 
Example #30
Source File: HelmServiceIT.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void generateHelmChartsTest() throws Exception {
  // Given
  final HelmConfig helmConfig = new HelmConfig();
  helmConfig.setChart("ITChart");
  helmConfig.setVersion("1337");
  helmConfig.setType("KUBERNEtES,oPenShift");
  helmConfig.setSourceDir(new File(HelmServiceIT.class.getResource("/it/sources").toURI()).getAbsolutePath());
  helmConfig.setOutputDir("target/helm-it");
  helmConfig.setTarballOutputDir("target/helm-it");
  helmConfig.setChartExtension("tar");
  helmConfig.setAdditionalFiles(Collections.singletonList(
      new File(HelmServiceIT.class.getResource("/it/sources/additional-file.txt").toURI())
  ));
  helmConfig.setTemplates(Collections.singletonList(
      ResourceUtil.load(new File(HelmServiceIT.class.getResource("/it/sources/global-template.yml").toURI()), Template.class)
  ));
  final AtomicInteger generatedChartCount = new AtomicInteger(0);
  helmConfig.setGeneratedChartListeners(Collections.singletonList(
      (helmConfig1, type, chartFile) -> generatedChartCount.incrementAndGet()));
  final KitLogger logger = new KitLogger.StdoutLogger();
  // When
  HelmService.generateHelmCharts(logger, helmConfig);
  // Then
  assertThat(new File("target/helm-it/kubernetes/Chart.yaml").exists(), is(true));
  assertThat(new File("target/helm-it/kubernetes/values.yaml").exists(), is(true));
  assertThat(new File("target/helm-it/kubernetes/additional-file.txt").exists(), is(true));
  assertThat(new File("target/helm-it/kubernetes/templates/kubernetes.yaml").exists(), is(true));
  assertThat(new File("target/helm-it/openshift/Chart.yaml").exists(), is(true));
  assertThat(new File("target/helm-it/openshift/values.yaml").exists(), is(true));
  assertThat(new File("target/helm-it/openshift/additional-file.txt").exists(), is(true));
  assertThat(new File("target/helm-it/openshift/templates/test-pod.yaml").exists(), is(true));
  assertThat(new File("target/helm-it/openshift/templates/openshift.yaml").exists(), is(true));
  assertThat(new File("target/helm-it/ITChart-1337-helm.tar").exists(), is(true));
  assertThat(new File("target/helm-it/ITChart-1337-helmshift.tar").exists(), is(true));
  assertYamls();
  assertThat(generatedChartCount.get(), is(2));
}