blob: 72b6401ab57c1608d7303a53c0410882c226562d [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
18import org.apache.felix.scr.annotations.Activate;
19import org.apache.felix.scr.annotations.Component;
20import org.apache.felix.scr.annotations.Deactivate;
21import org.apache.felix.scr.annotations.Reference;
22import org.apache.felix.scr.annotations.ReferenceCardinality;
sangho1e575652015-05-14 00:39:53 -070023import org.apache.felix.scr.annotations.Service;
sanghob35a6192015-04-01 13:05:26 -070024import org.onlab.packet.Ethernet;
Charles Chanc42e84e2015-10-20 16:24:19 -070025import org.onlab.packet.IPv4;
Charles Chanc42e84e2015-10-20 16:24:19 -070026import org.onlab.packet.Ip4Prefix;
Charles Chanc42e84e2015-10-20 16:24:19 -070027import org.onlab.packet.IpPrefix;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070028import org.onlab.packet.VlanId;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -070029import org.onlab.util.KryoNamespace;
Saurav Das80980c72016-03-23 11:22:49 -070030import org.onosproject.cfg.ComponentConfigService;
sanghob35a6192015-04-01 13:05:26 -070031import org.onosproject.core.ApplicationId;
32import org.onosproject.core.CoreService;
33import org.onosproject.event.Event;
Charles Chand55e84d2016-03-30 17:54:24 -070034import org.onosproject.incubator.net.config.basics.McastConfig;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070035import org.onosproject.mastership.MastershipService;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070036import org.onosproject.net.Device;
37import org.onosproject.net.DeviceId;
38import org.onosproject.net.Link;
39import org.onosproject.net.Port;
Charles Chan68aa62d2015-11-09 16:37:23 -080040import org.onosproject.net.PortNumber;
Charles Chand6832882015-10-05 17:50:33 -070041import org.onosproject.net.config.ConfigFactory;
42import org.onosproject.net.config.NetworkConfigEvent;
Charles Chand6832882015-10-05 17:50:33 -070043import org.onosproject.net.config.NetworkConfigListener;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070044import org.onosproject.net.config.NetworkConfigRegistry;
Charles Chand6832882015-10-05 17:50:33 -070045import org.onosproject.net.config.basics.SubjectFactories;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070046import org.onosproject.net.device.DeviceEvent;
47import org.onosproject.net.device.DeviceListener;
48import org.onosproject.net.device.DeviceService;
Charles Chan68aa62d2015-11-09 16:37:23 -080049import org.onosproject.net.flow.DefaultTrafficSelector;
Charles Chan68aa62d2015-11-09 16:37:23 -080050import org.onosproject.net.flow.TrafficSelector;
51import org.onosproject.net.flow.TrafficTreatment;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070052import org.onosproject.net.flowobjective.FlowObjectiveService;
Charles Chan68aa62d2015-11-09 16:37:23 -080053import org.onosproject.net.host.HostEvent;
54import org.onosproject.net.host.HostListener;
Charles Chand55e84d2016-03-30 17:54:24 -070055import org.onosproject.net.mcast.McastEvent;
56import org.onosproject.net.mcast.McastListener;
57import org.onosproject.net.mcast.MulticastRouteService;
58import org.onosproject.net.packet.PacketPriority;
59import org.onosproject.net.topology.TopologyService;
60import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
61import org.onosproject.segmentrouting.config.DeviceConfiguration;
62import org.onosproject.segmentrouting.config.SegmentRoutingDeviceConfig;
63import org.onosproject.segmentrouting.config.SegmentRoutingAppConfig;
Charles Chanfc5c7802016-05-17 13:13:55 -070064import org.onosproject.segmentrouting.config.XConnectConfig;
Charles Chand55e84d2016-03-30 17:54:24 -070065import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
66import org.onosproject.segmentrouting.grouphandler.NeighborSet;
Charles Chand2990362016-04-18 13:44:03 -070067import org.onosproject.segmentrouting.storekey.NeighborSetNextObjectiveStoreKey;
68import org.onosproject.segmentrouting.storekey.PortNextObjectiveStoreKey;
sanghob35a6192015-04-01 13:05:26 -070069import org.onosproject.net.host.HostService;
sanghob35a6192015-04-01 13:05:26 -070070import org.onosproject.net.link.LinkEvent;
71import org.onosproject.net.link.LinkListener;
72import org.onosproject.net.link.LinkService;
73import org.onosproject.net.packet.InboundPacket;
74import org.onosproject.net.packet.PacketContext;
75import org.onosproject.net.packet.PacketProcessor;
76import org.onosproject.net.packet.PacketService;
Charles Chand2990362016-04-18 13:44:03 -070077import org.onosproject.segmentrouting.storekey.SubnetAssignedVidStoreKey;
78import org.onosproject.segmentrouting.storekey.SubnetNextObjectiveStoreKey;
Charles Chanfc5c7802016-05-17 13:13:55 -070079import org.onosproject.segmentrouting.storekey.XConnectStoreKey;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070080import org.onosproject.store.serializers.KryoNamespaces;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -070081import org.onosproject.store.service.EventuallyConsistentMap;
82import org.onosproject.store.service.EventuallyConsistentMapBuilder;
83import org.onosproject.store.service.StorageService;
84import org.onosproject.store.service.WallClockTimestamp;
Charles Chan35fd1a72016-06-13 18:54:31 -070085import org.opencord.cordconfig.CordConfigEvent;
86import org.opencord.cordconfig.CordConfigListener;
87import org.opencord.cordconfig.CordConfigService;
sanghob35a6192015-04-01 13:05:26 -070088import org.slf4j.Logger;
89import org.slf4j.LoggerFactory;
90
Saurav Das0e99e2b2015-10-28 12:39:42 -070091import java.util.Collections;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -070092import java.util.HashSet;
sangho1e575652015-05-14 00:39:53 -070093import java.util.List;
sanghob35a6192015-04-01 13:05:26 -070094import java.util.Map;
Charles Chan188ebf52015-12-23 00:15:11 -080095import java.util.Optional;
Saurav Das0e99e2b2015-10-28 12:39:42 -070096import java.util.Set;
sanghob35a6192015-04-01 13:05:26 -070097import java.util.concurrent.ConcurrentHashMap;
98import java.util.concurrent.ConcurrentLinkedQueue;
99import java.util.concurrent.Executors;
100import java.util.concurrent.ScheduledExecutorService;
101import java.util.concurrent.ScheduledFuture;
102import java.util.concurrent.TimeUnit;
103
Charles Chan3e783d02016-02-26 22:19:52 -0800104import static com.google.common.base.Preconditions.checkState;
Yuta HIGUCHI1624df12016-07-21 16:54:33 -0700105import static org.onlab.util.Tools.groupedThreads;
Charles Chan3e783d02016-02-26 22:19:52 -0800106
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700107
Charles Chane849c192016-01-11 18:28:54 -0800108/**
109 * Segment routing manager.
110 */
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700111@Service
112@Component(immediate = true)
sangho1e575652015-05-14 00:39:53 -0700113public class SegmentRoutingManager implements SegmentRoutingService {
sanghob35a6192015-04-01 13:05:26 -0700114
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700115 private static Logger log = LoggerFactory
116 .getLogger(SegmentRoutingManager.class);
sanghob35a6192015-04-01 13:05:26 -0700117
118 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
119 protected CoreService coreService;
120
121 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
sanghob35a6192015-04-01 13:05:26 -0700122 protected PacketService packetService;
123
124 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
sanghob35a6192015-04-01 13:05:26 -0700125 protected HostService hostService;
126
127 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
128 protected DeviceService deviceService;
129
130 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700131 protected FlowObjectiveService flowObjectiveService;
sanghob35a6192015-04-01 13:05:26 -0700132
133 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
134 protected LinkService linkService;
135
136 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
sanghob35a6192015-04-01 13:05:26 -0700137 protected MastershipService mastershipService;
sangho1e575652015-05-14 00:39:53 -0700138
Charles Chan5270ed02016-01-30 23:22:37 -0800139 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
140 protected StorageService storageService;
141
142 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
143 protected NetworkConfigRegistry cfgService;
144
Saurav Das80980c72016-03-23 11:22:49 -0700145 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
146 protected ComponentConfigService compCfgService;
147
Charles Chand55e84d2016-03-30 17:54:24 -0700148 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
149 protected MulticastRouteService multicastRouteService;
150
151 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
152 protected TopologyService topologyService;
153
Charles Chan35fd1a72016-06-13 18:54:31 -0700154 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
155 protected CordConfigService cordConfigService;
156
Srikanth Vavilapalli4db76e32015-04-07 15:12:32 -0700157 protected ArpHandler arpHandler = null;
158 protected IcmpHandler icmpHandler = null;
159 protected IpHandler ipHandler = null;
160 protected RoutingRulePopulator routingRulePopulator = null;
sanghob35a6192015-04-01 13:05:26 -0700161 protected ApplicationId appId;
sangho666cd6d2015-04-14 16:27:13 -0700162 protected DeviceConfiguration deviceConfiguration = null;
sanghob35a6192015-04-01 13:05:26 -0700163
Charles Chan93e71ba2016-04-29 14:38:22 -0700164 protected DefaultRoutingHandler defaultRoutingHandler = null;
sangho1e575652015-05-14 00:39:53 -0700165 private TunnelHandler tunnelHandler = null;
166 private PolicyHandler policyHandler = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700167 private InternalPacketProcessor processor = null;
168 private InternalLinkListener linkListener = null;
169 private InternalDeviceListener deviceListener = null;
Charles Chanfc5c7802016-05-17 13:13:55 -0700170 private AppConfigHandler appCfgHandler = null;
171 protected XConnectHandler xConnectHandler = null;
Charles Chand2990362016-04-18 13:44:03 -0700172 private McastHandler mcastHandler = null;
Charles Chan35fd1a72016-06-13 18:54:31 -0700173 protected HostHandler hostHandler = null;
174 private CordConfigHandler cordConfigHandler = null;
sanghob35a6192015-04-01 13:05:26 -0700175 private InternalEventHandler eventHandler = new InternalEventHandler();
Charles Chan5270ed02016-01-30 23:22:37 -0800176 private final InternalHostListener hostListener = new InternalHostListener();
Charles Chand55e84d2016-03-30 17:54:24 -0700177 private final InternalConfigListener cfgListener = new InternalConfigListener(this);
178 private final InternalMcastListener mcastListener = new InternalMcastListener();
Charles Chan35fd1a72016-06-13 18:54:31 -0700179 private final InternalCordConfigListener cordConfigListener = new InternalCordConfigListener();
sanghob35a6192015-04-01 13:05:26 -0700180
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700181 private ScheduledExecutorService executorService = Executors
Yuta HIGUCHI1624df12016-07-21 16:54:33 -0700182 .newScheduledThreadPool(1, groupedThreads("SegmentRoutingManager", "event-%d", log));
sanghob35a6192015-04-01 13:05:26 -0700183
Saurav Das4ce45962015-11-24 23:21:05 -0800184 @SuppressWarnings("unused")
sanghob35a6192015-04-01 13:05:26 -0700185 private static ScheduledFuture<?> eventHandlerFuture = null;
Saurav Das4ce45962015-11-24 23:21:05 -0800186 @SuppressWarnings("rawtypes")
Yuta HIGUCHI1624df12016-07-21 16:54:33 -0700187 private ConcurrentLinkedQueue<Event> eventQueue = new ConcurrentLinkedQueue<>();
Charles Chan68aa62d2015-11-09 16:37:23 -0800188 private Map<DeviceId, DefaultGroupHandler> groupHandlerMap =
Charles Chane849c192016-01-11 18:28:54 -0800189 new ConcurrentHashMap<>();
190 /**
191 * Per device next objective ID store with (device id + neighbor set) as key.
192 */
193 public EventuallyConsistentMap<NeighborSetNextObjectiveStoreKey, Integer>
Charles Chan68aa62d2015-11-09 16:37:23 -0800194 nsNextObjStore = null;
Charles Chane849c192016-01-11 18:28:54 -0800195 /**
196 * Per device next objective ID store with (device id + subnet) as key.
197 */
198 public EventuallyConsistentMap<SubnetNextObjectiveStoreKey, Integer>
Charles Chan68aa62d2015-11-09 16:37:23 -0800199 subnetNextObjStore = null;
Charles Chane849c192016-01-11 18:28:54 -0800200 /**
201 * Per device next objective ID store with (device id + port) as key.
202 */
203 public EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer>
Saurav Das4ce45962015-11-24 23:21:05 -0800204 portNextObjStore = null;
Saurav Das0e99e2b2015-10-28 12:39:42 -0700205 // Per device, per-subnet assigned-vlans store, with (device id + subnet
206 // IPv4 prefix) as key
207 private EventuallyConsistentMap<SubnetAssignedVidStoreKey, VlanId>
Charles Chane849c192016-01-11 18:28:54 -0800208 subnetVidStore = null;
Saurav Das4ce45962015-11-24 23:21:05 -0800209 private EventuallyConsistentMap<String, Tunnel> tunnelStore = null;
210 private EventuallyConsistentMap<String, Policy> policyStore = null;
sangho0b2b6d12015-05-20 22:16:38 -0700211
Charles Chand55e84d2016-03-30 17:54:24 -0700212 private final ConfigFactory<DeviceId, SegmentRoutingDeviceConfig> deviceConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700213 new ConfigFactory<DeviceId, SegmentRoutingDeviceConfig>(
214 SubjectFactories.DEVICE_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700215 SegmentRoutingDeviceConfig.class, "segmentrouting") {
Charles Chand6832882015-10-05 17:50:33 -0700216 @Override
Charles Chan5270ed02016-01-30 23:22:37 -0800217 public SegmentRoutingDeviceConfig createConfig() {
218 return new SegmentRoutingDeviceConfig();
Charles Chand6832882015-10-05 17:50:33 -0700219 }
220 };
Charles Chand55e84d2016-03-30 17:54:24 -0700221 private final ConfigFactory<ApplicationId, SegmentRoutingAppConfig> appConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700222 new ConfigFactory<ApplicationId, SegmentRoutingAppConfig>(
223 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700224 SegmentRoutingAppConfig.class, "segmentrouting") {
Charles Chan5270ed02016-01-30 23:22:37 -0800225 @Override
226 public SegmentRoutingAppConfig createConfig() {
227 return new SegmentRoutingAppConfig();
228 }
229 };
Charles Chanfc5c7802016-05-17 13:13:55 -0700230 private final ConfigFactory<ApplicationId, XConnectConfig> xConnectConfigFactory =
231 new ConfigFactory<ApplicationId, XConnectConfig>(
232 SubjectFactories.APP_SUBJECT_FACTORY,
233 XConnectConfig.class, "xconnect") {
234 @Override
235 public XConnectConfig createConfig() {
236 return new XConnectConfig();
237 }
238 };
Charles Chand55e84d2016-03-30 17:54:24 -0700239 private ConfigFactory<ApplicationId, McastConfig> mcastConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700240 new ConfigFactory<ApplicationId, McastConfig>(
241 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700242 McastConfig.class, "multicast") {
243 @Override
244 public McastConfig createConfig() {
245 return new McastConfig();
246 }
247 };
248
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700249 private Object threadSchedulerLock = new Object();
250 private static int numOfEventsQueued = 0;
251 private static int numOfEventsExecuted = 0;
sanghob35a6192015-04-01 13:05:26 -0700252 private static int numOfHandlerExecution = 0;
253 private static int numOfHandlerScheduled = 0;
254
Charles Chan116188d2016-02-18 14:22:42 -0800255 /**
256 * Segment Routing App ID.
257 */
258 public static final String SR_APP_ID = "org.onosproject.segmentrouting";
Charles Chane849c192016-01-11 18:28:54 -0800259 /**
260 * The starting value of per-subnet VLAN ID assignment.
261 */
Saurav Das0e99e2b2015-10-28 12:39:42 -0700262 private static final short ASSIGNED_VLAN_START = 4093;
Charles Chane849c192016-01-11 18:28:54 -0800263 /**
264 * The default VLAN ID assigned to the interfaces without subnet config.
265 */
Saurav Das0e99e2b2015-10-28 12:39:42 -0700266 public static final short ASSIGNED_VLAN_NO_SUBNET = 4094;
267
sanghob35a6192015-04-01 13:05:26 -0700268 @Activate
269 protected void activate() {
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700270 appId = coreService.registerApplication(SR_APP_ID);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700271
272 log.debug("Creating EC map nsnextobjectivestore");
273 EventuallyConsistentMapBuilder<NeighborSetNextObjectiveStoreKey, Integer>
274 nsNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700275 nsNextObjStore = nsNextObjMapBuilder
276 .withName("nsnextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700277 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700278 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700279 .build();
280 log.trace("Current size {}", nsNextObjStore.size());
281
Charles Chanc42e84e2015-10-20 16:24:19 -0700282 log.debug("Creating EC map subnetnextobjectivestore");
283 EventuallyConsistentMapBuilder<SubnetNextObjectiveStoreKey, Integer>
284 subnetNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
Charles Chanc42e84e2015-10-20 16:24:19 -0700285 subnetNextObjStore = subnetNextObjMapBuilder
286 .withName("subnetnextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700287 .withSerializer(createSerializer())
Charles Chanc42e84e2015-10-20 16:24:19 -0700288 .withTimestampProvider((k, v) -> new WallClockTimestamp())
289 .build();
290
Saurav Das4ce45962015-11-24 23:21:05 -0800291 log.debug("Creating EC map subnetnextobjectivestore");
292 EventuallyConsistentMapBuilder<PortNextObjectiveStoreKey, Integer>
293 portNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
294 portNextObjStore = portNextObjMapBuilder
295 .withName("portnextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700296 .withSerializer(createSerializer())
Saurav Das4ce45962015-11-24 23:21:05 -0800297 .withTimestampProvider((k, v) -> new WallClockTimestamp())
298 .build();
299
sangho0b2b6d12015-05-20 22:16:38 -0700300 EventuallyConsistentMapBuilder<String, Tunnel> tunnelMapBuilder =
301 storageService.eventuallyConsistentMapBuilder();
sangho0b2b6d12015-05-20 22:16:38 -0700302 tunnelStore = tunnelMapBuilder
303 .withName("tunnelstore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700304 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700305 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho0b2b6d12015-05-20 22:16:38 -0700306 .build();
307
308 EventuallyConsistentMapBuilder<String, Policy> policyMapBuilder =
309 storageService.eventuallyConsistentMapBuilder();
sangho0b2b6d12015-05-20 22:16:38 -0700310 policyStore = policyMapBuilder
311 .withName("policystore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700312 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700313 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho0b2b6d12015-05-20 22:16:38 -0700314 .build();
315
Saurav Das0e99e2b2015-10-28 12:39:42 -0700316 EventuallyConsistentMapBuilder<SubnetAssignedVidStoreKey, VlanId>
317 subnetVidStoreMapBuilder = storageService.eventuallyConsistentMapBuilder();
Saurav Das0e99e2b2015-10-28 12:39:42 -0700318 subnetVidStore = subnetVidStoreMapBuilder
319 .withName("subnetvidstore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700320 .withSerializer(createSerializer())
Saurav Das0e99e2b2015-10-28 12:39:42 -0700321 .withTimestampProvider((k, v) -> new WallClockTimestamp())
322 .build();
323
Saurav Das80980c72016-03-23 11:22:49 -0700324 compCfgService.preSetProperty("org.onosproject.net.group.impl.GroupManager",
325 "purgeOnDisconnection", "true");
326 compCfgService.preSetProperty("org.onosproject.net.flow.impl.FlowRuleManager",
327 "purgeOnDisconnection", "true");
328
Charles Chanb8e10c82015-10-14 11:24:40 -0700329 processor = new InternalPacketProcessor();
330 linkListener = new InternalLinkListener();
331 deviceListener = new InternalDeviceListener();
Charles Chanfc5c7802016-05-17 13:13:55 -0700332 appCfgHandler = new AppConfigHandler(this);
333 xConnectHandler = new XConnectHandler(this);
Charles Chand2990362016-04-18 13:44:03 -0700334 mcastHandler = new McastHandler(this);
335 hostHandler = new HostHandler(this);
Charles Chan35fd1a72016-06-13 18:54:31 -0700336 cordConfigHandler = new CordConfigHandler(this);
Charles Chanb8e10c82015-10-14 11:24:40 -0700337
Charles Chan3e783d02016-02-26 22:19:52 -0800338 cfgService.addListener(cfgListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700339 cfgService.registerConfigFactory(deviceConfigFactory);
340 cfgService.registerConfigFactory(appConfigFactory);
Charles Chanfc5c7802016-05-17 13:13:55 -0700341 cfgService.registerConfigFactory(xConnectConfigFactory);
Charles Chand55e84d2016-03-30 17:54:24 -0700342 cfgService.registerConfigFactory(mcastConfigFactory);
Charles Chan5270ed02016-01-30 23:22:37 -0800343 hostService.addListener(hostListener);
Charles Chanb8e10c82015-10-14 11:24:40 -0700344 packetService.addProcessor(processor, PacketProcessor.director(2));
345 linkService.addListener(linkListener);
346 deviceService.addListener(deviceListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700347 multicastRouteService.addListener(mcastListener);
Charles Chan35fd1a72016-06-13 18:54:31 -0700348 cordConfigService.addListener(cordConfigListener);
Charles Chanb8e10c82015-10-14 11:24:40 -0700349
Charles Chan188ebf52015-12-23 00:15:11 -0800350 // Request ARP packet-in
351 TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
352 selector.matchEthType(Ethernet.TYPE_ARP);
353 packetService.requestPackets(selector.build(), PacketPriority.CONTROL, appId, Optional.empty());
354
Charles Chanb8e10c82015-10-14 11:24:40 -0700355 cfgListener.configureNetwork();
356
sanghob35a6192015-04-01 13:05:26 -0700357 log.info("Started");
358 }
359
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700360 private KryoNamespace.Builder createSerializer() {
361 return new KryoNamespace.Builder()
362 .register(KryoNamespaces.API)
363 .register(NeighborSetNextObjectiveStoreKey.class,
364 SubnetNextObjectiveStoreKey.class,
365 SubnetAssignedVidStoreKey.class,
366 NeighborSet.class,
367 Tunnel.class,
368 DefaultTunnel.class,
369 Policy.class,
370 TunnelPolicy.class,
371 Policy.Type.class,
372 PortNextObjectiveStoreKey.class,
Charles Chanfc5c7802016-05-17 13:13:55 -0700373 XConnectStoreKey.class
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700374 );
375 }
376
sanghob35a6192015-04-01 13:05:26 -0700377 @Deactivate
378 protected void deactivate() {
Charles Chand6832882015-10-05 17:50:33 -0700379 cfgService.removeListener(cfgListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700380 cfgService.unregisterConfigFactory(deviceConfigFactory);
381 cfgService.unregisterConfigFactory(appConfigFactory);
382 cfgService.unregisterConfigFactory(mcastConfigFactory);
Charles Chand6832882015-10-05 17:50:33 -0700383
Charles Chan188ebf52015-12-23 00:15:11 -0800384 // Withdraw ARP packet-in
385 TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
386 selector.matchEthType(Ethernet.TYPE_ARP);
387 packetService.cancelPackets(selector.build(), PacketPriority.CONTROL, appId, Optional.empty());
388
sanghob35a6192015-04-01 13:05:26 -0700389 packetService.removeProcessor(processor);
Charles Chanb8e10c82015-10-14 11:24:40 -0700390 linkService.removeListener(linkListener);
391 deviceService.removeListener(deviceListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700392 multicastRouteService.removeListener(mcastListener);
Charles Chan35fd1a72016-06-13 18:54:31 -0700393 cordConfigService.removeListener(cordConfigListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700394
sanghob35a6192015-04-01 13:05:26 -0700395 processor = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700396 linkListener = null;
Charles Chand55e84d2016-03-30 17:54:24 -0700397 deviceListener = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700398 groupHandlerMap.clear();
399
Charles Chand55e84d2016-03-30 17:54:24 -0700400 nsNextObjStore.destroy();
401 subnetNextObjStore.destroy();
402 portNextObjStore.destroy();
Charles Chand55e84d2016-03-30 17:54:24 -0700403 tunnelStore.destroy();
404 policyStore.destroy();
405 subnetVidStore.destroy();
sanghob35a6192015-04-01 13:05:26 -0700406 log.info("Stopped");
407 }
408
sangho1e575652015-05-14 00:39:53 -0700409 @Override
410 public List<Tunnel> getTunnels() {
411 return tunnelHandler.getTunnels();
412 }
413
414 @Override
sangho71abe1b2015-06-29 14:58:47 -0700415 public TunnelHandler.Result createTunnel(Tunnel tunnel) {
416 return tunnelHandler.createTunnel(tunnel);
sangho1e575652015-05-14 00:39:53 -0700417 }
418
419 @Override
sangho71abe1b2015-06-29 14:58:47 -0700420 public TunnelHandler.Result removeTunnel(Tunnel tunnel) {
sangho1e575652015-05-14 00:39:53 -0700421 for (Policy policy: policyHandler.getPolicies()) {
422 if (policy.type() == Policy.Type.TUNNEL_FLOW) {
423 TunnelPolicy tunnelPolicy = (TunnelPolicy) policy;
424 if (tunnelPolicy.tunnelId().equals(tunnel.id())) {
425 log.warn("Cannot remove the tunnel used by a policy");
sangho71abe1b2015-06-29 14:58:47 -0700426 return TunnelHandler.Result.TUNNEL_IN_USE;
sangho1e575652015-05-14 00:39:53 -0700427 }
428 }
429 }
sangho71abe1b2015-06-29 14:58:47 -0700430 return tunnelHandler.removeTunnel(tunnel);
sangho1e575652015-05-14 00:39:53 -0700431 }
432
433 @Override
sangho71abe1b2015-06-29 14:58:47 -0700434 public PolicyHandler.Result removePolicy(Policy policy) {
435 return policyHandler.removePolicy(policy);
sangho1e575652015-05-14 00:39:53 -0700436 }
437
438 @Override
sangho71abe1b2015-06-29 14:58:47 -0700439 public PolicyHandler.Result createPolicy(Policy policy) {
440 return policyHandler.createPolicy(policy);
sangho1e575652015-05-14 00:39:53 -0700441 }
442
443 @Override
444 public List<Policy> getPolicies() {
445 return policyHandler.getPolicies();
446 }
447
Saurav Das59232cf2016-04-27 18:35:50 -0700448 @Override
449 public void rerouteNetwork() {
450 cfgListener.configureNetwork();
451 for (Device device : deviceService.getDevices()) {
452 defaultRoutingHandler.populatePortAddressingRules(device.id());
453 }
454 defaultRoutingHandler.startPopulationProcess();
455 }
456
sanghof9d0bf12015-05-19 11:57:42 -0700457 /**
458 * Returns the tunnel object with the tunnel ID.
459 *
460 * @param tunnelId Tunnel ID
461 * @return Tunnel reference
462 */
sangho1e575652015-05-14 00:39:53 -0700463 public Tunnel getTunnel(String tunnelId) {
464 return tunnelHandler.getTunnel(tunnelId);
465 }
466
sanghob35a6192015-04-01 13:05:26 -0700467 /**
Saurav Das0e99e2b2015-10-28 12:39:42 -0700468 * Returns the vlan-id assigned to the subnet configured for a device.
469 * If no vlan-id has been assigned, a new one is assigned out of a pool of ids,
470 * if and only if this controller instance is the master for the device.
471 * <p>
472 * USAGE: The assigned vlans are meant to be applied to untagged packets on those
473 * switches/pipelines that need this functionality. These vids are meant
474 * to be used internally within a switch, and thus need to be unique only
475 * on a switch level. Note that packets never go out on the wire with these
476 * vlans. Currently, vlan ids are assigned from value 4093 down.
477 * Vlan id 4094 expected to be used for all ports that are not assigned subnets.
478 * Vlan id 4095 is reserved and unused. Only a single vlan id is assigned
479 * per subnet.
sanghob35a6192015-04-01 13:05:26 -0700480 *
Saurav Das0e99e2b2015-10-28 12:39:42 -0700481 * @param deviceId switch dpid
482 * @param subnet IPv4 prefix for which assigned vlan is desired
483 * @return VlanId assigned for the subnet on the device, or
484 * null if no vlan assignment was found and this instance is not
485 * the master for the device.
sanghob35a6192015-04-01 13:05:26 -0700486 */
Charles Chane849c192016-01-11 18:28:54 -0800487 // TODO: We should avoid assigning VLAN IDs that are used by VLAN cross-connection.
Saurav Das0e99e2b2015-10-28 12:39:42 -0700488 public VlanId getSubnetAssignedVlanId(DeviceId deviceId, Ip4Prefix subnet) {
489 VlanId assignedVid = subnetVidStore.get(new SubnetAssignedVidStoreKey(
490 deviceId, subnet));
491 if (assignedVid != null) {
492 log.debug("Query for subnet:{} on device:{} returned assigned-vlan "
493 + "{}", subnet, deviceId, assignedVid);
494 return assignedVid;
495 }
496 //check mastership for the right to assign a vlan
497 if (!mastershipService.isLocalMaster(deviceId)) {
498 log.warn("This controller instance is not the master for device {}. "
499 + "Cannot assign vlan-id for subnet {}", deviceId, subnet);
500 return null;
501 }
502 // vlan assignment is expensive but done only once
Charles Chan9f676b62015-10-29 14:58:10 -0700503 Set<Ip4Prefix> configuredSubnets = deviceConfiguration.getSubnets(deviceId);
Saurav Das0e99e2b2015-10-28 12:39:42 -0700504 Set<Short> assignedVlans = new HashSet<>();
505 Set<Ip4Prefix> unassignedSubnets = new HashSet<>();
506 for (Ip4Prefix sub : configuredSubnets) {
507 VlanId v = subnetVidStore.get(new SubnetAssignedVidStoreKey(deviceId,
508 sub));
509 if (v != null) {
510 assignedVlans.add(v.toShort());
511 } else {
512 unassignedSubnets.add(sub);
513 }
514 }
515 short nextAssignedVlan = ASSIGNED_VLAN_START;
516 if (!assignedVlans.isEmpty()) {
517 nextAssignedVlan = (short) (Collections.min(assignedVlans) - 1);
518 }
519 for (Ip4Prefix unsub : unassignedSubnets) {
Charles Chan5270ed02016-01-30 23:22:37 -0800520 // Special case for default route. Assign default VLAN ID to /32 and /0 subnets
521 if (unsub.prefixLength() == IpPrefix.MAX_INET_MASK_LENGTH ||
522 unsub.prefixLength() == 0) {
523 subnetVidStore.put(new SubnetAssignedVidStoreKey(deviceId, unsub),
524 VlanId.vlanId(ASSIGNED_VLAN_NO_SUBNET));
525 } else {
526 subnetVidStore.put(new SubnetAssignedVidStoreKey(deviceId, unsub),
527 VlanId.vlanId(nextAssignedVlan--));
528 log.info("Assigned vlan: {} to subnet: {} on device: {}",
529 nextAssignedVlan + 1, unsub, deviceId);
530 }
sanghob35a6192015-04-01 13:05:26 -0700531 }
532
Saurav Das0e99e2b2015-10-28 12:39:42 -0700533 return subnetVidStore.get(new SubnetAssignedVidStoreKey(deviceId, subnet));
sanghob35a6192015-04-01 13:05:26 -0700534 }
535
sangho1e575652015-05-14 00:39:53 -0700536 /**
Saurav Das0e99e2b2015-10-28 12:39:42 -0700537 * Returns the next objective ID for the given NeighborSet.
Saurav Das8a0732e2015-11-20 15:27:53 -0800538 * If the nextObjective does not exist, a new one is created and
Saurav Das4ce45962015-11-24 23:21:05 -0800539 * its id is returned.
sangho1e575652015-05-14 00:39:53 -0700540 *
sanghof9d0bf12015-05-19 11:57:42 -0700541 * @param deviceId Device ID
542 * @param ns NegighborSet
Saurav Das8a0732e2015-11-20 15:27:53 -0800543 * @param meta metadata passed into the creation of a Next Objective
544 * @return next objective ID or -1 if an error was encountered during the
545 * creation of the nextObjective
sangho1e575652015-05-14 00:39:53 -0700546 */
Saurav Das8a0732e2015-11-20 15:27:53 -0800547 public int getNextObjectiveId(DeviceId deviceId, NeighborSet ns,
548 TrafficSelector meta) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700549 if (groupHandlerMap.get(deviceId) != null) {
550 log.trace("getNextObjectiveId query in device {}", deviceId);
551 return groupHandlerMap
Saurav Das8a0732e2015-11-20 15:27:53 -0800552 .get(deviceId).getNextObjectiveId(ns, meta);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700553 } else {
Saurav Das4ce45962015-11-24 23:21:05 -0800554 log.warn("getNextObjectiveId query - groupHandler for device {} "
555 + "not found", deviceId);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700556 return -1;
557 }
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700558 }
559
Charles Chanc42e84e2015-10-20 16:24:19 -0700560 /**
Saurav Das4ce45962015-11-24 23:21:05 -0800561 * Returns the next objective ID for the given subnet prefix. It is expected
562 * that the next-objective has been pre-created from configuration.
Charles Chanc42e84e2015-10-20 16:24:19 -0700563 *
564 * @param deviceId Device ID
565 * @param prefix Subnet
Saurav Das4ce45962015-11-24 23:21:05 -0800566 * @return next objective ID or -1 if it was not found
Charles Chanc42e84e2015-10-20 16:24:19 -0700567 */
568 public int getSubnetNextObjectiveId(DeviceId deviceId, IpPrefix prefix) {
569 if (groupHandlerMap.get(deviceId) != null) {
570 log.trace("getSubnetNextObjectiveId query in device {}", deviceId);
571 return groupHandlerMap
572 .get(deviceId).getSubnetNextObjectiveId(prefix);
573 } else {
Saurav Das4ce45962015-11-24 23:21:05 -0800574 log.warn("getSubnetNextObjectiveId query - groupHandler for "
575 + "device {} not found", deviceId);
576 return -1;
577 }
578 }
579
580 /**
581 * Returns the next objective ID for the given portNumber, given the treatment.
582 * There could be multiple different treatments to the same outport, which
583 * would result in different objectives. If the next object
584 * does not exist, a new one is created and its id is returned.
585 *
586 * @param deviceId Device ID
587 * @param portNum port number on device for which NextObjective is queried
588 * @param treatment the actions to apply on the packets (should include outport)
589 * @param meta metadata passed into the creation of a Next Objective if necessary
Saurav Das59232cf2016-04-27 18:35:50 -0700590 * @return next objective ID or -1 if an error occurred during retrieval or creation
Saurav Das4ce45962015-11-24 23:21:05 -0800591 */
592 public int getPortNextObjectiveId(DeviceId deviceId, PortNumber portNum,
593 TrafficTreatment treatment,
594 TrafficSelector meta) {
595 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
596 if (ghdlr != null) {
597 return ghdlr.getPortNextObjectiveId(portNum, treatment, meta);
598 } else {
Charles Chane849c192016-01-11 18:28:54 -0800599 log.warn("getPortNextObjectiveId query - groupHandler for device {}"
600 + " not found", deviceId);
601 return -1;
602 }
603 }
604
sanghob35a6192015-04-01 13:05:26 -0700605 private class InternalPacketProcessor implements PacketProcessor {
sanghob35a6192015-04-01 13:05:26 -0700606 @Override
607 public void process(PacketContext context) {
608
609 if (context.isHandled()) {
610 return;
611 }
612
613 InboundPacket pkt = context.inPacket();
614 Ethernet ethernet = pkt.parsed();
Saurav Das4ce45962015-11-24 23:21:05 -0800615 log.trace("Rcvd pktin: {}", ethernet);
sanghob35a6192015-04-01 13:05:26 -0700616 if (ethernet.getEtherType() == Ethernet.TYPE_ARP) {
617 arpHandler.processPacketIn(pkt);
618 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV4) {
619 IPv4 ipPacket = (IPv4) ethernet.getPayload();
620 ipHandler.addToPacketBuffer(ipPacket);
621 if (ipPacket.getProtocol() == IPv4.PROTOCOL_ICMP) {
622 icmpHandler.processPacketIn(pkt);
623 } else {
624 ipHandler.processPacketIn(pkt);
625 }
626 }
627 }
628 }
629
630 private class InternalLinkListener implements LinkListener {
631 @Override
632 public void event(LinkEvent event) {
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700633 if (event.type() == LinkEvent.Type.LINK_ADDED
634 || event.type() == LinkEvent.Type.LINK_REMOVED) {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700635 log.debug("Event {} received from Link Service", event.type());
sanghob35a6192015-04-01 13:05:26 -0700636 scheduleEventHandlerIfNotScheduled(event);
637 }
638 }
639 }
640
641 private class InternalDeviceListener implements DeviceListener {
sanghob35a6192015-04-01 13:05:26 -0700642 @Override
643 public void event(DeviceEvent event) {
sanghob35a6192015-04-01 13:05:26 -0700644 switch (event.type()) {
645 case DEVICE_ADDED:
646 case PORT_REMOVED:
sangho20eff1d2015-04-13 15:15:58 -0700647 case DEVICE_UPDATED:
648 case DEVICE_AVAILABILITY_CHANGED:
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700649 log.debug("Event {} received from Device Service", event.type());
sanghob35a6192015-04-01 13:05:26 -0700650 scheduleEventHandlerIfNotScheduled(event);
651 break;
652 default:
653 }
654 }
655 }
656
Saurav Das4ce45962015-11-24 23:21:05 -0800657 @SuppressWarnings("rawtypes")
sanghob35a6192015-04-01 13:05:26 -0700658 private void scheduleEventHandlerIfNotScheduled(Event event) {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700659 synchronized (threadSchedulerLock) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700660 eventQueue.add(event);
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700661 numOfEventsQueued++;
662
663 if ((numOfHandlerScheduled - numOfHandlerExecution) == 0) {
664 //No pending scheduled event handling threads. So start a new one.
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700665 eventHandlerFuture = executorService
666 .schedule(eventHandler, 100, TimeUnit.MILLISECONDS);
667 numOfHandlerScheduled++;
668 }
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700669 log.trace("numOfEventsQueued {}, numOfEventHandlerScheduled {}",
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700670 numOfEventsQueued,
671 numOfHandlerScheduled);
sanghob35a6192015-04-01 13:05:26 -0700672 }
sanghob35a6192015-04-01 13:05:26 -0700673 }
674
675 private class InternalEventHandler implements Runnable {
Srikanth Vavilapalli4db76e32015-04-07 15:12:32 -0700676 @Override
sanghob35a6192015-04-01 13:05:26 -0700677 public void run() {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700678 try {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700679 while (true) {
Saurav Das4ce45962015-11-24 23:21:05 -0800680 @SuppressWarnings("rawtypes")
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700681 Event event = null;
682 synchronized (threadSchedulerLock) {
683 if (!eventQueue.isEmpty()) {
684 event = eventQueue.poll();
685 numOfEventsExecuted++;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700686 } else {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700687 numOfHandlerExecution++;
688 log.debug("numOfHandlerExecution {} numOfEventsExecuted {}",
689 numOfHandlerExecution, numOfEventsExecuted);
690 break;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700691 }
sangho20eff1d2015-04-13 15:15:58 -0700692 }
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700693 if (event.type() == LinkEvent.Type.LINK_ADDED) {
694 processLinkAdded((Link) event.subject());
695 } else if (event.type() == LinkEvent.Type.LINK_REMOVED) {
Pier Ventre2c515312016-09-13 21:33:40 -0700696 Link linkRemoved = (Link) event.subject();
697 if (linkRemoved.src().elementId() instanceof DeviceId &&
698 !deviceService.isAvailable(linkRemoved.src().deviceId())) {
699 continue;
700 }
701 if (linkRemoved.dst().elementId() instanceof DeviceId &&
702 !deviceService.isAvailable(linkRemoved.dst().deviceId())) {
703 continue;
704 }
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700705 processLinkRemoved((Link) event.subject());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700706 } else if (event.type() == DeviceEvent.Type.DEVICE_ADDED ||
707 event.type() == DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED ||
708 event.type() == DeviceEvent.Type.DEVICE_UPDATED) {
Saurav Das423fe2b2015-12-04 10:52:59 -0800709 DeviceId deviceId = ((Device) event.subject()).id();
710 if (deviceService.isAvailable(deviceId)) {
Saurav Das837e0bb2015-10-30 17:45:38 -0700711 log.info("Processing device event {} for available device {}",
712 event.type(), ((Device) event.subject()).id());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700713 processDeviceAdded((Device) event.subject());
Saurav Das80980c72016-03-23 11:22:49 -0700714 } else {
715 log.info("Processing device event {} for unavailable device {}",
716 event.type(), ((Device) event.subject()).id());
717 processDeviceRemoved((Device) event.subject());
718 }
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700719 } else if (event.type() == DeviceEvent.Type.PORT_REMOVED) {
720 processPortRemoved((Device) event.subject(),
721 ((DeviceEvent) event).port());
Saurav Dasb5c236e2016-06-07 10:08:06 -0700722 } else if (event.type() == DeviceEvent.Type.PORT_ADDED ||
723 event.type() == DeviceEvent.Type.PORT_UPDATED) {
724 log.info("** PORT ADDED OR UPDATED {}/{} -> {}",
Yuta HIGUCHI1624df12016-07-21 16:54:33 -0700725 event.subject(),
Saurav Dasb5c236e2016-06-07 10:08:06 -0700726 ((DeviceEvent) event).port(),
727 event.type());
728 /* XXX create method for single port filtering rules
729 if (defaultRoutingHandler != null) {
730 defaultRoutingHandler.populatePortAddressingRules(
731 ((Device) event.subject()).id());
732 }*/
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700733 } else {
734 log.warn("Unhandled event type: {}", event.type());
735 }
sanghob35a6192015-04-01 13:05:26 -0700736 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700737 } catch (Exception e) {
738 log.error("SegmentRouting event handler "
739 + "thread thrown an exception: {}", e);
sanghob35a6192015-04-01 13:05:26 -0700740 }
sanghob35a6192015-04-01 13:05:26 -0700741 }
742 }
743
sanghob35a6192015-04-01 13:05:26 -0700744 private void processLinkAdded(Link link) {
Saurav Dasb5c236e2016-06-07 10:08:06 -0700745 log.info("** LINK ADDED {}", link.toString());
Charles Chan0b4e6182015-11-03 10:42:14 -0800746 if (!deviceConfiguration.isConfigured(link.src().deviceId())) {
747 log.warn("Source device of this link is not configured.");
748 return;
749 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700750 //Irrespective whether the local is a MASTER or not for this device,
751 //create group handler instance and push default TTP flow rules.
752 //Because in a multi-instance setup, instances can initiate
753 //groups for any devices. Also the default TTP rules are needed
754 //to be pushed before inserting any IP table entries for any device
755 DefaultGroupHandler groupHandler = groupHandlerMap.get(link.src()
756 .deviceId());
757 if (groupHandler != null) {
Saurav Das8a0732e2015-11-20 15:27:53 -0800758 groupHandler.linkUp(link, mastershipService.isLocalMaster(
759 link.src().deviceId()));
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700760 } else {
761 Device device = deviceService.getDevice(link.src().deviceId());
762 if (device != null) {
763 log.warn("processLinkAdded: Link Added "
764 + "Notification without Device Added "
765 + "event, still handling it");
766 processDeviceAdded(device);
767 groupHandler = groupHandlerMap.get(link.src()
768 .deviceId());
Saurav Das8a0732e2015-11-20 15:27:53 -0800769 groupHandler.linkUp(link, mastershipService.isLocalMaster(device.id()));
sanghob35a6192015-04-01 13:05:26 -0700770 }
771 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700772
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700773 log.trace("Starting optimized route population process");
774 defaultRoutingHandler.populateRoutingRulesForLinkStatusChange(null);
775 //log.trace("processLinkAdded: re-starting route population process");
776 //defaultRoutingHandler.startPopulationProcess();
Charles Chan2199c302016-04-23 17:36:10 -0700777
778 mcastHandler.init();
sanghob35a6192015-04-01 13:05:26 -0700779 }
780
781 private void processLinkRemoved(Link link) {
Saurav Dasb5c236e2016-06-07 10:08:06 -0700782 log.info("** LINK REMOVED {}", link.toString());
sangho834e4b02015-05-01 09:38:25 -0700783 DefaultGroupHandler groupHandler = groupHandlerMap.get(link.src().deviceId());
784 if (groupHandler != null) {
Saurav Das423fe2b2015-12-04 10:52:59 -0800785 groupHandler.portDown(link.src().port(),
786 mastershipService.isLocalMaster(link.src().deviceId()));
sangho834e4b02015-05-01 09:38:25 -0700787 }
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700788 log.trace("Starting optimized route population process");
789 defaultRoutingHandler.populateRoutingRulesForLinkStatusChange(link);
790 //log.trace("processLinkRemoved: re-starting route population process");
791 //defaultRoutingHandler.startPopulationProcess();
Charles Chan2199c302016-04-23 17:36:10 -0700792
793 mcastHandler.processLinkDown(link);
sanghob35a6192015-04-01 13:05:26 -0700794 }
795
796 private void processDeviceAdded(Device device) {
Saurav Dasb5c236e2016-06-07 10:08:06 -0700797 log.info("** DEVICE ADDED with ID {}", device.id());
Charles Chan0b4e6182015-11-03 10:42:14 -0800798 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
Saurav Das2857f382015-11-03 14:39:27 -0800799 log.warn("Device configuration uploading. Device {} will be "
800 + "processed after config completes.", device.id());
801 return;
802 }
Charles Chan2199c302016-04-23 17:36:10 -0700803 processDeviceAddedInternal(device.id());
804 }
805
806 private void processDeviceAddedInternal(DeviceId deviceId) {
Saurav Das837e0bb2015-10-30 17:45:38 -0700807 // Irrespective of whether the local is a MASTER or not for this device,
808 // we need to create a SR-group-handler instance. This is because in a
809 // multi-instance setup, any instance can initiate forwarding/next-objectives
810 // for any switch (even if this instance is a SLAVE or not even connected
811 // to the switch). To handle this, a default-group-handler instance is necessary
812 // per switch.
Charles Chan2199c302016-04-23 17:36:10 -0700813 log.debug("Current groupHandlerMap devs: {}", groupHandlerMap.keySet());
814 if (groupHandlerMap.get(deviceId) == null) {
Charles Chan0b4e6182015-11-03 10:42:14 -0800815 DefaultGroupHandler groupHandler;
816 try {
817 groupHandler = DefaultGroupHandler.
Charles Chan2199c302016-04-23 17:36:10 -0700818 createGroupHandler(deviceId,
819 appId,
820 deviceConfiguration,
821 linkService,
822 flowObjectiveService,
823 this);
Charles Chan0b4e6182015-11-03 10:42:14 -0800824 } catch (DeviceConfigNotFoundException e) {
825 log.warn(e.getMessage() + " Aborting processDeviceAdded.");
826 return;
827 }
Charles Chan2199c302016-04-23 17:36:10 -0700828 log.debug("updating groupHandlerMap with new config for device: {}",
829 deviceId);
830 groupHandlerMap.put(deviceId, groupHandler);
Saurav Das2857f382015-11-03 14:39:27 -0800831 }
Saurav Dasb5c236e2016-06-07 10:08:06 -0700832 // Also, in some cases, drivers may need extra
833 // information to process rules (eg. Router IP/MAC); and so, we send
834 // port addressing rules to the driver as well irrespective of whether
835 // this instance is the master or not.
836 defaultRoutingHandler.populatePortAddressingRules(deviceId);
837
Charles Chan2199c302016-04-23 17:36:10 -0700838 if (mastershipService.isLocalMaster(deviceId)) {
839 hostHandler.readInitialHosts(deviceId);
Charles Chanfc5c7802016-05-17 13:13:55 -0700840 xConnectHandler.init(deviceId);
Charles Chan35fd1a72016-06-13 18:54:31 -0700841 cordConfigHandler.init(deviceId);
Charles Chan2199c302016-04-23 17:36:10 -0700842 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
Charles Chanc42e84e2015-10-20 16:24:19 -0700843 groupHandler.createGroupsFromSubnetConfig();
Charles Chan2199c302016-04-23 17:36:10 -0700844 routingRulePopulator.populateSubnetBroadcastRule(deviceId);
Charles Chanc42e84e2015-10-20 16:24:19 -0700845 }
Charles Chan5270ed02016-01-30 23:22:37 -0800846
Charles Chanfc5c7802016-05-17 13:13:55 -0700847 appCfgHandler.initVRouters(deviceId);
sanghob35a6192015-04-01 13:05:26 -0700848 }
849
Saurav Das80980c72016-03-23 11:22:49 -0700850 private void processDeviceRemoved(Device device) {
851 nsNextObjStore.entrySet().stream()
852 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
853 .forEach(entry -> {
854 nsNextObjStore.remove(entry.getKey());
855 });
Saurav Das80980c72016-03-23 11:22:49 -0700856 subnetNextObjStore.entrySet().stream()
857 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
858 .forEach(entry -> {
859 subnetNextObjStore.remove(entry.getKey());
860 });
Saurav Das80980c72016-03-23 11:22:49 -0700861 portNextObjStore.entrySet().stream()
862 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
863 .forEach(entry -> {
864 portNextObjStore.remove(entry.getKey());
865 });
Saurav Das80980c72016-03-23 11:22:49 -0700866 subnetVidStore.entrySet().stream()
867 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
868 .forEach(entry -> {
869 subnetVidStore.remove(entry.getKey());
870 });
Saurav Das80980c72016-03-23 11:22:49 -0700871 groupHandlerMap.remove(device.id());
Saurav Das80980c72016-03-23 11:22:49 -0700872 defaultRoutingHandler.purgeEcmpGraph(device.id());
Charles Chan2199c302016-04-23 17:36:10 -0700873 mcastHandler.removeDevice(device.id());
Charles Chanfc5c7802016-05-17 13:13:55 -0700874 xConnectHandler.removeDevice(device.id());
Saurav Das80980c72016-03-23 11:22:49 -0700875 }
876
sanghob35a6192015-04-01 13:05:26 -0700877 private void processPortRemoved(Device device, Port port) {
Saurav Dasb5c236e2016-06-07 10:08:06 -0700878 log.info("Port {} was removed", port.toString());
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700879 DefaultGroupHandler groupHandler = groupHandlerMap.get(device.id());
sanghob35a6192015-04-01 13:05:26 -0700880 if (groupHandler != null) {
Saurav Das423fe2b2015-12-04 10:52:59 -0800881 groupHandler.portDown(port.number(),
882 mastershipService.isLocalMaster(device.id()));
sanghob35a6192015-04-01 13:05:26 -0700883 }
884 }
sangho1e575652015-05-14 00:39:53 -0700885
Charles Chand6832882015-10-05 17:50:33 -0700886 private class InternalConfigListener implements NetworkConfigListener {
Charles Chan4636be02015-10-07 14:21:45 -0700887 SegmentRoutingManager segmentRoutingManager;
888
Charles Chane849c192016-01-11 18:28:54 -0800889 /**
890 * Constructs the internal network config listener.
891 *
892 * @param srMgr segment routing manager
893 */
Charles Chan4636be02015-10-07 14:21:45 -0700894 public InternalConfigListener(SegmentRoutingManager srMgr) {
895 this.segmentRoutingManager = srMgr;
896 }
897
Charles Chane849c192016-01-11 18:28:54 -0800898 /**
899 * Reads network config and initializes related data structure accordingly.
900 */
Charles Chan4636be02015-10-07 14:21:45 -0700901 public void configureNetwork() {
Charles Chanf2565a92016-02-10 20:46:58 -0800902 deviceConfiguration = new DeviceConfiguration(appId,
903 segmentRoutingManager.cfgService);
Charles Chan4636be02015-10-07 14:21:45 -0700904
905 arpHandler = new ArpHandler(segmentRoutingManager);
906 icmpHandler = new IcmpHandler(segmentRoutingManager);
907 ipHandler = new IpHandler(segmentRoutingManager);
908 routingRulePopulator = new RoutingRulePopulator(segmentRoutingManager);
909 defaultRoutingHandler = new DefaultRoutingHandler(segmentRoutingManager);
910
911 tunnelHandler = new TunnelHandler(linkService, deviceConfiguration,
912 groupHandlerMap, tunnelStore);
913 policyHandler = new PolicyHandler(appId, deviceConfiguration,
914 flowObjectiveService,
915 tunnelHandler, policyStore);
916
Charles Chan4636be02015-10-07 14:21:45 -0700917 for (Device device : deviceService.getDevices()) {
Charles Chan2199c302016-04-23 17:36:10 -0700918 processDeviceAddedInternal(device.id());
Charles Chan4636be02015-10-07 14:21:45 -0700919 }
920
921 defaultRoutingHandler.startPopulationProcess();
Charles Chan2199c302016-04-23 17:36:10 -0700922 mcastHandler.init();
Charles Chan4636be02015-10-07 14:21:45 -0700923 }
924
Charles Chand6832882015-10-05 17:50:33 -0700925 @Override
926 public void event(NetworkConfigEvent event) {
Charles Chan5270ed02016-01-30 23:22:37 -0800927 // TODO move this part to NetworkConfigEventHandler
928 if (event.configClass().equals(SegmentRoutingDeviceConfig.class)) {
929 switch (event.type()) {
930 case CONFIG_ADDED:
931 log.info("Segment Routing Config added.");
932 configureNetwork();
933 break;
934 case CONFIG_UPDATED:
935 log.info("Segment Routing Config updated.");
936 // TODO support dynamic configuration
937 break;
938 default:
939 break;
Charles Chanb8e10c82015-10-14 11:24:40 -0700940 }
Charles Chan5270ed02016-01-30 23:22:37 -0800941 } else if (event.configClass().equals(SegmentRoutingAppConfig.class)) {
Charles Chanfc5c7802016-05-17 13:13:55 -0700942 checkState(appCfgHandler != null, "NetworkConfigEventHandler is not initialized");
Charles Chan5270ed02016-01-30 23:22:37 -0800943 switch (event.type()) {
944 case CONFIG_ADDED:
Charles Chanfc5c7802016-05-17 13:13:55 -0700945 appCfgHandler.processAppConfigAdded(event);
Charles Chan5270ed02016-01-30 23:22:37 -0800946 break;
947 case CONFIG_UPDATED:
Charles Chanfc5c7802016-05-17 13:13:55 -0700948 appCfgHandler.processAppConfigUpdated(event);
Charles Chan5270ed02016-01-30 23:22:37 -0800949 break;
950 case CONFIG_REMOVED:
Charles Chanfc5c7802016-05-17 13:13:55 -0700951 appCfgHandler.processAppConfigRemoved(event);
952 break;
953 default:
954 break;
955 }
956 } else if (event.configClass().equals(XConnectConfig.class)) {
957 checkState(xConnectHandler != null, "XConnectHandler is not initialized");
958 switch (event.type()) {
959 case CONFIG_ADDED:
960 xConnectHandler.processXConnectConfigAdded(event);
961 break;
962 case CONFIG_UPDATED:
963 xConnectHandler.processXConnectConfigUpdated(event);
964 break;
965 case CONFIG_REMOVED:
966 xConnectHandler.processXConnectConfigRemoved(event);
Charles Chan5270ed02016-01-30 23:22:37 -0800967 break;
968 default:
969 break;
Charles Chanb8e10c82015-10-14 11:24:40 -0700970 }
Charles Chand6832882015-10-05 17:50:33 -0700971 }
972 }
973 }
Charles Chan68aa62d2015-11-09 16:37:23 -0800974
975 private class InternalHostListener implements HostListener {
Charles Chan68aa62d2015-11-09 16:37:23 -0800976 @Override
977 public void event(HostEvent event) {
978 // Do not proceed without mastership
979 DeviceId deviceId = event.subject().location().deviceId();
980 if (!mastershipService.isLocalMaster(deviceId)) {
981 return;
982 }
983
984 switch (event.type()) {
985 case HOST_ADDED:
Charles Chand2990362016-04-18 13:44:03 -0700986 hostHandler.processHostAddedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -0800987 break;
988 case HOST_MOVED:
Charles Chand2990362016-04-18 13:44:03 -0700989 hostHandler.processHostMovedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -0800990 break;
991 case HOST_REMOVED:
Charles Chand2990362016-04-18 13:44:03 -0700992 hostHandler.processHostRemoveEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -0800993 break;
994 case HOST_UPDATED:
Charles Chand2990362016-04-18 13:44:03 -0700995 hostHandler.processHostUpdatedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -0800996 break;
997 default:
998 log.warn("Unsupported host event type: {}", event.type());
999 break;
1000 }
1001 }
1002 }
1003
Charles Chand55e84d2016-03-30 17:54:24 -07001004 private class InternalMcastListener implements McastListener {
1005 @Override
1006 public void event(McastEvent event) {
1007 switch (event.type()) {
1008 case SOURCE_ADDED:
Charles Chand2990362016-04-18 13:44:03 -07001009 mcastHandler.processSourceAdded(event);
Charles Chand55e84d2016-03-30 17:54:24 -07001010 break;
1011 case SINK_ADDED:
Charles Chand2990362016-04-18 13:44:03 -07001012 mcastHandler.processSinkAdded(event);
Charles Chand55e84d2016-03-30 17:54:24 -07001013 break;
1014 case SINK_REMOVED:
Charles Chand2990362016-04-18 13:44:03 -07001015 mcastHandler.processSinkRemoved(event);
Charles Chand55e84d2016-03-30 17:54:24 -07001016 break;
1017 case ROUTE_ADDED:
1018 case ROUTE_REMOVED:
1019 default:
1020 break;
1021 }
1022 }
1023 }
Charles Chan35fd1a72016-06-13 18:54:31 -07001024
1025 private class InternalCordConfigListener implements CordConfigListener {
1026 @Override
1027 public void event(CordConfigEvent event) {
1028 switch (event.type()) {
1029 case ACCESS_AGENT_ADDED:
1030 cordConfigHandler.processAccessAgentAddedEvent(event);
1031 break;
1032 case ACCESS_AGENT_UPDATED:
1033 cordConfigHandler.processAccessAgentUpdatedEvent(event);
1034 break;
1035 case ACCESS_AGENT_REMOVED:
1036 cordConfigHandler.processAccessAgentRemovedEvent(event);
1037 break;
1038 case ACCESS_DEVICE_ADDED:
1039 case ACCESS_DEVICE_UPDATED:
1040 case ACCESS_DEVICE_REMOVED:
1041 default:
1042 break;
1043 }
1044 }
1045 }
sanghob35a6192015-04-01 13:05:26 -07001046}