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