20f063f5c24fac2c03f9ab20501880b3356c164b
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / services / sal / SalRoleServiceImpl.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.services.sal;
9
10 import com.google.common.base.Preconditions;
11 import com.google.common.util.concurrent.AsyncFunction;
12 import com.google.common.util.concurrent.FutureCallback;
13 import com.google.common.util.concurrent.Futures;
14 import com.google.common.util.concurrent.JdkFutureAdapters;
15 import com.google.common.util.concurrent.ListenableFuture;
16 import com.google.common.util.concurrent.SettableFuture;
17 import java.math.BigInteger;
18 import java.util.concurrent.Future;
19 import java.util.concurrent.Semaphore;
20 import javax.annotation.concurrent.GuardedBy;
21 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext.CONNECTION_STATE;
22 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
23 import org.opendaylight.openflowplugin.api.openflow.device.RequestContextStack;
24 import org.opendaylight.openflowplugin.api.openflow.device.Xid;
25 import org.opendaylight.openflowplugin.impl.role.RoleChangeException;
26 import org.opendaylight.openflowplugin.impl.services.AbstractSimpleService;
27 import org.opendaylight.openflowplugin.impl.services.RoleService;
28 import org.opendaylight.openflowplugin.impl.services.util.ServiceException;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestOutput;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.OfpRole;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.SalRoleService;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.SetRoleInput;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.SetRoleOutput;
35 import org.opendaylight.yangtools.yang.common.RpcResult;
36 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40
41 public final class SalRoleServiceImpl extends AbstractSimpleService<SetRoleInput, SetRoleOutput> implements SalRoleService  {
42
43     private static final Logger LOG = LoggerFactory.getLogger(SalRoleServiceImpl.class);
44
45     private static final BigInteger MAX_GENERATION_ID = new BigInteger("ffffffffffffffff", 16);
46
47     private static final int MAX_RETRIES = 42;
48
49     private final DeviceContext deviceContext;
50     private final RoleService roleService;
51
52     private final Semaphore currentRoleGuard = new Semaphore(1, true);
53
54     @GuardedBy("currentRoleGuard")
55     private OfpRole currentRole = OfpRole.NOCHANGE;
56
57     public SalRoleServiceImpl(final RequestContextStack requestContextStack, final DeviceContext deviceContext) {
58         super(requestContextStack, deviceContext, SetRoleOutput.class);
59         this.deviceContext = Preconditions.checkNotNull(deviceContext);
60         this.roleService =  new RoleService(requestContextStack, deviceContext, RoleRequestOutput.class);
61     }
62
63     @Override
64     protected OfHeader buildRequest(final Xid xid, final SetRoleInput input) throws ServiceException {
65         return null;
66     }
67
68     @Override
69     public Future<RpcResult<SetRoleOutput>> setRole(final SetRoleInput input) {
70         LOG.info("SetRole called with input:{}", input);
71         try {
72             currentRoleGuard.acquire();
73             LOG.trace("currentRole lock queue length: {} " + currentRoleGuard.getQueueLength());
74         } catch (final InterruptedException e) {
75             LOG.error("Unexpected exception {} for acquire semaphore for input {}", e, input);
76             return RpcResultBuilder.<SetRoleOutput> failed().buildFuture();
77         }
78         // compare with last known role and set if different. If they are same, then return.
79         if (currentRole.equals(input.getControllerRole())) {
80             LOG.info("Role to be set is same as the last known role for the device:{}. Hence ignoring.",
81                     input.getControllerRole());
82             currentRoleGuard.release();
83             return RpcResultBuilder.<SetRoleOutput> success().buildFuture();
84         }
85
86         final SettableFuture<RpcResult<SetRoleOutput>> resultFuture = SettableFuture.create();
87         repeaterForChangeRole(resultFuture, input, 0);
88         /* Add Callback for release Guard */
89         Futures.addCallback(resultFuture, new FutureCallback<RpcResult<SetRoleOutput>>() {
90
91             @Override
92             public void onSuccess(final RpcResult<SetRoleOutput> result) {
93                 LOG.debug("SetRoleService for Node: {} is ok Role: {}", input.getNode().getValue(),
94                         input.getControllerRole());
95                 currentRoleGuard.release();
96             }
97
98             @Override
99             public void onFailure(final Throwable t) {
100                 LOG.error("SetRoleService set Role {} for Node: {} fail . Reason {}", input.getControllerRole(),
101                         input.getNode().getValue(), t);
102                 currentRoleGuard.release();
103             }
104         });
105         return resultFuture;
106     }
107
108     private void repeaterForChangeRole(final SettableFuture<RpcResult<SetRoleOutput>> future, final SetRoleInput input,
109             final int retryCounter) {
110         if (future.isCancelled()) {
111             future.setException(new RoleChangeException(String.format(
112                     "Set Role for device %s stop because Future was canceled", input.getNode().getValue())));
113             return;
114         }
115         if (retryCounter >= MAX_RETRIES) {
116             future.setException(new RoleChangeException(String.format("Set Role failed after %s tries on device %s",
117                     MAX_RETRIES, input.getNode().getValue())));
118             return;
119         }
120         // Check current connection state
121         final CONNECTION_STATE state = deviceContext.getPrimaryConnectionContext().getConnectionState();
122         switch (state) {
123         case RIP:
124             LOG.info("Device {} has been disconnected", input.getNode());
125             future.setException(new Exception(String.format(
126                     "Device connection doesn't exist anymore. Primary connection status : %s", state)));
127             return;
128         case WORKING:
129             // We can proceed
130             LOG.trace("Device {} has been working", input.getNode());
131             break;
132         default:
133             LOG.warn("Device {} is in state {}, role change is not allowed", input.getNode(), state);
134             future.setException(new Exception(String.format("Unexcpected device connection status : %s", state)));
135             return;
136         }
137
138         LOG.info("Requesting state change to {}", input.getControllerRole());
139         final ListenableFuture<RpcResult<SetRoleOutput>> changeRoleFuture = tryToChangeRole(input.getControllerRole());
140         Futures.addCallback(changeRoleFuture, new FutureCallback<RpcResult<SetRoleOutput>>() {
141
142             @Override
143             public void onSuccess(final RpcResult<SetRoleOutput> result) {
144                 if (result.isSuccessful()) {
145                     LOG.debug("setRoleOutput received after roleChangeTask execution:{}", result);
146                     currentRole = input.getControllerRole();
147                     future.set(RpcResultBuilder.<SetRoleOutput> success().withResult(result.getResult()).build());
148                 } else {
149                     LOG.error("setRole() failed with errors, will retry: {} times.", MAX_RETRIES - retryCounter);
150                     repeaterForChangeRole(future, input, (retryCounter + 1));
151                 }
152             }
153
154             @Override
155             public void onFailure(final Throwable t) {
156                 LOG.error("Exception in setRole(), will retry: {} times.", t, MAX_RETRIES - retryCounter);
157                 repeaterForChangeRole(future, input, (retryCounter + 1));
158             }
159         });
160     }
161
162     private ListenableFuture<RpcResult<SetRoleOutput>> tryToChangeRole(final OfpRole role) {
163         LOG.info("RoleChangeTask called on device:{} OFPRole:{}", getDeviceInfo().getNodeId().getValue(), role);
164
165         final Future<BigInteger> generationFuture = roleService.getGenerationIdFromDevice(getVersion());
166
167         return Futures.transform(JdkFutureAdapters.listenInPoolThread(generationFuture), (AsyncFunction<BigInteger, RpcResult<SetRoleOutput>>) generationId -> {
168             LOG.debug("RoleChangeTask, GenerationIdFromDevice from device {} is {}", getDeviceInfo().getNodeId().getValue(), generationId);
169             final BigInteger nextGenerationId = getNextGenerationId(generationId);
170             LOG.debug("nextGenerationId received from device:{} is {}", getDeviceInfo().getNodeId().getValue(), nextGenerationId);
171             final Future<RpcResult<SetRoleOutput>> submitRoleFuture = roleService.submitRoleChange(role, getVersion(), nextGenerationId);
172             return JdkFutureAdapters.listenInPoolThread(submitRoleFuture);
173         });
174     }
175
176     private static BigInteger getNextGenerationId(final BigInteger generationId) {
177         if (generationId.compareTo(MAX_GENERATION_ID) < 0) {
178             return generationId.add(BigInteger.ONE);
179         } else {
180             return BigInteger.ZERO;
181         }
182     }
183 }