Merge branch 'olt-to-cord' of /Users/ash/work/onos-next
diff --git a/BUCK b/BUCK
new file mode 100644
index 0000000..7ff65fe
--- /dev/null
+++ b/BUCK
@@ -0,0 +1,36 @@
+COMPILE_DEPS = [
+    '//lib:CORE_DEPS',
+    '//lib:javax.ws.rs-api',
+    '//lib:jersey-client',
+    '//lib:org.apache.karaf.shell.console',
+    '//utils/rest:onlab-rest',
+    '//cli:onos-cli',
+    '//core/store/serializers:onos-core-serializers',
+    '//apps/cordconfig:onos-apps-cordconfig',
+]
+
+BUNDLES = [
+    ':onos-apps-olt-api',
+    ':onos-apps-olt',
+]
+
+osgi_jar_with_tests (
+    name = 'onos-apps-olt-api',
+    srcs = glob(['api/' + SRC + '*.java']),
+    deps = COMPILE_DEPS,
+    visibility = ['PUBLIC'],
+)
+
+osgi_jar_with_tests (
+    srcs = glob(['app/' + SRC + '*.java']),
+    deps = COMPILE_DEPS + [':onos-apps-olt-api'],
+    visibility = ['PUBLIC'],
+)
+
+onos_app (
+    title = 'ONOS OLT REST API',
+    category = 'Security',
+    url = 'http://onosproject.org',
+    description = 'OLT application for CORD.',
+    included_bundles = BUNDLES,
+)
diff --git a/api/pom.xml b/api/pom.xml
new file mode 100644
index 0000000..448998c
--- /dev/null
+++ b/api/pom.xml
@@ -0,0 +1,77 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright 2016-present Open Networking Laboratory
+  ~
+  ~ 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.
+  -->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+              xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+
+    <parent>
+        <artifactId>onos-olt</artifactId>
+        <groupId>org.onosproject</groupId>
+        <version>1.7.0-SNAPSHOT</version>
+        <relativePath>../pom.xml</relativePath>
+    </parent>
+
+    <artifactId>onos-app-olt-api</artifactId>
+    <packaging>bundle</packaging>
+
+    <url>http://onosproject.org</url>
+
+    <description>CORD OLT application API</description>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.onosproject</groupId>
+            <artifactId>onlab-junit</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.onosproject</groupId>
+            <artifactId>onos-core-serializers</artifactId>
+            <version>${project.version}</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.onosproject</groupId>
+            <artifactId>onos-api</artifactId>
+            <version>${project.version}</version>
+            <classifier>tests</classifier>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.onosproject</groupId>
+            <artifactId>onos-cord-config</artifactId>
+            <version>${project.version}</version>
+        </dependency>
+
+    </dependencies>
+
+    <build>
+       <plugins>
+          <plugin>
+              <groupId>org.apache.felix</groupId>
+              <artifactId>maven-bundle-plugin</artifactId>
+              <extensions>true</extensions>
+              <configuration>
+                  <instructions>
+                     <Export-Package>org.onosproject.olt</Export-Package>
+                  </instructions>
+              </configuration>
+          </plugin>
+       </plugins>
+    </build>
+</project>
diff --git a/api/src/main/java/org/onosproject/olt/AccessDeviceEvent.java b/api/src/main/java/org/onosproject/olt/AccessDeviceEvent.java
new file mode 100644
index 0000000..8824cbd
--- /dev/null
+++ b/api/src/main/java/org/onosproject/olt/AccessDeviceEvent.java
@@ -0,0 +1,103 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * 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.olt;
+
+import org.onlab.packet.VlanId;
+import org.onosproject.event.AbstractEvent;
+import org.onosproject.net.DeviceId;
+
+import java.util.Optional;
+
+/**
+ * Describes an access device event.
+ */
+public class AccessDeviceEvent extends AbstractEvent<AccessDeviceEvent.Type, DeviceId> {
+
+    private final Optional<VlanId> sVlan;
+    private final Optional<VlanId> cVlan;
+
+    public enum Type {
+        /**
+         * A subscriber was registered and provisioned.
+         */
+        SUBSCRIBER_REGISTERED,
+
+        /**
+         * A subscriber was unregistered and deprovisioned.
+         */
+        SUBSCRIBER_UNREGISTERED,
+
+        /**
+         * An access device connected.
+         */
+        DEVICE_CONNECTED,
+
+        /**
+         * An access device disconnected.
+         */
+        DEVICE_DISCONNECTED
+
+    }
+
+    /**
+     *
+     * Creates an event of a given type and for the specified device,
+     * along with the cVlanId and sVlanId. The vlan fields may not be provisioned
+     * if the event is related to the access device (dis)connection.
+     *
+     * @param type the event type
+     * @param deviceId the device id
+     * @param sVlanId the service vlan
+     * @param cVlanId the customer vlan
+     */
+    public AccessDeviceEvent(Type type, DeviceId deviceId,
+                             VlanId sVlanId,
+                             VlanId cVlanId) {
+        super(type, deviceId);
+        this.sVlan = Optional.ofNullable(sVlanId);
+        this.cVlan = Optional.ofNullable(cVlanId);
+    }
+
+    /**
+     *
+     * Creates an event of a given type and for the specified device, and timestamp
+     * along with the cVlanId and sVlanId. The vlan fields may not be provisioned
+     * if the event is related to the access device (dis)connection.
+     *
+     * @param type the event type
+     * @param deviceId the device id
+     * @param time a timestamp
+     * @param sVlanId the service vlan
+     * @param cVlanId the customer vlan
+     */
+    protected AccessDeviceEvent(Type type, DeviceId deviceId, long time,
+                                VlanId sVlanId,
+                                VlanId cVlanId) {
+        super(type, deviceId, time);
+        this.sVlan = Optional.ofNullable(sVlanId);
+        this.cVlan = Optional.ofNullable(cVlanId);
+
+    }
+
+    public Optional<VlanId> sVlanId() {
+        return sVlan;
+    }
+
+    public Optional<VlanId> cVlanId() {
+        return cVlan;
+    }
+
+}
diff --git a/api/src/main/java/org/onosproject/olt/AccessDeviceListener.java b/api/src/main/java/org/onosproject/olt/AccessDeviceListener.java
new file mode 100644
index 0000000..14ec982
--- /dev/null
+++ b/api/src/main/java/org/onosproject/olt/AccessDeviceListener.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * 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.olt;
+
+import org.onosproject.event.EventListener;
+
+/**
+ * Entity capable of receiving access device related events.
+ */
+public interface AccessDeviceListener extends EventListener<AccessDeviceEvent> {
+}
diff --git a/api/src/main/java/org/onosproject/olt/AccessDeviceService.java b/api/src/main/java/org/onosproject/olt/AccessDeviceService.java
new file mode 100644
index 0000000..aa90540
--- /dev/null
+++ b/api/src/main/java/org/onosproject/olt/AccessDeviceService.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * 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.olt;
+
+import org.onlab.packet.VlanId;
+import org.onosproject.cordconfig.access.AccessDeviceData;
+import org.onosproject.event.ListenerService;
+import org.onosproject.net.ConnectPoint;
+import org.onosproject.net.DeviceId;
+
+import java.util.Collection;
+import java.util.Map;
+
+/**
+ * Service for interacting with an access device (OLT).
+ */
+public interface AccessDeviceService
+        extends ListenerService<AccessDeviceEvent, AccessDeviceListener> {
+
+    /**
+     * Provisions connectivity for a subscriber on an access device.
+     *
+     * @param port subscriber's connection point
+     * @param vlan VLAN ID to provision for subscriber
+     */
+    void provisionSubscriber(ConnectPoint port, VlanId vlan);
+
+    /**
+     * Removes provisioned connectivity for a subscriber from an access device.
+     *
+     * @param port subscriber's connection point
+     */
+    void removeSubscriber(ConnectPoint port);
+
+    /**
+     * Returns information about the provisioned subscribers.
+     *
+     * @return subscribers
+     */
+    Collection<Map.Entry<ConnectPoint, VlanId>> getSubscribers();
+
+    /**
+     * Returns the map of configured OLTs.
+     *
+     * @return a map
+     */
+    Map<DeviceId, AccessDeviceData> fetchOlts();
+
+}
diff --git a/api/src/main/java/org/onosproject/olt/package-info.java b/api/src/main/java/org/onosproject/olt/package-info.java
new file mode 100644
index 0000000..7cbf6c1
--- /dev/null
+++ b/api/src/main/java/org/onosproject/olt/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * 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.
+ */
+
+/**
+ * OLT application api.
+ */
+package org.onosproject.olt;
diff --git a/app/app.xml b/app/app.xml
new file mode 100644
index 0000000..5fcb040
--- /dev/null
+++ b/app/app.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright 2016-present Open Networking Laboratory
+  ~
+  ~ 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.
+  -->
+<app name="org.onosproject.olt" origin="ON.Lab" version="${project.version}"
+     category="Traffic Steering" url="http://onosproject.org" title="Optical Line Terminal App"
+     featuresRepo="mvn:${project.groupId}/${project.artifactId}/${project.version}/xml/features"
+     features="${project.artifactId}" apps="org.onosproject.cord-config">
+    <description>${project.description}</description>
+    <artifact>mvn:${project.groupId}/${project.artifactId}/${project.version}</artifact>
+    <artifact>mvn:${project.groupId}/onos-app-olt-api/${project.version}</artifact>
+</app>
diff --git a/app/features.xml b/app/features.xml
new file mode 100644
index 0000000..9556edd
--- /dev/null
+++ b/app/features.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<!--
+  ~ Copyright 2016-present Open Networking Laboratory
+  ~
+  ~ 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.
+  -->
+<features xmlns="http://karaf.apache.org/xmlns/features/v1.2.0" name="${project.artifactId}-${project.version}">
+    <feature name="${project.artifactId}" version="${project.version}"
+             description="${project.description}">
+        <feature>onos-api</feature>
+        <bundle>mvn:${project.groupId}/onos-app-olt-api/${project.version}</bundle>
+        <bundle>mvn:${project.groupId}/onos-app-olt/${project.version}</bundle>
+    </feature>
+</features>
diff --git a/app/pom.xml b/app/pom.xml
new file mode 100644
index 0000000..ad5e57f
--- /dev/null
+++ b/app/pom.xml
@@ -0,0 +1,129 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright 2016-present Open Networking Laboratory
+  ~
+  ~ 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.
+  -->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <parent>
+        <groupId>org.onosproject</groupId>
+        <artifactId>onos-olt</artifactId>
+        <version>1.7.0-SNAPSHOT</version>
+        <relativePath>../pom.xml</relativePath>
+    </parent>
+    <modelVersion>4.0.0</modelVersion>
+
+    <artifactId>onos-app-olt</artifactId>
+
+    <packaging>bundle</packaging>
+    <description>OLT application for CORD</description>
+
+    <properties>
+        <web.context>/onos/olt</web.context>
+        <api.version>1.0.0</api.version>
+        <api.title>ONOS OLT REST API</api.title>
+        <api.description>
+            APIs for interacting with the CORD OLT application.
+        </api.description>
+        <api.package>org.onosproject.olt.rest</api.package>
+    </properties>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.onosproject</groupId>
+            <artifactId>onos-cord-config</artifactId>
+            <version>${project.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.onosproject</groupId>
+            <artifactId>onos-app-olt-api</artifactId>
+            <version>${project.version}</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.onosproject</groupId>
+            <artifactId>onos-cli</artifactId>
+            <version>${project.version}</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.apache.karaf.shell</groupId>
+            <artifactId>org.apache.karaf.shell.console</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.onosproject</groupId>
+            <artifactId>onos-rest</artifactId>
+            <version>${project.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.onosproject</groupId>
+            <artifactId>onlab-rest</artifactId>
+            <version>${project.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>javax.ws.rs</groupId>
+            <artifactId>javax.ws.rs-api</artifactId>
+            <version>2.0.1</version>
+        </dependency>
+        <dependency>
+            <groupId>org.glassfish.jersey.containers</groupId>
+            <artifactId>jersey-container-servlet</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>com.fasterxml.jackson.core</groupId>
+            <artifactId>jackson-databind</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>com.fasterxml.jackson.core</groupId>
+            <artifactId>jackson-annotations</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>org.osgi</groupId>
+            <artifactId>org.osgi.compendium</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.osgi</groupId>
+            <artifactId>org.osgi.core</artifactId>
+        </dependency>
+    </dependencies>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-bundle-plugin</artifactId>
+                <extensions>true</extensions>
+                <configuration>
+                    <instructions>
+                        <_wab>src/main/webapp/</_wab>
+                        <Include-Resource>
+                            WEB-INF/classes/apidoc/swagger.json=target/swagger.json,
+                            {maven-resources}
+                        </Include-Resource>
+                        <Bundle-SymbolicName>
+                            ${project.groupId}.${project.artifactId}
+                        </Bundle-SymbolicName>
+                        <Import-Package>
+                            *,org.glassfish.jersey.servlet
+                        </Import-Package>
+                        <Web-ContextPath>${web.context}</Web-ContextPath>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+</project>
diff --git a/app/src/main/java/org/onosproject/olt/cli/ShowOltCommand.java b/app/src/main/java/org/onosproject/olt/cli/ShowOltCommand.java
new file mode 100644
index 0000000..a59714b
--- /dev/null
+++ b/app/src/main/java/org/onosproject/olt/cli/ShowOltCommand.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * 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.olt.cli;
+
+import org.apache.karaf.shell.commands.Argument;
+import org.apache.karaf.shell.commands.Command;
+import org.onosproject.cli.AbstractShellCommand;
+import org.onosproject.cordconfig.access.AccessDeviceData;
+import org.onosproject.net.DeviceId;
+import org.onosproject.olt.AccessDeviceService;
+
+import java.util.Map;
+
+/**
+ * Shows configured OLTs.
+ */
+@Command(scope = "onos", name = "olts",
+        description = "Shows configured OLTs")
+public class ShowOltCommand extends AbstractShellCommand {
+
+    @Argument(index = 0, name = "deviceId", description = "Access device ID",
+            required = false, multiValued = false)
+    private String strDeviceId = null;
+
+    @Override
+    protected void execute() {
+        AccessDeviceService service = AbstractShellCommand.get(AccessDeviceService.class);
+        Map<DeviceId, AccessDeviceData> data = service.fetchOlts();
+        if (strDeviceId != null) {
+            DeviceId deviceId = DeviceId.deviceId(strDeviceId);
+            print("OLT %s:", deviceId);
+            display(data.get(deviceId));
+        } else {
+            data.keySet().forEach(did -> {
+                print("OLT %s:", did);
+                display(data.get(did));
+            });
+        }
+    }
+
+    private void display(AccessDeviceData accessDeviceData) {
+        print("\tvlan : %s", accessDeviceData.vlan());
+        print("\tuplink : %s", accessDeviceData.uplink());
+    }
+}
diff --git a/app/src/main/java/org/onosproject/olt/cli/ShowSubscribersCommand.java b/app/src/main/java/org/onosproject/olt/cli/ShowSubscribersCommand.java
new file mode 100644
index 0000000..aee7b4d
--- /dev/null
+++ b/app/src/main/java/org/onosproject/olt/cli/ShowSubscribersCommand.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * 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.olt.cli;
+
+import org.apache.karaf.shell.commands.Command;
+import org.onlab.packet.VlanId;
+import org.onosproject.cli.AbstractShellCommand;
+import org.onosproject.net.ConnectPoint;
+import org.onosproject.olt.AccessDeviceService;
+
+import java.util.Map;
+
+/**
+ * Shows provisioned subscribers.
+ */
+@Command(scope = "onos", name = "subscribers",
+        description = "Shows provisioned subscribers")
+public class ShowSubscribersCommand extends AbstractShellCommand {
+
+    private static final String FORMAT = "port=%s, cvlan=%s";
+
+    @Override
+    protected void execute() {
+        AccessDeviceService service = AbstractShellCommand.get(AccessDeviceService.class);
+        service.getSubscribers().forEach(this::display);
+    }
+
+    private void display(Map.Entry<ConnectPoint, VlanId> subscriber) {
+        print(FORMAT, subscriber.getKey(), subscriber.getValue());
+    }
+}
diff --git a/app/src/main/java/org/onosproject/olt/cli/SubscriberAddCommand.java b/app/src/main/java/org/onosproject/olt/cli/SubscriberAddCommand.java
new file mode 100644
index 0000000..94578a7
--- /dev/null
+++ b/app/src/main/java/org/onosproject/olt/cli/SubscriberAddCommand.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * 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.olt.cli;
+
+import org.apache.karaf.shell.commands.Argument;
+import org.apache.karaf.shell.commands.Command;
+import org.onlab.packet.VlanId;
+import org.onosproject.cli.AbstractShellCommand;
+import org.onosproject.net.ConnectPoint;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.PortNumber;
+import org.onosproject.olt.AccessDeviceService;
+
+/**
+ * Adds a subscriber to an access device.
+ */
+@Command(scope = "onos", name = "add-subscriber-access",
+        description = "Adds a subscriber to an access device")
+public class SubscriberAddCommand extends AbstractShellCommand {
+
+    @Argument(index = 0, name = "deviceId", description = "Access device ID",
+            required = true, multiValued = false)
+    private String strDeviceId = null;
+
+    @Argument(index = 1, name = "port", description = "Subscriber port number",
+            required = true, multiValued = false)
+    private String strPort = null;
+
+    @Argument(index = 2, name = "vlanId",
+            description = "VLAN ID to add",
+            required = true, multiValued = false)
+    private String strVlanId = null;
+
+    @Override
+    protected void execute() {
+        AccessDeviceService service = AbstractShellCommand.get(AccessDeviceService.class);
+
+        DeviceId deviceId = DeviceId.deviceId(strDeviceId);
+        PortNumber port = PortNumber.portNumber(strPort);
+        VlanId vlan = VlanId.vlanId(Short.parseShort(strVlanId));
+        ConnectPoint connectPoint = new ConnectPoint(deviceId, port);
+
+        service.provisionSubscriber(connectPoint, vlan);
+    }
+}
diff --git a/app/src/main/java/org/onosproject/olt/cli/SubscriberRemoveCommand.java b/app/src/main/java/org/onosproject/olt/cli/SubscriberRemoveCommand.java
new file mode 100644
index 0000000..b119095
--- /dev/null
+++ b/app/src/main/java/org/onosproject/olt/cli/SubscriberRemoveCommand.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * 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.olt.cli;
+
+import org.apache.karaf.shell.commands.Argument;
+import org.apache.karaf.shell.commands.Command;
+import org.onosproject.cli.AbstractShellCommand;
+import org.onosproject.net.ConnectPoint;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.PortNumber;
+import org.onosproject.olt.AccessDeviceService;
+
+/**
+ * Adds a subscriber to an access device.
+ */
+@Command(scope = "onos", name = "remove-subscriber-access",
+        description = "Adds a subscriber to an access device")
+public class SubscriberRemoveCommand extends AbstractShellCommand {
+
+    @Argument(index = 0, name = "deviceId", description = "Access device ID",
+            required = true, multiValued = false)
+    private String strDeviceId = null;
+
+    @Argument(index = 1, name = "port", description = "Subscriber port number",
+            required = true, multiValued = false)
+    private String strPort = null;
+
+    @Override
+    protected void execute() {
+        AccessDeviceService service = AbstractShellCommand.get(AccessDeviceService.class);
+
+        DeviceId deviceId = DeviceId.deviceId(strDeviceId);
+        PortNumber port = PortNumber.portNumber(strPort);
+        ConnectPoint connectPoint = new ConnectPoint(deviceId, port);
+
+        service.removeSubscriber(connectPoint);
+
+    }
+}
diff --git a/app/src/main/java/org/onosproject/olt/cli/package-info.java b/app/src/main/java/org/onosproject/olt/cli/package-info.java
new file mode 100644
index 0000000..3b97404
--- /dev/null
+++ b/app/src/main/java/org/onosproject/olt/cli/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * 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.
+ */
+
+/**
+ * OLT application handling PMC OLT hardware.
+ */
+package org.onosproject.olt.cli;
diff --git a/app/src/main/java/org/onosproject/olt/impl/Olt.java b/app/src/main/java/org/onosproject/olt/impl/Olt.java
new file mode 100644
index 0000000..7075213
--- /dev/null
+++ b/app/src/main/java/org/onosproject/olt/impl/Olt.java
@@ -0,0 +1,578 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * 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.olt.impl;
+
+import com.google.common.collect.Maps;
+import org.apache.felix.scr.annotations.Activate;
+import org.apache.felix.scr.annotations.Component;
+import org.apache.felix.scr.annotations.Deactivate;
+import org.apache.felix.scr.annotations.Modified;
+import org.apache.felix.scr.annotations.Property;
+import org.apache.felix.scr.annotations.Reference;
+import org.apache.felix.scr.annotations.ReferenceCardinality;
+import org.apache.felix.scr.annotations.Service;
+import org.onlab.packet.EthType;
+import org.onlab.packet.VlanId;
+import org.onosproject.cfg.ComponentConfigService;
+import org.onosproject.cordconfig.access.AccessDeviceConfig;
+import org.onosproject.cordconfig.access.AccessDeviceData;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.event.AbstractListenerManager;
+import org.onosproject.mastership.MastershipService;
+import org.onosproject.net.ConnectPoint;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.Port;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.config.ConfigFactory;
+import org.onosproject.net.config.NetworkConfigEvent;
+import org.onosproject.net.config.NetworkConfigListener;
+import org.onosproject.net.config.NetworkConfigRegistry;
+import org.onosproject.net.config.basics.SubjectFactories;
+import org.onosproject.net.device.DeviceEvent;
+import org.onosproject.net.device.DeviceListener;
+import org.onosproject.net.device.DeviceService;
+import org.onosproject.net.flow.DefaultTrafficSelector;
+import org.onosproject.net.flow.DefaultTrafficTreatment;
+import org.onosproject.net.flow.TrafficSelector;
+import org.onosproject.net.flow.TrafficTreatment;
+import org.onosproject.net.flow.criteria.Criteria;
+import org.onosproject.net.flowobjective.DefaultFilteringObjective;
+import org.onosproject.net.flowobjective.DefaultForwardingObjective;
+import org.onosproject.net.flowobjective.FilteringObjective;
+import org.onosproject.net.flowobjective.FlowObjectiveService;
+import org.onosproject.net.flowobjective.ForwardingObjective;
+import org.onosproject.net.flowobjective.Objective;
+import org.onosproject.net.flowobjective.ObjectiveContext;
+import org.onosproject.net.flowobjective.ObjectiveError;
+import org.onosproject.olt.AccessDeviceEvent;
+import org.onosproject.olt.AccessDeviceListener;
+import org.onosproject.olt.AccessDeviceService;
+import org.onosproject.store.serializers.KryoNamespaces;
+import org.onosproject.store.service.Serializer;
+import org.onosproject.store.service.StorageService;
+import org.osgi.service.component.ComponentContext;
+import org.slf4j.Logger;
+
+import java.util.Collection;
+import java.util.Dictionary;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Properties;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+import static com.google.common.base.Strings.isNullOrEmpty;
+import static org.onlab.util.Tools.get;
+import static org.onlab.util.Tools.groupedThreads;
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Provisions rules on access devices.
+ */
+@Service
+@Component(immediate = true)
+public class Olt
+        extends AbstractListenerManager<AccessDeviceEvent, AccessDeviceListener>
+        implements AccessDeviceService {
+
+    private static final short DEFAULT_VLAN = 0;
+    private static final String SUBSCRIBERS = "existing-subscribers";
+
+    private final Logger log = getLogger(getClass());
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected FlowObjectiveService flowObjectiveService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected MastershipService mastershipService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected DeviceService deviceService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected CoreService coreService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected NetworkConfigRegistry networkConfig;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected ComponentConfigService componentConfigService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected StorageService storageService;
+
+    @Property(name = "defaultVlan", intValue = DEFAULT_VLAN,
+            label = "Default VLAN RG<->ONU traffic")
+    private int defaultVlan = DEFAULT_VLAN;
+
+    private final DeviceListener deviceListener = new InternalDeviceListener();
+
+    private ApplicationId appId;
+
+    private ExecutorService oltInstallers = Executors.newFixedThreadPool(4,
+                                                                         groupedThreads("onos/olt-service",
+                                                                                        "olt-installer-%d"));
+
+    private Map<DeviceId, AccessDeviceData> oltData = new ConcurrentHashMap<>();
+
+    private Map<ConnectPoint, VlanId> subscribers;
+
+    private InternalNetworkConfigListener configListener =
+            new InternalNetworkConfigListener();
+    private static final Class<AccessDeviceConfig> CONFIG_CLASS =
+            AccessDeviceConfig.class;
+
+    private ConfigFactory<DeviceId, AccessDeviceConfig> configFactory =
+            new ConfigFactory<DeviceId, AccessDeviceConfig>(
+                    SubjectFactories.DEVICE_SUBJECT_FACTORY, CONFIG_CLASS, "accessDevice") {
+                @Override
+                public AccessDeviceConfig createConfig() {
+                    return new AccessDeviceConfig();
+                }
+            };
+
+
+    @Activate
+    public void activate(ComponentContext context) {
+        modified(context);
+        appId = coreService.registerApplication("org.onosproject.olt");
+        componentConfigService.registerProperties(getClass());
+
+        eventDispatcher.addSink(AccessDeviceEvent.class, listenerRegistry);
+
+        networkConfig.registerConfigFactory(configFactory);
+        networkConfig.addListener(configListener);
+
+
+        networkConfig.getSubjects(DeviceId.class, AccessDeviceConfig.class).forEach(
+                subject -> {
+                    AccessDeviceConfig config = networkConfig.getConfig(subject, AccessDeviceConfig.class);
+                    if (config != null) {
+                        AccessDeviceData data = config.getOlt();
+                        oltData.put(data.deviceId(), data);
+                    }
+                }
+        );
+
+        oltData.keySet().stream()
+                .flatMap(did -> deviceService.getPorts(did).stream())
+                .filter(p -> !oltData.get(p.element().id()).uplink().equals(p.number()))
+                .filter(p -> p.isEnabled())
+                .forEach(p -> processFilteringObjectives((DeviceId) p.element().id(),
+                                                         p.number(), true));
+
+        subscribers = storageService.<ConnectPoint, VlanId>consistentMapBuilder()
+                .withName(SUBSCRIBERS)
+                .withSerializer(Serializer.using(KryoNamespaces.API))
+                .build().asJavaMap();
+
+        deviceService.addListener(deviceListener);
+
+        log.info("Started with Application ID {}", appId.id());
+    }
+
+    @Deactivate
+    public void deactivate() {
+        componentConfigService.unregisterProperties(getClass(), false);
+        deviceService.removeListener(deviceListener);
+        networkConfig.removeListener(configListener);
+        networkConfig.unregisterConfigFactory(configFactory);
+        log.info("Stopped");
+    }
+
+    @Modified
+    public void modified(ComponentContext context) {
+        Dictionary<?, ?> properties = context != null ? context.getProperties() : new Properties();
+
+        try {
+            String s = get(properties, "defaultVlan");
+            defaultVlan = isNullOrEmpty(s) ? DEFAULT_VLAN : Integer.parseInt(s.trim());
+        } catch (Exception e) {
+            defaultVlan = DEFAULT_VLAN;
+        }
+    }
+
+    @Override
+    public void provisionSubscriber(ConnectPoint port, VlanId vlan) {
+        AccessDeviceData olt = oltData.get(port.deviceId());
+
+        if (olt == null) {
+            log.warn("No data found for OLT device {}", port.deviceId());
+            return;
+        }
+
+        provisionVlans(olt.deviceId(), olt.uplink(), port.port(), vlan, olt.vlan(),
+                       olt.defaultVlan());
+    }
+
+    @Override
+    public void removeSubscriber(ConnectPoint port) {
+        AccessDeviceData olt = oltData.get(port.deviceId());
+
+        if (olt == null) {
+            log.warn("No data found for OLT device {}", port.deviceId());
+            return;
+        }
+
+        VlanId subscriberVlan = subscribers.remove(port);
+
+        if (subscriberVlan == null) {
+            log.warn("Unknown subscriber at location {}", port);
+            return;
+        }
+
+        unprovisionSubscriber(olt.deviceId(), olt.uplink(), port.port(), subscriberVlan,
+                              olt.vlan(), olt.defaultVlan());
+
+    }
+
+    @Override
+    public Collection<Map.Entry<ConnectPoint, VlanId>> getSubscribers() {
+        return subscribers.entrySet();
+    }
+
+    @Override
+    public Map<DeviceId, AccessDeviceData> fetchOlts() {
+        return Maps.newHashMap(oltData);
+    }
+
+    private void unprovisionSubscriber(DeviceId deviceId, PortNumber uplink,
+                                       PortNumber subscriberPort, VlanId subscriberVlan,
+                                       VlanId deviceVlan, Optional<VlanId> defaultVlan) {
+
+        CompletableFuture<ObjectiveError> downFuture = new CompletableFuture();
+        CompletableFuture<ObjectiveError> upFuture = new CompletableFuture();
+
+        ForwardingObjective.Builder upFwd = upBuilder(uplink, subscriberPort,
+                                                      subscriberVlan, deviceVlan,
+                                                      defaultVlan);
+        ForwardingObjective.Builder downFwd = downBuilder(uplink, subscriberPort,
+                                                          subscriberVlan, deviceVlan,
+                                                          defaultVlan);
+
+
+        flowObjectiveService.forward(deviceId, upFwd.remove(new ObjectiveContext() {
+            @Override
+            public void onSuccess(Objective objective) {
+                upFuture.complete(null);
+            }
+
+            @Override
+            public void onError(Objective objective, ObjectiveError error) {
+                upFuture.complete(error);
+            }
+        }));
+
+        flowObjectiveService.forward(deviceId, downFwd.remove(new ObjectiveContext() {
+            @Override
+            public void onSuccess(Objective objective) {
+                downFuture.complete(null);
+            }
+
+            @Override
+            public void onError(Objective objective, ObjectiveError error) {
+                downFuture.complete(error);
+            }
+        }));
+
+        upFuture.thenAcceptBothAsync(downFuture, (upStatus, downStatus) -> {
+            if (upStatus == null && downStatus == null) {
+                post(new AccessDeviceEvent(AccessDeviceEvent.Type.SUBSCRIBER_UNREGISTERED,
+                                           deviceId,
+                                           deviceVlan,
+                                           subscriberVlan));
+            } else if (downStatus != null) {
+                log.error("Subscriber with vlan {} on device {} " +
+                                  "on port {} failed downstream uninstallation: {}",
+                          subscriberVlan, deviceId, subscriberPort, downStatus);
+            } else if (upStatus != null) {
+                log.error("Subscriber with vlan {} on device {} " +
+                                  "on port {} failed upstream uninstallation: {}",
+                          subscriberVlan, deviceId, subscriberPort, upStatus);
+            }
+        }, oltInstallers);
+
+    }
+
+    private void provisionVlans(DeviceId deviceId, PortNumber uplinkPort,
+                                PortNumber subscriberPort,
+                                VlanId subscriberVlan, VlanId deviceVlan,
+                                Optional<VlanId> defaultVlan) {
+
+        CompletableFuture<ObjectiveError> downFuture = new CompletableFuture();
+        CompletableFuture<ObjectiveError> upFuture = new CompletableFuture();
+
+        ForwardingObjective.Builder upFwd = upBuilder(uplinkPort, subscriberPort,
+                                                      subscriberVlan, deviceVlan,
+                                                      defaultVlan);
+
+
+        ForwardingObjective.Builder downFwd = downBuilder(uplinkPort, subscriberPort,
+                                                          subscriberVlan, deviceVlan,
+                                                          defaultVlan);
+
+        ConnectPoint cp = new ConnectPoint(deviceId, subscriberPort);
+        subscribers.put(cp, subscriberVlan);
+
+        flowObjectiveService.forward(deviceId, upFwd.add(new ObjectiveContext() {
+            @Override
+            public void onSuccess(Objective objective) {
+                upFuture.complete(null);
+            }
+
+            @Override
+            public void onError(Objective objective, ObjectiveError error) {
+                upFuture.complete(error);
+            }
+        }));
+
+        flowObjectiveService.forward(deviceId, downFwd.add(new ObjectiveContext() {
+            @Override
+            public void onSuccess(Objective objective) {
+                downFuture.complete(null);
+            }
+
+            @Override
+            public void onError(Objective objective, ObjectiveError error) {
+                downFuture.complete(error);
+            }
+        }));
+
+        upFuture.thenAcceptBothAsync(downFuture, (upStatus, downStatus) -> {
+            if (upStatus == null && downStatus == null) {
+                post(new AccessDeviceEvent(AccessDeviceEvent.Type.SUBSCRIBER_REGISTERED,
+                                           deviceId,
+                                           deviceVlan,
+                                           subscriberVlan));
+
+            } else if (downStatus != null) {
+                log.error("Subscriber with vlan {} on device {} " +
+                                  "on port {} failed downstream installation: {}",
+                          subscriberVlan, deviceId, subscriberPort, downStatus);
+            } else if (upStatus != null) {
+                log.error("Subscriber with vlan {} on device {} " +
+                                  "on port {} failed upstream installation: {}",
+                          subscriberVlan, deviceId, subscriberPort, upStatus);
+            }
+        }, oltInstallers);
+
+    }
+
+    private ForwardingObjective.Builder downBuilder(PortNumber uplinkPort,
+                                                    PortNumber subscriberPort,
+                                                    VlanId subscriberVlan,
+                                                    VlanId deviceVlan,
+                                                    Optional<VlanId> defaultVlan) {
+        TrafficSelector downstream = DefaultTrafficSelector.builder()
+                .matchVlanId(deviceVlan)
+                .matchInPort(uplinkPort)
+                .matchInnerVlanId(subscriberVlan)
+                .build();
+
+        TrafficTreatment downstreamTreatment = DefaultTrafficTreatment.builder()
+                .popVlan()
+                .setVlanId(defaultVlan.orElse(VlanId.vlanId((short) this.defaultVlan)))
+                .setOutput(subscriberPort)
+                .build();
+
+        return DefaultForwardingObjective.builder()
+                .withFlag(ForwardingObjective.Flag.VERSATILE)
+                .withPriority(1000)
+                .makePermanent()
+                .withSelector(downstream)
+                .fromApp(appId)
+                .withTreatment(downstreamTreatment);
+    }
+
+    private ForwardingObjective.Builder upBuilder(PortNumber uplinkPort,
+                                                  PortNumber subscriberPort,
+                                                  VlanId subscriberVlan,
+                                                  VlanId deviceVlan,
+                                                  Optional<VlanId> defaultVlan) {
+        TrafficSelector upstream = DefaultTrafficSelector.builder()
+                .matchVlanId(defaultVlan.orElse(VlanId.vlanId((short) this.defaultVlan)))
+                .matchInPort(subscriberPort)
+                .build();
+
+
+        TrafficTreatment upstreamTreatment = DefaultTrafficTreatment.builder()
+                .pushVlan()
+                .setVlanId(subscriberVlan)
+                .pushVlan()
+                .setVlanId(deviceVlan)
+                .setOutput(uplinkPort)
+                .build();
+
+        return DefaultForwardingObjective.builder()
+                .withFlag(ForwardingObjective.Flag.VERSATILE)
+                .withPriority(1000)
+                .makePermanent()
+                .withSelector(upstream)
+                .fromApp(appId)
+                .withTreatment(upstreamTreatment);
+    }
+
+    private void processFilteringObjectives(DeviceId devId, PortNumber port, boolean install) {
+        if (!mastershipService.isLocalMaster(devId)) {
+            return;
+        }
+        DefaultFilteringObjective.Builder builder = DefaultFilteringObjective.builder();
+
+        FilteringObjective eapol = (install ? builder.permit() : builder.deny())
+                .withKey(Criteria.matchInPort(port))
+                .addCondition(Criteria.matchEthType(EthType.EtherType.EAPOL.ethType()))
+                .withMeta(DefaultTrafficTreatment.builder()
+                                  .setOutput(PortNumber.CONTROLLER).build())
+                .fromApp(appId)
+                .withPriority(1000)
+                .add(new ObjectiveContext() {
+                    @Override
+                    public void onSuccess(Objective objective) {
+                        log.info("Eapol filter for {} on {} installed.",
+                                 devId, port);
+                    }
+
+                    @Override
+                    public void onError(Objective objective, ObjectiveError error) {
+                        log.info("Eapol filter for {} on {} failed because {}",
+                                 devId, port, error);
+                    }
+                });
+
+        flowObjectiveService.filter(devId, eapol);
+
+    }
+
+    private class InternalDeviceListener implements DeviceListener {
+        @Override
+        public void event(DeviceEvent event) {
+            DeviceId devId = event.subject().id();
+            if (!oltData.containsKey(devId)) {
+                return;
+            }
+            switch (event.type()) {
+                //TODO: Port handling and bookkeeping should be improved once
+                // olt firmware handles correct behaviour.
+                case PORT_ADDED:
+                    if (!oltData.get(devId).uplink().equals(event.port().number()) &&
+                            event.port().isEnabled()) {
+                        processFilteringObjectives(devId, event.port().number(), true);
+                    }
+                    break;
+                case PORT_REMOVED:
+                    AccessDeviceData olt = oltData.get(devId);
+                    VlanId vlan = subscribers.get(new ConnectPoint(devId,
+                                                                   event.port().number()));
+                    unprovisionSubscriber(devId, olt.uplink(),
+                                          event.port().number(),
+                                          vlan, olt.vlan(), olt.defaultVlan());
+                    if (!oltData.get(devId).uplink().equals(event.port().number()) &&
+                            event.port().isEnabled()) {
+                        processFilteringObjectives(devId, event.port().number(), false);
+                    }
+                    break;
+                case PORT_UPDATED:
+                    if (oltData.get(devId).uplink().equals(event.port().number())) {
+                        break;
+                    }
+                    if (event.port().isEnabled()) {
+                        processFilteringObjectives(devId, event.port().number(), true);
+                    } else {
+                        processFilteringObjectives(devId, event.port().number(), false);
+                    }
+                    break;
+                case DEVICE_ADDED:
+                    post(new AccessDeviceEvent(
+                            AccessDeviceEvent.Type.DEVICE_CONNECTED, devId,
+                            null, null));
+                    provisionDefaultFlows(devId);
+                    break;
+                case DEVICE_REMOVED:
+                    post(new AccessDeviceEvent(
+                            AccessDeviceEvent.Type.DEVICE_DISCONNECTED, devId,
+                            null, null));
+                    break;
+                case DEVICE_AVAILABILITY_CHANGED:
+                    if (deviceService.isAvailable(devId)) {
+                        post(new AccessDeviceEvent(
+                                AccessDeviceEvent.Type.DEVICE_CONNECTED, devId,
+                                null, null));
+                    } else {
+                        post(new AccessDeviceEvent(
+                                AccessDeviceEvent.Type.DEVICE_DISCONNECTED, devId,
+                                null, null));
+                    }
+                    break;
+                case DEVICE_UPDATED:
+                case DEVICE_SUSPENDED:
+                case PORT_STATS_UPDATED:
+                default:
+                    return;
+            }
+        }
+    }
+
+    private class InternalNetworkConfigListener implements NetworkConfigListener {
+        @Override
+        public void event(NetworkConfigEvent event) {
+            switch (event.type()) {
+
+                case CONFIG_ADDED:
+                case CONFIG_UPDATED:
+
+                    AccessDeviceConfig config =
+                            networkConfig.getConfig((DeviceId) event.subject(), CONFIG_CLASS);
+                    if (config != null) {
+                        oltData.put(config.getOlt().deviceId(), config.getOlt());
+                        provisionDefaultFlows((DeviceId) event.subject());
+                    }
+
+                    break;
+                case CONFIG_REGISTERED:
+                case CONFIG_UNREGISTERED:
+                    break;
+                case CONFIG_REMOVED:
+                    oltData.remove(event.subject());
+                default:
+                    break;
+            }
+        }
+
+        @Override
+        public boolean isRelevant(NetworkConfigEvent event) {
+            return event.configClass().equals(CONFIG_CLASS);
+        }
+    }
+
+    private void provisionDefaultFlows(DeviceId deviceId) {
+        if (!mastershipService.isLocalMaster(deviceId)) {
+            return;
+        }
+        List<Port> ports = deviceService.getPorts(deviceId);
+
+        ports.stream()
+                .filter(p -> !oltData.get(p.element().id()).uplink().equals(p.number()))
+                .filter(p -> p.isEnabled())
+                .forEach(p -> processFilteringObjectives((DeviceId) p.element().id(),
+                                                         p.number(), true));
+
+    }
+
+}
diff --git a/app/src/main/java/org/onosproject/olt/impl/package-info.java b/app/src/main/java/org/onosproject/olt/impl/package-info.java
new file mode 100644
index 0000000..238823b
--- /dev/null
+++ b/app/src/main/java/org/onosproject/olt/impl/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * 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.
+ */
+
+/**
+ * OLT application handling PMC OLT hardware.
+ */
+package org.onosproject.olt.impl;
diff --git a/app/src/main/java/org/onosproject/olt/rest/OltWebResource.java b/app/src/main/java/org/onosproject/olt/rest/OltWebResource.java
new file mode 100644
index 0000000..84536ac
--- /dev/null
+++ b/app/src/main/java/org/onosproject/olt/rest/OltWebResource.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * 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.olt.rest;
+
+import javax.ws.rs.DELETE;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+import org.onlab.packet.VlanId;
+import org.onosproject.net.ConnectPoint;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.PortNumber;
+import org.onosproject.olt.AccessDeviceService;
+import org.onosproject.rest.AbstractWebResource;
+
+/**
+ * OLT REST APIs.
+ */
+
+@Path("oltapp")
+public class OltWebResource extends AbstractWebResource {
+
+    /**
+     * Provision a subscriber.
+     *
+     * @param device device id
+     * @param port port number
+     * @param vlan vlan id
+     * @return 200 OK
+     */
+    @POST
+    @Produces(MediaType.APPLICATION_JSON)
+    @Path("{device}/{port}/{vlan}")
+    public Response provisionSubscriber(
+            @PathParam("device")String device,
+            @PathParam("port")long port,
+            @PathParam("vlan")short vlan) {
+        AccessDeviceService service = get(AccessDeviceService.class);
+        DeviceId deviceId = DeviceId.deviceId(device);
+        PortNumber portNumber = PortNumber.portNumber(port);
+        VlanId vlanId = VlanId.vlanId(vlan);
+        ConnectPoint connectPoint = new ConnectPoint(deviceId, portNumber);
+        service.provisionSubscriber(connectPoint, vlanId);
+        return ok("").build();
+    }
+
+    /**
+     * Remove the provisioning for a subscriber.
+     *
+     * @param device device id
+     * @param port port number
+     * @return 204 NO CONTENT
+     */
+    @DELETE
+    @Path("{device}/{port}")
+    public Response removeSubscriber(
+            @PathParam("device")String device,
+            @PathParam("port")long port) {
+        AccessDeviceService service = get(AccessDeviceService.class);
+        DeviceId deviceId = DeviceId.deviceId(device);
+        PortNumber portNumber = PortNumber.portNumber(port);
+        ConnectPoint connectPoint = new ConnectPoint(deviceId, portNumber);
+        service.removeSubscriber(connectPoint);
+        return Response.noContent().build();
+    }
+}
diff --git a/app/src/main/java/org/onosproject/olt/rest/package-info.java b/app/src/main/java/org/onosproject/olt/rest/package-info.java
new file mode 100644
index 0000000..c0ddb5f
--- /dev/null
+++ b/app/src/main/java/org/onosproject/olt/rest/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * 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.
+ */
+
+/**
+ * REST APIs for the OLT application.
+ */
+package org.onosproject.olt.rest;
diff --git a/app/src/main/resources/OSGI-INF/blueprint/shell-config.xml b/app/src/main/resources/OSGI-INF/blueprint/shell-config.xml
new file mode 100644
index 0000000..3830357
--- /dev/null
+++ b/app/src/main/resources/OSGI-INF/blueprint/shell-config.xml
@@ -0,0 +1,46 @@
+<!--
+  ~ Copyright 2016-present Open Networking Laboratory
+  ~
+  ~ 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.
+  -->
+<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">
+
+    <command-bundle xmlns="http://karaf.apache.org/xmlns/shell/v1.1.0">
+        <command>
+            <action class="org.onosproject.olt.cli.SubscriberAddCommand"/>
+            <completers>
+                <ref component-id="deviceIdCompleter"/>
+                <null/>
+            </completers>
+        </command>
+        <command>
+            <action class="org.onosproject.olt.cli.SubscriberRemoveCommand"/>
+            <completers>
+                <ref component-id="deviceIdCompleter"/>
+                <null/>
+            </completers>
+        </command>
+        <command>
+            <action class="org.onosproject.olt.cli.ShowOltCommand"/>
+            <completers>
+                <ref component-id="deviceIdCompleter"/>
+                <null/>
+            </completers>
+        </command>
+        <command>
+            <action class="org.onosproject.olt.cli.ShowSubscribersCommand"/>
+        </command>
+    </command-bundle>
+
+    <bean id="deviceIdCompleter" class="org.onosproject.cli.net.DeviceIdCompleter"/>
+</blueprint>
diff --git a/app/src/main/webapp/WEB-INF/web.xml b/app/src/main/webapp/WEB-INF/web.xml
new file mode 100644
index 0000000..f463194
--- /dev/null
+++ b/app/src/main/webapp/WEB-INF/web.xml
@@ -0,0 +1,39 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright 2016-present Open Networking Laboratory
+  ~
+  ~ 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.
+  -->
+<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
+         xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
+         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
+         id="ONOS" version="2.5">
+    <display-name>OLT REST API v1.0</display-name>
+
+    <servlet>
+        <servlet-name>JAX-RS Service</servlet-name>
+        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
+        <init-param>
+            <param-name>jersey.config.server.provider.classnames</param-name>
+            <param-value>
+                org.onosproject.olt.rest.OltWebResource
+            </param-value>
+        </init-param>
+        <load-on-startup>1</load-on-startup>
+    </servlet>
+
+    <servlet-mapping>
+        <servlet-name>JAX-RS Service</servlet-name>
+        <url-pattern>/*</url-pattern>
+    </servlet-mapping>
+</web-app>
diff --git a/pom.xml b/pom.xml
new file mode 100644
index 0000000..676c49a
--- /dev/null
+++ b/pom.xml
@@ -0,0 +1,38 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright 2015-present Open Networking Laboratory
+  ~
+  ~ 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.
+  -->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <parent>
+        <groupId>org.onosproject</groupId>
+        <artifactId>onos-apps</artifactId>
+        <version>1.7.0-SNAPSHOT</version>
+        <relativePath>../pom.xml</relativePath>
+    </parent>
+    <modelVersion>4.0.0</modelVersion>
+
+    <artifactId>onos-olt</artifactId>
+
+    <packaging>pom</packaging>
+    <description>OLT application for CORD</description>
+
+    <modules>
+        <module>api</module>
+        <module>app</module>
+    </modules>
+
+</project>