io.fabric8.kubernetes.api.model.networking.NetworkPolicy Java Examples

The following examples show how to use io.fabric8.kubernetes.api.model.networking.NetworkPolicy. 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: K8sNetworkPolicyListCommand.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
protected void doExecute() {
    K8sNetworkPolicyService service = get(K8sNetworkPolicyService.class);
    List<NetworkPolicy> policies = Lists.newArrayList(service.networkPolicies());
    policies.sort(Comparator.comparing(p -> p.getMetadata().getName()));

    String format = genFormatString(ImmutableList.of(CLI_NAME_LENGTH,
            CLI_NAMESPACE_LENGTH, CLI_TYPES_LENGTH));

    if (outputJson()) {
        print("%s", json(policies));
    } else {
        print(format, "Name", "Namespace", "Types");

        for (NetworkPolicy policy : policies) {

            print(format,
                    StringUtils.substring(policy.getMetadata().getName(),
                            0, CLI_NAME_LENGTH - CLI_MARGIN_LENGTH),
                    StringUtils.substring(policy.getMetadata().getNamespace(),
                            0, CLI_NAMESPACE_LENGTH - CLI_MARGIN_LENGTH),
                    policy.getSpec().getPolicyTypes().isEmpty() ?
                            "" : policy.getSpec().getPolicyTypes());
        }
    }
}
 
Example #2
Source File: K8sNetworkPolicyWatcher.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public void eventReceived(Action action, NetworkPolicy service) {
    switch (action) {
        case ADDED:
            eventExecutor.execute(() -> processAddition(service));
            break;
        case MODIFIED:
            eventExecutor.execute(() -> processModification(service));
            break;
        case DELETED:
            eventExecutor.execute(() -> processDeletion(service));
            break;
        case ERROR:
            log.warn("Failures processing network policy manipulation.");
            break;
        default:
            // do nothing
            break;
    }
}
 
Example #3
Source File: KafkaConnectClusterTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testNetworkPolicyWithConnectorOperator() {
    KafkaConnect resource = new KafkaConnectBuilder(this.resource)
            .build();
    KafkaConnectCluster kc = KafkaConnectCluster.fromCrd(resource, VERSIONS);

    NetworkPolicy np = kc.generateNetworkPolicy(true, true);

    assertThat(np.getMetadata().getName(), is(kc.getName()));
    assertThat(np.getSpec().getPodSelector().getMatchLabels(), is(kc.getSelectorLabels().toMap()));
    assertThat(np.getSpec().getIngress().size(), is(2));
    assertThat(np.getSpec().getIngress().get(0).getPorts().size(), is(1));
    assertThat(np.getSpec().getIngress().get(0).getPorts().get(0).getPort().getIntVal(), is(KafkaConnectCluster.REST_API_PORT));
    assertThat(np.getSpec().getIngress().get(0).getFrom().size(), is(2));
    assertThat(np.getSpec().getIngress().get(0).getFrom().get(0).getPodSelector().getMatchLabels(), is(kc.getSelectorLabels().toMap()));
    assertThat(np.getSpec().getIngress().get(0).getFrom().get(0).getNamespaceSelector(), is(nullValue()));
    assertThat(np.getSpec().getIngress().get(0).getFrom().get(1).getPodSelector().getMatchLabels(), is(singletonMap(Labels.STRIMZI_KIND_LABEL, "cluster-operator")));
    assertThat(np.getSpec().getIngress().get(0).getFrom().get(1).getNamespaceSelector().getMatchLabels(), is(emptyMap()));
    assertThat(np.getSpec().getIngress().get(1).getPorts().size(), is(1));
    assertThat(np.getSpec().getIngress().get(1).getPorts().get(0).getPort().getIntVal(), is(KafkaConnectCluster.METRICS_PORT));
}
 
Example #4
Source File: CruiseControlTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testRestApiPortNetworkPolicy() {
    NetworkPolicyPeer clusterOperatorPeer = new NetworkPolicyPeerBuilder()
            .withNewPodSelector()
                .withMatchLabels(Collections.singletonMap(Labels.STRIMZI_KIND_LABEL, "cluster-operator"))
            .endPodSelector()
            .withNewNamespaceSelector().endNamespaceSelector()
            .build();

    NetworkPolicy np = cc.generateNetworkPolicy(true);

    assertThat(np.getSpec().getIngress().stream().filter(ing -> ing.getPorts().get(0).getPort().equals(new IntOrString(CruiseControl.REST_API_PORT))).findFirst().orElse(null), is(notNullValue()));

    List<NetworkPolicyPeer> rules = np.getSpec().getIngress().stream().filter(ing -> ing.getPorts().get(0).getPort().equals(new IntOrString(CruiseControl.REST_API_PORT))).map(NetworkPolicyIngressRule::getFrom).findFirst().orElse(null);

    assertThat(rules.size(), is(1));
    assertThat(rules.contains(clusterOperatorPeer), is(true));
}
 
Example #5
Source File: KafkaMirrorMaker2ClusterTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testNetworkPolicy() {
    KafkaMirrorMaker2 resource = new KafkaMirrorMaker2Builder(this.resource)
            .build();
    KafkaMirrorMaker2Cluster kc = KafkaMirrorMaker2Cluster.fromCrd(resource, VERSIONS);

    NetworkPolicy np = kc.generateNetworkPolicy(true, true);

    assertThat(np.getMetadata().getName(), is(kc.getName()));
    assertThat(np.getSpec().getPodSelector().getMatchLabels(), is(kc.getSelectorLabels().toMap()));
    assertThat(np.getSpec().getIngress().size(), is(2));
    assertThat(np.getSpec().getIngress().get(0).getPorts().size(), is(1));
    assertThat(np.getSpec().getIngress().get(0).getPorts().get(0).getPort().getIntVal(), is(KafkaConnectCluster.REST_API_PORT));

    assertThat(np.getSpec().getIngress().get(0).getFrom().size(), is(2));
    assertThat(np.getSpec().getIngress().get(0).getFrom().get(0).getPodSelector().getMatchLabels(), is(kc.getSelectorLabels().toMap()));
    assertThat(np.getSpec().getIngress().get(0).getFrom().get(0).getNamespaceSelector(), is(nullValue()));
    assertThat(np.getSpec().getIngress().get(0).getFrom().get(1).getPodSelector().getMatchLabels(), is(singletonMap(Labels.STRIMZI_KIND_LABEL, "cluster-operator")));
    assertThat(np.getSpec().getIngress().get(0).getFrom().get(1).getNamespaceSelector().getMatchLabels(), is(emptyMap()));
    assertThat(np.getSpec().getIngress().get(1).getPorts().size(), is(1));
    assertThat(np.getSpec().getIngress().get(1).getPorts().get(0).getPort().getIntVal(), is(KafkaConnectCluster.METRICS_PORT));
}
 
Example #6
Source File: KafkaConnectS2IClusterTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testNetworkPolicyWithConnectorOperator() {
    KafkaConnectS2I resource = new KafkaConnectS2IBuilder(this.resource)
            .build();
    KafkaConnectS2ICluster kc = KafkaConnectS2ICluster.fromCrd(resource, VERSIONS);

    NetworkPolicy np = kc.generateNetworkPolicy(true, true);

    assertThat(np.getMetadata().getName(), is(kc.getName()));
    assertThat(np.getSpec().getPodSelector().getMatchLabels(), is(kc.getSelectorLabels().toMap()));
    assertThat(np.getSpec().getIngress().size(), is(2));
    assertThat(np.getSpec().getIngress().get(0).getPorts().size(), is(1));
    assertThat(np.getSpec().getIngress().get(0).getPorts().get(0).getPort().getIntVal(), is(KafkaConnectCluster.REST_API_PORT));
    assertThat(np.getSpec().getIngress().get(0).getFrom().size(), is(2));
    assertThat(np.getSpec().getIngress().get(0).getFrom().get(0).getPodSelector().getMatchLabels(), is(kc.getSelectorLabels().toMap()));
    assertThat(np.getSpec().getIngress().get(0).getFrom().get(0).getNamespaceSelector(), is(nullValue()));
    assertThat(np.getSpec().getIngress().get(0).getFrom().get(1).getPodSelector().getMatchLabels(), is(singletonMap(Labels.STRIMZI_KIND_LABEL, "cluster-operator")));
    assertThat(np.getSpec().getIngress().get(0).getFrom().get(1).getNamespaceSelector().getMatchLabels(), is(emptyMap()));
    assertThat(np.getSpec().getIngress().get(1).getPorts().size(), is(1));
    assertThat(np.getSpec().getIngress().get(1).getPorts().get(0).getPort().getIntVal(), is(KafkaConnectCluster.METRICS_PORT));
}
 
Example #7
Source File: NetworkPolicyIT.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void update(){
  ReadyEntity<NetworkPolicy> networkPolicyReady = new ReadyEntity<>(NetworkPolicy.class, client, "networkpolicy", currentNamespace);
  networkPolicy = client.network().networkPolicies()
    .withName("networkpolicy").edit()
    .editMetadata().addToLabels("bar","foo").endMetadata()
    .done();

  await().atMost(30, TimeUnit.SECONDS).until(networkPolicyReady);
  assertNotNull(networkPolicy);
  assertEquals("networkpolicy",networkPolicy.getMetadata().getName());
  assertEquals(2,networkPolicy.getMetadata().getLabels().size());
  assertEquals("db", networkPolicy.getSpec().getPodSelector().getMatchLabels().get("role"));
  assertEquals("myproject", networkPolicy.getSpec().getIngress().get(0).getFrom().get(1)
    .getNamespaceSelector().getMatchLabels().get("project"));
  assertEquals("frontend", networkPolicy.getSpec().getIngress().get(0).getFrom().get(0)
    .getPodSelector().getMatchLabels().get("role"));
  assertEquals("TCP", networkPolicy.getSpec().getIngress().get(0).getPorts().get(0).getProtocol());
  assertEquals(6379, networkPolicy.getSpec().getIngress().get(0).getPorts().get(0).getPort().getIntVal().intValue());

}
 
Example #8
Source File: NetworkPolicyIT.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void load() {

  NetworkPolicy loadedNetworkPolicy = client.network().networkPolicies()
    .load(getClass().getResourceAsStream("/test-networkpolicy.yml")).get();

  assertNotNull(loadedNetworkPolicy);
  assertEquals("networkpolicy", loadedNetworkPolicy.getMetadata().getName());
  assertEquals("db", loadedNetworkPolicy.getSpec().getPodSelector().getMatchLabels().get("role"));
  assertEquals("myproject", loadedNetworkPolicy.getSpec().getIngress().get(0).getFrom().get(0)
    .getNamespaceSelector().getMatchLabels().get("project"));
  assertEquals("frontend", loadedNetworkPolicy.getSpec().getIngress().get(0).getFrom().get(1)
    .getPodSelector().getMatchLabels().get("role"));
  assertEquals("TCP", loadedNetworkPolicy.getSpec().getIngress().get(0).getPorts().get(0).getProtocol());
  assertEquals(6379, loadedNetworkPolicy.getSpec().getIngress().get(0).getPorts().get(0).getPort().getIntVal().intValue());

}
 
Example #9
Source File: K8sNetworkPolicyManager.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public void removeNetworkPolicy(String uid) {
    checkArgument(!Strings.isNullOrEmpty(uid), ERR_NULL_NETWORK_POLICY_UID);

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

        NetworkPolicy networkPolicy = k8sNetworkPolicyStore.removeNetworkPolicy(uid);

        if (networkPolicy != null) {
            log.info(String.format(MSG_NETWORK_POLICY,
                    networkPolicy.getMetadata().getName(), MSG_REMOVED));
        }
    }
}
 
Example #10
Source File: NetworkPolicyIT.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void get() {

  NetworkPolicy getNetworkPolicy = client.network().networkPolicies()
    .withName("networkpolicy").get();
  assertNotNull(getNetworkPolicy);
  assertEquals("networkpolicy", getNetworkPolicy.getMetadata().getName());
  assertEquals(1,getNetworkPolicy.getMetadata().getLabels().size());
  assertEquals("db", getNetworkPolicy.getSpec().getPodSelector().getMatchLabels().get("role"));
  assertEquals("myproject", getNetworkPolicy.getSpec().getIngress().get(0).getFrom().get(1)
    .getNamespaceSelector().getMatchLabels().get("project"));
  assertEquals("frontend", getNetworkPolicy.getSpec().getIngress().get(0).getFrom().get(0)
    .getPodSelector().getMatchLabels().get("role"));
  assertEquals("TCP", getNetworkPolicy.getSpec().getIngress().get(0).getPorts().get(0).getProtocol());
  assertEquals(6379, getNetworkPolicy.getSpec().getIngress().get(0).getPorts().get(0).getPort().getIntVal().intValue());
}
 
Example #11
Source File: K8sNetworkPolicyManager.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void updateNetworkPolicy(NetworkPolicy networkPolicy) {
    checkNotNull(networkPolicy, ERR_NULL_NETWORK_POLICY);
    checkArgument(!Strings.isNullOrEmpty(networkPolicy.getMetadata().getUid()),
            ERR_NULL_NETWORK_POLICY_UID);

    k8sNetworkPolicyStore.updateNetworkPolicy(networkPolicy);

    log.info(String.format(MSG_NETWORK_POLICY,
            networkPolicy.getMetadata().getName(), MSG_UPDATED));
}
 
Example #12
Source File: DistributedK8sNetworkPolicyStore.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public NetworkPolicy removeNetworkPolicy(String uid) {
    Versioned<NetworkPolicy> networkPolicy = networkPolicyStore.remove(uid);
    if (networkPolicy == null) {
        final String error = uid + ERR_NOT_FOUND;
        throw new IllegalArgumentException(error);
    }
    return networkPolicy.value();
}
 
Example #13
Source File: DistributedK8sNetworkPolicyStore.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void updateNetworkPolicy(NetworkPolicy networkPolicy) {
    networkPolicyStore.compute(networkPolicy.getMetadata().getUid(), (uid, existing) -> {
        final String error  = networkPolicy.getMetadata().getUid() + ERR_NOT_FOUND;
        checkArgument(existing != null, error);
        return networkPolicy;
    });
}
 
Example #14
Source File: K8sNetworkPolicyWatcher.java    From onos with Apache License 2.0 5 votes vote down vote up
private void processAddition(NetworkPolicy networkPolicy) {
    if (!isMaster()) {
        return;
    }

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

    if (k8sNetworkPolicyAdminService.networkPolicy(
            networkPolicy.getMetadata().getUid()) == null) {
        k8sNetworkPolicyAdminService.createNetworkPolicy(networkPolicy);
    }
}
 
Example #15
Source File: DistributedK8sNetworkPolicyStore.java    From onos with Apache License 2.0 5 votes vote down vote up
@Activate
protected void activate() {
    ApplicationId appId = coreService.registerApplication(APP_ID);
    networkPolicyStore = storageService.<String, NetworkPolicy>consistentMapBuilder()
            .withSerializer(Serializer.using(SERIALIZER_K8S_NETWORK_POLICY))
            .withName("k8s-network-policy-store")
            .withApplicationId(appId)
            .build();

    networkPolicyStore.addListener(networkPolicyMapListener);
    log.info("Started");
}
 
Example #16
Source File: K8sNetworkPolicyWatcher.java    From onos with Apache License 2.0 5 votes vote down vote up
private void processDeletion(NetworkPolicy networkPolicy) {
    if (!isMaster()) {
        return;
    }

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

    k8sNetworkPolicyAdminService.removeNetworkPolicy(networkPolicy.getMetadata().getUid());
}
 
Example #17
Source File: K8sNetworkPolicyWatcher.java    From onos with Apache License 2.0 5 votes vote down vote up
private void processModification(NetworkPolicy networkPolicy) {
    if (!isMaster()) {
        return;
    }

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

    if (k8sNetworkPolicyAdminService.networkPolicy(
            networkPolicy.getMetadata().getUid()) != null) {
        k8sNetworkPolicyAdminService.updateNetworkPolicy(networkPolicy);
    }
}
 
Example #18
Source File: DistributedK8sNetworkPolicyStore.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void createNetworkPolicy(NetworkPolicy networkPolicy) {
    networkPolicyStore.compute(networkPolicy.getMetadata().getUid(), (uid, existing) -> {
        final String error = networkPolicy.getMetadata().getUid() + ERR_DUPLICATE;
        checkArgument(existing == null, error);
        return networkPolicy;
    });
}
 
Example #19
Source File: K8sNetworkPolicyHandler.java    From onos with Apache License 2.0 5 votes vote down vote up
private Map<String, List<String>> getBlockRuleFilter(Pod pod, NetworkPolicy policy) {

        // if the POD is not included in the namespace of the given policy,
        // we do not block the POD
        if (!pod.getMetadata().getNamespace().equals(policy.getMetadata().getNamespace())) {
            return Maps.newConcurrentMap();
        }

        Map<String, String> labels = policy.getSpec().getPodSelector().getMatchLabels();
        Map<String, List<String>> filter = Maps.newConcurrentMap();
        String podIp = pod.getStatus().getPodIP();
        List<String> policyTypes = policy.getSpec().getPolicyTypes();

        if (podIp != null && policyTypes != null) {
            if (labels == null) {
                filter.put(podIp, policyTypes);
            } else {
                pod.getMetadata().getLabels().forEach((k, v) -> {
                    if (labels.get(k) != null && labels.get(k).equals(v)) {
                        filter.put(podIp, policyTypes);
                    }
                });
            }
        }

        return filter;
    }
 
Example #20
Source File: K8sNetworkPolicyHandler.java    From onos with Apache License 2.0 5 votes vote down vote up
private void processNetworkPolicyCreation(NetworkPolicy policy) {
    if (!isRelevantHelper()) {
        return;
    }

    setBlockRulesByPolicy(policy, true);
    setAllowRulesByPolicy(policy, true);
}
 
Example #21
Source File: K8sNetworkPolicyHandler.java    From onos with Apache License 2.0 5 votes vote down vote up
private void processNetworkPolicyRemoval(NetworkPolicy policy) {
    if (!isRelevantHelper()) {
        return;
    }

    setBlockRulesByPolicy(policy, false);
    setAllowRulesByPolicy(policy, false);
}
 
Example #22
Source File: K8sNetworkPolicyManager.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void createNetworkPolicy(NetworkPolicy networkPolicy) {
    checkNotNull(networkPolicy, ERR_NULL_NETWORK_POLICY);
    checkArgument(!Strings.isNullOrEmpty(networkPolicy.getMetadata().getUid()),
            ERR_NULL_NETWORK_POLICY_UID);

    k8sNetworkPolicyStore.createNetworkPolicy(networkPolicy);

    log.info(String.format(MSG_NETWORK_POLICY,
            networkPolicy.getMetadata().getName(), MSG_CREATED));
}
 
Example #23
Source File: K8sSyncStateCommand.java    From onos with Apache License 2.0 5 votes vote down vote up
private void printNetworkPolicy(NetworkPolicy policy) {
    print(NETWORK_POLICY_FORMAT,
            StringUtils.substring(policy.getMetadata().getName(),
                    0, CLI_NAME_LENGTH - CLI_MARGIN_LENGTH),
            StringUtils.substring(policy.getMetadata().getNamespace(),
                    0, CLI_NAMESPACE_LENGTH - CLI_MARGIN_LENGTH),
            policy.getSpec().getPolicyTypes().isEmpty() ?
                    "" : policy.getSpec().getPolicyTypes());
}
 
Example #24
Source File: K8sNetworkPolicyHandler.java    From onos with Apache License 2.0 5 votes vote down vote up
private void setBlockRulesByPolicy(NetworkPolicy policy, boolean install) {
    final Map<String, List<String>> filter = Maps.newConcurrentMap();

    k8sPodService.pods().forEach(pod ->
        filter.putAll(getBlockRuleFilter(pod, policy)));

    setBlockRules(filter, install);
}
 
Example #25
Source File: TracingST.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
private void deployJaeger() {
    LOGGER.info("=== Applying jaeger operator install files ===");

    Map<File, String> operatorFiles = Arrays.stream(Objects.requireNonNull(new File(JO_INSTALL_DIR).listFiles())
    ).collect(Collectors.toMap(file -> file, f -> TestUtils.getContent(f, TestUtils::toYamlString), (x, y) -> x, LinkedHashMap::new));

    for (Map.Entry<File, String> entry : operatorFiles.entrySet()) {
        LOGGER.info("Applying configuration file: {}", entry.getKey());
        jaegerConfigs.push(entry.getValue());
        cmdKubeClient().clientWithAdmin().namespace(cluster.getNamespace()).applyContent(entry.getValue());
    }

    installJaegerInstance();

    NetworkPolicy networkPolicy = new NetworkPolicyBuilder()
        .withNewApiVersion("networking.k8s.io/v1")
        .withNewKind("NetworkPolicy")
        .withNewMetadata()
            .withName("jaeger-allow")
        .endMetadata()
        .withNewSpec()
            .addNewIngress()
            .endIngress()
            .withNewPodSelector()
                .addToMatchLabels("app", "jaeger")
            .endPodSelector()
            .withPolicyTypes("Ingress")
        .endSpec()
        .build();

    LOGGER.debug("Going to apply the following NetworkPolicy: {}", networkPolicy.toString());
    KubernetesResource.deleteLater(kubeClient().getClient().network().networkPolicies().inNamespace(ResourceManager.kubeClient().getNamespace()).createOrReplace(networkPolicy));
    LOGGER.info("Network policy for jaeger successfully applied");
}
 
Example #26
Source File: K8sNetworkPolicyManagerTest.java    From onos with Apache License 2.0 5 votes vote down vote up
private static NetworkPolicy createK8sNetworkPolicy(String uid, String name) {
    ObjectMeta meta = new ObjectMeta();
    meta.setUid(uid);
    meta.setName(name);

    NetworkPolicy networkPolicy = new NetworkPolicy();
    networkPolicy.setApiVersion("v1");
    networkPolicy.setKind("NetworkPolicy");
    networkPolicy.setMetadata(meta);

    return networkPolicy;
}
 
Example #27
Source File: LoadTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
void testNetworkPolicyLoad() {
  KubernetesClient client = server.getClient();
  List<HasMetadata> itemList = client.load(getClass().getResourceAsStream("/test-networkpolicy.yml")).get();

  assertEquals(1, itemList.size());
  NetworkPolicy ingress = (NetworkPolicy) itemList.get(0);
  assertEquals("test-network-policy", ingress.getMetadata().getName());
  assertEquals(1, ingress.getSpec().getIngress().size());
  assertEquals(1, ingress.getSpec().getEgress().size());
}
 
Example #28
Source File: NetworkPolicyExample.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
  String namespace = "myproject";

  KubernetesClient client = new DefaultKubernetesClient();

  NetworkPolicy networkPolicy = new NetworkPolicyBuilder()
                                      .withNewMetadata()
                                        .withName("test-network-policy")
                                      .endMetadata()
                                      .withNewSpec()
                                      .withNewPodSelector()
                                        .withMatchLabels( new HashMap<String, String>() {{
                                          put("role","db");
                                        }})
                                      .endPodSelector()
                                      .endSpec()
                                .build();


  // create polict using NetworkPolicyBuilder object
  networkPolicy = client.network()
    .networkPolicies()
    .create(networkPolicy);

  // crate policy using YAML reosurce
  networkPolicy = client.network()
                                  .networkPolicies()
                                  .inNamespace(namespace)
                                  .load(NetworkPolicyExample.class.getResourceAsStream("/network-policy.yml"))
                                  .createOrReplace();

}
 
Example #29
Source File: NetworkPolicyIT.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@After
public void cleanup() {
  if (client.network().networkPolicies().list().getItems().size()!= 0) {
    client.network().networkPolicies().delete();
  }
  DeleteEntity<NetworkPolicy> networkPolicyDelete = new DeleteEntity<>(NetworkPolicy.class, client, "networkpolicy", currentNamespace);
  await().atMost(30, TimeUnit.SECONDS).until(networkPolicyDelete);
}
 
Example #30
Source File: NetworkPolicyIT.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void delete(){
  ReadyEntity<NetworkPolicy> networkPolicyReady = new ReadyEntity<>(NetworkPolicy.class, client, "networkpolicy", currentNamespace);
  await().atMost(30, TimeUnit.SECONDS).until(networkPolicyReady);
  boolean deleted = client.network().networkPolicies().delete(networkPolicy);

  assertTrue(deleted);

  DeleteEntity<NetworkPolicy> deleteEntity = new DeleteEntity<>(NetworkPolicy.class, client, "networkpolicy", currentNamespace);
  await().atMost(30, TimeUnit.SECONDS).until(deleteEntity);

  NetworkPolicyList networkPolicyList = client.network().networkPolicies().list();
  assertEquals(0,networkPolicyList.getItems().size());
}