blob: 4aa70f1e2376c0b42f3599c9d2547eac306bcfb1 [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();
Jonathan Hart65139e42013-09-13 16:52:25 +1200575 Thread.sleep(0, 100000);
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200576 } catch (IOException e) {
577 log.error("Failure writing flow mod", e);
Jonathan Hart65139e42013-09-13 16:52:25 +1200578 } catch (InterruptedException e) {
579 // TODO handle this properly
580 log.error("Interrupted", e);
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200581 }
Jonathan Hart309889c2013-08-13 23:26:24 +1200582 }
583 }
Jonathan Hart309889c2013-08-13 23:26:24 +1200584
Jonathan Hart0a46fe42013-08-10 17:08:47 +1200585 public synchronized void processRibDelete(RibUpdate update) {
Jonathan Hart8b9349e2013-07-26 15:55:28 +1200586 Prefix prefix = update.getPrefix();
587
Jonathan Hartd7e158d2013-08-07 23:04:48 +1200588 if (ptree.remove(prefix, update.getRibEntry())) {
589 /*
590 * Only delete flows if an entry was actually removed from the trie.
591 * If no entry was removed, the <prefix, nexthop> wasn't there so
592 * it's probably already been removed and we don't need to do anything
593 */
Jonathan Hart309889c2013-08-13 23:26:24 +1200594 _processDeletePrefix(prefix, update.getRibEntry());
Jonathan Hart309889c2013-08-13 23:26:24 +1200595 }
596 }
597
598 private void _processDeletePrefix(Prefix prefix, RibEntry ribEntry) {
599 deletePrefixFlows(prefix);
600
601 log.debug("Deleting {} to {}", prefix, ribEntry.getNextHop());
Jonathan Hartd992f1a2013-09-13 13:46:44 +1200602
Jonathan Hart309889c2013-08-13 23:26:24 +1200603 if (!bgpPeers.containsKey(ribEntry.getNextHop())) {
604 log.debug("Getting path for route with non-peer nexthop");
Jonathan Hartfb1ebc52013-08-17 16:25:51 +1200605 //Path path = prefixToPath.get(prefix);
606 Path path = prefixToPath.remove(prefix);
Jonathan Hart309889c2013-08-13 23:26:24 +1200607
Jonathan Hartd992f1a2013-09-13 13:46:44 +1200608 if (path != null) {
609 //path could be null if we added to the Ptree but didn't push
610 //flows yet because we were waiting to resolve ARP
Jonathan Hart309889c2013-08-13 23:26:24 +1200611
Jonathan Hartd992f1a2013-09-13 13:46:44 +1200612 path.decrementUsers();
613 log.debug("users {}, permanent {}", path.getUsers(), path.isPermanent());
614 if (path.getUsers() <= 0 && !path.isPermanent()) {
615 deletePath(path);
616 pushedPaths.remove(path.getDstIpAddress());
617 }
Jonathan Hart309889c2013-08-13 23:26:24 +1200618 }
619 }
620 }
621
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200622 private void deletePrefixFlows(Prefix prefix) {
623 Collection<PushedFlowMod> pushedFlowMods
624 = pushedFlows.removeAll(prefix);
625
626 for (PushedFlowMod pfm : pushedFlowMods) {
627 log.debug("Pushing a DELETE flow mod to {}, matches prefix {} with mac-rewrite {}",
628 new Object[] {HexString.toHexString(pfm.getDpid()),
629 pfm.getFlowMod().getMatch().getNetworkDestination() +
630 pfm.getFlowMod().getMatch().getNetworkDestinationMaskLen(),
631 HexString.toHexString(((OFActionDataLayerDestination)pfm.getFlowMod().getActions().get(0))
632 .getDataLayerAddress())});
633
634 sendDeleteFlowMod(pfm.getFlowMod(), pfm.getDpid());
635 }
636 }
637
638 private void deletePath(Path path) {
Jonathan Hart309889c2013-08-13 23:26:24 +1200639 for (PushedFlowMod pfm : path.getFlowMods()) {
640 log.debug("Pushing a DELETE flow mod to {}, dst MAC {}",
641 new Object[] {HexString.toHexString(pfm.getDpid()),
642 HexString.toHexString(pfm.getFlowMod().getMatch().getDataLayerDestination())
643 });
644
645 sendDeleteFlowMod(pfm.getFlowMod(), pfm.getDpid());
646 }
647 }
648
649 private void sendDeleteFlowMod(OFFlowMod addFlowMod, long dpid) {
650 addFlowMod.setCommand(OFFlowMod.OFPFC_DELETE_STRICT)
651 .setOutPort(OFPort.OFPP_NONE)
652 .setLengthU(OFFlowMod.MINIMUM_LENGTH);
653
654 addFlowMod.getActions().clear();
655
656 IOFSwitch sw = floodlightProvider.getSwitches().get(dpid);
657 if (sw == null) {
658 log.warn("Switch not found when pushing delete flow mod");
659 return;
660 }
661
662 try {
663 sw.write(addFlowMod, null);
664 sw.flush();
665 } catch (IOException e) {
666 log.error("Failure writing flow mod", e);
Jonathan Hartd7e158d2013-08-07 23:04:48 +1200667 }
Jonathan Hart8b9349e2013-07-26 15:55:28 +1200668 }
669
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200670 //TODO test next-hop changes
Jonathan Hart2f740782013-08-04 00:49:21 +1200671 //TODO check delete/add synchronization
Jonathan Hart0ee0f022013-08-03 22:21:54 +1200672
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700673 /*
674 * On startup we need to calculate a full mesh of paths between all gateway
675 * switches
676 */
Jonathan Hart1236a9b2013-06-18 22:10:05 +1200677 private void setupFullMesh(){
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700678 //For each border router, calculate and install a path from every other
679 //border switch to said border router. However, don't install the entry
680 //in to the first hop switch, as we need to install an entry to rewrite
681 //for each prefix received. This will be done later when prefixes have
682 //actually been received.
683
Jonathan Hartc824ad02013-07-03 15:58:45 +1200684 for (BgpPeer peer : bgpPeers.values()) {
685 Interface peerInterface = interfaces.get(peer.getInterfaceName());
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200686
Jonathan Hart309889c2013-08-13 23:26:24 +1200687 //We know there's not already a Path here pushed, because this is
688 //called before all other routing
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200689 Path path = new Path(peerInterface, peer.getIpAddress());
Jonathan Hart309889c2013-08-13 23:26:24 +1200690 path.setPermanent();
691
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200692 //See if we know the MAC address of the peer. If not we can't
693 //do anything until we learn it
694 byte[] mac = proxyArp.getMacAddress(peer.getIpAddress());
695 if (mac == null) {
696 log.debug("Don't know MAC for {}", peer.getIpAddress().getHostAddress());
697 //Put in the pending paths list first
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200698 pathsWaitingOnArp.put(peer.getIpAddress(), path);
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700699
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200700 proxyArp.sendArpRequest(peer.getIpAddress(), this, true);
701 continue;
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700702 }
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200703
704 //If we know the MAC, lets go ahead and push the paths to this peer
Jonathan Hart309889c2013-08-13 23:26:24 +1200705 setUpDataPath(path, MACAddress.valueOf(mac));
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700706 }
707 }
708
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200709 private void setUpDataPath(Path path, MACAddress dstMacAddress) {
710 calculateAndPushPath(path, dstMacAddress);
Jonathan Hart309889c2013-08-13 23:26:24 +1200711 }
712
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200713 private void calculateAndPushPath(Path path, MACAddress dstMacAddress) {
Jonathan Hart309889c2013-08-13 23:26:24 +1200714 Interface dstInterface = path.getDstInterface();
715
Jonathan Hartfb1ebc52013-08-17 16:25:51 +1200716 log.debug("Setting up path to {}, {}", path.getDstIpAddress().getHostAddress(),
717 dstMacAddress);
718
Jonathan Hart309889c2013-08-13 23:26:24 +1200719 List<PushedFlowMod> pushedFlows = new ArrayList<PushedFlowMod>();
720
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200721 for (Interface srcInterface : interfaces.values()) {
722 if (dstInterface.equals(srcInterface.getName())){
723 continue;
724 }
725
Jonathan Hartdefa44d2013-08-15 19:51:13 +1200726 DataPath shortestPath;
727 if (topoRouteTopology == null) {
728 log.debug("Using database topo");
729 shortestPath = topoRouteService.getShortestPath(
730 srcInterface.getSwitchPort(), dstInterface.getSwitchPort());
731 }
732 else {
733 log.debug("Using prepared topo");
734 shortestPath = topoRouteService.getTopoShortestPath(topoRouteTopology,
735 srcInterface.getSwitchPort(), dstInterface.getSwitchPort());
736 }
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200737
738 if (shortestPath == null){
739 log.debug("Shortest path between {} and {} not found",
740 srcInterface.getSwitchPort(), dstInterface.getSwitchPort());
741 return; // just quit here?
742 }
743
Jonathan Hart309889c2013-08-13 23:26:24 +1200744 pushedFlows.addAll(installPath(shortestPath.flowEntries(), dstMacAddress));
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200745 }
Jonathan Hart309889c2013-08-13 23:26:24 +1200746
747 path.setFlowMods(pushedFlows);
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200748 }
749
Jonathan Hart309889c2013-08-13 23:26:24 +1200750 private List<PushedFlowMod> installPath(List<FlowEntry> flowEntries, MACAddress dstMacAddress){
751 List<PushedFlowMod> flowMods = new ArrayList<PushedFlowMod>();
752
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700753 //Set up the flow mod
754 OFFlowMod fm =
755 (OFFlowMod) floodlightProvider.getOFMessageFactory()
756 .getMessage(OFType.FLOW_MOD);
757
758 OFActionOutput action = new OFActionOutput();
759 action.setMaxLength((short)0xffff);
760 List<OFAction> actions = new ArrayList<OFAction>();
761 actions.add(action);
762
763 fm.setIdleTimeout((short)0)
764 .setHardTimeout((short)0)
765 .setBufferId(OFPacketOut.BUFFER_ID_NONE)
766 .setCookie(L2_FWD_COOKIE)
767 .setCommand(OFFlowMod.OFPFC_ADD)
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700768 .setActions(actions)
769 .setLengthU(OFFlowMod.MINIMUM_LENGTH+OFActionOutput.MINIMUM_LENGTH);
770
771 //Don't push the first flow entry. We need to push entries in the
772 //first switch based on IP prefix which we don't know yet.
773 for (int i = 1; i < flowEntries.size(); i++){
774 FlowEntry flowEntry = flowEntries.get(i);
775
776 OFMatch match = new OFMatch();
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200777 match.setDataLayerDestination(dstMacAddress.toBytes());
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700778 match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_DST);
779 ((OFActionOutput) fm.getActions().get(0)).setPort(flowEntry.outPort().value());
780
781 fm.setMatch(match);
782
783 IOFSwitch sw = floodlightProvider.getSwitches().get(flowEntry.dpid().value());
784
785 if (sw == null){
786 log.warn("Switch not found when pushing flow mod");
787 continue;
788 }
789
Jonathan Hart309889c2013-08-13 23:26:24 +1200790 flowMods.add(new PushedFlowMod(sw.getId(), fm));
791
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700792 List<OFMessage> msglist = new ArrayList<OFMessage>();
793 msglist.add(fm);
794 try {
795 sw.write(msglist, null);
796 sw.flush();
797 } catch (IOException e) {
798 log.error("Failure writing flow mod", e);
799 }
800
801 try {
802 fm = fm.clone();
803 } catch (CloneNotSupportedException e1) {
804 log.error("Failure cloning flow mod", e1);
805 }
806 }
Jonathan Hart309889c2013-08-13 23:26:24 +1200807
808 return flowMods;
Jonathan Harte7e1c6e2013-06-04 20:50:23 -0700809 }
810
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200811 private void setupBgpPaths(){
Jonathan Hartc824ad02013-07-03 15:58:45 +1200812 for (BgpPeer bgpPeer : bgpPeers.values()){
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200813 Interface peerInterface = interfaces.get(bgpPeer.getInterfaceName());
814
815 DataPath path = topoRouteService.getShortestPath(
816 peerInterface.getSwitchPort(), bgpdAttachmentPoint);
817
818 if (path == null){
819 log.debug("Unable to compute path for BGP traffic for {}",
820 bgpPeer.getIpAddress());
821 continue;
822 }
823
824 //Set up the flow mod
825 OFFlowMod fm =
826 (OFFlowMod) floodlightProvider.getOFMessageFactory()
827 .getMessage(OFType.FLOW_MOD);
828
829 OFActionOutput action = new OFActionOutput();
830 action.setMaxLength((short)0xffff);
831 List<OFAction> actions = new ArrayList<OFAction>();
832 actions.add(action);
833
834 fm.setIdleTimeout((short)0)
835 .setHardTimeout((short)0)
836 .setBufferId(OFPacketOut.BUFFER_ID_NONE)
837 .setCookie(BGP_COOKIE)
838 .setCommand(OFFlowMod.OFPFC_ADD)
839 .setPriority(SDNIP_PRIORITY)
840 .setActions(actions)
841 .setLengthU(OFFlowMod.MINIMUM_LENGTH+OFActionOutput.MINIMUM_LENGTH);
842
843 //Forward = gateway -> bgpd, reverse = bgpd -> gateway
844 OFMatch forwardMatchSrc = new OFMatch();
845
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200846 String interfaceCidrAddress = peerInterface.getIpAddress().getHostAddress()
847 + "/32";
848 String peerCidrAddress = bgpPeer.getIpAddress().getHostAddress()
849 + "/32";
Jonathan Hart38c84932013-08-10 17:49:27 +1200850
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200851 //Common match fields
852 forwardMatchSrc.setDataLayerType(Ethernet.TYPE_IPv4);
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200853 forwardMatchSrc.setNetworkProtocol(IPv4.PROTOCOL_TCP);
854 forwardMatchSrc.setTransportDestination(BGP_PORT);
855 forwardMatchSrc.setWildcards(forwardMatchSrc.getWildcards() & ~OFMatch.OFPFW_IN_PORT
856 & ~OFMatch.OFPFW_DL_TYPE & ~OFMatch.OFPFW_NW_PROTO);
857
858
859 OFMatch reverseMatchSrc = forwardMatchSrc.clone();
860
861 forwardMatchSrc.setFromCIDR(peerCidrAddress, OFMatch.STR_NW_SRC);
862 forwardMatchSrc.setFromCIDR(interfaceCidrAddress, OFMatch.STR_NW_DST);
863
864 OFMatch forwardMatchDst = forwardMatchSrc.clone();
865
866 forwardMatchSrc.setTransportSource(BGP_PORT);
867 forwardMatchSrc.setWildcards(forwardMatchSrc.getWildcards() & ~OFMatch.OFPFW_TP_SRC);
868 forwardMatchDst.setTransportDestination(BGP_PORT);
869 forwardMatchDst.setWildcards(forwardMatchDst.getWildcards() & ~OFMatch.OFPFW_TP_DST);
870
871 reverseMatchSrc.setFromCIDR(interfaceCidrAddress, OFMatch.STR_NW_SRC);
872 reverseMatchSrc.setFromCIDR(peerCidrAddress, OFMatch.STR_NW_DST);
873
874 OFMatch reverseMatchDst = reverseMatchSrc.clone();
875
876 reverseMatchSrc.setTransportSource(BGP_PORT);
877 reverseMatchSrc.setWildcards(forwardMatchSrc.getWildcards() & ~OFMatch.OFPFW_TP_SRC);
878 reverseMatchDst.setTransportDestination(BGP_PORT);
879 reverseMatchDst.setWildcards(forwardMatchDst.getWildcards() & ~OFMatch.OFPFW_TP_DST);
880
881 fm.setMatch(forwardMatchSrc);
882
Jonathan Hart38c84932013-08-10 17:49:27 +1200883 OFMatch forwardIcmpMatch = new OFMatch();
884 forwardIcmpMatch.setDataLayerType(Ethernet.TYPE_IPv4);
885 forwardIcmpMatch.setNetworkProtocol(IPv4.PROTOCOL_ICMP);
886 forwardIcmpMatch.setWildcards(forwardIcmpMatch.getWildcards() &
887 ~OFMatch.OFPFW_DL_TYPE & ~OFMatch.OFPFW_NW_PROTO);
888
889 OFMatch reverseIcmpMatch = forwardIcmpMatch.clone();
890 forwardIcmpMatch.setFromCIDR(interfaceCidrAddress, OFMatch.STR_NW_DST);
891 reverseIcmpMatch.setFromCIDR(interfaceCidrAddress, OFMatch.STR_NW_SRC);
892
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200893 for (FlowEntry flowEntry : path.flowEntries()){
894 OFFlowMod forwardFlowModSrc, forwardFlowModDst;
895 OFFlowMod reverseFlowModSrc, reverseFlowModDst;
Jonathan Hart38c84932013-08-10 17:49:27 +1200896 OFFlowMod forwardIcmp, reverseIcmp;
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200897 try {
898 forwardFlowModSrc = fm.clone();
899 forwardFlowModDst = fm.clone();
900 reverseFlowModSrc = fm.clone();
901 reverseFlowModDst = fm.clone();
Jonathan Hart38c84932013-08-10 17:49:27 +1200902 forwardIcmp = fm.clone();
903 reverseIcmp = fm.clone();
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200904 } catch (CloneNotSupportedException e) {
905 log.warn("Clone failed", e);
906 continue;
907 }
908
909 forwardMatchSrc.setInputPort(flowEntry.inPort().value());
910 forwardFlowModSrc.setMatch(forwardMatchSrc);
911 ((OFActionOutput)forwardFlowModSrc.getActions().get(0))
912 .setPort(flowEntry.outPort().value());
913
914 forwardMatchDst.setInputPort(flowEntry.inPort().value());
915 forwardFlowModDst.setMatch(forwardMatchDst);
916 ((OFActionOutput)forwardFlowModDst.getActions().get(0))
917 .setPort(flowEntry.outPort().value());
918
919 reverseMatchSrc.setInputPort(flowEntry.outPort().value());
920 reverseFlowModSrc.setMatch(reverseMatchSrc);
921 ((OFActionOutput)reverseFlowModSrc.getActions().get(0))
922 .setPort(flowEntry.inPort().value());
923
924 reverseMatchDst.setInputPort(flowEntry.outPort().value());
925 reverseFlowModDst.setMatch(reverseMatchDst);
926 ((OFActionOutput)reverseFlowModDst.getActions().get(0))
927 .setPort(flowEntry.inPort().value());
928
Jonathan Hart38c84932013-08-10 17:49:27 +1200929 ((OFActionOutput)forwardIcmp.getActions().get(0))
930 .setPort(flowEntry.outPort().value());
931 forwardIcmp.setMatch(forwardIcmpMatch);
932
933 ((OFActionOutput)reverseIcmp.getActions().get(0))
934 .setPort(flowEntry.inPort().value());
935 reverseIcmp.setMatch(reverseIcmpMatch);
936
937
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200938 IOFSwitch sw = floodlightProvider.getSwitches().get(flowEntry.dpid().value());
939
Jonathan Hart38c84932013-08-10 17:49:27 +1200940 if (sw == null) {
941 log.warn("Switch not found when pushing BGP paths");
942 return;
943 }
944
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200945 List<OFMessage> msgList = new ArrayList<OFMessage>(2);
946 msgList.add(forwardFlowModSrc);
947 msgList.add(forwardFlowModDst);
948 msgList.add(reverseFlowModSrc);
949 msgList.add(reverseFlowModDst);
Jonathan Hart38c84932013-08-10 17:49:27 +1200950 msgList.add(forwardIcmp);
951 msgList.add(reverseIcmp);
Jonathan Hart832a7cb2013-06-24 11:25:35 +1200952
953 try {
954 sw.write(msgList, null);
955 sw.flush();
956 } catch (IOException e) {
957 log.error("Failure writing flow mod", e);
958 }
959 }
960 }
961 }
Jonathan Hart1236a9b2013-06-18 22:10:05 +1200962
Jonathan Hart4dfc3652013-08-02 20:22:36 +1200963 @Override
964 public void arpResponse(InetAddress ipAddress, byte[] macAddress) {
965 log.debug("Received ARP response: {} => {}", ipAddress.getHostAddress(),
966 MACAddress.valueOf(macAddress).toString());
967
Jonathan Hart0a46fe42013-08-10 17:08:47 +1200968 /*
969 * We synchronize on this to prevent changes to the ptree while we're pushing
970 * flows to the switches. If the ptree changes, the ptree and switches
971 * could get out of sync.
972 */
973 synchronized (this) {
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200974 Path path = pathsWaitingOnArp.remove(ipAddress);
Jonathan Hart309889c2013-08-13 23:26:24 +1200975
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200976 if (path != null) {
Jonathan Hart309889c2013-08-13 23:26:24 +1200977 log.debug("Pushing path to {} at {} on {}", new Object[] {
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200978 path.getDstIpAddress().getHostAddress(),
Jonathan Hart309889c2013-08-13 23:26:24 +1200979 MACAddress.valueOf(macAddress),
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200980 path.getDstInterface().getSwitchPort()});
981 //These paths should always be to BGP peers. Paths to non-peers are
982 //handled once the first prefix is ready to push
983 if (pushedPaths.containsKey(path.getDstInterface())) {
Jonathan Hart309889c2013-08-13 23:26:24 +1200984 //A path already got pushed to this endpoint while we were waiting
985 //for ARP. We'll copy over the permanent attribute if it is set on this path.
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200986 if (path.isPermanent()) {
987 pushedPaths.get(path.getDstInterface()).setPermanent();
Jonathan Hart309889c2013-08-13 23:26:24 +1200988 }
989 }
990 else {
Jonathan Harta23ffdb2013-08-14 14:36:54 +1200991 setUpDataPath(path, MACAddress.valueOf(macAddress));
992 pushedPaths.put(path.getDstIpAddress(), path);
Jonathan Hart309889c2013-08-13 23:26:24 +1200993 }
994 }
995
Jonathan Hart309889c2013-08-13 23:26:24 +1200996 Set<RibUpdate> prefixesToPush = prefixesWaitingOnArp.removeAll(ipAddress);
997
Jonathan Hart0a46fe42013-08-10 17:08:47 +1200998 for (RibUpdate update : prefixesToPush) {
999 //These will always be adds
1000
Jonathan Hartb39a67d2013-08-10 23:59:50 +12001001 RibEntry rib = ptree.lookup(update.getPrefix());
Jonathan Hart0a46fe42013-08-10 17:08:47 +12001002 if (rib != null && rib.equals(update.getRibEntry())) {
1003 log.debug("Pushing prefix {} next hop {}", update.getPrefix(),
Jonathan Hartb39a67d2013-08-10 23:59:50 +12001004 rib.getNextHop().getHostAddress());
Jonathan Hart0a46fe42013-08-10 17:08:47 +12001005 //We only push prefix flows if the prefix is still in the ptree
1006 //and the next hop is the same as our update. The prefix could
1007 //have been removed while we were waiting for the ARP, or the
1008 //next hop could have changed.
Jonathan Hart309889c2013-08-13 23:26:24 +12001009 _processRibAdd(update);
Jonathan Hart0a46fe42013-08-10 17:08:47 +12001010 } else {
1011 log.debug("Received ARP response, but {},{} is no longer in ptree",
1012 update.getPrefix(), update.getRibEntry());
1013 }
1014 }
Jonathan Hart0ee0f022013-08-03 22:21:54 +12001015 }
Jonathan Hart4dfc3652013-08-02 20:22:36 +12001016 }
1017
Jonathan Hartc82051c2013-08-24 15:12:20 +12001018 private void setupArpFlows() {
1019 OFMatch match = new OFMatch();
1020 match.setDataLayerType(Ethernet.TYPE_ARP);
1021 match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_TYPE);
1022
1023 OFFlowMod fm = new OFFlowMod();
1024 fm.setMatch(match);
1025
1026 OFActionOutput action = new OFActionOutput();
1027 action.setPort(OFPort.OFPP_CONTROLLER.getValue());
1028 action.setMaxLength((short)0xffff);
1029 List<OFAction> actions = new ArrayList<OFAction>(1);
1030 actions.add(action);
1031 fm.setActions(actions);
1032
1033 fm.setIdleTimeout((short)0)
1034 .setHardTimeout((short)0)
1035 .setBufferId(OFPacketOut.BUFFER_ID_NONE)
1036 .setCookie(0)
1037 .setCommand(OFFlowMod.OFPFC_ADD)
1038 .setPriority(ARP_PRIORITY)
1039 .setLengthU(OFFlowMod.MINIMUM_LENGTH + OFActionOutput.MINIMUM_LENGTH);
1040
1041 for (String strdpid : switches){
1042 IOFSwitch sw = floodlightProvider.getSwitches().get(HexString.toLong(strdpid));
1043 if (sw == null) {
1044 log.debug("Couldn't find switch to push ARP flow");
1045 }
1046 else {
1047 try {
1048 sw.write(fm, null);
1049 } catch (IOException e) {
1050 log.warn("Failure writing ARP flow to switch", e);
1051 }
1052 }
1053 }
1054 }
1055
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001056 private void beginRouting(){
1057 log.debug("Topology is now ready, beginning routing function");
Jonathan Hartdefa44d2013-08-15 19:51:13 +12001058 topoRouteTopology = topoRouteService.prepareShortestPathTopo();
1059
Jonathan Hartc82051c2013-08-24 15:12:20 +12001060 setupArpFlows();
1061
Jonathan Hart832a7cb2013-06-24 11:25:35 +12001062 setupBgpPaths();
Jonathan Hart98957bf2013-07-01 14:49:24 +12001063 setupFullMesh();
Jonathan Harte7694532013-09-12 12:34:46 +12001064
1065 //Suppress link discovery on external-facing router ports
1066 for (Interface intf : interfaces.values()) {
1067 linkDiscoveryService.AddToSuppressLLDPs(intf.getDpid(), intf.getPort());
1068 }
1069
Jonathan Hart0a46fe42013-08-10 17:08:47 +12001070 bgpUpdatesExecutor.execute(new Runnable() {
1071 @Override
1072 public void run() {
1073 doUpdatesThread();
1074 }
1075 });
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001076 }
1077
1078 private void checkSwitchesConnected(){
1079 for (String dpid : switches){
1080 if (floodlightProvider.getSwitches().get(HexString.toLong(dpid)) == null){
1081 log.debug("Not all switches are here yet");
1082 return;
1083 }
1084 }
1085 switchesConnected = true;
1086 }
1087
Jonathan Hartc824ad02013-07-03 15:58:45 +12001088 //Actually we only need to go half way round to verify full mesh connectivity
1089 //(n^2)/2
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001090 private void checkTopologyReady(){
Jonathan Hartc824ad02013-07-03 15:58:45 +12001091 for (Interface dstInterface : interfaces.values()) {
1092 for (Interface srcInterface : interfaces.values()) {
1093 if (dstInterface == srcInterface) {
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001094 continue;
1095 }
1096
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001097 DataPath shortestPath = topoRouteService.getShortestPath(
Jonathan Hartc824ad02013-07-03 15:58:45 +12001098 srcInterface.getSwitchPort(), dstInterface.getSwitchPort());
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001099
1100 if (shortestPath == null){
1101 log.debug("Shortest path between {} and {} not found",
Jonathan Hartc824ad02013-07-03 15:58:45 +12001102 srcInterface.getSwitchPort(), dstInterface.getSwitchPort());
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001103 return;
1104 }
1105 }
1106 }
1107 topologyReady = true;
1108 }
1109
1110 private void checkStatus(){
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001111 if (!switchesConnected){
1112 checkSwitchesConnected();
1113 }
1114 boolean oldTopologyReadyStatus = topologyReady;
1115 if (switchesConnected && !topologyReady){
1116 checkTopologyReady();
1117 }
1118 if (!oldTopologyReadyStatus && topologyReady){
1119 beginRouting();
1120 }
1121 }
Jonathan Harta23ffdb2013-08-14 14:36:54 +12001122
Jonathan Hart8b9349e2013-07-26 15:55:28 +12001123 private void doUpdatesThread() {
1124 boolean interrupted = false;
1125 try {
1126 while (true) {
1127 try {
1128 RibUpdate update = ribUpdates.take();
1129 switch (update.getOperation()){
1130 case UPDATE:
Jonathan Hart2f740782013-08-04 00:49:21 +12001131 processRibAdd(update);
Jonathan Hart8b9349e2013-07-26 15:55:28 +12001132 break;
1133 case DELETE:
Jonathan Hart2f740782013-08-04 00:49:21 +12001134 processRibDelete(update);
Jonathan Hart8b9349e2013-07-26 15:55:28 +12001135 break;
1136 }
1137 } catch (InterruptedException e) {
Jonathan Harta23ffdb2013-08-14 14:36:54 +12001138 log.debug("Interrupted while taking from updates queue", e);
Jonathan Hart8b9349e2013-07-26 15:55:28 +12001139 interrupted = true;
Jonathan Hart309889c2013-08-13 23:26:24 +12001140 } catch (Exception e) {
1141 log.debug("exception", e);
Jonathan Hart8b9349e2013-07-26 15:55:28 +12001142 }
1143 }
1144 } finally {
1145 if (interrupted) {
1146 Thread.currentThread().interrupt();
1147 }
1148 }
1149 }
pingping-lina2cbfad2013-03-07 08:39:21 +08001150
1151 @Override
Jonathan Hart64c0b202013-08-20 15:45:07 +12001152 public void topologyChanged() {
1153 if (topologyReady) {
1154 return;
1155 }
1156
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001157 boolean refreshNeeded = false;
1158 for (LDUpdate ldu : topology.getLastLinkUpdates()){
1159 if (!ldu.getOperation().equals(ILinkDiscovery.UpdateOperation.LINK_UPDATED)){
1160 //We don't need to recalculate anything for just link updates
Jonathan Hartb39a67d2013-08-10 23:59:50 +12001161 //They happen very frequently
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001162 refreshNeeded = true;
1163 }
Jonathan Hart98957bf2013-07-01 14:49:24 +12001164
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001165 log.debug("Topo change {}", ldu.getOperation());
Jonathan Hartc824ad02013-07-03 15:58:45 +12001166
Jonathan Hart98957bf2013-07-01 14:49:24 +12001167 if (ldu.getOperation().equals(ILinkDiscovery.UpdateOperation.LINK_ADDED)){
1168 synchronized (linkUpdates) {
1169 linkUpdates.add(ldu);
1170 }
1171 }
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001172 }
1173
Jonathan Hart64c0b202013-08-20 15:45:07 +12001174 if (refreshNeeded && !topologyReady){
Jonathan Hart98957bf2013-07-01 14:49:24 +12001175 topologyChangeDetectorTask.reschedule(TOPO_DETECTION_WAIT, TimeUnit.SECONDS);
pingping-lina2cbfad2013-03-07 08:39:21 +08001176 }
Jonathan Hart1236a9b2013-06-18 22:10:05 +12001177 }
Jonathan Hart64c0b202013-08-20 15:45:07 +12001178
1179 @Override
1180 public void addedSwitch(IOFSwitch sw) {
1181 if (!topologyReady) {
1182 sw.clearAllFlowMods();
1183 }
1184 }
1185
1186 @Override
1187 public void removedSwitch(IOFSwitch sw) {
1188 // TODO Auto-generated method stub
1189
1190 }
1191
1192 @Override
1193 public void switchPortChanged(Long switchId) {
1194 // TODO Auto-generated method stub
1195
1196 }
1197
1198 @Override
1199 public String getName() {
1200 // TODO Auto-generated method stub
1201 return null;
1202 }
pingping-lina2cbfad2013-03-07 08:39:21 +08001203}