Fix eos entity lookups with YangInstanceIdentifier
[controller.git] / opendaylight / md-sal / eos-dom-akka / src / main / java / org / opendaylight / controller / eos / akka / owner / supervisor / OwnerSyncer.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.owner.supervisor;
9
10 import static java.util.Objects.requireNonNull;
11
12 import akka.actor.typed.ActorRef;
13 import akka.actor.typed.Behavior;
14 import akka.actor.typed.javadsl.AbstractBehavior;
15 import akka.actor.typed.javadsl.ActorContext;
16 import akka.actor.typed.javadsl.Behaviors;
17 import akka.actor.typed.javadsl.Receive;
18 import akka.cluster.ddata.LWWRegister;
19 import akka.cluster.ddata.LWWRegisterKey;
20 import akka.cluster.ddata.ORMap;
21 import akka.cluster.ddata.ORSet;
22 import akka.cluster.ddata.typed.javadsl.DistributedData;
23 import akka.cluster.ddata.typed.javadsl.Replicator;
24 import akka.cluster.ddata.typed.javadsl.ReplicatorMessageAdapter;
25 import java.time.Duration;
26 import java.util.HashMap;
27 import java.util.HashSet;
28 import java.util.Map;
29 import java.util.Set;
30 import org.eclipse.jdt.annotation.Nullable;
31 import org.opendaylight.controller.eos.akka.owner.supervisor.command.DataCenterActivated;
32 import org.opendaylight.controller.eos.akka.owner.supervisor.command.InitialCandidateSync;
33 import org.opendaylight.controller.eos.akka.owner.supervisor.command.InitialOwnerSync;
34 import org.opendaylight.controller.eos.akka.owner.supervisor.command.OwnerSupervisorCommand;
35 import org.opendaylight.controller.eos.akka.owner.supervisor.command.OwnerSupervisorReply;
36 import org.opendaylight.controller.eos.akka.registry.candidate.CandidateRegistry;
37 import org.opendaylight.mdsal.binding.dom.codec.api.BindingInstanceIdentifierCodec;
38 import org.opendaylight.mdsal.eos.dom.api.DOMEntity;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 /**
43  * Behavior that retrieves current candidates/owners from distributed-data and switches to OwnerSupervisor when the
44  * sync has finished.
45  */
46 public final class OwnerSyncer extends AbstractBehavior<OwnerSupervisorCommand> {
47     private static final Logger LOG = LoggerFactory.getLogger(OwnerSyncer.class);
48
49     private final ReplicatorMessageAdapter<OwnerSupervisorCommand, LWWRegister<String>> ownerReplicator;
50     private final Map<DOMEntity, Set<String>> currentCandidates = new HashMap<>();
51     private final Map<DOMEntity, String> currentOwners = new HashMap<>();
52
53     // String representation of Entity to DOMEntity
54     private final Map<String, DOMEntity> entityLookup = new HashMap<>();
55     private final BindingInstanceIdentifierCodec iidCodec;
56
57     private int toSync = -1;
58
59     private OwnerSyncer(final ActorContext<OwnerSupervisorCommand> context,
60                         final @Nullable ActorRef<OwnerSupervisorReply> notifyDatacenterStarted,
61                         final BindingInstanceIdentifierCodec iidCodec) {
62         super(context);
63         this.iidCodec = requireNonNull(iidCodec);
64         LOG.debug("Starting candidate and owner sync");
65
66         final ActorRef<Replicator.Command> replicator = DistributedData.get(context.getSystem()).replicator();
67
68         ownerReplicator = new ReplicatorMessageAdapter<>(context, replicator, Duration.ofSeconds(5));
69
70         new ReplicatorMessageAdapter<OwnerSupervisorCommand, ORMap<DOMEntity, ORSet<String>>>(context, replicator,
71             Duration.ofSeconds(5)).askGet(
72                 askReplyTo -> new Replicator.Get<>(CandidateRegistry.KEY, Replicator.readLocal(), askReplyTo),
73                 InitialCandidateSync::new);
74
75         if (notifyDatacenterStarted != null) {
76             notifyDatacenterStarted.tell(DataCenterActivated.INSTANCE);
77         }
78     }
79
80     public static Behavior<OwnerSupervisorCommand> create(final ActorRef<OwnerSupervisorReply> notifyDatacenterStarted,
81             final BindingInstanceIdentifierCodec iidCodec) {
82         return Behaviors.setup(ctx -> new OwnerSyncer(ctx, notifyDatacenterStarted, iidCodec));
83     }
84
85     @Override
86     public Receive<OwnerSupervisorCommand> createReceive() {
87         return newReceiveBuilder()
88                 .onMessage(InitialCandidateSync.class, this::onInitialCandidateSync)
89                 .onMessage(InitialOwnerSync.class, this::onInitialOwnerSync)
90                 .build();
91     }
92
93     private Behavior<OwnerSupervisorCommand> onInitialCandidateSync(final InitialCandidateSync rsp) {
94         final Replicator.GetResponse<ORMap<DOMEntity, ORSet<String>>> response = rsp.getResponse();
95         if (response instanceof Replicator.GetSuccess) {
96             return doInitialSync((Replicator.GetSuccess<ORMap<DOMEntity, ORSet<String>>>) response);
97         } else if (response instanceof Replicator.NotFound) {
98             LOG.debug("No candidates found switching to supervisor");
99             return switchToSupervisor();
100         } else {
101             LOG.debug("Initial candidate sync failed, switching to supervisor. Sync reply: {}", response);
102             return switchToSupervisor();
103         }
104     }
105
106     private Behavior<OwnerSupervisorCommand> doInitialSync(
107             final Replicator.GetSuccess<ORMap<DOMEntity, ORSet<String>>> response) {
108
109         final ORMap<DOMEntity, ORSet<String>> candidates = response.get(CandidateRegistry.KEY);
110         candidates.getEntries().entrySet().forEach(entry -> {
111             currentCandidates.put(entry.getKey(), new HashSet<>(entry.getValue().getElements()));
112         });
113
114         toSync = candidates.keys().size();
115         for (final DOMEntity entity : candidates.keys().getElements()) {
116             entityLookup.put(entity.toString(), entity);
117
118             ownerReplicator.askGet(
119                     askReplyTo -> new Replicator.Get<>(
120                             new LWWRegisterKey<>(entity.toString()),
121                             Replicator.readLocal(),
122                             askReplyTo),
123                     InitialOwnerSync::new);
124         }
125
126         return this;
127     }
128
129     private Behavior<OwnerSupervisorCommand> onInitialOwnerSync(final InitialOwnerSync rsp) {
130         final Replicator.GetResponse<LWWRegister<String>> response = rsp.getResponse();
131         if (response instanceof Replicator.GetSuccess) {
132             handleOwnerRsp((Replicator.GetSuccess<LWWRegister<String>>) response);
133         } else if (response instanceof Replicator.NotFound) {
134             handleNotFoundOwnerRsp((Replicator.NotFound<LWWRegister<String>>) response);
135         } else {
136             LOG.debug("Initial sync failed response: {}", response);
137         }
138
139         // count the responses, on last switch behaviors
140         toSync--;
141         if (toSync == 0) {
142             return switchToSupervisor();
143         }
144
145         return this;
146     }
147
148     private Behavior<OwnerSupervisorCommand> switchToSupervisor() {
149         LOG.debug("Initial sync done, switching to supervisor. candidates: {}, owners: {}",
150                 currentCandidates, currentOwners);
151         return Behaviors.setup(ctx -> OwnerSupervisor.create(currentCandidates, currentOwners, iidCodec));
152     }
153
154     private void handleOwnerRsp(final Replicator.GetSuccess<LWWRegister<String>> rsp) {
155         final DOMEntity entity = entityLookup.get(rsp.key().id());
156         final String owner = rsp.get(rsp.key()).getValue();
157
158         currentOwners.put(entity, owner);
159     }
160
161     private static void handleNotFoundOwnerRsp(final Replicator.NotFound<LWWRegister<String>> rsp) {
162         LOG.debug("Owner not found. {}", rsp);
163     }
164 }