Merge "Bug 5596 Cleaning lifecycle conductor"
[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 io.netty.util.HashedWheelTimer;
18 import java.util.Iterator;
19 import java.util.concurrent.ConcurrentHashMap;
20 import java.util.concurrent.ConcurrentMap;
21 import javax.annotation.CheckForNull;
22 import javax.annotation.Nonnull;
23 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
24 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
25 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
26 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
27 import org.opendaylight.openflowplugin.api.openflow.OFPContext;
28 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
29 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
30 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
31 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceTerminationPhaseHandler;
32 import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleService;
33 import org.opendaylight.openflowplugin.api.openflow.role.RoleContext;
34 import org.opendaylight.openflowplugin.api.openflow.role.RoleManager;
35 import org.opendaylight.openflowplugin.impl.services.SalRoleServiceImpl;
36 import org.opendaylight.openflowplugin.impl.util.DeviceStateUtil;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 /**
41  * Gets invoked from RpcManagerInitial, registers a candidate with EntityOwnershipService.
42  * On receipt of the ownership notification, makes an rpc call to SalRoleService.
43  *
44  * Hands over to StatisticsManager at the end.
45  */
46 public class RoleManagerImpl implements RoleManager {
47     private static final Logger LOG = LoggerFactory.getLogger(RoleManagerImpl.class);
48
49     // Maximum limit of timeout retries when cleaning DS, to prevent infinite recursive loops
50     private static final int MAX_CLEAN_DS_RETRIES = 3;
51
52     private DeviceInitializationPhaseHandler deviceInitializationPhaseHandler;
53     private DeviceTerminationPhaseHandler deviceTerminationPhaseHandler;
54     private final DataBroker dataBroker;
55     private final ConcurrentMap<DeviceInfo, RoleContext> contexts = new ConcurrentHashMap<>();
56     private final HashedWheelTimer hashedWheelTimer;
57
58     public RoleManagerImpl(final DataBroker dataBroker, final HashedWheelTimer hashedWheelTimer) {
59         this.dataBroker = Preconditions.checkNotNull(dataBroker);
60         this.hashedWheelTimer = hashedWheelTimer;
61     }
62
63     @Override
64     public void setDeviceInitializationPhaseHandler(final DeviceInitializationPhaseHandler handler) {
65         deviceInitializationPhaseHandler = handler;
66     }
67
68     @Override
69     public void onDeviceContextLevelUp(@CheckForNull final DeviceInfo deviceInfo, final LifecycleService lifecycleService) throws Exception {
70         final DeviceContext deviceContext = Preconditions.checkNotNull(lifecycleService.getDeviceContext());
71         final RoleContext roleContext = new RoleContextImpl(deviceInfo, hashedWheelTimer, this);
72         roleContext.setSalRoleService(new SalRoleServiceImpl(roleContext, deviceContext));
73         Verify.verify(contexts.putIfAbsent(deviceInfo, roleContext) == null, "Role context for master Node %s is still not closed.", deviceInfo.getNodeId());
74         lifecycleService.setRoleContext(roleContext);
75         deviceInitializationPhaseHandler.onDeviceContextLevelUp(deviceInfo, lifecycleService);
76     }
77
78     @Override
79     public void close() {
80         LOG.debug("Close method on role manager was called.");
81         for (final Iterator<RoleContext> iterator = Iterators.consumingIterator(contexts.values().iterator()); iterator.hasNext();) {
82             // got here because last known role is LEADER and DS might need clearing up
83             final RoleContext roleContext = iterator.next();
84             contexts.remove(roleContext.getDeviceInfo());
85             removeDeviceFromOperationalDS(roleContext.getDeviceInfo(), MAX_CLEAN_DS_RETRIES);
86         }
87     }
88
89     @Override
90     public void onDeviceContextLevelDown(final DeviceInfo deviceInfo) {
91         LOG.trace("onDeviceContextLevelDown for node {}", deviceInfo.getNodeId());
92         final RoleContext roleContext = contexts.remove(deviceInfo);
93         if (roleContext != null) {
94             LOG.debug("Found roleContext associated to deviceContext: {}, now trying close the roleContext", deviceInfo.getNodeId());
95             contexts.remove(deviceInfo.getNodeId(), roleContext);
96         }
97         deviceTerminationPhaseHandler.onDeviceContextLevelDown(deviceInfo);
98     }
99
100     @Override
101     public CheckedFuture<Void, TransactionCommitFailedException> removeDeviceFromOperationalDS(final DeviceInfo deviceInfo, final int numRetries) {
102         final WriteTransaction delWtx = dataBroker.newWriteOnlyTransaction();
103         delWtx.delete(LogicalDatastoreType.OPERATIONAL, DeviceStateUtil.createNodeInstanceIdentifier(deviceInfo.getNodeId()));
104         final CheckedFuture<Void, TransactionCommitFailedException> delFuture = delWtx.submit();
105
106         Futures.addCallback(delFuture, new FutureCallback<Void>() {
107             @Override
108             public void onSuccess(final Void result) {
109                 LOG.debug("Delete Node {} was successful", deviceInfo);
110                 contexts.remove(deviceInfo);
111             }
112
113             @Override
114             public void onFailure(@Nonnull final Throwable t) {
115                 // If we have any retries left, we will try to clean the datastore again
116                 if (numRetries > 0) {
117                     // We "used" one retry here, so decrement it
118                     final int curRetries = numRetries - 1;
119                     LOG.debug("Delete node {} failed with exception {}. Trying again (retries left: {})", deviceInfo.getNodeId(), t, curRetries);
120                     // Recursive call to this method with "one less" retry
121                     removeDeviceFromOperationalDS(deviceInfo, curRetries);
122                     return;
123                 }
124
125                 // No retries left, so we will just close the role context, and ignore datastore cleanup
126                 LOG.warn("Delete node {} failed with exception {}. No retries left, aborting", deviceInfo.getNodeId(), t);
127                 contexts.remove(deviceInfo);
128             }
129         });
130
131         return delFuture;
132     }
133
134     @Override
135     public void setDeviceTerminationPhaseHandler(final DeviceTerminationPhaseHandler handler) {
136         deviceTerminationPhaseHandler = handler;
137     }
138
139     @VisibleForTesting
140     RoleContext getRoleContext(final DeviceInfo deviceInfo){
141         return contexts.get(deviceInfo);
142     }
143
144     @Override
145     public <T extends OFPContext> T gainContext(final DeviceInfo deviceInfo) {
146         return (T) contexts.get(deviceInfo);
147     }
148 }