blob: cd348442bb34496c1a960d5d72963676fe57dc80 [file] [log] [blame]
sangho80f11cb2015-04-01 13:05:26 -07001/*
Brian O'Connor0947d7e2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
sangho80f11cb2015-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
Jonghwan Hyune5ef7622017-08-25 17:48:36 -070018import java.util.Collections;
19import java.util.HashSet;
Ray Milkeyae0068a2017-08-15 11:02:29 -070020import java.util.List;
21import java.util.Map;
22import java.util.Map.Entry;
23import java.util.Optional;
24import java.util.Set;
25import java.util.concurrent.ConcurrentHashMap;
26import java.util.concurrent.ConcurrentLinkedQueue;
27import java.util.concurrent.Executors;
28import java.util.concurrent.ScheduledExecutorService;
29import java.util.concurrent.ScheduledFuture;
30import java.util.concurrent.TimeUnit;
31import java.util.concurrent.atomic.AtomicBoolean;
32import java.util.stream.Collectors;
33
Charles Chanf0ae41e2017-08-23 13:55:39 -070034import com.google.common.collect.Sets;
sangho80f11cb2015-04-01 13:05:26 -070035import org.apache.felix.scr.annotations.Activate;
36import org.apache.felix.scr.annotations.Component;
37import org.apache.felix.scr.annotations.Deactivate;
38import org.apache.felix.scr.annotations.Reference;
39import org.apache.felix.scr.annotations.ReferenceCardinality;
sangho27462c62015-05-14 00:39:53 -070040import org.apache.felix.scr.annotations.Service;
sangho80f11cb2015-04-01 13:05:26 -070041import org.onlab.packet.Ethernet;
Pier Ventreb6b81d52016-12-02 08:16:05 -080042import org.onlab.packet.ICMP6;
Charles Chan77277672015-10-20 16:24:19 -070043import org.onlab.packet.IPv4;
Pier Ventreb6a7f342016-11-26 21:05:22 -080044import org.onlab.packet.IPv6;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -070045import org.onlab.packet.IpAddress;
Charles Chan77277672015-10-20 16:24:19 -070046import org.onlab.packet.IpPrefix;
Jonathan Hart54541d12016-04-12 15:39:44 -070047import org.onlab.packet.VlanId;
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -070048import org.onlab.util.KryoNamespace;
Saurav Dasc3604f12016-03-23 11:22:49 -070049import org.onosproject.cfg.ComponentConfigService;
sangho80f11cb2015-04-01 13:05:26 -070050import org.onosproject.core.ApplicationId;
51import org.onosproject.core.CoreService;
52import org.onosproject.event.Event;
Jonathan Hart54541d12016-04-12 15:39:44 -070053import org.onosproject.mastership.MastershipService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080054import org.onosproject.net.ConnectPoint;
Jonathan Hart54541d12016-04-12 15:39:44 -070055import org.onosproject.net.Device;
56import org.onosproject.net.DeviceId;
Charles Chanf0ae41e2017-08-23 13:55:39 -070057import org.onosproject.net.Host;
58import org.onosproject.net.HostId;
Jonathan Hart54541d12016-04-12 15:39:44 -070059import org.onosproject.net.Link;
60import org.onosproject.net.Port;
Charles Chanf4586112015-11-09 16:37:23 -080061import org.onosproject.net.PortNumber;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -070062import org.onosproject.net.config.ConfigException;
Charles Chan72f556a2015-10-05 17:50:33 -070063import org.onosproject.net.config.ConfigFactory;
64import org.onosproject.net.config.NetworkConfigEvent;
Charles Chan72f556a2015-10-05 17:50:33 -070065import org.onosproject.net.config.NetworkConfigListener;
Jonathan Hart54541d12016-04-12 15:39:44 -070066import org.onosproject.net.config.NetworkConfigRegistry;
Ray Milkeyae0068a2017-08-15 11:02:29 -070067import org.onosproject.net.config.basics.InterfaceConfig;
68import org.onosproject.net.config.basics.McastConfig;
Charles Chan72f556a2015-10-05 17:50:33 -070069import org.onosproject.net.config.basics.SubjectFactories;
Jonathan Hart54541d12016-04-12 15:39:44 -070070import org.onosproject.net.device.DeviceEvent;
71import org.onosproject.net.device.DeviceListener;
72import org.onosproject.net.device.DeviceService;
Charles Chanf4586112015-11-09 16:37:23 -080073import org.onosproject.net.flow.TrafficSelector;
74import org.onosproject.net.flow.TrafficTreatment;
Jonathan Hart54541d12016-04-12 15:39:44 -070075import org.onosproject.net.flowobjective.FlowObjectiveService;
Charles Chanf4586112015-11-09 16:37:23 -080076import org.onosproject.net.host.HostEvent;
77import org.onosproject.net.host.HostListener;
Pier Ventreb6a7f342016-11-26 21:05:22 -080078import org.onosproject.net.host.HostService;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -070079import org.onosproject.net.host.InterfaceIpAddress;
Ray Milkeyae0068a2017-08-15 11:02:29 -070080import org.onosproject.net.intf.Interface;
81import org.onosproject.net.intf.InterfaceService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080082import org.onosproject.net.link.LinkEvent;
83import org.onosproject.net.link.LinkListener;
84import org.onosproject.net.link.LinkService;
Charles Chanc91c8782016-03-30 17:54:24 -070085import org.onosproject.net.mcast.McastEvent;
86import org.onosproject.net.mcast.McastListener;
87import org.onosproject.net.mcast.MulticastRouteService;
Ray Milkeyae0068a2017-08-15 11:02:29 -070088import org.onosproject.net.neighbour.NeighbourResolutionService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080089import org.onosproject.net.packet.InboundPacket;
90import org.onosproject.net.packet.PacketContext;
91import org.onosproject.net.packet.PacketProcessor;
92import org.onosproject.net.packet.PacketService;
Pier Ventref3cf5b92016-11-09 14:17:26 -080093import org.onosproject.net.topology.PathService;
Charles Chanc91c8782016-03-30 17:54:24 -070094import org.onosproject.net.topology.TopologyService;
Charles Chanf0ae41e2017-08-23 13:55:39 -070095import org.onosproject.routeservice.ResolvedRoute;
Ray Milkeyae0068a2017-08-15 11:02:29 -070096import org.onosproject.routeservice.RouteEvent;
97import org.onosproject.routeservice.RouteListener;
98import org.onosproject.routeservice.RouteService;
Charles Chanc91c8782016-03-30 17:54:24 -070099import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
100import org.onosproject.segmentrouting.config.DeviceConfiguration;
Pier Ventre6b19e482016-11-07 16:21:04 -0800101import org.onosproject.segmentrouting.config.PwaasConfig;
Pier Ventre6b19e482016-11-07 16:21:04 -0800102import org.onosproject.segmentrouting.config.SegmentRoutingAppConfig;
Ray Milkeyae0068a2017-08-15 11:02:29 -0700103import org.onosproject.segmentrouting.config.SegmentRoutingDeviceConfig;
Charles Chan82f19972016-05-17 13:13:55 -0700104import org.onosproject.segmentrouting.config.XConnectConfig;
Charles Chanc91c8782016-03-30 17:54:24 -0700105import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
Saurav Das261c3002017-06-13 15:35:54 -0700106import org.onosproject.segmentrouting.grouphandler.DestinationSet;
107import org.onosproject.segmentrouting.grouphandler.NextNeighbors;
Ray Milkeyae0068a2017-08-15 11:02:29 -0700108import org.onosproject.segmentrouting.pwaas.L2TunnelHandler;
Saurav Das261c3002017-06-13 15:35:54 -0700109import org.onosproject.segmentrouting.storekey.DestinationSetNextObjectiveStoreKey;
Charles Chan1eaf4802016-04-18 13:44:03 -0700110import org.onosproject.segmentrouting.storekey.PortNextObjectiveStoreKey;
Charles Chan10b0fb72017-02-02 16:20:42 -0800111import org.onosproject.segmentrouting.storekey.VlanNextObjectiveStoreKey;
Charles Chan82f19972016-05-17 13:13:55 -0700112import org.onosproject.segmentrouting.storekey.XConnectStoreKey;
Jonathan Hart54541d12016-04-12 15:39:44 -0700113import org.onosproject.store.serializers.KryoNamespaces;
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700114import org.onosproject.store.service.EventuallyConsistentMap;
115import org.onosproject.store.service.EventuallyConsistentMapBuilder;
116import org.onosproject.store.service.StorageService;
117import org.onosproject.store.service.WallClockTimestamp;
sangho80f11cb2015-04-01 13:05:26 -0700118import org.slf4j.Logger;
119import org.slf4j.LoggerFactory;
120
Ray Milkeyae0068a2017-08-15 11:02:29 -0700121import com.google.common.collect.HashMultimap;
122import com.google.common.collect.ImmutableMap;
123import com.google.common.collect.Maps;
124import com.google.common.collect.Multimap;
sangho80f11cb2015-04-01 13:05:26 -0700125
Charles Chand6d25332016-02-26 22:19:52 -0800126import static com.google.common.base.Preconditions.checkState;
Pier Ventreadb4ae62016-11-23 09:57:42 -0800127import static org.onlab.packet.Ethernet.TYPE_ARP;
Yuta HIGUCHIebee2f12016-07-21 16:54:33 -0700128import static org.onlab.util.Tools.groupedThreads;
Charles Chand6d25332016-02-26 22:19:52 -0800129
Charles Chanb7f75ac2016-01-11 18:28:54 -0800130/**
131 * Segment routing manager.
132 */
Jonathan Hart54541d12016-04-12 15:39:44 -0700133@Service
134@Component(immediate = true)
sangho27462c62015-05-14 00:39:53 -0700135public class SegmentRoutingManager implements SegmentRoutingService {
sangho80f11cb2015-04-01 13:05:26 -0700136
Charles Chan46fdfaf2016-11-09 20:51:44 -0800137 private static Logger log = LoggerFactory.getLogger(SegmentRoutingManager.class);
Charles Chan910be6a2017-08-23 14:46:43 -0700138 private static final String NOT_MASTER = "Current instance is not the master of {}. Ignore.";
sangho80f11cb2015-04-01 13:05:26 -0700139
140 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700141 private ComponentConfigService compCfgService;
sangho80f11cb2015-04-01 13:05:26 -0700142
143 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventreb6a7f342016-11-26 21:05:22 -0800144 private NeighbourResolutionService neighbourResolutionService;
145
146 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventref3cf5b92016-11-09 14:17:26 -0800147 public PathService pathService;
148
149 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700150 CoreService coreService;
sangho80f11cb2015-04-01 13:05:26 -0700151
152 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700153 PacketService packetService;
sangho80f11cb2015-04-01 13:05:26 -0700154
155 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700156 HostService hostService;
sangho80f11cb2015-04-01 13:05:26 -0700157
158 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700159 DeviceService deviceService;
sangho80f11cb2015-04-01 13:05:26 -0700160
161 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventref3cf5b92016-11-09 14:17:26 -0800162 public FlowObjectiveService flowObjectiveService;
sangho80f11cb2015-04-01 13:05:26 -0700163
164 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700165 LinkService linkService;
sangho27462c62015-05-14 00:39:53 -0700166
Charles Chan82ab1932016-01-30 23:22:37 -0800167 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventref3cf5b92016-11-09 14:17:26 -0800168 public MastershipService mastershipService;
Charles Chandebfea32016-10-24 14:52:01 -0700169
170 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventref3cf5b92016-11-09 14:17:26 -0800171 public StorageService storageService;
Charles Chandebfea32016-10-24 14:52:01 -0700172
173 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
174 MulticastRouteService multicastRouteService;
175
176 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
177 TopologyService topologyService;
178
179 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700180 RouteService routeService;
Charles Chan82ab1932016-01-30 23:22:37 -0800181
182 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan46fdfaf2016-11-09 20:51:44 -0800183 public NetworkConfigRegistry cfgService;
Charles Chan82ab1932016-01-30 23:22:37 -0800184
Saurav Dasc3604f12016-03-23 11:22:49 -0700185 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan46fdfaf2016-11-09 20:51:44 -0800186 public InterfaceService interfaceService;
187
Charles Chandebfea32016-10-24 14:52:01 -0700188 ArpHandler arpHandler = null;
189 IcmpHandler icmpHandler = null;
190 IpHandler ipHandler = null;
191 RoutingRulePopulator routingRulePopulator = null;
Ray Milkeyb85de082017-04-05 09:42:04 -0700192 ApplicationId appId;
193 DeviceConfiguration deviceConfiguration = null;
sangho80f11cb2015-04-01 13:05:26 -0700194
Charles Chandebfea32016-10-24 14:52:01 -0700195 DefaultRoutingHandler defaultRoutingHandler = null;
sangho27462c62015-05-14 00:39:53 -0700196 private TunnelHandler tunnelHandler = null;
197 private PolicyHandler policyHandler = null;
Charles Chan2b078ae2015-10-14 11:24:40 -0700198 private InternalPacketProcessor processor = null;
199 private InternalLinkListener linkListener = null;
200 private InternalDeviceListener deviceListener = null;
Charles Chan82f19972016-05-17 13:13:55 -0700201 private AppConfigHandler appCfgHandler = null;
Charles Chandebfea32016-10-24 14:52:01 -0700202 XConnectHandler xConnectHandler = null;
Charles Chan1eaf4802016-04-18 13:44:03 -0700203 private McastHandler mcastHandler = null;
Charles Chan3ed34d82017-06-22 18:03:14 -0700204 private HostHandler hostHandler = null;
Pier Ventreb6a7f342016-11-26 21:05:22 -0800205 private RouteHandler routeHandler = null;
Pier Ventreb6b81d52016-12-02 08:16:05 -0800206 private SegmentRoutingNeighbourDispatcher neighbourHandler = null;
Pier Ventre6b19e482016-11-07 16:21:04 -0800207 private L2TunnelHandler l2TunnelHandler = null;
sangho80f11cb2015-04-01 13:05:26 -0700208 private InternalEventHandler eventHandler = new InternalEventHandler();
Charles Chan82ab1932016-01-30 23:22:37 -0800209 private final InternalHostListener hostListener = new InternalHostListener();
Charles Chanc91c8782016-03-30 17:54:24 -0700210 private final InternalConfigListener cfgListener = new InternalConfigListener(this);
211 private final InternalMcastListener mcastListener = new InternalMcastListener();
Charles Chandebfea32016-10-24 14:52:01 -0700212 private final InternalRouteEventListener routeListener = new InternalRouteEventListener();
sangho80f11cb2015-04-01 13:05:26 -0700213
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700214 private ScheduledExecutorService executorService = Executors
Yuta HIGUCHIebee2f12016-07-21 16:54:33 -0700215 .newScheduledThreadPool(1, groupedThreads("SegmentRoutingManager", "event-%d", log));
sangho80f11cb2015-04-01 13:05:26 -0700216
Saurav Das2d94d312015-11-24 23:21:05 -0800217 @SuppressWarnings("unused")
sangho80f11cb2015-04-01 13:05:26 -0700218 private static ScheduledFuture<?> eventHandlerFuture = null;
Saurav Das2d94d312015-11-24 23:21:05 -0800219 @SuppressWarnings("rawtypes")
Yuta HIGUCHIebee2f12016-07-21 16:54:33 -0700220 private ConcurrentLinkedQueue<Event> eventQueue = new ConcurrentLinkedQueue<>();
Charles Chanf4586112015-11-09 16:37:23 -0800221 private Map<DeviceId, DefaultGroupHandler> groupHandlerMap =
Charles Chanb7f75ac2016-01-11 18:28:54 -0800222 new ConcurrentHashMap<>();
223 /**
Saurav Das261c3002017-06-13 15:35:54 -0700224 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan53de91f2017-08-22 15:07:34 -0700225 * Used to keep track on MPLS group information.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800226 */
Saurav Das261c3002017-06-13 15:35:54 -0700227 EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
228 dsNextObjStore = null;
Charles Chanb7f75ac2016-01-11 18:28:54 -0800229 /**
Charles Chan53de91f2017-08-22 15:07:34 -0700230 * Per device next objective ID store with (device id + vlanid) as key.
231 * Used to keep track on L2 flood group information.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800232 */
Ray Milkeyb85de082017-04-05 09:42:04 -0700233 EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer>
Charles Chan10b0fb72017-02-02 16:20:42 -0800234 vlanNextObjStore = null;
Charles Chanb7f75ac2016-01-11 18:28:54 -0800235 /**
Charles Chan53de91f2017-08-22 15:07:34 -0700236 * Per device next objective ID store with (device id + port + treatment + meta) as key.
237 * Used to keep track on L2 interface group and L3 unicast group information.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800238 */
Ray Milkeyb85de082017-04-05 09:42:04 -0700239 EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer>
Saurav Das2d94d312015-11-24 23:21:05 -0800240 portNextObjStore = null;
Charles Chan10b0fb72017-02-02 16:20:42 -0800241
Saurav Das62ae6792017-05-15 15:34:25 -0700242 // Local store for all links seen and their present status, used for
243 // optimized routing. The existence of the link in the keys is enough to know
244 // if the link has been "seen-before" by this instance of the controller.
245 // The boolean value indicates if the link is currently up or not.
246 // XXX Currently the optimized routing logic depends on "forgetting" a link
247 // when a switch goes down, but "remembering" it when only the link goes down.
248 // Consider changing this logic so we can use the Link Service instead of
249 // a local cache.
250 private Map<Link, Boolean> seenLinks = new ConcurrentHashMap<>();
251
Saurav Das2d94d312015-11-24 23:21:05 -0800252 private EventuallyConsistentMap<String, Tunnel> tunnelStore = null;
253 private EventuallyConsistentMap<String, Policy> policyStore = null;
sangho4a5c42a2015-05-20 22:16:38 -0700254
Saurav Das261c3002017-06-13 15:35:54 -0700255 private AtomicBoolean programmingScheduled = new AtomicBoolean();
256
Charles Chanc91c8782016-03-30 17:54:24 -0700257 private final ConfigFactory<DeviceId, SegmentRoutingDeviceConfig> deviceConfigFactory =
Charles Chan82f19972016-05-17 13:13:55 -0700258 new ConfigFactory<DeviceId, SegmentRoutingDeviceConfig>(
259 SubjectFactories.DEVICE_SUBJECT_FACTORY,
Charles Chanc91c8782016-03-30 17:54:24 -0700260 SegmentRoutingDeviceConfig.class, "segmentrouting") {
Charles Chan72f556a2015-10-05 17:50:33 -0700261 @Override
Charles Chan82ab1932016-01-30 23:22:37 -0800262 public SegmentRoutingDeviceConfig createConfig() {
263 return new SegmentRoutingDeviceConfig();
Charles Chan72f556a2015-10-05 17:50:33 -0700264 }
265 };
Pier Ventre6b19e482016-11-07 16:21:04 -0800266
Charles Chanc91c8782016-03-30 17:54:24 -0700267 private final ConfigFactory<ApplicationId, SegmentRoutingAppConfig> appConfigFactory =
Charles Chan82f19972016-05-17 13:13:55 -0700268 new ConfigFactory<ApplicationId, SegmentRoutingAppConfig>(
269 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chanc91c8782016-03-30 17:54:24 -0700270 SegmentRoutingAppConfig.class, "segmentrouting") {
Charles Chan82ab1932016-01-30 23:22:37 -0800271 @Override
272 public SegmentRoutingAppConfig createConfig() {
273 return new SegmentRoutingAppConfig();
274 }
275 };
Pier Ventre6b19e482016-11-07 16:21:04 -0800276
Charles Chan82f19972016-05-17 13:13:55 -0700277 private final ConfigFactory<ApplicationId, XConnectConfig> xConnectConfigFactory =
278 new ConfigFactory<ApplicationId, XConnectConfig>(
279 SubjectFactories.APP_SUBJECT_FACTORY,
280 XConnectConfig.class, "xconnect") {
281 @Override
282 public XConnectConfig createConfig() {
283 return new XConnectConfig();
284 }
285 };
Pier Ventre6b19e482016-11-07 16:21:04 -0800286
Charles Chanc91c8782016-03-30 17:54:24 -0700287 private ConfigFactory<ApplicationId, McastConfig> mcastConfigFactory =
Charles Chan82f19972016-05-17 13:13:55 -0700288 new ConfigFactory<ApplicationId, McastConfig>(
289 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chanc91c8782016-03-30 17:54:24 -0700290 McastConfig.class, "multicast") {
291 @Override
292 public McastConfig createConfig() {
293 return new McastConfig();
294 }
295 };
296
Pier Ventre6b19e482016-11-07 16:21:04 -0800297 private final ConfigFactory<ApplicationId, PwaasConfig> pwaasConfigFactory =
298 new ConfigFactory<ApplicationId, PwaasConfig>(
299 SubjectFactories.APP_SUBJECT_FACTORY,
300 PwaasConfig.class, "pwaas") {
301 @Override
302 public PwaasConfig createConfig() {
303 return new PwaasConfig();
304 }
305 };
306
Charles Chan3ed34d82017-06-22 18:03:14 -0700307 private static final Object THREAD_SCHED_LOCK = new Object();
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -0700308 private static int numOfEventsQueued = 0;
309 private static int numOfEventsExecuted = 0;
sangho80f11cb2015-04-01 13:05:26 -0700310 private static int numOfHandlerExecution = 0;
311 private static int numOfHandlerScheduled = 0;
312
Charles Chan1963f4f2016-02-18 14:22:42 -0800313 /**
314 * Segment Routing App ID.
315 */
Charles Chan46fdfaf2016-11-09 20:51:44 -0800316 public static final String APP_NAME = "org.onosproject.segmentrouting";
Charles Chan10b0fb72017-02-02 16:20:42 -0800317
Charles Chanb7f75ac2016-01-11 18:28:54 -0800318 /**
319 * The default VLAN ID assigned to the interfaces without subnet config.
320 */
Charles Chan10b0fb72017-02-02 16:20:42 -0800321 public static final VlanId INTERNAL_VLAN = VlanId.vlanId((short) 4094);
Saurav Das7c305372015-10-28 12:39:42 -0700322
sangho80f11cb2015-04-01 13:05:26 -0700323 @Activate
324 protected void activate() {
Charles Chan46fdfaf2016-11-09 20:51:44 -0800325 appId = coreService.registerApplication(APP_NAME);
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700326
327 log.debug("Creating EC map nsnextobjectivestore");
Saurav Das261c3002017-06-13 15:35:54 -0700328 EventuallyConsistentMapBuilder<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700329 nsNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
Saurav Das261c3002017-06-13 15:35:54 -0700330 dsNextObjStore = nsNextObjMapBuilder
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700331 .withName("nsnextobjectivestore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700332 .withSerializer(createSerializer())
Madan Jampani675ae202015-06-24 19:05:56 -0700333 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700334 .build();
Saurav Das261c3002017-06-13 15:35:54 -0700335 log.trace("Current size {}", dsNextObjStore.size());
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700336
Charles Chan10b0fb72017-02-02 16:20:42 -0800337 log.debug("Creating EC map vlannextobjectivestore");
338 EventuallyConsistentMapBuilder<VlanNextObjectiveStoreKey, Integer>
339 vlanNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
340 vlanNextObjStore = vlanNextObjMapBuilder
341 .withName("vlannextobjectivestore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700342 .withSerializer(createSerializer())
Charles Chan77277672015-10-20 16:24:19 -0700343 .withTimestampProvider((k, v) -> new WallClockTimestamp())
344 .build();
345
Saurav Das2d94d312015-11-24 23:21:05 -0800346 log.debug("Creating EC map subnetnextobjectivestore");
347 EventuallyConsistentMapBuilder<PortNextObjectiveStoreKey, Integer>
348 portNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
349 portNextObjStore = portNextObjMapBuilder
350 .withName("portnextobjectivestore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700351 .withSerializer(createSerializer())
Saurav Das2d94d312015-11-24 23:21:05 -0800352 .withTimestampProvider((k, v) -> new WallClockTimestamp())
353 .build();
354
sangho4a5c42a2015-05-20 22:16:38 -0700355 EventuallyConsistentMapBuilder<String, Tunnel> tunnelMapBuilder =
356 storageService.eventuallyConsistentMapBuilder();
sangho4a5c42a2015-05-20 22:16:38 -0700357 tunnelStore = tunnelMapBuilder
358 .withName("tunnelstore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700359 .withSerializer(createSerializer())
Madan Jampani675ae202015-06-24 19:05:56 -0700360 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho4a5c42a2015-05-20 22:16:38 -0700361 .build();
362
363 EventuallyConsistentMapBuilder<String, Policy> policyMapBuilder =
364 storageService.eventuallyConsistentMapBuilder();
sangho4a5c42a2015-05-20 22:16:38 -0700365 policyStore = policyMapBuilder
366 .withName("policystore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700367 .withSerializer(createSerializer())
Madan Jampani675ae202015-06-24 19:05:56 -0700368 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho4a5c42a2015-05-20 22:16:38 -0700369 .build();
370
Saurav Dasc3604f12016-03-23 11:22:49 -0700371 compCfgService.preSetProperty("org.onosproject.net.group.impl.GroupManager",
Pier Luigib9632ba2017-01-12 18:14:58 -0800372 "purgeOnDisconnection", "true");
Saurav Dasc3604f12016-03-23 11:22:49 -0700373 compCfgService.preSetProperty("org.onosproject.net.flow.impl.FlowRuleManager",
Pier Luigib9632ba2017-01-12 18:14:58 -0800374 "purgeOnDisconnection", "true");
Pier Luigib9632ba2017-01-12 18:14:58 -0800375 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
376 "requestInterceptsEnabled", "false");
Charles Chanc1909e12017-08-08 15:13:37 -0700377 compCfgService.preSetProperty("org.onosproject.net.neighbour.impl.NeighbourResolutionManager",
Pier Luigibc976df2017-01-12 22:46:39 -0800378 "requestInterceptsEnabled", "false");
Charles Chan9597f8d2017-07-24 15:56:10 -0700379 compCfgService.preSetProperty("org.onosproject.dhcprelay.DhcpRelayManager",
Pier Luigibc976df2017-01-12 22:46:39 -0800380 "arpEnabled", "false");
Pier Luigi0ebeb312017-02-02 22:31:34 -0800381 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
382 "greedyLearningIpv6", "true");
Charles Chancf8ea472017-02-28 15:15:17 -0800383 compCfgService.preSetProperty("org.onosproject.routing.cpr.ControlPlaneRedirectManager",
384 "forceUnprovision", "true");
Charles Chanc7b73c72017-08-10 16:57:28 -0700385 compCfgService.preSetProperty("org.onosproject.routeservice.store.RouteStoreImpl",
Charles Chan4c95c0d2017-07-20 16:16:25 -0700386 "distributed", "true");
Charles Chan804772f2017-08-14 11:42:11 -0700387 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
388 "multihomingEnabled", "true");
Saurav Dasc3604f12016-03-23 11:22:49 -0700389
Charles Chan2b078ae2015-10-14 11:24:40 -0700390 processor = new InternalPacketProcessor();
391 linkListener = new InternalLinkListener();
392 deviceListener = new InternalDeviceListener();
Charles Chan82f19972016-05-17 13:13:55 -0700393 appCfgHandler = new AppConfigHandler(this);
394 xConnectHandler = new XConnectHandler(this);
Charles Chan1eaf4802016-04-18 13:44:03 -0700395 mcastHandler = new McastHandler(this);
396 hostHandler = new HostHandler(this);
Charles Chandebfea32016-10-24 14:52:01 -0700397 routeHandler = new RouteHandler(this);
Pier Ventreb6b81d52016-12-02 08:16:05 -0800398 neighbourHandler = new SegmentRoutingNeighbourDispatcher(this);
Pier Ventre6b19e482016-11-07 16:21:04 -0800399 l2TunnelHandler = new L2TunnelHandler(this);
Charles Chan2b078ae2015-10-14 11:24:40 -0700400
Charles Chand6d25332016-02-26 22:19:52 -0800401 cfgService.addListener(cfgListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700402 cfgService.registerConfigFactory(deviceConfigFactory);
403 cfgService.registerConfigFactory(appConfigFactory);
Charles Chan82f19972016-05-17 13:13:55 -0700404 cfgService.registerConfigFactory(xConnectConfigFactory);
Charles Chanc91c8782016-03-30 17:54:24 -0700405 cfgService.registerConfigFactory(mcastConfigFactory);
Pier Ventre6b19e482016-11-07 16:21:04 -0800406 cfgService.registerConfigFactory(pwaasConfigFactory);
Charles Chan82ab1932016-01-30 23:22:37 -0800407 hostService.addListener(hostListener);
Charles Chan2b078ae2015-10-14 11:24:40 -0700408 packetService.addProcessor(processor, PacketProcessor.director(2));
409 linkService.addListener(linkListener);
410 deviceService.addListener(deviceListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700411 multicastRouteService.addListener(mcastListener);
Charles Chanfd48c222017-06-19 00:43:31 -0700412 routeService.addListener(routeListener);
Charles Chan2b078ae2015-10-14 11:24:40 -0700413
414 cfgListener.configureNetwork();
415
sangho80f11cb2015-04-01 13:05:26 -0700416 log.info("Started");
417 }
418
Jonathan Hart54541d12016-04-12 15:39:44 -0700419 private KryoNamespace.Builder createSerializer() {
420 return new KryoNamespace.Builder()
421 .register(KryoNamespaces.API)
Saurav Das261c3002017-06-13 15:35:54 -0700422 .register(DestinationSetNextObjectiveStoreKey.class,
Charles Chan10b0fb72017-02-02 16:20:42 -0800423 VlanNextObjectiveStoreKey.class,
Saurav Das261c3002017-06-13 15:35:54 -0700424 DestinationSet.class,
425 NextNeighbors.class,
Jonathan Hart54541d12016-04-12 15:39:44 -0700426 Tunnel.class,
427 DefaultTunnel.class,
428 Policy.class,
429 TunnelPolicy.class,
430 Policy.Type.class,
431 PortNextObjectiveStoreKey.class,
Charles Chan82f19972016-05-17 13:13:55 -0700432 XConnectStoreKey.class
Jonathan Hart54541d12016-04-12 15:39:44 -0700433 );
434 }
435
sangho80f11cb2015-04-01 13:05:26 -0700436 @Deactivate
437 protected void deactivate() {
Charles Chan72f556a2015-10-05 17:50:33 -0700438 cfgService.removeListener(cfgListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700439 cfgService.unregisterConfigFactory(deviceConfigFactory);
440 cfgService.unregisterConfigFactory(appConfigFactory);
Charles Chandebfea32016-10-24 14:52:01 -0700441 cfgService.unregisterConfigFactory(xConnectConfigFactory);
Charles Chanc91c8782016-03-30 17:54:24 -0700442 cfgService.unregisterConfigFactory(mcastConfigFactory);
Pier Ventre6b19e482016-11-07 16:21:04 -0800443 cfgService.unregisterConfigFactory(pwaasConfigFactory);
Charles Chan72f556a2015-10-05 17:50:33 -0700444
Charles Chanfd48c222017-06-19 00:43:31 -0700445 hostService.removeListener(hostListener);
sangho80f11cb2015-04-01 13:05:26 -0700446 packetService.removeProcessor(processor);
Charles Chan2b078ae2015-10-14 11:24:40 -0700447 linkService.removeListener(linkListener);
448 deviceService.removeListener(deviceListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700449 multicastRouteService.removeListener(mcastListener);
Charles Chandebfea32016-10-24 14:52:01 -0700450 routeService.removeListener(routeListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700451
Charles Chan2e71ef32017-02-23 15:44:08 -0800452 neighbourResolutionService.unregisterNeighbourHandlers(appId);
453
sangho80f11cb2015-04-01 13:05:26 -0700454 processor = null;
Charles Chan2b078ae2015-10-14 11:24:40 -0700455 linkListener = null;
Charles Chanc91c8782016-03-30 17:54:24 -0700456 deviceListener = null;
Charles Chan2b078ae2015-10-14 11:24:40 -0700457 groupHandlerMap.clear();
458
Saurav Das261c3002017-06-13 15:35:54 -0700459 dsNextObjStore.destroy();
Charles Chan10b0fb72017-02-02 16:20:42 -0800460 vlanNextObjStore.destroy();
Charles Chanc91c8782016-03-30 17:54:24 -0700461 portNextObjStore.destroy();
Charles Chanc91c8782016-03-30 17:54:24 -0700462 tunnelStore.destroy();
463 policyStore.destroy();
sangho80f11cb2015-04-01 13:05:26 -0700464 log.info("Stopped");
465 }
466
sangho27462c62015-05-14 00:39:53 -0700467 @Override
468 public List<Tunnel> getTunnels() {
469 return tunnelHandler.getTunnels();
470 }
471
472 @Override
sanghobd812f82015-06-29 14:58:47 -0700473 public TunnelHandler.Result createTunnel(Tunnel tunnel) {
474 return tunnelHandler.createTunnel(tunnel);
sangho27462c62015-05-14 00:39:53 -0700475 }
476
477 @Override
sanghobd812f82015-06-29 14:58:47 -0700478 public TunnelHandler.Result removeTunnel(Tunnel tunnel) {
sangho27462c62015-05-14 00:39:53 -0700479 for (Policy policy: policyHandler.getPolicies()) {
480 if (policy.type() == Policy.Type.TUNNEL_FLOW) {
481 TunnelPolicy tunnelPolicy = (TunnelPolicy) policy;
482 if (tunnelPolicy.tunnelId().equals(tunnel.id())) {
483 log.warn("Cannot remove the tunnel used by a policy");
sanghobd812f82015-06-29 14:58:47 -0700484 return TunnelHandler.Result.TUNNEL_IN_USE;
sangho27462c62015-05-14 00:39:53 -0700485 }
486 }
487 }
sanghobd812f82015-06-29 14:58:47 -0700488 return tunnelHandler.removeTunnel(tunnel);
sangho27462c62015-05-14 00:39:53 -0700489 }
490
491 @Override
sanghobd812f82015-06-29 14:58:47 -0700492 public PolicyHandler.Result removePolicy(Policy policy) {
493 return policyHandler.removePolicy(policy);
sangho27462c62015-05-14 00:39:53 -0700494 }
495
496 @Override
sanghobd812f82015-06-29 14:58:47 -0700497 public PolicyHandler.Result createPolicy(Policy policy) {
498 return policyHandler.createPolicy(policy);
sangho27462c62015-05-14 00:39:53 -0700499 }
500
501 @Override
502 public List<Policy> getPolicies() {
503 return policyHandler.getPolicies();
504 }
505
Saurav Das07c74602016-04-27 18:35:50 -0700506 @Override
507 public void rerouteNetwork() {
508 cfgListener.configureNetwork();
Saurav Das07c74602016-04-27 18:35:50 -0700509 }
510
Charles Chand7844e52016-10-20 17:02:44 -0700511 @Override
Pier Ventreb6a7f342016-11-26 21:05:22 -0800512 public Map<DeviceId, Set<IpPrefix>> getDeviceSubnetMap() {
513 Map<DeviceId, Set<IpPrefix>> deviceSubnetMap = Maps.newHashMap();
Charles Chand7844e52016-10-20 17:02:44 -0700514 deviceService.getAvailableDevices().forEach(device -> {
515 deviceSubnetMap.put(device.id(), deviceConfiguration.getSubnets(device.id()));
516 });
517 return deviceSubnetMap;
518 }
519
Saurav Das62ae6792017-05-15 15:34:25 -0700520
521 @Override
522 public ImmutableMap<DeviceId, EcmpShortestPathGraph> getCurrentEcmpSpg() {
523 if (defaultRoutingHandler != null) {
524 return defaultRoutingHandler.getCurrentEmcpSpgMap();
525 } else {
526 return null;
527 }
528 }
529
530 @Override
Saurav Das261c3002017-06-13 15:35:54 -0700531 public ImmutableMap<DestinationSetNextObjectiveStoreKey, NextNeighbors> getDestinationSet() {
532 if (dsNextObjStore != null) {
533 return ImmutableMap.copyOf(dsNextObjStore.entrySet());
Saurav Das62ae6792017-05-15 15:34:25 -0700534 } else {
535 return ImmutableMap.of();
536 }
537 }
538
Saurav Dasfbe74572017-08-03 18:30:35 -0700539 @Override
540 public void verifyGroups(DeviceId id) {
541 DefaultGroupHandler gh = groupHandlerMap.get(id);
542 if (gh != null) {
543 gh.triggerBucketCorrector();
544 }
545 }
546
sangho80f1f892015-05-19 11:57:42 -0700547 /**
Ray Milkeyb85de082017-04-05 09:42:04 -0700548 * Extracts the application ID from the manager.
549 *
550 * @return application ID
551 */
552 public ApplicationId appId() {
553 return appId;
554 }
555
556 /**
557 * Returns the device configuration.
558 *
559 * @return device configuration
560 */
561 public DeviceConfiguration deviceConfiguration() {
562 return deviceConfiguration;
563 }
564
565 /**
Saurav Das261c3002017-06-13 15:35:54 -0700566 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan53de91f2017-08-22 15:07:34 -0700567 * Used to keep track on MPLS group information.
Ray Milkeyb85de082017-04-05 09:42:04 -0700568 *
569 * @return next objective ID store
570 */
Saurav Das261c3002017-06-13 15:35:54 -0700571 public EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
572 dsNextObjStore() {
573 return dsNextObjStore;
Ray Milkeyb85de082017-04-05 09:42:04 -0700574 }
575
576 /**
Charles Chan53de91f2017-08-22 15:07:34 -0700577 * Per device next objective ID store with (device id + vlanid) as key.
578 * Used to keep track on L2 flood group information.
Ray Milkeyb85de082017-04-05 09:42:04 -0700579 *
580 * @return vlan next object store
581 */
582 public EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer> vlanNextObjStore() {
583 return vlanNextObjStore;
584 }
585
586 /**
Charles Chan53de91f2017-08-22 15:07:34 -0700587 * Per device next objective ID store with (device id + port + treatment + meta) as key.
588 * Used to keep track on L2 interface group and L3 unicast group information.
Ray Milkeyb85de082017-04-05 09:42:04 -0700589 *
590 * @return port next object store.
591 */
592 public EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer> portNextObjStore() {
593 return portNextObjStore;
594 }
595
596 /**
Saurav Das261c3002017-06-13 15:35:54 -0700597 * Returns the MPLS-ECMP configuration which indicates whether ECMP on
598 * labeled packets should be programmed or not.
Pier Ventre7a78de22016-10-31 15:00:01 -0700599 *
600 * @return MPLS-ECMP value
601 */
602 public boolean getMplsEcmp() {
603 SegmentRoutingAppConfig segmentRoutingAppConfig = cfgService
604 .getConfig(this.appId, SegmentRoutingAppConfig.class);
605 return segmentRoutingAppConfig != null && segmentRoutingAppConfig.mplsEcmp();
606 }
607
608 /**
sangho80f1f892015-05-19 11:57:42 -0700609 * Returns the tunnel object with the tunnel ID.
610 *
611 * @param tunnelId Tunnel ID
612 * @return Tunnel reference
613 */
sangho27462c62015-05-14 00:39:53 -0700614 public Tunnel getTunnel(String tunnelId) {
615 return tunnelHandler.getTunnel(tunnelId);
616 }
617
Charles Chan90772a72017-02-08 15:52:08 -0800618 // TODO Consider moving these to InterfaceService
sangho80f11cb2015-04-01 13:05:26 -0700619 /**
Charles Chan10b0fb72017-02-02 16:20:42 -0800620 * Returns untagged VLAN configured on given connect point.
Charles Chan90772a72017-02-08 15:52:08 -0800621 * <p>
622 * Only returns the first match if there are multiple untagged VLAN configured
623 * on the connect point.
sangho80f11cb2015-04-01 13:05:26 -0700624 *
Charles Chan10b0fb72017-02-02 16:20:42 -0800625 * @param connectPoint connect point
626 * @return untagged VLAN or null if not configured
sangho80f11cb2015-04-01 13:05:26 -0700627 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700628 VlanId getUntaggedVlanId(ConnectPoint connectPoint) {
Charles Chan10b0fb72017-02-02 16:20:42 -0800629 return interfaceService.getInterfacesByPort(connectPoint).stream()
630 .filter(intf -> !intf.vlanUntagged().equals(VlanId.NONE))
631 .map(Interface::vlanUntagged)
632 .findFirst().orElse(null);
sangho80f11cb2015-04-01 13:05:26 -0700633 }
634
sangho27462c62015-05-14 00:39:53 -0700635 /**
Charles Chan90772a72017-02-08 15:52:08 -0800636 * Returns tagged VLAN configured on given connect point.
637 * <p>
638 * Returns all matches if there are multiple tagged VLAN configured
639 * on the connect point.
640 *
641 * @param connectPoint connect point
642 * @return tagged VLAN or empty set if not configured
643 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700644 Set<VlanId> getTaggedVlanId(ConnectPoint connectPoint) {
Charles Chan90772a72017-02-08 15:52:08 -0800645 Set<Interface> interfaces = interfaceService.getInterfacesByPort(connectPoint);
646 return interfaces.stream()
647 .map(Interface::vlanTagged)
Charles Chan3ed34d82017-06-22 18:03:14 -0700648 .flatMap(Set::stream)
Charles Chan90772a72017-02-08 15:52:08 -0800649 .collect(Collectors.toSet());
650 }
651
652 /**
653 * Returns native VLAN configured on given connect point.
654 * <p>
655 * Only returns the first match if there are multiple native VLAN configured
656 * on the connect point.
657 *
658 * @param connectPoint connect point
659 * @return native VLAN or null if not configured
660 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700661 VlanId getNativeVlanId(ConnectPoint connectPoint) {
Charles Chan90772a72017-02-08 15:52:08 -0800662 Set<Interface> interfaces = interfaceService.getInterfacesByPort(connectPoint);
663 return interfaces.stream()
664 .filter(intf -> !intf.vlanNative().equals(VlanId.NONE))
665 .map(Interface::vlanNative)
666 .findFirst()
667 .orElse(null);
668 }
669
670 /**
Charles Chand9265a32017-06-16 15:19:24 -0700671 * Returns internal VLAN for untagged hosts on given connect point.
672 * <p>
673 * The internal VLAN is either vlan-untagged for an access port,
674 * or vlan-native for a trunk port.
675 *
676 * @param connectPoint connect point
677 * @return internal VLAN or null if both vlan-untagged and vlan-native are undefined
678 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700679 VlanId getInternalVlanId(ConnectPoint connectPoint) {
Charles Chand9265a32017-06-16 15:19:24 -0700680 VlanId untaggedVlanId = getUntaggedVlanId(connectPoint);
681 VlanId nativeVlanId = getNativeVlanId(connectPoint);
682 return untaggedVlanId != null ? untaggedVlanId : nativeVlanId;
683 }
684
685 /**
Charles Chan3ed34d82017-06-22 18:03:14 -0700686 * Returns optional pair device ID of given device.
687 *
688 * @param deviceId device ID
689 * @return optional pair device ID. Might be empty if pair device is not configured
690 */
691 Optional<DeviceId> getPairDeviceId(DeviceId deviceId) {
692 SegmentRoutingDeviceConfig deviceConfig =
693 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
694 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairDeviceId);
695 }
696 /**
697 * Returns optional pair device local port of given device.
698 *
699 * @param deviceId device ID
700 * @return optional pair device ID. Might be empty if pair device is not configured
701 */
702 Optional<PortNumber> getPairLocalPorts(DeviceId deviceId) {
703 SegmentRoutingDeviceConfig deviceConfig =
704 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
705 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairLocalPort);
706 }
707
708 /**
Charles Chan910be6a2017-08-23 14:46:43 -0700709 * Determine if current instance is the master of given connect point.
710 *
711 * @param cp connect point
712 * @return true if current instance is the master of given connect point
713 */
714 boolean isMasterOf(ConnectPoint cp) {
715 boolean isMaster = mastershipService.isLocalMaster(cp.deviceId());
716 if (!isMaster) {
717 log.debug(NOT_MASTER, cp);
718 }
719 return isMaster;
720 }
721
722 /**
Charles Chanf0ae41e2017-08-23 13:55:39 -0700723 * Returns locations of given resolved route.
724 *
725 * @param resolvedRoute resolved route
726 * @return locations of nexthop. Might be empty if next hop is not found
727 */
728 Set<ConnectPoint> nextHopLocations(ResolvedRoute resolvedRoute) {
729 HostId hostId = HostId.hostId(resolvedRoute.nextHopMac(), resolvedRoute.nextHopVlan());
730 return Optional.ofNullable(hostService.getHost(hostId))
731 .map(Host::locations).orElse(Sets.newHashSet())
732 .stream().map(l -> (ConnectPoint) l).collect(Collectors.toSet());
733 }
734
735 /**
Charles Chan90772a72017-02-08 15:52:08 -0800736 * Returns vlan port map of given device.
737 *
738 * @param deviceId device id
739 * @return vlan-port multimap
740 */
741 public Multimap<VlanId, PortNumber> getVlanPortMap(DeviceId deviceId) {
742 HashMultimap<VlanId, PortNumber> vlanPortMap = HashMultimap.create();
743
744 interfaceService.getInterfaces().stream()
745 .filter(intf -> intf.connectPoint().deviceId().equals(deviceId))
746 .forEach(intf -> {
747 vlanPortMap.put(intf.vlanUntagged(), intf.connectPoint().port());
Charles Chan3ed34d82017-06-22 18:03:14 -0700748 intf.vlanTagged().forEach(vlanTagged ->
749 vlanPortMap.put(vlanTagged, intf.connectPoint().port())
750 );
Charles Chan90772a72017-02-08 15:52:08 -0800751 vlanPortMap.put(intf.vlanNative(), intf.connectPoint().port());
752 });
753 vlanPortMap.removeAll(VlanId.NONE);
754
755 return vlanPortMap;
756 }
757
758 /**
Charles Chan10b0fb72017-02-02 16:20:42 -0800759 * Returns the next objective ID for the given vlan id. It is expected
Saurav Das2d94d312015-11-24 23:21:05 -0800760 * that the next-objective has been pre-created from configuration.
Charles Chan77277672015-10-20 16:24:19 -0700761 *
762 * @param deviceId Device ID
Charles Chan10b0fb72017-02-02 16:20:42 -0800763 * @param vlanId VLAN ID
Saurav Das2d94d312015-11-24 23:21:05 -0800764 * @return next objective ID or -1 if it was not found
Charles Chan77277672015-10-20 16:24:19 -0700765 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700766 int getVlanNextObjectiveId(DeviceId deviceId, VlanId vlanId) {
Charles Chan77277672015-10-20 16:24:19 -0700767 if (groupHandlerMap.get(deviceId) != null) {
Charles Chan10b0fb72017-02-02 16:20:42 -0800768 log.trace("getVlanNextObjectiveId query in device {}", deviceId);
769 return groupHandlerMap.get(deviceId).getVlanNextObjectiveId(vlanId);
Charles Chan77277672015-10-20 16:24:19 -0700770 } else {
Charles Chan10b0fb72017-02-02 16:20:42 -0800771 log.warn("getVlanNextObjectiveId query - groupHandler for "
Saurav Das2d94d312015-11-24 23:21:05 -0800772 + "device {} not found", deviceId);
773 return -1;
774 }
775 }
776
777 /**
778 * Returns the next objective ID for the given portNumber, given the treatment.
779 * There could be multiple different treatments to the same outport, which
Saurav Das2cb38292017-03-29 19:09:17 -0700780 * would result in different objectives. If the next object does not exist,
781 * and should be created, a new one is created and its id is returned.
Saurav Das2d94d312015-11-24 23:21:05 -0800782 *
783 * @param deviceId Device ID
784 * @param portNum port number on device for which NextObjective is queried
785 * @param treatment the actions to apply on the packets (should include outport)
786 * @param meta metadata passed into the creation of a Next Objective if necessary
Saurav Das2cb38292017-03-29 19:09:17 -0700787 * @param createIfMissing true if a next object should be created if not found
Saurav Das07c74602016-04-27 18:35:50 -0700788 * @return next objective ID or -1 if an error occurred during retrieval or creation
Saurav Das2d94d312015-11-24 23:21:05 -0800789 */
790 public int getPortNextObjectiveId(DeviceId deviceId, PortNumber portNum,
791 TrafficTreatment treatment,
Saurav Das2cb38292017-03-29 19:09:17 -0700792 TrafficSelector meta,
793 boolean createIfMissing) {
Saurav Das2d94d312015-11-24 23:21:05 -0800794 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
795 if (ghdlr != null) {
Saurav Das2cb38292017-03-29 19:09:17 -0700796 return ghdlr.getPortNextObjectiveId(portNum, treatment, meta, createIfMissing);
Saurav Das2d94d312015-11-24 23:21:05 -0800797 } else {
Charles Chanb7f75ac2016-01-11 18:28:54 -0800798 log.warn("getPortNextObjectiveId query - groupHandler for device {}"
799 + " not found", deviceId);
800 return -1;
801 }
802 }
803
Saurav Das62ae6792017-05-15 15:34:25 -0700804 /**
805 * Returns the group handler object for the specified device id.
806 *
807 * @param devId the device identifier
808 * @return the groupHandler object for the device id, or null if not found
809 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700810 DefaultGroupHandler getGroupHandler(DeviceId devId) {
Saurav Das62ae6792017-05-15 15:34:25 -0700811 return groupHandlerMap.get(devId);
812 }
813
814 /**
Saurav Dasfbe74572017-08-03 18:30:35 -0700815 * Returns the default routing handler object.
816 *
817 * @return the default routing handler object
818 */
819 public DefaultRoutingHandler getRoutingHandler() {
820 return defaultRoutingHandler;
821 }
822
823 /**
Saurav Das62ae6792017-05-15 15:34:25 -0700824 * Returns true if this controller instance has seen this link before. The
825 * link may not be currently up, but as long as the link had been seen before
826 * this method will return true. The one exception is when the link was
827 * indeed seen before, but this controller instance was forced to forget it
828 * by a call to purgeSeenLink method.
829 *
830 * @param link the infrastructure link being queried
831 * @return true if this controller instance has seen this link before
832 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700833 boolean isSeenLink(Link link) {
Saurav Das62ae6792017-05-15 15:34:25 -0700834 return seenLinks.containsKey(link);
835 }
836
837 /**
838 * Updates the seen link store. Updates can be for links that are currently
839 * available or not.
840 *
841 * @param link the link to update in the seen-link local store
842 * @param up the status of the link, true if up, false if down
843 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700844 void updateSeenLink(Link link, boolean up) {
Saurav Das62ae6792017-05-15 15:34:25 -0700845 seenLinks.put(link, up);
846 }
847
848 /**
849 * Returns the status of a seen-link (up or down). If the link has not
850 * been seen-before, a null object is returned.
851 *
852 * @param link the infrastructure link being queried
853 * @return null if the link was not seen-before;
854 * true if the seen-link is up;
855 * false if the seen-link is down
856 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700857 Boolean isSeenLinkUp(Link link) {
Saurav Das62ae6792017-05-15 15:34:25 -0700858 return seenLinks.get(link);
859 }
860
861 /**
862 * Makes this controller instance forget a previously seen before link.
863 *
864 * @param link the infrastructure link to purge
865 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700866 private void purgeSeenLink(Link link) {
Saurav Das62ae6792017-05-15 15:34:25 -0700867 seenLinks.remove(link);
868 }
869
870 /**
871 * Returns the status of a link as parallel link. A parallel link
872 * is defined as a link which has common src and dst switches as another
873 * seen-link that is currently enabled. It is not necessary for the link being
874 * queried to be a seen-link.
875 *
876 * @param link the infrastructure link being queried
877 * @return true if a seen-link exists that is up, and shares the
878 * same src and dst switches as the link being queried
879 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700880 private boolean isParallelLink(Link link) {
Saurav Das62ae6792017-05-15 15:34:25 -0700881 for (Entry<Link, Boolean> seen : seenLinks.entrySet()) {
882 Link seenLink = seen.getKey();
883 if (seenLink.equals(link)) {
884 continue;
885 }
886 if (seenLink.src().deviceId().equals(link.src().deviceId()) &&
887 seenLink.dst().deviceId().equals(link.dst().deviceId()) &&
888 seen.getValue()) {
889 return true;
890 }
891 }
892 return false;
893 }
894
Saurav Das261c3002017-06-13 15:35:54 -0700895 /**
896 * Returns true if the link being queried is a bidirectional link. A bidi
897 * link is defined as a link, whose reverse link - ie. the link in the reverse
898 * direction - has been seen-before and is up. It is not necessary for the link
899 * being queried to be a seen-link.
900 *
901 * @param link the infrastructure link being queried
902 * @return true if another unidirectional link exists in the reverse direction,
903 * has been seen-before and is up
904 */
905 public boolean isBidirectional(Link link) {
906 Link reverseLink = linkService.getLink(link.dst(), link.src());
907 if (reverseLink == null) {
908 return false;
909 }
910 Boolean result = isSeenLinkUp(reverseLink);
911 if (result == null) {
912 return false;
913 }
914 return result.booleanValue();
915 }
916
917 /**
918 * Determines if the given link should be avoided in routing calculations
919 * by policy or design.
920 *
921 * @param link the infrastructure link being queried
922 * @return true if link should be avoided
923 */
924 public boolean avoidLink(Link link) {
925 // XXX currently only avoids all pair-links. In the future can be
926 // extended to avoid any generic link
927 DeviceId src = link.src().deviceId();
928 PortNumber srcPort = link.src().port();
929 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(src)) {
930 log.warn("Device {} not configured..cannot avoid link {}", src, link);
931 return false;
932 }
933 DeviceId pairDev;
934 PortNumber pairLocalPort, pairRemotePort = null;
935 try {
936 pairDev = deviceConfiguration.getPairDeviceId(src);
937 pairLocalPort = deviceConfiguration.getPairLocalPort(src);
938 if (pairDev != null) {
939 pairRemotePort = deviceConfiguration.getPairLocalPort(pairDev);
940 }
941 } catch (DeviceConfigNotFoundException e) {
942 log.warn("Pair dev for dev {} not configured..cannot avoid link {}",
943 src, link);
944 return false;
945 }
946
947 if (srcPort.equals(pairLocalPort) &&
948 link.dst().deviceId().equals(pairDev) &&
949 link.dst().port().equals(pairRemotePort)) {
950 return true;
951 }
952 return false;
953 }
954
sangho80f11cb2015-04-01 13:05:26 -0700955 private class InternalPacketProcessor implements PacketProcessor {
sangho80f11cb2015-04-01 13:05:26 -0700956 @Override
957 public void process(PacketContext context) {
958
959 if (context.isHandled()) {
960 return;
961 }
962
963 InboundPacket pkt = context.inPacket();
964 Ethernet ethernet = pkt.parsed();
Pier Luigi37a35432017-02-01 13:50:04 -0800965
966 if (ethernet == null) {
967 return;
968 }
969
Saurav Das261c3002017-06-13 15:35:54 -0700970 log.trace("Rcvd pktin from {}: {}", context.inPacket().receivedFrom(),
971 ethernet);
Pier Ventreadb4ae62016-11-23 09:57:42 -0800972 if (ethernet.getEtherType() == TYPE_ARP) {
Saurav Das62ae6792017-05-15 15:34:25 -0700973 log.warn("Received unexpected ARP packet on {}",
974 context.inPacket().receivedFrom());
Saurav Das368cf212017-03-15 15:15:14 -0700975 log.trace("{}", ethernet);
Pier Ventre6b2c1b32016-12-09 17:26:04 -0800976 return;
sangho80f11cb2015-04-01 13:05:26 -0700977 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV4) {
Pier Ventreb6b81d52016-12-02 08:16:05 -0800978 IPv4 ipv4Packet = (IPv4) ethernet.getPayload();
979 //ipHandler.addToPacketBuffer(ipv4Packet);
980 if (ipv4Packet.getProtocol() == IPv4.PROTOCOL_ICMP) {
981 icmpHandler.processIcmp(ethernet, pkt.receivedFrom());
sangho80f11cb2015-04-01 13:05:26 -0700982 } else {
Charles Chand041ad82017-01-13 17:20:44 -0800983 // NOTE: We don't support IP learning at this moment so this
984 // is not necessary. Also it causes duplication of DHCP packets.
Pier Ventre6b2c1b32016-12-09 17:26:04 -0800985 // ipHandler.processPacketIn(ipv4Packet, pkt.receivedFrom());
sangho80f11cb2015-04-01 13:05:26 -0700986 }
Pier Ventreb6a7f342016-11-26 21:05:22 -0800987 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV6) {
988 IPv6 ipv6Packet = (IPv6) ethernet.getPayload();
Pier Ventreb6b81d52016-12-02 08:16:05 -0800989 //ipHandler.addToPacketBuffer(ipv6Packet);
Pier Luigi37a35432017-02-01 13:50:04 -0800990 // We deal with the packet only if the packet is a ICMP6 ECHO/REPLY
Pier Ventreb6b81d52016-12-02 08:16:05 -0800991 if (ipv6Packet.getNextHeader() == IPv6.PROTOCOL_ICMP6) {
992 ICMP6 icmp6Packet = (ICMP6) ipv6Packet.getPayload();
993 if (icmp6Packet.getIcmpType() == ICMP6.ECHO_REQUEST ||
994 icmp6Packet.getIcmpType() == ICMP6.ECHO_REPLY) {
995 icmpHandler.processIcmpv6(ethernet, pkt.receivedFrom());
996 } else {
Saurav Das62ae6792017-05-15 15:34:25 -0700997 log.trace("Received ICMPv6 0x{} - not handled",
Charles Chand3727b72017-03-13 13:10:30 -0700998 Integer.toHexString(icmp6Packet.getIcmpType() & 0xff));
Pier Ventreb6b81d52016-12-02 08:16:05 -0800999 }
1000 } else {
1001 // NOTE: We don't support IP learning at this moment so this
1002 // is not necessary. Also it causes duplication of DHCPv6 packets.
1003 // ipHandler.processPacketIn(ipv6Packet, pkt.receivedFrom());
1004 }
sangho80f11cb2015-04-01 13:05:26 -07001005 }
1006 }
1007 }
1008
1009 private class InternalLinkListener implements LinkListener {
1010 @Override
1011 public void event(LinkEvent event) {
Charles Chan0cff8aa2017-03-29 16:39:05 -07001012 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1013 event.type() == LinkEvent.Type.LINK_UPDATED ||
1014 event.type() == LinkEvent.Type.LINK_REMOVED) {
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001015 log.debug("Event {} received from Link Service", event.type());
sangho80f11cb2015-04-01 13:05:26 -07001016 scheduleEventHandlerIfNotScheduled(event);
1017 }
1018 }
1019 }
1020
1021 private class InternalDeviceListener implements DeviceListener {
sangho80f11cb2015-04-01 13:05:26 -07001022 @Override
1023 public void event(DeviceEvent event) {
sangho80f11cb2015-04-01 13:05:26 -07001024 switch (event.type()) {
1025 case DEVICE_ADDED:
Saurav Dasf0f592d2016-11-18 15:21:57 -08001026 case PORT_UPDATED:
1027 case PORT_ADDED:
sanghofb7c7292015-04-13 15:15:58 -07001028 case DEVICE_UPDATED:
1029 case DEVICE_AVAILABILITY_CHANGED:
Saurav Das62ae6792017-05-15 15:34:25 -07001030 log.trace("Event {} received from Device Service", event.type());
sangho80f11cb2015-04-01 13:05:26 -07001031 scheduleEventHandlerIfNotScheduled(event);
1032 break;
1033 default:
1034 }
1035 }
1036 }
1037
Saurav Das2d94d312015-11-24 23:21:05 -08001038 @SuppressWarnings("rawtypes")
sangho80f11cb2015-04-01 13:05:26 -07001039 private void scheduleEventHandlerIfNotScheduled(Event event) {
Charles Chan3ed34d82017-06-22 18:03:14 -07001040 synchronized (THREAD_SCHED_LOCK) {
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -07001041 eventQueue.add(event);
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001042 numOfEventsQueued++;
1043
1044 if ((numOfHandlerScheduled - numOfHandlerExecution) == 0) {
1045 //No pending scheduled event handling threads. So start a new one.
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -07001046 eventHandlerFuture = executorService
1047 .schedule(eventHandler, 100, TimeUnit.MILLISECONDS);
1048 numOfHandlerScheduled++;
1049 }
Jonathan Hart54541d12016-04-12 15:39:44 -07001050 log.trace("numOfEventsQueued {}, numOfEventHandlerScheduled {}",
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001051 numOfEventsQueued,
1052 numOfHandlerScheduled);
sangho80f11cb2015-04-01 13:05:26 -07001053 }
sangho80f11cb2015-04-01 13:05:26 -07001054 }
1055
1056 private class InternalEventHandler implements Runnable {
Srikanth Vavilapalli37a461b2015-04-07 15:12:32 -07001057 @Override
sangho80f11cb2015-04-01 13:05:26 -07001058 public void run() {
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -07001059 try {
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001060 while (true) {
Saurav Das2d94d312015-11-24 23:21:05 -08001061 @SuppressWarnings("rawtypes")
Charles Chan3ed34d82017-06-22 18:03:14 -07001062 Event event;
1063 synchronized (THREAD_SCHED_LOCK) {
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001064 if (!eventQueue.isEmpty()) {
1065 event = eventQueue.poll();
1066 numOfEventsExecuted++;
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -07001067 } else {
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001068 numOfHandlerExecution++;
1069 log.debug("numOfHandlerExecution {} numOfEventsExecuted {}",
1070 numOfHandlerExecution, numOfEventsExecuted);
1071 break;
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -07001072 }
sanghofb7c7292015-04-13 15:15:58 -07001073 }
Charles Chan0cff8aa2017-03-29 16:39:05 -07001074 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1075 event.type() == LinkEvent.Type.LINK_UPDATED) {
Saurav Das62ae6792017-05-15 15:34:25 -07001076 // Note: do not update seenLinks here, otherwise every
1077 // link, even one seen for the first time, will be appear
1078 // to be a previously seen link
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001079 processLinkAdded((Link) event.subject());
1080 } else if (event.type() == LinkEvent.Type.LINK_REMOVED) {
Pier Ventre6d593892016-09-13 21:33:40 -07001081 Link linkRemoved = (Link) event.subject();
Saurav Das62ae6792017-05-15 15:34:25 -07001082 if (linkRemoved.type() == Link.Type.DIRECT) {
1083 updateSeenLink(linkRemoved, false);
1084 }
1085 // device availability check helps to ensure that
1086 // multiple link-removed events are actually treated as a
1087 // single switch removed event. purgeSeenLink is necessary
1088 // so we do rerouting (instead of rehashing) when switch
1089 // comes back.
Pier Ventre6d593892016-09-13 21:33:40 -07001090 if (linkRemoved.src().elementId() instanceof DeviceId &&
1091 !deviceService.isAvailable(linkRemoved.src().deviceId())) {
Saurav Das62ae6792017-05-15 15:34:25 -07001092 purgeSeenLink(linkRemoved);
Pier Ventre6d593892016-09-13 21:33:40 -07001093 continue;
1094 }
1095 if (linkRemoved.dst().elementId() instanceof DeviceId &&
1096 !deviceService.isAvailable(linkRemoved.dst().deviceId())) {
Saurav Das62ae6792017-05-15 15:34:25 -07001097 purgeSeenLink(linkRemoved);
Pier Ventre6d593892016-09-13 21:33:40 -07001098 continue;
1099 }
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001100 processLinkRemoved((Link) event.subject());
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001101 } else if (event.type() == DeviceEvent.Type.DEVICE_ADDED ||
1102 event.type() == DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED ||
1103 event.type() == DeviceEvent.Type.DEVICE_UPDATED) {
Saurav Das62af8802015-12-04 10:52:59 -08001104 DeviceId deviceId = ((Device) event.subject()).id();
1105 if (deviceService.isAvailable(deviceId)) {
Saurav Dasc28b3432015-10-30 17:45:38 -07001106 log.info("Processing device event {} for available device {}",
1107 event.type(), ((Device) event.subject()).id());
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001108 processDeviceAdded((Device) event.subject());
Saurav Dasc3604f12016-03-23 11:22:49 -07001109 } else {
1110 log.info("Processing device event {} for unavailable device {}",
1111 event.type(), ((Device) event.subject()).id());
1112 processDeviceRemoved((Device) event.subject());
1113 }
Saurav Dasf0f592d2016-11-18 15:21:57 -08001114 } else if (event.type() == DeviceEvent.Type.PORT_ADDED) {
Saurav Dasd1872b02016-12-02 15:43:47 -08001115 // typically these calls come when device is added first time
1116 // so port filtering rules are handled at the device_added event.
1117 // port added calls represent all ports on the device,
1118 // enabled or not.
Saurav Das62ae6792017-05-15 15:34:25 -07001119 log.trace("** PORT ADDED {}/{} -> {}",
Saurav Dasd1872b02016-12-02 15:43:47 -08001120 ((DeviceEvent) event).subject().id(),
1121 ((DeviceEvent) event).port().number(),
1122 event.type());
Saurav Dasf0f592d2016-11-18 15:21:57 -08001123 } else if (event.type() == DeviceEvent.Type.PORT_UPDATED) {
Saurav Dasd1872b02016-12-02 15:43:47 -08001124 // these calls happen for every subsequent event
1125 // ports enabled, disabled, switch goes away, comes back
Saurav Dasf0f592d2016-11-18 15:21:57 -08001126 log.info("** PORT UPDATED {}/{} -> {}",
1127 event.subject(),
1128 ((DeviceEvent) event).port(),
1129 event.type());
1130 processPortUpdated(((Device) event.subject()),
1131 ((DeviceEvent) event).port());
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001132 } else {
1133 log.warn("Unhandled event type: {}", event.type());
1134 }
sangho80f11cb2015-04-01 13:05:26 -07001135 }
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -07001136 } catch (Exception e) {
1137 log.error("SegmentRouting event handler "
1138 + "thread thrown an exception: {}", e);
sangho80f11cb2015-04-01 13:05:26 -07001139 }
sangho80f11cb2015-04-01 13:05:26 -07001140 }
1141 }
1142
sangho80f11cb2015-04-01 13:05:26 -07001143 private void processLinkAdded(Link link) {
Saurav Dasb149be12016-06-07 10:08:06 -07001144 log.info("** LINK ADDED {}", link.toString());
Saurav Das62ae6792017-05-15 15:34:25 -07001145 if (link.type() != Link.Type.DIRECT) {
1146 // NOTE: A DIRECT link might be transiently marked as INDIRECT
1147 // if BDDP is received before LLDP. We can safely ignore that
1148 // until the LLDP is received and the link is marked as DIRECT.
1149 log.info("Ignore link {}->{}. Link type is {} instead of DIRECT.",
1150 link.src(), link.dst(), link.type());
1151 return;
1152 }
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001153 if (!deviceConfiguration.isConfigured(link.src().deviceId())) {
1154 updateSeenLink(link, true);
1155 // XXX revisit - what about devicePortMap
1156 log.warn("Source device of this link is not configured.. "
1157 + "not processing further");
1158 return;
1159 }
Saurav Das62ae6792017-05-15 15:34:25 -07001160
1161 //Irrespective of whether the local is a MASTER or not for this device,
1162 //create group handler instance and push default TTP flow rules if needed,
1163 //as in a multi-instance setup, instances can initiate groups for any device.
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -07001164 DefaultGroupHandler groupHandler = groupHandlerMap.get(link.src()
1165 .deviceId());
1166 if (groupHandler != null) {
Saurav Das62ae6792017-05-15 15:34:25 -07001167 groupHandler.portUpForLink(link);
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -07001168 } else {
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001169 // XXX revisit/cleanup
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -07001170 Device device = deviceService.getDevice(link.src().deviceId());
1171 if (device != null) {
1172 log.warn("processLinkAdded: Link Added "
1173 + "Notification without Device Added "
1174 + "event, still handling it");
1175 processDeviceAdded(device);
1176 groupHandler = groupHandlerMap.get(link.src()
1177 .deviceId());
Saurav Das62ae6792017-05-15 15:34:25 -07001178 groupHandler.portUpForLink(link);
sangho80f11cb2015-04-01 13:05:26 -07001179 }
1180 }
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -07001181
Saurav Das261c3002017-06-13 15:35:54 -07001182 /*// process link only if it is bidirectional
1183 if (!isBidirectional(link)) {
1184 log.debug("Link not bidirectional.. waiting for other direction "
1185 + "src {} --> dst {} ", link.dst(), link.src());
1186 // note that if we are not processing for routing, it should at least
1187 // be considered a seen-link
1188 updateSeenLink(link, true);
1189 return;
1190 }
1191 TO DO this ensure that rehash is still done correctly even if link is
1192 not processed for rerouting - perhaps rehash in both directions when
1193 it ultimately becomes bidi?
1194 */
1195
1196 log.debug("Starting optimized route population process for link "
1197 + "{} --> {}", link.src(), link.dst());
Saurav Das62ae6792017-05-15 15:34:25 -07001198 boolean seenBefore = isSeenLink(link);
1199 defaultRoutingHandler.populateRoutingRulesForLinkStatusChange(null, link, null);
Saurav Das261c3002017-06-13 15:35:54 -07001200
1201 // It's possible that linkUp causes no route-path change as ECMP graph does
1202 // not change if the link is a parallel link (same src-dst as another link.
1203 // However we still need to update ECMP hash groups to include new buckets
1204 // for the link that has come up.
Saurav Das62ae6792017-05-15 15:34:25 -07001205 if (mastershipService.isLocalMaster(link.src().deviceId())) {
Saurav Das261c3002017-06-13 15:35:54 -07001206 if (!seenBefore && isParallelLink(link)) {
Saurav Das62ae6792017-05-15 15:34:25 -07001207 // if link seen first time, we need to ensure hash-groups have all ports
Saurav Das261c3002017-06-13 15:35:54 -07001208 log.debug("Attempting retryHash for paralled first-time link {}", link);
Saurav Das62ae6792017-05-15 15:34:25 -07001209 groupHandler.retryHash(link, false, true);
1210 } else {
1211 //seen before-link
1212 if (isParallelLink(link)) {
Saurav Das261c3002017-06-13 15:35:54 -07001213 log.debug("Attempting retryHash for paralled seen-before "
1214 + "link {}", link);
Saurav Das62ae6792017-05-15 15:34:25 -07001215 groupHandler.retryHash(link, false, false);
1216 }
1217 }
1218 }
Charles Chan72779502016-04-23 17:36:10 -07001219
1220 mcastHandler.init();
sangho80f11cb2015-04-01 13:05:26 -07001221 }
1222
1223 private void processLinkRemoved(Link link) {
Saurav Dasb149be12016-06-07 10:08:06 -07001224 log.info("** LINK REMOVED {}", link.toString());
Saurav Das62ae6792017-05-15 15:34:25 -07001225 defaultRoutingHandler.populateRoutingRulesForLinkStatusChange(link, null, null);
1226
1227 // update local groupHandler stores
sangho2165d222015-05-01 09:38:25 -07001228 DefaultGroupHandler groupHandler = groupHandlerMap.get(link.src().deviceId());
1229 if (groupHandler != null) {
Saurav Das62ae6792017-05-15 15:34:25 -07001230 if (mastershipService.isLocalMaster(link.src().deviceId()) &&
1231 isParallelLink(link)) {
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001232 log.debug("* retrying hash for parallel link removed:{}", link);
Saurav Das62ae6792017-05-15 15:34:25 -07001233 groupHandler.retryHash(link, true, false);
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001234 } else {
1235 log.debug("Not attempting retry-hash for link removed: {} .. {}", link,
1236 (mastershipService.isLocalMaster(link.src().deviceId()))
1237 ? "not parallel" : "not master");
Saurav Das62ae6792017-05-15 15:34:25 -07001238 }
1239 // ensure local stores are updated
1240 groupHandler.portDown(link.src().port());
1241 } else {
1242 log.warn("group handler not found for dev:{} when removing link: {}",
1243 link.src().deviceId(), link);
sangho2165d222015-05-01 09:38:25 -07001244 }
Charles Chan72779502016-04-23 17:36:10 -07001245
1246 mcastHandler.processLinkDown(link);
sangho80f11cb2015-04-01 13:05:26 -07001247 }
1248
1249 private void processDeviceAdded(Device device) {
Saurav Dasb149be12016-06-07 10:08:06 -07001250 log.info("** DEVICE ADDED with ID {}", device.id());
Charles Chan9bd6aea2017-06-27 18:48:32 -07001251
1252 // NOTE: Punt ARP/NDP even when the device is not configured.
1253 // Host learning without network config is required for CORD config generator.
1254 routingRulePopulator.populateIpPunts(device.id());
1255 routingRulePopulator.populateArpNdpPunts(device.id());
1256
Charles Chan319d1a22015-11-03 10:42:14 -08001257 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
Saurav Das261c3002017-06-13 15:35:54 -07001258 log.warn("Device configuration unavailable. Device {} will be "
1259 + "processed after configuration.", device.id());
Saurav Das8ec0ec42015-11-03 14:39:27 -08001260 return;
1261 }
Charles Chan72779502016-04-23 17:36:10 -07001262 processDeviceAddedInternal(device.id());
1263 }
1264
1265 private void processDeviceAddedInternal(DeviceId deviceId) {
Saurav Dasc28b3432015-10-30 17:45:38 -07001266 // Irrespective of whether the local is a MASTER or not for this device,
1267 // we need to create a SR-group-handler instance. This is because in a
1268 // multi-instance setup, any instance can initiate forwarding/next-objectives
1269 // for any switch (even if this instance is a SLAVE or not even connected
1270 // to the switch). To handle this, a default-group-handler instance is necessary
1271 // per switch.
Charles Chan72779502016-04-23 17:36:10 -07001272 log.debug("Current groupHandlerMap devs: {}", groupHandlerMap.keySet());
1273 if (groupHandlerMap.get(deviceId) == null) {
Charles Chan319d1a22015-11-03 10:42:14 -08001274 DefaultGroupHandler groupHandler;
1275 try {
1276 groupHandler = DefaultGroupHandler.
Charles Chan72779502016-04-23 17:36:10 -07001277 createGroupHandler(deviceId,
1278 appId,
1279 deviceConfiguration,
1280 linkService,
1281 flowObjectiveService,
1282 this);
Charles Chan319d1a22015-11-03 10:42:14 -08001283 } catch (DeviceConfigNotFoundException e) {
1284 log.warn(e.getMessage() + " Aborting processDeviceAdded.");
1285 return;
1286 }
Charles Chan72779502016-04-23 17:36:10 -07001287 log.debug("updating groupHandlerMap with new config for device: {}",
1288 deviceId);
1289 groupHandlerMap.put(deviceId, groupHandler);
Saurav Das8ec0ec42015-11-03 14:39:27 -08001290 }
Saurav Dasb149be12016-06-07 10:08:06 -07001291
Charles Chan72779502016-04-23 17:36:10 -07001292 if (mastershipService.isLocalMaster(deviceId)) {
Saurav Dasf9332192017-02-18 14:05:44 -08001293 defaultRoutingHandler.populatePortAddressingRules(deviceId);
Charles Chandebfea32016-10-24 14:52:01 -07001294 hostHandler.init(deviceId);
Charles Chan82f19972016-05-17 13:13:55 -07001295 xConnectHandler.init(deviceId);
Charles Chan72779502016-04-23 17:36:10 -07001296 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
Charles Chan10b0fb72017-02-02 16:20:42 -08001297 groupHandler.createGroupsFromVlanConfig();
Charles Chan72779502016-04-23 17:36:10 -07001298 routingRulePopulator.populateSubnetBroadcastRule(deviceId);
Charles Chan77277672015-10-20 16:24:19 -07001299 }
Charles Chan82ab1932016-01-30 23:22:37 -08001300
Charles Chandebfea32016-10-24 14:52:01 -07001301 appCfgHandler.init(deviceId);
1302 routeHandler.init(deviceId);
sangho80f11cb2015-04-01 13:05:26 -07001303 }
1304
Saurav Dasc3604f12016-03-23 11:22:49 -07001305 private void processDeviceRemoved(Device device) {
Saurav Das261c3002017-06-13 15:35:54 -07001306 dsNextObjStore.entrySet().stream()
Saurav Dasc3604f12016-03-23 11:22:49 -07001307 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
1308 .forEach(entry -> {
Saurav Das261c3002017-06-13 15:35:54 -07001309 dsNextObjStore.remove(entry.getKey());
Saurav Dasc3604f12016-03-23 11:22:49 -07001310 });
Charles Chan10b0fb72017-02-02 16:20:42 -08001311 vlanNextObjStore.entrySet().stream()
Saurav Dasc3604f12016-03-23 11:22:49 -07001312 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan3ed34d82017-06-22 18:03:14 -07001313 .forEach(entry -> vlanNextObjStore.remove(entry.getKey()));
Saurav Dasc3604f12016-03-23 11:22:49 -07001314 portNextObjStore.entrySet().stream()
1315 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan3ed34d82017-06-22 18:03:14 -07001316 .forEach(entry -> portNextObjStore.remove(entry.getKey()));
Charles Chan17d75d82017-06-15 00:44:51 -07001317
1318 seenLinks.keySet().removeIf(key -> key.src().deviceId().equals(device.id()) ||
1319 key.dst().deviceId().equals(device.id()));
1320
Saurav Dasfbe74572017-08-03 18:30:35 -07001321 DefaultGroupHandler gh = groupHandlerMap.remove(device.id());
1322 if (gh != null) {
1323 gh.shutdown();
1324 }
Saurav Dasc3604f12016-03-23 11:22:49 -07001325 defaultRoutingHandler.purgeEcmpGraph(device.id());
Saurav Das62ae6792017-05-15 15:34:25 -07001326 // Note that a switch going down is associated with all of its links
1327 // going down as well, but it is treated as a single switch down event
1328 // while the link-downs are ignored.
1329 defaultRoutingHandler
1330 .populateRoutingRulesForLinkStatusChange(null, null, device.id());
Charles Chan72779502016-04-23 17:36:10 -07001331 mcastHandler.removeDevice(device.id());
Charles Chan82f19972016-05-17 13:13:55 -07001332 xConnectHandler.removeDevice(device.id());
Saurav Dasc3604f12016-03-23 11:22:49 -07001333 }
1334
Saurav Dasf0f592d2016-11-18 15:21:57 -08001335 private void processPortUpdated(Device device, Port port) {
1336 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
1337 log.warn("Device configuration uploading. Not handling port event for"
1338 + "dev: {} port: {}", device.id(), port.number());
1339 return;
1340 }
Saurav Dasf9332192017-02-18 14:05:44 -08001341
1342 if (!mastershipService.isLocalMaster(device.id())) {
1343 log.debug("Not master for dev:{} .. not handling port updated event"
1344 + "for port {}", device.id(), port.number());
1345 return;
1346 }
1347
1348 // first we handle filtering rules associated with the port
1349 if (port.isEnabled()) {
1350 log.info("Switchport {}/{} enabled..programming filters",
1351 device.id(), port.number());
Charles Chan43be46b2017-02-26 22:59:35 -08001352 routingRulePopulator.processSinglePortFilters(device.id(), port.number(), true);
Saurav Dasf9332192017-02-18 14:05:44 -08001353 } else {
1354 log.info("Switchport {}/{} disabled..removing filters",
1355 device.id(), port.number());
Charles Chan43be46b2017-02-26 22:59:35 -08001356 routingRulePopulator.processSinglePortFilters(device.id(), port.number(), false);
Saurav Dasf9332192017-02-18 14:05:44 -08001357 }
Saurav Dasf0f592d2016-11-18 15:21:57 -08001358
1359 // portUpdated calls are for ports that have gone down or up. For switch
1360 // to switch ports, link-events should take care of any re-routing or
1361 // group editing necessary for port up/down. Here we only process edge ports
1362 // that are already configured.
Saurav Das3fb28272017-03-04 16:08:47 -08001363 ConnectPoint cp = new ConnectPoint(device.id(), port.number());
1364 VlanId untaggedVlan = getUntaggedVlanId(cp);
1365 VlanId nativeVlan = getNativeVlanId(cp);
1366 Set<VlanId> taggedVlans = getTaggedVlanId(cp);
Charles Chan10b0fb72017-02-02 16:20:42 -08001367
Saurav Das3fb28272017-03-04 16:08:47 -08001368 if (untaggedVlan == null && nativeVlan == null && taggedVlans.isEmpty()) {
Saurav Das62ae6792017-05-15 15:34:25 -07001369 log.debug("Not handling port updated event for non-edge port (unconfigured) "
Saurav Dasf0f592d2016-11-18 15:21:57 -08001370 + "dev/port: {}/{}", device.id(), port.number());
1371 return;
1372 }
Saurav Das3fb28272017-03-04 16:08:47 -08001373 if (untaggedVlan != null) {
1374 processEdgePort(device, port, untaggedVlan, true);
1375 }
1376 if (nativeVlan != null) {
1377 processEdgePort(device, port, nativeVlan, true);
1378 }
1379 if (!taggedVlans.isEmpty()) {
1380 taggedVlans.forEach(tag -> processEdgePort(device, port, tag, false));
1381 }
Saurav Dasf0f592d2016-11-18 15:21:57 -08001382 }
1383
Saurav Das3fb28272017-03-04 16:08:47 -08001384 private void processEdgePort(Device device, Port port, VlanId vlanId,
1385 boolean popVlan) {
Saurav Dasf0f592d2016-11-18 15:21:57 -08001386 boolean portUp = port.isEnabled();
1387 if (portUp) {
Saurav Das3fb28272017-03-04 16:08:47 -08001388 log.info("Device:EdgePort {}:{} is enabled in vlan: {}", device.id(),
Charles Chan10b0fb72017-02-02 16:20:42 -08001389 port.number(), vlanId);
Saurav Dasf0f592d2016-11-18 15:21:57 -08001390 } else {
Saurav Das3fb28272017-03-04 16:08:47 -08001391 log.info("Device:EdgePort {}:{} is disabled in vlan: {}", device.id(),
Charles Chan10b0fb72017-02-02 16:20:42 -08001392 port.number(), vlanId);
Saurav Dasf0f592d2016-11-18 15:21:57 -08001393 }
1394
Srikanth Vavilapalli64505482015-04-21 13:04:13 -07001395 DefaultGroupHandler groupHandler = groupHandlerMap.get(device.id());
sangho80f11cb2015-04-01 13:05:26 -07001396 if (groupHandler != null) {
Saurav Das3fb28272017-03-04 16:08:47 -08001397 groupHandler.processEdgePort(port.number(), vlanId, popVlan, portUp);
Saurav Dasf0f592d2016-11-18 15:21:57 -08001398 } else {
1399 log.warn("Group handler not found for dev:{}. Not handling edge port"
1400 + " {} event for port:{}", device.id(),
1401 (portUp) ? "UP" : "DOWN", port.number());
sangho80f11cb2015-04-01 13:05:26 -07001402 }
1403 }
sangho27462c62015-05-14 00:39:53 -07001404
Charles Chan8ca5a122017-10-20 16:06:55 -07001405 private void createOrUpdateDeviceConfiguration() {
1406 if (deviceConfiguration == null) {
1407 deviceConfiguration = new DeviceConfiguration(this);
1408 } else {
1409 deviceConfiguration.updateConfig();
1410 }
1411 }
1412
Pier Ventreb6a7f342016-11-26 21:05:22 -08001413 /**
1414 * Registers the given connect point with the NRS, this is necessary
1415 * to receive the NDP and ARP packets from the NRS.
1416 *
1417 * @param portToRegister connect point to register
1418 */
1419 public void registerConnectPoint(ConnectPoint portToRegister) {
Charles Chan2e71ef32017-02-23 15:44:08 -08001420 neighbourResolutionService.registerNeighbourHandler(
Pier Ventreb6a7f342016-11-26 21:05:22 -08001421 portToRegister,
1422 neighbourHandler,
1423 appId
1424 );
1425 }
1426
Charles Chan72f556a2015-10-05 17:50:33 -07001427 private class InternalConfigListener implements NetworkConfigListener {
Saurav Das261c3002017-06-13 15:35:54 -07001428 private static final long PROGRAM_DELAY = 2;
Charles Chan46fdfaf2016-11-09 20:51:44 -08001429 SegmentRoutingManager srManager;
Charles Chane7c61022015-10-07 14:21:45 -07001430
Charles Chanb7f75ac2016-01-11 18:28:54 -08001431 /**
1432 * Constructs the internal network config listener.
1433 *
Charles Chan46fdfaf2016-11-09 20:51:44 -08001434 * @param srManager segment routing manager
Charles Chanb7f75ac2016-01-11 18:28:54 -08001435 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001436 InternalConfigListener(SegmentRoutingManager srManager) {
Charles Chan46fdfaf2016-11-09 20:51:44 -08001437 this.srManager = srManager;
Charles Chane7c61022015-10-07 14:21:45 -07001438 }
1439
Charles Chanb7f75ac2016-01-11 18:28:54 -08001440 /**
1441 * Reads network config and initializes related data structure accordingly.
1442 */
Charles Chane7c61022015-10-07 14:21:45 -07001443 public void configureNetwork() {
Charles Chan8ca5a122017-10-20 16:06:55 -07001444 createOrUpdateDeviceConfiguration();
Charles Chane7c61022015-10-07 14:21:45 -07001445
Charles Chan46fdfaf2016-11-09 20:51:44 -08001446 arpHandler = new ArpHandler(srManager);
1447 icmpHandler = new IcmpHandler(srManager);
1448 ipHandler = new IpHandler(srManager);
1449 routingRulePopulator = new RoutingRulePopulator(srManager);
1450 defaultRoutingHandler = new DefaultRoutingHandler(srManager);
Charles Chane7c61022015-10-07 14:21:45 -07001451
1452 tunnelHandler = new TunnelHandler(linkService, deviceConfiguration,
1453 groupHandlerMap, tunnelStore);
1454 policyHandler = new PolicyHandler(appId, deviceConfiguration,
1455 flowObjectiveService,
1456 tunnelHandler, policyStore);
Saurav Das261c3002017-06-13 15:35:54 -07001457 // add a small delay to absorb multiple network config added notifications
1458 if (!programmingScheduled.get()) {
1459 programmingScheduled.set(true);
1460 executorService.schedule(new ConfigChange(), PROGRAM_DELAY,
1461 TimeUnit.SECONDS);
Charles Chane7c61022015-10-07 14:21:45 -07001462 }
Charles Chan72779502016-04-23 17:36:10 -07001463 mcastHandler.init();
Charles Chane7c61022015-10-07 14:21:45 -07001464 }
1465
Charles Chan72f556a2015-10-05 17:50:33 -07001466 @Override
1467 public void event(NetworkConfigEvent event) {
Charles Chan82ab1932016-01-30 23:22:37 -08001468 // TODO move this part to NetworkConfigEventHandler
1469 if (event.configClass().equals(SegmentRoutingDeviceConfig.class)) {
1470 switch (event.type()) {
1471 case CONFIG_ADDED:
Charles Chan68363b12017-06-26 15:25:09 -07001472 log.info("Segment Routing Device Config added for {}", event.subject());
Charles Chan82ab1932016-01-30 23:22:37 -08001473 configureNetwork();
1474 break;
1475 case CONFIG_UPDATED:
Charles Chan68363b12017-06-26 15:25:09 -07001476 log.info("Segment Routing Config updated for {}", event.subject());
Charles Chan8ca5a122017-10-20 16:06:55 -07001477 createOrUpdateDeviceConfiguration();
Charles Chan68363b12017-06-26 15:25:09 -07001478 // TODO support dynamic configuration
1479 break;
1480 default:
1481 break;
1482 }
1483 } else if (event.configClass().equals(InterfaceConfig.class)) {
1484 switch (event.type()) {
1485 case CONFIG_ADDED:
1486 log.info("Interface Config added for {}", event.subject());
1487 configureNetwork();
1488 break;
1489 case CONFIG_UPDATED:
1490 log.info("Interface Config updated for {}", event.subject());
Charles Chan8ca5a122017-10-20 16:06:55 -07001491 createOrUpdateDeviceConfiguration();
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001492
1493 // Following code will be uncommented when [CORD-634] is fully implemented.
1494 // [CORD-634] Add dynamic config support for interfaces
1495 updateInterface((InterfaceConfig) event.config().get(),
1496 (InterfaceConfig) event.prevConfig().get());
Charles Chan82ab1932016-01-30 23:22:37 -08001497 // TODO support dynamic configuration
1498 break;
1499 default:
1500 break;
Charles Chan2b078ae2015-10-14 11:24:40 -07001501 }
Charles Chan82ab1932016-01-30 23:22:37 -08001502 } else if (event.configClass().equals(SegmentRoutingAppConfig.class)) {
Charles Chan82f19972016-05-17 13:13:55 -07001503 checkState(appCfgHandler != null, "NetworkConfigEventHandler is not initialized");
Charles Chan82ab1932016-01-30 23:22:37 -08001504 switch (event.type()) {
1505 case CONFIG_ADDED:
Charles Chan82f19972016-05-17 13:13:55 -07001506 appCfgHandler.processAppConfigAdded(event);
Charles Chan82ab1932016-01-30 23:22:37 -08001507 break;
1508 case CONFIG_UPDATED:
Charles Chan82f19972016-05-17 13:13:55 -07001509 appCfgHandler.processAppConfigUpdated(event);
Charles Chan82ab1932016-01-30 23:22:37 -08001510 break;
1511 case CONFIG_REMOVED:
Charles Chan82f19972016-05-17 13:13:55 -07001512 appCfgHandler.processAppConfigRemoved(event);
1513 break;
1514 default:
1515 break;
1516 }
Charles Chandebfea32016-10-24 14:52:01 -07001517 configureNetwork();
Charles Chan82f19972016-05-17 13:13:55 -07001518 } else if (event.configClass().equals(XConnectConfig.class)) {
1519 checkState(xConnectHandler != null, "XConnectHandler is not initialized");
1520 switch (event.type()) {
1521 case CONFIG_ADDED:
1522 xConnectHandler.processXConnectConfigAdded(event);
1523 break;
1524 case CONFIG_UPDATED:
1525 xConnectHandler.processXConnectConfigUpdated(event);
1526 break;
1527 case CONFIG_REMOVED:
1528 xConnectHandler.processXConnectConfigRemoved(event);
Charles Chan82ab1932016-01-30 23:22:37 -08001529 break;
1530 default:
1531 break;
Charles Chan2b078ae2015-10-14 11:24:40 -07001532 }
Pier Ventre6b19e482016-11-07 16:21:04 -08001533 } else if (event.configClass().equals(PwaasConfig.class)) {
1534 checkState(l2TunnelHandler != null, "L2TunnelHandler is not initialized");
1535 switch (event.type()) {
1536 case CONFIG_ADDED:
1537 l2TunnelHandler.processPwaasConfigAdded(event);
1538 break;
1539 case CONFIG_UPDATED:
1540 l2TunnelHandler.processPwaasConfigUpdated(event);
1541 break;
1542 case CONFIG_REMOVED:
1543 l2TunnelHandler.processPwaasConfigRemoved(event);
1544 break;
1545 default:
1546 break;
1547 }
Charles Chan72f556a2015-10-05 17:50:33 -07001548 }
1549 }
Saurav Das261c3002017-06-13 15:35:54 -07001550
1551 private final class ConfigChange implements Runnable {
1552 @Override
1553 public void run() {
1554 programmingScheduled.set(false);
1555 for (Device device : deviceService.getDevices()) {
1556 processDeviceAdded(device);
1557 }
1558 defaultRoutingHandler.startPopulationProcess();
1559 }
1560 }
Charles Chan72f556a2015-10-05 17:50:33 -07001561 }
Charles Chanf4586112015-11-09 16:37:23 -08001562
1563 private class InternalHostListener implements HostListener {
Charles Chanf4586112015-11-09 16:37:23 -08001564 @Override
1565 public void event(HostEvent event) {
Charles Chanf4586112015-11-09 16:37:23 -08001566 switch (event.type()) {
1567 case HOST_ADDED:
Charles Chan1eaf4802016-04-18 13:44:03 -07001568 hostHandler.processHostAddedEvent(event);
Charles Chanf4586112015-11-09 16:37:23 -08001569 break;
1570 case HOST_MOVED:
Charles Chan1eaf4802016-04-18 13:44:03 -07001571 hostHandler.processHostMovedEvent(event);
Charles Chan910be6a2017-08-23 14:46:43 -07001572 routeHandler.processHostMovedEvent(event);
Charles Chanf4586112015-11-09 16:37:23 -08001573 break;
1574 case HOST_REMOVED:
Charles Chand9265a32017-06-16 15:19:24 -07001575 hostHandler.processHostRemovedEvent(event);
Charles Chanf4586112015-11-09 16:37:23 -08001576 break;
1577 case HOST_UPDATED:
Charles Chan1eaf4802016-04-18 13:44:03 -07001578 hostHandler.processHostUpdatedEvent(event);
Charles Chanf4586112015-11-09 16:37:23 -08001579 break;
1580 default:
1581 log.warn("Unsupported host event type: {}", event.type());
1582 break;
1583 }
1584 }
1585 }
1586
Charles Chanc91c8782016-03-30 17:54:24 -07001587 private class InternalMcastListener implements McastListener {
1588 @Override
1589 public void event(McastEvent event) {
1590 switch (event.type()) {
1591 case SOURCE_ADDED:
Charles Chan1eaf4802016-04-18 13:44:03 -07001592 mcastHandler.processSourceAdded(event);
Charles Chanc91c8782016-03-30 17:54:24 -07001593 break;
1594 case SINK_ADDED:
Charles Chan1eaf4802016-04-18 13:44:03 -07001595 mcastHandler.processSinkAdded(event);
Charles Chanc91c8782016-03-30 17:54:24 -07001596 break;
1597 case SINK_REMOVED:
Charles Chan1eaf4802016-04-18 13:44:03 -07001598 mcastHandler.processSinkRemoved(event);
Charles Chanc91c8782016-03-30 17:54:24 -07001599 break;
1600 case ROUTE_ADDED:
1601 case ROUTE_REMOVED:
1602 default:
1603 break;
1604 }
1605 }
1606 }
Charles Chan41f5ec02016-06-13 18:54:31 -07001607
Charles Chandebfea32016-10-24 14:52:01 -07001608 private class InternalRouteEventListener implements RouteListener {
1609 @Override
1610 public void event(RouteEvent event) {
1611 switch (event.type()) {
1612 case ROUTE_ADDED:
1613 routeHandler.processRouteAdded(event);
1614 break;
1615 case ROUTE_UPDATED:
1616 routeHandler.processRouteUpdated(event);
1617 break;
1618 case ROUTE_REMOVED:
1619 routeHandler.processRouteRemoved(event);
1620 break;
Charles Chan910be6a2017-08-23 14:46:43 -07001621 case ALTERNATIVE_ROUTES_CHANGED:
1622 routeHandler.processAlternativeRoutesChanged(event);
1623 break;
Charles Chandebfea32016-10-24 14:52:01 -07001624 default:
1625 break;
1626 }
1627 }
1628 }
Saurav Das62ae6792017-05-15 15:34:25 -07001629
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001630 private void updateInterface(InterfaceConfig conf, InterfaceConfig prevConf) {
1631 try {
1632 Set<Interface> intfs = conf.getInterfaces();
1633 Set<Interface> prevIntfs = prevConf.getInterfaces();
1634
1635 // Now we only handle one interface config at each port.
1636 if (intfs.size() != 1 || prevIntfs.size() != 1) {
1637 log.warn("Interface update aborted - one at a time is allowed, " +
1638 "but {} / {}(prev) received.", intfs.size(), prevIntfs.size());
1639 return;
1640 }
1641
1642 Interface intf = intfs.stream().findFirst().get();
1643 Interface prevIntf = prevIntfs.stream().findFirst().get();
1644
1645 DeviceId deviceId = intf.connectPoint().deviceId();
1646 PortNumber portNum = intf.connectPoint().port();
1647
1648 if (!mastershipService.isLocalMaster(deviceId)) {
1649 log.debug("CONFIG_UPDATED event for interfaces should be " +
1650 "handled by master node for device {}", deviceId);
1651 return;
1652 }
1653
1654 removeSubnetConfig(prevIntf.connectPoint(),
1655 Sets.difference(new HashSet<>(prevIntf.ipAddressesList()),
1656 new HashSet<>(intf.ipAddressesList())));
1657
1658 if (prevIntf.vlanNative() != VlanId.NONE && !intf.vlanNative().equals(prevIntf.vlanNative())) {
1659 // RemoveVlanNative
1660 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanNative(), true, false);
1661 }
1662
1663 if (!prevIntf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
1664 // RemoveVlanTagged
1665 prevIntf.vlanTagged().stream().filter(i -> !intf.vlanTagged().contains(i)).forEach(
1666 vlanId -> updateVlanConfigInternal(deviceId, portNum, vlanId, false, false)
1667 );
1668 }
1669
1670 if (prevIntf.vlanUntagged() != VlanId.NONE && !intf.vlanUntagged().equals(prevIntf.vlanUntagged())) {
1671 // RemoveVlanUntagged
1672 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanUntagged(), true, false);
1673 }
1674
1675 if (intf.vlanNative() != VlanId.NONE && !prevIntf.vlanNative().equals(intf.vlanNative())) {
1676 // AddVlanNative
1677 updateVlanConfigInternal(deviceId, portNum, intf.vlanNative(), true, true);
1678 }
1679
1680 if (!intf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
1681 // AddVlanTagged
1682 intf.vlanTagged().stream().filter(i -> !prevIntf.vlanTagged().contains(i)).forEach(
1683 vlanId -> updateVlanConfigInternal(deviceId, portNum, vlanId, false, true)
1684 );
1685 }
1686
1687 if (intf.vlanUntagged() != VlanId.NONE && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())) {
1688 // AddVlanUntagged
1689 updateVlanConfigInternal(deviceId, portNum, intf.vlanUntagged(), true, true);
1690 }
1691 addSubnetConfig(prevIntf.connectPoint(),
1692 Sets.difference(new HashSet<>(intf.ipAddressesList()),
1693 new HashSet<>(prevIntf.ipAddressesList())));
1694 } catch (ConfigException e) {
1695 log.error("Error in configuration");
1696 }
1697 }
1698
1699 private void updateVlanConfigInternal(DeviceId deviceId, PortNumber portNum,
1700 VlanId vlanId, boolean pushVlan, boolean install) {
1701 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
1702 if (grpHandler == null) {
1703 log.warn("Failed to retrieve group handler for device {}", deviceId);
1704 return;
1705 }
1706
1707 // Update filtering objective for a single port
1708 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, install);
1709
1710 // Update filtering objective for multicast ingress port
1711 mcastHandler.updateFilterToDevice(deviceId, portNum, vlanId, install);
1712
1713 int nextId = getVlanNextObjectiveId(deviceId, vlanId);
1714
1715 if (nextId != -1 && !install) {
1716 // Update next objective for a single port as an output port
1717 // Remove a single port from L2FG
1718 grpHandler.updateGroupFromVlanConfiguration(portNum, Collections.singleton(vlanId), nextId, install);
1719 // Remove L2 Bridging rule and L3 Unicast rule to the host
1720 hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum, vlanId, pushVlan, install);
1721 // Remove broadcast forwarding rule and corresponding L2FG for VLAN
1722 // only if there is no port configured on that VLAN ID
1723 if (!getVlanPortMap(deviceId).containsKey(vlanId)) {
1724 // Remove broadcast forwarding rule for the VLAN
1725 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
1726 // Remove L2FG for VLAN
1727 grpHandler.removeBcastGroupFromVlan(deviceId, portNum, vlanId, pushVlan);
1728 } else {
1729 // Remove L2IG of the port
1730 grpHandler.removePortNextObjective(deviceId, portNum, vlanId, pushVlan);
1731 }
1732 } else if (install) {
1733 if (nextId != -1) {
1734 // Add a single port to L2FG
1735 grpHandler.updateGroupFromVlanConfiguration(portNum, Collections.singleton(vlanId), nextId, install);
1736 } else {
1737 // Create L2FG for VLAN
1738 grpHandler.createBcastGroupFromVlan(vlanId, Collections.singleton(portNum));
1739 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
1740 }
1741 hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum, vlanId, pushVlan, install);
1742 } else {
1743 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
1744 }
1745 }
1746
1747 private void removeSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
1748 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
1749 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
1750
1751 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
1752 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
1753 .filter(intf -> !intf.connectPoint().equals(cp))
1754 .flatMap(intf -> intf.ipAddressesList().stream())
1755 .collect(Collectors.toSet());
1756 // 1. Partial subnet population
1757 // Remove routing rules for removed subnet from previous configuration,
1758 // which does not also exist in other interfaces in the same device
1759 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
1760 .map(InterfaceIpAddress::subnetAddress)
1761 .collect(Collectors.toSet());
1762
1763 defaultRoutingHandler.revokeSubnet(
1764 ipPrefixSet.stream()
1765 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
1766 .collect(Collectors.toSet()));
1767
1768 // 2. Interface IP punts
1769 // Remove IP punts for old Intf address
1770 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
1771 .map(InterfaceIpAddress::ipAddress)
1772 .collect(Collectors.toSet());
1773 ipAddressSet.stream()
1774 .map(InterfaceIpAddress::ipAddress)
1775 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
1776 .forEach(interfaceIpAddress ->
1777 routingRulePopulator.revokeSingleIpPunts(
1778 cp.deviceId(), interfaceIpAddress));
1779
1780 // 3. Host unicast routing rule
1781 // Remove unicast routing rule
1782 hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, false);
1783 }
1784
1785 private void addSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
1786 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
1787 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
1788
1789 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
1790 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
1791 .filter(intf -> !intf.connectPoint().equals(cp))
1792 .flatMap(intf -> intf.ipAddressesList().stream())
1793 .collect(Collectors.toSet());
1794 // 1. Partial subnet population
1795 // Add routing rules for newly added subnet, which does not also exist in
1796 // other interfaces in the same device
1797 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
1798 .map(InterfaceIpAddress::subnetAddress)
1799 .collect(Collectors.toSet());
1800
1801 defaultRoutingHandler.populateSubnet(
1802 Collections.singleton(cp),
1803 ipPrefixSet.stream()
1804 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
1805 .collect(Collectors.toSet()));
1806
1807 // 2. Interface IP punts
1808 // Add IP punts for new Intf address
1809 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
1810 .map(InterfaceIpAddress::ipAddress)
1811 .collect(Collectors.toSet());
1812 ipAddressSet.stream()
1813 .map(InterfaceIpAddress::ipAddress)
1814 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
1815 .forEach(interfaceIpAddress ->
1816 routingRulePopulator.populateSingleIpPunts(
1817 cp.deviceId(), interfaceIpAddress));
1818
1819 // 3. Host unicast routing rule
1820 // Add unicast routing rule
1821 hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, true);
1822 }
sangho80f11cb2015-04-01 13:05:26 -07001823}