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