BUG-139: PCE-triggered Initial State Synchronization Procedure
[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.TriggerInitialSyncArgs;
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      * when PCE-triggered Initial State Synchronization Procedure is set during the session establishment, PCC will
138      * wait arrival of PCUpd message with PLSP-ID = 0 and SYNC = 1 in order to trigger the LSP-DB synchronization
139      * process.
140      * @param input
141      * @return
142      */
143     @Override
144     public synchronized ListenableFuture<OperationResult> triggerInitialSync(final TriggerInitialSyncArgs input) {
145         if(isTriggeredInitialSynchro() && !isSynchronized()) {
146             final PcupdMessageBuilder pcupdMessageBuilder = new PcupdMessageBuilder(MESSAGE_HEADER);
147             final SrpIdNumber srpIdNumber = createUpdateMessageSync(pcupdMessageBuilder);
148             final Message msg = new PcupdBuilder().setPcupdMessage(pcupdMessageBuilder.build()).build();
149             // Send the message
150             return sendMessage(msg, srpIdNumber, null);
151         }
152         return OperationResults.UNSENT.future();
153     }
154
155     private SrpIdNumber createUpdateMessageSync(final PcupdMessageBuilder pcupdMessageBuilder) {
156         final UpdatesBuilder updBuilder = new UpdatesBuilder();
157         // LSP mandatory in Upd
158         final Lsp lsp = new LspBuilder().setPlspId(new PlspId(0L)).setSync(Boolean.TRUE).build();
159         // SRP Mandatory in Upd
160         final SrpBuilder srpBuilder = new SrpBuilder();
161         // not sue wheter use 0 instead of nextRequest() or dont  insert srp == SRP-ID-number = 0
162         srpBuilder.setOperationId(nextRequest());
163         final Srp srp = srpBuilder.build();
164         //ERO Mandatory in Upd
165         final PathBuilder pb = new PathBuilder();
166         pb.setEro(new EroBuilder().build());
167
168         updBuilder.setPath(pb.build());
169         updBuilder.setLsp(lsp).setSrp(srp).setPath(pb.build());
170
171         pcupdMessageBuilder.setUpdates(Collections.singletonList(updBuilder.build()));
172         return srp.getOperationId();
173     }
174
175     private boolean handleErrorMessage(final PcerrMessage message) {
176         final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.pcerr.message.PcerrMessage errMsg = message.getPcerrMessage();
177         if (errMsg.getErrorType() instanceof StatefulCase) {
178             final StatefulCase stat = (StatefulCase)errMsg.getErrorType();
179             for (final Srps srps : stat.getStateful().getSrps()) {
180                 final SrpIdNumber id = srps.getSrp().getOperationId();
181                 if (id.getValue() != 0) {
182                     final PCEPRequest req = removeRequest(id);
183                     if (req != null) {
184                         req.done(OperationResults.createFailed(errMsg.getErrors()));
185                     } else {
186                         LOG.warn("Request ID {} not found in outstanding DB", id);
187                     }
188                 }
189             }
190         } else {
191             LOG.warn("Unhandled PCErr message {}.", errMsg);
192             return true;
193         }
194         return false;
195     }
196
197     private boolean isSolicited(final Srp srp, final Lsp lsp, final MessageContext ctx, final ReportedLspBuilder rlb) {
198         if (srp == null) {
199             return false;
200         }
201         final SrpIdNumber id = srp.getOperationId();
202         if (id.getValue() == 0) {
203             return false;
204         }
205         switch (lsp.getOperational()) {
206         case Active:
207         case Down:
208         case Up:
209             final PCEPRequest req = removeRequest(id);
210             if (req != null) {
211                 LOG.debug("Request {} resulted in LSP operational state {}", id, lsp.getOperational());
212                 rlb.setMetadata(req.getMetadata());
213                 ctx.resolveRequest(req);
214             } else {
215                 LOG.warn("Request ID {} not found in outstanding DB", id);
216             }
217             break;
218         case GoingDown:
219         case GoingUp:
220             // These are transitive states, so we don't have to do anything, as they will be followed
221             // up...
222             break;
223         default:
224             break;
225         }
226         return true;
227     }
228
229     private boolean manageNextReport(final Reports report, final MessageContext ctx) {
230         final Lsp lsp = report.getLsp();
231         final PlspId plspid = lsp.getPlspId();
232         if (!lsp.isSync() && (plspid == null || plspid.getValue() == 0)) {
233             purgeStaleLsps(ctx);
234             stateSynchronizationAchieved(ctx);
235             return true;
236         }
237         final ReportedLspBuilder rlb = new ReportedLspBuilder();
238         boolean solicited = false;
239         final Srp srp = report.getSrp();
240         solicited = isSolicited(srp, lsp, ctx, rlb);
241
242         // if remove flag is set in SRP object, remove the tunnel immediately
243         if (solicited && srp.getAugmentation(Srp1.class) != null) {
244             final Srp1 initiatedSrp = srp.getAugmentation(Srp1.class);
245             if (initiatedSrp.isRemove()) {
246                 super.removeLsp(ctx, plspid);
247                 return false;
248             }
249         }
250         rlb.setPath(Collections.singletonList(buildPath(report, srp, lsp)));
251
252         String name = lookupLspName(plspid);
253         if (lsp.getTlvs() != null && lsp.getTlvs().getSymbolicPathName() != null) {
254             name = Charsets.UTF_8.decode(ByteBuffer.wrap(lsp.getTlvs().getSymbolicPathName().getPathName().getValue())).toString();
255         }
256         //get LspDB from LSP and write it to pcc's node
257         final LspDbVersion lspDbVersion = geLspDbVersionTlv(lsp);
258         if (lspDbVersion != null) {
259             updatePccNode(ctx, new PathComputationClientBuilder().addAugmentation(PathComputationClient1.class,
260                     new PathComputationClient1Builder().setLspDbVersion(lspDbVersion).build()).build());
261         }
262         updateLsp(ctx, plspid, name, rlb, solicited, lsp.isRemove());
263         unmarkStaleLsp(plspid, lsp.isSync());
264
265         LOG.debug("LSP {} updated", lsp);
266         return true;
267     }
268
269     private static LspDbVersion geLspDbVersionTlv(final Lsp lsp) {
270         final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp.object.lsp.Tlvs tlvs = lsp.getTlvs();
271         if (tlvs != null && tlvs.getAugmentation(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714.Tlvs1.class) != null) {
272             return tlvs.getAugmentation(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714.Tlvs1.class).getLspDbVersion();
273         }
274         return null;
275     }
276
277     private Path buildPath(final Reports report, final Srp srp, final Lsp lsp) {
278         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();
279         if (report.getPath() != null) {
280             pb.fieldsFrom(report.getPath());
281         }
282         // LSP is mandatory (if there is none, parser will throw an exception)
283         // this is to ensure a path will be created at any rate
284         final Path1Builder p1Builder = new Path1Builder();
285         p1Builder.setLsp(report.getLsp());
286         final PathSetupType pst;
287         if (srp != null && srp.getTlvs() != null && srp.getTlvs().getPathSetupType() != null) {
288             pst = srp.getTlvs().getPathSetupType();
289             p1Builder.setPathSetupType(pst);
290         } else {
291             pst = null;
292         }
293         pb.addAugmentation(Path1.class, p1Builder.build());
294         final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp.object.lsp.Tlvs tlvs = report.getLsp().getTlvs();
295         if (tlvs != null) {
296             if (tlvs.getLspIdentifiers() != null) {
297                 pb.setLspId(tlvs.getLspIdentifiers().getLspId());
298             } else if (!isDefaultPST(pst)) {
299                 pb.setLspId(new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev150820.LspId(lsp.getPlspId().getValue()));
300             }
301         }
302         return pb.build();
303     }
304
305     @Override
306     protected boolean onMessage(final MessageContext ctx, final Message message) {
307         if (message instanceof PcerrMessage) {
308             return handleErrorMessage((PcerrMessage) message);
309         }
310         if (!(message instanceof PcrptMessage)) {
311             return true;
312         }
313         getSessionListenerState().updateLastReceivedRptMsg();
314         final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.pcrpt.message.PcrptMessage rpt = ((PcrptMessage) message).getPcrptMessage();
315         for (final Reports report : rpt.getReports()) {
316             if (!manageNextReport(report, ctx)) {
317                 return false;
318             }
319         }
320         return false;
321     }
322
323     private SrpIdNumber nextRequest() {
324         return new SrpIdNumber(this.requestId.getAndIncrement());
325     }
326
327     private class AddFunction implements AsyncFunction<Optional<ReportedLsp>, OperationResult>  {
328
329         private final AddLspArgs input;
330         private final InstanceIdentifier<ReportedLsp> lsp;
331
332         public AddFunction(final AddLspArgs input, final InstanceIdentifier<ReportedLsp> lsp) {
333             this.input = input;
334             this.lsp = lsp;
335         }
336
337         @Override
338         public ListenableFuture<OperationResult> apply(final Optional<ReportedLsp> rep) {
339             if (rep.isPresent()) {
340                 LOG.debug("Node {} already contains lsp {} at {}", this.input.getNode(), this.input.getName(), this.lsp);
341                 return OperationResults.createUnsent(PCEPErrors.USED_SYMBOLIC_PATH_NAME).future();
342             }
343             if (!getPeerCapabilities().getInstantiation()) {
344                 return OperationResults.createUnsent(PCEPErrors.CAPABILITY_NOT_SUPPORTED).future();
345             }
346
347             // Build the request
348             final RequestsBuilder rb = new RequestsBuilder();
349             final Arguments2 args = this.input.getArguments().getAugmentation(Arguments2.class);
350             Preconditions.checkArgument(args != null, "Input is missing operational tag.");
351             final Lsp inputLsp = args.getLsp();
352             Preconditions.checkArgument(inputLsp != null, "Reported LSP does not contain LSP object.");
353
354             rb.fieldsFrom(this.input.getArguments());
355
356             final TlvsBuilder tlvsBuilder;
357             if (inputLsp.getTlvs() != null) {
358                 tlvsBuilder = new TlvsBuilder(inputLsp.getTlvs());
359             } else {
360                 tlvsBuilder = new TlvsBuilder();
361             }
362             tlvsBuilder.setSymbolicPathName(
363                 new SymbolicPathNameBuilder().setPathName(new SymbolicPathName(this.input.getName().getBytes(Charsets.UTF_8))).build());
364
365             final SrpBuilder srpBuilder = new SrpBuilder();
366             srpBuilder.setOperationId(nextRequest());
367             srpBuilder.setProcessingRule(Boolean.TRUE);
368             if (!isDefaultPST(args.getPathSetupType())) {
369                 srpBuilder.setTlvs(
370                         new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.srp.object.srp.TlvsBuilder()
371                             .setPathSetupType(args.getPathSetupType()).build());
372             }
373             rb.setSrp(srpBuilder.build());
374
375             rb.setLsp(new LspBuilder().setAdministrative(inputLsp.isAdministrative()).setDelegate(inputLsp.isDelegate()).setPlspId(
376                 new PlspId(0L)).setTlvs(tlvsBuilder.build()).build());
377
378             final PcinitiateMessageBuilder ib = new PcinitiateMessageBuilder(MESSAGE_HEADER);
379             ib.setRequests(Collections.singletonList(rb.build()));
380
381             // Send the message
382             return sendMessage(new PcinitiateBuilder().setPcinitiateMessage(ib.build()).build(), rb.getSrp().getOperationId(),
383                 this.input.getArguments().getMetadata());
384         }
385     }
386
387     @Override
388     public synchronized ListenableFuture<OperationResult> addLsp(final AddLspArgs input) {
389         Preconditions.checkArgument(input != null && input.getName() != null && input.getNode() != null && input.getArguments() != null, MISSING_XML_TAG);
390         LOG.trace("AddLspArgs {}", input);
391         // Make sure there is no such LSP
392         final InstanceIdentifier<ReportedLsp> lsp = lspIdentifier(input.getName());
393         final ListenableFuture<Optional<ReportedLsp>> f = readOperationalData(lsp);
394         if (f == null) {
395             return OperationResults.createUnsent(PCEPErrors.LSP_INTERNAL_ERROR).future();
396         }
397         return Futures.transform(f, new AddFunction(input, lsp));
398     }
399
400     @Override
401     public synchronized ListenableFuture<OperationResult> removeLsp(final RemoveLspArgs input) {
402         Preconditions.checkArgument(input != null && input.getName() != null && input.getNode() != null, MISSING_XML_TAG);
403         LOG.trace("RemoveLspArgs {}", input);
404         // Make sure the LSP exists, we need it for PLSP-ID
405         final InstanceIdentifier<ReportedLsp> lsp = lspIdentifier(input.getName());
406         final ListenableFuture<Optional<ReportedLsp>> f = readOperationalData(lsp);
407         if (f == null) {
408             return OperationResults.createUnsent(PCEPErrors.LSP_INTERNAL_ERROR).future();
409         }
410         return Futures.transform(f, new AsyncFunction<Optional<ReportedLsp>, OperationResult>() {
411             @Override
412             public ListenableFuture<OperationResult> apply(final Optional<ReportedLsp> rep) {
413                 final Lsp reportedLsp = validateReportedLsp(rep, input);
414                 if (reportedLsp == null) {
415                     return OperationResults.createUnsent(PCEPErrors.UNKNOWN_PLSP_ID).future();
416                 }
417                 final PcinitiateMessageBuilder ib = new PcinitiateMessageBuilder(MESSAGE_HEADER);
418                 final Requests rb = buildRequest(rep, reportedLsp);
419                 ib.setRequests(Collections.singletonList(rb));
420                 return sendMessage(new PcinitiateBuilder().setPcinitiateMessage(ib.build()).build(), rb.getSrp().getOperationId(), null);
421             }
422         });
423     }
424
425     private Requests buildRequest(final Optional<ReportedLsp> rep, final Lsp reportedLsp) {
426         // Build the request and send it
427         final RequestsBuilder rb = new RequestsBuilder();
428         final SrpBuilder srpBuilder = new SrpBuilder().addAugmentation(Srp1.class, new Srp1Builder().setRemove(Boolean.TRUE).build()).setOperationId(nextRequest()).setProcessingRule(Boolean.TRUE);
429         final Optional<PathSetupType> maybePST = getPST(rep);
430         if (maybePST.isPresent()) {
431             srpBuilder.setTlvs(new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.srp.object.srp.TlvsBuilder()
432                 .setPathSetupType(maybePST.get())
433                 .build());
434         }
435         rb.setSrp(srpBuilder.build());
436         rb.setLsp(new LspBuilder().setRemove(Boolean.FALSE).setPlspId(reportedLsp.getPlspId()).setDelegate(reportedLsp.isDelegate()).build());
437         return rb.build();
438     }
439
440     private class UpdateFunction implements AsyncFunction<Optional<ReportedLsp>, OperationResult>  {
441
442         private final UpdateLspArgs input;
443
444         public UpdateFunction(final UpdateLspArgs input) {
445             this.input = input;
446         }
447
448         @Override
449         public ListenableFuture<OperationResult> apply(final Optional<ReportedLsp> rep) {
450             final Lsp reportedLsp = validateReportedLsp(rep, this.input);
451             if (reportedLsp == null) {
452                 return OperationResults.createUnsent(PCEPErrors.UNKNOWN_PLSP_ID).future();
453             }
454             // create mandatory objects
455             final Arguments3 args = this.input.getArguments().getAugmentation(Arguments3.class);
456             final SrpBuilder srpBuilder = new SrpBuilder();
457             srpBuilder.setOperationId(nextRequest());
458             srpBuilder.setProcessingRule(Boolean.TRUE);
459             if (args != null && args.getPathSetupType() != null) {
460                 if (!isDefaultPST(args.getPathSetupType())) {
461                     srpBuilder.setTlvs(
462                             new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.srp.object.srp.TlvsBuilder()
463                                 .setPathSetupType(args.getPathSetupType()).build());
464                 }
465             } else {
466                 final Optional<PathSetupType> maybePST = getPST(rep);
467                 if (maybePST.isPresent()) {
468                     srpBuilder.setTlvs(
469                             new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.srp.object.srp.TlvsBuilder()
470                                 .setPathSetupType(maybePST.get()).build());
471                 }
472             }
473             final Srp srp = srpBuilder.build();
474             final Lsp inputLsp = args.getLsp();
475             final Lsp lsp = (inputLsp != null) ?
476                 new LspBuilder().setPlspId(reportedLsp.getPlspId()).setDelegate((inputLsp.isDelegate() != null) ? inputLsp.isDelegate() : false).setTlvs(inputLsp.getTlvs()).setAdministrative((inputLsp.isAdministrative() != null) ? inputLsp.isAdministrative() : false).build()
477                 : new LspBuilder().setPlspId(reportedLsp.getPlspId()).build();
478             final Message msg = redelegate(reportedLsp.isDelegate(), srp, lsp, this.input);
479             return sendMessage(msg, srp.getOperationId(), this.input.getArguments().getMetadata());
480         }
481     }
482
483     private Message redelegate(final Boolean isDelegate, final Srp srp, final Lsp lsp, final UpdateLspArgs input) {
484         // the D bit that was reported decides the type of PCE message sent
485         Preconditions.checkNotNull(isDelegate);
486         if (isDelegate) {
487             // we already have delegation, send update
488             final UpdatesBuilder rb = new UpdatesBuilder();
489             rb.setSrp(srp);
490             rb.setLsp(lsp);
491             final PathBuilder pb = new PathBuilder();
492             pb.fieldsFrom(input.getArguments());
493             rb.setPath(pb.build());
494             final PcupdMessageBuilder ub = new PcupdMessageBuilder(MESSAGE_HEADER);
495             ub.setUpdates(Collections.singletonList(rb.build()));
496             return new PcupdBuilder().setPcupdMessage(ub.build()).build();
497         }
498         // we want to revoke delegation, different type of message
499         // is sent because of specification by Siva
500         // this message is also sent, when input delegate bit is set to 0
501         // generating an error in PCC
502         final List<Requests> reqs = new ArrayList<>();
503         reqs.add(new RequestsBuilder().setSrp(srp).setLsp(lsp).build());
504         final PcinitiateMessageBuilder ib = new PcinitiateMessageBuilder();
505         ib.setRequests(reqs);
506         return new PcinitiateBuilder().setPcinitiateMessage(ib.build()).build();
507     }
508
509     @Override
510     public synchronized ListenableFuture<OperationResult> updateLsp(final UpdateLspArgs input) {
511         Preconditions.checkArgument(input != null && input.getName() != null && input.getNode() != null && input.getArguments() != null, MISSING_XML_TAG);
512         LOG.trace("UpdateLspArgs {}", input);
513         // Make sure the LSP exists
514         final InstanceIdentifier<ReportedLsp> lsp = lspIdentifier(input.getName());
515         final ListenableFuture<Optional<ReportedLsp>> f = readOperationalData(lsp);
516         if (f == null) {
517             return OperationResults.createUnsent(PCEPErrors.LSP_INTERNAL_ERROR).future();
518         }
519         return Futures.transform(f, new UpdateFunction(input));
520     }
521
522     @Override
523     public synchronized ListenableFuture<OperationResult> ensureLspOperational(final EnsureLspOperationalInput input) {
524         Preconditions.checkArgument(input != null && input.getName() != null && input.getNode() != null && input.getArguments() != null, MISSING_XML_TAG);
525         final OperationalStatus op;
526         final Arguments1 aa = input.getArguments().getAugmentation(Arguments1.class);
527         if (aa != null) {
528             op = aa.getOperational();
529         } else {
530             op = null;
531         }
532
533         // Make sure the LSP exists
534         final InstanceIdentifier<ReportedLsp> lsp = lspIdentifier(input.getName());
535         LOG.debug("Checking if LSP {} has operational state {}", lsp, op);
536         final ListenableFuture<Optional<ReportedLsp>> f = readOperationalData(lsp);
537         if (f == null) {
538             return OperationResults.createUnsent(PCEPErrors.LSP_INTERNAL_ERROR).future();
539         }
540         return listenableFuture(f, input, op);
541     }
542
543     private ListenableFuture<OperationResult> listenableFuture(final ListenableFuture<Optional<ReportedLsp>> f, final EnsureLspOperationalInput input, final OperationalStatus op) {
544         return Futures.transform(f, new Function<Optional<ReportedLsp>, OperationResult>() {
545             @Override
546             public OperationResult apply(final Optional<ReportedLsp> rep) {
547                 if (!rep.isPresent()) {
548                     LOG.debug("Node {} does not contain LSP {}", input.getNode(), input.getName());
549                     return OperationResults.UNSENT;
550                 }
551                 // check if at least one of the paths has the same status as requested
552                 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()) {
553                     final Path1 p1 = p.getAugmentation(Path1.class);
554                     if (p1 == null) {
555                         LOG.warn("Node {} LSP {} does not contain data", input.getNode(), input.getName());
556                         return OperationResults.UNSENT;
557                     }
558                     if (op.equals(p1.getLsp().getOperational())) {
559                         return OperationResults.SUCCESS;
560                     }
561                 }
562                 return OperationResults.UNSENT;
563             }
564         });
565     }
566
567     @Override
568     protected Lsp validateReportedLsp(final Optional<ReportedLsp> rep, final LspId input) {
569         if (!rep.isPresent()) {
570             LOG.debug("Node {} does not contain LSP {}", input.getNode(), input.getName());
571             return null;
572         }
573         // it doesn't matter how many lsps there are in the path list, we only need data that is the same in each path
574         final Path1 ra = rep.get().getPath().get(0).getAugmentation(Path1.class);
575         Preconditions.checkState(ra != null, "Reported LSP reported null from data-store.");
576         final Lsp reportedLsp = ra.getLsp();
577         Preconditions.checkState(reportedLsp != null, "Reported LSP does not contain LSP object.");
578         return reportedLsp;
579     }
580
581     private Optional<PathSetupType> getPST(final Optional<ReportedLsp> rep) {
582         if (rep.isPresent()) {
583             final Path1 path1 = rep.get().getPath().get(0).getAugmentation(Path1.class);
584             if (path1 != null) {
585                 final PathSetupType pst = path1.getPathSetupType();
586                 if (!isDefaultPST(pst)) {
587                     return Optional.of(pst);
588                 }
589             }
590         }
591         return Optional.absent();
592     }
593
594     private static boolean isDefaultPST(final PathSetupType pst) {
595         if (pst != null && pst.getPst() != null && pst.getPst().shortValue() != 0) {
596             return false;
597         }
598         return true;
599     }
600
601     private static PeerCapabilities getCapabilities(final Stateful stateful) {
602         final PeerCapabilities capa = new PeerCapabilities();
603         capa.setStateful(true);
604         if (stateful.isLspUpdateCapability() != null) {
605             capa.setActive(stateful.isLspUpdateCapability());
606         }
607         final Stateful1 stateful1 = stateful.getAugmentation(Stateful1.class);
608         if (stateful1 != null && stateful1.isInitiation() != null) {
609             capa.setInstantiation(stateful1.isInitiation());
610         }
611         return capa;
612     }
613
614     /**
615      * Recover lspData and mark any LSPs in the LSP database that were previously reported by the PCC as stale
616      * @param lspData
617      * @param lsps
618      * @param incrementalSynchro
619      */
620     @Override
621     protected synchronized void loadLspData(final Node node, final Map<String, ReportedLsp> lspData, final Map<PlspId, String> lsps, final boolean incrementalSynchro) {
622         //load node's lsps from DS
623         final PathComputationClient pcc = node.getAugmentation(Node1.class).getPathComputationClient();
624         final List<ReportedLsp> reportedLsps = pcc.getReportedLsp();
625         for (final ReportedLsp reportedLsp : reportedLsps) {
626             final String lspName = reportedLsp.getName();
627             lspData.put(lspName, reportedLsp);
628             if (!reportedLsp.getPath().isEmpty()) {
629                 final Path1 path1 = reportedLsp.getPath().get(0).getAugmentation(Path1.class);
630                 if (path1 != null) {
631                     final PlspId plspId = path1.getLsp().getPlspId();
632                     if (!incrementalSynchro) {
633                         staleLsps.add(plspId);
634                     }
635                     lsps.put(plspId, lspName);
636                 }
637             }
638         }
639     }
640
641     /**
642      * When the PCC reports an LSP during state synchronization, if the LSP already
643      * exists in the LSP database, the PCE MUST update the LSP database and
644      * clear the stale marker from the LSP
645      * @param plspId
646      * @param sync
647      */
648     private synchronized void unmarkStaleLsp(final PlspId plspId, final boolean sync) {
649         if (!sync) {
650             staleLsps.remove(plspId);
651         }
652     }
653
654     /**
655      *  Purge any LSPs from the LSP database that are still marked as stale
656      * @param ctx
657      */
658     private synchronized void purgeStaleLsps(final MessageContext ctx) {
659         for (final PlspId plspId : staleLsps) {
660             removeLsp(ctx, plspId);
661         }
662         staleLsps.clear();
663     }
664 }