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