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

The following examples show how to use io.fabric8.kubernetes.api.model.Namespace. 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: NamespaceTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeleteMulti() {
  Namespace namespace1 = new NamespaceBuilder().withNewMetadata().withName("namespace1").and().build();
  Namespace namespace2 = new NamespaceBuilder().withNewMetadata().withName("namespace2").and().build();
  Namespace namespace3 = new NamespaceBuilder().withNewMetadata().withName("namespace3").and().build();

  server.expect().withPath("/api/v1/namespaces/namespace1").andReturn(200, namespace1).once();
  server.expect().withPath("/api/v1/namespaces/namespace2").andReturn(200, namespace2).once();

  KubernetesClient client = server.getClient();
  Boolean deleted = client.namespaces().delete(namespace1, namespace2);
  assertTrue(deleted);

  deleted = client.namespaces().delete(namespace3);
  assertFalse(deleted);
}
 
Example #2
Source File: ProjectEnricher.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
private Project convertToProject(Namespace namespace) {

        ProjectBuilder builder = new ProjectBuilder();
        builder.withMetadata(namespace.getMetadata());

        if (namespace.getSpec() != null) {
            NamespaceSpec namespaceSpec = namespace.getSpec();
            ProjectSpec projectSpec = new ProjectSpec();
            if (namespaceSpec.getFinalizers() != null) {
                projectSpec.setFinalizers(namespaceSpec.getFinalizers());
            }
            builder.withSpec(projectSpec);
        }

        if (namespace.getStatus() != null) {
            ProjectStatus status = new ProjectStatusBuilder()
                    .withPhase(namespace.getStatus().getPhase()).build();

            builder.withStatus(status);
        }

        return builder.build();
    }
 
Example #3
Source File: KubernetesLookupTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testCluster() throws Exception {
    Pod pod = objectMapper.readValue(new File(clusterJson), Pod.class);
    Namespace namespace = createNamespace();
    KubernetesLookup lookup = new KubernetesLookup(pod, namespace, masterUrl);
    try {
        assertEquals("Incorrect container name", "platform-forms-service", lookup.lookup("containerName"));
        assertEquals("Incorrect container id",
                "docker://2b7c2a93dfb48334aa549e29fdd38039ddd256eec43ba64c145fa4b75a1542f0",
                lookup.lookup("containerId"));
        assertEquals("Incorrect host name", "k8s-tmpcrm-worker-s03-04", lookup.lookup("host"));
        assertEquals("Incorrect pod name", "platform-forms-service-primary-5ddfc4f9b8-kfpzv", lookup.lookup("podName"));
    } finally {
        lookup.clearInfo();
    }
}
 
Example #4
Source File: ApplyService.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Returns true if the namespace is created
 */
public boolean applyNamespace(Namespace entity) {
    String namespace = getOrCreateMetadata(entity).getName();
    log.info("Using namespace: " + namespace);
    String name = getName(entity);
    Objects.requireNonNull(name, "No name for " + entity );
    Namespace old = kubernetesClient.namespaces().withName(name).get();
    if (!isRunning(old)) {
        try {
            Object answer = kubernetesClient.namespaces().create(entity);
            logGeneratedEntity("Created namespace: ", namespace, entity, answer);
            return true;
        } catch (Exception e) {
            onApplyError("Failed to create namespace: " + name + " due " + e.getMessage(), e);
        }
    }
    return false;
}
 
Example #5
Source File: IntegrationTestSupport.java    From java-operator-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Use this method to execute the cleanup of the integration test namespace only in case the test
 * was successful. This is useful to keep the Kubernetes resources around to debug a failed test run.
 * Unfortunately I couldn't make this work with standard JUnit methods as the @AfterAll method doesn't know
 * if the tests succeeded or not.
 *
 * @param test The code of the actual test.
 * @throws Exception if the test threw an exception.
 */
public void teardownIfSuccess(TestRun test) {
    try {
        test.run();

        log.info("Deleting namespace {} and stopping operator", TEST_NAMESPACE);
        Namespace namespace = k8sClient.namespaces().withName(TEST_NAMESPACE).get();
        if (namespace.getStatus().getPhase().equals("Active")) {
            k8sClient.namespaces().withName(TEST_NAMESPACE).delete();
        }
        await("namespace deleted").atMost(30, TimeUnit.SECONDS)
                .until(() -> k8sClient.namespaces().withName(TEST_NAMESPACE).get() == null);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    } finally {
        k8sClient.close();
    }
}
 
Example #6
Source File: KubernetesLookupTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testLocal() throws Exception {
    Pod pod = objectMapper.readValue(new File(localJson), Pod.class);
    Namespace namespace = createNamespace();
    KubernetesLookup lookup = new KubernetesLookup(pod, namespace, masterUrl);
    try {
        assertEquals("Incorrect container name", "sampleapp", lookup.lookup("containerName"));
        assertEquals("Incorrect container id",
                "docker://818b0098946c67e6ac56cb7c0934b7c2a9f50feb7244b422b2a7f566f7e5d0df",
                lookup.lookup("containerId"));
        assertEquals("Incorrect host name", "docker-desktop", lookup.lookup("host"));
        assertEquals("Incorrect pod name", "sampleapp-584f99476d-mnrp4", lookup.lookup("podName"));
    } finally {
        lookup.clearInfo();;
    }
}
 
Example #7
Source File: K8sNetworkingUtil.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the namespace hash value by given POD IP.
 *
 * @param k8sPodService         kubernetes POD service
 * @param k8sNamespaceService   kubernetes namespace service
 * @param podIp                 POD IP address
 * @return namespace hash value
 */
public static Integer namespaceHashByPodIp(K8sPodService k8sPodService,
                                           K8sNamespaceService k8sNamespaceService,
                                           String podIp) {
    String ns = k8sPodService.pods().stream()
            .filter(pod -> pod.getStatus().getPodIP() != null)
            .filter(pod -> pod.getStatus().getPodIP().equals(podIp))
            .map(pod -> pod.getMetadata().getNamespace())
            .findAny().orElse(null);

    if (ns != null) {
        return k8sNamespaceService.namespaces().stream()
                .filter(n -> n.getMetadata().getName().equals(ns))
                .map(Namespace::hashCode).findAny().orElse(null);
    } else {
        return null;
    }
}
 
Example #8
Source File: K8sNamespaceManager.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public void removeNamespace(String uid) {
    checkArgument(!Strings.isNullOrEmpty(uid), ERR_NULL_NAMESPACE_UID);

    synchronized (this) {
        if (isNamespaceInUse(uid)) {
            final String error = String.format(MSG_NAMESPACE, uid, ERR_IN_USE);
            throw new IllegalStateException(error);
        }
    }

    Namespace namespace = k8sNamespaceStore.removeNamespace(uid);

    if (namespace != null) {
        log.info(String.format(MSG_NAMESPACE,
                namespace.getMetadata().getName(), MSG_REMOVED));
    }
}
 
Example #9
Source File: K8sNamespaceWatcher.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public void eventReceived(Action action, Namespace namespace) {
    switch (action) {
        case ADDED:
            eventExecutor.execute(() -> processAddition(namespace));
            break;
        case MODIFIED:
            eventExecutor.execute(() -> processModification(namespace));
            break;
        case DELETED:
            eventExecutor.execute(() -> processDeletion(namespace));
            break;
        case ERROR:
            log.warn("Failures processing namespace manipulation.");
            break;
        default:
            // do nothing
            break;
    }
}
 
Example #10
Source File: K8sNamespaceManagerTest.java    From onos with Apache License 2.0 5 votes vote down vote up
private static Namespace createK8sNamespace(String uid, String name) {
    ObjectMeta meta = new ObjectMeta();
    meta.setUid(uid);
    meta.setName(name);

    Namespace namespace = new Namespace();
    namespace.setApiVersion("v1");
    namespace.setKind("Namespace");
    namespace.setMetadata(meta);

    return namespace;
}
 
Example #11
Source File: K8sNamespaceWatcher.java    From onos with Apache License 2.0 5 votes vote down vote up
private void processAddition(Namespace namespace) {
    if (!isMaster()) {
        return;
    }

    log.trace("Process namespace {} creating event from API server.",
            namespace.getMetadata().getName());

    if (k8sNamespaceAdminService.namespace(namespace.getMetadata().getUid()) == null) {
        k8sNamespaceAdminService.createNamespace(namespace);
    }
}
 
Example #12
Source File: K8sNamespaceListCommand.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
protected void doExecute() {
    K8sNamespaceService service = get(K8sNamespaceService.class);
    List<Namespace> namespaces = Lists.newArrayList(service.namespaces());
    namespaces.sort(Comparator.comparing(n -> n.getMetadata().getName()));

    String format = genFormatString(ImmutableList.of(CLI_NAME_LENGTH,
            CLI_PHASE_LENGTH, CLI_LABELS_LENGTH));

    if (outputJson()) {
        print("%s", json(namespaces));
    } else {
        print(format, "Name", "Phase", "Labels");

        for (Namespace namespace : namespaces) {

            print(format,
                    StringUtils.substring(namespace.getMetadata().getName(),
                            0, CLI_NAME_LENGTH - CLI_MARGIN_LENGTH),
                    namespace.getStatus().getPhase(),
                    namespace.getMetadata() != null &&
                            namespace.getMetadata().getLabels() != null &&
                            !namespace.getMetadata().getLabels().isEmpty() ?
                            StringUtils.substring(namespace.getMetadata()
                                            .getLabels().toString(), 0,
                                    CLI_LABELS_LENGTH - CLI_MARGIN_LENGTH) : "");
        }
    }
}
 
Example #13
Source File: K8sSyncStateCommand.java    From onos with Apache License 2.0 5 votes vote down vote up
private void printNamespace(Namespace namespace) {
    print(NAMESPACE_FORMAT,
            StringUtils.substring(namespace.getMetadata().getName(),
                    0, CLI_NAME_LENGTH - CLI_MARGIN_LENGTH),
            namespace.getStatus().getPhase(),
            namespace.getMetadata() != null &&
                    namespace.getMetadata().getLabels() != null &&
                    !namespace.getMetadata().getLabels().isEmpty() ?
                    StringUtils.substring(namespace.getMetadata()
                                    .getLabels().toString(), 0,
                            CLI_LABELS_LENGTH - CLI_MARGIN_LENGTH) : "");
}
 
Example #14
Source File: K8sNamespaceWatcher.java    From onos with Apache License 2.0 5 votes vote down vote up
private void processDeletion(Namespace namespace) {
    if (!isMaster()) {
        return;
    }

    log.trace("Process namespace {} removal event from API server.",
            namespace.getMetadata().getName());

    k8sNamespaceAdminService.removeNamespace(namespace.getMetadata().getUid());
}
 
Example #15
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 #16
Source File: K8sNetworkPolicyHandler.java    From onos with Apache License 2.0 5 votes vote down vote up
private Set<Namespace> namespacesByPolicyPeer(NetworkPolicyPeer peer) {
    if (peer.getNamespaceSelector() != null) {
        Map<String, String> labels = peer.getNamespaceSelector().getMatchLabels();
        if (labels == null || labels.size() == 0) {
            // if none of match labels are specified, it means the
            // target PODs are from any namespaces
            return k8sNamespaceService.namespaces();
        } else {
            return namespacesByLabels(labels);
        }
    }

    return Sets.newConcurrentHashSet();
}
 
Example #17
Source File: K8sNetworkPolicyHandler.java    From onos with Apache License 2.0 5 votes vote down vote up
private void setAllowNamespaceRules(int tunnelId, Set<Namespace> nsSet,
                                    String direction, boolean install) {

    nsSet.forEach(ns -> {
        setAllowNamespaceRulesBase(tunnelId, ns.hashCode(), direction, install);
    });
}
 
Example #18
Source File: K8sNetworkPolicyHandler.java    From onos with Apache License 2.0 5 votes vote down vote up
private Set<Namespace> namespacesByLabels(Map<String, String> labels) {
    Set<Namespace> nsSet = Sets.newConcurrentHashSet();
    k8sNamespaceService.namespaces().forEach(ns -> {
        if (ns != null && ns.getMetadata() != null &&
                ns.getMetadata().getLabels() != null && labels != null) {
            ns.getMetadata().getLabels().forEach((k, v) -> {
                if (labels.get(k) != null && labels.get(k).equals(v)) {
                    nsSet.add(ns);
                }
            });
        }
    });

    return nsSet;
}
 
Example #19
Source File: K8sNetworkPolicyHandler.java    From onos with Apache License 2.0 5 votes vote down vote up
private void processNamespaceRemoval(Namespace namespace) {
    if (!isRelevantHelper()) {
        return;
    }

    setDefaultAllowNamespaceRules(namespace, false);
}
 
Example #20
Source File: K8sNetworkPolicyHandler.java    From onos with Apache License 2.0 5 votes vote down vote up
private void processNamespaceCreation(Namespace namespace) {
    if (!isRelevantHelper()) {
        return;
    }

    setDefaultAllowNamespaceRules(namespace, true);
    setDefaultAllowServiceRules(true);
}
 
Example #21
Source File: KubernetesLookupTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private Namespace createNamespace() {
    Namespace namespace = new Namespace();
    ObjectMeta meta = new ObjectMeta();
    Map<String, String> annotations = new HashMap<>();
    annotations.put("test", "name");
    meta.setAnnotations(annotations);
    Map<String, String> labels = new HashMap<>();
    labels.put("ns", "my-namespace");
    meta.setLabels(labels);
    meta.setUid(UUID.randomUUID().toString());
    namespace.setMetadata(meta);
    return namespace;
}
 
Example #22
Source File: K8sNamespaceWatcher.java    From onos with Apache License 2.0 5 votes vote down vote up
private void processModification(Namespace namespace) {
    if (!isMaster()) {
        return;
    }

    log.trace("Process namespace {} updating event from API server.",
            namespace.getMetadata().getName());

    if (k8sNamespaceAdminService.namespace(namespace.getMetadata().getUid()) != null) {
        k8sNamespaceAdminService.updateNamespace(namespace);
    }
}
 
Example #23
Source File: K8sNetworkPolicyHandler.java    From onos with Apache License 2.0 5 votes vote down vote up
private void setDefaultAllowNamespaceRules(Namespace namespace, boolean install) {

        String ns = namespace.getMetadata().getName();
        if (KUBE_SYSTEM.equalsIgnoreCase(ns)) {
            setAllowNamespaceRulesBase(0, namespace.hashCode(),
                    DIRECTION_INGRESS, install);
        }
    }
 
Example #24
Source File: K8sNamespaceManager.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void updateNamespace(Namespace namespace) {
    checkNotNull(namespace, ERR_NULL_NAMESPACE);
    checkArgument(!Strings.isNullOrEmpty(namespace.getMetadata().getUid()),
            ERR_NULL_NAMESPACE_UID);

    k8sNamespaceStore.updateNamespace(namespace);

    log.info(String.format(MSG_NAMESPACE,
            namespace.getMetadata().getName(), MSG_UPDATED));
}
 
Example #25
Source File: K8sNamespaceManager.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void createNamespace(Namespace namespace) {
    checkNotNull(namespace, ERR_NULL_NAMESPACE);
    checkArgument(!Strings.isNullOrEmpty(namespace.getMetadata().getUid()),
            ERR_NULL_NAMESPACE_UID);

    k8sNamespaceStore.createNamespace(namespace);

    log.info(String.format(MSG_NAMESPACE,
            namespace.getMetadata().getName(), MSG_CREATED));
}
 
Example #26
Source File: DistributedK8sNamespaceStore.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public Namespace removeNamespace(String uid) {
    Versioned<Namespace> namespace = namespaceStore.remove(uid);
    if (namespace == null) {
        final String error = uid + ERR_NOT_FOUND;
        throw new IllegalArgumentException(error);
    }
    return namespace.value();
}
 
Example #27
Source File: DistributedK8sNamespaceStore.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void updateNamespace(Namespace namespace) {
    namespaceStore.compute(namespace.getMetadata().getUid(), (uid, existing) -> {
        final String error  = namespace.getMetadata().getUid() + ERR_NOT_FOUND;
        checkArgument(existing != null, error);
        return namespace;
    });
}
 
Example #28
Source File: DistributedK8sNamespaceStore.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void createNamespace(Namespace namespace) {
    namespaceStore.compute(namespace.getMetadata().getUid(), (uid, existing) -> {
        final String error = namespace.getMetadata().getUid() + ERR_DUPLICATE;
        checkArgument(existing == null, error);
        return namespace;
    });
}
 
Example #29
Source File: DistributedK8sNamespaceStore.java    From onos with Apache License 2.0 5 votes vote down vote up
@Activate
protected void activate() {
    ApplicationId appId = coreService.registerApplication(APP_ID);
    namespaceStore = storageService.<String, Namespace>consistentMapBuilder()
            .withSerializer(Serializer.using(SERIALIZER_K8S_NAMESPACE))
            .withName("k8s-namespace-store")
            .withApplicationId(appId)
            .build();

    namespaceStore.addListener(namespaceMapListener);
    log.info("Started");
}
 
Example #30
Source File: K8sNetworkingUtil.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the namespace hash value by given namespace name.
 *
 * @param k8sNamespaceService   kubernetes namespace service
 * @param ns                    namespace name
 * @return namespace hash value
 */
public static int namespaceHashByNamespace(K8sNamespaceService k8sNamespaceService,
                                           String ns) {

    return k8sNamespaceService.namespaces().stream()
            .filter(n -> n.getMetadata().getName() != null)
            .filter(n -> n.getMetadata().getName().equalsIgnoreCase(ns))
            .map(Namespace::hashCode).findAny().orElse(DEFAULT_NAMESPACE_HASH);
}