[ONOS-4170] LSP-DB sync

Change-Id: Icda3afd9cca8d1fb8c58b44da6bc26064b300388
diff --git a/protocols/pcep/api/BUCK b/protocols/pcep/api/BUCK
index 8930a95..5ced968 100644
--- a/protocols/pcep/api/BUCK
+++ b/protocols/pcep/api/BUCK
@@ -2,6 +2,7 @@
     '//lib:CORE_DEPS',
     '//protocols/pcep/pcepio:onos-protocols-pcep-pcepio',
     '//apps/pcep-api:onos-apps-pcep-api',
+    '//incubator/api:onos-incubator-api',
 ]
 
 osgi_jar_with_tests (
diff --git a/protocols/pcep/api/pom.xml b/protocols/pcep/api/pom.xml
index f334654..f514985 100644
--- a/protocols/pcep/api/pom.xml
+++ b/protocols/pcep/api/pom.xml
@@ -52,5 +52,9 @@
             <groupId>org.onosproject</groupId>
             <artifactId>onlab-misc</artifactId>
         </dependency>
+        <dependency>
+            <groupId>org.onosproject</groupId>
+            <artifactId>onos-incubator-api</artifactId>
+        </dependency>
     </dependencies>
 </project>
diff --git a/protocols/pcep/api/src/main/java/org/onosproject/pcep/controller/PcepClient.java b/protocols/pcep/api/src/main/java/org/onosproject/pcep/controller/PcepClient.java
index 297d71e..c5cf003 100644
--- a/protocols/pcep/api/src/main/java/org/onosproject/pcep/controller/PcepClient.java
+++ b/protocols/pcep/api/src/main/java/org/onosproject/pcep/controller/PcepClient.java
@@ -19,6 +19,7 @@
 
 import org.onosproject.pcepio.protocol.PcepFactory;
 import org.onosproject.pcepio.protocol.PcepMessage;
+import org.onosproject.pcepio.protocol.PcepStateReport;
 
 /**
  * Represents to provider facing side of a path computation client(pcc).
@@ -165,4 +166,34 @@
      * @return delegation flag
      */
     Boolean delegationInfo(LspKey lspKey);
+
+    /**
+     * Creates a temporary cache to hold report messages received during LSPDB sync.
+     *
+     * @param pccId PCC id which is the key to store report messages
+     */
+    void initializeSyncMsgList(PccId pccId);
+
+    /**
+     * Returns the list of report messages received during LSPDB sync.
+     *
+     * @param pccId PCC id which is the key for all the report messages
+     * @return list of report messages received during LSPDB sync
+     */
+    List<PcepStateReport> getSyncMsgList(PccId pccId);
+
+    /**
+     * Removes the list of report messages received during LSPDB sync.
+     *
+     * @param pccId PCC id which is the key for all the report messages
+     */
+    void removeSyncMsgList(PccId pccId);
+
+    /**
+     * Adds report message received during LSPDB sync into temporary cache.
+     *
+     * @param pccId PCC id which is the key to store report messages
+     * @param rptMsg the report message to be stored
+     */
+    void addSyncMsgToList(PccId pccId, PcepStateReport rptMsg);
 }
diff --git a/protocols/pcep/api/src/main/java/org/onosproject/pcep/controller/PcepClientController.java b/protocols/pcep/api/src/main/java/org/onosproject/pcep/controller/PcepClientController.java
index fff6759..0f14778 100644
--- a/protocols/pcep/api/src/main/java/org/onosproject/pcep/controller/PcepClientController.java
+++ b/protocols/pcep/api/src/main/java/org/onosproject/pcep/controller/PcepClientController.java
@@ -85,6 +85,20 @@
     void removeNodeListener(PcepNodeListener listener);
 
     /**
+     * Register a listener for packet events.
+     *
+     * @param listener the listener to notify
+     */
+    void addPacketListener(PcepPacketListener listener);
+
+    /**
+     * Unregister a packet listener.
+     *
+     * @param listener the listener to unregister
+     */
+    void removePacketListener(PcepPacketListener listener);
+
+    /**
      * Send a message to a particular pcc client.
      *
      * @param pccId the id of the client to send message.
diff --git a/protocols/pcep/api/src/main/java/org/onosproject/pcep/controller/PcepEventListener.java b/protocols/pcep/api/src/main/java/org/onosproject/pcep/controller/PcepEventListener.java
index 7ba8ca7..c7c347a 100644
--- a/protocols/pcep/api/src/main/java/org/onosproject/pcep/controller/PcepEventListener.java
+++ b/protocols/pcep/api/src/main/java/org/onosproject/pcep/controller/PcepEventListener.java
@@ -15,6 +15,7 @@
  */
 package org.onosproject.pcep.controller;
 
+import org.onosproject.incubator.net.tunnel.Tunnel;
 import org.onosproject.pcepio.protocol.PcepMessage;
 /**
  * Notifies providers about PCEP message events.
@@ -28,4 +29,21 @@
      * @param msg the message
      */
     void handleMessage(PccId pccId, PcepMessage msg);
+
+    /**
+     * Handles end of LSPDB sync actions.
+     *
+     * @param tunnel the tunnel on which action needs to be taken
+     * @param endOfSyncAction the action that needs to be taken for the tunnel
+     */
+    void handleEndOfSyncAction(Tunnel tunnel, PcepLspSyncAction endOfSyncAction);
+
+    /**
+     * Handles sending PCEP message to client on end of LSPDB sync.
+     *
+     * @param pccId id of the pcc
+     * @param msg the message to be sent
+     * @param endOfSyncAction the action that needs to be taken in the message
+     */
+    void handleEndOfSyncAction(PccId pccId, PcepMessage msg, PcepLspSyncAction endOfSyncAction);
 }
diff --git a/protocols/pcep/api/src/main/java/org/onosproject/pcep/controller/PcepLspSyncAction.java b/protocols/pcep/api/src/main/java/org/onosproject/pcep/controller/PcepLspSyncAction.java
new file mode 100644
index 0000000..92ce8e6
--- /dev/null
+++ b/protocols/pcep/api/src/main/java/org/onosproject/pcep/controller/PcepLspSyncAction.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.pcep.controller;
+
+/**
+ * Representation of actions to be taken for LSPs on end of LSP-DB sync.
+ */
+public enum PcepLspSyncAction {
+
+    /**
+     * Specifies that delete message for PCE intiiated tunnel should be sent.
+     */
+    SEND_DELETE(0),
+
+    /**
+     * Specifies that update message should be sent.
+     */
+    SEND_UPDATE(1),
+
+    /**
+     * Specifies that the tunnel should be removed from PCE.
+     */
+    REMOVE(2),
+
+    /**
+     * Specifies that the status of the tunnel should be set as unstable.
+     */
+    UNSTABLE(3);
+
+    int value;
+
+    /**
+     * Assigns val with the value for actions to be taken for LSPs on end of LSP-DB sync.
+     *
+     * @param val sync status
+     */
+    PcepLspSyncAction(int val) {
+        value = val;
+    }
+}
diff --git a/protocols/pcep/api/src/main/java/org/onosproject/pcep/controller/PcepPacketListener.java b/protocols/pcep/api/src/main/java/org/onosproject/pcep/controller/PcepPacketListener.java
new file mode 100644
index 0000000..c2017ae
--- /dev/null
+++ b/protocols/pcep/api/src/main/java/org/onosproject/pcep/controller/PcepPacketListener.java
@@ -0,0 +1,22 @@
+/*
+ * 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.pcep.controller;
+
+public interface PcepPacketListener {
+
+    void sendPacketIn(PccId pccId);
+
+}
diff --git a/protocols/pcep/api/src/main/java/org/onosproject/pcep/controller/driver/PcepAgent.java b/protocols/pcep/api/src/main/java/org/onosproject/pcep/controller/driver/PcepAgent.java
index de95962..55d5614 100755
--- a/protocols/pcep/api/src/main/java/org/onosproject/pcep/controller/driver/PcepAgent.java
+++ b/protocols/pcep/api/src/main/java/org/onosproject/pcep/controller/driver/PcepAgent.java
@@ -73,4 +73,12 @@
      * @param pccId PCEP client ID
      */
     void deleteNode(PccId pccId);
+
+    /**
+     * Analyzes report messages received during LSP DB sync again tunnel store and takes necessary actions.
+     *
+     * @param pccId the id of pcc client
+     * @return success or failure
+     */
+    boolean analyzeSyncMsgList(PccId pccId);
 }
diff --git a/protocols/pcep/ctl/BUCK b/protocols/pcep/ctl/BUCK
index dd7e29c..ae62881 100644
--- a/protocols/pcep/ctl/BUCK
+++ b/protocols/pcep/ctl/BUCK
@@ -2,6 +2,7 @@
     '//lib:CORE_DEPS',
     '//protocols/pcep/pcepio:onos-protocols-pcep-pcepio',
     '//protocols/pcep/api:onos-protocols-pcep-api',
+    '//incubator/api:onos-incubator-api',
 ]
 
 osgi_jar_with_tests (
diff --git a/protocols/pcep/ctl/src/main/java/org/onosproject/pcep/controller/impl/PcepClientControllerImpl.java b/protocols/pcep/ctl/src/main/java/org/onosproject/pcep/controller/impl/PcepClientControllerImpl.java
index 19e2ce4..20c2856 100644
--- a/protocols/pcep/ctl/src/main/java/org/onosproject/pcep/controller/impl/PcepClientControllerImpl.java
+++ b/protocols/pcep/ctl/src/main/java/org/onosproject/pcep/controller/impl/PcepClientControllerImpl.java
@@ -15,10 +15,16 @@
  */
 package org.onosproject.pcep.controller.impl;
 
+import java.util.Arrays;
 import java.util.Collection;
 import java.util.Collections;
+import java.util.HashMap;
 import java.util.HashSet;
+import java.util.Iterator;
 import java.util.LinkedList;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
 
@@ -28,25 +34,47 @@
 import org.apache.felix.scr.annotations.Reference;
 import org.apache.felix.scr.annotations.ReferenceCardinality;
 import org.apache.felix.scr.annotations.Service;
+import org.onosproject.incubator.net.tunnel.IpTunnelEndPoint;
+import org.onosproject.incubator.net.tunnel.Tunnel;
+import org.onosproject.incubator.net.tunnel.TunnelService;
+import org.onosproject.incubator.net.tunnel.Tunnel.State;
 import org.onosproject.net.device.DeviceService;
+import org.onosproject.pcep.controller.LspKey;
 import org.onosproject.pcep.controller.PccId;
 import org.onosproject.pcep.controller.PcepClient;
 import org.onosproject.pcep.controller.PcepClientController;
 import org.onosproject.pcep.controller.PcepClientListener;
 import org.onosproject.pcep.controller.PcepEventListener;
 import org.onosproject.pcep.controller.PcepNodeListener;
+import org.onosproject.pcep.controller.PcepPacketListener;
+import org.onosproject.pcep.controller.PcepSyncStatus;
 import org.onosproject.pcep.controller.driver.PcepAgent;
+import org.onosproject.pcepio.exceptions.PcepParseException;
+import org.onosproject.pcepio.protocol.PcInitiatedLspRequest;
 import org.onosproject.pcepio.protocol.PcepError;
 import org.onosproject.pcepio.protocol.PcepErrorInfo;
 import org.onosproject.pcepio.protocol.PcepErrorMsg;
 import org.onosproject.pcepio.protocol.PcepErrorObject;
 import org.onosproject.pcepio.protocol.PcepFactory;
+import org.onosproject.pcepio.protocol.PcepInitiateMsg;
+import org.onosproject.pcepio.protocol.PcepLspObject;
 import org.onosproject.pcepio.protocol.PcepMessage;
+import org.onosproject.pcepio.protocol.PcepReportMsg;
+import org.onosproject.pcepio.protocol.PcepStateReport;
+import org.onosproject.pcepio.types.PcepValueType;
+import org.onosproject.pcepio.types.StatefulIPv4LspIdentifiersTlv;
+import org.onosproject.pcepio.types.SymbolicPathNameTlv;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import com.google.common.collect.Sets;
+import static com.google.common.base.Preconditions.checkNotNull;
 
+import static org.onosproject.pcep.controller.PcepSyncStatus.IN_SYNC;
+import static org.onosproject.pcep.controller.PcepLspSyncAction.REMOVE;
+import static org.onosproject.pcep.controller.PcepLspSyncAction.SEND_UPDATE;
+import static org.onosproject.pcep.controller.PcepLspSyncAction.SEND_DELETE;
+import static org.onosproject.pcep.controller.PcepLspSyncAction.UNSTABLE;
 import static org.onosproject.pcepio.types.PcepErrorDetailInfo.ERROR_TYPE_19;
 import static org.onosproject.pcepio.types.PcepErrorDetailInfo.ERROR_VALUE_5;
 
@@ -70,9 +98,22 @@
 
     protected Set<PcepEventListener> pcepEventListener = Sets.newHashSet();
     protected Set<PcepNodeListener> pcepNodeListener = Sets.newHashSet();
+    protected Set<PcepPacketListener> pcepPacketListener = Sets.newHashSet();
 
     private final Controller ctrl = new Controller();
 
+    public static final String BANDWIDTH = "bandwidth";
+    public static final String LSP_SIG_TYPE = "lspSigType";
+    public static final String PCC_TUNNEL_ID = "PccTunnelId";
+    public static final String PLSP_ID = "PLspId";
+    public static final String LOCAL_LSP_ID = "localLspId";
+    public static final String PCE_INIT = "pceInit";
+    public static final String COST_TYPE = "costType";
+    public static final String DELEGATE = "delegation";
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected TunnelService tunnelService;
+
     @Activate
     public void activate() {
         ctrl.start(agent);
@@ -120,6 +161,16 @@
     }
 
     @Override
+    public void addPacketListener(PcepPacketListener listener) {
+        pcepPacketListener.add(listener);
+    }
+
+    @Override
+    public void removePacketListener(PcepPacketListener listener) {
+        pcepPacketListener.remove(listener);
+    }
+
+    @Override
     public void writeMessage(PccId pccId, PcepMessage msg) {
         this.getClient(pccId).sendMessage(msg);
     }
@@ -180,8 +231,48 @@
         case REPORT:
             //Only update the listener if respective capability is supported else send PCEP-ERR msg
             if (pc.capability().statefulPceCapability()) {
-                for (PcepEventListener l : pcepEventListener) {
-                    l.handleMessage(pccId, msg);
+
+                ListIterator<PcepStateReport> listIterator = ((PcepReportMsg) msg).getStateReportList().listIterator();
+                while (listIterator.hasNext()) {
+                    PcepStateReport stateRpt = listIterator.next();
+                    if (stateRpt.getLspObject().getSFlag()) {
+                        if (pc.lspDbSyncStatus() != PcepSyncStatus.IN_SYNC) {
+                            // Initialize LSP DB sync and temporary cache.
+                            pc.setLspDbSyncStatus(PcepSyncStatus.IN_SYNC);
+                            pc.initializeSyncMsgList(pccId);
+                        }
+                        // Store stateRpt in temporary cache.
+                        pc.addSyncMsgToList(pccId, stateRpt);
+
+                        // Don't send to provider as of now.
+                        continue;
+                    } else {
+                        if (pc.lspDbSyncStatus() == PcepSyncStatus.IN_SYNC) {
+                            // Set end of LSPDB sync.
+                            pc.setLspDbSyncStatus(PcepSyncStatus.SYNCED);
+
+                            // Call packet provider to initiate label DB sync (only if PCECC capable).
+                            if (pc.capability().pceccCapability()) {
+                                pc.setLabelDbSyncStatus(IN_SYNC);
+                                for (PcepPacketListener l : pcepPacketListener) {
+                                    l.sendPacketIn(pccId);
+                                }
+                            } else {
+                                // If label db sync is not to be done, handle end of LSPDB sync actions.
+                                agent.analyzeSyncMsgList(pccId);
+                            }
+                            continue;
+                        }
+                    }
+
+                    // It's a usual report message while sync is not undergoing. So process it immediately.
+                    LinkedList<PcepStateReport> llPcRptList = new LinkedList<>();
+                    llPcRptList.add(stateRpt);
+                    PcepMessage pcReportMsg = pc.factory().buildReportMsg().setStateReportList((llPcRptList))
+                            .build();
+                    for (PcepEventListener l : pcepEventListener) {
+                        l.handleMessage(pccId, pcReportMsg);
+                    }
                 }
             } else {
                 // Send PCEP-ERROR message.
@@ -304,5 +395,162 @@
                 l.deleteNode(pccId);
             }
         }
+
+        @SuppressWarnings({ "unchecked", "rawtypes" })
+        @Override
+        public boolean analyzeSyncMsgList(PccId pccId) {
+            PcepClient pc = getClient(pccId);
+            /*
+             * PLSP_ID is null while tunnel is created at PCE and PCInit msg carries it as 0. It is allocated by PCC and
+             * in that case it becomes the first PCRpt msg from PCC for this LSP, and hence symbolic path name must be
+             * carried in the PCRpt msg. Draft says: The SYMBOLIC-PATH-NAME TLV "MUST" be included in the LSP object in
+             * the LSP State Report (PCRpt) message when during a given PCEP session an LSP is "first" reported to a
+             * PCE. So two separate lists with separate keys are maintained.
+             */
+            Map<LspKey, Tunnel> preSyncLspDbByKey = new HashMap<>();
+            Map<String, Tunnel> preSyncLspDbByName = new HashMap<>();
+
+            // Query tunnel service and fetch all the tunnels with this PCC as ingress.
+            // Organize into two maps, with LSP key if known otherwise with symbolic path name, for quick search.
+            Collection<Tunnel> queriedTunnels = tunnelService.queryTunnel(Tunnel.Type.MPLS);
+            for (Tunnel tunnel : queriedTunnels) {
+                if (((IpTunnelEndPoint) tunnel.src()).ip().equals(pccId.ipAddress())) {
+                    String pLspId = tunnel.annotations().value(PLSP_ID);
+                    if (pLspId != null) {
+                        String localLspId = tunnel.annotations().value(LOCAL_LSP_ID);
+                        checkNotNull(localLspId);
+                        LspKey lspKey = new LspKey(Integer.valueOf(pLspId), Short.valueOf(localLspId));
+                        preSyncLspDbByKey.put(lspKey, tunnel);
+                    } else {
+                        preSyncLspDbByName.put(tunnel.tunnelName().value(), tunnel);
+                    }
+                }
+            }
+
+            List<PcepStateReport> syncStateRptList = pc.getSyncMsgList(pccId);
+            Iterator<PcepStateReport> stateRptListIterator = syncStateRptList.iterator();
+
+            // For every report, fetch PLSP id, local LSP id and symbolic path name from the message.
+            while (syncStateRptList.iterator().hasNext()) {
+                PcepStateReport stateRpt = stateRptListIterator.next();
+                Tunnel tunnel = null;
+
+                PcepLspObject lspObj = stateRpt.getLspObject();
+                ListIterator<PcepValueType> listTlvIterator = lspObj.getOptionalTlv().listIterator();
+                StatefulIPv4LspIdentifiersTlv ipv4LspIdenTlv = null;
+                SymbolicPathNameTlv pathNameTlv = null;
+
+                while (listTlvIterator.hasNext()) {
+                    PcepValueType tlv = listTlvIterator.next();
+                    switch (tlv.getType()) {
+                    case StatefulIPv4LspIdentifiersTlv.TYPE:
+                        ipv4LspIdenTlv = (StatefulIPv4LspIdentifiersTlv) tlv;
+                        break;
+
+                    case SymbolicPathNameTlv.TYPE:
+                        pathNameTlv = (SymbolicPathNameTlv) tlv;
+                        break;
+
+                    default:
+                        break;
+                    }
+                }
+
+                LspKey lspKeyOfRpt = new LspKey(lspObj.getPlspId(), ipv4LspIdenTlv.getLspId());
+                tunnel = preSyncLspDbByKey.get(lspKeyOfRpt);
+                // PCE tunnel is matched with PCRpt LSP. Now delete it from the preSyncLspDb list as the residual
+                // non-matching list will be processed at the end.
+                if (tunnel != null) {
+                    preSyncLspDbByKey.remove(lspKeyOfRpt);
+                } else if (pathNameTlv != null) {
+                    tunnel = preSyncLspDbByName.get(Arrays.toString(pathNameTlv.getValue()));
+                    if (tunnel != null) {
+                        preSyncLspDbByName.remove(tunnel.tunnelName());
+                    }
+                }
+
+                if (tunnel == null) {
+                    // If remove flag is set, and tunnel is not known to PCE, ignore it.
+                    if (lspObj.getCFlag() && !lspObj.getRFlag()) {
+                        // For initiated LSP, need to send PCInit delete msg.
+                        try {
+                            PcInitiatedLspRequest releaseLspRequest = pc.factory().buildPcInitiatedLspRequest()
+                                    .setLspObject(lspObj).build();
+                            LinkedList<PcInitiatedLspRequest> llPcInitiatedLspRequestList
+                                    = new LinkedList<PcInitiatedLspRequest>();
+                            llPcInitiatedLspRequestList.add(releaseLspRequest);
+
+                            PcepInitiateMsg pcInitiateMsg = pc.factory().buildPcepInitiateMsg()
+                                    .setPcInitiatedLspRequestList(llPcInitiatedLspRequestList).build();
+
+                            for (PcepEventListener l : pcepEventListener) {
+                                l.handleEndOfSyncAction(pccId, pcInitiateMsg, SEND_DELETE);
+                            }
+
+                        } catch (PcepParseException e) {
+                            log.error("Exception occured while sending initiate delete message {}", e.getMessage());
+                        }
+                    }
+                    continue;
+                }
+
+                if (!lspObj.getCFlag()) {
+                    // For learned LSP process both add/update PCRpt.
+                    LinkedList<PcepStateReport> llPcRptList = new LinkedList<>();
+                    llPcRptList.add(stateRpt);
+                    PcepMessage pcReportMsg = pc.factory().buildReportMsg().setStateReportList((llPcRptList))
+                            .build();
+
+                    for (PcepEventListener l : pcepEventListener) {
+                        l.handleMessage(pccId, pcReportMsg);
+                    }
+                    continue;
+                }
+
+                // Implied that tunnel != null and lspObj.getCFlag() is set
+                // State different for PCC sent LSP and PCE known LSP, send PCUpd msg.
+                State tunnelState = PcepLspStatus
+                        .getTunnelStatusFromLspStatus(PcepLspStatus.values()[lspObj.getOFlag()]);
+                if (tunnelState != tunnel.state()) {
+                    for (PcepEventListener l : pcepEventListener) {
+                        l.handleEndOfSyncAction(tunnel, SEND_UPDATE);
+                    }
+                }
+            }
+
+            // Check which tunnels are extra at PCE that were not reported by PCC.
+            Map<Object, Tunnel> preSyncLspDb = (Map) preSyncLspDbByKey;
+            handleResidualTunnels(preSyncLspDb);
+            preSyncLspDbByKey = null;
+
+            preSyncLspDb = (Map) preSyncLspDbByName;
+            handleResidualTunnels(preSyncLspDb);
+            preSyncLspDbByName = null;
+            preSyncLspDb = null;
+
+            pc.removeSyncMsgList(pccId);
+            return true;
+        }
+
+        /*
+         * Go through the tunnels which are known by PCE but were not reported by PCC during LSP DB sync and take
+         * appropriate actions.
+         */
+        private void handleResidualTunnels(Map<Object, Tunnel> preSyncLspDb) {
+            for (Tunnel pceExtraTunnel : preSyncLspDb.values()) {
+                if (pceExtraTunnel.annotations().value(PCE_INIT) == null
+                        || "false".equalsIgnoreCase(pceExtraTunnel.annotations().value(PCE_INIT))) {
+                    // PCC initiated tunnels should be removed from tunnel store.
+                    for (PcepEventListener l : pcepEventListener) {
+                        l.handleEndOfSyncAction(pceExtraTunnel, REMOVE);
+                    }
+                } else {
+                    // PCE initiated tunnels should be initiated again.
+                    for (PcepEventListener l : pcepEventListener) {
+                        l.handleEndOfSyncAction(pceExtraTunnel, UNSTABLE);
+                    }
+                }
+            }
+        }
     }
 }
diff --git a/protocols/pcep/ctl/src/main/java/org/onosproject/pcep/controller/impl/PcepClientImpl.java b/protocols/pcep/ctl/src/main/java/org/onosproject/pcep/controller/impl/PcepClientImpl.java
index ac51371..a62a611 100644
--- a/protocols/pcep/ctl/src/main/java/org/onosproject/pcep/controller/impl/PcepClientImpl.java
+++ b/protocols/pcep/ctl/src/main/java/org/onosproject/pcep/controller/impl/PcepClientImpl.java
@@ -19,6 +19,8 @@
 import java.net.InetSocketAddress;
 import java.net.SocketAddress;
 import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
 import java.util.concurrent.RejectedExecutionException;
@@ -36,6 +38,7 @@
 import org.onosproject.pcepio.protocol.PcepFactories;
 import org.onosproject.pcepio.protocol.PcepFactory;
 import org.onosproject.pcepio.protocol.PcepMessage;
+import org.onosproject.pcepio.protocol.PcepStateReport;
 import org.onosproject.pcepio.protocol.PcepVersion;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -70,6 +73,7 @@
     private byte sessionId;
     private PcepPacketStatsImpl pktStats;
     private Map<LspKey, Boolean> lspDelegationInfo;
+    private Map<PccId, List<PcepStateReport>> sycRptCache = new HashMap<>();
 
     @Override
     public void init(PccId pccId, PcepVersion pcepVersion, PcepPacketStats pktStats) {
@@ -192,7 +196,14 @@
 
     @Override
     public void setLabelDbSyncStatus(PcepSyncStatus syncStatus) {
+
+        PcepSyncStatus syncOldStatus = labelDbSyncStatus();
         this.labelDbSyncStatus = syncStatus;
+
+        if ((syncOldStatus == PcepSyncStatus.IN_SYNC) && (syncStatus == PcepSyncStatus.SYNCED)) {
+            // Perform end of LSP DB sync actions.
+            this.agent.analyzeSyncMsgList(pccId);
+        }
     }
 
     @Override
@@ -254,6 +265,29 @@
     }
 
     @Override
+    public void initializeSyncMsgList(PccId pccId) {
+        List<PcepStateReport> rptMsgList = new LinkedList<>();
+        sycRptCache.put(pccId, rptMsgList);
+    }
+
+    @Override
+    public List<PcepStateReport> getSyncMsgList(PccId pccId) {
+        return sycRptCache.get(pccId);
+    }
+
+    @Override
+    public void removeSyncMsgList(PccId pccId) {
+        sycRptCache.remove(pccId);
+    }
+
+    @Override
+    public void addSyncMsgToList(PccId pccId, PcepStateReport rptMsg) {
+        List<PcepStateReport> rptMsgList = sycRptCache.get(pccId);
+        rptMsgList.add(rptMsg);
+        sycRptCache.put(pccId, rptMsgList);
+    }
+
+    @Override
     public boolean isOptical() {
         return false;
     }
diff --git a/protocols/pcep/ctl/src/main/java/org/onosproject/pcep/controller/impl/PcepLspStatus.java b/protocols/pcep/ctl/src/main/java/org/onosproject/pcep/controller/impl/PcepLspStatus.java
new file mode 100644
index 0000000..79ed9fe
--- /dev/null
+++ b/protocols/pcep/ctl/src/main/java/org/onosproject/pcep/controller/impl/PcepLspStatus.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.pcep.controller.impl;
+
+import org.onosproject.incubator.net.tunnel.Tunnel.State;
+
+/**
+ * Representation of the PCEP LSP state.
+ */
+public enum PcepLspStatus {
+
+    /**
+     * Signifies that the LSP is not active.
+     */
+    DOWN,
+
+    /**
+     * Signifies that the LSP is signalled.
+     */
+    UP,
+
+    /**
+     * Signifies that the LSP is up and carrying traffic.
+     */
+    ACTIVE,
+
+    /**
+     * Signifies that the LSP is being torn down, resources are being released.
+     */
+    GOING_DOWN,
+
+    /**
+     * Signifies that the LSP is being signalled.
+     */
+    GOING_UP;
+
+    /**
+     * Returns the applicable PCEP LSP status corresponding to ONOS tunnel state.
+     *
+     * @param tunnelState ONOS tunnel state
+     * @return LSP status as per protocol
+     */
+    public static PcepLspStatus getLspStatusFromTunnelStatus(State tunnelState) {
+
+        switch (tunnelState) {
+
+        case INIT:
+            return PcepLspStatus.DOWN;
+
+        case ESTABLISHED:
+            return PcepLspStatus.GOING_UP;
+
+        case ACTIVE:
+            return PcepLspStatus.UP;
+
+        case FAILED: // fall through
+        case INACTIVE: // LSP is administratively down.
+        default:
+            return PcepLspStatus.DOWN;
+        }
+    }
+
+    /**
+     * Returns the applicable ONOS tunnel state corresponding to PCEP LSP status.
+     *
+     * @param lspState PCEP LSP status
+     * @return tunnel state
+     */
+    public static State getTunnelStatusFromLspStatus(PcepLspStatus lspState) {
+
+        switch (lspState) {
+
+        case DOWN:
+            return State.FAILED;
+
+        case UP: // fall through
+        case ACTIVE:
+            return State.ACTIVE;
+
+        case GOING_DOWN:
+            return State.FAILED;
+
+        case GOING_UP:
+            return State.ESTABLISHED;
+
+        default:
+            return State.FAILED;
+        }
+    }
+}
diff --git a/protocols/pcep/pcepio/src/main/java/org/onosproject/pcepio/protocol/ver1/PcepMetricObjectVer1.java b/protocols/pcep/pcepio/src/main/java/org/onosproject/pcepio/protocol/ver1/PcepMetricObjectVer1.java
index 1ac1340..6e82ffd 100644
--- a/protocols/pcep/pcepio/src/main/java/org/onosproject/pcepio/protocol/ver1/PcepMetricObjectVer1.java
+++ b/protocols/pcep/pcepio/src/main/java/org/onosproject/pcepio/protocol/ver1/PcepMetricObjectVer1.java
@@ -57,6 +57,10 @@
     public static final int BFLAG_RESET = 0;
     public static final byte CFLAG_CHECK = 0x02;
 
+    public static final byte IGP_METRIC = 0x01;
+    public static final byte TE_METRIC = 0x02;
+    public static final byte HOP_COUNT_METRIC = 0x03;
+
     static final PcepObjectHeader DEFAULT_METRIC_OBJECT_HEADER = new PcepObjectHeader(METRIC_OBJ_CLASS,
             METRIC_OBJ_TYPE, PcepObjectHeader.REQ_OBJ_OPTIONAL_PROCESS, PcepObjectHeader.RSP_OBJ_PROCESSED,
             METRIC_OBJ_MINIMUM_LENGTH);