blob: bd89102e2ff262136ddce07cb67fe929a502cddc [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;
Charles Chan2c15aca2016-11-09 20:51:44 -080036import org.onosproject.incubator.net.intf.InterfaceService;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070037import org.onosproject.mastership.MastershipService;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070038import org.onosproject.net.Device;
39import org.onosproject.net.DeviceId;
40import org.onosproject.net.Link;
41import org.onosproject.net.Port;
Charles Chan68aa62d2015-11-09 16:37:23 -080042import org.onosproject.net.PortNumber;
Charles Chand6832882015-10-05 17:50:33 -070043import org.onosproject.net.config.ConfigFactory;
44import org.onosproject.net.config.NetworkConfigEvent;
Charles Chand6832882015-10-05 17:50:33 -070045import org.onosproject.net.config.NetworkConfigListener;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070046import org.onosproject.net.config.NetworkConfigRegistry;
Charles Chand6832882015-10-05 17:50:33 -070047import org.onosproject.net.config.basics.SubjectFactories;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070048import org.onosproject.net.device.DeviceEvent;
49import org.onosproject.net.device.DeviceListener;
50import org.onosproject.net.device.DeviceService;
Charles Chan68aa62d2015-11-09 16:37:23 -080051import org.onosproject.net.flow.DefaultTrafficSelector;
Charles Chan68aa62d2015-11-09 16:37:23 -080052import org.onosproject.net.flow.TrafficSelector;
53import org.onosproject.net.flow.TrafficTreatment;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070054import org.onosproject.net.flowobjective.FlowObjectiveService;
Charles Chan68aa62d2015-11-09 16:37:23 -080055import org.onosproject.net.host.HostEvent;
56import org.onosproject.net.host.HostListener;
Charles Chand55e84d2016-03-30 17:54:24 -070057import org.onosproject.net.mcast.McastEvent;
58import org.onosproject.net.mcast.McastListener;
59import org.onosproject.net.mcast.MulticastRouteService;
60import org.onosproject.net.packet.PacketPriority;
61import org.onosproject.net.topology.TopologyService;
62import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
63import org.onosproject.segmentrouting.config.DeviceConfiguration;
64import org.onosproject.segmentrouting.config.SegmentRoutingDeviceConfig;
65import org.onosproject.segmentrouting.config.SegmentRoutingAppConfig;
Charles Chanfc5c7802016-05-17 13:13:55 -070066import org.onosproject.segmentrouting.config.XConnectConfig;
Charles Chand55e84d2016-03-30 17:54:24 -070067import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
68import org.onosproject.segmentrouting.grouphandler.NeighborSet;
Charles Chand2990362016-04-18 13:44:03 -070069import org.onosproject.segmentrouting.storekey.NeighborSetNextObjectiveStoreKey;
70import org.onosproject.segmentrouting.storekey.PortNextObjectiveStoreKey;
sanghob35a6192015-04-01 13:05:26 -070071import org.onosproject.net.host.HostService;
sanghob35a6192015-04-01 13:05:26 -070072import org.onosproject.net.link.LinkEvent;
73import org.onosproject.net.link.LinkListener;
74import org.onosproject.net.link.LinkService;
75import org.onosproject.net.packet.InboundPacket;
76import org.onosproject.net.packet.PacketContext;
77import org.onosproject.net.packet.PacketProcessor;
78import org.onosproject.net.packet.PacketService;
Charles Chand2990362016-04-18 13:44:03 -070079import org.onosproject.segmentrouting.storekey.SubnetAssignedVidStoreKey;
80import org.onosproject.segmentrouting.storekey.SubnetNextObjectiveStoreKey;
Charles Chanfc5c7802016-05-17 13:13:55 -070081import org.onosproject.segmentrouting.storekey.XConnectStoreKey;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070082import org.onosproject.store.serializers.KryoNamespaces;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -070083import org.onosproject.store.service.EventuallyConsistentMap;
84import org.onosproject.store.service.EventuallyConsistentMapBuilder;
85import org.onosproject.store.service.StorageService;
86import org.onosproject.store.service.WallClockTimestamp;
Charles Chan35fd1a72016-06-13 18:54:31 -070087import org.opencord.cordconfig.CordConfigEvent;
88import org.opencord.cordconfig.CordConfigListener;
89import org.opencord.cordconfig.CordConfigService;
sanghob35a6192015-04-01 13:05:26 -070090import org.slf4j.Logger;
91import org.slf4j.LoggerFactory;
92
Saurav Das0e99e2b2015-10-28 12:39:42 -070093import java.util.Collections;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -070094import java.util.HashSet;
sangho1e575652015-05-14 00:39:53 -070095import java.util.List;
sanghob35a6192015-04-01 13:05:26 -070096import java.util.Map;
Charles Chan188ebf52015-12-23 00:15:11 -080097import java.util.Optional;
Saurav Das0e99e2b2015-10-28 12:39:42 -070098import java.util.Set;
sanghob35a6192015-04-01 13:05:26 -070099import java.util.concurrent.ConcurrentHashMap;
100import java.util.concurrent.ConcurrentLinkedQueue;
101import java.util.concurrent.Executors;
102import java.util.concurrent.ScheduledExecutorService;
103import java.util.concurrent.ScheduledFuture;
104import java.util.concurrent.TimeUnit;
105
Charles Chan3e783d02016-02-26 22:19:52 -0800106import static com.google.common.base.Preconditions.checkState;
Yuta HIGUCHI1624df12016-07-21 16:54:33 -0700107import static org.onlab.util.Tools.groupedThreads;
Charles Chan3e783d02016-02-26 22:19:52 -0800108
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700109
Charles Chane849c192016-01-11 18:28:54 -0800110/**
111 * Segment routing manager.
112 */
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700113@Service
114@Component(immediate = true)
sangho1e575652015-05-14 00:39:53 -0700115public class SegmentRoutingManager implements SegmentRoutingService {
sanghob35a6192015-04-01 13:05:26 -0700116
Charles Chan2c15aca2016-11-09 20:51:44 -0800117 private static Logger log = LoggerFactory.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)
Charles Chan2c15aca2016-11-09 20:51:44 -0800144 public NetworkConfigRegistry cfgService;
Charles Chan5270ed02016-01-30 23:22:37 -0800145
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
Charles Chan2c15aca2016-11-09 20:51:44 -0800158 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
159 public InterfaceService interfaceService;
160
Srikanth Vavilapalli4db76e32015-04-07 15:12:32 -0700161 protected ArpHandler arpHandler = null;
162 protected IcmpHandler icmpHandler = null;
163 protected IpHandler ipHandler = null;
164 protected RoutingRulePopulator routingRulePopulator = null;
Charles Chan2c15aca2016-11-09 20:51:44 -0800165 public ApplicationId appId;
sangho666cd6d2015-04-14 16:27:13 -0700166 protected DeviceConfiguration deviceConfiguration = null;
sanghob35a6192015-04-01 13:05:26 -0700167
Charles Chan93e71ba2016-04-29 14:38:22 -0700168 protected DefaultRoutingHandler defaultRoutingHandler = null;
sangho1e575652015-05-14 00:39:53 -0700169 private TunnelHandler tunnelHandler = null;
170 private PolicyHandler policyHandler = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700171 private InternalPacketProcessor processor = null;
172 private InternalLinkListener linkListener = null;
173 private InternalDeviceListener deviceListener = null;
Charles Chanfc5c7802016-05-17 13:13:55 -0700174 private AppConfigHandler appCfgHandler = null;
175 protected XConnectHandler xConnectHandler = null;
Charles Chand2990362016-04-18 13:44:03 -0700176 private McastHandler mcastHandler = null;
Charles Chan35fd1a72016-06-13 18:54:31 -0700177 protected HostHandler hostHandler = null;
178 private CordConfigHandler cordConfigHandler = null;
sanghob35a6192015-04-01 13:05:26 -0700179 private InternalEventHandler eventHandler = new InternalEventHandler();
Charles Chan5270ed02016-01-30 23:22:37 -0800180 private final InternalHostListener hostListener = new InternalHostListener();
Charles Chand55e84d2016-03-30 17:54:24 -0700181 private final InternalConfigListener cfgListener = new InternalConfigListener(this);
182 private final InternalMcastListener mcastListener = new InternalMcastListener();
Charles Chan35fd1a72016-06-13 18:54:31 -0700183 private final InternalCordConfigListener cordConfigListener = new InternalCordConfigListener();
sanghob35a6192015-04-01 13:05:26 -0700184
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700185 private ScheduledExecutorService executorService = Executors
Yuta HIGUCHI1624df12016-07-21 16:54:33 -0700186 .newScheduledThreadPool(1, groupedThreads("SegmentRoutingManager", "event-%d", log));
sanghob35a6192015-04-01 13:05:26 -0700187
Saurav Das4ce45962015-11-24 23:21:05 -0800188 @SuppressWarnings("unused")
sanghob35a6192015-04-01 13:05:26 -0700189 private static ScheduledFuture<?> eventHandlerFuture = null;
Saurav Das4ce45962015-11-24 23:21:05 -0800190 @SuppressWarnings("rawtypes")
Yuta HIGUCHI1624df12016-07-21 16:54:33 -0700191 private ConcurrentLinkedQueue<Event> eventQueue = new ConcurrentLinkedQueue<>();
Charles Chan68aa62d2015-11-09 16:37:23 -0800192 private Map<DeviceId, DefaultGroupHandler> groupHandlerMap =
Charles Chane849c192016-01-11 18:28:54 -0800193 new ConcurrentHashMap<>();
194 /**
195 * Per device next objective ID store with (device id + neighbor set) as key.
196 */
197 public EventuallyConsistentMap<NeighborSetNextObjectiveStoreKey, Integer>
Charles Chan68aa62d2015-11-09 16:37:23 -0800198 nsNextObjStore = null;
Charles Chane849c192016-01-11 18:28:54 -0800199 /**
200 * Per device next objective ID store with (device id + subnet) as key.
201 */
202 public EventuallyConsistentMap<SubnetNextObjectiveStoreKey, Integer>
Charles Chan68aa62d2015-11-09 16:37:23 -0800203 subnetNextObjStore = null;
Charles Chane849c192016-01-11 18:28:54 -0800204 /**
205 * Per device next objective ID store with (device id + port) as key.
206 */
207 public EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer>
Saurav Das4ce45962015-11-24 23:21:05 -0800208 portNextObjStore = null;
Saurav Das0e99e2b2015-10-28 12:39:42 -0700209 // Per device, per-subnet assigned-vlans store, with (device id + subnet
210 // IPv4 prefix) as key
211 private EventuallyConsistentMap<SubnetAssignedVidStoreKey, VlanId>
Charles Chane849c192016-01-11 18:28:54 -0800212 subnetVidStore = null;
Saurav Das4ce45962015-11-24 23:21:05 -0800213 private EventuallyConsistentMap<String, Tunnel> tunnelStore = null;
214 private EventuallyConsistentMap<String, Policy> policyStore = null;
sangho0b2b6d12015-05-20 22:16:38 -0700215
Charles Chand55e84d2016-03-30 17:54:24 -0700216 private final ConfigFactory<DeviceId, SegmentRoutingDeviceConfig> deviceConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700217 new ConfigFactory<DeviceId, SegmentRoutingDeviceConfig>(
218 SubjectFactories.DEVICE_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700219 SegmentRoutingDeviceConfig.class, "segmentrouting") {
Charles Chand6832882015-10-05 17:50:33 -0700220 @Override
Charles Chan5270ed02016-01-30 23:22:37 -0800221 public SegmentRoutingDeviceConfig createConfig() {
222 return new SegmentRoutingDeviceConfig();
Charles Chand6832882015-10-05 17:50:33 -0700223 }
224 };
Charles Chand55e84d2016-03-30 17:54:24 -0700225 private final ConfigFactory<ApplicationId, SegmentRoutingAppConfig> appConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700226 new ConfigFactory<ApplicationId, SegmentRoutingAppConfig>(
227 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700228 SegmentRoutingAppConfig.class, "segmentrouting") {
Charles Chan5270ed02016-01-30 23:22:37 -0800229 @Override
230 public SegmentRoutingAppConfig createConfig() {
231 return new SegmentRoutingAppConfig();
232 }
233 };
Charles Chanfc5c7802016-05-17 13:13:55 -0700234 private final ConfigFactory<ApplicationId, XConnectConfig> xConnectConfigFactory =
235 new ConfigFactory<ApplicationId, XConnectConfig>(
236 SubjectFactories.APP_SUBJECT_FACTORY,
237 XConnectConfig.class, "xconnect") {
238 @Override
239 public XConnectConfig createConfig() {
240 return new XConnectConfig();
241 }
242 };
Charles Chand55e84d2016-03-30 17:54:24 -0700243 private ConfigFactory<ApplicationId, McastConfig> mcastConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700244 new ConfigFactory<ApplicationId, McastConfig>(
245 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700246 McastConfig.class, "multicast") {
247 @Override
248 public McastConfig createConfig() {
249 return new McastConfig();
250 }
251 };
252
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700253 private Object threadSchedulerLock = new Object();
254 private static int numOfEventsQueued = 0;
255 private static int numOfEventsExecuted = 0;
sanghob35a6192015-04-01 13:05:26 -0700256 private static int numOfHandlerExecution = 0;
257 private static int numOfHandlerScheduled = 0;
258
Charles Chan116188d2016-02-18 14:22:42 -0800259 /**
260 * Segment Routing App ID.
261 */
Charles Chan2c15aca2016-11-09 20:51:44 -0800262 public static final String APP_NAME = "org.onosproject.segmentrouting";
Charles Chane849c192016-01-11 18:28:54 -0800263 /**
264 * The starting value of per-subnet VLAN ID assignment.
265 */
Saurav Das0e99e2b2015-10-28 12:39:42 -0700266 private static final short ASSIGNED_VLAN_START = 4093;
Charles Chane849c192016-01-11 18:28:54 -0800267 /**
268 * The default VLAN ID assigned to the interfaces without subnet config.
269 */
Saurav Das0e99e2b2015-10-28 12:39:42 -0700270 public static final short ASSIGNED_VLAN_NO_SUBNET = 4094;
271
sanghob35a6192015-04-01 13:05:26 -0700272 @Activate
273 protected void activate() {
Charles Chan2c15aca2016-11-09 20:51:44 -0800274 appId = coreService.registerApplication(APP_NAME);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700275
276 log.debug("Creating EC map nsnextobjectivestore");
277 EventuallyConsistentMapBuilder<NeighborSetNextObjectiveStoreKey, Integer>
278 nsNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700279 nsNextObjStore = nsNextObjMapBuilder
280 .withName("nsnextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700281 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700282 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700283 .build();
284 log.trace("Current size {}", nsNextObjStore.size());
285
Charles Chanc42e84e2015-10-20 16:24:19 -0700286 log.debug("Creating EC map subnetnextobjectivestore");
287 EventuallyConsistentMapBuilder<SubnetNextObjectiveStoreKey, Integer>
288 subnetNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
Charles Chanc42e84e2015-10-20 16:24:19 -0700289 subnetNextObjStore = subnetNextObjMapBuilder
290 .withName("subnetnextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700291 .withSerializer(createSerializer())
Charles Chanc42e84e2015-10-20 16:24:19 -0700292 .withTimestampProvider((k, v) -> new WallClockTimestamp())
293 .build();
294
Saurav Das4ce45962015-11-24 23:21:05 -0800295 log.debug("Creating EC map subnetnextobjectivestore");
296 EventuallyConsistentMapBuilder<PortNextObjectiveStoreKey, Integer>
297 portNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
298 portNextObjStore = portNextObjMapBuilder
299 .withName("portnextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700300 .withSerializer(createSerializer())
Saurav Das4ce45962015-11-24 23:21:05 -0800301 .withTimestampProvider((k, v) -> new WallClockTimestamp())
302 .build();
303
sangho0b2b6d12015-05-20 22:16:38 -0700304 EventuallyConsistentMapBuilder<String, Tunnel> tunnelMapBuilder =
305 storageService.eventuallyConsistentMapBuilder();
sangho0b2b6d12015-05-20 22:16:38 -0700306 tunnelStore = tunnelMapBuilder
307 .withName("tunnelstore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700308 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700309 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho0b2b6d12015-05-20 22:16:38 -0700310 .build();
311
312 EventuallyConsistentMapBuilder<String, Policy> policyMapBuilder =
313 storageService.eventuallyConsistentMapBuilder();
sangho0b2b6d12015-05-20 22:16:38 -0700314 policyStore = policyMapBuilder
315 .withName("policystore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700316 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700317 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho0b2b6d12015-05-20 22:16:38 -0700318 .build();
319
Saurav Das0e99e2b2015-10-28 12:39:42 -0700320 EventuallyConsistentMapBuilder<SubnetAssignedVidStoreKey, VlanId>
321 subnetVidStoreMapBuilder = storageService.eventuallyConsistentMapBuilder();
Saurav Das0e99e2b2015-10-28 12:39:42 -0700322 subnetVidStore = subnetVidStoreMapBuilder
323 .withName("subnetvidstore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700324 .withSerializer(createSerializer())
Saurav Das0e99e2b2015-10-28 12:39:42 -0700325 .withTimestampProvider((k, v) -> new WallClockTimestamp())
326 .build();
327
Saurav Das80980c72016-03-23 11:22:49 -0700328 compCfgService.preSetProperty("org.onosproject.net.group.impl.GroupManager",
329 "purgeOnDisconnection", "true");
330 compCfgService.preSetProperty("org.onosproject.net.flow.impl.FlowRuleManager",
331 "purgeOnDisconnection", "true");
332
Charles Chanb8e10c82015-10-14 11:24:40 -0700333 processor = new InternalPacketProcessor();
334 linkListener = new InternalLinkListener();
335 deviceListener = new InternalDeviceListener();
Charles Chanfc5c7802016-05-17 13:13:55 -0700336 appCfgHandler = new AppConfigHandler(this);
337 xConnectHandler = new XConnectHandler(this);
Charles Chand2990362016-04-18 13:44:03 -0700338 mcastHandler = new McastHandler(this);
339 hostHandler = new HostHandler(this);
Charles Chan35fd1a72016-06-13 18:54:31 -0700340 cordConfigHandler = new CordConfigHandler(this);
Charles Chanb8e10c82015-10-14 11:24:40 -0700341
Charles Chan3e783d02016-02-26 22:19:52 -0800342 cfgService.addListener(cfgListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700343 cfgService.registerConfigFactory(deviceConfigFactory);
344 cfgService.registerConfigFactory(appConfigFactory);
Charles Chanfc5c7802016-05-17 13:13:55 -0700345 cfgService.registerConfigFactory(xConnectConfigFactory);
Charles Chand55e84d2016-03-30 17:54:24 -0700346 cfgService.registerConfigFactory(mcastConfigFactory);
Charles Chan5270ed02016-01-30 23:22:37 -0800347 hostService.addListener(hostListener);
Charles Chanb8e10c82015-10-14 11:24:40 -0700348 packetService.addProcessor(processor, PacketProcessor.director(2));
349 linkService.addListener(linkListener);
350 deviceService.addListener(deviceListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700351 multicastRouteService.addListener(mcastListener);
Charles Chan35fd1a72016-06-13 18:54:31 -0700352 cordConfigService.addListener(cordConfigListener);
Charles Chanb8e10c82015-10-14 11:24:40 -0700353
Charles Chan188ebf52015-12-23 00:15:11 -0800354 // Request ARP packet-in
355 TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
356 selector.matchEthType(Ethernet.TYPE_ARP);
357 packetService.requestPackets(selector.build(), PacketPriority.CONTROL, appId, Optional.empty());
358
Charles Chanb8e10c82015-10-14 11:24:40 -0700359 cfgListener.configureNetwork();
360
sanghob35a6192015-04-01 13:05:26 -0700361 log.info("Started");
362 }
363
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700364 private KryoNamespace.Builder createSerializer() {
365 return new KryoNamespace.Builder()
366 .register(KryoNamespaces.API)
367 .register(NeighborSetNextObjectiveStoreKey.class,
368 SubnetNextObjectiveStoreKey.class,
369 SubnetAssignedVidStoreKey.class,
370 NeighborSet.class,
371 Tunnel.class,
372 DefaultTunnel.class,
373 Policy.class,
374 TunnelPolicy.class,
375 Policy.Type.class,
376 PortNextObjectiveStoreKey.class,
Charles Chanfc5c7802016-05-17 13:13:55 -0700377 XConnectStoreKey.class
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700378 );
379 }
380
sanghob35a6192015-04-01 13:05:26 -0700381 @Deactivate
382 protected void deactivate() {
Charles Chand6832882015-10-05 17:50:33 -0700383 cfgService.removeListener(cfgListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700384 cfgService.unregisterConfigFactory(deviceConfigFactory);
385 cfgService.unregisterConfigFactory(appConfigFactory);
386 cfgService.unregisterConfigFactory(mcastConfigFactory);
Charles Chand6832882015-10-05 17:50:33 -0700387
Charles Chan188ebf52015-12-23 00:15:11 -0800388 // Withdraw ARP packet-in
389 TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
390 selector.matchEthType(Ethernet.TYPE_ARP);
391 packetService.cancelPackets(selector.build(), PacketPriority.CONTROL, appId, Optional.empty());
392
sanghob35a6192015-04-01 13:05:26 -0700393 packetService.removeProcessor(processor);
Charles Chanb8e10c82015-10-14 11:24:40 -0700394 linkService.removeListener(linkListener);
395 deviceService.removeListener(deviceListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700396 multicastRouteService.removeListener(mcastListener);
Charles Chan35fd1a72016-06-13 18:54:31 -0700397 cordConfigService.removeListener(cordConfigListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700398
sanghob35a6192015-04-01 13:05:26 -0700399 processor = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700400 linkListener = null;
Charles Chand55e84d2016-03-30 17:54:24 -0700401 deviceListener = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700402 groupHandlerMap.clear();
403
Charles Chand55e84d2016-03-30 17:54:24 -0700404 nsNextObjStore.destroy();
405 subnetNextObjStore.destroy();
406 portNextObjStore.destroy();
Charles Chand55e84d2016-03-30 17:54:24 -0700407 tunnelStore.destroy();
408 policyStore.destroy();
409 subnetVidStore.destroy();
sanghob35a6192015-04-01 13:05:26 -0700410 log.info("Stopped");
411 }
412
sangho1e575652015-05-14 00:39:53 -0700413 @Override
414 public List<Tunnel> getTunnels() {
415 return tunnelHandler.getTunnels();
416 }
417
418 @Override
sangho71abe1b2015-06-29 14:58:47 -0700419 public TunnelHandler.Result createTunnel(Tunnel tunnel) {
420 return tunnelHandler.createTunnel(tunnel);
sangho1e575652015-05-14 00:39:53 -0700421 }
422
423 @Override
sangho71abe1b2015-06-29 14:58:47 -0700424 public TunnelHandler.Result removeTunnel(Tunnel tunnel) {
sangho1e575652015-05-14 00:39:53 -0700425 for (Policy policy: policyHandler.getPolicies()) {
426 if (policy.type() == Policy.Type.TUNNEL_FLOW) {
427 TunnelPolicy tunnelPolicy = (TunnelPolicy) policy;
428 if (tunnelPolicy.tunnelId().equals(tunnel.id())) {
429 log.warn("Cannot remove the tunnel used by a policy");
sangho71abe1b2015-06-29 14:58:47 -0700430 return TunnelHandler.Result.TUNNEL_IN_USE;
sangho1e575652015-05-14 00:39:53 -0700431 }
432 }
433 }
sangho71abe1b2015-06-29 14:58:47 -0700434 return tunnelHandler.removeTunnel(tunnel);
sangho1e575652015-05-14 00:39:53 -0700435 }
436
437 @Override
sangho71abe1b2015-06-29 14:58:47 -0700438 public PolicyHandler.Result removePolicy(Policy policy) {
439 return policyHandler.removePolicy(policy);
sangho1e575652015-05-14 00:39:53 -0700440 }
441
442 @Override
sangho71abe1b2015-06-29 14:58:47 -0700443 public PolicyHandler.Result createPolicy(Policy policy) {
444 return policyHandler.createPolicy(policy);
sangho1e575652015-05-14 00:39:53 -0700445 }
446
447 @Override
448 public List<Policy> getPolicies() {
449 return policyHandler.getPolicies();
450 }
451
Saurav Das59232cf2016-04-27 18:35:50 -0700452 @Override
453 public void rerouteNetwork() {
454 cfgListener.configureNetwork();
455 for (Device device : deviceService.getDevices()) {
456 defaultRoutingHandler.populatePortAddressingRules(device.id());
457 }
458 defaultRoutingHandler.startPopulationProcess();
459 }
460
Charles Chanc81c45b2016-10-20 17:02:44 -0700461 @Override
462 public Map<DeviceId, Set<Ip4Prefix>> getDeviceSubnetMap() {
463 Map<DeviceId, Set<Ip4Prefix>> deviceSubnetMap = Maps.newHashMap();
464 deviceService.getAvailableDevices().forEach(device -> {
465 deviceSubnetMap.put(device.id(), deviceConfiguration.getSubnets(device.id()));
466 });
467 return deviceSubnetMap;
468 }
469
sanghof9d0bf12015-05-19 11:57:42 -0700470 /**
471 * Returns the tunnel object with the tunnel ID.
472 *
473 * @param tunnelId Tunnel ID
474 * @return Tunnel reference
475 */
sangho1e575652015-05-14 00:39:53 -0700476 public Tunnel getTunnel(String tunnelId) {
477 return tunnelHandler.getTunnel(tunnelId);
478 }
479
sanghob35a6192015-04-01 13:05:26 -0700480 /**
Saurav Das0e99e2b2015-10-28 12:39:42 -0700481 * Returns the vlan-id assigned to the subnet configured for a device.
482 * If no vlan-id has been assigned, a new one is assigned out of a pool of ids,
483 * if and only if this controller instance is the master for the device.
484 * <p>
485 * USAGE: The assigned vlans are meant to be applied to untagged packets on those
486 * switches/pipelines that need this functionality. These vids are meant
487 * to be used internally within a switch, and thus need to be unique only
488 * on a switch level. Note that packets never go out on the wire with these
489 * vlans. Currently, vlan ids are assigned from value 4093 down.
490 * Vlan id 4094 expected to be used for all ports that are not assigned subnets.
491 * Vlan id 4095 is reserved and unused. Only a single vlan id is assigned
492 * per subnet.
sanghob35a6192015-04-01 13:05:26 -0700493 *
Saurav Das0e99e2b2015-10-28 12:39:42 -0700494 * @param deviceId switch dpid
495 * @param subnet IPv4 prefix for which assigned vlan is desired
496 * @return VlanId assigned for the subnet on the device, or
497 * null if no vlan assignment was found and this instance is not
498 * the master for the device.
sanghob35a6192015-04-01 13:05:26 -0700499 */
Charles Chane849c192016-01-11 18:28:54 -0800500 // TODO: We should avoid assigning VLAN IDs that are used by VLAN cross-connection.
Saurav Das0e99e2b2015-10-28 12:39:42 -0700501 public VlanId getSubnetAssignedVlanId(DeviceId deviceId, Ip4Prefix subnet) {
502 VlanId assignedVid = subnetVidStore.get(new SubnetAssignedVidStoreKey(
503 deviceId, subnet));
504 if (assignedVid != null) {
505 log.debug("Query for subnet:{} on device:{} returned assigned-vlan "
506 + "{}", subnet, deviceId, assignedVid);
507 return assignedVid;
508 }
509 //check mastership for the right to assign a vlan
510 if (!mastershipService.isLocalMaster(deviceId)) {
511 log.warn("This controller instance is not the master for device {}. "
512 + "Cannot assign vlan-id for subnet {}", deviceId, subnet);
513 return null;
514 }
515 // vlan assignment is expensive but done only once
Charles Chan9f676b62015-10-29 14:58:10 -0700516 Set<Ip4Prefix> configuredSubnets = deviceConfiguration.getSubnets(deviceId);
Saurav Das0e99e2b2015-10-28 12:39:42 -0700517 Set<Short> assignedVlans = new HashSet<>();
518 Set<Ip4Prefix> unassignedSubnets = new HashSet<>();
519 for (Ip4Prefix sub : configuredSubnets) {
520 VlanId v = subnetVidStore.get(new SubnetAssignedVidStoreKey(deviceId,
521 sub));
522 if (v != null) {
523 assignedVlans.add(v.toShort());
524 } else {
525 unassignedSubnets.add(sub);
526 }
527 }
528 short nextAssignedVlan = ASSIGNED_VLAN_START;
529 if (!assignedVlans.isEmpty()) {
530 nextAssignedVlan = (short) (Collections.min(assignedVlans) - 1);
531 }
532 for (Ip4Prefix unsub : unassignedSubnets) {
Charles Chan5270ed02016-01-30 23:22:37 -0800533 // Special case for default route. Assign default VLAN ID to /32 and /0 subnets
534 if (unsub.prefixLength() == IpPrefix.MAX_INET_MASK_LENGTH ||
535 unsub.prefixLength() == 0) {
536 subnetVidStore.put(new SubnetAssignedVidStoreKey(deviceId, unsub),
537 VlanId.vlanId(ASSIGNED_VLAN_NO_SUBNET));
538 } else {
539 subnetVidStore.put(new SubnetAssignedVidStoreKey(deviceId, unsub),
540 VlanId.vlanId(nextAssignedVlan--));
541 log.info("Assigned vlan: {} to subnet: {} on device: {}",
542 nextAssignedVlan + 1, unsub, deviceId);
543 }
sanghob35a6192015-04-01 13:05:26 -0700544 }
545
Saurav Das0e99e2b2015-10-28 12:39:42 -0700546 return subnetVidStore.get(new SubnetAssignedVidStoreKey(deviceId, subnet));
sanghob35a6192015-04-01 13:05:26 -0700547 }
548
sangho1e575652015-05-14 00:39:53 -0700549 /**
Saurav Das0e99e2b2015-10-28 12:39:42 -0700550 * Returns the next objective ID for the given NeighborSet.
Saurav Das8a0732e2015-11-20 15:27:53 -0800551 * If the nextObjective does not exist, a new one is created and
Saurav Das4ce45962015-11-24 23:21:05 -0800552 * its id is returned.
sangho1e575652015-05-14 00:39:53 -0700553 *
sanghof9d0bf12015-05-19 11:57:42 -0700554 * @param deviceId Device ID
555 * @param ns NegighborSet
Saurav Das8a0732e2015-11-20 15:27:53 -0800556 * @param meta metadata passed into the creation of a Next Objective
557 * @return next objective ID or -1 if an error was encountered during the
558 * creation of the nextObjective
sangho1e575652015-05-14 00:39:53 -0700559 */
Saurav Das8a0732e2015-11-20 15:27:53 -0800560 public int getNextObjectiveId(DeviceId deviceId, NeighborSet ns,
561 TrafficSelector meta) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700562 if (groupHandlerMap.get(deviceId) != null) {
563 log.trace("getNextObjectiveId query in device {}", deviceId);
564 return groupHandlerMap
Saurav Das8a0732e2015-11-20 15:27:53 -0800565 .get(deviceId).getNextObjectiveId(ns, meta);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700566 } else {
Saurav Das4ce45962015-11-24 23:21:05 -0800567 log.warn("getNextObjectiveId query - groupHandler for device {} "
568 + "not found", deviceId);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700569 return -1;
570 }
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700571 }
572
Charles Chanc42e84e2015-10-20 16:24:19 -0700573 /**
Saurav Das4ce45962015-11-24 23:21:05 -0800574 * Returns the next objective ID for the given subnet prefix. It is expected
575 * that the next-objective has been pre-created from configuration.
Charles Chanc42e84e2015-10-20 16:24:19 -0700576 *
577 * @param deviceId Device ID
578 * @param prefix Subnet
Saurav Das4ce45962015-11-24 23:21:05 -0800579 * @return next objective ID or -1 if it was not found
Charles Chanc42e84e2015-10-20 16:24:19 -0700580 */
581 public int getSubnetNextObjectiveId(DeviceId deviceId, IpPrefix prefix) {
582 if (groupHandlerMap.get(deviceId) != null) {
583 log.trace("getSubnetNextObjectiveId query in device {}", deviceId);
584 return groupHandlerMap
585 .get(deviceId).getSubnetNextObjectiveId(prefix);
586 } else {
Saurav Das4ce45962015-11-24 23:21:05 -0800587 log.warn("getSubnetNextObjectiveId query - groupHandler for "
588 + "device {} not found", deviceId);
589 return -1;
590 }
591 }
592
593 /**
594 * Returns the next objective ID for the given portNumber, given the treatment.
595 * There could be multiple different treatments to the same outport, which
596 * would result in different objectives. If the next object
597 * does not exist, a new one is created and its id is returned.
598 *
599 * @param deviceId Device ID
600 * @param portNum port number on device for which NextObjective is queried
601 * @param treatment the actions to apply on the packets (should include outport)
602 * @param meta metadata passed into the creation of a Next Objective if necessary
Saurav Das59232cf2016-04-27 18:35:50 -0700603 * @return next objective ID or -1 if an error occurred during retrieval or creation
Saurav Das4ce45962015-11-24 23:21:05 -0800604 */
605 public int getPortNextObjectiveId(DeviceId deviceId, PortNumber portNum,
606 TrafficTreatment treatment,
607 TrafficSelector meta) {
608 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
609 if (ghdlr != null) {
610 return ghdlr.getPortNextObjectiveId(portNum, treatment, meta);
611 } else {
Charles Chane849c192016-01-11 18:28:54 -0800612 log.warn("getPortNextObjectiveId query - groupHandler for device {}"
613 + " not found", deviceId);
614 return -1;
615 }
616 }
617
sanghob35a6192015-04-01 13:05:26 -0700618 private class InternalPacketProcessor implements PacketProcessor {
sanghob35a6192015-04-01 13:05:26 -0700619 @Override
620 public void process(PacketContext context) {
621
622 if (context.isHandled()) {
623 return;
624 }
625
626 InboundPacket pkt = context.inPacket();
627 Ethernet ethernet = pkt.parsed();
Saurav Das4ce45962015-11-24 23:21:05 -0800628 log.trace("Rcvd pktin: {}", ethernet);
sanghob35a6192015-04-01 13:05:26 -0700629 if (ethernet.getEtherType() == Ethernet.TYPE_ARP) {
630 arpHandler.processPacketIn(pkt);
631 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV4) {
632 IPv4 ipPacket = (IPv4) ethernet.getPayload();
633 ipHandler.addToPacketBuffer(ipPacket);
634 if (ipPacket.getProtocol() == IPv4.PROTOCOL_ICMP) {
635 icmpHandler.processPacketIn(pkt);
636 } else {
637 ipHandler.processPacketIn(pkt);
638 }
639 }
640 }
641 }
642
643 private class InternalLinkListener implements LinkListener {
644 @Override
645 public void event(LinkEvent event) {
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700646 if (event.type() == LinkEvent.Type.LINK_ADDED
647 || event.type() == LinkEvent.Type.LINK_REMOVED) {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700648 log.debug("Event {} received from Link Service", event.type());
sanghob35a6192015-04-01 13:05:26 -0700649 scheduleEventHandlerIfNotScheduled(event);
650 }
651 }
652 }
653
654 private class InternalDeviceListener implements DeviceListener {
sanghob35a6192015-04-01 13:05:26 -0700655 @Override
656 public void event(DeviceEvent event) {
sanghob35a6192015-04-01 13:05:26 -0700657 switch (event.type()) {
658 case DEVICE_ADDED:
659 case PORT_REMOVED:
sangho20eff1d2015-04-13 15:15:58 -0700660 case DEVICE_UPDATED:
661 case DEVICE_AVAILABILITY_CHANGED:
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700662 log.debug("Event {} received from Device Service", event.type());
sanghob35a6192015-04-01 13:05:26 -0700663 scheduleEventHandlerIfNotScheduled(event);
664 break;
665 default:
666 }
667 }
668 }
669
Saurav Das4ce45962015-11-24 23:21:05 -0800670 @SuppressWarnings("rawtypes")
sanghob35a6192015-04-01 13:05:26 -0700671 private void scheduleEventHandlerIfNotScheduled(Event event) {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700672 synchronized (threadSchedulerLock) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700673 eventQueue.add(event);
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700674 numOfEventsQueued++;
675
676 if ((numOfHandlerScheduled - numOfHandlerExecution) == 0) {
677 //No pending scheduled event handling threads. So start a new one.
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700678 eventHandlerFuture = executorService
679 .schedule(eventHandler, 100, TimeUnit.MILLISECONDS);
680 numOfHandlerScheduled++;
681 }
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700682 log.trace("numOfEventsQueued {}, numOfEventHandlerScheduled {}",
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700683 numOfEventsQueued,
684 numOfHandlerScheduled);
sanghob35a6192015-04-01 13:05:26 -0700685 }
sanghob35a6192015-04-01 13:05:26 -0700686 }
687
688 private class InternalEventHandler implements Runnable {
Srikanth Vavilapalli4db76e32015-04-07 15:12:32 -0700689 @Override
sanghob35a6192015-04-01 13:05:26 -0700690 public void run() {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700691 try {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700692 while (true) {
Saurav Das4ce45962015-11-24 23:21:05 -0800693 @SuppressWarnings("rawtypes")
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700694 Event event = null;
695 synchronized (threadSchedulerLock) {
696 if (!eventQueue.isEmpty()) {
697 event = eventQueue.poll();
698 numOfEventsExecuted++;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700699 } else {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700700 numOfHandlerExecution++;
701 log.debug("numOfHandlerExecution {} numOfEventsExecuted {}",
702 numOfHandlerExecution, numOfEventsExecuted);
703 break;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700704 }
sangho20eff1d2015-04-13 15:15:58 -0700705 }
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700706 if (event.type() == LinkEvent.Type.LINK_ADDED) {
707 processLinkAdded((Link) event.subject());
708 } else if (event.type() == LinkEvent.Type.LINK_REMOVED) {
Pier Ventre2c515312016-09-13 21:33:40 -0700709 Link linkRemoved = (Link) event.subject();
710 if (linkRemoved.src().elementId() instanceof DeviceId &&
711 !deviceService.isAvailable(linkRemoved.src().deviceId())) {
712 continue;
713 }
714 if (linkRemoved.dst().elementId() instanceof DeviceId &&
715 !deviceService.isAvailable(linkRemoved.dst().deviceId())) {
716 continue;
717 }
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700718 processLinkRemoved((Link) event.subject());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700719 } else if (event.type() == DeviceEvent.Type.DEVICE_ADDED ||
720 event.type() == DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED ||
721 event.type() == DeviceEvent.Type.DEVICE_UPDATED) {
Saurav Das423fe2b2015-12-04 10:52:59 -0800722 DeviceId deviceId = ((Device) event.subject()).id();
723 if (deviceService.isAvailable(deviceId)) {
Saurav Das837e0bb2015-10-30 17:45:38 -0700724 log.info("Processing device event {} for available device {}",
725 event.type(), ((Device) event.subject()).id());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700726 processDeviceAdded((Device) event.subject());
Saurav Das80980c72016-03-23 11:22:49 -0700727 } else {
728 log.info("Processing device event {} for unavailable device {}",
729 event.type(), ((Device) event.subject()).id());
730 processDeviceRemoved((Device) event.subject());
731 }
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700732 } else if (event.type() == DeviceEvent.Type.PORT_REMOVED) {
733 processPortRemoved((Device) event.subject(),
734 ((DeviceEvent) event).port());
Saurav Dasb5c236e2016-06-07 10:08:06 -0700735 } else if (event.type() == DeviceEvent.Type.PORT_ADDED ||
736 event.type() == DeviceEvent.Type.PORT_UPDATED) {
737 log.info("** PORT ADDED OR UPDATED {}/{} -> {}",
Yuta HIGUCHI1624df12016-07-21 16:54:33 -0700738 event.subject(),
Saurav Dasb5c236e2016-06-07 10:08:06 -0700739 ((DeviceEvent) event).port(),
740 event.type());
741 /* XXX create method for single port filtering rules
742 if (defaultRoutingHandler != null) {
743 defaultRoutingHandler.populatePortAddressingRules(
744 ((Device) event.subject()).id());
745 }*/
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700746 } else {
747 log.warn("Unhandled event type: {}", event.type());
748 }
sanghob35a6192015-04-01 13:05:26 -0700749 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700750 } catch (Exception e) {
751 log.error("SegmentRouting event handler "
752 + "thread thrown an exception: {}", e);
sanghob35a6192015-04-01 13:05:26 -0700753 }
sanghob35a6192015-04-01 13:05:26 -0700754 }
755 }
756
sanghob35a6192015-04-01 13:05:26 -0700757 private void processLinkAdded(Link link) {
Saurav Dasb5c236e2016-06-07 10:08:06 -0700758 log.info("** LINK ADDED {}", link.toString());
Charles Chan0b4e6182015-11-03 10:42:14 -0800759 if (!deviceConfiguration.isConfigured(link.src().deviceId())) {
760 log.warn("Source device of this link is not configured.");
761 return;
762 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700763 //Irrespective whether the local is a MASTER or not for this device,
764 //create group handler instance and push default TTP flow rules.
765 //Because in a multi-instance setup, instances can initiate
766 //groups for any devices. Also the default TTP rules are needed
767 //to be pushed before inserting any IP table entries for any device
768 DefaultGroupHandler groupHandler = groupHandlerMap.get(link.src()
769 .deviceId());
770 if (groupHandler != null) {
Saurav Das8a0732e2015-11-20 15:27:53 -0800771 groupHandler.linkUp(link, mastershipService.isLocalMaster(
772 link.src().deviceId()));
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700773 } else {
774 Device device = deviceService.getDevice(link.src().deviceId());
775 if (device != null) {
776 log.warn("processLinkAdded: Link Added "
777 + "Notification without Device Added "
778 + "event, still handling it");
779 processDeviceAdded(device);
780 groupHandler = groupHandlerMap.get(link.src()
781 .deviceId());
Saurav Das8a0732e2015-11-20 15:27:53 -0800782 groupHandler.linkUp(link, mastershipService.isLocalMaster(device.id()));
sanghob35a6192015-04-01 13:05:26 -0700783 }
784 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700785
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700786 log.trace("Starting optimized route population process");
787 defaultRoutingHandler.populateRoutingRulesForLinkStatusChange(null);
788 //log.trace("processLinkAdded: re-starting route population process");
789 //defaultRoutingHandler.startPopulationProcess();
Charles Chan2199c302016-04-23 17:36:10 -0700790
791 mcastHandler.init();
sanghob35a6192015-04-01 13:05:26 -0700792 }
793
794 private void processLinkRemoved(Link link) {
Saurav Dasb5c236e2016-06-07 10:08:06 -0700795 log.info("** LINK REMOVED {}", link.toString());
sangho834e4b02015-05-01 09:38:25 -0700796 DefaultGroupHandler groupHandler = groupHandlerMap.get(link.src().deviceId());
797 if (groupHandler != null) {
Saurav Das423fe2b2015-12-04 10:52:59 -0800798 groupHandler.portDown(link.src().port(),
799 mastershipService.isLocalMaster(link.src().deviceId()));
sangho834e4b02015-05-01 09:38:25 -0700800 }
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700801 log.trace("Starting optimized route population process");
802 defaultRoutingHandler.populateRoutingRulesForLinkStatusChange(link);
803 //log.trace("processLinkRemoved: re-starting route population process");
804 //defaultRoutingHandler.startPopulationProcess();
Charles Chan2199c302016-04-23 17:36:10 -0700805
806 mcastHandler.processLinkDown(link);
sanghob35a6192015-04-01 13:05:26 -0700807 }
808
809 private void processDeviceAdded(Device device) {
Saurav Dasb5c236e2016-06-07 10:08:06 -0700810 log.info("** DEVICE ADDED with ID {}", device.id());
Charles Chan0b4e6182015-11-03 10:42:14 -0800811 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
Saurav Das2857f382015-11-03 14:39:27 -0800812 log.warn("Device configuration uploading. Device {} will be "
813 + "processed after config completes.", device.id());
814 return;
815 }
Charles Chan2199c302016-04-23 17:36:10 -0700816 processDeviceAddedInternal(device.id());
817 }
818
819 private void processDeviceAddedInternal(DeviceId deviceId) {
Saurav Das837e0bb2015-10-30 17:45:38 -0700820 // Irrespective of whether the local is a MASTER or not for this device,
821 // we need to create a SR-group-handler instance. This is because in a
822 // multi-instance setup, any instance can initiate forwarding/next-objectives
823 // for any switch (even if this instance is a SLAVE or not even connected
824 // to the switch). To handle this, a default-group-handler instance is necessary
825 // per switch.
Charles Chan2199c302016-04-23 17:36:10 -0700826 log.debug("Current groupHandlerMap devs: {}", groupHandlerMap.keySet());
827 if (groupHandlerMap.get(deviceId) == null) {
Charles Chan0b4e6182015-11-03 10:42:14 -0800828 DefaultGroupHandler groupHandler;
829 try {
830 groupHandler = DefaultGroupHandler.
Charles Chan2199c302016-04-23 17:36:10 -0700831 createGroupHandler(deviceId,
832 appId,
833 deviceConfiguration,
834 linkService,
835 flowObjectiveService,
836 this);
Charles Chan0b4e6182015-11-03 10:42:14 -0800837 } catch (DeviceConfigNotFoundException e) {
838 log.warn(e.getMessage() + " Aborting processDeviceAdded.");
839 return;
840 }
Charles Chan2199c302016-04-23 17:36:10 -0700841 log.debug("updating groupHandlerMap with new config for device: {}",
842 deviceId);
843 groupHandlerMap.put(deviceId, groupHandler);
Saurav Das2857f382015-11-03 14:39:27 -0800844 }
Saurav Dasb5c236e2016-06-07 10:08:06 -0700845 // Also, in some cases, drivers may need extra
846 // information to process rules (eg. Router IP/MAC); and so, we send
847 // port addressing rules to the driver as well irrespective of whether
848 // this instance is the master or not.
849 defaultRoutingHandler.populatePortAddressingRules(deviceId);
850
Charles Chan2199c302016-04-23 17:36:10 -0700851 if (mastershipService.isLocalMaster(deviceId)) {
852 hostHandler.readInitialHosts(deviceId);
Charles Chanfc5c7802016-05-17 13:13:55 -0700853 xConnectHandler.init(deviceId);
Charles Chan35fd1a72016-06-13 18:54:31 -0700854 cordConfigHandler.init(deviceId);
Charles Chan2199c302016-04-23 17:36:10 -0700855 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
Charles Chanc42e84e2015-10-20 16:24:19 -0700856 groupHandler.createGroupsFromSubnetConfig();
Charles Chan2199c302016-04-23 17:36:10 -0700857 routingRulePopulator.populateSubnetBroadcastRule(deviceId);
Charles Chanc42e84e2015-10-20 16:24:19 -0700858 }
Charles Chan5270ed02016-01-30 23:22:37 -0800859
Charles Chanfc5c7802016-05-17 13:13:55 -0700860 appCfgHandler.initVRouters(deviceId);
sanghob35a6192015-04-01 13:05:26 -0700861 }
862
Saurav Das80980c72016-03-23 11:22:49 -0700863 private void processDeviceRemoved(Device device) {
864 nsNextObjStore.entrySet().stream()
865 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
866 .forEach(entry -> {
867 nsNextObjStore.remove(entry.getKey());
868 });
Saurav Das80980c72016-03-23 11:22:49 -0700869 subnetNextObjStore.entrySet().stream()
870 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
871 .forEach(entry -> {
872 subnetNextObjStore.remove(entry.getKey());
873 });
Saurav Das80980c72016-03-23 11:22:49 -0700874 portNextObjStore.entrySet().stream()
875 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
876 .forEach(entry -> {
877 portNextObjStore.remove(entry.getKey());
878 });
Saurav Das80980c72016-03-23 11:22:49 -0700879 subnetVidStore.entrySet().stream()
880 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
881 .forEach(entry -> {
882 subnetVidStore.remove(entry.getKey());
883 });
Saurav Das80980c72016-03-23 11:22:49 -0700884 groupHandlerMap.remove(device.id());
Saurav Das80980c72016-03-23 11:22:49 -0700885 defaultRoutingHandler.purgeEcmpGraph(device.id());
Charles Chan2199c302016-04-23 17:36:10 -0700886 mcastHandler.removeDevice(device.id());
Charles Chanfc5c7802016-05-17 13:13:55 -0700887 xConnectHandler.removeDevice(device.id());
Saurav Das80980c72016-03-23 11:22:49 -0700888 }
889
sanghob35a6192015-04-01 13:05:26 -0700890 private void processPortRemoved(Device device, Port port) {
Saurav Dasb5c236e2016-06-07 10:08:06 -0700891 log.info("Port {} was removed", port.toString());
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700892 DefaultGroupHandler groupHandler = groupHandlerMap.get(device.id());
sanghob35a6192015-04-01 13:05:26 -0700893 if (groupHandler != null) {
Saurav Das423fe2b2015-12-04 10:52:59 -0800894 groupHandler.portDown(port.number(),
895 mastershipService.isLocalMaster(device.id()));
sanghob35a6192015-04-01 13:05:26 -0700896 }
897 }
sangho1e575652015-05-14 00:39:53 -0700898
Charles Chand6832882015-10-05 17:50:33 -0700899 private class InternalConfigListener implements NetworkConfigListener {
Charles Chan2c15aca2016-11-09 20:51:44 -0800900 SegmentRoutingManager srManager;
Charles Chan4636be02015-10-07 14:21:45 -0700901
Charles Chane849c192016-01-11 18:28:54 -0800902 /**
903 * Constructs the internal network config listener.
904 *
Charles Chan2c15aca2016-11-09 20:51:44 -0800905 * @param srManager segment routing manager
Charles Chane849c192016-01-11 18:28:54 -0800906 */
Charles Chan2c15aca2016-11-09 20:51:44 -0800907 public InternalConfigListener(SegmentRoutingManager srManager) {
908 this.srManager = srManager;
Charles Chan4636be02015-10-07 14:21:45 -0700909 }
910
Charles Chane849c192016-01-11 18:28:54 -0800911 /**
912 * Reads network config and initializes related data structure accordingly.
913 */
Charles Chan4636be02015-10-07 14:21:45 -0700914 public void configureNetwork() {
Charles Chan2c15aca2016-11-09 20:51:44 -0800915 deviceConfiguration = new DeviceConfiguration(srManager);
Charles Chan4636be02015-10-07 14:21:45 -0700916
Charles Chan2c15aca2016-11-09 20:51:44 -0800917 arpHandler = new ArpHandler(srManager);
918 icmpHandler = new IcmpHandler(srManager);
919 ipHandler = new IpHandler(srManager);
920 routingRulePopulator = new RoutingRulePopulator(srManager);
921 defaultRoutingHandler = new DefaultRoutingHandler(srManager);
Charles Chan4636be02015-10-07 14:21:45 -0700922
923 tunnelHandler = new TunnelHandler(linkService, deviceConfiguration,
924 groupHandlerMap, tunnelStore);
925 policyHandler = new PolicyHandler(appId, deviceConfiguration,
926 flowObjectiveService,
927 tunnelHandler, policyStore);
928
Charles Chan4636be02015-10-07 14:21:45 -0700929 for (Device device : deviceService.getDevices()) {
Charles Chan2199c302016-04-23 17:36:10 -0700930 processDeviceAddedInternal(device.id());
Charles Chan4636be02015-10-07 14:21:45 -0700931 }
932
933 defaultRoutingHandler.startPopulationProcess();
Charles Chan2199c302016-04-23 17:36:10 -0700934 mcastHandler.init();
Charles Chan4636be02015-10-07 14:21:45 -0700935 }
936
Charles Chand6832882015-10-05 17:50:33 -0700937 @Override
938 public void event(NetworkConfigEvent event) {
Charles Chan5270ed02016-01-30 23:22:37 -0800939 // TODO move this part to NetworkConfigEventHandler
940 if (event.configClass().equals(SegmentRoutingDeviceConfig.class)) {
941 switch (event.type()) {
942 case CONFIG_ADDED:
943 log.info("Segment Routing Config added.");
944 configureNetwork();
945 break;
946 case CONFIG_UPDATED:
947 log.info("Segment Routing Config updated.");
948 // TODO support dynamic configuration
949 break;
950 default:
951 break;
Charles Chanb8e10c82015-10-14 11:24:40 -0700952 }
Charles Chan5270ed02016-01-30 23:22:37 -0800953 } else if (event.configClass().equals(SegmentRoutingAppConfig.class)) {
Charles Chanfc5c7802016-05-17 13:13:55 -0700954 checkState(appCfgHandler != null, "NetworkConfigEventHandler is not initialized");
Charles Chan5270ed02016-01-30 23:22:37 -0800955 switch (event.type()) {
956 case CONFIG_ADDED:
Charles Chanfc5c7802016-05-17 13:13:55 -0700957 appCfgHandler.processAppConfigAdded(event);
Charles Chan5270ed02016-01-30 23:22:37 -0800958 break;
959 case CONFIG_UPDATED:
Charles Chanfc5c7802016-05-17 13:13:55 -0700960 appCfgHandler.processAppConfigUpdated(event);
Charles Chan5270ed02016-01-30 23:22:37 -0800961 break;
962 case CONFIG_REMOVED:
Charles Chanfc5c7802016-05-17 13:13:55 -0700963 appCfgHandler.processAppConfigRemoved(event);
964 break;
965 default:
966 break;
967 }
968 } else if (event.configClass().equals(XConnectConfig.class)) {
969 checkState(xConnectHandler != null, "XConnectHandler is not initialized");
970 switch (event.type()) {
971 case CONFIG_ADDED:
972 xConnectHandler.processXConnectConfigAdded(event);
973 break;
974 case CONFIG_UPDATED:
975 xConnectHandler.processXConnectConfigUpdated(event);
976 break;
977 case CONFIG_REMOVED:
978 xConnectHandler.processXConnectConfigRemoved(event);
Charles Chan5270ed02016-01-30 23:22:37 -0800979 break;
980 default:
981 break;
Charles Chanb8e10c82015-10-14 11:24:40 -0700982 }
Charles Chand6832882015-10-05 17:50:33 -0700983 }
984 }
985 }
Charles Chan68aa62d2015-11-09 16:37:23 -0800986
987 private class InternalHostListener implements HostListener {
Charles Chan68aa62d2015-11-09 16:37:23 -0800988 @Override
989 public void event(HostEvent event) {
990 // Do not proceed without mastership
991 DeviceId deviceId = event.subject().location().deviceId();
992 if (!mastershipService.isLocalMaster(deviceId)) {
993 return;
994 }
995
996 switch (event.type()) {
997 case HOST_ADDED:
Charles Chand2990362016-04-18 13:44:03 -0700998 hostHandler.processHostAddedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -0800999 break;
1000 case HOST_MOVED:
Charles Chand2990362016-04-18 13:44:03 -07001001 hostHandler.processHostMovedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -08001002 break;
1003 case HOST_REMOVED:
Charles Chand2990362016-04-18 13:44:03 -07001004 hostHandler.processHostRemoveEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -08001005 break;
1006 case HOST_UPDATED:
Charles Chand2990362016-04-18 13:44:03 -07001007 hostHandler.processHostUpdatedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -08001008 break;
1009 default:
1010 log.warn("Unsupported host event type: {}", event.type());
1011 break;
1012 }
1013 }
1014 }
1015
Charles Chand55e84d2016-03-30 17:54:24 -07001016 private class InternalMcastListener implements McastListener {
1017 @Override
1018 public void event(McastEvent event) {
1019 switch (event.type()) {
1020 case SOURCE_ADDED:
Charles Chand2990362016-04-18 13:44:03 -07001021 mcastHandler.processSourceAdded(event);
Charles Chand55e84d2016-03-30 17:54:24 -07001022 break;
1023 case SINK_ADDED:
Charles Chand2990362016-04-18 13:44:03 -07001024 mcastHandler.processSinkAdded(event);
Charles Chand55e84d2016-03-30 17:54:24 -07001025 break;
1026 case SINK_REMOVED:
Charles Chand2990362016-04-18 13:44:03 -07001027 mcastHandler.processSinkRemoved(event);
Charles Chand55e84d2016-03-30 17:54:24 -07001028 break;
1029 case ROUTE_ADDED:
1030 case ROUTE_REMOVED:
1031 default:
1032 break;
1033 }
1034 }
1035 }
Charles Chan35fd1a72016-06-13 18:54:31 -07001036
1037 private class InternalCordConfigListener implements CordConfigListener {
1038 @Override
1039 public void event(CordConfigEvent event) {
1040 switch (event.type()) {
1041 case ACCESS_AGENT_ADDED:
1042 cordConfigHandler.processAccessAgentAddedEvent(event);
1043 break;
1044 case ACCESS_AGENT_UPDATED:
1045 cordConfigHandler.processAccessAgentUpdatedEvent(event);
1046 break;
1047 case ACCESS_AGENT_REMOVED:
1048 cordConfigHandler.processAccessAgentRemovedEvent(event);
1049 break;
1050 case ACCESS_DEVICE_ADDED:
1051 case ACCESS_DEVICE_UPDATED:
1052 case ACCESS_DEVICE_REMOVED:
1053 default:
1054 break;
1055 }
1056 }
1057 }
sanghob35a6192015-04-01 13:05:26 -07001058}