blob: 5f4869dcdf68ea912d122440cf25526f16309589 [file] [log] [blame]
HIGUCHI Yutaea60e5f2013-06-12 11:10:21 -07001package net.onrc.onos.ofcontroller.bgproute;
pingping-lina2cbfad2013-03-07 08:39:21 +08002
Jonathan Hartd1f23252013-06-13 15:17:05 +12003import java.io.File;
Jonathan Harte7e1c6e2013-06-04 20:50:23 -07004import java.io.IOException;
5import java.net.InetAddress;
Jonathan Hart61ba9372013-05-19 20:10:29 -07006import java.net.UnknownHostException;
pingping-lina2cbfad2013-03-07 08:39:21 +08007import java.util.ArrayList;
Jonathan Hart61ba9372013-05-19 20:10:29 -07008import java.util.Collection;
pingping-lina2cbfad2013-03-07 08:39:21 +08009import java.util.HashMap;
Jonathan Hart98957bf2013-07-01 14:49:24 +120010import java.util.Iterator;
Jonathan Harte7e1c6e2013-06-04 20:50:23 -070011import java.util.List;
Jonathan Hart61ba9372013-05-19 20:10:29 -070012import java.util.Map;
Jonathan Hart4dfc3652013-08-02 20:22:36 +120013import java.util.Set;
Jonathan Hart8b9349e2013-07-26 15:55:28 +120014import java.util.concurrent.BlockingQueue;
15import java.util.concurrent.ExecutorService;
Jonathan Hart98957bf2013-07-01 14:49:24 +120016import java.util.concurrent.Executors;
Jonathan Hart8b9349e2013-07-26 15:55:28 +120017import java.util.concurrent.LinkedBlockingQueue;
Jonathan Hart98957bf2013-07-01 14:49:24 +120018import java.util.concurrent.ScheduledExecutorService;
19import java.util.concurrent.TimeUnit;
pingping-lina2cbfad2013-03-07 08:39:21 +080020
Jonathan Hart61ba9372013-05-19 20:10:29 -070021import net.floodlightcontroller.core.IFloodlightProviderService;
Jonathan Harte7e1c6e2013-06-04 20:50:23 -070022import net.floodlightcontroller.core.IOFSwitch;
Jonathan Hart1236a9b2013-06-18 22:10:05 +120023import net.floodlightcontroller.core.IOFSwitchListener;
pingping-lina2cbfad2013-03-07 08:39:21 +080024import net.floodlightcontroller.core.module.FloodlightModuleContext;
25import net.floodlightcontroller.core.module.FloodlightModuleException;
26import net.floodlightcontroller.core.module.IFloodlightModule;
27import net.floodlightcontroller.core.module.IFloodlightService;
Jonathan Hart98957bf2013-07-01 14:49:24 +120028import net.floodlightcontroller.core.util.SingletonTask;
Jonathan Harte7e1c6e2013-06-04 20:50:23 -070029import net.floodlightcontroller.devicemanager.IDeviceService;
30import net.floodlightcontroller.packet.Ethernet;
Jonathan Hart832a7cb2013-06-24 11:25:35 +120031import net.floodlightcontroller.packet.IPv4;
pingping-lina2cbfad2013-03-07 08:39:21 +080032import net.floodlightcontroller.restserver.IRestApiService;
Jonathan Hart98957bf2013-07-01 14:49:24 +120033import net.floodlightcontroller.routing.Link;
pingping-lina2cbfad2013-03-07 08:39:21 +080034import net.floodlightcontroller.topology.ITopologyListener;
35import net.floodlightcontroller.topology.ITopologyService;
Jonathan Hart4dfc3652013-08-02 20:22:36 +120036import net.floodlightcontroller.util.MACAddress;
Jonathan Hart0ee0f022013-08-03 22:21:54 +120037import net.onrc.onos.ofcontroller.bgproute.RibUpdate.Operation;
Jonathan Hart98957bf2013-07-01 14:49:24 +120038import net.onrc.onos.ofcontroller.core.INetMapTopologyService.ITopoLinkService;
HIGUCHI Yuta20514902013-06-12 11:24:16 -070039import net.onrc.onos.ofcontroller.core.INetMapTopologyService.ITopoRouteService;
Jonathan Hart98957bf2013-07-01 14:49:24 +120040import net.onrc.onos.ofcontroller.core.internal.TopoLinkServiceImpl;
HIGUCHI Yutaa56fbde2013-06-17 14:26:05 -070041import net.onrc.onos.ofcontroller.linkdiscovery.ILinkDiscovery;
42import net.onrc.onos.ofcontroller.linkdiscovery.ILinkDiscovery.LDUpdate;
Jonathan Hart4dfc3652013-08-02 20:22:36 +120043import net.onrc.onos.ofcontroller.proxyarp.IArpRequester;
Jonathan Hartc7ca35d2013-06-25 20:54:25 +120044import net.onrc.onos.ofcontroller.proxyarp.ProxyArpManager;
Pavlin Radoslavovddd01ba2013-07-03 15:40:44 -070045import net.onrc.onos.ofcontroller.routing.TopoRouteService;
HIGUCHI Yuta356086e2013-06-12 15:21:19 -070046import net.onrc.onos.ofcontroller.util.DataPath;
Jonathan Hart832a7cb2013-06-24 11:25:35 +120047import net.onrc.onos.ofcontroller.util.Dpid;
HIGUCHI Yuta356086e2013-06-12 15:21:19 -070048import net.onrc.onos.ofcontroller.util.FlowEntry;
HIGUCHI Yuta356086e2013-06-12 15:21:19 -070049import net.onrc.onos.ofcontroller.util.Port;
50import net.onrc.onos.ofcontroller.util.SwitchPort;
pingping-line2a09ca2013-03-23 09:33:58 +080051import net.sf.json.JSONArray;
52import net.sf.json.JSONObject;
53import net.sf.json.JSONSerializer;
pingping-lina2cbfad2013-03-07 08:39:21 +080054
Jonathan Hartd1f23252013-06-13 15:17:05 +120055import org.codehaus.jackson.JsonParseException;
56import org.codehaus.jackson.map.JsonMappingException;
57import org.codehaus.jackson.map.ObjectMapper;
Jonathan Harte7e1c6e2013-06-04 20:50:23 -070058import org.openflow.protocol.OFFlowMod;
59import org.openflow.protocol.OFMatch;
60import org.openflow.protocol.OFMessage;
61import org.openflow.protocol.OFPacketOut;
Jonathan Hart9575cb62013-07-05 13:43:49 +120062import org.openflow.protocol.OFPort;
Jonathan Harte7e1c6e2013-06-04 20:50:23 -070063import org.openflow.protocol.OFType;
64import org.openflow.protocol.action.OFAction;
65import org.openflow.protocol.action.OFActionDataLayerDestination;
66import org.openflow.protocol.action.OFActionOutput;
Jonathan Hart1236a9b2013-06-18 22:10:05 +120067import org.openflow.util.HexString;
pingping-lina2cbfad2013-03-07 08:39:21 +080068import org.slf4j.Logger;
69import org.slf4j.LoggerFactory;
70
Jonathan Hart4dfc3652013-08-02 20:22:36 +120071import com.google.common.collect.HashMultimap;
Jonathan Hart0ee0f022013-08-03 22:21:54 +120072import com.google.common.collect.Multimap;
Jonathan Hart4dfc3652013-08-02 20:22:36 +120073import com.google.common.collect.Multimaps;
74import com.google.common.collect.SetMultimap;
Jonathan Hart8b9349e2013-07-26 15:55:28 +120075import com.google.common.util.concurrent.ThreadFactoryBuilder;
76
Jonathan Hart1236a9b2013-06-18 22:10:05 +120077public class BgpRoute implements IFloodlightModule, IBgpRouteService,
Jonathan Hart4dfc3652013-08-02 20:22:36 +120078 ITopologyListener, IOFSwitchListener,
79 IArpRequester {
pingping-lina2cbfad2013-03-07 08:39:21 +080080
81 protected static Logger log = LoggerFactory.getLogger(BgpRoute.class);
82
83 protected IFloodlightProviderService floodlightProvider;
84 protected ITopologyService topology;
Jonathan Harte7e1c6e2013-06-04 20:50:23 -070085 protected ITopoRouteService topoRouteService;
86 protected IDeviceService devices;
87 protected IRestApiService restApi;
88
Jonathan Hartc7ca35d2013-06-25 20:54:25 +120089 protected ProxyArpManager proxyArp;
90
pingping-lina2cbfad2013-03-07 08:39:21 +080091 protected static Ptree ptree;
Jonathan Hart8b9349e2013-07-26 15:55:28 +120092 protected BlockingQueue<RibUpdate> ribUpdates;
93
Jonathan Hart61ba9372013-05-19 20:10:29 -070094 protected String bgpdRestIp;
95 protected String routerId;
Jonathan Hart9575cb62013-07-05 13:43:49 +120096 protected String configFilename = "config.json";
Jonathan Harte7e1c6e2013-06-04 20:50:23 -070097
98 //We need to identify our flows somehow. But like it says in LearningSwitch.java,
99 //the controller/OS should hand out cookie IDs to prevent conflicts.
100 protected final long APP_COOKIE = 0xa0000000000000L;
101 //Cookie for flows that do L2 forwarding within SDN domain to egress routers
102 protected final long L2_FWD_COOKIE = APP_COOKIE + 1;
103 //Cookie for flows in ingress switches that rewrite the MAC address
104 protected final long MAC_RW_COOKIE = APP_COOKIE + 2;
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200105 //Cookie for flows that setup BGP paths
106 protected final long BGP_COOKIE = APP_COOKIE + 3;
Jonathan Hart50a8d1e2013-06-06 16:00:47 +1200107 //Forwarding uses priority 0, and the mac rewrite entries in ingress switches
108 //need to be higher priority than this otherwise the rewrite may not get done
109 protected final short SDNIP_PRIORITY = 10;
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700110
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200111 protected final short BGP_PORT = 179;
112
Jonathan Hart98957bf2013-07-01 14:49:24 +1200113 protected final int TOPO_DETECTION_WAIT = 2; //seconds
114
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200115 //Configuration stuff
Jonathan Hart1236a9b2013-06-18 22:10:05 +1200116 protected List<String> switches;
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200117 protected Map<String, Interface> interfaces;
Jonathan Hartc824ad02013-07-03 15:58:45 +1200118 protected Map<InetAddress, BgpPeer> bgpPeers;
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200119 protected SwitchPort bgpdAttachmentPoint;
Jonathan Hart1236a9b2013-06-18 22:10:05 +1200120
121 //True when all switches have connected
122 protected volatile boolean switchesConnected = false;
123 //True when we have a full mesh of shortest paths between gateways
124 protected volatile boolean topologyReady = false;
Jonathan Hart98957bf2013-07-01 14:49:24 +1200125
Jonathan Hart98957bf2013-07-01 14:49:24 +1200126 protected ArrayList<LDUpdate> linkUpdates;
127 protected SingletonTask topologyChangeDetectorTask;
128
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200129 //protected HashMap<InetAddress, RibUpdate> prefixesWaitingOnArp;
130 //protected HashMap<InetAddress, PathUpdate> pathsWaitingOnArp;
131 protected SetMultimap<InetAddress, RibUpdate> prefixesWaitingOnArp;
132 protected SetMultimap<InetAddress, PathUpdate> pathsWaitingOnArp;
133
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200134 protected Multimap<Prefix, PushedFlowMod> pushedFlows;
135
136 private class PushedFlowMod {
137 private long dpid;
138 private OFFlowMod flowMod;
139
140 public PushedFlowMod(long dpid, OFFlowMod flowMod) {
141 this.dpid = dpid;
142 this.flowMod = flowMod;
143 }
144
145 public long getDpid() {
146 return dpid;
147 }
148
149 public OFFlowMod getFlowMod() {
150 return flowMod;
151 }
152 }
153
Jonathan Hart98957bf2013-07-01 14:49:24 +1200154 protected class TopologyChangeDetector implements Runnable {
155 @Override
156 public void run() {
157 log.debug("Running topology change detection task");
158 synchronized (linkUpdates) {
Jonathan Hartc824ad02013-07-03 15:58:45 +1200159 //This is the model the REST API uses to retrieve network graph info
Jonathan Hart98957bf2013-07-01 14:49:24 +1200160 ITopoLinkService topoLinkService = new TopoLinkServiceImpl();
161
162 List<Link> activeLinks = topoLinkService.getActiveLinks();
Jonathan Hart98957bf2013-07-01 14:49:24 +1200163
164 Iterator<LDUpdate> it = linkUpdates.iterator();
165 while (it.hasNext()){
166 LDUpdate ldu = it.next();
167 Link l = new Link(ldu.getSrc(), ldu.getSrcPort(),
168 ldu.getDst(), ldu.getDstPort());
169
170 if (activeLinks.contains(l)){
171 log.debug("Not found: {}", l);
172 it.remove();
173 }
174 }
175 }
176
177 if (linkUpdates.isEmpty()){
178 //All updates have been seen in network map.
179 //We can check if topology is ready
Jonathan Hart8b9349e2013-07-26 15:55:28 +1200180 log.debug("No known changes outstanding. Checking topology now");
Jonathan Hart98957bf2013-07-01 14:49:24 +1200181 checkStatus();
182 }
183 else {
184 //We know of some link updates that haven't propagated to the database yet
Jonathan Hart8b9349e2013-07-26 15:55:28 +1200185 log.debug("Some changes not found in network map - {} links missing", linkUpdates.size());
Jonathan Hart98957bf2013-07-01 14:49:24 +1200186 topologyChangeDetectorTask.reschedule(TOPO_DETECTION_WAIT, TimeUnit.SECONDS);
187 }
188 }
189 }
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700190
Jonathan Hartd1f23252013-06-13 15:17:05 +1200191 private void readGatewaysConfiguration(String gatewaysFilename){
192 File gatewaysFile = new File(gatewaysFilename);
193 ObjectMapper mapper = new ObjectMapper();
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700194
Jonathan Hartd1f23252013-06-13 15:17:05 +1200195 try {
Jonathan Hart1236a9b2013-06-18 22:10:05 +1200196 Configuration config = mapper.readValue(gatewaysFile, Configuration.class);
197
Jonathan Hart1236a9b2013-06-18 22:10:05 +1200198 switches = config.getSwitches();
Jonathan Hart9575cb62013-07-05 13:43:49 +1200199 interfaces = new HashMap<String, Interface>();
200 for (Interface intf : config.getInterfaces()){
201 interfaces.put(intf.getName(), intf);
202 }
Jonathan Hartc824ad02013-07-03 15:58:45 +1200203 bgpPeers = new HashMap<InetAddress, BgpPeer>();
204 for (BgpPeer peer : config.getPeers()){
205 bgpPeers.put(peer.getIpAddress(), peer);
206 }
Jonathan Hart1236a9b2013-06-18 22:10:05 +1200207
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200208 bgpdAttachmentPoint = new SwitchPort(
209 new Dpid(config.getBgpdAttachmentDpid()),
210 new Port(config.getBgpdAttachmentPort()));
Jonathan Hart1236a9b2013-06-18 22:10:05 +1200211
Jonathan Hartd1f23252013-06-13 15:17:05 +1200212 } catch (JsonParseException e) {
213 log.error("Error in JSON file", e);
214 System.exit(1);
215 } catch (JsonMappingException e) {
216 log.error("Error in JSON file", e);
217 System.exit(1);
218 } catch (IOException e) {
219 log.error("Error reading JSON file", e);
220 System.exit(1);
221 }
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700222 }
pingping-lina2cbfad2013-03-07 08:39:21 +0800223
224 @Override
225 public Collection<Class<? extends IFloodlightService>> getModuleServices() {
Jonathan Hart61ba9372013-05-19 20:10:29 -0700226 Collection<Class<? extends IFloodlightService>> l
227 = new ArrayList<Class<? extends IFloodlightService>>();
pingping-lina2cbfad2013-03-07 08:39:21 +0800228 l.add(IBgpRouteService.class);
229 return l;
230 }
231
232 @Override
233 public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() {
Jonathan Hart61ba9372013-05-19 20:10:29 -0700234 Map<Class<? extends IFloodlightService>, IFloodlightService> m
235 = new HashMap<Class<? extends IFloodlightService>, IFloodlightService>();
pingping-line2a09ca2013-03-23 09:33:58 +0800236 m.put(IBgpRouteService.class, this);
pingping-lina2cbfad2013-03-07 08:39:21 +0800237 return m;
238 }
239
pingping-lina2cbfad2013-03-07 08:39:21 +0800240 @Override
241 public Collection<Class<? extends IFloodlightService>> getModuleDependencies() {
Jonathan Hart61ba9372013-05-19 20:10:29 -0700242 Collection<Class<? extends IFloodlightService>> l
243 = new ArrayList<Class<? extends IFloodlightService>>();
pingping-lina2cbfad2013-03-07 08:39:21 +0800244 l.add(IFloodlightProviderService.class);
245 l.add(ITopologyService.class);
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700246 l.add(IDeviceService.class);
247 l.add(IRestApiService.class);
pingping-lina2cbfad2013-03-07 08:39:21 +0800248 return l;
249 }
250
251 @Override
252 public void init(FloodlightModuleContext context)
253 throws FloodlightModuleException {
254
255 ptree = new Ptree(32);
Jonathan Hart8b9349e2013-07-26 15:55:28 +1200256
257 ribUpdates = new LinkedBlockingQueue<RibUpdate>();
Jonathan Hartc824ad02013-07-03 15:58:45 +1200258
pingping-lina2cbfad2013-03-07 08:39:21 +0800259 // Register floodlight provider and REST handler.
260 floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class);
pingping-lina2cbfad2013-03-07 08:39:21 +0800261 topology = context.getServiceImpl(ITopologyService.class);
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700262 devices = context.getServiceImpl(IDeviceService.class);
Jonathan Hartc7ca35d2013-06-25 20:54:25 +1200263 restApi = context.getServiceImpl(IRestApiService.class);
264
265 //TODO We'll initialise this here for now, but it should really be done as
266 //part of the controller core
Jonathan Hart6261dcd2013-07-22 17:58:35 +1200267 proxyArp = new ProxyArpManager(floodlightProvider, topology, devices);
pingping-lina2cbfad2013-03-07 08:39:21 +0800268
Jonathan Hart98957bf2013-07-01 14:49:24 +1200269 linkUpdates = new ArrayList<LDUpdate>();
270 ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
271 topologyChangeDetectorTask = new SingletonTask(executor, new TopologyChangeDetector());
Pavlin Radoslavovddd01ba2013-07-03 15:40:44 -0700272
273 topoRouteService = new TopoRouteService("");
Jonathan Hart98957bf2013-07-01 14:49:24 +1200274
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200275 pathsWaitingOnArp = Multimaps.synchronizedSetMultimap(
276 HashMultimap.<InetAddress, PathUpdate>create());
277 prefixesWaitingOnArp = Multimaps.synchronizedSetMultimap(
278 HashMultimap.<InetAddress, RibUpdate>create());
279
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200280 pushedFlows = HashMultimap.<Prefix, PushedFlowMod>create();
281
Jonathan Hart61ba9372013-05-19 20:10:29 -0700282 //Read in config values
283 bgpdRestIp = context.getConfigParams(this).get("BgpdRestIp");
284 if (bgpdRestIp == null){
285 log.error("BgpdRestIp property not found in config file");
286 System.exit(1);
287 }
288 else {
289 log.info("BgpdRestIp set to {}", bgpdRestIp);
290 }
291
292 routerId = context.getConfigParams(this).get("RouterId");
293 if (routerId == null){
294 log.error("RouterId property not found in config file");
295 System.exit(1);
296 }
297 else {
298 log.info("RouterId set to {}", routerId);
299 }
Jonathan Hartd1f23252013-06-13 15:17:05 +1200300
Jonathan Hart9575cb62013-07-05 13:43:49 +1200301 String configFilenameParameter = context.getConfigParams(this).get("configfile");
302 if (configFilenameParameter != null){
303 configFilename = configFilenameParameter;
304 }
305 log.debug("Config file set to {}", configFilename);
306
307 readGatewaysConfiguration(configFilename);
pingping-lina2cbfad2013-03-07 08:39:21 +0800308 // Test.
309 //test();
310 }
311
312 public Ptree getPtree() {
313 return ptree;
314 }
Jonathan Hart61ba9372013-05-19 20:10:29 -0700315
316 public void clearPtree() {
317 //ptree = null;
318 ptree = new Ptree(32);
pingping-line2a09ca2013-03-23 09:33:58 +0800319 }
Jonathan Hart61ba9372013-05-19 20:10:29 -0700320
pingping-line2a09ca2013-03-23 09:33:58 +0800321 public String getBGPdRestIp() {
Jonathan Hart61ba9372013-05-19 20:10:29 -0700322 return bgpdRestIp;
pingping-line2a09ca2013-03-23 09:33:58 +0800323 }
Jonathan Hart61ba9372013-05-19 20:10:29 -0700324
pingping-line2a09ca2013-03-23 09:33:58 +0800325 public String getRouterId() {
Jonathan Hart61ba9372013-05-19 20:10:29 -0700326 return routerId;
pingping-line2a09ca2013-03-23 09:33:58 +0800327 }
pingping-lina2cbfad2013-03-07 08:39:21 +0800328
329 // Return nexthop address as byte array.
330 public Rib lookupRib(byte[] dest) {
331 if (ptree == null) {
332 log.debug("lookupRib: ptree null");
333 return null;
334 }
335
336 PtreeNode node = ptree.match(dest, 32);
337 if (node == null) {
338 log.debug("lookupRib: ptree node null");
339 return null;
340 }
Jonathan Hart61ba9372013-05-19 20:10:29 -0700341
pingping-lina2cbfad2013-03-07 08:39:21 +0800342 if (node.rib == null) {
343 log.debug("lookupRib: ptree rib null");
344 return null;
345 }
Jonathan Hart61ba9372013-05-19 20:10:29 -0700346
pingping-lina2cbfad2013-03-07 08:39:21 +0800347 ptree.delReference(node);
348
349 return node.rib;
350 }
351
Jonathan Hart61ba9372013-05-19 20:10:29 -0700352 //TODO looks like this should be a unit test
pingping-lina2cbfad2013-03-07 08:39:21 +0800353 @SuppressWarnings("unused")
Jonathan Hart61ba9372013-05-19 20:10:29 -0700354 private void test() throws UnknownHostException {
pingping-lina2cbfad2013-03-07 08:39:21 +0800355 System.out.println("Here it is");
356 Prefix p = new Prefix("128.0.0.0", 8);
357 Prefix q = new Prefix("8.0.0.0", 8);
358 Prefix r = new Prefix("10.0.0.0", 24);
359 Prefix a = new Prefix("10.0.0.1", 32);
360
Jonathan Hartd1b9d872013-07-23 12:17:21 +1200361 ptree.acquire(p.getAddress(), p.getPrefixLength());
362 ptree.acquire(q.getAddress(), q.getPrefixLength());
363 ptree.acquire(r.getAddress(), r.getPrefixLength());
pingping-lina2cbfad2013-03-07 08:39:21 +0800364
365 System.out.println("Traverse start");
366 for (PtreeNode node = ptree.begin(); node != null; node = ptree.next(node)) {
367 Prefix p_result = new Prefix(node.key, node.keyBits);
368 }
369
Jonathan Hartd1b9d872013-07-23 12:17:21 +1200370 PtreeNode n = ptree.match(a.getAddress(), a.getPrefixLength());
pingping-lina2cbfad2013-03-07 08:39:21 +0800371 if (n != null) {
372 System.out.println("Matched prefix for 10.0.0.1:");
373 Prefix x = new Prefix(n.key, n.keyBits);
374 ptree.delReference(n);
375 }
376
Jonathan Hartd1b9d872013-07-23 12:17:21 +1200377 n = ptree.lookup(p.getAddress(), p.getPrefixLength());
pingping-lina2cbfad2013-03-07 08:39:21 +0800378 if (n != null) {
379 ptree.delReference(n);
380 ptree.delReference(n);
381 }
382 System.out.println("Traverse start");
383 for (PtreeNode node = ptree.begin(); node != null; node = ptree.next(node)) {
384 Prefix p_result = new Prefix(node.key, node.keyBits);
385 }
386
Jonathan Hartd1b9d872013-07-23 12:17:21 +1200387 n = ptree.lookup(q.getAddress(), q.getPrefixLength());
pingping-lina2cbfad2013-03-07 08:39:21 +0800388 if (n != null) {
389 ptree.delReference(n);
390 ptree.delReference(n);
391 }
392 System.out.println("Traverse start");
393 for (PtreeNode node = ptree.begin(); node != null; node = ptree.next(node)) {
394 Prefix p_result = new Prefix(node.key, node.keyBits);
395 }
396
Jonathan Hartd1b9d872013-07-23 12:17:21 +1200397 n = ptree.lookup(r.getAddress(), r.getPrefixLength());
pingping-lina2cbfad2013-03-07 08:39:21 +0800398 if (n != null) {
399 ptree.delReference(n);
400 ptree.delReference(n);
401 }
402 System.out.println("Traverse start");
403 for (PtreeNode node = ptree.begin(); node != null; node = ptree.next(node)) {
404 Prefix p_result = new Prefix(node.key, node.keyBits);
405 }
406
407 }
408
Jonathan Hart1236a9b2013-06-18 22:10:05 +1200409 private String getPrefixFromPtree(PtreeNode node){
410 InetAddress address = null;
411 try {
412 address = InetAddress.getByAddress(node.key);
413 } catch (UnknownHostException e1) {
414 //Should never happen is the reverse conversion has already been done
415 log.error("Malformed IP address");
416 return "";
417 }
418 return address.toString() + "/" + node.rib.masklen;
419 }
420
Jonathan Hart61ba9372013-05-19 20:10:29 -0700421 private void retrieveRib(){
422 String url = "http://" + bgpdRestIp + "/wm/bgp/" + routerId;
423 String response = RestClient.get(url);
424
425 if (response.equals("")){
426 return;
427 }
428
429 response = response.replaceAll("\"", "'");
430 JSONObject jsonObj = (JSONObject) JSONSerializer.toJSON(response);
431 JSONArray rib_json_array = jsonObj.getJSONArray("rib");
432 String router_id = jsonObj.getString("router-id");
433
434 int size = rib_json_array.size();
435
436 log.info("Retrived RIB of {} entries from BGPd", size);
437
438 for (int j = 0; j < size; j++) {
439 JSONObject second_json_object = rib_json_array.getJSONObject(j);
440 String prefix = second_json_object.getString("prefix");
441 String nexthop = second_json_object.getString("nexthop");
442
443 //insert each rib entry into the local rib;
444 String[] substring = prefix.split("/");
445 String prefix1 = substring[0];
446 String mask1 = substring[1];
447
448 Prefix p;
449 try {
450 p = new Prefix(prefix1, Integer.valueOf(mask1));
451 } catch (NumberFormatException e) {
452 log.warn("Wrong mask format in RIB JSON: {}", mask1);
453 continue;
454 } catch (UnknownHostException e1) {
455 log.warn("Wrong prefix format in RIB JSON: {}", prefix1);
456 continue;
457 }
458
Jonathan Hartd1b9d872013-07-23 12:17:21 +1200459 PtreeNode node = ptree.acquire(p.getAddress(), p.getPrefixLength());
460 Rib rib = new Rib(router_id, nexthop, p.getPrefixLength());
Jonathan Hart61ba9372013-05-19 20:10:29 -0700461
462 if (node.rib != null) {
463 node.rib = null;
464 ptree.delReference(node);
465 }
466
467 node.rib = rib;
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700468
Jonathan Hart50a8d1e2013-06-06 16:00:47 +1200469 prefixAdded(node);
Jonathan Hart61ba9372013-05-19 20:10:29 -0700470 }
471 }
472
Jonathan Hart8b9349e2013-07-26 15:55:28 +1200473 @Override
474 public void newRibUpdate(RibUpdate update) {
475 ribUpdates.add(update);
476 }
477
478 //TODO temporary
479 public void wrapPrefixAdded(RibUpdate update) {
480 Prefix prefix = update.getPrefix();
481
482 PtreeNode node = ptree.acquire(prefix.getAddress(), prefix.getPrefixLength());
483
484 if (node.rib != null) {
485 node.rib = null;
486 ptree.delReference(node);
487 }
488 node.rib = update.getRibEntry();
489
490 prefixAdded(node);
491 }
492
493 //TODO temporary
494 public void wrapPrefixDeleted(RibUpdate update) {
495 Prefix prefix = update.getPrefix();
496
497 PtreeNode node = ptree.lookup(prefix.getAddress(), prefix.getPrefixLength());
498
499 /*
500 * Remove the flows from the switches before the rib is lost
501 * Theory: we could get a delete for a prefix not in the Ptree.
502 * This would result in a null node being returned. We could get a delete for
503 * a node that's not actually there, but is a aggregate node. This would result
504 * in a non-null node with a null rib. Only a non-null node with a non-null
505 * rib is an actual prefix in the Ptree.
506 */
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200507 //if (node != null && node.rib != null){
508 //prefixDeleted(node);
509 //}
Jonathan Hart8b9349e2013-07-26 15:55:28 +1200510
511 if (node != null && node.rib != null) {
512 if (update.getRibEntry().equals(node.rib)) {
513 node.rib = null;
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200514 ptree.delReference(node);
515
516 prefixDeleted(update);
Jonathan Hart8b9349e2013-07-26 15:55:28 +1200517 }
518 }
519 }
520
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200521 //TODO compatibility layer
Jonathan Hart50a8d1e2013-06-06 16:00:47 +1200522 public void prefixAdded(PtreeNode node) {
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200523 //String strPrefix = getPrefixFromPtree(node);
524
525
526 Prefix prefix = null;
527 try {
528 prefix = new Prefix(node.key, node.rib.masklen);
529 } catch (UnknownHostException e) {
530 log.error(" ", e);
531 }
532 /*try {
533 prefix = new Prefix(strPrefix, node.rib.masklen);
534 } catch (UnknownHostException e) {
535 log.error(" ", e);
536 }*/
537 /*log.debug(" hello {}", strPrefix.split("/")[0]);
538 try {
539 prefix = new Prefix(strPrefix.split("/")[0], node.rib.masklen);
540 } catch (NumberFormatException e) {
541 log.debug(" ", e);
542 } catch (UnknownHostException e) {
543 log.debug(" ", e);
544 }*/
545
546 RibUpdate update = new RibUpdate(Operation.UPDATE, prefix, node.rib);
547
548 prefixAdded(update);
549 }
550
551 public void prefixAdded(RibUpdate update) {
Jonathan Hart1236a9b2013-06-18 22:10:05 +1200552 if (!topologyReady){
553 return;
554 }
555
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200556 //TODO before we do anything, we have to check that the RIB entry is still in the
557 //Ptree because it could have been removed while we were waiting for ARP.
558 //I think we'll have to make prefixAdded and prefixDelete atomic as well
559 //to protect against the prefix getting deleted while where trying to add it
560
561 //String prefix = getPrefixFromPtree(node);
Jonathan Hart1236a9b2013-06-18 22:10:05 +1200562
Jonathan Hartc824ad02013-07-03 15:58:45 +1200563 log.debug("New prefix {} added, next hop {}, routerId {}",
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200564 new Object[] {update.getPrefix(), update.getRibEntry().nextHop.getHostAddress(),
565 update.getRibEntry().routerId.getHostAddress()});
Jonathan Hart1236a9b2013-06-18 22:10:05 +1200566
Jonathan Hartc824ad02013-07-03 15:58:45 +1200567 //TODO this is wrong, we shouldn't be dealing with BGP peers here.
Jonathan Hart6261dcd2013-07-22 17:58:35 +1200568 //We need to figure out where the device is attached and what its
Jonathan Hartc824ad02013-07-03 15:58:45 +1200569 //mac address is by learning.
570 //The next hop is not necessarily the peer, and the peer's attachment
571 //point is not necessarily the next hop's attachment point.
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200572 //BgpPeer peer = bgpPeers.get(node.rib.nextHop);
573 BgpPeer peer = bgpPeers.get(update.getRibEntry().nextHop);
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700574
Jonathan Hartc824ad02013-07-03 15:58:45 +1200575 if (peer == null){
576 //TODO local router isn't in peers list so this will get thrown
Jonathan Hart50a8d1e2013-06-06 16:00:47 +1200577 //Need to work out what to do about local prefixes with next hop 0.0.0.0.
Jonathan Hartc824ad02013-07-03 15:58:45 +1200578
579 //The other scenario is this is a route server route. In that
580 //case the next hop is not in our configuration
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200581 log.error("Couldn't find next hop router in router {} in config",
582 //node.rib.nextHop.toString());
583 update.getRibEntry().nextHop.getHostAddress());
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700584 return; //just quit out here? This is probably a configuration error
585 }
Jonathan Hartc824ad02013-07-03 15:58:45 +1200586
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200587 //Get MAC address for peer from the ARP module
588 //TODO separate out the 'ask for MAC' bit to another method
589 byte[] peerMacAddress = proxyArp.getMacAddress(peer.getIpAddress());
590 if (peerMacAddress == null) {
591 prefixesWaitingOnArp.put(peer.getIpAddress(), update);
592 proxyArp.sendArpRequest(peer.getIpAddress(), this, true);
593 return;
594 }
595
Jonathan Hartc824ad02013-07-03 15:58:45 +1200596 Interface peerInterface = interfaces.get(peer.getInterfaceName());
Jonathan Hart50a8d1e2013-06-06 16:00:47 +1200597
Jonathan Hartc824ad02013-07-03 15:58:45 +1200598 //Add a flow to rewrite mac for this prefix to all border switches
599 for (Interface srcInterface : interfaces.values()) {
600 if (srcInterface == peerInterface) {
601 //Don't push a flow for the switch where this peer is attached
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700602 continue;
603 }
Jonathan Hartc824ad02013-07-03 15:58:45 +1200604
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700605 DataPath shortestPath = topoRouteService.getShortestPath(
Jonathan Hartc824ad02013-07-03 15:58:45 +1200606 srcInterface.getSwitchPort(),
607 peerInterface.getSwitchPort());
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700608
609 if (shortestPath == null){
610 log.debug("Shortest path between {} and {} not found",
Jonathan Hartc824ad02013-07-03 15:58:45 +1200611 srcInterface.getSwitchPort(),
612 peerInterface.getSwitchPort());
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700613 return; // just quit here?
614 }
615
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700616 //Set up the flow mod
617 OFFlowMod fm =
618 (OFFlowMod) floodlightProvider.getOFMessageFactory()
619 .getMessage(OFType.FLOW_MOD);
620
621 fm.setIdleTimeout((short)0)
622 .setHardTimeout((short)0)
623 .setBufferId(OFPacketOut.BUFFER_ID_NONE)
624 .setCookie(MAC_RW_COOKIE)
625 .setCommand(OFFlowMod.OFPFC_ADD)
Jonathan Hart50a8d1e2013-06-06 16:00:47 +1200626 .setPriority(SDNIP_PRIORITY)
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700627 .setLengthU(OFFlowMod.MINIMUM_LENGTH
628 + OFActionDataLayerDestination.MINIMUM_LENGTH
629 + OFActionOutput.MINIMUM_LENGTH);
630
631 OFMatch match = new OFMatch();
632 match.setDataLayerType(Ethernet.TYPE_IPv4);
Jonathan Hart50a8d1e2013-06-06 16:00:47 +1200633 match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_TYPE);
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700634
Jonathan Hartc824ad02013-07-03 15:58:45 +1200635 //match.setDataLayerSource(ingressRouter.getRouterMac().toBytes());
636 //match.setDataLayerSource(peer.getMacAddress().toBytes());
637 //match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_SRC);
Jonathan Hart50a8d1e2013-06-06 16:00:47 +1200638
639 InetAddress address = null;
640 try {
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200641 //address = InetAddress.getByAddress(node.key);
642 address = InetAddress.getByAddress(update.getPrefix().getAddress());
Jonathan Hart50a8d1e2013-06-06 16:00:47 +1200643 } catch (UnknownHostException e1) {
644 //Should never happen is the reverse conversion has already been done
645 log.error("Malformed IP address");
646 return;
647 }
648
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200649 //match.setFromCIDR(address.getHostAddress() + "/" + node.rib.masklen, OFMatch.STR_NW_DST);
650 match.setFromCIDR(address.getHostAddress() + "/" +
651 update.getPrefix().getPrefixLength(), OFMatch.STR_NW_DST);
Jonathan Hart50a8d1e2013-06-06 16:00:47 +1200652 fm.setMatch(match);
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700653
654 //Set up MAC rewrite action
655 OFActionDataLayerDestination macRewriteAction = new OFActionDataLayerDestination();
Jonathan Hartc824ad02013-07-03 15:58:45 +1200656 //TODO use ARP module rather than configured mac addresses
657 //TODO the peer's mac address is not necessarily the next hop's...
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200658 //macRewriteAction.setDataLayerAddress(peer.getMacAddress().toBytes());
659 macRewriteAction.setDataLayerAddress(peerMacAddress);
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700660
661 //Set up output action
662 OFActionOutput outputAction = new OFActionOutput();
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200663 outputAction.setMaxLength((short)0xffff);
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700664
Jonathan Hart50a8d1e2013-06-06 16:00:47 +1200665 Port outputPort = shortestPath.flowEntries().get(0).outPort();
666 outputAction.setPort(outputPort.value());
667
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700668 List<OFAction> actions = new ArrayList<OFAction>();
669 actions.add(macRewriteAction);
670 actions.add(outputAction);
671 fm.setActions(actions);
672
673 //Write to switch
674 IOFSwitch sw = floodlightProvider.getSwitches()
Jonathan Hartc824ad02013-07-03 15:58:45 +1200675 .get(srcInterface.getDpid());
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700676
677 if (sw == null){
678 log.warn("Switch not found when pushing flow mod");
679 continue;
680 }
681
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200682 //TODO if prefix Added/Deleted are synchronized this shouldn't have to be
683 pushedFlows.put(update.getPrefix(), new PushedFlowMod(sw.getId(), fm));
684
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700685 List<OFMessage> msglist = new ArrayList<OFMessage>();
686 msglist.add(fm);
687 try {
688 sw.write(msglist, null);
689 sw.flush();
690 } catch (IOException e) {
691 log.error("Failure writing flow mod", e);
692 }
693 }
694 }
695
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200696 //TODO test next-hop changes
697 //TODO delete should match add
698
699 public void prefixDeleted(RibUpdate update) {
700 if (!topologyReady) {
701 return;
702 }
703
704 log.debug("In prefixDeleted for {}", update.getPrefix());
705
706 Collection<PushedFlowMod> pushedFlowMods
707 = pushedFlows.removeAll(update.getPrefix());
708
709 for (PushedFlowMod pfm : pushedFlowMods) {
710 log.debug("Pushing a DELETE flow mod to {}, matches prefix {} with mac-rewrite {}",
711 new Object[] {HexString.toHexString(pfm.getDpid()),
712 pfm.getFlowMod().getMatch().getNetworkDestination() +
713 pfm.getFlowMod().getMatch().getNetworkDestinationMaskLen(),
714 HexString.toHexString(((OFActionDataLayerDestination)pfm.getFlowMod().getActions().get(0))
715 .getDataLayerAddress())});
716
717 OFFlowMod fm = pfm.getFlowMod();
718
719 fm.setCommand(OFFlowMod.OFPFC_DELETE)
720 .setLengthU(OFFlowMod.MINIMUM_LENGTH);
721
722 fm.getActions().clear();
723
724 IOFSwitch sw = floodlightProvider.getSwitches().get(pfm.getDpid());
725 if (sw == null) {
726 log.warn("Switch not found when pushing delete flow mod");
727 continue;
728 }
729
730 try {
731 sw.write(fm, null);
732 sw.flush();
733 } catch (IOException e) {
734 log.error("Failure writing flow mod", e);
735 }
736 }
737 }
738
739 /*public void prefixDeleted(PtreeNode node) {
Jonathan Hart1236a9b2013-06-18 22:10:05 +1200740 if (!topologyReady) {
741 return;
742 }
Jonathan Hart50a8d1e2013-06-06 16:00:47 +1200743
Jonathan Hart1236a9b2013-06-18 22:10:05 +1200744 String prefix = getPrefixFromPtree(node);
745
746 log.debug("Prefix {} deleted, next hop {}",
747 prefix, node.rib.nextHop.toString());
748
749 //Remove MAC rewriting flows from other border switches
Jonathan Hartc824ad02013-07-03 15:58:45 +1200750 BgpPeer peer = bgpPeers.get(node.rib.nextHop);
751 if (peer == null){
752 //either a router server route or local route. Can't handle right now
753 return;
754 }
Jonathan Hart1236a9b2013-06-18 22:10:05 +1200755
Jonathan Hartc824ad02013-07-03 15:58:45 +1200756 Interface peerInterface = interfaces.get(peer.getInterfaceName());
757
758 for (Interface srcInterface : interfaces.values()) {
759 if (srcInterface == peerInterface) {
Jonathan Hart1236a9b2013-06-18 22:10:05 +1200760 continue;
761 }
762
763 //Set up the flow mod
764 OFFlowMod fm =
765 (OFFlowMod) floodlightProvider.getOFMessageFactory()
766 .getMessage(OFType.FLOW_MOD);
767
768 fm.setIdleTimeout((short)0)
769 .setHardTimeout((short)0)
770 .setBufferId(OFPacketOut.BUFFER_ID_NONE)
771 .setCookie(MAC_RW_COOKIE)
772 .setCommand(OFFlowMod.OFPFC_DELETE)
Jonathan Hart9575cb62013-07-05 13:43:49 +1200773 .setOutPort(OFPort.OFPP_NONE)
Jonathan Hart1236a9b2013-06-18 22:10:05 +1200774 .setPriority(SDNIP_PRIORITY)
775 .setLengthU(OFFlowMod.MINIMUM_LENGTH);
776 //+ OFActionDataLayerDestination.MINIMUM_LENGTH
777 //+ OFActionOutput.MINIMUM_LENGTH);
778
779 OFMatch match = new OFMatch();
780 match.setDataLayerType(Ethernet.TYPE_IPv4);
781 match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_TYPE);
782
Jonathan Hartc824ad02013-07-03 15:58:45 +1200783 //match.setDataLayerSource(ingressRouter.getRouterMac().toBytes());
784 //match.setDataLayerSource(peer.getMacAddress().toBytes());
785 //match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_SRC);
Jonathan Hart1236a9b2013-06-18 22:10:05 +1200786
Jonathan Hart1236a9b2013-06-18 22:10:05 +1200787 InetAddress address = null;
788 try {
789 address = InetAddress.getByAddress(node.key);
790 } catch (UnknownHostException e1) {
791 //Should never happen is the reverse conversion has already been done
792 log.error("Malformed IP address");
793 return;
794 }
795
796 match.setFromCIDR(address.getHostAddress() + "/" + node.rib.masklen, OFMatch.STR_NW_DST);
797 fm.setMatch(match);
798
799 //Write to switch
800 IOFSwitch sw = floodlightProvider.getSwitches()
Jonathan Hartc824ad02013-07-03 15:58:45 +1200801 .get(srcInterface.getDpid());
Jonathan Hart1236a9b2013-06-18 22:10:05 +1200802
803 if (sw == null){
804 log.warn("Switch not found when pushing flow mod");
805 continue;
806 }
807
808 List<OFMessage> msglist = new ArrayList<OFMessage>();
809 msglist.add(fm);
810 try {
811 sw.write(msglist, null);
812 sw.flush();
813 } catch (IOException e) {
814 log.error("Failure writing flow mod", e);
815 }
816 }
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200817 }*/
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700818
819 /*
820 * On startup we need to calculate a full mesh of paths between all gateway
821 * switches
822 */
Jonathan Hart1236a9b2013-06-18 22:10:05 +1200823 private void setupFullMesh(){
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700824 //For each border router, calculate and install a path from every other
825 //border switch to said border router. However, don't install the entry
826 //in to the first hop switch, as we need to install an entry to rewrite
827 //for each prefix received. This will be done later when prefixes have
828 //actually been received.
829
Jonathan Hartc824ad02013-07-03 15:58:45 +1200830 for (BgpPeer peer : bgpPeers.values()) {
831 Interface peerInterface = interfaces.get(peer.getInterfaceName());
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200832
833 //See if we know the MAC address of the peer. If not we can't
834 //do anything until we learn it
835 byte[] mac = proxyArp.getMacAddress(peer.getIpAddress());
836 if (mac == null) {
837 log.debug("Don't know MAC for {}", peer.getIpAddress().getHostAddress());
838 //Put in the pending paths list first
839 pathsWaitingOnArp.put(peer.getIpAddress(),
840 new PathUpdate(peerInterface, peer.getIpAddress()));
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700841
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200842 proxyArp.sendArpRequest(peer.getIpAddress(), this, true);
843 continue;
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700844 }
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200845
846 //If we know the MAC, lets go ahead and push the paths to this peer
847 calculateAndPushPath(peerInterface, MACAddress.valueOf(mac));
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700848 }
849 }
850
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200851 private void calculateAndPushPath(Interface dstInterface, MACAddress dstMacAddress) {
852 for (Interface srcInterface : interfaces.values()) {
853 if (dstInterface.equals(srcInterface.getName())){
854 continue;
855 }
856
857 DataPath shortestPath = topoRouteService.getShortestPath(
858 srcInterface.getSwitchPort(), dstInterface.getSwitchPort());
859
860 if (shortestPath == null){
861 log.debug("Shortest path between {} and {} not found",
862 srcInterface.getSwitchPort(), dstInterface.getSwitchPort());
863 return; // just quit here?
864 }
865
866 //install flows
867 installPath(shortestPath.flowEntries(), dstMacAddress);
868 }
869 }
870
871 private void installPath(List<FlowEntry> flowEntries, MACAddress dstMacAddress){
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700872 //Set up the flow mod
873 OFFlowMod fm =
874 (OFFlowMod) floodlightProvider.getOFMessageFactory()
875 .getMessage(OFType.FLOW_MOD);
876
877 OFActionOutput action = new OFActionOutput();
878 action.setMaxLength((short)0xffff);
879 List<OFAction> actions = new ArrayList<OFAction>();
880 actions.add(action);
881
882 fm.setIdleTimeout((short)0)
883 .setHardTimeout((short)0)
884 .setBufferId(OFPacketOut.BUFFER_ID_NONE)
885 .setCookie(L2_FWD_COOKIE)
886 .setCommand(OFFlowMod.OFPFC_ADD)
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700887 .setActions(actions)
888 .setLengthU(OFFlowMod.MINIMUM_LENGTH+OFActionOutput.MINIMUM_LENGTH);
889
890 //Don't push the first flow entry. We need to push entries in the
891 //first switch based on IP prefix which we don't know yet.
892 for (int i = 1; i < flowEntries.size(); i++){
893 FlowEntry flowEntry = flowEntries.get(i);
894
895 OFMatch match = new OFMatch();
Jonathan Hartc824ad02013-07-03 15:58:45 +1200896 //TODO Again using MAC address from configuration
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200897 match.setDataLayerDestination(dstMacAddress.toBytes());
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700898 match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_DST);
899 ((OFActionOutput) fm.getActions().get(0)).setPort(flowEntry.outPort().value());
900
901 fm.setMatch(match);
902
903 IOFSwitch sw = floodlightProvider.getSwitches().get(flowEntry.dpid().value());
904
905 if (sw == null){
906 log.warn("Switch not found when pushing flow mod");
907 continue;
908 }
909
910 List<OFMessage> msglist = new ArrayList<OFMessage>();
911 msglist.add(fm);
912 try {
913 sw.write(msglist, null);
914 sw.flush();
915 } catch (IOException e) {
916 log.error("Failure writing flow mod", e);
917 }
918
919 try {
920 fm = fm.clone();
921 } catch (CloneNotSupportedException e1) {
922 log.error("Failure cloning flow mod", e1);
923 }
924 }
925 }
926
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200927 private void setupBgpPaths(){
Jonathan Hartc824ad02013-07-03 15:58:45 +1200928 for (BgpPeer bgpPeer : bgpPeers.values()){
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200929 Interface peerInterface = interfaces.get(bgpPeer.getInterfaceName());
930
931 DataPath path = topoRouteService.getShortestPath(
932 peerInterface.getSwitchPort(), bgpdAttachmentPoint);
933
934 if (path == null){
935 log.debug("Unable to compute path for BGP traffic for {}",
936 bgpPeer.getIpAddress());
937 continue;
938 }
939
940 //Set up the flow mod
941 OFFlowMod fm =
942 (OFFlowMod) floodlightProvider.getOFMessageFactory()
943 .getMessage(OFType.FLOW_MOD);
944
945 OFActionOutput action = new OFActionOutput();
946 action.setMaxLength((short)0xffff);
947 List<OFAction> actions = new ArrayList<OFAction>();
948 actions.add(action);
949
950 fm.setIdleTimeout((short)0)
951 .setHardTimeout((short)0)
952 .setBufferId(OFPacketOut.BUFFER_ID_NONE)
953 .setCookie(BGP_COOKIE)
954 .setCommand(OFFlowMod.OFPFC_ADD)
955 .setPriority(SDNIP_PRIORITY)
956 .setActions(actions)
957 .setLengthU(OFFlowMod.MINIMUM_LENGTH+OFActionOutput.MINIMUM_LENGTH);
958
959 //Forward = gateway -> bgpd, reverse = bgpd -> gateway
960 OFMatch forwardMatchSrc = new OFMatch();
961
962
963 String interfaceCidrAddress = peerInterface.getIpAddress().getHostAddress()
964 + "/32";
965 String peerCidrAddress = bgpPeer.getIpAddress().getHostAddress()
966 + "/32";
967
968 //Common match fields
969 forwardMatchSrc.setDataLayerType(Ethernet.TYPE_IPv4);
970 //forwardMatch.setWildcards(forwardMatch.getWildcards() & ~OFMatch.OFPFW_DL_TYPE);
971 forwardMatchSrc.setNetworkProtocol(IPv4.PROTOCOL_TCP);
972 forwardMatchSrc.setTransportDestination(BGP_PORT);
973 forwardMatchSrc.setWildcards(forwardMatchSrc.getWildcards() & ~OFMatch.OFPFW_IN_PORT
974 & ~OFMatch.OFPFW_DL_TYPE & ~OFMatch.OFPFW_NW_PROTO);
975
976
977 OFMatch reverseMatchSrc = forwardMatchSrc.clone();
978
979 forwardMatchSrc.setFromCIDR(peerCidrAddress, OFMatch.STR_NW_SRC);
980 forwardMatchSrc.setFromCIDR(interfaceCidrAddress, OFMatch.STR_NW_DST);
981
982 OFMatch forwardMatchDst = forwardMatchSrc.clone();
983
984 forwardMatchSrc.setTransportSource(BGP_PORT);
985 forwardMatchSrc.setWildcards(forwardMatchSrc.getWildcards() & ~OFMatch.OFPFW_TP_SRC);
986 forwardMatchDst.setTransportDestination(BGP_PORT);
987 forwardMatchDst.setWildcards(forwardMatchDst.getWildcards() & ~OFMatch.OFPFW_TP_DST);
988
989 reverseMatchSrc.setFromCIDR(interfaceCidrAddress, OFMatch.STR_NW_SRC);
990 reverseMatchSrc.setFromCIDR(peerCidrAddress, OFMatch.STR_NW_DST);
991
992 OFMatch reverseMatchDst = reverseMatchSrc.clone();
993
994 reverseMatchSrc.setTransportSource(BGP_PORT);
995 reverseMatchSrc.setWildcards(forwardMatchSrc.getWildcards() & ~OFMatch.OFPFW_TP_SRC);
996 reverseMatchDst.setTransportDestination(BGP_PORT);
997 reverseMatchDst.setWildcards(forwardMatchDst.getWildcards() & ~OFMatch.OFPFW_TP_DST);
998
999 fm.setMatch(forwardMatchSrc);
1000
1001 for (FlowEntry flowEntry : path.flowEntries()){
1002 OFFlowMod forwardFlowModSrc, forwardFlowModDst;
1003 OFFlowMod reverseFlowModSrc, reverseFlowModDst;
1004 try {
1005 forwardFlowModSrc = fm.clone();
1006 forwardFlowModDst = fm.clone();
1007 reverseFlowModSrc = fm.clone();
1008 reverseFlowModDst = fm.clone();
1009 } catch (CloneNotSupportedException e) {
1010 log.warn("Clone failed", e);
1011 continue;
1012 }
1013
1014 forwardMatchSrc.setInputPort(flowEntry.inPort().value());
1015 forwardFlowModSrc.setMatch(forwardMatchSrc);
1016 ((OFActionOutput)forwardFlowModSrc.getActions().get(0))
1017 .setPort(flowEntry.outPort().value());
1018
1019 forwardMatchDst.setInputPort(flowEntry.inPort().value());
1020 forwardFlowModDst.setMatch(forwardMatchDst);
1021 ((OFActionOutput)forwardFlowModDst.getActions().get(0))
1022 .setPort(flowEntry.outPort().value());
1023
1024 reverseMatchSrc.setInputPort(flowEntry.outPort().value());
1025 reverseFlowModSrc.setMatch(reverseMatchSrc);
1026 ((OFActionOutput)reverseFlowModSrc.getActions().get(0))
1027 .setPort(flowEntry.inPort().value());
1028
1029 reverseMatchDst.setInputPort(flowEntry.outPort().value());
1030 reverseFlowModDst.setMatch(reverseMatchDst);
1031 ((OFActionOutput)reverseFlowModDst.getActions().get(0))
1032 .setPort(flowEntry.inPort().value());
1033
1034 IOFSwitch sw = floodlightProvider.getSwitches().get(flowEntry.dpid().value());
1035
1036 //Hopefully the switch is there
1037 List<OFMessage> msgList = new ArrayList<OFMessage>(2);
1038 msgList.add(forwardFlowModSrc);
1039 msgList.add(forwardFlowModDst);
1040 msgList.add(reverseFlowModSrc);
1041 msgList.add(reverseFlowModDst);
1042
1043 try {
1044 sw.write(msgList, null);
1045 sw.flush();
1046 } catch (IOException e) {
1047 log.error("Failure writing flow mod", e);
1048 }
1049 }
1050 }
1051 }
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001052
Jonathan Hart4dfc3652013-08-02 20:22:36 +12001053 @Override
1054 public void arpResponse(InetAddress ipAddress, byte[] macAddress) {
1055 log.debug("Received ARP response: {} => {}", ipAddress.getHostAddress(),
1056 MACAddress.valueOf(macAddress).toString());
1057
1058 Set<PathUpdate> pathsToPush = pathsWaitingOnArp.removeAll(ipAddress);
1059
1060 for (PathUpdate update : pathsToPush) {
1061 log.debug("Pushing path to {} at {} on {}", new Object[] {
1062 update.getDstIpAddress().getHostAddress(),
1063 MACAddress.valueOf(macAddress),
1064 update.getDstInterface().getSwitchPort()});
1065 calculateAndPushPath(update.getDstInterface(),
1066 MACAddress.valueOf(macAddress));
1067 }
Jonathan Hart0ee0f022013-08-03 22:21:54 +12001068
1069 Set<RibUpdate> prefixesToPush = prefixesWaitingOnArp.removeAll(ipAddress);
1070
1071 for (RibUpdate update : prefixesToPush) {
1072 //These must always be adds
1073 log.debug("Pushing prefix {} next hop {}", update.getPrefix(),
1074 update.getRibEntry().nextHop.getHostAddress());
1075 prefixAdded(update);
1076 }
Jonathan Hart4dfc3652013-08-02 20:22:36 +12001077 }
1078
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001079 private void beginRouting(){
1080 log.debug("Topology is now ready, beginning routing function");
Jonathan Hart832a7cb2013-06-24 11:25:35 +12001081 setupBgpPaths();
Jonathan Hart98957bf2013-07-01 14:49:24 +12001082 setupFullMesh();
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001083
Jonathan Hart832a7cb2013-06-24 11:25:35 +12001084 //Traverse ptree and create flows for all routes
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001085 for (PtreeNode node = ptree.begin(); node != null; node = ptree.next(node)){
1086 if (node.rib != null){
1087 prefixAdded(node);
1088 }
1089 }
1090 }
1091
1092 private void checkSwitchesConnected(){
1093 for (String dpid : switches){
1094 if (floodlightProvider.getSwitches().get(HexString.toLong(dpid)) == null){
1095 log.debug("Not all switches are here yet");
1096 return;
1097 }
1098 }
1099 switchesConnected = true;
1100 }
1101
Jonathan Hartc824ad02013-07-03 15:58:45 +12001102 //Actually we only need to go half way round to verify full mesh connectivity
1103 //(n^2)/2
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001104 private void checkTopologyReady(){
Jonathan Hartc824ad02013-07-03 15:58:45 +12001105 for (Interface dstInterface : interfaces.values()) {
1106 for (Interface srcInterface : interfaces.values()) {
1107 if (dstInterface == srcInterface) {
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001108 continue;
1109 }
1110
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001111 DataPath shortestPath = topoRouteService.getShortestPath(
Jonathan Hartc824ad02013-07-03 15:58:45 +12001112 srcInterface.getSwitchPort(), dstInterface.getSwitchPort());
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001113
1114 if (shortestPath == null){
1115 log.debug("Shortest path between {} and {} not found",
Jonathan Hartc824ad02013-07-03 15:58:45 +12001116 srcInterface.getSwitchPort(), dstInterface.getSwitchPort());
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001117 return;
1118 }
1119 }
1120 }
1121 topologyReady = true;
1122 }
1123
1124 private void checkStatus(){
1125 log.debug("In checkStatus, swC {}, toRe {}", switchesConnected, topologyReady);
1126
1127 if (!switchesConnected){
1128 checkSwitchesConnected();
1129 }
1130 boolean oldTopologyReadyStatus = topologyReady;
1131 if (switchesConnected && !topologyReady){
1132 checkTopologyReady();
1133 }
1134 if (!oldTopologyReadyStatus && topologyReady){
1135 beginRouting();
1136 }
1137 }
1138
pingping-lina2cbfad2013-03-07 08:39:21 +08001139 @Override
1140 public void startUp(FloodlightModuleContext context) {
pingping-line2a09ca2013-03-23 09:33:58 +08001141 restApi.addRestletRoutable(new BgpRouteWebRoutable());
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001142 floodlightProvider.addOFSwitchListener(this);
Jonathan Hart61ba9372013-05-19 20:10:29 -07001143 topology.addListener(this);
pingping-line2a09ca2013-03-23 09:33:58 +08001144
Jonathan Hartc7ca35d2013-06-25 20:54:25 +12001145 floodlightProvider.addOFMessageListener(OFType.PACKET_IN, proxyArp);
1146
Jonathan Hart8b9349e2013-07-26 15:55:28 +12001147 ExecutorService e = Executors.newSingleThreadExecutor(
1148 new ThreadFactoryBuilder().setNameFormat("bgp-updates-%d").build());
1149
1150
1151 e.execute(new Runnable() {
1152 @Override
1153 public void run() {
1154 doUpdatesThread();
1155 }
1156 });
1157
Jonathan Hart61ba9372013-05-19 20:10:29 -07001158 //Retrieve the RIB from BGPd during startup
1159 retrieveRib();
pingping-lina2cbfad2013-03-07 08:39:21 +08001160 }
Jonathan Hart8b9349e2013-07-26 15:55:28 +12001161
1162 private void doUpdatesThread() {
1163 boolean interrupted = false;
1164 try {
1165 while (true) {
1166 try {
1167 RibUpdate update = ribUpdates.take();
1168 switch (update.getOperation()){
1169 case UPDATE:
1170 wrapPrefixAdded(update);
1171 break;
1172 case DELETE:
1173 wrapPrefixDeleted(update);
1174 break;
1175 }
1176 } catch (InterruptedException e) {
1177 interrupted = true;
1178 }
1179 }
1180 } finally {
1181 if (interrupted) {
1182 Thread.currentThread().interrupt();
1183 }
1184 }
1185 }
pingping-lina2cbfad2013-03-07 08:39:21 +08001186
1187 @Override
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001188 public void topologyChanged() {
1189 //There seems to be more topology events than there should be. Lots of link
1190 //updated, port up and switch updated on what should be a fairly static topology
pingping-lina2cbfad2013-03-07 08:39:21 +08001191
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001192 boolean refreshNeeded = false;
1193 for (LDUpdate ldu : topology.getLastLinkUpdates()){
1194 if (!ldu.getOperation().equals(ILinkDiscovery.UpdateOperation.LINK_UPDATED)){
1195 //We don't need to recalculate anything for just link updates
1196 //They happen way too frequently (may be a bug in our link discovery)
1197 refreshNeeded = true;
1198 }
Jonathan Hart98957bf2013-07-01 14:49:24 +12001199
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001200 log.debug("Topo change {}", ldu.getOperation());
Jonathan Hartc824ad02013-07-03 15:58:45 +12001201
Jonathan Hart98957bf2013-07-01 14:49:24 +12001202 if (ldu.getOperation().equals(ILinkDiscovery.UpdateOperation.LINK_ADDED)){
1203 synchronized (linkUpdates) {
1204 linkUpdates.add(ldu);
1205 }
1206 }
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001207 }
1208
1209 if (refreshNeeded){
Jonathan Hart98957bf2013-07-01 14:49:24 +12001210 topologyChangeDetectorTask.reschedule(TOPO_DETECTION_WAIT, TimeUnit.SECONDS);
pingping-lina2cbfad2013-03-07 08:39:21 +08001211 }
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001212 }
pingping-lina2cbfad2013-03-07 08:39:21 +08001213
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001214 //TODO determine whether we need to listen for switch joins
1215 @Override
1216 public void addedSwitch(IOFSwitch sw) {
1217 //checkStatus();
1218 }
1219
1220 @Override
1221 public void removedSwitch(IOFSwitch sw) {
1222 // TODO Auto-generated method stub
1223 }
1224
1225 @Override
1226 public void switchPortChanged(Long switchId) {}
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001227
1228 @Override
1229 public String getName() {
1230 return "BgpRoute";
pingping-lina2cbfad2013-03-07 08:39:21 +08001231 }
1232}