Merge "SONAR TD - Group actions redundancy"
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / lifecycle / LifecycleServiceImpl.java
1 /*
2  * Copyright (c) 2016 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.impl.lifecycle;
9
10 import com.google.common.base.Optional;
11 import com.google.common.util.concurrent.FutureCallback;
12 import com.google.common.util.concurrent.Futures;
13 import com.google.common.util.concurrent.ListenableFuture;
14 import java.util.Collection;
15 import java.util.List;
16 import java.util.Objects;
17 import java.util.concurrent.ExecutionException;
18 import javax.annotation.Nullable;
19 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
20 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceRegistration;
21 import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
22 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
23 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
24 import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleService;
25 import org.opendaylight.openflowplugin.api.openflow.role.RoleContext;
26 import org.opendaylight.openflowplugin.api.openflow.rpc.RpcContext;
27 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsContext;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 public class LifecycleServiceImpl implements LifecycleService {
33
34     private static final Logger LOG = LoggerFactory.getLogger(LifecycleServiceImpl.class);
35
36     private DeviceContext deviceContext;
37     private RpcContext rpcContext;
38     private RoleContext roleContext;
39     private StatisticsContext statContext;
40     private ClusterSingletonServiceRegistration registration;
41
42
43     @Override
44     public void instantiateServiceInstance() {
45         try {
46
47             if (LOG.isDebugEnabled()) {
48                 LOG.debug("========== Starting clustering MASTER services for node {} ==========", this.deviceContext.getDeviceInfo().getLOGValue());
49             }
50
51             if (connectionInterrupted()) {
52                 return;
53             }
54
55             LOG.info("Starting device context cluster services for node {}", getIdentifier());
56             this.deviceContext.startupClusterServices();
57
58             if (connectionInterrupted()) {
59                 return;
60             }
61
62             LOG.info("Starting statistics context cluster services for node {}", getIdentifier());
63             this.statContext.startupClusterServices();
64
65             if (connectionInterrupted()) {
66                 return;
67             }
68
69             LOG.info("Statistics initial gathering OK, submitting data for node {}", getIdentifier());
70             this.deviceContext.initialSubmitTransaction();
71
72             if (connectionInterrupted()) {
73                 return;
74             }
75
76             LOG.info("Starting rpc context cluster services for node {}", getIdentifier());
77             this.rpcContext.startupClusterServices();
78
79             if (connectionInterrupted()) {
80                 return;
81             }
82
83             LOG.info("Starting role context cluster services for node {}", getIdentifier());
84             this.roleContext.startupClusterServices();
85
86             if (connectionInterrupted()) {
87                 return;
88             }
89
90             LOG.info("Caching flows IDs ...");
91             fillDeviceFlowRegistry();
92
93         } catch (ExecutionException | InterruptedException e) {
94             LOG.warn("Cluster service {} was unable to start.", this.getIdentifier());
95             this.deviceContext.shutdownConnection();
96         }
97     }
98
99     private boolean connectionInterrupted() {
100         if (this.deviceContext.getPrimaryConnectionContext().getConnectionState().equals(ConnectionContext.CONNECTION_STATE.RIP)) {
101             LOG.warn("Node {} was disconnected, will stop starting MASTER services.", this.deviceContext.getDeviceInfo().getLOGValue());
102             return true;
103         }
104         return false;
105     }
106
107     @Override
108     public ListenableFuture<Void> closeServiceInstance() {
109         if (LOG.isDebugEnabled()) {
110             LOG.debug("========== Stopping clustering MASTER services for node {} ==========", this.deviceContext.getDeviceInfo().getLOGValue());
111         }
112
113         final boolean connectionInterrupted =
114                 this.deviceContext
115                         .getPrimaryConnectionContext()
116                         .getConnectionState()
117                         .equals(ConnectionContext.CONNECTION_STATE.RIP);
118
119         LOG.info("Stopping role context cluster services for node {}", getIdentifier());
120         roleContext.stopClusterServices(connectionInterrupted);
121
122         LOG.info("Stopping statistics context cluster services for node {}", getIdentifier());
123         statContext.stopClusterServices(connectionInterrupted);
124
125         LOG.info("Stopping rpc context cluster services for node {}", getIdentifier());
126         rpcContext.stopClusterServices(connectionInterrupted);
127
128         LOG.info("Stopping device context cluster services for node {}", getIdentifier());
129         return deviceContext.stopClusterServices(connectionInterrupted);
130     }
131
132     @Override
133     public ServiceGroupIdentifier getIdentifier() {
134         return deviceContext.getServiceIdentifier();
135     }
136
137
138     @Override
139     public void close() throws Exception {
140         if (registration != null) {
141             registration.close();
142             registration = null;
143         }
144     }
145
146     @Override
147     public void registerService(final ClusterSingletonServiceProvider singletonServiceProvider) {
148         this.registration = singletonServiceProvider.registerClusterSingletonService(this);
149     }
150
151     @Override
152     public void setDeviceContext(final DeviceContext deviceContext) {
153         this.deviceContext = deviceContext;
154     }
155
156     @Override
157     public void setRpcContext(final RpcContext rpcContext) {
158         this.rpcContext = rpcContext;
159     }
160
161     @Override
162     public void setRoleContext(final RoleContext roleContext) {
163         this.roleContext = roleContext;
164     }
165
166     @Override
167     public void setStatContext(final StatisticsContext statContext) {
168         this.statContext = statContext;
169     }
170
171     @Override
172     public DeviceContext getDeviceContext() {
173         return this.deviceContext;
174     }
175
176     @Override
177     public void closeConnection() {
178         this.deviceContext.shutdownConnection();
179     }
180
181     private void fillDeviceFlowRegistry() {
182         // Fill device flow registry with flows from datastore
183         final ListenableFuture<List<Optional<FlowCapableNode>>> deviceFlowRegistryFill = deviceContext.getDeviceFlowRegistry().fill();
184
185         // Start statistics scheduling only after we finished initializing device flow registry
186         Futures.addCallback(deviceFlowRegistryFill, new FutureCallback<List<Optional<FlowCapableNode>>>() {
187             @Override
188             public void onSuccess(@Nullable List<Optional<FlowCapableNode>> result) {
189                 if (LOG.isDebugEnabled()) {
190                     // Count all flows we read from datastore for debugging purposes.
191                     // This number do not always represent how many flows were actually added
192                     // to DeviceFlowRegistry, because of possible duplicates.
193                     long flowCount = Optional.fromNullable(result).asSet().stream()
194                             .flatMap(Collection::stream)
195                             .filter(Objects::nonNull)
196                             .flatMap(flowCapableNodeOptional -> flowCapableNodeOptional.asSet().stream())
197                             .filter(Objects::nonNull)
198                             .filter(flowCapableNode -> Objects.nonNull(flowCapableNode.getTable()))
199                             .flatMap(flowCapableNode -> flowCapableNode.getTable().stream())
200                             .filter(Objects::nonNull)
201                             .filter(table -> Objects.nonNull(table.getFlow()))
202                             .flatMap(table -> table.getFlow().stream())
203                             .filter(Objects::nonNull)
204                             .count();
205
206                     LOG.debug("Finished filling flow registry with {} flows for node: {}", flowCount, deviceContext.getDeviceInfo().getLOGValue());
207                 }
208             }
209
210             @Override
211             public void onFailure(Throwable t) {
212                 if (deviceFlowRegistryFill.isCancelled()) {
213                     LOG.debug("Cancelled filling flow registry with flows for node: {}", deviceContext.getDeviceInfo().getLOGValue());
214                 } else {
215                     LOG.warn("Failed filling flow registry with flows for node: {} with exception: {}", deviceContext.getDeviceInfo().getLOGValue(), t);
216                 }
217             }
218         });
219     }
220
221 }