Code Clean Up
[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.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 : this.lsps.keySet()) {
209             this.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                     Stateful07TopologySessionListener.this.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, (AsyncFunction<Optional<ReportedLsp>, OperationResult>) rep -> {
518             final Lsp reportedLsp = validateReportedLsp(rep, input);
519             if (reportedLsp == null) {
520                 return OperationResults.createUnsent(PCEPErrors.UNKNOWN_PLSP_ID).future();
521             }
522             final PcinitiateMessageBuilder ib = new PcinitiateMessageBuilder(MESSAGE_HEADER);
523             final Requests rb = buildRequest(rep, reportedLsp);
524             ib.setRequests(Collections.singletonList(rb));
525             return sendMessage(new PcinitiateBuilder().setPcinitiateMessage(ib.build()).build(), rb.getSrp().getOperationId(), null);
526         });
527     }
528
529     private Requests buildRequest(final Optional<ReportedLsp> rep, final Lsp reportedLsp) {
530         // Build the request and send it
531         final RequestsBuilder rb = new RequestsBuilder();
532         final SrpBuilder srpBuilder = new SrpBuilder().addAugmentation(Srp1.class, new Srp1Builder().setRemove(Boolean.TRUE).build()).setOperationId(nextRequest()).setProcessingRule(Boolean.TRUE);
533         final Optional<PathSetupType> maybePST = getPST(rep);
534         if (maybePST.isPresent()) {
535             srpBuilder.setTlvs(new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.srp.object.srp.TlvsBuilder()
536                 .setPathSetupType(maybePST.get())
537                 .build());
538         }
539         rb.setSrp(srpBuilder.build());
540         rb.setLsp(new LspBuilder().setRemove(Boolean.FALSE).setPlspId(reportedLsp.getPlspId()).setDelegate(reportedLsp.isDelegate()).build());
541         return rb.build();
542     }
543
544     private class UpdateFunction implements AsyncFunction<Optional<ReportedLsp>, OperationResult>  {
545
546         private final UpdateLspArgs input;
547
548         public UpdateFunction(final UpdateLspArgs input) {
549             this.input = input;
550         }
551
552         @Override
553         public ListenableFuture<OperationResult> apply(final Optional<ReportedLsp> rep) {
554             final Lsp reportedLsp = validateReportedLsp(rep, this.input);
555             if (reportedLsp == null) {
556                 return OperationResults.createUnsent(PCEPErrors.UNKNOWN_PLSP_ID).future();
557             }
558             // create mandatory objects
559             final Arguments3 args = this.input.getArguments().getAugmentation(Arguments3.class);
560             final SrpBuilder srpBuilder = new SrpBuilder();
561             srpBuilder.setOperationId(nextRequest());
562             srpBuilder.setProcessingRule(Boolean.TRUE);
563             if ((args != null && args.getPathSetupType() != null)) {
564                 if (!PSTUtil.isDefaultPST(args.getPathSetupType())) {
565                     srpBuilder.setTlvs(
566                             new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.srp.object.srp.TlvsBuilder()
567                                 .setPathSetupType(args.getPathSetupType()).build());
568                 }
569             } else {
570                 final Optional<PathSetupType> maybePST = getPST(rep);
571                 if (maybePST.isPresent()) {
572                     srpBuilder.setTlvs(
573                             new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.srp.object.srp.TlvsBuilder()
574                                 .setPathSetupType(maybePST.get()).build());
575                 }
576             }
577             final Srp srp = srpBuilder.build();
578             final Lsp inputLsp = (args != null) ? args.getLsp() : null;
579             final LspBuilder lspBuilder = new LspBuilder().setPlspId(reportedLsp.getPlspId());
580             if (inputLsp != null) {
581                 lspBuilder.setDelegate(inputLsp.isDelegate() != null && inputLsp.isDelegate())
582                         .setTlvs(inputLsp.getTlvs())
583                         .setAdministrative(inputLsp.isAdministrative() != null && inputLsp.isAdministrative());
584             }
585             return redelegate(reportedLsp, srp, lspBuilder.build(), this.input);
586         }
587     }
588
589     private ListenableFuture<OperationResult> redelegate(final Lsp reportedLsp, final Srp srp, final Lsp lsp, final UpdateLspArgs input) {
590         // the D bit that was reported decides the type of PCE message sent
591         Preconditions.checkNotNull(reportedLsp.isDelegate());
592         final Message msg;
593         if (reportedLsp.isDelegate()) {
594             // we already have delegation, send update
595             final UpdatesBuilder rb = new UpdatesBuilder();
596             rb.setSrp(srp);
597             rb.setLsp(lsp);
598             final PathBuilder pb = new PathBuilder();
599             pb.fieldsFrom(input.getArguments());
600             rb.setPath(pb.build());
601             final PcupdMessageBuilder ub = new PcupdMessageBuilder(MESSAGE_HEADER);
602             ub.setUpdates(Collections.singletonList(rb.build()));
603             msg = new PcupdBuilder().setPcupdMessage(ub.build()).build();
604         } else {
605             final Lsp1 lspCreateFlag = reportedLsp.getAugmentation(Lsp1.class);
606             // we only retake delegation for PCE initiated tunnels
607             if (lspCreateFlag != null && !lspCreateFlag.isCreate()) {
608                 LOG.warn("Unable to retake delegation of PCC-initiated tunnel: {}", reportedLsp);
609                 return OperationResults.createUnsent(PCEPErrors.UPDATE_REQ_FOR_NON_LSP).future();
610             }
611             // we want to revoke delegation, different type of message
612             // is sent because of specification by Siva
613             // this message is also sent, when input delegate bit is set to 0
614             // generating an error in PCC
615             final List<Requests> reqs = new ArrayList<>();
616             reqs.add(new RequestsBuilder().setSrp(srp).setLsp(lsp).build());
617             final PcinitiateMessageBuilder ib = new PcinitiateMessageBuilder();
618             ib.setRequests(reqs);
619             msg = new PcinitiateBuilder().setPcinitiateMessage(ib.build()).build();
620         }
621         return sendMessage(msg, srp.getOperationId(), input.getArguments().getMetadata());
622     }
623
624     @Override
625     public synchronized ListenableFuture<OperationResult> updateLsp(final UpdateLspArgs input) {
626         Preconditions.checkArgument(input != null && input.getName() != null && input.getNode() != null && input.getArguments() != null, MISSING_XML_TAG);
627         LOG.trace("UpdateLspArgs {}", input);
628         // Make sure the LSP exists
629         final InstanceIdentifier<ReportedLsp> lsp = lspIdentifier(input.getName());
630         final ListenableFuture<Optional<ReportedLsp>> f = readOperationalData(lsp);
631         if (f == null) {
632             return OperationResults.createUnsent(PCEPErrors.LSP_INTERNAL_ERROR).future();
633         }
634         return Futures.transform(f, new UpdateFunction(input));
635     }
636
637     @Override
638     public synchronized ListenableFuture<OperationResult> ensureLspOperational(final EnsureLspOperationalInput input) {
639         Preconditions.checkArgument(input != null && input.getName() != null && input.getNode() != null && input.getArguments() != null, MISSING_XML_TAG);
640         final OperationalStatus op;
641         final Arguments1 aa = input.getArguments().getAugmentation(Arguments1.class);
642         if (aa != null) {
643             op = aa.getOperational();
644         } else {
645             op = null;
646         }
647
648         // Make sure the LSP exists
649         final InstanceIdentifier<ReportedLsp> lsp = lspIdentifier(input.getName());
650         LOG.debug("Checking if LSP {} has operational state {}", lsp, op);
651         final ListenableFuture<Optional<ReportedLsp>> f = readOperationalData(lsp);
652         if (f == null) {
653             return OperationResults.createUnsent(PCEPErrors.LSP_INTERNAL_ERROR).future();
654         }
655         return listenableFuture(f, input, op);
656     }
657
658     private ListenableFuture<OperationResult> listenableFuture(final ListenableFuture<Optional<ReportedLsp>> f, final EnsureLspOperationalInput input, final OperationalStatus op) {
659         return Futures.transform(f, (Function<Optional<ReportedLsp>, OperationResult>) rep -> {
660             if (!rep.isPresent()) {
661                 LOG.debug("Node {} does not contain LSP {}", input.getNode(), input.getName());
662                 return OperationResults.UNSENT;
663             }
664             // check if at least one of the paths has the same status as requested
665             for (final Path p : rep.get().getPath()) {
666                 final Path1 p1 = p.getAugmentation(Path1.class);
667                 if (p1 == null) {
668                     LOG.warn("Node {} LSP {} does not contain data", input.getNode(), input.getName());
669                     return OperationResults.UNSENT;
670                 }
671                 if (op.equals(p1.getLsp().getOperational())) {
672                     return OperationResults.SUCCESS;
673                 }
674             }
675             return OperationResults.UNSENT;
676         });
677     }
678
679     @Override
680     protected Lsp validateReportedLsp(final Optional<ReportedLsp> rep,  final LspId input) {
681         if (!rep.isPresent()) {
682             LOG.debug("Node {} does not contain LSP {}", input.getNode(), input.getName());
683             return null;
684         }
685         // it doesn't matter how many lsps there are in the path list, we only need data that is the same in each path
686         final Path1 ra = rep.get().getPath().get(0).getAugmentation(Path1.class);
687         Preconditions.checkState(ra != null, "Reported LSP reported null from data-store.");
688         final Lsp reportedLsp = ra.getLsp();
689         Preconditions.checkState(reportedLsp != null, "Reported LSP does not contain LSP object.");
690         return reportedLsp;
691     }
692
693     private Optional<PathSetupType> getPST(final Optional<ReportedLsp> rep) {
694         if (rep.isPresent()) {
695             final Path1 path1 = rep.get().getPath().get(0).getAugmentation(Path1.class);
696             if (path1 != null) {
697                 final PathSetupType pst = path1.getPathSetupType();
698                 if (!PSTUtil.isDefaultPST(pst)) {
699                     return Optional.of(pst);
700                 }
701             }
702         }
703         return Optional.absent();
704     }
705
706     private static PeerCapabilities getCapabilities(final Stateful stateful) {
707         final PeerCapabilities capa = new PeerCapabilities();
708         capa.setStateful(true);
709         if (stateful.isLspUpdateCapability() != null) {
710             capa.setActive(stateful.isLspUpdateCapability());
711         }
712         final Stateful1 stateful1 = stateful.getAugmentation(Stateful1.class);
713         if (stateful1 != null && stateful1.isInitiation() != null) {
714             capa.setInstantiation(stateful1.isInitiation());
715         }
716         return capa;
717     }
718
719     /**
720      * Recover lspData and mark any LSPs in the LSP database that were previously reported by the PCC as stale
721      * @param lspData
722      * @param lsps
723      * @param incrementalSynchro
724      */
725     @Override
726     protected synchronized void loadLspData(final Node node, final Map<String, ReportedLsp> lspData, final Map<PlspId, String> lsps, final boolean incrementalSynchro) {
727         //load node's lsps from DS
728         final PathComputationClient pcc = node.getAugmentation(Node1.class).getPathComputationClient();
729         final List<ReportedLsp> reportedLsps = pcc.getReportedLsp();
730         for (final ReportedLsp reportedLsp : reportedLsps) {
731             final String lspName = reportedLsp.getName();
732             lspData.put(lspName, reportedLsp);
733             if (!reportedLsp.getPath().isEmpty()) {
734                 final Path1 path1 = reportedLsp.getPath().get(0).getAugmentation(Path1.class);
735                 if (path1 != null) {
736                     final PlspId plspId = path1.getLsp().getPlspId();
737                     if (!incrementalSynchro) {
738                         this.staleLsps.add(plspId);
739                     }
740                     lsps.put(plspId, lspName);
741                 }
742             }
743         }
744     }
745
746     /**
747      * When the PCC reports an LSP during state synchronization, if the LSP already
748      * exists in the LSP database, the PCE MUST update the LSP database and
749      * clear the stale marker from the LSP
750      * @param plspId
751      */
752     private synchronized void unmarkStaleLsp(final PlspId plspId) {
753         this.staleLsps.remove(plspId);
754     }
755
756     /**
757      *  Purge any LSPs from the LSP database that are still marked as stale
758      * @param ctx
759      */
760     private synchronized void purgeStaleLsps(final MessageContext ctx) {
761         for (final PlspId plspId : this.staleLsps) {
762             removeLsp(ctx, plspId);
763         }
764         this.staleLsps.clear();
765     }
766 }