714273375c2370e16d2fd68a8dee27db7ca462a2
[controller.git] / opendaylight / md-sal / eos-dom-akka / src / main / java / org / opendaylight / controller / eos / akka / AkkaEntityOwnershipService.java
1 /*
2  * Copyright (c) 2021 PANTHEON.tech, s.r.o. 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.controller.eos.akka;
9
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;
24 import java.util.Set;
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;
85
86 /**
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.
90  */
91 @Singleton
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);
98
99     private final Set<DOMEntity> registeredEntities = ConcurrentHashMap.newKeySet();
100     private final String localCandidate;
101     private final Scheduler scheduler;
102     private final String datacenter;
103
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;
110
111     private final BindingInstanceIdentifierCodec iidCodec;
112
113     private Registration reg;
114
115     @VisibleForTesting
116     protected AkkaEntityOwnershipService(final ActorSystem actorSystem, final BindingCodecTree codecTree)
117             throws ExecutionException, InterruptedException {
118         final var typedActorSystem = Adapter.toTyped(actorSystem);
119         scheduler = typedActorSystem.scheduler();
120
121         final Cluster cluster = Cluster.get(typedActorSystem);
122         datacenter = cluster.selfMember().dataCenter();
123
124         localCandidate = cluster.selfMember().getRoles().stream()
125             .filter(role -> !role.contains(DATACENTER_PREFIX))
126             .findFirst()
127             .orElseThrow(() -> new IllegalArgumentException("No valid role found."));
128
129         iidCodec = codecTree.getInstanceIdentifierCodec();
130         bootstrap = Adapter.spawn(actorSystem, Behaviors.setup(
131                 context -> EOSMain.create(iidCodec)), "EOSBootstrap");
132
133         final CompletionStage<RunningContext> ask = AskPattern.ask(bootstrap,
134                 GetRunningContext::new, Duration.ofSeconds(5), scheduler);
135         runningContext = ask.toCompletableFuture().get();
136
137         candidateRegistry = runningContext.getCandidateRegistry();
138         listenerRegistry = runningContext.getListenerRegistry();
139         ownerStateChecker = runningContext.getOwnerStateChecker();
140         ownerSupervisor = runningContext.getOwnerSupervisor();
141     }
142
143     @Inject
144     @Activate
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);
151
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)
156             .build());
157     }
158
159     @PreDestroy
160     @Deactivate
161     @Override
162     public void close() throws InterruptedException, ExecutionException {
163         if (reg != null) {
164             reg.close();
165             reg = null;
166         }
167         AskPattern.ask(bootstrap, Terminate::new, Duration.ofSeconds(5), scheduler).toCompletableFuture().get();
168     }
169
170     @Override
171     public Registration registerCandidate(final DOMEntity entity)
172             throws CandidateAlreadyRegisteredException {
173         if (!registeredEntities.add(entity)) {
174             throw new CandidateAlreadyRegisteredException(entity);
175         }
176
177         final RegisterCandidate msg = new RegisterCandidate(entity, localCandidate);
178         LOG.debug("Registering candidate with message: {}", msg);
179         candidateRegistry.tell(msg);
180
181         return new CandidateRegistration(entity, this);
182     }
183
184     @Override
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));
188
189         return new ListenerRegistration(listener, entityType, this);
190     }
191
192     @Override
193     public Optional<EntityOwnershipState> getOwnershipState(final DOMEntity entity) {
194         LOG.debug("Retrieving ownership state for {}", entity);
195
196         final CompletionStage<GetOwnershipStateReply> result = AskPattern.ask(ownerStateChecker,
197             replyTo -> new GetOwnershipState(entity, replyTo),
198             Duration.ofSeconds(5), scheduler);
199
200         final GetOwnershipStateReply reply;
201         try {
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();
206         }
207
208         return Optional.ofNullable(reply.getOwnershipState());
209     }
210
211     @Override
212     public boolean isCandidateRegistered(final DOMEntity forEntity) {
213         return registeredEntities.contains(forEntity);
214     }
215
216     @Override
217     public ListenableFuture<Empty> activateDataCenter() {
218         LOG.debug("Activating datacenter: {}", datacenter);
219
220         return toListenableFuture("Activate",
221             AskPattern.ask(ownerSupervisor, ActivateDataCenter::new, DATACENTER_OP_TIMEOUT, scheduler));
222     }
223
224     @Override
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));
229     }
230
231     @VisibleForTesting
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));
235     }
236
237     @VisibleForTesting
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);
242     }
243
244     @VisibleForTesting
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);
249     }
250
251     void unregisterCandidate(final DOMEntity entity) {
252         LOG.debug("Unregistering candidate for {}", entity);
253
254         if (registeredEntities.remove(entity)) {
255             candidateRegistry.tell(new UnregisterCandidate(entity, localCandidate));
256         }
257     }
258
259     void unregisterListener(final String entityType, final DOMEntityOwnershipListener listener) {
260         LOG.debug("Unregistering listener {} for type {}", listener, entityType);
261
262         listenerRegistry.tell(new UnregisterListener(entityType, listener));
263     }
264
265     @VisibleForTesting
266     RunningContext getRunningContext() {
267         return runningContext;
268     }
269
270     private static <R extends StateCheckerReply, O extends RpcOutput> ListenableFuture<RpcResult<O>> toRpcFuture(
271             final CompletionStage<R> stage, final Function<R, O> outputFunction) {
272
273         final SettableFuture<RpcResult<O>> future = SettableFuture.create();
274         stage.whenComplete((reply, failure) -> {
275             if (failure != null) {
276                 future.setException(failure);
277             } else {
278                 future.set(RpcResultBuilder.success(outputFunction.apply(reply)).build());
279             }
280         });
281         return future;
282     }
283
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);
290             } else {
291                 LOG.debug("{} DataCenter successful", op);
292                 future.set(Empty.value());
293             }
294         });
295         return future;
296     }
297 }