2 * Copyright (c) 2021 PANTHEON.tech, s.r.o. 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.eos.akka;
10 import akka.actor.ActorSystem;
11 import akka.actor.typed.ActorRef;
12 import akka.actor.typed.Scheduler;
13 import akka.actor.typed.javadsl.Adapter;
14 import akka.actor.typed.javadsl.AskPattern;
15 import akka.actor.typed.javadsl.Behaviors;
16 import akka.cluster.typed.Cluster;
17 import com.google.common.annotations.VisibleForTesting;
18 import com.google.common.collect.ImmutableClassToInstanceMap;
19 import com.google.common.util.concurrent.ListenableFuture;
20 import com.google.common.util.concurrent.SettableFuture;
21 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
22 import java.time.Duration;
23 import java.util.Optional;
25 import java.util.concurrent.CompletionStage;
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.concurrent.ExecutionException;
28 import java.util.function.Function;
29 import javax.annotation.PreDestroy;
30 import javax.inject.Inject;
31 import javax.inject.Singleton;
32 import org.opendaylight.controller.cluster.ActorSystemProvider;
33 import org.opendaylight.controller.eos.akka.bootstrap.EOSMain;
34 import org.opendaylight.controller.eos.akka.bootstrap.command.BootstrapCommand;
35 import org.opendaylight.controller.eos.akka.bootstrap.command.GetRunningContext;
36 import org.opendaylight.controller.eos.akka.bootstrap.command.RunningContext;
37 import org.opendaylight.controller.eos.akka.bootstrap.command.Terminate;
38 import org.opendaylight.controller.eos.akka.owner.checker.command.GetEntitiesRequest;
39 import org.opendaylight.controller.eos.akka.owner.checker.command.GetEntityOwnerReply;
40 import org.opendaylight.controller.eos.akka.owner.checker.command.GetEntityOwnerRequest;
41 import org.opendaylight.controller.eos.akka.owner.checker.command.GetEntityReply;
42 import org.opendaylight.controller.eos.akka.owner.checker.command.GetEntityRequest;
43 import org.opendaylight.controller.eos.akka.owner.checker.command.GetOwnershipState;
44 import org.opendaylight.controller.eos.akka.owner.checker.command.GetOwnershipStateReply;
45 import org.opendaylight.controller.eos.akka.owner.checker.command.StateCheckerCommand;
46 import org.opendaylight.controller.eos.akka.owner.checker.command.StateCheckerReply;
47 import org.opendaylight.controller.eos.akka.owner.supervisor.command.ActivateDataCenter;
48 import org.opendaylight.controller.eos.akka.owner.supervisor.command.DeactivateDataCenter;
49 import org.opendaylight.controller.eos.akka.owner.supervisor.command.OwnerSupervisorCommand;
50 import org.opendaylight.controller.eos.akka.registry.candidate.command.CandidateRegistryCommand;
51 import org.opendaylight.controller.eos.akka.registry.candidate.command.RegisterCandidate;
52 import org.opendaylight.controller.eos.akka.registry.candidate.command.UnregisterCandidate;
53 import org.opendaylight.controller.eos.akka.registry.listener.type.command.RegisterListener;
54 import org.opendaylight.controller.eos.akka.registry.listener.type.command.TypeListenerRegistryCommand;
55 import org.opendaylight.controller.eos.akka.registry.listener.type.command.UnregisterListener;
56 import org.opendaylight.mdsal.binding.api.RpcProviderService;
57 import org.opendaylight.mdsal.binding.dom.codec.api.BindingCodecTree;
58 import org.opendaylight.mdsal.binding.dom.codec.api.BindingInstanceIdentifierCodec;
59 import org.opendaylight.mdsal.eos.common.api.CandidateAlreadyRegisteredException;
60 import org.opendaylight.mdsal.eos.common.api.EntityOwnershipState;
61 import org.opendaylight.mdsal.eos.dom.api.DOMEntity;
62 import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipListener;
63 import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipService;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.GetEntities;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.GetEntitiesInput;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.GetEntitiesOutput;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.GetEntity;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.GetEntityInput;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.GetEntityOutput;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.GetEntityOwner;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.GetEntityOwnerInput;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.GetEntityOwnerOutput;
73 import org.opendaylight.yangtools.concepts.Registration;
74 import org.opendaylight.yangtools.yang.binding.Rpc;
75 import org.opendaylight.yangtools.yang.binding.RpcOutput;
76 import org.opendaylight.yangtools.yang.common.Empty;
77 import org.opendaylight.yangtools.yang.common.RpcResult;
78 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
79 import org.osgi.service.component.annotations.Activate;
80 import org.osgi.service.component.annotations.Component;
81 import org.osgi.service.component.annotations.Deactivate;
82 import org.osgi.service.component.annotations.Reference;
83 import org.slf4j.Logger;
84 import org.slf4j.LoggerFactory;
87 * DOMEntityOwnershipService implementation backed by native Akka clustering constructs. We use distributed-data
88 * to track all registered candidates and cluster-singleton to maintain a single cluster-wide authority which selects
89 * the appropriate owners.
92 @Component(immediate = true, service = { DOMEntityOwnershipService.class, DataCenterControl.class })
93 public class AkkaEntityOwnershipService implements DOMEntityOwnershipService, DataCenterControl, AutoCloseable {
94 private static final Logger LOG = LoggerFactory.getLogger(AkkaEntityOwnershipService.class);
95 private static final String DATACENTER_PREFIX = "dc";
96 private static final Duration DATACENTER_OP_TIMEOUT = Duration.ofSeconds(20);
97 private static final Duration QUERY_TIMEOUT = Duration.ofSeconds(10);
99 private final Set<DOMEntity> registeredEntities = ConcurrentHashMap.newKeySet();
100 private final String localCandidate;
101 private final Scheduler scheduler;
102 private final String datacenter;
104 private final ActorRef<BootstrapCommand> bootstrap;
105 private final RunningContext runningContext;
106 private final ActorRef<CandidateRegistryCommand> candidateRegistry;
107 private final ActorRef<TypeListenerRegistryCommand> listenerRegistry;
108 private final ActorRef<StateCheckerCommand> ownerStateChecker;
109 protected final ActorRef<OwnerSupervisorCommand> ownerSupervisor;
111 private final BindingInstanceIdentifierCodec iidCodec;
113 private Registration reg;
116 protected AkkaEntityOwnershipService(final ActorSystem actorSystem, final BindingCodecTree codecTree)
117 throws ExecutionException, InterruptedException {
118 final var typedActorSystem = Adapter.toTyped(actorSystem);
119 scheduler = typedActorSystem.scheduler();
121 final Cluster cluster = Cluster.get(typedActorSystem);
122 datacenter = cluster.selfMember().dataCenter();
124 localCandidate = cluster.selfMember().getRoles().stream()
125 .filter(role -> !role.contains(DATACENTER_PREFIX))
127 .orElseThrow(() -> new IllegalArgumentException("No valid role found."));
129 iidCodec = codecTree.getInstanceIdentifierCodec();
130 bootstrap = Adapter.spawn(actorSystem, Behaviors.setup(
131 context -> EOSMain.create(iidCodec)), "EOSBootstrap");
133 final CompletionStage<RunningContext> ask = AskPattern.ask(bootstrap,
134 GetRunningContext::new, Duration.ofSeconds(5), scheduler);
135 runningContext = ask.toCompletableFuture().get();
137 candidateRegistry = runningContext.getCandidateRegistry();
138 listenerRegistry = runningContext.getListenerRegistry();
139 ownerStateChecker = runningContext.getOwnerStateChecker();
140 ownerSupervisor = runningContext.getOwnerSupervisor();
145 @SuppressFBWarnings(value = "MC_OVERRIDABLE_METHOD_CALL_IN_CONSTRUCTOR",
146 justification = "Non-final for testing 'this' reference is expected to be stable at registration time")
147 public AkkaEntityOwnershipService(@Reference final ActorSystemProvider actorProvider,
148 @Reference final RpcProviderService rpcProvider, @Reference final BindingCodecTree codecTree)
149 throws ExecutionException, InterruptedException {
150 this(actorProvider.getActorSystem(), codecTree);
152 reg = rpcProvider.registerRpcImplementations(ImmutableClassToInstanceMap.<Rpc<?, ?>>builder()
153 .put(GetEntity.class, this::getEntity)
154 .put(GetEntities.class, this::getEntities)
155 .put(GetEntityOwner.class, this::getEntityOwner)
162 public void close() throws InterruptedException, ExecutionException {
167 AskPattern.ask(bootstrap, Terminate::new, Duration.ofSeconds(5), scheduler).toCompletableFuture().get();
171 public Registration registerCandidate(final DOMEntity entity)
172 throws CandidateAlreadyRegisteredException {
173 if (!registeredEntities.add(entity)) {
174 throw new CandidateAlreadyRegisteredException(entity);
177 final RegisterCandidate msg = new RegisterCandidate(entity, localCandidate);
178 LOG.debug("Registering candidate with message: {}", msg);
179 candidateRegistry.tell(msg);
181 return new CandidateRegistration(entity, this);
185 public Registration registerListener(final String entityType, final DOMEntityOwnershipListener listener) {
186 LOG.debug("Registering listener {} for type {}", listener, entityType);
187 listenerRegistry.tell(new RegisterListener(entityType, listener));
189 return new ListenerRegistration(listener, entityType, this);
193 public Optional<EntityOwnershipState> getOwnershipState(final DOMEntity entity) {
194 LOG.debug("Retrieving ownership state for {}", entity);
196 final CompletionStage<GetOwnershipStateReply> result = AskPattern.ask(ownerStateChecker,
197 replyTo -> new GetOwnershipState(entity, replyTo),
198 Duration.ofSeconds(5), scheduler);
200 final GetOwnershipStateReply reply;
202 reply = result.toCompletableFuture().get();
203 } catch (final InterruptedException | ExecutionException exception) {
204 LOG.warn("Failed to retrieve ownership state for {}", entity, exception);
205 return Optional.empty();
208 return Optional.ofNullable(reply.getOwnershipState());
212 public boolean isCandidateRegistered(final DOMEntity forEntity) {
213 return registeredEntities.contains(forEntity);
217 public ListenableFuture<Empty> activateDataCenter() {
218 LOG.debug("Activating datacenter: {}", datacenter);
220 return toListenableFuture("Activate",
221 AskPattern.ask(ownerSupervisor, ActivateDataCenter::new, DATACENTER_OP_TIMEOUT, scheduler));
225 public ListenableFuture<Empty> deactivateDataCenter() {
226 LOG.debug("Deactivating datacenter: {}", datacenter);
227 return toListenableFuture("Deactivate",
228 AskPattern.ask(ownerSupervisor, DeactivateDataCenter::new, DATACENTER_OP_TIMEOUT, scheduler));
232 final ListenableFuture<RpcResult<GetEntitiesOutput>> getEntities(final GetEntitiesInput input) {
233 return toRpcFuture(AskPattern.ask(ownerStateChecker, GetEntitiesRequest::new, QUERY_TIMEOUT, scheduler),
234 reply -> reply.toOutput(iidCodec));
238 final ListenableFuture<RpcResult<GetEntityOutput>> getEntity(final GetEntityInput input) {
239 return toRpcFuture(AskPattern.ask(ownerStateChecker,
240 (final ActorRef<GetEntityReply> replyTo) -> new GetEntityRequest(replyTo, input), QUERY_TIMEOUT, scheduler),
241 GetEntityReply::toOutput);
245 final ListenableFuture<RpcResult<GetEntityOwnerOutput>> getEntityOwner(final GetEntityOwnerInput input) {
246 return toRpcFuture(AskPattern.ask(ownerStateChecker,
247 (final ActorRef<GetEntityOwnerReply> replyTo) -> new GetEntityOwnerRequest(replyTo, input), QUERY_TIMEOUT,
248 scheduler), GetEntityOwnerReply::toOutput);
251 void unregisterCandidate(final DOMEntity entity) {
252 LOG.debug("Unregistering candidate for {}", entity);
254 if (registeredEntities.remove(entity)) {
255 candidateRegistry.tell(new UnregisterCandidate(entity, localCandidate));
259 void unregisterListener(final String entityType, final DOMEntityOwnershipListener listener) {
260 LOG.debug("Unregistering listener {} for type {}", listener, entityType);
262 listenerRegistry.tell(new UnregisterListener(entityType, listener));
266 RunningContext getRunningContext() {
267 return runningContext;
270 private static <R extends StateCheckerReply, O extends RpcOutput> ListenableFuture<RpcResult<O>> toRpcFuture(
271 final CompletionStage<R> stage, final Function<R, O> outputFunction) {
273 final SettableFuture<RpcResult<O>> future = SettableFuture.create();
274 stage.whenComplete((reply, failure) -> {
275 if (failure != null) {
276 future.setException(failure);
278 future.set(RpcResultBuilder.success(outputFunction.apply(reply)).build());
284 private static ListenableFuture<Empty> toListenableFuture(final String op, final CompletionStage<?> stage) {
285 final SettableFuture<Empty> future = SettableFuture.create();
286 stage.whenComplete((reply, failure) -> {
287 if (failure != null) {
288 LOG.warn("{} DataCenter failed", op, failure);
289 future.setException(failure);
291 LOG.debug("{} DataCenter successful", op);
292 future.set(Empty.value());