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