Merge "Bug 4957 RoleContext updated with initialization"
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / role / RoleContextImpl.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.util.concurrent.FutureCallback;
12 import com.google.common.util.concurrent.Futures;
13 import com.google.common.util.concurrent.JdkFutureAdapters;
14 import com.google.common.util.concurrent.SettableFuture;
15 import java.util.concurrent.Future;
16 import javax.annotation.Nullable;
17 import org.opendaylight.controller.md.sal.common.api.clustering.CandidateAlreadyRegisteredException;
18 import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
19 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipCandidateRegistration;
20 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
21 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
22 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
23 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
24 import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
25 import org.opendaylight.openflowplugin.api.openflow.role.RoleContext;
26 import org.opendaylight.openflowplugin.api.openflow.role.RoleManager;
27 import org.opendaylight.openflowplugin.impl.rpc.AbstractRequestContext;
28 import org.opendaylight.openflowplugin.impl.services.SalRoleServiceImpl;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.OfpRole;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.SalRoleService;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.SetRoleInput;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.SetRoleInputBuilder;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.SetRoleOutput;
35 import org.opendaylight.yangtools.yang.common.RpcResult;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 /**
40  * Created by kramesha on 9/12/15.
41  */
42 public class RoleContextImpl implements RoleContext {
43     private static final Logger LOG = LoggerFactory.getLogger(RoleContextImpl.class);
44
45     private final EntityOwnershipService entityOwnershipService;
46     private EntityOwnershipCandidateRegistration entityOwnershipCandidateRegistration;
47     private final RpcProviderRegistry rpcProviderRegistry;
48     private final DeviceContext deviceContext;
49     private final Entity entity;
50     private final OpenflowOwnershipListener openflowOwnershipListener;
51     private SalRoleService salRoleService;
52     private FutureCallback<Boolean> roleChangeCallback;
53
54     private final SettableFuture<OfpRole> initRoleChangeFuture;
55
56     public RoleContextImpl(final DeviceContext deviceContext, final RpcProviderRegistry rpcProviderRegistry,
57                            final EntityOwnershipService entityOwnershipService, final OpenflowOwnershipListener openflowOwnershipListener) {
58         this.entityOwnershipService = entityOwnershipService;
59         this.rpcProviderRegistry = rpcProviderRegistry;
60         this.deviceContext = deviceContext;
61         entity = new Entity(RoleManager.ENTITY_TYPE, deviceContext.getPrimaryConnectionContext().getNodeId().getValue());
62
63         this.openflowOwnershipListener =  openflowOwnershipListener;
64         salRoleService = new SalRoleServiceImpl(this, deviceContext);
65
66         initRoleChangeFuture = SettableFuture.create();
67     }
68
69     @Override
70     public Future<OfpRole> initialization() throws CandidateAlreadyRegisteredException {
71         LOG.debug("Initialization requestOpenflowEntityOwnership for entity {}", entity);
72         openflowOwnershipListener.registerRoleChangeListener(this);
73         entityOwnershipCandidateRegistration = entityOwnershipService.registerCandidate(entity);
74         LOG.info("RoleContextImpl : Candidate registered with ownership service for device :{}", deviceContext
75                 .getPrimaryConnectionContext().getNodeId().getValue());
76         return initRoleChangeFuture;
77     }
78
79     @Override
80     public void facilitateRoleChange(final FutureCallback<Boolean> roleChangeCallback) {
81         this.roleChangeCallback = roleChangeCallback;
82         if (!isDeviceConnected()) {
83             throw new IllegalStateException(
84                     "Device is disconnected. Giving up on Role Change:" + deviceContext.getDeviceState().getNodeId());
85         }
86     }
87
88     private void requestOpenflowEntityOwnership() {
89
90         LOG.debug("requestOpenflowEntityOwnership for entity {}", entity);
91         try {
92             entityOwnershipCandidateRegistration = entityOwnershipService.registerCandidate(entity);
93
94             // The role change listener must be registered after registering a candidate
95             openflowOwnershipListener.registerRoleChangeListener(this);
96             LOG.info("RoleContextImpl : Candidate registered with ownership service for device :{}", deviceContext.getPrimaryConnectionContext().getNodeId().getValue());
97         } catch (final CandidateAlreadyRegisteredException e) {
98             // we can log and move for this error, as listener is present and role changes will be served.
99             LOG.error("Candidate - Entity already registered with Openflow candidate ", entity, e );
100         }
101     }
102
103     @Override
104     public void onRoleChanged(final OfpRole oldRole, final OfpRole newRole) {
105         LOG.trace("onRoleChanged method call for Entity {}", entity);
106
107         if (!isDeviceConnected()) {
108             // this can happen as after the disconnect, we still get a last messsage from EntityOwnershipService.
109             LOG.info("Device {} is disconnected from this node. Hence not attempting a role change.",
110                     deviceContext.getPrimaryConnectionContext().getNodeId());
111             if (!initRoleChangeFuture.isDone()) {
112                 LOG.debug("RoleChange is not valid for initialization Entity {} anymore - Device is disconnected", entity);
113                 initRoleChangeFuture.cancel(true);
114             }
115             return;
116         }
117
118         if (!initRoleChangeFuture.isDone()) {
119             LOG.debug("Initialization Role for entity {} is chosed {}", entity, newRole);
120             initRoleChangeFuture.set(newRole);
121         }
122
123         LOG.debug("Role change received from ownership listener from {} to {} for device:{}", oldRole, newRole,
124                 deviceContext.getPrimaryConnectionContext().getNodeId());
125
126         final SetRoleInput setRoleInput = (new SetRoleInputBuilder())
127                 .setControllerRole(newRole)
128                 .setNode(new NodeRef(deviceContext.getDeviceState().getNodeInstanceIdentifier()))
129                 .build();
130
131         final Future<RpcResult<SetRoleOutput>> setRoleOutputFuture = salRoleService.setRole(setRoleInput);
132
133         Futures.addCallback(JdkFutureAdapters.listenInPoolThread(setRoleOutputFuture), new FutureCallback<RpcResult<SetRoleOutput>>() {
134             @Override
135             public void onSuccess(final RpcResult<SetRoleOutput> setRoleOutputRpcResult) {
136                 LOG.debug("Rolechange {} successful made on switch :{}", newRole,
137                         deviceContext.getPrimaryConnectionContext().getNodeId());
138                 deviceContext.getDeviceState().setRole(newRole);
139                 if (roleChangeCallback != null) {
140                     roleChangeCallback.onSuccess(true);
141                 }
142             }
143
144             @Override
145             public void onFailure(final Throwable throwable) {
146                 LOG.error("Error in setRole {} for device {} ", newRole,
147                         deviceContext.getPrimaryConnectionContext().getNodeId(), throwable);
148                 if (roleChangeCallback != null) {
149                     roleChangeCallback.onFailure(throwable);
150                 }
151             }
152         });
153     }
154
155     @Override
156     public void close() throws Exception {
157         if (entityOwnershipCandidateRegistration != null) {
158             LOG.debug("Closing EntityOwnershipCandidateRegistration for {}", entity);
159             entityOwnershipCandidateRegistration.close();
160         }
161     }
162
163     @Override
164     public void onDeviceContextClosed(final DeviceContext deviceContext) {
165         try {
166             LOG.debug("onDeviceContextClosed called");
167             this.close();
168         } catch (final Exception e) {
169             LOG.error("Exception in onDeviceContextClosed of RoleContext", e);
170         }
171     }
172
173     @Override
174     public Entity getEntity() {
175         return entity;
176     }
177
178     @Override
179     public void onDeviceDisconnectedFromCluster() {
180         LOG.debug("Called onDeviceDisconnectedFromCluster in DeviceContext for entity:{}", entity);
181         deviceContext.onDeviceDisconnectedFromCluster();
182     }
183
184     private boolean isDeviceConnected() {
185         return ConnectionContext.CONNECTION_STATE.WORKING.equals(
186                 deviceContext.getPrimaryConnectionContext().getConnectionState());
187     }
188
189     @Nullable
190     @Override
191     public <T> RequestContext<T> createRequestContext() {
192         final AbstractRequestContext<T> ret = new AbstractRequestContext<T>(deviceContext.getReservedXid()) {
193             @Override
194             public void close() {
195             }
196         };
197         return ret;
198     }
199
200     @VisibleForTesting
201     public void setSalRoleService(final SalRoleService salRoleService) {
202         this.salRoleService = salRoleService;
203     }
204 }