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

The following examples show how to use io.fabric8.kubernetes.api.model.networking.NetworkPolicyIngressRuleBuilder. 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: NetworkPolicyIT.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Before
public void init(){
  currentNamespace = session.getNamespace();
  networkPolicy = new NetworkPolicyBuilder()
    .withNewMetadata()
    .withName("networkpolicy")
    .addToLabels("foo","bar")
    .endMetadata()
    .withNewSpec()
    .withNewPodSelector()
    .addToMatchLabels("role","db")
    .endPodSelector()
    .addToIngress(0,
      new NetworkPolicyIngressRuleBuilder()
      .addToFrom(0, new NetworkPolicyPeerBuilder().withNewPodSelector()
        .addToMatchLabels("role","frontend").endPodSelector()
        .build()
      ).addToFrom(1, new NetworkPolicyPeerBuilder().withNewNamespaceSelector()
        .addToMatchLabels("project","myproject").endNamespaceSelector()
          .build()
      )
      .addToPorts(0,new NetworkPolicyPortBuilder().withPort(new IntOrString(6379))
        .withProtocol("TCP").build())
      .build()
    )
    .endSpec()
    .build();

  client.network().networkPolicies().create(networkPolicy);
}
 
Example #2
Source File: KafkaConnectCluster.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
/**
 * @param namespaceAndPodSelectorNetworkPolicySupported whether the kube cluster supports namespace selectors
 * @param connectorOperatorEnabled Whether the ConnectorOperator is enabled or not
 * @return The network policy.
 */
public NetworkPolicy generateNetworkPolicy(boolean namespaceAndPodSelectorNetworkPolicySupported, boolean connectorOperatorEnabled) {
    if (connectorOperatorEnabled) {
        List<NetworkPolicyIngressRule> rules = new ArrayList<>(2);

        // Give CO access to the REST API
        NetworkPolicyIngressRule restApiRule = new NetworkPolicyIngressRuleBuilder()
                .addNewPort()
                .withNewPort(REST_API_PORT)
                .endPort()
                .build();

        // OCP 3.11 doesn't support network policies with the `from` section containing a namespace.
        // Since the CO can run in a different namespace, we have to leave it wide open on OCP 3.11
        // Therefore these rules are set only when using something else than OCP 3.11 and leaving
        // the `from` section empty on 3.11
        if (namespaceAndPodSelectorNetworkPolicySupported) {
            List<NetworkPolicyPeer> peers = new ArrayList<>(2);

            // Other connect pods in the same cluster need to talk with each other over the REST API
            NetworkPolicyPeer connectPeer = new NetworkPolicyPeerBuilder()
                    .withNewPodSelector()
                    .addToMatchLabels(getSelectorLabels().toMap())
                    .endPodSelector()
                    .build();
            peers.add(connectPeer);

            // CO needs to talk with the Connect pods to manage connectors
            NetworkPolicyPeer clusterOperatorPeer = new NetworkPolicyPeerBuilder()
                    .withNewPodSelector()
                    .addToMatchLabels(Labels.STRIMZI_KIND_LABEL, "cluster-operator")
                    .endPodSelector()
                    .withNewNamespaceSelector()
                    .endNamespaceSelector()
                    .build();
            peers.add(clusterOperatorPeer);

            restApiRule.setFrom(peers);
        }

        rules.add(restApiRule);

        // If metrics are enabled, we have to open them as well. Otherwise they will be blocked.
        if (isMetricsEnabled) {
            NetworkPolicyPort metricsPort = new NetworkPolicyPort();
            metricsPort.setPort(new IntOrString(METRICS_PORT));

            NetworkPolicyIngressRule metricsRule = new NetworkPolicyIngressRuleBuilder()
                    .withPorts(metricsPort)
                    .withFrom()
                    .build();

            rules.add(metricsRule);
        }

        NetworkPolicy networkPolicy = new NetworkPolicyBuilder()
                .withNewMetadata()
                    .withName(name)
                    .withNamespace(namespace)
                    .withLabels(labels.toMap())
                    .withOwnerReferences(createOwnerReference())
                .endMetadata()
                .withNewSpec()
                    .withNewPodSelector()
                        .addToMatchLabels(getSelectorLabels().toMap())
                    .endPodSelector()
                    .withIngress(rules)
                .endSpec()
                .build();

        log.trace("Created network policy {}", networkPolicy);
        return networkPolicy;
    } else {
        return null;
    }
}
 
Example #3
Source File: CruiseControl.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
/**
 * @param namespaceAndPodSelectorNetworkPolicySupported whether the kube cluster supports namespace selectors
 * @return The network policy.
 */
public NetworkPolicy generateNetworkPolicy(boolean namespaceAndPodSelectorNetworkPolicySupported) {
    List<NetworkPolicyIngressRule> rules = new ArrayList<>(1);

    // CO can access the REST API
    NetworkPolicyIngressRule restApiRule = new NetworkPolicyIngressRuleBuilder()
            .addNewPort()
                .withNewPort(REST_API_PORT)
            .endPort()
            .build();

    if (namespaceAndPodSelectorNetworkPolicySupported) {
        NetworkPolicyPeer clusterOperatorPeer = new NetworkPolicyPeerBuilder()
                .withNewPodSelector() // cluster operator
                    .addToMatchLabels(Labels.STRIMZI_KIND_LABEL, "cluster-operator")
                .endPodSelector()
                .withNewNamespaceSelector()
                .endNamespaceSelector()
                .build();
        restApiRule.setFrom(Collections.singletonList(clusterOperatorPeer));
    }

    rules.add(restApiRule);

    NetworkPolicy networkPolicy = new NetworkPolicyBuilder()
            .withNewMetadata()
                .withName(policyName(cluster))
                .withNamespace(namespace)
                .withLabels(labels.toMap())
                .withOwnerReferences(createOwnerReference())
            .endMetadata()
            .withNewSpec()
                .withNewPodSelector()
                    .addToMatchLabels(Labels.STRIMZI_NAME_LABEL, cruiseControlName(cluster))
                .endPodSelector()
            .withIngress(rules)
            .endSpec()
            .build();

    log.trace("Created network policy {}", networkPolicy);
    return networkPolicy;
}
 
Example #4
Source File: SerializationTest.java    From enmasse with Apache License 2.0 4 votes vote down vote up
@Test
public void testSerializeStandardInfraConfig() throws IOException {
    StandardInfraConfig infraConfig = new StandardInfraConfigBuilder()
            .withNewMetadata()
            .withName("infra")
            .withAnnotations(new HashMap<>())
            .withLabels(new HashMap<>())
            .endMetadata()

            .editOrNewSpec()
            .withVersion("123")
            .editOrNewNetworkPolicy()
            .withIngress(new NetworkPolicyIngressRuleBuilder().build())
            .withEgress()
            .endNetworkPolicy()
            .editOrNewAdmin()
            .editOrNewResources()
            .withMemory("512Mi")
            .endResources()
            .endAdmin()
            .editOrNewBroker()
            .editOrNewResources()
            .withMemory("128Mi")
            .withStorage("2Gi")
            .endResources()
            .withStorageClassName("local")
            .withUpdatePersistentVolumeClaim(false)
            .withAddressFullPolicy("FAIL")
            .endBroker()
            .editOrNewRouter()
            .editOrNewResources()
            .withMemory("128Mi")
            .endResources()
            .withLinkCapacity(100)
            .endRouter()
            .endSpec()
            .build();

    ObjectMapper mapper = new ObjectMapper();
    String serialized = mapper.writeValueAsString(infraConfig);
    StandardInfraConfig deserialized = mapper.readValue(serialized, StandardInfraConfig.class);
    assertEquals(infraConfig, deserialized);

    serialized = "{" +
            "\"apiVersion\":\"admin.enmasse.io/v1beta1\"," +
            "\"kind\":\"StandardInfraConfig\"," +
            "\"metadata\":{" +
            "  \"name\":\"infra\"," +
            "  \"labels\": {}," +
            "  \"annotations\": {}" +
            "}," +
            "\"spec\": {" +
            "  \"version\": \"123\"," +
            "  \"networkPolicy\": {" +
            "    \"ingress\": [{\"from\":[],\"ports\":[]}]," +
            "    \"egress\": []" +
            "  }," +
            "  \"broker\": {" +
            "     \"resources\": {" +
            "       \"memory\": \"128Mi\"," +
            "       \"storage\": \"2Gi\"" +
            "     }," +
            "     \"addressFullPolicy\": \"FAIL\"," +
            "     \"storageClassName\": \"local\"," +
            "     \"updatePersistentVolumeClaim\": false" +
            "  }," +
            "  \"admin\": {" +
            "     \"resources\": {" +
            "       \"memory\": \"512Mi\"" +
            "     }" +
            "  }," +
            "  \"router\": {" +
            "     \"resources\": {" +
            "       \"memory\": \"128Mi\"" +
            "     }," +
            "     \"linkCapacity\": 100" +
            "  }" +
            "}}";


    deserialized = mapper.readValue(serialized, StandardInfraConfig.class);
    assertEquals(infraConfig, deserialized);
}
 
Example #5
Source File: SerializationTest.java    From enmasse with Apache License 2.0 4 votes vote down vote up
@Test
public void testSerializeBrokeredInfraConfig() throws IOException {
    BrokeredInfraConfig infraConfig = new BrokeredInfraConfigBuilder()
            .withNewMetadata()
            .withName("infra")
            .withAnnotations(new HashMap<>())
            .withLabels(new HashMap<>())
            .endMetadata()

            .editOrNewSpec()
            .withVersion("123")
            .editOrNewNetworkPolicy()
            .withIngress(new NetworkPolicyIngressRuleBuilder().build())
            .endNetworkPolicy()
            .editOrNewAdmin()
            .editOrNewResources()
            .withMemory("512Mi")
            .endResources()
            .endAdmin()
            .editOrNewBroker()
            .editOrNewResources()
            .withMemory("128Mi")
            .withStorage("2Gi")
            .endResources()
            .withStorageClassName("local")
            .withUpdatePersistentVolumeClaim(false)
            .withAddressFullPolicy("FAIL")
            .endBroker()
            .endSpec()
            .build();

    ObjectMapper mapper = new ObjectMapper();
    String serialized = mapper.writeValueAsString(infraConfig);
    BrokeredInfraConfig deserialized = mapper.readValue(serialized, BrokeredInfraConfig.class);
    assertEquals(infraConfig, deserialized);

    serialized = "{" +
            "\"apiVersion\":\"admin.enmasse.io/v1beta1\"," +
            "\"kind\":\"BrokeredInfraConfig\"," +
            "\"metadata\":{" +
            "  \"name\":\"infra\"," +
            "  \"labels\": {}," +
            "  \"annotations\": {}" +
            "}," +
            "\"spec\": {" +
            "  \"version\": \"123\"," +
            "  \"networkPolicy\": {" +
            "    \"ingress\": [{\"from\":[],\"ports\":[]}]," +
            "    \"egress\": []" +
            "  }," +
            "  \"broker\": {" +
            "     \"resources\": {" +
            "       \"memory\": \"128Mi\"," +
            "       \"storage\": \"2Gi\"" +
            "     }," +
            "     \"addressFullPolicy\": \"FAIL\"," +
            "     \"storageClassName\": \"local\"," +
            "     \"updatePersistentVolumeClaim\": false" +
            "  }," +
            "  \"admin\": {" +
            "     \"resources\": {" +
            "       \"memory\": \"512Mi\"" +
            "     }" +
            "  }" +
            "}}";


    deserialized = mapper.readValue(serialized, BrokeredInfraConfig.class);
    assertEquals(infraConfig, deserialized);
}
 
Example #6
Source File: NetworkPolicyCrudTest.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Test
public void crudTest(){

  KubernetesClient client = kubernetesServer.getClient();

  NetworkPolicy networkPolicy = new NetworkPolicyBuilder()
    .withNewMetadata()
    .withName("networkpolicy")
    .addToLabels("foo","bar")
    .endMetadata()
    .withNewSpec()
    .withNewPodSelector()
    .addToMatchLabels("role","db")
    .endPodSelector()
    .addToIngress(0,
      new NetworkPolicyIngressRuleBuilder()
        .addToFrom(0, new NetworkPolicyPeerBuilder().withNewPodSelector()
          .addToMatchLabels("role","frontend").endPodSelector()
          .build()
        ).addToFrom(1, new NetworkPolicyPeerBuilder().withNewNamespaceSelector()
        .addToMatchLabels("project","myproject").endNamespaceSelector()
        .build()
      )
        .addToPorts(0,new NetworkPolicyPortBuilder().withPort(new IntOrString(6379))
          .withProtocol("TCP").build())
        .build()
    )
    .endSpec()
    .build();

  //test of Creation
  networkPolicy = client.network().networkPolicies().create(networkPolicy);

  assertNotNull(networkPolicy);
  assertEquals("networkpolicy", networkPolicy.getMetadata().getName());
  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());


  //test of list
  NetworkPolicyList networkPolicyList = client.network().networkPolicies()
    .withLabels(Collections.singletonMap("foo","bar")).list();

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


  //test of updation
  networkPolicy = client.network().networkPolicies()
    .withName("networkpolicy").edit()
    .editSpec().editIngress(0).editFirstPort().withPort(new IntOrString(6679)).endPort().endIngress().endSpec()
    .done();

  logger.info("Updated PodSecurityPolicy : " + networkPolicy.toString());
  assertNotNull(networkPolicy);
  assertEquals("networkpolicy",networkPolicy.getMetadata().getName());
  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(6679, networkPolicy.getSpec().getIngress().get(0).getPorts().get(0).getPort().getIntVal().intValue());


  //test of deletion
  boolean deleted = client.network().networkPolicies().delete();
  assertTrue(deleted);
  networkPolicyList = client.network().networkPolicies().list();
  assertEquals(0,networkPolicyList.getItems().size());

}