blob: 6c25b7d817cd50f7d31779dbed2270470bcc3aaa [file] [log] [blame]
sanghob35a6192015-04-01 13:05:26 -07001/*
Brian O'Connor5ab426f2016-04-09 01:19:45 -07002 * Copyright 2015-present Open Networking Laboratory
sanghob35a6192015-04-01 13:05:26 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.segmentrouting;
17
Charles Chanc81c45b2016-10-20 17:02:44 -070018import com.google.common.collect.Maps;
sanghob35a6192015-04-01 13:05:26 -070019import org.apache.felix.scr.annotations.Activate;
20import org.apache.felix.scr.annotations.Component;
21import org.apache.felix.scr.annotations.Deactivate;
22import org.apache.felix.scr.annotations.Reference;
23import org.apache.felix.scr.annotations.ReferenceCardinality;
sangho1e575652015-05-14 00:39:53 -070024import org.apache.felix.scr.annotations.Service;
sanghob35a6192015-04-01 13:05:26 -070025import org.onlab.packet.Ethernet;
Charles Chanc42e84e2015-10-20 16:24:19 -070026import org.onlab.packet.IPv4;
Charles Chanc42e84e2015-10-20 16:24:19 -070027import org.onlab.packet.Ip4Prefix;
Charles Chanc42e84e2015-10-20 16:24:19 -070028import org.onlab.packet.IpPrefix;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070029import org.onlab.packet.VlanId;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -070030import org.onlab.util.KryoNamespace;
Saurav Das80980c72016-03-23 11:22:49 -070031import org.onosproject.cfg.ComponentConfigService;
sanghob35a6192015-04-01 13:05:26 -070032import org.onosproject.core.ApplicationId;
33import org.onosproject.core.CoreService;
34import org.onosproject.event.Event;
Charles Chand55e84d2016-03-30 17:54:24 -070035import org.onosproject.incubator.net.config.basics.McastConfig;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070036import org.onosproject.mastership.MastershipService;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070037import org.onosproject.net.Device;
38import org.onosproject.net.DeviceId;
39import org.onosproject.net.Link;
40import org.onosproject.net.Port;
Charles Chan68aa62d2015-11-09 16:37:23 -080041import org.onosproject.net.PortNumber;
Charles Chand6832882015-10-05 17:50:33 -070042import org.onosproject.net.config.ConfigFactory;
43import org.onosproject.net.config.NetworkConfigEvent;
Charles Chand6832882015-10-05 17:50:33 -070044import org.onosproject.net.config.NetworkConfigListener;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070045import org.onosproject.net.config.NetworkConfigRegistry;
Charles Chand6832882015-10-05 17:50:33 -070046import org.onosproject.net.config.basics.SubjectFactories;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070047import org.onosproject.net.device.DeviceEvent;
48import org.onosproject.net.device.DeviceListener;
49import org.onosproject.net.device.DeviceService;
Charles Chan68aa62d2015-11-09 16:37:23 -080050import org.onosproject.net.flow.DefaultTrafficSelector;
Charles Chan68aa62d2015-11-09 16:37:23 -080051import org.onosproject.net.flow.TrafficSelector;
52import org.onosproject.net.flow.TrafficTreatment;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070053import org.onosproject.net.flowobjective.FlowObjectiveService;
Charles Chan68aa62d2015-11-09 16:37:23 -080054import org.onosproject.net.host.HostEvent;
55import org.onosproject.net.host.HostListener;
Charles Chand55e84d2016-03-30 17:54:24 -070056import org.onosproject.net.mcast.McastEvent;
57import org.onosproject.net.mcast.McastListener;
58import org.onosproject.net.mcast.MulticastRouteService;
59import org.onosproject.net.packet.PacketPriority;
60import org.onosproject.net.topology.TopologyService;
61import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
62import org.onosproject.segmentrouting.config.DeviceConfiguration;
63import org.onosproject.segmentrouting.config.SegmentRoutingDeviceConfig;
64import org.onosproject.segmentrouting.config.SegmentRoutingAppConfig;
Charles Chanfc5c7802016-05-17 13:13:55 -070065import org.onosproject.segmentrouting.config.XConnectConfig;
Charles Chand55e84d2016-03-30 17:54:24 -070066import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
67import org.onosproject.segmentrouting.grouphandler.NeighborSet;
Charles Chand2990362016-04-18 13:44:03 -070068import org.onosproject.segmentrouting.storekey.NeighborSetNextObjectiveStoreKey;
69import org.onosproject.segmentrouting.storekey.PortNextObjectiveStoreKey;
sanghob35a6192015-04-01 13:05:26 -070070import org.onosproject.net.host.HostService;
sanghob35a6192015-04-01 13:05:26 -070071import org.onosproject.net.link.LinkEvent;
72import org.onosproject.net.link.LinkListener;
73import org.onosproject.net.link.LinkService;
74import org.onosproject.net.packet.InboundPacket;
75import org.onosproject.net.packet.PacketContext;
76import org.onosproject.net.packet.PacketProcessor;
77import org.onosproject.net.packet.PacketService;
Charles Chand2990362016-04-18 13:44:03 -070078import org.onosproject.segmentrouting.storekey.SubnetAssignedVidStoreKey;
79import org.onosproject.segmentrouting.storekey.SubnetNextObjectiveStoreKey;
Charles Chanfc5c7802016-05-17 13:13:55 -070080import org.onosproject.segmentrouting.storekey.XConnectStoreKey;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070081import org.onosproject.store.serializers.KryoNamespaces;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -070082import org.onosproject.store.service.EventuallyConsistentMap;
83import org.onosproject.store.service.EventuallyConsistentMapBuilder;
84import org.onosproject.store.service.StorageService;
85import org.onosproject.store.service.WallClockTimestamp;
Charles Chan35fd1a72016-06-13 18:54:31 -070086import org.opencord.cordconfig.CordConfigEvent;
87import org.opencord.cordconfig.CordConfigListener;
88import org.opencord.cordconfig.CordConfigService;
sanghob35a6192015-04-01 13:05:26 -070089import org.slf4j.Logger;
90import org.slf4j.LoggerFactory;
91
Saurav Das0e99e2b2015-10-28 12:39:42 -070092import java.util.Collections;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -070093import java.util.HashSet;
sangho1e575652015-05-14 00:39:53 -070094import java.util.List;
sanghob35a6192015-04-01 13:05:26 -070095import java.util.Map;
Charles Chan188ebf52015-12-23 00:15:11 -080096import java.util.Optional;
Saurav Das0e99e2b2015-10-28 12:39:42 -070097import java.util.Set;
sanghob35a6192015-04-01 13:05:26 -070098import java.util.concurrent.ConcurrentHashMap;
99import java.util.concurrent.ConcurrentLinkedQueue;
100import java.util.concurrent.Executors;
101import java.util.concurrent.ScheduledExecutorService;
102import java.util.concurrent.ScheduledFuture;
103import java.util.concurrent.TimeUnit;
104
Charles Chan3e783d02016-02-26 22:19:52 -0800105import static com.google.common.base.Preconditions.checkState;
Yuta HIGUCHI1624df12016-07-21 16:54:33 -0700106import static org.onlab.util.Tools.groupedThreads;
Charles Chan3e783d02016-02-26 22:19:52 -0800107
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700108
Charles Chane849c192016-01-11 18:28:54 -0800109/**
110 * Segment routing manager.
111 */
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700112@Service
113@Component(immediate = true)
sangho1e575652015-05-14 00:39:53 -0700114public class SegmentRoutingManager implements SegmentRoutingService {
sanghob35a6192015-04-01 13:05:26 -0700115
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700116 private static Logger log = LoggerFactory
117 .getLogger(SegmentRoutingManager.class);
sanghob35a6192015-04-01 13:05:26 -0700118
119 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
120 protected CoreService coreService;
121
122 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
sanghob35a6192015-04-01 13:05:26 -0700123 protected PacketService packetService;
124
125 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
sanghob35a6192015-04-01 13:05:26 -0700126 protected HostService hostService;
127
128 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
129 protected DeviceService deviceService;
130
131 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700132 protected FlowObjectiveService flowObjectiveService;
sanghob35a6192015-04-01 13:05:26 -0700133
134 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
135 protected LinkService linkService;
136
137 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
sanghob35a6192015-04-01 13:05:26 -0700138 protected MastershipService mastershipService;
sangho1e575652015-05-14 00:39:53 -0700139
Charles Chan5270ed02016-01-30 23:22:37 -0800140 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
141 protected StorageService storageService;
142
143 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
144 protected NetworkConfigRegistry cfgService;
145
Saurav Das80980c72016-03-23 11:22:49 -0700146 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
147 protected ComponentConfigService compCfgService;
148
Charles Chand55e84d2016-03-30 17:54:24 -0700149 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
150 protected MulticastRouteService multicastRouteService;
151
152 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
153 protected TopologyService topologyService;
154
Charles Chan35fd1a72016-06-13 18:54:31 -0700155 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
156 protected CordConfigService cordConfigService;
157
Srikanth Vavilapalli4db76e32015-04-07 15:12:32 -0700158 protected ArpHandler arpHandler = null;
159 protected IcmpHandler icmpHandler = null;
160 protected IpHandler ipHandler = null;
161 protected RoutingRulePopulator routingRulePopulator = null;
sanghob35a6192015-04-01 13:05:26 -0700162 protected ApplicationId appId;
sangho666cd6d2015-04-14 16:27:13 -0700163 protected DeviceConfiguration deviceConfiguration = null;
sanghob35a6192015-04-01 13:05:26 -0700164
Charles Chan93e71ba2016-04-29 14:38:22 -0700165 protected DefaultRoutingHandler defaultRoutingHandler = null;
sangho1e575652015-05-14 00:39:53 -0700166 private TunnelHandler tunnelHandler = null;
167 private PolicyHandler policyHandler = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700168 private InternalPacketProcessor processor = null;
169 private InternalLinkListener linkListener = null;
170 private InternalDeviceListener deviceListener = null;
Charles Chanfc5c7802016-05-17 13:13:55 -0700171 private AppConfigHandler appCfgHandler = null;
172 protected XConnectHandler xConnectHandler = null;
Charles Chand2990362016-04-18 13:44:03 -0700173 private McastHandler mcastHandler = null;
Charles Chan35fd1a72016-06-13 18:54:31 -0700174 protected HostHandler hostHandler = null;
175 private CordConfigHandler cordConfigHandler = null;
sanghob35a6192015-04-01 13:05:26 -0700176 private InternalEventHandler eventHandler = new InternalEventHandler();
Charles Chan5270ed02016-01-30 23:22:37 -0800177 private final InternalHostListener hostListener = new InternalHostListener();
Charles Chand55e84d2016-03-30 17:54:24 -0700178 private final InternalConfigListener cfgListener = new InternalConfigListener(this);
179 private final InternalMcastListener mcastListener = new InternalMcastListener();
Charles Chan35fd1a72016-06-13 18:54:31 -0700180 private final InternalCordConfigListener cordConfigListener = new InternalCordConfigListener();
sanghob35a6192015-04-01 13:05:26 -0700181
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700182 private ScheduledExecutorService executorService = Executors
Yuta HIGUCHI1624df12016-07-21 16:54:33 -0700183 .newScheduledThreadPool(1, groupedThreads("SegmentRoutingManager", "event-%d", log));
sanghob35a6192015-04-01 13:05:26 -0700184
Saurav Das4ce45962015-11-24 23:21:05 -0800185 @SuppressWarnings("unused")
sanghob35a6192015-04-01 13:05:26 -0700186 private static ScheduledFuture<?> eventHandlerFuture = null;
Saurav Das4ce45962015-11-24 23:21:05 -0800187 @SuppressWarnings("rawtypes")
Yuta HIGUCHI1624df12016-07-21 16:54:33 -0700188 private ConcurrentLinkedQueue<Event> eventQueue = new ConcurrentLinkedQueue<>();
Charles Chan68aa62d2015-11-09 16:37:23 -0800189 private Map<DeviceId, DefaultGroupHandler> groupHandlerMap =
Charles Chane849c192016-01-11 18:28:54 -0800190 new ConcurrentHashMap<>();
191 /**
192 * Per device next objective ID store with (device id + neighbor set) as key.
193 */
194 public EventuallyConsistentMap<NeighborSetNextObjectiveStoreKey, Integer>
Charles Chan68aa62d2015-11-09 16:37:23 -0800195 nsNextObjStore = null;
Charles Chane849c192016-01-11 18:28:54 -0800196 /**
197 * Per device next objective ID store with (device id + subnet) as key.
198 */
199 public EventuallyConsistentMap<SubnetNextObjectiveStoreKey, Integer>
Charles Chan68aa62d2015-11-09 16:37:23 -0800200 subnetNextObjStore = null;
Charles Chane849c192016-01-11 18:28:54 -0800201 /**
202 * Per device next objective ID store with (device id + port) as key.
203 */
204 public EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer>
Saurav Das4ce45962015-11-24 23:21:05 -0800205 portNextObjStore = null;
Saurav Das0e99e2b2015-10-28 12:39:42 -0700206 // Per device, per-subnet assigned-vlans store, with (device id + subnet
207 // IPv4 prefix) as key
208 private EventuallyConsistentMap<SubnetAssignedVidStoreKey, VlanId>
Charles Chane849c192016-01-11 18:28:54 -0800209 subnetVidStore = null;
Saurav Das4ce45962015-11-24 23:21:05 -0800210 private EventuallyConsistentMap<String, Tunnel> tunnelStore = null;
211 private EventuallyConsistentMap<String, Policy> policyStore = null;
sangho0b2b6d12015-05-20 22:16:38 -0700212
Charles Chand55e84d2016-03-30 17:54:24 -0700213 private final ConfigFactory<DeviceId, SegmentRoutingDeviceConfig> deviceConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700214 new ConfigFactory<DeviceId, SegmentRoutingDeviceConfig>(
215 SubjectFactories.DEVICE_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700216 SegmentRoutingDeviceConfig.class, "segmentrouting") {
Charles Chand6832882015-10-05 17:50:33 -0700217 @Override
Charles Chan5270ed02016-01-30 23:22:37 -0800218 public SegmentRoutingDeviceConfig createConfig() {
219 return new SegmentRoutingDeviceConfig();
Charles Chand6832882015-10-05 17:50:33 -0700220 }
221 };
Charles Chand55e84d2016-03-30 17:54:24 -0700222 private final ConfigFactory<ApplicationId, SegmentRoutingAppConfig> appConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700223 new ConfigFactory<ApplicationId, SegmentRoutingAppConfig>(
224 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700225 SegmentRoutingAppConfig.class, "segmentrouting") {
Charles Chan5270ed02016-01-30 23:22:37 -0800226 @Override
227 public SegmentRoutingAppConfig createConfig() {
228 return new SegmentRoutingAppConfig();
229 }
230 };
Charles Chanfc5c7802016-05-17 13:13:55 -0700231 private final ConfigFactory<ApplicationId, XConnectConfig> xConnectConfigFactory =
232 new ConfigFactory<ApplicationId, XConnectConfig>(
233 SubjectFactories.APP_SUBJECT_FACTORY,
234 XConnectConfig.class, "xconnect") {
235 @Override
236 public XConnectConfig createConfig() {
237 return new XConnectConfig();
238 }
239 };
Charles Chand55e84d2016-03-30 17:54:24 -0700240 private ConfigFactory<ApplicationId, McastConfig> mcastConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700241 new ConfigFactory<ApplicationId, McastConfig>(
242 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700243 McastConfig.class, "multicast") {
244 @Override
245 public McastConfig createConfig() {
246 return new McastConfig();
247 }
248 };
249
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700250 private Object threadSchedulerLock = new Object();
251 private static int numOfEventsQueued = 0;
252 private static int numOfEventsExecuted = 0;
sanghob35a6192015-04-01 13:05:26 -0700253 private static int numOfHandlerExecution = 0;
254 private static int numOfHandlerScheduled = 0;
255
Charles Chan116188d2016-02-18 14:22:42 -0800256 /**
257 * Segment Routing App ID.
258 */
259 public static final String SR_APP_ID = "org.onosproject.segmentrouting";
Charles Chane849c192016-01-11 18:28:54 -0800260 /**
261 * The starting value of per-subnet VLAN ID assignment.
262 */
Saurav Das0e99e2b2015-10-28 12:39:42 -0700263 private static final short ASSIGNED_VLAN_START = 4093;
Charles Chane849c192016-01-11 18:28:54 -0800264 /**
265 * The default VLAN ID assigned to the interfaces without subnet config.
266 */
Saurav Das0e99e2b2015-10-28 12:39:42 -0700267 public static final short ASSIGNED_VLAN_NO_SUBNET = 4094;
268
sanghob35a6192015-04-01 13:05:26 -0700269 @Activate
270 protected void activate() {
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700271 appId = coreService.registerApplication(SR_APP_ID);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700272
273 log.debug("Creating EC map nsnextobjectivestore");
274 EventuallyConsistentMapBuilder<NeighborSetNextObjectiveStoreKey, Integer>
275 nsNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700276 nsNextObjStore = nsNextObjMapBuilder
277 .withName("nsnextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700278 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700279 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700280 .build();
281 log.trace("Current size {}", nsNextObjStore.size());
282
Charles Chanc42e84e2015-10-20 16:24:19 -0700283 log.debug("Creating EC map subnetnextobjectivestore");
284 EventuallyConsistentMapBuilder<SubnetNextObjectiveStoreKey, Integer>
285 subnetNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
Charles Chanc42e84e2015-10-20 16:24:19 -0700286 subnetNextObjStore = subnetNextObjMapBuilder
287 .withName("subnetnextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700288 .withSerializer(createSerializer())
Charles Chanc42e84e2015-10-20 16:24:19 -0700289 .withTimestampProvider((k, v) -> new WallClockTimestamp())
290 .build();
291
Saurav Das4ce45962015-11-24 23:21:05 -0800292 log.debug("Creating EC map subnetnextobjectivestore");
293 EventuallyConsistentMapBuilder<PortNextObjectiveStoreKey, Integer>
294 portNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
295 portNextObjStore = portNextObjMapBuilder
296 .withName("portnextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700297 .withSerializer(createSerializer())
Saurav Das4ce45962015-11-24 23:21:05 -0800298 .withTimestampProvider((k, v) -> new WallClockTimestamp())
299 .build();
300
sangho0b2b6d12015-05-20 22:16:38 -0700301 EventuallyConsistentMapBuilder<String, Tunnel> tunnelMapBuilder =
302 storageService.eventuallyConsistentMapBuilder();
sangho0b2b6d12015-05-20 22:16:38 -0700303 tunnelStore = tunnelMapBuilder
304 .withName("tunnelstore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700305 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700306 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho0b2b6d12015-05-20 22:16:38 -0700307 .build();
308
309 EventuallyConsistentMapBuilder<String, Policy> policyMapBuilder =
310 storageService.eventuallyConsistentMapBuilder();
sangho0b2b6d12015-05-20 22:16:38 -0700311 policyStore = policyMapBuilder
312 .withName("policystore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700313 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700314 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho0b2b6d12015-05-20 22:16:38 -0700315 .build();
316
Saurav Das0e99e2b2015-10-28 12:39:42 -0700317 EventuallyConsistentMapBuilder<SubnetAssignedVidStoreKey, VlanId>
318 subnetVidStoreMapBuilder = storageService.eventuallyConsistentMapBuilder();
Saurav Das0e99e2b2015-10-28 12:39:42 -0700319 subnetVidStore = subnetVidStoreMapBuilder
320 .withName("subnetvidstore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700321 .withSerializer(createSerializer())
Saurav Das0e99e2b2015-10-28 12:39:42 -0700322 .withTimestampProvider((k, v) -> new WallClockTimestamp())
323 .build();
324
Saurav Das80980c72016-03-23 11:22:49 -0700325 compCfgService.preSetProperty("org.onosproject.net.group.impl.GroupManager",
326 "purgeOnDisconnection", "true");
327 compCfgService.preSetProperty("org.onosproject.net.flow.impl.FlowRuleManager",
328 "purgeOnDisconnection", "true");
329
Charles Chanb8e10c82015-10-14 11:24:40 -0700330 processor = new InternalPacketProcessor();
331 linkListener = new InternalLinkListener();
332 deviceListener = new InternalDeviceListener();
Charles Chanfc5c7802016-05-17 13:13:55 -0700333 appCfgHandler = new AppConfigHandler(this);
334 xConnectHandler = new XConnectHandler(this);
Charles Chand2990362016-04-18 13:44:03 -0700335 mcastHandler = new McastHandler(this);
336 hostHandler = new HostHandler(this);
Charles Chan35fd1a72016-06-13 18:54:31 -0700337 cordConfigHandler = new CordConfigHandler(this);
Charles Chanb8e10c82015-10-14 11:24:40 -0700338
Charles Chan3e783d02016-02-26 22:19:52 -0800339 cfgService.addListener(cfgListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700340 cfgService.registerConfigFactory(deviceConfigFactory);
341 cfgService.registerConfigFactory(appConfigFactory);
Charles Chanfc5c7802016-05-17 13:13:55 -0700342 cfgService.registerConfigFactory(xConnectConfigFactory);
Charles Chand55e84d2016-03-30 17:54:24 -0700343 cfgService.registerConfigFactory(mcastConfigFactory);
Charles Chan5270ed02016-01-30 23:22:37 -0800344 hostService.addListener(hostListener);
Charles Chanb8e10c82015-10-14 11:24:40 -0700345 packetService.addProcessor(processor, PacketProcessor.director(2));
346 linkService.addListener(linkListener);
347 deviceService.addListener(deviceListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700348 multicastRouteService.addListener(mcastListener);
Charles Chan35fd1a72016-06-13 18:54:31 -0700349 cordConfigService.addListener(cordConfigListener);
Charles Chanb8e10c82015-10-14 11:24:40 -0700350
Charles Chan188ebf52015-12-23 00:15:11 -0800351 // Request ARP packet-in
352 TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
353 selector.matchEthType(Ethernet.TYPE_ARP);
354 packetService.requestPackets(selector.build(), PacketPriority.CONTROL, appId, Optional.empty());
355
Charles Chanb8e10c82015-10-14 11:24:40 -0700356 cfgListener.configureNetwork();
357
sanghob35a6192015-04-01 13:05:26 -0700358 log.info("Started");
359 }
360
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700361 private KryoNamespace.Builder createSerializer() {
362 return new KryoNamespace.Builder()
363 .register(KryoNamespaces.API)
364 .register(NeighborSetNextObjectiveStoreKey.class,
365 SubnetNextObjectiveStoreKey.class,
366 SubnetAssignedVidStoreKey.class,
367 NeighborSet.class,
368 Tunnel.class,
369 DefaultTunnel.class,
370 Policy.class,
371 TunnelPolicy.class,
372 Policy.Type.class,
373 PortNextObjectiveStoreKey.class,
Charles Chanfc5c7802016-05-17 13:13:55 -0700374 XConnectStoreKey.class
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700375 );
376 }
377
sanghob35a6192015-04-01 13:05:26 -0700378 @Deactivate
379 protected void deactivate() {
Charles Chand6832882015-10-05 17:50:33 -0700380 cfgService.removeListener(cfgListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700381 cfgService.unregisterConfigFactory(deviceConfigFactory);
382 cfgService.unregisterConfigFactory(appConfigFactory);
383 cfgService.unregisterConfigFactory(mcastConfigFactory);
Charles Chand6832882015-10-05 17:50:33 -0700384
Charles Chan188ebf52015-12-23 00:15:11 -0800385 // Withdraw ARP packet-in
386 TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
387 selector.matchEthType(Ethernet.TYPE_ARP);
388 packetService.cancelPackets(selector.build(), PacketPriority.CONTROL, appId, Optional.empty());
389
sanghob35a6192015-04-01 13:05:26 -0700390 packetService.removeProcessor(processor);
Charles Chanb8e10c82015-10-14 11:24:40 -0700391 linkService.removeListener(linkListener);
392 deviceService.removeListener(deviceListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700393 multicastRouteService.removeListener(mcastListener);
Charles Chan35fd1a72016-06-13 18:54:31 -0700394 cordConfigService.removeListener(cordConfigListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700395
sanghob35a6192015-04-01 13:05:26 -0700396 processor = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700397 linkListener = null;
Charles Chand55e84d2016-03-30 17:54:24 -0700398 deviceListener = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700399 groupHandlerMap.clear();
400
Charles Chand55e84d2016-03-30 17:54:24 -0700401 nsNextObjStore.destroy();
402 subnetNextObjStore.destroy();
403 portNextObjStore.destroy();
Charles Chand55e84d2016-03-30 17:54:24 -0700404 tunnelStore.destroy();
405 policyStore.destroy();
406 subnetVidStore.destroy();
sanghob35a6192015-04-01 13:05:26 -0700407 log.info("Stopped");
408 }
409
sangho1e575652015-05-14 00:39:53 -0700410 @Override
411 public List<Tunnel> getTunnels() {
412 return tunnelHandler.getTunnels();
413 }
414
415 @Override
sangho71abe1b2015-06-29 14:58:47 -0700416 public TunnelHandler.Result createTunnel(Tunnel tunnel) {
417 return tunnelHandler.createTunnel(tunnel);
sangho1e575652015-05-14 00:39:53 -0700418 }
419
420 @Override
sangho71abe1b2015-06-29 14:58:47 -0700421 public TunnelHandler.Result removeTunnel(Tunnel tunnel) {
sangho1e575652015-05-14 00:39:53 -0700422 for (Policy policy: policyHandler.getPolicies()) {
423 if (policy.type() == Policy.Type.TUNNEL_FLOW) {
424 TunnelPolicy tunnelPolicy = (TunnelPolicy) policy;
425 if (tunnelPolicy.tunnelId().equals(tunnel.id())) {
426 log.warn("Cannot remove the tunnel used by a policy");
sangho71abe1b2015-06-29 14:58:47 -0700427 return TunnelHandler.Result.TUNNEL_IN_USE;
sangho1e575652015-05-14 00:39:53 -0700428 }
429 }
430 }
sangho71abe1b2015-06-29 14:58:47 -0700431 return tunnelHandler.removeTunnel(tunnel);
sangho1e575652015-05-14 00:39:53 -0700432 }
433
434 @Override
sangho71abe1b2015-06-29 14:58:47 -0700435 public PolicyHandler.Result removePolicy(Policy policy) {
436 return policyHandler.removePolicy(policy);
sangho1e575652015-05-14 00:39:53 -0700437 }
438
439 @Override
sangho71abe1b2015-06-29 14:58:47 -0700440 public PolicyHandler.Result createPolicy(Policy policy) {
441 return policyHandler.createPolicy(policy);
sangho1e575652015-05-14 00:39:53 -0700442 }
443
444 @Override
445 public List<Policy> getPolicies() {
446 return policyHandler.getPolicies();
447 }
448
Saurav Das59232cf2016-04-27 18:35:50 -0700449 @Override
450 public void rerouteNetwork() {
451 cfgListener.configureNetwork();
452 for (Device device : deviceService.getDevices()) {
453 defaultRoutingHandler.populatePortAddressingRules(device.id());
454 }
455 defaultRoutingHandler.startPopulationProcess();
456 }
457
Charles Chanc81c45b2016-10-20 17:02:44 -0700458 @Override
459 public Map<DeviceId, Set<Ip4Prefix>> getDeviceSubnetMap() {
460 Map<DeviceId, Set<Ip4Prefix>> deviceSubnetMap = Maps.newHashMap();
461 deviceService.getAvailableDevices().forEach(device -> {
462 deviceSubnetMap.put(device.id(), deviceConfiguration.getSubnets(device.id()));
463 });
464 return deviceSubnetMap;
465 }
466
sanghof9d0bf12015-05-19 11:57:42 -0700467 /**
468 * Returns the tunnel object with the tunnel ID.
469 *
470 * @param tunnelId Tunnel ID
471 * @return Tunnel reference
472 */
sangho1e575652015-05-14 00:39:53 -0700473 public Tunnel getTunnel(String tunnelId) {
474 return tunnelHandler.getTunnel(tunnelId);
475 }
476
sanghob35a6192015-04-01 13:05:26 -0700477 /**
Saurav Das0e99e2b2015-10-28 12:39:42 -0700478 * Returns the vlan-id assigned to the subnet configured for a device.
479 * If no vlan-id has been assigned, a new one is assigned out of a pool of ids,
480 * if and only if this controller instance is the master for the device.
481 * <p>
482 * USAGE: The assigned vlans are meant to be applied to untagged packets on those
483 * switches/pipelines that need this functionality. These vids are meant
484 * to be used internally within a switch, and thus need to be unique only
485 * on a switch level. Note that packets never go out on the wire with these
486 * vlans. Currently, vlan ids are assigned from value 4093 down.
487 * Vlan id 4094 expected to be used for all ports that are not assigned subnets.
488 * Vlan id 4095 is reserved and unused. Only a single vlan id is assigned
489 * per subnet.
sanghob35a6192015-04-01 13:05:26 -0700490 *
Saurav Das0e99e2b2015-10-28 12:39:42 -0700491 * @param deviceId switch dpid
492 * @param subnet IPv4 prefix for which assigned vlan is desired
493 * @return VlanId assigned for the subnet on the device, or
494 * null if no vlan assignment was found and this instance is not
495 * the master for the device.
sanghob35a6192015-04-01 13:05:26 -0700496 */
Charles Chane849c192016-01-11 18:28:54 -0800497 // TODO: We should avoid assigning VLAN IDs that are used by VLAN cross-connection.
Saurav Das0e99e2b2015-10-28 12:39:42 -0700498 public VlanId getSubnetAssignedVlanId(DeviceId deviceId, Ip4Prefix subnet) {
499 VlanId assignedVid = subnetVidStore.get(new SubnetAssignedVidStoreKey(
500 deviceId, subnet));
501 if (assignedVid != null) {
502 log.debug("Query for subnet:{} on device:{} returned assigned-vlan "
503 + "{}", subnet, deviceId, assignedVid);
504 return assignedVid;
505 }
506 //check mastership for the right to assign a vlan
507 if (!mastershipService.isLocalMaster(deviceId)) {
508 log.warn("This controller instance is not the master for device {}. "
509 + "Cannot assign vlan-id for subnet {}", deviceId, subnet);
510 return null;
511 }
512 // vlan assignment is expensive but done only once
Charles Chan9f676b62015-10-29 14:58:10 -0700513 Set<Ip4Prefix> configuredSubnets = deviceConfiguration.getSubnets(deviceId);
Saurav Das0e99e2b2015-10-28 12:39:42 -0700514 Set<Short> assignedVlans = new HashSet<>();
515 Set<Ip4Prefix> unassignedSubnets = new HashSet<>();
516 for (Ip4Prefix sub : configuredSubnets) {
517 VlanId v = subnetVidStore.get(new SubnetAssignedVidStoreKey(deviceId,
518 sub));
519 if (v != null) {
520 assignedVlans.add(v.toShort());
521 } else {
522 unassignedSubnets.add(sub);
523 }
524 }
525 short nextAssignedVlan = ASSIGNED_VLAN_START;
526 if (!assignedVlans.isEmpty()) {
527 nextAssignedVlan = (short) (Collections.min(assignedVlans) - 1);
528 }
529 for (Ip4Prefix unsub : unassignedSubnets) {
Charles Chan5270ed02016-01-30 23:22:37 -0800530 // Special case for default route. Assign default VLAN ID to /32 and /0 subnets
531 if (unsub.prefixLength() == IpPrefix.MAX_INET_MASK_LENGTH ||
532 unsub.prefixLength() == 0) {
533 subnetVidStore.put(new SubnetAssignedVidStoreKey(deviceId, unsub),
534 VlanId.vlanId(ASSIGNED_VLAN_NO_SUBNET));
535 } else {
536 subnetVidStore.put(new SubnetAssignedVidStoreKey(deviceId, unsub),
537 VlanId.vlanId(nextAssignedVlan--));
538 log.info("Assigned vlan: {} to subnet: {} on device: {}",
539 nextAssignedVlan + 1, unsub, deviceId);
540 }
sanghob35a6192015-04-01 13:05:26 -0700541 }
542
Saurav Das0e99e2b2015-10-28 12:39:42 -0700543 return subnetVidStore.get(new SubnetAssignedVidStoreKey(deviceId, subnet));
sanghob35a6192015-04-01 13:05:26 -0700544 }
545
sangho1e575652015-05-14 00:39:53 -0700546 /**
Saurav Das0e99e2b2015-10-28 12:39:42 -0700547 * Returns the next objective ID for the given NeighborSet.
Saurav Das8a0732e2015-11-20 15:27:53 -0800548 * If the nextObjective does not exist, a new one is created and
Saurav Das4ce45962015-11-24 23:21:05 -0800549 * its id is returned.
sangho1e575652015-05-14 00:39:53 -0700550 *
sanghof9d0bf12015-05-19 11:57:42 -0700551 * @param deviceId Device ID
552 * @param ns NegighborSet
Saurav Das8a0732e2015-11-20 15:27:53 -0800553 * @param meta metadata passed into the creation of a Next Objective
554 * @return next objective ID or -1 if an error was encountered during the
555 * creation of the nextObjective
sangho1e575652015-05-14 00:39:53 -0700556 */
Saurav Das8a0732e2015-11-20 15:27:53 -0800557 public int getNextObjectiveId(DeviceId deviceId, NeighborSet ns,
558 TrafficSelector meta) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700559 if (groupHandlerMap.get(deviceId) != null) {
560 log.trace("getNextObjectiveId query in device {}", deviceId);
561 return groupHandlerMap
Saurav Das8a0732e2015-11-20 15:27:53 -0800562 .get(deviceId).getNextObjectiveId(ns, meta);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700563 } else {
Saurav Das4ce45962015-11-24 23:21:05 -0800564 log.warn("getNextObjectiveId query - groupHandler for device {} "
565 + "not found", deviceId);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700566 return -1;
567 }
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700568 }
569
Charles Chanc42e84e2015-10-20 16:24:19 -0700570 /**
Saurav Das4ce45962015-11-24 23:21:05 -0800571 * Returns the next objective ID for the given subnet prefix. It is expected
572 * that the next-objective has been pre-created from configuration.
Charles Chanc42e84e2015-10-20 16:24:19 -0700573 *
574 * @param deviceId Device ID
575 * @param prefix Subnet
Saurav Das4ce45962015-11-24 23:21:05 -0800576 * @return next objective ID or -1 if it was not found
Charles Chanc42e84e2015-10-20 16:24:19 -0700577 */
578 public int getSubnetNextObjectiveId(DeviceId deviceId, IpPrefix prefix) {
579 if (groupHandlerMap.get(deviceId) != null) {
580 log.trace("getSubnetNextObjectiveId query in device {}", deviceId);
581 return groupHandlerMap
582 .get(deviceId).getSubnetNextObjectiveId(prefix);
583 } else {
Saurav Das4ce45962015-11-24 23:21:05 -0800584 log.warn("getSubnetNextObjectiveId query - groupHandler for "
585 + "device {} not found", deviceId);
586 return -1;
587 }
588 }
589
590 /**
591 * Returns the next objective ID for the given portNumber, given the treatment.
592 * There could be multiple different treatments to the same outport, which
593 * would result in different objectives. If the next object
594 * does not exist, a new one is created and its id is returned.
595 *
596 * @param deviceId Device ID
597 * @param portNum port number on device for which NextObjective is queried
598 * @param treatment the actions to apply on the packets (should include outport)
599 * @param meta metadata passed into the creation of a Next Objective if necessary
Saurav Das59232cf2016-04-27 18:35:50 -0700600 * @return next objective ID or -1 if an error occurred during retrieval or creation
Saurav Das4ce45962015-11-24 23:21:05 -0800601 */
602 public int getPortNextObjectiveId(DeviceId deviceId, PortNumber portNum,
603 TrafficTreatment treatment,
604 TrafficSelector meta) {
605 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
606 if (ghdlr != null) {
607 return ghdlr.getPortNextObjectiveId(portNum, treatment, meta);
608 } else {
Charles Chane849c192016-01-11 18:28:54 -0800609 log.warn("getPortNextObjectiveId query - groupHandler for device {}"
610 + " not found", deviceId);
611 return -1;
612 }
613 }
614
sanghob35a6192015-04-01 13:05:26 -0700615 private class InternalPacketProcessor implements PacketProcessor {
sanghob35a6192015-04-01 13:05:26 -0700616 @Override
617 public void process(PacketContext context) {
618
619 if (context.isHandled()) {
620 return;
621 }
622
623 InboundPacket pkt = context.inPacket();
624 Ethernet ethernet = pkt.parsed();
Saurav Das4ce45962015-11-24 23:21:05 -0800625 log.trace("Rcvd pktin: {}", ethernet);
sanghob35a6192015-04-01 13:05:26 -0700626 if (ethernet.getEtherType() == Ethernet.TYPE_ARP) {
627 arpHandler.processPacketIn(pkt);
628 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV4) {
629 IPv4 ipPacket = (IPv4) ethernet.getPayload();
630 ipHandler.addToPacketBuffer(ipPacket);
631 if (ipPacket.getProtocol() == IPv4.PROTOCOL_ICMP) {
632 icmpHandler.processPacketIn(pkt);
633 } else {
634 ipHandler.processPacketIn(pkt);
635 }
636 }
637 }
638 }
639
640 private class InternalLinkListener implements LinkListener {
641 @Override
642 public void event(LinkEvent event) {
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700643 if (event.type() == LinkEvent.Type.LINK_ADDED
644 || event.type() == LinkEvent.Type.LINK_REMOVED) {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700645 log.debug("Event {} received from Link Service", event.type());
sanghob35a6192015-04-01 13:05:26 -0700646 scheduleEventHandlerIfNotScheduled(event);
647 }
648 }
649 }
650
651 private class InternalDeviceListener implements DeviceListener {
sanghob35a6192015-04-01 13:05:26 -0700652 @Override
653 public void event(DeviceEvent event) {
sanghob35a6192015-04-01 13:05:26 -0700654 switch (event.type()) {
655 case DEVICE_ADDED:
656 case PORT_REMOVED:
sangho20eff1d2015-04-13 15:15:58 -0700657 case DEVICE_UPDATED:
658 case DEVICE_AVAILABILITY_CHANGED:
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700659 log.debug("Event {} received from Device Service", event.type());
sanghob35a6192015-04-01 13:05:26 -0700660 scheduleEventHandlerIfNotScheduled(event);
661 break;
662 default:
663 }
664 }
665 }
666
Saurav Das4ce45962015-11-24 23:21:05 -0800667 @SuppressWarnings("rawtypes")
sanghob35a6192015-04-01 13:05:26 -0700668 private void scheduleEventHandlerIfNotScheduled(Event event) {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700669 synchronized (threadSchedulerLock) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700670 eventQueue.add(event);
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700671 numOfEventsQueued++;
672
673 if ((numOfHandlerScheduled - numOfHandlerExecution) == 0) {
674 //No pending scheduled event handling threads. So start a new one.
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700675 eventHandlerFuture = executorService
676 .schedule(eventHandler, 100, TimeUnit.MILLISECONDS);
677 numOfHandlerScheduled++;
678 }
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700679 log.trace("numOfEventsQueued {}, numOfEventHandlerScheduled {}",
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700680 numOfEventsQueued,
681 numOfHandlerScheduled);
sanghob35a6192015-04-01 13:05:26 -0700682 }
sanghob35a6192015-04-01 13:05:26 -0700683 }
684
685 private class InternalEventHandler implements Runnable {
Srikanth Vavilapalli4db76e32015-04-07 15:12:32 -0700686 @Override
sanghob35a6192015-04-01 13:05:26 -0700687 public void run() {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700688 try {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700689 while (true) {
Saurav Das4ce45962015-11-24 23:21:05 -0800690 @SuppressWarnings("rawtypes")
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700691 Event event = null;
692 synchronized (threadSchedulerLock) {
693 if (!eventQueue.isEmpty()) {
694 event = eventQueue.poll();
695 numOfEventsExecuted++;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700696 } else {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700697 numOfHandlerExecution++;
698 log.debug("numOfHandlerExecution {} numOfEventsExecuted {}",
699 numOfHandlerExecution, numOfEventsExecuted);
700 break;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700701 }
sangho20eff1d2015-04-13 15:15:58 -0700702 }
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700703 if (event.type() == LinkEvent.Type.LINK_ADDED) {
704 processLinkAdded((Link) event.subject());
705 } else if (event.type() == LinkEvent.Type.LINK_REMOVED) {
Pier Ventre2c515312016-09-13 21:33:40 -0700706 Link linkRemoved = (Link) event.subject();
707 if (linkRemoved.src().elementId() instanceof DeviceId &&
708 !deviceService.isAvailable(linkRemoved.src().deviceId())) {
709 continue;
710 }
711 if (linkRemoved.dst().elementId() instanceof DeviceId &&
712 !deviceService.isAvailable(linkRemoved.dst().deviceId())) {
713 continue;
714 }
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700715 processLinkRemoved((Link) event.subject());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700716 } else if (event.type() == DeviceEvent.Type.DEVICE_ADDED ||
717 event.type() == DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED ||
718 event.type() == DeviceEvent.Type.DEVICE_UPDATED) {
Saurav Das423fe2b2015-12-04 10:52:59 -0800719 DeviceId deviceId = ((Device) event.subject()).id();
720 if (deviceService.isAvailable(deviceId)) {
Saurav Das837e0bb2015-10-30 17:45:38 -0700721 log.info("Processing device event {} for available device {}",
722 event.type(), ((Device) event.subject()).id());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700723 processDeviceAdded((Device) event.subject());
Saurav Das80980c72016-03-23 11:22:49 -0700724 } else {
725 log.info("Processing device event {} for unavailable device {}",
726 event.type(), ((Device) event.subject()).id());
727 processDeviceRemoved((Device) event.subject());
728 }
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700729 } else if (event.type() == DeviceEvent.Type.PORT_REMOVED) {
730 processPortRemoved((Device) event.subject(),
731 ((DeviceEvent) event).port());
Saurav Dasb5c236e2016-06-07 10:08:06 -0700732 } else if (event.type() == DeviceEvent.Type.PORT_ADDED ||
733 event.type() == DeviceEvent.Type.PORT_UPDATED) {
734 log.info("** PORT ADDED OR UPDATED {}/{} -> {}",
Yuta HIGUCHI1624df12016-07-21 16:54:33 -0700735 event.subject(),
Saurav Dasb5c236e2016-06-07 10:08:06 -0700736 ((DeviceEvent) event).port(),
737 event.type());
738 /* XXX create method for single port filtering rules
739 if (defaultRoutingHandler != null) {
740 defaultRoutingHandler.populatePortAddressingRules(
741 ((Device) event.subject()).id());
742 }*/
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700743 } else {
744 log.warn("Unhandled event type: {}", event.type());
745 }
sanghob35a6192015-04-01 13:05:26 -0700746 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700747 } catch (Exception e) {
748 log.error("SegmentRouting event handler "
749 + "thread thrown an exception: {}", e);
sanghob35a6192015-04-01 13:05:26 -0700750 }
sanghob35a6192015-04-01 13:05:26 -0700751 }
752 }
753
sanghob35a6192015-04-01 13:05:26 -0700754 private void processLinkAdded(Link link) {
Saurav Dasb5c236e2016-06-07 10:08:06 -0700755 log.info("** LINK ADDED {}", link.toString());
Charles Chan0b4e6182015-11-03 10:42:14 -0800756 if (!deviceConfiguration.isConfigured(link.src().deviceId())) {
757 log.warn("Source device of this link is not configured.");
758 return;
759 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700760 //Irrespective whether the local is a MASTER or not for this device,
761 //create group handler instance and push default TTP flow rules.
762 //Because in a multi-instance setup, instances can initiate
763 //groups for any devices. Also the default TTP rules are needed
764 //to be pushed before inserting any IP table entries for any device
765 DefaultGroupHandler groupHandler = groupHandlerMap.get(link.src()
766 .deviceId());
767 if (groupHandler != null) {
Saurav Das8a0732e2015-11-20 15:27:53 -0800768 groupHandler.linkUp(link, mastershipService.isLocalMaster(
769 link.src().deviceId()));
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700770 } else {
771 Device device = deviceService.getDevice(link.src().deviceId());
772 if (device != null) {
773 log.warn("processLinkAdded: Link Added "
774 + "Notification without Device Added "
775 + "event, still handling it");
776 processDeviceAdded(device);
777 groupHandler = groupHandlerMap.get(link.src()
778 .deviceId());
Saurav Das8a0732e2015-11-20 15:27:53 -0800779 groupHandler.linkUp(link, mastershipService.isLocalMaster(device.id()));
sanghob35a6192015-04-01 13:05:26 -0700780 }
781 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700782
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700783 log.trace("Starting optimized route population process");
784 defaultRoutingHandler.populateRoutingRulesForLinkStatusChange(null);
785 //log.trace("processLinkAdded: re-starting route population process");
786 //defaultRoutingHandler.startPopulationProcess();
Charles Chan2199c302016-04-23 17:36:10 -0700787
788 mcastHandler.init();
sanghob35a6192015-04-01 13:05:26 -0700789 }
790
791 private void processLinkRemoved(Link link) {
Saurav Dasb5c236e2016-06-07 10:08:06 -0700792 log.info("** LINK REMOVED {}", link.toString());
sangho834e4b02015-05-01 09:38:25 -0700793 DefaultGroupHandler groupHandler = groupHandlerMap.get(link.src().deviceId());
794 if (groupHandler != null) {
Saurav Das423fe2b2015-12-04 10:52:59 -0800795 groupHandler.portDown(link.src().port(),
796 mastershipService.isLocalMaster(link.src().deviceId()));
sangho834e4b02015-05-01 09:38:25 -0700797 }
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700798 log.trace("Starting optimized route population process");
799 defaultRoutingHandler.populateRoutingRulesForLinkStatusChange(link);
800 //log.trace("processLinkRemoved: re-starting route population process");
801 //defaultRoutingHandler.startPopulationProcess();
Charles Chan2199c302016-04-23 17:36:10 -0700802
803 mcastHandler.processLinkDown(link);
sanghob35a6192015-04-01 13:05:26 -0700804 }
805
806 private void processDeviceAdded(Device device) {
Saurav Dasb5c236e2016-06-07 10:08:06 -0700807 log.info("** DEVICE ADDED with ID {}", device.id());
Charles Chan0b4e6182015-11-03 10:42:14 -0800808 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
Saurav Das2857f382015-11-03 14:39:27 -0800809 log.warn("Device configuration uploading. Device {} will be "
810 + "processed after config completes.", device.id());
811 return;
812 }
Charles Chan2199c302016-04-23 17:36:10 -0700813 processDeviceAddedInternal(device.id());
814 }
815
816 private void processDeviceAddedInternal(DeviceId deviceId) {
Saurav Das837e0bb2015-10-30 17:45:38 -0700817 // Irrespective of whether the local is a MASTER or not for this device,
818 // we need to create a SR-group-handler instance. This is because in a
819 // multi-instance setup, any instance can initiate forwarding/next-objectives
820 // for any switch (even if this instance is a SLAVE or not even connected
821 // to the switch). To handle this, a default-group-handler instance is necessary
822 // per switch.
Charles Chan2199c302016-04-23 17:36:10 -0700823 log.debug("Current groupHandlerMap devs: {}", groupHandlerMap.keySet());
824 if (groupHandlerMap.get(deviceId) == null) {
Charles Chan0b4e6182015-11-03 10:42:14 -0800825 DefaultGroupHandler groupHandler;
826 try {
827 groupHandler = DefaultGroupHandler.
Charles Chan2199c302016-04-23 17:36:10 -0700828 createGroupHandler(deviceId,
829 appId,
830 deviceConfiguration,
831 linkService,
832 flowObjectiveService,
833 this);
Charles Chan0b4e6182015-11-03 10:42:14 -0800834 } catch (DeviceConfigNotFoundException e) {
835 log.warn(e.getMessage() + " Aborting processDeviceAdded.");
836 return;
837 }
Charles Chan2199c302016-04-23 17:36:10 -0700838 log.debug("updating groupHandlerMap with new config for device: {}",
839 deviceId);
840 groupHandlerMap.put(deviceId, groupHandler);
Saurav Das2857f382015-11-03 14:39:27 -0800841 }
Saurav Dasb5c236e2016-06-07 10:08:06 -0700842 // Also, in some cases, drivers may need extra
843 // information to process rules (eg. Router IP/MAC); and so, we send
844 // port addressing rules to the driver as well irrespective of whether
845 // this instance is the master or not.
846 defaultRoutingHandler.populatePortAddressingRules(deviceId);
847
Charles Chan2199c302016-04-23 17:36:10 -0700848 if (mastershipService.isLocalMaster(deviceId)) {
849 hostHandler.readInitialHosts(deviceId);
Charles Chanfc5c7802016-05-17 13:13:55 -0700850 xConnectHandler.init(deviceId);
Charles Chan35fd1a72016-06-13 18:54:31 -0700851 cordConfigHandler.init(deviceId);
Charles Chan2199c302016-04-23 17:36:10 -0700852 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
Charles Chanc42e84e2015-10-20 16:24:19 -0700853 groupHandler.createGroupsFromSubnetConfig();
Charles Chan2199c302016-04-23 17:36:10 -0700854 routingRulePopulator.populateSubnetBroadcastRule(deviceId);
Charles Chanc42e84e2015-10-20 16:24:19 -0700855 }
Charles Chan5270ed02016-01-30 23:22:37 -0800856
Charles Chanfc5c7802016-05-17 13:13:55 -0700857 appCfgHandler.initVRouters(deviceId);
sanghob35a6192015-04-01 13:05:26 -0700858 }
859
Saurav Das80980c72016-03-23 11:22:49 -0700860 private void processDeviceRemoved(Device device) {
861 nsNextObjStore.entrySet().stream()
862 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
863 .forEach(entry -> {
864 nsNextObjStore.remove(entry.getKey());
865 });
Saurav Das80980c72016-03-23 11:22:49 -0700866 subnetNextObjStore.entrySet().stream()
867 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
868 .forEach(entry -> {
869 subnetNextObjStore.remove(entry.getKey());
870 });
Saurav Das80980c72016-03-23 11:22:49 -0700871 portNextObjStore.entrySet().stream()
872 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
873 .forEach(entry -> {
874 portNextObjStore.remove(entry.getKey());
875 });
Saurav Das80980c72016-03-23 11:22:49 -0700876 subnetVidStore.entrySet().stream()
877 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
878 .forEach(entry -> {
879 subnetVidStore.remove(entry.getKey());
880 });
Saurav Das80980c72016-03-23 11:22:49 -0700881 groupHandlerMap.remove(device.id());
Saurav Das80980c72016-03-23 11:22:49 -0700882 defaultRoutingHandler.purgeEcmpGraph(device.id());
Charles Chan2199c302016-04-23 17:36:10 -0700883 mcastHandler.removeDevice(device.id());
Charles Chanfc5c7802016-05-17 13:13:55 -0700884 xConnectHandler.removeDevice(device.id());
Saurav Das80980c72016-03-23 11:22:49 -0700885 }
886
sanghob35a6192015-04-01 13:05:26 -0700887 private void processPortRemoved(Device device, Port port) {
Saurav Dasb5c236e2016-06-07 10:08:06 -0700888 log.info("Port {} was removed", port.toString());
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700889 DefaultGroupHandler groupHandler = groupHandlerMap.get(device.id());
sanghob35a6192015-04-01 13:05:26 -0700890 if (groupHandler != null) {
Saurav Das423fe2b2015-12-04 10:52:59 -0800891 groupHandler.portDown(port.number(),
892 mastershipService.isLocalMaster(device.id()));
sanghob35a6192015-04-01 13:05:26 -0700893 }
894 }
sangho1e575652015-05-14 00:39:53 -0700895
Charles Chand6832882015-10-05 17:50:33 -0700896 private class InternalConfigListener implements NetworkConfigListener {
Charles Chan4636be02015-10-07 14:21:45 -0700897 SegmentRoutingManager segmentRoutingManager;
898
Charles Chane849c192016-01-11 18:28:54 -0800899 /**
900 * Constructs the internal network config listener.
901 *
902 * @param srMgr segment routing manager
903 */
Charles Chan4636be02015-10-07 14:21:45 -0700904 public InternalConfigListener(SegmentRoutingManager srMgr) {
905 this.segmentRoutingManager = srMgr;
906 }
907
Charles Chane849c192016-01-11 18:28:54 -0800908 /**
909 * Reads network config and initializes related data structure accordingly.
910 */
Charles Chan4636be02015-10-07 14:21:45 -0700911 public void configureNetwork() {
Charles Chanf2565a92016-02-10 20:46:58 -0800912 deviceConfiguration = new DeviceConfiguration(appId,
913 segmentRoutingManager.cfgService);
Charles Chan4636be02015-10-07 14:21:45 -0700914
915 arpHandler = new ArpHandler(segmentRoutingManager);
916 icmpHandler = new IcmpHandler(segmentRoutingManager);
917 ipHandler = new IpHandler(segmentRoutingManager);
918 routingRulePopulator = new RoutingRulePopulator(segmentRoutingManager);
919 defaultRoutingHandler = new DefaultRoutingHandler(segmentRoutingManager);
920
921 tunnelHandler = new TunnelHandler(linkService, deviceConfiguration,
922 groupHandlerMap, tunnelStore);
923 policyHandler = new PolicyHandler(appId, deviceConfiguration,
924 flowObjectiveService,
925 tunnelHandler, policyStore);
926
Charles Chan4636be02015-10-07 14:21:45 -0700927 for (Device device : deviceService.getDevices()) {
Charles Chan2199c302016-04-23 17:36:10 -0700928 processDeviceAddedInternal(device.id());
Charles Chan4636be02015-10-07 14:21:45 -0700929 }
930
931 defaultRoutingHandler.startPopulationProcess();
Charles Chan2199c302016-04-23 17:36:10 -0700932 mcastHandler.init();
Charles Chan4636be02015-10-07 14:21:45 -0700933 }
934
Charles Chand6832882015-10-05 17:50:33 -0700935 @Override
936 public void event(NetworkConfigEvent event) {
Charles Chan5270ed02016-01-30 23:22:37 -0800937 // TODO move this part to NetworkConfigEventHandler
938 if (event.configClass().equals(SegmentRoutingDeviceConfig.class)) {
939 switch (event.type()) {
940 case CONFIG_ADDED:
941 log.info("Segment Routing Config added.");
942 configureNetwork();
943 break;
944 case CONFIG_UPDATED:
945 log.info("Segment Routing Config updated.");
946 // TODO support dynamic configuration
947 break;
948 default:
949 break;
Charles Chanb8e10c82015-10-14 11:24:40 -0700950 }
Charles Chan5270ed02016-01-30 23:22:37 -0800951 } else if (event.configClass().equals(SegmentRoutingAppConfig.class)) {
Charles Chanfc5c7802016-05-17 13:13:55 -0700952 checkState(appCfgHandler != null, "NetworkConfigEventHandler is not initialized");
Charles Chan5270ed02016-01-30 23:22:37 -0800953 switch (event.type()) {
954 case CONFIG_ADDED:
Charles Chanfc5c7802016-05-17 13:13:55 -0700955 appCfgHandler.processAppConfigAdded(event);
Charles Chan5270ed02016-01-30 23:22:37 -0800956 break;
957 case CONFIG_UPDATED:
Charles Chanfc5c7802016-05-17 13:13:55 -0700958 appCfgHandler.processAppConfigUpdated(event);
Charles Chan5270ed02016-01-30 23:22:37 -0800959 break;
960 case CONFIG_REMOVED:
Charles Chanfc5c7802016-05-17 13:13:55 -0700961 appCfgHandler.processAppConfigRemoved(event);
962 break;
963 default:
964 break;
965 }
966 } else if (event.configClass().equals(XConnectConfig.class)) {
967 checkState(xConnectHandler != null, "XConnectHandler is not initialized");
968 switch (event.type()) {
969 case CONFIG_ADDED:
970 xConnectHandler.processXConnectConfigAdded(event);
971 break;
972 case CONFIG_UPDATED:
973 xConnectHandler.processXConnectConfigUpdated(event);
974 break;
975 case CONFIG_REMOVED:
976 xConnectHandler.processXConnectConfigRemoved(event);
Charles Chan5270ed02016-01-30 23:22:37 -0800977 break;
978 default:
979 break;
Charles Chanb8e10c82015-10-14 11:24:40 -0700980 }
Charles Chand6832882015-10-05 17:50:33 -0700981 }
982 }
983 }
Charles Chan68aa62d2015-11-09 16:37:23 -0800984
985 private class InternalHostListener implements HostListener {
Charles Chan68aa62d2015-11-09 16:37:23 -0800986 @Override
987 public void event(HostEvent event) {
988 // Do not proceed without mastership
989 DeviceId deviceId = event.subject().location().deviceId();
990 if (!mastershipService.isLocalMaster(deviceId)) {
991 return;
992 }
993
994 switch (event.type()) {
995 case HOST_ADDED:
Charles Chand2990362016-04-18 13:44:03 -0700996 hostHandler.processHostAddedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -0800997 break;
998 case HOST_MOVED:
Charles Chand2990362016-04-18 13:44:03 -0700999 hostHandler.processHostMovedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -08001000 break;
1001 case HOST_REMOVED:
Charles Chand2990362016-04-18 13:44:03 -07001002 hostHandler.processHostRemoveEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -08001003 break;
1004 case HOST_UPDATED:
Charles Chand2990362016-04-18 13:44:03 -07001005 hostHandler.processHostUpdatedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -08001006 break;
1007 default:
1008 log.warn("Unsupported host event type: {}", event.type());
1009 break;
1010 }
1011 }
1012 }
1013
Charles Chand55e84d2016-03-30 17:54:24 -07001014 private class InternalMcastListener implements McastListener {
1015 @Override
1016 public void event(McastEvent event) {
1017 switch (event.type()) {
1018 case SOURCE_ADDED:
Charles Chand2990362016-04-18 13:44:03 -07001019 mcastHandler.processSourceAdded(event);
Charles Chand55e84d2016-03-30 17:54:24 -07001020 break;
1021 case SINK_ADDED:
Charles Chand2990362016-04-18 13:44:03 -07001022 mcastHandler.processSinkAdded(event);
Charles Chand55e84d2016-03-30 17:54:24 -07001023 break;
1024 case SINK_REMOVED:
Charles Chand2990362016-04-18 13:44:03 -07001025 mcastHandler.processSinkRemoved(event);
Charles Chand55e84d2016-03-30 17:54:24 -07001026 break;
1027 case ROUTE_ADDED:
1028 case ROUTE_REMOVED:
1029 default:
1030 break;
1031 }
1032 }
1033 }
Charles Chan35fd1a72016-06-13 18:54:31 -07001034
1035 private class InternalCordConfigListener implements CordConfigListener {
1036 @Override
1037 public void event(CordConfigEvent event) {
1038 switch (event.type()) {
1039 case ACCESS_AGENT_ADDED:
1040 cordConfigHandler.processAccessAgentAddedEvent(event);
1041 break;
1042 case ACCESS_AGENT_UPDATED:
1043 cordConfigHandler.processAccessAgentUpdatedEvent(event);
1044 break;
1045 case ACCESS_AGENT_REMOVED:
1046 cordConfigHandler.processAccessAgentRemovedEvent(event);
1047 break;
1048 case ACCESS_DEVICE_ADDED:
1049 case ACCESS_DEVICE_UPDATED:
1050 case ACCESS_DEVICE_REMOVED:
1051 default:
1052 break;
1053 }
1054 }
1055 }
sanghob35a6192015-04-01 13:05:26 -07001056}