8cdfd50fbc309c6dcf13e8f8deca078a8f598735
[onosfw.git] /
1 /*
2  * Copyright 2014-2015 Open Networking Laboratory
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.onosproject.provider.lldp.impl;
17
18 import com.google.common.collect.Sets;
19 import org.jboss.netty.util.Timeout;
20 import org.jboss.netty.util.TimerTask;
21 import org.onlab.packet.Ethernet;
22 import org.onlab.packet.ONOSLLDP;
23 import org.onlab.util.Timer;
24 import org.onosproject.net.ConnectPoint;
25 import org.onosproject.net.Device;
26 import org.onosproject.net.DeviceId;
27 import org.onosproject.net.Link.Type;
28 import org.onosproject.net.LinkKey;
29 import org.onosproject.net.Port;
30 import org.onosproject.net.PortNumber;
31 import org.onosproject.net.link.DefaultLinkDescription;
32 import org.onosproject.net.link.LinkDescription;
33 import org.onosproject.net.packet.DefaultOutboundPacket;
34 import org.onosproject.net.packet.OutboundPacket;
35 import org.onosproject.net.packet.PacketContext;
36 import org.slf4j.Logger;
37
38 import java.nio.ByteBuffer;
39 import java.util.Set;
40
41 import static java.util.concurrent.TimeUnit.MILLISECONDS;
42 import static org.onosproject.net.PortNumber.portNumber;
43 import static org.onosproject.net.flow.DefaultTrafficTreatment.builder;
44 import static org.slf4j.LoggerFactory.getLogger;
45
46 /**
47  * Run discovery process from a physical switch. Ports are initially labeled as
48  * slow ports. When an LLDP is successfully received, label the remote port as
49  * fast. Every probeRate milliseconds, loop over all fast ports and send an
50  * LLDP, send an LLDP for a single slow port. Based on FlowVisor topology
51  * discovery implementation.
52  */
53 class LinkDiscovery implements TimerTask {
54
55     private final Logger log = getLogger(getClass());
56
57     private static final String SRC_MAC = "DE:AD:BE:EF:BA:11";
58
59     private final Device device;
60     private final DiscoveryContext context;
61
62     private final ONOSLLDP lldpPacket;
63     private final Ethernet ethPacket;
64     private Ethernet bddpEth;
65
66     private Timeout timeout;
67     private volatile boolean isStopped;
68
69     // Set of ports to be probed
70     private final Set<Long> ports = Sets.newConcurrentHashSet();
71
72     /**
73      * Instantiates discovery manager for the given physical switch. Creates a
74      * generic LLDP packet that will be customized for the port it is sent out on.
75      * Starts the the timer for the discovery process.
76      *
77      * @param device  the physical switch
78      * @param context discovery context
79      */
80     LinkDiscovery(Device device, DiscoveryContext context) {
81         this.device = device;
82         this.context = context;
83
84         lldpPacket = new ONOSLLDP();
85         lldpPacket.setChassisId(device.chassisId());
86         lldpPacket.setDevice(device.id().toString());
87
88         ethPacket = new Ethernet();
89         ethPacket.setEtherType(Ethernet.TYPE_LLDP);
90         ethPacket.setDestinationMACAddress(ONOSLLDP.LLDP_NICIRA);
91         ethPacket.setPayload(this.lldpPacket);
92         ethPacket.setPad(true);
93
94         bddpEth = new Ethernet();
95         bddpEth.setPayload(lldpPacket);
96         bddpEth.setEtherType(Ethernet.TYPE_BSN);
97         bddpEth.setDestinationMACAddress(ONOSLLDP.BDDP_MULTICAST);
98         bddpEth.setPad(true);
99
100         isStopped = true;
101         start();
102         log.debug("Started discovery manager for switch {}", device.id());
103
104     }
105
106     synchronized void stop() {
107         if (!isStopped) {
108             isStopped = true;
109             timeout.cancel();
110         } else {
111             log.warn("LinkDiscovery stopped multiple times?");
112         }
113     }
114
115     synchronized void start() {
116         if (isStopped) {
117             isStopped = false;
118             timeout = Timer.getTimer().newTimeout(this, 0, MILLISECONDS);
119         } else {
120             log.warn("LinkDiscovery started multiple times?");
121         }
122     }
123
124     synchronized boolean isStopped() {
125         return isStopped || timeout.isCancelled();
126     }
127
128     /**
129      * Add physical port port to discovery process.
130      * Send out initial LLDP and label it as slow port.
131      *
132      * @param port the port
133      */
134     void addPort(Port port) {
135         boolean newPort = ports.add(port.number().toLong());
136         boolean isMaster = context.mastershipService().isLocalMaster(device.id());
137         if (newPort && isMaster) {
138             log.debug("Sending initial probe to port {}@{}", port.number().toLong(), device.id());
139             sendProbes(port.number().toLong());
140         }
141     }
142
143     /**
144      * Handles an incoming LLDP packet. Creates link in topology and adds the
145      * link for staleness tracking.
146      *
147      * @param packetContext packet context
148      * @return true if handled
149      */
150     boolean handleLLDP(PacketContext packetContext) {
151         Ethernet eth = packetContext.inPacket().parsed();
152         if (eth == null) {
153             return false;
154         }
155
156         ONOSLLDP onoslldp = ONOSLLDP.parseONOSLLDP(eth);
157         if (onoslldp != null) {
158             PortNumber srcPort = portNumber(onoslldp.getPort());
159             PortNumber dstPort = packetContext.inPacket().receivedFrom().port();
160             DeviceId srcDeviceId = DeviceId.deviceId(onoslldp.getDeviceString());
161             DeviceId dstDeviceId = packetContext.inPacket().receivedFrom().deviceId();
162
163             ConnectPoint src = new ConnectPoint(srcDeviceId, srcPort);
164             ConnectPoint dst = new ConnectPoint(dstDeviceId, dstPort);
165
166             LinkDescription ld = eth.getEtherType() == Ethernet.TYPE_LLDP ?
167                     new DefaultLinkDescription(src, dst, Type.DIRECT) :
168                     new DefaultLinkDescription(src, dst, Type.INDIRECT);
169
170             try {
171                 context.providerService().linkDetected(ld);
172                 context.touchLink(LinkKey.linkKey(src, dst));
173             } catch (IllegalStateException e) {
174                 return true;
175             }
176             return true;
177         }
178         return false;
179     }
180
181
182     /**
183      * Execute this method every t milliseconds. Loops over all ports
184      * labeled as fast and sends out an LLDP. Send out an LLDP on a single slow
185      * port.
186      *
187      * @param t timeout
188      */
189     @Override
190     public void run(Timeout t) {
191         if (isStopped()) {
192             return;
193         }
194
195         if (context.mastershipService().isLocalMaster(device.id())) {
196             log.trace("Sending probes from {}", device.id());
197             ports.forEach(this::sendProbes);
198         }
199
200         if (!isStopped()) {
201             timeout = Timer.getTimer().newTimeout(this, context.probeRate(), MILLISECONDS);
202         }
203     }
204
205     /**
206      * Creates packet_out LLDP for specified output port.
207      *
208      * @param port the port
209      * @return Packet_out message with LLDP data
210      */
211     private OutboundPacket createOutBoundLLDP(Long port) {
212         if (port == null) {
213             return null;
214         }
215         lldpPacket.setPortId(port.intValue());
216         ethPacket.setSourceMACAddress(SRC_MAC);
217         return new DefaultOutboundPacket(device.id(),
218                                          builder().setOutput(portNumber(port)).build(),
219                                          ByteBuffer.wrap(ethPacket.serialize()));
220     }
221
222     /**
223      * Creates packet_out BDDP for specified output port.
224      *
225      * @param port the port
226      * @return Packet_out message with LLDP data
227      */
228     private OutboundPacket createOutBoundBDDP(Long port) {
229         if (port == null) {
230             return null;
231         }
232         lldpPacket.setPortId(port.intValue());
233         bddpEth.setSourceMACAddress(SRC_MAC);
234         return new DefaultOutboundPacket(device.id(),
235                                          builder().setOutput(portNumber(port)).build(),
236                                          ByteBuffer.wrap(bddpEth.serialize()));
237     }
238
239     private void sendProbes(Long portNumber) {
240         log.trace("Sending probes out to {}@{}", portNumber, device.id());
241         OutboundPacket pkt = createOutBoundLLDP(portNumber);
242         context.packetService().emit(pkt);
243         if (context.useBDDP()) {
244             OutboundPacket bpkt = createOutBoundBDDP(portNumber);
245             context.packetService().emit(bpkt);
246         }
247     }
248
249     boolean containsPort(long portNumber) {
250         return ports.contains(portNumber);
251     }
252
253 }