c4a67e02927abeb18dff06c634791762cad2497c
[openflowplugin.git] / applications / topology-lldp-discovery / src / main / java / org / opendaylight / openflowplugin / applications / topology / lldp / LLDPLinkAger.java
1 /*
2  * Copyright (c) 2014 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.openflowplugin.applications.topology.lldp;
9
10 import com.google.common.annotations.VisibleForTesting;
11 import java.util.Date;
12 import java.util.List;
13 import java.util.Map.Entry;
14 import java.util.Timer;
15 import java.util.TimerTask;
16 import java.util.concurrent.ConcurrentHashMap;
17 import java.util.concurrent.ConcurrentMap;
18 import javax.annotation.PreDestroy;
19 import javax.inject.Inject;
20 import javax.inject.Singleton;
21 import org.eclipse.jdt.annotation.NonNull;
22 import org.opendaylight.mdsal.binding.api.ClusteredDataTreeChangeListener;
23 import org.opendaylight.mdsal.binding.api.DataBroker;
24 import org.opendaylight.mdsal.binding.api.DataObjectModification;
25 import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
26 import org.opendaylight.mdsal.binding.api.DataTreeModification;
27 import org.opendaylight.mdsal.binding.api.NotificationPublishService;
28 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
29 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipService;
30 import org.opendaylight.openflowplugin.api.openflow.configuration.ConfigurationListener;
31 import org.opendaylight.openflowplugin.api.openflow.configuration.ConfigurationService;
32 import org.opendaylight.openflowplugin.applications.topology.lldp.utils.LLDPDiscoveryUtils;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.topology.discovery.rev130819.LinkDiscovered;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.topology.discovery.rev130819.LinkRemoved;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.topology.discovery.rev130819.LinkRemovedBuilder;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.lldp.discovery.config.rev160511.TopologyLldpDiscoveryConfig;
39 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
40 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId;
41 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
42 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
43 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Link;
44 import org.opendaylight.yangtools.concepts.Registration;
45 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 @Singleton
50 public final class LLDPLinkAger implements ConfigurationListener, ClusteredDataTreeChangeListener<Link>, AutoCloseable {
51     private static final Logger LOG = LoggerFactory.getLogger(LLDPLinkAger.class);
52     static final String TOPOLOGY_ID = "flow:1";
53     static final InstanceIdentifier<Link> II_TO_LINK = InstanceIdentifier.create(NetworkTopology.class)
54             .child(Topology.class, new TopologyKey(new TopologyId(TOPOLOGY_ID))).child(Link.class);
55
56     private final long linkExpirationTime;
57     // FIXME: use Instant instead of Date
58     private final ConcurrentMap<LinkDiscovered, Date> linkToDate = new ConcurrentHashMap<>();
59     private final Timer timer = new Timer();
60     private final NotificationPublishService notificationService;
61     private final AutoCloseable configurationServiceRegistration;
62     private final EntityOwnershipService eos;
63     private Registration listenerRegistration;
64
65     /**
66      * default ctor - start timer.
67      */
68     @Inject
69     @SuppressWarnings("checkstyle:IllegalCatch")
70     public LLDPLinkAger(final TopologyLldpDiscoveryConfig topologyLldpDiscoveryConfig,
71                         final NotificationPublishService notificationService,
72                         final ConfigurationService configurationService,
73                         final EntityOwnershipService entityOwnershipService,
74                         final DataBroker dataBroker) {
75         linkExpirationTime = topologyLldpDiscoveryConfig.getTopologyLldpExpirationInterval().getValue().toJava();
76         this.notificationService = notificationService;
77         configurationServiceRegistration = configurationService.registerListener(this);
78         eos = entityOwnershipService;
79         final DataTreeIdentifier<Link> dtiToNodeConnector = DataTreeIdentifier.of(LogicalDatastoreType.OPERATIONAL,
80                 II_TO_LINK);
81         try {
82             listenerRegistration = dataBroker.registerDataTreeChangeListener(dtiToNodeConnector, LLDPLinkAger.this);
83         } catch (Exception e) {
84             LOG.error("DataTreeChangeListeners registration failed:", e);
85             throw new IllegalStateException("LLDPLinkAger startup failed!", e);
86         }
87         timer.schedule(new LLDPAgingTask(), 0,
88             topologyLldpDiscoveryConfig.getTopologyLldpInterval().getValue().toJava());
89     }
90
91     public void put(final LinkDiscovered link) {
92         Date expires = new Date();
93         expires.setTime(expires.getTime() + linkExpirationTime);
94         linkToDate.put(link, expires);
95     }
96
97     @Override
98     @PreDestroy
99     public void close() throws Exception {
100         if (listenerRegistration != null) {
101             listenerRegistration.close();
102             listenerRegistration = null;
103         }
104         timer.cancel();
105         linkToDate.clear();
106         configurationServiceRegistration.close();
107     }
108
109     @Override
110     public void onDataTreeChanged(final List<DataTreeModification<Link>> changes) {
111         for (DataTreeModification<Link> modification : changes) {
112             switch (modification.getRootNode().modificationType()) {
113                 case WRITE:
114                     break;
115                 case SUBTREE_MODIFIED:
116                     // NOOP
117                     break;
118                 case DELETE:
119                     processLinkDeleted(modification.getRootNode());
120                     break;
121                 default:
122                     LOG.error("Unhandled modification type: {}", modification.getRootNode().modificationType());
123             }
124         }
125     }
126
127     @VisibleForTesting
128     public boolean isLinkToDateEmpty() {
129         return linkToDate.isEmpty();
130     }
131
132     @Override
133     public void onPropertyChanged(@NonNull final String propertyName, @NonNull final String propertyValue) {
134         final TopologyLLDPDiscoveryProperty lldpDiscoveryProperty = TopologyLLDPDiscoveryProperty.forValue(
135                 propertyName);
136         if (lldpDiscoveryProperty != null) {
137             switch (lldpDiscoveryProperty) {
138                 case LLDP_SECURE_KEY:
139                 case TOPOLOGY_LLDP_INTERVAL:
140                 case TOPOLOGY_LLDP_EXPIRATION_INTERVAL:
141                     LOG.warn("Runtime update not supported for property {}", lldpDiscoveryProperty);
142                     break;
143                 default:
144                     LOG.warn("No topology lldp discovery property found.");
145                     break;
146             }
147         }
148     }
149
150     protected boolean isLinkPresent(final LinkDiscovered linkDiscovered) {
151         return linkToDate.containsKey(linkDiscovered);
152     }
153
154     private void processLinkDeleted(final DataObjectModification<Link> rootNode) {
155         Link link = rootNode.getDataBefore();
156         LOG.trace("Removing link {} from linkToDate cache", link);
157         LinkDiscovered linkDiscovered = LLDPDiscoveryUtils.toLLDPLinkDiscovered(link);
158         linkToDate.remove(linkDiscovered);
159     }
160
161     private final class LLDPAgingTask extends TimerTask {
162         @Override
163         public void run() {
164             for (Entry<LinkDiscovered, Date> entry : linkToDate.entrySet()) {
165                 LinkDiscovered link = entry.getKey();
166                 Date expires = entry.getValue();
167                 Date now = new Date();
168                 if (now.after(expires)) {
169                     if (notificationService != null) {
170                         LinkRemovedBuilder lrb = new LinkRemovedBuilder(link);
171                         NodeKey nodeKey = link.getDestination().getValue().firstKeyOf(Node.class);
172                         LOG.info("No update received for link {} from last {} milliseconds. Removing link from cache.",
173                                 link, linkExpirationTime);
174                         linkToDate.remove(link);
175                         if (nodeKey != null && LLDPDiscoveryUtils.isEntityOwned(eos, nodeKey.getId().getValue())) {
176                             LOG.info("Publish Link Remove event for the link {}", link);
177                             final LinkRemoved lr = lrb.build();
178                             try {
179                                 notificationService.putNotification(lr);
180                             } catch (InterruptedException e) {
181                                 LOG.warn("Interrupted while publishing notification {}", lr, e);
182                             }
183                         } else {
184                             LOG.trace("Skip publishing Link Remove event for the link {} because link destination "
185                                     + "node is not owned by the controller", link);
186                         }
187                     }
188                 }
189             }
190         }
191     }
192 }