Bump upstream SNAPSHOTS
[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.util.concurrent.ListenableFuture;
19 import com.google.common.util.concurrent.SettableFuture;
20 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
21 import java.time.Duration;
22 import java.util.Optional;
23 import java.util.Set;
24 import java.util.concurrent.CompletionStage;
25 import java.util.concurrent.ConcurrentHashMap;
26 import java.util.concurrent.ExecutionException;
27 import java.util.function.Function;
28 import javax.annotation.PreDestroy;
29 import javax.inject.Inject;
30 import javax.inject.Singleton;
31 import org.opendaylight.controller.cluster.ActorSystemProvider;
32 import org.opendaylight.controller.eos.akka.bootstrap.EOSMain;
33 import org.opendaylight.controller.eos.akka.bootstrap.command.BootstrapCommand;
34 import org.opendaylight.controller.eos.akka.bootstrap.command.GetRunningContext;
35 import org.opendaylight.controller.eos.akka.bootstrap.command.RunningContext;
36 import org.opendaylight.controller.eos.akka.bootstrap.command.Terminate;
37 import org.opendaylight.controller.eos.akka.owner.checker.command.GetEntitiesRequest;
38 import org.opendaylight.controller.eos.akka.owner.checker.command.GetEntityOwnerReply;
39 import org.opendaylight.controller.eos.akka.owner.checker.command.GetEntityOwnerRequest;
40 import org.opendaylight.controller.eos.akka.owner.checker.command.GetEntityReply;
41 import org.opendaylight.controller.eos.akka.owner.checker.command.GetEntityRequest;
42 import org.opendaylight.controller.eos.akka.owner.checker.command.GetOwnershipState;
43 import org.opendaylight.controller.eos.akka.owner.checker.command.GetOwnershipStateReply;
44 import org.opendaylight.controller.eos.akka.owner.checker.command.StateCheckerCommand;
45 import org.opendaylight.controller.eos.akka.owner.checker.command.StateCheckerReply;
46 import org.opendaylight.controller.eos.akka.owner.supervisor.command.ActivateDataCenter;
47 import org.opendaylight.controller.eos.akka.owner.supervisor.command.DeactivateDataCenter;
48 import org.opendaylight.controller.eos.akka.owner.supervisor.command.OwnerSupervisorCommand;
49 import org.opendaylight.controller.eos.akka.registry.candidate.command.CandidateRegistryCommand;
50 import org.opendaylight.controller.eos.akka.registry.candidate.command.RegisterCandidate;
51 import org.opendaylight.controller.eos.akka.registry.candidate.command.UnregisterCandidate;
52 import org.opendaylight.controller.eos.akka.registry.listener.type.command.RegisterListener;
53 import org.opendaylight.controller.eos.akka.registry.listener.type.command.TypeListenerRegistryCommand;
54 import org.opendaylight.controller.eos.akka.registry.listener.type.command.UnregisterListener;
55 import org.opendaylight.mdsal.binding.api.RpcProviderService;
56 import org.opendaylight.mdsal.binding.dom.codec.api.BindingCodecTree;
57 import org.opendaylight.mdsal.binding.dom.codec.api.BindingInstanceIdentifierCodec;
58 import org.opendaylight.mdsal.eos.common.api.CandidateAlreadyRegisteredException;
59 import org.opendaylight.mdsal.eos.common.api.EntityOwnershipState;
60 import org.opendaylight.mdsal.eos.dom.api.DOMEntity;
61 import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipCandidateRegistration;
62 import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipListener;
63 import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipListenerRegistration;
64 import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipService;
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.GetEntityInput;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.GetEntityOutput;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.GetEntityOwnerInput;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.GetEntityOwnerOutput;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.OdlEntityOwnersService;
72 import org.opendaylight.yangtools.concepts.Registration;
73 import org.opendaylight.yangtools.yang.binding.RpcOutput;
74 import org.opendaylight.yangtools.yang.common.Empty;
75 import org.opendaylight.yangtools.yang.common.RpcResult;
76 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
77 import org.osgi.service.component.annotations.Activate;
78 import org.osgi.service.component.annotations.Component;
79 import org.osgi.service.component.annotations.Deactivate;
80 import org.osgi.service.component.annotations.Reference;
81 import org.slf4j.Logger;
82 import org.slf4j.LoggerFactory;
83
84 /**
85  * DOMEntityOwnershipService implementation backed by native Akka clustering constructs. We use distributed-data
86  * to track all registered candidates and cluster-singleton to maintain a single cluster-wide authority which selects
87  * the appropriate owners.
88  */
89 @Singleton
90 @Component(immediate = true, service = { DOMEntityOwnershipService.class, DataCenterControl.class })
91 public class AkkaEntityOwnershipService implements DOMEntityOwnershipService, DataCenterControl, AutoCloseable,
92         OdlEntityOwnersService {
93     private static final Logger LOG = LoggerFactory.getLogger(AkkaEntityOwnershipService.class);
94     private static final String DATACENTER_PREFIX = "dc";
95     private static final Duration DATACENTER_OP_TIMEOUT = Duration.ofSeconds(20);
96     private static final Duration QUERY_TIMEOUT = Duration.ofSeconds(10);
97
98     private final Set<DOMEntity> registeredEntities = ConcurrentHashMap.newKeySet();
99     private final String localCandidate;
100     private final Scheduler scheduler;
101     private final String datacenter;
102
103     private final ActorRef<BootstrapCommand> bootstrap;
104     private final RunningContext runningContext;
105     private final ActorRef<CandidateRegistryCommand> candidateRegistry;
106     private final ActorRef<TypeListenerRegistryCommand> listenerRegistry;
107     private final ActorRef<StateCheckerCommand> ownerStateChecker;
108     protected final ActorRef<OwnerSupervisorCommand> ownerSupervisor;
109
110     private final BindingInstanceIdentifierCodec iidCodec;
111
112     private Registration reg;
113
114     @VisibleForTesting
115     protected AkkaEntityOwnershipService(final ActorSystem actorSystem, final BindingCodecTree codecTree)
116             throws ExecutionException, InterruptedException {
117         final var typedActorSystem = Adapter.toTyped(actorSystem);
118         scheduler = typedActorSystem.scheduler();
119
120         final Cluster cluster = Cluster.get(typedActorSystem);
121         datacenter = cluster.selfMember().dataCenter();
122
123         localCandidate = cluster.selfMember().getRoles().stream()
124             .filter(role -> !role.contains(DATACENTER_PREFIX))
125             .findFirst()
126             .orElseThrow(() -> new IllegalArgumentException("No valid role found."));
127
128         iidCodec = codecTree.getInstanceIdentifierCodec();
129         bootstrap = Adapter.spawn(actorSystem, Behaviors.setup(
130                 context -> EOSMain.create(iidCodec)), "EOSBootstrap");
131
132         final CompletionStage<RunningContext> ask = AskPattern.ask(bootstrap,
133                 GetRunningContext::new, Duration.ofSeconds(5), scheduler);
134         runningContext = ask.toCompletableFuture().get();
135
136         candidateRegistry = runningContext.getCandidateRegistry();
137         listenerRegistry = runningContext.getListenerRegistry();
138         ownerStateChecker = runningContext.getOwnerStateChecker();
139         ownerSupervisor = runningContext.getOwnerSupervisor();
140     }
141
142     @Inject
143     @Activate
144     @SuppressFBWarnings(value = "MC_OVERRIDABLE_METHOD_CALL_IN_CONSTRUCTOR",
145         justification = "Non-final for testing 'this' reference is expected to be stable at registration time")
146     public AkkaEntityOwnershipService(@Reference final ActorSystemProvider actorProvider,
147             @Reference final RpcProviderService rpcProvider, @Reference final BindingCodecTree codecTree)
148             throws ExecutionException, InterruptedException {
149         this(actorProvider.getActorSystem(), codecTree);
150
151         reg = rpcProvider.registerRpcImplementation(OdlEntityOwnersService.class, this);
152     }
153
154     @PreDestroy
155     @Deactivate
156     @Override
157     public void close() throws InterruptedException, ExecutionException {
158         if (reg != null) {
159             reg.close();
160             reg = null;
161         }
162         AskPattern.ask(bootstrap, Terminate::new, Duration.ofSeconds(5), scheduler).toCompletableFuture().get();
163     }
164
165     @Override
166     public DOMEntityOwnershipCandidateRegistration registerCandidate(final DOMEntity entity)
167             throws CandidateAlreadyRegisteredException {
168         if (!registeredEntities.add(entity)) {
169             throw new CandidateAlreadyRegisteredException(entity);
170         }
171
172         final RegisterCandidate msg = new RegisterCandidate(entity, localCandidate);
173         LOG.debug("Registering candidate with message: {}", msg);
174         candidateRegistry.tell(msg);
175
176         return new CandidateRegistration(entity, this);
177     }
178
179     @Override
180     public DOMEntityOwnershipListenerRegistration registerListener(final String entityType,
181                                                                    final DOMEntityOwnershipListener listener) {
182         LOG.debug("Registering listener {} for type {}", listener, entityType);
183         listenerRegistry.tell(new RegisterListener(entityType, listener));
184
185         return new ListenerRegistration(listener, entityType, this);
186     }
187
188     @Override
189     public Optional<EntityOwnershipState> getOwnershipState(final DOMEntity entity) {
190         LOG.debug("Retrieving ownership state for {}", entity);
191
192         final CompletionStage<GetOwnershipStateReply> result = AskPattern.ask(ownerStateChecker,
193             replyTo -> new GetOwnershipState(entity, replyTo),
194             Duration.ofSeconds(5), scheduler);
195
196         final GetOwnershipStateReply reply;
197         try {
198             reply = result.toCompletableFuture().get();
199         } catch (final InterruptedException | ExecutionException exception) {
200             LOG.warn("Failed to retrieve ownership state for {}", entity, exception);
201             return Optional.empty();
202         }
203
204         return Optional.ofNullable(reply.getOwnershipState());
205     }
206
207     @Override
208     public boolean isCandidateRegistered(final DOMEntity forEntity) {
209         return registeredEntities.contains(forEntity);
210     }
211
212     @Override
213     public ListenableFuture<Empty> activateDataCenter() {
214         LOG.debug("Activating datacenter: {}", datacenter);
215
216         return toListenableFuture("Activate",
217             AskPattern.ask(ownerSupervisor, ActivateDataCenter::new, DATACENTER_OP_TIMEOUT, scheduler));
218     }
219
220     @Override
221     public ListenableFuture<Empty> deactivateDataCenter() {
222         LOG.debug("Deactivating datacenter: {}", datacenter);
223         return toListenableFuture("Deactivate",
224             AskPattern.ask(ownerSupervisor, DeactivateDataCenter::new, DATACENTER_OP_TIMEOUT, scheduler));
225     }
226
227     @Override
228     public ListenableFuture<RpcResult<GetEntitiesOutput>> getEntities(final GetEntitiesInput input) {
229         return toRpcFuture(AskPattern.ask(ownerStateChecker, GetEntitiesRequest::new, QUERY_TIMEOUT, scheduler),
230                 reply -> reply.toOutput(iidCodec));
231     }
232
233     @Override
234     public ListenableFuture<RpcResult<GetEntityOutput>> getEntity(final GetEntityInput input) {
235         return toRpcFuture(AskPattern.ask(ownerStateChecker,
236             (final ActorRef<GetEntityReply> replyTo) -> new GetEntityRequest(replyTo, input), QUERY_TIMEOUT, scheduler),
237             GetEntityReply::toOutput);
238     }
239
240     @Override
241     public ListenableFuture<RpcResult<GetEntityOwnerOutput>> getEntityOwner(final GetEntityOwnerInput input) {
242         return toRpcFuture(AskPattern.ask(ownerStateChecker,
243             (final ActorRef<GetEntityOwnerReply> replyTo) -> new GetEntityOwnerRequest(replyTo, input), QUERY_TIMEOUT,
244             scheduler), GetEntityOwnerReply::toOutput);
245     }
246
247     void unregisterCandidate(final DOMEntity entity) {
248         LOG.debug("Unregistering candidate for {}", entity);
249
250         if (registeredEntities.remove(entity)) {
251             candidateRegistry.tell(new UnregisterCandidate(entity, localCandidate));
252         }
253     }
254
255     void unregisterListener(final String entityType, final DOMEntityOwnershipListener listener) {
256         LOG.debug("Unregistering listener {} for type {}", listener, entityType);
257
258         listenerRegistry.tell(new UnregisterListener(entityType, listener));
259     }
260
261     @VisibleForTesting
262     RunningContext getRunningContext() {
263         return runningContext;
264     }
265
266     private static <R extends StateCheckerReply, O extends RpcOutput> ListenableFuture<RpcResult<O>> toRpcFuture(
267             final CompletionStage<R> stage, final Function<R, O> outputFunction) {
268
269         final SettableFuture<RpcResult<O>> future = SettableFuture.create();
270         stage.whenComplete((reply, failure) -> {
271             if (failure != null) {
272                 future.setException(failure);
273             } else {
274                 future.set(RpcResultBuilder.success(outputFunction.apply(reply)).build());
275             }
276         });
277         return future;
278     }
279
280     private static ListenableFuture<Empty> toListenableFuture(final String op, final CompletionStage<?> stage) {
281         final SettableFuture<Empty> future = SettableFuture.create();
282         stage.whenComplete((reply, failure) -> {
283             if (failure != null) {
284                 LOG.warn("{} DataCenter failed", op, failure);
285                 future.setException(failure);
286             } else {
287                 LOG.debug("{} DataCenter successful", op);
288                 future.set(Empty.value());
289             }
290         });
291         return future;
292     }
293 }