Bug 5596 Changes when closing device
[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.concurrent.ExecutionException;
17 import javax.annotation.Nullable;
18 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
19 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceRegistration;
20 import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
21 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
22 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
23 import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleService;
24 import org.opendaylight.openflowplugin.api.openflow.role.RoleContext;
25 import org.opendaylight.openflowplugin.api.openflow.rpc.RpcContext;
26 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsContext;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30
31 public class LifecycleServiceImpl implements LifecycleService {
32
33     private static final Logger LOG = LoggerFactory.getLogger(LifecycleServiceImpl.class);
34
35     private DeviceContext deviceContext;
36     private RpcContext rpcContext;
37     private RoleContext roleContext;
38     private StatisticsContext statContext;
39     private ClusterSingletonServiceRegistration registration;
40
41
42     @Override
43     public void instantiateServiceInstance() {
44         try {
45
46             if (LOG.isDebugEnabled()) {
47                 LOG.debug("Starting clustering MASTER services for node {}", this.deviceContext.getDeviceInfo().getNodeId().getValue());
48                 LOG.debug("===============================================");
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().getNodeId().getValue());
102             return true;
103         }
104         return false;
105     }
106
107     @Override
108     public ListenableFuture<Void> closeServiceInstance() {
109         roleContext.stopClusterServices();
110         statContext.stopClusterServices();
111         rpcContext.stopClusterServices();
112         return deviceContext.stopClusterServices();
113     }
114
115     @Override
116     public ServiceGroupIdentifier getIdentifier() {
117         return deviceContext.getServiceIdentifier();
118     }
119
120
121     @Override
122     public void close() throws Exception {
123         if (registration != null) {
124             registration.close();
125             registration = null;
126         }
127     }
128
129     @Override
130     public void registerService(final ClusterSingletonServiceProvider singletonServiceProvider) {
131         this.registration = singletonServiceProvider.registerClusterSingletonService(this);
132     }
133
134     @Override
135     public void setDeviceContext(final DeviceContext deviceContext) {
136         this.deviceContext = deviceContext;
137     }
138
139     @Override
140     public void setRpcContext(final RpcContext rpcContext) {
141         this.rpcContext = rpcContext;
142     }
143
144     @Override
145     public void setRoleContext(final RoleContext roleContext) {
146         this.roleContext = roleContext;
147     }
148
149     @Override
150     public void setStatContext(final StatisticsContext statContext) {
151         this.statContext = statContext;
152     }
153
154     @Override
155     public DeviceContext getDeviceContext() {
156         return this.deviceContext;
157     }
158
159     @Override
160     public void closeConnection() {
161         this.deviceContext.shutdownConnection();
162     }
163
164     private void fillDeviceFlowRegistry() {
165         // Fill device flow registry with flows from datastore
166         final ListenableFuture<List<Optional<FlowCapableNode>>> deviceFlowRegistryFill = deviceContext.getDeviceFlowRegistry().fill();
167
168         // Start statistics scheduling only after we finished initializing device flow registry
169         Futures.addCallback(deviceFlowRegistryFill, new FutureCallback<List<Optional<FlowCapableNode>>>() {
170             @Override
171             public void onSuccess(@Nullable List<Optional<FlowCapableNode>> result) {
172                 if (LOG.isDebugEnabled()) {
173                     // Count all flows we read from datastore for debugging purposes.
174                     // This number do not always represent how many flows were actually added
175                     // to DeviceFlowRegistry, because of possible duplicates.
176                     long flowCount = Optional.fromNullable(result).asSet().stream()
177                             .flatMap(Collection::stream)
178                             .flatMap(flowCapableNodeOptional -> flowCapableNodeOptional.asSet().stream())
179                             .flatMap(flowCapableNode -> flowCapableNode.getTable().stream())
180                             .flatMap(table -> table.getFlow().stream())
181                             .count();
182
183                     LOG.debug("Finished filling flow registry with {} flows for node: {}", flowCount, getIdentifier());
184                 }
185             }
186
187             @Override
188             public void onFailure(Throwable t) {
189                 if (deviceFlowRegistryFill.isCancelled()) {
190                     LOG.debug("Cancelled filling flow registry with flows for node: {}", getIdentifier());
191                 } else {
192                     LOG.warn("Failed filling flow registry with flows for node: {} with exception: {}", getIdentifier(), t);
193                 }
194             }
195         });
196     }
197
198 }