blob: 1825fedeb142c00a5bdf79a11339dd1e44801f05 [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;
pingping-lina2cbfad2013-03-07 08:39:21 +08006import java.util.ArrayList;
Jonathan Hart61ba9372013-05-19 20:10:29 -07007import java.util.Collection;
pingping-lina2cbfad2013-03-07 08:39:21 +08008import java.util.HashMap;
Jonathan Hart98957bf2013-07-01 14:49:24 +12009import java.util.Iterator;
Jonathan Harte7e1c6e2013-06-04 20:50:23 -070010import java.util.List;
Jonathan Hart61ba9372013-05-19 20:10:29 -070011import java.util.Map;
Jonathan Hart4dfc3652013-08-02 20:22:36 +120012import java.util.Set;
Jonathan Hart8b9349e2013-07-26 15:55:28 +120013import java.util.concurrent.BlockingQueue;
14import java.util.concurrent.ExecutorService;
Jonathan Hart98957bf2013-07-01 14:49:24 +120015import java.util.concurrent.Executors;
Jonathan Hart8b9349e2013-07-26 15:55:28 +120016import java.util.concurrent.LinkedBlockingQueue;
Jonathan Hart98957bf2013-07-01 14:49:24 +120017import java.util.concurrent.ScheduledExecutorService;
18import java.util.concurrent.TimeUnit;
pingping-lina2cbfad2013-03-07 08:39:21 +080019
Jonathan Hart61ba9372013-05-19 20:10:29 -070020import net.floodlightcontroller.core.IFloodlightProviderService;
Jonathan Harte7e1c6e2013-06-04 20:50:23 -070021import net.floodlightcontroller.core.IOFSwitch;
Jonathan Hart1236a9b2013-06-18 22:10:05 +120022import net.floodlightcontroller.core.IOFSwitchListener;
pingping-lina2cbfad2013-03-07 08:39:21 +080023import net.floodlightcontroller.core.module.FloodlightModuleContext;
24import net.floodlightcontroller.core.module.FloodlightModuleException;
25import net.floodlightcontroller.core.module.IFloodlightModule;
26import net.floodlightcontroller.core.module.IFloodlightService;
Jonathan Hart98957bf2013-07-01 14:49:24 +120027import net.floodlightcontroller.core.util.SingletonTask;
Jonathan Harte7e1c6e2013-06-04 20:50:23 -070028import net.floodlightcontroller.devicemanager.IDeviceService;
29import net.floodlightcontroller.packet.Ethernet;
Jonathan Hart832a7cb2013-06-24 11:25:35 +120030import net.floodlightcontroller.packet.IPv4;
pingping-lina2cbfad2013-03-07 08:39:21 +080031import net.floodlightcontroller.restserver.IRestApiService;
Jonathan Hart98957bf2013-07-01 14:49:24 +120032import net.floodlightcontroller.routing.Link;
pingping-lina2cbfad2013-03-07 08:39:21 +080033import net.floodlightcontroller.topology.ITopologyListener;
34import net.floodlightcontroller.topology.ITopologyService;
Jonathan Hart4dfc3652013-08-02 20:22:36 +120035import net.floodlightcontroller.util.MACAddress;
Jonathan Hart0ee0f022013-08-03 22:21:54 +120036import net.onrc.onos.ofcontroller.bgproute.RibUpdate.Operation;
Jonathan Hart98957bf2013-07-01 14:49:24 +120037import net.onrc.onos.ofcontroller.core.INetMapTopologyService.ITopoLinkService;
HIGUCHI Yuta20514902013-06-12 11:24:16 -070038import net.onrc.onos.ofcontroller.core.INetMapTopologyService.ITopoRouteService;
Jonathan Hart98957bf2013-07-01 14:49:24 +120039import net.onrc.onos.ofcontroller.core.internal.TopoLinkServiceImpl;
HIGUCHI Yutaa56fbde2013-06-17 14:26:05 -070040import net.onrc.onos.ofcontroller.linkdiscovery.ILinkDiscovery;
41import net.onrc.onos.ofcontroller.linkdiscovery.ILinkDiscovery.LDUpdate;
Jonathan Hart4dfc3652013-08-02 20:22:36 +120042import net.onrc.onos.ofcontroller.proxyarp.IArpRequester;
Jonathan Hartc7ca35d2013-06-25 20:54:25 +120043import net.onrc.onos.ofcontroller.proxyarp.ProxyArpManager;
Pavlin Radoslavovddd01ba2013-07-03 15:40:44 -070044import net.onrc.onos.ofcontroller.routing.TopoRouteService;
HIGUCHI Yuta356086e2013-06-12 15:21:19 -070045import net.onrc.onos.ofcontroller.util.DataPath;
Jonathan Hart832a7cb2013-06-24 11:25:35 +120046import net.onrc.onos.ofcontroller.util.Dpid;
HIGUCHI Yuta356086e2013-06-12 15:21:19 -070047import net.onrc.onos.ofcontroller.util.FlowEntry;
HIGUCHI Yuta356086e2013-06-12 15:21:19 -070048import net.onrc.onos.ofcontroller.util.Port;
49import net.onrc.onos.ofcontroller.util.SwitchPort;
pingping-line2a09ca2013-03-23 09:33:58 +080050import net.sf.json.JSONArray;
51import net.sf.json.JSONObject;
52import net.sf.json.JSONSerializer;
pingping-lina2cbfad2013-03-07 08:39:21 +080053
Jonathan Hartd1f23252013-06-13 15:17:05 +120054import org.codehaus.jackson.JsonParseException;
55import org.codehaus.jackson.map.JsonMappingException;
56import org.codehaus.jackson.map.ObjectMapper;
Jonathan Harte7e1c6e2013-06-04 20:50:23 -070057import org.openflow.protocol.OFFlowMod;
58import org.openflow.protocol.OFMatch;
59import org.openflow.protocol.OFMessage;
60import org.openflow.protocol.OFPacketOut;
Jonathan Hart9575cb62013-07-05 13:43:49 +120061import org.openflow.protocol.OFPort;
Jonathan Harte7e1c6e2013-06-04 20:50:23 -070062import org.openflow.protocol.OFType;
63import org.openflow.protocol.action.OFAction;
64import org.openflow.protocol.action.OFActionDataLayerDestination;
65import org.openflow.protocol.action.OFActionOutput;
Jonathan Hart1236a9b2013-06-18 22:10:05 +120066import org.openflow.util.HexString;
pingping-lina2cbfad2013-03-07 08:39:21 +080067import org.slf4j.Logger;
68import org.slf4j.LoggerFactory;
69
Jonathan Hart4dfc3652013-08-02 20:22:36 +120070import com.google.common.collect.HashMultimap;
Jonathan Hart0ee0f022013-08-03 22:21:54 +120071import com.google.common.collect.Multimap;
Jonathan Hart4dfc3652013-08-02 20:22:36 +120072import com.google.common.collect.Multimaps;
73import com.google.common.collect.SetMultimap;
Jonathan Hart8b9349e2013-07-26 15:55:28 +120074import com.google.common.util.concurrent.ThreadFactoryBuilder;
75
Jonathan Hart1236a9b2013-06-18 22:10:05 +120076public class BgpRoute implements IFloodlightModule, IBgpRouteService,
Jonathan Hart4dfc3652013-08-02 20:22:36 +120077 ITopologyListener, IOFSwitchListener,
78 IArpRequester {
pingping-lina2cbfad2013-03-07 08:39:21 +080079
80 protected static Logger log = LoggerFactory.getLogger(BgpRoute.class);
81
82 protected IFloodlightProviderService floodlightProvider;
83 protected ITopologyService topology;
Jonathan Harte7e1c6e2013-06-04 20:50:23 -070084 protected ITopoRouteService topoRouteService;
85 protected IDeviceService devices;
86 protected IRestApiService restApi;
87
Jonathan Hartc7ca35d2013-06-25 20:54:25 +120088 protected ProxyArpManager proxyArp;
89
Jonathan Hartd7e158d2013-08-07 23:04:48 +120090 //protected static Ptree ptree;
91 protected IPatriciaTrie 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 SetMultimap<InetAddress, RibUpdate> prefixesWaitingOnArp;
130 protected SetMultimap<InetAddress, PathUpdate> pathsWaitingOnArp;
131
Jonathan Hart0a46fe42013-08-10 17:08:47 +1200132 protected ExecutorService bgpUpdatesExecutor;
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
Jonathan Hartd7e158d2013-08-07 23:04:48 +1200255 //ptree = new Ptree(32);
256 ptree = new PatriciaTrie(32);
Jonathan Hart8b9349e2013-07-26 15:55:28 +1200257
258 ribUpdates = new LinkedBlockingQueue<RibUpdate>();
Jonathan Hartc824ad02013-07-03 15:58:45 +1200259
pingping-lina2cbfad2013-03-07 08:39:21 +0800260 // Register floodlight provider and REST handler.
261 floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class);
pingping-lina2cbfad2013-03-07 08:39:21 +0800262 topology = context.getServiceImpl(ITopologyService.class);
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700263 devices = context.getServiceImpl(IDeviceService.class);
Jonathan Hartc7ca35d2013-06-25 20:54:25 +1200264 restApi = context.getServiceImpl(IRestApiService.class);
265
266 //TODO We'll initialise this here for now, but it should really be done as
267 //part of the controller core
Jonathan Hart6261dcd2013-07-22 17:58:35 +1200268 proxyArp = new ProxyArpManager(floodlightProvider, topology, devices);
pingping-lina2cbfad2013-03-07 08:39:21 +0800269
Jonathan Hart98957bf2013-07-01 14:49:24 +1200270 linkUpdates = new ArrayList<LDUpdate>();
271 ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
272 topologyChangeDetectorTask = new SingletonTask(executor, new TopologyChangeDetector());
Pavlin Radoslavovddd01ba2013-07-03 15:40:44 -0700273
274 topoRouteService = new TopoRouteService("");
Jonathan Hart98957bf2013-07-01 14:49:24 +1200275
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200276 pathsWaitingOnArp = Multimaps.synchronizedSetMultimap(
277 HashMultimap.<InetAddress, PathUpdate>create());
278 prefixesWaitingOnArp = Multimaps.synchronizedSetMultimap(
279 HashMultimap.<InetAddress, RibUpdate>create());
280
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200281 pushedFlows = HashMultimap.<Prefix, PushedFlowMod>create();
282
Jonathan Hart0a46fe42013-08-10 17:08:47 +1200283 bgpUpdatesExecutor = Executors.newSingleThreadExecutor(
284 new ThreadFactoryBuilder().setNameFormat("bgp-updates-%d").build());
285
Jonathan Hart61ba9372013-05-19 20:10:29 -0700286 //Read in config values
287 bgpdRestIp = context.getConfigParams(this).get("BgpdRestIp");
288 if (bgpdRestIp == null){
289 log.error("BgpdRestIp property not found in config file");
290 System.exit(1);
291 }
292 else {
293 log.info("BgpdRestIp set to {}", bgpdRestIp);
294 }
295
296 routerId = context.getConfigParams(this).get("RouterId");
297 if (routerId == null){
298 log.error("RouterId property not found in config file");
299 System.exit(1);
300 }
301 else {
302 log.info("RouterId set to {}", routerId);
303 }
Jonathan Hartd1f23252013-06-13 15:17:05 +1200304
Jonathan Hart9575cb62013-07-05 13:43:49 +1200305 String configFilenameParameter = context.getConfigParams(this).get("configfile");
306 if (configFilenameParameter != null){
307 configFilename = configFilenameParameter;
308 }
309 log.debug("Config file set to {}", configFilename);
310
311 readGatewaysConfiguration(configFilename);
pingping-lina2cbfad2013-03-07 08:39:21 +0800312 // Test.
313 //test();
314 }
315
Jonathan Hartd7e158d2013-08-07 23:04:48 +1200316 //public Ptree getPtree() {
317 public IPatriciaTrie getPtree() {
pingping-lina2cbfad2013-03-07 08:39:21 +0800318 return ptree;
319 }
Jonathan Hart61ba9372013-05-19 20:10:29 -0700320
321 public void clearPtree() {
322 //ptree = null;
Jonathan Hartd7e158d2013-08-07 23:04:48 +1200323 //ptree = new Ptree(32);
324 ptree = new PatriciaTrie(32);
pingping-line2a09ca2013-03-23 09:33:58 +0800325 }
Jonathan Hart61ba9372013-05-19 20:10:29 -0700326
pingping-line2a09ca2013-03-23 09:33:58 +0800327 public String getBGPdRestIp() {
Jonathan Hart61ba9372013-05-19 20:10:29 -0700328 return bgpdRestIp;
pingping-line2a09ca2013-03-23 09:33:58 +0800329 }
Jonathan Hart61ba9372013-05-19 20:10:29 -0700330
pingping-line2a09ca2013-03-23 09:33:58 +0800331 public String getRouterId() {
Jonathan Hart61ba9372013-05-19 20:10:29 -0700332 return routerId;
pingping-line2a09ca2013-03-23 09:33:58 +0800333 }
pingping-lina2cbfad2013-03-07 08:39:21 +0800334
335 // Return nexthop address as byte array.
Jonathan Hartd7e158d2013-08-07 23:04:48 +1200336 /*
pingping-lina2cbfad2013-03-07 08:39:21 +0800337 public Rib lookupRib(byte[] dest) {
338 if (ptree == null) {
339 log.debug("lookupRib: ptree null");
340 return null;
341 }
342
343 PtreeNode node = ptree.match(dest, 32);
344 if (node == null) {
345 log.debug("lookupRib: ptree node null");
346 return null;
347 }
Jonathan Hart61ba9372013-05-19 20:10:29 -0700348
pingping-lina2cbfad2013-03-07 08:39:21 +0800349 if (node.rib == null) {
350 log.debug("lookupRib: ptree rib null");
351 return null;
352 }
Jonathan Hart61ba9372013-05-19 20:10:29 -0700353
pingping-lina2cbfad2013-03-07 08:39:21 +0800354 ptree.delReference(node);
355
356 return node.rib;
357 }
Jonathan Hartd7e158d2013-08-07 23:04:48 +1200358 */
pingping-lina2cbfad2013-03-07 08:39:21 +0800359
Jonathan Hartd7e158d2013-08-07 23:04:48 +1200360 /*
Jonathan Hart61ba9372013-05-19 20:10:29 -0700361 //TODO looks like this should be a unit test
pingping-lina2cbfad2013-03-07 08:39:21 +0800362 @SuppressWarnings("unused")
Jonathan Hart61ba9372013-05-19 20:10:29 -0700363 private void test() throws UnknownHostException {
pingping-lina2cbfad2013-03-07 08:39:21 +0800364 System.out.println("Here it is");
365 Prefix p = new Prefix("128.0.0.0", 8);
366 Prefix q = new Prefix("8.0.0.0", 8);
367 Prefix r = new Prefix("10.0.0.0", 24);
368 Prefix a = new Prefix("10.0.0.1", 32);
369
Jonathan Hartd1b9d872013-07-23 12:17:21 +1200370 ptree.acquire(p.getAddress(), p.getPrefixLength());
371 ptree.acquire(q.getAddress(), q.getPrefixLength());
372 ptree.acquire(r.getAddress(), r.getPrefixLength());
pingping-lina2cbfad2013-03-07 08:39:21 +0800373
374 System.out.println("Traverse start");
375 for (PtreeNode node = ptree.begin(); node != null; node = ptree.next(node)) {
376 Prefix p_result = new Prefix(node.key, node.keyBits);
377 }
378
Jonathan Hartd1b9d872013-07-23 12:17:21 +1200379 PtreeNode n = ptree.match(a.getAddress(), a.getPrefixLength());
pingping-lina2cbfad2013-03-07 08:39:21 +0800380 if (n != null) {
381 System.out.println("Matched prefix for 10.0.0.1:");
382 Prefix x = new Prefix(n.key, n.keyBits);
383 ptree.delReference(n);
384 }
385
Jonathan Hartd1b9d872013-07-23 12:17:21 +1200386 n = ptree.lookup(p.getAddress(), p.getPrefixLength());
pingping-lina2cbfad2013-03-07 08:39:21 +0800387 if (n != null) {
388 ptree.delReference(n);
389 ptree.delReference(n);
390 }
391 System.out.println("Traverse start");
392 for (PtreeNode node = ptree.begin(); node != null; node = ptree.next(node)) {
393 Prefix p_result = new Prefix(node.key, node.keyBits);
394 }
395
Jonathan Hartd1b9d872013-07-23 12:17:21 +1200396 n = ptree.lookup(q.getAddress(), q.getPrefixLength());
pingping-lina2cbfad2013-03-07 08:39:21 +0800397 if (n != null) {
398 ptree.delReference(n);
399 ptree.delReference(n);
400 }
401 System.out.println("Traverse start");
402 for (PtreeNode node = ptree.begin(); node != null; node = ptree.next(node)) {
403 Prefix p_result = new Prefix(node.key, node.keyBits);
404 }
405
Jonathan Hartd1b9d872013-07-23 12:17:21 +1200406 n = ptree.lookup(r.getAddress(), r.getPrefixLength());
pingping-lina2cbfad2013-03-07 08:39:21 +0800407 if (n != null) {
408 ptree.delReference(n);
409 ptree.delReference(n);
410 }
411 System.out.println("Traverse start");
412 for (PtreeNode node = ptree.begin(); node != null; node = ptree.next(node)) {
413 Prefix p_result = new Prefix(node.key, node.keyBits);
414 }
415
416 }
Jonathan Hartd7e158d2013-08-07 23:04:48 +1200417 */
pingping-lina2cbfad2013-03-07 08:39:21 +0800418
Jonathan Hartdf6ec332013-08-04 01:37:14 +1200419 //TODO once the Ptree is object oriented this can go
Jonathan Hart0a46fe42013-08-10 17:08:47 +1200420 /*
Jonathan Hart1236a9b2013-06-18 22:10:05 +1200421 private String getPrefixFromPtree(PtreeNode node){
422 InetAddress address = null;
423 try {
424 address = InetAddress.getByAddress(node.key);
425 } catch (UnknownHostException e1) {
426 //Should never happen is the reverse conversion has already been done
427 log.error("Malformed IP address");
428 return "";
429 }
430 return address.toString() + "/" + node.rib.masklen;
431 }
Jonathan Hart0a46fe42013-08-10 17:08:47 +1200432 */
Jonathan Hart1236a9b2013-06-18 22:10:05 +1200433
Jonathan Hart61ba9372013-05-19 20:10:29 -0700434 private void retrieveRib(){
435 String url = "http://" + bgpdRestIp + "/wm/bgp/" + routerId;
436 String response = RestClient.get(url);
437
438 if (response.equals("")){
439 return;
440 }
441
442 response = response.replaceAll("\"", "'");
443 JSONObject jsonObj = (JSONObject) JSONSerializer.toJSON(response);
444 JSONArray rib_json_array = jsonObj.getJSONArray("rib");
445 String router_id = jsonObj.getString("router-id");
446
447 int size = rib_json_array.size();
448
449 log.info("Retrived RIB of {} entries from BGPd", size);
450
451 for (int j = 0; j < size; j++) {
452 JSONObject second_json_object = rib_json_array.getJSONObject(j);
453 String prefix = second_json_object.getString("prefix");
454 String nexthop = second_json_object.getString("nexthop");
455
456 //insert each rib entry into the local rib;
457 String[] substring = prefix.split("/");
458 String prefix1 = substring[0];
459 String mask1 = substring[1];
460
461 Prefix p;
462 try {
463 p = new Prefix(prefix1, Integer.valueOf(mask1));
464 } catch (NumberFormatException e) {
465 log.warn("Wrong mask format in RIB JSON: {}", mask1);
466 continue;
Jonathan Hart32e18222013-08-07 22:05:42 +1200467 } catch (IllegalArgumentException e1) {
Jonathan Hart61ba9372013-05-19 20:10:29 -0700468 log.warn("Wrong prefix format in RIB JSON: {}", prefix1);
469 continue;
470 }
471
Jonathan Hartd7e158d2013-08-07 23:04:48 +1200472 //PtreeNode node = ptree.acquire(p.getAddress(), p.getPrefixLength());
Jonathan Hartd1b9d872013-07-23 12:17:21 +1200473 Rib rib = new Rib(router_id, nexthop, p.getPrefixLength());
Jonathan Hart61ba9372013-05-19 20:10:29 -0700474
Jonathan Hartd7e158d2013-08-07 23:04:48 +1200475 /*
Jonathan Hart61ba9372013-05-19 20:10:29 -0700476 if (node.rib != null) {
477 node.rib = null;
478 ptree.delReference(node);
479 }
480
481 node.rib = rib;
Jonathan Hartd7e158d2013-08-07 23:04:48 +1200482 */
483
Jonathan Hart0a46fe42013-08-10 17:08:47 +1200484 //ptree.put(p, rib);
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700485
Jonathan Hart0a46fe42013-08-10 17:08:47 +1200486 //addPrefixFlows(p, rib);
487 try {
488 ribUpdates.put(new RibUpdate(Operation.UPDATE, p, rib));
489 } catch (InterruptedException e) {
490 log.debug("Interrupted while pushing onto update queue");
491 }
Jonathan Hart61ba9372013-05-19 20:10:29 -0700492 }
493 }
494
Jonathan Hart8b9349e2013-07-26 15:55:28 +1200495 @Override
496 public void newRibUpdate(RibUpdate update) {
497 ribUpdates.add(update);
498 }
499
Jonathan Hart0a46fe42013-08-10 17:08:47 +1200500 public synchronized void processRibAdd(RibUpdate update) {
Jonathan Hart8b9349e2013-07-26 15:55:28 +1200501 Prefix prefix = update.getPrefix();
502
Jonathan Hartd7e158d2013-08-07 23:04:48 +1200503 //PtreeNode node = ptree.acquire(prefix.getAddress(), prefix.getPrefixLength());
504 Rib rib = ptree.put(prefix, update.getRibEntry());
Jonathan Hart8b9349e2013-07-26 15:55:28 +1200505
Jonathan Hartd7e158d2013-08-07 23:04:48 +1200506 //if (node.rib != null) {
Jonathan Hart0a46fe42013-08-10 17:08:47 +1200507 if (rib != null && !rib.equals(update.getRibEntry())) {
Jonathan Hart2f740782013-08-04 00:49:21 +1200508 //There was an existing nexthop for this prefix. This update supersedes that,
509 //so we need to remove the old flows for this prefix from the switches
510 deletePrefixFlows(prefix);
511
512 //Then remove the old nexthop from the Ptree
Jonathan Hartd7e158d2013-08-07 23:04:48 +1200513 //node.rib = null;
514 //ptree.delReference(node);
Jonathan Hart8b9349e2013-07-26 15:55:28 +1200515 }
Jonathan Hart2f740782013-08-04 00:49:21 +1200516
517 //Put the new nexthop in the Ptree
Jonathan Hartd7e158d2013-08-07 23:04:48 +1200518 //node.rib = update.getRibEntry();
Jonathan Hart8b9349e2013-07-26 15:55:28 +1200519
Jonathan Hart2f740782013-08-04 00:49:21 +1200520 //Push flows for the new <prefix, nexthop>
Jonathan Hart2f740782013-08-04 00:49:21 +1200521 addPrefixFlows(prefix, update.getRibEntry());
Jonathan Hart8b9349e2013-07-26 15:55:28 +1200522 }
523
Jonathan Hart0a46fe42013-08-10 17:08:47 +1200524 public synchronized void processRibDelete(RibUpdate update) {
Jonathan Hart8b9349e2013-07-26 15:55:28 +1200525 Prefix prefix = update.getPrefix();
526
Jonathan Hartd7e158d2013-08-07 23:04:48 +1200527 //PtreeNode node = ptree.lookup(prefix.getAddress(), prefix.getPrefixLength());
Jonathan Hart8b9349e2013-07-26 15:55:28 +1200528
529 /*
530 * Remove the flows from the switches before the rib is lost
531 * Theory: we could get a delete for a prefix not in the Ptree.
532 * This would result in a null node being returned. We could get a delete for
533 * a node that's not actually there, but is a aggregate node. This would result
534 * in a non-null node with a null rib. Only a non-null node with a non-null
535 * rib is an actual prefix in the Ptree.
536 */
Jonathan Hart8b9349e2013-07-26 15:55:28 +1200537
Jonathan Hartd7e158d2013-08-07 23:04:48 +1200538 /*
Jonathan Hart8b9349e2013-07-26 15:55:28 +1200539 if (node != null && node.rib != null) {
540 if (update.getRibEntry().equals(node.rib)) {
541 node.rib = null;
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200542 ptree.delReference(node);
543
Jonathan Hart2f740782013-08-04 00:49:21 +1200544 deletePrefixFlows(update.getPrefix());
Jonathan Hart8b9349e2013-07-26 15:55:28 +1200545 }
546 }
Jonathan Hartd7e158d2013-08-07 23:04:48 +1200547 */
548
549 if (ptree.remove(prefix, update.getRibEntry())) {
550 /*
551 * Only delete flows if an entry was actually removed from the trie.
552 * If no entry was removed, the <prefix, nexthop> wasn't there so
553 * it's probably already been removed and we don't need to do anything
554 */
555 deletePrefixFlows(prefix);
556 }
Jonathan Hart8b9349e2013-07-26 15:55:28 +1200557 }
558
Jonathan Hart2f740782013-08-04 00:49:21 +1200559 //TODO compatibility layer, used by beginRouting()
Jonathan Hartd7e158d2013-08-07 23:04:48 +1200560 /*public void prefixAdded(PtreeNode node) {
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200561 Prefix prefix = null;
562 try {
563 prefix = new Prefix(node.key, node.rib.masklen);
Jonathan Hart32e18222013-08-07 22:05:42 +1200564 } catch (IllegalArgumentException e) {
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200565 log.error(" ", e);
566 }
Jonathan Hartdf6ec332013-08-04 01:37:14 +1200567
Jonathan Hart2f740782013-08-04 00:49:21 +1200568 addPrefixFlows(prefix, node.rib);
Jonathan Hartd7e158d2013-08-07 23:04:48 +1200569 }*/
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200570
Jonathan Hart2f740782013-08-04 00:49:21 +1200571 private void addPrefixFlows(Prefix prefix, Rib rib) {
Jonathan Hart1236a9b2013-06-18 22:10:05 +1200572 if (!topologyReady){
573 return;
574 }
575
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200576 //TODO before we do anything, we have to check that the RIB entry is still in the
577 //Ptree because it could have been removed while we were waiting for ARP.
578 //I think we'll have to make prefixAdded and prefixDelete atomic as well
579 //to protect against the prefix getting deleted while where trying to add it
Jonathan Hart2f740782013-08-04 00:49:21 +1200580
Jonathan Hartc824ad02013-07-03 15:58:45 +1200581 log.debug("New prefix {} added, next hop {}, routerId {}",
Jonathan Hart2f740782013-08-04 00:49:21 +1200582 new Object[] {prefix, rib.nextHop.getHostAddress(),
583 rib.routerId.getHostAddress()});
Jonathan Hart1236a9b2013-06-18 22:10:05 +1200584
Jonathan Hartc824ad02013-07-03 15:58:45 +1200585 //TODO this is wrong, we shouldn't be dealing with BGP peers here.
Jonathan Hart6261dcd2013-07-22 17:58:35 +1200586 //We need to figure out where the device is attached and what its
Jonathan Hartc824ad02013-07-03 15:58:45 +1200587 //mac address is by learning.
588 //The next hop is not necessarily the peer, and the peer's attachment
589 //point is not necessarily the next hop's attachment point.
Jonathan Hart2f740782013-08-04 00:49:21 +1200590 BgpPeer peer = bgpPeers.get(rib.nextHop);
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700591
Jonathan Hartc824ad02013-07-03 15:58:45 +1200592 if (peer == null){
593 //TODO local router isn't in peers list so this will get thrown
Jonathan Hart50a8d1e2013-06-06 16:00:47 +1200594 //Need to work out what to do about local prefixes with next hop 0.0.0.0.
Jonathan Hartc824ad02013-07-03 15:58:45 +1200595
596 //The other scenario is this is a route server route. In that
597 //case the next hop is not in our configuration
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200598 log.error("Couldn't find next hop router in router {} in config",
Jonathan Hart2f740782013-08-04 00:49:21 +1200599 rib.nextHop.getHostAddress());
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700600 return; //just quit out here? This is probably a configuration error
601 }
Jonathan Hartc824ad02013-07-03 15:58:45 +1200602
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200603 //Get MAC address for peer from the ARP module
604 //TODO separate out the 'ask for MAC' bit to another method
605 byte[] peerMacAddress = proxyArp.getMacAddress(peer.getIpAddress());
606 if (peerMacAddress == null) {
Jonathan Hart2f740782013-08-04 00:49:21 +1200607 //A RibUpdate is still a nice way to package them up
608 prefixesWaitingOnArp.put(peer.getIpAddress(),
609 new RibUpdate(Operation.UPDATE, prefix, rib));
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200610 proxyArp.sendArpRequest(peer.getIpAddress(), this, true);
611 return;
612 }
613
Jonathan Hartc824ad02013-07-03 15:58:45 +1200614 Interface peerInterface = interfaces.get(peer.getInterfaceName());
Jonathan Hart50a8d1e2013-06-06 16:00:47 +1200615
Jonathan Hartc824ad02013-07-03 15:58:45 +1200616 //Add a flow to rewrite mac for this prefix to all border switches
617 for (Interface srcInterface : interfaces.values()) {
618 if (srcInterface == peerInterface) {
619 //Don't push a flow for the switch where this peer is attached
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700620 continue;
621 }
Jonathan Hartc824ad02013-07-03 15:58:45 +1200622
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700623 DataPath shortestPath = topoRouteService.getShortestPath(
Jonathan Hartc824ad02013-07-03 15:58:45 +1200624 srcInterface.getSwitchPort(),
625 peerInterface.getSwitchPort());
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700626
627 if (shortestPath == null){
628 log.debug("Shortest path between {} and {} not found",
Jonathan Hartc824ad02013-07-03 15:58:45 +1200629 srcInterface.getSwitchPort(),
630 peerInterface.getSwitchPort());
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700631 return; // just quit here?
632 }
633
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700634 //Set up the flow mod
635 OFFlowMod fm =
636 (OFFlowMod) floodlightProvider.getOFMessageFactory()
637 .getMessage(OFType.FLOW_MOD);
638
639 fm.setIdleTimeout((short)0)
640 .setHardTimeout((short)0)
641 .setBufferId(OFPacketOut.BUFFER_ID_NONE)
642 .setCookie(MAC_RW_COOKIE)
643 .setCommand(OFFlowMod.OFPFC_ADD)
Jonathan Hart50a8d1e2013-06-06 16:00:47 +1200644 .setPriority(SDNIP_PRIORITY)
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700645 .setLengthU(OFFlowMod.MINIMUM_LENGTH
646 + OFActionDataLayerDestination.MINIMUM_LENGTH
647 + OFActionOutput.MINIMUM_LENGTH);
648
649 OFMatch match = new OFMatch();
650 match.setDataLayerType(Ethernet.TYPE_IPv4);
Jonathan Hart50a8d1e2013-06-06 16:00:47 +1200651 match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_TYPE);
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700652
Jonathan Hart0a46fe42013-08-10 17:08:47 +1200653 /*
Jonathan Hart50a8d1e2013-06-06 16:00:47 +1200654 InetAddress address = null;
655 try {
Jonathan Hart2f740782013-08-04 00:49:21 +1200656 address = InetAddress.getByAddress(prefix.getAddress());
Jonathan Hart50a8d1e2013-06-06 16:00:47 +1200657 } catch (UnknownHostException e1) {
658 //Should never happen is the reverse conversion has already been done
659 log.error("Malformed IP address");
660 return;
Jonathan Hart0a46fe42013-08-10 17:08:47 +1200661 }*/
Jonathan Hart50a8d1e2013-06-06 16:00:47 +1200662
Jonathan Hart0a46fe42013-08-10 17:08:47 +1200663 //match.setFromCIDR(address.getHostAddress() + "/" +
664 // prefix.getPrefixLength(), OFMatch.STR_NW_DST);
665 match.setFromCIDR(prefix.toString(), OFMatch.STR_NW_DST);
Jonathan Hart50a8d1e2013-06-06 16:00:47 +1200666 fm.setMatch(match);
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700667
668 //Set up MAC rewrite action
669 OFActionDataLayerDestination macRewriteAction = new OFActionDataLayerDestination();
Jonathan Hartc824ad02013-07-03 15:58:45 +1200670 //TODO the peer's mac address is not necessarily the next hop's...
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200671 macRewriteAction.setDataLayerAddress(peerMacAddress);
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700672
673 //Set up output action
674 OFActionOutput outputAction = new OFActionOutput();
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200675 outputAction.setMaxLength((short)0xffff);
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700676
Jonathan Hart50a8d1e2013-06-06 16:00:47 +1200677 Port outputPort = shortestPath.flowEntries().get(0).outPort();
678 outputAction.setPort(outputPort.value());
679
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700680 List<OFAction> actions = new ArrayList<OFAction>();
681 actions.add(macRewriteAction);
682 actions.add(outputAction);
683 fm.setActions(actions);
684
685 //Write to switch
686 IOFSwitch sw = floodlightProvider.getSwitches()
Jonathan Hartc824ad02013-07-03 15:58:45 +1200687 .get(srcInterface.getDpid());
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700688
689 if (sw == null){
690 log.warn("Switch not found when pushing flow mod");
691 continue;
692 }
693
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200694 //TODO if prefix Added/Deleted are synchronized this shouldn't have to be
Jonathan Hart2f740782013-08-04 00:49:21 +1200695 pushedFlows.put(prefix, new PushedFlowMod(sw.getId(), fm));
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200696
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700697 List<OFMessage> msglist = new ArrayList<OFMessage>();
698 msglist.add(fm);
699 try {
700 sw.write(msglist, null);
701 sw.flush();
702 } catch (IOException e) {
703 log.error("Failure writing flow mod", e);
704 }
705 }
706 }
707
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200708 //TODO test next-hop changes
Jonathan Hart2f740782013-08-04 00:49:21 +1200709 //TODO check delete/add synchronization
Jonathan Hart2f740782013-08-04 00:49:21 +1200710
711 private void deletePrefixFlows(Prefix prefix) {
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200712 if (!topologyReady) {
713 return;
714 }
715
Jonathan Hartdf6ec332013-08-04 01:37:14 +1200716 log.debug("In deletePrefixFlows for {}", prefix);
Jonathan Hart2f740782013-08-04 00:49:21 +1200717
718 /*for (Map.Entry<Prefix, PushedFlowMod> entry : pushedFlows.entries()) {
719 log.debug("Pushed flow: {} => {}", entry.getKey(), entry.getValue());
720 }*/
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200721
722 Collection<PushedFlowMod> pushedFlowMods
Jonathan Hart2f740782013-08-04 00:49:21 +1200723 = pushedFlows.removeAll(prefix);
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200724
725 for (PushedFlowMod pfm : pushedFlowMods) {
726 log.debug("Pushing a DELETE flow mod to {}, matches prefix {} with mac-rewrite {}",
727 new Object[] {HexString.toHexString(pfm.getDpid()),
728 pfm.getFlowMod().getMatch().getNetworkDestination() +
729 pfm.getFlowMod().getMatch().getNetworkDestinationMaskLen(),
730 HexString.toHexString(((OFActionDataLayerDestination)pfm.getFlowMod().getActions().get(0))
731 .getDataLayerAddress())});
732
733 OFFlowMod fm = pfm.getFlowMod();
734
735 fm.setCommand(OFFlowMod.OFPFC_DELETE)
Jonathan Hart2f740782013-08-04 00:49:21 +1200736 .setOutPort(OFPort.OFPP_NONE)
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200737 .setLengthU(OFFlowMod.MINIMUM_LENGTH);
738
739 fm.getActions().clear();
740
741 IOFSwitch sw = floodlightProvider.getSwitches().get(pfm.getDpid());
742 if (sw == null) {
743 log.warn("Switch not found when pushing delete flow mod");
744 continue;
745 }
746
747 try {
748 sw.write(fm, null);
749 sw.flush();
750 } catch (IOException e) {
751 log.error("Failure writing flow mod", e);
752 }
753 }
754 }
755
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700756 /*
757 * On startup we need to calculate a full mesh of paths between all gateway
758 * switches
759 */
Jonathan Hart1236a9b2013-06-18 22:10:05 +1200760 private void setupFullMesh(){
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700761 //For each border router, calculate and install a path from every other
762 //border switch to said border router. However, don't install the entry
763 //in to the first hop switch, as we need to install an entry to rewrite
764 //for each prefix received. This will be done later when prefixes have
765 //actually been received.
766
Jonathan Hartc824ad02013-07-03 15:58:45 +1200767 for (BgpPeer peer : bgpPeers.values()) {
768 Interface peerInterface = interfaces.get(peer.getInterfaceName());
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200769
770 //See if we know the MAC address of the peer. If not we can't
771 //do anything until we learn it
772 byte[] mac = proxyArp.getMacAddress(peer.getIpAddress());
773 if (mac == null) {
774 log.debug("Don't know MAC for {}", peer.getIpAddress().getHostAddress());
775 //Put in the pending paths list first
776 pathsWaitingOnArp.put(peer.getIpAddress(),
777 new PathUpdate(peerInterface, peer.getIpAddress()));
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700778
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200779 proxyArp.sendArpRequest(peer.getIpAddress(), this, true);
780 continue;
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700781 }
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200782
783 //If we know the MAC, lets go ahead and push the paths to this peer
784 calculateAndPushPath(peerInterface, MACAddress.valueOf(mac));
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700785 }
786 }
787
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200788 private void calculateAndPushPath(Interface dstInterface, MACAddress dstMacAddress) {
789 for (Interface srcInterface : interfaces.values()) {
790 if (dstInterface.equals(srcInterface.getName())){
791 continue;
792 }
793
794 DataPath shortestPath = topoRouteService.getShortestPath(
795 srcInterface.getSwitchPort(), dstInterface.getSwitchPort());
796
797 if (shortestPath == null){
798 log.debug("Shortest path between {} and {} not found",
799 srcInterface.getSwitchPort(), dstInterface.getSwitchPort());
800 return; // just quit here?
801 }
802
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200803 installPath(shortestPath.flowEntries(), dstMacAddress);
804 }
805 }
806
807 private void installPath(List<FlowEntry> flowEntries, MACAddress dstMacAddress){
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700808 //Set up the flow mod
809 OFFlowMod fm =
810 (OFFlowMod) floodlightProvider.getOFMessageFactory()
811 .getMessage(OFType.FLOW_MOD);
812
813 OFActionOutput action = new OFActionOutput();
814 action.setMaxLength((short)0xffff);
815 List<OFAction> actions = new ArrayList<OFAction>();
816 actions.add(action);
817
818 fm.setIdleTimeout((short)0)
819 .setHardTimeout((short)0)
820 .setBufferId(OFPacketOut.BUFFER_ID_NONE)
821 .setCookie(L2_FWD_COOKIE)
822 .setCommand(OFFlowMod.OFPFC_ADD)
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700823 .setActions(actions)
824 .setLengthU(OFFlowMod.MINIMUM_LENGTH+OFActionOutput.MINIMUM_LENGTH);
825
826 //Don't push the first flow entry. We need to push entries in the
827 //first switch based on IP prefix which we don't know yet.
828 for (int i = 1; i < flowEntries.size(); i++){
829 FlowEntry flowEntry = flowEntries.get(i);
830
831 OFMatch match = new OFMatch();
Jonathan Hartc824ad02013-07-03 15:58:45 +1200832 //TODO Again using MAC address from configuration
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200833 match.setDataLayerDestination(dstMacAddress.toBytes());
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700834 match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_DST);
835 ((OFActionOutput) fm.getActions().get(0)).setPort(flowEntry.outPort().value());
836
837 fm.setMatch(match);
838
839 IOFSwitch sw = floodlightProvider.getSwitches().get(flowEntry.dpid().value());
840
841 if (sw == null){
842 log.warn("Switch not found when pushing flow mod");
843 continue;
844 }
845
846 List<OFMessage> msglist = new ArrayList<OFMessage>();
847 msglist.add(fm);
848 try {
849 sw.write(msglist, null);
850 sw.flush();
851 } catch (IOException e) {
852 log.error("Failure writing flow mod", e);
853 }
854
855 try {
856 fm = fm.clone();
857 } catch (CloneNotSupportedException e1) {
858 log.error("Failure cloning flow mod", e1);
859 }
860 }
861 }
862
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200863 private void setupBgpPaths(){
Jonathan Hartc824ad02013-07-03 15:58:45 +1200864 for (BgpPeer bgpPeer : bgpPeers.values()){
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200865 Interface peerInterface = interfaces.get(bgpPeer.getInterfaceName());
866
867 DataPath path = topoRouteService.getShortestPath(
868 peerInterface.getSwitchPort(), bgpdAttachmentPoint);
869
870 if (path == null){
871 log.debug("Unable to compute path for BGP traffic for {}",
872 bgpPeer.getIpAddress());
873 continue;
874 }
875
876 //Set up the flow mod
877 OFFlowMod fm =
878 (OFFlowMod) floodlightProvider.getOFMessageFactory()
879 .getMessage(OFType.FLOW_MOD);
880
881 OFActionOutput action = new OFActionOutput();
882 action.setMaxLength((short)0xffff);
883 List<OFAction> actions = new ArrayList<OFAction>();
884 actions.add(action);
885
886 fm.setIdleTimeout((short)0)
887 .setHardTimeout((short)0)
888 .setBufferId(OFPacketOut.BUFFER_ID_NONE)
889 .setCookie(BGP_COOKIE)
890 .setCommand(OFFlowMod.OFPFC_ADD)
891 .setPriority(SDNIP_PRIORITY)
892 .setActions(actions)
893 .setLengthU(OFFlowMod.MINIMUM_LENGTH+OFActionOutput.MINIMUM_LENGTH);
894
895 //Forward = gateway -> bgpd, reverse = bgpd -> gateway
896 OFMatch forwardMatchSrc = new OFMatch();
897
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200898 String interfaceCidrAddress = peerInterface.getIpAddress().getHostAddress()
899 + "/32";
900 String peerCidrAddress = bgpPeer.getIpAddress().getHostAddress()
901 + "/32";
Jonathan Hart38c84932013-08-10 17:49:27 +1200902
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200903 //Common match fields
904 forwardMatchSrc.setDataLayerType(Ethernet.TYPE_IPv4);
905 //forwardMatch.setWildcards(forwardMatch.getWildcards() & ~OFMatch.OFPFW_DL_TYPE);
906 forwardMatchSrc.setNetworkProtocol(IPv4.PROTOCOL_TCP);
907 forwardMatchSrc.setTransportDestination(BGP_PORT);
908 forwardMatchSrc.setWildcards(forwardMatchSrc.getWildcards() & ~OFMatch.OFPFW_IN_PORT
909 & ~OFMatch.OFPFW_DL_TYPE & ~OFMatch.OFPFW_NW_PROTO);
910
911
912 OFMatch reverseMatchSrc = forwardMatchSrc.clone();
913
914 forwardMatchSrc.setFromCIDR(peerCidrAddress, OFMatch.STR_NW_SRC);
915 forwardMatchSrc.setFromCIDR(interfaceCidrAddress, OFMatch.STR_NW_DST);
916
917 OFMatch forwardMatchDst = forwardMatchSrc.clone();
918
919 forwardMatchSrc.setTransportSource(BGP_PORT);
920 forwardMatchSrc.setWildcards(forwardMatchSrc.getWildcards() & ~OFMatch.OFPFW_TP_SRC);
921 forwardMatchDst.setTransportDestination(BGP_PORT);
922 forwardMatchDst.setWildcards(forwardMatchDst.getWildcards() & ~OFMatch.OFPFW_TP_DST);
923
924 reverseMatchSrc.setFromCIDR(interfaceCidrAddress, OFMatch.STR_NW_SRC);
925 reverseMatchSrc.setFromCIDR(peerCidrAddress, OFMatch.STR_NW_DST);
926
927 OFMatch reverseMatchDst = reverseMatchSrc.clone();
928
929 reverseMatchSrc.setTransportSource(BGP_PORT);
930 reverseMatchSrc.setWildcards(forwardMatchSrc.getWildcards() & ~OFMatch.OFPFW_TP_SRC);
931 reverseMatchDst.setTransportDestination(BGP_PORT);
932 reverseMatchDst.setWildcards(forwardMatchDst.getWildcards() & ~OFMatch.OFPFW_TP_DST);
933
934 fm.setMatch(forwardMatchSrc);
935
Jonathan Hart38c84932013-08-10 17:49:27 +1200936 OFMatch forwardIcmpMatch = new OFMatch();
937 forwardIcmpMatch.setDataLayerType(Ethernet.TYPE_IPv4);
938 forwardIcmpMatch.setNetworkProtocol(IPv4.PROTOCOL_ICMP);
939 forwardIcmpMatch.setWildcards(forwardIcmpMatch.getWildcards() &
940 ~OFMatch.OFPFW_DL_TYPE & ~OFMatch.OFPFW_NW_PROTO);
941
942 OFMatch reverseIcmpMatch = forwardIcmpMatch.clone();
943 forwardIcmpMatch.setFromCIDR(interfaceCidrAddress, OFMatch.STR_NW_DST);
944 reverseIcmpMatch.setFromCIDR(interfaceCidrAddress, OFMatch.STR_NW_SRC);
945
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200946 for (FlowEntry flowEntry : path.flowEntries()){
947 OFFlowMod forwardFlowModSrc, forwardFlowModDst;
948 OFFlowMod reverseFlowModSrc, reverseFlowModDst;
Jonathan Hart38c84932013-08-10 17:49:27 +1200949 OFFlowMod forwardIcmp, reverseIcmp;
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200950 try {
951 forwardFlowModSrc = fm.clone();
952 forwardFlowModDst = fm.clone();
953 reverseFlowModSrc = fm.clone();
954 reverseFlowModDst = fm.clone();
Jonathan Hart38c84932013-08-10 17:49:27 +1200955 forwardIcmp = fm.clone();
956 reverseIcmp = fm.clone();
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200957 } catch (CloneNotSupportedException e) {
958 log.warn("Clone failed", e);
959 continue;
960 }
961
962 forwardMatchSrc.setInputPort(flowEntry.inPort().value());
963 forwardFlowModSrc.setMatch(forwardMatchSrc);
964 ((OFActionOutput)forwardFlowModSrc.getActions().get(0))
965 .setPort(flowEntry.outPort().value());
966
967 forwardMatchDst.setInputPort(flowEntry.inPort().value());
968 forwardFlowModDst.setMatch(forwardMatchDst);
969 ((OFActionOutput)forwardFlowModDst.getActions().get(0))
970 .setPort(flowEntry.outPort().value());
971
972 reverseMatchSrc.setInputPort(flowEntry.outPort().value());
973 reverseFlowModSrc.setMatch(reverseMatchSrc);
974 ((OFActionOutput)reverseFlowModSrc.getActions().get(0))
975 .setPort(flowEntry.inPort().value());
976
977 reverseMatchDst.setInputPort(flowEntry.outPort().value());
978 reverseFlowModDst.setMatch(reverseMatchDst);
979 ((OFActionOutput)reverseFlowModDst.getActions().get(0))
980 .setPort(flowEntry.inPort().value());
981
Jonathan Hart38c84932013-08-10 17:49:27 +1200982 ((OFActionOutput)forwardIcmp.getActions().get(0))
983 .setPort(flowEntry.outPort().value());
984 forwardIcmp.setMatch(forwardIcmpMatch);
985
986 ((OFActionOutput)reverseIcmp.getActions().get(0))
987 .setPort(flowEntry.inPort().value());
988 reverseIcmp.setMatch(reverseIcmpMatch);
989
990
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200991 IOFSwitch sw = floodlightProvider.getSwitches().get(flowEntry.dpid().value());
992
Jonathan Hart38c84932013-08-10 17:49:27 +1200993 if (sw == null) {
994 log.warn("Switch not found when pushing BGP paths");
995 return;
996 }
997
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200998 List<OFMessage> msgList = new ArrayList<OFMessage>(2);
999 msgList.add(forwardFlowModSrc);
1000 msgList.add(forwardFlowModDst);
1001 msgList.add(reverseFlowModSrc);
1002 msgList.add(reverseFlowModDst);
Jonathan Hart38c84932013-08-10 17:49:27 +12001003 msgList.add(forwardIcmp);
1004 msgList.add(reverseIcmp);
Jonathan Hart832a7cb2013-06-24 11:25:35 +12001005
1006 try {
1007 sw.write(msgList, null);
1008 sw.flush();
1009 } catch (IOException e) {
1010 log.error("Failure writing flow mod", e);
1011 }
1012 }
1013 }
1014 }
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001015
Jonathan Hart4dfc3652013-08-02 20:22:36 +12001016 @Override
1017 public void arpResponse(InetAddress ipAddress, byte[] macAddress) {
1018 log.debug("Received ARP response: {} => {}", ipAddress.getHostAddress(),
1019 MACAddress.valueOf(macAddress).toString());
1020
1021 Set<PathUpdate> pathsToPush = pathsWaitingOnArp.removeAll(ipAddress);
1022
1023 for (PathUpdate update : pathsToPush) {
1024 log.debug("Pushing path to {} at {} on {}", new Object[] {
1025 update.getDstIpAddress().getHostAddress(),
1026 MACAddress.valueOf(macAddress),
1027 update.getDstInterface().getSwitchPort()});
1028 calculateAndPushPath(update.getDstInterface(),
1029 MACAddress.valueOf(macAddress));
1030 }
Jonathan Hart0ee0f022013-08-03 22:21:54 +12001031
1032 Set<RibUpdate> prefixesToPush = prefixesWaitingOnArp.removeAll(ipAddress);
1033
Jonathan Hart0a46fe42013-08-10 17:08:47 +12001034 /*
1035 * We synchronize on this to prevent changes to the ptree while we're pushing
1036 * flows to the switches. If the ptree changes, the ptree and switches
1037 * could get out of sync.
1038 */
1039 synchronized (this) {
1040 for (RibUpdate update : prefixesToPush) {
1041 //These will always be adds
1042
1043 //addPrefixFlows(update.getPrefix(), update.getRibEntry());
1044 //processRibAdd(update);
1045 Rib rib = ptree.lookup(update.getPrefix());
1046 if (rib != null && rib.equals(update.getRibEntry())) {
1047 log.debug("Pushing prefix {} next hop {}", update.getPrefix(),
1048 rib.nextHop.getHostAddress());
1049 //We only push prefix flows if the prefix is still in the ptree
1050 //and the next hop is the same as our update. The prefix could
1051 //have been removed while we were waiting for the ARP, or the
1052 //next hop could have changed.
1053 addPrefixFlows(update.getPrefix(), rib);
1054 } else {
1055 log.debug("Received ARP response, but {},{} is no longer in ptree",
1056 update.getPrefix(), update.getRibEntry());
1057 }
1058 }
Jonathan Hart0ee0f022013-08-03 22:21:54 +12001059 }
Jonathan Hart4dfc3652013-08-02 20:22:36 +12001060 }
1061
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001062 private void beginRouting(){
1063 log.debug("Topology is now ready, beginning routing function");
Jonathan Hart832a7cb2013-06-24 11:25:35 +12001064 setupBgpPaths();
Jonathan Hart98957bf2013-07-01 14:49:24 +12001065 setupFullMesh();
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001066
Jonathan Hart832a7cb2013-06-24 11:25:35 +12001067 //Traverse ptree and create flows for all routes
Jonathan Hartd7e158d2013-08-07 23:04:48 +12001068 /*
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001069 for (PtreeNode node = ptree.begin(); node != null; node = ptree.next(node)){
1070 if (node.rib != null){
1071 prefixAdded(node);
1072 }
1073 }
Jonathan Hartd7e158d2013-08-07 23:04:48 +12001074 */
1075
Jonathan Hart0a46fe42013-08-10 17:08:47 +12001076 /*
Jonathan Hartd7e158d2013-08-07 23:04:48 +12001077 synchronized (ptree) {
1078 Iterator<IPatriciaTrie.Entry> it = ptree.iterator();
1079 while (it.hasNext()) {
1080 IPatriciaTrie.Entry entry = it.next();
1081 addPrefixFlows(entry.getPrefix(), entry.getRib());
1082 }
1083 }
Jonathan Hart0a46fe42013-08-10 17:08:47 +12001084 */
1085
1086 bgpUpdatesExecutor.execute(new Runnable() {
1087 @Override
1088 public void run() {
1089 doUpdatesThread();
1090 }
1091 });
Jonathan Hartd7e158d2013-08-07 23:04:48 +12001092
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001093 }
1094
1095 private void checkSwitchesConnected(){
1096 for (String dpid : switches){
1097 if (floodlightProvider.getSwitches().get(HexString.toLong(dpid)) == null){
1098 log.debug("Not all switches are here yet");
1099 return;
1100 }
1101 }
1102 switchesConnected = true;
1103 }
1104
Jonathan Hartc824ad02013-07-03 15:58:45 +12001105 //Actually we only need to go half way round to verify full mesh connectivity
1106 //(n^2)/2
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001107 private void checkTopologyReady(){
Jonathan Hartc824ad02013-07-03 15:58:45 +12001108 for (Interface dstInterface : interfaces.values()) {
1109 for (Interface srcInterface : interfaces.values()) {
1110 if (dstInterface == srcInterface) {
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001111 continue;
1112 }
1113
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001114 DataPath shortestPath = topoRouteService.getShortestPath(
Jonathan Hartc824ad02013-07-03 15:58:45 +12001115 srcInterface.getSwitchPort(), dstInterface.getSwitchPort());
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001116
1117 if (shortestPath == null){
1118 log.debug("Shortest path between {} and {} not found",
Jonathan Hartc824ad02013-07-03 15:58:45 +12001119 srcInterface.getSwitchPort(), dstInterface.getSwitchPort());
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001120 return;
1121 }
1122 }
1123 }
1124 topologyReady = true;
1125 }
1126
1127 private void checkStatus(){
1128 log.debug("In checkStatus, swC {}, toRe {}", switchesConnected, topologyReady);
1129
1130 if (!switchesConnected){
1131 checkSwitchesConnected();
1132 }
1133 boolean oldTopologyReadyStatus = topologyReady;
1134 if (switchesConnected && !topologyReady){
1135 checkTopologyReady();
1136 }
1137 if (!oldTopologyReadyStatus && topologyReady){
1138 beginRouting();
1139 }
1140 }
1141
pingping-lina2cbfad2013-03-07 08:39:21 +08001142 @Override
1143 public void startUp(FloodlightModuleContext context) {
pingping-line2a09ca2013-03-23 09:33:58 +08001144 restApi.addRestletRoutable(new BgpRouteWebRoutable());
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001145 floodlightProvider.addOFSwitchListener(this);
Jonathan Hart61ba9372013-05-19 20:10:29 -07001146 topology.addListener(this);
pingping-line2a09ca2013-03-23 09:33:58 +08001147
Jonathan Hartc7ca35d2013-06-25 20:54:25 +12001148 floodlightProvider.addOFMessageListener(OFType.PACKET_IN, proxyArp);
1149
Jonathan Hart61ba9372013-05-19 20:10:29 -07001150 //Retrieve the RIB from BGPd during startup
1151 retrieveRib();
pingping-lina2cbfad2013-03-07 08:39:21 +08001152 }
Jonathan Hart8b9349e2013-07-26 15:55:28 +12001153
1154 private void doUpdatesThread() {
1155 boolean interrupted = false;
1156 try {
1157 while (true) {
1158 try {
1159 RibUpdate update = ribUpdates.take();
1160 switch (update.getOperation()){
1161 case UPDATE:
Jonathan Hart2f740782013-08-04 00:49:21 +12001162 processRibAdd(update);
Jonathan Hart8b9349e2013-07-26 15:55:28 +12001163 break;
1164 case DELETE:
Jonathan Hart2f740782013-08-04 00:49:21 +12001165 processRibDelete(update);
Jonathan Hart8b9349e2013-07-26 15:55:28 +12001166 break;
1167 }
1168 } catch (InterruptedException e) {
1169 interrupted = true;
1170 }
1171 }
1172 } finally {
1173 if (interrupted) {
1174 Thread.currentThread().interrupt();
1175 }
1176 }
1177 }
pingping-lina2cbfad2013-03-07 08:39:21 +08001178
1179 @Override
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001180 public void topologyChanged() {
1181 //There seems to be more topology events than there should be. Lots of link
1182 //updated, port up and switch updated on what should be a fairly static topology
pingping-lina2cbfad2013-03-07 08:39:21 +08001183
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001184 boolean refreshNeeded = false;
1185 for (LDUpdate ldu : topology.getLastLinkUpdates()){
1186 if (!ldu.getOperation().equals(ILinkDiscovery.UpdateOperation.LINK_UPDATED)){
1187 //We don't need to recalculate anything for just link updates
1188 //They happen way too frequently (may be a bug in our link discovery)
1189 refreshNeeded = true;
1190 }
Jonathan Hart98957bf2013-07-01 14:49:24 +12001191
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001192 log.debug("Topo change {}", ldu.getOperation());
Jonathan Hartc824ad02013-07-03 15:58:45 +12001193
Jonathan Hart98957bf2013-07-01 14:49:24 +12001194 if (ldu.getOperation().equals(ILinkDiscovery.UpdateOperation.LINK_ADDED)){
1195 synchronized (linkUpdates) {
1196 linkUpdates.add(ldu);
1197 }
1198 }
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001199 }
1200
1201 if (refreshNeeded){
Jonathan Hart98957bf2013-07-01 14:49:24 +12001202 topologyChangeDetectorTask.reschedule(TOPO_DETECTION_WAIT, TimeUnit.SECONDS);
pingping-lina2cbfad2013-03-07 08:39:21 +08001203 }
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001204 }
pingping-lina2cbfad2013-03-07 08:39:21 +08001205
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001206 //TODO determine whether we need to listen for switch joins
1207 @Override
1208 public void addedSwitch(IOFSwitch sw) {
1209 //checkStatus();
1210 }
1211
1212 @Override
1213 public void removedSwitch(IOFSwitch sw) {
1214 // TODO Auto-generated method stub
1215 }
1216
1217 @Override
1218 public void switchPortChanged(Long switchId) {}
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001219
1220 @Override
1221 public String getName() {
1222 return "BgpRoute";
pingping-lina2cbfad2013-03-07 08:39:21 +08001223 }
1224}