blob: e6c324d23dd116f129ec644e77633aeb6b3d32b0 [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;
64import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
65import org.onosproject.segmentrouting.grouphandler.NeighborSet;
Charles Chand2990362016-04-18 13:44:03 -070066import org.onosproject.segmentrouting.storekey.NeighborSetNextObjectiveStoreKey;
67import org.onosproject.segmentrouting.storekey.PortNextObjectiveStoreKey;
sanghob35a6192015-04-01 13:05:26 -070068import org.onosproject.net.host.HostService;
sanghob35a6192015-04-01 13:05:26 -070069import org.onosproject.net.link.LinkEvent;
70import org.onosproject.net.link.LinkListener;
71import org.onosproject.net.link.LinkService;
72import org.onosproject.net.packet.InboundPacket;
73import org.onosproject.net.packet.PacketContext;
74import org.onosproject.net.packet.PacketProcessor;
75import org.onosproject.net.packet.PacketService;
Charles Chand2990362016-04-18 13:44:03 -070076import org.onosproject.segmentrouting.storekey.SubnetAssignedVidStoreKey;
77import org.onosproject.segmentrouting.storekey.SubnetNextObjectiveStoreKey;
78import org.onosproject.segmentrouting.storekey.XConnectNextObjectiveStoreKey;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070079import org.onosproject.store.serializers.KryoNamespaces;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -070080import org.onosproject.store.service.EventuallyConsistentMap;
81import org.onosproject.store.service.EventuallyConsistentMapBuilder;
82import org.onosproject.store.service.StorageService;
83import org.onosproject.store.service.WallClockTimestamp;
sanghob35a6192015-04-01 13:05:26 -070084import org.slf4j.Logger;
85import org.slf4j.LoggerFactory;
86
Saurav Das0e99e2b2015-10-28 12:39:42 -070087import java.util.Collections;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -070088import java.util.HashSet;
sangho1e575652015-05-14 00:39:53 -070089import java.util.List;
sanghob35a6192015-04-01 13:05:26 -070090import java.util.Map;
Charles Chan188ebf52015-12-23 00:15:11 -080091import java.util.Optional;
Saurav Das0e99e2b2015-10-28 12:39:42 -070092import java.util.Set;
sanghob35a6192015-04-01 13:05:26 -070093import java.util.concurrent.ConcurrentHashMap;
94import java.util.concurrent.ConcurrentLinkedQueue;
95import java.util.concurrent.Executors;
96import java.util.concurrent.ScheduledExecutorService;
97import java.util.concurrent.ScheduledFuture;
98import java.util.concurrent.TimeUnit;
99
Charles Chan3e783d02016-02-26 22:19:52 -0800100import static com.google.common.base.Preconditions.checkState;
101
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700102
Charles Chane849c192016-01-11 18:28:54 -0800103/**
104 * Segment routing manager.
105 */
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700106@Service
107@Component(immediate = true)
sangho1e575652015-05-14 00:39:53 -0700108public class SegmentRoutingManager implements SegmentRoutingService {
sanghob35a6192015-04-01 13:05:26 -0700109
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700110 private static Logger log = LoggerFactory
111 .getLogger(SegmentRoutingManager.class);
sanghob35a6192015-04-01 13:05:26 -0700112
113 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
114 protected CoreService coreService;
115
116 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
sanghob35a6192015-04-01 13:05:26 -0700117 protected PacketService packetService;
118
119 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
sanghob35a6192015-04-01 13:05:26 -0700120 protected HostService hostService;
121
122 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
123 protected DeviceService deviceService;
124
125 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700126 protected FlowObjectiveService flowObjectiveService;
sanghob35a6192015-04-01 13:05:26 -0700127
128 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
129 protected LinkService linkService;
130
131 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
sanghob35a6192015-04-01 13:05:26 -0700132 protected MastershipService mastershipService;
sangho1e575652015-05-14 00:39:53 -0700133
Charles Chan5270ed02016-01-30 23:22:37 -0800134 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
135 protected StorageService storageService;
136
137 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
138 protected NetworkConfigRegistry cfgService;
139
Saurav Das80980c72016-03-23 11:22:49 -0700140 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
141 protected ComponentConfigService compCfgService;
142
Charles Chand55e84d2016-03-30 17:54:24 -0700143 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
144 protected MulticastRouteService multicastRouteService;
145
146 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
147 protected TopologyService topologyService;
148
Srikanth Vavilapalli4db76e32015-04-07 15:12:32 -0700149 protected ArpHandler arpHandler = null;
150 protected IcmpHandler icmpHandler = null;
151 protected IpHandler ipHandler = null;
152 protected RoutingRulePopulator routingRulePopulator = null;
sanghob35a6192015-04-01 13:05:26 -0700153 protected ApplicationId appId;
sangho666cd6d2015-04-14 16:27:13 -0700154 protected DeviceConfiguration deviceConfiguration = null;
sanghob35a6192015-04-01 13:05:26 -0700155
Srikanth Vavilapalli4db76e32015-04-07 15:12:32 -0700156 private DefaultRoutingHandler defaultRoutingHandler = null;
sangho1e575652015-05-14 00:39:53 -0700157 private TunnelHandler tunnelHandler = null;
158 private PolicyHandler policyHandler = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700159 private InternalPacketProcessor processor = null;
160 private InternalLinkListener linkListener = null;
161 private InternalDeviceListener deviceListener = null;
Charles Chan5270ed02016-01-30 23:22:37 -0800162 private NetworkConfigEventHandler netcfgHandler = null;
Charles Chand2990362016-04-18 13:44:03 -0700163 private McastHandler mcastHandler = null;
164 private HostHandler hostHandler = null;
sanghob35a6192015-04-01 13:05:26 -0700165 private InternalEventHandler eventHandler = new InternalEventHandler();
Charles Chan5270ed02016-01-30 23:22:37 -0800166 private final InternalHostListener hostListener = new InternalHostListener();
Charles Chand55e84d2016-03-30 17:54:24 -0700167 private final InternalConfigListener cfgListener = new InternalConfigListener(this);
168 private final InternalMcastListener mcastListener = new InternalMcastListener();
sanghob35a6192015-04-01 13:05:26 -0700169
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700170 private ScheduledExecutorService executorService = Executors
171 .newScheduledThreadPool(1);
sanghob35a6192015-04-01 13:05:26 -0700172
Saurav Das4ce45962015-11-24 23:21:05 -0800173 @SuppressWarnings("unused")
sanghob35a6192015-04-01 13:05:26 -0700174 private static ScheduledFuture<?> eventHandlerFuture = null;
Saurav Das4ce45962015-11-24 23:21:05 -0800175 @SuppressWarnings("rawtypes")
sanghob35a6192015-04-01 13:05:26 -0700176 private ConcurrentLinkedQueue<Event> eventQueue = new ConcurrentLinkedQueue<Event>();
Charles Chan68aa62d2015-11-09 16:37:23 -0800177 private Map<DeviceId, DefaultGroupHandler> groupHandlerMap =
Charles Chane849c192016-01-11 18:28:54 -0800178 new ConcurrentHashMap<>();
179 /**
180 * Per device next objective ID store with (device id + neighbor set) as key.
181 */
182 public EventuallyConsistentMap<NeighborSetNextObjectiveStoreKey, Integer>
Charles Chan68aa62d2015-11-09 16:37:23 -0800183 nsNextObjStore = null;
Charles Chane849c192016-01-11 18:28:54 -0800184 /**
185 * Per device next objective ID store with (device id + subnet) as key.
186 */
187 public EventuallyConsistentMap<SubnetNextObjectiveStoreKey, Integer>
Charles Chan68aa62d2015-11-09 16:37:23 -0800188 subnetNextObjStore = null;
Charles Chane849c192016-01-11 18:28:54 -0800189 /**
190 * Per device next objective ID store with (device id + port) as key.
191 */
192 public EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer>
Saurav Das4ce45962015-11-24 23:21:05 -0800193 portNextObjStore = null;
Charles Chane849c192016-01-11 18:28:54 -0800194 /**
195 * Per cross-connect objective ID store with VLAN ID as key.
196 */
197 public EventuallyConsistentMap<XConnectNextObjectiveStoreKey, Integer>
198 xConnectNextObjStore = null;
Saurav Das0e99e2b2015-10-28 12:39:42 -0700199 // Per device, per-subnet assigned-vlans store, with (device id + subnet
200 // IPv4 prefix) as key
201 private EventuallyConsistentMap<SubnetAssignedVidStoreKey, VlanId>
Charles Chane849c192016-01-11 18:28:54 -0800202 subnetVidStore = null;
Saurav Das4ce45962015-11-24 23:21:05 -0800203 private EventuallyConsistentMap<String, Tunnel> tunnelStore = null;
204 private EventuallyConsistentMap<String, Policy> policyStore = null;
sangho0b2b6d12015-05-20 22:16:38 -0700205
Charles Chand55e84d2016-03-30 17:54:24 -0700206 private final ConfigFactory<DeviceId, SegmentRoutingDeviceConfig> deviceConfigFactory =
Charles Chan5270ed02016-01-30 23:22:37 -0800207 new ConfigFactory<DeviceId, SegmentRoutingDeviceConfig>(SubjectFactories.DEVICE_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700208 SegmentRoutingDeviceConfig.class, "segmentrouting") {
Charles Chand6832882015-10-05 17:50:33 -0700209 @Override
Charles Chan5270ed02016-01-30 23:22:37 -0800210 public SegmentRoutingDeviceConfig createConfig() {
211 return new SegmentRoutingDeviceConfig();
Charles Chand6832882015-10-05 17:50:33 -0700212 }
213 };
Charles Chand55e84d2016-03-30 17:54:24 -0700214 private final ConfigFactory<ApplicationId, SegmentRoutingAppConfig> appConfigFactory =
Charles Chan5270ed02016-01-30 23:22:37 -0800215 new ConfigFactory<ApplicationId, SegmentRoutingAppConfig>(SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700216 SegmentRoutingAppConfig.class, "segmentrouting") {
Charles Chan5270ed02016-01-30 23:22:37 -0800217 @Override
218 public SegmentRoutingAppConfig createConfig() {
219 return new SegmentRoutingAppConfig();
220 }
221 };
Charles Chan68aa62d2015-11-09 16:37:23 -0800222
Charles Chand55e84d2016-03-30 17:54:24 -0700223 private ConfigFactory<ApplicationId, McastConfig> mcastConfigFactory =
224 new ConfigFactory<ApplicationId, McastConfig>(SubjectFactories.APP_SUBJECT_FACTORY,
225 McastConfig.class, "multicast") {
226 @Override
227 public McastConfig createConfig() {
228 return new McastConfig();
229 }
230 };
231
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700232 private Object threadSchedulerLock = new Object();
233 private static int numOfEventsQueued = 0;
234 private static int numOfEventsExecuted = 0;
sanghob35a6192015-04-01 13:05:26 -0700235 private static int numOfHandlerExecution = 0;
236 private static int numOfHandlerScheduled = 0;
237
Charles Chan116188d2016-02-18 14:22:42 -0800238 /**
239 * Segment Routing App ID.
240 */
241 public static final String SR_APP_ID = "org.onosproject.segmentrouting";
Charles Chane849c192016-01-11 18:28:54 -0800242 /**
243 * The starting value of per-subnet VLAN ID assignment.
244 */
Saurav Das0e99e2b2015-10-28 12:39:42 -0700245 private static final short ASSIGNED_VLAN_START = 4093;
Charles Chane849c192016-01-11 18:28:54 -0800246 /**
247 * The default VLAN ID assigned to the interfaces without subnet config.
248 */
Saurav Das0e99e2b2015-10-28 12:39:42 -0700249 public static final short ASSIGNED_VLAN_NO_SUBNET = 4094;
250
sanghob35a6192015-04-01 13:05:26 -0700251 @Activate
252 protected void activate() {
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700253 appId = coreService.registerApplication(SR_APP_ID);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700254
255 log.debug("Creating EC map nsnextobjectivestore");
256 EventuallyConsistentMapBuilder<NeighborSetNextObjectiveStoreKey, Integer>
257 nsNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700258 nsNextObjStore = nsNextObjMapBuilder
259 .withName("nsnextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700260 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700261 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700262 .build();
263 log.trace("Current size {}", nsNextObjStore.size());
264
Charles Chanc42e84e2015-10-20 16:24:19 -0700265 log.debug("Creating EC map subnetnextobjectivestore");
266 EventuallyConsistentMapBuilder<SubnetNextObjectiveStoreKey, Integer>
267 subnetNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
Charles Chanc42e84e2015-10-20 16:24:19 -0700268 subnetNextObjStore = subnetNextObjMapBuilder
269 .withName("subnetnextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700270 .withSerializer(createSerializer())
Charles Chanc42e84e2015-10-20 16:24:19 -0700271 .withTimestampProvider((k, v) -> new WallClockTimestamp())
272 .build();
273
Saurav Das4ce45962015-11-24 23:21:05 -0800274 log.debug("Creating EC map subnetnextobjectivestore");
275 EventuallyConsistentMapBuilder<PortNextObjectiveStoreKey, Integer>
276 portNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
277 portNextObjStore = portNextObjMapBuilder
278 .withName("portnextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700279 .withSerializer(createSerializer())
Saurav Das4ce45962015-11-24 23:21:05 -0800280 .withTimestampProvider((k, v) -> new WallClockTimestamp())
281 .build();
282
Charles Chane849c192016-01-11 18:28:54 -0800283 log.debug("Creating EC map xconnectnextobjectivestore");
284 EventuallyConsistentMapBuilder<XConnectNextObjectiveStoreKey, Integer>
285 xConnectNextObjStoreBuilder = storageService.eventuallyConsistentMapBuilder();
286 xConnectNextObjStore = xConnectNextObjStoreBuilder
287 .withName("xconnectnextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700288 .withSerializer(createSerializer())
Charles Chane849c192016-01-11 18:28:54 -0800289 .withTimestampProvider((k, v) -> new WallClockTimestamp())
290 .build();
291
sangho0b2b6d12015-05-20 22:16:38 -0700292 EventuallyConsistentMapBuilder<String, Tunnel> tunnelMapBuilder =
293 storageService.eventuallyConsistentMapBuilder();
sangho0b2b6d12015-05-20 22:16:38 -0700294 tunnelStore = tunnelMapBuilder
295 .withName("tunnelstore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700296 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700297 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho0b2b6d12015-05-20 22:16:38 -0700298 .build();
299
300 EventuallyConsistentMapBuilder<String, Policy> policyMapBuilder =
301 storageService.eventuallyConsistentMapBuilder();
sangho0b2b6d12015-05-20 22:16:38 -0700302 policyStore = policyMapBuilder
303 .withName("policystore")
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
Saurav Das0e99e2b2015-10-28 12:39:42 -0700308 EventuallyConsistentMapBuilder<SubnetAssignedVidStoreKey, VlanId>
309 subnetVidStoreMapBuilder = storageService.eventuallyConsistentMapBuilder();
Saurav Das0e99e2b2015-10-28 12:39:42 -0700310 subnetVidStore = subnetVidStoreMapBuilder
311 .withName("subnetvidstore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700312 .withSerializer(createSerializer())
Saurav Das0e99e2b2015-10-28 12:39:42 -0700313 .withTimestampProvider((k, v) -> new WallClockTimestamp())
314 .build();
315
Saurav Das80980c72016-03-23 11:22:49 -0700316 compCfgService.preSetProperty("org.onosproject.net.group.impl.GroupManager",
317 "purgeOnDisconnection", "true");
318 compCfgService.preSetProperty("org.onosproject.net.flow.impl.FlowRuleManager",
319 "purgeOnDisconnection", "true");
320
Charles Chanb8e10c82015-10-14 11:24:40 -0700321 processor = new InternalPacketProcessor();
322 linkListener = new InternalLinkListener();
323 deviceListener = new InternalDeviceListener();
Charles Chan5270ed02016-01-30 23:22:37 -0800324 netcfgHandler = new NetworkConfigEventHandler(this);
Charles Chand2990362016-04-18 13:44:03 -0700325 mcastHandler = new McastHandler(this);
326 hostHandler = new HostHandler(this);
Charles Chanb8e10c82015-10-14 11:24:40 -0700327
Charles Chan3e783d02016-02-26 22:19:52 -0800328 cfgService.addListener(cfgListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700329 cfgService.registerConfigFactory(deviceConfigFactory);
330 cfgService.registerConfigFactory(appConfigFactory);
331 cfgService.registerConfigFactory(mcastConfigFactory);
Charles Chan5270ed02016-01-30 23:22:37 -0800332 hostService.addListener(hostListener);
Charles Chanb8e10c82015-10-14 11:24:40 -0700333 packetService.addProcessor(processor, PacketProcessor.director(2));
334 linkService.addListener(linkListener);
335 deviceService.addListener(deviceListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700336 multicastRouteService.addListener(mcastListener);
Charles Chanb8e10c82015-10-14 11:24:40 -0700337
Charles Chan188ebf52015-12-23 00:15:11 -0800338 // Request ARP packet-in
339 TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
340 selector.matchEthType(Ethernet.TYPE_ARP);
341 packetService.requestPackets(selector.build(), PacketPriority.CONTROL, appId, Optional.empty());
342
Charles Chanb8e10c82015-10-14 11:24:40 -0700343 cfgListener.configureNetwork();
344
sanghob35a6192015-04-01 13:05:26 -0700345 log.info("Started");
346 }
347
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700348 private KryoNamespace.Builder createSerializer() {
349 return new KryoNamespace.Builder()
350 .register(KryoNamespaces.API)
351 .register(NeighborSetNextObjectiveStoreKey.class,
352 SubnetNextObjectiveStoreKey.class,
353 SubnetAssignedVidStoreKey.class,
354 NeighborSet.class,
355 Tunnel.class,
356 DefaultTunnel.class,
357 Policy.class,
358 TunnelPolicy.class,
359 Policy.Type.class,
360 PortNextObjectiveStoreKey.class,
361 XConnectNextObjectiveStoreKey.class
362 );
363 }
364
sanghob35a6192015-04-01 13:05:26 -0700365 @Deactivate
366 protected void deactivate() {
Charles Chand6832882015-10-05 17:50:33 -0700367 cfgService.removeListener(cfgListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700368 cfgService.unregisterConfigFactory(deviceConfigFactory);
369 cfgService.unregisterConfigFactory(appConfigFactory);
370 cfgService.unregisterConfigFactory(mcastConfigFactory);
Charles Chand6832882015-10-05 17:50:33 -0700371
Charles Chan188ebf52015-12-23 00:15:11 -0800372 // Withdraw ARP packet-in
373 TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
374 selector.matchEthType(Ethernet.TYPE_ARP);
375 packetService.cancelPackets(selector.build(), PacketPriority.CONTROL, appId, Optional.empty());
376
sanghob35a6192015-04-01 13:05:26 -0700377 packetService.removeProcessor(processor);
Charles Chanb8e10c82015-10-14 11:24:40 -0700378 linkService.removeListener(linkListener);
379 deviceService.removeListener(deviceListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700380 multicastRouteService.removeListener(mcastListener);
381
sanghob35a6192015-04-01 13:05:26 -0700382 processor = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700383 linkListener = null;
Charles Chand55e84d2016-03-30 17:54:24 -0700384 deviceListener = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700385 groupHandlerMap.clear();
386
Charles Chand55e84d2016-03-30 17:54:24 -0700387 nsNextObjStore.destroy();
388 subnetNextObjStore.destroy();
389 portNextObjStore.destroy();
390 xConnectNextObjStore.destroy();
391 tunnelStore.destroy();
392 policyStore.destroy();
393 subnetVidStore.destroy();
sanghob35a6192015-04-01 13:05:26 -0700394 log.info("Stopped");
395 }
396
sangho1e575652015-05-14 00:39:53 -0700397
398 @Override
399 public List<Tunnel> getTunnels() {
400 return tunnelHandler.getTunnels();
401 }
402
403 @Override
sangho71abe1b2015-06-29 14:58:47 -0700404 public TunnelHandler.Result createTunnel(Tunnel tunnel) {
405 return tunnelHandler.createTunnel(tunnel);
sangho1e575652015-05-14 00:39:53 -0700406 }
407
408 @Override
sangho71abe1b2015-06-29 14:58:47 -0700409 public TunnelHandler.Result removeTunnel(Tunnel tunnel) {
sangho1e575652015-05-14 00:39:53 -0700410 for (Policy policy: policyHandler.getPolicies()) {
411 if (policy.type() == Policy.Type.TUNNEL_FLOW) {
412 TunnelPolicy tunnelPolicy = (TunnelPolicy) policy;
413 if (tunnelPolicy.tunnelId().equals(tunnel.id())) {
414 log.warn("Cannot remove the tunnel used by a policy");
sangho71abe1b2015-06-29 14:58:47 -0700415 return TunnelHandler.Result.TUNNEL_IN_USE;
sangho1e575652015-05-14 00:39:53 -0700416 }
417 }
418 }
sangho71abe1b2015-06-29 14:58:47 -0700419 return tunnelHandler.removeTunnel(tunnel);
sangho1e575652015-05-14 00:39:53 -0700420 }
421
422 @Override
sangho71abe1b2015-06-29 14:58:47 -0700423 public PolicyHandler.Result removePolicy(Policy policy) {
424 return policyHandler.removePolicy(policy);
sangho1e575652015-05-14 00:39:53 -0700425 }
426
427 @Override
sangho71abe1b2015-06-29 14:58:47 -0700428 public PolicyHandler.Result createPolicy(Policy policy) {
429 return policyHandler.createPolicy(policy);
sangho1e575652015-05-14 00:39:53 -0700430 }
431
432 @Override
433 public List<Policy> getPolicies() {
434 return policyHandler.getPolicies();
435 }
436
sanghof9d0bf12015-05-19 11:57:42 -0700437 /**
438 * Returns the tunnel object with the tunnel ID.
439 *
440 * @param tunnelId Tunnel ID
441 * @return Tunnel reference
442 */
sangho1e575652015-05-14 00:39:53 -0700443 public Tunnel getTunnel(String tunnelId) {
444 return tunnelHandler.getTunnel(tunnelId);
445 }
446
sanghob35a6192015-04-01 13:05:26 -0700447 /**
Saurav Das0e99e2b2015-10-28 12:39:42 -0700448 * Returns the vlan-id assigned to the subnet configured for a device.
449 * If no vlan-id has been assigned, a new one is assigned out of a pool of ids,
450 * if and only if this controller instance is the master for the device.
451 * <p>
452 * USAGE: The assigned vlans are meant to be applied to untagged packets on those
453 * switches/pipelines that need this functionality. These vids are meant
454 * to be used internally within a switch, and thus need to be unique only
455 * on a switch level. Note that packets never go out on the wire with these
456 * vlans. Currently, vlan ids are assigned from value 4093 down.
457 * Vlan id 4094 expected to be used for all ports that are not assigned subnets.
458 * Vlan id 4095 is reserved and unused. Only a single vlan id is assigned
459 * per subnet.
sanghob35a6192015-04-01 13:05:26 -0700460 *
Saurav Das0e99e2b2015-10-28 12:39:42 -0700461 * @param deviceId switch dpid
462 * @param subnet IPv4 prefix for which assigned vlan is desired
463 * @return VlanId assigned for the subnet on the device, or
464 * null if no vlan assignment was found and this instance is not
465 * the master for the device.
sanghob35a6192015-04-01 13:05:26 -0700466 */
Charles Chane849c192016-01-11 18:28:54 -0800467 // TODO: We should avoid assigning VLAN IDs that are used by VLAN cross-connection.
Saurav Das0e99e2b2015-10-28 12:39:42 -0700468 public VlanId getSubnetAssignedVlanId(DeviceId deviceId, Ip4Prefix subnet) {
469 VlanId assignedVid = subnetVidStore.get(new SubnetAssignedVidStoreKey(
470 deviceId, subnet));
471 if (assignedVid != null) {
472 log.debug("Query for subnet:{} on device:{} returned assigned-vlan "
473 + "{}", subnet, deviceId, assignedVid);
474 return assignedVid;
475 }
476 //check mastership for the right to assign a vlan
477 if (!mastershipService.isLocalMaster(deviceId)) {
478 log.warn("This controller instance is not the master for device {}. "
479 + "Cannot assign vlan-id for subnet {}", deviceId, subnet);
480 return null;
481 }
482 // vlan assignment is expensive but done only once
Charles Chan9f676b62015-10-29 14:58:10 -0700483 Set<Ip4Prefix> configuredSubnets = deviceConfiguration.getSubnets(deviceId);
Saurav Das0e99e2b2015-10-28 12:39:42 -0700484 Set<Short> assignedVlans = new HashSet<>();
485 Set<Ip4Prefix> unassignedSubnets = new HashSet<>();
486 for (Ip4Prefix sub : configuredSubnets) {
487 VlanId v = subnetVidStore.get(new SubnetAssignedVidStoreKey(deviceId,
488 sub));
489 if (v != null) {
490 assignedVlans.add(v.toShort());
491 } else {
492 unassignedSubnets.add(sub);
493 }
494 }
495 short nextAssignedVlan = ASSIGNED_VLAN_START;
496 if (!assignedVlans.isEmpty()) {
497 nextAssignedVlan = (short) (Collections.min(assignedVlans) - 1);
498 }
499 for (Ip4Prefix unsub : unassignedSubnets) {
Charles Chan5270ed02016-01-30 23:22:37 -0800500 // Special case for default route. Assign default VLAN ID to /32 and /0 subnets
501 if (unsub.prefixLength() == IpPrefix.MAX_INET_MASK_LENGTH ||
502 unsub.prefixLength() == 0) {
503 subnetVidStore.put(new SubnetAssignedVidStoreKey(deviceId, unsub),
504 VlanId.vlanId(ASSIGNED_VLAN_NO_SUBNET));
505 } else {
506 subnetVidStore.put(new SubnetAssignedVidStoreKey(deviceId, unsub),
507 VlanId.vlanId(nextAssignedVlan--));
508 log.info("Assigned vlan: {} to subnet: {} on device: {}",
509 nextAssignedVlan + 1, unsub, deviceId);
510 }
sanghob35a6192015-04-01 13:05:26 -0700511 }
512
Saurav Das0e99e2b2015-10-28 12:39:42 -0700513 return subnetVidStore.get(new SubnetAssignedVidStoreKey(deviceId, subnet));
sanghob35a6192015-04-01 13:05:26 -0700514 }
515
sangho1e575652015-05-14 00:39:53 -0700516 /**
Saurav Das0e99e2b2015-10-28 12:39:42 -0700517 * Returns the next objective ID for the given NeighborSet.
Saurav Das8a0732e2015-11-20 15:27:53 -0800518 * If the nextObjective does not exist, a new one is created and
Saurav Das4ce45962015-11-24 23:21:05 -0800519 * its id is returned.
sangho1e575652015-05-14 00:39:53 -0700520 *
sanghof9d0bf12015-05-19 11:57:42 -0700521 * @param deviceId Device ID
522 * @param ns NegighborSet
Saurav Das8a0732e2015-11-20 15:27:53 -0800523 * @param meta metadata passed into the creation of a Next Objective
524 * @return next objective ID or -1 if an error was encountered during the
525 * creation of the nextObjective
sangho1e575652015-05-14 00:39:53 -0700526 */
Saurav Das8a0732e2015-11-20 15:27:53 -0800527 public int getNextObjectiveId(DeviceId deviceId, NeighborSet ns,
528 TrafficSelector meta) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700529 if (groupHandlerMap.get(deviceId) != null) {
530 log.trace("getNextObjectiveId query in device {}", deviceId);
531 return groupHandlerMap
Saurav Das8a0732e2015-11-20 15:27:53 -0800532 .get(deviceId).getNextObjectiveId(ns, meta);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700533 } else {
Saurav Das4ce45962015-11-24 23:21:05 -0800534 log.warn("getNextObjectiveId query - groupHandler for device {} "
535 + "not found", deviceId);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700536 return -1;
537 }
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700538 }
539
Charles Chanc42e84e2015-10-20 16:24:19 -0700540 /**
Saurav Das4ce45962015-11-24 23:21:05 -0800541 * Returns the next objective ID for the given subnet prefix. It is expected
542 * that the next-objective has been pre-created from configuration.
Charles Chanc42e84e2015-10-20 16:24:19 -0700543 *
544 * @param deviceId Device ID
545 * @param prefix Subnet
Saurav Das4ce45962015-11-24 23:21:05 -0800546 * @return next objective ID or -1 if it was not found
Charles Chanc42e84e2015-10-20 16:24:19 -0700547 */
548 public int getSubnetNextObjectiveId(DeviceId deviceId, IpPrefix prefix) {
549 if (groupHandlerMap.get(deviceId) != null) {
550 log.trace("getSubnetNextObjectiveId query in device {}", deviceId);
551 return groupHandlerMap
552 .get(deviceId).getSubnetNextObjectiveId(prefix);
553 } else {
Saurav Das4ce45962015-11-24 23:21:05 -0800554 log.warn("getSubnetNextObjectiveId query - groupHandler for "
555 + "device {} not found", deviceId);
556 return -1;
557 }
558 }
559
560 /**
561 * Returns the next objective ID for the given portNumber, given the treatment.
562 * There could be multiple different treatments to the same outport, which
563 * would result in different objectives. If the next object
564 * does not exist, a new one is created and its id is returned.
565 *
566 * @param deviceId Device ID
567 * @param portNum port number on device for which NextObjective is queried
568 * @param treatment the actions to apply on the packets (should include outport)
569 * @param meta metadata passed into the creation of a Next Objective if necessary
570 * @return next objective ID or -1 if it was not found
571 */
572 public int getPortNextObjectiveId(DeviceId deviceId, PortNumber portNum,
573 TrafficTreatment treatment,
574 TrafficSelector meta) {
575 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
576 if (ghdlr != null) {
577 return ghdlr.getPortNextObjectiveId(portNum, treatment, meta);
578 } else {
Charles Chane849c192016-01-11 18:28:54 -0800579 log.warn("getPortNextObjectiveId query - groupHandler for device {}"
580 + " not found", deviceId);
581 return -1;
582 }
583 }
584
585 /**
586 * Returns the next objective ID of type broadcast associated with the VLAN
587 * cross-connection.
588 *
589 * @param deviceId Device ID for the cross-connection
590 * @param vlanId VLAN ID for the cross-connection
591 * @return next objective ID or -1 if it was not found
592 */
593 public int getXConnectNextObjectiveId(DeviceId deviceId, VlanId vlanId) {
594 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
595 if (ghdlr != null) {
596 return ghdlr.getXConnectNextObjectiveId(vlanId);
597 } else {
598 log.warn("getPortNextObjectiveId query - groupHandler for device {}"
Saurav Das4ce45962015-11-24 23:21:05 -0800599 + " not found", deviceId);
Charles Chanc42e84e2015-10-20 16:24:19 -0700600 return -1;
601 }
602 }
603
sanghob35a6192015-04-01 13:05:26 -0700604 private class InternalPacketProcessor implements PacketProcessor {
sanghob35a6192015-04-01 13:05:26 -0700605 @Override
606 public void process(PacketContext context) {
607
608 if (context.isHandled()) {
609 return;
610 }
611
612 InboundPacket pkt = context.inPacket();
613 Ethernet ethernet = pkt.parsed();
Saurav Das4ce45962015-11-24 23:21:05 -0800614 log.trace("Rcvd pktin: {}", ethernet);
sanghob35a6192015-04-01 13:05:26 -0700615 if (ethernet.getEtherType() == Ethernet.TYPE_ARP) {
616 arpHandler.processPacketIn(pkt);
617 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV4) {
618 IPv4 ipPacket = (IPv4) ethernet.getPayload();
619 ipHandler.addToPacketBuffer(ipPacket);
620 if (ipPacket.getProtocol() == IPv4.PROTOCOL_ICMP) {
621 icmpHandler.processPacketIn(pkt);
622 } else {
623 ipHandler.processPacketIn(pkt);
624 }
625 }
626 }
627 }
628
629 private class InternalLinkListener implements LinkListener {
630 @Override
631 public void event(LinkEvent event) {
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700632 if (event.type() == LinkEvent.Type.LINK_ADDED
633 || event.type() == LinkEvent.Type.LINK_REMOVED) {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700634 log.debug("Event {} received from Link Service", event.type());
sanghob35a6192015-04-01 13:05:26 -0700635 scheduleEventHandlerIfNotScheduled(event);
636 }
637 }
638 }
639
640 private class InternalDeviceListener implements DeviceListener {
sanghob35a6192015-04-01 13:05:26 -0700641 @Override
642 public void event(DeviceEvent event) {
sanghob35a6192015-04-01 13:05:26 -0700643 switch (event.type()) {
644 case DEVICE_ADDED:
645 case PORT_REMOVED:
sangho20eff1d2015-04-13 15:15:58 -0700646 case DEVICE_UPDATED:
647 case DEVICE_AVAILABILITY_CHANGED:
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700648 log.debug("Event {} received from Device Service", event.type());
sanghob35a6192015-04-01 13:05:26 -0700649 scheduleEventHandlerIfNotScheduled(event);
650 break;
651 default:
652 }
653 }
654 }
655
Saurav Das4ce45962015-11-24 23:21:05 -0800656 @SuppressWarnings("rawtypes")
sanghob35a6192015-04-01 13:05:26 -0700657 private void scheduleEventHandlerIfNotScheduled(Event event) {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700658 synchronized (threadSchedulerLock) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700659 eventQueue.add(event);
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700660 numOfEventsQueued++;
661
662 if ((numOfHandlerScheduled - numOfHandlerExecution) == 0) {
663 //No pending scheduled event handling threads. So start a new one.
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700664 eventHandlerFuture = executorService
665 .schedule(eventHandler, 100, TimeUnit.MILLISECONDS);
666 numOfHandlerScheduled++;
667 }
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700668 log.trace("numOfEventsQueued {}, numOfEventHandlerScheduled {}",
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700669 numOfEventsQueued,
670 numOfHandlerScheduled);
sanghob35a6192015-04-01 13:05:26 -0700671 }
sanghob35a6192015-04-01 13:05:26 -0700672 }
673
674 private class InternalEventHandler implements Runnable {
Srikanth Vavilapalli4db76e32015-04-07 15:12:32 -0700675 @Override
sanghob35a6192015-04-01 13:05:26 -0700676 public void run() {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700677 try {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700678 while (true) {
Saurav Das4ce45962015-11-24 23:21:05 -0800679 @SuppressWarnings("rawtypes")
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700680 Event event = null;
681 synchronized (threadSchedulerLock) {
682 if (!eventQueue.isEmpty()) {
683 event = eventQueue.poll();
684 numOfEventsExecuted++;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700685 } else {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700686 numOfHandlerExecution++;
687 log.debug("numOfHandlerExecution {} numOfEventsExecuted {}",
688 numOfHandlerExecution, numOfEventsExecuted);
689 break;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700690 }
sangho20eff1d2015-04-13 15:15:58 -0700691 }
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700692 if (event.type() == LinkEvent.Type.LINK_ADDED) {
693 processLinkAdded((Link) event.subject());
694 } else if (event.type() == LinkEvent.Type.LINK_REMOVED) {
695 processLinkRemoved((Link) event.subject());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700696 } else if (event.type() == DeviceEvent.Type.DEVICE_ADDED ||
697 event.type() == DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED ||
698 event.type() == DeviceEvent.Type.DEVICE_UPDATED) {
Saurav Das423fe2b2015-12-04 10:52:59 -0800699 DeviceId deviceId = ((Device) event.subject()).id();
700 if (deviceService.isAvailable(deviceId)) {
Saurav Das837e0bb2015-10-30 17:45:38 -0700701 log.info("Processing device event {} for available device {}",
702 event.type(), ((Device) event.subject()).id());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700703 processDeviceAdded((Device) event.subject());
Saurav Das80980c72016-03-23 11:22:49 -0700704 } else {
705 log.info("Processing device event {} for unavailable device {}",
706 event.type(), ((Device) event.subject()).id());
707 processDeviceRemoved((Device) event.subject());
708 }
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700709 } else if (event.type() == DeviceEvent.Type.PORT_REMOVED) {
710 processPortRemoved((Device) event.subject(),
711 ((DeviceEvent) event).port());
712 } else {
713 log.warn("Unhandled event type: {}", event.type());
714 }
sanghob35a6192015-04-01 13:05:26 -0700715 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700716 } catch (Exception e) {
717 log.error("SegmentRouting event handler "
718 + "thread thrown an exception: {}", e);
sanghob35a6192015-04-01 13:05:26 -0700719 }
sanghob35a6192015-04-01 13:05:26 -0700720 }
721 }
722
sanghob35a6192015-04-01 13:05:26 -0700723 private void processLinkAdded(Link link) {
724 log.debug("A new link {} was added", link.toString());
Charles Chan0b4e6182015-11-03 10:42:14 -0800725 if (!deviceConfiguration.isConfigured(link.src().deviceId())) {
726 log.warn("Source device of this link is not configured.");
727 return;
728 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700729 //Irrespective whether the local is a MASTER or not for this device,
730 //create group handler instance and push default TTP flow rules.
731 //Because in a multi-instance setup, instances can initiate
732 //groups for any devices. Also the default TTP rules are needed
733 //to be pushed before inserting any IP table entries for any device
734 DefaultGroupHandler groupHandler = groupHandlerMap.get(link.src()
735 .deviceId());
736 if (groupHandler != null) {
Saurav Das8a0732e2015-11-20 15:27:53 -0800737 groupHandler.linkUp(link, mastershipService.isLocalMaster(
738 link.src().deviceId()));
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700739 } else {
740 Device device = deviceService.getDevice(link.src().deviceId());
741 if (device != null) {
742 log.warn("processLinkAdded: Link Added "
743 + "Notification without Device Added "
744 + "event, still handling it");
745 processDeviceAdded(device);
746 groupHandler = groupHandlerMap.get(link.src()
747 .deviceId());
Saurav Das8a0732e2015-11-20 15:27:53 -0800748 groupHandler.linkUp(link, mastershipService.isLocalMaster(device.id()));
sanghob35a6192015-04-01 13:05:26 -0700749 }
750 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700751
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700752 log.trace("Starting optimized route population process");
753 defaultRoutingHandler.populateRoutingRulesForLinkStatusChange(null);
754 //log.trace("processLinkAdded: re-starting route population process");
755 //defaultRoutingHandler.startPopulationProcess();
sanghob35a6192015-04-01 13:05:26 -0700756 }
757
758 private void processLinkRemoved(Link link) {
759 log.debug("A link {} was removed", link.toString());
sangho834e4b02015-05-01 09:38:25 -0700760 DefaultGroupHandler groupHandler = groupHandlerMap.get(link.src().deviceId());
761 if (groupHandler != null) {
Saurav Das423fe2b2015-12-04 10:52:59 -0800762 groupHandler.portDown(link.src().port(),
763 mastershipService.isLocalMaster(link.src().deviceId()));
sangho834e4b02015-05-01 09:38:25 -0700764 }
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700765 log.trace("Starting optimized route population process");
766 defaultRoutingHandler.populateRoutingRulesForLinkStatusChange(link);
767 //log.trace("processLinkRemoved: re-starting route population process");
768 //defaultRoutingHandler.startPopulationProcess();
sanghob35a6192015-04-01 13:05:26 -0700769 }
770
771 private void processDeviceAdded(Device device) {
772 log.debug("A new device with ID {} was added", device.id());
Charles Chan0b4e6182015-11-03 10:42:14 -0800773 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
Saurav Das2857f382015-11-03 14:39:27 -0800774 log.warn("Device configuration uploading. Device {} will be "
775 + "processed after config completes.", device.id());
776 return;
777 }
Saurav Das837e0bb2015-10-30 17:45:38 -0700778 // Irrespective of whether the local is a MASTER or not for this device,
779 // we need to create a SR-group-handler instance. This is because in a
780 // multi-instance setup, any instance can initiate forwarding/next-objectives
781 // for any switch (even if this instance is a SLAVE or not even connected
782 // to the switch). To handle this, a default-group-handler instance is necessary
783 // per switch.
Saurav Das2857f382015-11-03 14:39:27 -0800784 if (groupHandlerMap.get(device.id()) == null) {
Charles Chan0b4e6182015-11-03 10:42:14 -0800785 DefaultGroupHandler groupHandler;
786 try {
787 groupHandler = DefaultGroupHandler.
788 createGroupHandler(device.id(),
789 appId,
790 deviceConfiguration,
791 linkService,
792 flowObjectiveService,
Charles Chan188ebf52015-12-23 00:15:11 -0800793 this);
Charles Chan0b4e6182015-11-03 10:42:14 -0800794 } catch (DeviceConfigNotFoundException e) {
795 log.warn(e.getMessage() + " Aborting processDeviceAdded.");
796 return;
797 }
Saurav Das2857f382015-11-03 14:39:27 -0800798 groupHandlerMap.put(device.id(), groupHandler);
799 // Also, in some cases, drivers may need extra
800 // information to process rules (eg. Router IP/MAC); and so, we send
801 // port addressing rules to the driver as well irrespective of whether
802 // this instance is the master or not.
803 defaultRoutingHandler.populatePortAddressingRules(device.id());
Charles Chand2990362016-04-18 13:44:03 -0700804 hostHandler.readInitialHosts();
Saurav Das2857f382015-11-03 14:39:27 -0800805 }
Charles Chanc42e84e2015-10-20 16:24:19 -0700806 if (mastershipService.isLocalMaster(device.id())) {
Saurav Das2857f382015-11-03 14:39:27 -0800807 DefaultGroupHandler groupHandler = groupHandlerMap.get(device.id());
Charles Chanc42e84e2015-10-20 16:24:19 -0700808 groupHandler.createGroupsFromSubnetConfig();
Charles Chan68aa62d2015-11-09 16:37:23 -0800809 routingRulePopulator.populateSubnetBroadcastRule(device.id());
Charles Chane849c192016-01-11 18:28:54 -0800810 groupHandler.createGroupsForXConnect(device.id());
811 routingRulePopulator.populateXConnectBroadcastRule(device.id());
Charles Chanc42e84e2015-10-20 16:24:19 -0700812 }
Charles Chan5270ed02016-01-30 23:22:37 -0800813
814 netcfgHandler.initVRouters(device.id());
sanghob35a6192015-04-01 13:05:26 -0700815 }
816
Saurav Das80980c72016-03-23 11:22:49 -0700817 private void processDeviceRemoved(Device device) {
818 nsNextObjStore.entrySet().stream()
819 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
820 .forEach(entry -> {
821 nsNextObjStore.remove(entry.getKey());
822 });
823
824 subnetNextObjStore.entrySet().stream()
825 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
826 .forEach(entry -> {
827 subnetNextObjStore.remove(entry.getKey());
828 });
829
830 portNextObjStore.entrySet().stream()
831 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
832 .forEach(entry -> {
833 portNextObjStore.remove(entry.getKey());
834 });
835
836 xConnectNextObjStore.entrySet().stream()
837 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
838 .forEach(entry -> {
839 xConnectNextObjStore.remove(entry.getKey());
840 });
841
842 subnetVidStore.entrySet().stream()
843 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
844 .forEach(entry -> {
845 subnetVidStore.remove(entry.getKey());
846 });
847
848 groupHandlerMap.remove(device.id());
849
850 defaultRoutingHandler.purgeEcmpGraph(device.id());
851 }
852
sanghob35a6192015-04-01 13:05:26 -0700853 private void processPortRemoved(Device device, Port port) {
854 log.debug("Port {} was removed", port.toString());
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700855 DefaultGroupHandler groupHandler = groupHandlerMap.get(device.id());
sanghob35a6192015-04-01 13:05:26 -0700856 if (groupHandler != null) {
Saurav Das423fe2b2015-12-04 10:52:59 -0800857 groupHandler.portDown(port.number(),
858 mastershipService.isLocalMaster(device.id()));
sanghob35a6192015-04-01 13:05:26 -0700859 }
860 }
sangho1e575652015-05-14 00:39:53 -0700861
Charles Chand6832882015-10-05 17:50:33 -0700862 private class InternalConfigListener implements NetworkConfigListener {
Charles Chan4636be02015-10-07 14:21:45 -0700863 SegmentRoutingManager segmentRoutingManager;
864
Charles Chane849c192016-01-11 18:28:54 -0800865 /**
866 * Constructs the internal network config listener.
867 *
868 * @param srMgr segment routing manager
869 */
Charles Chan4636be02015-10-07 14:21:45 -0700870 public InternalConfigListener(SegmentRoutingManager srMgr) {
871 this.segmentRoutingManager = srMgr;
872 }
873
Charles Chane849c192016-01-11 18:28:54 -0800874 /**
875 * Reads network config and initializes related data structure accordingly.
876 */
Charles Chan4636be02015-10-07 14:21:45 -0700877 public void configureNetwork() {
Charles Chanf2565a92016-02-10 20:46:58 -0800878 deviceConfiguration = new DeviceConfiguration(appId,
879 segmentRoutingManager.cfgService);
Charles Chan4636be02015-10-07 14:21:45 -0700880
881 arpHandler = new ArpHandler(segmentRoutingManager);
882 icmpHandler = new IcmpHandler(segmentRoutingManager);
883 ipHandler = new IpHandler(segmentRoutingManager);
884 routingRulePopulator = new RoutingRulePopulator(segmentRoutingManager);
885 defaultRoutingHandler = new DefaultRoutingHandler(segmentRoutingManager);
886
887 tunnelHandler = new TunnelHandler(linkService, deviceConfiguration,
888 groupHandlerMap, tunnelStore);
889 policyHandler = new PolicyHandler(appId, deviceConfiguration,
890 flowObjectiveService,
891 tunnelHandler, policyStore);
892
Charles Chan4636be02015-10-07 14:21:45 -0700893 for (Device device : deviceService.getDevices()) {
Saurav Das837e0bb2015-10-30 17:45:38 -0700894 // Irrespective of whether the local is a MASTER or not for this device,
895 // we need to create a SR-group-handler instance. This is because in a
896 // multi-instance setup, any instance can initiate forwarding/next-objectives
897 // for any switch (even if this instance is a SLAVE or not even connected
898 // to the switch). To handle this, a default-group-handler instance is necessary
899 // per switch.
Saurav Das2857f382015-11-03 14:39:27 -0800900 if (groupHandlerMap.get(device.id()) == null) {
Charles Chan0b4e6182015-11-03 10:42:14 -0800901 DefaultGroupHandler groupHandler;
902 try {
903 groupHandler = DefaultGroupHandler.
904 createGroupHandler(device.id(),
905 appId,
906 deviceConfiguration,
907 linkService,
908 flowObjectiveService,
Charles Chan188ebf52015-12-23 00:15:11 -0800909 segmentRoutingManager);
Charles Chan0b4e6182015-11-03 10:42:14 -0800910 } catch (DeviceConfigNotFoundException e) {
911 log.warn(e.getMessage() + " Aborting configureNetwork.");
912 return;
913 }
Saurav Das2857f382015-11-03 14:39:27 -0800914 groupHandlerMap.put(device.id(), groupHandler);
Saurav Das837e0bb2015-10-30 17:45:38 -0700915
Saurav Das2857f382015-11-03 14:39:27 -0800916 // Also, in some cases, drivers may need extra
917 // information to process rules (eg. Router IP/MAC); and so, we send
918 // port addressing rules to the driver as well, irrespective of whether
919 // this instance is the master or not.
920 defaultRoutingHandler.populatePortAddressingRules(device.id());
Charles Chand2990362016-04-18 13:44:03 -0700921 hostHandler.readInitialHosts();
Saurav Das2857f382015-11-03 14:39:27 -0800922 }
Charles Chanc42e84e2015-10-20 16:24:19 -0700923 if (mastershipService.isLocalMaster(device.id())) {
Saurav Das2857f382015-11-03 14:39:27 -0800924 DefaultGroupHandler groupHandler = groupHandlerMap.get(device.id());
Charles Chanc42e84e2015-10-20 16:24:19 -0700925 groupHandler.createGroupsFromSubnetConfig();
Charles Chan68aa62d2015-11-09 16:37:23 -0800926 routingRulePopulator.populateSubnetBroadcastRule(device.id());
Charles Chane849c192016-01-11 18:28:54 -0800927 groupHandler.createGroupsForXConnect(device.id());
928 routingRulePopulator.populateXConnectBroadcastRule(device.id());
Charles Chanc42e84e2015-10-20 16:24:19 -0700929 }
Charles Chan4636be02015-10-07 14:21:45 -0700930 }
931
932 defaultRoutingHandler.startPopulationProcess();
933 }
934
Charles Chand6832882015-10-05 17:50:33 -0700935 @Override
936 public void event(NetworkConfigEvent event) {
Charles Chan5270ed02016-01-30 23:22:37 -0800937 // TODO move this part to NetworkConfigEventHandler
938 if (event.configClass().equals(SegmentRoutingDeviceConfig.class)) {
939 switch (event.type()) {
940 case CONFIG_ADDED:
941 log.info("Segment Routing Config added.");
942 configureNetwork();
943 break;
944 case CONFIG_UPDATED:
945 log.info("Segment Routing Config updated.");
946 // TODO support dynamic configuration
947 break;
948 default:
949 break;
Charles Chanb8e10c82015-10-14 11:24:40 -0700950 }
Charles Chan5270ed02016-01-30 23:22:37 -0800951 } else if (event.configClass().equals(SegmentRoutingAppConfig.class)) {
Charles Chan3e783d02016-02-26 22:19:52 -0800952 checkState(netcfgHandler != null, "NetworkConfigEventHandler is not initialized");
Charles Chan5270ed02016-01-30 23:22:37 -0800953 switch (event.type()) {
954 case CONFIG_ADDED:
955 netcfgHandler.processVRouterConfigAdded(event);
956 break;
957 case CONFIG_UPDATED:
958 netcfgHandler.processVRouterConfigUpdated(event);
959 break;
960 case CONFIG_REMOVED:
961 netcfgHandler.processVRouterConfigRemoved(event);
962 break;
963 default:
964 break;
Charles Chanb8e10c82015-10-14 11:24:40 -0700965 }
Charles Chand6832882015-10-05 17:50:33 -0700966 }
967 }
968 }
Charles Chan68aa62d2015-11-09 16:37:23 -0800969
970 private class InternalHostListener implements HostListener {
Charles Chan68aa62d2015-11-09 16:37:23 -0800971 @Override
972 public void event(HostEvent event) {
973 // Do not proceed without mastership
974 DeviceId deviceId = event.subject().location().deviceId();
975 if (!mastershipService.isLocalMaster(deviceId)) {
976 return;
977 }
978
979 switch (event.type()) {
980 case HOST_ADDED:
Charles Chand2990362016-04-18 13:44:03 -0700981 hostHandler.processHostAddedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -0800982 break;
983 case HOST_MOVED:
Charles Chand2990362016-04-18 13:44:03 -0700984 hostHandler.processHostMovedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -0800985 break;
986 case HOST_REMOVED:
Charles Chand2990362016-04-18 13:44:03 -0700987 hostHandler.processHostRemoveEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -0800988 break;
989 case HOST_UPDATED:
Charles Chand2990362016-04-18 13:44:03 -0700990 hostHandler.processHostUpdatedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -0800991 break;
992 default:
993 log.warn("Unsupported host event type: {}", event.type());
994 break;
995 }
996 }
997 }
998
Charles Chand55e84d2016-03-30 17:54:24 -0700999 private class InternalMcastListener implements McastListener {
1000 @Override
1001 public void event(McastEvent event) {
1002 switch (event.type()) {
1003 case SOURCE_ADDED:
Charles Chand2990362016-04-18 13:44:03 -07001004 mcastHandler.processSourceAdded(event);
Charles Chand55e84d2016-03-30 17:54:24 -07001005 break;
1006 case SINK_ADDED:
Charles Chand2990362016-04-18 13:44:03 -07001007 mcastHandler.processSinkAdded(event);
Charles Chand55e84d2016-03-30 17:54:24 -07001008 break;
1009 case SINK_REMOVED:
Charles Chand2990362016-04-18 13:44:03 -07001010 mcastHandler.processSinkRemoved(event);
Charles Chand55e84d2016-03-30 17:54:24 -07001011 break;
1012 case ROUTE_ADDED:
1013 case ROUTE_REMOVED:
1014 default:
1015 break;
1016 }
1017 }
1018 }
sanghob35a6192015-04-01 13:05:26 -07001019}