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