Merge changes I05cce46d,Ia329ea5f,I933c58d1
[transportpce.git] / networkmodel / src / main / java / org / opendaylight / transportpce / networkmodel / NetConfTopologyListener.java
1 /*
2  * Copyright © 2016 Orange 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.transportpce.networkmodel;
9
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.util.concurrent.ListenableFuture;
12 import java.util.Collection;
13 import java.util.Map;
14 import java.util.Optional;
15 import java.util.concurrent.ConcurrentHashMap;
16 import java.util.concurrent.ExecutionException;
17 import javax.annotation.Nonnull;
18 import org.opendaylight.mdsal.binding.api.DataBroker;
19 import org.opendaylight.mdsal.binding.api.DataObjectModification;
20 import org.opendaylight.mdsal.binding.api.DataTreeChangeListener;
21 import org.opendaylight.mdsal.binding.api.DataTreeModification;
22 import org.opendaylight.mdsal.binding.api.MountPoint;
23 import org.opendaylight.mdsal.binding.api.NotificationService;
24 import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
25 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
26 import org.opendaylight.transportpce.common.StringConstants;
27 import org.opendaylight.transportpce.common.Timeouts;
28 import org.opendaylight.transportpce.common.device.DeviceTransactionManager;
29 import org.opendaylight.transportpce.common.mapping.PortMapping;
30 import org.opendaylight.transportpce.networkmodel.dto.NodeRegistration;
31 import org.opendaylight.transportpce.networkmodel.service.NetworkModelService;
32 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.CreateSubscriptionInputBuilder;
33 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.CreateSubscriptionOutput;
34 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.NotificationsService;
35 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.StreamNameType;
36 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.Netconf;
37 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.Streams;
38 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.streams.Stream;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeConnectionStatus.ConnectionStatus;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapability;
42 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
43 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
44 import org.opendaylight.yangtools.yang.common.RpcResult;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 public class NetConfTopologyListener implements DataTreeChangeListener<Node> {
49
50     private static final Logger LOG = LoggerFactory.getLogger(NetConfTopologyListener.class);
51     private static final String RPC_SERVICE_FAILED = "Failed to get RpcService for node {}";
52     private final NetworkModelService networkModelService;
53     private final DataBroker dataBroker;
54     private final DeviceTransactionManager deviceTransactionManager;
55     private final Map<String, NodeRegistration> registrations;
56     private final PortMapping portMapping;
57
58     public NetConfTopologyListener(final NetworkModelService networkModelService, final DataBroker dataBroker,
59              DeviceTransactionManager deviceTransactionManager, PortMapping portMapping) {
60         this.networkModelService = networkModelService;
61         this.dataBroker = dataBroker;
62         this.deviceTransactionManager = deviceTransactionManager;
63         this.registrations = new ConcurrentHashMap<>();
64         this.portMapping = portMapping;
65     }
66
67     public void onDataTreeChanged(@Nonnull Collection<DataTreeModification<Node>> changes) {
68         LOG.info("onDataTreeChanged - {}", this.getClass().getSimpleName());
69         for (DataTreeModification<Node> change : changes) {
70             DataObjectModification<Node> rootNode = change.getRootNode();
71             if (rootNode.getDataBefore() == null) {
72                 continue;
73             }
74             String nodeId = rootNode.getDataBefore().key().getNodeId().getValue();
75             NetconfNode netconfNodeBefore = rootNode.getDataBefore().augmentation(NetconfNode.class);
76             switch (rootNode.getModificationType()) {
77                 case DELETE:
78                     if (this.networkModelService.deleteOpenRoadmnode(nodeId)) {
79                         onDeviceDisConnected(nodeId);
80                         LOG.info("Device {} correctly disconnected from controller", nodeId);
81                     }
82                     break;
83                 case WRITE:
84                     NetconfNode netconfNodeAfter = rootNode.getDataAfter().augmentation(NetconfNode.class);
85                     if (ConnectionStatus.Connecting.equals(netconfNodeBefore.getConnectionStatus())
86                         && ConnectionStatus.Connected.equals(netconfNodeAfter.getConnectionStatus())) {
87                         LOG.info("Connecting Node: {}", nodeId);
88                         Optional<AvailableCapability> deviceCapabilityOpt = netconfNodeAfter
89                             .getAvailableCapabilities().getAvailableCapability().stream()
90                             .filter(cp -> cp.getCapability().contains(StringConstants.OPENROADM_DEVICE_MODEL_NAME))
91                             .sorted((c1, c2) -> c2.getCapability().compareTo(c1.getCapability()))
92                             .findFirst();
93                         if (deviceCapabilityOpt.isEmpty()) {
94                             LOG.error("Unable to get openroadm-device-capability");
95                             return;
96                         }
97                         this.networkModelService
98                             .createOpenRoadmNode(nodeId, deviceCapabilityOpt.get().getCapability());
99                         onDeviceConnected(nodeId,deviceCapabilityOpt.get().getCapability());
100                         LOG.info("Device {} correctly connected to controller", nodeId);
101                     }
102                     if (ConnectionStatus.Connected.equals(netconfNodeBefore.getConnectionStatus())
103                         && ConnectionStatus.Connecting.equals(netconfNodeAfter.getConnectionStatus())) {
104                         LOG.warn("Node: {} is being disconnected", nodeId);
105                     }
106                     break;
107                 default:
108                     LOG.debug("Unknown modification type {}", rootNode.getModificationType().name());
109                     break;
110             }
111         }
112     }
113
114     private void onDeviceConnected(final String nodeId, String openRoadmVersion) {
115         LOG.info("onDeviceConnected: {}", nodeId);
116         Optional<MountPoint> mountPointOpt = this.deviceTransactionManager.getDeviceMountPoint(nodeId);
117         MountPoint mountPoint;
118         if (mountPointOpt.isPresent()) {
119             mountPoint = mountPointOpt.get();
120         } else {
121             LOG.error("Failed to get mount point for node {}", nodeId);
122             return;
123         }
124         final Optional<NotificationService> notificationService = mountPoint.getService(NotificationService.class);
125         if (!notificationService.isPresent()) {
126             LOG.error(RPC_SERVICE_FAILED, nodeId);
127             return;
128         }
129         NodeRegistration nodeRegistration = new NodeRegistration(nodeId, openRoadmVersion,
130             notificationService.get(), this.dataBroker, this.portMapping);
131         nodeRegistration.registerListeners();
132         registrations.put(nodeId, nodeRegistration);
133         String streamName = getSupportedStream(nodeId);
134         LOG.info("Device is supporting notification stream {}",streamName);
135         subscribeStream(mountPoint, streamName, nodeId);
136     }
137
138     private void onDeviceDisConnected(final String nodeId) {
139         LOG.info("onDeviceDisConnected: {}", nodeId);
140         NodeRegistration nodeRegistration = this.registrations.remove(nodeId);
141         nodeRegistration.unregisterListeners();
142     }
143
144     private boolean subscribeStream(MountPoint mountPoint, String streamName, String nodeId) {
145         final Optional<RpcConsumerRegistry> service = mountPoint.getService(RpcConsumerRegistry.class);
146         if (!service.isPresent()) {
147             return false;
148         }
149         final NotificationsService rpcService = service.get().getRpcService(NotificationsService.class);
150         if (rpcService == null) {
151             LOG.error(RPC_SERVICE_FAILED, nodeId);
152             return false;
153         }
154         final CreateSubscriptionInputBuilder createSubscriptionInputBuilder = new CreateSubscriptionInputBuilder()
155             .setStream(new StreamNameType(streamName));
156         LOG.info("Triggering notification stream {} for node {}", streamName, nodeId);
157         ListenableFuture<RpcResult<CreateSubscriptionOutput>> subscription = rpcService
158             .createSubscription(createSubscriptionInputBuilder.build());
159         try {
160             subscription.get();
161         } catch (InterruptedException | ExecutionException e) {
162             LOG.error("Error during subscription to stream {}", streamName, e);
163         }
164         return true;
165     }
166
167     @VisibleForTesting
168     public NetConfTopologyListener(final NetworkModelService networkModelService, final DataBroker dataBroker,
169         DeviceTransactionManager deviceTransactionManager, PortMapping portMapping,
170         Map<String, NodeRegistration> registrations) {
171         this.networkModelService = networkModelService;
172         this.dataBroker = dataBroker;
173         this.deviceTransactionManager = deviceTransactionManager;
174         this.portMapping = portMapping;
175         this.registrations = registrations;
176     }
177
178     private String getSupportedStream(String nodeId) {
179         InstanceIdentifier<Streams> streamsIID = InstanceIdentifier.create(Netconf.class).child(Streams.class);
180         Optional<Streams> ordmInfoObject =
181                 deviceTransactionManager.getDataFromDevice(nodeId, LogicalDatastoreType.OPERATIONAL, streamsIID,
182                         Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
183         if (ordmInfoObject == null || ordmInfoObject.isEmpty() || ordmInfoObject.get().getStream().isEmpty()) {
184             LOG.error("List of streams supports by device is not present");
185             return "NETCONF";
186         }
187         for (Stream strm : ordmInfoObject.get().getStream().values()) {
188             LOG.debug("Streams are {}", strm);
189             if ("OPENROADM".equalsIgnoreCase(strm.getName().getValue())) {
190                 return strm.getName().getValue();
191             }
192         }
193         return "NETCONF";
194     }
195 }