2 * Copyright (c) 2017 Cisco Systems, Inc. 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.cluster.sharding;
10 import static java.util.Objects.requireNonNull;
12 import akka.actor.ActorRef;
13 import akka.actor.Props;
14 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedActor;
15 import org.opendaylight.controller.cluster.dom.api.LeaderLocation;
16 import org.opendaylight.controller.cluster.dom.api.LeaderLocationListener;
17 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
18 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
19 import org.opendaylight.controller.cluster.notifications.RoleChangeNotification;
22 * Proxy actor which acts as a facade for user-provided
23 * {@link LeaderLocationListener}. It subscribes for {@link LeaderStateChanged}
24 * notifications in its pre start hook and translates them to
25 * {@link LeaderLocationListener#onLeaderLocationChanged(LeaderLocation)}
28 public final class RoleChangeListenerActor extends AbstractUntypedActor {
29 private final LeaderLocationListener leaderLocationListener;
30 private final ActorRef roleChangeNotifier;
32 private RoleChangeListenerActor(final ActorRef roleChangeNotifier, final LeaderLocationListener listener) {
33 this.roleChangeNotifier = requireNonNull(roleChangeNotifier);
34 this.leaderLocationListener = requireNonNull(listener);
38 public void preStart() throws Exception {
40 roleChangeNotifier.tell(new RegisterRoleChangeListener(), getSelf());
44 protected void handleReceive(final Object message) {
45 if (message instanceof RoleChangeNotification) {
46 ignoreMessage(message);
47 } else if (message instanceof LeaderStateChanged) {
48 onLeaderStateChanged((LeaderStateChanged) message);
50 unknownMessage(message);
54 private void onLeaderStateChanged(final LeaderStateChanged message) {
55 final LeaderLocation newLocation;
56 if (message.getLeaderId() == null) {
57 newLocation = LeaderLocation.UNKNOWN;
58 } else if (message.getMemberId().equals(message.getLeaderId())) {
59 newLocation = LeaderLocation.LOCAL;
61 newLocation = LeaderLocation.REMOTE;
64 // TODO should we wrap this in try catch block?
65 leaderLocationListener.onLeaderLocationChanged(newLocation);
68 public static Props props(final ActorRef roleChangeNotifier, final LeaderLocationListener listener) {
69 return Props.create(RoleChangeListenerActor.class, roleChangeNotifier, listener);