blob: 1b55cd65ba51fd7a8991ad01ca0cd9f3eebc0f1b [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 /*
Jonathan Hartb39a67d2013-08-10 23:59:50 +1200337 public RibEntry lookupRib(byte[] dest) {
pingping-lina2cbfad2013-03-07 08:39:21 +0800338 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 Hartb39a67d2013-08-10 23:59:50 +1200473 RibEntry rib = new RibEntry(router_id, nexthop);
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());
Jonathan Hartb39a67d2013-08-10 23:59:50 +1200504 RibEntry 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 Hartb39a67d2013-08-10 23:59:50 +1200571 private void addPrefixFlows(Prefix prefix, RibEntry 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 Hartb39a67d2013-08-10 23:59:50 +1200581 log.debug("New prefix {} added, next hop {}",
582 prefix, rib.getNextHop().getHostAddress());
Jonathan Hart1236a9b2013-06-18 22:10:05 +1200583
Jonathan Hartc824ad02013-07-03 15:58:45 +1200584 //TODO this is wrong, we shouldn't be dealing with BGP peers here.
Jonathan Hart6261dcd2013-07-22 17:58:35 +1200585 //We need to figure out where the device is attached and what its
Jonathan Hartc824ad02013-07-03 15:58:45 +1200586 //mac address is by learning.
587 //The next hop is not necessarily the peer, and the peer's attachment
588 //point is not necessarily the next hop's attachment point.
Jonathan Hartb39a67d2013-08-10 23:59:50 +1200589 BgpPeer peer = bgpPeers.get(rib.getNextHop());
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700590
Jonathan Hartc824ad02013-07-03 15:58:45 +1200591 if (peer == null){
592 //TODO local router isn't in peers list so this will get thrown
Jonathan Hart50a8d1e2013-06-06 16:00:47 +1200593 //Need to work out what to do about local prefixes with next hop 0.0.0.0.
Jonathan Hartc824ad02013-07-03 15:58:45 +1200594
595 //The other scenario is this is a route server route. In that
596 //case the next hop is not in our configuration
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200597 log.error("Couldn't find next hop router in router {} in config",
Jonathan Hartb39a67d2013-08-10 23:59:50 +1200598 rib.getNextHop().getHostAddress());
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700599 return; //just quit out here? This is probably a configuration error
600 }
Jonathan Hartc824ad02013-07-03 15:58:45 +1200601
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200602 //Get MAC address for peer from the ARP module
603 //TODO separate out the 'ask for MAC' bit to another method
604 byte[] peerMacAddress = proxyArp.getMacAddress(peer.getIpAddress());
605 if (peerMacAddress == null) {
Jonathan Hart2f740782013-08-04 00:49:21 +1200606 //A RibUpdate is still a nice way to package them up
607 prefixesWaitingOnArp.put(peer.getIpAddress(),
608 new RibUpdate(Operation.UPDATE, prefix, rib));
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200609 proxyArp.sendArpRequest(peer.getIpAddress(), this, true);
610 return;
611 }
612
Jonathan Hartc824ad02013-07-03 15:58:45 +1200613 Interface peerInterface = interfaces.get(peer.getInterfaceName());
Jonathan Hart50a8d1e2013-06-06 16:00:47 +1200614
Jonathan Hartc824ad02013-07-03 15:58:45 +1200615 //Add a flow to rewrite mac for this prefix to all border switches
616 for (Interface srcInterface : interfaces.values()) {
617 if (srcInterface == peerInterface) {
618 //Don't push a flow for the switch where this peer is attached
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700619 continue;
620 }
Jonathan Hartc824ad02013-07-03 15:58:45 +1200621
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700622 DataPath shortestPath = topoRouteService.getShortestPath(
Jonathan Hartc824ad02013-07-03 15:58:45 +1200623 srcInterface.getSwitchPort(),
624 peerInterface.getSwitchPort());
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700625
626 if (shortestPath == null){
627 log.debug("Shortest path between {} and {} not found",
Jonathan Hartc824ad02013-07-03 15:58:45 +1200628 srcInterface.getSwitchPort(),
629 peerInterface.getSwitchPort());
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700630 return; // just quit here?
631 }
632
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700633 //Set up the flow mod
634 OFFlowMod fm =
635 (OFFlowMod) floodlightProvider.getOFMessageFactory()
636 .getMessage(OFType.FLOW_MOD);
637
638 fm.setIdleTimeout((short)0)
639 .setHardTimeout((short)0)
640 .setBufferId(OFPacketOut.BUFFER_ID_NONE)
641 .setCookie(MAC_RW_COOKIE)
642 .setCommand(OFFlowMod.OFPFC_ADD)
Jonathan Hart50a8d1e2013-06-06 16:00:47 +1200643 .setPriority(SDNIP_PRIORITY)
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700644 .setLengthU(OFFlowMod.MINIMUM_LENGTH
645 + OFActionDataLayerDestination.MINIMUM_LENGTH
646 + OFActionOutput.MINIMUM_LENGTH);
647
648 OFMatch match = new OFMatch();
649 match.setDataLayerType(Ethernet.TYPE_IPv4);
Jonathan Hart50a8d1e2013-06-06 16:00:47 +1200650 match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_TYPE);
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700651
Jonathan Hart0a46fe42013-08-10 17:08:47 +1200652 /*
Jonathan Hart50a8d1e2013-06-06 16:00:47 +1200653 InetAddress address = null;
654 try {
Jonathan Hart2f740782013-08-04 00:49:21 +1200655 address = InetAddress.getByAddress(prefix.getAddress());
Jonathan Hart50a8d1e2013-06-06 16:00:47 +1200656 } catch (UnknownHostException e1) {
657 //Should never happen is the reverse conversion has already been done
658 log.error("Malformed IP address");
659 return;
Jonathan Hart0a46fe42013-08-10 17:08:47 +1200660 }*/
Jonathan Hart50a8d1e2013-06-06 16:00:47 +1200661
Jonathan Hart0a46fe42013-08-10 17:08:47 +1200662 //match.setFromCIDR(address.getHostAddress() + "/" +
663 // prefix.getPrefixLength(), OFMatch.STR_NW_DST);
664 match.setFromCIDR(prefix.toString(), OFMatch.STR_NW_DST);
Jonathan Hart50a8d1e2013-06-06 16:00:47 +1200665 fm.setMatch(match);
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700666
667 //Set up MAC rewrite action
668 OFActionDataLayerDestination macRewriteAction = new OFActionDataLayerDestination();
Jonathan Hartc824ad02013-07-03 15:58:45 +1200669 //TODO the peer's mac address is not necessarily the next hop's...
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200670 macRewriteAction.setDataLayerAddress(peerMacAddress);
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700671
672 //Set up output action
673 OFActionOutput outputAction = new OFActionOutput();
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200674 outputAction.setMaxLength((short)0xffff);
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700675
Jonathan Hart50a8d1e2013-06-06 16:00:47 +1200676 Port outputPort = shortestPath.flowEntries().get(0).outPort();
677 outputAction.setPort(outputPort.value());
678
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700679 List<OFAction> actions = new ArrayList<OFAction>();
680 actions.add(macRewriteAction);
681 actions.add(outputAction);
682 fm.setActions(actions);
683
684 //Write to switch
685 IOFSwitch sw = floodlightProvider.getSwitches()
Jonathan Hartc824ad02013-07-03 15:58:45 +1200686 .get(srcInterface.getDpid());
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700687
688 if (sw == null){
689 log.warn("Switch not found when pushing flow mod");
690 continue;
691 }
692
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200693 //TODO if prefix Added/Deleted are synchronized this shouldn't have to be
Jonathan Hart2f740782013-08-04 00:49:21 +1200694 pushedFlows.put(prefix, new PushedFlowMod(sw.getId(), fm));
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200695
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700696 List<OFMessage> msglist = new ArrayList<OFMessage>();
697 msglist.add(fm);
698 try {
699 sw.write(msglist, null);
700 sw.flush();
701 } catch (IOException e) {
702 log.error("Failure writing flow mod", e);
703 }
704 }
705 }
706
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200707 //TODO test next-hop changes
Jonathan Hart2f740782013-08-04 00:49:21 +1200708 //TODO check delete/add synchronization
Jonathan Hart2f740782013-08-04 00:49:21 +1200709
710 private void deletePrefixFlows(Prefix prefix) {
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200711 if (!topologyReady) {
712 return;
713 }
714
Jonathan Hartdf6ec332013-08-04 01:37:14 +1200715 log.debug("In deletePrefixFlows for {}", prefix);
Jonathan Hart2f740782013-08-04 00:49:21 +1200716
717 /*for (Map.Entry<Prefix, PushedFlowMod> entry : pushedFlows.entries()) {
718 log.debug("Pushed flow: {} => {}", entry.getKey(), entry.getValue());
719 }*/
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200720
721 Collection<PushedFlowMod> pushedFlowMods
Jonathan Hart2f740782013-08-04 00:49:21 +1200722 = pushedFlows.removeAll(prefix);
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200723
724 for (PushedFlowMod pfm : pushedFlowMods) {
725 log.debug("Pushing a DELETE flow mod to {}, matches prefix {} with mac-rewrite {}",
726 new Object[] {HexString.toHexString(pfm.getDpid()),
727 pfm.getFlowMod().getMatch().getNetworkDestination() +
728 pfm.getFlowMod().getMatch().getNetworkDestinationMaskLen(),
729 HexString.toHexString(((OFActionDataLayerDestination)pfm.getFlowMod().getActions().get(0))
730 .getDataLayerAddress())});
731
732 OFFlowMod fm = pfm.getFlowMod();
733
734 fm.setCommand(OFFlowMod.OFPFC_DELETE)
Jonathan Hart2f740782013-08-04 00:49:21 +1200735 .setOutPort(OFPort.OFPP_NONE)
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200736 .setLengthU(OFFlowMod.MINIMUM_LENGTH);
737
738 fm.getActions().clear();
739
740 IOFSwitch sw = floodlightProvider.getSwitches().get(pfm.getDpid());
741 if (sw == null) {
742 log.warn("Switch not found when pushing delete flow mod");
743 continue;
744 }
745
746 try {
747 sw.write(fm, null);
748 sw.flush();
749 } catch (IOException e) {
750 log.error("Failure writing flow mod", e);
751 }
752 }
753 }
754
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700755 /*
756 * On startup we need to calculate a full mesh of paths between all gateway
757 * switches
758 */
Jonathan Hart1236a9b2013-06-18 22:10:05 +1200759 private void setupFullMesh(){
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700760 //For each border router, calculate and install a path from every other
761 //border switch to said border router. However, don't install the entry
762 //in to the first hop switch, as we need to install an entry to rewrite
763 //for each prefix received. This will be done later when prefixes have
764 //actually been received.
765
Jonathan Hartc824ad02013-07-03 15:58:45 +1200766 for (BgpPeer peer : bgpPeers.values()) {
767 Interface peerInterface = interfaces.get(peer.getInterfaceName());
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200768
769 //See if we know the MAC address of the peer. If not we can't
770 //do anything until we learn it
771 byte[] mac = proxyArp.getMacAddress(peer.getIpAddress());
772 if (mac == null) {
773 log.debug("Don't know MAC for {}", peer.getIpAddress().getHostAddress());
774 //Put in the pending paths list first
775 pathsWaitingOnArp.put(peer.getIpAddress(),
776 new PathUpdate(peerInterface, peer.getIpAddress()));
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700777
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200778 proxyArp.sendArpRequest(peer.getIpAddress(), this, true);
779 continue;
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700780 }
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200781
782 //If we know the MAC, lets go ahead and push the paths to this peer
783 calculateAndPushPath(peerInterface, MACAddress.valueOf(mac));
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700784 }
785 }
786
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200787 private void calculateAndPushPath(Interface dstInterface, MACAddress dstMacAddress) {
788 for (Interface srcInterface : interfaces.values()) {
789 if (dstInterface.equals(srcInterface.getName())){
790 continue;
791 }
792
793 DataPath shortestPath = topoRouteService.getShortestPath(
794 srcInterface.getSwitchPort(), dstInterface.getSwitchPort());
795
796 if (shortestPath == null){
797 log.debug("Shortest path between {} and {} not found",
798 srcInterface.getSwitchPort(), dstInterface.getSwitchPort());
799 return; // just quit here?
800 }
801
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200802 installPath(shortestPath.flowEntries(), dstMacAddress);
803 }
804 }
805
806 private void installPath(List<FlowEntry> flowEntries, MACAddress dstMacAddress){
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700807 //Set up the flow mod
808 OFFlowMod fm =
809 (OFFlowMod) floodlightProvider.getOFMessageFactory()
810 .getMessage(OFType.FLOW_MOD);
811
812 OFActionOutput action = new OFActionOutput();
813 action.setMaxLength((short)0xffff);
814 List<OFAction> actions = new ArrayList<OFAction>();
815 actions.add(action);
816
817 fm.setIdleTimeout((short)0)
818 .setHardTimeout((short)0)
819 .setBufferId(OFPacketOut.BUFFER_ID_NONE)
820 .setCookie(L2_FWD_COOKIE)
821 .setCommand(OFFlowMod.OFPFC_ADD)
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700822 .setActions(actions)
823 .setLengthU(OFFlowMod.MINIMUM_LENGTH+OFActionOutput.MINIMUM_LENGTH);
824
825 //Don't push the first flow entry. We need to push entries in the
826 //first switch based on IP prefix which we don't know yet.
827 for (int i = 1; i < flowEntries.size(); i++){
828 FlowEntry flowEntry = flowEntries.get(i);
829
830 OFMatch match = new OFMatch();
Jonathan Hartc824ad02013-07-03 15:58:45 +1200831 //TODO Again using MAC address from configuration
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200832 match.setDataLayerDestination(dstMacAddress.toBytes());
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700833 match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_DST);
834 ((OFActionOutput) fm.getActions().get(0)).setPort(flowEntry.outPort().value());
835
836 fm.setMatch(match);
837
838 IOFSwitch sw = floodlightProvider.getSwitches().get(flowEntry.dpid().value());
839
840 if (sw == null){
841 log.warn("Switch not found when pushing flow mod");
842 continue;
843 }
844
845 List<OFMessage> msglist = new ArrayList<OFMessage>();
846 msglist.add(fm);
847 try {
848 sw.write(msglist, null);
849 sw.flush();
850 } catch (IOException e) {
851 log.error("Failure writing flow mod", e);
852 }
853
854 try {
855 fm = fm.clone();
856 } catch (CloneNotSupportedException e1) {
857 log.error("Failure cloning flow mod", e1);
858 }
859 }
860 }
861
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200862 private void setupBgpPaths(){
Jonathan Hartc824ad02013-07-03 15:58:45 +1200863 for (BgpPeer bgpPeer : bgpPeers.values()){
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200864 Interface peerInterface = interfaces.get(bgpPeer.getInterfaceName());
865
866 DataPath path = topoRouteService.getShortestPath(
867 peerInterface.getSwitchPort(), bgpdAttachmentPoint);
868
869 if (path == null){
870 log.debug("Unable to compute path for BGP traffic for {}",
871 bgpPeer.getIpAddress());
872 continue;
873 }
874
875 //Set up the flow mod
876 OFFlowMod fm =
877 (OFFlowMod) floodlightProvider.getOFMessageFactory()
878 .getMessage(OFType.FLOW_MOD);
879
880 OFActionOutput action = new OFActionOutput();
881 action.setMaxLength((short)0xffff);
882 List<OFAction> actions = new ArrayList<OFAction>();
883 actions.add(action);
884
885 fm.setIdleTimeout((short)0)
886 .setHardTimeout((short)0)
887 .setBufferId(OFPacketOut.BUFFER_ID_NONE)
888 .setCookie(BGP_COOKIE)
889 .setCommand(OFFlowMod.OFPFC_ADD)
890 .setPriority(SDNIP_PRIORITY)
891 .setActions(actions)
892 .setLengthU(OFFlowMod.MINIMUM_LENGTH+OFActionOutput.MINIMUM_LENGTH);
893
894 //Forward = gateway -> bgpd, reverse = bgpd -> gateway
895 OFMatch forwardMatchSrc = new OFMatch();
896
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200897 String interfaceCidrAddress = peerInterface.getIpAddress().getHostAddress()
898 + "/32";
899 String peerCidrAddress = bgpPeer.getIpAddress().getHostAddress()
900 + "/32";
Jonathan Hart38c84932013-08-10 17:49:27 +1200901
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200902 //Common match fields
903 forwardMatchSrc.setDataLayerType(Ethernet.TYPE_IPv4);
904 //forwardMatch.setWildcards(forwardMatch.getWildcards() & ~OFMatch.OFPFW_DL_TYPE);
905 forwardMatchSrc.setNetworkProtocol(IPv4.PROTOCOL_TCP);
906 forwardMatchSrc.setTransportDestination(BGP_PORT);
907 forwardMatchSrc.setWildcards(forwardMatchSrc.getWildcards() & ~OFMatch.OFPFW_IN_PORT
908 & ~OFMatch.OFPFW_DL_TYPE & ~OFMatch.OFPFW_NW_PROTO);
909
910
911 OFMatch reverseMatchSrc = forwardMatchSrc.clone();
912
913 forwardMatchSrc.setFromCIDR(peerCidrAddress, OFMatch.STR_NW_SRC);
914 forwardMatchSrc.setFromCIDR(interfaceCidrAddress, OFMatch.STR_NW_DST);
915
916 OFMatch forwardMatchDst = forwardMatchSrc.clone();
917
918 forwardMatchSrc.setTransportSource(BGP_PORT);
919 forwardMatchSrc.setWildcards(forwardMatchSrc.getWildcards() & ~OFMatch.OFPFW_TP_SRC);
920 forwardMatchDst.setTransportDestination(BGP_PORT);
921 forwardMatchDst.setWildcards(forwardMatchDst.getWildcards() & ~OFMatch.OFPFW_TP_DST);
922
923 reverseMatchSrc.setFromCIDR(interfaceCidrAddress, OFMatch.STR_NW_SRC);
924 reverseMatchSrc.setFromCIDR(peerCidrAddress, OFMatch.STR_NW_DST);
925
926 OFMatch reverseMatchDst = reverseMatchSrc.clone();
927
928 reverseMatchSrc.setTransportSource(BGP_PORT);
929 reverseMatchSrc.setWildcards(forwardMatchSrc.getWildcards() & ~OFMatch.OFPFW_TP_SRC);
930 reverseMatchDst.setTransportDestination(BGP_PORT);
931 reverseMatchDst.setWildcards(forwardMatchDst.getWildcards() & ~OFMatch.OFPFW_TP_DST);
932
933 fm.setMatch(forwardMatchSrc);
934
Jonathan Hart38c84932013-08-10 17:49:27 +1200935 OFMatch forwardIcmpMatch = new OFMatch();
936 forwardIcmpMatch.setDataLayerType(Ethernet.TYPE_IPv4);
937 forwardIcmpMatch.setNetworkProtocol(IPv4.PROTOCOL_ICMP);
938 forwardIcmpMatch.setWildcards(forwardIcmpMatch.getWildcards() &
939 ~OFMatch.OFPFW_DL_TYPE & ~OFMatch.OFPFW_NW_PROTO);
940
941 OFMatch reverseIcmpMatch = forwardIcmpMatch.clone();
942 forwardIcmpMatch.setFromCIDR(interfaceCidrAddress, OFMatch.STR_NW_DST);
943 reverseIcmpMatch.setFromCIDR(interfaceCidrAddress, OFMatch.STR_NW_SRC);
944
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200945 for (FlowEntry flowEntry : path.flowEntries()){
946 OFFlowMod forwardFlowModSrc, forwardFlowModDst;
947 OFFlowMod reverseFlowModSrc, reverseFlowModDst;
Jonathan Hart38c84932013-08-10 17:49:27 +1200948 OFFlowMod forwardIcmp, reverseIcmp;
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200949 try {
950 forwardFlowModSrc = fm.clone();
951 forwardFlowModDst = fm.clone();
952 reverseFlowModSrc = fm.clone();
953 reverseFlowModDst = fm.clone();
Jonathan Hart38c84932013-08-10 17:49:27 +1200954 forwardIcmp = fm.clone();
955 reverseIcmp = fm.clone();
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200956 } catch (CloneNotSupportedException e) {
957 log.warn("Clone failed", e);
958 continue;
959 }
960
961 forwardMatchSrc.setInputPort(flowEntry.inPort().value());
962 forwardFlowModSrc.setMatch(forwardMatchSrc);
963 ((OFActionOutput)forwardFlowModSrc.getActions().get(0))
964 .setPort(flowEntry.outPort().value());
965
966 forwardMatchDst.setInputPort(flowEntry.inPort().value());
967 forwardFlowModDst.setMatch(forwardMatchDst);
968 ((OFActionOutput)forwardFlowModDst.getActions().get(0))
969 .setPort(flowEntry.outPort().value());
970
971 reverseMatchSrc.setInputPort(flowEntry.outPort().value());
972 reverseFlowModSrc.setMatch(reverseMatchSrc);
973 ((OFActionOutput)reverseFlowModSrc.getActions().get(0))
974 .setPort(flowEntry.inPort().value());
975
976 reverseMatchDst.setInputPort(flowEntry.outPort().value());
977 reverseFlowModDst.setMatch(reverseMatchDst);
978 ((OFActionOutput)reverseFlowModDst.getActions().get(0))
979 .setPort(flowEntry.inPort().value());
980
Jonathan Hart38c84932013-08-10 17:49:27 +1200981 ((OFActionOutput)forwardIcmp.getActions().get(0))
982 .setPort(flowEntry.outPort().value());
983 forwardIcmp.setMatch(forwardIcmpMatch);
984
985 ((OFActionOutput)reverseIcmp.getActions().get(0))
986 .setPort(flowEntry.inPort().value());
987 reverseIcmp.setMatch(reverseIcmpMatch);
988
989
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200990 IOFSwitch sw = floodlightProvider.getSwitches().get(flowEntry.dpid().value());
991
Jonathan Hart38c84932013-08-10 17:49:27 +1200992 if (sw == null) {
993 log.warn("Switch not found when pushing BGP paths");
994 return;
995 }
996
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200997 List<OFMessage> msgList = new ArrayList<OFMessage>(2);
998 msgList.add(forwardFlowModSrc);
999 msgList.add(forwardFlowModDst);
1000 msgList.add(reverseFlowModSrc);
1001 msgList.add(reverseFlowModDst);
Jonathan Hart38c84932013-08-10 17:49:27 +12001002 msgList.add(forwardIcmp);
1003 msgList.add(reverseIcmp);
Jonathan Hart832a7cb2013-06-24 11:25:35 +12001004
1005 try {
1006 sw.write(msgList, null);
1007 sw.flush();
1008 } catch (IOException e) {
1009 log.error("Failure writing flow mod", e);
1010 }
1011 }
1012 }
1013 }
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001014
Jonathan Hart4dfc3652013-08-02 20:22:36 +12001015 @Override
1016 public void arpResponse(InetAddress ipAddress, byte[] macAddress) {
1017 log.debug("Received ARP response: {} => {}", ipAddress.getHostAddress(),
1018 MACAddress.valueOf(macAddress).toString());
1019
1020 Set<PathUpdate> pathsToPush = pathsWaitingOnArp.removeAll(ipAddress);
1021
1022 for (PathUpdate update : pathsToPush) {
1023 log.debug("Pushing path to {} at {} on {}", new Object[] {
1024 update.getDstIpAddress().getHostAddress(),
1025 MACAddress.valueOf(macAddress),
1026 update.getDstInterface().getSwitchPort()});
1027 calculateAndPushPath(update.getDstInterface(),
1028 MACAddress.valueOf(macAddress));
1029 }
Jonathan Hart0ee0f022013-08-03 22:21:54 +12001030
1031 Set<RibUpdate> prefixesToPush = prefixesWaitingOnArp.removeAll(ipAddress);
1032
Jonathan Hart0a46fe42013-08-10 17:08:47 +12001033 /*
1034 * We synchronize on this to prevent changes to the ptree while we're pushing
1035 * flows to the switches. If the ptree changes, the ptree and switches
1036 * could get out of sync.
1037 */
1038 synchronized (this) {
1039 for (RibUpdate update : prefixesToPush) {
1040 //These will always be adds
1041
1042 //addPrefixFlows(update.getPrefix(), update.getRibEntry());
1043 //processRibAdd(update);
Jonathan Hartb39a67d2013-08-10 23:59:50 +12001044 RibEntry rib = ptree.lookup(update.getPrefix());
Jonathan Hart0a46fe42013-08-10 17:08:47 +12001045 if (rib != null && rib.equals(update.getRibEntry())) {
1046 log.debug("Pushing prefix {} next hop {}", update.getPrefix(),
Jonathan Hartb39a67d2013-08-10 23:59:50 +12001047 rib.getNextHop().getHostAddress());
Jonathan Hart0a46fe42013-08-10 17:08:47 +12001048 //We only push prefix flows if the prefix is still in the ptree
1049 //and the next hop is the same as our update. The prefix could
1050 //have been removed while we were waiting for the ARP, or the
1051 //next hop could have changed.
1052 addPrefixFlows(update.getPrefix(), rib);
1053 } else {
1054 log.debug("Received ARP response, but {},{} is no longer in ptree",
1055 update.getPrefix(), update.getRibEntry());
1056 }
1057 }
Jonathan Hart0ee0f022013-08-03 22:21:54 +12001058 }
Jonathan Hart4dfc3652013-08-02 20:22:36 +12001059 }
1060
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001061 private void beginRouting(){
1062 log.debug("Topology is now ready, beginning routing function");
Jonathan Hart832a7cb2013-06-24 11:25:35 +12001063 setupBgpPaths();
Jonathan Hart98957bf2013-07-01 14:49:24 +12001064 setupFullMesh();
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001065
Jonathan Hart832a7cb2013-06-24 11:25:35 +12001066 //Traverse ptree and create flows for all routes
Jonathan Hartd7e158d2013-08-07 23:04:48 +12001067 /*
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001068 for (PtreeNode node = ptree.begin(); node != null; node = ptree.next(node)){
1069 if (node.rib != null){
1070 prefixAdded(node);
1071 }
1072 }
Jonathan Hartd7e158d2013-08-07 23:04:48 +12001073 */
1074
Jonathan Hart0a46fe42013-08-10 17:08:47 +12001075 /*
Jonathan Hartd7e158d2013-08-07 23:04:48 +12001076 synchronized (ptree) {
1077 Iterator<IPatriciaTrie.Entry> it = ptree.iterator();
1078 while (it.hasNext()) {
1079 IPatriciaTrie.Entry entry = it.next();
1080 addPrefixFlows(entry.getPrefix(), entry.getRib());
1081 }
1082 }
Jonathan Hart0a46fe42013-08-10 17:08:47 +12001083 */
1084
1085 bgpUpdatesExecutor.execute(new Runnable() {
1086 @Override
1087 public void run() {
1088 doUpdatesThread();
1089 }
1090 });
Jonathan Hartd7e158d2013-08-07 23:04:48 +12001091
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001092 }
1093
1094 private void checkSwitchesConnected(){
1095 for (String dpid : switches){
1096 if (floodlightProvider.getSwitches().get(HexString.toLong(dpid)) == null){
1097 log.debug("Not all switches are here yet");
1098 return;
1099 }
1100 }
1101 switchesConnected = true;
1102 }
1103
Jonathan Hartc824ad02013-07-03 15:58:45 +12001104 //Actually we only need to go half way round to verify full mesh connectivity
1105 //(n^2)/2
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001106 private void checkTopologyReady(){
Jonathan Hartc824ad02013-07-03 15:58:45 +12001107 for (Interface dstInterface : interfaces.values()) {
1108 for (Interface srcInterface : interfaces.values()) {
1109 if (dstInterface == srcInterface) {
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001110 continue;
1111 }
1112
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001113 DataPath shortestPath = topoRouteService.getShortestPath(
Jonathan Hartc824ad02013-07-03 15:58:45 +12001114 srcInterface.getSwitchPort(), dstInterface.getSwitchPort());
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001115
1116 if (shortestPath == null){
1117 log.debug("Shortest path between {} and {} not found",
Jonathan Hartc824ad02013-07-03 15:58:45 +12001118 srcInterface.getSwitchPort(), dstInterface.getSwitchPort());
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001119 return;
1120 }
1121 }
1122 }
1123 topologyReady = true;
1124 }
1125
1126 private void checkStatus(){
1127 log.debug("In checkStatus, swC {}, toRe {}", switchesConnected, topologyReady);
1128
1129 if (!switchesConnected){
1130 checkSwitchesConnected();
1131 }
1132 boolean oldTopologyReadyStatus = topologyReady;
1133 if (switchesConnected && !topologyReady){
1134 checkTopologyReady();
1135 }
1136 if (!oldTopologyReadyStatus && topologyReady){
1137 beginRouting();
1138 }
1139 }
1140
pingping-lina2cbfad2013-03-07 08:39:21 +08001141 @Override
1142 public void startUp(FloodlightModuleContext context) {
pingping-line2a09ca2013-03-23 09:33:58 +08001143 restApi.addRestletRoutable(new BgpRouteWebRoutable());
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001144 floodlightProvider.addOFSwitchListener(this);
Jonathan Hart61ba9372013-05-19 20:10:29 -07001145 topology.addListener(this);
pingping-line2a09ca2013-03-23 09:33:58 +08001146
Jonathan Hartc7ca35d2013-06-25 20:54:25 +12001147 floodlightProvider.addOFMessageListener(OFType.PACKET_IN, proxyArp);
1148
Jonathan Hart61ba9372013-05-19 20:10:29 -07001149 //Retrieve the RIB from BGPd during startup
1150 retrieveRib();
pingping-lina2cbfad2013-03-07 08:39:21 +08001151 }
Jonathan Hart8b9349e2013-07-26 15:55:28 +12001152
1153 private void doUpdatesThread() {
1154 boolean interrupted = false;
1155 try {
1156 while (true) {
1157 try {
1158 RibUpdate update = ribUpdates.take();
1159 switch (update.getOperation()){
1160 case UPDATE:
Jonathan Hart2f740782013-08-04 00:49:21 +12001161 processRibAdd(update);
Jonathan Hart8b9349e2013-07-26 15:55:28 +12001162 break;
1163 case DELETE:
Jonathan Hart2f740782013-08-04 00:49:21 +12001164 processRibDelete(update);
Jonathan Hart8b9349e2013-07-26 15:55:28 +12001165 break;
1166 }
1167 } catch (InterruptedException e) {
1168 interrupted = true;
1169 }
1170 }
1171 } finally {
1172 if (interrupted) {
1173 Thread.currentThread().interrupt();
1174 }
1175 }
1176 }
pingping-lina2cbfad2013-03-07 08:39:21 +08001177
1178 @Override
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001179 public void topologyChanged() {
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001180 boolean refreshNeeded = false;
1181 for (LDUpdate ldu : topology.getLastLinkUpdates()){
1182 if (!ldu.getOperation().equals(ILinkDiscovery.UpdateOperation.LINK_UPDATED)){
1183 //We don't need to recalculate anything for just link updates
Jonathan Hartb39a67d2013-08-10 23:59:50 +12001184 //They happen very frequently
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001185 refreshNeeded = true;
1186 }
Jonathan Hart98957bf2013-07-01 14:49:24 +12001187
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001188 log.debug("Topo change {}", ldu.getOperation());
Jonathan Hartc824ad02013-07-03 15:58:45 +12001189
Jonathan Hart98957bf2013-07-01 14:49:24 +12001190 if (ldu.getOperation().equals(ILinkDiscovery.UpdateOperation.LINK_ADDED)){
1191 synchronized (linkUpdates) {
1192 linkUpdates.add(ldu);
1193 }
1194 }
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001195 }
1196
1197 if (refreshNeeded){
Jonathan Hart98957bf2013-07-01 14:49:24 +12001198 topologyChangeDetectorTask.reschedule(TOPO_DETECTION_WAIT, TimeUnit.SECONDS);
pingping-lina2cbfad2013-03-07 08:39:21 +08001199 }
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001200 }
pingping-lina2cbfad2013-03-07 08:39:21 +08001201
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001202 //TODO determine whether we need to listen for switch joins
1203 @Override
1204 public void addedSwitch(IOFSwitch sw) {
1205 //checkStatus();
1206 }
1207
1208 @Override
1209 public void removedSwitch(IOFSwitch sw) {
1210 // TODO Auto-generated method stub
1211 }
1212
1213 @Override
1214 public void switchPortChanged(Long switchId) {}
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001215
1216 @Override
1217 public String getName() {
1218 return "BgpRoute";
pingping-lina2cbfad2013-03-07 08:39:21 +08001219 }
1220}