[ONOS-4691] Refactoring OpticalPortOperator (2/3)

- Define ConfigOperator for a Port
- Refactor OpticalPortOperator as PortConfigOperator
- Add plug-in mechanism for PortConfigOperator on DeviceManager
- Move OpticalPortConfig, OpticalPortOperator to optical-model bundle

Change-Id: I5d416305b0c1b0e31e0ad64baa92d126303548bc
diff --git a/apps/optical-model/src/main/java/org/onosproject/net/optical/config/OpticalPortConfig.java b/apps/optical-model/src/main/java/org/onosproject/net/optical/config/OpticalPortConfig.java
new file mode 100644
index 0000000..bd008a0
--- /dev/null
+++ b/apps/optical-model/src/main/java/org/onosproject/net/optical/config/OpticalPortConfig.java
@@ -0,0 +1,199 @@
+/*
+ * 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.
+ */
+package org.onosproject.net.optical.config;
+
+import java.util.Optional;
+
+import org.onosproject.net.config.Config;
+import org.onosproject.net.ConnectPoint;
+import org.onosproject.net.Port;
+
+import com.fasterxml.jackson.databind.JsonNode;
+
+import static org.onosproject.net.config.Config.FieldPresence.OPTIONAL;
+
+
+/**
+ * Configurations for an optical port on a device.
+ */
+public final class OpticalPortConfig extends Config<ConnectPoint> {
+
+    // optical type {OMS, OCH, ODUClt, fiber}
+    public static final String TYPE = "type";
+
+    // port name. "name" is the alphanumeric name of the port, but "port" refers
+    // to the port number used as a name string (i.e., for ports without
+    // alphanumeric names).
+    public static final String NAME = "name";
+    public static final String PORT = "port";
+    public static final String STATIC_PORT = "staticPort";
+    public static final String STATIC_LAMBDA = "staticLambda";
+
+    // **Linc-OE : remove if it's not needed after all.**
+    public static final String SPEED = "speed";
+
+    @Override
+    public boolean isValid() {
+        return hasOnlyFields(TYPE, NAME, PORT, STATIC_PORT, STATIC_LAMBDA, SPEED) &&
+                isNumber(STATIC_LAMBDA, OPTIONAL) && isNumber(SPEED, OPTIONAL);
+    }
+
+    /**
+     * Returns the Enum value representing the type of port.
+     *
+     * @return the port type, or null if invalid or unset
+     */
+    public Port.Type type() {
+        JsonNode type = object.path(TYPE);
+        if (type.isMissingNode()) {
+            return null;
+        }
+        return Port.Type.valueOf(type.asText());
+    }
+
+    /**
+     * Returns the port name associated with this port configuration. The Name
+     * is an alphanumeric string.
+     *
+     * @return the name of this port, else, an empty string
+     */
+    public String name() {
+        return getStringValue(NAME);
+    }
+
+    /**
+     * Returns a stringified representation of the port number, configured in
+     * some port types without an alphanumeric name as the port name.
+     *
+     * @return A string representation of the port number
+     */
+    public String numberName() {
+        return getStringValue(PORT);
+    }
+
+    /**
+     * Returns the string-representation of name of the output port. This is
+     * usually an OMS port for an OCH input ports, or an OCH port for ODU input
+     * ports.
+     *
+     * @return the name of this port, else, an empty string
+     */
+    public String staticPort() {
+        return getStringValue(STATIC_PORT);
+    }
+
+    private String getStringValue(String field) {
+        JsonNode name = object.path(field);
+        return name.isMissingNode() ? "" : name.asText();
+    }
+
+    /**
+     * Returns the output lambda configured for this port. The lambda value is
+     * expressed as a frequency value. If the port type doesn't have a notion of
+     * lambdas, this returns an empty Optional.
+     *
+     * @return an Optional that may contain a frequency value.
+     */
+    public Optional<Long> staticLambda() {
+        JsonNode sl = object.path(STATIC_LAMBDA);
+        if (sl.isMissingNode()) {
+            return Optional.empty();
+        }
+        return Optional.of(sl.asLong());
+    }
+
+    /**
+     * Returns the port speed configured for this port. If the port doesn't have
+     * a notion of speed, this returns an empty Optional.
+     *
+     * @return a port speed value whose default is 0.
+     */
+    public Optional<Integer> speed() {
+        JsonNode s = object.path(SPEED);
+        if (s.isMissingNode()) {
+            return Optional.empty();
+        }
+        return Optional.of(s.asInt());
+    }
+
+    /**
+     * Sets the port type, or updates it if it's already set. A null argument removes
+     * this field.
+     *
+     * @param type the port type
+     * @return this OpticalPortConfig instance
+     */
+    public OpticalPortConfig portType(Port.Type type) {
+        // if unspecified, ideally fall back on FIBER or PACKET.
+        String pt = (type == null) ? null : type.toString();
+        return (OpticalPortConfig) setOrClear(TYPE, pt);
+    }
+
+    /**
+     * Sets the port name, or updates it if already set. A null argument removes
+     * this field.
+     *
+     * @param name the port's name
+     * @return this OpticalPortConfig instance
+     */
+    public OpticalPortConfig portName(String name) {
+        return (OpticalPortConfig) setOrClear(NAME, name);
+    }
+
+    /**
+     * Sets the port name from port number, or updates it if already set. A null
+     * argument removes this field.
+     *
+     * @param name the port number, to be used as name
+     * @return this OpticalPortConfig instance
+     */
+    public OpticalPortConfig portNumberName(Long name) {
+        return (OpticalPortConfig) setOrClear(PORT, name);
+    }
+
+    /**
+     * Sets the output port name, or updates it if already set. A null argument
+     * removes this field.
+     *
+     * @param name the output port's name
+     * @return this OpticalPortConfig instance
+     */
+    public OpticalPortConfig staticPort(String name) {
+        return (OpticalPortConfig) setOrClear(STATIC_PORT, name);
+    }
+
+    /**
+     * Sets the output lambda index, or updates it if already set. A null argument
+     * removes this field.
+     *
+     * @param index the output lambda
+     * @return this OpticalPortConfig instance
+     */
+    public OpticalPortConfig staticLambda(Long index) {
+        return (OpticalPortConfig) setOrClear(STATIC_LAMBDA, index);
+    }
+
+    /**
+     * Sets the port speed, or updates it if already set. A null argument
+     * removes this field.
+     *
+     * @param bw the port bandwidth
+     * @return this OpticalPortConfig instance
+     */
+    public OpticalPortConfig speed(Integer bw) {
+        return (OpticalPortConfig) setOrClear(SPEED, bw);
+    }
+}
diff --git a/apps/optical-model/src/main/java/org/onosproject/net/optical/config/OpticalPortOperator.java b/apps/optical-model/src/main/java/org/onosproject/net/optical/config/OpticalPortOperator.java
new file mode 100644
index 0000000..f6dc912
--- /dev/null
+++ b/apps/optical-model/src/main/java/org/onosproject/net/optical/config/OpticalPortOperator.java
@@ -0,0 +1,212 @@
+/*
+ * 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.
+ */
+package org.onosproject.net.optical.config;
+
+import static org.onosproject.net.optical.device.OchPortHelper.ochPortDescription;
+import static org.onosproject.net.optical.device.OduCltPortHelper.oduCltPortDescription;
+import static org.onosproject.net.optical.device.OmsPortHelper.omsPortDescription;
+import static org.onosproject.net.optical.device.OtuPortHelper.otuPortDescription;
+import static org.slf4j.LoggerFactory.getLogger;
+
+import java.util.Set;
+
+import static com.google.common.base.MoreObjects.firstNonNull;
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import org.onosproject.net.config.NetworkConfigService;
+import org.onosproject.net.config.PortConfigOperator;
+import org.onosproject.net.AnnotationKeys;
+import org.onosproject.net.ConnectPoint;
+import org.onosproject.net.DefaultAnnotations;
+import org.onosproject.net.Port;
+import org.onosproject.net.Port.Type;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.SparseAnnotations;
+import org.onosproject.net.device.DefaultPortDescription;
+import org.onosproject.net.device.OchPortDescription;
+import org.onosproject.net.device.OduCltPortDescription;
+import org.onosproject.net.device.OmsPortDescription;
+import org.onosproject.net.device.OtuPortDescription;
+import org.onosproject.net.device.PortDescription;
+import org.slf4j.Logger;
+
+import com.google.common.collect.Sets;
+
+/**
+ * Implementations of merge policies for various sources of optical port
+ * configuration information. This includes applications, provides, and network
+ * configurations.
+ */
+public final class OpticalPortOperator implements PortConfigOperator {
+
+    private static final Logger log = getLogger(OpticalPortOperator.class);
+
+    /**
+     * Port.Type this PortConfigOperator reacts on.
+     */
+    private final Set<Port.Type> optical = Sets.immutableEnumSet(Port.Type.ODUCLT,
+                                                                 Port.Type.OMS,
+                                                                 Port.Type.OCH,
+                                                                 Port.Type.OTU,
+                                                                 Port.Type.FIBER,
+                                                                 Port.Type.PACKET);
+
+    private NetworkConfigService networkConfigService;
+
+
+    public OpticalPortOperator() {
+    }
+
+    @Override
+    public void bindService(NetworkConfigService networkConfigService) {
+        this.networkConfigService = networkConfigService;
+    }
+
+    private OpticalPortConfig lookupConfig(ConnectPoint cp) {
+        if (networkConfigService == null) {
+            return null;
+        }
+        return networkConfigService.getConfig(cp, OpticalPortConfig.class);
+    }
+
+    /**
+     * Generates a PortDescription containing fields from a PortDescription and
+     * an OpticalPortConfig.
+     *
+     * @param cp {@link ConnectPoint} representing the port.
+     * @param descr input {@link PortDescription}
+     * @return Combined {@link PortDescription}
+     */
+    @Override
+    public PortDescription combine(ConnectPoint cp, PortDescription descr) {
+        checkNotNull(cp);
+
+        // short-circuit for non-optical ports
+        // must be removed if we need type override
+        if (descr != null && !optical.contains(descr.type())) {
+            return descr;
+        }
+
+        OpticalPortConfig opc = lookupConfig(cp);
+        if (opc == null) {
+            return descr;
+        }
+
+        PortNumber number = descr.portNumber();
+        // handle PortNumber "name" portion
+        if (!opc.name().isEmpty()) {
+            number = PortNumber.portNumber(descr.portNumber().toLong(), opc.name());
+        }
+
+        // handle additional annotations
+        SparseAnnotations annotations = combine(opc, descr.annotations());
+
+        // (Future work) handle type overwrite?
+        Type type = firstNonNull(opc.type(), descr.type());
+        if (type != descr.type()) {
+            // TODO: Do we need to be able to overwrite Port.Type?
+            log.warn("Port type overwrite requested for {}. Ignoring.", cp);
+        }
+
+        return updateDescription(number, annotations, descr);
+    }
+
+    // updates a port description whose port type has not changed.
+    /**
+     * Updates {@link PortDescription} using specified number and annotations.
+     *
+     * @param port {@link PortNumber} to use in updated description
+     * @param sa   annotations to use in updated description
+     * @param descr base {@link PortDescription}
+     * @return updated {@link PortDescription}
+     */
+    private static PortDescription updateDescription(PortNumber port,
+                                                     SparseAnnotations sa,
+                                                     PortDescription descr) {
+
+        // TODO This switch can go away once deprecation is complete.
+        switch (descr.type()) {
+            case OMS:
+                if (descr instanceof OmsPortDescription) {
+                    OmsPortDescription oms = (OmsPortDescription) descr;
+                    return omsPortDescription(port, oms.isEnabled(), oms.minFrequency(),
+                                                  oms.maxFrequency(), oms.grid(), sa);
+                }
+                break;
+            case OCH:
+                // We might need to update lambda below with STATIC_LAMBDA.
+                if (descr instanceof OchPortDescription) {
+                    OchPortDescription och = (OchPortDescription) descr;
+                    return ochPortDescription(port, och.isEnabled(), och.signalType(),
+                            och.isTunable(), och.lambda(), sa);
+                }
+                break;
+            case ODUCLT:
+                if (descr instanceof OduCltPortDescription) {
+                    OduCltPortDescription odu = (OduCltPortDescription) descr;
+                    return oduCltPortDescription(port, odu.isEnabled(), odu.signalType(), sa);
+                }
+                break;
+            case PACKET:
+            case FIBER:
+            case COPPER:
+                break;
+            case OTU:
+                if (descr instanceof OtuPortDescription) {
+                    OtuPortDescription otu = (OtuPortDescription) descr;
+                    return otuPortDescription(port, otu.isEnabled(), otu.signalType(), sa);
+                }
+                break;
+            default:
+                log.warn("Unsupported optical port type {} - can't update", descr.type());
+                return descr;
+        }
+        if (port.exactlyEquals(descr.portNumber()) && sa.equals(descr.annotations())) {
+            // result is no-op
+            return descr;
+        }
+        return new DefaultPortDescription(port,
+                                          descr.isEnabled(),
+                                          descr.type(),
+                                          descr.portSpeed(),
+                                          sa);
+    }
+
+    /**
+     * Generates an annotation from an existing annotation and OptcalPortConfig.
+     *
+     * @param opc the port config entity from network config
+     * @param an the annotation
+     * @return annotation combining both sources
+     */
+    private static SparseAnnotations combine(OpticalPortConfig opc, SparseAnnotations an) {
+        DefaultAnnotations.Builder b = DefaultAnnotations.builder();
+        b.putAll(an);
+        if (!opc.staticPort().isEmpty()) {
+            b.set(AnnotationKeys.STATIC_PORT, opc.staticPort());
+        }
+        if (opc.staticLambda().isPresent()) {
+            b.set(AnnotationKeys.STATIC_LAMBDA, String.valueOf(opc.staticLambda().get()));
+        }
+        // The following may not need to be carried.
+        if (!opc.name().isEmpty()) {
+            b.set(AnnotationKeys.PORT_NAME, opc.name());
+        }
+        return b.build();
+    }
+
+
+}
diff --git a/apps/optical-model/src/main/java/org/onosproject/net/optical/config/package-info.java b/apps/optical-model/src/main/java/org/onosproject/net/optical/config/package-info.java
new file mode 100644
index 0000000..2deb1f7
--- /dev/null
+++ b/apps/optical-model/src/main/java/org/onosproject/net/optical/config/package-info.java
@@ -0,0 +1,19 @@
+/*
+ * 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.
+ */
+/**
+ * Various optical model related configurations.
+ */
+package org.onosproject.net.optical.config;
diff --git a/apps/optical-model/src/main/java/org/onosproject/net/optical/internal/OpticalModelLoader.java b/apps/optical-model/src/main/java/org/onosproject/net/optical/internal/OpticalModelLoader.java
new file mode 100644
index 0000000..494fc24
--- /dev/null
+++ b/apps/optical-model/src/main/java/org/onosproject/net/optical/internal/OpticalModelLoader.java
@@ -0,0 +1,79 @@
+/*
+ * 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.net.optical.internal;
+
+import static org.onosproject.net.config.basics.SubjectFactories.CONNECT_POINT_SUBJECT_FACTORY;
+
+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.Reference;
+import org.apache.felix.scr.annotations.ReferenceCardinality;
+import org.onosproject.net.ConnectPoint;
+import org.onosproject.net.config.ConfigFactory;
+import org.onosproject.net.config.NetworkConfigRegistry;
+import org.onosproject.net.config.PortConfigOperatorRegistry;
+import org.onosproject.net.optical.config.OpticalPortConfig;
+import org.onosproject.net.optical.config.OpticalPortOperator;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Loader which registers optical model related config, etc.
+ */
+@Component(immediate = true)
+public class OpticalModelLoader {
+
+    private final Logger log = LoggerFactory.getLogger(getClass());
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected PortConfigOperatorRegistry portOperatorRegistry;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected NetworkConfigRegistry netcfgRegistry;
+
+
+    private OpticalPortOperator opticalPortOp;
+
+    private ConfigFactory<ConnectPoint, OpticalPortConfig>
+        opticalPortConfigFactory = new ConfigFactory<ConnectPoint, OpticalPortConfig>(CONNECT_POINT_SUBJECT_FACTORY,
+                                                       OpticalPortConfig.class,
+                                                       "optical") {
+        @Override
+        public OpticalPortConfig createConfig() {
+            return new OpticalPortConfig();
+        }
+    };
+
+    @Activate
+    protected void activate() {
+        netcfgRegistry.registerConfigFactory(opticalPortConfigFactory);
+
+        opticalPortOp = new OpticalPortOperator();
+        portOperatorRegistry.registerPortConfigOperator(opticalPortOp,
+                                                        OpticalPortConfig.class);
+
+        log.info("Started");
+    }
+
+    @Deactivate
+    protected void deactivate() {
+        portOperatorRegistry.unregisterPortConfigOperator(opticalPortOp);
+
+        netcfgRegistry.unregisterConfigFactory(opticalPortConfigFactory);
+        log.info("Stopped");
+    }
+}
diff --git a/apps/optical-model/src/main/java/org/onosproject/net/optical/internal/package-info.java b/apps/optical-model/src/main/java/org/onosproject/net/optical/internal/package-info.java
new file mode 100644
index 0000000..8707ad5
--- /dev/null
+++ b/apps/optical-model/src/main/java/org/onosproject/net/optical/internal/package-info.java
@@ -0,0 +1,19 @@
+/*
+ * 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.
+ */
+/**
+ * Internal tools for optical model.
+ */
+package org.onosproject.net.optical.internal;