2 * Copyright (c) 2016 Cisco 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.mdsal.singleton.dom.impl;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static com.google.common.base.Verify.verify;
13 import static com.google.common.base.Verify.verifyNotNull;
14 import static java.util.Objects.requireNonNull;
16 import com.google.common.annotations.VisibleForTesting;
17 import com.google.common.base.MoreObjects;
18 import com.google.common.collect.ImmutableList;
19 import com.google.common.collect.ImmutableSet;
20 import com.google.common.util.concurrent.FutureCallback;
21 import com.google.common.util.concurrent.Futures;
22 import com.google.common.util.concurrent.ListenableFuture;
23 import com.google.common.util.concurrent.MoreExecutors;
24 import com.google.common.util.concurrent.SettableFuture;
25 import java.util.Collection;
26 import java.util.HashMap;
27 import java.util.Iterator;
29 import java.util.Map.Entry;
31 import java.util.concurrent.ConcurrentHashMap;
32 import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
33 import java.util.concurrent.atomic.AtomicReference;
34 import javax.annotation.CheckReturnValue;
35 import javax.annotation.concurrent.GuardedBy;
36 import javax.annotation.concurrent.ThreadSafe;
37 import org.eclipse.jdt.annotation.NonNull;
38 import org.opendaylight.mdsal.eos.common.api.CandidateAlreadyRegisteredException;
39 import org.opendaylight.mdsal.eos.common.api.EntityOwnershipChangeState;
40 import org.opendaylight.mdsal.eos.common.api.GenericEntity;
41 import org.opendaylight.mdsal.eos.common.api.GenericEntityOwnershipCandidateRegistration;
42 import org.opendaylight.mdsal.eos.common.api.GenericEntityOwnershipChange;
43 import org.opendaylight.mdsal.eos.common.api.GenericEntityOwnershipListener;
44 import org.opendaylight.mdsal.eos.common.api.GenericEntityOwnershipService;
45 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonService;
46 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceRegistration;
47 import org.opendaylight.yangtools.concepts.Path;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
52 * Implementation of {@link ClusterSingletonServiceGroup} on top of the Entitiy Ownership Service. Since EOS is atomic
53 * in its operation and singleton services incur startup and most notably cleanup, we need to do something smart here.
56 * The implementation takes advantage of the fact that EOS provides stable ownership, i.e. owners are not moved as
57 * a result on new candidates appearing. We use two entities:
58 * - service entity, to which all nodes register
59 * - cleanup entity, which only the service entity owner registers to
62 * Once the cleanup entity ownership is acquired, services are started. As long as the cleanup entity is registered,
63 * it should remain the owner. In case a new service owner emerges, the old owner will start the cleanup process,
64 * eventually releasing the cleanup entity. The new owner registers for the cleanup entity -- but will not see it
65 * granted until the old owner finishes the cleanup.
67 * @param <P> the instance identifier path type
68 * @param <E> the GenericEntity type
69 * @param <C> the GenericEntityOwnershipChange type
70 * @param <G> the GenericEntityOwnershipListener type
71 * @param <S> the GenericEntityOwnershipService type
74 final class ClusterSingletonServiceGroupImpl<P extends Path<P>, E extends GenericEntity<P>,
75 C extends GenericEntityOwnershipChange<P, E>, G extends GenericEntityOwnershipListener<P, C>,
76 S extends GenericEntityOwnershipService<P, E, G>> extends ClusterSingletonServiceGroup<P, E, C> {
78 private enum EntityState {
80 * This entity was never registered.
84 * Registration exists, but we are waiting for it to resolve.
88 * Registration indicated we are the owner.
92 * Registration indicated we are the owner, but global state is uncertain -- meaning there can be owners in
93 * another partition, for example.
97 * Registration indicated we are not the owner. In this state we do not care about global state, therefore we
98 * do not need an UNOWNED_JEOPARDY state.
105 * Local service is up and running.
107 // FIXME: we should support async startup, which will require a STARTING state.
110 * Local service is being stopped.
115 private static final Logger LOG = LoggerFactory.getLogger(ClusterSingletonServiceGroupImpl.class);
117 private final S entityOwnershipService;
118 private final String identifier;
120 /* Entity instances */
121 private final E serviceEntity;
122 private final E cleanupEntity;
124 private final Set<ClusterSingletonServiceRegistration> members = ConcurrentHashMap.newKeySet();
126 private final Map<ClusterSingletonServiceRegistration, ServiceInfo> services = new HashMap<>();
128 // Marker for when any state changed
129 @SuppressWarnings("rawtypes")
130 private static final AtomicIntegerFieldUpdater<ClusterSingletonServiceGroupImpl> DIRTY_UPDATER =
131 AtomicIntegerFieldUpdater.newUpdater(ClusterSingletonServiceGroupImpl.class, "dirty");
132 private volatile int dirty;
134 // Simplified lock: non-reentrant, support tryLock() only
135 @SuppressWarnings("rawtypes")
136 private static final AtomicIntegerFieldUpdater<ClusterSingletonServiceGroupImpl> LOCK_UPDATER =
137 AtomicIntegerFieldUpdater.newUpdater(ClusterSingletonServiceGroupImpl.class, "lock");
138 @SuppressWarnings("unused")
139 private volatile int lock;
142 * State tracking is quite involved, as we are tracking up to four asynchronous sources of events:
143 * - user calling close()
144 * - service entity ownership
145 * - cleanup entity ownership
146 * - service shutdown future
148 * Absolutely correct solution would be a set of behaviors, which govern each state, remembering where we want to
149 * get to and what we are doing. That would result in ~15 classes which would quickly render this code unreadable
150 * due to boilerplate overhead.
152 * We therefore take a different approach, tracking state directly in this class and evaluate state transitions
153 * based on recorded bits -- without explicit representation of state machine state.
156 * Group close future. In can only go from null to non-null reference. Whenever it is non-null, it indicates that
157 * the user has closed the group and we are converging to termination.
159 // We are using volatile get-and-set to support non-blocking close(). It may be more efficient to inline it here,
160 // as we perform a volatile read after unlocking -- that volatile read may easier on L1 cache.
161 // XXX: above needs a microbenchmark contention ever becomes a problem.
162 private final AtomicReference<SettableFuture<Void>> closeFuture = new AtomicReference<>();
165 * Service (base) entity registration. This entity selects an owner candidate across nodes. Candidates proceed to
166 * acquire {@link #cleanupEntity}.
169 private GenericEntityOwnershipCandidateRegistration<P, E> serviceEntityReg = null;
171 * Service (base) entity last reported state.
174 private EntityState serviceEntityState = EntityState.UNREGISTERED;
177 * Cleanup (owner) entity registration. This entity guards access to service state and coordinates shutdown cleanup
181 private GenericEntityOwnershipCandidateRegistration<P, E> cleanupEntityReg;
183 * Cleanup (owner) entity last reported state.
186 private EntityState cleanupEntityState = EntityState.UNREGISTERED;
188 private volatile boolean initialized;
191 * Class constructor. Note: last argument is reused as-is.
193 * @param identifier non-empty string as identifier
194 * @param mainEntity as Entity instance
195 * @param closeEntity as Entity instance
196 * @param entityOwnershipService GenericEntityOwnershipService instance
197 * @param parent parent service
198 * @param services Services list
200 ClusterSingletonServiceGroupImpl(final String identifier, final S entityOwnershipService, final E mainEntity,
201 final E closeEntity, final Collection<ClusterSingletonServiceRegistration> services) {
202 checkArgument(!identifier.isEmpty(), "Identifier may not be empty");
203 this.identifier = identifier;
204 this.entityOwnershipService = requireNonNull(entityOwnershipService);
205 this.serviceEntity = requireNonNull(mainEntity);
206 this.cleanupEntity = requireNonNull(closeEntity);
207 members.addAll(services);
209 LOG.debug("Instantiated new service group for {}", identifier);
213 ClusterSingletonServiceGroupImpl(final String identifier, final E mainEntity,
214 final E closeEntity, final S entityOwnershipService) {
215 this(identifier, entityOwnershipService, mainEntity, closeEntity, ImmutableList.of());
219 public String getIdentifier() {
224 ListenableFuture<?> closeClusterSingletonGroup() {
225 final ListenableFuture<?> ret = destroyGroup();
232 LOG.debug("Service group {} postponing sync on close", identifier);
238 private boolean isClosed() {
239 return closeFuture.get() != null;
243 void initialize() throws CandidateAlreadyRegisteredException {
246 checkState(!initialized, "Singleton group %s was already initilized", identifier);
247 LOG.debug("Initializing service group {} with services {}", identifier, members);
248 synchronized (this) {
249 serviceEntityState = EntityState.REGISTERED;
250 serviceEntityReg = entityOwnershipService.registerCandidate(serviceEntity);
258 private void checkNotClosed() {
259 checkState(!isClosed(), "Service group %s has already been closed", identifier);
263 void registerService(final ClusterSingletonServiceRegistration reg) {
264 final ClusterSingletonService service = reg.getInstance();
265 verify(identifier.equals(service.getIdentifier().getValue()));
268 checkState(initialized, "Service group %s is not initialized yet", identifier);
270 // First put the service
271 LOG.debug("Adding service {} to service group {}", service, identifier);
272 verify(members.add(reg));
276 LOG.debug("Service group {} delayed register of {}", identifier, reg);
285 ListenableFuture<?> unregisterService(final ClusterSingletonServiceRegistration reg) {
286 final ClusterSingletonService service = reg.getInstance();
287 verify(identifier.equals(service.getIdentifier().getValue()));
290 verify(members.remove(reg));
292 if (members.isEmpty()) {
293 // We need to let AbstractClusterSingletonServiceProviderImpl know this group is to be shutdown
294 // before we start applying state, because while we do not re-enter, the user is free to do whatever,
295 // notably including registering a service with the same ID from the service shutdown hook. That
296 // registration request needs to hit the successor of this group.
297 return destroyGroup();
303 LOG.debug("Service group {} delayed unregister of {}", identifier, reg);
308 private synchronized @NonNull ListenableFuture<?> destroyGroup() {
309 final SettableFuture<Void> future = SettableFuture.create();
310 if (!closeFuture.compareAndSet(null, future)) {
311 return verifyNotNull(closeFuture.get());
314 if (serviceEntityReg != null) {
315 // We are still holding the service registration, close it now...
316 LOG.debug("Service group {} unregistering service entity {}", identifier, serviceEntity);
317 serviceEntityReg.close();
318 serviceEntityReg = null;
326 void ownershipChanged(final C ownershipChange) {
327 LOG.debug("Ownership change {} for ClusterSingletonServiceGroup {}", ownershipChange, identifier);
329 synchronized (this) {
330 lockedOwnershipChanged(ownershipChange);
335 LOG.debug("Service group {} postponing ownership change sync");
344 * Handle an ownership change with the lock held. Callers are expected to handle termination conditions, this method
345 * and anything it calls must not call {@link #lockedClose(SettableFuture)}.
347 * @param ownershipChange reported change
350 private void lockedOwnershipChanged(final C ownershipChange) {
351 final E entity = ownershipChange.getEntity();
352 if (serviceEntity.equals(entity)) {
353 serviceOwnershipChanged(ownershipChange.getState(), ownershipChange.inJeopardy());
355 } else if (cleanupEntity.equals(entity)) {
356 cleanupCandidateOwnershipChanged(ownershipChange.getState(), ownershipChange.inJeopardy());
359 LOG.warn("Group {} received unrecognized change {}", identifier, ownershipChange);
364 private void cleanupCandidateOwnershipChanged(final EntityOwnershipChangeState state, final boolean jeopardy) {
367 case LOCAL_OWNERSHIP_GRANTED:
368 case LOCAL_OWNERSHIP_RETAINED_WITH_NO_CHANGE:
369 LOG.warn("Service group {} cleanup entity owned without certainty", identifier);
370 cleanupEntityState = EntityState.OWNED_JEOPARDY;
372 case LOCAL_OWNERSHIP_LOST_NEW_OWNER:
373 case LOCAL_OWNERSHIP_LOST_NO_OWNER:
374 case REMOTE_OWNERSHIP_CHANGED:
375 case REMOTE_OWNERSHIP_LOST_NO_OWNER:
376 LOG.info("Service group {} cleanup entity ownership uncertain", identifier);
377 cleanupEntityState = EntityState.UNOWNED;
380 throw new IllegalStateException("Unhandled cleanup entity jeopardy change " + state);
386 if (cleanupEntityState == EntityState.OWNED_JEOPARDY) {
387 // Pair info message with previous jeopardy
388 LOG.info("Service group {} cleanup entity ownership ascertained", identifier);
392 case LOCAL_OWNERSHIP_GRANTED:
393 case LOCAL_OWNERSHIP_RETAINED_WITH_NO_CHANGE:
394 cleanupEntityState = EntityState.OWNED;
396 case LOCAL_OWNERSHIP_LOST_NEW_OWNER:
397 case LOCAL_OWNERSHIP_LOST_NO_OWNER:
398 case REMOTE_OWNERSHIP_LOST_NO_OWNER:
399 case REMOTE_OWNERSHIP_CHANGED:
400 cleanupEntityState = EntityState.UNOWNED;
403 LOG.warn("Service group {} ignoring unhandled cleanup entity change {}", identifier, state);
409 private void serviceOwnershipChanged(final EntityOwnershipChangeState state, final boolean jeopardy) {
411 LOG.info("Service group {} service entity ownership uncertain", identifier);
413 case LOCAL_OWNERSHIP_GRANTED:
414 case LOCAL_OWNERSHIP_RETAINED_WITH_NO_CHANGE:
415 serviceEntityState = EntityState.OWNED_JEOPARDY;
417 case LOCAL_OWNERSHIP_LOST_NEW_OWNER:
418 case LOCAL_OWNERSHIP_LOST_NO_OWNER:
419 case REMOTE_OWNERSHIP_CHANGED:
420 case REMOTE_OWNERSHIP_LOST_NO_OWNER:
421 serviceEntityState = EntityState.UNOWNED;
424 throw new IllegalStateException("Unhandled cleanup entity jeopardy change " + state);
429 if (serviceEntityState == EntityState.OWNED_JEOPARDY) {
430 // Pair info message with previous jeopardy
431 LOG.info("Service group {} service entity ownership ascertained", identifier);
435 case LOCAL_OWNERSHIP_GRANTED:
436 case LOCAL_OWNERSHIP_RETAINED_WITH_NO_CHANGE:
437 LOG.debug("Service group {} acquired service entity ownership", identifier);
438 serviceEntityState = EntityState.OWNED;
440 case LOCAL_OWNERSHIP_LOST_NEW_OWNER:
441 case LOCAL_OWNERSHIP_LOST_NO_OWNER:
442 case REMOTE_OWNERSHIP_CHANGED:
443 case REMOTE_OWNERSHIP_LOST_NO_OWNER:
444 LOG.debug("Service group {} lost service entity ownership", identifier);
445 serviceEntityState = EntityState.UNOWNED;
448 LOG.warn("Service group {} ignoring unhandled cleanup entity change {}", identifier, state);
452 // has to be called with lock asserted, which will be released prior to returning
453 private void reconcileState() {
454 // Always check if there is any state change to be applied.
457 if (conditionalClean()) {
461 // We may have ran a round of reconciliation, but the either one of may have happened asynchronously:
464 // - service future completed
465 // - entity state changed
467 // We are dropping the lock, but we need to recheck dirty and try to apply state again if it is found to
468 // be dirty again. This closes the following race condition:
470 // A: runs these checks holding the lock
471 // B: modifies them, fails to acquire lock
472 // A: releases lock -> noone takes care of reconciliation
479 LOG.debug("Service group {} re-running reconciliation", identifier);
483 LOG.debug("Service group {} will be reconciled by someone else", identifier);
485 LOG.debug("Service group {} is completely reconciled", identifier);
492 private void serviceTransitionCompleted() {
499 // Has to be called with lock asserted
500 private void tryReconcileState() {
501 // First take a safe snapshot of current state on which we will base our decisions.
502 final Set<ClusterSingletonServiceRegistration> localMembers;
503 final boolean haveCleanup;
504 final boolean haveService;
505 synchronized (this) {
506 if (serviceEntityReg != null) {
507 switch (serviceEntityState) {
518 throw new IllegalStateException("Unhandled service entity state " + serviceEntityState);
524 if (haveService && cleanupEntityReg == null) {
525 // We have the service entity but have not registered for cleanup entity. Do that now and retry.
526 LOG.debug("Service group {} registering cleanup entity", identifier);
528 cleanupEntityState = EntityState.REGISTERED;
529 cleanupEntityReg = entityOwnershipService.registerCandidate(cleanupEntity);
530 } catch (CandidateAlreadyRegisteredException e) {
531 LOG.error("Service group {} failed to take ownership, aborting", identifier, e);
532 if (serviceEntityReg != null) {
533 serviceEntityReg.close();
534 serviceEntityReg = null;
541 if (cleanupEntityReg != null) {
542 switch (cleanupEntityState) {
553 throw new IllegalStateException("Unhandled service entity state " + serviceEntityState);
559 localMembers = ImmutableSet.copyOf(members);
562 if (haveService && haveCleanup) {
563 ensureServicesStarting(localMembers);
567 ensureServicesStopping();
569 if (!haveService && services.isEmpty()) {
570 LOG.debug("Service group {} has no running services", identifier);
571 final boolean canFinishClose;
572 synchronized (this) {
573 if (cleanupEntityReg != null) {
574 LOG.debug("Service group {} releasing cleanup entity", identifier);
575 cleanupEntityReg.close();
576 cleanupEntityReg = null;
579 switch (cleanupEntityState) {
583 // When we are registered we need to wait for registration to resolve, otherwise
584 // the notification could be routed to the next incarnation of this group -- which could be
585 // confused by the fact it is not registered, but receives, for example, OWNED notification.
586 canFinishClose = false;
590 canFinishClose = true;
593 throw new IllegalStateException("Unhandled cleanup entity state " + cleanupEntityState);
597 if (canFinishClose) {
598 final SettableFuture<Void> localFuture = closeFuture.get();
599 if (localFuture != null && !localFuture.isDone()) {
600 LOG.debug("Service group {} completing termination", identifier);
601 localFuture.set(null);
607 // Has to be called with lock asserted
608 @SuppressWarnings("illegalCatch")
609 private void ensureServicesStarting(final Set<ClusterSingletonServiceRegistration> localConfig) {
610 LOG.debug("Service group {} starting services", identifier);
612 // This may look counter-intuitive, but the localConfig may be missing some services that are started -- for
613 // example when this method is executed as part of unregisterService() call. In that case we need to ensure
614 // services in the list are stopping
615 final Iterator<Entry<ClusterSingletonServiceRegistration, ServiceInfo>> it = services.entrySet().iterator();
616 while (it.hasNext()) {
617 final Entry<ClusterSingletonServiceRegistration, ServiceInfo> entry = it.next();
618 final ClusterSingletonServiceRegistration reg = entry.getKey();
619 if (!localConfig.contains(reg)) {
620 final ServiceInfo newInfo = ensureStopping(reg, entry.getValue());
621 if (newInfo != null) {
622 entry.setValue(newInfo);
629 // Now make sure member services are being juggled around
630 for (ClusterSingletonServiceRegistration reg : localConfig) {
631 if (!services.containsKey(reg)) {
632 final ClusterSingletonService service = reg.getInstance();
633 LOG.debug("Starting service {}", service);
636 service.instantiateServiceInstance();
637 } catch (Exception e) {
638 LOG.warn("Service group {} service {} failed to start, attempting to continue", identifier, service,
643 services.put(reg, ServiceInfo.started());
648 // Has to be called with lock asserted
649 private void ensureServicesStopping() {
650 final Iterator<Entry<ClusterSingletonServiceRegistration, ServiceInfo>> it = services.entrySet().iterator();
651 while (it.hasNext()) {
652 final Entry<ClusterSingletonServiceRegistration, ServiceInfo> entry = it.next();
653 final ServiceInfo newInfo = ensureStopping(entry.getKey(), entry.getValue());
654 if (newInfo != null) {
655 entry.setValue(newInfo);
662 @SuppressWarnings("illegalCatch")
663 private ServiceInfo ensureStopping(final ClusterSingletonServiceRegistration reg, final ServiceInfo info) {
664 switch (info.getState()) {
666 final ClusterSingletonService service = reg.getInstance();
668 LOG.debug("Service group {} stopping service {}", identifier, service);
669 final @NonNull ListenableFuture<?> future;
671 future = verifyNotNull(service.closeServiceInstance());
672 } catch (Exception e) {
673 LOG.warn("Service group {} service {} failed to stop, attempting to continue", identifier, service,
678 Futures.addCallback(future, new FutureCallback<Object>() {
680 public void onSuccess(final Object result) {
681 LOG.debug("Service group {} service {} stopped successfully", identifier, service);
682 serviceTransitionCompleted();
686 public void onFailure(final Throwable cause) {
687 LOG.debug("Service group {} service {} stopped with error", identifier, service, cause);
688 serviceTransitionCompleted();
690 }, MoreExecutors.directExecutor());
691 return info.toState(ServiceState.STOPPING, future);
693 if (info.getFuture().isDone()) {
694 LOG.debug("Service group {} removed stopped service {}", identifier, reg.getInstance());
699 throw new IllegalStateException("Unhandled state " + info.getState());
703 private void markDirty() {
707 private boolean isDirty() {
711 private boolean conditionalClean() {
712 return DIRTY_UPDATER.compareAndSet(this, 1, 0);
715 private boolean tryLock() {
716 return LOCK_UPDATER.compareAndSet(this, 0, 1);
719 private boolean unlock() {
720 verify(LOCK_UPDATER.compareAndSet(this, 1, 0));
725 public String toString() {
726 return MoreObjects.toStringHelper(this).add("identifier", identifier).toString();