Switch to MD-SAL APIs
[openflowplugin.git] / applications / forwardingrules-manager / src / main / java / org / opendaylight / openflowplugin / applications / frm / impl / ForwardingRulesManagerImpl.java
1 /*
2  * Copyright (c) 2014, 2017 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.openflowplugin.applications.frm.impl;
9
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.Preconditions;
12 import com.google.common.util.concurrent.ListenableFuture;
13 import java.util.Objects;
14 import java.util.Optional;
15 import java.util.concurrent.ExecutionException;
16 import java.util.concurrent.atomic.AtomicLong;
17 import javax.annotation.Nonnull;
18 import javax.annotation.PostConstruct;
19 import javax.annotation.PreDestroy;
20 import javax.inject.Inject;
21 import javax.inject.Singleton;
22 import org.apache.aries.blueprint.annotation.service.Reference;
23 import org.opendaylight.mdsal.binding.api.DataBroker;
24 import org.opendaylight.mdsal.binding.api.ReadTransaction;
25 import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
26 import org.opendaylight.mdsal.binding.api.RpcProviderService;
27 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
28 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
29 import org.opendaylight.openflowplugin.api.openflow.configuration.ConfigurationService;
30 import org.opendaylight.openflowplugin.api.openflow.mastership.MastershipChangeServiceManager;
31 import org.opendaylight.openflowplugin.applications.frm.FlowNodeReconciliation;
32 import org.opendaylight.openflowplugin.applications.frm.ForwardingRulesCommiter;
33 import org.opendaylight.openflowplugin.applications.frm.ForwardingRulesManager;
34 import org.opendaylight.openflowplugin.applications.frm.ForwardingRulesProperty;
35 import org.opendaylight.openflowplugin.applications.frm.NodeConfigurator;
36 import org.opendaylight.openflowplugin.applications.frm.nodeconfigurator.NodeConfiguratorImpl;
37 import org.opendaylight.openflowplugin.applications.frm.recovery.OpenflowServiceRecoveryHandler;
38 import org.opendaylight.openflowplugin.applications.reconciliation.NotificationRegistration;
39 import org.opendaylight.openflowplugin.applications.reconciliation.ReconciliationManager;
40 import org.opendaylight.serviceutils.srm.RecoverableListener;
41 import org.opendaylight.serviceutils.srm.ServiceRecoveryRegistry;
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.meters.Meter;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.SalFlowService;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.SalGroupService;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.SalMeterService;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.SalBundleService;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.app.arbitrator.reconcile.service.rev180227.ArbitratorReconcileService;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.app.forwardingrules.manager.config.rev160511.ForwardingRulesManagerConfig;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.rf.state.rev170713.ResultState;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026.SalTableService;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeatures;
56 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
59
60 /**
61  * forwardingrules-manager org.opendaylight.openflowplugin.applications.frm.impl
62  *
63  * <p>
64  * Manager and middle point for whole module. It contains ActiveNodeHolder and
65  * provide all RPC services.
66  *
67  */
68 @Singleton
69 public class ForwardingRulesManagerImpl implements ForwardingRulesManager {
70     private static final Logger LOG = LoggerFactory.getLogger(ForwardingRulesManagerImpl.class);
71
72     static final int STARTUP_LOOP_TICK = 500;
73     static final int STARTUP_LOOP_MAX_RETRIES = 8;
74     private static final int FRM_RECONCILIATION_PRIORITY = Integer.getInteger("frm.reconciliation.priority", 1);
75     private static final String SERVICE_NAME = "FRM";
76
77     private final AtomicLong txNum = new AtomicLong();
78     private final DataBroker dataService;
79     private final SalFlowService salFlowService;
80     private final SalGroupService salGroupService;
81     private final SalMeterService salMeterService;
82     private final SalTableService salTableService;
83     private final ClusterSingletonServiceProvider clusterSingletonServiceProvider;
84     private final SalBundleService salBundleService;
85     private final AutoCloseable configurationServiceRegistration;
86     private final MastershipChangeServiceManager mastershipChangeServiceManager;
87     private final RpcProviderService rpcProviderService;
88     private ForwardingRulesCommiter<Flow> flowListener;
89     private ForwardingRulesCommiter<Group> groupListener;
90     private ForwardingRulesCommiter<Meter> meterListener;
91     private ForwardingRulesCommiter<TableFeatures> tableListener;
92     private FlowNodeReconciliation nodeListener;
93     private NotificationRegistration reconciliationNotificationRegistration;
94     private FlowNodeConnectorInventoryTranslatorImpl flowNodeConnectorInventoryTranslatorImpl;
95     private DeviceMastershipManager deviceMastershipManager;
96     private final ReconciliationManager reconciliationManager;
97     private DevicesGroupRegistry devicesGroupRegistry;
98     private NodeConfigurator nodeConfigurator;
99     private final ArbitratorReconcileService arbitratorReconciliationManager;
100     private boolean disableReconciliation;
101     private boolean staleMarkingEnabled;
102     private int reconciliationRetryCount;
103     private boolean isBundleBasedReconciliationEnabled;
104     private final OpenflowServiceRecoveryHandler openflowServiceRecoveryHandler;
105     private final ServiceRecoveryRegistry serviceRecoveryRegistry;
106
107     @Inject
108     public ForwardingRulesManagerImpl(@Reference final DataBroker dataBroker,
109                                       @Reference final RpcConsumerRegistry rpcRegistry,
110                                       @Reference final RpcProviderService rpcProviderService,
111                                       final ForwardingRulesManagerConfig config,
112                                       @Reference final MastershipChangeServiceManager mastershipChangeServiceManager,
113                                       @Reference final ClusterSingletonServiceProvider clusterSingletonService,
114                                       @Reference final ConfigurationService configurationService,
115                                       @Reference final ReconciliationManager reconciliationManager,
116                                       final OpenflowServiceRecoveryHandler openflowServiceRecoveryHandler,
117                                       @Reference final ServiceRecoveryRegistry serviceRecoveryRegistry) {
118         disableReconciliation = config.isDisableReconciliation();
119         staleMarkingEnabled = config.isStaleMarkingEnabled();
120         reconciliationRetryCount = config.getReconciliationRetryCount();
121         isBundleBasedReconciliationEnabled = config.isBundleBasedReconciliationEnabled();
122         this.configurationServiceRegistration = configurationService.registerListener(this);
123         this.dataService = Preconditions.checkNotNull(dataBroker, "DataBroker can not be null!");
124         this.clusterSingletonServiceProvider = Preconditions.checkNotNull(clusterSingletonService,
125                 "ClusterSingletonService provider can not be null");
126         this.reconciliationManager = reconciliationManager;
127         this.rpcProviderService = rpcProviderService;
128         this.mastershipChangeServiceManager = mastershipChangeServiceManager;
129
130         Preconditions.checkArgument(rpcRegistry != null, "RpcProviderRegistry can not be null !");
131
132         this.salFlowService = Preconditions.checkNotNull(rpcRegistry.getRpcService(SalFlowService.class),
133                 "RPC SalFlowService not found.");
134         this.salGroupService = Preconditions.checkNotNull(rpcRegistry.getRpcService(SalGroupService.class),
135                 "RPC SalGroupService not found.");
136         this.salMeterService = Preconditions.checkNotNull(rpcRegistry.getRpcService(SalMeterService.class),
137                 "RPC SalMeterService not found.");
138         this.salTableService = Preconditions.checkNotNull(rpcRegistry.getRpcService(SalTableService.class),
139                 "RPC SalTableService not found.");
140         this.salBundleService = Preconditions.checkNotNull(rpcRegistry.getRpcService(SalBundleService.class),
141                 "RPC SalBundlService not found.");
142         this.openflowServiceRecoveryHandler = Preconditions.checkNotNull(openflowServiceRecoveryHandler,
143                 "Openflow service recovery handler cannot be null");
144         this.serviceRecoveryRegistry = Preconditions.checkNotNull(serviceRecoveryRegistry,
145                 "Service recovery registry cannot be null");
146         this.arbitratorReconciliationManager = Preconditions
147                 .checkNotNull(rpcRegistry.getRpcService(ArbitratorReconcileService.class),
148                         "ArbitratorReconciliationManager can not be null!");
149     }
150
151     @Override
152     @PostConstruct
153     public void start() {
154         nodeConfigurator = new NodeConfiguratorImpl();
155         this.devicesGroupRegistry = new DevicesGroupRegistry();
156
157         this.nodeListener = new FlowNodeReconciliationImpl(this, dataService, SERVICE_NAME, FRM_RECONCILIATION_PRIORITY,
158                 ResultState.DONOTHING);
159         if (this.isReconciliationDisabled()) {
160             LOG.debug("Reconciliation is disabled by user");
161         } else {
162             this.reconciliationNotificationRegistration = reconciliationManager.registerService(this.nodeListener);
163             LOG.debug("Reconciliation is enabled by user and successfully registered to the reconciliation framework");
164         }
165         this.deviceMastershipManager = new DeviceMastershipManager(clusterSingletonServiceProvider, this.nodeListener,
166                 dataService, mastershipChangeServiceManager, rpcProviderService,
167                 new FrmReconciliationServiceImpl(this));
168         flowNodeConnectorInventoryTranslatorImpl = new FlowNodeConnectorInventoryTranslatorImpl(dataService);
169
170         this.flowListener = new FlowForwarder(this, dataService);
171         this.groupListener = new GroupForwarder(this, dataService);
172         this.meterListener = new MeterForwarder(this, dataService);
173         this.tableListener = new TableForwarder(this, dataService);
174         LOG.info("ForwardingRulesManager has started successfully.");
175     }
176
177     @Override
178     @PreDestroy
179     public void close() throws Exception {
180         configurationServiceRegistration.close();
181
182         if (this.flowListener != null) {
183             this.flowListener.close();
184             this.flowListener = null;
185         }
186         if (this.groupListener != null) {
187             this.groupListener.close();
188             this.groupListener = null;
189         }
190         if (this.meterListener != null) {
191             this.meterListener.close();
192             this.meterListener = null;
193         }
194         if (this.tableListener != null) {
195             this.tableListener.close();
196             this.tableListener = null;
197         }
198         if (this.nodeListener != null) {
199             this.nodeListener.close();
200             this.nodeListener = null;
201         }
202         if (deviceMastershipManager != null) {
203             deviceMastershipManager.close();
204         }
205         if (this.reconciliationNotificationRegistration != null) {
206             this.reconciliationNotificationRegistration.close();
207             this.reconciliationNotificationRegistration = null;
208         }
209     }
210
211     @Override
212     public ReadTransaction getReadTransaction() {
213         return dataService.newReadOnlyTransaction();
214     }
215
216     @Override
217     public String getNewTransactionId() {
218         return "DOM-" + txNum.getAndIncrement();
219     }
220
221     @Override
222     public boolean isNodeActive(final InstanceIdentifier<FlowCapableNode> ident) {
223         return deviceMastershipManager.isNodeActive(ident.firstKeyOf(Node.class).getId());
224     }
225
226     @Override
227     public boolean checkNodeInOperationalDataStore(final InstanceIdentifier<FlowCapableNode> ident) {
228         boolean result = false;
229         InstanceIdentifier<Node> nodeIid = ident.firstIdentifierOf(Node.class);
230         try (ReadTransaction transaction = dataService.newReadOnlyTransaction()) {
231             ListenableFuture<Optional<Node>> future = transaction
232                 .read(LogicalDatastoreType.OPERATIONAL, nodeIid);
233             Optional<Node> optionalDataObject = future.get();
234             if (optionalDataObject.isPresent()) {
235                 result = true;
236             } else {
237                 LOG.debug("{}: Failed to read {}", Thread.currentThread().getStackTrace()[1], nodeIid);
238             }
239         } catch (ExecutionException | InterruptedException e) {
240             LOG.warn("Failed to read {} ", nodeIid, e);
241         }
242
243         return result;
244     }
245
246     @Override
247     public SalFlowService getSalFlowService() {
248         return salFlowService;
249     }
250
251     @Override
252     public SalGroupService getSalGroupService() {
253         return salGroupService;
254     }
255
256     @Override
257     public SalMeterService getSalMeterService() {
258         return salMeterService;
259     }
260
261     @Override
262     public SalTableService getSalTableService() {
263         return salTableService;
264     }
265
266     @Override
267     public DevicesGroupRegistry getDevicesGroupRegistry() {
268         return this.devicesGroupRegistry;
269     }
270
271     @Override
272     public SalBundleService getSalBundleService() {
273         return salBundleService;
274     }
275
276     @Override
277     public ForwardingRulesCommiter<Flow> getFlowCommiter() {
278         return flowListener;
279     }
280
281     @Override
282     public ForwardingRulesCommiter<Group> getGroupCommiter() {
283         return groupListener;
284     }
285
286     @Override
287     public ForwardingRulesCommiter<Meter> getMeterCommiter() {
288         return meterListener;
289     }
290
291     @Override
292     public ForwardingRulesCommiter<TableFeatures> getTableFeaturesCommiter() {
293         return tableListener;
294     }
295
296     @Override
297     public ArbitratorReconcileService getArbitratorReconciliationManager() {
298         return arbitratorReconciliationManager;
299     }
300
301     @Override
302     public boolean isReconciliationDisabled() {
303         return disableReconciliation;
304     }
305
306     @Override
307     public boolean isStaleMarkingEnabled() {
308         return staleMarkingEnabled;
309     }
310
311     @Override
312     public int getReconciliationRetryCount() {
313         return reconciliationRetryCount;
314     }
315
316     @Override
317     public void addRecoverableListener(final RecoverableListener recoverableListener) {
318         serviceRecoveryRegistry.addRecoverableListener(openflowServiceRecoveryHandler.buildServiceRegistryKey(),
319                 recoverableListener);
320     }
321
322     @Override
323     public FlowNodeConnectorInventoryTranslatorImpl getFlowNodeConnectorInventoryTranslatorImpl() {
324         return flowNodeConnectorInventoryTranslatorImpl;
325     }
326
327     @Override
328     public NodeConfigurator getNodeConfigurator() {
329         return nodeConfigurator;
330     }
331
332     public FlowNodeReconciliation getNodeListener() {
333         return nodeListener;
334     }
335
336     @Override
337     public boolean isBundleBasedReconciliationEnabled() {
338         return isBundleBasedReconciliationEnabled;
339     }
340
341     @Override
342     public boolean isNodeOwner(final InstanceIdentifier<FlowCapableNode> ident) {
343         return Objects.nonNull(ident) && deviceMastershipManager.isDeviceMastered(ident.firstKeyOf(Node.class).getId());
344     }
345
346     @VisibleForTesting
347     public void setDeviceMastershipManager(final DeviceMastershipManager deviceMastershipManager) {
348         this.deviceMastershipManager = deviceMastershipManager;
349     }
350
351     @Override
352     public void onPropertyChanged(@Nonnull final String propertyName, @Nonnull final String propertyValue) {
353         Optional.ofNullable(ForwardingRulesProperty.forValue(propertyName)).ifPresent(forwardingRulesProperty -> {
354             switch (forwardingRulesProperty) {
355                 case DISABLE_RECONCILIATION:
356                     disableReconciliation = Boolean.valueOf(propertyValue);
357                     break;
358                 case STALE_MARKING_ENABLED:
359                     staleMarkingEnabled = Boolean.valueOf(propertyValue);
360                     break;
361                 case RECONCILIATION_RETRY_COUNT:
362                     reconciliationRetryCount = Integer.parseInt(propertyValue);
363                     break;
364                 case BUNDLE_BASED_RECONCILIATION_ENABLED:
365                     isBundleBasedReconciliationEnabled = Boolean.valueOf(propertyValue);
366                     break;
367                 default:
368                     LOG.warn("No forwarding rule property found.");
369                     break;
370             }
371         });
372     }
373 }