Merge "Added RFC 8040 URL, JSON payloads in flow examples"
[openflowplugin.git] / applications / arbitratorreconciliation / impl / src / main / java / org / opendaylight / openflowplugin / applications / arbitratorreconciliation / impl / ArbitratorReconciliationManagerImpl.java
1 /*
2  * Copyright (c) 2018 Ericsson India Global Services Pvt Ltd. 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
9 package org.opendaylight.openflowplugin.applications.arbitratorreconciliation.impl;
10
11 import com.google.common.base.Function;
12 import com.google.common.base.Preconditions;
13 import com.google.common.collect.ImmutableSet;
14 import com.google.common.util.concurrent.FutureCallback;
15 import com.google.common.util.concurrent.Futures;
16 import com.google.common.util.concurrent.ListenableFuture;
17 import com.google.common.util.concurrent.ListeningExecutorService;
18 import com.google.common.util.concurrent.MoreExecutors;
19 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
20 import java.util.ArrayList;
21 import java.util.Collections;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.concurrent.Callable;
25 import java.util.concurrent.ConcurrentHashMap;
26 import java.util.concurrent.ExecutionException;
27 import java.util.concurrent.Executors;
28 import java.util.concurrent.atomic.AtomicLong;
29 import javax.annotation.PostConstruct;
30 import javax.annotation.PreDestroy;
31 import javax.inject.Inject;
32 import javax.inject.Singleton;
33 import org.apache.aries.blueprint.annotation.service.Reference;
34 import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
35 import org.opendaylight.mdsal.binding.api.RpcProviderService;
36 import org.opendaylight.openflowplugin.api.OFConstants;
37 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
38 import org.opendaylight.openflowplugin.applications.reconciliation.NotificationRegistration;
39 import org.opendaylight.openflowplugin.applications.reconciliation.ReconciliationManager;
40 import org.opendaylight.openflowplugin.applications.reconciliation.ReconciliationNotificationListener;
41 import org.opendaylight.serviceutils.upgrade.UpgradeState;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupId;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupTypes;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupBuilder;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesInput;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesInputBuilder;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesOutput;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.ControlBundleInput;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.ControlBundleInputBuilder;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.ControlBundleOutput;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.SalBundleService;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.Messages;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.MessagesBuilder;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.messages.Message;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.messages.MessageBuilder;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleRemoveFlowCase;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleRemoveFlowCaseBuilder;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleRemoveGroupCase;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleRemoveGroupCaseBuilder;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.bundle.remove.flow._case.RemoveFlowCaseDataBuilder;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.bundle.remove.group._case.RemoveGroupCaseDataBuilder;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleControlType;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleFlags;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleId;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.app.arbitrator.reconcile.service.rev180227.ArbitratorReconcileService;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.app.arbitrator.reconcile.service.rev180227.CommitActiveBundleInput;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.app.arbitrator.reconcile.service.rev180227.CommitActiveBundleOutput;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.app.arbitrator.reconcile.service.rev180227.CommitActiveBundleOutputBuilder;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.app.arbitrator.reconcile.service.rev180227.GetActiveBundleInput;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.app.arbitrator.reconcile.service.rev180227.GetActiveBundleOutput;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.app.arbitrator.reconcile.service.rev180227.GetActiveBundleOutputBuilder;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.rf.state.rev170713.ResultState;
79 import org.opendaylight.yangtools.concepts.ObjectRegistration;
80 import org.opendaylight.yangtools.util.concurrent.FluentFutures;
81 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
82 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
83 import org.opendaylight.yangtools.yang.binding.RpcService;
84 import org.opendaylight.yangtools.yang.common.RpcError;
85 import org.opendaylight.yangtools.yang.common.RpcResult;
86 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
87 import org.opendaylight.yangtools.yang.common.Uint32;
88 import org.opendaylight.yangtools.yang.common.Uint64;
89 import org.slf4j.Logger;
90 import org.slf4j.LoggerFactory;
91
92 @Singleton
93 public class ArbitratorReconciliationManagerImpl implements ArbitratorReconcileService,
94         ReconciliationNotificationListener, AutoCloseable {
95
96     private static final Logger LOG = LoggerFactory.getLogger(ArbitratorReconciliationManagerImpl.class);
97     private static final int THREAD_POOL_SIZE = 4;
98     private static final AtomicLong BUNDLE_ID = new AtomicLong();
99     private static final BundleFlags BUNDLE_FLAGS = new BundleFlags(true, true);
100     private static final int ARBITRATOR_RECONCILIATION_PRIORITY = Integer
101             .getInteger("arbitrator.reconciliation.manager.priority", 0/*default*/);
102     private static final String SERVICE_NAME = "ArbitratorReconciliationManager";
103     private static final String SEPARATOR = ":";
104
105     private static final BundleRemoveFlowCase DELETE_ALL_FLOW = new BundleRemoveFlowCaseBuilder()
106             .setRemoveFlowCaseData(
107                     new RemoveFlowCaseDataBuilder(new FlowBuilder().setTableId(OFConstants.OFPTT_ALL).build()).build())
108             .build();
109     private static final BundleRemoveGroupCase DELETE_ALL_GROUP = new BundleRemoveGroupCaseBuilder()
110             .setRemoveGroupCaseData(new RemoveGroupCaseDataBuilder(new GroupBuilder()
111                     .setGroupType(GroupTypes.GroupAll)
112                     .setGroupId(new GroupId(OFConstants.OFPG_ALL))
113                     .build()).build())
114             .build();
115
116     private final SalBundleService salBundleService;
117     private final ReconciliationManager reconciliationManager;
118     private final RpcProviderService rpcProviderService;
119     private final UpgradeState upgradeState;
120     private NotificationRegistration registration;
121     private final ListeningExecutorService executor = MoreExecutors.listeningDecorator(
122             Executors.newFixedThreadPool(THREAD_POOL_SIZE));
123     private final Map<Uint64, BundleDetails> bundleIdMap = new ConcurrentHashMap<>();
124     private  ObjectRegistration<? extends RpcService> rpcRegistration;
125
126     @Inject
127     public ArbitratorReconciliationManagerImpl(
128             @Reference ReconciliationManager reconciliationManager, @Reference RpcProviderService rpcProviderService,
129             @Reference final RpcConsumerRegistry rpcRegistry, @Reference UpgradeState upgradeState) {
130         Preconditions.checkArgument(rpcRegistry != null, "RpcConsumerRegistry cannot be null !");
131         this.reconciliationManager = Preconditions.checkNotNull(reconciliationManager,
132                 "ReconciliationManager cannot be null!");
133         this.salBundleService = Preconditions.checkNotNull(rpcRegistry.getRpcService(SalBundleService.class),
134                 "RPC SalBundleService not found.");
135         this.rpcProviderService = rpcProviderService;
136         this.upgradeState = Preconditions.checkNotNull(upgradeState, "UpgradeState cannot be null!");
137     }
138
139     @PostConstruct
140     public void start() {
141         registration = reconciliationManager.registerService(this);
142         LOG.info("ArbitratorReconciliationManager has started successfully.");
143     }
144
145     @Override
146     @PreDestroy
147     public void close() throws Exception {
148         executor.shutdown();
149         if (registration != null) {
150             registration.close();
151             registration = null;
152         }
153     }
154
155     @Override
156     public ListenableFuture<RpcResult<CommitActiveBundleOutput>> commitActiveBundle(
157             CommitActiveBundleInput input) {
158         Uint64 nodeId = input.getNodeId();
159         if (bundleIdMap.containsKey(nodeId)) {
160             BundleId bundleId = bundleIdMap.get(nodeId).getBundleId();
161             if (bundleId != null) {
162                 final ControlBundleInput commitBundleInput = new ControlBundleInputBuilder()
163                         .setNode(input.getNode())
164                         .setBundleId(bundleId)
165                         .setFlags(BUNDLE_FLAGS)
166                         .setType(BundleControlType.ONFBCTCOMMITREQUEST)
167                         .build();
168                 ListenableFuture<RpcResult<ControlBundleOutput>> rpcResult = salBundleService
169                         .controlBundle(commitBundleInput);
170                 bundleIdMap.put(nodeId, new BundleDetails(bundleId, rpcResult));
171
172                 Futures.addCallback(rpcResult,
173                         new CommitActiveBundleCallback(nodeId),
174                         MoreExecutors.directExecutor());
175                 return Futures.transform(
176                         rpcResult,
177                         createRpcResultCondenser("committed active bundle"),
178                         MoreExecutors.directExecutor());
179             }
180         }
181         return RpcResultBuilder.success(new CommitActiveBundleOutputBuilder()
182                 .setResult(null).build())
183                 .withRpcErrors(Collections.singleton(RpcResultBuilder.newError(RpcError.ErrorType.APPLICATION,
184                         null, "No active bundle found for the node" + nodeId.toString()))).buildFuture();
185     }
186
187     @Override
188     public ListenableFuture<RpcResult<GetActiveBundleOutput>> getActiveBundle(final GetActiveBundleInput input) {
189         Uint64 nodeId = input.getNodeId();
190         BundleDetails bundleDetails = bundleIdMap.get(nodeId);
191         if (bundleDetails != null) {
192             try {
193                 //This blocking call is used to prevent the applications from pushing flows and groups via the default
194                 // pipeline when the commit bundle is ongoing.
195                 bundleDetails.getResult().get();
196                 return RpcResultBuilder.success(new GetActiveBundleOutputBuilder()
197                         .setResult(bundleDetails.getBundleId())
198                         .build())
199                         .buildFuture();
200             } catch (InterruptedException | ExecutionException | NullPointerException e) {
201                 return RpcResultBuilder.<GetActiveBundleOutput>failed()
202                         .withRpcErrors(Collections.singleton(RpcResultBuilder.newError(RpcError.ErrorType.APPLICATION,
203                                 null, e.getMessage()))).buildFuture();
204             }
205         }
206         return RpcResultBuilder.success(new GetActiveBundleOutputBuilder()
207                 .setResult(null).build()).buildFuture();
208     }
209
210     @Override
211     public ListenableFuture<Boolean> startReconciliation(DeviceInfo node) {
212         registerRpc(node);
213         if (upgradeState.isUpgradeInProgress()) {
214             LOG.trace("Starting arbitrator reconciliation for node {}", node.getDatapathId());
215             return reconcileConfiguration(node);
216         }
217         LOG.trace("arbitrator reconciliation is disabled");
218         return FluentFutures.immediateTrueFluentFuture();
219     }
220
221     @Override
222     public ListenableFuture<Boolean> endReconciliation(DeviceInfo node) {
223         Uint64 datapathId = node.getDatapathId();
224         LOG.trace("Stopping arbitrator reconciliation for node {}", datapathId);
225         bundleIdMap.remove(datapathId);
226         deregisterRpc(node);
227         return FluentFutures.immediateTrueFluentFuture();
228     }
229
230     @Override
231     public int getPriority() {
232         return ARBITRATOR_RECONCILIATION_PRIORITY;
233     }
234
235     @Override
236     public String getName() {
237         return SERVICE_NAME;
238     }
239
240     @Override
241     public ResultState getResultState() {
242         return ResultState.DONOTHING;
243     }
244
245     private ListenableFuture<Boolean> reconcileConfiguration(DeviceInfo node) {
246         LOG.info("Triggering arbitrator reconciliation for device {}", node.getDatapathId());
247         ArbitratorReconciliationTask upgradeReconTask = new ArbitratorReconciliationTask(node);
248         return executor.submit(upgradeReconTask);
249     }
250
251     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
252             justification = "https://github.com/spotbugs/spotbugs/issues/811")
253     private static Messages createMessages(final NodeRef nodeRef) {
254         final List<Message> messages = new ArrayList<>();
255         messages.add(new MessageBuilder()
256                 .setNode(nodeRef)
257                 .setBundleInnerMessage(DELETE_ALL_FLOW).build());
258         messages.add(new MessageBuilder()
259                 .setNode(nodeRef)
260                 .setBundleInnerMessage(DELETE_ALL_GROUP).build());
261         LOG.debug("The size of the flows and group messages created in createMessage() {}", messages.size());
262         return new MessagesBuilder().setMessage(messages).build();
263     }
264
265     private class ArbitratorReconciliationTask implements Callable<Boolean> {
266         final DeviceInfo deviceInfo;
267
268         ArbitratorReconciliationTask(final DeviceInfo deviceInfo) {
269             this.deviceInfo = deviceInfo;
270         }
271
272         @Override
273         public Boolean call() {
274             InstanceIdentifier<FlowCapableNode> nodeIdentity = deviceInfo.getNodeInstanceIdentifier()
275                     .augmentation(FlowCapableNode.class);
276             String node = nodeIdentity.firstKeyOf(Node.class).getId().getValue();
277             BundleId bundleIdValue = new BundleId(Uint32.valueOf(BUNDLE_ID.getAndIncrement()));
278             LOG.debug("Triggering arbitrator reconciliation for device :{}", node);
279             final NodeRef nodeRef = new NodeRef(nodeIdentity.firstIdentifierOf(Node.class));
280
281             final ControlBundleInput closeBundleInput = new ControlBundleInputBuilder()
282                     .setNode(nodeRef)
283                     .setBundleId(bundleIdValue)
284                     .setFlags(BUNDLE_FLAGS)
285                     .setType(BundleControlType.ONFBCTCLOSEREQUEST)
286                     .build();
287
288             final ControlBundleInput openBundleInput = new ControlBundleInputBuilder()
289                     .setNode(nodeRef)
290                     .setBundleId(bundleIdValue)
291                     .setFlags(BUNDLE_FLAGS)
292                     .setType(BundleControlType.ONFBCTOPENREQUEST)
293                     .build();
294
295             final AddBundleMessagesInput addBundleMessagesInput = new AddBundleMessagesInputBuilder()
296                     .setNode(nodeRef)
297                     .setBundleId(bundleIdValue)
298                     .setFlags(BUNDLE_FLAGS)
299                     .setMessages(createMessages(nodeRef))
300                     .build();
301
302             ListenableFuture<RpcResult<ControlBundleOutput>> closeBundle = salBundleService
303                     .controlBundle(closeBundleInput);
304
305             ListenableFuture<RpcResult<ControlBundleOutput>> openBundleMessagesFuture = Futures
306                     .transformAsync(closeBundle, rpcResult -> salBundleService
307                             .controlBundle(openBundleInput), MoreExecutors.directExecutor());
308
309             ListenableFuture<RpcResult<AddBundleMessagesOutput>> addBundleMessagesFuture = Futures
310                     .transformAsync(openBundleMessagesFuture, rpcResult -> {
311                         if (rpcResult.isSuccessful()) {
312                             return salBundleService
313                                     .addBundleMessages(addBundleMessagesInput);
314                         }
315                         return FluentFutures.immediateNullFluentFuture();
316                     }, MoreExecutors.directExecutor());
317             Uint64 nodeId = getDpnIdFromNodeName(node);
318             try {
319                 if (addBundleMessagesFuture.get().isSuccessful()) {
320                     bundleIdMap.put(nodeId, new BundleDetails(bundleIdValue,FluentFutures.immediateNullFluentFuture()));
321                     LOG.debug("Arbitrator reconciliation initial task has been completed for node {} ", nodeId);
322                     return true;
323                 } else {
324                     LOG.error("Error while performing arbitrator reconciliation for device:{}", nodeId);
325                     return false;
326                 }
327             } catch (InterruptedException | ExecutionException e) {
328                 LOG.error("Error while performing arbitrator reconciliation for device:{}", nodeId, e);
329                 return false;
330             }
331         }
332     }
333
334     public final class CommitActiveBundleCallback implements FutureCallback<RpcResult<?>> {
335         private final Uint64 nodeId;
336
337         private CommitActiveBundleCallback(final Uint64 nodeId) {
338             this.nodeId = nodeId;
339         }
340
341         @Override
342         public void onSuccess(RpcResult<?> rpcResult) {
343             LOG.debug("Completed arbitrator reconciliation for device:{}", nodeId);
344             bundleIdMap.remove(nodeId);
345         }
346
347         @Override
348         public void onFailure(Throwable throwable) {
349             LOG.error("Error while performing arbitrator reconciliation for device {}", nodeId, throwable);
350         }
351     }
352
353     private static <D> Function<RpcResult<D>,
354             RpcResult<CommitActiveBundleOutput>> createRpcResultCondenser(final String action) {
355         return input -> {
356             final RpcResultBuilder<CommitActiveBundleOutput> resultSink;
357             if (input != null) {
358                 List<RpcError> errors = new ArrayList<>();
359                 if (!input.isSuccessful()) {
360                     errors.addAll(input.getErrors());
361                     resultSink = RpcResultBuilder.<CommitActiveBundleOutput>failed().withRpcErrors(errors);
362                 } else {
363                     resultSink = RpcResultBuilder.success();
364                 }
365             } else {
366                 resultSink = RpcResultBuilder.<CommitActiveBundleOutput>failed()
367                         .withError(RpcError.ErrorType.APPLICATION, "action of " + action + " failed");
368             }
369             return resultSink.build();
370         };
371     }
372
373     private void registerRpc(DeviceInfo node) {
374         KeyedInstanceIdentifier<Node, NodeKey> path = InstanceIdentifier.create(Nodes.class)
375                 .child(Node.class, new NodeKey(node.getNodeId()));
376         LOG.debug("The path is registered : {}", path);
377         rpcRegistration = rpcProviderService.registerRpcImplementation(ArbitratorReconcileService.class,
378                 this, ImmutableSet.of(path));
379     }
380
381     private void deregisterRpc(DeviceInfo node) {
382         KeyedInstanceIdentifier<Node, NodeKey> path = InstanceIdentifier.create(Nodes.class)
383                 .child(Node.class, new NodeKey(node.getNodeId()));
384         LOG.debug("The path is unregistered : {}", path);
385         if (rpcRegistration != null) {
386             rpcRegistration.close();
387         }
388     }
389
390     private static class BundleDetails {
391         private final BundleId bundleId;
392         private final ListenableFuture<RpcResult<ControlBundleOutput>> result;
393
394         BundleDetails(BundleId bundleId, ListenableFuture<RpcResult<ControlBundleOutput>> result) {
395             this.bundleId = bundleId;
396             this.result = result;
397         }
398
399         public BundleId getBundleId() {
400             return bundleId;
401         }
402
403         public ListenableFuture<RpcResult<ControlBundleOutput>> getResult() {
404             return result;
405         }
406     }
407
408     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
409             justification = "https://github.com/spotbugs/spotbugs/issues/811")
410     private static Uint64 getDpnIdFromNodeName(String nodeName) {
411         String dpnId = nodeName.substring(nodeName.lastIndexOf(SEPARATOR) + 1);
412         return Uint64.valueOf(dpnId);
413     }
414 }