blob: ced12d0d9fcd001d68ad6b24b63a9c37fc0fbf22 [file] [log] [blame]
sangho80f11cb2015-04-01 13:05:26 -07001/*
Brian O'Connor0947d7e2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
sangho80f11cb2015-04-01 13:05:26 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.segmentrouting;
17
Jonathan Hart61e24e12017-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 Chanf0ae41e2017-08-23 13:55:39 -070022import com.google.common.collect.Sets;
sangho80f11cb2015-04-01 13:05:26 -070023import org.onlab.packet.Ethernet;
Pier Ventreb6b81d52016-12-02 08:16:05 -080024import org.onlab.packet.ICMP6;
Charles Chan77277672015-10-20 16:24:19 -070025import org.onlab.packet.IPv4;
Pier Ventreb6a7f342016-11-26 21:05:22 -080026import org.onlab.packet.IPv6;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -070027import org.onlab.packet.IpAddress;
Charles Chan77277672015-10-20 16:24:19 -070028import org.onlab.packet.IpPrefix;
Jonathan Hart54541d12016-04-12 15:39:44 -070029import org.onlab.packet.VlanId;
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -070030import org.onlab.util.KryoNamespace;
Charles Chan873661e2017-11-30 15:37:50 -080031import org.onlab.util.Tools;
Saurav Dasc3604f12016-03-23 11:22:49 -070032import org.onosproject.cfg.ComponentConfigService;
Saurav Das00e553b2018-04-21 17:19:48 -070033import org.onosproject.cluster.ClusterEvent;
34import org.onosproject.cluster.ClusterEventListener;
Pier Luigi580fd8a2018-01-16 10:47:50 +010035import org.onosproject.cluster.ClusterService;
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -070036import org.onosproject.cluster.LeadershipService;
Pierdb27b8d2018-04-17 16:29:56 +020037import org.onosproject.cluster.NodeId;
sangho80f11cb2015-04-01 13:05:26 -070038import org.onosproject.core.ApplicationId;
39import org.onosproject.core.CoreService;
40import org.onosproject.event.Event;
Charles Chanfbcb8812018-04-18 18:41:05 -070041import org.onosproject.mastership.MastershipEvent;
42import org.onosproject.mastership.MastershipListener;
Jonathan Hart54541d12016-04-12 15:39:44 -070043import org.onosproject.mastership.MastershipService;
Pier1f87aca2018-03-14 16:47:32 -070044import org.onosproject.mcast.api.McastEvent;
45import org.onosproject.mcast.api.McastListener;
46import org.onosproject.mcast.api.MulticastRouteService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080047import org.onosproject.net.ConnectPoint;
Jonathan Hart54541d12016-04-12 15:39:44 -070048import org.onosproject.net.Device;
49import org.onosproject.net.DeviceId;
Charles Chanf0ae41e2017-08-23 13:55:39 -070050import org.onosproject.net.Host;
51import org.onosproject.net.HostId;
Jonathan Hart54541d12016-04-12 15:39:44 -070052import org.onosproject.net.Link;
53import org.onosproject.net.Port;
Charles Chanf4586112015-11-09 16:37:23 -080054import org.onosproject.net.PortNumber;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -070055import org.onosproject.net.config.ConfigException;
Charles Chan72f556a2015-10-05 17:50:33 -070056import org.onosproject.net.config.ConfigFactory;
57import org.onosproject.net.config.NetworkConfigEvent;
Charles Chan72f556a2015-10-05 17:50:33 -070058import org.onosproject.net.config.NetworkConfigListener;
Jonathan Hart54541d12016-04-12 15:39:44 -070059import org.onosproject.net.config.NetworkConfigRegistry;
Ray Milkeyae0068a2017-08-15 11:02:29 -070060import org.onosproject.net.config.basics.InterfaceConfig;
61import org.onosproject.net.config.basics.McastConfig;
Charles Chan72f556a2015-10-05 17:50:33 -070062import org.onosproject.net.config.basics.SubjectFactories;
Saurav Dase6c448a2018-01-18 12:07:33 -080063import org.onosproject.net.device.DeviceAdminService;
Jonathan Hart54541d12016-04-12 15:39:44 -070064import org.onosproject.net.device.DeviceEvent;
65import org.onosproject.net.device.DeviceListener;
66import org.onosproject.net.device.DeviceService;
Charles Chanf4586112015-11-09 16:37:23 -080067import org.onosproject.net.flow.TrafficSelector;
68import org.onosproject.net.flow.TrafficTreatment;
Jonathan Hart54541d12016-04-12 15:39:44 -070069import org.onosproject.net.flowobjective.FlowObjectiveService;
Charles Chan0b1dd7e2018-08-19 19:21:46 -070070import org.onosproject.net.flowobjective.NextObjective;
Charles Chanf4586112015-11-09 16:37:23 -080071import org.onosproject.net.host.HostEvent;
72import org.onosproject.net.host.HostListener;
Charles Chanc6bcdf92018-06-01 16:33:48 -070073import org.onosproject.net.host.HostProbingService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080074import org.onosproject.net.host.HostService;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -070075import org.onosproject.net.host.InterfaceIpAddress;
Pierdb27b8d2018-04-17 16:29:56 +020076import org.onosproject.net.intent.WorkPartitionService;
Ray Milkeyae0068a2017-08-15 11:02:29 -070077import org.onosproject.net.intf.Interface;
78import org.onosproject.net.intf.InterfaceService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080079import org.onosproject.net.link.LinkEvent;
80import org.onosproject.net.link.LinkListener;
81import org.onosproject.net.link.LinkService;
Ray Milkeyae0068a2017-08-15 11:02:29 -070082import org.onosproject.net.neighbour.NeighbourResolutionService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080083import org.onosproject.net.packet.InboundPacket;
84import org.onosproject.net.packet.PacketContext;
85import org.onosproject.net.packet.PacketProcessor;
86import org.onosproject.net.packet.PacketService;
Pier Luigid8a15162018-02-15 16:33:08 +010087import org.onosproject.net.topology.TopologyEvent;
88import org.onosproject.net.topology.TopologyListener;
Charles Chanc91c8782016-03-30 17:54:24 -070089import org.onosproject.net.topology.TopologyService;
Charles Chanf0ae41e2017-08-23 13:55:39 -070090import org.onosproject.routeservice.ResolvedRoute;
Ray Milkeyae0068a2017-08-15 11:02:29 -070091import org.onosproject.routeservice.RouteEvent;
92import org.onosproject.routeservice.RouteListener;
93import org.onosproject.routeservice.RouteService;
Charles Chanc91c8782016-03-30 17:54:24 -070094import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
95import org.onosproject.segmentrouting.config.DeviceConfiguration;
Pier Ventre6b19e482016-11-07 16:21:04 -080096import org.onosproject.segmentrouting.config.SegmentRoutingAppConfig;
Ray Milkeyae0068a2017-08-15 11:02:29 -070097import org.onosproject.segmentrouting.config.SegmentRoutingDeviceConfig;
Charles Chan82f19972016-05-17 13:13:55 -070098import org.onosproject.segmentrouting.config.XConnectConfig;
Charles Chanc91c8782016-03-30 17:54:24 -070099import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
Saurav Das261c3002017-06-13 15:35:54 -0700100import org.onosproject.segmentrouting.grouphandler.DestinationSet;
101import org.onosproject.segmentrouting.grouphandler.NextNeighbors;
Pier Luigi69f774d2018-02-28 12:10:50 +0100102import org.onosproject.segmentrouting.mcast.McastHandler;
103import org.onosproject.segmentrouting.mcast.McastRole;
Piere99511d2018-04-19 16:47:06 +0200104import org.onosproject.segmentrouting.mcast.McastRoleStoreKey;
Ray Milkey2bd24a92018-08-17 14:54:17 -0700105import org.onosproject.segmentrouting.mcast.McastStoreKey;
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700106import org.onosproject.segmentrouting.pwaas.DefaultL2Tunnel;
Andreas Pantelopoulos96851252018-03-20 13:58:49 -0700107import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelDescription;
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800108import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelHandler;
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700109import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelPolicy;
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800110import org.onosproject.segmentrouting.pwaas.L2Tunnel;
Ray Milkey2bd24a92018-08-17 14:54:17 -0700111import org.onosproject.segmentrouting.pwaas.L2TunnelDescription;
Ray Milkeyae0068a2017-08-15 11:02:29 -0700112import org.onosproject.segmentrouting.pwaas.L2TunnelHandler;
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800113import org.onosproject.segmentrouting.pwaas.L2TunnelPolicy;
Saurav Das261c3002017-06-13 15:35:54 -0700114import org.onosproject.segmentrouting.storekey.DestinationSetNextObjectiveStoreKey;
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700115import org.onosproject.segmentrouting.storekey.DummyVlanIdStoreKey;
Charles Chan1eaf4802016-04-18 13:44:03 -0700116import org.onosproject.segmentrouting.storekey.PortNextObjectiveStoreKey;
Charles Chan10b0fb72017-02-02 16:20:42 -0800117import org.onosproject.segmentrouting.storekey.VlanNextObjectiveStoreKey;
Charles Chan82f19972016-05-17 13:13:55 -0700118import org.onosproject.segmentrouting.storekey.XConnectStoreKey;
Charles Chan8d316332018-06-19 20:31:57 -0700119import org.onosproject.segmentrouting.xconnect.api.XconnectService;
Jonathan Hart54541d12016-04-12 15:39:44 -0700120import org.onosproject.store.serializers.KryoNamespaces;
Srikanth Vavilapalli7cd16712015-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 Chan873661e2017-11-30 15:37:50 -0800125import org.osgi.service.component.ComponentContext;
Ray Milkey2bd24a92018-08-17 14:54:17 -0700126import org.osgi.service.component.annotations.Activate;
127import org.osgi.service.component.annotations.Component;
128import org.osgi.service.component.annotations.Deactivate;
129import org.osgi.service.component.annotations.Modified;
130import org.osgi.service.component.annotations.Reference;
131import org.osgi.service.component.annotations.ReferenceCardinality;
sangho80f11cb2015-04-01 13:05:26 -0700132import org.slf4j.Logger;
133import org.slf4j.LoggerFactory;
134
Saurav Das00e553b2018-04-21 17:19:48 -0700135import java.time.Instant;
Andreas Pantelopoulosd988c1a2018-03-15 16:56:09 -0700136import java.util.ArrayList;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800137import java.util.Collections;
Charles Chan873661e2017-11-30 15:37:50 -0800138import java.util.Dictionary;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800139import java.util.HashSet;
140import java.util.List;
141import java.util.Map;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800142import java.util.Optional;
143import java.util.Set;
Andrea Campanella060cad82018-04-17 12:09:34 +0200144import java.util.concurrent.CompletableFuture;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800145import java.util.concurrent.ConcurrentHashMap;
Andrea Campanella060cad82018-04-17 12:09:34 +0200146import java.util.concurrent.CopyOnWriteArrayList;
Charles Chan77cdde42018-05-08 21:35:50 -0700147import java.util.concurrent.ExecutorService;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800148import java.util.concurrent.Executors;
149import java.util.concurrent.ScheduledExecutorService;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800150import java.util.concurrent.TimeUnit;
151import java.util.concurrent.atomic.AtomicBoolean;
152import java.util.stream.Collectors;
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700153import java.util.stream.IntStream;
sangho80f11cb2015-04-01 13:05:26 -0700154
Charles Chand6d25332016-02-26 22:19:52 -0800155import static com.google.common.base.Preconditions.checkState;
Pier Ventreadb4ae62016-11-23 09:57:42 -0800156import static org.onlab.packet.Ethernet.TYPE_ARP;
Yuta HIGUCHIebee2f12016-07-21 16:54:33 -0700157import static org.onlab.util.Tools.groupedThreads;
Saurav Dase321cff2018-02-09 17:26:45 -0800158import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_REGISTERED;
159import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_UNREGISTERED;
Charles Chand6d25332016-02-26 22:19:52 -0800160
Charles Chanb7f75ac2016-01-11 18:28:54 -0800161/**
162 * Segment routing manager.
163 */
Ray Milkey2bd24a92018-08-17 14:54:17 -0700164@Component(immediate = true, service = SegmentRoutingService.class)
sangho27462c62015-05-14 00:39:53 -0700165public class SegmentRoutingManager implements SegmentRoutingService {
sangho80f11cb2015-04-01 13:05:26 -0700166
Charles Chan46fdfaf2016-11-09 20:51:44 -0800167 private static Logger log = LoggerFactory.getLogger(SegmentRoutingManager.class);
Charles Chan910be6a2017-08-23 14:46:43 -0700168 private static final String NOT_MASTER = "Current instance is not the master of {}. Ignore.";
sangho80f11cb2015-04-01 13:05:26 -0700169
Ray Milkey2bd24a92018-08-17 14:54:17 -0700170 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chandebfea32016-10-24 14:52:01 -0700171 private ComponentConfigService compCfgService;
sangho80f11cb2015-04-01 13:05:26 -0700172
Ray Milkey2bd24a92018-08-17 14:54:17 -0700173 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pier Ventreb6a7f342016-11-26 21:05:22 -0800174 private NeighbourResolutionService neighbourResolutionService;
175
Ray Milkey2bd24a92018-08-17 14:54:17 -0700176 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pier Luigi69f774d2018-02-28 12:10:50 +0100177 public CoreService coreService;
sangho80f11cb2015-04-01 13:05:26 -0700178
Ray Milkey2bd24a92018-08-17 14:54:17 -0700179 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chandebfea32016-10-24 14:52:01 -0700180 PacketService packetService;
sangho80f11cb2015-04-01 13:05:26 -0700181
Ray Milkey2bd24a92018-08-17 14:54:17 -0700182 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chandebfea32016-10-24 14:52:01 -0700183 HostService hostService;
sangho80f11cb2015-04-01 13:05:26 -0700184
Ray Milkey2bd24a92018-08-17 14:54:17 -0700185 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chanc6bcdf92018-06-01 16:33:48 -0700186 HostProbingService probingService;
Charles Chan873661e2017-11-30 15:37:50 -0800187
Ray Milkey2bd24a92018-08-17 14:54:17 -0700188 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pier Luigi69f774d2018-02-28 12:10:50 +0100189 public DeviceService deviceService;
sangho80f11cb2015-04-01 13:05:26 -0700190
Ray Milkey2bd24a92018-08-17 14:54:17 -0700191 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Saurav Dase6c448a2018-01-18 12:07:33 -0800192 DeviceAdminService deviceAdminService;
193
Ray Milkey2bd24a92018-08-17 14:54:17 -0700194 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pier Ventref3cf5b92016-11-09 14:17:26 -0800195 public FlowObjectiveService flowObjectiveService;
sangho80f11cb2015-04-01 13:05:26 -0700196
Ray Milkey2bd24a92018-08-17 14:54:17 -0700197 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pier Luigi69f774d2018-02-28 12:10:50 +0100198 public LinkService linkService;
sangho27462c62015-05-14 00:39:53 -0700199
Ray Milkey2bd24a92018-08-17 14:54:17 -0700200 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pier Ventref3cf5b92016-11-09 14:17:26 -0800201 public MastershipService mastershipService;
Charles Chandebfea32016-10-24 14:52:01 -0700202
Ray Milkey2bd24a92018-08-17 14:54:17 -0700203 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pier Ventref3cf5b92016-11-09 14:17:26 -0800204 public StorageService storageService;
Charles Chandebfea32016-10-24 14:52:01 -0700205
Ray Milkey2bd24a92018-08-17 14:54:17 -0700206 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pier Luigi69f774d2018-02-28 12:10:50 +0100207 public MulticastRouteService multicastRouteService;
Charles Chandebfea32016-10-24 14:52:01 -0700208
Ray Milkey2bd24a92018-08-17 14:54:17 -0700209 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chan83163812018-01-09 13:45:07 -0800210 public TopologyService topologyService;
Charles Chandebfea32016-10-24 14:52:01 -0700211
Ray Milkey2bd24a92018-08-17 14:54:17 -0700212 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chandebfea32016-10-24 14:52:01 -0700213 RouteService routeService;
Charles Chan82ab1932016-01-30 23:22:37 -0800214
Ray Milkey2bd24a92018-08-17 14:54:17 -0700215 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chan46fdfaf2016-11-09 20:51:44 -0800216 public NetworkConfigRegistry cfgService;
Charles Chan82ab1932016-01-30 23:22:37 -0800217
Ray Milkey2bd24a92018-08-17 14:54:17 -0700218 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Charles Chan46fdfaf2016-11-09 20:51:44 -0800219 public InterfaceService interfaceService;
220
Ray Milkey2bd24a92018-08-17 14:54:17 -0700221 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pier Luigi580fd8a2018-01-16 10:47:50 +0100222 public ClusterService clusterService;
223
Ray Milkey2bd24a92018-08-17 14:54:17 -0700224 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pierdb27b8d2018-04-17 16:29:56 +0200225 public WorkPartitionService workPartitionService;
Pier Luigi580fd8a2018-01-16 10:47:50 +0100226
Ray Milkey2bd24a92018-08-17 14:54:17 -0700227 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700228 public LeadershipService leadershipService;
229
Ray Milkey2bd24a92018-08-17 14:54:17 -0700230 @Reference(cardinality = ReferenceCardinality.OPTIONAL)
Charles Chan8d316332018-06-19 20:31:57 -0700231 public XconnectService xconnectService;
232
Ray Milkey2bd24a92018-08-17 14:54:17 -0700233 //@Property(name = "activeProbing", boolValue = true,
234 // label = "Enable active probing to discover dual-homed hosts.")
Charles Chan873661e2017-11-30 15:37:50 -0800235 boolean activeProbing = true;
236
Ray Milkey2bd24a92018-08-17 14:54:17 -0700237 //@Property(name = "singleHomedDown", boolValue = false,
238 // label = "Enable administratively taking down single-homed hosts "
239 // + "when all uplinks are gone")
Saurav Dasec683dc2018-04-27 18:42:30 -0700240 boolean singleHomedDown = false;
241
Ray Milkey2bd24a92018-08-17 14:54:17 -0700242 //@Property(name = "respondToUnknownHosts", boolValue = true,
243 // label = "Enable this to respond to ARP/NDP requests from unknown hosts.")
Andreas Pantelopoulos6464d862018-06-18 12:50:35 -0700244 boolean respondToUnknownHosts = true;
245
Ray Milkey2bd24a92018-08-17 14:54:17 -0700246 //@Property(name = "routeDoubleTaggedHosts", boolValue = false,
247 // label = "Program flows and groups to pop and route double tagged hosts")
Charles Chanfbca55e2018-07-24 16:40:35 -0700248 boolean routeDoubleTaggedHosts = false;
Charles Chan4eb73bb2018-07-19 14:55:31 -0700249
Saurav Das9bf49582018-08-13 15:34:26 -0700250 private static final int DEFAULT_INTERNAL_VLAN = 4094;
Ray Milkey2bd24a92018-08-17 14:54:17 -0700251 //@Property(name = "defaultInternalVlan", intValue = DEFAULT_INTERNAL_VLAN,
252 // label = "internal vlan assigned by default to unconfigured ports")
Saurav Das9bf49582018-08-13 15:34:26 -0700253 private int defaultInternalVlan = DEFAULT_INTERNAL_VLAN;
254
255 private static final int PW_TRANSPORT_VLAN = 4090;
Ray Milkey2bd24a92018-08-17 14:54:17 -0700256 //@Property(name = "pwTransportVlan", intValue = PW_TRANSPORT_VLAN,
257 // label = "vlan used for transport of pseudowires between switches")
Saurav Das9bf49582018-08-13 15:34:26 -0700258 private int pwTransportVlan = PW_TRANSPORT_VLAN;
259
Charles Chandebfea32016-10-24 14:52:01 -0700260 ArpHandler arpHandler = null;
261 IcmpHandler icmpHandler = null;
262 IpHandler ipHandler = null;
263 RoutingRulePopulator routingRulePopulator = null;
Ray Milkeyb85de082017-04-05 09:42:04 -0700264 ApplicationId appId;
265 DeviceConfiguration deviceConfiguration = null;
sangho80f11cb2015-04-01 13:05:26 -0700266
Charles Chandebfea32016-10-24 14:52:01 -0700267 DefaultRoutingHandler defaultRoutingHandler = null;
sangho27462c62015-05-14 00:39:53 -0700268 private TunnelHandler tunnelHandler = null;
269 private PolicyHandler policyHandler = null;
Charles Chan2b078ae2015-10-14 11:24:40 -0700270 private InternalPacketProcessor processor = null;
271 private InternalLinkListener linkListener = null;
272 private InternalDeviceListener deviceListener = null;
Charles Chan82f19972016-05-17 13:13:55 -0700273 private AppConfigHandler appCfgHandler = null;
Pier Luigi69f774d2018-02-28 12:10:50 +0100274 public XConnectHandler xConnectHandler = null;
Saurav Dase6c448a2018-01-18 12:07:33 -0800275 McastHandler mcastHandler = null;
276 HostHandler hostHandler = null;
Pier Ventreb6a7f342016-11-26 21:05:22 -0800277 private RouteHandler routeHandler = null;
Saurav Dase6c448a2018-01-18 12:07:33 -0800278 LinkHandler linkHandler = null;
Pier Ventreb6b81d52016-12-02 08:16:05 -0800279 private SegmentRoutingNeighbourDispatcher neighbourHandler = null;
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800280 private DefaultL2TunnelHandler l2TunnelHandler = null;
Pier Luigid8a15162018-02-15 16:33:08 +0100281 private TopologyHandler topologyHandler = null;
Charles Chan82ab1932016-01-30 23:22:37 -0800282 private final InternalHostListener hostListener = new InternalHostListener();
Charles Chanc91c8782016-03-30 17:54:24 -0700283 private final InternalConfigListener cfgListener = new InternalConfigListener(this);
284 private final InternalMcastListener mcastListener = new InternalMcastListener();
Charles Chandebfea32016-10-24 14:52:01 -0700285 private final InternalRouteEventListener routeListener = new InternalRouteEventListener();
Pier Luigid8a15162018-02-15 16:33:08 +0100286 private final InternalTopologyListener topologyListener = new InternalTopologyListener();
Charles Chanfbcb8812018-04-18 18:41:05 -0700287 private final InternalMastershipListener mastershipListener = new InternalMastershipListener();
Saurav Das00e553b2018-04-21 17:19:48 -0700288 final InternalClusterListener clusterListener = new InternalClusterListener();
Andrea Campanella060cad82018-04-17 12:09:34 +0200289 //Completable future for network configuration process to buffer config events handling during activation
290 private CompletableFuture<Boolean> networkConfigCompletion = null;
Charles Chan39b75522018-04-21 00:44:29 -0700291 private List<Event> queuedEvents = new CopyOnWriteArrayList<>();
sangho80f11cb2015-04-01 13:05:26 -0700292
Charles Chan52003922018-04-05 16:31:15 -0700293 // Handles device, link, topology and network config events
Charles Chanfbcb8812018-04-18 18:41:05 -0700294 private ScheduledExecutorService mainEventExecutor;
sangho80f11cb2015-04-01 13:05:26 -0700295
Charles Chanfbcb8812018-04-18 18:41:05 -0700296 // Handles host, route and mcast events respectively
297 private ScheduledExecutorService hostEventExecutor;
298 private ScheduledExecutorService routeEventExecutor;
299 private ScheduledExecutorService mcastEventExecutor;
Charles Chan77cdde42018-05-08 21:35:50 -0700300 private ExecutorService packetExecutor;
Charles Chan52003922018-04-05 16:31:15 -0700301
302 Map<DeviceId, DefaultGroupHandler> groupHandlerMap = new ConcurrentHashMap<>();
Charles Chanb7f75ac2016-01-11 18:28:54 -0800303 /**
Saurav Das261c3002017-06-13 15:35:54 -0700304 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan53de91f2017-08-22 15:07:34 -0700305 * Used to keep track on MPLS group information.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800306 */
Charles Chan873661e2017-11-30 15:37:50 -0800307 private EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Saurav Das261c3002017-06-13 15:35:54 -0700308 dsNextObjStore = null;
Charles Chanb7f75ac2016-01-11 18:28:54 -0800309 /**
Charles Chan53de91f2017-08-22 15:07:34 -0700310 * Per device next objective ID store with (device id + vlanid) as key.
311 * Used to keep track on L2 flood group information.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800312 */
Charles Chan873661e2017-11-30 15:37:50 -0800313 private EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer>
Charles Chan10b0fb72017-02-02 16:20:42 -0800314 vlanNextObjStore = null;
Charles Chanb7f75ac2016-01-11 18:28:54 -0800315 /**
Charles Chan53de91f2017-08-22 15:07:34 -0700316 * Per device next objective ID store with (device id + port + treatment + meta) as key.
317 * Used to keep track on L2 interface group and L3 unicast group information.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800318 */
Charles Chan873661e2017-11-30 15:37:50 -0800319 private EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer>
Saurav Das2d94d312015-11-24 23:21:05 -0800320 portNextObjStore = null;
Charles Chan10b0fb72017-02-02 16:20:42 -0800321
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700322 /**
323 * Per port dummy VLAN ID store with (connect point + ip address) as key.
324 * Used to keep track on dummy VLAN ID allocation.
325 */
326 private EventuallyConsistentMap<DummyVlanIdStoreKey, VlanId>
327 dummyVlanIdStore = null;
328
Saurav Das2d94d312015-11-24 23:21:05 -0800329 private EventuallyConsistentMap<String, Tunnel> tunnelStore = null;
330 private EventuallyConsistentMap<String, Policy> policyStore = null;
sangho4a5c42a2015-05-20 22:16:38 -0700331
Saurav Das261c3002017-06-13 15:35:54 -0700332 private AtomicBoolean programmingScheduled = new AtomicBoolean();
333
Charles Chanc91c8782016-03-30 17:54:24 -0700334 private final ConfigFactory<DeviceId, SegmentRoutingDeviceConfig> deviceConfigFactory =
Charles Chan82f19972016-05-17 13:13:55 -0700335 new ConfigFactory<DeviceId, SegmentRoutingDeviceConfig>(
336 SubjectFactories.DEVICE_SUBJECT_FACTORY,
Charles Chanc91c8782016-03-30 17:54:24 -0700337 SegmentRoutingDeviceConfig.class, "segmentrouting") {
Charles Chan72f556a2015-10-05 17:50:33 -0700338 @Override
Charles Chan82ab1932016-01-30 23:22:37 -0800339 public SegmentRoutingDeviceConfig createConfig() {
340 return new SegmentRoutingDeviceConfig();
Charles Chan72f556a2015-10-05 17:50:33 -0700341 }
342 };
Pier Ventre6b19e482016-11-07 16:21:04 -0800343
Charles Chanc91c8782016-03-30 17:54:24 -0700344 private final ConfigFactory<ApplicationId, SegmentRoutingAppConfig> appConfigFactory =
Charles Chan82f19972016-05-17 13:13:55 -0700345 new ConfigFactory<ApplicationId, SegmentRoutingAppConfig>(
346 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chanc91c8782016-03-30 17:54:24 -0700347 SegmentRoutingAppConfig.class, "segmentrouting") {
Charles Chan82ab1932016-01-30 23:22:37 -0800348 @Override
349 public SegmentRoutingAppConfig createConfig() {
350 return new SegmentRoutingAppConfig();
351 }
352 };
Pier Ventre6b19e482016-11-07 16:21:04 -0800353
Charles Chan82f19972016-05-17 13:13:55 -0700354 private final ConfigFactory<ApplicationId, XConnectConfig> xConnectConfigFactory =
355 new ConfigFactory<ApplicationId, XConnectConfig>(
356 SubjectFactories.APP_SUBJECT_FACTORY,
357 XConnectConfig.class, "xconnect") {
358 @Override
359 public XConnectConfig createConfig() {
360 return new XConnectConfig();
361 }
362 };
Pier Ventre6b19e482016-11-07 16:21:04 -0800363
Charles Chanc91c8782016-03-30 17:54:24 -0700364 private ConfigFactory<ApplicationId, McastConfig> mcastConfigFactory =
Charles Chan82f19972016-05-17 13:13:55 -0700365 new ConfigFactory<ApplicationId, McastConfig>(
366 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chanc91c8782016-03-30 17:54:24 -0700367 McastConfig.class, "multicast") {
368 @Override
369 public McastConfig createConfig() {
370 return new McastConfig();
371 }
372 };
373
Charles Chan1963f4f2016-02-18 14:22:42 -0800374 /**
375 * Segment Routing App ID.
376 */
Charles Chan46fdfaf2016-11-09 20:51:44 -0800377 public static final String APP_NAME = "org.onosproject.segmentrouting";
Saurav Das7c305372015-10-28 12:39:42 -0700378
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700379 /**
380 * Minumum and maximum value of dummy VLAN ID to be allocated.
381 */
382 public static final int MIN_DUMMY_VLAN_ID = 2;
383 public static final int MAX_DUMMY_VLAN_ID = 4093;
384
Saurav Dasec683dc2018-04-27 18:42:30 -0700385 Instant lastEdgePortEvent = Instant.EPOCH;
386
sangho80f11cb2015-04-01 13:05:26 -0700387 @Activate
Charles Chan873661e2017-11-30 15:37:50 -0800388 protected void activate(ComponentContext context) {
Charles Chan46fdfaf2016-11-09 20:51:44 -0800389 appId = coreService.registerApplication(APP_NAME);
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700390
Charles Chanfbcb8812018-04-18 18:41:05 -0700391 mainEventExecutor = Executors.newSingleThreadScheduledExecutor(groupedThreads("sr-event-main", "%d", log));
392 hostEventExecutor = Executors.newSingleThreadScheduledExecutor(groupedThreads("sr-event-host", "%d", log));
393 routeEventExecutor = Executors.newSingleThreadScheduledExecutor(groupedThreads("sr-event-route", "%d", log));
394 mcastEventExecutor = Executors.newSingleThreadScheduledExecutor(groupedThreads("sr-event-mcast", "%d", log));
Charles Chan77cdde42018-05-08 21:35:50 -0700395 packetExecutor = Executors.newSingleThreadExecutor(groupedThreads("sr-packet", "%d", log));
Charles Chanfbcb8812018-04-18 18:41:05 -0700396
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700397 log.debug("Creating EC map nsnextobjectivestore");
Saurav Das261c3002017-06-13 15:35:54 -0700398 EventuallyConsistentMapBuilder<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700399 nsNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
Saurav Das261c3002017-06-13 15:35:54 -0700400 dsNextObjStore = nsNextObjMapBuilder
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700401 .withName("nsnextobjectivestore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700402 .withSerializer(createSerializer())
Madan Jampani675ae202015-06-24 19:05:56 -0700403 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700404 .build();
Saurav Das261c3002017-06-13 15:35:54 -0700405 log.trace("Current size {}", dsNextObjStore.size());
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700406
Charles Chan10b0fb72017-02-02 16:20:42 -0800407 log.debug("Creating EC map vlannextobjectivestore");
408 EventuallyConsistentMapBuilder<VlanNextObjectiveStoreKey, Integer>
409 vlanNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
410 vlanNextObjStore = vlanNextObjMapBuilder
411 .withName("vlannextobjectivestore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700412 .withSerializer(createSerializer())
Charles Chan77277672015-10-20 16:24:19 -0700413 .withTimestampProvider((k, v) -> new WallClockTimestamp())
414 .build();
415
Saurav Das2d94d312015-11-24 23:21:05 -0800416 log.debug("Creating EC map subnetnextobjectivestore");
417 EventuallyConsistentMapBuilder<PortNextObjectiveStoreKey, Integer>
418 portNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
419 portNextObjStore = portNextObjMapBuilder
420 .withName("portnextobjectivestore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700421 .withSerializer(createSerializer())
Saurav Das2d94d312015-11-24 23:21:05 -0800422 .withTimestampProvider((k, v) -> new WallClockTimestamp())
423 .build();
424
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700425 EventuallyConsistentMapBuilder<DummyVlanIdStoreKey, VlanId>
426 dummyVlanIdMapBuilder = storageService.eventuallyConsistentMapBuilder();
427 dummyVlanIdStore = dummyVlanIdMapBuilder
428 .withName("dummyvlanidstore")
429 .withSerializer(createSerializer())
430 .withTimestampProvider((k, v) -> new WallClockTimestamp())
431 .build();
432
sangho4a5c42a2015-05-20 22:16:38 -0700433 EventuallyConsistentMapBuilder<String, Tunnel> tunnelMapBuilder =
434 storageService.eventuallyConsistentMapBuilder();
sangho4a5c42a2015-05-20 22:16:38 -0700435 tunnelStore = tunnelMapBuilder
436 .withName("tunnelstore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700437 .withSerializer(createSerializer())
Madan Jampani675ae202015-06-24 19:05:56 -0700438 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho4a5c42a2015-05-20 22:16:38 -0700439 .build();
440
441 EventuallyConsistentMapBuilder<String, Policy> policyMapBuilder =
442 storageService.eventuallyConsistentMapBuilder();
sangho4a5c42a2015-05-20 22:16:38 -0700443 policyStore = policyMapBuilder
444 .withName("policystore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700445 .withSerializer(createSerializer())
Madan Jampani675ae202015-06-24 19:05:56 -0700446 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho4a5c42a2015-05-20 22:16:38 -0700447 .build();
448
Saurav Dasc3604f12016-03-23 11:22:49 -0700449 compCfgService.preSetProperty("org.onosproject.net.group.impl.GroupManager",
Pier Luigib9632ba2017-01-12 18:14:58 -0800450 "purgeOnDisconnection", "true");
Saurav Dasc3604f12016-03-23 11:22:49 -0700451 compCfgService.preSetProperty("org.onosproject.net.flow.impl.FlowRuleManager",
Pier Luigib9632ba2017-01-12 18:14:58 -0800452 "purgeOnDisconnection", "true");
Pier Luigib9632ba2017-01-12 18:14:58 -0800453 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
454 "requestInterceptsEnabled", "false");
Charles Chanc1909e12017-08-08 15:13:37 -0700455 compCfgService.preSetProperty("org.onosproject.net.neighbour.impl.NeighbourResolutionManager",
Pier Luigibc976df2017-01-12 22:46:39 -0800456 "requestInterceptsEnabled", "false");
Charles Chan9597f8d2017-07-24 15:56:10 -0700457 compCfgService.preSetProperty("org.onosproject.dhcprelay.DhcpRelayManager",
Pier Luigibc976df2017-01-12 22:46:39 -0800458 "arpEnabled", "false");
Pier Luigi0ebeb312017-02-02 22:31:34 -0800459 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
460 "greedyLearningIpv6", "true");
Charles Chancf8ea472017-02-28 15:15:17 -0800461 compCfgService.preSetProperty("org.onosproject.routing.cpr.ControlPlaneRedirectManager",
462 "forceUnprovision", "true");
Charles Chanc7b73c72017-08-10 16:57:28 -0700463 compCfgService.preSetProperty("org.onosproject.routeservice.store.RouteStoreImpl",
Charles Chan4c95c0d2017-07-20 16:16:25 -0700464 "distributed", "true");
Charles Chan804772f2017-08-14 11:42:11 -0700465 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
466 "multihomingEnabled", "true");
Charles Chan0c9c19f2017-11-29 19:54:20 -0800467 compCfgService.preSetProperty("org.onosproject.provider.lldp.impl.LldpLinkProvider",
468 "staleLinkAge", "15000");
469 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
470 "allowDuplicateIps", "false");
Yi Tsenga7da8d82018-08-19 03:09:54 +0800471 // For P4 switches
472 compCfgService.preSetProperty("org.onosproject.net.flow.impl.FlowRuleManager",
Charles Chan02298512018-08-30 17:30:45 -0700473 "fallbackFlowPollFrequency", "4");
Yi Tsenga7da8d82018-08-19 03:09:54 +0800474 compCfgService.preSetProperty("org.onosproject.net.group.impl.GroupManager",
Charles Chan02298512018-08-30 17:30:45 -0700475 "fallbackGroupPollFrequency", "3");
Charles Chan873661e2017-11-30 15:37:50 -0800476 compCfgService.registerProperties(getClass());
477 modified(context);
Saurav Dasc3604f12016-03-23 11:22:49 -0700478
Charles Chan2b078ae2015-10-14 11:24:40 -0700479 processor = new InternalPacketProcessor();
480 linkListener = new InternalLinkListener();
481 deviceListener = new InternalDeviceListener();
Charles Chan82f19972016-05-17 13:13:55 -0700482 appCfgHandler = new AppConfigHandler(this);
483 xConnectHandler = new XConnectHandler(this);
Charles Chan1eaf4802016-04-18 13:44:03 -0700484 mcastHandler = new McastHandler(this);
485 hostHandler = new HostHandler(this);
Saurav Dase6c448a2018-01-18 12:07:33 -0800486 linkHandler = new LinkHandler(this);
Charles Chandebfea32016-10-24 14:52:01 -0700487 routeHandler = new RouteHandler(this);
Pier Ventreb6b81d52016-12-02 08:16:05 -0800488 neighbourHandler = new SegmentRoutingNeighbourDispatcher(this);
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800489 l2TunnelHandler = new DefaultL2TunnelHandler(this);
Pier Luigid8a15162018-02-15 16:33:08 +0100490 topologyHandler = new TopologyHandler(this);
Charles Chan2b078ae2015-10-14 11:24:40 -0700491
Charles Chand6d25332016-02-26 22:19:52 -0800492 cfgService.addListener(cfgListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700493 cfgService.registerConfigFactory(deviceConfigFactory);
494 cfgService.registerConfigFactory(appConfigFactory);
Charles Chan82f19972016-05-17 13:13:55 -0700495 cfgService.registerConfigFactory(xConnectConfigFactory);
Charles Chanc91c8782016-03-30 17:54:24 -0700496 cfgService.registerConfigFactory(mcastConfigFactory);
Saurav Dase321cff2018-02-09 17:26:45 -0800497 log.info("Configuring network before adding listeners");
Andrea Campanella060cad82018-04-17 12:09:34 +0200498
Charles Chan6961f222018-01-04 14:26:07 -0800499 cfgListener.configureNetwork();
500
Charles Chan82ab1932016-01-30 23:22:37 -0800501 hostService.addListener(hostListener);
Charles Chan2b078ae2015-10-14 11:24:40 -0700502 packetService.addProcessor(processor, PacketProcessor.director(2));
503 linkService.addListener(linkListener);
504 deviceService.addListener(deviceListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700505 multicastRouteService.addListener(mcastListener);
Charles Chanfd48c222017-06-19 00:43:31 -0700506 routeService.addListener(routeListener);
Pier Luigid8a15162018-02-15 16:33:08 +0100507 topologyService.addListener(topologyListener);
Charles Chanfbcb8812018-04-18 18:41:05 -0700508 mastershipService.addListener(mastershipListener);
Saurav Das00e553b2018-04-21 17:19:48 -0700509 clusterService.addListener(clusterListener);
Charles Chan2b078ae2015-10-14 11:24:40 -0700510
Charles Chanc12c3d02018-03-09 15:53:44 -0800511 linkHandler.init();
Andreas Pantelopoulos75eef062018-01-11 07:53:48 -0800512 l2TunnelHandler.init();
513
Andrea Campanella060cad82018-04-17 12:09:34 +0200514 networkConfigCompletion.whenComplete((value, ex) -> {
515 //setting to null for easier fall through
516 networkConfigCompletion = null;
517 //process all queued events
Charles Chan39b75522018-04-21 00:44:29 -0700518 queuedEvents.forEach(event -> {
Andrea Campanella060cad82018-04-17 12:09:34 +0200519 mainEventExecutor.execute(new InternalEventHandler(event));
520 });
521 });
522
sangho80f11cb2015-04-01 13:05:26 -0700523 log.info("Started");
524 }
525
Saurav Dase6c448a2018-01-18 12:07:33 -0800526 KryoNamespace.Builder createSerializer() {
Jonathan Hart54541d12016-04-12 15:39:44 -0700527 return new KryoNamespace.Builder()
528 .register(KryoNamespaces.API)
Saurav Das261c3002017-06-13 15:35:54 -0700529 .register(DestinationSetNextObjectiveStoreKey.class,
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800530 VlanNextObjectiveStoreKey.class,
531 DestinationSet.class,
Andreas Pantelopoulos92998c92018-05-29 13:11:14 -0700532 DestinationSet.DestinationSetType.class,
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800533 NextNeighbors.class,
534 Tunnel.class,
535 DefaultTunnel.class,
536 Policy.class,
537 TunnelPolicy.class,
538 Policy.Type.class,
539 PortNextObjectiveStoreKey.class,
540 XConnectStoreKey.class,
541 L2Tunnel.class,
542 L2TunnelPolicy.class,
543 DefaultL2Tunnel.class,
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700544 DefaultL2TunnelPolicy.class,
545 DummyVlanIdStoreKey.class
Jonathan Hart54541d12016-04-12 15:39:44 -0700546 );
547 }
548
sangho80f11cb2015-04-01 13:05:26 -0700549 @Deactivate
550 protected void deactivate() {
Charles Chanfbcb8812018-04-18 18:41:05 -0700551 mainEventExecutor.shutdown();
552 hostEventExecutor.shutdown();
553 routeEventExecutor.shutdown();
554 mcastEventExecutor.shutdown();
Charles Chan77cdde42018-05-08 21:35:50 -0700555 packetExecutor.shutdown();
Charles Chanfbcb8812018-04-18 18:41:05 -0700556
Ray Milkeyaee4d3e2018-05-11 09:59:19 -0700557 mainEventExecutor = null;
558 hostEventExecutor = null;
559 routeEventExecutor = null;
560 mcastEventExecutor = null;
561 packetExecutor = null;
562
Charles Chan72f556a2015-10-05 17:50:33 -0700563 cfgService.removeListener(cfgListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700564 cfgService.unregisterConfigFactory(deviceConfigFactory);
565 cfgService.unregisterConfigFactory(appConfigFactory);
Charles Chandebfea32016-10-24 14:52:01 -0700566 cfgService.unregisterConfigFactory(xConnectConfigFactory);
Charles Chanc91c8782016-03-30 17:54:24 -0700567 cfgService.unregisterConfigFactory(mcastConfigFactory);
Charles Chan873661e2017-11-30 15:37:50 -0800568 compCfgService.unregisterProperties(getClass(), false);
Charles Chan72f556a2015-10-05 17:50:33 -0700569
Charles Chanfd48c222017-06-19 00:43:31 -0700570 hostService.removeListener(hostListener);
sangho80f11cb2015-04-01 13:05:26 -0700571 packetService.removeProcessor(processor);
Charles Chan2b078ae2015-10-14 11:24:40 -0700572 linkService.removeListener(linkListener);
573 deviceService.removeListener(deviceListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700574 multicastRouteService.removeListener(mcastListener);
Charles Chandebfea32016-10-24 14:52:01 -0700575 routeService.removeListener(routeListener);
Pier Luigid8a15162018-02-15 16:33:08 +0100576 topologyService.removeListener(topologyListener);
Charles Chanfbcb8812018-04-18 18:41:05 -0700577 mastershipService.removeListener(mastershipListener);
Saurav Das00e553b2018-04-21 17:19:48 -0700578 clusterService.removeListener(clusterListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700579
Charles Chan2e71ef32017-02-23 15:44:08 -0800580 neighbourResolutionService.unregisterNeighbourHandlers(appId);
581
sangho80f11cb2015-04-01 13:05:26 -0700582 processor = null;
Charles Chan2b078ae2015-10-14 11:24:40 -0700583 linkListener = null;
Charles Chanc91c8782016-03-30 17:54:24 -0700584 deviceListener = null;
Charles Chan05bb1702018-04-19 13:10:01 -0700585 groupHandlerMap.forEach((k, v) -> v.shutdown());
Charles Chan2b078ae2015-10-14 11:24:40 -0700586 groupHandlerMap.clear();
Saurav Das49368392018-04-23 18:42:12 -0700587 defaultRoutingHandler.shutdown();
Charles Chan2b078ae2015-10-14 11:24:40 -0700588
Saurav Das261c3002017-06-13 15:35:54 -0700589 dsNextObjStore.destroy();
Charles Chan10b0fb72017-02-02 16:20:42 -0800590 vlanNextObjStore.destroy();
Charles Chanc91c8782016-03-30 17:54:24 -0700591 portNextObjStore.destroy();
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700592 dummyVlanIdStore.destroy();
Charles Chanc91c8782016-03-30 17:54:24 -0700593 tunnelStore.destroy();
594 policyStore.destroy();
Pier Luigi35dab3f2018-01-25 16:16:02 +0100595
596 mcastHandler.terminate();
sangho80f11cb2015-04-01 13:05:26 -0700597 log.info("Stopped");
598 }
599
Charles Chan873661e2017-11-30 15:37:50 -0800600 @Modified
601 private void modified(ComponentContext context) {
602 Dictionary<?, ?> properties = context.getProperties();
603 if (properties == null) {
604 return;
605 }
606
Andreas Pantelopoulos6464d862018-06-18 12:50:35 -0700607 String strActiveProbing = Tools.get(properties, "activeProbing");
608 boolean expectActiveProbing = Boolean.parseBoolean(strActiveProbing);
Charles Chan873661e2017-11-30 15:37:50 -0800609 if (expectActiveProbing != activeProbing) {
610 activeProbing = expectActiveProbing;
611 log.info("{} active probing", activeProbing ? "Enabling" : "Disabling");
612 }
Saurav Dasec683dc2018-04-27 18:42:30 -0700613
614 String strSingleHomedDown = Tools.get(properties, "singleHomedDown");
615 boolean expectSingleHomedDown = Boolean.parseBoolean(strSingleHomedDown);
616 if (expectSingleHomedDown != singleHomedDown) {
617 singleHomedDown = expectSingleHomedDown;
618 log.info("{} downing of single homed hosts for lost uplinks",
619 singleHomedDown ? "Enabling" : "Disabling");
620 if (singleHomedDown && linkHandler != null) {
621 hostService.getHosts().forEach(host -> host.locations()
622 .forEach(loc -> {
623 if (interfaceService.isConfigured(loc)) {
624 linkHandler.checkUplinksForHost(loc);
625 }
626 }));
627 } else {
628 log.warn("Disabling singleHomedDown does not re-enable already "
629 + "downed ports for single-homed hosts");
630 }
631 }
Andreas Pantelopoulos6464d862018-06-18 12:50:35 -0700632
633 String strRespondToUnknownHosts = Tools.get(properties, "respondToUnknownHosts");
634 boolean expectRespondToUnknownHosts = Boolean.parseBoolean(strRespondToUnknownHosts);
635 if (expectRespondToUnknownHosts != respondToUnknownHosts) {
636 respondToUnknownHosts = expectRespondToUnknownHosts;
637 log.info("{} responding to ARPs/NDPs from unknown hosts", respondToUnknownHosts ? "Enabling" : "Disabling");
638 }
Charles Chan4eb73bb2018-07-19 14:55:31 -0700639
Charles Chanfbca55e2018-07-24 16:40:35 -0700640 String strRouteDoubleTaggedHosts = Tools.get(properties, "routeDoubleTaggedHosts");
641 boolean expectRouteDoubleTaggedHosts = Boolean.parseBoolean(strRouteDoubleTaggedHosts);
642 if (expectRouteDoubleTaggedHosts != routeDoubleTaggedHosts) {
643 routeDoubleTaggedHosts = expectRouteDoubleTaggedHosts;
644 log.info("{} routing for double tagged hosts", routeDoubleTaggedHosts ? "Enabling" : "Disabling");
Charles Chan4eb73bb2018-07-19 14:55:31 -0700645
Charles Chanfbca55e2018-07-24 16:40:35 -0700646 if (routeDoubleTaggedHosts) {
Charles Chan4eb73bb2018-07-19 14:55:31 -0700647 hostHandler.populateAllDoubleTaggedHost();
648 } else {
649 hostHandler.revokeAllDoubleTaggedHost();
650 }
651 }
Saurav Das9bf49582018-08-13 15:34:26 -0700652
653 String strDefaultInternalVlan = Tools.get(properties, "defaultInternalVlan");
654 int defIntVlan = Integer.parseInt(strDefaultInternalVlan);
655 if (defIntVlan != defaultInternalVlan) {
656 if (canUseVlanId(defIntVlan)) {
657 log.warn("Default internal vlan value changed from {} to {}.. "
658 + "re-programming filtering rules, but NOT any groups already "
659 + "created with the former value", defaultInternalVlan, defIntVlan);
660 VlanId oldDefIntVlan = VlanId.vlanId((short) defaultInternalVlan);
661 defaultInternalVlan = defIntVlan;
662 routingRulePopulator
663 .updateSpecialVlanFilteringRules(true, oldDefIntVlan,
664 VlanId.vlanId((short) defIntVlan));
665 } else {
666 log.warn("Cannot change default internal vlan to unusable "
667 + "value {}", defIntVlan);
668 }
669 }
670
671 String strPwTxpVlan = Tools.get(properties, "pwTransportVlan");
672 int pwTxpVlan = Integer.parseInt(strPwTxpVlan);
673 if (pwTxpVlan != pwTransportVlan) {
674 if (canUseVlanId(pwTxpVlan)) {
675 log.warn("Pseudowire transport vlan value changed from {} to {}.. "
676 + "re-programming filtering rules, but NOT any groups already "
677 + "created with the former value", pwTransportVlan,
678 pwTxpVlan);
679 VlanId oldPwTxpVlan = VlanId.vlanId((short) pwTransportVlan);
680 pwTransportVlan = pwTxpVlan;
681 routingRulePopulator
682 .updateSpecialVlanFilteringRules(false, oldPwTxpVlan,
683 VlanId.vlanId((short) pwTxpVlan));
684 } else {
685 log.warn("Cannot change pseudowire transport vlan to unusable "
686 + "value {}", pwTxpVlan);
687 }
688 }
689
690 }
691
692 /**
693 * Returns true if given vlan id is not being used in the system currently,
694 * either as one of the default system wide vlans or as one of the
695 * configured interface vlans.
696 *
697 * @param vlanId given vlan id
698 * @return true if vlan is not currently in use
699 */
700 public boolean canUseVlanId(int vlanId) {
701 if (vlanId >= 4095 || vlanId <= 1) {
702 log.error("Vlan id {} value is not in valid range 2 <--> 4094",
703 vlanId);
704 return false;
705 }
706
707 VlanId vid = VlanId.vlanId((short) vlanId);
708 if (getDefaultInternalVlan().equals(vid) || getPwTransportVlan().equals(vid)) {
709 log.warn("Vlan id {} value is already in use system-wide. "
710 + "DefaultInternalVlan:{} PwTransportVlan:{} ", vlanId,
711 getDefaultInternalVlan(), getPwTransportVlan());
712 return false;
713 }
714
715 if (interfaceService.inUse(vid)) {
716 log.warn("Vlan id {} value is already in use on a configured "
717 + "interface in the system", vlanId);
718 return false;
719 }
720 return true;
721 }
722
723 /**
724 * Returns the VlanId assigned internally by default to unconfigured ports.
725 *
726 * @return the default internal vlan id
727 */
728 public VlanId getDefaultInternalVlan() {
729 return VlanId.vlanId((short) defaultInternalVlan);
730 }
731
732 /**
733 * Returns the Vlan id used to transport pseudowire traffic across the
734 * network.
735 *
736 * @return the pseudowire transport vlan id
737 */
738 public VlanId getPwTransportVlan() {
739 return VlanId.vlanId((short) pwTransportVlan);
Charles Chan873661e2017-11-30 15:37:50 -0800740 }
741
sangho27462c62015-05-14 00:39:53 -0700742 @Override
743 public List<Tunnel> getTunnels() {
744 return tunnelHandler.getTunnels();
745 }
746
747 @Override
sanghobd812f82015-06-29 14:58:47 -0700748 public TunnelHandler.Result createTunnel(Tunnel tunnel) {
749 return tunnelHandler.createTunnel(tunnel);
sangho27462c62015-05-14 00:39:53 -0700750 }
751
752 @Override
sanghobd812f82015-06-29 14:58:47 -0700753 public TunnelHandler.Result removeTunnel(Tunnel tunnel) {
sangho27462c62015-05-14 00:39:53 -0700754 for (Policy policy: policyHandler.getPolicies()) {
755 if (policy.type() == Policy.Type.TUNNEL_FLOW) {
756 TunnelPolicy tunnelPolicy = (TunnelPolicy) policy;
757 if (tunnelPolicy.tunnelId().equals(tunnel.id())) {
758 log.warn("Cannot remove the tunnel used by a policy");
sanghobd812f82015-06-29 14:58:47 -0700759 return TunnelHandler.Result.TUNNEL_IN_USE;
sangho27462c62015-05-14 00:39:53 -0700760 }
761 }
762 }
sanghobd812f82015-06-29 14:58:47 -0700763 return tunnelHandler.removeTunnel(tunnel);
sangho27462c62015-05-14 00:39:53 -0700764 }
765
766 @Override
sanghobd812f82015-06-29 14:58:47 -0700767 public PolicyHandler.Result removePolicy(Policy policy) {
768 return policyHandler.removePolicy(policy);
sangho27462c62015-05-14 00:39:53 -0700769 }
770
771 @Override
sanghobd812f82015-06-29 14:58:47 -0700772 public PolicyHandler.Result createPolicy(Policy policy) {
773 return policyHandler.createPolicy(policy);
sangho27462c62015-05-14 00:39:53 -0700774 }
775
776 @Override
777 public List<Policy> getPolicies() {
778 return policyHandler.getPolicies();
779 }
780
Saurav Das07c74602016-04-27 18:35:50 -0700781 @Override
Andreas Pantelopoulosd988c1a2018-03-15 16:56:09 -0700782 public Set<L2TunnelDescription> getL2TunnelDescriptions(boolean pending) {
783 return l2TunnelHandler.getL2Descriptions(pending);
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700784 }
785
786 @Override
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800787 public List<L2Tunnel> getL2Tunnels() {
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700788 return l2TunnelHandler.getL2Tunnels();
789 }
790
791 @Override
Andreas Pantelopoulos4c7de132018-02-22 12:32:42 -0800792 public List<L2TunnelPolicy> getL2Policies() {
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700793 return l2TunnelHandler.getL2Policies();
794 }
795
Saurav Dasdebcf882018-04-06 20:16:01 -0700796 @Override
Andreas Pantelopoulos96851252018-03-20 13:58:49 -0700797 @Deprecated
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700798 public L2TunnelHandler.Result addPseudowiresBulk(List<DefaultL2TunnelDescription> bulkPseudowires) {
799
Andreas Pantelopoulosd988c1a2018-03-15 16:56:09 -0700800 // get both added and pending pseudowires
801 List<L2TunnelDescription> pseudowires = new ArrayList<>();
802 pseudowires.addAll(l2TunnelHandler.getL2Descriptions(false));
803 pseudowires.addAll(l2TunnelHandler.getL2Descriptions(true));
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700804 pseudowires.addAll(bulkPseudowires);
Andreas Pantelopoulosd988c1a2018-03-15 16:56:09 -0700805
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700806 Set<L2TunnelDescription> newPseudowires = new HashSet(bulkPseudowires);
807
Andreas Pantelopoulos96851252018-03-20 13:58:49 -0700808 L2TunnelHandler.Result retRes = L2TunnelHandler.Result.SUCCESS;
809 L2TunnelHandler.Result res;
810 for (DefaultL2TunnelDescription pw : bulkPseudowires) {
811 res = addPseudowire(pw);
812 if (res != L2TunnelHandler.Result.SUCCESS) {
813 log.error("Pseudowire with id {} can not be instantiated !", res);
814 retRes = res;
815 }
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700816 }
Andreas Pantelopoulos96851252018-03-20 13:58:49 -0700817
818 return retRes;
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700819 }
820
821 @Override
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800822 public L2TunnelHandler.Result addPseudowire(L2TunnelDescription l2TunnelDescription) {
Andreas Pantelopoulos87a06102018-03-21 16:44:18 -0700823 return l2TunnelHandler.deployPseudowire(l2TunnelDescription);
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700824 }
825
826 @Override
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -0800827 public L2TunnelHandler.Result removePseudowire(Integer pwId) {
Andreas Pantelopoulos87a06102018-03-21 16:44:18 -0700828 return l2TunnelHandler.tearDownPseudowire(pwId);
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700829 }
830
831 @Override
Saurav Das07c74602016-04-27 18:35:50 -0700832 public void rerouteNetwork() {
833 cfgListener.configureNetwork();
Saurav Das07c74602016-04-27 18:35:50 -0700834 }
835
Charles Chand7844e52016-10-20 17:02:44 -0700836 @Override
Pier Ventreb6a7f342016-11-26 21:05:22 -0800837 public Map<DeviceId, Set<IpPrefix>> getDeviceSubnetMap() {
838 Map<DeviceId, Set<IpPrefix>> deviceSubnetMap = Maps.newHashMap();
Jonathan Hart61e24e12017-11-30 18:23:42 -0800839 deviceConfiguration.getRouters().forEach(device ->
840 deviceSubnetMap.put(device, deviceConfiguration.getSubnets(device)));
Charles Chand7844e52016-10-20 17:02:44 -0700841 return deviceSubnetMap;
842 }
843
Saurav Das62ae6792017-05-15 15:34:25 -0700844
845 @Override
846 public ImmutableMap<DeviceId, EcmpShortestPathGraph> getCurrentEcmpSpg() {
847 if (defaultRoutingHandler != null) {
848 return defaultRoutingHandler.getCurrentEmcpSpgMap();
849 } else {
850 return null;
851 }
852 }
853
854 @Override
Charles Chan0b1dd7e2018-08-19 19:21:46 -0700855 public ImmutableMap<DestinationSetNextObjectiveStoreKey, NextNeighbors> getDstNextObjStore() {
Saurav Das261c3002017-06-13 15:35:54 -0700856 if (dsNextObjStore != null) {
857 return ImmutableMap.copyOf(dsNextObjStore.entrySet());
Saurav Das62ae6792017-05-15 15:34:25 -0700858 } else {
859 return ImmutableMap.of();
860 }
861 }
862
Saurav Dasfbe74572017-08-03 18:30:35 -0700863 @Override
Charles Chan0b1dd7e2018-08-19 19:21:46 -0700864 public ImmutableMap<VlanNextObjectiveStoreKey, Integer> getVlanNextObjStore() {
865 if (vlanNextObjStore != null) {
866 return ImmutableMap.copyOf(vlanNextObjStore.entrySet());
867 } else {
868 return ImmutableMap.of();
869 }
870 }
871
872 @Override
873 public ImmutableMap<PortNextObjectiveStoreKey, Integer> getPortNextObjStore() {
874 if (portNextObjStore != null) {
875 return ImmutableMap.copyOf(portNextObjStore.entrySet());
876 } else {
877 return ImmutableMap.of();
878 }
879 }
880
881 @Override
882 public ImmutableMap<String, NextObjective> getPwInitNext() {
883 if (l2TunnelHandler != null) {
884 return l2TunnelHandler.getInitNext();
885 } else {
886 return ImmutableMap.of();
887 }
888 }
889
890 @Override
891 public ImmutableMap<String, NextObjective> getPwTermNext() {
892 if (l2TunnelHandler != null) {
893 return l2TunnelHandler.getTermNext();
894 } else {
895 return ImmutableMap.of();
896 }
897 }
898
899 @Override
900 public void invalidateNextObj(int nextId) {
901 if (dsNextObjStore != null) {
902 dsNextObjStore.entrySet().forEach(e -> {
903 if (e.getValue().nextId() == nextId) {
904 dsNextObjStore.remove(e.getKey());
905 }
906 });
907 }
908 if (vlanNextObjStore != null) {
909 vlanNextObjStore.entrySet().forEach(e -> {
910 if (e.getValue() == nextId) {
911 vlanNextObjStore.remove(e.getKey());
912 }
913 });
914 }
915 if (portNextObjStore != null) {
916 portNextObjStore.entrySet().forEach(e -> {
917 if (e.getValue() == nextId) {
918 portNextObjStore.remove(e.getKey());
919 }
920 });
921 }
922 if (mcastHandler != null) {
923 mcastHandler.removeNextId(nextId);
924 }
925 if (l2TunnelHandler != null) {
926 l2TunnelHandler.removeNextId(nextId);
927 }
928 if (xconnectService != null) {
929 xconnectService.removeNextId(nextId);
930 }
931 }
932
933 @Override
Saurav Dasfbe74572017-08-03 18:30:35 -0700934 public void verifyGroups(DeviceId id) {
935 DefaultGroupHandler gh = groupHandlerMap.get(id);
936 if (gh != null) {
937 gh.triggerBucketCorrector();
938 }
939 }
940
Saurav Das6430f412018-01-25 09:49:01 -0800941 @Override
942 public ImmutableMap<Link, Boolean> getSeenLinks() {
943 return linkHandler.getSeenLinks();
944 }
945
946 @Override
947 public ImmutableMap<DeviceId, Set<PortNumber>> getDownedPortState() {
948 return linkHandler.getDownedPorts();
949 }
950
Pier Luigi0f9635b2018-01-15 18:06:43 +0100951 @Override
952 public Map<McastStoreKey, Integer> getMcastNextIds(IpAddress mcastIp) {
Charles Chan0b1dd7e2018-08-19 19:21:46 -0700953 return mcastHandler.getNextIds(mcastIp);
Pier Luigi0f9635b2018-01-15 18:06:43 +0100954 }
955
956 @Override
Pier Luigi69f774d2018-02-28 12:10:50 +0100957 public Map<McastStoreKey, McastRole> getMcastRoles(IpAddress mcastIp) {
Pier Luigi0f9635b2018-01-15 18:06:43 +0100958 return mcastHandler.getMcastRoles(mcastIp);
959 }
960
961 @Override
Piere99511d2018-04-19 16:47:06 +0200962 public Map<McastRoleStoreKey, McastRole> getMcastRoles(IpAddress mcastIp, ConnectPoint sourcecp) {
963 return mcastHandler.getMcastRoles(mcastIp, sourcecp);
964 }
965
966 @Override
Pier Luigi0f9635b2018-01-15 18:06:43 +0100967 public Map<ConnectPoint, List<ConnectPoint>> getMcastPaths(IpAddress mcastIp) {
968 return mcastHandler.getMcastPaths(mcastIp);
969 }
970
Pierdb27b8d2018-04-17 16:29:56 +0200971 @Override
Pier71c55772018-04-17 17:25:22 +0200972 public Multimap<ConnectPoint, List<ConnectPoint>> getMcastTrees(IpAddress mcastIp,
973 ConnectPoint sourcecp) {
974 return mcastHandler.getMcastTrees(mcastIp, sourcecp);
975 }
976
977 @Override
Pierdb27b8d2018-04-17 16:29:56 +0200978 public Map<IpAddress, NodeId> getMcastLeaders(IpAddress mcastIp) {
979 return mcastHandler.getMcastLeaders(mcastIp);
980 }
981
Charles Chanb13e0702018-04-17 18:56:53 -0700982 @Override
983 public Map<Set<DeviceId>, NodeId> getShouldProgram() {
984 return defaultRoutingHandler == null ? ImmutableMap.of() :
985 ImmutableMap.copyOf(defaultRoutingHandler.shouldProgram);
986 }
987
988 @Override
989 public Map<DeviceId, Boolean> getShouldProgramCache() {
990 return defaultRoutingHandler == null ? ImmutableMap.of() :
991 ImmutableMap.copyOf(defaultRoutingHandler.shouldProgramCache);
992 }
993
Charles Chan8d316332018-06-19 20:31:57 -0700994 @Override
Ray Milkeyb85de082017-04-05 09:42:04 -0700995 public ApplicationId appId() {
996 return appId;
997 }
998
999 /**
1000 * Returns the device configuration.
1001 *
1002 * @return device configuration
1003 */
1004 public DeviceConfiguration deviceConfiguration() {
1005 return deviceConfiguration;
1006 }
1007
1008 /**
Saurav Das261c3002017-06-13 15:35:54 -07001009 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan53de91f2017-08-22 15:07:34 -07001010 * Used to keep track on MPLS group information.
Ray Milkeyb85de082017-04-05 09:42:04 -07001011 *
1012 * @return next objective ID store
1013 */
Saurav Das261c3002017-06-13 15:35:54 -07001014 public EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
1015 dsNextObjStore() {
1016 return dsNextObjStore;
Ray Milkeyb85de082017-04-05 09:42:04 -07001017 }
1018
1019 /**
Charles Chan53de91f2017-08-22 15:07:34 -07001020 * Per device next objective ID store with (device id + vlanid) as key.
1021 * Used to keep track on L2 flood group information.
Ray Milkeyb85de082017-04-05 09:42:04 -07001022 *
1023 * @return vlan next object store
1024 */
1025 public EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer> vlanNextObjStore() {
1026 return vlanNextObjStore;
1027 }
1028
1029 /**
Charles Chan53de91f2017-08-22 15:07:34 -07001030 * Per device next objective ID store with (device id + port + treatment + meta) as key.
1031 * Used to keep track on L2 interface group and L3 unicast group information.
Ray Milkeyb85de082017-04-05 09:42:04 -07001032 *
1033 * @return port next object store.
1034 */
1035 public EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer> portNextObjStore() {
1036 return portNextObjStore;
1037 }
1038
1039 /**
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001040 * Per port dummy VLAN ID store with (connect point + ip address) as key.
1041 * Used to keep track on dummy VLAN ID allocation.
1042 *
1043 * @return dummy vlan id store.
1044 */
1045 public EventuallyConsistentMap<DummyVlanIdStoreKey, VlanId> dummyVlanIdStore() {
1046 return dummyVlanIdStore;
1047 }
1048
1049 /**
Saurav Das261c3002017-06-13 15:35:54 -07001050 * Returns the MPLS-ECMP configuration which indicates whether ECMP on
1051 * labeled packets should be programmed or not.
Pier Ventre7a78de22016-10-31 15:00:01 -07001052 *
1053 * @return MPLS-ECMP value
1054 */
1055 public boolean getMplsEcmp() {
1056 SegmentRoutingAppConfig segmentRoutingAppConfig = cfgService
1057 .getConfig(this.appId, SegmentRoutingAppConfig.class);
1058 return segmentRoutingAppConfig != null && segmentRoutingAppConfig.mplsEcmp();
1059 }
1060
1061 /**
sangho80f1f892015-05-19 11:57:42 -07001062 * Returns the tunnel object with the tunnel ID.
1063 *
1064 * @param tunnelId Tunnel ID
1065 * @return Tunnel reference
1066 */
sangho27462c62015-05-14 00:39:53 -07001067 public Tunnel getTunnel(String tunnelId) {
1068 return tunnelHandler.getTunnel(tunnelId);
1069 }
1070
Charles Chan8d316332018-06-19 20:31:57 -07001071 @Override
Pier Luigi69f774d2018-02-28 12:10:50 +01001072 public VlanId getInternalVlanId(ConnectPoint connectPoint) {
Charles Chan098ca202018-05-01 11:50:20 -07001073 VlanId untaggedVlanId = interfaceService.getUntaggedVlanId(connectPoint);
1074 VlanId nativeVlanId = interfaceService.getNativeVlanId(connectPoint);
Charles Chand9265a32017-06-16 15:19:24 -07001075 return untaggedVlanId != null ? untaggedVlanId : nativeVlanId;
1076 }
1077
Charles Chan8d316332018-06-19 20:31:57 -07001078 @Override
1079 public Optional<DeviceId> getPairDeviceId(DeviceId deviceId) {
Charles Chan3ed34d82017-06-22 18:03:14 -07001080 SegmentRoutingDeviceConfig deviceConfig =
1081 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
1082 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairDeviceId);
1083 }
Charles Chan8d316332018-06-19 20:31:57 -07001084
1085 @Override
Saurav Dasec683dc2018-04-27 18:42:30 -07001086 public Optional<PortNumber> getPairLocalPort(DeviceId deviceId) {
Charles Chan3ed34d82017-06-22 18:03:14 -07001087 SegmentRoutingDeviceConfig deviceConfig =
1088 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
1089 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairLocalPort);
1090 }
1091
1092 /**
Charles Chanf0ae41e2017-08-23 13:55:39 -07001093 * Returns locations of given resolved route.
1094 *
1095 * @param resolvedRoute resolved route
1096 * @return locations of nexthop. Might be empty if next hop is not found
1097 */
1098 Set<ConnectPoint> nextHopLocations(ResolvedRoute resolvedRoute) {
1099 HostId hostId = HostId.hostId(resolvedRoute.nextHopMac(), resolvedRoute.nextHopVlan());
1100 return Optional.ofNullable(hostService.getHost(hostId))
1101 .map(Host::locations).orElse(Sets.newHashSet())
1102 .stream().map(l -> (ConnectPoint) l).collect(Collectors.toSet());
1103 }
1104
1105 /**
Charles Chan90772a72017-02-08 15:52:08 -08001106 * Returns vlan port map of given device.
1107 *
1108 * @param deviceId device id
1109 * @return vlan-port multimap
1110 */
1111 public Multimap<VlanId, PortNumber> getVlanPortMap(DeviceId deviceId) {
1112 HashMultimap<VlanId, PortNumber> vlanPortMap = HashMultimap.create();
1113
1114 interfaceService.getInterfaces().stream()
1115 .filter(intf -> intf.connectPoint().deviceId().equals(deviceId))
1116 .forEach(intf -> {
1117 vlanPortMap.put(intf.vlanUntagged(), intf.connectPoint().port());
Charles Chan3ed34d82017-06-22 18:03:14 -07001118 intf.vlanTagged().forEach(vlanTagged ->
1119 vlanPortMap.put(vlanTagged, intf.connectPoint().port())
1120 );
Charles Chan90772a72017-02-08 15:52:08 -08001121 vlanPortMap.put(intf.vlanNative(), intf.connectPoint().port());
1122 });
1123 vlanPortMap.removeAll(VlanId.NONE);
1124
1125 return vlanPortMap;
1126 }
1127
1128 /**
Charles Chan10b0fb72017-02-02 16:20:42 -08001129 * Returns the next objective ID for the given vlan id. It is expected
Saurav Das2d94d312015-11-24 23:21:05 -08001130 * that the next-objective has been pre-created from configuration.
Charles Chan77277672015-10-20 16:24:19 -07001131 *
1132 * @param deviceId Device ID
Charles Chan10b0fb72017-02-02 16:20:42 -08001133 * @param vlanId VLAN ID
Saurav Das2d94d312015-11-24 23:21:05 -08001134 * @return next objective ID or -1 if it was not found
Charles Chan77277672015-10-20 16:24:19 -07001135 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001136 int getVlanNextObjectiveId(DeviceId deviceId, VlanId vlanId) {
Charles Chan77277672015-10-20 16:24:19 -07001137 if (groupHandlerMap.get(deviceId) != null) {
Charles Chan10b0fb72017-02-02 16:20:42 -08001138 log.trace("getVlanNextObjectiveId query in device {}", deviceId);
1139 return groupHandlerMap.get(deviceId).getVlanNextObjectiveId(vlanId);
Charles Chan77277672015-10-20 16:24:19 -07001140 } else {
Charles Chan10b0fb72017-02-02 16:20:42 -08001141 log.warn("getVlanNextObjectiveId query - groupHandler for "
Saurav Das2d94d312015-11-24 23:21:05 -08001142 + "device {} not found", deviceId);
1143 return -1;
1144 }
1145 }
1146
1147 /**
1148 * Returns the next objective ID for the given portNumber, given the treatment.
1149 * There could be multiple different treatments to the same outport, which
Saurav Das2cb38292017-03-29 19:09:17 -07001150 * would result in different objectives. If the next object does not exist,
1151 * and should be created, a new one is created and its id is returned.
Saurav Das2d94d312015-11-24 23:21:05 -08001152 *
1153 * @param deviceId Device ID
1154 * @param portNum port number on device for which NextObjective is queried
1155 * @param treatment the actions to apply on the packets (should include outport)
1156 * @param meta metadata passed into the creation of a Next Objective if necessary
Saurav Das2cb38292017-03-29 19:09:17 -07001157 * @param createIfMissing true if a next object should be created if not found
Saurav Das07c74602016-04-27 18:35:50 -07001158 * @return next objective ID or -1 if an error occurred during retrieval or creation
Saurav Das2d94d312015-11-24 23:21:05 -08001159 */
1160 public int getPortNextObjectiveId(DeviceId deviceId, PortNumber portNum,
1161 TrafficTreatment treatment,
Saurav Das2cb38292017-03-29 19:09:17 -07001162 TrafficSelector meta,
1163 boolean createIfMissing) {
Saurav Das2d94d312015-11-24 23:21:05 -08001164 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
1165 if (ghdlr != null) {
Saurav Das2cb38292017-03-29 19:09:17 -07001166 return ghdlr.getPortNextObjectiveId(portNum, treatment, meta, createIfMissing);
Saurav Das2d94d312015-11-24 23:21:05 -08001167 } else {
Charles Chanb7f75ac2016-01-11 18:28:54 -08001168 log.warn("getPortNextObjectiveId query - groupHandler for device {}"
1169 + " not found", deviceId);
1170 return -1;
1171 }
1172 }
1173
Saurav Das62ae6792017-05-15 15:34:25 -07001174 /**
1175 * Returns the group handler object for the specified device id.
1176 *
1177 * @param devId the device identifier
1178 * @return the groupHandler object for the device id, or null if not found
1179 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001180 DefaultGroupHandler getGroupHandler(DeviceId devId) {
Saurav Das62ae6792017-05-15 15:34:25 -07001181 return groupHandlerMap.get(devId);
1182 }
1183
1184 /**
Saurav Dasfbe74572017-08-03 18:30:35 -07001185 * Returns the default routing handler object.
1186 *
1187 * @return the default routing handler object
1188 */
1189 public DefaultRoutingHandler getRoutingHandler() {
1190 return defaultRoutingHandler;
1191 }
1192
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001193 /**
1194 * Returns new dummy VLAN ID.
1195 * Dummy VLAN ID should be unique in each connect point.
1196 *
1197 * @param cp connect point
1198 * @param ipAddress IP address
1199 * @return new dummy VLAN ID. Returns VlanId.NONE if no VLAN ID is available.
1200 */
1201 public synchronized VlanId allocateDummyVlanId(ConnectPoint cp, IpAddress ipAddress) {
1202 Set<VlanId> usedVlanId = Sets.union(getVlanPortMap(cp.deviceId()).keySet(),
1203 dummyVlanIdStore.entrySet().stream().filter(entry ->
1204 (entry.getKey()).connectPoint().equals(cp))
1205 .map(Map.Entry::getValue)
1206 .collect(Collectors.toSet()));
1207
1208 VlanId dummyVlanId = IntStream.range(MIN_DUMMY_VLAN_ID, MAX_DUMMY_VLAN_ID).mapToObj(
1209 i -> VlanId.vlanId((short) (i & 0xFFFF))
1210 ).filter(vlanId -> !usedVlanId.contains(vlanId)).findFirst().orElse(VlanId.NONE);
1211
1212 if (!dummyVlanId.equals(VlanId.NONE)) {
1213 this.dummyVlanIdStore.put(new DummyVlanIdStoreKey(cp, ipAddress), dummyVlanId);
1214 log.debug("Dummy VLAN ID {} is allocated to {}, {}", dummyVlanId, cp, ipAddress);
1215 } else {
1216 log.error("Failed to allocate dummy VLAN ID for {}, {}", cp, ipAddress);
1217 }
1218 return dummyVlanId;
1219 }
1220
1221
sangho80f11cb2015-04-01 13:05:26 -07001222 private class InternalPacketProcessor implements PacketProcessor {
sangho80f11cb2015-04-01 13:05:26 -07001223 @Override
1224 public void process(PacketContext context) {
Charles Chan77cdde42018-05-08 21:35:50 -07001225 packetExecutor.execute(() -> processPacketInternal(context));
1226 }
sangho80f11cb2015-04-01 13:05:26 -07001227
Charles Chan77cdde42018-05-08 21:35:50 -07001228 private void processPacketInternal(PacketContext context) {
sangho80f11cb2015-04-01 13:05:26 -07001229 if (context.isHandled()) {
1230 return;
1231 }
1232
1233 InboundPacket pkt = context.inPacket();
1234 Ethernet ethernet = pkt.parsed();
Pier Luigi37a35432017-02-01 13:50:04 -08001235
1236 if (ethernet == null) {
1237 return;
1238 }
1239
Saurav Das261c3002017-06-13 15:35:54 -07001240 log.trace("Rcvd pktin from {}: {}", context.inPacket().receivedFrom(),
1241 ethernet);
Pier Ventreadb4ae62016-11-23 09:57:42 -08001242 if (ethernet.getEtherType() == TYPE_ARP) {
Saurav Das62ae6792017-05-15 15:34:25 -07001243 log.warn("Received unexpected ARP packet on {}",
1244 context.inPacket().receivedFrom());
Saurav Das368cf212017-03-15 15:15:14 -07001245 log.trace("{}", ethernet);
Pier Ventre6b2c1b32016-12-09 17:26:04 -08001246 return;
sangho80f11cb2015-04-01 13:05:26 -07001247 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV4) {
Pier Ventreb6b81d52016-12-02 08:16:05 -08001248 IPv4 ipv4Packet = (IPv4) ethernet.getPayload();
1249 //ipHandler.addToPacketBuffer(ipv4Packet);
1250 if (ipv4Packet.getProtocol() == IPv4.PROTOCOL_ICMP) {
1251 icmpHandler.processIcmp(ethernet, pkt.receivedFrom());
sangho80f11cb2015-04-01 13:05:26 -07001252 } else {
Charles Chand041ad82017-01-13 17:20:44 -08001253 // NOTE: We don't support IP learning at this moment so this
1254 // is not necessary. Also it causes duplication of DHCP packets.
Pier Ventre6b2c1b32016-12-09 17:26:04 -08001255 // ipHandler.processPacketIn(ipv4Packet, pkt.receivedFrom());
sangho80f11cb2015-04-01 13:05:26 -07001256 }
Pier Ventreb6a7f342016-11-26 21:05:22 -08001257 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV6) {
1258 IPv6 ipv6Packet = (IPv6) ethernet.getPayload();
Pier Ventreb6b81d52016-12-02 08:16:05 -08001259 //ipHandler.addToPacketBuffer(ipv6Packet);
Pier Luigi37a35432017-02-01 13:50:04 -08001260 // We deal with the packet only if the packet is a ICMP6 ECHO/REPLY
Pier Ventreb6b81d52016-12-02 08:16:05 -08001261 if (ipv6Packet.getNextHeader() == IPv6.PROTOCOL_ICMP6) {
1262 ICMP6 icmp6Packet = (ICMP6) ipv6Packet.getPayload();
1263 if (icmp6Packet.getIcmpType() == ICMP6.ECHO_REQUEST ||
1264 icmp6Packet.getIcmpType() == ICMP6.ECHO_REPLY) {
1265 icmpHandler.processIcmpv6(ethernet, pkt.receivedFrom());
1266 } else {
Saurav Das62ae6792017-05-15 15:34:25 -07001267 log.trace("Received ICMPv6 0x{} - not handled",
Charles Chand3727b72017-03-13 13:10:30 -07001268 Integer.toHexString(icmp6Packet.getIcmpType() & 0xff));
Pier Ventreb6b81d52016-12-02 08:16:05 -08001269 }
1270 } else {
1271 // NOTE: We don't support IP learning at this moment so this
1272 // is not necessary. Also it causes duplication of DHCPv6 packets.
1273 // ipHandler.processPacketIn(ipv6Packet, pkt.receivedFrom());
1274 }
sangho80f11cb2015-04-01 13:05:26 -07001275 }
1276 }
1277 }
1278
sangho80f11cb2015-04-01 13:05:26 -07001279 private class InternalEventHandler implements Runnable {
Charles Chan52003922018-04-05 16:31:15 -07001280 private Event event;
1281
1282 InternalEventHandler(Event event) {
1283 this.event = event;
1284 }
1285
Srikanth Vavilapalli37a461b2015-04-07 15:12:32 -07001286 @Override
sangho80f11cb2015-04-01 13:05:26 -07001287 public void run() {
Charles Chan52003922018-04-05 16:31:15 -07001288 try {
1289 // TODO We should also change SR routing and PW to listen to TopologyEvents
1290 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1291 event.type() == LinkEvent.Type.LINK_UPDATED) {
1292 linkHandler.processLinkAdded((Link) event.subject());
1293 } else if (event.type() == LinkEvent.Type.LINK_REMOVED) {
1294 linkHandler.processLinkRemoved((Link) event.subject());
1295 } else if (event.type() == DeviceEvent.Type.DEVICE_ADDED ||
1296 event.type() == DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED ||
1297 event.type() == DeviceEvent.Type.DEVICE_UPDATED) {
1298 DeviceId deviceId = ((Device) event.subject()).id();
1299 if (deviceService.isAvailable(deviceId)) {
1300 log.info("** DEVICE UP Processing device event {} "
1301 + "for available device {}",
1302 event.type(), ((Device) event.subject()).id());
1303 processDeviceAdded((Device) event.subject());
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001304 } else {
Charles Chanb8f3af52018-08-29 21:21:51 -07001305 if (event.type() == DeviceEvent.Type.DEVICE_ADDED) {
1306 // Note: For p4 devices, the device will be added but unavailable at the beginning.
1307 // The device will later on being marked as available once the pipeline is pushed
1308 // to the device.
1309 log.info("** DEVICE ADDED but unavailable. Ignore");
1310 return;
1311 }
Charles Chan52003922018-04-05 16:31:15 -07001312 log.info(" ** DEVICE DOWN Processing device event {}"
1313 + " for unavailable device {}",
1314 event.type(), ((Device) event.subject()).id());
1315 processDeviceRemoved((Device) event.subject());
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001316 }
Charles Chan52003922018-04-05 16:31:15 -07001317 } else if (event.type() == DeviceEvent.Type.PORT_ADDED) {
1318 // typically these calls come when device is added first time
1319 // so port filtering rules are handled at the device_added event.
1320 // port added calls represent all ports on the device,
1321 // enabled or not.
1322 log.trace("** PORT ADDED {}/{} -> {}",
1323 ((DeviceEvent) event).subject().id(),
1324 ((DeviceEvent) event).port().number(),
1325 event.type());
1326 } else if (event.type() == DeviceEvent.Type.PORT_UPDATED) {
1327 // these calls happen for every subsequent event
1328 // ports enabled, disabled, switch goes away, comes back
1329 log.info("** PORT UPDATED {}/{} -> {}",
1330 event.subject(),
1331 ((DeviceEvent) event).port(),
1332 event.type());
Saurav Dasec683dc2018-04-27 18:42:30 -07001333 processPortUpdatedInternal(((Device) event.subject()),
Charles Chan52003922018-04-05 16:31:15 -07001334 ((DeviceEvent) event).port());
1335 } else if (event.type() == TopologyEvent.Type.TOPOLOGY_CHANGED) {
1336 // Process topology event, needed for all modules relying on
1337 // topology service for path computation
1338 TopologyEvent topologyEvent = (TopologyEvent) event;
1339 log.info("Processing topology event {}, topology age {}, reasons {}",
1340 event.type(), topologyEvent.subject().time(),
1341 topologyEvent.reasons().size());
1342 topologyHandler.processTopologyChange(topologyEvent.reasons());
1343 } else if (event.type() == HostEvent.Type.HOST_ADDED) {
1344 hostHandler.processHostAddedEvent((HostEvent) event);
1345 } else if (event.type() == HostEvent.Type.HOST_MOVED) {
1346 hostHandler.processHostMovedEvent((HostEvent) event);
1347 routeHandler.processHostMovedEvent((HostEvent) event);
1348 } else if (event.type() == HostEvent.Type.HOST_REMOVED) {
1349 hostHandler.processHostRemovedEvent((HostEvent) event);
1350 } else if (event.type() == HostEvent.Type.HOST_UPDATED) {
1351 hostHandler.processHostUpdatedEvent((HostEvent) event);
1352 } else if (event.type() == RouteEvent.Type.ROUTE_ADDED) {
1353 routeHandler.processRouteAdded((RouteEvent) event);
1354 } else if (event.type() == RouteEvent.Type.ROUTE_UPDATED) {
1355 routeHandler.processRouteUpdated((RouteEvent) event);
1356 } else if (event.type() == RouteEvent.Type.ROUTE_REMOVED) {
1357 routeHandler.processRouteRemoved((RouteEvent) event);
1358 } else if (event.type() == RouteEvent.Type.ALTERNATIVE_ROUTES_CHANGED) {
1359 routeHandler.processAlternativeRoutesChanged((RouteEvent) event);
1360 } else if (event.type() == McastEvent.Type.SOURCES_ADDED ||
1361 event.type() == McastEvent.Type.SOURCES_REMOVED ||
1362 event.type() == McastEvent.Type.SINKS_ADDED ||
1363 event.type() == McastEvent.Type.SINKS_REMOVED ||
1364 event.type() == McastEvent.Type.ROUTE_ADDED ||
1365 event.type() == McastEvent.Type.ROUTE_REMOVED) {
1366 mcastHandler.processMcastEvent((McastEvent) event);
1367 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED) {
1368 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1369 Class configClass = netcfgEvent.configClass();
1370 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1371 appCfgHandler.processAppConfigAdded(netcfgEvent);
1372 log.info("App config event .. configuring network");
1373 cfgListener.configureNetwork();
1374 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1375 log.info("Segment Routing Device Config added for {}", event.subject());
1376 cfgListener.configureNetwork();
1377 } else if (configClass.equals(XConnectConfig.class)) {
1378 xConnectHandler.processXConnectConfigAdded(netcfgEvent);
1379 } else if (configClass.equals(InterfaceConfig.class)) {
1380 log.info("Interface Config added for {}", event.subject());
1381 cfgListener.configureNetwork();
1382 } else {
1383 log.error("Unhandled config class: {}", configClass);
1384 }
1385 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED) {
1386 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1387 Class configClass = netcfgEvent.configClass();
1388 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1389 appCfgHandler.processAppConfigUpdated(netcfgEvent);
1390 log.info("App config event .. configuring network");
1391 cfgListener.configureNetwork();
1392 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1393 log.info("Segment Routing Device Config updated for {}", event.subject());
1394 createOrUpdateDeviceConfiguration();
1395 } else if (configClass.equals(XConnectConfig.class)) {
1396 xConnectHandler.processXConnectConfigUpdated(netcfgEvent);
1397 } else if (configClass.equals(InterfaceConfig.class)) {
1398 log.info("Interface Config updated for {}", event.subject());
1399 createOrUpdateDeviceConfiguration();
1400 updateInterface((InterfaceConfig) netcfgEvent.config().get(),
1401 (InterfaceConfig) netcfgEvent.prevConfig().get());
1402 } else {
1403 log.error("Unhandled config class: {}", configClass);
1404 }
1405 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_REMOVED) {
1406 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1407 Class configClass = netcfgEvent.configClass();
1408 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1409 appCfgHandler.processAppConfigRemoved(netcfgEvent);
1410 log.info("App config event .. configuring network");
1411 cfgListener.configureNetwork();
1412 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1413 // TODO Handle sr device config removal
1414 log.info("SegmentRoutingDeviceConfig removal is not handled in current implementation");
1415 } else if (configClass.equals(XConnectConfig.class)) {
1416 xConnectHandler.processXConnectConfigRemoved(netcfgEvent);
1417 } else if (configClass.equals(InterfaceConfig.class)) {
1418 // TODO Handle interface removal
1419 log.info("InterfaceConfig removal is not handled in current implementation");
1420 } else {
1421 log.error("Unhandled config class: {}", configClass);
1422 }
Saurav Das00e553b2018-04-21 17:19:48 -07001423 } else if (event.type() == MastershipEvent.Type.MASTER_CHANGED) {
1424 MastershipEvent me = (MastershipEvent) event;
1425 DeviceId deviceId = me.subject();
1426 Optional<DeviceId> pairDeviceId = getPairDeviceId(deviceId);
1427 log.info(" ** MASTERSHIP CHANGED Invalidating shouldProgram cache"
1428 + " for {}/pair={} due to change", deviceId, pairDeviceId);
1429 defaultRoutingHandler.invalidateShouldProgramCache(deviceId);
1430 pairDeviceId.ifPresent(defaultRoutingHandler::invalidateShouldProgramCache);
1431 defaultRoutingHandler.checkFullRerouteForMasterChange(deviceId, me);
Charles Chan52003922018-04-05 16:31:15 -07001432 } else {
1433 log.warn("Unhandled event type: {}", event.type());
sangho80f11cb2015-04-01 13:05:26 -07001434 }
Charles Chan52003922018-04-05 16:31:15 -07001435 } catch (Exception e) {
1436 log.error("SegmentRouting event handler thread thrown an exception: {}",
1437 e.getMessage(), e);
sangho80f11cb2015-04-01 13:05:26 -07001438 }
sangho80f11cb2015-04-01 13:05:26 -07001439 }
1440 }
1441
Saurav Dase6c448a2018-01-18 12:07:33 -08001442 void processDeviceAdded(Device device) {
Saurav Dasb149be12016-06-07 10:08:06 -07001443 log.info("** DEVICE ADDED with ID {}", device.id());
Charles Chan9bd6aea2017-06-27 18:48:32 -07001444
1445 // NOTE: Punt ARP/NDP even when the device is not configured.
1446 // Host learning without network config is required for CORD config generator.
1447 routingRulePopulator.populateIpPunts(device.id());
1448 routingRulePopulator.populateArpNdpPunts(device.id());
1449
Charles Chan319d1a22015-11-03 10:42:14 -08001450 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
Saurav Das261c3002017-06-13 15:35:54 -07001451 log.warn("Device configuration unavailable. Device {} will be "
1452 + "processed after configuration.", device.id());
Saurav Das8ec0ec42015-11-03 14:39:27 -08001453 return;
1454 }
Charles Chan72779502016-04-23 17:36:10 -07001455 processDeviceAddedInternal(device.id());
1456 }
1457
1458 private void processDeviceAddedInternal(DeviceId deviceId) {
Saurav Dasc28b3432015-10-30 17:45:38 -07001459 // Irrespective of whether the local is a MASTER or not for this device,
1460 // we need to create a SR-group-handler instance. This is because in a
1461 // multi-instance setup, any instance can initiate forwarding/next-objectives
1462 // for any switch (even if this instance is a SLAVE or not even connected
1463 // to the switch). To handle this, a default-group-handler instance is necessary
1464 // per switch.
Charles Chan72779502016-04-23 17:36:10 -07001465 log.debug("Current groupHandlerMap devs: {}", groupHandlerMap.keySet());
1466 if (groupHandlerMap.get(deviceId) == null) {
Charles Chan319d1a22015-11-03 10:42:14 -08001467 DefaultGroupHandler groupHandler;
1468 try {
1469 groupHandler = DefaultGroupHandler.
Charles Chan72779502016-04-23 17:36:10 -07001470 createGroupHandler(deviceId,
1471 appId,
1472 deviceConfiguration,
1473 linkService,
1474 flowObjectiveService,
1475 this);
Charles Chan319d1a22015-11-03 10:42:14 -08001476 } catch (DeviceConfigNotFoundException e) {
1477 log.warn(e.getMessage() + " Aborting processDeviceAdded.");
1478 return;
1479 }
Saurav Das2b6a00f2017-12-05 15:00:23 -08001480 log.debug("updating groupHandlerMap with new grpHdlr for device: {}",
Charles Chan72779502016-04-23 17:36:10 -07001481 deviceId);
1482 groupHandlerMap.put(deviceId, groupHandler);
Saurav Das8ec0ec42015-11-03 14:39:27 -08001483 }
Saurav Dasb149be12016-06-07 10:08:06 -07001484
Charles Chan72779502016-04-23 17:36:10 -07001485 if (mastershipService.isLocalMaster(deviceId)) {
Saurav Dasf9332192017-02-18 14:05:44 -08001486 defaultRoutingHandler.populatePortAddressingRules(deviceId);
Charles Chan82f19972016-05-17 13:13:55 -07001487 xConnectHandler.init(deviceId);
Charles Chan72779502016-04-23 17:36:10 -07001488 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
Charles Chan10b0fb72017-02-02 16:20:42 -08001489 groupHandler.createGroupsFromVlanConfig();
Charles Chan72779502016-04-23 17:36:10 -07001490 routingRulePopulator.populateSubnetBroadcastRule(deviceId);
Charles Chan77277672015-10-20 16:24:19 -07001491 }
Charles Chan82ab1932016-01-30 23:22:37 -08001492
Charles Chandebfea32016-10-24 14:52:01 -07001493 appCfgHandler.init(deviceId);
Charles Chan074fae62018-04-29 18:11:37 -07001494 hostEventExecutor.execute(() -> hostHandler.init(deviceId));
1495 routeEventExecutor.execute(() -> routeHandler.init(deviceId));
sangho80f11cb2015-04-01 13:05:26 -07001496 }
1497
Saurav Dasc3604f12016-03-23 11:22:49 -07001498 private void processDeviceRemoved(Device device) {
Saurav Das261c3002017-06-13 15:35:54 -07001499 dsNextObjStore.entrySet().stream()
Saurav Dasc3604f12016-03-23 11:22:49 -07001500 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan873661e2017-11-30 15:37:50 -08001501 .forEach(entry -> dsNextObjStore.remove(entry.getKey()));
Charles Chan10b0fb72017-02-02 16:20:42 -08001502 vlanNextObjStore.entrySet().stream()
Saurav Dasc3604f12016-03-23 11:22:49 -07001503 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan3ed34d82017-06-22 18:03:14 -07001504 .forEach(entry -> vlanNextObjStore.remove(entry.getKey()));
Saurav Dasc3604f12016-03-23 11:22:49 -07001505 portNextObjStore.entrySet().stream()
1506 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan3ed34d82017-06-22 18:03:14 -07001507 .forEach(entry -> portNextObjStore.remove(entry.getKey()));
Saurav Dase6c448a2018-01-18 12:07:33 -08001508 linkHandler.processDeviceRemoved(device);
Charles Chan17d75d82017-06-15 00:44:51 -07001509
Saurav Dasfbe74572017-08-03 18:30:35 -07001510 DefaultGroupHandler gh = groupHandlerMap.remove(device.id());
1511 if (gh != null) {
1512 gh.shutdown();
1513 }
Saurav Das62ae6792017-05-15 15:34:25 -07001514 // Note that a switch going down is associated with all of its links
1515 // going down as well, but it is treated as a single switch down event
Saurav Dasdebcf882018-04-06 20:16:01 -07001516 // while the link-downs are ignored. We cannot rely on the ordering of
1517 // events - i.e we cannot expect all link-downs to come before the
1518 // switch down - so we purge all seen-links for the switch before
1519 // handling route-path changes for the switch-down
Saurav Das62ae6792017-05-15 15:34:25 -07001520 defaultRoutingHandler
Saurav Dasdc7f2752018-03-18 21:28:15 -07001521 .populateRoutingRulesForLinkStatusChange(null, null, device.id(), true);
Saurav Das6430f412018-01-25 09:49:01 -08001522 defaultRoutingHandler.purgeEcmpGraph(device.id());
Charles Chan82f19972016-05-17 13:13:55 -07001523 xConnectHandler.removeDevice(device.id());
Saurav Das97241862018-02-14 14:14:54 -08001524
1525 // Cleanup all internal groupHandler stores for this device. Should be
1526 // done after all rerouting or rehashing has been completed
1527 groupHandlerMap.entrySet()
1528 .forEach(entry -> entry.getValue().cleanUpForNeighborDown(device.id()));
Saurav Dasc3604f12016-03-23 11:22:49 -07001529 }
1530
Saurav Das49368392018-04-23 18:42:12 -07001531 /**
1532 * Purge the destinationSet nextObjective store of entries with this device
1533 * as key. Erases app-level knowledge of hashed groups in this device.
1534 *
1535 * @param devId the device identifier
1536 */
Saurav Das00e553b2018-04-21 17:19:48 -07001537 void purgeHashedNextObjectiveStore(DeviceId devId) {
Saurav Das49368392018-04-23 18:42:12 -07001538 log.debug("Purging hashed next-obj store for dev:{}", devId);
Saurav Das00e553b2018-04-21 17:19:48 -07001539 dsNextObjStore.entrySet().stream()
1540 .filter(entry -> entry.getKey().deviceId().equals(devId))
1541 .forEach(entry -> dsNextObjStore.remove(entry.getKey()));
1542 }
1543
Saurav Dasec683dc2018-04-27 18:42:30 -07001544 private void processPortUpdatedInternal(Device device, Port port) {
Saurav Dasf0f592d2016-11-18 15:21:57 -08001545 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
1546 log.warn("Device configuration uploading. Not handling port event for"
1547 + "dev: {} port: {}", device.id(), port.number());
1548 return;
1549 }
Saurav Dasf9332192017-02-18 14:05:44 -08001550
Saurav Dasec683dc2018-04-27 18:42:30 -07001551 if (interfaceService.isConfigured(new ConnectPoint(device.id(), port.number()))) {
1552 lastEdgePortEvent = Instant.now();
1553 }
1554
Saurav Dasf9332192017-02-18 14:05:44 -08001555 if (!mastershipService.isLocalMaster(device.id())) {
1556 log.debug("Not master for dev:{} .. not handling port updated event"
1557 + "for port {}", device.id(), port.number());
1558 return;
1559 }
Saurav Dasec683dc2018-04-27 18:42:30 -07001560 processPortUpdated(device.id(), port);
1561 }
Saurav Dasf9332192017-02-18 14:05:44 -08001562
Saurav Dasec683dc2018-04-27 18:42:30 -07001563 /**
1564 * Adds or remove filtering rules for the given switchport. If switchport is
1565 * an edge facing port, additionally handles host probing and broadcast
1566 * rules. Must be called by local master of device.
1567 *
1568 * @param deviceId the device identifier
1569 * @param port the port to update
1570 */
1571 void processPortUpdated(DeviceId deviceId, Port port) {
Saurav Dasf9332192017-02-18 14:05:44 -08001572 // first we handle filtering rules associated with the port
1573 if (port.isEnabled()) {
1574 log.info("Switchport {}/{} enabled..programming filters",
Saurav Dasec683dc2018-04-27 18:42:30 -07001575 deviceId, port.number());
1576 routingRulePopulator.processSinglePortFilters(deviceId, port.number(), true);
Saurav Dasf9332192017-02-18 14:05:44 -08001577 } else {
1578 log.info("Switchport {}/{} disabled..removing filters",
Saurav Dasec683dc2018-04-27 18:42:30 -07001579 deviceId, port.number());
1580 routingRulePopulator.processSinglePortFilters(deviceId, port.number(), false);
Saurav Dasf9332192017-02-18 14:05:44 -08001581 }
Saurav Dasf0f592d2016-11-18 15:21:57 -08001582
1583 // portUpdated calls are for ports that have gone down or up. For switch
1584 // to switch ports, link-events should take care of any re-routing or
1585 // group editing necessary for port up/down. Here we only process edge ports
1586 // that are already configured.
Saurav Dasec683dc2018-04-27 18:42:30 -07001587 ConnectPoint cp = new ConnectPoint(deviceId, port.number());
Charles Chan098ca202018-05-01 11:50:20 -07001588 VlanId untaggedVlan = interfaceService.getUntaggedVlanId(cp);
1589 VlanId nativeVlan = interfaceService.getNativeVlanId(cp);
1590 Set<VlanId> taggedVlans = interfaceService.getTaggedVlanId(cp);
Charles Chan10b0fb72017-02-02 16:20:42 -08001591
Saurav Das3fb28272017-03-04 16:08:47 -08001592 if (untaggedVlan == null && nativeVlan == null && taggedVlans.isEmpty()) {
Saurav Das62ae6792017-05-15 15:34:25 -07001593 log.debug("Not handling port updated event for non-edge port (unconfigured) "
Saurav Dasec683dc2018-04-27 18:42:30 -07001594 + "dev/port: {}/{}", deviceId, port.number());
Saurav Dasf0f592d2016-11-18 15:21:57 -08001595 return;
1596 }
Saurav Das3fb28272017-03-04 16:08:47 -08001597 if (untaggedVlan != null) {
Saurav Dasec683dc2018-04-27 18:42:30 -07001598 processEdgePort(deviceId, port, untaggedVlan, true);
Saurav Das3fb28272017-03-04 16:08:47 -08001599 }
1600 if (nativeVlan != null) {
Saurav Dasec683dc2018-04-27 18:42:30 -07001601 processEdgePort(deviceId, port, nativeVlan, true);
Saurav Das3fb28272017-03-04 16:08:47 -08001602 }
1603 if (!taggedVlans.isEmpty()) {
Saurav Dasec683dc2018-04-27 18:42:30 -07001604 taggedVlans.forEach(tag -> processEdgePort(deviceId, port, tag, false));
Saurav Das3fb28272017-03-04 16:08:47 -08001605 }
Saurav Dasf0f592d2016-11-18 15:21:57 -08001606 }
1607
Saurav Dasec683dc2018-04-27 18:42:30 -07001608 private void processEdgePort(DeviceId deviceId, Port port, VlanId vlanId,
Saurav Das3fb28272017-03-04 16:08:47 -08001609 boolean popVlan) {
Saurav Dasf0f592d2016-11-18 15:21:57 -08001610 boolean portUp = port.isEnabled();
1611 if (portUp) {
Saurav Dasec683dc2018-04-27 18:42:30 -07001612 log.info("Device:EdgePort {}:{} is enabled in vlan: {}", deviceId,
Charles Chan10b0fb72017-02-02 16:20:42 -08001613 port.number(), vlanId);
Charles Chan074fae62018-04-29 18:11:37 -07001614 hostEventExecutor.execute(() -> hostHandler.processPortUp(new ConnectPoint(deviceId, port.number())));
Saurav Dasf0f592d2016-11-18 15:21:57 -08001615 } else {
Saurav Dasec683dc2018-04-27 18:42:30 -07001616 log.info("Device:EdgePort {}:{} is disabled in vlan: {}", deviceId,
Charles Chan10b0fb72017-02-02 16:20:42 -08001617 port.number(), vlanId);
Saurav Dasf0f592d2016-11-18 15:21:57 -08001618 }
1619
Saurav Dasec683dc2018-04-27 18:42:30 -07001620 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
sangho80f11cb2015-04-01 13:05:26 -07001621 if (groupHandler != null) {
Saurav Das3fb28272017-03-04 16:08:47 -08001622 groupHandler.processEdgePort(port.number(), vlanId, popVlan, portUp);
Saurav Dasf0f592d2016-11-18 15:21:57 -08001623 } else {
1624 log.warn("Group handler not found for dev:{}. Not handling edge port"
Saurav Dasec683dc2018-04-27 18:42:30 -07001625 + " {} event for port:{}", deviceId,
Saurav Dasf0f592d2016-11-18 15:21:57 -08001626 (portUp) ? "UP" : "DOWN", port.number());
sangho80f11cb2015-04-01 13:05:26 -07001627 }
1628 }
sangho27462c62015-05-14 00:39:53 -07001629
Charles Chan8ca5a122017-10-20 16:06:55 -07001630 private void createOrUpdateDeviceConfiguration() {
1631 if (deviceConfiguration == null) {
Saurav Dase321cff2018-02-09 17:26:45 -08001632 log.info("Creating new DeviceConfiguration");
Charles Chan8ca5a122017-10-20 16:06:55 -07001633 deviceConfiguration = new DeviceConfiguration(this);
1634 } else {
Saurav Dase321cff2018-02-09 17:26:45 -08001635 log.info("Updating DeviceConfiguration");
Charles Chan8ca5a122017-10-20 16:06:55 -07001636 deviceConfiguration.updateConfig();
1637 }
1638 }
1639
Charles Chanfbcb8812018-04-18 18:41:05 -07001640 private void createOrUpdateDefaultRoutingHandler() {
1641 if (defaultRoutingHandler == null) {
1642 log.info("Creating new DefaultRoutingHandler");
1643 defaultRoutingHandler = new DefaultRoutingHandler(this);
1644 } else {
1645 log.info("Updating DefaultRoutingHandler");
1646 defaultRoutingHandler.update(this);
1647 }
1648 }
1649
Pier Ventreb6a7f342016-11-26 21:05:22 -08001650 /**
1651 * Registers the given connect point with the NRS, this is necessary
1652 * to receive the NDP and ARP packets from the NRS.
1653 *
1654 * @param portToRegister connect point to register
1655 */
1656 public void registerConnectPoint(ConnectPoint portToRegister) {
Charles Chan2e71ef32017-02-23 15:44:08 -08001657 neighbourResolutionService.registerNeighbourHandler(
Pier Ventreb6a7f342016-11-26 21:05:22 -08001658 portToRegister,
1659 neighbourHandler,
1660 appId
1661 );
1662 }
1663
Charles Chan72f556a2015-10-05 17:50:33 -07001664 private class InternalConfigListener implements NetworkConfigListener {
Saurav Das261c3002017-06-13 15:35:54 -07001665 private static final long PROGRAM_DELAY = 2;
Charles Chan46fdfaf2016-11-09 20:51:44 -08001666 SegmentRoutingManager srManager;
Charles Chane7c61022015-10-07 14:21:45 -07001667
Charles Chanb7f75ac2016-01-11 18:28:54 -08001668 /**
1669 * Constructs the internal network config listener.
1670 *
Charles Chan46fdfaf2016-11-09 20:51:44 -08001671 * @param srManager segment routing manager
Charles Chanb7f75ac2016-01-11 18:28:54 -08001672 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001673 InternalConfigListener(SegmentRoutingManager srManager) {
Charles Chan46fdfaf2016-11-09 20:51:44 -08001674 this.srManager = srManager;
Charles Chane7c61022015-10-07 14:21:45 -07001675 }
1676
Charles Chanb7f75ac2016-01-11 18:28:54 -08001677 /**
1678 * Reads network config and initializes related data structure accordingly.
1679 */
Charles Chan873661e2017-11-30 15:37:50 -08001680 void configureNetwork() {
Saurav Dase321cff2018-02-09 17:26:45 -08001681 log.info("Configuring network ...");
Andrea Campanella060cad82018-04-17 12:09:34 +02001682
1683 // Setting handling of network configuration events completable future
1684 // The completable future is needed because of the async behaviour of the configureNetwork,
1685 // listener registration and event arrival
1686 // Enables us to buffer the events and execute them when the configure network is done.
1687 networkConfigCompletion = new CompletableFuture<>();
1688
1689 // add a small delay to absorb multiple network config added notifications
1690 if (!programmingScheduled.get()) {
1691 log.info("Buffering config calls for {} secs", PROGRAM_DELAY);
1692 programmingScheduled.set(true);
1693 mainEventExecutor.schedule(new ConfigChange(), PROGRAM_DELAY, TimeUnit.SECONDS);
1694 }
1695
Charles Chan8ca5a122017-10-20 16:06:55 -07001696 createOrUpdateDeviceConfiguration();
Charles Chane7c61022015-10-07 14:21:45 -07001697
Charles Chan46fdfaf2016-11-09 20:51:44 -08001698 arpHandler = new ArpHandler(srManager);
1699 icmpHandler = new IcmpHandler(srManager);
1700 ipHandler = new IpHandler(srManager);
1701 routingRulePopulator = new RoutingRulePopulator(srManager);
Charles Chanfbcb8812018-04-18 18:41:05 -07001702 createOrUpdateDefaultRoutingHandler();
Charles Chane7c61022015-10-07 14:21:45 -07001703
1704 tunnelHandler = new TunnelHandler(linkService, deviceConfiguration,
1705 groupHandlerMap, tunnelStore);
1706 policyHandler = new PolicyHandler(appId, deviceConfiguration,
1707 flowObjectiveService,
1708 tunnelHandler, policyStore);
Andrea Campanella060cad82018-04-17 12:09:34 +02001709 networkConfigCompletion.complete(true);
1710
Charles Chan72779502016-04-23 17:36:10 -07001711 mcastHandler.init();
Andrea Campanella060cad82018-04-17 12:09:34 +02001712
Charles Chane7c61022015-10-07 14:21:45 -07001713 }
1714
Charles Chan72f556a2015-10-05 17:50:33 -07001715 @Override
1716 public void event(NetworkConfigEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001717 if (mainEventExecutor == null) {
1718 return;
1719 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001720 checkState(appCfgHandler != null, "NetworkConfigEventHandler is not initialized");
1721 checkState(xConnectHandler != null, "XConnectHandler is not initialized");
1722 switch (event.type()) {
1723 case CONFIG_ADDED:
1724 case CONFIG_UPDATED:
1725 case CONFIG_REMOVED:
1726 log.trace("Schedule Network Config event {}", event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001727 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1728 mainEventExecutor.execute(new InternalEventHandler(event));
1729 } else {
Charles Chan39b75522018-04-21 00:44:29 -07001730 queuedEvents.add(event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001731 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001732 break;
1733 default:
1734 break;
Charles Chan72f556a2015-10-05 17:50:33 -07001735 }
1736 }
Saurav Das261c3002017-06-13 15:35:54 -07001737
Charles Chanc4a68c32018-01-03 16:26:32 -08001738 @Override
1739 public boolean isRelevant(NetworkConfigEvent event) {
Saurav Dase321cff2018-02-09 17:26:45 -08001740 if (event.type() == CONFIG_REGISTERED ||
1741 event.type() == CONFIG_UNREGISTERED) {
1742 log.debug("Ignore event {} due to type mismatch", event);
1743 return false;
Charles Chanc4a68c32018-01-03 16:26:32 -08001744 }
Saurav Dase321cff2018-02-09 17:26:45 -08001745
1746 if (!event.configClass().equals(SegmentRoutingDeviceConfig.class) &&
1747 !event.configClass().equals(SegmentRoutingAppConfig.class) &&
1748 !event.configClass().equals(InterfaceConfig.class) &&
Andreas Pantelopouloscdbb22c2018-02-23 14:18:00 -08001749 !event.configClass().equals(XConnectConfig.class)) {
Saurav Dase321cff2018-02-09 17:26:45 -08001750 log.debug("Ignore event {} due to class mismatch", event);
1751 return false;
1752 }
1753
1754 return true;
Charles Chanc4a68c32018-01-03 16:26:32 -08001755 }
1756
Saurav Das261c3002017-06-13 15:35:54 -07001757 private final class ConfigChange implements Runnable {
1758 @Override
1759 public void run() {
1760 programmingScheduled.set(false);
Saurav Dase321cff2018-02-09 17:26:45 -08001761 log.info("Reacting to config changes after buffer delay");
Saurav Das261c3002017-06-13 15:35:54 -07001762 for (Device device : deviceService.getDevices()) {
1763 processDeviceAdded(device);
1764 }
1765 defaultRoutingHandler.startPopulationProcess();
1766 }
1767 }
Charles Chan72f556a2015-10-05 17:50:33 -07001768 }
Charles Chanf4586112015-11-09 16:37:23 -08001769
Charles Chan3f4aca62018-03-21 16:57:47 -07001770 private class InternalLinkListener implements LinkListener {
1771 @Override
1772 public void event(LinkEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001773 if (mainEventExecutor == null) {
1774 return;
1775 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001776 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1777 event.type() == LinkEvent.Type.LINK_UPDATED ||
1778 event.type() == LinkEvent.Type.LINK_REMOVED) {
1779 log.trace("Schedule Link event {}", event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001780 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1781 mainEventExecutor.execute(new InternalEventHandler(event));
1782 } else {
Charles Chan39b75522018-04-21 00:44:29 -07001783 queuedEvents.add(event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001784 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001785 }
1786 }
1787 }
1788
1789 private class InternalDeviceListener implements DeviceListener {
1790 @Override
1791 public void event(DeviceEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001792 if (mainEventExecutor == null) {
1793 return;
1794 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001795 switch (event.type()) {
1796 case DEVICE_ADDED:
1797 case PORT_UPDATED:
1798 case PORT_ADDED:
1799 case DEVICE_UPDATED:
1800 case DEVICE_AVAILABILITY_CHANGED:
1801 log.trace("Schedule Device event {}", event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001802 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1803 mainEventExecutor.execute(new InternalEventHandler(event));
1804 } else {
Charles Chan39b75522018-04-21 00:44:29 -07001805 queuedEvents.add(event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001806 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001807 break;
1808 default:
1809 }
1810 }
1811 }
1812
1813 private class InternalTopologyListener implements TopologyListener {
1814 @Override
1815 public void event(TopologyEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001816 if (mainEventExecutor == null) {
1817 return;
1818 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001819 switch (event.type()) {
1820 case TOPOLOGY_CHANGED:
1821 log.trace("Schedule Topology event {}", event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001822 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1823 mainEventExecutor.execute(new InternalEventHandler(event));
1824 } else {
Charles Chan39b75522018-04-21 00:44:29 -07001825 queuedEvents.add(event);
Andrea Campanella060cad82018-04-17 12:09:34 +02001826 }
Charles Chan3f4aca62018-03-21 16:57:47 -07001827 break;
1828 default:
1829 }
1830 }
1831 }
1832
Charles Chanf4586112015-11-09 16:37:23 -08001833 private class InternalHostListener implements HostListener {
Charles Chanf4586112015-11-09 16:37:23 -08001834 @Override
1835 public void event(HostEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001836 if (hostEventExecutor == null) {
1837 return;
1838 }
Charles Chanf4586112015-11-09 16:37:23 -08001839 switch (event.type()) {
1840 case HOST_ADDED:
Charles Chanf4586112015-11-09 16:37:23 -08001841 case HOST_MOVED:
Charles Chanf4586112015-11-09 16:37:23 -08001842 case HOST_REMOVED:
Charles Chanf4586112015-11-09 16:37:23 -08001843 case HOST_UPDATED:
Charles Chan3f4aca62018-03-21 16:57:47 -07001844 log.trace("Schedule Host event {}", event);
Charles Chandbbbb8a2018-04-07 11:35:08 -07001845 hostEventExecutor.execute(new InternalEventHandler(event));
Charles Chanf4586112015-11-09 16:37:23 -08001846 break;
1847 default:
1848 log.warn("Unsupported host event type: {}", event.type());
1849 break;
1850 }
1851 }
1852 }
1853
Charles Chanc91c8782016-03-30 17:54:24 -07001854 private class InternalMcastListener implements McastListener {
1855 @Override
1856 public void event(McastEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001857 if (mcastEventExecutor == null) {
1858 return;
1859 }
Charles Chanc91c8782016-03-30 17:54:24 -07001860 switch (event.type()) {
Pier1f87aca2018-03-14 16:47:32 -07001861 case SOURCES_ADDED:
1862 case SOURCES_REMOVED:
1863 case SINKS_ADDED:
1864 case SINKS_REMOVED:
Charles Chanc91c8782016-03-30 17:54:24 -07001865 case ROUTE_REMOVED:
Pierdb27b8d2018-04-17 16:29:56 +02001866 case ROUTE_ADDED:
Charles Chan3f4aca62018-03-21 16:57:47 -07001867 log.trace("Schedule Mcast event {}", event);
Charles Chandbbbb8a2018-04-07 11:35:08 -07001868 mcastEventExecutor.execute(new InternalEventHandler(event));
Pier Luigi6786b922018-02-02 16:19:11 +01001869 break;
Charles Chanc91c8782016-03-30 17:54:24 -07001870 default:
Charles Chan3f4aca62018-03-21 16:57:47 -07001871 log.warn("Unsupported mcast event type: {}", event.type());
Charles Chanc91c8782016-03-30 17:54:24 -07001872 break;
1873 }
1874 }
1875 }
Charles Chan41f5ec02016-06-13 18:54:31 -07001876
Charles Chandebfea32016-10-24 14:52:01 -07001877 private class InternalRouteEventListener implements RouteListener {
1878 @Override
1879 public void event(RouteEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001880 if (routeEventExecutor == null) {
1881 return;
1882 }
Charles Chandebfea32016-10-24 14:52:01 -07001883 switch (event.type()) {
1884 case ROUTE_ADDED:
Charles Chandebfea32016-10-24 14:52:01 -07001885 case ROUTE_UPDATED:
Charles Chandebfea32016-10-24 14:52:01 -07001886 case ROUTE_REMOVED:
Charles Chan910be6a2017-08-23 14:46:43 -07001887 case ALTERNATIVE_ROUTES_CHANGED:
Charles Chan3f4aca62018-03-21 16:57:47 -07001888 log.trace("Schedule Route event {}", event);
Charles Chandbbbb8a2018-04-07 11:35:08 -07001889 routeEventExecutor.execute(new InternalEventHandler(event));
Charles Chan910be6a2017-08-23 14:46:43 -07001890 break;
Charles Chandebfea32016-10-24 14:52:01 -07001891 default:
Charles Chan3f4aca62018-03-21 16:57:47 -07001892 log.warn("Unsupported route event type: {}", event.type());
Charles Chandebfea32016-10-24 14:52:01 -07001893 break;
1894 }
1895 }
1896 }
Saurav Das62ae6792017-05-15 15:34:25 -07001897
Charles Chanfbcb8812018-04-18 18:41:05 -07001898 private class InternalMastershipListener implements MastershipListener {
1899 @Override
1900 public void event(MastershipEvent event) {
Ray Milkeyaee4d3e2018-05-11 09:59:19 -07001901 if (mainEventExecutor == null) {
1902 return;
1903 }
Charles Chanfbcb8812018-04-18 18:41:05 -07001904 switch (event.type()) {
Saurav Das00e553b2018-04-21 17:19:48 -07001905 case MASTER_CHANGED:
1906 log.debug("Mastership event: {}/{}", event.subject(),
1907 event.roleInfo());
1908 mainEventExecutor.execute(new InternalEventHandler(event));
1909 break;
1910 case BACKUPS_CHANGED:
1911 case SUSPENDED:
1912 default:
1913 log.debug("Mastership event type {} not handled", event.type());
1914 break;
Charles Chanfbcb8812018-04-18 18:41:05 -07001915 }
1916 }
1917 }
1918
Saurav Das00e553b2018-04-21 17:19:48 -07001919 class InternalClusterListener implements ClusterEventListener {
1920 private Instant lastClusterEvent = Instant.EPOCH;
1921
1922 long timeSinceLastClusterEvent() {
1923 return Instant.now().toEpochMilli() - lastClusterEvent.toEpochMilli();
1924 }
1925
1926 @Override
1927 public void event(ClusterEvent event) {
1928 switch (event.type()) {
1929 case INSTANCE_ACTIVATED:
1930 case INSTANCE_ADDED:
1931 case INSTANCE_READY:
1932 log.debug("Cluster event {} ignored", event.type());
1933 break;
1934 case INSTANCE_DEACTIVATED:
1935 case INSTANCE_REMOVED:
1936 log.info("** Cluster event {}", event.type());
1937 lastClusterEvent = Instant.now();
1938 break;
1939 default:
1940 break;
1941 }
1942
1943 }
1944
1945 }
1946
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001947 private void updateInterface(InterfaceConfig conf, InterfaceConfig prevConf) {
1948 try {
1949 Set<Interface> intfs = conf.getInterfaces();
1950 Set<Interface> prevIntfs = prevConf.getInterfaces();
1951
1952 // Now we only handle one interface config at each port.
1953 if (intfs.size() != 1 || prevIntfs.size() != 1) {
1954 log.warn("Interface update aborted - one at a time is allowed, " +
1955 "but {} / {}(prev) received.", intfs.size(), prevIntfs.size());
1956 return;
1957 }
1958
Andrea Campanella060cad82018-04-17 12:09:34 +02001959 //The system is in an incoherent state, abort
1960 if (defaultRoutingHandler == null) {
1961 log.warn("Interface update aborted, defaultRoutingHandler is null");
1962 return;
1963 }
1964
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001965 Interface intf = intfs.stream().findFirst().get();
1966 Interface prevIntf = prevIntfs.stream().findFirst().get();
1967
1968 DeviceId deviceId = intf.connectPoint().deviceId();
1969 PortNumber portNum = intf.connectPoint().port();
1970
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001971 removeSubnetConfig(prevIntf.connectPoint(),
1972 Sets.difference(new HashSet<>(prevIntf.ipAddressesList()),
1973 new HashSet<>(intf.ipAddressesList())));
1974
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09001975 if (!prevIntf.vlanNative().equals(VlanId.NONE)
1976 && !prevIntf.vlanNative().equals(intf.vlanUntagged())
1977 && !prevIntf.vlanNative().equals(intf.vlanNative())) {
1978 if (intf.vlanTagged().contains(prevIntf.vlanNative())) {
1979 // Update filtering objective and L2IG group bucket
1980 updatePortVlanTreatment(deviceId, portNum, prevIntf.vlanNative(), false);
1981 } else {
1982 // RemoveVlanNative
1983 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanNative(), true, false);
1984 }
1985 }
1986
1987 if (!prevIntf.vlanUntagged().equals(VlanId.NONE)
1988 && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())
1989 && !prevIntf.vlanUntagged().equals(intf.vlanNative())) {
1990 if (intf.vlanTagged().contains(prevIntf.vlanUntagged())) {
1991 // Update filtering objective and L2IG group bucket
1992 updatePortVlanTreatment(deviceId, portNum, prevIntf.vlanUntagged(), false);
1993 } else {
1994 // RemoveVlanUntagged
1995 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanUntagged(), true, false);
1996 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001997 }
1998
1999 if (!prevIntf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
2000 // RemoveVlanTagged
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002001 Sets.difference(prevIntf.vlanTagged(), intf.vlanTagged()).stream()
2002 .filter(i -> !intf.vlanUntagged().equals(i))
2003 .filter(i -> !intf.vlanNative().equals(i))
2004 .forEach(vlanId -> updateVlanConfigInternal(
2005 deviceId, portNum, vlanId, false, false));
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002006 }
2007
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002008 if (!intf.vlanNative().equals(VlanId.NONE)
2009 && !prevIntf.vlanNative().equals(intf.vlanNative())
2010 && !prevIntf.vlanUntagged().equals(intf.vlanNative())) {
2011 if (prevIntf.vlanTagged().contains(intf.vlanNative())) {
2012 // Update filtering objective and L2IG group bucket
2013 updatePortVlanTreatment(deviceId, portNum, intf.vlanNative(), true);
2014 } else {
2015 // AddVlanNative
2016 updateVlanConfigInternal(deviceId, portNum, intf.vlanNative(), true, true);
2017 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002018 }
2019
2020 if (!intf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
2021 // AddVlanTagged
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002022 Sets.difference(intf.vlanTagged(), prevIntf.vlanTagged()).stream()
2023 .filter(i -> !prevIntf.vlanUntagged().equals(i))
2024 .filter(i -> !prevIntf.vlanNative().equals(i))
2025 .forEach(vlanId -> updateVlanConfigInternal(
2026 deviceId, portNum, vlanId, false, true)
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002027 );
2028 }
2029
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002030 if (!intf.vlanUntagged().equals(VlanId.NONE)
2031 && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())
2032 && !prevIntf.vlanNative().equals(intf.vlanUntagged())) {
2033 if (prevIntf.vlanTagged().contains(intf.vlanUntagged())) {
2034 // Update filtering objective and L2IG group bucket
2035 updatePortVlanTreatment(deviceId, portNum, intf.vlanUntagged(), true);
2036 } else {
2037 // AddVlanUntagged
2038 updateVlanConfigInternal(deviceId, portNum, intf.vlanUntagged(), true, true);
2039 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002040 }
2041 addSubnetConfig(prevIntf.connectPoint(),
2042 Sets.difference(new HashSet<>(intf.ipAddressesList()),
2043 new HashSet<>(prevIntf.ipAddressesList())));
2044 } catch (ConfigException e) {
2045 log.error("Error in configuration");
2046 }
2047 }
2048
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002049 private void updatePortVlanTreatment(DeviceId deviceId, PortNumber portNum,
2050 VlanId vlanId, boolean pushVlan) {
2051 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
2052 if (grpHandler == null) {
2053 log.warn("Failed to retrieve group handler for device {}", deviceId);
2054 return;
2055 }
2056
2057 // Update filtering objective for a single port
2058 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, !pushVlan, vlanId, false);
2059 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, true);
2060
2061 if (getVlanNextObjectiveId(deviceId, vlanId) != -1) {
2062 // Update L2IG bucket of the port
2063 grpHandler.updateL2InterfaceGroupBucket(portNum, vlanId, pushVlan);
2064 } else {
2065 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
2066 }
2067 }
2068
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002069 private void updateVlanConfigInternal(DeviceId deviceId, PortNumber portNum,
2070 VlanId vlanId, boolean pushVlan, boolean install) {
2071 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
2072 if (grpHandler == null) {
2073 log.warn("Failed to retrieve group handler for device {}", deviceId);
2074 return;
2075 }
2076
2077 // Update filtering objective for a single port
2078 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, install);
2079
2080 // Update filtering objective for multicast ingress port
2081 mcastHandler.updateFilterToDevice(deviceId, portNum, vlanId, install);
2082
2083 int nextId = getVlanNextObjectiveId(deviceId, vlanId);
2084
2085 if (nextId != -1 && !install) {
2086 // Update next objective for a single port as an output port
2087 // Remove a single port from L2FG
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002088 grpHandler.updateGroupFromVlanConfiguration(vlanId, portNum, nextId, install);
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002089 // Remove L2 Bridging rule and L3 Unicast rule to the host
Charles Chan074fae62018-04-29 18:11:37 -07002090 hostEventExecutor.execute(() -> hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum,
2091 vlanId, pushVlan, install));
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002092 // Remove broadcast forwarding rule and corresponding L2FG for VLAN
2093 // only if there is no port configured on that VLAN ID
2094 if (!getVlanPortMap(deviceId).containsKey(vlanId)) {
2095 // Remove broadcast forwarding rule for the VLAN
2096 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
2097 // Remove L2FG for VLAN
2098 grpHandler.removeBcastGroupFromVlan(deviceId, portNum, vlanId, pushVlan);
2099 } else {
2100 // Remove L2IG of the port
2101 grpHandler.removePortNextObjective(deviceId, portNum, vlanId, pushVlan);
2102 }
2103 } else if (install) {
2104 if (nextId != -1) {
2105 // Add a single port to L2FG
Jonghwan Hyuna4ce0aa2018-02-12 16:43:45 +09002106 grpHandler.updateGroupFromVlanConfiguration(vlanId, portNum, nextId, install);
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002107 } else {
2108 // Create L2FG for VLAN
2109 grpHandler.createBcastGroupFromVlan(vlanId, Collections.singleton(portNum));
2110 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
2111 }
Charles Chan074fae62018-04-29 18:11:37 -07002112 hostEventExecutor.execute(() -> hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum,
2113 vlanId, pushVlan, install));
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002114 } else {
2115 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
2116 }
2117 }
2118
2119 private void removeSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
2120 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
2121 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
2122
2123 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
2124 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
2125 .filter(intf -> !intf.connectPoint().equals(cp))
2126 .flatMap(intf -> intf.ipAddressesList().stream())
2127 .collect(Collectors.toSet());
2128 // 1. Partial subnet population
2129 // Remove routing rules for removed subnet from previous configuration,
2130 // which does not also exist in other interfaces in the same device
2131 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
2132 .map(InterfaceIpAddress::subnetAddress)
2133 .collect(Collectors.toSet());
2134
2135 defaultRoutingHandler.revokeSubnet(
2136 ipPrefixSet.stream()
2137 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
2138 .collect(Collectors.toSet()));
2139
2140 // 2. Interface IP punts
2141 // Remove IP punts for old Intf address
2142 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
2143 .map(InterfaceIpAddress::ipAddress)
2144 .collect(Collectors.toSet());
2145 ipAddressSet.stream()
2146 .map(InterfaceIpAddress::ipAddress)
2147 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
2148 .forEach(interfaceIpAddress ->
2149 routingRulePopulator.revokeSingleIpPunts(
2150 cp.deviceId(), interfaceIpAddress));
2151
2152 // 3. Host unicast routing rule
2153 // Remove unicast routing rule
Charles Chan074fae62018-04-29 18:11:37 -07002154 hostEventExecutor.execute(() -> hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, false));
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002155 }
2156
2157 private void addSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
2158 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
2159 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
2160
2161 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
2162 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
2163 .filter(intf -> !intf.connectPoint().equals(cp))
2164 .flatMap(intf -> intf.ipAddressesList().stream())
2165 .collect(Collectors.toSet());
2166 // 1. Partial subnet population
2167 // Add routing rules for newly added subnet, which does not also exist in
2168 // other interfaces in the same device
2169 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
2170 .map(InterfaceIpAddress::subnetAddress)
2171 .collect(Collectors.toSet());
2172
2173 defaultRoutingHandler.populateSubnet(
2174 Collections.singleton(cp),
2175 ipPrefixSet.stream()
2176 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
2177 .collect(Collectors.toSet()));
2178
2179 // 2. Interface IP punts
2180 // Add IP punts for new Intf address
2181 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
2182 .map(InterfaceIpAddress::ipAddress)
2183 .collect(Collectors.toSet());
2184 ipAddressSet.stream()
2185 .map(InterfaceIpAddress::ipAddress)
2186 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
2187 .forEach(interfaceIpAddress ->
2188 routingRulePopulator.populateSingleIpPunts(
2189 cp.deviceId(), interfaceIpAddress));
2190
2191 // 3. Host unicast routing rule
2192 // Add unicast routing rule
Charles Chan074fae62018-04-29 18:11:37 -07002193 hostEventExecutor.execute(() -> hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, true));
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07002194 }
sangho80f11cb2015-04-01 13:05:26 -07002195}