2 * Copyright (c) 2015 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
9 package org.opendaylight.netconf.topology.impl;
11 import akka.actor.ActorContext;
12 import akka.actor.ActorRef;
13 import akka.actor.ActorSystem;
14 import akka.actor.TypedActor;
15 import akka.actor.TypedProps;
16 import akka.cluster.Cluster;
17 import akka.dispatch.OnComplete;
18 import com.google.common.base.Function;
19 import com.google.common.collect.FluentIterable;
20 import com.google.common.collect.Lists;
21 import com.google.common.util.concurrent.FutureCallback;
22 import com.google.common.util.concurrent.Futures;
23 import com.google.common.util.concurrent.ListenableFuture;
24 import java.util.ArrayList;
25 import java.util.Collections;
26 import java.util.List;
27 import java.util.Map.Entry;
28 import java.util.concurrent.TimeUnit;
29 import javax.annotation.Nonnull;
30 import javax.annotation.Nullable;
31 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
32 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
33 import org.opendaylight.netconf.api.NetconfMessage;
34 import org.opendaylight.netconf.api.NetconfTerminationReason;
35 import org.opendaylight.netconf.client.NetconfClientSession;
36 import org.opendaylight.netconf.client.NetconfClientSessionListener;
37 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
38 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
39 import org.opendaylight.netconf.topology.NetconfTopology;
40 import org.opendaylight.netconf.topology.NodeManager;
41 import org.opendaylight.netconf.topology.NodeManagerCallback;
42 import org.opendaylight.netconf.topology.RoleChangeStrategy;
43 import org.opendaylight.netconf.topology.TopologyManager;
44 import org.opendaylight.netconf.topology.pipeline.ClusteredNetconfDeviceCommunicator.NetconfClientSessionListenerRegistration;
45 import org.opendaylight.netconf.topology.pipeline.TopologyMountPointFacade.ConnectionStatusListenerRegistration;
46 import org.opendaylight.netconf.topology.util.BaseNodeManager;
47 import org.opendaylight.netconf.topology.util.BaseTopologyManager;
48 import org.opendaylight.netconf.topology.util.messages.AnnounceMasterMountPoint;
49 import org.opendaylight.netconf.topology.util.messages.AnnounceMasterMountPointDown;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeBuilder;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeConnectionStatus.ConnectionStatus;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.AvailableCapabilitiesBuilder;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.ClusteredConnectionStatusBuilder;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.UnavailableCapabilities;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.UnavailableCapabilitiesBuilder;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.clustered.connection.status.NodeStatus.Status;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.clustered.connection.status.NodeStatusBuilder;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.unavailable.capabilities.UnavailableCapability;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.unavailable.capabilities.UnavailableCapability.FailureReason;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.unavailable.capabilities.UnavailableCapabilityBuilder;
62 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
63 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
64 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
65 import org.opendaylight.yangtools.yang.common.QName;
66 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
67 import org.slf4j.Logger;
68 import org.slf4j.LoggerFactory;
69 import scala.concurrent.Future;
70 import scala.concurrent.duration.FiniteDuration;
72 public class NetconfNodeManagerCallback implements NodeManagerCallback, NetconfClientSessionListener{
74 private static final Logger LOG = LoggerFactory.getLogger(NetconfNodeManagerCallback.class);
76 public static final Function<Entry<QName, FailureReason>, UnavailableCapability> UNAVAILABLE_CAPABILITY_TRANSFORMER = new Function<Entry<QName, FailureReason>, UnavailableCapability>() {
78 public UnavailableCapability apply(final Entry<QName, FailureReason> input) {
79 return new UnavailableCapabilityBuilder()
80 .setCapability(input.getKey().toString())
81 .setFailureReason(input.getValue()).build();
84 public static final Function<QName, String> AVAILABLE_CAPABILITY_TRANSFORMER = new Function<QName, String>() {
86 public String apply(QName qName) {
87 // intern string representation of a capability to avoid duplicates
88 return qName.toString().intern();
92 private static final String UNKNOWN_REASON = "Unknown reason";
94 private boolean isMaster = false;
95 private ClusteredNetconfTopology topologyDispatcher;
96 private final ActorSystem actorSystem;
97 private final Cluster clusterExtension;
99 private final RoleChangeStrategy roleChangeStrategy;
101 private String nodeId;
102 private String topologyId;
103 private TopologyManager topologyManager;
104 private NodeManager nodeManager;
105 // cached context so that we can use it in callbacks from topology
106 private ActorContext cachedContext;
108 private Node currentConfig;
109 private Node currentOperationalNode;
111 private ConnectionStatusListenerRegistration connectionStatusregistration = null;
112 private NetconfClientSessionListenerRegistration sessionListener = null;
114 private ActorRef masterDataBrokerRef = null;
115 private boolean connected = false;
117 public NetconfNodeManagerCallback(final String nodeId,
118 final String topologyId,
119 final ActorSystem actorSystem,
120 final NetconfTopology topologyDispatcher,
121 final RoleChangeStrategy roleChangeStrategy) {
122 this.nodeId = nodeId;
123 this.topologyId = topologyId;
124 this.actorSystem = actorSystem;
125 this.clusterExtension = Cluster.get(actorSystem);
126 this.topologyDispatcher = (ClusteredNetconfTopology) topologyDispatcher;
127 this.roleChangeStrategy = roleChangeStrategy;
129 final Future<ActorRef> topologyRefFuture = actorSystem.actorSelection("/user/" + topologyId).resolveOne(FiniteDuration.create(10L, TimeUnit.SECONDS));
130 topologyRefFuture.onComplete(new OnComplete<ActorRef>() {
132 public void onComplete(Throwable throwable, ActorRef actorRef) throws Throwable {
133 if (throwable != null) {
134 LOG.warn("Unable to resolve actor for path: {} ", "/user/" + topologyId, throwable);
138 LOG.debug("Actor ref for path {} resolved", "/user/" + topologyId);
139 topologyManager = TypedActor.get(actorSystem).typedActorOf(new TypedProps<>(TopologyManager.class, BaseTopologyManager.class), actorRef);
141 }, actorSystem.dispatcher());
143 final Future<ActorRef> nodeRefFuture = actorSystem.actorSelection("/user/" + topologyId + "/" + nodeId).resolveOne(FiniteDuration.create(10L, TimeUnit.SECONDS));
144 nodeRefFuture.onComplete(new OnComplete<ActorRef>() {
146 public void onComplete(Throwable throwable, ActorRef actorRef) throws Throwable {
147 if (throwable != null) {
148 LOG.warn("Unable to resolve actor for path: {} ", "/user/" + topologyId + "/" + nodeId, throwable);
150 LOG.debug("Actor ref for path {} resolved", "/user/" + topologyId);
151 nodeManager = TypedActor.get(actorSystem).typedActorOf(new TypedProps<>(NodeManager.class, BaseNodeManager.class), actorRef);
153 }, actorSystem.dispatcher());
158 @Override public Node getInitialState(@Nonnull final NodeId nodeId,
159 @Nonnull final Node configNode) {
160 final NetconfNode netconfNode = configNode.getAugmentation(NetconfNode.class);
162 final Node initialNode = new NodeBuilder()
164 .addAugmentation(NetconfNode.class,
165 new NetconfNodeBuilder()
166 .setHost(netconfNode.getHost())
167 .setPort(netconfNode.getPort())
168 .setConnectionStatus(ConnectionStatus.Connecting)
169 .setClusteredConnectionStatus(
170 new ClusteredConnectionStatusBuilder()
173 new NodeStatusBuilder()
174 .setNode(clusterExtension.selfAddress().toString())
175 .setStatus(Status.Unavailable)
181 if (currentOperationalNode == null) {
182 currentOperationalNode = initialNode;
188 @Nonnull @Override public Node getFailedState(@Nonnull final NodeId nodeId,
189 @Nullable final Node configNode) {
190 final NetconfNode netconfNode = configNode == null ? currentOperationalNode.getAugmentation(NetconfNode.class) : configNode.getAugmentation(NetconfNode.class);
192 final Node failedNode = new NodeBuilder()
194 .addAugmentation(NetconfNode.class,
195 new NetconfNodeBuilder()
196 .setHost(netconfNode.getHost())
197 .setPort(netconfNode.getPort())
198 .setConnectionStatus(ConnectionStatus.UnableToConnect)
199 .setClusteredConnectionStatus(
200 new ClusteredConnectionStatusBuilder()
202 Collections.singletonList(
203 new NodeStatusBuilder()
204 .setNode(clusterExtension.selfAddress().toString())
205 .setStatus(Status.Failed)
211 if (currentOperationalNode == null) {
212 currentOperationalNode = failedNode;
218 @Nonnull @Override public ListenableFuture<Node> onNodeCreated(@Nonnull final NodeId nodeId,
219 @Nonnull final Node configNode) {
220 cachedContext = TypedActor.context();
221 this.nodeId = nodeId.getValue();
222 this.currentConfig = configNode;
223 // set initial state before anything happens
224 this.currentOperationalNode = getInitialState(nodeId, configNode);
226 // connect magic, send config into the netconf pipeline through topo dispatcher
227 final ListenableFuture<NetconfDeviceCapabilities> connectionFuture = topologyDispatcher.connectNode(nodeId, configNode);
229 Futures.addCallback(connectionFuture, new FutureCallback<NetconfDeviceCapabilities>() {
231 public void onSuccess(@Nullable NetconfDeviceCapabilities result) {
232 connectionStatusregistration = topologyDispatcher.registerConnectionStatusListener(nodeId, nodeManager);
233 sessionListener = topologyDispatcher.registerNetconfClientSessionListener(nodeId, NetconfNodeManagerCallback.this);
237 public void onFailure(Throwable t) {
238 LOG.error("Connection to device failed", t);
242 final NetconfNode netconfNode = configNode.getAugmentation(NetconfNode.class);
244 // transform future result into state that gets written into datastore
245 return Futures.transform(connectionFuture, new Function<NetconfDeviceCapabilities, Node>() {
248 public Node apply(NetconfDeviceCapabilities input) {
250 currentOperationalNode = new NodeBuilder().setNodeId(nodeId)
251 .addAugmentation(NetconfNode.class,
252 new NetconfNodeBuilder()
253 .setConnectionStatus(ConnectionStatus.Connected)
254 .setClusteredConnectionStatus(
255 new ClusteredConnectionStatusBuilder()
257 Collections.singletonList(
258 new NodeStatusBuilder()
259 .setNode(clusterExtension.selfAddress().toString())
260 .setStatus(Status.Connected)
263 .setHost(netconfNode.getHost())
264 .setPort(netconfNode.getPort())
265 .setAvailableCapabilities(new AvailableCapabilitiesBuilder().build())
266 .setUnavailableCapabilities(new UnavailableCapabilitiesBuilder().build())
268 return currentOperationalNode;
275 public ListenableFuture<Node> onNodeUpdated(@Nonnull final NodeId nodeId,
276 @Nonnull final Node configNode) {
277 // first disconnect this node
278 topologyDispatcher.unregisterMountPoint(nodeId);
280 if (connectionStatusregistration != null) {
281 connectionStatusregistration.close();
283 topologyDispatcher.disconnectNode(nodeId);
285 // now reinit this connection with new settings
286 final ListenableFuture<NetconfDeviceCapabilities> connectionFuture = topologyDispatcher.connectNode(nodeId, configNode);
288 Futures.addCallback(connectionFuture, new FutureCallback<NetconfDeviceCapabilities>() {
290 public void onSuccess(@Nullable NetconfDeviceCapabilities result) {
291 connectionStatusregistration = topologyDispatcher.registerConnectionStatusListener(nodeId, NetconfNodeManagerCallback.this);
295 public void onFailure(Throwable t) {
296 LOG.error("Connection to device failed", t);
300 final NetconfNode netconfNode = configNode.getAugmentation(NetconfNode.class);
302 return Futures.transform(connectionFuture, new Function<NetconfDeviceCapabilities, Node>() {
305 public Node apply(NetconfDeviceCapabilities input) {
307 return new NodeBuilder()
309 .addAugmentation(NetconfNode.class,
310 new NetconfNodeBuilder()
311 .setConnectionStatus(ConnectionStatus.Connected)
312 .setClusteredConnectionStatus(
313 new ClusteredConnectionStatusBuilder()
315 Collections.singletonList(
316 new NodeStatusBuilder()
317 .setNode(clusterExtension.selfAddress().toString())
318 .setStatus(Status.Connected)
321 .setHost(netconfNode.getHost())
322 .setPort(netconfNode.getPort())
323 .setAvailableCapabilities(new AvailableCapabilitiesBuilder().build())
324 .setUnavailableCapabilities(new UnavailableCapabilitiesBuilder().build())
331 @Nonnull @Override public ListenableFuture<Void> onNodeDeleted(@Nonnull final NodeId nodeId) {
332 // cleanup and disconnect
333 topologyDispatcher.unregisterMountPoint(nodeId);
335 if(connectionStatusregistration != null) {
336 connectionStatusregistration.close();
338 roleChangeStrategy.unregisterRoleCandidate();
339 return topologyDispatcher.disconnectNode(nodeId);
344 public ListenableFuture<Node> getCurrentStatusForNode(@Nonnull NodeId nodeId) {
345 LOG.debug("Getting current status for node: {} status: {}", nodeId, currentOperationalNode);
346 return Futures.immediateFuture(currentOperationalNode);
350 public void onRoleChanged(final RoleChangeDTO roleChangeDTO) {
351 topologyDispatcher.unregisterMountPoint(new NodeId(nodeId));
353 isMaster = roleChangeDTO.isOwner();
355 LOG.warn("Gained ownership of node - registering master mount point");
356 topologyDispatcher.registerMountPoint(TypedActor.context(), new NodeId(nodeId));
358 // even though mount point is ready, we dont know who the master mount point will be since we havent received the announce msg
359 // after we receive the message we can go ahead and register the mount point
360 if (connected && masterDataBrokerRef != null) {
361 topologyDispatcher.registerMountPoint(TypedActor.context(), new NodeId(nodeId), masterDataBrokerRef);
363 LOG.debug("Mount point is ready, still waiting for master mount point");
369 public void onDeviceConnected(final SchemaContext remoteSchemaContext, final NetconfSessionPreferences netconfSessionPreferences, final DOMRpcService deviceRpc) {
370 // we need to notify the higher level that something happened, get a current status from all other nodes, and aggregate a new result
372 if (!isMaster && masterDataBrokerRef != null) {
373 // if we're not master but one is present already, we need to register mountpoint
374 LOG.warn("Device connected, master already present in topology, registering mount point");
375 topologyDispatcher.registerMountPoint(cachedContext, new NodeId(nodeId), masterDataBrokerRef);
377 List<String> capabilityList = new ArrayList<>();
378 capabilityList.addAll(netconfSessionPreferences.getNetconfDeviceCapabilities().getNonModuleBasedCapabilities());
379 capabilityList.addAll(FluentIterable.from(netconfSessionPreferences.getNetconfDeviceCapabilities().getResolvedCapabilities()).transform(AVAILABLE_CAPABILITY_TRANSFORMER).toList());
380 final AvailableCapabilitiesBuilder avCapabalitiesBuilder = new AvailableCapabilitiesBuilder();
381 avCapabalitiesBuilder.setAvailableCapability(capabilityList);
383 final UnavailableCapabilities unavailableCapabilities =
384 new UnavailableCapabilitiesBuilder().setUnavailableCapability(FluentIterable.from(netconfSessionPreferences.getNetconfDeviceCapabilities().getUnresolvedCapabilites().entrySet())
385 .transform(UNAVAILABLE_CAPABILITY_TRANSFORMER).toList()).build();
387 final NetconfNode netconfNode = currentConfig.getAugmentation(NetconfNode.class);
388 currentOperationalNode = new NodeBuilder().setNodeId(new NodeId(nodeId))
389 .addAugmentation(NetconfNode.class,
390 new NetconfNodeBuilder()
391 .setConnectionStatus(ConnectionStatus.Connected)
392 .setClusteredConnectionStatus(
393 new ClusteredConnectionStatusBuilder()
395 Collections.singletonList(
396 new NodeStatusBuilder()
397 .setNode(clusterExtension.selfAddress().toString())
398 .setStatus(Status.Connected)
401 .setHost(netconfNode.getHost())
402 .setPort(netconfNode.getPort())
403 .setAvailableCapabilities(avCapabalitiesBuilder.build())
404 .setUnavailableCapabilities(unavailableCapabilities)
407 topologyManager.notifyNodeStatusChange(new NodeId(nodeId));
411 public void onDeviceDisconnected() {
412 // we need to notify the higher level that something happened, get a current status from all other nodes, and aggregate a new result
413 LOG.debug("onDeviceDisconnected received, unregistered role candidate");
416 // announce that master mount point is going down
417 // for (final Member member : clusterExtension.state().getMembers()) {
418 // actorSystem.actorSelection(member.address() + "/user/" + topologyId + "/" + nodeId).tell(new AnnounceMasterMountPointDown(), null);
420 // set master to false since we are unregistering, the ownershipChanged callback can sometimes lag behind causing multiple nodes behaving as masters
422 // onRoleChanged() callback can sometimes lag behind, so unregister the mount right when it disconnects
423 topologyDispatcher.unregisterMountPoint(new NodeId(nodeId));
426 final NetconfNode netconfNode = currentConfig.getAugmentation(NetconfNode.class);
427 currentOperationalNode = new NodeBuilder().setNodeId(new NodeId(nodeId))
428 .addAugmentation(NetconfNode.class,
429 new NetconfNodeBuilder()
430 .setConnectionStatus(ConnectionStatus.Connecting)
431 .setClusteredConnectionStatus(
432 new ClusteredConnectionStatusBuilder()
434 Collections.singletonList(
435 new NodeStatusBuilder()
436 .setNode(clusterExtension.selfAddress().toString())
437 .setStatus(Status.Unavailable)
440 .setHost(netconfNode.getHost())
441 .setPort(netconfNode.getPort())
443 topologyManager.notifyNodeStatusChange(new NodeId(nodeId));
447 public void onDeviceFailed(Throwable throwable) {
448 // we need to notify the higher level that something happened, get a current status from all other nodes, and aggregate a new result
449 // no need to remove mountpoint, we should receive onRoleChanged callback after unregistering from election that unregisters the mountpoint
450 LOG.debug("onDeviceFailed received");
452 String reason = (throwable != null && throwable.getMessage() != null) ? throwable.getMessage() : UNKNOWN_REASON;
454 currentOperationalNode = new NodeBuilder().setNodeId(new NodeId(nodeId))
455 .addAugmentation(NetconfNode.class,
456 new NetconfNodeBuilder()
457 .setConnectionStatus(ConnectionStatus.UnableToConnect)
458 .setClusteredConnectionStatus(
459 new ClusteredConnectionStatusBuilder()
461 Collections.singletonList(
462 new NodeStatusBuilder()
463 .setNode(clusterExtension.selfAddress().toString())
464 .setStatus(Status.Failed)
467 .setConnectedMessage(reason)
469 topologyManager.notifyNodeStatusChange(new NodeId(nodeId));
473 public void onNotification(DOMNotification domNotification) {
478 public void close() {
483 public void onReceive(Object message, ActorRef actorRef) {
484 LOG.warn("Netconf node callback received message {}", message);
485 if (message instanceof AnnounceMasterMountPoint) {
486 masterDataBrokerRef = actorRef;
487 // candidate gets registered when mount point is already prepared so we can go ahead a register it
488 if (roleChangeStrategy.isCandidateRegistered()) {
489 topologyDispatcher.registerMountPoint(TypedActor.context(), new NodeId(nodeId), masterDataBrokerRef);
491 LOG.warn("Announce master mount point msg received but mount point is not ready yet");
493 } else if (message instanceof AnnounceMasterMountPointDown) {
494 LOG.warn("Master mountpoint went down");
495 masterDataBrokerRef = null;
496 topologyDispatcher.unregisterMountPoint(new NodeId(nodeId));
501 public void onSessionUp(NetconfClientSession netconfClientSession) {
502 //NetconfClientSession is up, we can register role candidate
503 LOG.debug("Netconf client session is up, registering role candidate");
504 roleChangeStrategy.registerRoleCandidate(nodeManager);
508 public void onSessionDown(NetconfClientSession netconfClientSession, Exception e) {
509 LOG.debug("Netconf client session is down, unregistering role candidate");
510 roleChangeStrategy.unregisterRoleCandidate();
514 public void onSessionTerminated(NetconfClientSession netconfClientSession, NetconfTerminationReason netconfTerminationReason) {
515 LOG.debug("Netconf client session is down, unregistering role candidate");
516 roleChangeStrategy.unregisterRoleCandidate();
520 public void onMessage(NetconfClientSession netconfClientSession, NetconfMessage netconfMessage) {