Java Code Examples for io.fabric8.kubernetes.api.model.ObjectMeta#setNamespace()

The following examples show how to use io.fabric8.kubernetes.api.model.ObjectMeta#setNamespace() . 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: MockKubernetesServerSupport.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
protected void createMockService(final String serviceName, final String ip, final Map<String, String> labels, final String namespace) {
    final ServiceSpec serviceSpec = new ServiceSpec();
    serviceSpec.setPorts(Collections.singletonList(new ServicePort("http", 0, 8080, "http", new IntOrString(8080))));
    serviceSpec.setClusterIP(ip);
    serviceSpec.setType("ClusterIP");
    serviceSpec.setSessionAffinity("ClientIP");

    final ObjectMeta metadata = new ObjectMeta();
    metadata.setName(serviceName);
    metadata.setNamespace(MOCK_NAMESPACE);
    metadata.setLabels(labels);

    final Service service = new Service("v1", "Service", metadata, serviceSpec, new ServiceStatus(new LoadBalancerStatus()));
    if (namespace != null) {
        this.server.getClient().inNamespace(namespace).services().create(service);
    } else {
        this.server.getClient().services().create(service);
    }

}
 
Example 2
Source File: KubernetesDiscoveredServiceWorkItemHandlerTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testGivenServiceExists() {
    final ServiceSpec serviceSpec = new ServiceSpec();
    serviceSpec.setPorts(Collections.singletonList(new ServicePort("http", 0, 8080, "http", new IntOrString(8080))));
    serviceSpec.setClusterIP("172.30.158.31");
    serviceSpec.setType("ClusterIP");
    serviceSpec.setSessionAffinity("ClientIP");

    final ObjectMeta metadata = new ObjectMeta();
    metadata.setName("test-kieserver");
    metadata.setNamespace(MOCK_NAMESPACE);
    metadata.setLabels(Collections.singletonMap("test-kieserver", "service"));

    final Service service = new Service("v1", "Service", metadata, serviceSpec, new ServiceStatus(new LoadBalancerStatus()));
    getClient().services().create(service);

    final DiscoveredServiceWorkItemHandler handler = new TestDiscoveredServiceWorkItemHandler(this);
    final ServiceInfo serviceInfo = handler.findEndpoint(MOCK_NAMESPACE, "test-kieserver");
    assertThat(serviceInfo, notNullValue());
    assertThat(serviceInfo.getUrl(), is("http://172.30.158.31:8080/test-kieserver"));
}
 
Example 3
Source File: KubernetesService.java    From vault-crd with Apache License 2.0 6 votes vote down vote up
private ObjectMeta metaData(ObjectMeta resource, String compare) {
    ObjectMeta meta = new ObjectMeta();
    meta.setNamespace(resource.getNamespace());
    meta.setName(resource.getName());
    if (resource.getLabels() != null) {
        meta.setLabels(resource.getLabels());
    }

    HashMap<String, String> annotations = new HashMap<>();
    if (resource.getAnnotations() != null) {
        annotations.putAll(resource.getAnnotations());
    }
    annotations.put(crdName + LAST_UPDATE_ANNOTATION, LocalDateTime.now().toString());
    annotations.put(crdName + COMPARE_ANNOTATION, compare);
    meta.setAnnotations(annotations);
    return meta;
}
 
Example 4
Source File: TillerInstaller.java    From microbean-helm with Apache License 2.0 6 votes vote down vote up
protected Service createService(final String namespace,
                                final String serviceName,
                                Map<String, String> labels) {
  labels = normalizeLabels(labels);

  final Service service = new Service();
  
  final ObjectMeta metadata = new ObjectMeta();
  metadata.setNamespace(normalizeNamespace(namespace));
  metadata.setName(normalizeServiceName(serviceName));
  metadata.setLabels(labels);
  
  service.setMetadata(metadata);
  service.setSpec(this.createServiceSpec(labels));

  return service;
}
 
Example 5
Source File: KubernetesDiscoveryClientFilterMetadataTest.java    From spring-cloud-kubernetes with Apache License 2.0 6 votes vote down vote up
private void setupServiceWithLabelsAndAnnotationsAndPorts(String serviceId,
		String namespace, Map<String, String> labels, Map<String, String> annotations,
		Map<Integer, String> ports) {
	final Service service = new ServiceBuilder().withNewMetadata()
			.withNamespace(namespace).withLabels(labels).withAnnotations(annotations)
			.endMetadata().withNewSpec().withPorts(getServicePorts(ports)).endSpec()
			.build();
	when(this.serviceOperation.withName(serviceId)).thenReturn(this.serviceResource);
	when(this.serviceResource.get()).thenReturn(service);
	when(this.kubernetesClient.services()).thenReturn(this.serviceOperation);
	when(this.kubernetesClient.services().inNamespace(anyString()))
			.thenReturn(this.serviceOperation);

	ObjectMeta objectMeta = new ObjectMeta();
	objectMeta.setNamespace(namespace);

	final Endpoints endpoints = new EndpointsBuilder().withMetadata(objectMeta)
			.addNewSubset().addAllToPorts(getEndpointPorts(ports)).addNewAddress()
			.endAddress().endSubset().build();

	when(this.endpointsResource.get()).thenReturn(endpoints);
	when(this.endpointsOperation.withName(serviceId))
			.thenReturn(this.endpointsResource);
	when(this.kubernetesClient.endpoints()).thenReturn(this.endpointsOperation);
}
 
Example 6
Source File: ApplyService.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
public void applyRoleBinding(RoleBinding entity, String sourceName) {
    String id = getName(entity);

    Objects.requireNonNull(id, "No name for " + entity + " " + sourceName);
    String namespace = KubernetesHelper.getNamespace(entity);
    if (StringUtils.isBlank(namespace)) {
        namespace = getNamespace();
    }
    applyNamespace(namespace);
    RoleBinding old = kubernetesClient.rbac().roleBindings().inNamespace(namespace).withName(id).get();
    if (isRunning(old)) {
        if (UserConfigurationCompare.configEqual(entity, old)) {
            log.info("RoleBinding has not changed so not doing anything");
        } else {
            if (isRecreateMode()) {
                log.info("Deleting RoleBinding: " + id);
                kubernetesClient.rbac().roleBindings().inNamespace(namespace).withName(id).delete();
                doCreateRoleBinding(entity, namespace, sourceName);
            } else {
                log.info("Updating RoleBinding from " + sourceName);
                try {
                    String resourceVersion = KubernetesHelper.getResourceVersion(old);
                    ObjectMeta metadata = getOrCreateMetadata(entity);
                    metadata.setNamespace(namespace);
                    metadata.setResourceVersion(resourceVersion);
                    Object answer = kubernetesClient.rbac().roleBindings().inNamespace(namespace).withName(id).replace(entity);
                    logGeneratedEntity("Updated RoleBinding: ", namespace, entity, answer);
                } catch (Exception e) {
                    onApplyError("Failed to update RoleBinding from " + sourceName + ". " + e + ". " + entity, e);
                }
            }
        }
    } else {
        if (!isAllowCreate()) {
            log.warn("Creation disabled so not creating RoleBinding from " + sourceName + " namespace " + namespace + " name " + getName(entity));
        } else {
            doCreateRoleBinding(entity, namespace, sourceName);
        }
    }
}
 
Example 7
Source File: TillerInstaller.java    From microbean-helm with Apache License 2.0 5 votes vote down vote up
protected Deployment createDeployment(String namespace,
                                      final String deploymentName,
                                      final int replicas,
                                      Map<String, String> labels,
                                      final Map<String, String> nodeSelector,
                                      final String serviceAccountName,
                                      final String imageName,
                                      final ImagePullPolicy imagePullPolicy,
                                      final int maxHistory,
                                      final boolean hostNetwork,
                                      final boolean tls,
                                      final boolean verifyTls) {
  namespace = normalizeNamespace(namespace);
  labels = normalizeLabels(labels);

  final Deployment deployment = new Deployment();

  final ObjectMeta metadata = new ObjectMeta();
  metadata.setNamespace(namespace);
  metadata.setName(normalizeDeploymentName(deploymentName));
  metadata.setLabels(labels);
  deployment.setMetadata(metadata);

  deployment.setSpec(this.createDeploymentSpec(Math.max(1, replicas),
                                               labels,
                                               nodeSelector,
                                               serviceAccountName,
                                               imageName,
                                               imagePullPolicy,
                                               maxHistory,
                                               namespace,
                                               hostNetwork,
                                               tls,
                                               verifyTls));
  return deployment;
}
 
Example 8
Source File: TillerInstaller.java    From microbean-helm with Apache License 2.0 5 votes vote down vote up
protected Secret createSecret(final String namespace,
                              final URI tlsKeyUri,
                              final URI tlsCertUri,
                              final URI tlsCaCertUri,
                              final Map<String, String> labels)
  throws IOException {
  
  final Secret secret = new Secret();
  secret.setType("Opaque");

  final Map<String, String> secretData = new HashMap<>();
  
  try (final InputStream tlsKeyStream = read(tlsKeyUri)) {
    if (tlsKeyStream != null) {
      secretData.put("tls.key", Base64.getEncoder().encodeToString(toByteArray(tlsKeyStream)));
    }
  }

  try (final InputStream tlsCertStream = read(tlsCertUri)) {
    if (tlsCertStream != null) {
      secretData.put("tls.crt", Base64.getEncoder().encodeToString(toByteArray(tlsCertStream)));
    }
  }
  
  try (final InputStream tlsCaCertStream = read(tlsCaCertUri)) {
    if (tlsCaCertStream != null) {
      secretData.put("ca.crt", Base64.getEncoder().encodeToString(toByteArray(tlsCaCertStream)));
    }
  }

  secret.setData(secretData);

  final ObjectMeta metadata = new ObjectMeta();
  metadata.setNamespace(normalizeNamespace(namespace));
  metadata.setName(SECRET_NAME);
  metadata.setLabels(normalizeLabels(labels));
  secret.setMetadata(metadata);
  
  return secret;
}
 
Example 9
Source File: KafkaResourceListTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDeserialize() throws IOException {
    final KafkaResourceList list = new YAMLMapper().readValue(KafkaResourceListTest.class.getResourceAsStream("/io/syndesis/connector/kafka/kafkas.yaml"),
        KafkaResourceList.class);

    assertThat(list).isNotNull();

    final List<Kafka> items = list.getItems();
    assertThat(items).hasSize(2);

    final Status myClusterStatus = new Status(Arrays.asList(
        new Listener("plain", Collections.singletonList(new Address("my-cluster-kafka-bootstrap.zregvart.svc", 9092))),
        new Listener("tls", Collections.singletonList(new Address("my-cluster-kafka-bootstrap.zregvart.svc", 9093)))));
    final Kafka myCluster = new Kafka(myClusterStatus);

    final ObjectMeta myClusterMetadata = myCluster.getMetadata();
    myClusterMetadata.setName("my-cluster");
    myClusterMetadata.setNamespace("zregvart");

    final Status zoransClusterStatus = new Status(Arrays.asList(
        new Listener("plain", Collections.singletonList(new Address("zorans-cluster-kafka-bootstrap.zregvart.svc", 9092))),
        new Listener("tls", Collections.singletonList(new Address("zorans-cluster-kafka-bootstrap.zregvart.svc", 9093)))));
    final Kafka zoransCluster = new Kafka(zoransClusterStatus);

    final ObjectMeta zoransClusterMetadata = zoransCluster.getMetadata();
    zoransClusterMetadata.setName("zorans-cluster");
    zoransClusterMetadata.setNamespace("zregvart");

    assertThat(items).contains(zoransCluster, zoransCluster);
}
 
Example 10
Source File: ApplyService.java    From jkube with Eclipse Public License 2.0 4 votes vote down vote up
public void applyBuildConfig(BuildConfig entity, String sourceName) {
    OpenShiftClient openShiftClient = getOpenShiftClient();
    if (openShiftClient != null) {
        String id = getName(entity);

        Objects.requireNonNull(id, "No name for " + entity + " " + sourceName);
        String namespace = KubernetesHelper.getNamespace(entity);
        if (StringUtils.isBlank(namespace)) {
            namespace = getNamespace();
        }
        applyNamespace(namespace);
        BuildConfig old = openShiftClient.buildConfigs().inNamespace(namespace).withName(id).get();
        if (isRunning(old)) {
            if (UserConfigurationCompare.configEqual(entity, old)) {
                log.info("BuildConfig has not changed so not doing anything");
            } else {
                if (isRecreateMode()) {
                    log.info("Deleting BuildConfig: " + id);
                    openShiftClient.buildConfigs().inNamespace(namespace).withName(id).delete();
                    doCreateBuildConfig(entity, namespace, sourceName);
                } else {
                    log.info("Updating BuildConfig from " + sourceName);
                    try {
                        String resourceVersion = KubernetesHelper.getResourceVersion(old);
                        ObjectMeta metadata = getOrCreateMetadata(entity);
                        metadata.setNamespace(namespace);
                        metadata.setResourceVersion(resourceVersion);
                        Object answer = patchService.compareAndPatchEntity(namespace, entity, old);
                        logGeneratedEntity("Updated BuildConfig: ", namespace, entity, answer);
                    } catch (Exception e) {
                        onApplyError("Failed to update BuildConfig from " + sourceName + ". " + e + ". " + entity, e);
                    }
                }
            }
        } else {
            if (!isAllowCreate()) {
                log.warn("Creation disabled so not creating BuildConfig from " + sourceName + " namespace " + namespace + " name " + getName(entity));
            } else {
                doCreateBuildConfig(entity, namespace, sourceName);
            }
        }
    }
}
 
Example 11
Source File: ResourceUtils.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
public static Kafka createKafkaCluster(String clusterCmNamespace, String clusterCmName, int replicas,
                                       String image, int healthDelay, int healthTimeout,
                                       Map<String, Object> metricsCm,
                                       Map<String, Object> kafkaConfiguration,
                                       Map<String, Object> zooConfiguration,
                                       Storage kafkaStorage,
                                       SingleVolumeStorage zkStorage,
                                       Logging kafkaLogging, Logging zkLogging,
                                       KafkaExporterSpec keSpec,
                                       CruiseControlSpec ccSpec) {
    Kafka result = new Kafka();
    ObjectMeta meta = new ObjectMeta();
    meta.setNamespace(clusterCmNamespace);
    meta.setName(clusterCmName);
    meta.setLabels(Labels.fromMap(TestUtils.map(Labels.KUBERNETES_DOMAIN + "part-of", "tests", "my-user-label", "cromulent")).toMap());
    result.setMetadata(meta);

    KafkaSpec spec = new KafkaSpec();

    KafkaClusterSpec kafkaClusterSpec = new KafkaClusterSpec();
    kafkaClusterSpec.setReplicas(replicas);
    kafkaClusterSpec.setImage(image);
    if (kafkaLogging != null) {
        kafkaClusterSpec.setLogging(kafkaLogging);
    }
    Probe livenessProbe = new Probe();
    livenessProbe.setInitialDelaySeconds(healthDelay);
    livenessProbe.setTimeoutSeconds(healthTimeout);
    livenessProbe.setSuccessThreshold(4);
    livenessProbe.setFailureThreshold(10);
    livenessProbe.setPeriodSeconds(33);
    kafkaClusterSpec.setLivenessProbe(livenessProbe);
    kafkaClusterSpec.setReadinessProbe(livenessProbe);
    if (metricsCm != null) {
        kafkaClusterSpec.setMetrics(metricsCm);
    }

    if (kafkaConfiguration != null) {
        kafkaClusterSpec.setConfig(kafkaConfiguration);
    }
    kafkaClusterSpec.setStorage(kafkaStorage);
    spec.setKafka(kafkaClusterSpec);

    ZookeeperClusterSpec zk = new ZookeeperClusterSpec();
    zk.setReplicas(replicas);
    zk.setImage(image + "-zk");
    if (zkLogging != null) {
        zk.setLogging(zkLogging);
    }
    zk.setLivenessProbe(livenessProbe);
    zk.setReadinessProbe(livenessProbe);
    if (zooConfiguration != null) {
        zk.setConfig(zooConfiguration);
    }
    zk.setStorage(zkStorage);
    if (metricsCm != null) {
        zk.setMetrics(metricsCm);
    }

    spec.setKafkaExporter(keSpec);
    spec.setCruiseControl(ccSpec);

    spec.setZookeeper(zk);
    result.setSpec(spec);
    return result;
}