[ONOS-8012] Implement kubernetes network policy store and manager

Change-Id: I0386f1103046f69f5f06586229fb2ac5a0926c15
diff --git a/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/cli/K8sNetworkPolicyListCommand.java b/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/cli/K8sNetworkPolicyListCommand.java
new file mode 100644
index 0000000..cc6d24f
--- /dev/null
+++ b/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/cli/K8sNetworkPolicyListCommand.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright 2019-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.k8snetworking.cli;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.google.common.collect.Lists;
+import io.fabric8.kubernetes.api.model.networking.NetworkPolicy;
+import io.fabric8.kubernetes.client.utils.Serialization;
+import org.apache.karaf.shell.api.action.Command;
+import org.apache.karaf.shell.api.action.lifecycle.Service;
+import org.onosproject.cli.AbstractShellCommand;
+import org.onosproject.k8snetworking.api.K8sNetworkPolicyService;
+
+import java.io.IOException;
+import java.util.Comparator;
+import java.util.List;
+
+import static org.onosproject.k8snetworking.util.K8sNetworkingUtil.prettyJson;
+
+/**
+ * Lists kubernetes network policies.
+ */
+@Service
+@Command(scope = "onos", name = "k8s-network-policies",
+        description = "Lists all kubernetes network policies")
+public class K8sNetworkPolicyListCommand extends AbstractShellCommand {
+
+    private static final String FORMAT = "%-50s%-15s%-30s";
+
+    @Override
+    protected void doExecute() {
+        K8sNetworkPolicyService service = get(K8sNetworkPolicyService.class);
+        List<NetworkPolicy> policies = Lists.newArrayList(service.networkPolicies());
+        policies.sort(Comparator.comparing(p -> p.getMetadata().getName()));
+
+        if (outputJson()) {
+            print("%s", json(policies));
+        } else {
+            print(FORMAT, "Name", "Namespace", "Types");
+
+            for (NetworkPolicy policy : policies) {
+
+                print(FORMAT,
+                        policy.getMetadata().getName(),
+                        policy.getMetadata().getNamespace(),
+                        policy.getSpec().getPolicyTypes().isEmpty() ?
+                                "" : policy.getSpec().getPolicyTypes());
+            }
+        }
+    }
+
+    private String json(List<NetworkPolicy> policies) {
+        ObjectMapper mapper = new ObjectMapper();
+        ArrayNode result = mapper.createArrayNode();
+
+        try {
+            for (NetworkPolicy policy : policies) {
+                ObjectNode json = (ObjectNode) new ObjectMapper()
+                        .readTree(Serialization.asJson(policy));
+                result.add(json);
+            }
+            return prettyJson(mapper, result.toString());
+        } catch (IOException e) {
+            log.warn("Failed to parse Network Policy's JSON string.");
+            return "";
+        }
+    }
+}
diff --git a/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/cli/K8sSyncStateCommand.java b/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/cli/K8sSyncStateCommand.java
index 1d39b30..4c7e83d 100644
--- a/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/cli/K8sSyncStateCommand.java
+++ b/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/cli/K8sSyncStateCommand.java
@@ -19,6 +19,7 @@
 import io.fabric8.kubernetes.api.model.Endpoints;
 import io.fabric8.kubernetes.api.model.Pod;
 import io.fabric8.kubernetes.api.model.extensions.Ingress;
+import io.fabric8.kubernetes.api.model.networking.NetworkPolicy;
 import io.fabric8.kubernetes.client.KubernetesClient;
 import org.apache.karaf.shell.api.action.Command;
 import org.apache.karaf.shell.api.action.lifecycle.Service;
@@ -29,6 +30,7 @@
 import org.onosproject.k8snetworking.api.K8sEndpointsAdminService;
 import org.onosproject.k8snetworking.api.K8sIngressAdminService;
 import org.onosproject.k8snetworking.api.K8sNetworkAdminService;
+import org.onosproject.k8snetworking.api.K8sNetworkPolicyAdminService;
 import org.onosproject.k8snetworking.api.K8sPodAdminService;
 import org.onosproject.k8snetworking.api.K8sPort;
 import org.onosproject.k8snetworking.api.K8sServiceAdminService;
@@ -55,6 +57,7 @@
     private static final String SERVICE_FORMAT = "%-50s%-30s%-30s";
     private static final String ENDPOINTS_FORMAT = "%-50s%-50s%-20s";
     private static final String INGRESS_FORMAT = "%-50s%-15s%-30s";
+    private static final String NETWORK_POLICY_FORMAT = "%-50s%-15s%-30s";
 
     private static final String PORT_ID = "portId";
     private static final String DEVICE_ID = "deviceId";
@@ -75,6 +78,8 @@
                 get(K8sEndpointsAdminService.class);
         K8sNetworkAdminService networkAdminService =
                 get(K8sNetworkAdminService.class);
+        K8sNetworkPolicyAdminService networkPolicyAdminService =
+                get(K8sNetworkPolicyAdminService.class);
 
         K8sApiConfig config =
                 configService.apiConfigs().stream().findAny().orElse(null);
@@ -137,6 +142,16 @@
             printIngresses(ingress);
         });
 
+        print("\nSynchronizing kubernetes network policies");
+        print(NETWORK_POLICY_FORMAT, "Name", "Namespace", "Types");
+        client.network().networkPolicies().inAnyNamespace().list().getItems().forEach(policy -> {
+            if (networkPolicyAdminService.networkPolicy(policy.getMetadata().getUid()) != null) {
+                networkPolicyAdminService.updateNetworkPolicy(policy);
+            } else {
+                networkPolicyAdminService.createNetworkPolicy(policy);
+            }
+            printNetworkPolicy(policy);
+        });
     }
 
     private void printIngresses(Ingress ingress) {
@@ -192,6 +207,14 @@
                 containers.isEmpty() ? "" : containers);
     }
 
+    private void printNetworkPolicy(NetworkPolicy policy) {
+        print(NETWORK_POLICY_FORMAT,
+                policy.getMetadata().getName(),
+                policy.getMetadata().getNamespace(),
+                policy.getSpec().getPolicyTypes().isEmpty() ?
+                        "" : policy.getSpec().getPolicyTypes());
+    }
+
     private void syncPortFromPod(Pod pod, K8sNetworkAdminService adminService) {
         Map<String, String> annotations = pod.getMetadata().getAnnotations();
         if (annotations != null && !annotations.isEmpty() &&
diff --git a/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/impl/DistributedK8sNetworkPolicyStore.java b/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/impl/DistributedK8sNetworkPolicyStore.java
new file mode 100644
index 0000000..25f34e3
--- /dev/null
+++ b/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/impl/DistributedK8sNetworkPolicyStore.java
@@ -0,0 +1,201 @@
+/*
+ * Copyright 2019-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.k8snetworking.impl;
+
+import com.google.common.collect.ImmutableSet;
+import io.fabric8.kubernetes.api.model.IntOrString;
+import io.fabric8.kubernetes.api.model.LabelSelector;
+import io.fabric8.kubernetes.api.model.LabelSelectorRequirement;
+import io.fabric8.kubernetes.api.model.ObjectMeta;
+import io.fabric8.kubernetes.api.model.networking.IPBlock;
+import io.fabric8.kubernetes.api.model.networking.NetworkPolicy;
+import io.fabric8.kubernetes.api.model.networking.NetworkPolicyEgressRule;
+import io.fabric8.kubernetes.api.model.networking.NetworkPolicyIngressRule;
+import io.fabric8.kubernetes.api.model.networking.NetworkPolicyPeer;
+import io.fabric8.kubernetes.api.model.networking.NetworkPolicyPort;
+import io.fabric8.kubernetes.api.model.networking.NetworkPolicySpec;
+import org.onlab.util.KryoNamespace;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.k8snetworking.api.K8sNetworkPolicyEvent;
+import org.onosproject.k8snetworking.api.K8sNetworkPolicyStore;
+import org.onosproject.k8snetworking.api.K8sNetworkPolicyStoreDelegate;
+import org.onosproject.store.AbstractStore;
+import org.onosproject.store.serializers.KryoNamespaces;
+import org.onosproject.store.service.ConsistentMap;
+import org.onosproject.store.service.MapEvent;
+import org.onosproject.store.service.MapEventListener;
+import org.onosproject.store.service.Serializer;
+import org.onosproject.store.service.StorageService;
+import org.onosproject.store.service.Versioned;
+import org.osgi.service.component.annotations.Activate;
+import org.osgi.service.component.annotations.Component;
+import org.osgi.service.component.annotations.Deactivate;
+import org.osgi.service.component.annotations.Reference;
+import org.osgi.service.component.annotations.ReferenceCardinality;
+import org.slf4j.Logger;
+
+import java.util.LinkedHashMap;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+
+import static com.google.common.base.Preconditions.checkArgument;
+import static java.util.concurrent.Executors.newSingleThreadExecutor;
+import static org.onlab.util.Tools.groupedThreads;
+import static org.onosproject.k8snetworking.api.K8sNetworkPolicyEvent.Type.K8S_NETWORK_POLICY_CREATED;
+import static org.onosproject.k8snetworking.api.K8sNetworkPolicyEvent.Type.K8S_NETWORK_POLICY_REMOVED;
+import static org.onosproject.k8snetworking.api.K8sNetworkPolicyEvent.Type.K8S_NETWORK_POLICY_UPDATED;
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Implementation of kubernetes network policy store using consistent map.
+ */
+@Component(immediate = true, service = K8sNetworkPolicyStore.class)
+public class DistributedK8sNetworkPolicyStore
+        extends AbstractStore<K8sNetworkPolicyEvent, K8sNetworkPolicyStoreDelegate>
+        implements K8sNetworkPolicyStore {
+
+    private final Logger log = getLogger(getClass());
+
+    private static final String ERR_NOT_FOUND = " does not exist";
+    private static final String ERR_DUPLICATE = " already exists";
+    private static final String APP_ID = "org.onosproject.k8snetwork";
+
+    private static final KryoNamespace
+            SERIALIZER_K8S_NETWORK_POLICY = KryoNamespace.newBuilder()
+            .register(KryoNamespaces.API)
+            .register(NetworkPolicy.class)
+            .register(ObjectMeta.class)
+            .register(NetworkPolicySpec.class)
+            .register(NetworkPolicyIngressRule.class)
+            .register(NetworkPolicyEgressRule.class)
+            .register(LabelSelector.class)
+            .register(NetworkPolicyPeer.class)
+            .register(NetworkPolicyPort.class)
+            .register(IPBlock.class)
+            .register(LabelSelector.class)
+            .register(LabelSelectorRequirement.class)
+            .register(LinkedHashMap.class)
+            .register(IntOrString.class)
+            .build();
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY)
+    protected CoreService coreService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY)
+    protected StorageService storageService;
+
+    private final ExecutorService eventExecutor = newSingleThreadExecutor(
+            groupedThreads(this.getClass().getSimpleName(), "event-handler", log));
+
+    private final MapEventListener<String, NetworkPolicy> networkPolicyMapListener = new K8sNetworkPolicyMapListener();
+
+    private ConsistentMap<String, NetworkPolicy> networkPolicyStore;
+
+    @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");
+    }
+
+    @Deactivate
+    protected void deactivate() {
+        networkPolicyStore.removeListener(networkPolicyMapListener);
+        eventExecutor.shutdown();
+        log.info("Stopped");
+    }
+
+    @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;
+        });
+    }
+
+    @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;
+        });
+    }
+
+    @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();
+    }
+
+    @Override
+    public NetworkPolicy networkPolicy(String uid) {
+        return networkPolicyStore.asJavaMap().get(uid);
+    }
+
+    @Override
+    public Set<NetworkPolicy> networkPolicies() {
+        return ImmutableSet.copyOf(networkPolicyStore.asJavaMap().values());
+    }
+
+    @Override
+    public void clear() {
+        networkPolicyStore.clear();
+    }
+
+    private class K8sNetworkPolicyMapListener implements MapEventListener<String, NetworkPolicy> {
+
+        @Override
+        public void event(MapEvent<String, NetworkPolicy> event) {
+
+            switch (event.type()) {
+                case INSERT:
+                    log.debug("Kubernetes network policy created {}", event.newValue());
+                    eventExecutor.execute(() ->
+                            notifyDelegate(new K8sNetworkPolicyEvent(
+                                    K8S_NETWORK_POLICY_CREATED, event.newValue().value())));
+                    break;
+                case UPDATE:
+                    log.debug("Kubernetes network policy updated {}", event.newValue());
+                    eventExecutor.execute(() ->
+                            notifyDelegate(new K8sNetworkPolicyEvent(
+                                    K8S_NETWORK_POLICY_UPDATED, event.newValue().value())));
+                    break;
+                case REMOVE:
+                    log.debug("Kubernetes network policy removed {}", event.oldValue());
+                    eventExecutor.execute(() ->
+                            notifyDelegate(new K8sNetworkPolicyEvent(
+                                    K8S_NETWORK_POLICY_REMOVED, event.oldValue().value())));
+                    break;
+                default:
+                    // do nothing
+                    break;
+            }
+        }
+    }
+}
diff --git a/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/impl/K8sNetworkPolicyManager.java b/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/impl/K8sNetworkPolicyManager.java
new file mode 100644
index 0000000..8f43afd
--- /dev/null
+++ b/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/impl/K8sNetworkPolicyManager.java
@@ -0,0 +1,168 @@
+/*
+ * Copyright 2019-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.k8snetworking.impl;
+
+import com.google.common.base.Strings;
+import com.google.common.collect.ImmutableSet;
+import io.fabric8.kubernetes.api.model.networking.NetworkPolicy;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.event.ListenerRegistry;
+import org.onosproject.k8snetworking.api.K8sNetworkPolicyAdminService;
+import org.onosproject.k8snetworking.api.K8sNetworkPolicyEvent;
+import org.onosproject.k8snetworking.api.K8sNetworkPolicyListener;
+import org.onosproject.k8snetworking.api.K8sNetworkPolicyService;
+import org.onosproject.k8snetworking.api.K8sNetworkPolicyStore;
+import org.onosproject.k8snetworking.api.K8sNetworkPolicyStoreDelegate;
+import org.osgi.service.component.annotations.Activate;
+import org.osgi.service.component.annotations.Component;
+import org.osgi.service.component.annotations.Deactivate;
+import org.osgi.service.component.annotations.Reference;
+import org.osgi.service.component.annotations.ReferenceCardinality;
+import org.slf4j.Logger;
+
+import java.util.Set;
+
+import static com.google.common.base.Preconditions.checkArgument;
+import static com.google.common.base.Preconditions.checkNotNull;
+import static org.onosproject.k8snetworking.api.Constants.K8S_NETWORKING_APP_ID;
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Provides implementation of administering and interfacing kubernetes network policy.
+ */
+@Component(
+        immediate = true,
+        service = {K8sNetworkPolicyAdminService.class, K8sNetworkPolicyService.class }
+)
+public class K8sNetworkPolicyManager
+        extends ListenerRegistry<K8sNetworkPolicyEvent, K8sNetworkPolicyListener>
+        implements K8sNetworkPolicyAdminService, K8sNetworkPolicyService {
+
+    protected final Logger log = getLogger(getClass());
+
+    private static final String MSG_NETWORK_POLICY  = "Kubernetes network policy %s %s";
+    private static final String MSG_CREATED = "created";
+    private static final String MSG_UPDATED = "updated";
+    private static final String MSG_REMOVED = "removed";
+
+    private static final String
+            ERR_NULL_NETWORK_POLICY = "Kubernetes network policy cannot be null";
+    private static final String
+            ERR_NULL_NETWORK_POLICY_UID  = "Kubernetes network policy UID cannot be null";
+
+    private static final String ERR_IN_USE = " still in use";
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY)
+    protected CoreService coreService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY)
+    protected K8sNetworkPolicyStore k8sNetworkPolicyStore;
+
+    private final K8sNetworkPolicyStoreDelegate
+            delegate = new InternalNetworkPolicyStorageDelegate();
+
+    private ApplicationId appId;
+
+    @Activate
+    protected void activate() {
+        appId = coreService.registerApplication(K8S_NETWORKING_APP_ID);
+
+        k8sNetworkPolicyStore.setDelegate(delegate);
+        log.info("Started");
+    }
+
+    @Deactivate
+    protected void deactivate() {
+        k8sNetworkPolicyStore.unsetDelegate(delegate);
+        log.info("Stopped");
+    }
+
+    @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));
+    }
+
+    @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));
+    }
+
+    @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));
+            }
+        }
+    }
+
+    @Override
+    public void clear() {
+        k8sNetworkPolicyStore.clear();
+    }
+
+    @Override
+    public NetworkPolicy networkPolicy(String uid) {
+        checkArgument(!Strings.isNullOrEmpty(uid), ERR_NULL_NETWORK_POLICY_UID);
+        return k8sNetworkPolicyStore.networkPolicy(uid);
+    }
+
+    @Override
+    public Set<NetworkPolicy> networkPolicies() {
+        return ImmutableSet.copyOf(k8sNetworkPolicyStore.networkPolicies());
+    }
+
+    private boolean isNetworkPolicyInUse(String uid) {
+        return false;
+    }
+
+    private class InternalNetworkPolicyStorageDelegate
+            implements K8sNetworkPolicyStoreDelegate {
+
+        @Override
+        public void notify(K8sNetworkPolicyEvent event) {
+            if (event != null) {
+                log.trace("send kubernetes network policy event {}", event);
+                process(event);
+            }
+        }
+    }
+}
diff --git a/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/impl/K8sNetworkPolicyWatcher.java b/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/impl/K8sNetworkPolicyWatcher.java
new file mode 100644
index 0000000..1f8c4a3
--- /dev/null
+++ b/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/impl/K8sNetworkPolicyWatcher.java
@@ -0,0 +1,207 @@
+/*
+ * Copyright 2019-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.k8snetworking.impl;
+
+import io.fabric8.kubernetes.api.model.networking.NetworkPolicy;
+import io.fabric8.kubernetes.client.KubernetesClient;
+import io.fabric8.kubernetes.client.KubernetesClientException;
+import io.fabric8.kubernetes.client.Watcher;
+import org.onosproject.cluster.ClusterService;
+import org.onosproject.cluster.LeadershipService;
+import org.onosproject.cluster.NodeId;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.k8snetworking.api.K8sNetworkPolicyAdminService;
+import org.onosproject.k8snode.api.K8sApiConfigEvent;
+import org.onosproject.k8snode.api.K8sApiConfigListener;
+import org.onosproject.k8snode.api.K8sApiConfigService;
+import org.onosproject.mastership.MastershipService;
+import org.osgi.service.component.annotations.Activate;
+import org.osgi.service.component.annotations.Component;
+import org.osgi.service.component.annotations.Deactivate;
+import org.osgi.service.component.annotations.Reference;
+import org.osgi.service.component.annotations.ReferenceCardinality;
+import org.slf4j.Logger;
+
+import java.util.Objects;
+import java.util.concurrent.ExecutorService;
+
+import static java.util.concurrent.Executors.newSingleThreadExecutor;
+import static org.onlab.util.Tools.groupedThreads;
+import static org.onosproject.k8snetworking.api.Constants.K8S_NETWORKING_APP_ID;
+import static org.onosproject.k8snetworking.util.K8sNetworkingUtil.k8sClient;
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Kubernetes network policy watcher used for feeding network policy information.
+ */
+@Component(immediate = true)
+public class K8sNetworkPolicyWatcher {
+
+    private final Logger log = getLogger(getClass());
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY)
+    protected CoreService coreService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY)
+    protected MastershipService mastershipService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY)
+    protected ClusterService clusterService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY)
+    protected LeadershipService leadershipService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY)
+    protected K8sNetworkPolicyAdminService k8sNetworkPolicyAdminService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY)
+    protected K8sApiConfigService k8sApiConfigService;
+
+    private final ExecutorService eventExecutor = newSingleThreadExecutor(
+            groupedThreads(this.getClass().getSimpleName(), "event-handler"));
+
+    private final InternalK8sNetworkPolicyWatcher
+            internalK8sNetworkPolicyWatcher = new InternalK8sNetworkPolicyWatcher();
+    private final InternalK8sApiConfigListener
+            internalK8sApiConfigListener = new InternalK8sApiConfigListener();
+
+    private ApplicationId appId;
+    private NodeId localNodeId;
+
+    @Activate
+    protected void activate() {
+        appId = coreService.registerApplication(K8S_NETWORKING_APP_ID);
+        localNodeId = clusterService.getLocalNode().id();
+        leadershipService.runForLeadership(appId.name());
+        k8sApiConfigService.addListener(internalK8sApiConfigListener);
+
+        log.info("Started");
+    }
+
+    @Deactivate
+    protected void deactivate() {
+        k8sApiConfigService.removeListener(internalK8sApiConfigListener);
+        leadershipService.withdraw(appId.name());
+        eventExecutor.shutdown();
+
+        log.info("Stopped");
+    }
+
+    private class InternalK8sApiConfigListener implements K8sApiConfigListener {
+
+        private boolean isRelevantHelper() {
+            return Objects.equals(localNodeId, leadershipService.getLeader(appId.name()));
+        }
+
+        @Override
+        public void event(K8sApiConfigEvent event) {
+
+            switch (event.type()) {
+                case K8S_API_CONFIG_UPDATED:
+                    eventExecutor.execute(this::processConfigUpdating);
+                    break;
+                case K8S_API_CONFIG_CREATED:
+                case K8S_API_CONFIG_REMOVED:
+                default:
+                    // do nothing
+                    break;
+            }
+        }
+
+        private void processConfigUpdating() {
+            if (!isRelevantHelper()) {
+                return;
+            }
+
+            KubernetesClient client = k8sClient(k8sApiConfigService);
+
+            if (client != null) {
+                client.network().networkPolicies().inAnyNamespace().watch(
+                        internalK8sNetworkPolicyWatcher);
+            }
+        }
+    }
+
+    private class InternalK8sNetworkPolicyWatcher implements Watcher<NetworkPolicy> {
+
+        @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;
+            }
+        }
+
+        @Override
+        public void onClose(KubernetesClientException e) {
+            log.info("Network policy watcher OnClose: {}" + e);
+        }
+
+        private void processAddition(NetworkPolicy networkPolicy) {
+            if (!isMaster()) {
+                return;
+            }
+
+            log.trace("Process network policy {} creating event from API server.",
+                    networkPolicy.getMetadata().getName());
+
+            k8sNetworkPolicyAdminService.createNetworkPolicy(networkPolicy);
+        }
+
+        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);
+            }
+        }
+
+        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());
+        }
+
+        private boolean isMaster() {
+            return Objects.equals(localNodeId, leadershipService.getLeader(appId.name()));
+        }
+    }
+}
diff --git a/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/web/K8sManagementWebResource.java b/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/web/K8sManagementWebResource.java
new file mode 100644
index 0000000..42adb65
--- /dev/null
+++ b/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/web/K8sManagementWebResource.java
@@ -0,0 +1,242 @@
+/*
+ * Copyright 2019-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.k8snetworking.web;
+
+import io.fabric8.kubernetes.api.model.Pod;
+import io.fabric8.kubernetes.client.KubernetesClient;
+import org.onlab.packet.IpAddress;
+import org.onlab.packet.MacAddress;
+import org.onlab.util.ItemNotFoundException;
+import org.onosproject.k8snetworking.api.DefaultK8sPort;
+import org.onosproject.k8snetworking.api.K8sEndpointsAdminService;
+import org.onosproject.k8snetworking.api.K8sIngressAdminService;
+import org.onosproject.k8snetworking.api.K8sNetworkAdminService;
+import org.onosproject.k8snetworking.api.K8sNetworkPolicyAdminService;
+import org.onosproject.k8snetworking.api.K8sPodAdminService;
+import org.onosproject.k8snetworking.api.K8sPort;
+import org.onosproject.k8snetworking.api.K8sServiceAdminService;
+import org.onosproject.k8snetworking.util.K8sNetworkingUtil;
+import org.onosproject.k8snode.api.K8sApiConfig;
+import org.onosproject.k8snode.api.K8sApiConfigService;
+import org.onosproject.k8snode.api.K8sNode;
+import org.onosproject.k8snode.api.K8sNodeAdminService;
+import org.onosproject.k8snode.api.K8sNodeState;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.PortNumber;
+import org.onosproject.rest.AbstractWebResource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.util.Map;
+
+import static java.lang.Thread.sleep;
+import static org.onosproject.k8snetworking.api.K8sPort.State.INACTIVE;
+import static org.onosproject.k8snode.api.K8sNode.Type.MASTER;
+import static org.onosproject.k8snode.api.K8sNode.Type.MINION;
+import static org.onosproject.k8snode.api.K8sNodeState.COMPLETE;
+
+/**
+ * REST interface for synchronizing kubernetes network states and rules.
+ */
+@Path("management")
+public class K8sManagementWebResource extends AbstractWebResource {
+    private final Logger log = LoggerFactory.getLogger(getClass());
+
+    private static final String PORT_ID = "portId";
+    private static final String DEVICE_ID = "deviceId";
+    private static final String PORT_NUMBER = "portNumber";
+    private static final String IP_ADDRESS = "ipAddress";
+    private static final String MAC_ADDRESS = "macAddress";
+    private static final String NETWORK_ID = "networkId";
+
+    private static final long SLEEP_MIDDLE_MS = 3000; // we wait 3s
+    private static final long TIMEOUT_MS = 10000; // we wait 10s
+
+    private final K8sApiConfigService configService = get(K8sApiConfigService.class);
+    private final K8sPodAdminService podAdminService = get(K8sPodAdminService.class);
+    private final K8sServiceAdminService serviceAdminService =
+                                            get(K8sServiceAdminService.class);
+    private final K8sIngressAdminService ingressAdminService =
+                                            get(K8sIngressAdminService.class);
+    private final K8sEndpointsAdminService endpointsAdminService =
+                                            get(K8sEndpointsAdminService.class);
+    private final K8sNetworkAdminService networkAdminService =
+                                            get(K8sNetworkAdminService.class);
+    private final K8sNodeAdminService nodeAdminService =
+                                            get(K8sNodeAdminService.class);
+    private final K8sNetworkPolicyAdminService policyAdminService =
+                                            get(K8sNetworkPolicyAdminService.class);
+
+    /**
+     * Synchronizes the all states with kubernetes API server.
+     *
+     * @return 200 OK with sync result, 404 not found
+     * @throws InterruptedException exception
+     */
+    @GET
+    @Produces(MediaType.APPLICATION_JSON)
+    @Path("sync/states")
+    public Response syncStates() {
+        K8sApiConfig config =
+                configService.apiConfigs().stream().findAny().orElse(null);
+        if (config == null) {
+            throw new ItemNotFoundException("Failed to find valid kubernetes API configuration.");
+        }
+
+        KubernetesClient client = K8sNetworkingUtil.k8sClient(config);
+
+        if (client == null) {
+            throw new ItemNotFoundException("Failed to connect to kubernetes API server.");
+        }
+
+        client.services().inAnyNamespace().list().getItems().forEach(svc -> {
+            if (serviceAdminService.service(svc.getMetadata().getUid()) != null) {
+                serviceAdminService.updateService(svc);
+            } else {
+                serviceAdminService.createService(svc);
+            }
+        });
+
+        client.endpoints().inAnyNamespace().list().getItems().forEach(ep -> {
+            if (endpointsAdminService.endpoints(ep.getMetadata().getUid()) != null) {
+                endpointsAdminService.updateEndpoints(ep);
+            } else {
+                endpointsAdminService.createEndpoints(ep);
+            }
+        });
+
+        client.pods().inAnyNamespace().list().getItems().forEach(pod -> {
+            if (podAdminService.pod(pod.getMetadata().getUid()) != null) {
+                podAdminService.updatePod(pod);
+            } else {
+                podAdminService.createPod(pod);
+            }
+
+            syncPortFromPod(pod, networkAdminService);
+        });
+
+        client.extensions().ingresses().inAnyNamespace().list().getItems().forEach(ingress -> {
+            if (ingressAdminService.ingress(ingress.getMetadata().getUid()) != null) {
+                ingressAdminService.updateIngress(ingress);
+            } else {
+                ingressAdminService.createIngress(ingress);
+            }
+        });
+
+        client.network().networkPolicies().inAnyNamespace().list().getItems().forEach(policy -> {
+            if (policyAdminService.networkPolicy(policy.getMetadata().getUid()) != null) {
+                policyAdminService.updateNetworkPolicy(policy);
+            } else {
+                policyAdminService.createNetworkPolicy(policy);
+            }
+        });
+
+        return ok(mapper().createObjectNode()).build();
+    }
+
+    /**
+     * Synchronizes the flow rules.
+     *
+     * @return 200 OK with sync result, 404 not found
+     */
+    @GET
+    @Produces(MediaType.APPLICATION_JSON)
+    @Path("sync/rules")
+    public Response syncRules() {
+
+        syncRulesBase();
+        return ok(mapper().createObjectNode()).build();
+    }
+
+    private void syncPortFromPod(Pod pod, K8sNetworkAdminService adminService) {
+        Map<String, String> annotations = pod.getMetadata().getAnnotations();
+        if (annotations != null && !annotations.isEmpty() &&
+                annotations.get(PORT_ID) != null) {
+            String portId = annotations.get(PORT_ID);
+
+            K8sPort oldPort = adminService.port(portId);
+
+            String networkId = annotations.get(NETWORK_ID);
+            DeviceId deviceId = DeviceId.deviceId(annotations.get(DEVICE_ID));
+            PortNumber portNumber = PortNumber.portNumber(annotations.get(PORT_NUMBER));
+            IpAddress ipAddress = IpAddress.valueOf(annotations.get(IP_ADDRESS));
+            MacAddress macAddress = MacAddress.valueOf(annotations.get(MAC_ADDRESS));
+
+            K8sPort newPort = DefaultK8sPort.builder()
+                    .portId(portId)
+                    .networkId(networkId)
+                    .deviceId(deviceId)
+                    .ipAddress(ipAddress)
+                    .macAddress(macAddress)
+                    .portNumber(portNumber)
+                    .state(INACTIVE)
+                    .build();
+
+            if (oldPort == null) {
+                adminService.createPort(newPort);
+            } else {
+                adminService.updatePort(newPort);
+            }
+        }
+    }
+
+    private void syncRulesBase() {
+        nodeAdminService.completeNodes(MASTER).forEach(this::syncRulesBaseForNode);
+        nodeAdminService.completeNodes(MINION).forEach(this::syncRulesBaseForNode);
+    }
+
+    private void syncRulesBaseForNode(K8sNode k8sNode) {
+        K8sNode updated = k8sNode.updateState(K8sNodeState.INIT);
+        nodeAdminService.updateNode(updated);
+
+        boolean result = true;
+        long timeoutExpiredMs = System.currentTimeMillis() + TIMEOUT_MS;
+
+        while (nodeAdminService.node(k8sNode.hostname()).state() != COMPLETE) {
+
+            long  waitMs = timeoutExpiredMs - System.currentTimeMillis();
+
+            try {
+                sleep(SLEEP_MIDDLE_MS);
+            } catch (InterruptedException e) {
+                log.error("Exception caused during node synchronization...");
+            }
+
+            if (nodeAdminService.node(k8sNode.hostname()).state() == COMPLETE) {
+                break;
+            } else {
+                nodeAdminService.updateNode(updated);
+                log.info("Failed to synchronize flow rules, retrying...");
+            }
+
+            if (waitMs <= 0) {
+                result = false;
+                break;
+            }
+        }
+
+        if (result) {
+            log.info("Successfully synchronize flow rules for node {}!", k8sNode.hostname());
+        } else {
+            log.warn("Failed to synchronize flow rules for node {}.", k8sNode.hostname());
+        }
+    }
+}
diff --git a/apps/k8s-networking/app/src/test/java/org/onosproject/k8snetworking/impl/K8sNetworkPolicyManagerTest.java b/apps/k8s-networking/app/src/test/java/org/onosproject/k8snetworking/impl/K8sNetworkPolicyManagerTest.java
new file mode 100644
index 0000000..9642cd2
--- /dev/null
+++ b/apps/k8s-networking/app/src/test/java/org/onosproject/k8snetworking/impl/K8sNetworkPolicyManagerTest.java
@@ -0,0 +1,218 @@
+/*
+ * Copyright 2019-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.k8snetworking.impl;
+
+import com.google.common.collect.Lists;
+import com.google.common.util.concurrent.MoreExecutors;
+import io.fabric8.kubernetes.api.model.ObjectMeta;
+import io.fabric8.kubernetes.api.model.networking.NetworkPolicy;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.onlab.junit.TestUtils;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreServiceAdapter;
+import org.onosproject.core.DefaultApplicationId;
+import org.onosproject.event.Event;
+import org.onosproject.k8snetworking.api.K8sNetworkPolicyEvent;
+import org.onosproject.k8snetworking.api.K8sNetworkPolicyListener;
+import org.onosproject.store.service.TestStorageService;
+
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.onosproject.k8snetworking.api.K8sNetworkPolicyEvent.Type.K8S_NETWORK_POLICY_CREATED;
+import static org.onosproject.k8snetworking.api.K8sNetworkPolicyEvent.Type.K8S_NETWORK_POLICY_REMOVED;
+import static org.onosproject.k8snetworking.api.K8sNetworkPolicyEvent.Type.K8S_NETWORK_POLICY_UPDATED;
+
+/**
+ * Unit tests for kubernetes network policy manager.
+ */
+public class K8sNetworkPolicyManagerTest {
+
+    private static final ApplicationId TEST_APP_ID = new DefaultApplicationId(1, "test");
+
+    private static final String UNKNOWN_UID = "unknown_uid";
+    private static final String UPDATED_UID = "updated_uid";
+    private static final String UPDATED_NAME = "updated_name";
+
+    private static final String NETWORK_POLICY_UID = "network_policy_uid";
+    private static final String NETWORK_POLICY_NAME = "network_policy_name";
+
+    private static final NetworkPolicy NETWORK_POLICY =
+            createK8sNetworkPolicy(NETWORK_POLICY_UID, NETWORK_POLICY_NAME);
+    private static final NetworkPolicy NETWORK_POLICY_UPDATED =
+            createK8sNetworkPolicy(NETWORK_POLICY_UID, UPDATED_NAME);
+
+    private final TestK8sNetworkPolicyListener testListener = new TestK8sNetworkPolicyListener();
+
+    private K8sNetworkPolicyManager target;
+    private DistributedK8sNetworkPolicyStore k8sNetworkPolicyStore;
+
+    @Before
+    public void setUp() throws Exception {
+        k8sNetworkPolicyStore = new DistributedK8sNetworkPolicyStore();
+        TestUtils.setField(k8sNetworkPolicyStore, "coreService", new TestCoreService());
+        TestUtils.setField(k8sNetworkPolicyStore, "storageService", new TestStorageService());
+        TestUtils.setField(k8sNetworkPolicyStore, "eventExecutor", MoreExecutors.newDirectExecutorService());
+        k8sNetworkPolicyStore.activate();
+
+        target = new K8sNetworkPolicyManager();
+        TestUtils.setField(target, "coreService", new TestCoreService());
+        target.k8sNetworkPolicyStore = k8sNetworkPolicyStore;
+        target.addListener(testListener);
+        target.activate();
+    }
+
+    @After
+    public void tearDown() {
+        target.removeListener(testListener);
+        k8sNetworkPolicyStore.deactivate();
+        target.deactivate();
+        k8sNetworkPolicyStore = null;
+        target = null;
+    }
+
+    /**
+     * Tests if getting all network policies return correct set of network policies.
+     */
+    @Test
+    public void testGetNetworkPolicies() {
+        createBasicNetworkPolicies();
+        assertEquals("Number of network policies did not match", 1, target.networkPolicies().size());
+    }
+
+    /**
+     * Tests if getting a network policy with UID returns the correct network policy.
+     */
+    @Test
+    public void testGetNetworkPolicyByUid() {
+        createBasicNetworkPolicies();
+        assertNotNull("Network policy did not match", target.networkPolicy(NETWORK_POLICY_UID));
+        assertNull("Network policy did not match", target.networkPolicy(UNKNOWN_UID));
+    }
+
+    /**
+     * Tests creating and removing a network policy, and checks if it triggers proper events.
+     */
+    @Test
+    public void testCreateAndRemoveNetworkPolicy() {
+        target.createNetworkPolicy(NETWORK_POLICY);
+        assertEquals("Number of network policies did not match", 1, target.networkPolicies().size());
+        assertNotNull("Network policy was not created", target.networkPolicy(NETWORK_POLICY_UID));
+
+        target.removeNetworkPolicy(NETWORK_POLICY_UID);
+        assertEquals("Number of network policies did not match", 0, target.networkPolicies().size());
+        assertNull("Network policy was not removed", target.networkPolicy(NETWORK_POLICY_UID));
+        validateEvents(K8S_NETWORK_POLICY_CREATED, K8S_NETWORK_POLICY_REMOVED);
+    }
+
+    /**
+     * Tests updating a network policy, and checks if it triggers proper events.
+     */
+    @Test
+    public void testCreateAndUpdateNetworkPolicy() {
+        target.createNetworkPolicy(NETWORK_POLICY);
+        assertEquals("Number of network policies did not match", 1, target.networkPolicies().size());
+        assertEquals("Network policy did not match", NETWORK_POLICY_NAME,
+                target.networkPolicy(NETWORK_POLICY_UID).getMetadata().getName());
+
+        target.updateNetworkPolicy(NETWORK_POLICY_UPDATED);
+        assertEquals("Number of network policies did not match", 1, target.networkPolicies().size());
+        assertEquals("Network policy did not match", UPDATED_NAME,
+                target.networkPolicy(NETWORK_POLICY_UID).getMetadata().getName());
+        validateEvents(K8S_NETWORK_POLICY_CREATED, K8S_NETWORK_POLICY_UPDATED);
+    }
+
+    /**
+     * Tests if creating a null network policy fails with an exception.
+     */
+    @Test(expected = NullPointerException.class)
+    public void testCreateNullNetworkPolicy() {
+        target.createNetworkPolicy(null);
+    }
+
+    /**
+     * Tests if creating a duplicate network policies fails with an exception.
+     */
+    @Test(expected = IllegalArgumentException.class)
+    public void testCreateDuplicatedNetworkPolicy() {
+        target.createNetworkPolicy(NETWORK_POLICY);
+        target.createNetworkPolicy(NETWORK_POLICY);
+    }
+
+    /**
+     * Tests if removing network policy with null ID fails with an exception.
+     */
+    @Test(expected = IllegalArgumentException.class)
+    public void testRemoveNetworkPolicyWithNull() {
+        target.removeNetworkPolicy(null);
+    }
+
+    /**
+     * Tests if updating an unregistered network policy fails with an exception.
+     */
+    @Test(expected = IllegalArgumentException.class)
+    public void testUpdateUnregisteredNetworkPolicy() {
+        target.updateNetworkPolicy(NETWORK_POLICY);
+    }
+
+    private void createBasicNetworkPolicies() {
+        target.createNetworkPolicy(NETWORK_POLICY);
+    }
+
+    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;
+    }
+
+    private static class TestCoreService extends CoreServiceAdapter {
+
+        @Override
+        public ApplicationId registerApplication(String name) {
+            return TEST_APP_ID;
+        }
+    }
+
+    private static class TestK8sNetworkPolicyListener implements K8sNetworkPolicyListener {
+        private List<K8sNetworkPolicyEvent> events = Lists.newArrayList();
+
+        @Override
+        public void event(K8sNetworkPolicyEvent event) {
+            events.add(event);
+        }
+    }
+
+    private void validateEvents(Enum... types) {
+        int i = 0;
+        assertEquals("Number of events did not match", types.length, testListener.events.size());
+        for (Event event : testListener.events) {
+            assertEquals("Incorrect event received", types[i], event.type());
+            i++;
+        }
+        testListener.events.clear();
+    }
+}