Java Code Examples for io.fabric8.kubernetes.api.model.KubernetesListBuilder#addToItems()

The following examples show how to use io.fabric8.kubernetes.api.model.KubernetesListBuilder#addToItems() . 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: AddBuilderImageStreamResourceDecorator.java    From dekorate with Apache License 2.0 6 votes vote down vote up
public void visit(KubernetesListBuilder list) {
  ObjectMeta meta = getMandatoryDeploymentMetadata(list);

  String repository = Images.getRepository(config.getBuilderImage());

  String name = !repository.contains("/")
    ? repository
    : repository.substring(repository.lastIndexOf("/") + 1);

  String dockerImageRepo = Images.removeTag(config.getBuilderImage());

  list.addToItems(new ImageStreamBuilder()
    .withNewMetadata()
    .withName(name)
    .withLabels(meta.getLabels())
    .endMetadata()
    .withNewSpec()
    .withDockerImageRepository(dockerImageRepo)
    .endSpec());
}
 
Example 2
Source File: AddRoleBindingResourceDecorator.java    From dekorate with Apache License 2.0 6 votes vote down vote up
public void visit(KubernetesListBuilder list) {
  ObjectMeta meta = getMandatoryDeploymentMetadata(list);
  String name = Strings.isNotNullOrEmpty(this.name) ? this.name :  meta.getName() + ":view";
  String serviceAccount = Strings.isNotNullOrEmpty(this.serviceAccount) ? this.serviceAccount :  meta.getName();

  list.addToItems(new RoleBindingBuilder()
    .withNewMetadata()
    .withName(name)
    .withLabels(meta.getLabels())
    .endMetadata()
    .withNewRoleRef()
    .withKind(kind.name())
    .withName(role)
    .withApiGroup(DEFAULT_RBAC_API_GROUP)
    .endRoleRef()
    .addNewSubject()
    .withKind("ServiceAccount")
    .withName(serviceAccount)
    .endSubject());
}
 
Example 3
Source File: AptReader.java    From dekorate with Apache License 2.0 6 votes vote down vote up
private Map<String, KubernetesList> read(File file) {
  try (InputStream is = new FileInputStream(file)) {
    final Matcher fileNameMatcher = inputFileIncludePattern.matcher(file.getName());
    final String name = fileNameMatcher.find() ? fileNameMatcher.group(1) : "invalid-name";
    final KubernetesResource resource = Serialization.unmarshal(is, KubernetesResource.class);
    if (resource instanceof KubernetesList) {
      return Collections.singletonMap(name,  (KubernetesList) resource);
    } else if (resource instanceof HasMetadata) {
      final KubernetesListBuilder klb = new KubernetesListBuilder();
      klb.addToItems((HasMetadata) resource);
      return Collections.singletonMap(name, klb.build());
    }
  } catch (IOException e) {
    processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, file.getAbsolutePath() + " not found.");
  }
  return null;
}
 
Example 4
Source File: AddServiceMonitorResourceDecorator.java    From dekorate with Apache License 2.0 6 votes vote down vote up
public void visit(KubernetesListBuilder list) {
  ObjectMeta meta = getMandatoryDeploymentMetadata(list);
  list.addToItems(new ServiceMonitorBuilder()
                  .withNewMetadata()
                  .withName(meta.getName())
                  .withLabels(meta.getLabels())
                  .endMetadata()
                  .withNewSpec()
                  .withNewSelector()
                  .addToMatchLabels(meta.getLabels())
                  .endSelector()
                  .addNewEndpoint()
                  .withPort(config.getPort())
                  .withNewPath(config.getPath())
                  .withInterval(config.getInterval() + "s")
                  .withHonorLabels(config.isHonorLabels())
                  .endEndpoint()
                  .endSpec());
}
 
Example 5
Source File: AddApplicationResourceDecorator.java    From dekorate with Apache License 2.0 6 votes vote down vote up
public void visit(KubernetesListBuilder list) {
  ObjectMeta meta = getMandatoryDeploymentMetadata(list);
  list.addToItems(new ApplicationBuilder()
           .withNewMetadata()
           .withName(meta.getName())
           .withLabels(meta.getLabels())
           .endMetadata()
           .withNewSpec()
           .withNewSelector()
           .withMatchLabels(meta.getLabels())
           .endSelector()
           .withNewDescriptor()
           .withVersion(meta.getLabels().getOrDefault(Labels.VERSION, "latest"))
           .withOwners(Arrays.stream(config.getOwners()).map(AddApplicationResourceDecorator::adapt).collect(Collectors.toList()))
           .withLinks(Arrays.stream(config.getLinks()).map(AddApplicationResourceDecorator::adapt).collect(Collectors.toList()))
           .withMaintainers(Arrays.stream(config.getMaintainers()).map(AddApplicationResourceDecorator::adapt).collect(Collectors.toList()))
           .withIcons(Arrays.stream(config.getIcons()).map(AddApplicationResourceDecorator::adapt).collect(Collectors.toList()))
           .withKeywords(config.getKeywords())
           .withNotes(config.getNotes())
           .endDescriptor()
           .endSpec());
}
 
Example 6
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 7
Source File: OpenshiftBuildService.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
private void checkOrCreateImageStream(BuildServiceConfig config, OpenShiftClient client, KubernetesListBuilder builder, String imageStreamName) {
    boolean hasImageStream = client.imageStreams().withName(imageStreamName).get() != null;
    if (hasImageStream && config.getBuildRecreateMode().isImageStream()) {
        client.imageStreams().withName(imageStreamName).delete();
        hasImageStream = false;
    }
    if (!hasImageStream) {
        log.info("Creating ImageStream %s", imageStreamName);
        builder.addToItems(new ImageStreamBuilder()
            .withNewMetadata()
                .withName(imageStreamName)
            .endMetadata()
            .withNewSpec()
                .withNewLookupPolicy()
                    .withLocal(config.isS2iImageStreamLookupPolicyLocal())
                .endLookupPolicy()
            .endSpec()
            .build()
        );
    } else {
        log.info("Adding to ImageStream %s", imageStreamName);
    }
}
 
Example 8
Source File: RouteEnricher.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void create(PlatformMode platformMode, final KubernetesListBuilder listBuilder) {
    ResourceConfig resourceConfig = getConfiguration().getResource();

    if (resourceConfig != null && resourceConfig.getRouteDomain() != null) {
        routeDomainPostfix = resourceConfig.getRouteDomain();
    }

    if(platformMode == PlatformMode.openshift && generateRoute.equals(Boolean.TRUE)) {
        final List<Route> routes = new ArrayList<>();
        listBuilder.accept(new TypedVisitor<ServiceBuilder>() {

            @Override
            public void visit(ServiceBuilder serviceBuilder) {
                addRoute(listBuilder, serviceBuilder, routes);
            }
        });

        if (!routes.isEmpty()) {
            Route[] routeArray = new Route[routes.size()];
            routes.toArray(routeArray);
            listBuilder.addToItems(routeArray);
        }
    }
}
 
Example 9
Source File: DockerHealthCheckEnricherTest.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
private KubernetesListBuilder addDeployment(KubernetesListBuilder list, String name) {
    return list.addToItems(new DeploymentBuilder()
        .withNewMetadata()
        .withName(name)
        .endMetadata()
        .withNewSpec()
        .withNewTemplate()
        .withNewSpec()
        .addNewContainer()
        .withName(name)
        .endContainer()
        .endSpec()
        .endTemplate()
        .endSpec()
        .build());
}
 
Example 10
Source File: OpenshiftBuildService.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
private String createBuildConfig(KubernetesListBuilder builder, String buildName, BuildStrategy buildStrategyResource, BuildOutput buildOutput) {
    log.info("Creating BuildServiceConfig %s for %s build", buildName, buildStrategyResource.getType());
    builder.addToItems(new BuildConfigBuilder()
        .withNewMetadata()
        .withName(buildName)
        .endMetadata()
        .withSpec(getBuildConfigSpec(buildStrategyResource, buildOutput))
        .build()
    );
    return buildName;
}
 
Example 11
Source File: DefaultNamespaceEnricher.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * This method will create a default Namespace or Project if a namespace property is
 * specified in the xml resourceConfig or as a parameter to a mojo.
 * @param platformMode platform mode whether it's Kubernetes or OpenShift
 * @param builder list of kubernetes resources
 */
@Override
public void create(PlatformMode platformMode, KubernetesListBuilder builder) {

    final String name = config.getNamespace();

    if (name == null || name.isEmpty()) {
        return;
    }

    if (!KubernetesResourceUtil.checkForKind(builder, NAMESPACE_KINDS)) {
        String type = getConfig(Config.type);
        if ("project".equalsIgnoreCase(type) || "namespace".equalsIgnoreCase(type)) {
            if (platformMode == PlatformMode.kubernetes) {

                log.info("Adding a default Namespace:" + config.getNamespace());
                Namespace namespace = handlerHub.getNamespaceHandler().getNamespace(config.getNamespace());
                builder.addToNamespaceItems(namespace);
            } else {

                log.info("Adding a default Project" + config.getNamespace());
                Project project = handlerHub.getProjectHandler().getProject(config.getNamespace());
                builder.addToItems(project);
            }
        }
    }
}
 
Example 12
Source File: AddDockerImageStreamResourceDecorator.java    From dekorate with Apache License 2.0 5 votes vote down vote up
public void visit(KubernetesListBuilder list) {
  ObjectMeta meta = getMandatoryDeploymentMetadata(list);

  list.addToItems(new ImageStreamBuilder()
    .withNewMetadata()
      .withName(config.getName())
    .withLabels(meta.getLabels())
    .endMetadata()
    .withNewSpec()
      .withDockerImageRepository(dockerImageRepository)
    .endSpec());
}
 
Example 13
Source File: AddOutputImageStreamResourceDecorator.java    From dekorate with Apache License 2.0 5 votes vote down vote up
public void visit(KubernetesListBuilder list) {
  ObjectMeta meta = getMandatoryDeploymentMetadata(list);

  list.addToItems(new ImageStreamBuilder()
    .withNewMetadata()
    .withName(config.getName())
    .withLabels(meta.getLabels())
    .endMetadata()
    .withNewSpec()
    .endSpec());
}
 
Example 14
Source File: AddServiceBindingResourceDecorator.java    From dekorate with Apache License 2.0 5 votes vote down vote up
public void visit(KubernetesListBuilder list) {
  ObjectMeta meta = getMandatoryDeploymentMetadata(list);
        list.addToItems(new ServiceBindingBuilder()
                        .withNewMetadata()
                        .withName(instance.getName())
                        .endMetadata()
                        .withNewSpec()
                        .withNewInstanceRef(instance.getName())
                        .withSecretName(instance.getBindingSecret())
                        .endSpec());
}
 
Example 15
Source File: AddServiceInstanceResourceDecorator.java    From dekorate with Apache License 2.0 5 votes vote down vote up
public void visit(KubernetesListBuilder list) {
  ObjectMeta meta = getMandatoryDeploymentMetadata(list);
  list.addToItems(new ServiceInstanceBuilder()
                  .withNewMetadata()
                  .withName(meta.getName())
                  .endMetadata()
                  .withNewSpec()
                  .withClusterServiceClassExternalName(instance.getServiceClass())
                  .withClusterServicePlanExternalName(instance.getServicePlan())
                  .withParameters(toMap(instance.getParameters()))
                  .endSpec());
}
 
Example 16
Source File: ProjectEnricher.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void create(PlatformMode platformMode, KubernetesListBuilder builder) {
    if(platformMode == PlatformMode.openshift) {
        for(HasMetadata item : builder.buildItems()) {
            if(item instanceof Namespace) {
                Project project = convertToProject((Namespace) item);
                removeItemFromKubernetesBuilder(builder, item);
                builder.addToItems(project);
            }
        }
    }
}
 
Example 17
Source File: KubernetesResourceUtil.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Read all Kubernetes resource fragments from a directory and create a {@link KubernetesListBuilder} which
 * can be adapted later.
 *
 * @param platformMode platform whether it's Kubernetes/OpenShift
 * @param apiVersions the api versions to use
 * @param defaultName the default name to use when none is given
 * @param resourceFiles files to add.
 * @return the list builder
 * @throws IOException IOException in case file is not found
 */
public static KubernetesListBuilder readResourceFragmentsFrom(PlatformMode platformMode, ResourceVersioning apiVersions,
                                                              String defaultName,
                                                              File[] resourceFiles) throws IOException {
    KubernetesListBuilder builder = new KubernetesListBuilder();
    if (resourceFiles != null) {
        for (File file : resourceFiles) {
            if(file.getName().endsWith("cr.yml") || file.getName().endsWith("cr.yaml")) // Don't process custom resources
                continue;
            HasMetadata resource = getResource(platformMode, apiVersions, file, defaultName);
            builder.addToItems(resource);
        }
    }
    return builder;
}
 
Example 18
Source File: DefaultControllerEnricher.java    From jkube with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void create(PlatformMode platformMode, KubernetesListBuilder builder) {
    final String name = getConfig(Config.name, JKubeProjectUtil.createDefaultResourceName(getContext().getGav().getSanitizedArtifactId()));
    ResourceConfig xmlResourceConfig = Optional.ofNullable(getConfiguration().getResource())
        .orElse(ResourceConfig.builder().build());
    ResourceConfig config = ResourceConfig.toBuilder(xmlResourceConfig)
            .controllerName(name)
            .imagePullPolicy(getImagePullPolicy(xmlResourceConfig, getConfig(Config.pullPolicy)))
            .replicas(getReplicaCount(builder, xmlResourceConfig, Configs.asInt(getConfig(Config.replicaCount))))
            .build();

    final List<ImageConfiguration> images = getImages();

    // Check if at least a replica set is added. If not add a default one
    if (!KubernetesResourceUtil.checkForKind(builder, POD_CONTROLLER_KINDS)) {
        // At least one image must be present, otherwise the resulting config will be invalid
        if (!images.isEmpty()) {
            String type = getConfig(Config.type);
            if ("deployment".equalsIgnoreCase(type) || "deploymentConfig".equalsIgnoreCase(type)) {
                if (platformMode == PlatformMode.kubernetes  || (platformMode == PlatformMode.openshift && useDeploymentForOpenShift())) {
                    log.info("Adding a default Deployment");
                    Deployment deployment = deployHandler.getDeployment(config, images);
                    builder.addToItems(deployment);
                    setProcessingInstruction(FABRIC8_GENERATED_CONTAINERS, getContainersFromPodSpec(deployment.getSpec().getTemplate()));
                } else {
                    log.info("Adding a default DeploymentConfig");
                    DeploymentConfig deploymentConfig = deployConfigHandler.getDeploymentConfig(config, images, getOpenshiftDeployTimeoutInSeconds(3600L), getValueFromConfig(IMAGE_CHANGE_TRIGGERS, true), getValueFromConfig(OPENSHIFT_ENABLE_AUTOMATIC_TRIGGER, true), isOpenShiftMode(), getProcessingInstructionViaKey(FABRIC8_GENERATED_CONTAINERS));
                    builder.addToItems(deploymentConfig);
                    setProcessingInstruction(FABRIC8_GENERATED_CONTAINERS, getContainersFromPodSpec(deploymentConfig.getSpec().getTemplate()));
                }
            } else if ("statefulSet".equalsIgnoreCase(type)) {
                log.info("Adding a default StatefulSet");
                StatefulSet statefulSet = statefulSetHandler.getStatefulSet(config, images);
                builder.addToItems(statefulSet);
                setProcessingInstruction(FABRIC8_GENERATED_CONTAINERS, getContainersFromPodSpec(statefulSet.getSpec().getTemplate()));
            } else if ("daemonSet".equalsIgnoreCase(type)) {
                log.info("Adding a default DaemonSet");
                DaemonSet daemonSet = daemonSetHandler.getDaemonSet(config, images);
                builder.addToItems(daemonSet);
                setProcessingInstruction(FABRIC8_GENERATED_CONTAINERS, getContainersFromPodSpec(daemonSet.getSpec().getTemplate()));
            } else if ("replicaSet".equalsIgnoreCase(type)) {
                log.info("Adding a default ReplicaSet");
                ReplicaSet replicaSet = rsHandler.getReplicaSet(config, images);
                builder.addToItems(replicaSet);
                setProcessingInstruction(FABRIC8_GENERATED_CONTAINERS, getContainersFromPodSpec(replicaSet.getSpec().getTemplate()));
            } else if ("replicationController".equalsIgnoreCase(type)) {
                log.info("Adding a default ReplicationController");
                ReplicationController replicationController = rcHandler.getReplicationController(config, images);
                builder.addToReplicationControllerItems(replicationController);
                setProcessingInstruction(FABRIC8_GENERATED_CONTAINERS, getContainersFromPodSpec(replicationController.getSpec().getTemplate()));
            } else if ("job".equalsIgnoreCase(type)) {
                log.info("Adding a default Job");
                Job job = jobHandler.getJob(config, images);
                builder.addToItems(job);
                setProcessingInstruction(FABRIC8_GENERATED_CONTAINERS, getContainersFromPodSpec(job.getSpec().getTemplate()));
            }
        }
    }
}
 
Example 19
Source File: AddBuildConfigResourceDecorator.java    From dekorate with Apache License 2.0 4 votes vote down vote up
public void visit(KubernetesListBuilder list) {
  ObjectMeta meta = getMandatoryDeploymentMetadata(list);

  String repository = Images.getRepository(config.getBuilderImage());
  String builderRepository = Images.getRepository(config.getBuilderImage());
  String builderTag = Images.getTag(config.getBuilderImage());

  String builderName = !builderRepository.contains("/")
    ? builderRepository
    : builderRepository.substring(builderRepository.lastIndexOf("/") + 1);

  //First we need to consult the labels
  String fallbackVersion = Strings.isNotNullOrEmpty(config.getVersion()) ? config.getVersion() : LATEST;
  String version = meta.getLabels().getOrDefault(Labels.VERSION, fallbackVersion);

  list.addToItems(new BuildConfigBuilder()
    .withNewMetadata()
    .withName(config.getName())
    .withLabels(meta.getLabels())
    .endMetadata()
    .withNewSpec()
    .withNewOutput()
    .withNewTo()
    .withKind(IMAGESTREAMTAG)
    .withName(config.getName() + ":" + version)
    .endTo()
    .endOutput()
    .withNewSource()
    .withNewBinary()
    .endBinary()
    .endSource()
    .withNewStrategy()
    .withNewSourceStrategy()
    .withEnv()
    .withNewFrom()
    .withKind(IMAGESTREAMTAG)
    .withName(builderName + ":" + builderTag)
    .endFrom()
    .endSourceStrategy()
    .endStrategy()
    .endSpec());
}
 
Example 20
Source File: TaskProvidingDecorator.java    From dekorate with Apache License 2.0 4 votes vote down vote up
@Override
public void visit(KubernetesListBuilder list) {
  list.addToItems(task);
}