blob: 60927168e076731ebdb150c64ec2623722f60fec [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
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -070034import com.fasterxml.jackson.databind.node.ObjectNode;
Charles Chanf0ae41e2017-08-23 13:55:39 -070035import com.google.common.collect.Sets;
sangho80f11cb2015-04-01 13:05:26 -070036import org.apache.felix.scr.annotations.Activate;
37import org.apache.felix.scr.annotations.Component;
38import org.apache.felix.scr.annotations.Deactivate;
39import org.apache.felix.scr.annotations.Reference;
40import org.apache.felix.scr.annotations.ReferenceCardinality;
sangho27462c62015-05-14 00:39:53 -070041import org.apache.felix.scr.annotations.Service;
sangho80f11cb2015-04-01 13:05:26 -070042import org.onlab.packet.Ethernet;
Pier Ventreb6b81d52016-12-02 08:16:05 -080043import org.onlab.packet.ICMP6;
Charles Chan77277672015-10-20 16:24:19 -070044import org.onlab.packet.IPv4;
Pier Ventreb6a7f342016-11-26 21:05:22 -080045import org.onlab.packet.IPv6;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -070046import org.onlab.packet.IpAddress;
Charles Chan77277672015-10-20 16:24:19 -070047import org.onlab.packet.IpPrefix;
Jonathan Hart54541d12016-04-12 15:39:44 -070048import org.onlab.packet.VlanId;
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -070049import org.onlab.util.KryoNamespace;
Saurav Dasc3604f12016-03-23 11:22:49 -070050import org.onosproject.cfg.ComponentConfigService;
sangho80f11cb2015-04-01 13:05:26 -070051import org.onosproject.core.ApplicationId;
52import org.onosproject.core.CoreService;
53import org.onosproject.event.Event;
Jonathan Hart54541d12016-04-12 15:39:44 -070054import org.onosproject.mastership.MastershipService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080055import org.onosproject.net.ConnectPoint;
Jonathan Hart54541d12016-04-12 15:39:44 -070056import org.onosproject.net.Device;
57import org.onosproject.net.DeviceId;
Charles Chanf0ae41e2017-08-23 13:55:39 -070058import org.onosproject.net.Host;
59import org.onosproject.net.HostId;
Jonathan Hart54541d12016-04-12 15:39:44 -070060import org.onosproject.net.Link;
61import org.onosproject.net.Port;
Charles Chanf4586112015-11-09 16:37:23 -080062import org.onosproject.net.PortNumber;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -070063import org.onosproject.net.config.ConfigException;
Charles Chan72f556a2015-10-05 17:50:33 -070064import org.onosproject.net.config.ConfigFactory;
65import org.onosproject.net.config.NetworkConfigEvent;
Charles Chan72f556a2015-10-05 17:50:33 -070066import org.onosproject.net.config.NetworkConfigListener;
Jonathan Hart54541d12016-04-12 15:39:44 -070067import org.onosproject.net.config.NetworkConfigRegistry;
Ray Milkeyae0068a2017-08-15 11:02:29 -070068import org.onosproject.net.config.basics.InterfaceConfig;
69import org.onosproject.net.config.basics.McastConfig;
Charles Chan72f556a2015-10-05 17:50:33 -070070import org.onosproject.net.config.basics.SubjectFactories;
Jonathan Hart54541d12016-04-12 15:39:44 -070071import org.onosproject.net.device.DeviceEvent;
72import org.onosproject.net.device.DeviceListener;
73import org.onosproject.net.device.DeviceService;
Charles Chanf4586112015-11-09 16:37:23 -080074import org.onosproject.net.flow.TrafficSelector;
75import org.onosproject.net.flow.TrafficTreatment;
Jonathan Hart54541d12016-04-12 15:39:44 -070076import org.onosproject.net.flowobjective.FlowObjectiveService;
Charles Chanf4586112015-11-09 16:37:23 -080077import org.onosproject.net.host.HostEvent;
78import org.onosproject.net.host.HostListener;
Pier Ventreb6a7f342016-11-26 21:05:22 -080079import org.onosproject.net.host.HostService;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -070080import org.onosproject.net.host.InterfaceIpAddress;
Ray Milkeyae0068a2017-08-15 11:02:29 -070081import org.onosproject.net.intf.Interface;
82import org.onosproject.net.intf.InterfaceService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080083import org.onosproject.net.link.LinkEvent;
84import org.onosproject.net.link.LinkListener;
85import org.onosproject.net.link.LinkService;
Charles Chanc91c8782016-03-30 17:54:24 -070086import org.onosproject.net.mcast.McastEvent;
87import org.onosproject.net.mcast.McastListener;
88import org.onosproject.net.mcast.MulticastRouteService;
Ray Milkeyae0068a2017-08-15 11:02:29 -070089import org.onosproject.net.neighbour.NeighbourResolutionService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080090import org.onosproject.net.packet.InboundPacket;
91import org.onosproject.net.packet.PacketContext;
92import org.onosproject.net.packet.PacketProcessor;
93import org.onosproject.net.packet.PacketService;
Pier Ventref3cf5b92016-11-09 14:17:26 -080094import org.onosproject.net.topology.PathService;
Charles Chanc91c8782016-03-30 17:54:24 -070095import org.onosproject.net.topology.TopologyService;
Charles Chanf0ae41e2017-08-23 13:55:39 -070096import org.onosproject.routeservice.ResolvedRoute;
Ray Milkeyae0068a2017-08-15 11:02:29 -070097import org.onosproject.routeservice.RouteEvent;
98import org.onosproject.routeservice.RouteListener;
99import org.onosproject.routeservice.RouteService;
Charles Chanc91c8782016-03-30 17:54:24 -0700100import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
101import org.onosproject.segmentrouting.config.DeviceConfiguration;
Pier Ventre6b19e482016-11-07 16:21:04 -0800102import org.onosproject.segmentrouting.config.PwaasConfig;
Pier Ventre6b19e482016-11-07 16:21:04 -0800103import org.onosproject.segmentrouting.config.SegmentRoutingAppConfig;
Ray Milkeyae0068a2017-08-15 11:02:29 -0700104import org.onosproject.segmentrouting.config.SegmentRoutingDeviceConfig;
Charles Chan82f19972016-05-17 13:13:55 -0700105import org.onosproject.segmentrouting.config.XConnectConfig;
Charles Chanc91c8782016-03-30 17:54:24 -0700106import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
Saurav Das261c3002017-06-13 15:35:54 -0700107import org.onosproject.segmentrouting.grouphandler.DestinationSet;
108import org.onosproject.segmentrouting.grouphandler.NextNeighbors;
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700109import org.onosproject.segmentrouting.pwaas.DefaultL2Tunnel;
110import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelPolicy;
Ray Milkeyae0068a2017-08-15 11:02:29 -0700111import org.onosproject.segmentrouting.pwaas.L2TunnelHandler;
Saurav Das261c3002017-06-13 15:35:54 -0700112import org.onosproject.segmentrouting.storekey.DestinationSetNextObjectiveStoreKey;
Charles Chan1eaf4802016-04-18 13:44:03 -0700113import org.onosproject.segmentrouting.storekey.PortNextObjectiveStoreKey;
Charles Chan10b0fb72017-02-02 16:20:42 -0800114import org.onosproject.segmentrouting.storekey.VlanNextObjectiveStoreKey;
Charles Chan82f19972016-05-17 13:13:55 -0700115import org.onosproject.segmentrouting.storekey.XConnectStoreKey;
Jonathan Hart54541d12016-04-12 15:39:44 -0700116import org.onosproject.store.serializers.KryoNamespaces;
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700117import org.onosproject.store.service.EventuallyConsistentMap;
118import org.onosproject.store.service.EventuallyConsistentMapBuilder;
119import org.onosproject.store.service.StorageService;
120import org.onosproject.store.service.WallClockTimestamp;
sangho80f11cb2015-04-01 13:05:26 -0700121import org.slf4j.Logger;
122import org.slf4j.LoggerFactory;
123
Ray Milkeyae0068a2017-08-15 11:02:29 -0700124import com.google.common.collect.HashMultimap;
125import com.google.common.collect.ImmutableMap;
126import com.google.common.collect.Maps;
127import com.google.common.collect.Multimap;
sangho80f11cb2015-04-01 13:05:26 -0700128
Charles Chand6d25332016-02-26 22:19:52 -0800129import static com.google.common.base.Preconditions.checkState;
Pier Ventreadb4ae62016-11-23 09:57:42 -0800130import static org.onlab.packet.Ethernet.TYPE_ARP;
Yuta HIGUCHIebee2f12016-07-21 16:54:33 -0700131import static org.onlab.util.Tools.groupedThreads;
Charles Chand6d25332016-02-26 22:19:52 -0800132
Charles Chanb7f75ac2016-01-11 18:28:54 -0800133/**
134 * Segment routing manager.
135 */
Jonathan Hart54541d12016-04-12 15:39:44 -0700136@Service
137@Component(immediate = true)
sangho27462c62015-05-14 00:39:53 -0700138public class SegmentRoutingManager implements SegmentRoutingService {
sangho80f11cb2015-04-01 13:05:26 -0700139
Charles Chan46fdfaf2016-11-09 20:51:44 -0800140 private static Logger log = LoggerFactory.getLogger(SegmentRoutingManager.class);
Charles Chan910be6a2017-08-23 14:46:43 -0700141 private static final String NOT_MASTER = "Current instance is not the master of {}. Ignore.";
sangho80f11cb2015-04-01 13:05:26 -0700142
143 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700144 private ComponentConfigService compCfgService;
sangho80f11cb2015-04-01 13:05:26 -0700145
146 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventreb6a7f342016-11-26 21:05:22 -0800147 private NeighbourResolutionService neighbourResolutionService;
148
149 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventref3cf5b92016-11-09 14:17:26 -0800150 public PathService pathService;
151
152 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700153 CoreService coreService;
sangho80f11cb2015-04-01 13:05:26 -0700154
155 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700156 PacketService packetService;
sangho80f11cb2015-04-01 13:05:26 -0700157
158 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700159 HostService hostService;
sangho80f11cb2015-04-01 13:05:26 -0700160
161 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700162 DeviceService deviceService;
sangho80f11cb2015-04-01 13:05:26 -0700163
164 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventref3cf5b92016-11-09 14:17:26 -0800165 public FlowObjectiveService flowObjectiveService;
sangho80f11cb2015-04-01 13:05:26 -0700166
167 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700168 LinkService linkService;
sangho27462c62015-05-14 00:39:53 -0700169
Charles Chan82ab1932016-01-30 23:22:37 -0800170 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventref3cf5b92016-11-09 14:17:26 -0800171 public MastershipService mastershipService;
Charles Chandebfea32016-10-24 14:52:01 -0700172
173 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventref3cf5b92016-11-09 14:17:26 -0800174 public StorageService storageService;
Charles Chandebfea32016-10-24 14:52:01 -0700175
176 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
177 MulticastRouteService multicastRouteService;
178
179 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
180 TopologyService topologyService;
181
182 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700183 RouteService routeService;
Charles Chan82ab1932016-01-30 23:22:37 -0800184
185 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan46fdfaf2016-11-09 20:51:44 -0800186 public NetworkConfigRegistry cfgService;
Charles Chan82ab1932016-01-30 23:22:37 -0800187
Saurav Dasc3604f12016-03-23 11:22:49 -0700188 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan46fdfaf2016-11-09 20:51:44 -0800189 public InterfaceService interfaceService;
190
Charles Chandebfea32016-10-24 14:52:01 -0700191 ArpHandler arpHandler = null;
192 IcmpHandler icmpHandler = null;
193 IpHandler ipHandler = null;
194 RoutingRulePopulator routingRulePopulator = null;
Ray Milkeyb85de082017-04-05 09:42:04 -0700195 ApplicationId appId;
196 DeviceConfiguration deviceConfiguration = null;
sangho80f11cb2015-04-01 13:05:26 -0700197
Charles Chandebfea32016-10-24 14:52:01 -0700198 DefaultRoutingHandler defaultRoutingHandler = null;
sangho27462c62015-05-14 00:39:53 -0700199 private TunnelHandler tunnelHandler = null;
200 private PolicyHandler policyHandler = null;
Charles Chan2b078ae2015-10-14 11:24:40 -0700201 private InternalPacketProcessor processor = null;
202 private InternalLinkListener linkListener = null;
203 private InternalDeviceListener deviceListener = null;
Charles Chan82f19972016-05-17 13:13:55 -0700204 private AppConfigHandler appCfgHandler = null;
Charles Chandebfea32016-10-24 14:52:01 -0700205 XConnectHandler xConnectHandler = null;
Charles Chan1eaf4802016-04-18 13:44:03 -0700206 private McastHandler mcastHandler = null;
Charles Chan3ed34d82017-06-22 18:03:14 -0700207 private HostHandler hostHandler = null;
Pier Ventreb6a7f342016-11-26 21:05:22 -0800208 private RouteHandler routeHandler = null;
Pier Ventreb6b81d52016-12-02 08:16:05 -0800209 private SegmentRoutingNeighbourDispatcher neighbourHandler = null;
Pier Ventre6b19e482016-11-07 16:21:04 -0800210 private L2TunnelHandler l2TunnelHandler = null;
sangho80f11cb2015-04-01 13:05:26 -0700211 private InternalEventHandler eventHandler = new InternalEventHandler();
Charles Chan82ab1932016-01-30 23:22:37 -0800212 private final InternalHostListener hostListener = new InternalHostListener();
Charles Chanc91c8782016-03-30 17:54:24 -0700213 private final InternalConfigListener cfgListener = new InternalConfigListener(this);
214 private final InternalMcastListener mcastListener = new InternalMcastListener();
Charles Chandebfea32016-10-24 14:52:01 -0700215 private final InternalRouteEventListener routeListener = new InternalRouteEventListener();
sangho80f11cb2015-04-01 13:05:26 -0700216
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700217 private ScheduledExecutorService executorService = Executors
Yuta HIGUCHIebee2f12016-07-21 16:54:33 -0700218 .newScheduledThreadPool(1, groupedThreads("SegmentRoutingManager", "event-%d", log));
sangho80f11cb2015-04-01 13:05:26 -0700219
Saurav Das2d94d312015-11-24 23:21:05 -0800220 @SuppressWarnings("unused")
sangho80f11cb2015-04-01 13:05:26 -0700221 private static ScheduledFuture<?> eventHandlerFuture = null;
Saurav Das2d94d312015-11-24 23:21:05 -0800222 @SuppressWarnings("rawtypes")
Yuta HIGUCHIebee2f12016-07-21 16:54:33 -0700223 private ConcurrentLinkedQueue<Event> eventQueue = new ConcurrentLinkedQueue<>();
Charles Chanf4586112015-11-09 16:37:23 -0800224 private Map<DeviceId, DefaultGroupHandler> groupHandlerMap =
Charles Chanb7f75ac2016-01-11 18:28:54 -0800225 new ConcurrentHashMap<>();
226 /**
Saurav Das261c3002017-06-13 15:35:54 -0700227 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan53de91f2017-08-22 15:07:34 -0700228 * Used to keep track on MPLS group information.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800229 */
Saurav Das261c3002017-06-13 15:35:54 -0700230 EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
231 dsNextObjStore = null;
Charles Chanb7f75ac2016-01-11 18:28:54 -0800232 /**
Charles Chan53de91f2017-08-22 15:07:34 -0700233 * Per device next objective ID store with (device id + vlanid) as key.
234 * Used to keep track on L2 flood group information.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800235 */
Ray Milkeyb85de082017-04-05 09:42:04 -0700236 EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer>
Charles Chan10b0fb72017-02-02 16:20:42 -0800237 vlanNextObjStore = null;
Charles Chanb7f75ac2016-01-11 18:28:54 -0800238 /**
Charles Chan53de91f2017-08-22 15:07:34 -0700239 * Per device next objective ID store with (device id + port + treatment + meta) as key.
240 * Used to keep track on L2 interface group and L3 unicast group information.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800241 */
Ray Milkeyb85de082017-04-05 09:42:04 -0700242 EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer>
Saurav Das2d94d312015-11-24 23:21:05 -0800243 portNextObjStore = null;
Charles Chan10b0fb72017-02-02 16:20:42 -0800244
Saurav Das62ae6792017-05-15 15:34:25 -0700245 // Local store for all links seen and their present status, used for
246 // optimized routing. The existence of the link in the keys is enough to know
247 // if the link has been "seen-before" by this instance of the controller.
248 // The boolean value indicates if the link is currently up or not.
249 // XXX Currently the optimized routing logic depends on "forgetting" a link
250 // when a switch goes down, but "remembering" it when only the link goes down.
251 // Consider changing this logic so we can use the Link Service instead of
252 // a local cache.
253 private Map<Link, Boolean> seenLinks = new ConcurrentHashMap<>();
254
Saurav Das2d94d312015-11-24 23:21:05 -0800255 private EventuallyConsistentMap<String, Tunnel> tunnelStore = null;
256 private EventuallyConsistentMap<String, Policy> policyStore = null;
sangho4a5c42a2015-05-20 22:16:38 -0700257
Saurav Das261c3002017-06-13 15:35:54 -0700258 private AtomicBoolean programmingScheduled = new AtomicBoolean();
259
Charles Chanc91c8782016-03-30 17:54:24 -0700260 private final ConfigFactory<DeviceId, SegmentRoutingDeviceConfig> deviceConfigFactory =
Charles Chan82f19972016-05-17 13:13:55 -0700261 new ConfigFactory<DeviceId, SegmentRoutingDeviceConfig>(
262 SubjectFactories.DEVICE_SUBJECT_FACTORY,
Charles Chanc91c8782016-03-30 17:54:24 -0700263 SegmentRoutingDeviceConfig.class, "segmentrouting") {
Charles Chan72f556a2015-10-05 17:50:33 -0700264 @Override
Charles Chan82ab1932016-01-30 23:22:37 -0800265 public SegmentRoutingDeviceConfig createConfig() {
266 return new SegmentRoutingDeviceConfig();
Charles Chan72f556a2015-10-05 17:50:33 -0700267 }
268 };
Pier Ventre6b19e482016-11-07 16:21:04 -0800269
Charles Chanc91c8782016-03-30 17:54:24 -0700270 private final ConfigFactory<ApplicationId, SegmentRoutingAppConfig> appConfigFactory =
Charles Chan82f19972016-05-17 13:13:55 -0700271 new ConfigFactory<ApplicationId, SegmentRoutingAppConfig>(
272 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chanc91c8782016-03-30 17:54:24 -0700273 SegmentRoutingAppConfig.class, "segmentrouting") {
Charles Chan82ab1932016-01-30 23:22:37 -0800274 @Override
275 public SegmentRoutingAppConfig createConfig() {
276 return new SegmentRoutingAppConfig();
277 }
278 };
Pier Ventre6b19e482016-11-07 16:21:04 -0800279
Charles Chan82f19972016-05-17 13:13:55 -0700280 private final ConfigFactory<ApplicationId, XConnectConfig> xConnectConfigFactory =
281 new ConfigFactory<ApplicationId, XConnectConfig>(
282 SubjectFactories.APP_SUBJECT_FACTORY,
283 XConnectConfig.class, "xconnect") {
284 @Override
285 public XConnectConfig createConfig() {
286 return new XConnectConfig();
287 }
288 };
Pier Ventre6b19e482016-11-07 16:21:04 -0800289
Charles Chanc91c8782016-03-30 17:54:24 -0700290 private ConfigFactory<ApplicationId, McastConfig> mcastConfigFactory =
Charles Chan82f19972016-05-17 13:13:55 -0700291 new ConfigFactory<ApplicationId, McastConfig>(
292 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chanc91c8782016-03-30 17:54:24 -0700293 McastConfig.class, "multicast") {
294 @Override
295 public McastConfig createConfig() {
296 return new McastConfig();
297 }
298 };
299
Pier Ventre6b19e482016-11-07 16:21:04 -0800300 private final ConfigFactory<ApplicationId, PwaasConfig> pwaasConfigFactory =
301 new ConfigFactory<ApplicationId, PwaasConfig>(
302 SubjectFactories.APP_SUBJECT_FACTORY,
303 PwaasConfig.class, "pwaas") {
304 @Override
305 public PwaasConfig createConfig() {
306 return new PwaasConfig();
307 }
308 };
309
Charles Chan3ed34d82017-06-22 18:03:14 -0700310 private static final Object THREAD_SCHED_LOCK = new Object();
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -0700311 private static int numOfEventsQueued = 0;
312 private static int numOfEventsExecuted = 0;
sangho80f11cb2015-04-01 13:05:26 -0700313 private static int numOfHandlerExecution = 0;
314 private static int numOfHandlerScheduled = 0;
315
Charles Chan1963f4f2016-02-18 14:22:42 -0800316 /**
317 * Segment Routing App ID.
318 */
Charles Chan46fdfaf2016-11-09 20:51:44 -0800319 public static final String APP_NAME = "org.onosproject.segmentrouting";
Charles Chan10b0fb72017-02-02 16:20:42 -0800320
Charles Chanb7f75ac2016-01-11 18:28:54 -0800321 /**
322 * The default VLAN ID assigned to the interfaces without subnet config.
323 */
Charles Chan10b0fb72017-02-02 16:20:42 -0800324 public static final VlanId INTERNAL_VLAN = VlanId.vlanId((short) 4094);
Saurav Das7c305372015-10-28 12:39:42 -0700325
sangho80f11cb2015-04-01 13:05:26 -0700326 @Activate
327 protected void activate() {
Charles Chan46fdfaf2016-11-09 20:51:44 -0800328 appId = coreService.registerApplication(APP_NAME);
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700329
330 log.debug("Creating EC map nsnextobjectivestore");
Saurav Das261c3002017-06-13 15:35:54 -0700331 EventuallyConsistentMapBuilder<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700332 nsNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
Saurav Das261c3002017-06-13 15:35:54 -0700333 dsNextObjStore = nsNextObjMapBuilder
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700334 .withName("nsnextobjectivestore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700335 .withSerializer(createSerializer())
Madan Jampani675ae202015-06-24 19:05:56 -0700336 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700337 .build();
Saurav Das261c3002017-06-13 15:35:54 -0700338 log.trace("Current size {}", dsNextObjStore.size());
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700339
Charles Chan10b0fb72017-02-02 16:20:42 -0800340 log.debug("Creating EC map vlannextobjectivestore");
341 EventuallyConsistentMapBuilder<VlanNextObjectiveStoreKey, Integer>
342 vlanNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
343 vlanNextObjStore = vlanNextObjMapBuilder
344 .withName("vlannextobjectivestore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700345 .withSerializer(createSerializer())
Charles Chan77277672015-10-20 16:24:19 -0700346 .withTimestampProvider((k, v) -> new WallClockTimestamp())
347 .build();
348
Saurav Das2d94d312015-11-24 23:21:05 -0800349 log.debug("Creating EC map subnetnextobjectivestore");
350 EventuallyConsistentMapBuilder<PortNextObjectiveStoreKey, Integer>
351 portNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
352 portNextObjStore = portNextObjMapBuilder
353 .withName("portnextobjectivestore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700354 .withSerializer(createSerializer())
Saurav Das2d94d312015-11-24 23:21:05 -0800355 .withTimestampProvider((k, v) -> new WallClockTimestamp())
356 .build();
357
sangho4a5c42a2015-05-20 22:16:38 -0700358 EventuallyConsistentMapBuilder<String, Tunnel> tunnelMapBuilder =
359 storageService.eventuallyConsistentMapBuilder();
sangho4a5c42a2015-05-20 22:16:38 -0700360 tunnelStore = tunnelMapBuilder
361 .withName("tunnelstore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700362 .withSerializer(createSerializer())
Madan Jampani675ae202015-06-24 19:05:56 -0700363 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho4a5c42a2015-05-20 22:16:38 -0700364 .build();
365
366 EventuallyConsistentMapBuilder<String, Policy> policyMapBuilder =
367 storageService.eventuallyConsistentMapBuilder();
sangho4a5c42a2015-05-20 22:16:38 -0700368 policyStore = policyMapBuilder
369 .withName("policystore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700370 .withSerializer(createSerializer())
Madan Jampani675ae202015-06-24 19:05:56 -0700371 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho4a5c42a2015-05-20 22:16:38 -0700372 .build();
373
Saurav Dasc3604f12016-03-23 11:22:49 -0700374 compCfgService.preSetProperty("org.onosproject.net.group.impl.GroupManager",
Pier Luigib9632ba2017-01-12 18:14:58 -0800375 "purgeOnDisconnection", "true");
Saurav Dasc3604f12016-03-23 11:22:49 -0700376 compCfgService.preSetProperty("org.onosproject.net.flow.impl.FlowRuleManager",
Pier Luigib9632ba2017-01-12 18:14:58 -0800377 "purgeOnDisconnection", "true");
Pier Luigib9632ba2017-01-12 18:14:58 -0800378 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
379 "requestInterceptsEnabled", "false");
Charles Chanc1909e12017-08-08 15:13:37 -0700380 compCfgService.preSetProperty("org.onosproject.net.neighbour.impl.NeighbourResolutionManager",
Pier Luigibc976df2017-01-12 22:46:39 -0800381 "requestInterceptsEnabled", "false");
Charles Chan9597f8d2017-07-24 15:56:10 -0700382 compCfgService.preSetProperty("org.onosproject.dhcprelay.DhcpRelayManager",
Pier Luigibc976df2017-01-12 22:46:39 -0800383 "arpEnabled", "false");
Pier Luigi0ebeb312017-02-02 22:31:34 -0800384 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
385 "greedyLearningIpv6", "true");
Charles Chancf8ea472017-02-28 15:15:17 -0800386 compCfgService.preSetProperty("org.onosproject.routing.cpr.ControlPlaneRedirectManager",
387 "forceUnprovision", "true");
Charles Chanc7b73c72017-08-10 16:57:28 -0700388 compCfgService.preSetProperty("org.onosproject.routeservice.store.RouteStoreImpl",
Charles Chan4c95c0d2017-07-20 16:16:25 -0700389 "distributed", "true");
Charles Chan804772f2017-08-14 11:42:11 -0700390 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
391 "multihomingEnabled", "true");
Saurav Dasc3604f12016-03-23 11:22:49 -0700392
Charles Chan2b078ae2015-10-14 11:24:40 -0700393 processor = new InternalPacketProcessor();
394 linkListener = new InternalLinkListener();
395 deviceListener = new InternalDeviceListener();
Charles Chan82f19972016-05-17 13:13:55 -0700396 appCfgHandler = new AppConfigHandler(this);
397 xConnectHandler = new XConnectHandler(this);
Charles Chan1eaf4802016-04-18 13:44:03 -0700398 mcastHandler = new McastHandler(this);
399 hostHandler = new HostHandler(this);
Charles Chandebfea32016-10-24 14:52:01 -0700400 routeHandler = new RouteHandler(this);
Pier Ventreb6b81d52016-12-02 08:16:05 -0800401 neighbourHandler = new SegmentRoutingNeighbourDispatcher(this);
Pier Ventre6b19e482016-11-07 16:21:04 -0800402 l2TunnelHandler = new L2TunnelHandler(this);
Charles Chan2b078ae2015-10-14 11:24:40 -0700403
Charles Chand6d25332016-02-26 22:19:52 -0800404 cfgService.addListener(cfgListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700405 cfgService.registerConfigFactory(deviceConfigFactory);
406 cfgService.registerConfigFactory(appConfigFactory);
Charles Chan82f19972016-05-17 13:13:55 -0700407 cfgService.registerConfigFactory(xConnectConfigFactory);
Charles Chanc91c8782016-03-30 17:54:24 -0700408 cfgService.registerConfigFactory(mcastConfigFactory);
Pier Ventre6b19e482016-11-07 16:21:04 -0800409 cfgService.registerConfigFactory(pwaasConfigFactory);
Charles Chan82ab1932016-01-30 23:22:37 -0800410 hostService.addListener(hostListener);
Charles Chan2b078ae2015-10-14 11:24:40 -0700411 packetService.addProcessor(processor, PacketProcessor.director(2));
412 linkService.addListener(linkListener);
413 deviceService.addListener(deviceListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700414 multicastRouteService.addListener(mcastListener);
Charles Chanfd48c222017-06-19 00:43:31 -0700415 routeService.addListener(routeListener);
Charles Chan2b078ae2015-10-14 11:24:40 -0700416
417 cfgListener.configureNetwork();
418
sangho80f11cb2015-04-01 13:05:26 -0700419 log.info("Started");
420 }
421
Jonathan Hart54541d12016-04-12 15:39:44 -0700422 private KryoNamespace.Builder createSerializer() {
423 return new KryoNamespace.Builder()
424 .register(KryoNamespaces.API)
Saurav Das261c3002017-06-13 15:35:54 -0700425 .register(DestinationSetNextObjectiveStoreKey.class,
Charles Chan10b0fb72017-02-02 16:20:42 -0800426 VlanNextObjectiveStoreKey.class,
Saurav Das261c3002017-06-13 15:35:54 -0700427 DestinationSet.class,
428 NextNeighbors.class,
Jonathan Hart54541d12016-04-12 15:39:44 -0700429 Tunnel.class,
430 DefaultTunnel.class,
431 Policy.class,
432 TunnelPolicy.class,
433 Policy.Type.class,
434 PortNextObjectiveStoreKey.class,
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700435 XConnectStoreKey.class,
436 DefaultL2Tunnel.class,
437 DefaultL2TunnelPolicy.class
Jonathan Hart54541d12016-04-12 15:39:44 -0700438 );
439 }
440
sangho80f11cb2015-04-01 13:05:26 -0700441 @Deactivate
442 protected void deactivate() {
Charles Chan72f556a2015-10-05 17:50:33 -0700443 cfgService.removeListener(cfgListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700444 cfgService.unregisterConfigFactory(deviceConfigFactory);
445 cfgService.unregisterConfigFactory(appConfigFactory);
Charles Chandebfea32016-10-24 14:52:01 -0700446 cfgService.unregisterConfigFactory(xConnectConfigFactory);
Charles Chanc91c8782016-03-30 17:54:24 -0700447 cfgService.unregisterConfigFactory(mcastConfigFactory);
Pier Ventre6b19e482016-11-07 16:21:04 -0800448 cfgService.unregisterConfigFactory(pwaasConfigFactory);
Charles Chan72f556a2015-10-05 17:50:33 -0700449
Charles Chanfd48c222017-06-19 00:43:31 -0700450 hostService.removeListener(hostListener);
sangho80f11cb2015-04-01 13:05:26 -0700451 packetService.removeProcessor(processor);
Charles Chan2b078ae2015-10-14 11:24:40 -0700452 linkService.removeListener(linkListener);
453 deviceService.removeListener(deviceListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700454 multicastRouteService.removeListener(mcastListener);
Charles Chandebfea32016-10-24 14:52:01 -0700455 routeService.removeListener(routeListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700456
Charles Chan2e71ef32017-02-23 15:44:08 -0800457 neighbourResolutionService.unregisterNeighbourHandlers(appId);
458
sangho80f11cb2015-04-01 13:05:26 -0700459 processor = null;
Charles Chan2b078ae2015-10-14 11:24:40 -0700460 linkListener = null;
Charles Chanc91c8782016-03-30 17:54:24 -0700461 deviceListener = null;
Charles Chan2b078ae2015-10-14 11:24:40 -0700462 groupHandlerMap.clear();
463
Saurav Das261c3002017-06-13 15:35:54 -0700464 dsNextObjStore.destroy();
Charles Chan10b0fb72017-02-02 16:20:42 -0800465 vlanNextObjStore.destroy();
Charles Chanc91c8782016-03-30 17:54:24 -0700466 portNextObjStore.destroy();
Charles Chanc91c8782016-03-30 17:54:24 -0700467 tunnelStore.destroy();
468 policyStore.destroy();
sangho80f11cb2015-04-01 13:05:26 -0700469 log.info("Stopped");
470 }
471
sangho27462c62015-05-14 00:39:53 -0700472 @Override
473 public List<Tunnel> getTunnels() {
474 return tunnelHandler.getTunnels();
475 }
476
477 @Override
sanghobd812f82015-06-29 14:58:47 -0700478 public TunnelHandler.Result createTunnel(Tunnel tunnel) {
479 return tunnelHandler.createTunnel(tunnel);
sangho27462c62015-05-14 00:39:53 -0700480 }
481
482 @Override
sanghobd812f82015-06-29 14:58:47 -0700483 public TunnelHandler.Result removeTunnel(Tunnel tunnel) {
sangho27462c62015-05-14 00:39:53 -0700484 for (Policy policy: policyHandler.getPolicies()) {
485 if (policy.type() == Policy.Type.TUNNEL_FLOW) {
486 TunnelPolicy tunnelPolicy = (TunnelPolicy) policy;
487 if (tunnelPolicy.tunnelId().equals(tunnel.id())) {
488 log.warn("Cannot remove the tunnel used by a policy");
sanghobd812f82015-06-29 14:58:47 -0700489 return TunnelHandler.Result.TUNNEL_IN_USE;
sangho27462c62015-05-14 00:39:53 -0700490 }
491 }
492 }
sanghobd812f82015-06-29 14:58:47 -0700493 return tunnelHandler.removeTunnel(tunnel);
sangho27462c62015-05-14 00:39:53 -0700494 }
495
496 @Override
sanghobd812f82015-06-29 14:58:47 -0700497 public PolicyHandler.Result removePolicy(Policy policy) {
498 return policyHandler.removePolicy(policy);
sangho27462c62015-05-14 00:39:53 -0700499 }
500
501 @Override
sanghobd812f82015-06-29 14:58:47 -0700502 public PolicyHandler.Result createPolicy(Policy policy) {
503 return policyHandler.createPolicy(policy);
sangho27462c62015-05-14 00:39:53 -0700504 }
505
506 @Override
507 public List<Policy> getPolicies() {
508 return policyHandler.getPolicies();
509 }
510
Saurav Das07c74602016-04-27 18:35:50 -0700511 @Override
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700512 public List<DefaultL2Tunnel> getL2Tunnels() {
513 return l2TunnelHandler.getL2Tunnels();
514 }
515
516 @Override
517 public List<DefaultL2TunnelPolicy> getL2Policies() {
518 return l2TunnelHandler.getL2Policies();
519 }
520
521 @Override
522 public L2TunnelHandler.Result addPseudowire(String tunnelId, String pwLabel, String cP1,
523 String cP1InnerVlan, String cP1OuterVlan, String cP2,
524 String cP2InnerVlan, String cP2OuterVlan,
525 String mode, String sdTag) {
526
527 PwaasConfig config = cfgService.getConfig(appId(), PwaasConfig.class);
528 if (config == null) {
529 log.warn("Configuration for Pwaas class could not be found!");
530 return L2TunnelHandler.Result.CONFIG_NOT_FOUND;
531 }
532
533 ObjectNode object = config.addPseudowire(tunnelId, pwLabel,
534 cP1, cP1InnerVlan, cP1OuterVlan,
535 cP2, cP2InnerVlan, cP2OuterVlan,
536 mode, sdTag);
537 if (object == null) {
538 log.warn("Could not add pseudowire to the configuration!");
539 return L2TunnelHandler.Result.ADDITION_ERROR;
540 }
541
542 // inform everyone about the valid change in the pw configuration
543 cfgService.applyConfig(appId(), PwaasConfig.class, object);
544 return L2TunnelHandler.Result.SUCCESS;
545 }
546
547 @Override
548 public L2TunnelHandler.Result removePseudowire(String pwId) {
549
550 PwaasConfig config = cfgService.getConfig(appId(), PwaasConfig.class);
551 if (config == null) {
552 log.warn("Configuration for Pwaas class could not be found!");
553 return L2TunnelHandler.Result.CONFIG_NOT_FOUND;
554 }
555
556 ObjectNode object = config.removePseudowire(pwId);
557 if (object == null) {
558 log.warn("Could not delete pseudowire from configuration!");
559 return L2TunnelHandler.Result.REMOVAL_ERROR;
560 }
561
562 // sanity check, this should never fail since we removed a pw
563 // and we always check when we update the configuration
564 config.isValid();
565
566 // inform everyone
567 cfgService.applyConfig(appId(), PwaasConfig.class, object);
568
569 return L2TunnelHandler.Result.SUCCESS;
570 }
571
572 @Override
Saurav Das07c74602016-04-27 18:35:50 -0700573 public void rerouteNetwork() {
574 cfgListener.configureNetwork();
Saurav Das07c74602016-04-27 18:35:50 -0700575 }
576
Charles Chand7844e52016-10-20 17:02:44 -0700577 @Override
Pier Ventreb6a7f342016-11-26 21:05:22 -0800578 public Map<DeviceId, Set<IpPrefix>> getDeviceSubnetMap() {
579 Map<DeviceId, Set<IpPrefix>> deviceSubnetMap = Maps.newHashMap();
Charles Chand7844e52016-10-20 17:02:44 -0700580 deviceService.getAvailableDevices().forEach(device -> {
581 deviceSubnetMap.put(device.id(), deviceConfiguration.getSubnets(device.id()));
582 });
583 return deviceSubnetMap;
584 }
585
Saurav Das62ae6792017-05-15 15:34:25 -0700586
587 @Override
588 public ImmutableMap<DeviceId, EcmpShortestPathGraph> getCurrentEcmpSpg() {
589 if (defaultRoutingHandler != null) {
590 return defaultRoutingHandler.getCurrentEmcpSpgMap();
591 } else {
592 return null;
593 }
594 }
595
596 @Override
Saurav Das261c3002017-06-13 15:35:54 -0700597 public ImmutableMap<DestinationSetNextObjectiveStoreKey, NextNeighbors> getDestinationSet() {
598 if (dsNextObjStore != null) {
599 return ImmutableMap.copyOf(dsNextObjStore.entrySet());
Saurav Das62ae6792017-05-15 15:34:25 -0700600 } else {
601 return ImmutableMap.of();
602 }
603 }
604
Saurav Dasfbe74572017-08-03 18:30:35 -0700605 @Override
606 public void verifyGroups(DeviceId id) {
607 DefaultGroupHandler gh = groupHandlerMap.get(id);
608 if (gh != null) {
609 gh.triggerBucketCorrector();
610 }
611 }
612
sangho80f1f892015-05-19 11:57:42 -0700613 /**
Ray Milkeyb85de082017-04-05 09:42:04 -0700614 * Extracts the application ID from the manager.
615 *
616 * @return application ID
617 */
618 public ApplicationId appId() {
619 return appId;
620 }
621
622 /**
623 * Returns the device configuration.
624 *
625 * @return device configuration
626 */
627 public DeviceConfiguration deviceConfiguration() {
628 return deviceConfiguration;
629 }
630
631 /**
Saurav Das261c3002017-06-13 15:35:54 -0700632 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan53de91f2017-08-22 15:07:34 -0700633 * Used to keep track on MPLS group information.
Ray Milkeyb85de082017-04-05 09:42:04 -0700634 *
635 * @return next objective ID store
636 */
Saurav Das261c3002017-06-13 15:35:54 -0700637 public EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
638 dsNextObjStore() {
639 return dsNextObjStore;
Ray Milkeyb85de082017-04-05 09:42:04 -0700640 }
641
642 /**
Charles Chan53de91f2017-08-22 15:07:34 -0700643 * Per device next objective ID store with (device id + vlanid) as key.
644 * Used to keep track on L2 flood group information.
Ray Milkeyb85de082017-04-05 09:42:04 -0700645 *
646 * @return vlan next object store
647 */
648 public EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer> vlanNextObjStore() {
649 return vlanNextObjStore;
650 }
651
652 /**
Charles Chan53de91f2017-08-22 15:07:34 -0700653 * Per device next objective ID store with (device id + port + treatment + meta) as key.
654 * Used to keep track on L2 interface group and L3 unicast group information.
Ray Milkeyb85de082017-04-05 09:42:04 -0700655 *
656 * @return port next object store.
657 */
658 public EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer> portNextObjStore() {
659 return portNextObjStore;
660 }
661
662 /**
Saurav Das261c3002017-06-13 15:35:54 -0700663 * Returns the MPLS-ECMP configuration which indicates whether ECMP on
664 * labeled packets should be programmed or not.
Pier Ventre7a78de22016-10-31 15:00:01 -0700665 *
666 * @return MPLS-ECMP value
667 */
668 public boolean getMplsEcmp() {
669 SegmentRoutingAppConfig segmentRoutingAppConfig = cfgService
670 .getConfig(this.appId, SegmentRoutingAppConfig.class);
671 return segmentRoutingAppConfig != null && segmentRoutingAppConfig.mplsEcmp();
672 }
673
674 /**
sangho80f1f892015-05-19 11:57:42 -0700675 * Returns the tunnel object with the tunnel ID.
676 *
677 * @param tunnelId Tunnel ID
678 * @return Tunnel reference
679 */
sangho27462c62015-05-14 00:39:53 -0700680 public Tunnel getTunnel(String tunnelId) {
681 return tunnelHandler.getTunnel(tunnelId);
682 }
683
Charles Chan90772a72017-02-08 15:52:08 -0800684 // TODO Consider moving these to InterfaceService
sangho80f11cb2015-04-01 13:05:26 -0700685 /**
Charles Chan10b0fb72017-02-02 16:20:42 -0800686 * Returns untagged VLAN configured on given connect point.
Charles Chan90772a72017-02-08 15:52:08 -0800687 * <p>
688 * Only returns the first match if there are multiple untagged VLAN configured
689 * on the connect point.
sangho80f11cb2015-04-01 13:05:26 -0700690 *
Charles Chan10b0fb72017-02-02 16:20:42 -0800691 * @param connectPoint connect point
692 * @return untagged VLAN or null if not configured
sangho80f11cb2015-04-01 13:05:26 -0700693 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700694 VlanId getUntaggedVlanId(ConnectPoint connectPoint) {
Charles Chan10b0fb72017-02-02 16:20:42 -0800695 return interfaceService.getInterfacesByPort(connectPoint).stream()
696 .filter(intf -> !intf.vlanUntagged().equals(VlanId.NONE))
697 .map(Interface::vlanUntagged)
698 .findFirst().orElse(null);
sangho80f11cb2015-04-01 13:05:26 -0700699 }
700
sangho27462c62015-05-14 00:39:53 -0700701 /**
Charles Chan90772a72017-02-08 15:52:08 -0800702 * Returns tagged VLAN configured on given connect point.
703 * <p>
704 * Returns all matches if there are multiple tagged VLAN configured
705 * on the connect point.
706 *
707 * @param connectPoint connect point
708 * @return tagged VLAN or empty set if not configured
709 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700710 Set<VlanId> getTaggedVlanId(ConnectPoint connectPoint) {
Charles Chan90772a72017-02-08 15:52:08 -0800711 Set<Interface> interfaces = interfaceService.getInterfacesByPort(connectPoint);
712 return interfaces.stream()
713 .map(Interface::vlanTagged)
Charles Chan3ed34d82017-06-22 18:03:14 -0700714 .flatMap(Set::stream)
Charles Chan90772a72017-02-08 15:52:08 -0800715 .collect(Collectors.toSet());
716 }
717
718 /**
719 * Returns native VLAN configured on given connect point.
720 * <p>
721 * Only returns the first match if there are multiple native VLAN configured
722 * on the connect point.
723 *
724 * @param connectPoint connect point
725 * @return native VLAN or null if not configured
726 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700727 VlanId getNativeVlanId(ConnectPoint connectPoint) {
Charles Chan90772a72017-02-08 15:52:08 -0800728 Set<Interface> interfaces = interfaceService.getInterfacesByPort(connectPoint);
729 return interfaces.stream()
730 .filter(intf -> !intf.vlanNative().equals(VlanId.NONE))
731 .map(Interface::vlanNative)
732 .findFirst()
733 .orElse(null);
734 }
735
736 /**
Charles Chand9265a32017-06-16 15:19:24 -0700737 * Returns internal VLAN for untagged hosts on given connect point.
738 * <p>
739 * The internal VLAN is either vlan-untagged for an access port,
740 * or vlan-native for a trunk port.
741 *
742 * @param connectPoint connect point
743 * @return internal VLAN or null if both vlan-untagged and vlan-native are undefined
744 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700745 VlanId getInternalVlanId(ConnectPoint connectPoint) {
Charles Chand9265a32017-06-16 15:19:24 -0700746 VlanId untaggedVlanId = getUntaggedVlanId(connectPoint);
747 VlanId nativeVlanId = getNativeVlanId(connectPoint);
748 return untaggedVlanId != null ? untaggedVlanId : nativeVlanId;
749 }
750
751 /**
Charles Chan3ed34d82017-06-22 18:03:14 -0700752 * Returns optional pair device ID of given device.
753 *
754 * @param deviceId device ID
755 * @return optional pair device ID. Might be empty if pair device is not configured
756 */
757 Optional<DeviceId> getPairDeviceId(DeviceId deviceId) {
758 SegmentRoutingDeviceConfig deviceConfig =
759 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
760 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairDeviceId);
761 }
762 /**
763 * Returns optional pair device local port of given device.
764 *
765 * @param deviceId device ID
766 * @return optional pair device ID. Might be empty if pair device is not configured
767 */
768 Optional<PortNumber> getPairLocalPorts(DeviceId deviceId) {
769 SegmentRoutingDeviceConfig deviceConfig =
770 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
771 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairLocalPort);
772 }
773
774 /**
Charles Chan910be6a2017-08-23 14:46:43 -0700775 * Determine if current instance is the master of given connect point.
776 *
777 * @param cp connect point
778 * @return true if current instance is the master of given connect point
779 */
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700780 public boolean isMasterOf(ConnectPoint cp) {
Charles Chan910be6a2017-08-23 14:46:43 -0700781 boolean isMaster = mastershipService.isLocalMaster(cp.deviceId());
782 if (!isMaster) {
783 log.debug(NOT_MASTER, cp);
784 }
785 return isMaster;
786 }
787
788 /**
Charles Chanf0ae41e2017-08-23 13:55:39 -0700789 * Returns locations of given resolved route.
790 *
791 * @param resolvedRoute resolved route
792 * @return locations of nexthop. Might be empty if next hop is not found
793 */
794 Set<ConnectPoint> nextHopLocations(ResolvedRoute resolvedRoute) {
795 HostId hostId = HostId.hostId(resolvedRoute.nextHopMac(), resolvedRoute.nextHopVlan());
796 return Optional.ofNullable(hostService.getHost(hostId))
797 .map(Host::locations).orElse(Sets.newHashSet())
798 .stream().map(l -> (ConnectPoint) l).collect(Collectors.toSet());
799 }
800
801 /**
Charles Chan90772a72017-02-08 15:52:08 -0800802 * Returns vlan port map of given device.
803 *
804 * @param deviceId device id
805 * @return vlan-port multimap
806 */
807 public Multimap<VlanId, PortNumber> getVlanPortMap(DeviceId deviceId) {
808 HashMultimap<VlanId, PortNumber> vlanPortMap = HashMultimap.create();
809
810 interfaceService.getInterfaces().stream()
811 .filter(intf -> intf.connectPoint().deviceId().equals(deviceId))
812 .forEach(intf -> {
813 vlanPortMap.put(intf.vlanUntagged(), intf.connectPoint().port());
Charles Chan3ed34d82017-06-22 18:03:14 -0700814 intf.vlanTagged().forEach(vlanTagged ->
815 vlanPortMap.put(vlanTagged, intf.connectPoint().port())
816 );
Charles Chan90772a72017-02-08 15:52:08 -0800817 vlanPortMap.put(intf.vlanNative(), intf.connectPoint().port());
818 });
819 vlanPortMap.removeAll(VlanId.NONE);
820
821 return vlanPortMap;
822 }
823
824 /**
Charles Chan10b0fb72017-02-02 16:20:42 -0800825 * Returns the next objective ID for the given vlan id. It is expected
Saurav Das2d94d312015-11-24 23:21:05 -0800826 * that the next-objective has been pre-created from configuration.
Charles Chan77277672015-10-20 16:24:19 -0700827 *
828 * @param deviceId Device ID
Charles Chan10b0fb72017-02-02 16:20:42 -0800829 * @param vlanId VLAN ID
Saurav Das2d94d312015-11-24 23:21:05 -0800830 * @return next objective ID or -1 if it was not found
Charles Chan77277672015-10-20 16:24:19 -0700831 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700832 int getVlanNextObjectiveId(DeviceId deviceId, VlanId vlanId) {
Charles Chan77277672015-10-20 16:24:19 -0700833 if (groupHandlerMap.get(deviceId) != null) {
Charles Chan10b0fb72017-02-02 16:20:42 -0800834 log.trace("getVlanNextObjectiveId query in device {}", deviceId);
835 return groupHandlerMap.get(deviceId).getVlanNextObjectiveId(vlanId);
Charles Chan77277672015-10-20 16:24:19 -0700836 } else {
Charles Chan10b0fb72017-02-02 16:20:42 -0800837 log.warn("getVlanNextObjectiveId query - groupHandler for "
Saurav Das2d94d312015-11-24 23:21:05 -0800838 + "device {} not found", deviceId);
839 return -1;
840 }
841 }
842
843 /**
844 * Returns the next objective ID for the given portNumber, given the treatment.
845 * There could be multiple different treatments to the same outport, which
Saurav Das2cb38292017-03-29 19:09:17 -0700846 * would result in different objectives. If the next object does not exist,
847 * and should be created, a new one is created and its id is returned.
Saurav Das2d94d312015-11-24 23:21:05 -0800848 *
849 * @param deviceId Device ID
850 * @param portNum port number on device for which NextObjective is queried
851 * @param treatment the actions to apply on the packets (should include outport)
852 * @param meta metadata passed into the creation of a Next Objective if necessary
Saurav Das2cb38292017-03-29 19:09:17 -0700853 * @param createIfMissing true if a next object should be created if not found
Saurav Das07c74602016-04-27 18:35:50 -0700854 * @return next objective ID or -1 if an error occurred during retrieval or creation
Saurav Das2d94d312015-11-24 23:21:05 -0800855 */
856 public int getPortNextObjectiveId(DeviceId deviceId, PortNumber portNum,
857 TrafficTreatment treatment,
Saurav Das2cb38292017-03-29 19:09:17 -0700858 TrafficSelector meta,
859 boolean createIfMissing) {
Saurav Das2d94d312015-11-24 23:21:05 -0800860 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
861 if (ghdlr != null) {
Saurav Das2cb38292017-03-29 19:09:17 -0700862 return ghdlr.getPortNextObjectiveId(portNum, treatment, meta, createIfMissing);
Saurav Das2d94d312015-11-24 23:21:05 -0800863 } else {
Charles Chanb7f75ac2016-01-11 18:28:54 -0800864 log.warn("getPortNextObjectiveId query - groupHandler for device {}"
865 + " not found", deviceId);
866 return -1;
867 }
868 }
869
Saurav Das62ae6792017-05-15 15:34:25 -0700870 /**
871 * Returns the group handler object for the specified device id.
872 *
873 * @param devId the device identifier
874 * @return the groupHandler object for the device id, or null if not found
875 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700876 DefaultGroupHandler getGroupHandler(DeviceId devId) {
Saurav Das62ae6792017-05-15 15:34:25 -0700877 return groupHandlerMap.get(devId);
878 }
879
880 /**
Saurav Dasfbe74572017-08-03 18:30:35 -0700881 * Returns the default routing handler object.
882 *
883 * @return the default routing handler object
884 */
885 public DefaultRoutingHandler getRoutingHandler() {
886 return defaultRoutingHandler;
887 }
888
889 /**
Saurav Das62ae6792017-05-15 15:34:25 -0700890 * Returns true if this controller instance has seen this link before. The
891 * link may not be currently up, but as long as the link had been seen before
892 * this method will return true. The one exception is when the link was
893 * indeed seen before, but this controller instance was forced to forget it
894 * by a call to purgeSeenLink method.
895 *
896 * @param link the infrastructure link being queried
897 * @return true if this controller instance has seen this link before
898 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700899 boolean isSeenLink(Link link) {
Saurav Das62ae6792017-05-15 15:34:25 -0700900 return seenLinks.containsKey(link);
901 }
902
903 /**
904 * Updates the seen link store. Updates can be for links that are currently
905 * available or not.
906 *
907 * @param link the link to update in the seen-link local store
908 * @param up the status of the link, true if up, false if down
909 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700910 void updateSeenLink(Link link, boolean up) {
Saurav Das62ae6792017-05-15 15:34:25 -0700911 seenLinks.put(link, up);
912 }
913
914 /**
915 * Returns the status of a seen-link (up or down). If the link has not
916 * been seen-before, a null object is returned.
917 *
918 * @param link the infrastructure link being queried
919 * @return null if the link was not seen-before;
920 * true if the seen-link is up;
921 * false if the seen-link is down
922 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700923 Boolean isSeenLinkUp(Link link) {
Saurav Das62ae6792017-05-15 15:34:25 -0700924 return seenLinks.get(link);
925 }
926
927 /**
928 * Makes this controller instance forget a previously seen before link.
929 *
930 * @param link the infrastructure link to purge
931 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700932 private void purgeSeenLink(Link link) {
Saurav Das62ae6792017-05-15 15:34:25 -0700933 seenLinks.remove(link);
934 }
935
936 /**
937 * Returns the status of a link as parallel link. A parallel link
938 * is defined as a link which has common src and dst switches as another
939 * seen-link that is currently enabled. It is not necessary for the link being
940 * queried to be a seen-link.
941 *
942 * @param link the infrastructure link being queried
943 * @return true if a seen-link exists that is up, and shares the
944 * same src and dst switches as the link being queried
945 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700946 private boolean isParallelLink(Link link) {
Saurav Das62ae6792017-05-15 15:34:25 -0700947 for (Entry<Link, Boolean> seen : seenLinks.entrySet()) {
948 Link seenLink = seen.getKey();
949 if (seenLink.equals(link)) {
950 continue;
951 }
952 if (seenLink.src().deviceId().equals(link.src().deviceId()) &&
953 seenLink.dst().deviceId().equals(link.dst().deviceId()) &&
954 seen.getValue()) {
955 return true;
956 }
957 }
958 return false;
959 }
960
Saurav Das261c3002017-06-13 15:35:54 -0700961 /**
962 * Returns true if the link being queried is a bidirectional link. A bidi
963 * link is defined as a link, whose reverse link - ie. the link in the reverse
964 * direction - has been seen-before and is up. It is not necessary for the link
965 * being queried to be a seen-link.
966 *
967 * @param link the infrastructure link being queried
968 * @return true if another unidirectional link exists in the reverse direction,
969 * has been seen-before and is up
970 */
971 public boolean isBidirectional(Link link) {
972 Link reverseLink = linkService.getLink(link.dst(), link.src());
973 if (reverseLink == null) {
974 return false;
975 }
976 Boolean result = isSeenLinkUp(reverseLink);
977 if (result == null) {
978 return false;
979 }
980 return result.booleanValue();
981 }
982
983 /**
984 * Determines if the given link should be avoided in routing calculations
985 * by policy or design.
986 *
987 * @param link the infrastructure link being queried
988 * @return true if link should be avoided
989 */
990 public boolean avoidLink(Link link) {
991 // XXX currently only avoids all pair-links. In the future can be
992 // extended to avoid any generic link
993 DeviceId src = link.src().deviceId();
994 PortNumber srcPort = link.src().port();
995 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(src)) {
996 log.warn("Device {} not configured..cannot avoid link {}", src, link);
997 return false;
998 }
999 DeviceId pairDev;
1000 PortNumber pairLocalPort, pairRemotePort = null;
1001 try {
1002 pairDev = deviceConfiguration.getPairDeviceId(src);
1003 pairLocalPort = deviceConfiguration.getPairLocalPort(src);
1004 if (pairDev != null) {
1005 pairRemotePort = deviceConfiguration.getPairLocalPort(pairDev);
1006 }
1007 } catch (DeviceConfigNotFoundException e) {
1008 log.warn("Pair dev for dev {} not configured..cannot avoid link {}",
1009 src, link);
1010 return false;
1011 }
1012
1013 if (srcPort.equals(pairLocalPort) &&
1014 link.dst().deviceId().equals(pairDev) &&
1015 link.dst().port().equals(pairRemotePort)) {
1016 return true;
1017 }
1018 return false;
1019 }
1020
sangho80f11cb2015-04-01 13:05:26 -07001021 private class InternalPacketProcessor implements PacketProcessor {
sangho80f11cb2015-04-01 13:05:26 -07001022 @Override
1023 public void process(PacketContext context) {
1024
1025 if (context.isHandled()) {
1026 return;
1027 }
1028
1029 InboundPacket pkt = context.inPacket();
1030 Ethernet ethernet = pkt.parsed();
Pier Luigi37a35432017-02-01 13:50:04 -08001031
1032 if (ethernet == null) {
1033 return;
1034 }
1035
Saurav Das261c3002017-06-13 15:35:54 -07001036 log.trace("Rcvd pktin from {}: {}", context.inPacket().receivedFrom(),
1037 ethernet);
Pier Ventreadb4ae62016-11-23 09:57:42 -08001038 if (ethernet.getEtherType() == TYPE_ARP) {
Saurav Das62ae6792017-05-15 15:34:25 -07001039 log.warn("Received unexpected ARP packet on {}",
1040 context.inPacket().receivedFrom());
Saurav Das368cf212017-03-15 15:15:14 -07001041 log.trace("{}", ethernet);
Pier Ventre6b2c1b32016-12-09 17:26:04 -08001042 return;
sangho80f11cb2015-04-01 13:05:26 -07001043 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV4) {
Pier Ventreb6b81d52016-12-02 08:16:05 -08001044 IPv4 ipv4Packet = (IPv4) ethernet.getPayload();
1045 //ipHandler.addToPacketBuffer(ipv4Packet);
1046 if (ipv4Packet.getProtocol() == IPv4.PROTOCOL_ICMP) {
1047 icmpHandler.processIcmp(ethernet, pkt.receivedFrom());
sangho80f11cb2015-04-01 13:05:26 -07001048 } else {
Charles Chand041ad82017-01-13 17:20:44 -08001049 // NOTE: We don't support IP learning at this moment so this
1050 // is not necessary. Also it causes duplication of DHCP packets.
Pier Ventre6b2c1b32016-12-09 17:26:04 -08001051 // ipHandler.processPacketIn(ipv4Packet, pkt.receivedFrom());
sangho80f11cb2015-04-01 13:05:26 -07001052 }
Pier Ventreb6a7f342016-11-26 21:05:22 -08001053 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV6) {
1054 IPv6 ipv6Packet = (IPv6) ethernet.getPayload();
Pier Ventreb6b81d52016-12-02 08:16:05 -08001055 //ipHandler.addToPacketBuffer(ipv6Packet);
Pier Luigi37a35432017-02-01 13:50:04 -08001056 // We deal with the packet only if the packet is a ICMP6 ECHO/REPLY
Pier Ventreb6b81d52016-12-02 08:16:05 -08001057 if (ipv6Packet.getNextHeader() == IPv6.PROTOCOL_ICMP6) {
1058 ICMP6 icmp6Packet = (ICMP6) ipv6Packet.getPayload();
1059 if (icmp6Packet.getIcmpType() == ICMP6.ECHO_REQUEST ||
1060 icmp6Packet.getIcmpType() == ICMP6.ECHO_REPLY) {
1061 icmpHandler.processIcmpv6(ethernet, pkt.receivedFrom());
1062 } else {
Saurav Das62ae6792017-05-15 15:34:25 -07001063 log.trace("Received ICMPv6 0x{} - not handled",
Charles Chand3727b72017-03-13 13:10:30 -07001064 Integer.toHexString(icmp6Packet.getIcmpType() & 0xff));
Pier Ventreb6b81d52016-12-02 08:16:05 -08001065 }
1066 } else {
1067 // NOTE: We don't support IP learning at this moment so this
1068 // is not necessary. Also it causes duplication of DHCPv6 packets.
1069 // ipHandler.processPacketIn(ipv6Packet, pkt.receivedFrom());
1070 }
sangho80f11cb2015-04-01 13:05:26 -07001071 }
1072 }
1073 }
1074
1075 private class InternalLinkListener implements LinkListener {
1076 @Override
1077 public void event(LinkEvent event) {
Charles Chan0cff8aa2017-03-29 16:39:05 -07001078 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1079 event.type() == LinkEvent.Type.LINK_UPDATED ||
1080 event.type() == LinkEvent.Type.LINK_REMOVED) {
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001081 log.debug("Event {} received from Link Service", event.type());
sangho80f11cb2015-04-01 13:05:26 -07001082 scheduleEventHandlerIfNotScheduled(event);
1083 }
1084 }
1085 }
1086
1087 private class InternalDeviceListener implements DeviceListener {
sangho80f11cb2015-04-01 13:05:26 -07001088 @Override
1089 public void event(DeviceEvent event) {
sangho80f11cb2015-04-01 13:05:26 -07001090 switch (event.type()) {
1091 case DEVICE_ADDED:
Saurav Dasf0f592d2016-11-18 15:21:57 -08001092 case PORT_UPDATED:
1093 case PORT_ADDED:
sanghofb7c7292015-04-13 15:15:58 -07001094 case DEVICE_UPDATED:
1095 case DEVICE_AVAILABILITY_CHANGED:
Saurav Das62ae6792017-05-15 15:34:25 -07001096 log.trace("Event {} received from Device Service", event.type());
sangho80f11cb2015-04-01 13:05:26 -07001097 scheduleEventHandlerIfNotScheduled(event);
1098 break;
1099 default:
1100 }
1101 }
1102 }
1103
Saurav Das2d94d312015-11-24 23:21:05 -08001104 @SuppressWarnings("rawtypes")
sangho80f11cb2015-04-01 13:05:26 -07001105 private void scheduleEventHandlerIfNotScheduled(Event event) {
Charles Chan3ed34d82017-06-22 18:03:14 -07001106 synchronized (THREAD_SCHED_LOCK) {
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -07001107 eventQueue.add(event);
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001108 numOfEventsQueued++;
1109
1110 if ((numOfHandlerScheduled - numOfHandlerExecution) == 0) {
1111 //No pending scheduled event handling threads. So start a new one.
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -07001112 eventHandlerFuture = executorService
1113 .schedule(eventHandler, 100, TimeUnit.MILLISECONDS);
1114 numOfHandlerScheduled++;
1115 }
Jonathan Hart54541d12016-04-12 15:39:44 -07001116 log.trace("numOfEventsQueued {}, numOfEventHandlerScheduled {}",
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001117 numOfEventsQueued,
1118 numOfHandlerScheduled);
sangho80f11cb2015-04-01 13:05:26 -07001119 }
sangho80f11cb2015-04-01 13:05:26 -07001120 }
1121
1122 private class InternalEventHandler implements Runnable {
Srikanth Vavilapalli37a461b2015-04-07 15:12:32 -07001123 @Override
sangho80f11cb2015-04-01 13:05:26 -07001124 public void run() {
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -07001125 try {
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001126 while (true) {
Saurav Das2d94d312015-11-24 23:21:05 -08001127 @SuppressWarnings("rawtypes")
Charles Chan3ed34d82017-06-22 18:03:14 -07001128 Event event;
1129 synchronized (THREAD_SCHED_LOCK) {
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001130 if (!eventQueue.isEmpty()) {
1131 event = eventQueue.poll();
1132 numOfEventsExecuted++;
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -07001133 } else {
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001134 numOfHandlerExecution++;
1135 log.debug("numOfHandlerExecution {} numOfEventsExecuted {}",
1136 numOfHandlerExecution, numOfEventsExecuted);
1137 break;
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -07001138 }
sanghofb7c7292015-04-13 15:15:58 -07001139 }
Charles Chan0cff8aa2017-03-29 16:39:05 -07001140 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1141 event.type() == LinkEvent.Type.LINK_UPDATED) {
Saurav Das62ae6792017-05-15 15:34:25 -07001142 // Note: do not update seenLinks here, otherwise every
1143 // link, even one seen for the first time, will be appear
1144 // to be a previously seen link
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001145 processLinkAdded((Link) event.subject());
1146 } else if (event.type() == LinkEvent.Type.LINK_REMOVED) {
Pier Ventre6d593892016-09-13 21:33:40 -07001147 Link linkRemoved = (Link) event.subject();
Saurav Das62ae6792017-05-15 15:34:25 -07001148 if (linkRemoved.type() == Link.Type.DIRECT) {
1149 updateSeenLink(linkRemoved, false);
1150 }
1151 // device availability check helps to ensure that
1152 // multiple link-removed events are actually treated as a
1153 // single switch removed event. purgeSeenLink is necessary
1154 // so we do rerouting (instead of rehashing) when switch
1155 // comes back.
Pier Ventre6d593892016-09-13 21:33:40 -07001156 if (linkRemoved.src().elementId() instanceof DeviceId &&
1157 !deviceService.isAvailable(linkRemoved.src().deviceId())) {
Saurav Das62ae6792017-05-15 15:34:25 -07001158 purgeSeenLink(linkRemoved);
Pier Ventre6d593892016-09-13 21:33:40 -07001159 continue;
1160 }
1161 if (linkRemoved.dst().elementId() instanceof DeviceId &&
1162 !deviceService.isAvailable(linkRemoved.dst().deviceId())) {
Saurav Das62ae6792017-05-15 15:34:25 -07001163 purgeSeenLink(linkRemoved);
Pier Ventre6d593892016-09-13 21:33:40 -07001164 continue;
1165 }
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001166 processLinkRemoved((Link) event.subject());
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001167 } else if (event.type() == DeviceEvent.Type.DEVICE_ADDED ||
1168 event.type() == DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED ||
1169 event.type() == DeviceEvent.Type.DEVICE_UPDATED) {
Saurav Das62af8802015-12-04 10:52:59 -08001170 DeviceId deviceId = ((Device) event.subject()).id();
1171 if (deviceService.isAvailable(deviceId)) {
Saurav Dasc28b3432015-10-30 17:45:38 -07001172 log.info("Processing device event {} for available device {}",
1173 event.type(), ((Device) event.subject()).id());
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001174 processDeviceAdded((Device) event.subject());
Saurav Dasc3604f12016-03-23 11:22:49 -07001175 } else {
1176 log.info("Processing device event {} for unavailable device {}",
1177 event.type(), ((Device) event.subject()).id());
1178 processDeviceRemoved((Device) event.subject());
1179 }
Saurav Dasf0f592d2016-11-18 15:21:57 -08001180 } else if (event.type() == DeviceEvent.Type.PORT_ADDED) {
Saurav Dasd1872b02016-12-02 15:43:47 -08001181 // typically these calls come when device is added first time
1182 // so port filtering rules are handled at the device_added event.
1183 // port added calls represent all ports on the device,
1184 // enabled or not.
Saurav Das62ae6792017-05-15 15:34:25 -07001185 log.trace("** PORT ADDED {}/{} -> {}",
Saurav Dasd1872b02016-12-02 15:43:47 -08001186 ((DeviceEvent) event).subject().id(),
1187 ((DeviceEvent) event).port().number(),
1188 event.type());
Saurav Dasf0f592d2016-11-18 15:21:57 -08001189 } else if (event.type() == DeviceEvent.Type.PORT_UPDATED) {
Saurav Dasd1872b02016-12-02 15:43:47 -08001190 // these calls happen for every subsequent event
1191 // ports enabled, disabled, switch goes away, comes back
Saurav Dasf0f592d2016-11-18 15:21:57 -08001192 log.info("** PORT UPDATED {}/{} -> {}",
1193 event.subject(),
1194 ((DeviceEvent) event).port(),
1195 event.type());
1196 processPortUpdated(((Device) event.subject()),
1197 ((DeviceEvent) event).port());
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001198 } else {
1199 log.warn("Unhandled event type: {}", event.type());
1200 }
sangho80f11cb2015-04-01 13:05:26 -07001201 }
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -07001202 } catch (Exception e) {
1203 log.error("SegmentRouting event handler "
1204 + "thread thrown an exception: {}", e);
sangho80f11cb2015-04-01 13:05:26 -07001205 }
sangho80f11cb2015-04-01 13:05:26 -07001206 }
1207 }
1208
sangho80f11cb2015-04-01 13:05:26 -07001209 private void processLinkAdded(Link link) {
Saurav Dasb149be12016-06-07 10:08:06 -07001210 log.info("** LINK ADDED {}", link.toString());
Saurav Das62ae6792017-05-15 15:34:25 -07001211 if (link.type() != Link.Type.DIRECT) {
1212 // NOTE: A DIRECT link might be transiently marked as INDIRECT
1213 // if BDDP is received before LLDP. We can safely ignore that
1214 // until the LLDP is received and the link is marked as DIRECT.
1215 log.info("Ignore link {}->{}. Link type is {} instead of DIRECT.",
1216 link.src(), link.dst(), link.type());
1217 return;
1218 }
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001219 if (!deviceConfiguration.isConfigured(link.src().deviceId())) {
1220 updateSeenLink(link, true);
1221 // XXX revisit - what about devicePortMap
1222 log.warn("Source device of this link is not configured.. "
1223 + "not processing further");
1224 return;
1225 }
Saurav Das62ae6792017-05-15 15:34:25 -07001226
1227 //Irrespective of whether the local is a MASTER or not for this device,
1228 //create group handler instance and push default TTP flow rules if needed,
1229 //as in a multi-instance setup, instances can initiate groups for any device.
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -07001230 DefaultGroupHandler groupHandler = groupHandlerMap.get(link.src()
1231 .deviceId());
1232 if (groupHandler != null) {
Saurav Das62ae6792017-05-15 15:34:25 -07001233 groupHandler.portUpForLink(link);
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -07001234 } else {
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001235 // XXX revisit/cleanup
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -07001236 Device device = deviceService.getDevice(link.src().deviceId());
1237 if (device != null) {
1238 log.warn("processLinkAdded: Link Added "
1239 + "Notification without Device Added "
1240 + "event, still handling it");
1241 processDeviceAdded(device);
1242 groupHandler = groupHandlerMap.get(link.src()
1243 .deviceId());
Saurav Das62ae6792017-05-15 15:34:25 -07001244 groupHandler.portUpForLink(link);
sangho80f11cb2015-04-01 13:05:26 -07001245 }
1246 }
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -07001247
Saurav Das261c3002017-06-13 15:35:54 -07001248 /*// process link only if it is bidirectional
1249 if (!isBidirectional(link)) {
1250 log.debug("Link not bidirectional.. waiting for other direction "
1251 + "src {} --> dst {} ", link.dst(), link.src());
1252 // note that if we are not processing for routing, it should at least
1253 // be considered a seen-link
1254 updateSeenLink(link, true);
1255 return;
1256 }
1257 TO DO this ensure that rehash is still done correctly even if link is
1258 not processed for rerouting - perhaps rehash in both directions when
1259 it ultimately becomes bidi?
1260 */
1261
1262 log.debug("Starting optimized route population process for link "
1263 + "{} --> {}", link.src(), link.dst());
Saurav Das62ae6792017-05-15 15:34:25 -07001264 boolean seenBefore = isSeenLink(link);
1265 defaultRoutingHandler.populateRoutingRulesForLinkStatusChange(null, link, null);
Saurav Das261c3002017-06-13 15:35:54 -07001266
1267 // It's possible that linkUp causes no route-path change as ECMP graph does
1268 // not change if the link is a parallel link (same src-dst as another link.
1269 // However we still need to update ECMP hash groups to include new buckets
1270 // for the link that has come up.
Saurav Das62ae6792017-05-15 15:34:25 -07001271 if (mastershipService.isLocalMaster(link.src().deviceId())) {
Saurav Das261c3002017-06-13 15:35:54 -07001272 if (!seenBefore && isParallelLink(link)) {
Saurav Das62ae6792017-05-15 15:34:25 -07001273 // if link seen first time, we need to ensure hash-groups have all ports
Saurav Das261c3002017-06-13 15:35:54 -07001274 log.debug("Attempting retryHash for paralled first-time link {}", link);
Saurav Das62ae6792017-05-15 15:34:25 -07001275 groupHandler.retryHash(link, false, true);
1276 } else {
1277 //seen before-link
1278 if (isParallelLink(link)) {
Saurav Das261c3002017-06-13 15:35:54 -07001279 log.debug("Attempting retryHash for paralled seen-before "
1280 + "link {}", link);
Saurav Das62ae6792017-05-15 15:34:25 -07001281 groupHandler.retryHash(link, false, false);
1282 }
1283 }
1284 }
Charles Chan72779502016-04-23 17:36:10 -07001285
1286 mcastHandler.init();
sangho80f11cb2015-04-01 13:05:26 -07001287 }
1288
1289 private void processLinkRemoved(Link link) {
Saurav Dasb149be12016-06-07 10:08:06 -07001290 log.info("** LINK REMOVED {}", link.toString());
Saurav Das62ae6792017-05-15 15:34:25 -07001291 defaultRoutingHandler.populateRoutingRulesForLinkStatusChange(link, null, null);
1292
1293 // update local groupHandler stores
sangho2165d222015-05-01 09:38:25 -07001294 DefaultGroupHandler groupHandler = groupHandlerMap.get(link.src().deviceId());
1295 if (groupHandler != null) {
Saurav Das62ae6792017-05-15 15:34:25 -07001296 if (mastershipService.isLocalMaster(link.src().deviceId()) &&
1297 isParallelLink(link)) {
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001298 log.debug("* retrying hash for parallel link removed:{}", link);
Saurav Das62ae6792017-05-15 15:34:25 -07001299 groupHandler.retryHash(link, true, false);
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001300 } else {
1301 log.debug("Not attempting retry-hash for link removed: {} .. {}", link,
1302 (mastershipService.isLocalMaster(link.src().deviceId()))
1303 ? "not parallel" : "not master");
Saurav Das62ae6792017-05-15 15:34:25 -07001304 }
1305 // ensure local stores are updated
1306 groupHandler.portDown(link.src().port());
1307 } else {
1308 log.warn("group handler not found for dev:{} when removing link: {}",
1309 link.src().deviceId(), link);
sangho2165d222015-05-01 09:38:25 -07001310 }
Charles Chan72779502016-04-23 17:36:10 -07001311
1312 mcastHandler.processLinkDown(link);
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -07001313 l2TunnelHandler.processLinkDown(link);
sangho80f11cb2015-04-01 13:05:26 -07001314 }
1315
1316 private void processDeviceAdded(Device device) {
Saurav Dasb149be12016-06-07 10:08:06 -07001317 log.info("** DEVICE ADDED with ID {}", device.id());
Charles Chan9bd6aea2017-06-27 18:48:32 -07001318
1319 // NOTE: Punt ARP/NDP even when the device is not configured.
1320 // Host learning without network config is required for CORD config generator.
1321 routingRulePopulator.populateIpPunts(device.id());
1322 routingRulePopulator.populateArpNdpPunts(device.id());
1323
Charles Chan319d1a22015-11-03 10:42:14 -08001324 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
Saurav Das261c3002017-06-13 15:35:54 -07001325 log.warn("Device configuration unavailable. Device {} will be "
1326 + "processed after configuration.", device.id());
Saurav Das8ec0ec42015-11-03 14:39:27 -08001327 return;
1328 }
Charles Chan72779502016-04-23 17:36:10 -07001329 processDeviceAddedInternal(device.id());
1330 }
1331
1332 private void processDeviceAddedInternal(DeviceId deviceId) {
Saurav Dasc28b3432015-10-30 17:45:38 -07001333 // Irrespective of whether the local is a MASTER or not for this device,
1334 // we need to create a SR-group-handler instance. This is because in a
1335 // multi-instance setup, any instance can initiate forwarding/next-objectives
1336 // for any switch (even if this instance is a SLAVE or not even connected
1337 // to the switch). To handle this, a default-group-handler instance is necessary
1338 // per switch.
Charles Chan72779502016-04-23 17:36:10 -07001339 log.debug("Current groupHandlerMap devs: {}", groupHandlerMap.keySet());
1340 if (groupHandlerMap.get(deviceId) == null) {
Charles Chan319d1a22015-11-03 10:42:14 -08001341 DefaultGroupHandler groupHandler;
1342 try {
1343 groupHandler = DefaultGroupHandler.
Charles Chan72779502016-04-23 17:36:10 -07001344 createGroupHandler(deviceId,
1345 appId,
1346 deviceConfiguration,
1347 linkService,
1348 flowObjectiveService,
1349 this);
Charles Chan319d1a22015-11-03 10:42:14 -08001350 } catch (DeviceConfigNotFoundException e) {
1351 log.warn(e.getMessage() + " Aborting processDeviceAdded.");
1352 return;
1353 }
Charles Chan72779502016-04-23 17:36:10 -07001354 log.debug("updating groupHandlerMap with new config for device: {}",
1355 deviceId);
1356 groupHandlerMap.put(deviceId, groupHandler);
Saurav Das8ec0ec42015-11-03 14:39:27 -08001357 }
Saurav Dasb149be12016-06-07 10:08:06 -07001358
Charles Chan72779502016-04-23 17:36:10 -07001359 if (mastershipService.isLocalMaster(deviceId)) {
Saurav Dasf9332192017-02-18 14:05:44 -08001360 defaultRoutingHandler.populatePortAddressingRules(deviceId);
Charles Chandebfea32016-10-24 14:52:01 -07001361 hostHandler.init(deviceId);
Charles Chan82f19972016-05-17 13:13:55 -07001362 xConnectHandler.init(deviceId);
Charles Chan72779502016-04-23 17:36:10 -07001363 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
Charles Chan10b0fb72017-02-02 16:20:42 -08001364 groupHandler.createGroupsFromVlanConfig();
Charles Chan72779502016-04-23 17:36:10 -07001365 routingRulePopulator.populateSubnetBroadcastRule(deviceId);
Charles Chan77277672015-10-20 16:24:19 -07001366 }
Charles Chan82ab1932016-01-30 23:22:37 -08001367
Charles Chandebfea32016-10-24 14:52:01 -07001368 appCfgHandler.init(deviceId);
1369 routeHandler.init(deviceId);
sangho80f11cb2015-04-01 13:05:26 -07001370 }
1371
Saurav Dasc3604f12016-03-23 11:22:49 -07001372 private void processDeviceRemoved(Device device) {
Saurav Das261c3002017-06-13 15:35:54 -07001373 dsNextObjStore.entrySet().stream()
Saurav Dasc3604f12016-03-23 11:22:49 -07001374 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
1375 .forEach(entry -> {
Saurav Das261c3002017-06-13 15:35:54 -07001376 dsNextObjStore.remove(entry.getKey());
Saurav Dasc3604f12016-03-23 11:22:49 -07001377 });
Charles Chan10b0fb72017-02-02 16:20:42 -08001378 vlanNextObjStore.entrySet().stream()
Saurav Dasc3604f12016-03-23 11:22:49 -07001379 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan3ed34d82017-06-22 18:03:14 -07001380 .forEach(entry -> vlanNextObjStore.remove(entry.getKey()));
Saurav Dasc3604f12016-03-23 11:22:49 -07001381 portNextObjStore.entrySet().stream()
1382 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan3ed34d82017-06-22 18:03:14 -07001383 .forEach(entry -> portNextObjStore.remove(entry.getKey()));
Charles Chan17d75d82017-06-15 00:44:51 -07001384
1385 seenLinks.keySet().removeIf(key -> key.src().deviceId().equals(device.id()) ||
1386 key.dst().deviceId().equals(device.id()));
1387
Saurav Dasfbe74572017-08-03 18:30:35 -07001388 DefaultGroupHandler gh = groupHandlerMap.remove(device.id());
1389 if (gh != null) {
1390 gh.shutdown();
1391 }
Saurav Dasc3604f12016-03-23 11:22:49 -07001392 defaultRoutingHandler.purgeEcmpGraph(device.id());
Saurav Das62ae6792017-05-15 15:34:25 -07001393 // Note that a switch going down is associated with all of its links
1394 // going down as well, but it is treated as a single switch down event
1395 // while the link-downs are ignored.
1396 defaultRoutingHandler
1397 .populateRoutingRulesForLinkStatusChange(null, null, device.id());
Charles Chan72779502016-04-23 17:36:10 -07001398 mcastHandler.removeDevice(device.id());
Charles Chan82f19972016-05-17 13:13:55 -07001399 xConnectHandler.removeDevice(device.id());
Saurav Dasc3604f12016-03-23 11:22:49 -07001400 }
1401
Saurav Dasf0f592d2016-11-18 15:21:57 -08001402 private void processPortUpdated(Device device, Port port) {
1403 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
1404 log.warn("Device configuration uploading. Not handling port event for"
1405 + "dev: {} port: {}", device.id(), port.number());
1406 return;
1407 }
Saurav Dasf9332192017-02-18 14:05:44 -08001408
1409 if (!mastershipService.isLocalMaster(device.id())) {
1410 log.debug("Not master for dev:{} .. not handling port updated event"
1411 + "for port {}", device.id(), port.number());
1412 return;
1413 }
1414
1415 // first we handle filtering rules associated with the port
1416 if (port.isEnabled()) {
1417 log.info("Switchport {}/{} enabled..programming filters",
1418 device.id(), port.number());
Charles Chan43be46b2017-02-26 22:59:35 -08001419 routingRulePopulator.processSinglePortFilters(device.id(), port.number(), true);
Saurav Dasf9332192017-02-18 14:05:44 -08001420 } else {
1421 log.info("Switchport {}/{} disabled..removing filters",
1422 device.id(), port.number());
Charles Chan43be46b2017-02-26 22:59:35 -08001423 routingRulePopulator.processSinglePortFilters(device.id(), port.number(), false);
Saurav Dasf9332192017-02-18 14:05:44 -08001424 }
Saurav Dasf0f592d2016-11-18 15:21:57 -08001425
1426 // portUpdated calls are for ports that have gone down or up. For switch
1427 // to switch ports, link-events should take care of any re-routing or
1428 // group editing necessary for port up/down. Here we only process edge ports
1429 // that are already configured.
Saurav Das3fb28272017-03-04 16:08:47 -08001430 ConnectPoint cp = new ConnectPoint(device.id(), port.number());
1431 VlanId untaggedVlan = getUntaggedVlanId(cp);
1432 VlanId nativeVlan = getNativeVlanId(cp);
1433 Set<VlanId> taggedVlans = getTaggedVlanId(cp);
Charles Chan10b0fb72017-02-02 16:20:42 -08001434
Saurav Das3fb28272017-03-04 16:08:47 -08001435 if (untaggedVlan == null && nativeVlan == null && taggedVlans.isEmpty()) {
Saurav Das62ae6792017-05-15 15:34:25 -07001436 log.debug("Not handling port updated event for non-edge port (unconfigured) "
Saurav Dasf0f592d2016-11-18 15:21:57 -08001437 + "dev/port: {}/{}", device.id(), port.number());
1438 return;
1439 }
Saurav Das3fb28272017-03-04 16:08:47 -08001440 if (untaggedVlan != null) {
1441 processEdgePort(device, port, untaggedVlan, true);
1442 }
1443 if (nativeVlan != null) {
1444 processEdgePort(device, port, nativeVlan, true);
1445 }
1446 if (!taggedVlans.isEmpty()) {
1447 taggedVlans.forEach(tag -> processEdgePort(device, port, tag, false));
1448 }
Saurav Dasf0f592d2016-11-18 15:21:57 -08001449 }
1450
Saurav Das3fb28272017-03-04 16:08:47 -08001451 private void processEdgePort(Device device, Port port, VlanId vlanId,
1452 boolean popVlan) {
Saurav Dasf0f592d2016-11-18 15:21:57 -08001453 boolean portUp = port.isEnabled();
1454 if (portUp) {
Saurav Das3fb28272017-03-04 16:08:47 -08001455 log.info("Device:EdgePort {}:{} is enabled in vlan: {}", device.id(),
Charles Chan10b0fb72017-02-02 16:20:42 -08001456 port.number(), vlanId);
Saurav Dasf0f592d2016-11-18 15:21:57 -08001457 } else {
Saurav Das3fb28272017-03-04 16:08:47 -08001458 log.info("Device:EdgePort {}:{} is disabled in vlan: {}", device.id(),
Charles Chan10b0fb72017-02-02 16:20:42 -08001459 port.number(), vlanId);
Saurav Dasf0f592d2016-11-18 15:21:57 -08001460 }
1461
Srikanth Vavilapalli64505482015-04-21 13:04:13 -07001462 DefaultGroupHandler groupHandler = groupHandlerMap.get(device.id());
sangho80f11cb2015-04-01 13:05:26 -07001463 if (groupHandler != null) {
Saurav Das3fb28272017-03-04 16:08:47 -08001464 groupHandler.processEdgePort(port.number(), vlanId, popVlan, portUp);
Saurav Dasf0f592d2016-11-18 15:21:57 -08001465 } else {
1466 log.warn("Group handler not found for dev:{}. Not handling edge port"
1467 + " {} event for port:{}", device.id(),
1468 (portUp) ? "UP" : "DOWN", port.number());
sangho80f11cb2015-04-01 13:05:26 -07001469 }
1470 }
sangho27462c62015-05-14 00:39:53 -07001471
Charles Chan8ca5a122017-10-20 16:06:55 -07001472 private void createOrUpdateDeviceConfiguration() {
1473 if (deviceConfiguration == null) {
1474 deviceConfiguration = new DeviceConfiguration(this);
1475 } else {
1476 deviceConfiguration.updateConfig();
1477 }
1478 }
1479
Pier Ventreb6a7f342016-11-26 21:05:22 -08001480 /**
1481 * Registers the given connect point with the NRS, this is necessary
1482 * to receive the NDP and ARP packets from the NRS.
1483 *
1484 * @param portToRegister connect point to register
1485 */
1486 public void registerConnectPoint(ConnectPoint portToRegister) {
Charles Chan2e71ef32017-02-23 15:44:08 -08001487 neighbourResolutionService.registerNeighbourHandler(
Pier Ventreb6a7f342016-11-26 21:05:22 -08001488 portToRegister,
1489 neighbourHandler,
1490 appId
1491 );
1492 }
1493
Charles Chan72f556a2015-10-05 17:50:33 -07001494 private class InternalConfigListener implements NetworkConfigListener {
Saurav Das261c3002017-06-13 15:35:54 -07001495 private static final long PROGRAM_DELAY = 2;
Charles Chan46fdfaf2016-11-09 20:51:44 -08001496 SegmentRoutingManager srManager;
Charles Chane7c61022015-10-07 14:21:45 -07001497
Charles Chanb7f75ac2016-01-11 18:28:54 -08001498 /**
1499 * Constructs the internal network config listener.
1500 *
Charles Chan46fdfaf2016-11-09 20:51:44 -08001501 * @param srManager segment routing manager
Charles Chanb7f75ac2016-01-11 18:28:54 -08001502 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001503 InternalConfigListener(SegmentRoutingManager srManager) {
Charles Chan46fdfaf2016-11-09 20:51:44 -08001504 this.srManager = srManager;
Charles Chane7c61022015-10-07 14:21:45 -07001505 }
1506
Charles Chanb7f75ac2016-01-11 18:28:54 -08001507 /**
1508 * Reads network config and initializes related data structure accordingly.
1509 */
Charles Chane7c61022015-10-07 14:21:45 -07001510 public void configureNetwork() {
Charles Chan8ca5a122017-10-20 16:06:55 -07001511 createOrUpdateDeviceConfiguration();
Charles Chane7c61022015-10-07 14:21:45 -07001512
Charles Chan46fdfaf2016-11-09 20:51:44 -08001513 arpHandler = new ArpHandler(srManager);
1514 icmpHandler = new IcmpHandler(srManager);
1515 ipHandler = new IpHandler(srManager);
1516 routingRulePopulator = new RoutingRulePopulator(srManager);
1517 defaultRoutingHandler = new DefaultRoutingHandler(srManager);
Charles Chane7c61022015-10-07 14:21:45 -07001518
1519 tunnelHandler = new TunnelHandler(linkService, deviceConfiguration,
1520 groupHandlerMap, tunnelStore);
1521 policyHandler = new PolicyHandler(appId, deviceConfiguration,
1522 flowObjectiveService,
1523 tunnelHandler, policyStore);
Saurav Das261c3002017-06-13 15:35:54 -07001524 // add a small delay to absorb multiple network config added notifications
1525 if (!programmingScheduled.get()) {
1526 programmingScheduled.set(true);
1527 executorService.schedule(new ConfigChange(), PROGRAM_DELAY,
1528 TimeUnit.SECONDS);
Charles Chane7c61022015-10-07 14:21:45 -07001529 }
Charles Chan72779502016-04-23 17:36:10 -07001530 mcastHandler.init();
Charles Chane7c61022015-10-07 14:21:45 -07001531 }
1532
Charles Chan72f556a2015-10-05 17:50:33 -07001533 @Override
1534 public void event(NetworkConfigEvent event) {
Charles Chan82ab1932016-01-30 23:22:37 -08001535 // TODO move this part to NetworkConfigEventHandler
1536 if (event.configClass().equals(SegmentRoutingDeviceConfig.class)) {
1537 switch (event.type()) {
1538 case CONFIG_ADDED:
Charles Chan68363b12017-06-26 15:25:09 -07001539 log.info("Segment Routing Device Config added for {}", event.subject());
Charles Chan82ab1932016-01-30 23:22:37 -08001540 configureNetwork();
1541 break;
1542 case CONFIG_UPDATED:
Charles Chan68363b12017-06-26 15:25:09 -07001543 log.info("Segment Routing Config updated for {}", event.subject());
Charles Chan8ca5a122017-10-20 16:06:55 -07001544 createOrUpdateDeviceConfiguration();
Charles Chan68363b12017-06-26 15:25:09 -07001545 // TODO support dynamic configuration
1546 break;
1547 default:
1548 break;
1549 }
1550 } else if (event.configClass().equals(InterfaceConfig.class)) {
1551 switch (event.type()) {
1552 case CONFIG_ADDED:
1553 log.info("Interface Config added for {}", event.subject());
1554 configureNetwork();
1555 break;
1556 case CONFIG_UPDATED:
1557 log.info("Interface Config updated for {}", event.subject());
Charles Chan8ca5a122017-10-20 16:06:55 -07001558 createOrUpdateDeviceConfiguration();
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001559
1560 // Following code will be uncommented when [CORD-634] is fully implemented.
1561 // [CORD-634] Add dynamic config support for interfaces
1562 updateInterface((InterfaceConfig) event.config().get(),
1563 (InterfaceConfig) event.prevConfig().get());
Charles Chan82ab1932016-01-30 23:22:37 -08001564 // TODO support dynamic configuration
1565 break;
1566 default:
1567 break;
Charles Chan2b078ae2015-10-14 11:24:40 -07001568 }
Charles Chan82ab1932016-01-30 23:22:37 -08001569 } else if (event.configClass().equals(SegmentRoutingAppConfig.class)) {
Charles Chan82f19972016-05-17 13:13:55 -07001570 checkState(appCfgHandler != null, "NetworkConfigEventHandler is not initialized");
Charles Chan82ab1932016-01-30 23:22:37 -08001571 switch (event.type()) {
1572 case CONFIG_ADDED:
Charles Chan82f19972016-05-17 13:13:55 -07001573 appCfgHandler.processAppConfigAdded(event);
Charles Chan82ab1932016-01-30 23:22:37 -08001574 break;
1575 case CONFIG_UPDATED:
Charles Chan82f19972016-05-17 13:13:55 -07001576 appCfgHandler.processAppConfigUpdated(event);
Charles Chan82ab1932016-01-30 23:22:37 -08001577 break;
1578 case CONFIG_REMOVED:
Charles Chan82f19972016-05-17 13:13:55 -07001579 appCfgHandler.processAppConfigRemoved(event);
1580 break;
1581 default:
1582 break;
1583 }
Charles Chandebfea32016-10-24 14:52:01 -07001584 configureNetwork();
Charles Chan82f19972016-05-17 13:13:55 -07001585 } else if (event.configClass().equals(XConnectConfig.class)) {
1586 checkState(xConnectHandler != null, "XConnectHandler is not initialized");
1587 switch (event.type()) {
1588 case CONFIG_ADDED:
1589 xConnectHandler.processXConnectConfigAdded(event);
1590 break;
1591 case CONFIG_UPDATED:
1592 xConnectHandler.processXConnectConfigUpdated(event);
1593 break;
1594 case CONFIG_REMOVED:
1595 xConnectHandler.processXConnectConfigRemoved(event);
Charles Chan82ab1932016-01-30 23:22:37 -08001596 break;
1597 default:
1598 break;
Charles Chan2b078ae2015-10-14 11:24:40 -07001599 }
Pier Ventre6b19e482016-11-07 16:21:04 -08001600 } else if (event.configClass().equals(PwaasConfig.class)) {
1601 checkState(l2TunnelHandler != null, "L2TunnelHandler is not initialized");
1602 switch (event.type()) {
1603 case CONFIG_ADDED:
1604 l2TunnelHandler.processPwaasConfigAdded(event);
1605 break;
1606 case CONFIG_UPDATED:
1607 l2TunnelHandler.processPwaasConfigUpdated(event);
1608 break;
1609 case CONFIG_REMOVED:
1610 l2TunnelHandler.processPwaasConfigRemoved(event);
1611 break;
1612 default:
1613 break;
1614 }
Charles Chan72f556a2015-10-05 17:50:33 -07001615 }
1616 }
Saurav Das261c3002017-06-13 15:35:54 -07001617
1618 private final class ConfigChange implements Runnable {
1619 @Override
1620 public void run() {
1621 programmingScheduled.set(false);
1622 for (Device device : deviceService.getDevices()) {
1623 processDeviceAdded(device);
1624 }
1625 defaultRoutingHandler.startPopulationProcess();
1626 }
1627 }
Charles Chan72f556a2015-10-05 17:50:33 -07001628 }
Charles Chanf4586112015-11-09 16:37:23 -08001629
1630 private class InternalHostListener implements HostListener {
Charles Chanf4586112015-11-09 16:37:23 -08001631 @Override
1632 public void event(HostEvent event) {
Charles Chanf4586112015-11-09 16:37:23 -08001633 switch (event.type()) {
1634 case HOST_ADDED:
Charles Chan1eaf4802016-04-18 13:44:03 -07001635 hostHandler.processHostAddedEvent(event);
Charles Chanf4586112015-11-09 16:37:23 -08001636 break;
1637 case HOST_MOVED:
Charles Chan1eaf4802016-04-18 13:44:03 -07001638 hostHandler.processHostMovedEvent(event);
Charles Chan910be6a2017-08-23 14:46:43 -07001639 routeHandler.processHostMovedEvent(event);
Charles Chanf4586112015-11-09 16:37:23 -08001640 break;
1641 case HOST_REMOVED:
Charles Chand9265a32017-06-16 15:19:24 -07001642 hostHandler.processHostRemovedEvent(event);
Charles Chanf4586112015-11-09 16:37:23 -08001643 break;
1644 case HOST_UPDATED:
Charles Chan1eaf4802016-04-18 13:44:03 -07001645 hostHandler.processHostUpdatedEvent(event);
Charles Chanf4586112015-11-09 16:37:23 -08001646 break;
1647 default:
1648 log.warn("Unsupported host event type: {}", event.type());
1649 break;
1650 }
1651 }
1652 }
1653
Charles Chanc91c8782016-03-30 17:54:24 -07001654 private class InternalMcastListener implements McastListener {
1655 @Override
1656 public void event(McastEvent event) {
1657 switch (event.type()) {
1658 case SOURCE_ADDED:
Charles Chan1eaf4802016-04-18 13:44:03 -07001659 mcastHandler.processSourceAdded(event);
Charles Chanc91c8782016-03-30 17:54:24 -07001660 break;
1661 case SINK_ADDED:
Charles Chan1eaf4802016-04-18 13:44:03 -07001662 mcastHandler.processSinkAdded(event);
Charles Chanc91c8782016-03-30 17:54:24 -07001663 break;
1664 case SINK_REMOVED:
Charles Chan1eaf4802016-04-18 13:44:03 -07001665 mcastHandler.processSinkRemoved(event);
Charles Chanc91c8782016-03-30 17:54:24 -07001666 break;
1667 case ROUTE_ADDED:
1668 case ROUTE_REMOVED:
1669 default:
1670 break;
1671 }
1672 }
1673 }
Charles Chan41f5ec02016-06-13 18:54:31 -07001674
Charles Chandebfea32016-10-24 14:52:01 -07001675 private class InternalRouteEventListener implements RouteListener {
1676 @Override
1677 public void event(RouteEvent event) {
1678 switch (event.type()) {
1679 case ROUTE_ADDED:
1680 routeHandler.processRouteAdded(event);
1681 break;
1682 case ROUTE_UPDATED:
1683 routeHandler.processRouteUpdated(event);
1684 break;
1685 case ROUTE_REMOVED:
1686 routeHandler.processRouteRemoved(event);
1687 break;
Charles Chan910be6a2017-08-23 14:46:43 -07001688 case ALTERNATIVE_ROUTES_CHANGED:
1689 routeHandler.processAlternativeRoutesChanged(event);
1690 break;
Charles Chandebfea32016-10-24 14:52:01 -07001691 default:
1692 break;
1693 }
1694 }
1695 }
Saurav Das62ae6792017-05-15 15:34:25 -07001696
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001697 private void updateInterface(InterfaceConfig conf, InterfaceConfig prevConf) {
1698 try {
1699 Set<Interface> intfs = conf.getInterfaces();
1700 Set<Interface> prevIntfs = prevConf.getInterfaces();
1701
1702 // Now we only handle one interface config at each port.
1703 if (intfs.size() != 1 || prevIntfs.size() != 1) {
1704 log.warn("Interface update aborted - one at a time is allowed, " +
1705 "but {} / {}(prev) received.", intfs.size(), prevIntfs.size());
1706 return;
1707 }
1708
1709 Interface intf = intfs.stream().findFirst().get();
1710 Interface prevIntf = prevIntfs.stream().findFirst().get();
1711
1712 DeviceId deviceId = intf.connectPoint().deviceId();
1713 PortNumber portNum = intf.connectPoint().port();
1714
1715 if (!mastershipService.isLocalMaster(deviceId)) {
1716 log.debug("CONFIG_UPDATED event for interfaces should be " +
1717 "handled by master node for device {}", deviceId);
1718 return;
1719 }
1720
1721 removeSubnetConfig(prevIntf.connectPoint(),
1722 Sets.difference(new HashSet<>(prevIntf.ipAddressesList()),
1723 new HashSet<>(intf.ipAddressesList())));
1724
1725 if (prevIntf.vlanNative() != VlanId.NONE && !intf.vlanNative().equals(prevIntf.vlanNative())) {
1726 // RemoveVlanNative
1727 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanNative(), true, false);
1728 }
1729
1730 if (!prevIntf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
1731 // RemoveVlanTagged
1732 prevIntf.vlanTagged().stream().filter(i -> !intf.vlanTagged().contains(i)).forEach(
1733 vlanId -> updateVlanConfigInternal(deviceId, portNum, vlanId, false, false)
1734 );
1735 }
1736
1737 if (prevIntf.vlanUntagged() != VlanId.NONE && !intf.vlanUntagged().equals(prevIntf.vlanUntagged())) {
1738 // RemoveVlanUntagged
1739 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanUntagged(), true, false);
1740 }
1741
1742 if (intf.vlanNative() != VlanId.NONE && !prevIntf.vlanNative().equals(intf.vlanNative())) {
1743 // AddVlanNative
1744 updateVlanConfigInternal(deviceId, portNum, intf.vlanNative(), true, true);
1745 }
1746
1747 if (!intf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
1748 // AddVlanTagged
1749 intf.vlanTagged().stream().filter(i -> !prevIntf.vlanTagged().contains(i)).forEach(
1750 vlanId -> updateVlanConfigInternal(deviceId, portNum, vlanId, false, true)
1751 );
1752 }
1753
1754 if (intf.vlanUntagged() != VlanId.NONE && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())) {
1755 // AddVlanUntagged
1756 updateVlanConfigInternal(deviceId, portNum, intf.vlanUntagged(), true, true);
1757 }
1758 addSubnetConfig(prevIntf.connectPoint(),
1759 Sets.difference(new HashSet<>(intf.ipAddressesList()),
1760 new HashSet<>(prevIntf.ipAddressesList())));
1761 } catch (ConfigException e) {
1762 log.error("Error in configuration");
1763 }
1764 }
1765
1766 private void updateVlanConfigInternal(DeviceId deviceId, PortNumber portNum,
1767 VlanId vlanId, boolean pushVlan, boolean install) {
1768 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
1769 if (grpHandler == null) {
1770 log.warn("Failed to retrieve group handler for device {}", deviceId);
1771 return;
1772 }
1773
1774 // Update filtering objective for a single port
1775 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, install);
1776
1777 // Update filtering objective for multicast ingress port
1778 mcastHandler.updateFilterToDevice(deviceId, portNum, vlanId, install);
1779
1780 int nextId = getVlanNextObjectiveId(deviceId, vlanId);
1781
1782 if (nextId != -1 && !install) {
1783 // Update next objective for a single port as an output port
1784 // Remove a single port from L2FG
1785 grpHandler.updateGroupFromVlanConfiguration(portNum, Collections.singleton(vlanId), nextId, install);
1786 // Remove L2 Bridging rule and L3 Unicast rule to the host
1787 hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum, vlanId, pushVlan, install);
1788 // Remove broadcast forwarding rule and corresponding L2FG for VLAN
1789 // only if there is no port configured on that VLAN ID
1790 if (!getVlanPortMap(deviceId).containsKey(vlanId)) {
1791 // Remove broadcast forwarding rule for the VLAN
1792 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
1793 // Remove L2FG for VLAN
1794 grpHandler.removeBcastGroupFromVlan(deviceId, portNum, vlanId, pushVlan);
1795 } else {
1796 // Remove L2IG of the port
1797 grpHandler.removePortNextObjective(deviceId, portNum, vlanId, pushVlan);
1798 }
1799 } else if (install) {
1800 if (nextId != -1) {
1801 // Add a single port to L2FG
1802 grpHandler.updateGroupFromVlanConfiguration(portNum, Collections.singleton(vlanId), nextId, install);
1803 } else {
1804 // Create L2FG for VLAN
1805 grpHandler.createBcastGroupFromVlan(vlanId, Collections.singleton(portNum));
1806 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
1807 }
1808 hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum, vlanId, pushVlan, install);
1809 } else {
1810 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
1811 }
1812 }
1813
1814 private void removeSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
1815 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
1816 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
1817
1818 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
1819 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
1820 .filter(intf -> !intf.connectPoint().equals(cp))
1821 .flatMap(intf -> intf.ipAddressesList().stream())
1822 .collect(Collectors.toSet());
1823 // 1. Partial subnet population
1824 // Remove routing rules for removed subnet from previous configuration,
1825 // which does not also exist in other interfaces in the same device
1826 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
1827 .map(InterfaceIpAddress::subnetAddress)
1828 .collect(Collectors.toSet());
1829
1830 defaultRoutingHandler.revokeSubnet(
1831 ipPrefixSet.stream()
1832 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
1833 .collect(Collectors.toSet()));
1834
1835 // 2. Interface IP punts
1836 // Remove IP punts for old Intf address
1837 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
1838 .map(InterfaceIpAddress::ipAddress)
1839 .collect(Collectors.toSet());
1840 ipAddressSet.stream()
1841 .map(InterfaceIpAddress::ipAddress)
1842 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
1843 .forEach(interfaceIpAddress ->
1844 routingRulePopulator.revokeSingleIpPunts(
1845 cp.deviceId(), interfaceIpAddress));
1846
1847 // 3. Host unicast routing rule
1848 // Remove unicast routing rule
1849 hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, false);
1850 }
1851
1852 private void addSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
1853 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
1854 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
1855
1856 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
1857 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
1858 .filter(intf -> !intf.connectPoint().equals(cp))
1859 .flatMap(intf -> intf.ipAddressesList().stream())
1860 .collect(Collectors.toSet());
1861 // 1. Partial subnet population
1862 // Add routing rules for newly added subnet, which does not also exist in
1863 // other interfaces in the same device
1864 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
1865 .map(InterfaceIpAddress::subnetAddress)
1866 .collect(Collectors.toSet());
1867
1868 defaultRoutingHandler.populateSubnet(
1869 Collections.singleton(cp),
1870 ipPrefixSet.stream()
1871 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
1872 .collect(Collectors.toSet()));
1873
1874 // 2. Interface IP punts
1875 // Add IP punts for new Intf address
1876 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
1877 .map(InterfaceIpAddress::ipAddress)
1878 .collect(Collectors.toSet());
1879 ipAddressSet.stream()
1880 .map(InterfaceIpAddress::ipAddress)
1881 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
1882 .forEach(interfaceIpAddress ->
1883 routingRulePopulator.populateSingleIpPunts(
1884 cp.deviceId(), interfaceIpAddress));
1885
1886 // 3. Host unicast routing rule
1887 // Add unicast routing rule
1888 hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, true);
1889 }
sangho80f11cb2015-04-01 13:05:26 -07001890}