blob: 93665ecd630d7479543e7d5d1a151edbe999907a [file] [log] [blame]
sanghob35a6192015-04-01 13:05:26 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
sanghob35a6192015-04-01 13:05:26 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.segmentrouting;
17
Jonathan Hart8ca2bc02017-11-30 18:23:42 -080018import com.google.common.collect.HashMultimap;
19import com.google.common.collect.ImmutableMap;
20import com.google.common.collect.Maps;
21import com.google.common.collect.Multimap;
Charles Chan9640c812017-08-23 13:55:39 -070022import com.google.common.collect.Sets;
sanghob35a6192015-04-01 13:05:26 -070023import org.apache.felix.scr.annotations.Activate;
24import org.apache.felix.scr.annotations.Component;
25import org.apache.felix.scr.annotations.Deactivate;
Charles Chan47933752017-11-30 15:37:50 -080026import org.apache.felix.scr.annotations.Modified;
27import org.apache.felix.scr.annotations.Property;
sanghob35a6192015-04-01 13:05:26 -070028import org.apache.felix.scr.annotations.Reference;
29import org.apache.felix.scr.annotations.ReferenceCardinality;
sangho1e575652015-05-14 00:39:53 -070030import org.apache.felix.scr.annotations.Service;
sanghob35a6192015-04-01 13:05:26 -070031import org.onlab.packet.Ethernet;
Pier Ventre735b8c82016-12-02 08:16:05 -080032import org.onlab.packet.ICMP6;
Charles Chanc42e84e2015-10-20 16:24:19 -070033import org.onlab.packet.IPv4;
Pier Ventre10bd8d12016-11-26 21:05:22 -080034import org.onlab.packet.IPv6;
Jonghwan Hyun42fe1052017-08-25 17:48:36 -070035import org.onlab.packet.IpAddress;
Charles Chanc42e84e2015-10-20 16:24:19 -070036import org.onlab.packet.IpPrefix;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070037import org.onlab.packet.VlanId;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -070038import org.onlab.util.KryoNamespace;
Charles Chan47933752017-11-30 15:37:50 -080039import org.onlab.util.Tools;
Saurav Das80980c72016-03-23 11:22:49 -070040import org.onosproject.cfg.ComponentConfigService;
Pier Luigieba73a02018-01-16 10:47:50 +010041import org.onosproject.cluster.ClusterService;
42import org.onosproject.cluster.LeadershipService;
sanghob35a6192015-04-01 13:05:26 -070043import org.onosproject.core.ApplicationId;
44import org.onosproject.core.CoreService;
45import org.onosproject.event.Event;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070046import org.onosproject.mastership.MastershipService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080047import org.onosproject.net.ConnectPoint;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070048import org.onosproject.net.Device;
49import org.onosproject.net.DeviceId;
Charles Chan9640c812017-08-23 13:55:39 -070050import org.onosproject.net.Host;
51import org.onosproject.net.HostId;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070052import org.onosproject.net.Link;
53import org.onosproject.net.Port;
Charles Chan68aa62d2015-11-09 16:37:23 -080054import org.onosproject.net.PortNumber;
Jonghwan Hyun42fe1052017-08-25 17:48:36 -070055import org.onosproject.net.config.ConfigException;
Charles Chand6832882015-10-05 17:50:33 -070056import org.onosproject.net.config.ConfigFactory;
57import org.onosproject.net.config.NetworkConfigEvent;
Charles Chand6832882015-10-05 17:50:33 -070058import org.onosproject.net.config.NetworkConfigListener;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070059import org.onosproject.net.config.NetworkConfigRegistry;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070060import org.onosproject.net.config.basics.InterfaceConfig;
61import org.onosproject.net.config.basics.McastConfig;
Charles Chand6832882015-10-05 17:50:33 -070062import org.onosproject.net.config.basics.SubjectFactories;
Saurav Das45f48152018-01-18 12:07:33 -080063import org.onosproject.net.device.DeviceAdminService;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070064import org.onosproject.net.device.DeviceEvent;
65import org.onosproject.net.device.DeviceListener;
66import org.onosproject.net.device.DeviceService;
Charles Chan68aa62d2015-11-09 16:37:23 -080067import org.onosproject.net.flow.TrafficSelector;
68import org.onosproject.net.flow.TrafficTreatment;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070069import org.onosproject.net.flowobjective.FlowObjectiveService;
Charles Chan68aa62d2015-11-09 16:37:23 -080070import org.onosproject.net.host.HostEvent;
71import org.onosproject.net.host.HostListener;
Charles Chan47933752017-11-30 15:37:50 -080072import org.onosproject.net.host.HostLocationProbingService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080073import org.onosproject.net.host.HostService;
Jonghwan Hyun42fe1052017-08-25 17:48:36 -070074import org.onosproject.net.host.InterfaceIpAddress;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070075import org.onosproject.net.intf.Interface;
76import org.onosproject.net.intf.InterfaceService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080077import org.onosproject.net.link.LinkEvent;
78import org.onosproject.net.link.LinkListener;
79import org.onosproject.net.link.LinkService;
Charles Chand55e84d2016-03-30 17:54:24 -070080import org.onosproject.net.mcast.McastEvent;
81import org.onosproject.net.mcast.McastListener;
82import org.onosproject.net.mcast.MulticastRouteService;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070083import org.onosproject.net.neighbour.NeighbourResolutionService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080084import org.onosproject.net.packet.InboundPacket;
85import org.onosproject.net.packet.PacketContext;
86import org.onosproject.net.packet.PacketProcessor;
87import org.onosproject.net.packet.PacketService;
Pier Luigi83f919b2018-02-15 16:33:08 +010088import org.onosproject.net.topology.TopologyEvent;
89import org.onosproject.net.topology.TopologyListener;
Charles Chand55e84d2016-03-30 17:54:24 -070090import org.onosproject.net.topology.TopologyService;
Charles Chan9640c812017-08-23 13:55:39 -070091import org.onosproject.routeservice.ResolvedRoute;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070092import org.onosproject.routeservice.RouteEvent;
93import org.onosproject.routeservice.RouteListener;
94import org.onosproject.routeservice.RouteService;
Charles Chand55e84d2016-03-30 17:54:24 -070095import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
96import org.onosproject.segmentrouting.config.DeviceConfiguration;
Pier Ventref34966c2016-11-07 16:21:04 -080097import org.onosproject.segmentrouting.config.SegmentRoutingAppConfig;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070098import org.onosproject.segmentrouting.config.SegmentRoutingDeviceConfig;
Charles Chanfc5c7802016-05-17 13:13:55 -070099import org.onosproject.segmentrouting.config.XConnectConfig;
Charles Chand55e84d2016-03-30 17:54:24 -0700100import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
Saurav Das7bcbe702017-06-13 15:35:54 -0700101import org.onosproject.segmentrouting.grouphandler.DestinationSet;
102import org.onosproject.segmentrouting.grouphandler.NextNeighbors;
Pier Luigi96fe0772018-02-28 12:10:50 +0100103import org.onosproject.segmentrouting.mcast.McastHandler;
104import org.onosproject.segmentrouting.mcast.McastRole;
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700105import org.onosproject.segmentrouting.pwaas.DefaultL2Tunnel;
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800106import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelHandler;
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700107import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelPolicy;
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800108import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelDescription;
109
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800110import org.onosproject.segmentrouting.pwaas.L2Tunnel;
Ray Milkey6c1f0f02017-08-15 11:02:29 -0700111import org.onosproject.segmentrouting.pwaas.L2TunnelHandler;
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800112import org.onosproject.segmentrouting.pwaas.L2TunnelPolicy;
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800113import org.onosproject.segmentrouting.pwaas.L2TunnelDescription;
114
Saurav Das7bcbe702017-06-13 15:35:54 -0700115import org.onosproject.segmentrouting.storekey.DestinationSetNextObjectiveStoreKey;
Pier Luigib29144d2018-01-15 18:06:43 +0100116import org.onosproject.segmentrouting.storekey.McastStoreKey;
Charles Chand2990362016-04-18 13:44:03 -0700117import org.onosproject.segmentrouting.storekey.PortNextObjectiveStoreKey;
Charles Chan59cc16d2017-02-02 16:20:42 -0800118import org.onosproject.segmentrouting.storekey.VlanNextObjectiveStoreKey;
Charles Chanfc5c7802016-05-17 13:13:55 -0700119import org.onosproject.segmentrouting.storekey.XConnectStoreKey;
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700120import org.onosproject.store.serializers.KryoNamespaces;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700121import org.onosproject.store.service.EventuallyConsistentMap;
122import org.onosproject.store.service.EventuallyConsistentMapBuilder;
123import org.onosproject.store.service.StorageService;
124import org.onosproject.store.service.WallClockTimestamp;
Charles Chan47933752017-11-30 15:37:50 -0800125import org.osgi.service.component.ComponentContext;
sanghob35a6192015-04-01 13:05:26 -0700126import org.slf4j.Logger;
127import org.slf4j.LoggerFactory;
128
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700129import java.util.ArrayList;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800130import java.util.Collections;
Charles Chan47933752017-11-30 15:37:50 -0800131import java.util.Dictionary;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800132import java.util.HashSet;
133import java.util.List;
134import java.util.Map;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800135import java.util.Optional;
136import java.util.Set;
137import java.util.concurrent.ConcurrentHashMap;
138import java.util.concurrent.ConcurrentLinkedQueue;
139import java.util.concurrent.Executors;
140import java.util.concurrent.ScheduledExecutorService;
141import java.util.concurrent.ScheduledFuture;
142import java.util.concurrent.TimeUnit;
143import java.util.concurrent.atomic.AtomicBoolean;
144import java.util.stream.Collectors;
sanghob35a6192015-04-01 13:05:26 -0700145
Charles Chan3e783d02016-02-26 22:19:52 -0800146import static com.google.common.base.Preconditions.checkState;
Pier Ventree0ae7a32016-11-23 09:57:42 -0800147import static org.onlab.packet.Ethernet.TYPE_ARP;
Yuta HIGUCHI1624df12016-07-21 16:54:33 -0700148import static org.onlab.util.Tools.groupedThreads;
Saurav Dase7f51012018-02-09 17:26:45 -0800149import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_REGISTERED;
150import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_UNREGISTERED;
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800151import static org.onosproject.segmentrouting.pwaas.PwaasUtil.configurationValidity;
Charles Chan3e783d02016-02-26 22:19:52 -0800152
Charles Chane849c192016-01-11 18:28:54 -0800153/**
154 * Segment routing manager.
155 */
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700156@Service
157@Component(immediate = true)
sangho1e575652015-05-14 00:39:53 -0700158public class SegmentRoutingManager implements SegmentRoutingService {
sanghob35a6192015-04-01 13:05:26 -0700159
Charles Chan2c15aca2016-11-09 20:51:44 -0800160 private static Logger log = LoggerFactory.getLogger(SegmentRoutingManager.class);
Charles Chan2fde6d42017-08-23 14:46:43 -0700161 private static final String NOT_MASTER = "Current instance is not the master of {}. Ignore.";
sanghob35a6192015-04-01 13:05:26 -0700162
163 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700164 private ComponentConfigService compCfgService;
sanghob35a6192015-04-01 13:05:26 -0700165
166 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre10bd8d12016-11-26 21:05:22 -0800167 private NeighbourResolutionService neighbourResolutionService;
168
169 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi96fe0772018-02-28 12:10:50 +0100170 public CoreService coreService;
sanghob35a6192015-04-01 13:05:26 -0700171
172 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700173 PacketService packetService;
sanghob35a6192015-04-01 13:05:26 -0700174
175 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700176 HostService hostService;
sanghob35a6192015-04-01 13:05:26 -0700177
178 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan47933752017-11-30 15:37:50 -0800179 HostLocationProbingService probingService;
180
181 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi96fe0772018-02-28 12:10:50 +0100182 public DeviceService deviceService;
sanghob35a6192015-04-01 13:05:26 -0700183
184 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Saurav Das45f48152018-01-18 12:07:33 -0800185 DeviceAdminService deviceAdminService;
186
187 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre42287df2016-11-09 14:17:26 -0800188 public FlowObjectiveService flowObjectiveService;
sanghob35a6192015-04-01 13:05:26 -0700189
190 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi96fe0772018-02-28 12:10:50 +0100191 public LinkService linkService;
sangho1e575652015-05-14 00:39:53 -0700192
Charles Chan5270ed02016-01-30 23:22:37 -0800193 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre42287df2016-11-09 14:17:26 -0800194 public MastershipService mastershipService;
Charles Chan03a73e02016-10-24 14:52:01 -0700195
196 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre42287df2016-11-09 14:17:26 -0800197 public StorageService storageService;
Charles Chan03a73e02016-10-24 14:52:01 -0700198
199 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi96fe0772018-02-28 12:10:50 +0100200 public MulticastRouteService multicastRouteService;
Charles Chan03a73e02016-10-24 14:52:01 -0700201
202 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chanf237e1b2018-01-09 13:45:07 -0800203 public TopologyService topologyService;
Charles Chan03a73e02016-10-24 14:52:01 -0700204
205 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700206 RouteService routeService;
Charles Chan5270ed02016-01-30 23:22:37 -0800207
208 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan2c15aca2016-11-09 20:51:44 -0800209 public NetworkConfigRegistry cfgService;
Charles Chan5270ed02016-01-30 23:22:37 -0800210
Saurav Das80980c72016-03-23 11:22:49 -0700211 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan2c15aca2016-11-09 20:51:44 -0800212 public InterfaceService interfaceService;
213
Pier Luigieba73a02018-01-16 10:47:50 +0100214 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
215 public ClusterService clusterService;
216
217 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
218 public LeadershipService leadershipService;
219
Charles Chan47933752017-11-30 15:37:50 -0800220 @Property(name = "activeProbing", boolValue = true,
221 label = "Enable active probing to discover dual-homed hosts.")
222 boolean activeProbing = true;
223
Charles Chan03a73e02016-10-24 14:52:01 -0700224 ArpHandler arpHandler = null;
225 IcmpHandler icmpHandler = null;
226 IpHandler ipHandler = null;
227 RoutingRulePopulator routingRulePopulator = null;
Ray Milkeye4afdb52017-04-05 09:42:04 -0700228 ApplicationId appId;
229 DeviceConfiguration deviceConfiguration = null;
sanghob35a6192015-04-01 13:05:26 -0700230
Charles Chan03a73e02016-10-24 14:52:01 -0700231 DefaultRoutingHandler defaultRoutingHandler = null;
sangho1e575652015-05-14 00:39:53 -0700232 private TunnelHandler tunnelHandler = null;
233 private PolicyHandler policyHandler = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700234 private InternalPacketProcessor processor = null;
235 private InternalLinkListener linkListener = null;
236 private InternalDeviceListener deviceListener = null;
Charles Chanfc5c7802016-05-17 13:13:55 -0700237 private AppConfigHandler appCfgHandler = null;
Pier Luigi96fe0772018-02-28 12:10:50 +0100238 public XConnectHandler xConnectHandler = null;
Saurav Das45f48152018-01-18 12:07:33 -0800239 McastHandler mcastHandler = null;
240 HostHandler hostHandler = null;
Pier Ventre10bd8d12016-11-26 21:05:22 -0800241 private RouteHandler routeHandler = null;
Saurav Das45f48152018-01-18 12:07:33 -0800242 LinkHandler linkHandler = null;
Pier Ventre735b8c82016-12-02 08:16:05 -0800243 private SegmentRoutingNeighbourDispatcher neighbourHandler = null;
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800244 private DefaultL2TunnelHandler l2TunnelHandler = null;
Pier Luigi83f919b2018-02-15 16:33:08 +0100245 private TopologyHandler topologyHandler = null;
sanghob35a6192015-04-01 13:05:26 -0700246 private InternalEventHandler eventHandler = new InternalEventHandler();
Charles Chan5270ed02016-01-30 23:22:37 -0800247 private final InternalHostListener hostListener = new InternalHostListener();
Charles Chand55e84d2016-03-30 17:54:24 -0700248 private final InternalConfigListener cfgListener = new InternalConfigListener(this);
249 private final InternalMcastListener mcastListener = new InternalMcastListener();
Charles Chan03a73e02016-10-24 14:52:01 -0700250 private final InternalRouteEventListener routeListener = new InternalRouteEventListener();
Pier Luigi83f919b2018-02-15 16:33:08 +0100251 private final InternalTopologyListener topologyListener = new InternalTopologyListener();
sanghob35a6192015-04-01 13:05:26 -0700252
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700253 private ScheduledExecutorService executorService = Executors
Yuta HIGUCHI1624df12016-07-21 16:54:33 -0700254 .newScheduledThreadPool(1, groupedThreads("SegmentRoutingManager", "event-%d", log));
sanghob35a6192015-04-01 13:05:26 -0700255
Saurav Das4ce45962015-11-24 23:21:05 -0800256 @SuppressWarnings("unused")
sanghob35a6192015-04-01 13:05:26 -0700257 private static ScheduledFuture<?> eventHandlerFuture = null;
Saurav Das4ce45962015-11-24 23:21:05 -0800258 @SuppressWarnings("rawtypes")
Yuta HIGUCHI1624df12016-07-21 16:54:33 -0700259 private ConcurrentLinkedQueue<Event> eventQueue = new ConcurrentLinkedQueue<>();
Saurav Das45f48152018-01-18 12:07:33 -0800260 Map<DeviceId, DefaultGroupHandler> groupHandlerMap =
Charles Chane849c192016-01-11 18:28:54 -0800261 new ConcurrentHashMap<>();
262 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700263 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan5bc32632017-08-22 15:07:34 -0700264 * Used to keep track on MPLS group information.
Charles Chane849c192016-01-11 18:28:54 -0800265 */
Charles Chan47933752017-11-30 15:37:50 -0800266 private EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Saurav Das7bcbe702017-06-13 15:35:54 -0700267 dsNextObjStore = null;
Charles Chane849c192016-01-11 18:28:54 -0800268 /**
Charles Chan5bc32632017-08-22 15:07:34 -0700269 * Per device next objective ID store with (device id + vlanid) as key.
270 * Used to keep track on L2 flood group information.
Charles Chane849c192016-01-11 18:28:54 -0800271 */
Charles Chan47933752017-11-30 15:37:50 -0800272 private EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer>
Charles Chan59cc16d2017-02-02 16:20:42 -0800273 vlanNextObjStore = null;
Charles Chane849c192016-01-11 18:28:54 -0800274 /**
Charles Chan5bc32632017-08-22 15:07:34 -0700275 * Per device next objective ID store with (device id + port + treatment + meta) as key.
276 * Used to keep track on L2 interface group and L3 unicast group information.
Charles Chane849c192016-01-11 18:28:54 -0800277 */
Charles Chan47933752017-11-30 15:37:50 -0800278 private EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer>
Saurav Das4ce45962015-11-24 23:21:05 -0800279 portNextObjStore = null;
Charles Chan59cc16d2017-02-02 16:20:42 -0800280
Saurav Das4ce45962015-11-24 23:21:05 -0800281 private EventuallyConsistentMap<String, Tunnel> tunnelStore = null;
282 private EventuallyConsistentMap<String, Policy> policyStore = null;
sangho0b2b6d12015-05-20 22:16:38 -0700283
Saurav Das7bcbe702017-06-13 15:35:54 -0700284 private AtomicBoolean programmingScheduled = new AtomicBoolean();
285
Charles Chand55e84d2016-03-30 17:54:24 -0700286 private final ConfigFactory<DeviceId, SegmentRoutingDeviceConfig> deviceConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700287 new ConfigFactory<DeviceId, SegmentRoutingDeviceConfig>(
288 SubjectFactories.DEVICE_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700289 SegmentRoutingDeviceConfig.class, "segmentrouting") {
Charles Chand6832882015-10-05 17:50:33 -0700290 @Override
Charles Chan5270ed02016-01-30 23:22:37 -0800291 public SegmentRoutingDeviceConfig createConfig() {
292 return new SegmentRoutingDeviceConfig();
Charles Chand6832882015-10-05 17:50:33 -0700293 }
294 };
Pier Ventref34966c2016-11-07 16:21:04 -0800295
Charles Chand55e84d2016-03-30 17:54:24 -0700296 private final ConfigFactory<ApplicationId, SegmentRoutingAppConfig> appConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700297 new ConfigFactory<ApplicationId, SegmentRoutingAppConfig>(
298 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700299 SegmentRoutingAppConfig.class, "segmentrouting") {
Charles Chan5270ed02016-01-30 23:22:37 -0800300 @Override
301 public SegmentRoutingAppConfig createConfig() {
302 return new SegmentRoutingAppConfig();
303 }
304 };
Pier Ventref34966c2016-11-07 16:21:04 -0800305
Charles Chanfc5c7802016-05-17 13:13:55 -0700306 private final ConfigFactory<ApplicationId, XConnectConfig> xConnectConfigFactory =
307 new ConfigFactory<ApplicationId, XConnectConfig>(
308 SubjectFactories.APP_SUBJECT_FACTORY,
309 XConnectConfig.class, "xconnect") {
310 @Override
311 public XConnectConfig createConfig() {
312 return new XConnectConfig();
313 }
314 };
Pier Ventref34966c2016-11-07 16:21:04 -0800315
Charles Chand55e84d2016-03-30 17:54:24 -0700316 private ConfigFactory<ApplicationId, McastConfig> mcastConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700317 new ConfigFactory<ApplicationId, McastConfig>(
318 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700319 McastConfig.class, "multicast") {
320 @Override
321 public McastConfig createConfig() {
322 return new McastConfig();
323 }
324 };
325
Charles Chan65238242017-06-22 18:03:14 -0700326 private static final Object THREAD_SCHED_LOCK = new Object();
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700327 private static int numOfEventsQueued = 0;
328 private static int numOfEventsExecuted = 0;
sanghob35a6192015-04-01 13:05:26 -0700329 private static int numOfHandlerExecution = 0;
330 private static int numOfHandlerScheduled = 0;
331
Charles Chan116188d2016-02-18 14:22:42 -0800332 /**
333 * Segment Routing App ID.
334 */
Charles Chan2c15aca2016-11-09 20:51:44 -0800335 public static final String APP_NAME = "org.onosproject.segmentrouting";
Charles Chan59cc16d2017-02-02 16:20:42 -0800336
Charles Chane849c192016-01-11 18:28:54 -0800337 /**
338 * The default VLAN ID assigned to the interfaces without subnet config.
339 */
Charles Chan59cc16d2017-02-02 16:20:42 -0800340 public static final VlanId INTERNAL_VLAN = VlanId.vlanId((short) 4094);
Saurav Das0e99e2b2015-10-28 12:39:42 -0700341
sanghob35a6192015-04-01 13:05:26 -0700342 @Activate
Charles Chan47933752017-11-30 15:37:50 -0800343 protected void activate(ComponentContext context) {
Charles Chan2c15aca2016-11-09 20:51:44 -0800344 appId = coreService.registerApplication(APP_NAME);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700345
346 log.debug("Creating EC map nsnextobjectivestore");
Saurav Das7bcbe702017-06-13 15:35:54 -0700347 EventuallyConsistentMapBuilder<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700348 nsNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
Saurav Das7bcbe702017-06-13 15:35:54 -0700349 dsNextObjStore = nsNextObjMapBuilder
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700350 .withName("nsnextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700351 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700352 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700353 .build();
Saurav Das7bcbe702017-06-13 15:35:54 -0700354 log.trace("Current size {}", dsNextObjStore.size());
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700355
Charles Chan59cc16d2017-02-02 16:20:42 -0800356 log.debug("Creating EC map vlannextobjectivestore");
357 EventuallyConsistentMapBuilder<VlanNextObjectiveStoreKey, Integer>
358 vlanNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
359 vlanNextObjStore = vlanNextObjMapBuilder
360 .withName("vlannextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700361 .withSerializer(createSerializer())
Charles Chanc42e84e2015-10-20 16:24:19 -0700362 .withTimestampProvider((k, v) -> new WallClockTimestamp())
363 .build();
364
Saurav Das4ce45962015-11-24 23:21:05 -0800365 log.debug("Creating EC map subnetnextobjectivestore");
366 EventuallyConsistentMapBuilder<PortNextObjectiveStoreKey, Integer>
367 portNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
368 portNextObjStore = portNextObjMapBuilder
369 .withName("portnextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700370 .withSerializer(createSerializer())
Saurav Das4ce45962015-11-24 23:21:05 -0800371 .withTimestampProvider((k, v) -> new WallClockTimestamp())
372 .build();
373
sangho0b2b6d12015-05-20 22:16:38 -0700374 EventuallyConsistentMapBuilder<String, Tunnel> tunnelMapBuilder =
375 storageService.eventuallyConsistentMapBuilder();
sangho0b2b6d12015-05-20 22:16:38 -0700376 tunnelStore = tunnelMapBuilder
377 .withName("tunnelstore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700378 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700379 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho0b2b6d12015-05-20 22:16:38 -0700380 .build();
381
382 EventuallyConsistentMapBuilder<String, Policy> policyMapBuilder =
383 storageService.eventuallyConsistentMapBuilder();
sangho0b2b6d12015-05-20 22:16:38 -0700384 policyStore = policyMapBuilder
385 .withName("policystore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700386 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700387 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho0b2b6d12015-05-20 22:16:38 -0700388 .build();
389
Saurav Das80980c72016-03-23 11:22:49 -0700390 compCfgService.preSetProperty("org.onosproject.net.group.impl.GroupManager",
Pier Luigi9e5c5ca2017-01-12 18:14:58 -0800391 "purgeOnDisconnection", "true");
Saurav Das80980c72016-03-23 11:22:49 -0700392 compCfgService.preSetProperty("org.onosproject.net.flow.impl.FlowRuleManager",
Pier Luigi9e5c5ca2017-01-12 18:14:58 -0800393 "purgeOnDisconnection", "true");
Pier Luigi9e5c5ca2017-01-12 18:14:58 -0800394 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
395 "requestInterceptsEnabled", "false");
Charles Chand3baaba2017-08-08 15:13:37 -0700396 compCfgService.preSetProperty("org.onosproject.net.neighbour.impl.NeighbourResolutionManager",
Pier Luigi7e415132017-01-12 22:46:39 -0800397 "requestInterceptsEnabled", "false");
Charles Chanc760f382017-07-24 15:56:10 -0700398 compCfgService.preSetProperty("org.onosproject.dhcprelay.DhcpRelayManager",
Pier Luigi7e415132017-01-12 22:46:39 -0800399 "arpEnabled", "false");
Pier Luigi9b1d6262017-02-02 22:31:34 -0800400 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
401 "greedyLearningIpv6", "true");
Charles Chanc6d227e2017-02-28 15:15:17 -0800402 compCfgService.preSetProperty("org.onosproject.routing.cpr.ControlPlaneRedirectManager",
403 "forceUnprovision", "true");
Charles Chanef624ed2017-08-10 16:57:28 -0700404 compCfgService.preSetProperty("org.onosproject.routeservice.store.RouteStoreImpl",
Charles Chan73316522017-07-20 16:16:25 -0700405 "distributed", "true");
Charles Chan35a32322017-08-14 11:42:11 -0700406 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
407 "multihomingEnabled", "true");
Charles Chan807d87a2017-11-29 19:54:20 -0800408 compCfgService.preSetProperty("org.onosproject.provider.lldp.impl.LldpLinkProvider",
409 "staleLinkAge", "15000");
410 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
411 "allowDuplicateIps", "false");
Charles Chan47933752017-11-30 15:37:50 -0800412 compCfgService.registerProperties(getClass());
413 modified(context);
Saurav Das80980c72016-03-23 11:22:49 -0700414
Charles Chanb8e10c82015-10-14 11:24:40 -0700415 processor = new InternalPacketProcessor();
416 linkListener = new InternalLinkListener();
417 deviceListener = new InternalDeviceListener();
Charles Chanfc5c7802016-05-17 13:13:55 -0700418 appCfgHandler = new AppConfigHandler(this);
419 xConnectHandler = new XConnectHandler(this);
Charles Chand2990362016-04-18 13:44:03 -0700420 mcastHandler = new McastHandler(this);
421 hostHandler = new HostHandler(this);
Saurav Das45f48152018-01-18 12:07:33 -0800422 linkHandler = new LinkHandler(this);
Charles Chan03a73e02016-10-24 14:52:01 -0700423 routeHandler = new RouteHandler(this);
Pier Ventre735b8c82016-12-02 08:16:05 -0800424 neighbourHandler = new SegmentRoutingNeighbourDispatcher(this);
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800425 l2TunnelHandler = new DefaultL2TunnelHandler(this);
Pier Luigi83f919b2018-02-15 16:33:08 +0100426 topologyHandler = new TopologyHandler(this);
Charles Chanb8e10c82015-10-14 11:24:40 -0700427
Charles Chan3e783d02016-02-26 22:19:52 -0800428 cfgService.addListener(cfgListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700429 cfgService.registerConfigFactory(deviceConfigFactory);
430 cfgService.registerConfigFactory(appConfigFactory);
Charles Chanfc5c7802016-05-17 13:13:55 -0700431 cfgService.registerConfigFactory(xConnectConfigFactory);
Charles Chand55e84d2016-03-30 17:54:24 -0700432 cfgService.registerConfigFactory(mcastConfigFactory);
Saurav Dase7f51012018-02-09 17:26:45 -0800433 log.info("Configuring network before adding listeners");
Charles Chan132393a2018-01-04 14:26:07 -0800434 cfgListener.configureNetwork();
435
Charles Chan5270ed02016-01-30 23:22:37 -0800436 hostService.addListener(hostListener);
Charles Chanb8e10c82015-10-14 11:24:40 -0700437 packetService.addProcessor(processor, PacketProcessor.director(2));
438 linkService.addListener(linkListener);
439 deviceService.addListener(deviceListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700440 multicastRouteService.addListener(mcastListener);
Charles Chanc7a8a682017-06-19 00:43:31 -0700441 routeService.addListener(routeListener);
Pier Luigi83f919b2018-02-15 16:33:08 +0100442 topologyService.addListener(topologyListener);
Charles Chanb8e10c82015-10-14 11:24:40 -0700443
Charles Chanb39777c2018-03-09 15:53:44 -0800444 linkHandler.init();
Andreas Pantelopoulos4a768c02018-01-11 07:53:48 -0800445 l2TunnelHandler.init();
446
sanghob35a6192015-04-01 13:05:26 -0700447 log.info("Started");
448 }
449
Saurav Das45f48152018-01-18 12:07:33 -0800450 KryoNamespace.Builder createSerializer() {
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700451 return new KryoNamespace.Builder()
452 .register(KryoNamespaces.API)
Saurav Das7bcbe702017-06-13 15:35:54 -0700453 .register(DestinationSetNextObjectiveStoreKey.class,
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800454 VlanNextObjectiveStoreKey.class,
455 DestinationSet.class,
456 NextNeighbors.class,
457 Tunnel.class,
458 DefaultTunnel.class,
459 Policy.class,
460 TunnelPolicy.class,
461 Policy.Type.class,
462 PortNextObjectiveStoreKey.class,
463 XConnectStoreKey.class,
464 L2Tunnel.class,
465 L2TunnelPolicy.class,
466 DefaultL2Tunnel.class,
467 DefaultL2TunnelPolicy.class
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700468 );
469 }
470
sanghob35a6192015-04-01 13:05:26 -0700471 @Deactivate
472 protected void deactivate() {
Charles Chand6832882015-10-05 17:50:33 -0700473 cfgService.removeListener(cfgListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700474 cfgService.unregisterConfigFactory(deviceConfigFactory);
475 cfgService.unregisterConfigFactory(appConfigFactory);
Charles Chan03a73e02016-10-24 14:52:01 -0700476 cfgService.unregisterConfigFactory(xConnectConfigFactory);
Charles Chand55e84d2016-03-30 17:54:24 -0700477 cfgService.unregisterConfigFactory(mcastConfigFactory);
Charles Chan47933752017-11-30 15:37:50 -0800478 compCfgService.unregisterProperties(getClass(), false);
Charles Chand6832882015-10-05 17:50:33 -0700479
Charles Chanc7a8a682017-06-19 00:43:31 -0700480 hostService.removeListener(hostListener);
sanghob35a6192015-04-01 13:05:26 -0700481 packetService.removeProcessor(processor);
Charles Chanb8e10c82015-10-14 11:24:40 -0700482 linkService.removeListener(linkListener);
483 deviceService.removeListener(deviceListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700484 multicastRouteService.removeListener(mcastListener);
Charles Chan03a73e02016-10-24 14:52:01 -0700485 routeService.removeListener(routeListener);
Pier Luigi83f919b2018-02-15 16:33:08 +0100486 topologyService.removeListener(topologyListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700487
Charles Chan0aa674e2017-02-23 15:44:08 -0800488 neighbourResolutionService.unregisterNeighbourHandlers(appId);
489
sanghob35a6192015-04-01 13:05:26 -0700490 processor = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700491 linkListener = null;
Charles Chand55e84d2016-03-30 17:54:24 -0700492 deviceListener = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700493 groupHandlerMap.clear();
494
Saurav Das7bcbe702017-06-13 15:35:54 -0700495 dsNextObjStore.destroy();
Charles Chan59cc16d2017-02-02 16:20:42 -0800496 vlanNextObjStore.destroy();
Charles Chand55e84d2016-03-30 17:54:24 -0700497 portNextObjStore.destroy();
Charles Chand55e84d2016-03-30 17:54:24 -0700498 tunnelStore.destroy();
499 policyStore.destroy();
Pier Luigib72201b2018-01-25 16:16:02 +0100500
501 mcastHandler.terminate();
sanghob35a6192015-04-01 13:05:26 -0700502 log.info("Stopped");
503 }
504
Charles Chan47933752017-11-30 15:37:50 -0800505 @Modified
506 private void modified(ComponentContext context) {
507 Dictionary<?, ?> properties = context.getProperties();
508 if (properties == null) {
509 return;
510 }
511
512 String strActiveProving = Tools.get(properties, "activeProbing");
513 boolean expectActiveProbing = Boolean.parseBoolean(strActiveProving);
514
515 if (expectActiveProbing != activeProbing) {
516 activeProbing = expectActiveProbing;
517 log.info("{} active probing", activeProbing ? "Enabling" : "Disabling");
518 }
519 }
520
sangho1e575652015-05-14 00:39:53 -0700521 @Override
522 public List<Tunnel> getTunnels() {
523 return tunnelHandler.getTunnels();
524 }
525
526 @Override
sangho71abe1b2015-06-29 14:58:47 -0700527 public TunnelHandler.Result createTunnel(Tunnel tunnel) {
528 return tunnelHandler.createTunnel(tunnel);
sangho1e575652015-05-14 00:39:53 -0700529 }
530
531 @Override
sangho71abe1b2015-06-29 14:58:47 -0700532 public TunnelHandler.Result removeTunnel(Tunnel tunnel) {
sangho1e575652015-05-14 00:39:53 -0700533 for (Policy policy: policyHandler.getPolicies()) {
534 if (policy.type() == Policy.Type.TUNNEL_FLOW) {
535 TunnelPolicy tunnelPolicy = (TunnelPolicy) policy;
536 if (tunnelPolicy.tunnelId().equals(tunnel.id())) {
537 log.warn("Cannot remove the tunnel used by a policy");
sangho71abe1b2015-06-29 14:58:47 -0700538 return TunnelHandler.Result.TUNNEL_IN_USE;
sangho1e575652015-05-14 00:39:53 -0700539 }
540 }
541 }
sangho71abe1b2015-06-29 14:58:47 -0700542 return tunnelHandler.removeTunnel(tunnel);
sangho1e575652015-05-14 00:39:53 -0700543 }
544
545 @Override
sangho71abe1b2015-06-29 14:58:47 -0700546 public PolicyHandler.Result removePolicy(Policy policy) {
547 return policyHandler.removePolicy(policy);
sangho1e575652015-05-14 00:39:53 -0700548 }
549
550 @Override
sangho71abe1b2015-06-29 14:58:47 -0700551 public PolicyHandler.Result createPolicy(Policy policy) {
552 return policyHandler.createPolicy(policy);
sangho1e575652015-05-14 00:39:53 -0700553 }
554
555 @Override
556 public List<Policy> getPolicies() {
557 return policyHandler.getPolicies();
558 }
559
Saurav Das59232cf2016-04-27 18:35:50 -0700560 @Override
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700561 public Set<L2TunnelDescription> getL2TunnelDescriptions(boolean pending) {
562 return l2TunnelHandler.getL2Descriptions(pending);
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700563 }
564
565 @Override
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800566 public List<L2Tunnel> getL2Tunnels() {
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700567 return l2TunnelHandler.getL2Tunnels();
568 }
569
570 @Override
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800571 public List<L2TunnelPolicy> getL2Policies() {
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700572 return l2TunnelHandler.getL2Policies();
573 }
574
575 @Override
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700576 public L2TunnelHandler.Result addPseudowiresBulk(List<DefaultL2TunnelDescription> bulkPseudowires) {
577
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700578 // get both added and pending pseudowires
579 List<L2TunnelDescription> pseudowires = new ArrayList<>();
580 pseudowires.addAll(l2TunnelHandler.getL2Descriptions(false));
581 pseudowires.addAll(l2TunnelHandler.getL2Descriptions(true));
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700582 pseudowires.addAll(bulkPseudowires);
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700583
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700584 Set<L2TunnelDescription> newPseudowires = new HashSet(bulkPseudowires);
585
586 // check global validity for all the new pseudowires, if it fails
587 // do not add any of them
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700588 log.debug("Verifying set of pseudowires {}", pseudowires);
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700589 boolean res = configurationValidity(pseudowires);
590 if (res) {
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700591 log.debug("Pseudowire configuration is valid, deploying pseudowires!");
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700592 l2TunnelHandler.deploy(newPseudowires);
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700593
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700594 return L2TunnelHandler.Result.SUCCESS;
595 } else {
596 log.error("Bulk pseudowires {} can not be added, error in global configuration!",
597 newPseudowires);
598 return L2TunnelHandler.Result.ADDITION_ERROR;
599 }
600 }
601
602 @Override
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800603 public L2TunnelHandler.Result addPseudowire(L2TunnelDescription l2TunnelDescription) {
604
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700605 // get both added and pending pseudowires
606 List<L2TunnelDescription> newPseudowires = new ArrayList<>();
607 newPseudowires.addAll(l2TunnelHandler.getL2Descriptions(false));
608 newPseudowires.addAll(l2TunnelHandler.getL2Descriptions(true));
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800609
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700610 // add the new pseudowire to the List
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800611 newPseudowires.add(l2TunnelDescription);
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700612 // validate the new list of pseudowires
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800613 boolean res = configurationValidity(newPseudowires);
614 if (res) {
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800615 // deploy a set with ONLY the new pseudowire
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700616 Set<L2TunnelDescription> pwToDeploy = new HashSet<>();
617 pwToDeploy.add(l2TunnelDescription);
618 l2TunnelHandler.deploy(pwToDeploy);
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800619
620 log.info("Pseudowire with {} deployment started, check log for any errors in this process!",
621 l2TunnelDescription.l2Tunnel().tunnelId());
622 return L2TunnelHandler.Result.SUCCESS;
623 } else {
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800624 log.error("Pseudowire with {} can not be added!", l2TunnelDescription.l2Tunnel().tunnelId());
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700625 return L2TunnelHandler.Result.ADDITION_ERROR;
626 }
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700627 }
628
629 @Override
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800630 public L2TunnelHandler.Result removePseudowire(Integer pwId) {
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700631
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700632 // get both added and pending pseudowires
633 Set<L2TunnelDescription> pseudowires = l2TunnelHandler.getL2Descriptions(false)
634 .stream()
635 .filter(pw -> pw.l2Tunnel().tunnelId() == pwId)
636 .collect(Collectors.toSet());
637 Set<L2TunnelDescription> pendingPseudowires = l2TunnelHandler.getL2Descriptions(true)
638 .stream()
639 .filter(pw -> pw.l2Tunnel().tunnelId() == pwId)
640 .collect(Collectors.toSet());
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700641
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700642 if ((pendingPseudowires.size() == 0) && (pseudowires.size() == 0)) {
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800643 log.error("Pseudowire with id {} does not exist", pwId);
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700644 return L2TunnelHandler.Result.REMOVAL_ERROR;
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700645 }
646 if (pendingPseudowires.size() != 0) {
647 log.info("Remove pseudowire from pending store!");
648 // will fill when we implement failure mechanism detection.
649 }
650 if (pseudowires.size() != 0) {
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800651 l2TunnelHandler.tearDown(new HashSet<>(pseudowires));
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800652 log.info("Removal of pseudowire with {} started, check log for any errors in this process!",
653 pwId);
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700654 }
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700655
656 return L2TunnelHandler.Result.SUCCESS;
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700657 }
658
659 @Override
Saurav Das59232cf2016-04-27 18:35:50 -0700660 public void rerouteNetwork() {
661 cfgListener.configureNetwork();
Saurav Das59232cf2016-04-27 18:35:50 -0700662 }
663
Charles Chanc81c45b2016-10-20 17:02:44 -0700664 @Override
Pier Ventre10bd8d12016-11-26 21:05:22 -0800665 public Map<DeviceId, Set<IpPrefix>> getDeviceSubnetMap() {
666 Map<DeviceId, Set<IpPrefix>> deviceSubnetMap = Maps.newHashMap();
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800667 deviceConfiguration.getRouters().forEach(device ->
668 deviceSubnetMap.put(device, deviceConfiguration.getSubnets(device)));
Charles Chanc81c45b2016-10-20 17:02:44 -0700669 return deviceSubnetMap;
670 }
671
Saurav Dasc88d4662017-05-15 15:34:25 -0700672
673 @Override
674 public ImmutableMap<DeviceId, EcmpShortestPathGraph> getCurrentEcmpSpg() {
675 if (defaultRoutingHandler != null) {
676 return defaultRoutingHandler.getCurrentEmcpSpgMap();
677 } else {
678 return null;
679 }
680 }
681
682 @Override
Saurav Das7bcbe702017-06-13 15:35:54 -0700683 public ImmutableMap<DestinationSetNextObjectiveStoreKey, NextNeighbors> getDestinationSet() {
684 if (dsNextObjStore != null) {
685 return ImmutableMap.copyOf(dsNextObjStore.entrySet());
Saurav Dasc88d4662017-05-15 15:34:25 -0700686 } else {
687 return ImmutableMap.of();
688 }
689 }
690
Saurav Dasceccf242017-08-03 18:30:35 -0700691 @Override
692 public void verifyGroups(DeviceId id) {
693 DefaultGroupHandler gh = groupHandlerMap.get(id);
694 if (gh != null) {
695 gh.triggerBucketCorrector();
696 }
697 }
698
Saurav Dasc568c342018-01-25 09:49:01 -0800699 @Override
700 public ImmutableMap<Link, Boolean> getSeenLinks() {
701 return linkHandler.getSeenLinks();
702 }
703
704 @Override
705 public ImmutableMap<DeviceId, Set<PortNumber>> getDownedPortState() {
706 return linkHandler.getDownedPorts();
707 }
708
Pier Luigib29144d2018-01-15 18:06:43 +0100709 @Override
710 public Map<McastStoreKey, Integer> getMcastNextIds(IpAddress mcastIp) {
711 return mcastHandler.getMcastNextIds(mcastIp);
712 }
713
714 @Override
Pier Luigi96fe0772018-02-28 12:10:50 +0100715 public Map<McastStoreKey, McastRole> getMcastRoles(IpAddress mcastIp) {
Pier Luigib29144d2018-01-15 18:06:43 +0100716 return mcastHandler.getMcastRoles(mcastIp);
717 }
718
719 @Override
720 public Map<ConnectPoint, List<ConnectPoint>> getMcastPaths(IpAddress mcastIp) {
721 return mcastHandler.getMcastPaths(mcastIp);
722 }
723
sanghof9d0bf12015-05-19 11:57:42 -0700724 /**
Ray Milkeye4afdb52017-04-05 09:42:04 -0700725 * Extracts the application ID from the manager.
726 *
727 * @return application ID
728 */
729 public ApplicationId appId() {
730 return appId;
731 }
732
733 /**
734 * Returns the device configuration.
735 *
736 * @return device configuration
737 */
738 public DeviceConfiguration deviceConfiguration() {
739 return deviceConfiguration;
740 }
741
742 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700743 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan5bc32632017-08-22 15:07:34 -0700744 * Used to keep track on MPLS group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -0700745 *
746 * @return next objective ID store
747 */
Saurav Das7bcbe702017-06-13 15:35:54 -0700748 public EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
749 dsNextObjStore() {
750 return dsNextObjStore;
Ray Milkeye4afdb52017-04-05 09:42:04 -0700751 }
752
753 /**
Charles Chan5bc32632017-08-22 15:07:34 -0700754 * Per device next objective ID store with (device id + vlanid) as key.
755 * Used to keep track on L2 flood group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -0700756 *
757 * @return vlan next object store
758 */
759 public EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer> vlanNextObjStore() {
760 return vlanNextObjStore;
761 }
762
763 /**
Charles Chan5bc32632017-08-22 15:07:34 -0700764 * Per device next objective ID store with (device id + port + treatment + meta) as key.
765 * Used to keep track on L2 interface group and L3 unicast group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -0700766 *
767 * @return port next object store.
768 */
769 public EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer> portNextObjStore() {
770 return portNextObjStore;
771 }
772
773 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700774 * Returns the MPLS-ECMP configuration which indicates whether ECMP on
775 * labeled packets should be programmed or not.
Pier Ventre98161782016-10-31 15:00:01 -0700776 *
777 * @return MPLS-ECMP value
778 */
779 public boolean getMplsEcmp() {
780 SegmentRoutingAppConfig segmentRoutingAppConfig = cfgService
781 .getConfig(this.appId, SegmentRoutingAppConfig.class);
782 return segmentRoutingAppConfig != null && segmentRoutingAppConfig.mplsEcmp();
783 }
784
785 /**
sanghof9d0bf12015-05-19 11:57:42 -0700786 * Returns the tunnel object with the tunnel ID.
787 *
788 * @param tunnelId Tunnel ID
789 * @return Tunnel reference
790 */
sangho1e575652015-05-14 00:39:53 -0700791 public Tunnel getTunnel(String tunnelId) {
792 return tunnelHandler.getTunnel(tunnelId);
793 }
794
Charles Chan7ffd81f2017-02-08 15:52:08 -0800795 // TODO Consider moving these to InterfaceService
sanghob35a6192015-04-01 13:05:26 -0700796 /**
Charles Chan59cc16d2017-02-02 16:20:42 -0800797 * Returns untagged VLAN configured on given connect point.
Charles Chan7ffd81f2017-02-08 15:52:08 -0800798 * <p>
799 * Only returns the first match if there are multiple untagged VLAN configured
800 * on the connect point.
sanghob35a6192015-04-01 13:05:26 -0700801 *
Charles Chan59cc16d2017-02-02 16:20:42 -0800802 * @param connectPoint connect point
803 * @return untagged VLAN or null if not configured
sanghob35a6192015-04-01 13:05:26 -0700804 */
Charles Chan65238242017-06-22 18:03:14 -0700805 VlanId getUntaggedVlanId(ConnectPoint connectPoint) {
Charles Chan59cc16d2017-02-02 16:20:42 -0800806 return interfaceService.getInterfacesByPort(connectPoint).stream()
807 .filter(intf -> !intf.vlanUntagged().equals(VlanId.NONE))
808 .map(Interface::vlanUntagged)
809 .findFirst().orElse(null);
sanghob35a6192015-04-01 13:05:26 -0700810 }
811
sangho1e575652015-05-14 00:39:53 -0700812 /**
Charles Chan7ffd81f2017-02-08 15:52:08 -0800813 * Returns tagged VLAN configured on given connect point.
814 * <p>
815 * Returns all matches if there are multiple tagged VLAN configured
816 * on the connect point.
817 *
818 * @param connectPoint connect point
819 * @return tagged VLAN or empty set if not configured
820 */
Charles Chan65238242017-06-22 18:03:14 -0700821 Set<VlanId> getTaggedVlanId(ConnectPoint connectPoint) {
Charles Chan7ffd81f2017-02-08 15:52:08 -0800822 Set<Interface> interfaces = interfaceService.getInterfacesByPort(connectPoint);
823 return interfaces.stream()
824 .map(Interface::vlanTagged)
Charles Chan65238242017-06-22 18:03:14 -0700825 .flatMap(Set::stream)
Charles Chan7ffd81f2017-02-08 15:52:08 -0800826 .collect(Collectors.toSet());
827 }
828
829 /**
830 * Returns native VLAN configured on given connect point.
831 * <p>
832 * Only returns the first match if there are multiple native VLAN configured
833 * on the connect point.
834 *
835 * @param connectPoint connect point
836 * @return native VLAN or null if not configured
837 */
Charles Chan65238242017-06-22 18:03:14 -0700838 VlanId getNativeVlanId(ConnectPoint connectPoint) {
Charles Chan7ffd81f2017-02-08 15:52:08 -0800839 Set<Interface> interfaces = interfaceService.getInterfacesByPort(connectPoint);
840 return interfaces.stream()
841 .filter(intf -> !intf.vlanNative().equals(VlanId.NONE))
842 .map(Interface::vlanNative)
843 .findFirst()
844 .orElse(null);
845 }
846
847 /**
Charles Chanf9a52702017-06-16 15:19:24 -0700848 * Returns internal VLAN for untagged hosts on given connect point.
849 * <p>
850 * The internal VLAN is either vlan-untagged for an access port,
851 * or vlan-native for a trunk port.
852 *
853 * @param connectPoint connect point
854 * @return internal VLAN or null if both vlan-untagged and vlan-native are undefined
855 */
Pier Luigi96fe0772018-02-28 12:10:50 +0100856 public VlanId getInternalVlanId(ConnectPoint connectPoint) {
Charles Chanf9a52702017-06-16 15:19:24 -0700857 VlanId untaggedVlanId = getUntaggedVlanId(connectPoint);
858 VlanId nativeVlanId = getNativeVlanId(connectPoint);
859 return untaggedVlanId != null ? untaggedVlanId : nativeVlanId;
860 }
861
862 /**
Charles Chan65238242017-06-22 18:03:14 -0700863 * Returns optional pair device ID of given device.
864 *
865 * @param deviceId device ID
866 * @return optional pair device ID. Might be empty if pair device is not configured
867 */
868 Optional<DeviceId> getPairDeviceId(DeviceId deviceId) {
869 SegmentRoutingDeviceConfig deviceConfig =
870 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
871 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairDeviceId);
872 }
873 /**
874 * Returns optional pair device local port of given device.
875 *
876 * @param deviceId device ID
877 * @return optional pair device ID. Might be empty if pair device is not configured
878 */
879 Optional<PortNumber> getPairLocalPorts(DeviceId deviceId) {
880 SegmentRoutingDeviceConfig deviceConfig =
881 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
882 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairLocalPort);
883 }
884
885 /**
Charles Chan2fde6d42017-08-23 14:46:43 -0700886 * Determine if current instance is the master of given connect point.
887 *
888 * @param cp connect point
889 * @return true if current instance is the master of given connect point
890 */
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700891 public boolean isMasterOf(ConnectPoint cp) {
Charles Chan2fde6d42017-08-23 14:46:43 -0700892 boolean isMaster = mastershipService.isLocalMaster(cp.deviceId());
893 if (!isMaster) {
894 log.debug(NOT_MASTER, cp);
895 }
896 return isMaster;
897 }
898
899 /**
Charles Chan9640c812017-08-23 13:55:39 -0700900 * Returns locations of given resolved route.
901 *
902 * @param resolvedRoute resolved route
903 * @return locations of nexthop. Might be empty if next hop is not found
904 */
905 Set<ConnectPoint> nextHopLocations(ResolvedRoute resolvedRoute) {
906 HostId hostId = HostId.hostId(resolvedRoute.nextHopMac(), resolvedRoute.nextHopVlan());
907 return Optional.ofNullable(hostService.getHost(hostId))
908 .map(Host::locations).orElse(Sets.newHashSet())
909 .stream().map(l -> (ConnectPoint) l).collect(Collectors.toSet());
910 }
911
912 /**
Charles Chan7ffd81f2017-02-08 15:52:08 -0800913 * Returns vlan port map of given device.
914 *
915 * @param deviceId device id
916 * @return vlan-port multimap
917 */
918 public Multimap<VlanId, PortNumber> getVlanPortMap(DeviceId deviceId) {
919 HashMultimap<VlanId, PortNumber> vlanPortMap = HashMultimap.create();
920
921 interfaceService.getInterfaces().stream()
922 .filter(intf -> intf.connectPoint().deviceId().equals(deviceId))
923 .forEach(intf -> {
924 vlanPortMap.put(intf.vlanUntagged(), intf.connectPoint().port());
Charles Chan65238242017-06-22 18:03:14 -0700925 intf.vlanTagged().forEach(vlanTagged ->
926 vlanPortMap.put(vlanTagged, intf.connectPoint().port())
927 );
Charles Chan7ffd81f2017-02-08 15:52:08 -0800928 vlanPortMap.put(intf.vlanNative(), intf.connectPoint().port());
929 });
930 vlanPortMap.removeAll(VlanId.NONE);
931
932 return vlanPortMap;
933 }
934
935 /**
Charles Chan59cc16d2017-02-02 16:20:42 -0800936 * Returns the next objective ID for the given vlan id. It is expected
Saurav Das4ce45962015-11-24 23:21:05 -0800937 * that the next-objective has been pre-created from configuration.
Charles Chanc42e84e2015-10-20 16:24:19 -0700938 *
939 * @param deviceId Device ID
Charles Chan59cc16d2017-02-02 16:20:42 -0800940 * @param vlanId VLAN ID
Saurav Das4ce45962015-11-24 23:21:05 -0800941 * @return next objective ID or -1 if it was not found
Charles Chanc42e84e2015-10-20 16:24:19 -0700942 */
Charles Chan65238242017-06-22 18:03:14 -0700943 int getVlanNextObjectiveId(DeviceId deviceId, VlanId vlanId) {
Charles Chanc42e84e2015-10-20 16:24:19 -0700944 if (groupHandlerMap.get(deviceId) != null) {
Charles Chan59cc16d2017-02-02 16:20:42 -0800945 log.trace("getVlanNextObjectiveId query in device {}", deviceId);
946 return groupHandlerMap.get(deviceId).getVlanNextObjectiveId(vlanId);
Charles Chanc42e84e2015-10-20 16:24:19 -0700947 } else {
Charles Chan59cc16d2017-02-02 16:20:42 -0800948 log.warn("getVlanNextObjectiveId query - groupHandler for "
Saurav Das4ce45962015-11-24 23:21:05 -0800949 + "device {} not found", deviceId);
950 return -1;
951 }
952 }
953
954 /**
955 * Returns the next objective ID for the given portNumber, given the treatment.
956 * There could be multiple different treatments to the same outport, which
Saurav Das961beb22017-03-29 19:09:17 -0700957 * would result in different objectives. If the next object does not exist,
958 * and should be created, a new one is created and its id is returned.
Saurav Das4ce45962015-11-24 23:21:05 -0800959 *
960 * @param deviceId Device ID
961 * @param portNum port number on device for which NextObjective is queried
962 * @param treatment the actions to apply on the packets (should include outport)
963 * @param meta metadata passed into the creation of a Next Objective if necessary
Saurav Das961beb22017-03-29 19:09:17 -0700964 * @param createIfMissing true if a next object should be created if not found
Saurav Das59232cf2016-04-27 18:35:50 -0700965 * @return next objective ID or -1 if an error occurred during retrieval or creation
Saurav Das4ce45962015-11-24 23:21:05 -0800966 */
967 public int getPortNextObjectiveId(DeviceId deviceId, PortNumber portNum,
968 TrafficTreatment treatment,
Saurav Das961beb22017-03-29 19:09:17 -0700969 TrafficSelector meta,
970 boolean createIfMissing) {
Saurav Das4ce45962015-11-24 23:21:05 -0800971 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
972 if (ghdlr != null) {
Saurav Das961beb22017-03-29 19:09:17 -0700973 return ghdlr.getPortNextObjectiveId(portNum, treatment, meta, createIfMissing);
Saurav Das4ce45962015-11-24 23:21:05 -0800974 } else {
Charles Chane849c192016-01-11 18:28:54 -0800975 log.warn("getPortNextObjectiveId query - groupHandler for device {}"
976 + " not found", deviceId);
977 return -1;
978 }
979 }
980
Saurav Dasc88d4662017-05-15 15:34:25 -0700981 /**
982 * Returns the group handler object for the specified device id.
983 *
984 * @param devId the device identifier
985 * @return the groupHandler object for the device id, or null if not found
986 */
Charles Chan65238242017-06-22 18:03:14 -0700987 DefaultGroupHandler getGroupHandler(DeviceId devId) {
Saurav Dasc88d4662017-05-15 15:34:25 -0700988 return groupHandlerMap.get(devId);
989 }
990
991 /**
Saurav Dasceccf242017-08-03 18:30:35 -0700992 * Returns the default routing handler object.
993 *
994 * @return the default routing handler object
995 */
996 public DefaultRoutingHandler getRoutingHandler() {
997 return defaultRoutingHandler;
998 }
999
sanghob35a6192015-04-01 13:05:26 -07001000 private class InternalPacketProcessor implements PacketProcessor {
sanghob35a6192015-04-01 13:05:26 -07001001 @Override
1002 public void process(PacketContext context) {
1003
1004 if (context.isHandled()) {
1005 return;
1006 }
1007
1008 InboundPacket pkt = context.inPacket();
1009 Ethernet ethernet = pkt.parsed();
Pier Luigi7dad71c2017-02-01 13:50:04 -08001010
1011 if (ethernet == null) {
1012 return;
1013 }
1014
Saurav Das7bcbe702017-06-13 15:35:54 -07001015 log.trace("Rcvd pktin from {}: {}", context.inPacket().receivedFrom(),
1016 ethernet);
Pier Ventree0ae7a32016-11-23 09:57:42 -08001017 if (ethernet.getEtherType() == TYPE_ARP) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001018 log.warn("Received unexpected ARP packet on {}",
1019 context.inPacket().receivedFrom());
Saurav Das76ae6812017-03-15 15:15:14 -07001020 log.trace("{}", ethernet);
Pier Ventre968da122016-12-09 17:26:04 -08001021 return;
sanghob35a6192015-04-01 13:05:26 -07001022 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV4) {
Pier Ventre735b8c82016-12-02 08:16:05 -08001023 IPv4 ipv4Packet = (IPv4) ethernet.getPayload();
1024 //ipHandler.addToPacketBuffer(ipv4Packet);
1025 if (ipv4Packet.getProtocol() == IPv4.PROTOCOL_ICMP) {
1026 icmpHandler.processIcmp(ethernet, pkt.receivedFrom());
sanghob35a6192015-04-01 13:05:26 -07001027 } else {
Charles Chan50035632017-01-13 17:20:44 -08001028 // NOTE: We don't support IP learning at this moment so this
1029 // is not necessary. Also it causes duplication of DHCP packets.
Pier Ventre968da122016-12-09 17:26:04 -08001030 // ipHandler.processPacketIn(ipv4Packet, pkt.receivedFrom());
sanghob35a6192015-04-01 13:05:26 -07001031 }
Pier Ventre10bd8d12016-11-26 21:05:22 -08001032 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV6) {
1033 IPv6 ipv6Packet = (IPv6) ethernet.getPayload();
Pier Ventre735b8c82016-12-02 08:16:05 -08001034 //ipHandler.addToPacketBuffer(ipv6Packet);
Pier Luigi7dad71c2017-02-01 13:50:04 -08001035 // We deal with the packet only if the packet is a ICMP6 ECHO/REPLY
Pier Ventre735b8c82016-12-02 08:16:05 -08001036 if (ipv6Packet.getNextHeader() == IPv6.PROTOCOL_ICMP6) {
1037 ICMP6 icmp6Packet = (ICMP6) ipv6Packet.getPayload();
1038 if (icmp6Packet.getIcmpType() == ICMP6.ECHO_REQUEST ||
1039 icmp6Packet.getIcmpType() == ICMP6.ECHO_REPLY) {
1040 icmpHandler.processIcmpv6(ethernet, pkt.receivedFrom());
1041 } else {
Saurav Dasc88d4662017-05-15 15:34:25 -07001042 log.trace("Received ICMPv6 0x{} - not handled",
Charles Chan0ed44fb2017-03-13 13:10:30 -07001043 Integer.toHexString(icmp6Packet.getIcmpType() & 0xff));
Pier Ventre735b8c82016-12-02 08:16:05 -08001044 }
1045 } else {
1046 // NOTE: We don't support IP learning at this moment so this
1047 // is not necessary. Also it causes duplication of DHCPv6 packets.
1048 // ipHandler.processPacketIn(ipv6Packet, pkt.receivedFrom());
1049 }
sanghob35a6192015-04-01 13:05:26 -07001050 }
1051 }
1052 }
1053
1054 private class InternalLinkListener implements LinkListener {
1055 @Override
1056 public void event(LinkEvent event) {
Charles Chanb1f8c762017-03-29 16:39:05 -07001057 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1058 event.type() == LinkEvent.Type.LINK_UPDATED ||
1059 event.type() == LinkEvent.Type.LINK_REMOVED) {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001060 log.debug("Event {} received from Link Service", event.type());
sanghob35a6192015-04-01 13:05:26 -07001061 scheduleEventHandlerIfNotScheduled(event);
1062 }
1063 }
1064 }
1065
1066 private class InternalDeviceListener implements DeviceListener {
sanghob35a6192015-04-01 13:05:26 -07001067 @Override
1068 public void event(DeviceEvent event) {
sanghob35a6192015-04-01 13:05:26 -07001069 switch (event.type()) {
1070 case DEVICE_ADDED:
Saurav Das1a129a02016-11-18 15:21:57 -08001071 case PORT_UPDATED:
1072 case PORT_ADDED:
sangho20eff1d2015-04-13 15:15:58 -07001073 case DEVICE_UPDATED:
1074 case DEVICE_AVAILABILITY_CHANGED:
Saurav Dasc88d4662017-05-15 15:34:25 -07001075 log.trace("Event {} received from Device Service", event.type());
sanghob35a6192015-04-01 13:05:26 -07001076 scheduleEventHandlerIfNotScheduled(event);
1077 break;
1078 default:
1079 }
1080 }
1081 }
1082
Pier Luigi83f919b2018-02-15 16:33:08 +01001083 /**
1084 * Internal listener for topology events.
1085 */
1086 private class InternalTopologyListener implements TopologyListener {
1087 @Override
1088 public void event(TopologyEvent event) {
1089 switch (event.type()) {
1090 case TOPOLOGY_CHANGED:
1091 log.debug("Event {} received from TopologyService", event.type());
1092 scheduleEventHandlerIfNotScheduled(event);
1093 break;
1094 default:
1095 }
1096 }
1097 }
1098
Saurav Das4ce45962015-11-24 23:21:05 -08001099 @SuppressWarnings("rawtypes")
sanghob35a6192015-04-01 13:05:26 -07001100 private void scheduleEventHandlerIfNotScheduled(Event event) {
Charles Chan65238242017-06-22 18:03:14 -07001101 synchronized (THREAD_SCHED_LOCK) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001102 eventQueue.add(event);
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001103 numOfEventsQueued++;
1104
1105 if ((numOfHandlerScheduled - numOfHandlerExecution) == 0) {
1106 //No pending scheduled event handling threads. So start a new one.
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001107 eventHandlerFuture = executorService
1108 .schedule(eventHandler, 100, TimeUnit.MILLISECONDS);
1109 numOfHandlerScheduled++;
1110 }
Jonathan Hartc19f7c12016-04-12 15:39:44 -07001111 log.trace("numOfEventsQueued {}, numOfEventHandlerScheduled {}",
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001112 numOfEventsQueued,
1113 numOfHandlerScheduled);
sanghob35a6192015-04-01 13:05:26 -07001114 }
sanghob35a6192015-04-01 13:05:26 -07001115 }
1116
1117 private class InternalEventHandler implements Runnable {
Srikanth Vavilapalli4db76e32015-04-07 15:12:32 -07001118 @Override
sanghob35a6192015-04-01 13:05:26 -07001119 public void run() {
Pier Luigieefa2762018-02-12 09:56:20 +01001120 while (true) {
1121 try {
Saurav Das4ce45962015-11-24 23:21:05 -08001122 @SuppressWarnings("rawtypes")
Charles Chan65238242017-06-22 18:03:14 -07001123 Event event;
1124 synchronized (THREAD_SCHED_LOCK) {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001125 if (!eventQueue.isEmpty()) {
1126 event = eventQueue.poll();
1127 numOfEventsExecuted++;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001128 } else {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001129 numOfHandlerExecution++;
1130 log.debug("numOfHandlerExecution {} numOfEventsExecuted {}",
1131 numOfHandlerExecution, numOfEventsExecuted);
1132 break;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001133 }
sangho20eff1d2015-04-13 15:15:58 -07001134 }
Pier Luigi83f919b2018-02-15 16:33:08 +01001135 // TODO We should also change SR routing and PW to listen to TopologyEvents
Charles Chanb1f8c762017-03-29 16:39:05 -07001136 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1137 event.type() == LinkEvent.Type.LINK_UPDATED) {
Saurav Das45f48152018-01-18 12:07:33 -08001138 linkHandler.processLinkAdded((Link) event.subject());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001139 } else if (event.type() == LinkEvent.Type.LINK_REMOVED) {
Saurav Das45f48152018-01-18 12:07:33 -08001140 linkHandler.processLinkRemoved((Link) event.subject());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001141 } else if (event.type() == DeviceEvent.Type.DEVICE_ADDED ||
1142 event.type() == DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED ||
1143 event.type() == DeviceEvent.Type.DEVICE_UPDATED) {
Saurav Das423fe2b2015-12-04 10:52:59 -08001144 DeviceId deviceId = ((Device) event.subject()).id();
1145 if (deviceService.isAvailable(deviceId)) {
Saurav Dase0d4c872018-03-05 14:37:16 -08001146 log.info("** DEVICE UP Processing device event {} "
1147 + "for available device {}",
Saurav Das837e0bb2015-10-30 17:45:38 -07001148 event.type(), ((Device) event.subject()).id());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001149 processDeviceAdded((Device) event.subject());
Saurav Das80980c72016-03-23 11:22:49 -07001150 } else {
Saurav Dase0d4c872018-03-05 14:37:16 -08001151 log.info(" ** DEVICE DOWN Processing device event {}"
1152 + " for unavailable device {}",
Pier Luigieefa2762018-02-12 09:56:20 +01001153 event.type(), ((Device) event.subject()).id());
Saurav Das80980c72016-03-23 11:22:49 -07001154 processDeviceRemoved((Device) event.subject());
1155 }
Saurav Das1a129a02016-11-18 15:21:57 -08001156 } else if (event.type() == DeviceEvent.Type.PORT_ADDED) {
Saurav Dasd2fded02016-12-02 15:43:47 -08001157 // typically these calls come when device is added first time
1158 // so port filtering rules are handled at the device_added event.
1159 // port added calls represent all ports on the device,
1160 // enabled or not.
Saurav Dasc88d4662017-05-15 15:34:25 -07001161 log.trace("** PORT ADDED {}/{} -> {}",
Saurav Dasd2fded02016-12-02 15:43:47 -08001162 ((DeviceEvent) event).subject().id(),
1163 ((DeviceEvent) event).port().number(),
1164 event.type());
Saurav Das1a129a02016-11-18 15:21:57 -08001165 } else if (event.type() == DeviceEvent.Type.PORT_UPDATED) {
Saurav Dasd2fded02016-12-02 15:43:47 -08001166 // these calls happen for every subsequent event
1167 // ports enabled, disabled, switch goes away, comes back
Saurav Das1a129a02016-11-18 15:21:57 -08001168 log.info("** PORT UPDATED {}/{} -> {}",
1169 event.subject(),
1170 ((DeviceEvent) event).port(),
1171 event.type());
1172 processPortUpdated(((Device) event.subject()),
1173 ((DeviceEvent) event).port());
Pier Luigi83f919b2018-02-15 16:33:08 +01001174 } else if (event.type() == TopologyEvent.Type.TOPOLOGY_CHANGED) {
1175 // Process topology event, needed for all modules relying on
1176 // topology service for path computation
1177 TopologyEvent topologyEvent = (TopologyEvent) event;
1178 log.info("Processing topology event {}, topology age {}, reasons {}",
1179 event.type(), topologyEvent.subject().time(),
1180 topologyEvent.reasons().size());
1181 topologyHandler.processTopologyChange(topologyEvent.reasons());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001182 } else {
1183 log.warn("Unhandled event type: {}", event.type());
1184 }
Pier Luigieefa2762018-02-12 09:56:20 +01001185 } catch (Exception e) {
1186 log.error("SegmentRouting event handler thread thrown an exception: {}",
1187 e.getMessage(), e);
sanghob35a6192015-04-01 13:05:26 -07001188 }
1189 }
sanghob35a6192015-04-01 13:05:26 -07001190 }
1191 }
1192
Saurav Das45f48152018-01-18 12:07:33 -08001193 void processDeviceAdded(Device device) {
Saurav Dasb5c236e2016-06-07 10:08:06 -07001194 log.info("** DEVICE ADDED with ID {}", device.id());
Charles Chan91ccbf72017-06-27 18:48:32 -07001195
1196 // NOTE: Punt ARP/NDP even when the device is not configured.
1197 // Host learning without network config is required for CORD config generator.
1198 routingRulePopulator.populateIpPunts(device.id());
1199 routingRulePopulator.populateArpNdpPunts(device.id());
1200
Charles Chan0b4e6182015-11-03 10:42:14 -08001201 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001202 log.warn("Device configuration unavailable. Device {} will be "
1203 + "processed after configuration.", device.id());
Saurav Das2857f382015-11-03 14:39:27 -08001204 return;
1205 }
Charles Chan2199c302016-04-23 17:36:10 -07001206 processDeviceAddedInternal(device.id());
1207 }
1208
1209 private void processDeviceAddedInternal(DeviceId deviceId) {
Saurav Das837e0bb2015-10-30 17:45:38 -07001210 // Irrespective of whether the local is a MASTER or not for this device,
1211 // we need to create a SR-group-handler instance. This is because in a
1212 // multi-instance setup, any instance can initiate forwarding/next-objectives
1213 // for any switch (even if this instance is a SLAVE or not even connected
1214 // to the switch). To handle this, a default-group-handler instance is necessary
1215 // per switch.
Charles Chan2199c302016-04-23 17:36:10 -07001216 log.debug("Current groupHandlerMap devs: {}", groupHandlerMap.keySet());
1217 if (groupHandlerMap.get(deviceId) == null) {
Charles Chan0b4e6182015-11-03 10:42:14 -08001218 DefaultGroupHandler groupHandler;
1219 try {
1220 groupHandler = DefaultGroupHandler.
Charles Chan2199c302016-04-23 17:36:10 -07001221 createGroupHandler(deviceId,
1222 appId,
1223 deviceConfiguration,
1224 linkService,
1225 flowObjectiveService,
1226 this);
Charles Chan0b4e6182015-11-03 10:42:14 -08001227 } catch (DeviceConfigNotFoundException e) {
1228 log.warn(e.getMessage() + " Aborting processDeviceAdded.");
1229 return;
1230 }
Saurav Dasf14d9ef2017-12-05 15:00:23 -08001231 log.debug("updating groupHandlerMap with new grpHdlr for device: {}",
Charles Chan2199c302016-04-23 17:36:10 -07001232 deviceId);
1233 groupHandlerMap.put(deviceId, groupHandler);
Saurav Das2857f382015-11-03 14:39:27 -08001234 }
Saurav Dasb5c236e2016-06-07 10:08:06 -07001235
Charles Chan2199c302016-04-23 17:36:10 -07001236 if (mastershipService.isLocalMaster(deviceId)) {
Saurav Das018605f2017-02-18 14:05:44 -08001237 defaultRoutingHandler.populatePortAddressingRules(deviceId);
Charles Chan03a73e02016-10-24 14:52:01 -07001238 hostHandler.init(deviceId);
Charles Chanfc5c7802016-05-17 13:13:55 -07001239 xConnectHandler.init(deviceId);
Charles Chan2199c302016-04-23 17:36:10 -07001240 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
Charles Chan59cc16d2017-02-02 16:20:42 -08001241 groupHandler.createGroupsFromVlanConfig();
Charles Chan2199c302016-04-23 17:36:10 -07001242 routingRulePopulator.populateSubnetBroadcastRule(deviceId);
Charles Chanc42e84e2015-10-20 16:24:19 -07001243 }
Charles Chan5270ed02016-01-30 23:22:37 -08001244
Charles Chan03a73e02016-10-24 14:52:01 -07001245 appCfgHandler.init(deviceId);
1246 routeHandler.init(deviceId);
sanghob35a6192015-04-01 13:05:26 -07001247 }
1248
Saurav Das80980c72016-03-23 11:22:49 -07001249 private void processDeviceRemoved(Device device) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001250 dsNextObjStore.entrySet().stream()
Saurav Das80980c72016-03-23 11:22:49 -07001251 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan47933752017-11-30 15:37:50 -08001252 .forEach(entry -> dsNextObjStore.remove(entry.getKey()));
Charles Chan59cc16d2017-02-02 16:20:42 -08001253 vlanNextObjStore.entrySet().stream()
Saurav Das80980c72016-03-23 11:22:49 -07001254 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan65238242017-06-22 18:03:14 -07001255 .forEach(entry -> vlanNextObjStore.remove(entry.getKey()));
Saurav Das80980c72016-03-23 11:22:49 -07001256 portNextObjStore.entrySet().stream()
1257 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan65238242017-06-22 18:03:14 -07001258 .forEach(entry -> portNextObjStore.remove(entry.getKey()));
Saurav Das45f48152018-01-18 12:07:33 -08001259 linkHandler.processDeviceRemoved(device);
Charles Chaned3742352017-06-15 00:44:51 -07001260
Saurav Dasceccf242017-08-03 18:30:35 -07001261 DefaultGroupHandler gh = groupHandlerMap.remove(device.id());
1262 if (gh != null) {
1263 gh.shutdown();
1264 }
Saurav Dasc88d4662017-05-15 15:34:25 -07001265 // Note that a switch going down is associated with all of its links
1266 // going down as well, but it is treated as a single switch down event
1267 // while the link-downs are ignored.
1268 defaultRoutingHandler
1269 .populateRoutingRulesForLinkStatusChange(null, null, device.id());
Saurav Dasc568c342018-01-25 09:49:01 -08001270 defaultRoutingHandler.purgeEcmpGraph(device.id());
Charles Chanfc5c7802016-05-17 13:13:55 -07001271 xConnectHandler.removeDevice(device.id());
Saurav Dasa4020382018-02-14 14:14:54 -08001272
1273 // Cleanup all internal groupHandler stores for this device. Should be
1274 // done after all rerouting or rehashing has been completed
1275 groupHandlerMap.entrySet()
1276 .forEach(entry -> entry.getValue().cleanUpForNeighborDown(device.id()));
Saurav Das80980c72016-03-23 11:22:49 -07001277 }
1278
Saurav Das1a129a02016-11-18 15:21:57 -08001279 private void processPortUpdated(Device device, Port port) {
1280 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
1281 log.warn("Device configuration uploading. Not handling port event for"
1282 + "dev: {} port: {}", device.id(), port.number());
1283 return;
1284 }
Saurav Das018605f2017-02-18 14:05:44 -08001285
1286 if (!mastershipService.isLocalMaster(device.id())) {
1287 log.debug("Not master for dev:{} .. not handling port updated event"
1288 + "for port {}", device.id(), port.number());
1289 return;
1290 }
1291
1292 // first we handle filtering rules associated with the port
1293 if (port.isEnabled()) {
1294 log.info("Switchport {}/{} enabled..programming filters",
1295 device.id(), port.number());
Charles Chan7e4f8192017-02-26 22:59:35 -08001296 routingRulePopulator.processSinglePortFilters(device.id(), port.number(), true);
Saurav Das018605f2017-02-18 14:05:44 -08001297 } else {
1298 log.info("Switchport {}/{} disabled..removing filters",
1299 device.id(), port.number());
Charles Chan7e4f8192017-02-26 22:59:35 -08001300 routingRulePopulator.processSinglePortFilters(device.id(), port.number(), false);
Saurav Das018605f2017-02-18 14:05:44 -08001301 }
Saurav Das1a129a02016-11-18 15:21:57 -08001302
1303 // portUpdated calls are for ports that have gone down or up. For switch
1304 // to switch ports, link-events should take care of any re-routing or
1305 // group editing necessary for port up/down. Here we only process edge ports
1306 // that are already configured.
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001307 ConnectPoint cp = new ConnectPoint(device.id(), port.number());
1308 VlanId untaggedVlan = getUntaggedVlanId(cp);
1309 VlanId nativeVlan = getNativeVlanId(cp);
1310 Set<VlanId> taggedVlans = getTaggedVlanId(cp);
Charles Chan59cc16d2017-02-02 16:20:42 -08001311
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001312 if (untaggedVlan == null && nativeVlan == null && taggedVlans.isEmpty()) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001313 log.debug("Not handling port updated event for non-edge port (unconfigured) "
Saurav Das1a129a02016-11-18 15:21:57 -08001314 + "dev/port: {}/{}", device.id(), port.number());
1315 return;
1316 }
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001317 if (untaggedVlan != null) {
1318 processEdgePort(device, port, untaggedVlan, true);
1319 }
1320 if (nativeVlan != null) {
1321 processEdgePort(device, port, nativeVlan, true);
1322 }
1323 if (!taggedVlans.isEmpty()) {
1324 taggedVlans.forEach(tag -> processEdgePort(device, port, tag, false));
1325 }
Saurav Das1a129a02016-11-18 15:21:57 -08001326 }
1327
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001328 private void processEdgePort(Device device, Port port, VlanId vlanId,
1329 boolean popVlan) {
Saurav Das1a129a02016-11-18 15:21:57 -08001330 boolean portUp = port.isEnabled();
1331 if (portUp) {
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001332 log.info("Device:EdgePort {}:{} is enabled in vlan: {}", device.id(),
Charles Chan59cc16d2017-02-02 16:20:42 -08001333 port.number(), vlanId);
Charles Chan47933752017-11-30 15:37:50 -08001334 hostHandler.processPortUp(new ConnectPoint(device.id(), port.number()));
Saurav Das1a129a02016-11-18 15:21:57 -08001335 } else {
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001336 log.info("Device:EdgePort {}:{} is disabled in vlan: {}", device.id(),
Charles Chan59cc16d2017-02-02 16:20:42 -08001337 port.number(), vlanId);
Saurav Das1a129a02016-11-18 15:21:57 -08001338 }
1339
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -07001340 DefaultGroupHandler groupHandler = groupHandlerMap.get(device.id());
sanghob35a6192015-04-01 13:05:26 -07001341 if (groupHandler != null) {
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001342 groupHandler.processEdgePort(port.number(), vlanId, popVlan, portUp);
Saurav Das1a129a02016-11-18 15:21:57 -08001343 } else {
1344 log.warn("Group handler not found for dev:{}. Not handling edge port"
1345 + " {} event for port:{}", device.id(),
1346 (portUp) ? "UP" : "DOWN", port.number());
sanghob35a6192015-04-01 13:05:26 -07001347 }
1348 }
sangho1e575652015-05-14 00:39:53 -07001349
Charles Chan27fe1a52017-10-20 16:06:55 -07001350 private void createOrUpdateDeviceConfiguration() {
1351 if (deviceConfiguration == null) {
Saurav Dase7f51012018-02-09 17:26:45 -08001352 log.info("Creating new DeviceConfiguration");
Charles Chan27fe1a52017-10-20 16:06:55 -07001353 deviceConfiguration = new DeviceConfiguration(this);
1354 } else {
Saurav Dase7f51012018-02-09 17:26:45 -08001355 log.info("Updating DeviceConfiguration");
Charles Chan27fe1a52017-10-20 16:06:55 -07001356 deviceConfiguration.updateConfig();
1357 }
1358 }
1359
Pier Ventre10bd8d12016-11-26 21:05:22 -08001360 /**
1361 * Registers the given connect point with the NRS, this is necessary
1362 * to receive the NDP and ARP packets from the NRS.
1363 *
1364 * @param portToRegister connect point to register
1365 */
1366 public void registerConnectPoint(ConnectPoint portToRegister) {
Charles Chan0aa674e2017-02-23 15:44:08 -08001367 neighbourResolutionService.registerNeighbourHandler(
Pier Ventre10bd8d12016-11-26 21:05:22 -08001368 portToRegister,
1369 neighbourHandler,
1370 appId
1371 );
1372 }
1373
Charles Chand6832882015-10-05 17:50:33 -07001374 private class InternalConfigListener implements NetworkConfigListener {
Saurav Das7bcbe702017-06-13 15:35:54 -07001375 private static final long PROGRAM_DELAY = 2;
Charles Chan2c15aca2016-11-09 20:51:44 -08001376 SegmentRoutingManager srManager;
Charles Chan4636be02015-10-07 14:21:45 -07001377
Charles Chane849c192016-01-11 18:28:54 -08001378 /**
1379 * Constructs the internal network config listener.
1380 *
Charles Chan2c15aca2016-11-09 20:51:44 -08001381 * @param srManager segment routing manager
Charles Chane849c192016-01-11 18:28:54 -08001382 */
Charles Chan65238242017-06-22 18:03:14 -07001383 InternalConfigListener(SegmentRoutingManager srManager) {
Charles Chan2c15aca2016-11-09 20:51:44 -08001384 this.srManager = srManager;
Charles Chan4636be02015-10-07 14:21:45 -07001385 }
1386
Charles Chane849c192016-01-11 18:28:54 -08001387 /**
1388 * Reads network config and initializes related data structure accordingly.
1389 */
Charles Chan47933752017-11-30 15:37:50 -08001390 void configureNetwork() {
Saurav Dase7f51012018-02-09 17:26:45 -08001391 log.info("Configuring network ...");
Charles Chan27fe1a52017-10-20 16:06:55 -07001392 createOrUpdateDeviceConfiguration();
Charles Chan4636be02015-10-07 14:21:45 -07001393
Charles Chan2c15aca2016-11-09 20:51:44 -08001394 arpHandler = new ArpHandler(srManager);
1395 icmpHandler = new IcmpHandler(srManager);
1396 ipHandler = new IpHandler(srManager);
1397 routingRulePopulator = new RoutingRulePopulator(srManager);
1398 defaultRoutingHandler = new DefaultRoutingHandler(srManager);
Charles Chan4636be02015-10-07 14:21:45 -07001399
1400 tunnelHandler = new TunnelHandler(linkService, deviceConfiguration,
1401 groupHandlerMap, tunnelStore);
1402 policyHandler = new PolicyHandler(appId, deviceConfiguration,
1403 flowObjectiveService,
1404 tunnelHandler, policyStore);
Saurav Das7bcbe702017-06-13 15:35:54 -07001405 // add a small delay to absorb multiple network config added notifications
1406 if (!programmingScheduled.get()) {
Saurav Dase7f51012018-02-09 17:26:45 -08001407 log.info("Buffering config calls for {} secs", PROGRAM_DELAY);
Saurav Das7bcbe702017-06-13 15:35:54 -07001408 programmingScheduled.set(true);
1409 executorService.schedule(new ConfigChange(), PROGRAM_DELAY,
1410 TimeUnit.SECONDS);
Charles Chan4636be02015-10-07 14:21:45 -07001411 }
Charles Chan2199c302016-04-23 17:36:10 -07001412 mcastHandler.init();
Charles Chan4636be02015-10-07 14:21:45 -07001413 }
1414
Charles Chand6832882015-10-05 17:50:33 -07001415 @Override
1416 public void event(NetworkConfigEvent event) {
Charles Chan5270ed02016-01-30 23:22:37 -08001417 // TODO move this part to NetworkConfigEventHandler
1418 if (event.configClass().equals(SegmentRoutingDeviceConfig.class)) {
1419 switch (event.type()) {
1420 case CONFIG_ADDED:
Charles Chan278ce832017-06-26 15:25:09 -07001421 log.info("Segment Routing Device Config added for {}", event.subject());
Charles Chan5270ed02016-01-30 23:22:37 -08001422 configureNetwork();
1423 break;
1424 case CONFIG_UPDATED:
Charles Chan278ce832017-06-26 15:25:09 -07001425 log.info("Segment Routing Config updated for {}", event.subject());
Charles Chan27fe1a52017-10-20 16:06:55 -07001426 createOrUpdateDeviceConfiguration();
Charles Chan278ce832017-06-26 15:25:09 -07001427 // TODO support dynamic configuration
1428 break;
1429 default:
1430 break;
1431 }
1432 } else if (event.configClass().equals(InterfaceConfig.class)) {
1433 switch (event.type()) {
1434 case CONFIG_ADDED:
1435 log.info("Interface Config added for {}", event.subject());
1436 configureNetwork();
1437 break;
1438 case CONFIG_UPDATED:
1439 log.info("Interface Config updated for {}", event.subject());
Charles Chan27fe1a52017-10-20 16:06:55 -07001440 createOrUpdateDeviceConfiguration();
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001441
1442 // Following code will be uncommented when [CORD-634] is fully implemented.
1443 // [CORD-634] Add dynamic config support for interfaces
1444 updateInterface((InterfaceConfig) event.config().get(),
1445 (InterfaceConfig) event.prevConfig().get());
Charles Chan5270ed02016-01-30 23:22:37 -08001446 // TODO support dynamic configuration
1447 break;
1448 default:
1449 break;
Charles Chanb8e10c82015-10-14 11:24:40 -07001450 }
Charles Chan5270ed02016-01-30 23:22:37 -08001451 } else if (event.configClass().equals(SegmentRoutingAppConfig.class)) {
Charles Chanfc5c7802016-05-17 13:13:55 -07001452 checkState(appCfgHandler != null, "NetworkConfigEventHandler is not initialized");
Charles Chan5270ed02016-01-30 23:22:37 -08001453 switch (event.type()) {
1454 case CONFIG_ADDED:
Charles Chanfc5c7802016-05-17 13:13:55 -07001455 appCfgHandler.processAppConfigAdded(event);
Charles Chan5270ed02016-01-30 23:22:37 -08001456 break;
1457 case CONFIG_UPDATED:
Charles Chanfc5c7802016-05-17 13:13:55 -07001458 appCfgHandler.processAppConfigUpdated(event);
Charles Chan5270ed02016-01-30 23:22:37 -08001459 break;
1460 case CONFIG_REMOVED:
Charles Chanfc5c7802016-05-17 13:13:55 -07001461 appCfgHandler.processAppConfigRemoved(event);
1462 break;
1463 default:
1464 break;
1465 }
Saurav Dase7f51012018-02-09 17:26:45 -08001466 log.info("App config event .. configuring network");
Charles Chan03a73e02016-10-24 14:52:01 -07001467 configureNetwork();
Charles Chanfc5c7802016-05-17 13:13:55 -07001468 } else if (event.configClass().equals(XConnectConfig.class)) {
1469 checkState(xConnectHandler != null, "XConnectHandler is not initialized");
1470 switch (event.type()) {
1471 case CONFIG_ADDED:
1472 xConnectHandler.processXConnectConfigAdded(event);
1473 break;
1474 case CONFIG_UPDATED:
1475 xConnectHandler.processXConnectConfigUpdated(event);
1476 break;
1477 case CONFIG_REMOVED:
1478 xConnectHandler.processXConnectConfigRemoved(event);
Charles Chan5270ed02016-01-30 23:22:37 -08001479 break;
1480 default:
1481 break;
Charles Chanb8e10c82015-10-14 11:24:40 -07001482 }
Charles Chand6832882015-10-05 17:50:33 -07001483 }
1484 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001485
Charles Chan50443e82018-01-03 16:26:32 -08001486 @Override
1487 public boolean isRelevant(NetworkConfigEvent event) {
Saurav Dase7f51012018-02-09 17:26:45 -08001488 if (event.type() == CONFIG_REGISTERED ||
1489 event.type() == CONFIG_UNREGISTERED) {
1490 log.debug("Ignore event {} due to type mismatch", event);
1491 return false;
Charles Chan50443e82018-01-03 16:26:32 -08001492 }
Saurav Dase7f51012018-02-09 17:26:45 -08001493
1494 if (!event.configClass().equals(SegmentRoutingDeviceConfig.class) &&
1495 !event.configClass().equals(SegmentRoutingAppConfig.class) &&
1496 !event.configClass().equals(InterfaceConfig.class) &&
Andreas Pantelopouloscd339592018-02-23 14:18:00 -08001497 !event.configClass().equals(XConnectConfig.class)) {
Saurav Dase7f51012018-02-09 17:26:45 -08001498 log.debug("Ignore event {} due to class mismatch", event);
1499 return false;
1500 }
1501
1502 return true;
Charles Chan50443e82018-01-03 16:26:32 -08001503 }
1504
Saurav Das7bcbe702017-06-13 15:35:54 -07001505 private final class ConfigChange implements Runnable {
1506 @Override
1507 public void run() {
1508 programmingScheduled.set(false);
Saurav Dase7f51012018-02-09 17:26:45 -08001509 log.info("Reacting to config changes after buffer delay");
Saurav Das7bcbe702017-06-13 15:35:54 -07001510 for (Device device : deviceService.getDevices()) {
1511 processDeviceAdded(device);
1512 }
1513 defaultRoutingHandler.startPopulationProcess();
1514 }
1515 }
Charles Chand6832882015-10-05 17:50:33 -07001516 }
Charles Chan68aa62d2015-11-09 16:37:23 -08001517
1518 private class InternalHostListener implements HostListener {
Charles Chan68aa62d2015-11-09 16:37:23 -08001519 @Override
1520 public void event(HostEvent event) {
Charles Chan68aa62d2015-11-09 16:37:23 -08001521 switch (event.type()) {
1522 case HOST_ADDED:
Charles Chand2990362016-04-18 13:44:03 -07001523 hostHandler.processHostAddedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -08001524 break;
1525 case HOST_MOVED:
Charles Chand2990362016-04-18 13:44:03 -07001526 hostHandler.processHostMovedEvent(event);
Charles Chan2fde6d42017-08-23 14:46:43 -07001527 routeHandler.processHostMovedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -08001528 break;
1529 case HOST_REMOVED:
Charles Chanf9a52702017-06-16 15:19:24 -07001530 hostHandler.processHostRemovedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -08001531 break;
1532 case HOST_UPDATED:
Charles Chand2990362016-04-18 13:44:03 -07001533 hostHandler.processHostUpdatedEvent(event);
Charles Chan68aa62d2015-11-09 16:37:23 -08001534 break;
1535 default:
1536 log.warn("Unsupported host event type: {}", event.type());
1537 break;
1538 }
1539 }
1540 }
1541
Charles Chand55e84d2016-03-30 17:54:24 -07001542 private class InternalMcastListener implements McastListener {
1543 @Override
1544 public void event(McastEvent event) {
1545 switch (event.type()) {
1546 case SOURCE_ADDED:
Pier Luigi57d41792018-02-26 12:31:38 +01001547 case SOURCE_UPDATED:
Charles Chand55e84d2016-03-30 17:54:24 -07001548 case SINK_ADDED:
Charles Chand55e84d2016-03-30 17:54:24 -07001549 case SINK_REMOVED:
Charles Chand55e84d2016-03-30 17:54:24 -07001550 case ROUTE_REMOVED:
Pier Luigi05514fd2018-02-28 17:24:03 +01001551 mcastHandler.processMcastEvent(event);
Pier Luigi9930da52018-02-02 16:19:11 +01001552 break;
1553 case ROUTE_ADDED:
Charles Chand55e84d2016-03-30 17:54:24 -07001554 default:
1555 break;
1556 }
1557 }
1558 }
Charles Chan35fd1a72016-06-13 18:54:31 -07001559
Charles Chan03a73e02016-10-24 14:52:01 -07001560 private class InternalRouteEventListener implements RouteListener {
1561 @Override
1562 public void event(RouteEvent event) {
1563 switch (event.type()) {
1564 case ROUTE_ADDED:
1565 routeHandler.processRouteAdded(event);
1566 break;
1567 case ROUTE_UPDATED:
1568 routeHandler.processRouteUpdated(event);
1569 break;
1570 case ROUTE_REMOVED:
1571 routeHandler.processRouteRemoved(event);
1572 break;
Charles Chan2fde6d42017-08-23 14:46:43 -07001573 case ALTERNATIVE_ROUTES_CHANGED:
1574 routeHandler.processAlternativeRoutesChanged(event);
1575 break;
Charles Chan03a73e02016-10-24 14:52:01 -07001576 default:
1577 break;
1578 }
1579 }
1580 }
Saurav Dasc88d4662017-05-15 15:34:25 -07001581
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001582 private void updateInterface(InterfaceConfig conf, InterfaceConfig prevConf) {
1583 try {
1584 Set<Interface> intfs = conf.getInterfaces();
1585 Set<Interface> prevIntfs = prevConf.getInterfaces();
1586
1587 // Now we only handle one interface config at each port.
1588 if (intfs.size() != 1 || prevIntfs.size() != 1) {
1589 log.warn("Interface update aborted - one at a time is allowed, " +
1590 "but {} / {}(prev) received.", intfs.size(), prevIntfs.size());
1591 return;
1592 }
1593
1594 Interface intf = intfs.stream().findFirst().get();
1595 Interface prevIntf = prevIntfs.stream().findFirst().get();
1596
1597 DeviceId deviceId = intf.connectPoint().deviceId();
1598 PortNumber portNum = intf.connectPoint().port();
1599
1600 if (!mastershipService.isLocalMaster(deviceId)) {
1601 log.debug("CONFIG_UPDATED event for interfaces should be " +
1602 "handled by master node for device {}", deviceId);
1603 return;
1604 }
1605
1606 removeSubnetConfig(prevIntf.connectPoint(),
1607 Sets.difference(new HashSet<>(prevIntf.ipAddressesList()),
1608 new HashSet<>(intf.ipAddressesList())));
1609
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001610 if (!prevIntf.vlanNative().equals(VlanId.NONE)
1611 && !prevIntf.vlanNative().equals(intf.vlanUntagged())
1612 && !prevIntf.vlanNative().equals(intf.vlanNative())) {
1613 if (intf.vlanTagged().contains(prevIntf.vlanNative())) {
1614 // Update filtering objective and L2IG group bucket
1615 updatePortVlanTreatment(deviceId, portNum, prevIntf.vlanNative(), false);
1616 } else {
1617 // RemoveVlanNative
1618 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanNative(), true, false);
1619 }
1620 }
1621
1622 if (!prevIntf.vlanUntagged().equals(VlanId.NONE)
1623 && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())
1624 && !prevIntf.vlanUntagged().equals(intf.vlanNative())) {
1625 if (intf.vlanTagged().contains(prevIntf.vlanUntagged())) {
1626 // Update filtering objective and L2IG group bucket
1627 updatePortVlanTreatment(deviceId, portNum, prevIntf.vlanUntagged(), false);
1628 } else {
1629 // RemoveVlanUntagged
1630 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanUntagged(), true, false);
1631 }
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001632 }
1633
1634 if (!prevIntf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
1635 // RemoveVlanTagged
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001636 Sets.difference(prevIntf.vlanTagged(), intf.vlanTagged()).stream()
1637 .filter(i -> !intf.vlanUntagged().equals(i))
1638 .filter(i -> !intf.vlanNative().equals(i))
1639 .forEach(vlanId -> updateVlanConfigInternal(
1640 deviceId, portNum, vlanId, false, false));
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001641 }
1642
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001643 if (!intf.vlanNative().equals(VlanId.NONE)
1644 && !prevIntf.vlanNative().equals(intf.vlanNative())
1645 && !prevIntf.vlanUntagged().equals(intf.vlanNative())) {
1646 if (prevIntf.vlanTagged().contains(intf.vlanNative())) {
1647 // Update filtering objective and L2IG group bucket
1648 updatePortVlanTreatment(deviceId, portNum, intf.vlanNative(), true);
1649 } else {
1650 // AddVlanNative
1651 updateVlanConfigInternal(deviceId, portNum, intf.vlanNative(), true, true);
1652 }
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001653 }
1654
1655 if (!intf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
1656 // AddVlanTagged
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001657 Sets.difference(intf.vlanTagged(), prevIntf.vlanTagged()).stream()
1658 .filter(i -> !prevIntf.vlanUntagged().equals(i))
1659 .filter(i -> !prevIntf.vlanNative().equals(i))
1660 .forEach(vlanId -> updateVlanConfigInternal(
1661 deviceId, portNum, vlanId, false, true)
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001662 );
1663 }
1664
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001665 if (!intf.vlanUntagged().equals(VlanId.NONE)
1666 && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())
1667 && !prevIntf.vlanNative().equals(intf.vlanUntagged())) {
1668 if (prevIntf.vlanTagged().contains(intf.vlanUntagged())) {
1669 // Update filtering objective and L2IG group bucket
1670 updatePortVlanTreatment(deviceId, portNum, intf.vlanUntagged(), true);
1671 } else {
1672 // AddVlanUntagged
1673 updateVlanConfigInternal(deviceId, portNum, intf.vlanUntagged(), true, true);
1674 }
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001675 }
1676 addSubnetConfig(prevIntf.connectPoint(),
1677 Sets.difference(new HashSet<>(intf.ipAddressesList()),
1678 new HashSet<>(prevIntf.ipAddressesList())));
1679 } catch (ConfigException e) {
1680 log.error("Error in configuration");
1681 }
1682 }
1683
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001684 private void updatePortVlanTreatment(DeviceId deviceId, PortNumber portNum,
1685 VlanId vlanId, boolean pushVlan) {
1686 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
1687 if (grpHandler == null) {
1688 log.warn("Failed to retrieve group handler for device {}", deviceId);
1689 return;
1690 }
1691
1692 // Update filtering objective for a single port
1693 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, !pushVlan, vlanId, false);
1694 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, true);
1695
1696 if (getVlanNextObjectiveId(deviceId, vlanId) != -1) {
1697 // Update L2IG bucket of the port
1698 grpHandler.updateL2InterfaceGroupBucket(portNum, vlanId, pushVlan);
1699 } else {
1700 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
1701 }
1702 }
1703
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001704 private void updateVlanConfigInternal(DeviceId deviceId, PortNumber portNum,
1705 VlanId vlanId, boolean pushVlan, boolean install) {
1706 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
1707 if (grpHandler == null) {
1708 log.warn("Failed to retrieve group handler for device {}", deviceId);
1709 return;
1710 }
1711
1712 // Update filtering objective for a single port
1713 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, install);
1714
1715 // Update filtering objective for multicast ingress port
1716 mcastHandler.updateFilterToDevice(deviceId, portNum, vlanId, install);
1717
1718 int nextId = getVlanNextObjectiveId(deviceId, vlanId);
1719
1720 if (nextId != -1 && !install) {
1721 // Update next objective for a single port as an output port
1722 // Remove a single port from L2FG
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001723 grpHandler.updateGroupFromVlanConfiguration(vlanId, portNum, nextId, install);
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001724 // Remove L2 Bridging rule and L3 Unicast rule to the host
1725 hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum, vlanId, pushVlan, install);
1726 // Remove broadcast forwarding rule and corresponding L2FG for VLAN
1727 // only if there is no port configured on that VLAN ID
1728 if (!getVlanPortMap(deviceId).containsKey(vlanId)) {
1729 // Remove broadcast forwarding rule for the VLAN
1730 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
1731 // Remove L2FG for VLAN
1732 grpHandler.removeBcastGroupFromVlan(deviceId, portNum, vlanId, pushVlan);
1733 } else {
1734 // Remove L2IG of the port
1735 grpHandler.removePortNextObjective(deviceId, portNum, vlanId, pushVlan);
1736 }
1737 } else if (install) {
1738 if (nextId != -1) {
1739 // Add a single port to L2FG
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001740 grpHandler.updateGroupFromVlanConfiguration(vlanId, portNum, nextId, install);
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001741 } else {
1742 // Create L2FG for VLAN
1743 grpHandler.createBcastGroupFromVlan(vlanId, Collections.singleton(portNum));
1744 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
1745 }
1746 hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum, vlanId, pushVlan, install);
1747 } else {
1748 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
1749 }
1750 }
1751
1752 private void removeSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
1753 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
1754 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
1755
1756 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
1757 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
1758 .filter(intf -> !intf.connectPoint().equals(cp))
1759 .flatMap(intf -> intf.ipAddressesList().stream())
1760 .collect(Collectors.toSet());
1761 // 1. Partial subnet population
1762 // Remove routing rules for removed subnet from previous configuration,
1763 // which does not also exist in other interfaces in the same device
1764 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
1765 .map(InterfaceIpAddress::subnetAddress)
1766 .collect(Collectors.toSet());
1767
1768 defaultRoutingHandler.revokeSubnet(
1769 ipPrefixSet.stream()
1770 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
1771 .collect(Collectors.toSet()));
1772
1773 // 2. Interface IP punts
1774 // Remove IP punts for old Intf address
1775 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
1776 .map(InterfaceIpAddress::ipAddress)
1777 .collect(Collectors.toSet());
1778 ipAddressSet.stream()
1779 .map(InterfaceIpAddress::ipAddress)
1780 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
1781 .forEach(interfaceIpAddress ->
1782 routingRulePopulator.revokeSingleIpPunts(
1783 cp.deviceId(), interfaceIpAddress));
1784
1785 // 3. Host unicast routing rule
1786 // Remove unicast routing rule
1787 hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, false);
1788 }
1789
1790 private void addSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
1791 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
1792 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
1793
1794 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
1795 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
1796 .filter(intf -> !intf.connectPoint().equals(cp))
1797 .flatMap(intf -> intf.ipAddressesList().stream())
1798 .collect(Collectors.toSet());
1799 // 1. Partial subnet population
1800 // Add routing rules for newly added subnet, which does not also exist in
1801 // other interfaces in the same device
1802 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
1803 .map(InterfaceIpAddress::subnetAddress)
1804 .collect(Collectors.toSet());
1805
1806 defaultRoutingHandler.populateSubnet(
1807 Collections.singleton(cp),
1808 ipPrefixSet.stream()
1809 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
1810 .collect(Collectors.toSet()));
1811
1812 // 2. Interface IP punts
1813 // Add IP punts for new Intf address
1814 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
1815 .map(InterfaceIpAddress::ipAddress)
1816 .collect(Collectors.toSet());
1817 ipAddressSet.stream()
1818 .map(InterfaceIpAddress::ipAddress)
1819 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
1820 .forEach(interfaceIpAddress ->
1821 routingRulePopulator.populateSingleIpPunts(
1822 cp.deviceId(), interfaceIpAddress));
1823
1824 // 3. Host unicast routing rule
1825 // Add unicast routing rule
1826 hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, true);
1827 }
sanghob35a6192015-04-01 13:05:26 -07001828}