blob: 37666b2b3e59eacb1bc7d4cbfe5af727b9962286 [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 Hart64c0b202013-08-20 15:45:07 +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.packet.Ethernet;
Jonathan Hart832a7cb2013-06-24 11:25:35 +120029import net.floodlightcontroller.packet.IPv4;
pingping-lina2cbfad2013-03-07 08:39:21 +080030import net.floodlightcontroller.restserver.IRestApiService;
Jonathan Hart98957bf2013-07-01 14:49:24 +120031import net.floodlightcontroller.routing.Link;
pingping-lina2cbfad2013-03-07 08:39:21 +080032import net.floodlightcontroller.topology.ITopologyListener;
33import net.floodlightcontroller.topology.ITopologyService;
Jonathan Hart4dfc3652013-08-02 20:22:36 +120034import net.floodlightcontroller.util.MACAddress;
Jonathan Hart0ee0f022013-08-03 22:21:54 +120035import net.onrc.onos.ofcontroller.bgproute.RibUpdate.Operation;
Jonathan Hart98957bf2013-07-01 14:49:24 +120036import net.onrc.onos.ofcontroller.core.INetMapTopologyService.ITopoLinkService;
HIGUCHI Yuta20514902013-06-12 11:24:16 -070037import net.onrc.onos.ofcontroller.core.INetMapTopologyService.ITopoRouteService;
Jonathan Hart98957bf2013-07-01 14:49:24 +120038import net.onrc.onos.ofcontroller.core.internal.TopoLinkServiceImpl;
HIGUCHI Yutaa56fbde2013-06-17 14:26:05 -070039import net.onrc.onos.ofcontroller.linkdiscovery.ILinkDiscovery;
40import net.onrc.onos.ofcontroller.linkdiscovery.ILinkDiscovery.LDUpdate;
Jonathan Harte7694532013-09-12 12:34:46 +120041import net.onrc.onos.ofcontroller.linkdiscovery.ILinkDiscoveryService;
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 Hart309889c2013-08-13 23:26:24 +120074import com.google.common.net.InetAddresses;
Jonathan Hart8b9349e2013-07-26 15:55:28 +120075import com.google.common.util.concurrent.ThreadFactoryBuilder;
76
Jonathan Hart1236a9b2013-06-18 22:10:05 +120077public class BgpRoute implements IFloodlightModule, IBgpRouteService,
Jonathan Hart64c0b202013-08-20 15:45:07 +120078 ITopologyListener, IArpRequester,
79 IOFSwitchListener {
pingping-lina2cbfad2013-03-07 08:39:21 +080080
81 protected static Logger log = LoggerFactory.getLogger(BgpRoute.class);
82
83 protected IFloodlightProviderService floodlightProvider;
84 protected ITopologyService topology;
Jonathan Harte7e1c6e2013-06-04 20:50:23 -070085 protected ITopoRouteService topoRouteService;
Jonathan Harte7694532013-09-12 12:34:46 +120086 protected ILinkDiscoveryService linkDiscoveryService;
Jonathan Harte7e1c6e2013-06-04 20:50:23 -070087 protected IRestApiService restApi;
88
Jonathan Hartc7ca35d2013-06-25 20:54:25 +120089 protected ProxyArpManager proxyArp;
90
Jonathan Hart29b972d2013-08-12 23:43:51 +120091 protected IPatriciaTrie<RibEntry> ptree;
Jonathan Hartabf10222013-08-13 10:19:34 +120092 protected IPatriciaTrie<Interface> interfacePtrie;
Jonathan Hart8b9349e2013-07-26 15:55:28 +120093 protected BlockingQueue<RibUpdate> ribUpdates;
94
Jonathan Hart61ba9372013-05-19 20:10:29 -070095 protected String bgpdRestIp;
96 protected String routerId;
Jonathan Hart9575cb62013-07-05 13:43:49 +120097 protected String configFilename = "config.json";
Jonathan Harte7e1c6e2013-06-04 20:50:23 -070098
99 //We need to identify our flows somehow. But like it says in LearningSwitch.java,
100 //the controller/OS should hand out cookie IDs to prevent conflicts.
101 protected final long APP_COOKIE = 0xa0000000000000L;
102 //Cookie for flows that do L2 forwarding within SDN domain to egress routers
103 protected final long L2_FWD_COOKIE = APP_COOKIE + 1;
104 //Cookie for flows in ingress switches that rewrite the MAC address
105 protected final long MAC_RW_COOKIE = APP_COOKIE + 2;
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200106 //Cookie for flows that setup BGP paths
107 protected final long BGP_COOKIE = APP_COOKIE + 3;
Jonathan Hart50a8d1e2013-06-06 16:00:47 +1200108 //Forwarding uses priority 0, and the mac rewrite entries in ingress switches
109 //need to be higher priority than this otherwise the rewrite may not get done
110 protected final short SDNIP_PRIORITY = 10;
Jonathan Hartc82051c2013-08-24 15:12:20 +1200111 protected final short ARP_PRIORITY = 20;
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700112
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200113 protected final short BGP_PORT = 179;
114
Jonathan Hart98957bf2013-07-01 14:49:24 +1200115 protected final int TOPO_DETECTION_WAIT = 2; //seconds
116
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200117 //Configuration stuff
Jonathan Hart1236a9b2013-06-18 22:10:05 +1200118 protected List<String> switches;
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200119 protected Map<String, Interface> interfaces;
Jonathan Hartc824ad02013-07-03 15:58:45 +1200120 protected Map<InetAddress, BgpPeer> bgpPeers;
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200121 protected SwitchPort bgpdAttachmentPoint;
Jonathan Hart2f790d22013-08-15 14:01:24 +1200122 protected MACAddress bgpdMacAddress;
Jonathan Hart1236a9b2013-06-18 22:10:05 +1200123
124 //True when all switches have connected
125 protected volatile boolean switchesConnected = false;
126 //True when we have a full mesh of shortest paths between gateways
127 protected volatile boolean topologyReady = false;
Jonathan Hart98957bf2013-07-01 14:49:24 +1200128
Jonathan Hart98957bf2013-07-01 14:49:24 +1200129 protected ArrayList<LDUpdate> linkUpdates;
130 protected SingletonTask topologyChangeDetectorTask;
131
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200132 protected SetMultimap<InetAddress, RibUpdate> prefixesWaitingOnArp;
Jonathan Hart309889c2013-08-13 23:26:24 +1200133
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200134 protected Map<InetAddress, Path> pathsWaitingOnArp;
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200135
Jonathan Hart0a46fe42013-08-10 17:08:47 +1200136 protected ExecutorService bgpUpdatesExecutor;
137
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200138 protected Map<InetAddress, Path> pushedPaths;
139 protected Map<Prefix, Path> prefixToPath;
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200140 protected Multimap<Prefix, PushedFlowMod> pushedFlows;
Jonathan Hartdefa44d2013-08-15 19:51:13 +1200141
142 protected volatile Map<Long, ?> topoRouteTopology = null;
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200143
Jonathan Hart98957bf2013-07-01 14:49:24 +1200144 protected class TopologyChangeDetector implements Runnable {
145 @Override
146 public void run() {
147 log.debug("Running topology change detection task");
148 synchronized (linkUpdates) {
Jonathan Hartc824ad02013-07-03 15:58:45 +1200149 //This is the model the REST API uses to retrieve network graph info
Jonathan Hart98957bf2013-07-01 14:49:24 +1200150 ITopoLinkService topoLinkService = new TopoLinkServiceImpl();
151
152 List<Link> activeLinks = topoLinkService.getActiveLinks();
Jonathan Hart98957bf2013-07-01 14:49:24 +1200153
154 Iterator<LDUpdate> it = linkUpdates.iterator();
155 while (it.hasNext()){
156 LDUpdate ldu = it.next();
157 Link l = new Link(ldu.getSrc(), ldu.getSrcPort(),
158 ldu.getDst(), ldu.getDstPort());
159
160 if (activeLinks.contains(l)){
161 log.debug("Not found: {}", l);
162 it.remove();
163 }
164 }
165 }
166
Jonathan Hart64c0b202013-08-20 15:45:07 +1200167 if (!topologyReady) {
168 if (linkUpdates.isEmpty()){
169 //All updates have been seen in network map.
170 //We can check if topology is ready
171 log.debug("No known changes outstanding. Checking topology now");
172 checkStatus();
173 }
174 else {
175 //We know of some link updates that haven't propagated to the database yet
176 log.debug("Some changes not found in network map - {} links missing", linkUpdates.size());
177 topologyChangeDetectorTask.reschedule(TOPO_DETECTION_WAIT, TimeUnit.SECONDS);
178 }
Jonathan Hart98957bf2013-07-01 14:49:24 +1200179 }
180 }
181 }
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700182
Jonathan Hartd1f23252013-06-13 15:17:05 +1200183 private void readGatewaysConfiguration(String gatewaysFilename){
184 File gatewaysFile = new File(gatewaysFilename);
185 ObjectMapper mapper = new ObjectMapper();
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700186
Jonathan Hartd1f23252013-06-13 15:17:05 +1200187 try {
Jonathan Hart1236a9b2013-06-18 22:10:05 +1200188 Configuration config = mapper.readValue(gatewaysFile, Configuration.class);
189
Jonathan Hart1236a9b2013-06-18 22:10:05 +1200190 switches = config.getSwitches();
Jonathan Hart9575cb62013-07-05 13:43:49 +1200191 interfaces = new HashMap<String, Interface>();
192 for (Interface intf : config.getInterfaces()){
193 interfaces.put(intf.getName(), intf);
194 }
Jonathan Hartc824ad02013-07-03 15:58:45 +1200195 bgpPeers = new HashMap<InetAddress, BgpPeer>();
196 for (BgpPeer peer : config.getPeers()){
197 bgpPeers.put(peer.getIpAddress(), peer);
198 }
Jonathan Hart1236a9b2013-06-18 22:10:05 +1200199
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200200 bgpdAttachmentPoint = new SwitchPort(
201 new Dpid(config.getBgpdAttachmentDpid()),
202 new Port(config.getBgpdAttachmentPort()));
Jonathan Hart1236a9b2013-06-18 22:10:05 +1200203
Jonathan Hart2f790d22013-08-15 14:01:24 +1200204 bgpdMacAddress = config.getBgpdMacAddress();
Jonathan Hartd1f23252013-06-13 15:17:05 +1200205 } catch (JsonParseException e) {
206 log.error("Error in JSON file", e);
207 System.exit(1);
208 } catch (JsonMappingException e) {
209 log.error("Error in JSON file", e);
210 System.exit(1);
211 } catch (IOException e) {
212 log.error("Error reading JSON file", e);
213 System.exit(1);
214 }
Jonathan Hartabf10222013-08-13 10:19:34 +1200215
216 //Populate the interface Patricia Trie
217 for (Interface intf : interfaces.values()) {
218 Prefix prefix = new Prefix(intf.getIpAddress().getAddress(), intf.getPrefixLength());
219 interfacePtrie.put(prefix, intf);
220 }
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700221 }
pingping-lina2cbfad2013-03-07 08:39:21 +0800222
223 @Override
224 public Collection<Class<? extends IFloodlightService>> getModuleServices() {
Jonathan Hart61ba9372013-05-19 20:10:29 -0700225 Collection<Class<? extends IFloodlightService>> l
226 = new ArrayList<Class<? extends IFloodlightService>>();
pingping-lina2cbfad2013-03-07 08:39:21 +0800227 l.add(IBgpRouteService.class);
228 return l;
229 }
230
231 @Override
232 public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() {
Jonathan Hart61ba9372013-05-19 20:10:29 -0700233 Map<Class<? extends IFloodlightService>, IFloodlightService> m
234 = new HashMap<Class<? extends IFloodlightService>, IFloodlightService>();
pingping-line2a09ca2013-03-23 09:33:58 +0800235 m.put(IBgpRouteService.class, this);
pingping-lina2cbfad2013-03-07 08:39:21 +0800236 return m;
237 }
238
pingping-lina2cbfad2013-03-07 08:39:21 +0800239 @Override
240 public Collection<Class<? extends IFloodlightService>> getModuleDependencies() {
Jonathan Hart61ba9372013-05-19 20:10:29 -0700241 Collection<Class<? extends IFloodlightService>> l
242 = new ArrayList<Class<? extends IFloodlightService>>();
pingping-lina2cbfad2013-03-07 08:39:21 +0800243 l.add(IFloodlightProviderService.class);
244 l.add(ITopologyService.class);
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700245 l.add(IRestApiService.class);
pingping-lina2cbfad2013-03-07 08:39:21 +0800246 return l;
247 }
248
249 @Override
250 public void init(FloodlightModuleContext context)
251 throws FloodlightModuleException {
252
Jonathan Hart29b972d2013-08-12 23:43:51 +1200253 ptree = new PatriciaTrie<RibEntry>(32);
Jonathan Hartabf10222013-08-13 10:19:34 +1200254 interfacePtrie = new PatriciaTrie<Interface>(32);
Jonathan Hart8b9349e2013-07-26 15:55:28 +1200255
256 ribUpdates = new LinkedBlockingQueue<RibUpdate>();
Jonathan Hartc824ad02013-07-03 15:58:45 +1200257
pingping-lina2cbfad2013-03-07 08:39:21 +0800258 // Register floodlight provider and REST handler.
259 floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class);
pingping-lina2cbfad2013-03-07 08:39:21 +0800260 topology = context.getServiceImpl(ITopologyService.class);
Jonathan Harte7694532013-09-12 12:34:46 +1200261 linkDiscoveryService = context.getServiceImpl(ILinkDiscoveryService.class);
Jonathan Hartc7ca35d2013-06-25 20:54:25 +1200262 restApi = context.getServiceImpl(IRestApiService.class);
263
264 //TODO We'll initialise this here for now, but it should really be done as
265 //part of the controller core
Jonathan Hart2f790d22013-08-15 14:01:24 +1200266 proxyArp = new ProxyArpManager(floodlightProvider, topology);
pingping-lina2cbfad2013-03-07 08:39:21 +0800267
Jonathan Hart98957bf2013-07-01 14:49:24 +1200268 linkUpdates = new ArrayList<LDUpdate>();
269 ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
270 topologyChangeDetectorTask = new SingletonTask(executor, new TopologyChangeDetector());
Pavlin Radoslavovddd01ba2013-07-03 15:40:44 -0700271
272 topoRouteService = new TopoRouteService("");
Jonathan Hart98957bf2013-07-01 14:49:24 +1200273
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200274 pathsWaitingOnArp = new HashMap<InetAddress, Path>();
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200275 prefixesWaitingOnArp = Multimaps.synchronizedSetMultimap(
276 HashMultimap.<InetAddress, RibUpdate>create());
277
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200278 pushedPaths = new HashMap<InetAddress, Path>();
279 prefixToPath = new HashMap<Prefix, Path>();
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200280 pushedFlows = HashMultimap.<Prefix, PushedFlowMod>create();
281
Jonathan Hart0a46fe42013-08-10 17:08:47 +1200282 bgpUpdatesExecutor = Executors.newSingleThreadExecutor(
283 new ThreadFactoryBuilder().setNameFormat("bgp-updates-%d").build());
284
Jonathan Hart61ba9372013-05-19 20:10:29 -0700285 //Read in config values
286 bgpdRestIp = context.getConfigParams(this).get("BgpdRestIp");
287 if (bgpdRestIp == null){
288 log.error("BgpdRestIp property not found in config file");
289 System.exit(1);
290 }
291 else {
292 log.info("BgpdRestIp set to {}", bgpdRestIp);
293 }
294
295 routerId = context.getConfigParams(this).get("RouterId");
296 if (routerId == null){
297 log.error("RouterId property not found in config file");
298 System.exit(1);
299 }
300 else {
301 log.info("RouterId set to {}", routerId);
302 }
Jonathan Hartd1f23252013-06-13 15:17:05 +1200303
Jonathan Hart9575cb62013-07-05 13:43:49 +1200304 String configFilenameParameter = context.getConfigParams(this).get("configfile");
305 if (configFilenameParameter != null){
306 configFilename = configFilenameParameter;
307 }
308 log.debug("Config file set to {}", configFilename);
309
310 readGatewaysConfiguration(configFilename);
Jonathan Hart2f790d22013-08-15 14:01:24 +1200311
Jonathan Hart1633a402013-08-24 11:38:56 +1200312 proxyArp.setL3Mode(interfacePtrie, interfaces.values(), bgpdMacAddress);
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200313 }
314
315 @Override
316 public void startUp(FloodlightModuleContext context) {
317 restApi.addRestletRoutable(new BgpRouteWebRoutable());
318 topology.addListener(this);
Jonathan Hart64c0b202013-08-20 15:45:07 +1200319 floodlightProvider.addOFSwitchListener(this);
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200320
Jonathan Hart2f790d22013-08-15 14:01:24 +1200321 proxyArp.startUp();
322
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200323 floodlightProvider.addOFMessageListener(OFType.PACKET_IN, proxyArp);
324
325 //Retrieve the RIB from BGPd during startup
326 retrieveRib();
pingping-lina2cbfad2013-03-07 08:39:21 +0800327 }
328
Jonathan Hart29b972d2013-08-12 23:43:51 +1200329 public IPatriciaTrie<RibEntry> getPtree() {
pingping-lina2cbfad2013-03-07 08:39:21 +0800330 return ptree;
331 }
Jonathan Hart61ba9372013-05-19 20:10:29 -0700332
333 public void clearPtree() {
Jonathan Hart29b972d2013-08-12 23:43:51 +1200334 ptree = new PatriciaTrie<RibEntry>(32);
pingping-line2a09ca2013-03-23 09:33:58 +0800335 }
Jonathan Hart61ba9372013-05-19 20:10:29 -0700336
pingping-line2a09ca2013-03-23 09:33:58 +0800337 public String getBGPdRestIp() {
Jonathan Hart61ba9372013-05-19 20:10:29 -0700338 return bgpdRestIp;
pingping-line2a09ca2013-03-23 09:33:58 +0800339 }
Jonathan Hart61ba9372013-05-19 20:10:29 -0700340
pingping-line2a09ca2013-03-23 09:33:58 +0800341 public String getRouterId() {
Jonathan Hart61ba9372013-05-19 20:10:29 -0700342 return routerId;
pingping-line2a09ca2013-03-23 09:33:58 +0800343 }
pingping-lina2cbfad2013-03-07 08:39:21 +0800344
Jonathan Hart61ba9372013-05-19 20:10:29 -0700345 private void retrieveRib(){
346 String url = "http://" + bgpdRestIp + "/wm/bgp/" + routerId;
347 String response = RestClient.get(url);
348
349 if (response.equals("")){
350 return;
351 }
352
353 response = response.replaceAll("\"", "'");
354 JSONObject jsonObj = (JSONObject) JSONSerializer.toJSON(response);
355 JSONArray rib_json_array = jsonObj.getJSONArray("rib");
356 String router_id = jsonObj.getString("router-id");
357
358 int size = rib_json_array.size();
359
360 log.info("Retrived RIB of {} entries from BGPd", size);
361
362 for (int j = 0; j < size; j++) {
363 JSONObject second_json_object = rib_json_array.getJSONObject(j);
364 String prefix = second_json_object.getString("prefix");
365 String nexthop = second_json_object.getString("nexthop");
366
367 //insert each rib entry into the local rib;
368 String[] substring = prefix.split("/");
369 String prefix1 = substring[0];
370 String mask1 = substring[1];
371
372 Prefix p;
373 try {
374 p = new Prefix(prefix1, Integer.valueOf(mask1));
375 } catch (NumberFormatException e) {
376 log.warn("Wrong mask format in RIB JSON: {}", mask1);
377 continue;
Jonathan Hart32e18222013-08-07 22:05:42 +1200378 } catch (IllegalArgumentException e1) {
Jonathan Hart61ba9372013-05-19 20:10:29 -0700379 log.warn("Wrong prefix format in RIB JSON: {}", prefix1);
380 continue;
381 }
382
Jonathan Hartb39a67d2013-08-10 23:59:50 +1200383 RibEntry rib = new RibEntry(router_id, nexthop);
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200384
Jonathan Hart0a46fe42013-08-10 17:08:47 +1200385 try {
386 ribUpdates.put(new RibUpdate(Operation.UPDATE, p, rib));
387 } catch (InterruptedException e) {
388 log.debug("Interrupted while pushing onto update queue");
389 }
Jonathan Hart61ba9372013-05-19 20:10:29 -0700390 }
391 }
392
Jonathan Hart8b9349e2013-07-26 15:55:28 +1200393 @Override
394 public void newRibUpdate(RibUpdate update) {
Jonathan Hart9ea31212013-08-12 21:40:34 +1200395 try {
396 ribUpdates.put(update);
397 } catch (InterruptedException e) {
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200398 log.debug("Interrupted while putting on ribUpdates queue", e);
399 Thread.currentThread().interrupt();
Jonathan Hart9ea31212013-08-12 21:40:34 +1200400 }
Jonathan Hart8b9349e2013-07-26 15:55:28 +1200401 }
402
Jonathan Hart0a46fe42013-08-10 17:08:47 +1200403 public synchronized void processRibAdd(RibUpdate update) {
Jonathan Hart8b9349e2013-07-26 15:55:28 +1200404 Prefix prefix = update.getPrefix();
405
Jonathan Hart9ea31212013-08-12 21:40:34 +1200406 log.debug("Processing prefix add {}", prefix);
407
Jonathan Hartb39a67d2013-08-10 23:59:50 +1200408 RibEntry rib = ptree.put(prefix, update.getRibEntry());
Jonathan Hart8b9349e2013-07-26 15:55:28 +1200409
Jonathan Hart0a46fe42013-08-10 17:08:47 +1200410 if (rib != null && !rib.equals(update.getRibEntry())) {
Jonathan Hart2f740782013-08-04 00:49:21 +1200411 //There was an existing nexthop for this prefix. This update supersedes that,
412 //so we need to remove the old flows for this prefix from the switches
Jonathan Hart309889c2013-08-13 23:26:24 +1200413 _processDeletePrefix(prefix, rib);
Jonathan Hart8b9349e2013-07-26 15:55:28 +1200414 }
Jonathan Hart2f740782013-08-04 00:49:21 +1200415
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200416 if (update.getRibEntry().getNextHop().equals(
417 InetAddresses.forString("0.0.0.0"))) {
Jonathan Hart309889c2013-08-13 23:26:24 +1200418 //Route originated by SDN domain
419 //We don't handle these at the moment
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200420 log.debug("Own route {} to {}", prefix,
421 update.getRibEntry().getNextHop().getHostAddress());
Jonathan Hart309889c2013-08-13 23:26:24 +1200422 return;
423 }
424
425 _processRibAdd(update);
Jonathan Hart8b9349e2013-07-26 15:55:28 +1200426 }
427
Jonathan Hart309889c2013-08-13 23:26:24 +1200428 private void _processRibAdd(RibUpdate update) {
429 Prefix prefix = update.getPrefix();
430 RibEntry rib = update.getRibEntry();
431
432 InetAddress dstIpAddress = rib.getNextHop();
433
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200434 //See if we know the MAC address of the next hop
Jonathan Hart309889c2013-08-13 23:26:24 +1200435 byte[] nextHopMacAddress = proxyArp.getMacAddress(rib.getNextHop());
Jonathan Hart309889c2013-08-13 23:26:24 +1200436
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200437 //Find the attachment point (egress interface) of the next hop
438 Interface egressInterface = null;
Jonathan Hart309889c2013-08-13 23:26:24 +1200439 if (bgpPeers.containsKey(dstIpAddress)) {
440 //Route to a peer
441 log.debug("Route to peer {}", dstIpAddress);
442 BgpPeer peer = bgpPeers.get(dstIpAddress);
443 egressInterface = interfaces.get(peer.getInterfaceName());
Jonathan Hart309889c2013-08-13 23:26:24 +1200444 }
445 else {
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200446 //Route to non-peer
Jonathan Hart309889c2013-08-13 23:26:24 +1200447 log.debug("Route to non-peer {}", dstIpAddress);
448 egressInterface = interfacePtrie.match(
449 new Prefix(dstIpAddress.getAddress(), 32));
450 if (egressInterface == null) {
451 log.warn("No outgoing interface found for {}", dstIpAddress.getHostAddress());
452 return;
453 }
Jonathan Hart309889c2013-08-13 23:26:24 +1200454 }
455
456 if (nextHopMacAddress == null) {
457 prefixesWaitingOnArp.put(dstIpAddress,
458 new RibUpdate(Operation.UPDATE, prefix, rib));
459 proxyArp.sendArpRequest(dstIpAddress, this, true);
460 return;
461 }
462 else {
463 if (!bgpPeers.containsKey(dstIpAddress)) {
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200464 //If the prefix is for a non-peer we need to ensure there's a path,
465 //and push one if there isn't.
466 Path path = pushedPaths.get(dstIpAddress);
Jonathan Hart309889c2013-08-13 23:26:24 +1200467 if (path == null) {
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200468 path = new Path(egressInterface, dstIpAddress);
469 setUpDataPath(path, MACAddress.valueOf(nextHopMacAddress));
Jonathan Hart309889c2013-08-13 23:26:24 +1200470 pushedPaths.put(dstIpAddress, path);
471 }
Jonathan Hart309889c2013-08-13 23:26:24 +1200472
473 path.incrementUsers();
474 prefixToPath.put(prefix, path);
475 }
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200476
477 //For all prefixes we need to add the first-hop mac-rewriting flows
Jonathan Hart309889c2013-08-13 23:26:24 +1200478 addPrefixFlows(prefix, egressInterface, nextHopMacAddress);
479 }
480 }
481
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200482 private void addPrefixFlows(Prefix prefix, Interface egressInterface, byte[] nextHopMacAddress) {
483 log.debug("Adding flows for prefix {} added, next hop mac {}",
484 prefix, HexString.toHexString(nextHopMacAddress));
Jonathan Hartd5f2e952013-09-13 16:31:23 +1200485
486 //We only need one flow mod per switch, so pick one interface on each switch
487 Map<Long, Interface> srcInterfaces = new HashMap<Long, Interface>();
488 for (Interface intf : interfaces.values()) {
489 if (!srcInterfaces.containsKey(intf.getDpid())
490 && intf != egressInterface) {
491 srcInterfaces.put(intf.getDpid(), intf);
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200492 }
Jonathan Hartd5f2e952013-09-13 16:31:23 +1200493 }
494
495 //Add a flow to rewrite mac for this prefix to all other border switches
496 //for (Interface srcInterface : interfaces.values()) {
497 for (Interface srcInterface : srcInterfaces.values()) {
498 //if (srcInterface == egressInterface) {
499 //Don't push a flow for the switch where this peer is attached
500 //continue;
501 //}
Jonathan Hartdefa44d2013-08-15 19:51:13 +1200502
503
504 DataPath shortestPath;
505 if (topoRouteTopology == null) {
506 shortestPath = topoRouteService.getShortestPath(
507 srcInterface.getSwitchPort(),
508 egressInterface.getSwitchPort());
509 }
510 else {
511 shortestPath = topoRouteService.getTopoShortestPath(
512 topoRouteTopology, srcInterface.getSwitchPort(),
513 egressInterface.getSwitchPort());
514 }
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200515
516 if (shortestPath == null){
517 log.debug("Shortest path between {} and {} not found",
518 srcInterface.getSwitchPort(),
519 egressInterface.getSwitchPort());
520 return; // just quit here?
521 }
522
523 //Set up the flow mod
524 OFFlowMod fm = (OFFlowMod) floodlightProvider.getOFMessageFactory()
525 .getMessage(OFType.FLOW_MOD);
526
527 fm.setIdleTimeout((short)0)
528 .setHardTimeout((short)0)
529 .setBufferId(OFPacketOut.BUFFER_ID_NONE)
530 .setCookie(MAC_RW_COOKIE)
531 .setCommand(OFFlowMod.OFPFC_ADD)
532 .setPriority(SDNIP_PRIORITY)
533 .setLengthU(OFFlowMod.MINIMUM_LENGTH
534 + OFActionDataLayerDestination.MINIMUM_LENGTH
535 + OFActionOutput.MINIMUM_LENGTH);
536
537 OFMatch match = new OFMatch();
538 match.setDataLayerType(Ethernet.TYPE_IPv4);
539 match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_TYPE);
540
541 match.setFromCIDR(prefix.toString(), OFMatch.STR_NW_DST);
542 fm.setMatch(match);
543
544 //Set up MAC rewrite action
545 OFActionDataLayerDestination macRewriteAction = new OFActionDataLayerDestination();
546 macRewriteAction.setDataLayerAddress(nextHopMacAddress);
547
548 //Set up output action
549 OFActionOutput outputAction = new OFActionOutput();
550 outputAction.setMaxLength((short)0xffff);
551 Port outputPort = shortestPath.flowEntries().get(0).outPort();
552 outputAction.setPort(outputPort.value());
553
554 List<OFAction> actions = new ArrayList<OFAction>();
555 actions.add(macRewriteAction);
556 actions.add(outputAction);
557 fm.setActions(actions);
558
559 //Write to switch
560 IOFSwitch sw = floodlightProvider.getSwitches()
561 .get(srcInterface.getDpid());
562
563 if (sw == null){
564 log.warn("Switch not found when pushing flow mod");
565 continue;
566 }
567
568 pushedFlows.put(prefix, new PushedFlowMod(sw.getId(), fm));
569
570 List<OFMessage> msglist = new ArrayList<OFMessage>();
571 msglist.add(fm);
572 try {
573 sw.write(msglist, null);
574 sw.flush();
575 } catch (IOException e) {
576 log.error("Failure writing flow mod", e);
577 }
Jonathan Hart309889c2013-08-13 23:26:24 +1200578 }
579 }
Jonathan Hart309889c2013-08-13 23:26:24 +1200580
Jonathan Hart0a46fe42013-08-10 17:08:47 +1200581 public synchronized void processRibDelete(RibUpdate update) {
Jonathan Hart8b9349e2013-07-26 15:55:28 +1200582 Prefix prefix = update.getPrefix();
583
Jonathan Hartd7e158d2013-08-07 23:04:48 +1200584 if (ptree.remove(prefix, update.getRibEntry())) {
585 /*
586 * Only delete flows if an entry was actually removed from the trie.
587 * If no entry was removed, the <prefix, nexthop> wasn't there so
588 * it's probably already been removed and we don't need to do anything
589 */
Jonathan Hart309889c2013-08-13 23:26:24 +1200590 _processDeletePrefix(prefix, update.getRibEntry());
Jonathan Hart309889c2013-08-13 23:26:24 +1200591 }
592 }
593
594 private void _processDeletePrefix(Prefix prefix, RibEntry ribEntry) {
595 deletePrefixFlows(prefix);
596
597 log.debug("Deleting {} to {}", prefix, ribEntry.getNextHop());
Jonathan Hartd992f1a2013-09-13 13:46:44 +1200598
Jonathan Hart309889c2013-08-13 23:26:24 +1200599 if (!bgpPeers.containsKey(ribEntry.getNextHop())) {
600 log.debug("Getting path for route with non-peer nexthop");
Jonathan Hartfb1ebc52013-08-17 16:25:51 +1200601 //Path path = prefixToPath.get(prefix);
602 Path path = prefixToPath.remove(prefix);
Jonathan Hart309889c2013-08-13 23:26:24 +1200603
Jonathan Hartd992f1a2013-09-13 13:46:44 +1200604 if (path != null) {
605 //path could be null if we added to the Ptree but didn't push
606 //flows yet because we were waiting to resolve ARP
Jonathan Hart309889c2013-08-13 23:26:24 +1200607
Jonathan Hartd992f1a2013-09-13 13:46:44 +1200608 path.decrementUsers();
609 log.debug("users {}, permanent {}", path.getUsers(), path.isPermanent());
610 if (path.getUsers() <= 0 && !path.isPermanent()) {
611 deletePath(path);
612 pushedPaths.remove(path.getDstIpAddress());
613 }
Jonathan Hart309889c2013-08-13 23:26:24 +1200614 }
615 }
616 }
617
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200618 private void deletePrefixFlows(Prefix prefix) {
619 Collection<PushedFlowMod> pushedFlowMods
620 = pushedFlows.removeAll(prefix);
621
622 for (PushedFlowMod pfm : pushedFlowMods) {
623 log.debug("Pushing a DELETE flow mod to {}, matches prefix {} with mac-rewrite {}",
624 new Object[] {HexString.toHexString(pfm.getDpid()),
625 pfm.getFlowMod().getMatch().getNetworkDestination() +
626 pfm.getFlowMod().getMatch().getNetworkDestinationMaskLen(),
627 HexString.toHexString(((OFActionDataLayerDestination)pfm.getFlowMod().getActions().get(0))
628 .getDataLayerAddress())});
629
630 sendDeleteFlowMod(pfm.getFlowMod(), pfm.getDpid());
631 }
632 }
633
634 private void deletePath(Path path) {
Jonathan Hart309889c2013-08-13 23:26:24 +1200635 for (PushedFlowMod pfm : path.getFlowMods()) {
636 log.debug("Pushing a DELETE flow mod to {}, dst MAC {}",
637 new Object[] {HexString.toHexString(pfm.getDpid()),
638 HexString.toHexString(pfm.getFlowMod().getMatch().getDataLayerDestination())
639 });
640
641 sendDeleteFlowMod(pfm.getFlowMod(), pfm.getDpid());
642 }
643 }
644
645 private void sendDeleteFlowMod(OFFlowMod addFlowMod, long dpid) {
646 addFlowMod.setCommand(OFFlowMod.OFPFC_DELETE_STRICT)
647 .setOutPort(OFPort.OFPP_NONE)
648 .setLengthU(OFFlowMod.MINIMUM_LENGTH);
649
650 addFlowMod.getActions().clear();
651
652 IOFSwitch sw = floodlightProvider.getSwitches().get(dpid);
653 if (sw == null) {
654 log.warn("Switch not found when pushing delete flow mod");
655 return;
656 }
657
658 try {
659 sw.write(addFlowMod, null);
660 sw.flush();
661 } catch (IOException e) {
662 log.error("Failure writing flow mod", e);
Jonathan Hartd7e158d2013-08-07 23:04:48 +1200663 }
Jonathan Hart8b9349e2013-07-26 15:55:28 +1200664 }
665
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200666 //TODO test next-hop changes
Jonathan Hart2f740782013-08-04 00:49:21 +1200667 //TODO check delete/add synchronization
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200668
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700669 /*
670 * On startup we need to calculate a full mesh of paths between all gateway
671 * switches
672 */
Jonathan Hart1236a9b2013-06-18 22:10:05 +1200673 private void setupFullMesh(){
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700674 //For each border router, calculate and install a path from every other
675 //border switch to said border router. However, don't install the entry
676 //in to the first hop switch, as we need to install an entry to rewrite
677 //for each prefix received. This will be done later when prefixes have
678 //actually been received.
679
Jonathan Hartc824ad02013-07-03 15:58:45 +1200680 for (BgpPeer peer : bgpPeers.values()) {
681 Interface peerInterface = interfaces.get(peer.getInterfaceName());
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200682
Jonathan Hart309889c2013-08-13 23:26:24 +1200683 //We know there's not already a Path here pushed, because this is
684 //called before all other routing
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200685 Path path = new Path(peerInterface, peer.getIpAddress());
Jonathan Hart309889c2013-08-13 23:26:24 +1200686 path.setPermanent();
687
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200688 //See if we know the MAC address of the peer. If not we can't
689 //do anything until we learn it
690 byte[] mac = proxyArp.getMacAddress(peer.getIpAddress());
691 if (mac == null) {
692 log.debug("Don't know MAC for {}", peer.getIpAddress().getHostAddress());
693 //Put in the pending paths list first
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200694 pathsWaitingOnArp.put(peer.getIpAddress(), path);
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700695
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200696 proxyArp.sendArpRequest(peer.getIpAddress(), this, true);
697 continue;
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700698 }
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200699
700 //If we know the MAC, lets go ahead and push the paths to this peer
Jonathan Hart309889c2013-08-13 23:26:24 +1200701 setUpDataPath(path, MACAddress.valueOf(mac));
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700702 }
703 }
704
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200705 private void setUpDataPath(Path path, MACAddress dstMacAddress) {
706 calculateAndPushPath(path, dstMacAddress);
Jonathan Hart309889c2013-08-13 23:26:24 +1200707 }
708
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200709 private void calculateAndPushPath(Path path, MACAddress dstMacAddress) {
Jonathan Hart309889c2013-08-13 23:26:24 +1200710 Interface dstInterface = path.getDstInterface();
711
Jonathan Hartfb1ebc52013-08-17 16:25:51 +1200712 log.debug("Setting up path to {}, {}", path.getDstIpAddress().getHostAddress(),
713 dstMacAddress);
714
Jonathan Hart309889c2013-08-13 23:26:24 +1200715 List<PushedFlowMod> pushedFlows = new ArrayList<PushedFlowMod>();
716
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200717 for (Interface srcInterface : interfaces.values()) {
718 if (dstInterface.equals(srcInterface.getName())){
719 continue;
720 }
721
Jonathan Hartdefa44d2013-08-15 19:51:13 +1200722 DataPath shortestPath;
723 if (topoRouteTopology == null) {
724 log.debug("Using database topo");
725 shortestPath = topoRouteService.getShortestPath(
726 srcInterface.getSwitchPort(), dstInterface.getSwitchPort());
727 }
728 else {
729 log.debug("Using prepared topo");
730 shortestPath = topoRouteService.getTopoShortestPath(topoRouteTopology,
731 srcInterface.getSwitchPort(), dstInterface.getSwitchPort());
732 }
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200733
734 if (shortestPath == null){
735 log.debug("Shortest path between {} and {} not found",
736 srcInterface.getSwitchPort(), dstInterface.getSwitchPort());
737 return; // just quit here?
738 }
739
Jonathan Hart309889c2013-08-13 23:26:24 +1200740 pushedFlows.addAll(installPath(shortestPath.flowEntries(), dstMacAddress));
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200741 }
Jonathan Hart309889c2013-08-13 23:26:24 +1200742
743 path.setFlowMods(pushedFlows);
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200744 }
745
Jonathan Hart309889c2013-08-13 23:26:24 +1200746 private List<PushedFlowMod> installPath(List<FlowEntry> flowEntries, MACAddress dstMacAddress){
747 List<PushedFlowMod> flowMods = new ArrayList<PushedFlowMod>();
748
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700749 //Set up the flow mod
750 OFFlowMod fm =
751 (OFFlowMod) floodlightProvider.getOFMessageFactory()
752 .getMessage(OFType.FLOW_MOD);
753
754 OFActionOutput action = new OFActionOutput();
755 action.setMaxLength((short)0xffff);
756 List<OFAction> actions = new ArrayList<OFAction>();
757 actions.add(action);
758
759 fm.setIdleTimeout((short)0)
760 .setHardTimeout((short)0)
761 .setBufferId(OFPacketOut.BUFFER_ID_NONE)
762 .setCookie(L2_FWD_COOKIE)
763 .setCommand(OFFlowMod.OFPFC_ADD)
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700764 .setActions(actions)
765 .setLengthU(OFFlowMod.MINIMUM_LENGTH+OFActionOutput.MINIMUM_LENGTH);
766
767 //Don't push the first flow entry. We need to push entries in the
768 //first switch based on IP prefix which we don't know yet.
769 for (int i = 1; i < flowEntries.size(); i++){
770 FlowEntry flowEntry = flowEntries.get(i);
771
772 OFMatch match = new OFMatch();
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200773 match.setDataLayerDestination(dstMacAddress.toBytes());
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700774 match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_DST);
775 ((OFActionOutput) fm.getActions().get(0)).setPort(flowEntry.outPort().value());
776
777 fm.setMatch(match);
778
779 IOFSwitch sw = floodlightProvider.getSwitches().get(flowEntry.dpid().value());
780
781 if (sw == null){
782 log.warn("Switch not found when pushing flow mod");
783 continue;
784 }
785
Jonathan Hart309889c2013-08-13 23:26:24 +1200786 flowMods.add(new PushedFlowMod(sw.getId(), fm));
787
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700788 List<OFMessage> msglist = new ArrayList<OFMessage>();
789 msglist.add(fm);
790 try {
791 sw.write(msglist, null);
792 sw.flush();
793 } catch (IOException e) {
794 log.error("Failure writing flow mod", e);
795 }
796
797 try {
798 fm = fm.clone();
799 } catch (CloneNotSupportedException e1) {
800 log.error("Failure cloning flow mod", e1);
801 }
802 }
Jonathan Hart309889c2013-08-13 23:26:24 +1200803
804 return flowMods;
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700805 }
806
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200807 private void setupBgpPaths(){
Jonathan Hartc824ad02013-07-03 15:58:45 +1200808 for (BgpPeer bgpPeer : bgpPeers.values()){
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200809 Interface peerInterface = interfaces.get(bgpPeer.getInterfaceName());
810
811 DataPath path = topoRouteService.getShortestPath(
812 peerInterface.getSwitchPort(), bgpdAttachmentPoint);
813
814 if (path == null){
815 log.debug("Unable to compute path for BGP traffic for {}",
816 bgpPeer.getIpAddress());
817 continue;
818 }
819
820 //Set up the flow mod
821 OFFlowMod fm =
822 (OFFlowMod) floodlightProvider.getOFMessageFactory()
823 .getMessage(OFType.FLOW_MOD);
824
825 OFActionOutput action = new OFActionOutput();
826 action.setMaxLength((short)0xffff);
827 List<OFAction> actions = new ArrayList<OFAction>();
828 actions.add(action);
829
830 fm.setIdleTimeout((short)0)
831 .setHardTimeout((short)0)
832 .setBufferId(OFPacketOut.BUFFER_ID_NONE)
833 .setCookie(BGP_COOKIE)
834 .setCommand(OFFlowMod.OFPFC_ADD)
835 .setPriority(SDNIP_PRIORITY)
836 .setActions(actions)
837 .setLengthU(OFFlowMod.MINIMUM_LENGTH+OFActionOutput.MINIMUM_LENGTH);
838
839 //Forward = gateway -> bgpd, reverse = bgpd -> gateway
840 OFMatch forwardMatchSrc = new OFMatch();
841
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200842 String interfaceCidrAddress = peerInterface.getIpAddress().getHostAddress()
843 + "/32";
844 String peerCidrAddress = bgpPeer.getIpAddress().getHostAddress()
845 + "/32";
Jonathan Hart38c84932013-08-10 17:49:27 +1200846
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200847 //Common match fields
848 forwardMatchSrc.setDataLayerType(Ethernet.TYPE_IPv4);
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200849 forwardMatchSrc.setNetworkProtocol(IPv4.PROTOCOL_TCP);
850 forwardMatchSrc.setTransportDestination(BGP_PORT);
851 forwardMatchSrc.setWildcards(forwardMatchSrc.getWildcards() & ~OFMatch.OFPFW_IN_PORT
852 & ~OFMatch.OFPFW_DL_TYPE & ~OFMatch.OFPFW_NW_PROTO);
853
854
855 OFMatch reverseMatchSrc = forwardMatchSrc.clone();
856
857 forwardMatchSrc.setFromCIDR(peerCidrAddress, OFMatch.STR_NW_SRC);
858 forwardMatchSrc.setFromCIDR(interfaceCidrAddress, OFMatch.STR_NW_DST);
859
860 OFMatch forwardMatchDst = forwardMatchSrc.clone();
861
862 forwardMatchSrc.setTransportSource(BGP_PORT);
863 forwardMatchSrc.setWildcards(forwardMatchSrc.getWildcards() & ~OFMatch.OFPFW_TP_SRC);
864 forwardMatchDst.setTransportDestination(BGP_PORT);
865 forwardMatchDst.setWildcards(forwardMatchDst.getWildcards() & ~OFMatch.OFPFW_TP_DST);
866
867 reverseMatchSrc.setFromCIDR(interfaceCidrAddress, OFMatch.STR_NW_SRC);
868 reverseMatchSrc.setFromCIDR(peerCidrAddress, OFMatch.STR_NW_DST);
869
870 OFMatch reverseMatchDst = reverseMatchSrc.clone();
871
872 reverseMatchSrc.setTransportSource(BGP_PORT);
873 reverseMatchSrc.setWildcards(forwardMatchSrc.getWildcards() & ~OFMatch.OFPFW_TP_SRC);
874 reverseMatchDst.setTransportDestination(BGP_PORT);
875 reverseMatchDst.setWildcards(forwardMatchDst.getWildcards() & ~OFMatch.OFPFW_TP_DST);
876
877 fm.setMatch(forwardMatchSrc);
878
Jonathan Hart38c84932013-08-10 17:49:27 +1200879 OFMatch forwardIcmpMatch = new OFMatch();
880 forwardIcmpMatch.setDataLayerType(Ethernet.TYPE_IPv4);
881 forwardIcmpMatch.setNetworkProtocol(IPv4.PROTOCOL_ICMP);
882 forwardIcmpMatch.setWildcards(forwardIcmpMatch.getWildcards() &
883 ~OFMatch.OFPFW_DL_TYPE & ~OFMatch.OFPFW_NW_PROTO);
884
885 OFMatch reverseIcmpMatch = forwardIcmpMatch.clone();
886 forwardIcmpMatch.setFromCIDR(interfaceCidrAddress, OFMatch.STR_NW_DST);
887 reverseIcmpMatch.setFromCIDR(interfaceCidrAddress, OFMatch.STR_NW_SRC);
888
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200889 for (FlowEntry flowEntry : path.flowEntries()){
890 OFFlowMod forwardFlowModSrc, forwardFlowModDst;
891 OFFlowMod reverseFlowModSrc, reverseFlowModDst;
Jonathan Hart38c84932013-08-10 17:49:27 +1200892 OFFlowMod forwardIcmp, reverseIcmp;
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200893 try {
894 forwardFlowModSrc = fm.clone();
895 forwardFlowModDst = fm.clone();
896 reverseFlowModSrc = fm.clone();
897 reverseFlowModDst = fm.clone();
Jonathan Hart38c84932013-08-10 17:49:27 +1200898 forwardIcmp = fm.clone();
899 reverseIcmp = fm.clone();
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200900 } catch (CloneNotSupportedException e) {
901 log.warn("Clone failed", e);
902 continue;
903 }
904
905 forwardMatchSrc.setInputPort(flowEntry.inPort().value());
906 forwardFlowModSrc.setMatch(forwardMatchSrc);
907 ((OFActionOutput)forwardFlowModSrc.getActions().get(0))
908 .setPort(flowEntry.outPort().value());
909
910 forwardMatchDst.setInputPort(flowEntry.inPort().value());
911 forwardFlowModDst.setMatch(forwardMatchDst);
912 ((OFActionOutput)forwardFlowModDst.getActions().get(0))
913 .setPort(flowEntry.outPort().value());
914
915 reverseMatchSrc.setInputPort(flowEntry.outPort().value());
916 reverseFlowModSrc.setMatch(reverseMatchSrc);
917 ((OFActionOutput)reverseFlowModSrc.getActions().get(0))
918 .setPort(flowEntry.inPort().value());
919
920 reverseMatchDst.setInputPort(flowEntry.outPort().value());
921 reverseFlowModDst.setMatch(reverseMatchDst);
922 ((OFActionOutput)reverseFlowModDst.getActions().get(0))
923 .setPort(flowEntry.inPort().value());
924
Jonathan Hart38c84932013-08-10 17:49:27 +1200925 ((OFActionOutput)forwardIcmp.getActions().get(0))
926 .setPort(flowEntry.outPort().value());
927 forwardIcmp.setMatch(forwardIcmpMatch);
928
929 ((OFActionOutput)reverseIcmp.getActions().get(0))
930 .setPort(flowEntry.inPort().value());
931 reverseIcmp.setMatch(reverseIcmpMatch);
932
933
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200934 IOFSwitch sw = floodlightProvider.getSwitches().get(flowEntry.dpid().value());
935
Jonathan Hart38c84932013-08-10 17:49:27 +1200936 if (sw == null) {
937 log.warn("Switch not found when pushing BGP paths");
938 return;
939 }
940
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200941 List<OFMessage> msgList = new ArrayList<OFMessage>(2);
942 msgList.add(forwardFlowModSrc);
943 msgList.add(forwardFlowModDst);
944 msgList.add(reverseFlowModSrc);
945 msgList.add(reverseFlowModDst);
Jonathan Hart38c84932013-08-10 17:49:27 +1200946 msgList.add(forwardIcmp);
947 msgList.add(reverseIcmp);
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200948
949 try {
950 sw.write(msgList, null);
951 sw.flush();
952 } catch (IOException e) {
953 log.error("Failure writing flow mod", e);
954 }
955 }
956 }
957 }
Jonathan Hart1236a9b2013-06-18 22:10:05 +1200958
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200959 @Override
960 public void arpResponse(InetAddress ipAddress, byte[] macAddress) {
961 log.debug("Received ARP response: {} => {}", ipAddress.getHostAddress(),
962 MACAddress.valueOf(macAddress).toString());
963
Jonathan Hart0a46fe42013-08-10 17:08:47 +1200964 /*
965 * We synchronize on this to prevent changes to the ptree while we're pushing
966 * flows to the switches. If the ptree changes, the ptree and switches
967 * could get out of sync.
968 */
969 synchronized (this) {
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200970 Path path = pathsWaitingOnArp.remove(ipAddress);
Jonathan Hart309889c2013-08-13 23:26:24 +1200971
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200972 if (path != null) {
Jonathan Hart309889c2013-08-13 23:26:24 +1200973 log.debug("Pushing path to {} at {} on {}", new Object[] {
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200974 path.getDstIpAddress().getHostAddress(),
Jonathan Hart309889c2013-08-13 23:26:24 +1200975 MACAddress.valueOf(macAddress),
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200976 path.getDstInterface().getSwitchPort()});
977 //These paths should always be to BGP peers. Paths to non-peers are
978 //handled once the first prefix is ready to push
979 if (pushedPaths.containsKey(path.getDstInterface())) {
Jonathan Hart309889c2013-08-13 23:26:24 +1200980 //A path already got pushed to this endpoint while we were waiting
981 //for ARP. We'll copy over the permanent attribute if it is set on this path.
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200982 if (path.isPermanent()) {
983 pushedPaths.get(path.getDstInterface()).setPermanent();
Jonathan Hart309889c2013-08-13 23:26:24 +1200984 }
985 }
986 else {
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200987 setUpDataPath(path, MACAddress.valueOf(macAddress));
988 pushedPaths.put(path.getDstIpAddress(), path);
Jonathan Hart309889c2013-08-13 23:26:24 +1200989 }
990 }
991
Jonathan Hart309889c2013-08-13 23:26:24 +1200992 Set<RibUpdate> prefixesToPush = prefixesWaitingOnArp.removeAll(ipAddress);
993
Jonathan Hart0a46fe42013-08-10 17:08:47 +1200994 for (RibUpdate update : prefixesToPush) {
995 //These will always be adds
996
Jonathan Hartb39a67d2013-08-10 23:59:50 +1200997 RibEntry rib = ptree.lookup(update.getPrefix());
Jonathan Hart0a46fe42013-08-10 17:08:47 +1200998 if (rib != null && rib.equals(update.getRibEntry())) {
999 log.debug("Pushing prefix {} next hop {}", update.getPrefix(),
Jonathan Hartb39a67d2013-08-10 23:59:50 +12001000 rib.getNextHop().getHostAddress());
Jonathan Hart0a46fe42013-08-10 17:08:47 +12001001 //We only push prefix flows if the prefix is still in the ptree
1002 //and the next hop is the same as our update. The prefix could
1003 //have been removed while we were waiting for the ARP, or the
1004 //next hop could have changed.
Jonathan Hart309889c2013-08-13 23:26:24 +12001005 _processRibAdd(update);
Jonathan Hart0a46fe42013-08-10 17:08:47 +12001006 } else {
1007 log.debug("Received ARP response, but {},{} is no longer in ptree",
1008 update.getPrefix(), update.getRibEntry());
1009 }
1010 }
Jonathan Hart0ee0f022013-08-03 22:21:54 +12001011 }
Jonathan Hart4dfc3652013-08-02 20:22:36 +12001012 }
1013
Jonathan Hartc82051c2013-08-24 15:12:20 +12001014 private void setupArpFlows() {
1015 OFMatch match = new OFMatch();
1016 match.setDataLayerType(Ethernet.TYPE_ARP);
1017 match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_TYPE);
1018
1019 OFFlowMod fm = new OFFlowMod();
1020 fm.setMatch(match);
1021
1022 OFActionOutput action = new OFActionOutput();
1023 action.setPort(OFPort.OFPP_CONTROLLER.getValue());
1024 action.setMaxLength((short)0xffff);
1025 List<OFAction> actions = new ArrayList<OFAction>(1);
1026 actions.add(action);
1027 fm.setActions(actions);
1028
1029 fm.setIdleTimeout((short)0)
1030 .setHardTimeout((short)0)
1031 .setBufferId(OFPacketOut.BUFFER_ID_NONE)
1032 .setCookie(0)
1033 .setCommand(OFFlowMod.OFPFC_ADD)
1034 .setPriority(ARP_PRIORITY)
1035 .setLengthU(OFFlowMod.MINIMUM_LENGTH + OFActionOutput.MINIMUM_LENGTH);
1036
1037 for (String strdpid : switches){
1038 IOFSwitch sw = floodlightProvider.getSwitches().get(HexString.toLong(strdpid));
1039 if (sw == null) {
1040 log.debug("Couldn't find switch to push ARP flow");
1041 }
1042 else {
1043 try {
1044 sw.write(fm, null);
1045 } catch (IOException e) {
1046 log.warn("Failure writing ARP flow to switch", e);
1047 }
1048 }
1049 }
1050 }
1051
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001052 private void beginRouting(){
1053 log.debug("Topology is now ready, beginning routing function");
Jonathan Hartdefa44d2013-08-15 19:51:13 +12001054 topoRouteTopology = topoRouteService.prepareShortestPathTopo();
1055
Jonathan Hartc82051c2013-08-24 15:12:20 +12001056 setupArpFlows();
1057
Jonathan Hart832a7cb2013-06-24 11:25:35 +12001058 setupBgpPaths();
Jonathan Hart98957bf2013-07-01 14:49:24 +12001059 setupFullMesh();
Jonathan Harte7694532013-09-12 12:34:46 +12001060
1061 //Suppress link discovery on external-facing router ports
1062 for (Interface intf : interfaces.values()) {
1063 linkDiscoveryService.AddToSuppressLLDPs(intf.getDpid(), intf.getPort());
1064 }
1065
Jonathan Hart0a46fe42013-08-10 17:08:47 +12001066 bgpUpdatesExecutor.execute(new Runnable() {
1067 @Override
1068 public void run() {
1069 doUpdatesThread();
1070 }
1071 });
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001072 }
1073
1074 private void checkSwitchesConnected(){
1075 for (String dpid : switches){
1076 if (floodlightProvider.getSwitches().get(HexString.toLong(dpid)) == null){
1077 log.debug("Not all switches are here yet");
1078 return;
1079 }
1080 }
1081 switchesConnected = true;
1082 }
1083
Jonathan Hartc824ad02013-07-03 15:58:45 +12001084 //Actually we only need to go half way round to verify full mesh connectivity
1085 //(n^2)/2
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001086 private void checkTopologyReady(){
Jonathan Hartc824ad02013-07-03 15:58:45 +12001087 for (Interface dstInterface : interfaces.values()) {
1088 for (Interface srcInterface : interfaces.values()) {
1089 if (dstInterface == srcInterface) {
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001090 continue;
1091 }
1092
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001093 DataPath shortestPath = topoRouteService.getShortestPath(
Jonathan Hartc824ad02013-07-03 15:58:45 +12001094 srcInterface.getSwitchPort(), dstInterface.getSwitchPort());
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001095
1096 if (shortestPath == null){
1097 log.debug("Shortest path between {} and {} not found",
Jonathan Hartc824ad02013-07-03 15:58:45 +12001098 srcInterface.getSwitchPort(), dstInterface.getSwitchPort());
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001099 return;
1100 }
1101 }
1102 }
1103 topologyReady = true;
1104 }
1105
1106 private void checkStatus(){
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001107 if (!switchesConnected){
1108 checkSwitchesConnected();
1109 }
1110 boolean oldTopologyReadyStatus = topologyReady;
1111 if (switchesConnected && !topologyReady){
1112 checkTopologyReady();
1113 }
1114 if (!oldTopologyReadyStatus && topologyReady){
1115 beginRouting();
1116 }
1117 }
Jonathan Harta23ffdb2013-08-14 14:36:54 +12001118
Jonathan Hart8b9349e2013-07-26 15:55:28 +12001119 private void doUpdatesThread() {
1120 boolean interrupted = false;
1121 try {
1122 while (true) {
1123 try {
1124 RibUpdate update = ribUpdates.take();
1125 switch (update.getOperation()){
1126 case UPDATE:
Jonathan Hart2f740782013-08-04 00:49:21 +12001127 processRibAdd(update);
Jonathan Hart8b9349e2013-07-26 15:55:28 +12001128 break;
1129 case DELETE:
Jonathan Hart2f740782013-08-04 00:49:21 +12001130 processRibDelete(update);
Jonathan Hart8b9349e2013-07-26 15:55:28 +12001131 break;
1132 }
1133 } catch (InterruptedException e) {
Jonathan Harta23ffdb2013-08-14 14:36:54 +12001134 log.debug("Interrupted while taking from updates queue", e);
Jonathan Hart8b9349e2013-07-26 15:55:28 +12001135 interrupted = true;
Jonathan Hart309889c2013-08-13 23:26:24 +12001136 } catch (Exception e) {
1137 log.debug("exception", e);
Jonathan Hart8b9349e2013-07-26 15:55:28 +12001138 }
1139 }
1140 } finally {
1141 if (interrupted) {
1142 Thread.currentThread().interrupt();
1143 }
1144 }
1145 }
pingping-lina2cbfad2013-03-07 08:39:21 +08001146
1147 @Override
Jonathan Hart64c0b202013-08-20 15:45:07 +12001148 public void topologyChanged() {
1149 if (topologyReady) {
1150 return;
1151 }
1152
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001153 boolean refreshNeeded = false;
1154 for (LDUpdate ldu : topology.getLastLinkUpdates()){
1155 if (!ldu.getOperation().equals(ILinkDiscovery.UpdateOperation.LINK_UPDATED)){
1156 //We don't need to recalculate anything for just link updates
Jonathan Hartb39a67d2013-08-10 23:59:50 +12001157 //They happen very frequently
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001158 refreshNeeded = true;
1159 }
Jonathan Hart98957bf2013-07-01 14:49:24 +12001160
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001161 log.debug("Topo change {}", ldu.getOperation());
Jonathan Hartc824ad02013-07-03 15:58:45 +12001162
Jonathan Hart98957bf2013-07-01 14:49:24 +12001163 if (ldu.getOperation().equals(ILinkDiscovery.UpdateOperation.LINK_ADDED)){
1164 synchronized (linkUpdates) {
1165 linkUpdates.add(ldu);
1166 }
1167 }
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001168 }
1169
Jonathan Hart64c0b202013-08-20 15:45:07 +12001170 if (refreshNeeded && !topologyReady){
Jonathan Hart98957bf2013-07-01 14:49:24 +12001171 topologyChangeDetectorTask.reschedule(TOPO_DETECTION_WAIT, TimeUnit.SECONDS);
pingping-lina2cbfad2013-03-07 08:39:21 +08001172 }
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001173 }
Jonathan Hart64c0b202013-08-20 15:45:07 +12001174
1175 @Override
1176 public void addedSwitch(IOFSwitch sw) {
1177 if (!topologyReady) {
1178 sw.clearAllFlowMods();
1179 }
1180 }
1181
1182 @Override
1183 public void removedSwitch(IOFSwitch sw) {
1184 // TODO Auto-generated method stub
1185
1186 }
1187
1188 @Override
1189 public void switchPortChanged(Long switchId) {
1190 // TODO Auto-generated method stub
1191
1192 }
1193
1194 @Override
1195 public String getName() {
1196 // TODO Auto-generated method stub
1197 return null;
1198 }
pingping-lina2cbfad2013-03-07 08:39:21 +08001199}