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