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