Merge "BUG-5020 Handling exception while submission"
[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 javax.annotation.Nullable;
11 import java.util.concurrent.Future;
12
13 import com.google.common.annotations.VisibleForTesting;
14 import com.google.common.base.Preconditions;
15 import com.google.common.util.concurrent.FutureCallback;
16 import com.google.common.util.concurrent.Futures;
17 import com.google.common.util.concurrent.JdkFutureAdapters;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import com.google.common.util.concurrent.SettableFuture;
20 import org.opendaylight.controller.md.sal.common.api.clustering.CandidateAlreadyRegisteredException;
21 import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
22 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipCandidateRegistration;
23 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
24 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
25 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
26 import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
27 import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
28 import org.opendaylight.openflowplugin.api.openflow.role.RoleContext;
29 import org.opendaylight.openflowplugin.impl.rpc.AbstractRequestContext;
30 import org.opendaylight.openflowplugin.impl.services.SalRoleServiceImpl;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.OfpRole;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.SalRoleService;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.SetRoleInput;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.SetRoleInputBuilder;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.SetRoleOutput;
37 import org.opendaylight.yangtools.yang.common.RpcResult;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 /**
42  * Created by kramesha on 9/12/15.
43  */
44 public class RoleContextImpl implements RoleContext {
45     private static final Logger LOG = LoggerFactory.getLogger(RoleContextImpl.class);
46
47     private final EntityOwnershipService entityOwnershipService;
48     private EntityOwnershipCandidateRegistration entityOwnershipCandidateRegistration;
49     private final DeviceContext deviceContext;
50     private final Entity entity;
51     private SalRoleService salRoleService;
52
53     private final SettableFuture<OfpRole> initRoleChangeFuture;
54
55     public RoleContextImpl(final DeviceContext deviceContext, final EntityOwnershipService entityOwnershipService, final Entity entity) {
56         this.entityOwnershipService = Preconditions.checkNotNull(entityOwnershipService);
57         this.deviceContext = Preconditions.checkNotNull(deviceContext);
58         this.entity = Preconditions.checkNotNull(entity);
59
60         salRoleService = new SalRoleServiceImpl(this, deviceContext);
61         initRoleChangeFuture = SettableFuture.create();
62     }
63
64     @Override
65     public ListenableFuture<OfpRole> initialization() {
66         LOG.debug("Initialization requestOpenflowEntityOwnership for entity {}", entity);
67         try {
68             entityOwnershipCandidateRegistration = entityOwnershipService.registerCandidate(entity);
69             LOG.debug("RoleContextImpl : Candidate registered with ownership service for device :{}", deviceContext
70                     .getPrimaryConnectionContext().getNodeId().getValue());
71         } catch (final CandidateAlreadyRegisteredException e) {
72             completeInitRoleChangeFuture(null, e);
73         }
74         return initRoleChangeFuture;
75     }
76
77     @Override
78     public void onRoleChanged(final OfpRole oldRole, final OfpRole newRole) {
79         LOG.trace("onRoleChanged method call for Entity {}", entity);
80
81         if (!isDeviceConnected()) {
82             // this can happen as after the disconnect, we still get a last messsage from EntityOwnershipService.
83             LOG.info("Device {} is disconnected from this node. Hence not attempting a role change.",
84                     deviceContext.getPrimaryConnectionContext().getNodeId());
85             completeInitRoleChangeFuture(null, null);
86             return;
87         }
88
89         LOG.debug("Role change received from ownership listener from {} to {} for device:{}", oldRole, newRole,
90                 deviceContext.getPrimaryConnectionContext().getNodeId());
91
92         final SetRoleInput setRoleInput = (new SetRoleInputBuilder())
93                 .setControllerRole(newRole)
94                 .setNode(new NodeRef(deviceContext.getDeviceState().getNodeInstanceIdentifier()))
95                 .build();
96
97         final Future<RpcResult<SetRoleOutput>> setRoleOutputFuture = salRoleService.setRole(setRoleInput);
98
99         Futures.addCallback(JdkFutureAdapters.listenInPoolThread(setRoleOutputFuture), new FutureCallback<RpcResult<SetRoleOutput>>() {
100             @Override
101             public void onSuccess(final RpcResult<SetRoleOutput> setRoleOutputRpcResult) {
102                 LOG.debug("Rolechange {} successful made on switch :{}", newRole,
103                         deviceContext.getPrimaryConnectionContext().getNodeId());
104                 deviceContext.getDeviceState().setRole(newRole);
105                 deviceContext.onClusterRoleChange(newRole);
106                 completeInitRoleChangeFuture(newRole, null);
107             }
108
109             @Override
110             public void onFailure(final Throwable throwable) {
111                 LOG.error("Error in setRole {} for device {} ", newRole,
112                         deviceContext.getPrimaryConnectionContext().getNodeId(), throwable);
113                 completeInitRoleChangeFuture(null, throwable);
114             }
115         });
116     }
117
118     void completeInitRoleChangeFuture(@Nullable final OfpRole role, @Nullable final Throwable throwable) {
119         if (initRoleChangeFuture.isDone()) {
120             return;
121         }
122         if (!isDeviceConnected()) {
123             LOG.debug("Device {} is disconnected from this node. Hence not attempting a role change.", deviceContext
124                     .getPrimaryConnectionContext().getNodeId());
125             initRoleChangeFuture.cancel(true);
126             return;
127         }
128         if (throwable != null) {
129             LOG.warn("Connection Role change fail for entity {}", entity);
130             initRoleChangeFuture.setException(throwable);
131         } else if (role != null) {
132             LOG.debug("Initialization Role for entity {} is chosed {}", entity, role);
133             initRoleChangeFuture.set(role);
134         } else {
135             LOG.debug("Unexpected initialization Role Change close for entity {}", entity);
136             initRoleChangeFuture.cancel(true);
137         }
138     }
139
140     @Override
141     public void close() {
142         if (entityOwnershipCandidateRegistration != null) {
143             LOG.debug("Closing EntityOwnershipCandidateRegistration for {}", entity);
144             entityOwnershipCandidateRegistration.close();
145         }
146     }
147
148     @Override
149     public Entity getEntity() {
150         return entity;
151     }
152
153     private boolean isDeviceConnected() {
154         return ConnectionContext.CONNECTION_STATE.WORKING.equals(
155                 deviceContext.getPrimaryConnectionContext().getConnectionState());
156     }
157
158     @Nullable
159     @Override
160     public <T> RequestContext<T> createRequestContext() {
161         final AbstractRequestContext<T> ret = new AbstractRequestContext<T>(deviceContext.getReservedXid()) {
162             @Override
163             public void close() {
164             }
165         };
166         return ret;
167     }
168
169     @VisibleForTesting
170     void setSalRoleService(final SalRoleService salRoleService) {
171         this.salRoleService = salRoleService;
172     }
173
174     @Override
175     public DeviceState getDeviceState() {
176         return deviceContext.getDeviceState();
177     }
178 }