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