DeviceFlowRegistry - prevent NPE
[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().getNodeId().getValue());
49                 LOG.debug("===============================================");
50             }
51
52             if (connectionInterrupted()) {
53                 return;
54             }
55
56             LOG.info("Starting device context cluster services for node {}", getIdentifier());
57             this.deviceContext.startupClusterServices();
58
59             if (connectionInterrupted()) {
60                 return;
61             }
62
63             LOG.info("Starting statistics context cluster services for node {}", getIdentifier());
64             this.statContext.startupClusterServices();
65
66             if (connectionInterrupted()) {
67                 return;
68             }
69
70             LOG.info("Statistics initial gathering OK, submitting data for node {}", getIdentifier());
71             this.deviceContext.initialSubmitTransaction();
72
73             if (connectionInterrupted()) {
74                 return;
75             }
76
77             LOG.info("Starting rpc context cluster services for node {}", getIdentifier());
78             this.rpcContext.startupClusterServices();
79
80             if (connectionInterrupted()) {
81                 return;
82             }
83
84             LOG.info("Starting role context cluster services for node {}", getIdentifier());
85             this.roleContext.startupClusterServices();
86
87             if (connectionInterrupted()) {
88                 return;
89             }
90
91             LOG.info("Caching flows IDs ...");
92             fillDeviceFlowRegistry();
93
94         } catch (ExecutionException | InterruptedException e) {
95             LOG.warn("Cluster service {} was unable to start.", this.getIdentifier());
96             this.deviceContext.shutdownConnection();
97         }
98     }
99
100     private boolean connectionInterrupted() {
101         if (this.deviceContext.getPrimaryConnectionContext().getConnectionState().equals(ConnectionContext.CONNECTION_STATE.RIP)) {
102             LOG.warn("Node {} was disconnected, will stop starting MASTER services.", this.deviceContext.getDeviceInfo().getNodeId().getValue());
103             return true;
104         }
105         return false;
106     }
107
108     @Override
109     public ListenableFuture<Void> closeServiceInstance() {
110         roleContext.stopClusterServices();
111         statContext.stopClusterServices();
112         rpcContext.stopClusterServices();
113         return deviceContext.stopClusterServices();
114     }
115
116     @Override
117     public ServiceGroupIdentifier getIdentifier() {
118         return deviceContext.getServiceIdentifier();
119     }
120
121
122     @Override
123     public void close() throws Exception {
124         if (registration != null) {
125             registration.close();
126             registration = null;
127         }
128     }
129
130     @Override
131     public void registerService(final ClusterSingletonServiceProvider singletonServiceProvider) {
132         this.registration = singletonServiceProvider.registerClusterSingletonService(this);
133     }
134
135     @Override
136     public void setDeviceContext(final DeviceContext deviceContext) {
137         this.deviceContext = deviceContext;
138     }
139
140     @Override
141     public void setRpcContext(final RpcContext rpcContext) {
142         this.rpcContext = rpcContext;
143     }
144
145     @Override
146     public void setRoleContext(final RoleContext roleContext) {
147         this.roleContext = roleContext;
148     }
149
150     @Override
151     public void setStatContext(final StatisticsContext statContext) {
152         this.statContext = statContext;
153     }
154
155     @Override
156     public DeviceContext getDeviceContext() {
157         return this.deviceContext;
158     }
159
160     @Override
161     public void closeConnection() {
162         this.deviceContext.shutdownConnection();
163     }
164
165     private void fillDeviceFlowRegistry() {
166         // Fill device flow registry with flows from datastore
167         final ListenableFuture<List<Optional<FlowCapableNode>>> deviceFlowRegistryFill = deviceContext.getDeviceFlowRegistry().fill();
168
169         // Start statistics scheduling only after we finished initializing device flow registry
170         Futures.addCallback(deviceFlowRegistryFill, new FutureCallback<List<Optional<FlowCapableNode>>>() {
171             @Override
172             public void onSuccess(@Nullable List<Optional<FlowCapableNode>> result) {
173                 if (LOG.isDebugEnabled()) {
174                     // Count all flows we read from datastore for debugging purposes.
175                     // This number do not always represent how many flows were actually added
176                     // to DeviceFlowRegistry, because of possible duplicates.
177                     long flowCount = Optional.fromNullable(result).asSet().stream()
178                             .flatMap(Collection::stream)
179                             .filter(Objects::nonNull)
180                             .flatMap(flowCapableNodeOptional -> flowCapableNodeOptional.asSet().stream())
181                             .filter(Objects::nonNull)
182                             .filter(flowCapableNode -> Objects.nonNull(flowCapableNode.getTable()))
183                             .flatMap(flowCapableNode -> flowCapableNode.getTable().stream())
184                             .filter(Objects::nonNull)
185                             .filter(table -> Objects.nonNull(table.getFlow()))
186                             .flatMap(table -> table.getFlow().stream())
187                             .filter(Objects::nonNull)
188                             .count();
189
190                     LOG.debug("Finished filling flow registry with {} flows for node: {}", flowCount, getIdentifier());
191                 }
192             }
193
194             @Override
195             public void onFailure(Throwable t) {
196                 if (deviceFlowRegistryFill.isCancelled()) {
197                     LOG.debug("Cancelled filling flow registry with flows for node: {}", getIdentifier());
198                 } else {
199                     LOG.warn("Failed filling flow registry with flows for node: {} with exception: {}", getIdentifier(), t);
200                 }
201             }
202         });
203     }
204
205 }