blob: 84c5190a45a1dcd142312c131bdb699a98a32332 [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 Chan2df0e8a2017-01-09 11:45:08 -0800354 /* Request ARP packet-in.
355 * Copy flag set to true since in cross-connect case we still want to
356 * forward ARP packet to the flood group.
357 */
Charles Chan188ebf52015-12-23 00:15:11 -0800358 TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
359 selector.matchEthType(Ethernet.TYPE_ARP);
Charles Chan2df0e8a2017-01-09 11:45:08 -0800360 packetService.requestPackets(selector.build(), PacketPriority.CONTROL, appId, true);
Charles Chan188ebf52015-12-23 00:15:11 -0800361
Charles Chanb8e10c82015-10-14 11:24:40 -0700362 cfgListener.configureNetwork();
363
sanghob35a6192015-04-01 13:05:26 -0700364 log.info("Started");
365 }
366
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700367 private KryoNamespace.Builder createSerializer() {
368 return new KryoNamespace.Builder()
369 .register(KryoNamespaces.API)
370 .register(NeighborSetNextObjectiveStoreKey.class,
371 SubnetNextObjectiveStoreKey.class,
372 SubnetAssignedVidStoreKey.class,
373 NeighborSet.class,
374 Tunnel.class,
375 DefaultTunnel.class,
376 Policy.class,
377 TunnelPolicy.class,
378 Policy.Type.class,
379 PortNextObjectiveStoreKey.class,
Charles Chanfc5c7802016-05-17 13:13:55 -0700380 XConnectStoreKey.class
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700381 );
382 }
383
sanghob35a6192015-04-01 13:05:26 -0700384 @Deactivate
385 protected void deactivate() {
Charles Chand6832882015-10-05 17:50:33 -0700386 cfgService.removeListener(cfgListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700387 cfgService.unregisterConfigFactory(deviceConfigFactory);
388 cfgService.unregisterConfigFactory(appConfigFactory);
389 cfgService.unregisterConfigFactory(mcastConfigFactory);
Charles Chand6832882015-10-05 17:50:33 -0700390
Charles Chan188ebf52015-12-23 00:15:11 -0800391 // Withdraw ARP packet-in
392 TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
393 selector.matchEthType(Ethernet.TYPE_ARP);
394 packetService.cancelPackets(selector.build(), PacketPriority.CONTROL, appId, Optional.empty());
395
sanghob35a6192015-04-01 13:05:26 -0700396 packetService.removeProcessor(processor);
Charles Chanb8e10c82015-10-14 11:24:40 -0700397 linkService.removeListener(linkListener);
398 deviceService.removeListener(deviceListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700399 multicastRouteService.removeListener(mcastListener);
Charles Chan35fd1a72016-06-13 18:54:31 -0700400 cordConfigService.removeListener(cordConfigListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700401
sanghob35a6192015-04-01 13:05:26 -0700402 processor = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700403 linkListener = null;
Charles Chand55e84d2016-03-30 17:54:24 -0700404 deviceListener = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700405 groupHandlerMap.clear();
406
Charles Chand55e84d2016-03-30 17:54:24 -0700407 nsNextObjStore.destroy();
408 subnetNextObjStore.destroy();
409 portNextObjStore.destroy();
Charles Chand55e84d2016-03-30 17:54:24 -0700410 tunnelStore.destroy();
411 policyStore.destroy();
412 subnetVidStore.destroy();
sanghob35a6192015-04-01 13:05:26 -0700413 log.info("Stopped");
414 }
415
sangho1e575652015-05-14 00:39:53 -0700416 @Override
417 public List<Tunnel> getTunnels() {
418 return tunnelHandler.getTunnels();
419 }
420
421 @Override
sangho71abe1b2015-06-29 14:58:47 -0700422 public TunnelHandler.Result createTunnel(Tunnel tunnel) {
423 return tunnelHandler.createTunnel(tunnel);
sangho1e575652015-05-14 00:39:53 -0700424 }
425
426 @Override
sangho71abe1b2015-06-29 14:58:47 -0700427 public TunnelHandler.Result removeTunnel(Tunnel tunnel) {
sangho1e575652015-05-14 00:39:53 -0700428 for (Policy policy: policyHandler.getPolicies()) {
429 if (policy.type() == Policy.Type.TUNNEL_FLOW) {
430 TunnelPolicy tunnelPolicy = (TunnelPolicy) policy;
431 if (tunnelPolicy.tunnelId().equals(tunnel.id())) {
432 log.warn("Cannot remove the tunnel used by a policy");
sangho71abe1b2015-06-29 14:58:47 -0700433 return TunnelHandler.Result.TUNNEL_IN_USE;
sangho1e575652015-05-14 00:39:53 -0700434 }
435 }
436 }
sangho71abe1b2015-06-29 14:58:47 -0700437 return tunnelHandler.removeTunnel(tunnel);
sangho1e575652015-05-14 00:39:53 -0700438 }
439
440 @Override
sangho71abe1b2015-06-29 14:58:47 -0700441 public PolicyHandler.Result removePolicy(Policy policy) {
442 return policyHandler.removePolicy(policy);
sangho1e575652015-05-14 00:39:53 -0700443 }
444
445 @Override
sangho71abe1b2015-06-29 14:58:47 -0700446 public PolicyHandler.Result createPolicy(Policy policy) {
447 return policyHandler.createPolicy(policy);
sangho1e575652015-05-14 00:39:53 -0700448 }
449
450 @Override
451 public List<Policy> getPolicies() {
452 return policyHandler.getPolicies();
453 }
454
Saurav Das59232cf2016-04-27 18:35:50 -0700455 @Override
456 public void rerouteNetwork() {
457 cfgListener.configureNetwork();
458 for (Device device : deviceService.getDevices()) {
459 defaultRoutingHandler.populatePortAddressingRules(device.id());
460 }
461 defaultRoutingHandler.startPopulationProcess();
462 }
463
Charles Chanc81c45b2016-10-20 17:02:44 -0700464 @Override
465 public Map<DeviceId, Set<Ip4Prefix>> getDeviceSubnetMap() {
466 Map<DeviceId, Set<Ip4Prefix>> deviceSubnetMap = Maps.newHashMap();
467 deviceService.getAvailableDevices().forEach(device -> {
468 deviceSubnetMap.put(device.id(), deviceConfiguration.getSubnets(device.id()));
469 });
470 return deviceSubnetMap;
471 }
472
sanghof9d0bf12015-05-19 11:57:42 -0700473 /**
Pier Ventre98161782016-10-31 15:00:01 -0700474 * Returns the MPLS-ECMP configuration.
475 *
476 * @return MPLS-ECMP value
477 */
478 public boolean getMplsEcmp() {
479 SegmentRoutingAppConfig segmentRoutingAppConfig = cfgService
480 .getConfig(this.appId, SegmentRoutingAppConfig.class);
481 return segmentRoutingAppConfig != null && segmentRoutingAppConfig.mplsEcmp();
482 }
483
484 /**
sanghof9d0bf12015-05-19 11:57:42 -0700485 * Returns the tunnel object with the tunnel ID.
486 *
487 * @param tunnelId Tunnel ID
488 * @return Tunnel reference
489 */
sangho1e575652015-05-14 00:39:53 -0700490 public Tunnel getTunnel(String tunnelId) {
491 return tunnelHandler.getTunnel(tunnelId);
492 }
493
sanghob35a6192015-04-01 13:05:26 -0700494 /**
Saurav Das0e99e2b2015-10-28 12:39:42 -0700495 * Returns the vlan-id assigned to the subnet configured for a device.
496 * If no vlan-id has been assigned, a new one is assigned out of a pool of ids,
497 * if and only if this controller instance is the master for the device.
498 * <p>
499 * USAGE: The assigned vlans are meant to be applied to untagged packets on those
500 * switches/pipelines that need this functionality. These vids are meant
501 * to be used internally within a switch, and thus need to be unique only
502 * on a switch level. Note that packets never go out on the wire with these
503 * vlans. Currently, vlan ids are assigned from value 4093 down.
504 * Vlan id 4094 expected to be used for all ports that are not assigned subnets.
505 * Vlan id 4095 is reserved and unused. Only a single vlan id is assigned
506 * per subnet.
sanghob35a6192015-04-01 13:05:26 -0700507 *
Saurav Das0e99e2b2015-10-28 12:39:42 -0700508 * @param deviceId switch dpid
509 * @param subnet IPv4 prefix for which assigned vlan is desired
510 * @return VlanId assigned for the subnet on the device, or
511 * null if no vlan assignment was found and this instance is not
512 * the master for the device.
sanghob35a6192015-04-01 13:05:26 -0700513 */
Charles Chane849c192016-01-11 18:28:54 -0800514 // TODO: We should avoid assigning VLAN IDs that are used by VLAN cross-connection.
Saurav Das0e99e2b2015-10-28 12:39:42 -0700515 public VlanId getSubnetAssignedVlanId(DeviceId deviceId, Ip4Prefix subnet) {
516 VlanId assignedVid = subnetVidStore.get(new SubnetAssignedVidStoreKey(
517 deviceId, subnet));
518 if (assignedVid != null) {
519 log.debug("Query for subnet:{} on device:{} returned assigned-vlan "
520 + "{}", subnet, deviceId, assignedVid);
521 return assignedVid;
522 }
523 //check mastership for the right to assign a vlan
524 if (!mastershipService.isLocalMaster(deviceId)) {
525 log.warn("This controller instance is not the master for device {}. "
526 + "Cannot assign vlan-id for subnet {}", deviceId, subnet);
527 return null;
528 }
529 // vlan assignment is expensive but done only once
Charles Chan9f676b62015-10-29 14:58:10 -0700530 Set<Ip4Prefix> configuredSubnets = deviceConfiguration.getSubnets(deviceId);
Saurav Das0e99e2b2015-10-28 12:39:42 -0700531 Set<Short> assignedVlans = new HashSet<>();
532 Set<Ip4Prefix> unassignedSubnets = new HashSet<>();
533 for (Ip4Prefix sub : configuredSubnets) {
534 VlanId v = subnetVidStore.get(new SubnetAssignedVidStoreKey(deviceId,
535 sub));
536 if (v != null) {
537 assignedVlans.add(v.toShort());
538 } else {
539 unassignedSubnets.add(sub);
540 }
541 }
542 short nextAssignedVlan = ASSIGNED_VLAN_START;
543 if (!assignedVlans.isEmpty()) {
544 nextAssignedVlan = (short) (Collections.min(assignedVlans) - 1);
545 }
546 for (Ip4Prefix unsub : unassignedSubnets) {
Charles Chan5270ed02016-01-30 23:22:37 -0800547 // Special case for default route. Assign default VLAN ID to /32 and /0 subnets
548 if (unsub.prefixLength() == IpPrefix.MAX_INET_MASK_LENGTH ||
549 unsub.prefixLength() == 0) {
550 subnetVidStore.put(new SubnetAssignedVidStoreKey(deviceId, unsub),
551 VlanId.vlanId(ASSIGNED_VLAN_NO_SUBNET));
552 } else {
553 subnetVidStore.put(new SubnetAssignedVidStoreKey(deviceId, unsub),
554 VlanId.vlanId(nextAssignedVlan--));
555 log.info("Assigned vlan: {} to subnet: {} on device: {}",
556 nextAssignedVlan + 1, unsub, deviceId);
557 }
sanghob35a6192015-04-01 13:05:26 -0700558 }
559
Saurav Das0e99e2b2015-10-28 12:39:42 -0700560 return subnetVidStore.get(new SubnetAssignedVidStoreKey(deviceId, subnet));
sanghob35a6192015-04-01 13:05:26 -0700561 }
562
sangho1e575652015-05-14 00:39:53 -0700563 /**
Saurav Das0e99e2b2015-10-28 12:39:42 -0700564 * Returns the next objective ID for the given NeighborSet.
Saurav Das8a0732e2015-11-20 15:27:53 -0800565 * If the nextObjective does not exist, a new one is created and
Saurav Das4ce45962015-11-24 23:21:05 -0800566 * its id is returned.
sangho1e575652015-05-14 00:39:53 -0700567 *
sanghof9d0bf12015-05-19 11:57:42 -0700568 * @param deviceId Device ID
569 * @param ns NegighborSet
Saurav Das8a0732e2015-11-20 15:27:53 -0800570 * @param meta metadata passed into the creation of a Next Objective
571 * @return next objective ID or -1 if an error was encountered during the
572 * creation of the nextObjective
sangho1e575652015-05-14 00:39:53 -0700573 */
Saurav Das8a0732e2015-11-20 15:27:53 -0800574 public int getNextObjectiveId(DeviceId deviceId, NeighborSet ns,
575 TrafficSelector meta) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700576 if (groupHandlerMap.get(deviceId) != null) {
577 log.trace("getNextObjectiveId query in device {}", deviceId);
578 return groupHandlerMap
Saurav Das8a0732e2015-11-20 15:27:53 -0800579 .get(deviceId).getNextObjectiveId(ns, meta);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700580 } else {
Saurav Das4ce45962015-11-24 23:21:05 -0800581 log.warn("getNextObjectiveId query - groupHandler for device {} "
582 + "not found", deviceId);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700583 return -1;
584 }
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700585 }
586
Charles Chanc42e84e2015-10-20 16:24:19 -0700587 /**
Saurav Das4ce45962015-11-24 23:21:05 -0800588 * Returns the next objective ID for the given subnet prefix. It is expected
589 * that the next-objective has been pre-created from configuration.
Charles Chanc42e84e2015-10-20 16:24:19 -0700590 *
591 * @param deviceId Device ID
592 * @param prefix Subnet
Saurav Das4ce45962015-11-24 23:21:05 -0800593 * @return next objective ID or -1 if it was not found
Charles Chanc42e84e2015-10-20 16:24:19 -0700594 */
595 public int getSubnetNextObjectiveId(DeviceId deviceId, IpPrefix prefix) {
596 if (groupHandlerMap.get(deviceId) != null) {
597 log.trace("getSubnetNextObjectiveId query in device {}", deviceId);
598 return groupHandlerMap
599 .get(deviceId).getSubnetNextObjectiveId(prefix);
600 } else {
Saurav Das4ce45962015-11-24 23:21:05 -0800601 log.warn("getSubnetNextObjectiveId query - groupHandler for "
602 + "device {} not found", deviceId);
603 return -1;
604 }
605 }
606
607 /**
608 * Returns the next objective ID for the given portNumber, given the treatment.
609 * There could be multiple different treatments to the same outport, which
610 * would result in different objectives. If the next object
611 * does not exist, a new one is created and its id is returned.
612 *
613 * @param deviceId Device ID
614 * @param portNum port number on device for which NextObjective is queried
615 * @param treatment the actions to apply on the packets (should include outport)
616 * @param meta metadata passed into the creation of a Next Objective if necessary
Saurav Das59232cf2016-04-27 18:35:50 -0700617 * @return next objective ID or -1 if an error occurred during retrieval or creation
Saurav Das4ce45962015-11-24 23:21:05 -0800618 */
619 public int getPortNextObjectiveId(DeviceId deviceId, PortNumber portNum,
620 TrafficTreatment treatment,
621 TrafficSelector meta) {
622 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
623 if (ghdlr != null) {
624 return ghdlr.getPortNextObjectiveId(portNum, treatment, meta);
625 } else {
Charles Chane849c192016-01-11 18:28:54 -0800626 log.warn("getPortNextObjectiveId query - groupHandler for device {}"
627 + " not found", deviceId);
628 return -1;
629 }
630 }
631
sanghob35a6192015-04-01 13:05:26 -0700632 private class InternalPacketProcessor implements PacketProcessor {
sanghob35a6192015-04-01 13:05:26 -0700633 @Override
634 public void process(PacketContext context) {
635
636 if (context.isHandled()) {
637 return;
638 }
639
640 InboundPacket pkt = context.inPacket();
641 Ethernet ethernet = pkt.parsed();
Saurav Das4ce45962015-11-24 23:21:05 -0800642 log.trace("Rcvd pktin: {}", ethernet);
sanghob35a6192015-04-01 13:05:26 -0700643 if (ethernet.getEtherType() == Ethernet.TYPE_ARP) {
644 arpHandler.processPacketIn(pkt);
645 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV4) {
646 IPv4 ipPacket = (IPv4) ethernet.getPayload();
647 ipHandler.addToPacketBuffer(ipPacket);
648 if (ipPacket.getProtocol() == IPv4.PROTOCOL_ICMP) {
649 icmpHandler.processPacketIn(pkt);
650 } else {
651 ipHandler.processPacketIn(pkt);
652 }
653 }
654 }
655 }
656
657 private class InternalLinkListener implements LinkListener {
658 @Override
659 public void event(LinkEvent event) {
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700660 if (event.type() == LinkEvent.Type.LINK_ADDED
661 || event.type() == LinkEvent.Type.LINK_REMOVED) {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700662 log.debug("Event {} received from Link Service", event.type());
sanghob35a6192015-04-01 13:05:26 -0700663 scheduleEventHandlerIfNotScheduled(event);
664 }
665 }
666 }
667
668 private class InternalDeviceListener implements DeviceListener {
sanghob35a6192015-04-01 13:05:26 -0700669 @Override
670 public void event(DeviceEvent event) {
sanghob35a6192015-04-01 13:05:26 -0700671 switch (event.type()) {
672 case DEVICE_ADDED:
Saurav Das1a129a02016-11-18 15:21:57 -0800673 case PORT_UPDATED:
674 case PORT_ADDED:
sangho20eff1d2015-04-13 15:15:58 -0700675 case DEVICE_UPDATED:
676 case DEVICE_AVAILABILITY_CHANGED:
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700677 log.debug("Event {} received from Device Service", event.type());
sanghob35a6192015-04-01 13:05:26 -0700678 scheduleEventHandlerIfNotScheduled(event);
679 break;
680 default:
681 }
682 }
683 }
684
Saurav Das4ce45962015-11-24 23:21:05 -0800685 @SuppressWarnings("rawtypes")
sanghob35a6192015-04-01 13:05:26 -0700686 private void scheduleEventHandlerIfNotScheduled(Event event) {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700687 synchronized (threadSchedulerLock) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700688 eventQueue.add(event);
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700689 numOfEventsQueued++;
690
691 if ((numOfHandlerScheduled - numOfHandlerExecution) == 0) {
692 //No pending scheduled event handling threads. So start a new one.
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700693 eventHandlerFuture = executorService
694 .schedule(eventHandler, 100, TimeUnit.MILLISECONDS);
695 numOfHandlerScheduled++;
696 }
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700697 log.trace("numOfEventsQueued {}, numOfEventHandlerScheduled {}",
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700698 numOfEventsQueued,
699 numOfHandlerScheduled);
sanghob35a6192015-04-01 13:05:26 -0700700 }
sanghob35a6192015-04-01 13:05:26 -0700701 }
702
703 private class InternalEventHandler implements Runnable {
Srikanth Vavilapalli4db76e32015-04-07 15:12:32 -0700704 @Override
sanghob35a6192015-04-01 13:05:26 -0700705 public void run() {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700706 try {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700707 while (true) {
Saurav Das4ce45962015-11-24 23:21:05 -0800708 @SuppressWarnings("rawtypes")
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700709 Event event = null;
710 synchronized (threadSchedulerLock) {
711 if (!eventQueue.isEmpty()) {
712 event = eventQueue.poll();
713 numOfEventsExecuted++;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700714 } else {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700715 numOfHandlerExecution++;
716 log.debug("numOfHandlerExecution {} numOfEventsExecuted {}",
717 numOfHandlerExecution, numOfEventsExecuted);
718 break;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700719 }
sangho20eff1d2015-04-13 15:15:58 -0700720 }
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700721 if (event.type() == LinkEvent.Type.LINK_ADDED) {
722 processLinkAdded((Link) event.subject());
723 } else if (event.type() == LinkEvent.Type.LINK_REMOVED) {
Pier Ventre2c515312016-09-13 21:33:40 -0700724 Link linkRemoved = (Link) event.subject();
725 if (linkRemoved.src().elementId() instanceof DeviceId &&
726 !deviceService.isAvailable(linkRemoved.src().deviceId())) {
727 continue;
728 }
729 if (linkRemoved.dst().elementId() instanceof DeviceId &&
730 !deviceService.isAvailable(linkRemoved.dst().deviceId())) {
731 continue;
732 }
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700733 processLinkRemoved((Link) event.subject());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700734 } else if (event.type() == DeviceEvent.Type.DEVICE_ADDED ||
735 event.type() == DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED ||
736 event.type() == DeviceEvent.Type.DEVICE_UPDATED) {
Saurav Das423fe2b2015-12-04 10:52:59 -0800737 DeviceId deviceId = ((Device) event.subject()).id();
738 if (deviceService.isAvailable(deviceId)) {
Saurav Das837e0bb2015-10-30 17:45:38 -0700739 log.info("Processing device event {} for available device {}",
740 event.type(), ((Device) event.subject()).id());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700741 processDeviceAdded((Device) event.subject());
Saurav Das80980c72016-03-23 11:22:49 -0700742 } else {
743 log.info("Processing device event {} for unavailable device {}",
744 event.type(), ((Device) event.subject()).id());
745 processDeviceRemoved((Device) event.subject());
746 }
Saurav Das1a129a02016-11-18 15:21:57 -0800747 } else if (event.type() == DeviceEvent.Type.PORT_ADDED) {
Saurav Dasd2fded02016-12-02 15:43:47 -0800748 // typically these calls come when device is added first time
749 // so port filtering rules are handled at the device_added event.
750 // port added calls represent all ports on the device,
751 // enabled or not.
Saurav Das1a129a02016-11-18 15:21:57 -0800752 log.debug("** PORT ADDED {}/{} -> {}",
Saurav Dasd2fded02016-12-02 15:43:47 -0800753 ((DeviceEvent) event).subject().id(),
754 ((DeviceEvent) event).port().number(),
755 event.type());
Saurav Das1a129a02016-11-18 15:21:57 -0800756 } else if (event.type() == DeviceEvent.Type.PORT_UPDATED) {
Saurav Dasd2fded02016-12-02 15:43:47 -0800757 // these calls happen for every subsequent event
758 // ports enabled, disabled, switch goes away, comes back
Saurav Das1a129a02016-11-18 15:21:57 -0800759 log.info("** PORT UPDATED {}/{} -> {}",
760 event.subject(),
761 ((DeviceEvent) event).port(),
762 event.type());
763 processPortUpdated(((Device) event.subject()),
764 ((DeviceEvent) event).port());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700765 } else {
766 log.warn("Unhandled event type: {}", event.type());
767 }
sanghob35a6192015-04-01 13:05:26 -0700768 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700769 } catch (Exception e) {
770 log.error("SegmentRouting event handler "
771 + "thread thrown an exception: {}", e);
sanghob35a6192015-04-01 13:05:26 -0700772 }
sanghob35a6192015-04-01 13:05:26 -0700773 }
774 }
775
sanghob35a6192015-04-01 13:05:26 -0700776 private void processLinkAdded(Link link) {
Saurav Dasb5c236e2016-06-07 10:08:06 -0700777 log.info("** LINK ADDED {}", link.toString());
Charles Chan0b4e6182015-11-03 10:42:14 -0800778 if (!deviceConfiguration.isConfigured(link.src().deviceId())) {
779 log.warn("Source device of this link is not configured.");
780 return;
781 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700782 //Irrespective whether the local is a MASTER or not for this device,
783 //create group handler instance and push default TTP flow rules.
784 //Because in a multi-instance setup, instances can initiate
785 //groups for any devices. Also the default TTP rules are needed
786 //to be pushed before inserting any IP table entries for any device
787 DefaultGroupHandler groupHandler = groupHandlerMap.get(link.src()
788 .deviceId());
789 if (groupHandler != null) {
Saurav Das8a0732e2015-11-20 15:27:53 -0800790 groupHandler.linkUp(link, mastershipService.isLocalMaster(
791 link.src().deviceId()));
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700792 } else {
793 Device device = deviceService.getDevice(link.src().deviceId());
794 if (device != null) {
795 log.warn("processLinkAdded: Link Added "
796 + "Notification without Device Added "
797 + "event, still handling it");
798 processDeviceAdded(device);
799 groupHandler = groupHandlerMap.get(link.src()
800 .deviceId());
Saurav Das8a0732e2015-11-20 15:27:53 -0800801 groupHandler.linkUp(link, mastershipService.isLocalMaster(device.id()));
sanghob35a6192015-04-01 13:05:26 -0700802 }
803 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700804
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700805 log.trace("Starting optimized route population process");
806 defaultRoutingHandler.populateRoutingRulesForLinkStatusChange(null);
807 //log.trace("processLinkAdded: re-starting route population process");
808 //defaultRoutingHandler.startPopulationProcess();
Charles Chan2199c302016-04-23 17:36:10 -0700809
810 mcastHandler.init();
sanghob35a6192015-04-01 13:05:26 -0700811 }
812
813 private void processLinkRemoved(Link link) {
Saurav Dasb5c236e2016-06-07 10:08:06 -0700814 log.info("** LINK REMOVED {}", link.toString());
sangho834e4b02015-05-01 09:38:25 -0700815 DefaultGroupHandler groupHandler = groupHandlerMap.get(link.src().deviceId());
816 if (groupHandler != null) {
Saurav Das423fe2b2015-12-04 10:52:59 -0800817 groupHandler.portDown(link.src().port(),
818 mastershipService.isLocalMaster(link.src().deviceId()));
sangho834e4b02015-05-01 09:38:25 -0700819 }
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700820 log.trace("Starting optimized route population process");
821 defaultRoutingHandler.populateRoutingRulesForLinkStatusChange(link);
822 //log.trace("processLinkRemoved: re-starting route population process");
823 //defaultRoutingHandler.startPopulationProcess();
Charles Chan2199c302016-04-23 17:36:10 -0700824
825 mcastHandler.processLinkDown(link);
sanghob35a6192015-04-01 13:05:26 -0700826 }
827
828 private void processDeviceAdded(Device device) {
Saurav Dasb5c236e2016-06-07 10:08:06 -0700829 log.info("** DEVICE ADDED with ID {}", device.id());
Charles Chan0b4e6182015-11-03 10:42:14 -0800830 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
Saurav Das2857f382015-11-03 14:39:27 -0800831 log.warn("Device configuration uploading. Device {} will be "
832 + "processed after config completes.", device.id());
833 return;
834 }
Charles Chan2199c302016-04-23 17:36:10 -0700835 processDeviceAddedInternal(device.id());
836 }
837
838 private void processDeviceAddedInternal(DeviceId deviceId) {
Saurav Das837e0bb2015-10-30 17:45:38 -0700839 // Irrespective of whether the local is a MASTER or not for this device,
840 // we need to create a SR-group-handler instance. This is because in a
841 // multi-instance setup, any instance can initiate forwarding/next-objectives
842 // for any switch (even if this instance is a SLAVE or not even connected
843 // to the switch). To handle this, a default-group-handler instance is necessary
844 // per switch.
Charles Chan2199c302016-04-23 17:36:10 -0700845 log.debug("Current groupHandlerMap devs: {}", groupHandlerMap.keySet());
846 if (groupHandlerMap.get(deviceId) == null) {
Charles Chan0b4e6182015-11-03 10:42:14 -0800847 DefaultGroupHandler groupHandler;
848 try {
849 groupHandler = DefaultGroupHandler.
Charles Chan2199c302016-04-23 17:36:10 -0700850 createGroupHandler(deviceId,
851 appId,
852 deviceConfiguration,
853 linkService,
854 flowObjectiveService,
855 this);
Charles Chan0b4e6182015-11-03 10:42:14 -0800856 } catch (DeviceConfigNotFoundException e) {
857 log.warn(e.getMessage() + " Aborting processDeviceAdded.");
858 return;
859 }
Charles Chan2199c302016-04-23 17:36:10 -0700860 log.debug("updating groupHandlerMap with new config for device: {}",
861 deviceId);
862 groupHandlerMap.put(deviceId, groupHandler);
Saurav Das2857f382015-11-03 14:39:27 -0800863 }
Saurav Dasb5c236e2016-06-07 10:08:06 -0700864 // Also, in some cases, drivers may need extra
865 // information to process rules (eg. Router IP/MAC); and so, we send
866 // port addressing rules to the driver as well irrespective of whether
867 // this instance is the master or not.
868 defaultRoutingHandler.populatePortAddressingRules(deviceId);
869
Charles Chan2199c302016-04-23 17:36:10 -0700870 if (mastershipService.isLocalMaster(deviceId)) {
871 hostHandler.readInitialHosts(deviceId);
Charles Chanfc5c7802016-05-17 13:13:55 -0700872 xConnectHandler.init(deviceId);
Charles Chan35fd1a72016-06-13 18:54:31 -0700873 cordConfigHandler.init(deviceId);
Charles Chan2199c302016-04-23 17:36:10 -0700874 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
Charles Chanc42e84e2015-10-20 16:24:19 -0700875 groupHandler.createGroupsFromSubnetConfig();
Charles Chan2199c302016-04-23 17:36:10 -0700876 routingRulePopulator.populateSubnetBroadcastRule(deviceId);
Charles Chanc42e84e2015-10-20 16:24:19 -0700877 }
Charles Chan5270ed02016-01-30 23:22:37 -0800878
Charles Chanfc5c7802016-05-17 13:13:55 -0700879 appCfgHandler.initVRouters(deviceId);
sanghob35a6192015-04-01 13:05:26 -0700880 }
881
Saurav Das80980c72016-03-23 11:22:49 -0700882 private void processDeviceRemoved(Device device) {
883 nsNextObjStore.entrySet().stream()
884 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
885 .forEach(entry -> {
886 nsNextObjStore.remove(entry.getKey());
887 });
Saurav Das80980c72016-03-23 11:22:49 -0700888 subnetNextObjStore.entrySet().stream()
889 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
890 .forEach(entry -> {
891 subnetNextObjStore.remove(entry.getKey());
892 });
Saurav Das80980c72016-03-23 11:22:49 -0700893 portNextObjStore.entrySet().stream()
894 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
895 .forEach(entry -> {
896 portNextObjStore.remove(entry.getKey());
897 });
Saurav Das80980c72016-03-23 11:22:49 -0700898 subnetVidStore.entrySet().stream()
899 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
900 .forEach(entry -> {
901 subnetVidStore.remove(entry.getKey());
902 });
Saurav Das80980c72016-03-23 11:22:49 -0700903 groupHandlerMap.remove(device.id());
Saurav Das80980c72016-03-23 11:22:49 -0700904 defaultRoutingHandler.purgeEcmpGraph(device.id());
Charles Chan2199c302016-04-23 17:36:10 -0700905 mcastHandler.removeDevice(device.id());
Charles Chanfc5c7802016-05-17 13:13:55 -0700906 xConnectHandler.removeDevice(device.id());
Saurav Das80980c72016-03-23 11:22:49 -0700907 }
908
Saurav Das1a129a02016-11-18 15:21:57 -0800909 private void processPortUpdated(Device device, Port port) {
910 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
911 log.warn("Device configuration uploading. Not handling port event for"
912 + "dev: {} port: {}", device.id(), port.number());
913 return;
914 }
915 /* XXX create method for single port filtering rules which are needed
916 for both switch-to-switch ports and edge ports
917 if (defaultRoutingHandler != null) {
918 defaultRoutingHandler.populatePortAddressingRules(
919 ((Device) event.subject()).id());
920 }*/
921
922 // portUpdated calls are for ports that have gone down or up. For switch
923 // to switch ports, link-events should take care of any re-routing or
924 // group editing necessary for port up/down. Here we only process edge ports
925 // that are already configured.
926 Ip4Prefix configuredSubnet = deviceConfiguration.getPortSubnet(device.id(),
927 port.number());
928 if (configuredSubnet == null) {
929 log.debug("Not handling port updated event for unconfigured port "
930 + "dev/port: {}/{}", device.id(), port.number());
931 return;
932 }
933 processEdgePort(device, port, configuredSubnet);
934 }
935
936 private void processEdgePort(Device device, Port port, Ip4Prefix subnet) {
937 boolean portUp = port.isEnabled();
938 if (portUp) {
939 log.info("Device:EdgePort {}:{} is enabled in subnet: {}", device.id(),
940 port.number(), subnet);
941 } else {
942 log.info("Device:EdgePort {}:{} is disabled in subnet: {}", device.id(),
943 port.number(), subnet);
944 }
945
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700946 DefaultGroupHandler groupHandler = groupHandlerMap.get(device.id());
sanghob35a6192015-04-01 13:05:26 -0700947 if (groupHandler != null) {
Saurav Das1a129a02016-11-18 15:21:57 -0800948 groupHandler.processEdgePort(port.number(), subnet, portUp,
Saurav Das423fe2b2015-12-04 10:52:59 -0800949 mastershipService.isLocalMaster(device.id()));
Saurav Das1a129a02016-11-18 15:21:57 -0800950 } else {
951 log.warn("Group handler not found for dev:{}. Not handling edge port"
952 + " {} event for port:{}", device.id(),
953 (portUp) ? "UP" : "DOWN", port.number());
sanghob35a6192015-04-01 13:05:26 -0700954 }
955 }
sangho1e575652015-05-14 00:39:53 -0700956
Charles Chand6832882015-10-05 17:50:33 -0700957 private class InternalConfigListener implements NetworkConfigListener {
Charles Chan2c15aca2016-11-09 20:51:44 -0800958 SegmentRoutingManager srManager;
Charles Chan4636be02015-10-07 14:21:45 -0700959
Charles Chane849c192016-01-11 18:28:54 -0800960 /**
961 * Constructs the internal network config listener.
962 *
Charles Chan2c15aca2016-11-09 20:51:44 -0800963 * @param srManager segment routing manager
Charles Chane849c192016-01-11 18:28:54 -0800964 */
Charles Chan2c15aca2016-11-09 20:51:44 -0800965 public InternalConfigListener(SegmentRoutingManager srManager) {
966 this.srManager = srManager;
Charles Chan4636be02015-10-07 14:21:45 -0700967 }
968
Charles Chane849c192016-01-11 18:28:54 -0800969 /**
970 * Reads network config and initializes related data structure accordingly.
971 */
Charles Chan4636be02015-10-07 14:21:45 -0700972 public void configureNetwork() {
Charles Chan2c15aca2016-11-09 20:51:44 -0800973 deviceConfiguration = new DeviceConfiguration(srManager);
Charles Chan4636be02015-10-07 14:21:45 -0700974
Charles Chan2c15aca2016-11-09 20:51:44 -0800975 arpHandler = new ArpHandler(srManager);
976 icmpHandler = new IcmpHandler(srManager);
977 ipHandler = new IpHandler(srManager);
978 routingRulePopulator = new RoutingRulePopulator(srManager);
979 defaultRoutingHandler = new DefaultRoutingHandler(srManager);
Charles Chan4636be02015-10-07 14:21:45 -0700980
981 tunnelHandler = new TunnelHandler(linkService, deviceConfiguration,
982 groupHandlerMap, tunnelStore);
983 policyHandler = new PolicyHandler(appId, deviceConfiguration,
984 flowObjectiveService,
985 tunnelHandler, policyStore);
986
Charles Chan4636be02015-10-07 14:21:45 -0700987 for (Device device : deviceService.getDevices()) {
Charles Chan2199c302016-04-23 17:36:10 -0700988 processDeviceAddedInternal(device.id());
Charles Chan4636be02015-10-07 14:21:45 -0700989 }
990
991 defaultRoutingHandler.startPopulationProcess();
Charles Chan2199c302016-04-23 17:36:10 -0700992 mcastHandler.init();
Charles Chan4636be02015-10-07 14:21:45 -0700993 }
994
Charles Chand6832882015-10-05 17:50:33 -0700995 @Override
996 public void event(NetworkConfigEvent event) {
Charles Chan5270ed02016-01-30 23:22:37 -0800997 // TODO move this part to NetworkConfigEventHandler
998 if (event.configClass().equals(SegmentRoutingDeviceConfig.class)) {
999 switch (event.type()) {
1000 case CONFIG_ADDED:
1001 log.info("Segment Routing Config added.");
1002 configureNetwork();
1003 break;
1004 case CONFIG_UPDATED:
1005 log.info("Segment Routing Config updated.");
1006 // TODO support dynamic configuration
1007 break;
1008 default:
1009 break;
Charles Chanb8e10c82015-10-14 11:24:40 -07001010 }
Charles Chan5270ed02016-01-30 23:22:37 -08001011 } else if (event.configClass().equals(SegmentRoutingAppConfig.class)) {
Charles Chanfc5c7802016-05-17 13:13:55 -07001012 checkState(appCfgHandler != null, "NetworkConfigEventHandler is not initialized");
Charles Chan5270ed02016-01-30 23:22:37 -08001013 switch (event.type()) {
1014 case CONFIG_ADDED:
Charles Chanfc5c7802016-05-17 13:13:55 -07001015 appCfgHandler.processAppConfigAdded(event);
Charles Chan5270ed02016-01-30 23:22:37 -08001016 break;
1017 case CONFIG_UPDATED:
Charles Chanfc5c7802016-05-17 13:13:55 -07001018 appCfgHandler.processAppConfigUpdated(event);
Charles Chan5270ed02016-01-30 23:22:37 -08001019 break;
1020 case CONFIG_REMOVED:
Charles Chanfc5c7802016-05-17 13:13:55 -07001021 appCfgHandler.processAppConfigRemoved(event);
1022 break;
1023 default:
1024 break;
1025 }
1026 } else if (event.configClass().equals(XConnectConfig.class)) {
1027 checkState(xConnectHandler != null, "XConnectHandler is not initialized");
1028 switch (event.type()) {
1029 case CONFIG_ADDED:
1030 xConnectHandler.processXConnectConfigAdded(event);
1031 break;
1032 case CONFIG_UPDATED:
1033 xConnectHandler.processXConnectConfigUpdated(event);
1034 break;
1035 case CONFIG_REMOVED:
1036 xConnectHandler.processXConnectConfigRemoved(event);
Charles Chan5270ed02016-01-30 23:22:37 -08001037 break;
1038 default:
1039 break;
Charles Chanb8e10c82015-10-14 11:24:40 -07001040 }
Charles Chand6832882015-10-05 17:50:33 -07001041 }
1042 }
1043 }
Charles Chan68aa62d2015-11-09 16:37:23 -08001044
1045 private class InternalHostListener implements HostListener {
Charles Chan68aa62d2015-11-09 16:37:23 -08001046 @Override
1047 public void event(HostEvent event) {
1048 // Do not proceed without mastership
1049 DeviceId deviceId = event.subject().location().deviceId();
1050 if (!mastershipService.isLocalMaster(deviceId)) {
1051 return;
1052 }
1053
1054 switch (event.type()) {
1055 case HOST_ADDED:
Charles Chand2990362016-04-18 13:44:03 -07001056 hostHandler.processHostAddedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -08001057 break;
1058 case HOST_MOVED:
Charles Chand2990362016-04-18 13:44:03 -07001059 hostHandler.processHostMovedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -08001060 break;
1061 case HOST_REMOVED:
Charles Chand2990362016-04-18 13:44:03 -07001062 hostHandler.processHostRemoveEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -08001063 break;
1064 case HOST_UPDATED:
Charles Chand2990362016-04-18 13:44:03 -07001065 hostHandler.processHostUpdatedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -08001066 break;
1067 default:
1068 log.warn("Unsupported host event type: {}", event.type());
1069 break;
1070 }
1071 }
1072 }
1073
Charles Chand55e84d2016-03-30 17:54:24 -07001074 private class InternalMcastListener implements McastListener {
1075 @Override
1076 public void event(McastEvent event) {
1077 switch (event.type()) {
1078 case SOURCE_ADDED:
Charles Chand2990362016-04-18 13:44:03 -07001079 mcastHandler.processSourceAdded(event);
Charles Chand55e84d2016-03-30 17:54:24 -07001080 break;
1081 case SINK_ADDED:
Charles Chand2990362016-04-18 13:44:03 -07001082 mcastHandler.processSinkAdded(event);
Charles Chand55e84d2016-03-30 17:54:24 -07001083 break;
1084 case SINK_REMOVED:
Charles Chand2990362016-04-18 13:44:03 -07001085 mcastHandler.processSinkRemoved(event);
Charles Chand55e84d2016-03-30 17:54:24 -07001086 break;
1087 case ROUTE_ADDED:
1088 case ROUTE_REMOVED:
1089 default:
1090 break;
1091 }
1092 }
1093 }
Charles Chan35fd1a72016-06-13 18:54:31 -07001094
1095 private class InternalCordConfigListener implements CordConfigListener {
1096 @Override
1097 public void event(CordConfigEvent event) {
1098 switch (event.type()) {
1099 case ACCESS_AGENT_ADDED:
1100 cordConfigHandler.processAccessAgentAddedEvent(event);
1101 break;
1102 case ACCESS_AGENT_UPDATED:
1103 cordConfigHandler.processAccessAgentUpdatedEvent(event);
1104 break;
1105 case ACCESS_AGENT_REMOVED:
1106 cordConfigHandler.processAccessAgentRemovedEvent(event);
1107 break;
1108 case ACCESS_DEVICE_ADDED:
1109 case ACCESS_DEVICE_UPDATED:
1110 case ACCESS_DEVICE_REMOVED:
1111 default:
1112 break;
1113 }
1114 }
1115 }
sanghob35a6192015-04-01 13:05:26 -07001116}