Merge "BUG-5839: Removing groups and meters on being stale-marked"
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / role / RoleManagerImpl.java
1 /**
2  * Copyright (c) 2015 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.role;
9
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Verify;
13 import com.google.common.collect.Iterators;
14 import com.google.common.util.concurrent.CheckedFuture;
15 import com.google.common.util.concurrent.FutureCallback;
16 import com.google.common.util.concurrent.Futures;
17 import com.google.common.util.concurrent.JdkFutureAdapters;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import io.netty.util.Timeout;
20 import io.netty.util.TimerTask;
21
22 import java.util.ArrayList;
23 import java.util.Iterator;
24 import java.util.List;
25 import java.util.concurrent.ConcurrentHashMap;
26 import java.util.concurrent.ConcurrentMap;
27 import java.util.concurrent.Future;
28 import java.util.concurrent.TimeUnit;
29 import javax.annotation.CheckForNull;
30 import javax.annotation.Nonnull;
31 import javax.annotation.Nullable;
32
33 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
34 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
35 import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
36 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipChange;
37 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListener;
38 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListenerRegistration;
39 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
40 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
41 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
42 import org.opendaylight.openflowplugin.api.OFConstants;
43 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
44 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
45 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceTerminationPhaseHandler;
46 import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleConductor;
47 import org.opendaylight.openflowplugin.api.openflow.lifecycle.RoleChangeListener;
48 import org.opendaylight.openflowplugin.api.openflow.lifecycle.ServiceChangeListener;
49 import org.opendaylight.openflowplugin.api.openflow.role.RoleContext;
50 import org.opendaylight.openflowplugin.api.openflow.role.RoleManager;
51 import org.opendaylight.openflowplugin.impl.services.SalRoleServiceImpl;
52 import org.opendaylight.openflowplugin.impl.util.DeviceStateUtil;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.OfpRole;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.SetRoleInput;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.SetRoleInputBuilder;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.SetRoleOutput;
59 import org.opendaylight.yangtools.yang.common.RpcResult;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
62
63 /**
64  * Gets invoked from RpcManagerInitial, registers a candidate with EntityOwnershipService.
65  * On receipt of the ownership notification, makes an rpc call to SalRoleService.
66  *
67  * Hands over to StatisticsManager at the end.
68  */
69 public class RoleManagerImpl implements RoleManager, EntityOwnershipListener, ServiceChangeListener {
70     private static final Logger LOG = LoggerFactory.getLogger(RoleManagerImpl.class);
71
72     private DeviceInitializationPhaseHandler deviceInitializationPhaseHandler;
73     private DeviceTerminationPhaseHandler deviceTerminationPhaseHandler;
74     private final DataBroker dataBroker;
75     private final EntityOwnershipService entityOwnershipService;
76     private final ConcurrentMap<NodeId, RoleContext> contexts = new ConcurrentHashMap<>();
77     private final ConcurrentMap<Entity, RoleContext> watchingEntities = new ConcurrentHashMap<>();
78     private final EntityOwnershipListenerRegistration entityOwnershipListenerRegistration;
79     private final EntityOwnershipListenerRegistration txEntityOwnershipListenerRegistration;
80     private List<RoleChangeListener> listeners = new ArrayList<>();
81
82     private final LifecycleConductor conductor;
83
84     public RoleManagerImpl(final EntityOwnershipService entityOwnershipService, final DataBroker dataBroker, final LifecycleConductor lifecycleConductor) {
85         this.entityOwnershipService = Preconditions.checkNotNull(entityOwnershipService);
86         this.dataBroker = Preconditions.checkNotNull(dataBroker);
87         this.entityOwnershipListenerRegistration = Preconditions.checkNotNull(entityOwnershipService.registerListener(RoleManager.ENTITY_TYPE, this));
88         this.txEntityOwnershipListenerRegistration = Preconditions.checkNotNull(entityOwnershipService.registerListener(TX_ENTITY_TYPE, this));
89         this.conductor = lifecycleConductor;
90         LOG.debug("Register OpenflowOwnershipListener to all entity ownership changes");
91     }
92
93     @Override
94     public void setDeviceInitializationPhaseHandler(final DeviceInitializationPhaseHandler handler) {
95         deviceInitializationPhaseHandler = handler;
96     }
97
98     @Override
99     public void onDeviceContextLevelUp(@CheckForNull final NodeId nodeId) throws Exception {
100         final DeviceContext deviceContext = Preconditions.checkNotNull(conductor.getDeviceContext(nodeId));
101         final RoleContext roleContext = new RoleContextImpl(nodeId, entityOwnershipService, makeEntity(nodeId), makeTxEntity(nodeId), conductor);
102         roleContext.setSalRoleService(new SalRoleServiceImpl(roleContext, deviceContext));
103         Verify.verify(contexts.putIfAbsent(nodeId, roleContext) == null, "Role context for master Node %s is still not closed.", nodeId);
104         makeDeviceRoleChange(OfpRole.BECOMESLAVE, roleContext, true);
105         notifyListenersRoleInitializationDone(roleContext.getNodeId(), roleContext.initialization());
106         watchingEntities.put(roleContext.getEntity(), roleContext);
107         deviceInitializationPhaseHandler.onDeviceContextLevelUp(nodeId);
108     }
109
110     @Override
111     public void close() {
112         LOG.debug("Close method on role manager was called.");
113         entityOwnershipListenerRegistration.close();
114         txEntityOwnershipListenerRegistration.close();
115         for (final Iterator<RoleContext> iterator = Iterators.consumingIterator(contexts.values().iterator()); iterator.hasNext();) {
116             // got here because last known role is LEADER and DS might need clearing up
117             final RoleContext roleContext = iterator.next();
118             watchingEntities.remove(roleContext.getEntity());
119             watchingEntities.remove(roleContext.getTxEntity());
120             contexts.remove(roleContext.getNodeId());
121             if (roleContext.isTxCandidateRegistered()) {
122                 LOG.info("Node {} was holder txEntity, so trying to remove device from operational DS.");
123                 removeDeviceFromOperationalDS(roleContext.getNodeId());
124             } else {
125                 roleContext.close();
126             }
127         }
128     }
129
130     @Override
131     public void onDeviceContextLevelDown(final DeviceContext deviceContext) {
132         final NodeId nodeId = deviceContext.getPrimaryConnectionContext().getNodeId();
133         LOG.trace("onDeviceContextLevelDown for node {}", nodeId);
134         final RoleContext roleContext = contexts.get(nodeId);
135         if (roleContext != null) {
136             LOG.debug("Found roleContext associated to deviceContext: {}, now trying close the roleContext", nodeId);
137             if (roleContext.isMainCandidateRegistered()) {
138                 roleContext.unregisterCandidate(roleContext.getEntity());
139             } else {
140                 contexts.remove(nodeId, roleContext);
141                 roleContext.close();
142             }
143         }
144         deviceTerminationPhaseHandler.onDeviceContextLevelDown(deviceContext);
145     }
146
147     @VisibleForTesting
148     static Entity makeEntity(final NodeId nodeId) {
149         return new Entity(RoleManager.ENTITY_TYPE, nodeId.getValue());
150     }
151
152     @VisibleForTesting
153     static Entity makeTxEntity(final NodeId nodeId) {
154         return new Entity(RoleManager.TX_ENTITY_TYPE, nodeId.getValue());
155     }
156
157     @Override
158     public void ownershipChanged(final EntityOwnershipChange ownershipChange) {
159
160         Preconditions.checkArgument(ownershipChange != null);
161         final RoleContext roleContext = watchingEntities.get(ownershipChange.getEntity());
162
163         LOG.debug("Received EOS message: wasOwner:{} isOwner:{} hasOwner:{} for entity type {} and node {}",
164                 ownershipChange.wasOwner(), ownershipChange.isOwner(), ownershipChange.hasOwner(),
165                 ownershipChange.getEntity().getType(),
166                 roleContext != null ? roleContext.getNodeId() : "-> no watching entity, disregarding notification <-");
167
168         if (roleContext != null) {
169             if (ownershipChange.getEntity().equals(roleContext.getEntity())) {
170                 changeOwnershipForMainEntity(ownershipChange, roleContext);
171             } else {
172                 changeOwnershipForTxEntity(ownershipChange, roleContext);
173             }
174         } else {
175             LOG.debug("OwnershipChange {}", ownershipChange);
176         }
177
178     }
179
180     @VisibleForTesting
181     void changeOwnershipForMainEntity(final EntityOwnershipChange ownershipChange, final RoleContext roleContext) {
182
183         if (roleContext.isMainCandidateRegistered()) {
184             LOG.debug("Main-EntityOwnershipRegistration is active for entity type {} and node {}",
185                     ownershipChange.getEntity().getType(), roleContext.getNodeId());
186             if (!ownershipChange.wasOwner() && ownershipChange.isOwner()) {
187                 // SLAVE -> MASTER
188                 LOG.debug("SLAVE to MASTER for node {}", roleContext.getNodeId());
189                 if (roleContext.registerCandidate(roleContext.getTxEntity())) {
190                     LOG.debug("Starting watching tx entity for node {}", roleContext.getNodeId());
191                     watchingEntities.putIfAbsent(roleContext.getTxEntity(), roleContext);
192                 }
193             } else if (ownershipChange.wasOwner() && !ownershipChange.isOwner()) {
194                 // MASTER -> SLAVE
195                 LOG.debug("MASTER to SLAVE for node {}", roleContext.getNodeId());
196                 conductor.addOneTimeListenerWhenServicesChangesDone(this, roleContext.getNodeId());
197                 makeDeviceRoleChange(OfpRole.BECOMESLAVE, roleContext, false);
198             }
199         } else {
200             LOG.debug("Main-EntityOwnershipRegistration is not active for entity type {} and node {}",
201                     ownershipChange.getEntity(), roleContext.getNodeId());
202             watchingEntities.remove(ownershipChange.getEntity(), roleContext);
203             if (roleContext.isTxCandidateRegistered()) {
204                 LOG.debug("tx candidate still registered for node {}, probably connection lost, trying to unregister tx candidate", roleContext.getNodeId());
205                 roleContext.unregisterCandidate(roleContext.getTxEntity());
206                 if (ownershipChange.wasOwner() && !ownershipChange.isOwner() && !ownershipChange.hasOwner()) {
207                     LOG.debug("Trying to remove from operational node: {}", roleContext.getNodeId());
208                     removeDeviceFromOperationalDS(roleContext.getNodeId());
209                 }
210             } else {
211                 final NodeId nodeId = roleContext.getNodeId();
212                 contexts.remove(nodeId, roleContext);
213                 roleContext.close();
214                 conductor.closeConnection(nodeId);
215             }
216         }
217     }
218
219     @VisibleForTesting
220     void changeOwnershipForTxEntity(final EntityOwnershipChange ownershipChange,
221             @Nonnull final RoleContext roleContext) {
222
223         if (roleContext.isTxCandidateRegistered()) {
224             LOG.debug("Tx-EntityOwnershipRegistration is active for entity type {} and node {}",
225                     ownershipChange.getEntity().getType(),
226                     roleContext.getNodeId());
227             if (!ownershipChange.wasOwner() && ownershipChange.isOwner()) {
228                 // SLAVE -> MASTER
229                 LOG.debug("SLAVE to MASTER for node {}", roleContext.getNodeId());
230                 makeDeviceRoleChange(OfpRole.BECOMEMASTER, roleContext,false);
231             } else if (ownershipChange.wasOwner() && !ownershipChange.isOwner()) {
232                 // MASTER -> SLAVE
233                 LOG.debug("MASTER to SLAVE for node {}", roleContext.getNodeId());
234                 LOG.warn("Tx-EntityOwnershipRegistration lost leadership entity type {} and node {}",
235                         ownershipChange.getEntity().getType(),roleContext.getNodeId());
236                 watchingEntities.remove(roleContext.getTxEntity(), roleContext);
237                 watchingEntities.remove(roleContext.getEntity(), roleContext);
238                 roleContext.unregisterCandidate(roleContext.getEntity());
239                 roleContext.unregisterCandidate(roleContext.getTxEntity());
240                 if (!ownershipChange.hasOwner()) {
241                     LOG.debug("Trying to remove from operational node: {}", roleContext.getNodeId());
242                     removeDeviceFromOperationalDS(roleContext.getNodeId());
243                 } else {
244                     final NodeId nodeId = roleContext.getNodeId();
245                     contexts.remove(nodeId, roleContext);
246                     roleContext.close();
247                     conductor.closeConnection(nodeId);
248                 }
249             }
250         } else {
251             LOG.debug("Tx-EntityOwnershipRegistration is not active for entity {}", ownershipChange.getEntity().getType());
252             watchingEntities.remove(roleContext.getTxEntity(), roleContext);
253             final NodeId nodeId = roleContext.getNodeId();
254             contexts.remove(nodeId, roleContext);
255             roleContext.close();
256             conductor.closeConnection(nodeId);
257         }
258     }
259
260     @VisibleForTesting
261     void makeDeviceRoleChange(final OfpRole role, final RoleContext roleContext, final Boolean init) {
262         final ListenableFuture<RpcResult<SetRoleOutput>> roleChangeFuture = sendRoleChangeToDevice(role, roleContext);
263         Futures.addCallback(roleChangeFuture, new FutureCallback<RpcResult<SetRoleOutput>>() {
264             @Override
265             public void onSuccess(@Nullable final RpcResult<SetRoleOutput> setRoleOutputRpcResult) {
266                 LOG.info("Role {} successfully set on device {}", role, roleContext.getNodeId());
267                 notifyListenersRoleChangeOnDevice(roleContext.getNodeId(), true, role, init);
268             }
269
270             @Override
271             public void onFailure(@Nonnull final Throwable throwable) {
272                 LOG.warn("Unable to set role {} on device {}", role, roleContext.getNodeId());
273                 notifyListenersRoleChangeOnDevice(roleContext.getNodeId(), false, role, init);
274             }
275         });
276     }
277
278
279     private ListenableFuture<RpcResult<SetRoleOutput>> sendRoleChangeToDevice(final OfpRole newRole, final RoleContext roleContext) {
280         LOG.debug("Sending new role {} to device {}", newRole, roleContext.getNodeId());
281         final Future<RpcResult<SetRoleOutput>> setRoleOutputFuture;
282         final Short version = conductor.gainVersionSafely(roleContext.getNodeId());
283         if (null == version) {
284             LOG.debug("Device version is null");
285             return Futures.immediateFuture(null);
286         }
287         if (version < OFConstants.OFP_VERSION_1_3) {
288             LOG.debug("Device version not support ROLE");
289             return Futures.immediateFuture(null);
290         } else {
291             final SetRoleInput setRoleInput = (new SetRoleInputBuilder()).setControllerRole(newRole)
292                     .setNode(new NodeRef(DeviceStateUtil.createNodeInstanceIdentifier(roleContext.getNodeId()))).build();
293             setRoleOutputFuture = roleContext.getSalRoleService().setRole(setRoleInput);
294             final TimerTask timerTask = new TimerTask() {
295
296                 @Override
297                 public void run(final Timeout timeout) throws Exception {
298                     if (!setRoleOutputFuture.isDone()) {
299                         LOG.warn("New role {} was not propagated to device {} during 10 sec", newRole, roleContext.getNodeId());
300                         setRoleOutputFuture.cancel(true);
301                     }
302                 }
303             };
304             conductor.newTimeout(timerTask, 10, TimeUnit.SECONDS);
305         }
306         return JdkFutureAdapters.listenInPoolThread(setRoleOutputFuture);
307     }
308
309     @VisibleForTesting
310     CheckedFuture<Void, TransactionCommitFailedException> removeDeviceFromOperationalDS(final NodeId nodeId) {
311
312         final WriteTransaction delWtx = dataBroker.newWriteOnlyTransaction();
313         delWtx.delete(LogicalDatastoreType.OPERATIONAL, DeviceStateUtil.createNodeInstanceIdentifier(nodeId));
314         final CheckedFuture<Void, TransactionCommitFailedException> delFuture = delWtx.submit();
315         Futures.addCallback(delFuture, new FutureCallback<Void>() {
316
317             @Override
318             public void onSuccess(final Void result) {
319                 LOG.debug("Delete Node {} was successful", nodeId);
320                 final RoleContext roleContext = contexts.remove(nodeId);
321                 if (roleContext != null) {
322                     roleContext.close();
323                 }
324             }
325
326             @Override
327             public void onFailure(@Nonnull final Throwable t) {
328                 LOG.warn("Delete Node {} failed. {}", nodeId, t);
329                 contexts.remove(nodeId);
330                 final RoleContext roleContext = contexts.remove(nodeId);
331                 if (roleContext != null) {
332                     roleContext.close();
333                 }
334             }
335         });
336         return delFuture;
337     }
338
339     @Override
340     public void setDeviceTerminationPhaseHandler(final DeviceTerminationPhaseHandler handler) {
341         deviceTerminationPhaseHandler = handler;
342     }
343
344     @Override
345     public void servicesChangeDone(final NodeId nodeId, final boolean success) {
346         LOG.debug("Services stopping done for node {} as " + (success ? "successful" : "unsuccessful"), nodeId);
347         final RoleContext roleContext = contexts.get(nodeId);
348         if (null != roleContext) {
349             /* Services stopped or failure */
350             roleContext.unregisterCandidate(roleContext.getTxEntity());
351         }
352     }
353
354     @VisibleForTesting
355     RoleContext getRoleContext(final NodeId nodeId){
356         return contexts.get(nodeId);
357     }
358
359     @Override
360     public void addRoleChangeListener(final RoleChangeListener roleChangeListener) {
361         this.listeners.add(roleChangeListener);
362     }
363
364     /**
365      * Invoked when initialization phase is done
366      * @param nodeId node identification
367      * @param success true if initialization done ok, false otherwise
368      */
369     @VisibleForTesting
370     void notifyListenersRoleInitializationDone(final NodeId nodeId, final boolean success){
371         LOG.debug("Notifying registered listeners for role initialization done, no. of listeners {}", listeners.size());
372         for (final RoleChangeListener listener : listeners) {
373             listener.roleInitializationDone(nodeId, success);
374         }
375     }
376
377     /**
378      * Notifies registered listener on role change. Role is the new role on device
379      * If initialization phase is true, we may skip service starting
380      * @param success true if role change on device done ok, false otherwise
381      * @param role new role meant to be set on device
382      * @param initializationPhase if true, then skipp services start
383      */
384     @VisibleForTesting
385     void notifyListenersRoleChangeOnDevice(final NodeId nodeId, final boolean success, final OfpRole role, final boolean initializationPhase){
386         LOG.debug("Notifying registered listeners for role change, no. of listeners {}", listeners.size());
387         for (final RoleChangeListener listener : listeners) {
388             listener.roleChangeOnDevice(nodeId, success, role, initializationPhase);
389         }
390     }
391
392 }