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