2 * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.cluster.datastore.entityownership;
10 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_OWNERS_PATH;
11 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_OWNER_NODE_ID;
12 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_OWNER_QNAME;
13 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.entityOwnersWithCandidate;
14 import akka.actor.ActorRef;
15 import akka.actor.ActorSelection;
16 import akka.actor.Props;
17 import akka.pattern.Patterns;
18 import com.google.common.base.Optional;
19 import java.util.Collection;
21 import java.util.concurrent.TimeUnit;
22 import org.opendaylight.controller.cluster.datastore.DatastoreContext;
23 import org.opendaylight.controller.cluster.datastore.Shard;
24 import org.opendaylight.controller.cluster.datastore.entityownership.messages.CandidateAdded;
25 import org.opendaylight.controller.cluster.datastore.entityownership.messages.CandidateRemoved;
26 import org.opendaylight.controller.cluster.datastore.entityownership.messages.RegisterCandidateLocal;
27 import org.opendaylight.controller.cluster.datastore.entityownership.messages.UnregisterCandidateLocal;
28 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
29 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
30 import org.opendaylight.controller.cluster.datastore.messages.SuccessReply;
31 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
32 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
34 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
36 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
37 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
38 import scala.concurrent.Future;
41 * Special Shard for EntityOwnership.
43 * @author Thomas Pantelis
45 class EntityOwnershipShard extends Shard {
46 private final String localMemberName;
47 private final EntityOwnershipShardCommitCoordinator commitCoordinator;
48 private final EntityOwnershipListenerSupport listenerSupport;
50 private static DatastoreContext noPersistenceDatastoreContext(DatastoreContext datastoreContext) {
51 return DatastoreContext.newBuilderFrom(datastoreContext).persistent(false).build();
54 protected EntityOwnershipShard(ShardIdentifier name, Map<String, String> peerAddresses,
55 DatastoreContext datastoreContext, SchemaContext schemaContext, String localMemberName) {
56 super(name, peerAddresses, noPersistenceDatastoreContext(datastoreContext), schemaContext);
57 this.localMemberName = localMemberName;
58 this.commitCoordinator = new EntityOwnershipShardCommitCoordinator(localMemberName, LOG);
59 this.listenerSupport = new EntityOwnershipListenerSupport(getContext());
63 protected void onDatastoreContext(DatastoreContext context) {
64 super.onDatastoreContext(noPersistenceDatastoreContext(context));
68 protected void onRecoveryComplete() {
69 super.onRecoveryComplete();
71 new CandidateListChangeListener(getSelf()).init(getDataStore());
72 new EntityOwnerChangeListener(localMemberName, listenerSupport).init(getDataStore());
76 public void onReceiveCommand(final Object message) throws Exception {
77 if(message instanceof RegisterCandidateLocal) {
78 onRegisterCandidateLocal((RegisterCandidateLocal)message);
79 } else if(message instanceof UnregisterCandidateLocal) {
80 onUnregisterCandidateLocal((UnregisterCandidateLocal)message);
81 } else if(message instanceof CandidateAdded){
82 onCandidateAdded((CandidateAdded) message);
83 } else if(message instanceof CandidateRemoved){
84 onCandidateRemoved((CandidateRemoved) message);
85 } else if(!commitCoordinator.handleMessage(message, this)) {
86 super.onReceiveCommand(message);
90 private void onRegisterCandidateLocal(RegisterCandidateLocal registerCandidate) {
91 LOG.debug("onRegisterCandidateLocal: {}", registerCandidate);
93 listenerSupport.addEntityOwnershipListener(registerCandidate.getEntity(), registerCandidate.getCandidate());
95 NormalizedNode<?, ?> entityOwners = entityOwnersWithCandidate(registerCandidate.getEntity().getType(),
96 registerCandidate.getEntity().getId(), localMemberName);
97 commitCoordinator.commitModification(new MergeModification(ENTITY_OWNERS_PATH, entityOwners), this);
99 getSender().tell(SuccessReply.INSTANCE, getSelf());
102 void tryCommitModifications(final BatchedModifications modifications) {
104 LOG.debug("Committing BatchedModifications {} locally", modifications.getTransactionID());
106 // Note that it's possible the commit won't get consensus and will timeout and not be applied
107 // to the state. However we don't need to retry it in that case b/c it will be committed to
108 // the journal first and, once a majority of followers come back on line and it is replicated,
109 // it will be applied at that point.
110 handleBatchedModificationsLocal(modifications, self());
112 final ActorSelection leader = getLeader();
113 if (leader != null) {
114 LOG.debug("Sending BatchedModifications {} to leader {}", modifications.getTransactionID(), leader);
116 Future<Object> future = Patterns.ask(leader, modifications, TimeUnit.SECONDS.toMillis(
117 getDatastoreContext().getShardTransactionCommitTimeoutInSeconds()));
119 Patterns.pipe(future, getContext().dispatcher()).pipeTo(getSelf(), ActorRef.noSender());
124 boolean hasLeader() {
125 return getLeader() != null && !isIsolatedLeader();
129 protected void onStateChanged() {
130 super.onStateChanged();
132 commitCoordinator.onStateChanged(this, isLeader());
135 private void onUnregisterCandidateLocal(UnregisterCandidateLocal unregisterCandidate) {
137 getSender().tell(SuccessReply.INSTANCE, getSelf());
140 private void onCandidateRemoved(CandidateRemoved message) {
145 LOG.debug("onCandidateRemoved: {}", message);
147 String currentOwner = getCurrentOwner(message.getEntityPath());
148 if(message.getRemovedCandidate().equals(currentOwner)){
149 writeNewOwner(message.getEntityPath(), newOwner(message.getRemainingCandidates()));
153 private void onCandidateAdded(CandidateAdded message) {
158 LOG.debug("onCandidateAdded: {}", message);
160 String currentOwner = getCurrentOwner(message.getEntityPath());
161 if(currentOwner == null){
162 writeNewOwner(message.getEntityPath(), newOwner(message.getAllCandidates()));
166 private void writeNewOwner(YangInstanceIdentifier entityPath, String newOwner) {
167 LOG.debug("Writing new owner {} for entity {}", newOwner, entityPath);
169 commitCoordinator.commitModification(new WriteModification(entityPath.node(ENTITY_OWNER_QNAME),
170 ImmutableNodes.leafNode(ENTITY_OWNER_NODE_ID, newOwner)), this);
173 private String newOwner(Collection<String> candidates) {
174 if(candidates.size() > 0){
175 return candidates.iterator().next();
181 private String getCurrentOwner(YangInstanceIdentifier entityId) {
182 DataTreeSnapshot snapshot = getDataStore().getDataTree().takeSnapshot();
183 Optional<NormalizedNode<?, ?>> optionalEntityOwner = snapshot.readNode(entityId.node(ENTITY_OWNER_QNAME));
184 if(optionalEntityOwner.isPresent()){
185 return optionalEntityOwner.get().getValue().toString();
190 public static Props props(final ShardIdentifier name, final Map<String, String> peerAddresses,
191 final DatastoreContext datastoreContext, final SchemaContext schemaContext, final String localMemberName) {
192 return Props.create(new Creator(name, peerAddresses, datastoreContext, schemaContext, localMemberName));
195 private static class Creator extends AbstractShardCreator {
196 private static final long serialVersionUID = 1L;
198 private final String localMemberName;
200 Creator(final ShardIdentifier name, final Map<String, String> peerAddresses,
201 final DatastoreContext datastoreContext, final SchemaContext schemaContext,
202 final String localMemberName) {
203 super(name, peerAddresses, datastoreContext, schemaContext);
204 this.localMemberName = localMemberName;
208 public Shard create() throws Exception {
209 return new EntityOwnershipShard(name, peerAddresses, datastoreContext, schemaContext, localMemberName);