blob: fce63fe92571f6d89eb7b1f5bb74d70e81d48986 [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) {
696 processLinkRemoved((Link) event.subject());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700697 } else if (event.type() == DeviceEvent.Type.DEVICE_ADDED ||
698 event.type() == DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED ||
699 event.type() == DeviceEvent.Type.DEVICE_UPDATED) {
Saurav Das423fe2b2015-12-04 10:52:59 -0800700 DeviceId deviceId = ((Device) event.subject()).id();
701 if (deviceService.isAvailable(deviceId)) {
Saurav Das837e0bb2015-10-30 17:45:38 -0700702 log.info("Processing device event {} for available device {}",
703 event.type(), ((Device) event.subject()).id());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700704 processDeviceAdded((Device) event.subject());
Saurav Das80980c72016-03-23 11:22:49 -0700705 } else {
706 log.info("Processing device event {} for unavailable device {}",
707 event.type(), ((Device) event.subject()).id());
708 processDeviceRemoved((Device) event.subject());
709 }
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700710 } else if (event.type() == DeviceEvent.Type.PORT_REMOVED) {
711 processPortRemoved((Device) event.subject(),
712 ((DeviceEvent) event).port());
Saurav Dasb5c236e2016-06-07 10:08:06 -0700713 } else if (event.type() == DeviceEvent.Type.PORT_ADDED ||
714 event.type() == DeviceEvent.Type.PORT_UPDATED) {
715 log.info("** PORT ADDED OR UPDATED {}/{} -> {}",
Yuta HIGUCHI1624df12016-07-21 16:54:33 -0700716 event.subject(),
Saurav Dasb5c236e2016-06-07 10:08:06 -0700717 ((DeviceEvent) event).port(),
718 event.type());
719 /* XXX create method for single port filtering rules
720 if (defaultRoutingHandler != null) {
721 defaultRoutingHandler.populatePortAddressingRules(
722 ((Device) event.subject()).id());
723 }*/
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700724 } else {
725 log.warn("Unhandled event type: {}", event.type());
726 }
sanghob35a6192015-04-01 13:05:26 -0700727 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700728 } catch (Exception e) {
729 log.error("SegmentRouting event handler "
730 + "thread thrown an exception: {}", e);
sanghob35a6192015-04-01 13:05:26 -0700731 }
sanghob35a6192015-04-01 13:05:26 -0700732 }
733 }
734
sanghob35a6192015-04-01 13:05:26 -0700735 private void processLinkAdded(Link link) {
Saurav Dasb5c236e2016-06-07 10:08:06 -0700736 log.info("** LINK ADDED {}", link.toString());
Charles Chan0b4e6182015-11-03 10:42:14 -0800737 if (!deviceConfiguration.isConfigured(link.src().deviceId())) {
738 log.warn("Source device of this link is not configured.");
739 return;
740 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700741 //Irrespective whether the local is a MASTER or not for this device,
742 //create group handler instance and push default TTP flow rules.
743 //Because in a multi-instance setup, instances can initiate
744 //groups for any devices. Also the default TTP rules are needed
745 //to be pushed before inserting any IP table entries for any device
746 DefaultGroupHandler groupHandler = groupHandlerMap.get(link.src()
747 .deviceId());
748 if (groupHandler != null) {
Saurav Das8a0732e2015-11-20 15:27:53 -0800749 groupHandler.linkUp(link, mastershipService.isLocalMaster(
750 link.src().deviceId()));
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700751 } else {
752 Device device = deviceService.getDevice(link.src().deviceId());
753 if (device != null) {
754 log.warn("processLinkAdded: Link Added "
755 + "Notification without Device Added "
756 + "event, still handling it");
757 processDeviceAdded(device);
758 groupHandler = groupHandlerMap.get(link.src()
759 .deviceId());
Saurav Das8a0732e2015-11-20 15:27:53 -0800760 groupHandler.linkUp(link, mastershipService.isLocalMaster(device.id()));
sanghob35a6192015-04-01 13:05:26 -0700761 }
762 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700763
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700764 log.trace("Starting optimized route population process");
765 defaultRoutingHandler.populateRoutingRulesForLinkStatusChange(null);
766 //log.trace("processLinkAdded: re-starting route population process");
767 //defaultRoutingHandler.startPopulationProcess();
Charles Chan2199c302016-04-23 17:36:10 -0700768
769 mcastHandler.init();
sanghob35a6192015-04-01 13:05:26 -0700770 }
771
772 private void processLinkRemoved(Link link) {
Saurav Dasb5c236e2016-06-07 10:08:06 -0700773 log.info("** LINK REMOVED {}", link.toString());
sangho834e4b02015-05-01 09:38:25 -0700774 DefaultGroupHandler groupHandler = groupHandlerMap.get(link.src().deviceId());
775 if (groupHandler != null) {
Saurav Das423fe2b2015-12-04 10:52:59 -0800776 groupHandler.portDown(link.src().port(),
777 mastershipService.isLocalMaster(link.src().deviceId()));
sangho834e4b02015-05-01 09:38:25 -0700778 }
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700779 log.trace("Starting optimized route population process");
780 defaultRoutingHandler.populateRoutingRulesForLinkStatusChange(link);
781 //log.trace("processLinkRemoved: re-starting route population process");
782 //defaultRoutingHandler.startPopulationProcess();
Charles Chan2199c302016-04-23 17:36:10 -0700783
784 mcastHandler.processLinkDown(link);
sanghob35a6192015-04-01 13:05:26 -0700785 }
786
787 private void processDeviceAdded(Device device) {
Saurav Dasb5c236e2016-06-07 10:08:06 -0700788 log.info("** DEVICE ADDED with ID {}", device.id());
Charles Chan0b4e6182015-11-03 10:42:14 -0800789 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
Saurav Das2857f382015-11-03 14:39:27 -0800790 log.warn("Device configuration uploading. Device {} will be "
791 + "processed after config completes.", device.id());
792 return;
793 }
Charles Chan2199c302016-04-23 17:36:10 -0700794 processDeviceAddedInternal(device.id());
795 }
796
797 private void processDeviceAddedInternal(DeviceId deviceId) {
Saurav Das837e0bb2015-10-30 17:45:38 -0700798 // Irrespective of whether the local is a MASTER or not for this device,
799 // we need to create a SR-group-handler instance. This is because in a
800 // multi-instance setup, any instance can initiate forwarding/next-objectives
801 // for any switch (even if this instance is a SLAVE or not even connected
802 // to the switch). To handle this, a default-group-handler instance is necessary
803 // per switch.
Charles Chan2199c302016-04-23 17:36:10 -0700804 log.debug("Current groupHandlerMap devs: {}", groupHandlerMap.keySet());
805 if (groupHandlerMap.get(deviceId) == null) {
Charles Chan0b4e6182015-11-03 10:42:14 -0800806 DefaultGroupHandler groupHandler;
807 try {
808 groupHandler = DefaultGroupHandler.
Charles Chan2199c302016-04-23 17:36:10 -0700809 createGroupHandler(deviceId,
810 appId,
811 deviceConfiguration,
812 linkService,
813 flowObjectiveService,
814 this);
Charles Chan0b4e6182015-11-03 10:42:14 -0800815 } catch (DeviceConfigNotFoundException e) {
816 log.warn(e.getMessage() + " Aborting processDeviceAdded.");
817 return;
818 }
Charles Chan2199c302016-04-23 17:36:10 -0700819 log.debug("updating groupHandlerMap with new config for device: {}",
820 deviceId);
821 groupHandlerMap.put(deviceId, groupHandler);
Saurav Das2857f382015-11-03 14:39:27 -0800822 }
Saurav Dasb5c236e2016-06-07 10:08:06 -0700823 // Also, in some cases, drivers may need extra
824 // information to process rules (eg. Router IP/MAC); and so, we send
825 // port addressing rules to the driver as well irrespective of whether
826 // this instance is the master or not.
827 defaultRoutingHandler.populatePortAddressingRules(deviceId);
828
Charles Chan2199c302016-04-23 17:36:10 -0700829 if (mastershipService.isLocalMaster(deviceId)) {
830 hostHandler.readInitialHosts(deviceId);
Charles Chanfc5c7802016-05-17 13:13:55 -0700831 xConnectHandler.init(deviceId);
Charles Chan35fd1a72016-06-13 18:54:31 -0700832 cordConfigHandler.init(deviceId);
Charles Chan2199c302016-04-23 17:36:10 -0700833 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
Charles Chanc42e84e2015-10-20 16:24:19 -0700834 groupHandler.createGroupsFromSubnetConfig();
Charles Chan2199c302016-04-23 17:36:10 -0700835 routingRulePopulator.populateSubnetBroadcastRule(deviceId);
Charles Chanc42e84e2015-10-20 16:24:19 -0700836 }
Charles Chan5270ed02016-01-30 23:22:37 -0800837
Charles Chanfc5c7802016-05-17 13:13:55 -0700838 appCfgHandler.initVRouters(deviceId);
sanghob35a6192015-04-01 13:05:26 -0700839 }
840
Saurav Das80980c72016-03-23 11:22:49 -0700841 private void processDeviceRemoved(Device device) {
842 nsNextObjStore.entrySet().stream()
843 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
844 .forEach(entry -> {
845 nsNextObjStore.remove(entry.getKey());
846 });
Saurav Das80980c72016-03-23 11:22:49 -0700847 subnetNextObjStore.entrySet().stream()
848 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
849 .forEach(entry -> {
850 subnetNextObjStore.remove(entry.getKey());
851 });
Saurav Das80980c72016-03-23 11:22:49 -0700852 portNextObjStore.entrySet().stream()
853 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
854 .forEach(entry -> {
855 portNextObjStore.remove(entry.getKey());
856 });
Saurav Das80980c72016-03-23 11:22:49 -0700857 subnetVidStore.entrySet().stream()
858 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
859 .forEach(entry -> {
860 subnetVidStore.remove(entry.getKey());
861 });
Saurav Das80980c72016-03-23 11:22:49 -0700862 groupHandlerMap.remove(device.id());
Saurav Das80980c72016-03-23 11:22:49 -0700863 defaultRoutingHandler.purgeEcmpGraph(device.id());
Charles Chan2199c302016-04-23 17:36:10 -0700864 mcastHandler.removeDevice(device.id());
Charles Chanfc5c7802016-05-17 13:13:55 -0700865 xConnectHandler.removeDevice(device.id());
Saurav Das80980c72016-03-23 11:22:49 -0700866 }
867
sanghob35a6192015-04-01 13:05:26 -0700868 private void processPortRemoved(Device device, Port port) {
Saurav Dasb5c236e2016-06-07 10:08:06 -0700869 log.info("Port {} was removed", port.toString());
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700870 DefaultGroupHandler groupHandler = groupHandlerMap.get(device.id());
sanghob35a6192015-04-01 13:05:26 -0700871 if (groupHandler != null) {
Saurav Das423fe2b2015-12-04 10:52:59 -0800872 groupHandler.portDown(port.number(),
873 mastershipService.isLocalMaster(device.id()));
sanghob35a6192015-04-01 13:05:26 -0700874 }
875 }
sangho1e575652015-05-14 00:39:53 -0700876
Charles Chand6832882015-10-05 17:50:33 -0700877 private class InternalConfigListener implements NetworkConfigListener {
Charles Chan4636be02015-10-07 14:21:45 -0700878 SegmentRoutingManager segmentRoutingManager;
879
Charles Chane849c192016-01-11 18:28:54 -0800880 /**
881 * Constructs the internal network config listener.
882 *
883 * @param srMgr segment routing manager
884 */
Charles Chan4636be02015-10-07 14:21:45 -0700885 public InternalConfigListener(SegmentRoutingManager srMgr) {
886 this.segmentRoutingManager = srMgr;
887 }
888
Charles Chane849c192016-01-11 18:28:54 -0800889 /**
890 * Reads network config and initializes related data structure accordingly.
891 */
Charles Chan4636be02015-10-07 14:21:45 -0700892 public void configureNetwork() {
Charles Chanf2565a92016-02-10 20:46:58 -0800893 deviceConfiguration = new DeviceConfiguration(appId,
894 segmentRoutingManager.cfgService);
Charles Chan4636be02015-10-07 14:21:45 -0700895
896 arpHandler = new ArpHandler(segmentRoutingManager);
897 icmpHandler = new IcmpHandler(segmentRoutingManager);
898 ipHandler = new IpHandler(segmentRoutingManager);
899 routingRulePopulator = new RoutingRulePopulator(segmentRoutingManager);
900 defaultRoutingHandler = new DefaultRoutingHandler(segmentRoutingManager);
901
902 tunnelHandler = new TunnelHandler(linkService, deviceConfiguration,
903 groupHandlerMap, tunnelStore);
904 policyHandler = new PolicyHandler(appId, deviceConfiguration,
905 flowObjectiveService,
906 tunnelHandler, policyStore);
907
Charles Chan4636be02015-10-07 14:21:45 -0700908 for (Device device : deviceService.getDevices()) {
Charles Chan2199c302016-04-23 17:36:10 -0700909 processDeviceAddedInternal(device.id());
Charles Chan4636be02015-10-07 14:21:45 -0700910 }
911
912 defaultRoutingHandler.startPopulationProcess();
Charles Chan2199c302016-04-23 17:36:10 -0700913 mcastHandler.init();
Charles Chan4636be02015-10-07 14:21:45 -0700914 }
915
Charles Chand6832882015-10-05 17:50:33 -0700916 @Override
917 public void event(NetworkConfigEvent event) {
Charles Chan5270ed02016-01-30 23:22:37 -0800918 // TODO move this part to NetworkConfigEventHandler
919 if (event.configClass().equals(SegmentRoutingDeviceConfig.class)) {
920 switch (event.type()) {
921 case CONFIG_ADDED:
922 log.info("Segment Routing Config added.");
923 configureNetwork();
924 break;
925 case CONFIG_UPDATED:
926 log.info("Segment Routing Config updated.");
927 // TODO support dynamic configuration
928 break;
929 default:
930 break;
Charles Chanb8e10c82015-10-14 11:24:40 -0700931 }
Charles Chan5270ed02016-01-30 23:22:37 -0800932 } else if (event.configClass().equals(SegmentRoutingAppConfig.class)) {
Charles Chanfc5c7802016-05-17 13:13:55 -0700933 checkState(appCfgHandler != null, "NetworkConfigEventHandler is not initialized");
Charles Chan5270ed02016-01-30 23:22:37 -0800934 switch (event.type()) {
935 case CONFIG_ADDED:
Charles Chanfc5c7802016-05-17 13:13:55 -0700936 appCfgHandler.processAppConfigAdded(event);
Charles Chan5270ed02016-01-30 23:22:37 -0800937 break;
938 case CONFIG_UPDATED:
Charles Chanfc5c7802016-05-17 13:13:55 -0700939 appCfgHandler.processAppConfigUpdated(event);
Charles Chan5270ed02016-01-30 23:22:37 -0800940 break;
941 case CONFIG_REMOVED:
Charles Chanfc5c7802016-05-17 13:13:55 -0700942 appCfgHandler.processAppConfigRemoved(event);
943 break;
944 default:
945 break;
946 }
947 } else if (event.configClass().equals(XConnectConfig.class)) {
948 checkState(xConnectHandler != null, "XConnectHandler is not initialized");
949 switch (event.type()) {
950 case CONFIG_ADDED:
951 xConnectHandler.processXConnectConfigAdded(event);
952 break;
953 case CONFIG_UPDATED:
954 xConnectHandler.processXConnectConfigUpdated(event);
955 break;
956 case CONFIG_REMOVED:
957 xConnectHandler.processXConnectConfigRemoved(event);
Charles Chan5270ed02016-01-30 23:22:37 -0800958 break;
959 default:
960 break;
Charles Chanb8e10c82015-10-14 11:24:40 -0700961 }
Charles Chand6832882015-10-05 17:50:33 -0700962 }
963 }
964 }
Charles Chan68aa62d2015-11-09 16:37:23 -0800965
966 private class InternalHostListener implements HostListener {
Charles Chan68aa62d2015-11-09 16:37:23 -0800967 @Override
968 public void event(HostEvent event) {
969 // Do not proceed without mastership
970 DeviceId deviceId = event.subject().location().deviceId();
971 if (!mastershipService.isLocalMaster(deviceId)) {
972 return;
973 }
974
975 switch (event.type()) {
976 case HOST_ADDED:
Charles Chand2990362016-04-18 13:44:03 -0700977 hostHandler.processHostAddedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -0800978 break;
979 case HOST_MOVED:
Charles Chand2990362016-04-18 13:44:03 -0700980 hostHandler.processHostMovedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -0800981 break;
982 case HOST_REMOVED:
Charles Chand2990362016-04-18 13:44:03 -0700983 hostHandler.processHostRemoveEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -0800984 break;
985 case HOST_UPDATED:
Charles Chand2990362016-04-18 13:44:03 -0700986 hostHandler.processHostUpdatedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -0800987 break;
988 default:
989 log.warn("Unsupported host event type: {}", event.type());
990 break;
991 }
992 }
993 }
994
Charles Chand55e84d2016-03-30 17:54:24 -0700995 private class InternalMcastListener implements McastListener {
996 @Override
997 public void event(McastEvent event) {
998 switch (event.type()) {
999 case SOURCE_ADDED:
Charles Chand2990362016-04-18 13:44:03 -07001000 mcastHandler.processSourceAdded(event);
Charles Chand55e84d2016-03-30 17:54:24 -07001001 break;
1002 case SINK_ADDED:
Charles Chand2990362016-04-18 13:44:03 -07001003 mcastHandler.processSinkAdded(event);
Charles Chand55e84d2016-03-30 17:54:24 -07001004 break;
1005 case SINK_REMOVED:
Charles Chand2990362016-04-18 13:44:03 -07001006 mcastHandler.processSinkRemoved(event);
Charles Chand55e84d2016-03-30 17:54:24 -07001007 break;
1008 case ROUTE_ADDED:
1009 case ROUTE_REMOVED:
1010 default:
1011 break;
1012 }
1013 }
1014 }
Charles Chan35fd1a72016-06-13 18:54:31 -07001015
1016 private class InternalCordConfigListener implements CordConfigListener {
1017 @Override
1018 public void event(CordConfigEvent event) {
1019 switch (event.type()) {
1020 case ACCESS_AGENT_ADDED:
1021 cordConfigHandler.processAccessAgentAddedEvent(event);
1022 break;
1023 case ACCESS_AGENT_UPDATED:
1024 cordConfigHandler.processAccessAgentUpdatedEvent(event);
1025 break;
1026 case ACCESS_AGENT_REMOVED:
1027 cordConfigHandler.processAccessAgentRemovedEvent(event);
1028 break;
1029 case ACCESS_DEVICE_ADDED:
1030 case ACCESS_DEVICE_UPDATED:
1031 case ACCESS_DEVICE_REMOVED:
1032 default:
1033 break;
1034 }
1035 }
1036 }
sanghob35a6192015-04-01 13:05:26 -07001037}