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