Simplify getDescription invocation
[netconf.git] / netconf / netconf-topology-singleton / src / main / java / org / opendaylight / netconf / topology / singleton / impl / NetconfNodeManager.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. 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.netconf.topology.singleton.impl;
9
10 import akka.actor.ActorRef;
11 import akka.actor.ActorSelection;
12 import akka.actor.PoisonPill;
13 import akka.dispatch.OnComplete;
14 import akka.pattern.AskTimeoutException;
15 import akka.pattern.Patterns;
16 import akka.util.Timeout;
17 import java.util.Collection;
18 import javax.annotation.concurrent.GuardedBy;
19 import org.opendaylight.mdsal.binding.api.ClusteredDataTreeChangeListener;
20 import org.opendaylight.mdsal.binding.api.DataObjectModification;
21 import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
22 import org.opendaylight.mdsal.binding.api.DataTreeModification;
23 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
24 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
25 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
26 import org.opendaylight.netconf.topology.singleton.api.NetconfTopologySingletonService;
27 import org.opendaylight.netconf.topology.singleton.impl.actors.NetconfNodeActor;
28 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
29 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils;
30 import org.opendaylight.netconf.topology.singleton.messages.AskForMasterMountPoint;
31 import org.opendaylight.netconf.topology.singleton.messages.RefreshSlaveActor;
32 import org.opendaylight.netconf.topology.singleton.messages.UnregisterSlaveMountPoint;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeConnectionStatus;
35 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
36 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
37 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
38 import org.opendaylight.yangtools.concepts.ListenerRegistration;
39 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
40 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
41 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44 import scala.concurrent.Future;
45
46 /**
47  * Managing and reacting on data tree changes in specific netconf node when master writes status to the operational
48  * data store (e.g. handling lifecycle of slave mount point).
49  */
50 class NetconfNodeManager
51         implements ClusteredDataTreeChangeListener<Node>, NetconfTopologySingletonService, AutoCloseable {
52
53     private static final Logger LOG = LoggerFactory.getLogger(NetconfNodeManager.class);
54
55     private final Timeout actorResponseWaitTime;
56     private final DOMMountPointService mountPointService;
57     private final SchemaSourceRegistry schemaRegistry;
58     private final SchemaRepository schemaRepository;
59
60     private volatile NetconfTopologySetup setup;
61     private volatile ListenerRegistration<NetconfNodeManager> dataChangeListenerRegistration;
62     private volatile RemoteDeviceId id;
63
64     @GuardedBy("this")
65     private ActorRef slaveActorRef;
66
67     @GuardedBy("this")
68     private boolean closed;
69
70     @GuardedBy("this")
71     private int lastUpdateCount;
72
73     NetconfNodeManager(final NetconfTopologySetup setup,
74                        final RemoteDeviceId id, final Timeout actorResponseWaitTime,
75                        final DOMMountPointService mountPointService) {
76         this.setup = setup;
77         this.id = id;
78         this.schemaRegistry = setup.getSchemaResourcesDTO().getSchemaRegistry();
79         this.schemaRepository = setup.getSchemaResourcesDTO().getSchemaRepository();
80         this.actorResponseWaitTime = actorResponseWaitTime;
81         this.mountPointService = mountPointService;
82     }
83
84     @Override
85     public void onDataTreeChanged(final Collection<DataTreeModification<Node>> changes) {
86         for (final DataTreeModification<Node> change : changes) {
87             final DataObjectModification<Node> rootNode = change.getRootNode();
88             final NodeId nodeId = NetconfTopologyUtils.getNodeId(rootNode.getIdentifier());
89             switch (rootNode.getModificationType()) {
90                 case SUBTREE_MODIFIED:
91                     LOG.debug("{}: Operational state for node {} - subtree modified from {} to {}",
92                             id, nodeId, rootNode.getDataBefore(), rootNode.getDataAfter());
93                     handleSlaveMountPoint(rootNode);
94                     break;
95                 case WRITE:
96                     if (rootNode.getDataBefore() != null) {
97                         LOG.debug("{}: Operational state for node {} updated from {} to {}",
98                                 id, nodeId, rootNode.getDataBefore(), rootNode.getDataAfter());
99                     } else {
100                         LOG.debug("{}: Operational state for node {} created: {}",
101                                 id, nodeId, rootNode.getDataAfter());
102                     }
103                     handleSlaveMountPoint(rootNode);
104                     break;
105                 case DELETE:
106                     LOG.debug("{}: Operational state for node {} deleted.", id, nodeId);
107                     unregisterSlaveMountpoint();
108                     break;
109                 default:
110                     LOG.debug("{}: Uknown operation for node: {}", id, nodeId);
111             }
112         }
113     }
114
115     @Override
116     public synchronized void close() {
117         if (closed) {
118             return;
119         }
120
121         closed = true;
122         closeActor();
123         if (dataChangeListenerRegistration != null) {
124             dataChangeListenerRegistration.close();
125             dataChangeListenerRegistration = null;
126         }
127     }
128
129     @GuardedBy("this")
130     private void closeActor() {
131         if (slaveActorRef != null) {
132             LOG.debug("{}: Sending poison pill to {}", id, slaveActorRef);
133             slaveActorRef.tell(PoisonPill.getInstance(), ActorRef.noSender());
134             slaveActorRef = null;
135         }
136     }
137
138     private synchronized void unregisterSlaveMountpoint() {
139         lastUpdateCount++;
140         if (slaveActorRef != null) {
141             LOG.debug("{}: Sending message to unregister slave mountpoint to {}", id, slaveActorRef);
142             slaveActorRef.tell(new UnregisterSlaveMountPoint(), ActorRef.noSender());
143         }
144     }
145
146     void registerDataTreeChangeListener(final String topologyId, final NodeKey key) {
147         final InstanceIdentifier<Node> path = NetconfTopologyUtils.createTopologyNodeListPath(key, topologyId);
148         LOG.debug("{}: Registering data tree change listener on path {}", id, path);
149         dataChangeListenerRegistration = setup.getDataBroker().registerDataTreeChangeListener(
150                 DataTreeIdentifier.create(LogicalDatastoreType.OPERATIONAL, path), this);
151     }
152
153     private synchronized void handleSlaveMountPoint(final DataObjectModification<Node> rootNode) {
154         if (closed) {
155             return;
156         }
157
158         @SuppressWarnings("ConstantConditions")
159         final NetconfNode netconfNodeAfter = rootNode.getDataAfter().augmentation(NetconfNode.class);
160
161         if (NetconfNodeConnectionStatus.ConnectionStatus.Connected.equals(netconfNodeAfter.getConnectionStatus())) {
162             lastUpdateCount++;
163             createOrUpdateActorRef();
164
165             final String masterAddress = netconfNodeAfter.getClusteredConnectionStatus().getNetconfMasterNode();
166             final String masterActorPath = NetconfTopologyUtils.createActorPath(masterAddress,
167                     NetconfTopologyUtils.createMasterActorName(id.getName(),
168                             netconfNodeAfter.getClusteredConnectionStatus().getNetconfMasterNode()));
169
170             final AskForMasterMountPoint askForMasterMountPoint = new AskForMasterMountPoint(slaveActorRef);
171             final ActorSelection masterActor = setup.getActorSystem().actorSelection(masterActorPath);
172
173             LOG.debug("{}: Sending {} message to master {}", id, askForMasterMountPoint, masterActor);
174
175             sendAskForMasterMountPointWithRetries(askForMasterMountPoint, masterActor, 1, lastUpdateCount);
176         } else {
177             unregisterSlaveMountpoint();
178         }
179     }
180
181     @GuardedBy("this")
182     private void sendAskForMasterMountPointWithRetries(final AskForMasterMountPoint askForMasterMountPoint,
183             final ActorSelection masterActor, final int tries, final int updateCount) {
184         final Future<Object> future = Patterns.ask(masterActor, askForMasterMountPoint, actorResponseWaitTime);
185         future.onComplete(new OnComplete<Object>() {
186             @Override
187             public void onComplete(final Throwable failure, final Object response) {
188                 synchronized (this) {
189                     // Ignore the response if we were since closed or another notification update occurred.
190                     if (closed || updateCount != lastUpdateCount) {
191                         return;
192                     }
193
194                     if (failure instanceof AskTimeoutException) {
195                         if (tries <= 5 || tries % 10 == 0) {
196                             LOG.warn("{}: Failed to send message to {} - retrying...", id, masterActor, failure);
197                         }
198                         sendAskForMasterMountPointWithRetries(askForMasterMountPoint, masterActor, tries + 1,
199                                 updateCount);
200                     } else if (failure != null) {
201                         LOG.error("{}: Failed to send message {} to {}. Slave mount point could not be created",
202                                 id, askForMasterMountPoint, masterActor, failure);
203                     } else {
204                         LOG.debug("{}: {} message to {} succeeded", id, askForMasterMountPoint, masterActor);
205                     }
206                 }
207             }
208         }, setup.getActorSystem().dispatcher());
209     }
210
211     @GuardedBy("this")
212     private void createOrUpdateActorRef() {
213         if (slaveActorRef == null) {
214             slaveActorRef = setup.getActorSystem().actorOf(NetconfNodeActor.props(setup, id, schemaRegistry,
215                     schemaRepository, actorResponseWaitTime, mountPointService));
216             LOG.debug("{}: Slave actor created with name {}", id, slaveActorRef);
217         } else {
218             slaveActorRef
219                     .tell(new RefreshSlaveActor(setup, id, schemaRegistry, schemaRepository, actorResponseWaitTime),
220                             ActorRef.noSender());
221         }
222     }
223
224     void refreshDevice(final NetconfTopologySetup netconfTopologyDeviceSetup, final RemoteDeviceId remoteDeviceId) {
225         setup = netconfTopologyDeviceSetup;
226         id = remoteDeviceId;
227     }
228 }