Merge "Remove Itemlifecycle"
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / lifecycle / ContextChainImpl.java
1 /*
2  * Copyright (c) 2016 Pantheon Technologies s.r.o. 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.collect.Lists;
11 import com.google.common.util.concurrent.Futures;
12 import com.google.common.util.concurrent.ListenableFuture;
13 import java.util.List;
14 import java.util.Objects;
15 import java.util.concurrent.CopyOnWriteArrayList;
16 import java.util.concurrent.ExecutorService;
17 import java.util.concurrent.atomic.AtomicBoolean;
18 import java.util.concurrent.atomic.AtomicReference;
19 import java.util.stream.Collectors;
20 import javax.annotation.Nonnull;
21 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
22 import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
23 import org.opendaylight.openflowplugin.api.openflow.OFPContext;
24 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
25 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
26 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceRemovedHandler;
27 import org.opendaylight.openflowplugin.api.openflow.lifecycle.ContextChain;
28 import org.opendaylight.openflowplugin.api.openflow.lifecycle.ContextChainMastershipState;
29 import org.opendaylight.openflowplugin.api.openflow.lifecycle.ContextChainMastershipWatcher;
30 import org.opendaylight.openflowplugin.api.openflow.lifecycle.ContextChainState;
31 import org.opendaylight.openflowplugin.api.openflow.lifecycle.ContextChainStateListener;
32 import org.opendaylight.openflowplugin.api.openflow.lifecycle.GuardedContext;
33 import org.opendaylight.openflowplugin.api.openflow.lifecycle.ReconciliationFrameworkStep;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 public class ContextChainImpl implements ContextChain {
38     private static final Logger LOG = LoggerFactory.getLogger(ContextChainImpl.class);
39
40     private final AtomicBoolean masterStateOnDevice = new AtomicBoolean(false);
41     private final AtomicBoolean initialGathering = new AtomicBoolean(false);
42     private final AtomicBoolean initialSubmitting = new AtomicBoolean(false);
43     private final AtomicBoolean registryFilling = new AtomicBoolean(false);
44     private final AtomicBoolean rpcRegistration = new AtomicBoolean(false);
45     private final List<DeviceRemovedHandler> deviceRemovedHandlers = new CopyOnWriteArrayList<>();
46     private final List<GuardedContext> contexts = new CopyOnWriteArrayList<>();
47     private final List<ConnectionContext> auxiliaryConnections = new CopyOnWriteArrayList<>();
48     private final ExecutorService executorService;
49     private final ContextChainMastershipWatcher contextChainMastershipWatcher;
50     private final DeviceInfo deviceInfo;
51     private final ConnectionContext primaryConnection;
52     private final AtomicReference<ContextChainState> contextChainState =
53             new AtomicReference<>(ContextChainState.UNDEFINED);
54     private AutoCloseable registration;
55
56     ContextChainImpl(@Nonnull final ContextChainMastershipWatcher contextChainMastershipWatcher,
57                      @Nonnull final ConnectionContext connectionContext,
58                      @Nonnull final ExecutorService executorService) {
59         this.contextChainMastershipWatcher = contextChainMastershipWatcher;
60         this.primaryConnection = connectionContext;
61         this.deviceInfo = connectionContext.getDeviceInfo();
62         this.executorService = executorService;
63     }
64
65     @Override
66     public <T extends OFPContext> void addContext(@Nonnull final T context) {
67         contexts.add(new GuardedContextImpl(context));
68     }
69
70     @Override
71     @SuppressWarnings("checkstyle:IllegalCatch")
72     public void instantiateServiceInstance() {
73         try {
74             contexts.forEach(OFPContext::instantiateServiceInstance);
75             LOG.info("Started clustering services for node {}", deviceInfo);
76         } catch (final Exception ex) {
77             LOG.warn("Not able to start clustering services for node {}", deviceInfo);
78             executorService.submit(() -> contextChainMastershipWatcher
79                     .onNotAbleToStartMastershipMandatory(deviceInfo, ex.toString()));
80         }
81     }
82
83     @Override
84     public ListenableFuture<Void> closeServiceInstance() {
85
86         contextChainMastershipWatcher.onSlaveRoleAcquired(deviceInfo);
87
88         final ListenableFuture<List<Void>> servicesToBeClosed = Futures
89                 .allAsList(Lists.reverse(contexts)
90                         .stream()
91                         .map(OFPContext::closeServiceInstance)
92                         .collect(Collectors.toList()));
93
94         return Futures.transform(servicesToBeClosed, (input) -> {
95             LOG.info("Closed clustering services for node {}", deviceInfo);
96             return null;
97         }, executorService);
98     }
99
100     @Nonnull
101     @Override
102     public ServiceGroupIdentifier getIdentifier() {
103         return deviceInfo.getServiceIdentifier();
104     }
105
106     @Override
107     @SuppressWarnings("checkstyle:IllegalCatch")
108     public void close() {
109         if (ContextChainState.CLOSED.equals(contextChainState.get())) {
110             LOG.debug("ContextChain for node {} is already in TERMINATION state.", deviceInfo);
111             return;
112         }
113
114         contextChainState.set(ContextChainState.CLOSED);
115         unMasterMe();
116
117         // Close all connections to devices
118         auxiliaryConnections.forEach(connectionContext -> connectionContext.closeConnection(false));
119         auxiliaryConnections.clear();
120
121         // If we are still registered and we are not already closing, then close the registration
122         if (Objects.nonNull(registration)) {
123             try {
124                 registration.close();
125                 registration = null;
126                 LOG.info("Closed clustering services registration for node {}", deviceInfo);
127             } catch (final Exception e) {
128                 LOG.warn("Failed to close clustering services registration for node {} with exception: ",
129                         deviceInfo, e);
130             }
131         }
132
133
134         // Close all contexts (device, statistics, rpc)
135         contexts.forEach(OFPContext::close);
136         contexts.clear();
137
138         // We are closing, so cleanup all managers now
139         deviceRemovedHandlers.forEach(h -> h.onDeviceRemoved(deviceInfo));
140         deviceRemovedHandlers.clear();
141
142         primaryConnection.closeConnection(false);
143
144     }
145
146     @Override
147     public void makeContextChainStateSlave() {
148         unMasterMe();
149         changeMastershipState(ContextChainState.WORKING_SLAVE);
150     }
151
152     @Override
153     public void registerServices(final ClusterSingletonServiceProvider clusterSingletonServiceProvider) {
154         registration = Objects.requireNonNull(clusterSingletonServiceProvider
155                 .registerClusterSingletonService(this));
156         LOG.debug("Registered clustering services for node {}", deviceInfo);
157     }
158
159     @Override
160     public boolean isMastered(@Nonnull ContextChainMastershipState mastershipState,
161                               boolean inReconciliationFrameworkStep) {
162         switch (mastershipState) {
163             case INITIAL_SUBMIT:
164                 LOG.debug("Device {}, initial submit OK.", deviceInfo);
165                 this.initialSubmitting.set(true);
166                 break;
167             case MASTER_ON_DEVICE:
168                 LOG.debug("Device {}, master state OK.", deviceInfo);
169                 this.masterStateOnDevice.set(true);
170                 break;
171             case INITIAL_GATHERING:
172                 LOG.debug("Device {}, initial gathering OK.", deviceInfo);
173                 this.initialGathering.set(true);
174                 break;
175             case RPC_REGISTRATION:
176                 LOG.debug("Device {}, RPC registration OK.", deviceInfo);
177                 this.rpcRegistration.set(true);
178                 break;
179             case INITIAL_FLOW_REGISTRY_FILL:
180                 // Flow registry fill is not mandatory to work as a master
181                 LOG.debug("Device {}, initial registry filling OK.", deviceInfo);
182                 this.registryFilling.set(true);
183                 break;
184             case CHECK:
185                 // no operation
186                 break;
187             default:
188                 // no operation
189                 break;
190         }
191
192         final boolean result = initialGathering.get() &&
193                 masterStateOnDevice.get() &&
194                 rpcRegistration.get() &&
195                 inReconciliationFrameworkStep || initialSubmitting.get();
196
197         if (!inReconciliationFrameworkStep &&
198                 result &&
199                 mastershipState != ContextChainMastershipState.CHECK) {
200             LOG.info("Device {} is able to work as master{}",
201                     deviceInfo,
202                     registryFilling.get() ? "." : " WITHOUT flow registry !!!");
203             changeMastershipState(ContextChainState.WORKING_MASTER);
204         }
205
206         return result;
207     }
208
209     @Override
210     public boolean isClosing() {
211         return ContextChainState.CLOSED.equals(contextChainState.get());
212     }
213
214     @Override
215     public void continueInitializationAfterReconciliation() {
216         contexts.forEach(context -> {
217             if (context.map(ReconciliationFrameworkStep.class::isInstance)) {
218                 context.map(ReconciliationFrameworkStep.class::cast).continueInitializationAfterReconciliation();
219             }
220         });
221     }
222
223     @Override
224     public boolean addAuxiliaryConnection(@Nonnull ConnectionContext connectionContext) {
225         return (connectionContext.getFeatures().getAuxiliaryId() != 0)
226                 && (!ConnectionContext.CONNECTION_STATE.RIP.equals(primaryConnection.getConnectionState()))
227                 && auxiliaryConnections.add(connectionContext);
228     }
229
230     @Override
231     public boolean auxiliaryConnectionDropped(@Nonnull ConnectionContext connectionContext) {
232         return auxiliaryConnections.remove(connectionContext);
233     }
234
235     @Override
236     public void registerDeviceRemovedHandler(@Nonnull final DeviceRemovedHandler deviceRemovedHandler) {
237         deviceRemovedHandlers.add(deviceRemovedHandler);
238     }
239
240     private void changeMastershipState(final ContextChainState contextChainState) {
241         if (ContextChainState.CLOSED.equals(this.contextChainState.get())) {
242             return;
243         }
244
245         boolean propagate = ContextChainState.UNDEFINED.equals(this.contextChainState.get());
246         this.contextChainState.set(contextChainState);
247
248         if (propagate) {
249             contexts.forEach(context -> {
250                 if (context.map(ContextChainStateListener.class::isInstance)) {
251                     context.map(ContextChainStateListener.class::cast).onStateAcquired(contextChainState);
252                 }
253             });
254         }
255     }
256
257     private void unMasterMe() {
258         registryFilling.set(false);
259         initialSubmitting.set(false);
260         initialGathering.set(false);
261         masterStateOnDevice.set(false);
262         rpcRegistration.set(false);
263     }
264 }