2dd33d1712c901e170169474b8444dd43c46d4d1
[bgpcep.git] / pcep / topology-provider / src / main / java / org / opendaylight / bgpcep / pcep / topology / provider / Stateful07TopologySessionListener.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.bgpcep.pcep.topology.provider;
9
10 import com.google.common.base.Function;
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.util.concurrent.AsyncFunction;
14 import com.google.common.util.concurrent.Futures;
15 import com.google.common.util.concurrent.ListenableFuture;
16 import java.net.InetAddress;
17 import java.nio.ByteBuffer;
18 import java.nio.charset.StandardCharsets;
19 import java.util.ArrayList;
20 import java.util.Collections;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.concurrent.atomic.AtomicLong;
24 import javax.annotation.concurrent.GuardedBy;
25 import org.opendaylight.controller.config.yang.pcep.topology.provider.PeerCapabilities;
26 import org.opendaylight.protocol.pcep.PCEPSession;
27 import org.opendaylight.protocol.pcep.spi.PCEPErrors;
28 import org.opendaylight.protocol.pcep.spi.PSTUtil;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714.PathComputationClient1;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714.PathComputationClient1Builder;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714.lsp.db.version.tlv.LspDbVersion;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.crabbe.initiated.rev131126.Lsp1;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.crabbe.initiated.rev131126.PcinitiateBuilder;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.crabbe.initiated.rev131126.Srp1;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.crabbe.initiated.rev131126.Srp1Builder;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.crabbe.initiated.rev131126.Stateful1;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.crabbe.initiated.rev131126.pcinitiate.message.PcinitiateMessageBuilder;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.crabbe.initiated.rev131126.pcinitiate.message.pcinitiate.message.Requests;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.crabbe.initiated.rev131126.pcinitiate.message.pcinitiate.message.RequestsBuilder;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.Arguments1;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.Arguments2;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.Arguments3;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.OperationalStatus;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.Path1;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.Path1Builder;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.PcrptMessage;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.PcupdBuilder;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.PlspId;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.SrpIdNumber;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.StatefulTlv1;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.StatefulTlv1Builder;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.SymbolicPathName;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.Tlvs1;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp.object.Lsp;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp.object.LspBuilder;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp.object.lsp.TlvsBuilder;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.pcerr.pcerr.message.error.type.StatefulCase;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.pcerr.pcerr.message.error.type.stateful._case.stateful.Srps;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.pcrpt.message.pcrpt.message.Reports;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.pcupd.message.PcupdMessageBuilder;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.pcupd.message.pcupd.message.UpdatesBuilder;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.pcupd.message.pcupd.message.updates.PathBuilder;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.srp.object.Srp;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.srp.object.SrpBuilder;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.stateful.capability.tlv.Stateful;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.symbolic.path.name.tlv.SymbolicPathNameBuilder;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Message;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.PcerrMessage;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.explicit.route.object.EroBuilder;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.open.Tlvs;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.path.setup.type.tlv.PathSetupType;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.AddLspArgs;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.EnsureLspOperationalInput;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.LspId;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.Node1;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.OperationResult;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.PccSyncState;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.RemoveLspArgs;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.TriggerSyncArgs;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.UpdateLspArgs;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.PathComputationClient;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.PathComputationClientBuilder;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.path.computation.client.ReportedLsp;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.path.computation.client.ReportedLspBuilder;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.path.computation.client.StatefulTlvBuilder;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.path.computation.client.reported.lsp.Path;
87 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
88 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
89 import org.slf4j.Logger;
90 import org.slf4j.LoggerFactory;
91
92 class Stateful07TopologySessionListener extends AbstractTopologySessionListener<SrpIdNumber, PlspId> {
93     private static final Logger LOG = LoggerFactory.getLogger(Stateful07TopologySessionListener.class);
94
95     private final AtomicLong requestId = new AtomicLong(1L);
96
97     @GuardedBy("this")
98     private final List<PlspId> staleLsps = new ArrayList<>();
99
100     /**
101      * Creates a new stateful topology session listener for given server session manager.
102      *
103      * @param serverSessionManager
104      */
105     Stateful07TopologySessionListener(final ServerSessionManager serverSessionManager) {
106         super(serverSessionManager);
107     }
108
109     @Override
110     protected void onSessionUp(final PCEPSession session, final PathComputationClientBuilder pccBuilder) {
111         final InetAddress peerAddress = session.getRemoteAddress();
112
113         final Tlvs tlvs = session.getRemoteTlvs();
114         if (tlvs != null && tlvs.getAugmentation(Tlvs1.class) != null) {
115             final Stateful stateful = tlvs.getAugmentation(Tlvs1.class).getStateful();
116             if (stateful != null) {
117                 getSessionListenerState().setPeerCapabilities(getCapabilities(stateful));
118                 pccBuilder.setReportedLsp(Collections.<ReportedLsp> emptyList());
119                 if (isSynchronized()) {
120                     pccBuilder.setStateSync(PccSyncState.Synchronized);
121                 } else if (isTriggeredInitialSynchro()) {
122                     pccBuilder.setStateSync(PccSyncState.TriggeredInitialSync);
123                 } else if (isIncrementalSynchro()) {
124                     pccBuilder.setStateSync(PccSyncState.IncrementalSync);
125                 } else {
126                     pccBuilder.setStateSync(PccSyncState.InitialResync);
127                 }
128                 pccBuilder.setStatefulTlv(new StatefulTlvBuilder().addAugmentation(StatefulTlv1.class,
129                     new StatefulTlv1Builder(tlvs.getAugmentation(Tlvs1.class)).build()).build());
130             } else {
131                 LOG.debug("Peer {} does not advertise stateful TLV", peerAddress);
132             }
133         } else {
134             LOG.debug("Peer {} does not advertise stateful TLV", peerAddress);
135         }
136     }
137
138     /**
139      * @param input
140      * @return
141      */
142     @Override
143     public synchronized ListenableFuture<OperationResult> triggerSync(final TriggerSyncArgs input) {
144         if (isTriggeredInitialSynchro() && !isSynchronized()) {
145             return triggerSynchronization(input);
146         } else if (getSynchronized() && isTriggeredReSyncEnabled()) {
147             Preconditions.checkArgument(input != null && input.getNode() != null, MISSING_XML_TAG);
148             if (input.getName() == null) {
149                 return triggerResyncronization(input);
150             } else {
151                 return triggerLspSyncronization(input);
152             }
153         }
154         return OperationResults.UNSENT.future();
155     }
156
157     private ListenableFuture<OperationResult> triggerLspSyncronization(final TriggerSyncArgs input) {
158         LOG.trace("Trigger Lsp Resynchronization {}", input);
159
160         // Make sure the LSP exists
161         final InstanceIdentifier<ReportedLsp> lsp = lspIdentifier(input.getName());
162         final ListenableFuture<Optional<ReportedLsp>> f = readOperationalData(lsp);
163         if (f == null) {
164             return OperationResults.createUnsent(PCEPErrors.LSP_INTERNAL_ERROR).future();
165         }
166         return Futures.transform(f, new ResyncLspFunction(input));
167     }
168
169     private ListenableFuture<OperationResult> triggerResyncronization(final TriggerSyncArgs input) {
170         LOG.trace("Trigger Resynchronization {}", input);
171         markAllLspAsStale();
172         updatePccState(PccSyncState.PcepTriggeredResync);
173         final PcupdMessageBuilder pcupdMessageBuilder = new PcupdMessageBuilder(MESSAGE_HEADER);
174         final SrpIdNumber srpIdNumber = createUpdateMessageSync(pcupdMessageBuilder);
175         final Message msg = new PcupdBuilder().setPcupdMessage(pcupdMessageBuilder.build()).build();
176         return sendMessage(msg, srpIdNumber, null);
177     }
178
179     private ListenableFuture<OperationResult> triggerSynchronization(final TriggerSyncArgs input) {
180         LOG.trace("Trigger Initial Synchronization {}", input);
181         final PcupdMessageBuilder pcupdMessageBuilder = new PcupdMessageBuilder(MESSAGE_HEADER);
182         final SrpIdNumber srpIdNumber = createUpdateMessageSync(pcupdMessageBuilder);
183         final Message msg = new PcupdBuilder().setPcupdMessage(pcupdMessageBuilder.build()).build();
184         return sendMessage(msg, srpIdNumber, null);
185     }
186
187     private SrpIdNumber createUpdateMessageSync(final PcupdMessageBuilder pcupdMessageBuilder) {
188         final UpdatesBuilder updBuilder = new UpdatesBuilder();
189         // LSP mandatory in Upd
190         final Lsp lsp = new LspBuilder().setPlspId(new PlspId(0L)).setSync(Boolean.TRUE).build();
191         // SRP Mandatory in Upd
192         final SrpBuilder srpBuilder = new SrpBuilder();
193         // not sue whether use 0 instead of nextRequest() or do not insert srp == SRP-ID-number = 0
194         srpBuilder.setOperationId(nextRequest());
195         final Srp srp = srpBuilder.build();
196         //ERO Mandatory in Upd
197         final PathBuilder pb = new PathBuilder();
198         pb.setEro(new EroBuilder().build());
199
200         updBuilder.setPath(pb.build());
201         updBuilder.setLsp(lsp).setSrp(srp).setPath(pb.build());
202
203         pcupdMessageBuilder.setUpdates(Collections.singletonList(updBuilder.build()));
204         return srp.getOperationId();
205     }
206
207     private void markAllLspAsStale() {
208         for (final PlspId plspId : lsps.keySet()) {
209             staleLsps.add(plspId);
210         }
211     }
212
213     private class ResyncLspFunction implements AsyncFunction<Optional<ReportedLsp>, OperationResult>  {
214
215         private final TriggerSyncArgs input;
216
217         public ResyncLspFunction(final TriggerSyncArgs input) {
218             this.input = input;
219         }
220
221         @Override
222         public ListenableFuture<OperationResult> apply(final Optional<ReportedLsp> rep) {
223             final Lsp reportedLsp = validateReportedLsp(rep, this.input);
224             if (reportedLsp == null || !rep.isPresent()) {
225                 return OperationResults.createUnsent(PCEPErrors.UNKNOWN_PLSP_ID).future();
226             }
227             // mark lsp as stale
228             final ReportedLsp staleLsp = rep.get();
229             if (!staleLsp.getPath().isEmpty()) {
230                 final Path1 path1 = staleLsp.getPath().get(0).getAugmentation(Path1.class);
231                 if (path1 != null) {
232                     staleLsps.add(path1.getLsp().getPlspId());
233                 }
234             }
235             updatePccState(PccSyncState.PcepTriggeredResync);
236             // create PCUpd with mandatory objects and LSP object set to 1
237             final SrpBuilder srpBuilder = new SrpBuilder();
238             srpBuilder.setOperationId(nextRequest());
239             srpBuilder.setProcessingRule(Boolean.TRUE);
240
241             final Optional<PathSetupType> maybePST = getPST(rep);
242             if (maybePST.isPresent()) {
243                 srpBuilder.setTlvs(
244                     new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.srp.object.srp.TlvsBuilder()
245                         .setPathSetupType(maybePST.get()).build());
246             }
247
248             final Srp srp = srpBuilder.build();
249             final Lsp lsp = new LspBuilder().setPlspId(reportedLsp.getPlspId()).setSync(Boolean.TRUE).build();
250
251             final Message msg = createPcepUpd(srp,lsp);
252             return sendMessage(msg, srp.getOperationId(), null);
253         }
254
255         private Message createPcepUpd(final Srp srp, final Lsp lsp) {
256             final UpdatesBuilder rb = new UpdatesBuilder();
257             rb.setSrp(srp);
258             rb.setLsp(lsp);
259             final PathBuilder pb = new PathBuilder();
260             rb.setPath(pb.build());
261             final PcupdMessageBuilder ub = new PcupdMessageBuilder(MESSAGE_HEADER);
262             ub.setUpdates(Collections.singletonList(rb.build()));
263             return new PcupdBuilder().setPcupdMessage(ub.build()).build();
264         }
265     }
266
267     private boolean handleErrorMessage(final PcerrMessage message) {
268         final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.pcerr.message.PcerrMessage errMsg = message.getPcerrMessage();
269         if (errMsg.getErrorType() instanceof StatefulCase) {
270             final StatefulCase stat = (StatefulCase)errMsg.getErrorType();
271             for (final Srps srps : stat.getStateful().getSrps()) {
272                 final SrpIdNumber id = srps.getSrp().getOperationId();
273                 if (id.getValue() != 0) {
274                     final PCEPRequest req = removeRequest(id);
275                     if (req != null) {
276                         req.done(OperationResults.createFailed(errMsg.getErrors()));
277                     } else {
278                         LOG.warn("Request ID {} not found in outstanding DB", id);
279                     }
280                 }
281             }
282         } else {
283             LOG.warn("Unhandled PCErr message {}.", errMsg);
284             return true;
285         }
286         return false;
287     }
288
289     private boolean isSolicited(final Srp srp, final Lsp lsp, final MessageContext ctx, final ReportedLspBuilder rlb) {
290         if (srp == null) {
291             return false;
292         }
293         final SrpIdNumber id = srp.getOperationId();
294         if (id.getValue() == 0) {
295             return false;
296         }
297         switch (lsp.getOperational()) {
298         case Active:
299         case Down:
300         case Up:
301             if(!isTriggeredSyncInProcess()) {
302                 final PCEPRequest req = removeRequest(id);
303                 if (req != null) {
304                     LOG.debug("Request {} resulted in LSP operational state {}", id, lsp.getOperational());
305                     rlb.setMetadata(req.getMetadata());
306                     ctx.resolveRequest(req);
307                 } else {
308                     LOG.warn("Request ID {} not found in outstanding DB", id);
309                 }
310             }
311             break;
312         case GoingDown:
313         case GoingUp:
314             // These are transitive states, so we don't have to do anything, as they will be followed
315             // up...
316             break;
317         default:
318             break;
319         }
320         return true;
321     }
322
323     private boolean manageNextReport(final Reports report, final MessageContext ctx) {
324         final Lsp lsp = report.getLsp();
325         final PlspId plspid = lsp.getPlspId();
326         final Srp srp = report.getSrp();
327
328         if (!lsp.isSync() && (plspid == null || plspid.getValue() == 0)) {
329             purgeStaleLsps(ctx);
330             if(isTriggeredSyncInProcess()) {
331                 if (srp == null) {
332                     return false;
333                 }
334                 final SrpIdNumber id = srp.getOperationId();
335                 if (id.getValue() == 0) {
336                     return false;
337                 }
338                 final PCEPRequest req = removeRequest(id);
339                 ctx.resolveRequest(req);
340             }
341             stateSynchronizationAchieved(ctx);
342             return true;
343         }
344         final ReportedLspBuilder rlb = new ReportedLspBuilder();
345         boolean solicited = false;
346         solicited = isSolicited(srp, lsp, ctx, rlb);
347
348         // if remove flag is set in SRP object, remove the tunnel immediately
349         if (solicited && srp.getAugmentation(Srp1.class) != null) {
350             final Srp1 initiatedSrp = srp.getAugmentation(Srp1.class);
351             if (initiatedSrp.isRemove()) {
352                 super.removeLsp(ctx, plspid);
353                 return false;
354             }
355         }
356         rlb.setPath(Collections.singletonList(buildPath(report, srp, lsp)));
357
358         String name = lookupLspName(plspid);
359         if (lsp.getTlvs() != null && lsp.getTlvs().getSymbolicPathName() != null) {
360             name = StandardCharsets.UTF_8.decode(ByteBuffer.wrap(lsp.getTlvs().getSymbolicPathName().getPathName().getValue())).toString();
361         }
362         //get LspDB from LSP and write it to pcc's node
363         final LspDbVersion lspDbVersion = geLspDbVersionTlv(lsp);
364         if (lspDbVersion != null) {
365             updatePccNode(ctx, new PathComputationClientBuilder().addAugmentation(PathComputationClient1.class,
366                     new PathComputationClient1Builder().setLspDbVersion(lspDbVersion).build()).build());
367         }
368         updateLsp(ctx, plspid, name, rlb, solicited, lsp.isRemove());
369         unmarkStaleLsp(plspid);
370
371         LOG.debug("LSP {} updated", lsp);
372         return true;
373     }
374
375     private static LspDbVersion geLspDbVersionTlv(final Lsp lsp) {
376         final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp.object.lsp.Tlvs tlvs = lsp.getTlvs();
377         if (tlvs != null && tlvs.getAugmentation(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714.Tlvs1.class) != null) {
378             return tlvs.getAugmentation(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714.Tlvs1.class).getLspDbVersion();
379         }
380         return null;
381     }
382
383     private Path buildPath(final Reports report, final Srp srp, final Lsp lsp) {
384         final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.path.computation.client.reported.lsp.PathBuilder pb = new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.path.computation.client.reported.lsp.PathBuilder();
385         if (report.getPath() != null) {
386             pb.fieldsFrom(report.getPath());
387         }
388         // LSP is mandatory (if there is none, parser will throw an exception)
389         // this is to ensure a path will be created at any rate
390         final Path1Builder p1Builder = new Path1Builder();
391         p1Builder.setLsp(report.getLsp());
392         final PathSetupType pst;
393         if (srp != null && srp.getTlvs() != null && srp.getTlvs().getPathSetupType() != null) {
394             pst = srp.getTlvs().getPathSetupType();
395             p1Builder.setPathSetupType(pst);
396         } else {
397             pst = null;
398         }
399         pb.addAugmentation(Path1.class, p1Builder.build());
400         final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp.object.lsp.Tlvs tlvs = report.getLsp().getTlvs();
401         if (tlvs != null) {
402             if (tlvs.getLspIdentifiers() != null) {
403                 pb.setLspId(tlvs.getLspIdentifiers().getLspId());
404             } else if (!PSTUtil.isDefaultPST(pst)) {
405                 pb.setLspId(new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev150820.LspId(lsp.getPlspId().getValue()));
406             }
407         }
408         return pb.build();
409     }
410
411     @Override
412     protected boolean onMessage(final MessageContext ctx, final Message message) {
413         if (message instanceof PcerrMessage) {
414             return handleErrorMessage((PcerrMessage) message);
415         }
416         if (!(message instanceof PcrptMessage)) {
417             return true;
418         }
419         getSessionListenerState().updateLastReceivedRptMsg();
420         final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.pcrpt.message.PcrptMessage rpt = ((PcrptMessage) message).getPcrptMessage();
421         for (final Reports report : rpt.getReports()) {
422             if (!manageNextReport(report, ctx)) {
423                 return false;
424             }
425         }
426         return false;
427     }
428
429     private SrpIdNumber nextRequest() {
430         return new SrpIdNumber(this.requestId.getAndIncrement());
431     }
432
433     private class AddFunction implements AsyncFunction<Optional<ReportedLsp>, OperationResult>  {
434
435         private final AddLspArgs input;
436         private final InstanceIdentifier<ReportedLsp> lsp;
437
438         public AddFunction(final AddLspArgs input, final InstanceIdentifier<ReportedLsp> lsp) {
439             this.input = input;
440             this.lsp = lsp;
441         }
442
443         @Override
444         public ListenableFuture<OperationResult> apply(final Optional<ReportedLsp> rep) {
445             if (rep.isPresent()) {
446                 LOG.debug("Node {} already contains lsp {} at {}", this.input.getNode(), this.input.getName(), this.lsp);
447                 return OperationResults.createUnsent(PCEPErrors.USED_SYMBOLIC_PATH_NAME).future();
448             }
449             if (!getPeerCapabilities().getInstantiation()) {
450                 return OperationResults.createUnsent(PCEPErrors.CAPABILITY_NOT_SUPPORTED).future();
451             }
452
453             // Build the request
454             final RequestsBuilder rb = new RequestsBuilder();
455             final Arguments2 args = this.input.getArguments().getAugmentation(Arguments2.class);
456             final Lsp inputLsp = (args != null) ? args.getLsp() : null;
457             if (inputLsp == null) {
458                 return OperationResults.createUnsent(PCEPErrors.LSP_MISSING).future();
459             }
460
461             rb.fieldsFrom(this.input.getArguments());
462
463             final TlvsBuilder tlvsBuilder;
464             if (inputLsp.getTlvs() != null) {
465                 tlvsBuilder = new TlvsBuilder(inputLsp.getTlvs());
466             } else {
467                 tlvsBuilder = new TlvsBuilder();
468             }
469             tlvsBuilder.setSymbolicPathName(
470                 new SymbolicPathNameBuilder().setPathName(new SymbolicPathName(this.input.getName().getBytes(StandardCharsets.UTF_8))).build());
471
472             final SrpBuilder srpBuilder = new SrpBuilder();
473             srpBuilder.setOperationId(nextRequest());
474             srpBuilder.setProcessingRule(Boolean.TRUE);
475             if (!PSTUtil.isDefaultPST(args.getPathSetupType())) {
476                 srpBuilder.setTlvs(
477                         new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.srp.object.srp.TlvsBuilder()
478                             .setPathSetupType(args.getPathSetupType()).build());
479             }
480             rb.setSrp(srpBuilder.build());
481
482             rb.setLsp(new LspBuilder().setAdministrative(inputLsp.isAdministrative()).setDelegate(inputLsp.isDelegate()).setPlspId(
483                 new PlspId(0L)).setTlvs(tlvsBuilder.build()).build());
484
485             final PcinitiateMessageBuilder ib = new PcinitiateMessageBuilder(MESSAGE_HEADER);
486             ib.setRequests(Collections.singletonList(rb.build()));
487
488             // Send the message
489             return sendMessage(new PcinitiateBuilder().setPcinitiateMessage(ib.build()).build(), rb.getSrp().getOperationId(),
490                 this.input.getArguments().getMetadata());
491         }
492     }
493
494     @Override
495     public synchronized ListenableFuture<OperationResult> addLsp(final AddLspArgs input) {
496         Preconditions.checkArgument(input != null && input.getName() != null && input.getNode() != null && input.getArguments() != null, MISSING_XML_TAG);
497         LOG.trace("AddLspArgs {}", input);
498         // Make sure there is no such LSP
499         final InstanceIdentifier<ReportedLsp> lsp = lspIdentifier(input.getName());
500         final ListenableFuture<Optional<ReportedLsp>> f = readOperationalData(lsp);
501         if (f == null) {
502             return OperationResults.createUnsent(PCEPErrors.LSP_INTERNAL_ERROR).future();
503         }
504         return Futures.transform(f, new AddFunction(input, lsp));
505     }
506
507     @Override
508     public synchronized ListenableFuture<OperationResult> removeLsp(final RemoveLspArgs input) {
509         Preconditions.checkArgument(input != null && input.getName() != null && input.getNode() != null, MISSING_XML_TAG);
510         LOG.trace("RemoveLspArgs {}", input);
511         // Make sure the LSP exists, we need it for PLSP-ID
512         final InstanceIdentifier<ReportedLsp> lsp = lspIdentifier(input.getName());
513         final ListenableFuture<Optional<ReportedLsp>> f = readOperationalData(lsp);
514         if (f == null) {
515             return OperationResults.createUnsent(PCEPErrors.LSP_INTERNAL_ERROR).future();
516         }
517         return Futures.transform(f, new AsyncFunction<Optional<ReportedLsp>, OperationResult>() {
518             @Override
519             public ListenableFuture<OperationResult> apply(final Optional<ReportedLsp> rep) {
520                 final Lsp reportedLsp = validateReportedLsp(rep, input);
521                 if (reportedLsp == null) {
522                     return OperationResults.createUnsent(PCEPErrors.UNKNOWN_PLSP_ID).future();
523                 }
524                 final PcinitiateMessageBuilder ib = new PcinitiateMessageBuilder(MESSAGE_HEADER);
525                 final Requests rb = buildRequest(rep, reportedLsp);
526                 ib.setRequests(Collections.singletonList(rb));
527                 return sendMessage(new PcinitiateBuilder().setPcinitiateMessage(ib.build()).build(), rb.getSrp().getOperationId(), null);
528             }
529         });
530     }
531
532     private Requests buildRequest(final Optional<ReportedLsp> rep, final Lsp reportedLsp) {
533         // Build the request and send it
534         final RequestsBuilder rb = new RequestsBuilder();
535         final SrpBuilder srpBuilder = new SrpBuilder().addAugmentation(Srp1.class, new Srp1Builder().setRemove(Boolean.TRUE).build()).setOperationId(nextRequest()).setProcessingRule(Boolean.TRUE);
536         final Optional<PathSetupType> maybePST = getPST(rep);
537         if (maybePST.isPresent()) {
538             srpBuilder.setTlvs(new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.srp.object.srp.TlvsBuilder()
539                 .setPathSetupType(maybePST.get())
540                 .build());
541         }
542         rb.setSrp(srpBuilder.build());
543         rb.setLsp(new LspBuilder().setRemove(Boolean.FALSE).setPlspId(reportedLsp.getPlspId()).setDelegate(reportedLsp.isDelegate()).build());
544         return rb.build();
545     }
546
547     private class UpdateFunction implements AsyncFunction<Optional<ReportedLsp>, OperationResult>  {
548
549         private final UpdateLspArgs input;
550
551         public UpdateFunction(final UpdateLspArgs input) {
552             this.input = input;
553         }
554
555         @Override
556         public ListenableFuture<OperationResult> apply(final Optional<ReportedLsp> rep) {
557             final Lsp reportedLsp = validateReportedLsp(rep, this.input);
558             if (reportedLsp == null) {
559                 return OperationResults.createUnsent(PCEPErrors.UNKNOWN_PLSP_ID).future();
560             }
561             // create mandatory objects
562             final Arguments3 args = this.input.getArguments().getAugmentation(Arguments3.class);
563             final SrpBuilder srpBuilder = new SrpBuilder();
564             srpBuilder.setOperationId(nextRequest());
565             srpBuilder.setProcessingRule(Boolean.TRUE);
566             if ((args != null && args.getPathSetupType() != null)) {
567                 if (!PSTUtil.isDefaultPST(args.getPathSetupType())) {
568                     srpBuilder.setTlvs(
569                             new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.srp.object.srp.TlvsBuilder()
570                                 .setPathSetupType(args.getPathSetupType()).build());
571                 }
572             } else {
573                 final Optional<PathSetupType> maybePST = getPST(rep);
574                 if (maybePST.isPresent()) {
575                     srpBuilder.setTlvs(
576                             new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.srp.object.srp.TlvsBuilder()
577                                 .setPathSetupType(maybePST.get()).build());
578                 }
579             }
580             final Srp srp = srpBuilder.build();
581             final Lsp inputLsp = (args != null) ? args.getLsp() : null;
582             final LspBuilder lspBuilder = new LspBuilder().setPlspId(reportedLsp.getPlspId());
583             if (inputLsp != null) {
584                 lspBuilder.setDelegate(inputLsp.isDelegate() != null && inputLsp.isDelegate())
585                         .setTlvs(inputLsp.getTlvs())
586                         .setAdministrative(inputLsp.isAdministrative() != null && inputLsp.isAdministrative());
587             }
588             return redelegate(reportedLsp, srp, lspBuilder.build(), this.input);
589         }
590     }
591
592     private ListenableFuture<OperationResult> redelegate(final Lsp reportedLsp, final Srp srp, final Lsp lsp, final UpdateLspArgs input) {
593         // the D bit that was reported decides the type of PCE message sent
594         Preconditions.checkNotNull(reportedLsp.isDelegate());
595         final Message msg;
596         if (reportedLsp.isDelegate()) {
597             // we already have delegation, send update
598             final UpdatesBuilder rb = new UpdatesBuilder();
599             rb.setSrp(srp);
600             rb.setLsp(lsp);
601             final PathBuilder pb = new PathBuilder();
602             pb.fieldsFrom(input.getArguments());
603             rb.setPath(pb.build());
604             final PcupdMessageBuilder ub = new PcupdMessageBuilder(MESSAGE_HEADER);
605             ub.setUpdates(Collections.singletonList(rb.build()));
606             msg = new PcupdBuilder().setPcupdMessage(ub.build()).build();
607         } else {
608             final Lsp1 lspCreateFlag = reportedLsp.getAugmentation(Lsp1.class);
609             // we only retake delegation for PCE initiated tunnels
610             if (lspCreateFlag != null && !lspCreateFlag.isCreate()) {
611                 LOG.warn("Unable to retake delegation of PCC-initiated tunnel: {}", reportedLsp);
612                 return OperationResults.createUnsent(PCEPErrors.UPDATE_REQ_FOR_NON_LSP).future();
613             }
614             // we want to revoke delegation, different type of message
615             // is sent because of specification by Siva
616             // this message is also sent, when input delegate bit is set to 0
617             // generating an error in PCC
618             final List<Requests> reqs = new ArrayList<>();
619             reqs.add(new RequestsBuilder().setSrp(srp).setLsp(lsp).build());
620             final PcinitiateMessageBuilder ib = new PcinitiateMessageBuilder();
621             ib.setRequests(reqs);
622             msg = new PcinitiateBuilder().setPcinitiateMessage(ib.build()).build();
623         }
624         return sendMessage(msg, srp.getOperationId(), input.getArguments().getMetadata());
625     }
626
627     @Override
628     public synchronized ListenableFuture<OperationResult> updateLsp(final UpdateLspArgs input) {
629         Preconditions.checkArgument(input != null && input.getName() != null && input.getNode() != null && input.getArguments() != null, MISSING_XML_TAG);
630         LOG.trace("UpdateLspArgs {}", input);
631         // Make sure the LSP exists
632         final InstanceIdentifier<ReportedLsp> lsp = lspIdentifier(input.getName());
633         final ListenableFuture<Optional<ReportedLsp>> f = readOperationalData(lsp);
634         if (f == null) {
635             return OperationResults.createUnsent(PCEPErrors.LSP_INTERNAL_ERROR).future();
636         }
637         return Futures.transform(f, new UpdateFunction(input));
638     }
639
640     @Override
641     public synchronized ListenableFuture<OperationResult> ensureLspOperational(final EnsureLspOperationalInput input) {
642         Preconditions.checkArgument(input != null && input.getName() != null && input.getNode() != null && input.getArguments() != null, MISSING_XML_TAG);
643         final OperationalStatus op;
644         final Arguments1 aa = input.getArguments().getAugmentation(Arguments1.class);
645         if (aa != null) {
646             op = aa.getOperational();
647         } else {
648             op = null;
649         }
650
651         // Make sure the LSP exists
652         final InstanceIdentifier<ReportedLsp> lsp = lspIdentifier(input.getName());
653         LOG.debug("Checking if LSP {} has operational state {}", lsp, op);
654         final ListenableFuture<Optional<ReportedLsp>> f = readOperationalData(lsp);
655         if (f == null) {
656             return OperationResults.createUnsent(PCEPErrors.LSP_INTERNAL_ERROR).future();
657         }
658         return listenableFuture(f, input, op);
659     }
660
661     private ListenableFuture<OperationResult> listenableFuture(final ListenableFuture<Optional<ReportedLsp>> f, final EnsureLspOperationalInput input, final OperationalStatus op) {
662         return Futures.transform(f, new Function<Optional<ReportedLsp>, OperationResult>() {
663             @Override
664             public OperationResult apply(final Optional<ReportedLsp> rep) {
665                 if (!rep.isPresent()) {
666                     LOG.debug("Node {} does not contain LSP {}", input.getNode(), input.getName());
667                     return OperationResults.UNSENT;
668                 }
669                 // check if at least one of the paths has the same status as requested
670                 for (final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.path.computation.client.reported.lsp.Path p : rep.get().getPath()) {
671                     final Path1 p1 = p.getAugmentation(Path1.class);
672                     if (p1 == null) {
673                         LOG.warn("Node {} LSP {} does not contain data", input.getNode(), input.getName());
674                         return OperationResults.UNSENT;
675                     }
676                     if (op.equals(p1.getLsp().getOperational())) {
677                         return OperationResults.SUCCESS;
678                     }
679                 }
680                 return OperationResults.UNSENT;
681             }
682         });
683     }
684
685     @Override
686     protected Lsp validateReportedLsp(final Optional<ReportedLsp> rep,  final LspId input) {
687         if (!rep.isPresent()) {
688             LOG.debug("Node {} does not contain LSP {}", input.getNode(), input.getName());
689             return null;
690         }
691         // it doesn't matter how many lsps there are in the path list, we only need data that is the same in each path
692         final Path1 ra = rep.get().getPath().get(0).getAugmentation(Path1.class);
693         Preconditions.checkState(ra != null, "Reported LSP reported null from data-store.");
694         final Lsp reportedLsp = ra.getLsp();
695         Preconditions.checkState(reportedLsp != null, "Reported LSP does not contain LSP object.");
696         return reportedLsp;
697     }
698
699     private Optional<PathSetupType> getPST(final Optional<ReportedLsp> rep) {
700         if (rep.isPresent()) {
701             final Path1 path1 = rep.get().getPath().get(0).getAugmentation(Path1.class);
702             if (path1 != null) {
703                 final PathSetupType pst = path1.getPathSetupType();
704                 if (!PSTUtil.isDefaultPST(pst)) {
705                     return Optional.of(pst);
706                 }
707             }
708         }
709         return Optional.absent();
710     }
711
712     private static PeerCapabilities getCapabilities(final Stateful stateful) {
713         final PeerCapabilities capa = new PeerCapabilities();
714         capa.setStateful(true);
715         if (stateful.isLspUpdateCapability() != null) {
716             capa.setActive(stateful.isLspUpdateCapability());
717         }
718         final Stateful1 stateful1 = stateful.getAugmentation(Stateful1.class);
719         if (stateful1 != null && stateful1.isInitiation() != null) {
720             capa.setInstantiation(stateful1.isInitiation());
721         }
722         return capa;
723     }
724
725     /**
726      * Recover lspData and mark any LSPs in the LSP database that were previously reported by the PCC as stale
727      * @param lspData
728      * @param lsps
729      * @param incrementalSynchro
730      */
731     @Override
732     protected synchronized void loadLspData(final Node node, final Map<String, ReportedLsp> lspData, final Map<PlspId, String> lsps, final boolean incrementalSynchro) {
733         //load node's lsps from DS
734         final PathComputationClient pcc = node.getAugmentation(Node1.class).getPathComputationClient();
735         final List<ReportedLsp> reportedLsps = pcc.getReportedLsp();
736         for (final ReportedLsp reportedLsp : reportedLsps) {
737             final String lspName = reportedLsp.getName();
738             lspData.put(lspName, reportedLsp);
739             if (!reportedLsp.getPath().isEmpty()) {
740                 final Path1 path1 = reportedLsp.getPath().get(0).getAugmentation(Path1.class);
741                 if (path1 != null) {
742                     final PlspId plspId = path1.getLsp().getPlspId();
743                     if (!incrementalSynchro) {
744                         staleLsps.add(plspId);
745                     }
746                     lsps.put(plspId, lspName);
747                 }
748             }
749         }
750     }
751
752     /**
753      * When the PCC reports an LSP during state synchronization, if the LSP already
754      * exists in the LSP database, the PCE MUST update the LSP database and
755      * clear the stale marker from the LSP
756      * @param plspId
757      */
758     private synchronized void unmarkStaleLsp(final PlspId plspId) {
759         staleLsps.remove(plspId);
760     }
761
762     /**
763      *  Purge any LSPs from the LSP database that are still marked as stale
764      * @param ctx
765      */
766     private synchronized void purgeStaleLsps(final MessageContext ctx) {
767         for (final PlspId plspId : staleLsps) {
768             removeLsp(ctx, plspId);
769         }
770         staleLsps.clear();
771     }
772 }