blob: 360afdd5a393841289ce1e44665829da2998b4ee [file] [log] [blame]
sanghob35a6192015-04-01 13:05:26 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
sanghob35a6192015-04-01 13:05:26 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.segmentrouting;
17
Jonathan Hart8ca2bc02017-11-30 18:23:42 -080018import com.google.common.collect.HashMultimap;
19import com.google.common.collect.ImmutableMap;
20import com.google.common.collect.Maps;
21import com.google.common.collect.Multimap;
Charles Chan9640c812017-08-23 13:55:39 -070022import com.google.common.collect.Sets;
sanghob35a6192015-04-01 13:05:26 -070023import org.apache.felix.scr.annotations.Activate;
24import org.apache.felix.scr.annotations.Component;
25import org.apache.felix.scr.annotations.Deactivate;
Charles Chan47933752017-11-30 15:37:50 -080026import org.apache.felix.scr.annotations.Modified;
27import org.apache.felix.scr.annotations.Property;
sanghob35a6192015-04-01 13:05:26 -070028import org.apache.felix.scr.annotations.Reference;
29import org.apache.felix.scr.annotations.ReferenceCardinality;
sangho1e575652015-05-14 00:39:53 -070030import org.apache.felix.scr.annotations.Service;
sanghob35a6192015-04-01 13:05:26 -070031import org.onlab.packet.Ethernet;
Pier Ventre735b8c82016-12-02 08:16:05 -080032import org.onlab.packet.ICMP6;
Charles Chanc42e84e2015-10-20 16:24:19 -070033import org.onlab.packet.IPv4;
Pier Ventre10bd8d12016-11-26 21:05:22 -080034import org.onlab.packet.IPv6;
Jonghwan Hyun42fe1052017-08-25 17:48:36 -070035import org.onlab.packet.IpAddress;
Charles Chanc42e84e2015-10-20 16:24:19 -070036import org.onlab.packet.IpPrefix;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070037import org.onlab.packet.VlanId;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -070038import org.onlab.util.KryoNamespace;
Charles Chan47933752017-11-30 15:37:50 -080039import org.onlab.util.Tools;
Saurav Das80980c72016-03-23 11:22:49 -070040import org.onosproject.cfg.ComponentConfigService;
Saurav Das201762d2018-04-21 17:19:48 -070041import org.onosproject.cluster.ClusterEvent;
42import org.onosproject.cluster.ClusterEventListener;
Pier Luigieba73a02018-01-16 10:47:50 +010043import org.onosproject.cluster.ClusterService;
Jonghwan Hyun800d9d02018-04-09 09:40:50 -070044import org.onosproject.cluster.LeadershipService;
Pier96f63cb2018-04-17 16:29:56 +020045import org.onosproject.cluster.NodeId;
sanghob35a6192015-04-01 13:05:26 -070046import org.onosproject.core.ApplicationId;
47import org.onosproject.core.CoreService;
48import org.onosproject.event.Event;
Charles Chan50bb6ef2018-04-18 18:41:05 -070049import org.onosproject.mastership.MastershipEvent;
50import org.onosproject.mastership.MastershipListener;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070051import org.onosproject.mastership.MastershipService;
Pier3ee24552018-03-14 16:47:32 -070052import org.onosproject.mcast.api.McastEvent;
53import org.onosproject.mcast.api.McastListener;
54import org.onosproject.mcast.api.MulticastRouteService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080055import org.onosproject.net.ConnectPoint;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070056import org.onosproject.net.Device;
57import org.onosproject.net.DeviceId;
Charles Chan9640c812017-08-23 13:55:39 -070058import org.onosproject.net.Host;
59import org.onosproject.net.HostId;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070060import org.onosproject.net.Link;
61import org.onosproject.net.Port;
Charles Chan68aa62d2015-11-09 16:37:23 -080062import org.onosproject.net.PortNumber;
Jonghwan Hyun42fe1052017-08-25 17:48:36 -070063import org.onosproject.net.config.ConfigException;
Charles Chand6832882015-10-05 17:50:33 -070064import org.onosproject.net.config.ConfigFactory;
65import org.onosproject.net.config.NetworkConfigEvent;
Charles Chand6832882015-10-05 17:50:33 -070066import org.onosproject.net.config.NetworkConfigListener;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070067import org.onosproject.net.config.NetworkConfigRegistry;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070068import org.onosproject.net.config.basics.InterfaceConfig;
69import org.onosproject.net.config.basics.McastConfig;
Charles Chand6832882015-10-05 17:50:33 -070070import org.onosproject.net.config.basics.SubjectFactories;
Saurav Das45f48152018-01-18 12:07:33 -080071import org.onosproject.net.device.DeviceAdminService;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070072import org.onosproject.net.device.DeviceEvent;
73import org.onosproject.net.device.DeviceListener;
74import org.onosproject.net.device.DeviceService;
Charles Chan68aa62d2015-11-09 16:37:23 -080075import org.onosproject.net.flow.TrafficSelector;
76import org.onosproject.net.flow.TrafficTreatment;
Jonathan Hartc19f7c12016-04-12 15:39:44 -070077import org.onosproject.net.flowobjective.FlowObjectiveService;
Charles Chan68aa62d2015-11-09 16:37:23 -080078import org.onosproject.net.host.HostEvent;
79import org.onosproject.net.host.HostListener;
Charles Chan47933752017-11-30 15:37:50 -080080import org.onosproject.net.host.HostLocationProbingService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080081import org.onosproject.net.host.HostService;
Jonghwan Hyun42fe1052017-08-25 17:48:36 -070082import org.onosproject.net.host.InterfaceIpAddress;
Pier96f63cb2018-04-17 16:29:56 +020083import org.onosproject.net.intent.WorkPartitionService;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070084import org.onosproject.net.intf.Interface;
85import org.onosproject.net.intf.InterfaceService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080086import org.onosproject.net.link.LinkEvent;
87import org.onosproject.net.link.LinkListener;
88import org.onosproject.net.link.LinkService;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070089import org.onosproject.net.neighbour.NeighbourResolutionService;
Pier Ventre10bd8d12016-11-26 21:05:22 -080090import org.onosproject.net.packet.InboundPacket;
91import org.onosproject.net.packet.PacketContext;
92import org.onosproject.net.packet.PacketProcessor;
93import org.onosproject.net.packet.PacketService;
Pier Luigi83f919b2018-02-15 16:33:08 +010094import org.onosproject.net.topology.TopologyEvent;
95import org.onosproject.net.topology.TopologyListener;
Charles Chand55e84d2016-03-30 17:54:24 -070096import org.onosproject.net.topology.TopologyService;
Charles Chan9640c812017-08-23 13:55:39 -070097import org.onosproject.routeservice.ResolvedRoute;
Ray Milkey6c1f0f02017-08-15 11:02:29 -070098import org.onosproject.routeservice.RouteEvent;
99import org.onosproject.routeservice.RouteListener;
100import org.onosproject.routeservice.RouteService;
Charles Chand55e84d2016-03-30 17:54:24 -0700101import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
102import org.onosproject.segmentrouting.config.DeviceConfiguration;
Pier Ventref34966c2016-11-07 16:21:04 -0800103import org.onosproject.segmentrouting.config.SegmentRoutingAppConfig;
Ray Milkey6c1f0f02017-08-15 11:02:29 -0700104import org.onosproject.segmentrouting.config.SegmentRoutingDeviceConfig;
Charles Chanfc5c7802016-05-17 13:13:55 -0700105import org.onosproject.segmentrouting.config.XConnectConfig;
Charles Chand55e84d2016-03-30 17:54:24 -0700106import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
Saurav Das7bcbe702017-06-13 15:35:54 -0700107import org.onosproject.segmentrouting.grouphandler.DestinationSet;
108import org.onosproject.segmentrouting.grouphandler.NextNeighbors;
Pier Luigi96fe0772018-02-28 12:10:50 +0100109import org.onosproject.segmentrouting.mcast.McastHandler;
110import org.onosproject.segmentrouting.mcast.McastRole;
Pier3e793752018-04-19 16:47:06 +0200111import org.onosproject.segmentrouting.mcast.McastRoleStoreKey;
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700112import org.onosproject.segmentrouting.pwaas.DefaultL2Tunnel;
Andreas Pantelopoulosffe69742018-03-20 13:58:49 -0700113import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelDescription;
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800114import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelHandler;
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700115import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelPolicy;
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800116
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800117import org.onosproject.segmentrouting.pwaas.L2Tunnel;
Ray Milkey6c1f0f02017-08-15 11:02:29 -0700118import org.onosproject.segmentrouting.pwaas.L2TunnelHandler;
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800119import org.onosproject.segmentrouting.pwaas.L2TunnelPolicy;
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800120import org.onosproject.segmentrouting.pwaas.L2TunnelDescription;
121
Saurav Das7bcbe702017-06-13 15:35:54 -0700122import org.onosproject.segmentrouting.storekey.DestinationSetNextObjectiveStoreKey;
Jonghwan Hyun800d9d02018-04-09 09:40:50 -0700123import org.onosproject.segmentrouting.storekey.DummyVlanIdStoreKey;
Pier3e793752018-04-19 16:47:06 +0200124import org.onosproject.segmentrouting.mcast.McastStoreKey;
Charles Chand2990362016-04-18 13:44:03 -0700125import org.onosproject.segmentrouting.storekey.PortNextObjectiveStoreKey;
Charles Chan59cc16d2017-02-02 16:20:42 -0800126import org.onosproject.segmentrouting.storekey.VlanNextObjectiveStoreKey;
Charles Chanfc5c7802016-05-17 13:13:55 -0700127import org.onosproject.segmentrouting.storekey.XConnectStoreKey;
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700128import org.onosproject.store.serializers.KryoNamespaces;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700129import org.onosproject.store.service.EventuallyConsistentMap;
130import org.onosproject.store.service.EventuallyConsistentMapBuilder;
131import org.onosproject.store.service.StorageService;
132import org.onosproject.store.service.WallClockTimestamp;
Charles Chan47933752017-11-30 15:37:50 -0800133import org.osgi.service.component.ComponentContext;
sanghob35a6192015-04-01 13:05:26 -0700134import org.slf4j.Logger;
135import org.slf4j.LoggerFactory;
136
Saurav Das201762d2018-04-21 17:19:48 -0700137import java.time.Instant;
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700138import java.util.ArrayList;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800139import java.util.Collections;
Charles Chan47933752017-11-30 15:37:50 -0800140import java.util.Dictionary;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800141import java.util.HashSet;
142import java.util.List;
143import java.util.Map;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800144import java.util.Optional;
145import java.util.Set;
Andrea Campanella6468e1f2018-04-17 12:09:34 +0200146import java.util.concurrent.CompletableFuture;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800147import java.util.concurrent.ConcurrentHashMap;
Andrea Campanella6468e1f2018-04-17 12:09:34 +0200148import java.util.concurrent.CopyOnWriteArrayList;
Charles Chan07f15f22018-05-08 21:35:50 -0700149import java.util.concurrent.ExecutorService;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800150import java.util.concurrent.Executors;
151import java.util.concurrent.ScheduledExecutorService;
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800152import java.util.concurrent.TimeUnit;
153import java.util.concurrent.atomic.AtomicBoolean;
154import java.util.stream.Collectors;
Jonghwan Hyun800d9d02018-04-09 09:40:50 -0700155import java.util.stream.IntStream;
sanghob35a6192015-04-01 13:05:26 -0700156
Charles Chan3e783d02016-02-26 22:19:52 -0800157import static com.google.common.base.Preconditions.checkState;
Pier Ventree0ae7a32016-11-23 09:57:42 -0800158import static org.onlab.packet.Ethernet.TYPE_ARP;
Yuta HIGUCHI1624df12016-07-21 16:54:33 -0700159import static org.onlab.util.Tools.groupedThreads;
Saurav Dase7f51012018-02-09 17:26:45 -0800160import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_REGISTERED;
161import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_UNREGISTERED;
Charles Chan3e783d02016-02-26 22:19:52 -0800162
Charles Chane849c192016-01-11 18:28:54 -0800163/**
164 * Segment routing manager.
165 */
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700166@Service
167@Component(immediate = true)
sangho1e575652015-05-14 00:39:53 -0700168public class SegmentRoutingManager implements SegmentRoutingService {
sanghob35a6192015-04-01 13:05:26 -0700169
Charles Chan2c15aca2016-11-09 20:51:44 -0800170 private static Logger log = LoggerFactory.getLogger(SegmentRoutingManager.class);
Charles Chan2fde6d42017-08-23 14:46:43 -0700171 private static final String NOT_MASTER = "Current instance is not the master of {}. Ignore.";
sanghob35a6192015-04-01 13:05:26 -0700172
173 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700174 private ComponentConfigService compCfgService;
sanghob35a6192015-04-01 13:05:26 -0700175
176 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre10bd8d12016-11-26 21:05:22 -0800177 private NeighbourResolutionService neighbourResolutionService;
178
179 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi96fe0772018-02-28 12:10:50 +0100180 public CoreService coreService;
sanghob35a6192015-04-01 13:05:26 -0700181
182 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700183 PacketService packetService;
sanghob35a6192015-04-01 13:05:26 -0700184
185 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700186 HostService hostService;
sanghob35a6192015-04-01 13:05:26 -0700187
188 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan47933752017-11-30 15:37:50 -0800189 HostLocationProbingService probingService;
190
191 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi96fe0772018-02-28 12:10:50 +0100192 public DeviceService deviceService;
sanghob35a6192015-04-01 13:05:26 -0700193
194 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Saurav Das45f48152018-01-18 12:07:33 -0800195 DeviceAdminService deviceAdminService;
196
197 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre42287df2016-11-09 14:17:26 -0800198 public FlowObjectiveService flowObjectiveService;
sanghob35a6192015-04-01 13:05:26 -0700199
200 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi96fe0772018-02-28 12:10:50 +0100201 public LinkService linkService;
sangho1e575652015-05-14 00:39:53 -0700202
Charles Chan5270ed02016-01-30 23:22:37 -0800203 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre42287df2016-11-09 14:17:26 -0800204 public MastershipService mastershipService;
Charles Chan03a73e02016-10-24 14:52:01 -0700205
206 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventre42287df2016-11-09 14:17:26 -0800207 public StorageService storageService;
Charles Chan03a73e02016-10-24 14:52:01 -0700208
209 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Luigi96fe0772018-02-28 12:10:50 +0100210 public MulticastRouteService multicastRouteService;
Charles Chan03a73e02016-10-24 14:52:01 -0700211
212 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chanf237e1b2018-01-09 13:45:07 -0800213 public TopologyService topologyService;
Charles Chan03a73e02016-10-24 14:52:01 -0700214
215 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan03a73e02016-10-24 14:52:01 -0700216 RouteService routeService;
Charles Chan5270ed02016-01-30 23:22:37 -0800217
218 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan2c15aca2016-11-09 20:51:44 -0800219 public NetworkConfigRegistry cfgService;
Charles Chan5270ed02016-01-30 23:22:37 -0800220
Saurav Das80980c72016-03-23 11:22:49 -0700221 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan2c15aca2016-11-09 20:51:44 -0800222 public InterfaceService interfaceService;
223
Pier Luigieba73a02018-01-16 10:47:50 +0100224 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
225 public ClusterService clusterService;
226
227 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier96f63cb2018-04-17 16:29:56 +0200228 public WorkPartitionService workPartitionService;
Pier Luigieba73a02018-01-16 10:47:50 +0100229
Jonghwan Hyun800d9d02018-04-09 09:40:50 -0700230 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
231 public LeadershipService leadershipService;
232
Charles Chan47933752017-11-30 15:37:50 -0800233 @Property(name = "activeProbing", boolValue = true,
234 label = "Enable active probing to discover dual-homed hosts.")
235 boolean activeProbing = true;
236
Saurav Das9a554292018-04-27 18:42:30 -0700237 @Property(name = "singleHomedDown", boolValue = false,
238 label = "Enable administratively taking down single-homed hosts "
239 + "when all uplinks are gone")
240 boolean singleHomedDown = false;
241
Charles Chan03a73e02016-10-24 14:52:01 -0700242 ArpHandler arpHandler = null;
243 IcmpHandler icmpHandler = null;
244 IpHandler ipHandler = null;
245 RoutingRulePopulator routingRulePopulator = null;
Ray Milkeye4afdb52017-04-05 09:42:04 -0700246 ApplicationId appId;
247 DeviceConfiguration deviceConfiguration = null;
sanghob35a6192015-04-01 13:05:26 -0700248
Charles Chan03a73e02016-10-24 14:52:01 -0700249 DefaultRoutingHandler defaultRoutingHandler = null;
sangho1e575652015-05-14 00:39:53 -0700250 private TunnelHandler tunnelHandler = null;
251 private PolicyHandler policyHandler = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700252 private InternalPacketProcessor processor = null;
253 private InternalLinkListener linkListener = null;
254 private InternalDeviceListener deviceListener = null;
Charles Chanfc5c7802016-05-17 13:13:55 -0700255 private AppConfigHandler appCfgHandler = null;
Pier Luigi96fe0772018-02-28 12:10:50 +0100256 public XConnectHandler xConnectHandler = null;
Saurav Das45f48152018-01-18 12:07:33 -0800257 McastHandler mcastHandler = null;
258 HostHandler hostHandler = null;
Pier Ventre10bd8d12016-11-26 21:05:22 -0800259 private RouteHandler routeHandler = null;
Saurav Das45f48152018-01-18 12:07:33 -0800260 LinkHandler linkHandler = null;
Pier Ventre735b8c82016-12-02 08:16:05 -0800261 private SegmentRoutingNeighbourDispatcher neighbourHandler = null;
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800262 private DefaultL2TunnelHandler l2TunnelHandler = null;
Pier Luigi83f919b2018-02-15 16:33:08 +0100263 private TopologyHandler topologyHandler = null;
Charles Chan5270ed02016-01-30 23:22:37 -0800264 private final InternalHostListener hostListener = new InternalHostListener();
Charles Chand55e84d2016-03-30 17:54:24 -0700265 private final InternalConfigListener cfgListener = new InternalConfigListener(this);
266 private final InternalMcastListener mcastListener = new InternalMcastListener();
Charles Chan03a73e02016-10-24 14:52:01 -0700267 private final InternalRouteEventListener routeListener = new InternalRouteEventListener();
Pier Luigi83f919b2018-02-15 16:33:08 +0100268 private final InternalTopologyListener topologyListener = new InternalTopologyListener();
Charles Chan50bb6ef2018-04-18 18:41:05 -0700269 private final InternalMastershipListener mastershipListener = new InternalMastershipListener();
Saurav Das201762d2018-04-21 17:19:48 -0700270 final InternalClusterListener clusterListener = new InternalClusterListener();
Andrea Campanella6468e1f2018-04-17 12:09:34 +0200271 //Completable future for network configuration process to buffer config events handling during activation
272 private CompletableFuture<Boolean> networkConfigCompletion = null;
Charles Chan10b2fee2018-04-21 00:44:29 -0700273 private List<Event> queuedEvents = new CopyOnWriteArrayList<>();
sanghob35a6192015-04-01 13:05:26 -0700274
Charles Chan9b7217c2018-04-05 16:31:15 -0700275 // Handles device, link, topology and network config events
Charles Chan50bb6ef2018-04-18 18:41:05 -0700276 private ScheduledExecutorService mainEventExecutor;
sanghob35a6192015-04-01 13:05:26 -0700277
Charles Chan50bb6ef2018-04-18 18:41:05 -0700278 // Handles host, route and mcast events respectively
279 private ScheduledExecutorService hostEventExecutor;
280 private ScheduledExecutorService routeEventExecutor;
281 private ScheduledExecutorService mcastEventExecutor;
Charles Chan07f15f22018-05-08 21:35:50 -0700282 private ExecutorService packetExecutor;
Charles Chan9b7217c2018-04-05 16:31:15 -0700283
284 Map<DeviceId, DefaultGroupHandler> groupHandlerMap = new ConcurrentHashMap<>();
Charles Chane849c192016-01-11 18:28:54 -0800285 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700286 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan5bc32632017-08-22 15:07:34 -0700287 * Used to keep track on MPLS group information.
Charles Chane849c192016-01-11 18:28:54 -0800288 */
Charles Chan47933752017-11-30 15:37:50 -0800289 private EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Saurav Das7bcbe702017-06-13 15:35:54 -0700290 dsNextObjStore = null;
Charles Chane849c192016-01-11 18:28:54 -0800291 /**
Charles Chan5bc32632017-08-22 15:07:34 -0700292 * Per device next objective ID store with (device id + vlanid) as key.
293 * Used to keep track on L2 flood group information.
Charles Chane849c192016-01-11 18:28:54 -0800294 */
Charles Chan47933752017-11-30 15:37:50 -0800295 private EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer>
Charles Chan59cc16d2017-02-02 16:20:42 -0800296 vlanNextObjStore = null;
Charles Chane849c192016-01-11 18:28:54 -0800297 /**
Charles Chan5bc32632017-08-22 15:07:34 -0700298 * Per device next objective ID store with (device id + port + treatment + meta) as key.
299 * Used to keep track on L2 interface group and L3 unicast group information.
Charles Chane849c192016-01-11 18:28:54 -0800300 */
Charles Chan47933752017-11-30 15:37:50 -0800301 private EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer>
Saurav Das4ce45962015-11-24 23:21:05 -0800302 portNextObjStore = null;
Charles Chan59cc16d2017-02-02 16:20:42 -0800303
Jonghwan Hyun800d9d02018-04-09 09:40:50 -0700304 /**
305 * Per port dummy VLAN ID store with (connect point + ip address) as key.
306 * Used to keep track on dummy VLAN ID allocation.
307 */
308 private EventuallyConsistentMap<DummyVlanIdStoreKey, VlanId>
309 dummyVlanIdStore = null;
310
Saurav Das4ce45962015-11-24 23:21:05 -0800311 private EventuallyConsistentMap<String, Tunnel> tunnelStore = null;
312 private EventuallyConsistentMap<String, Policy> policyStore = null;
sangho0b2b6d12015-05-20 22:16:38 -0700313
Saurav Das7bcbe702017-06-13 15:35:54 -0700314 private AtomicBoolean programmingScheduled = new AtomicBoolean();
315
Charles Chand55e84d2016-03-30 17:54:24 -0700316 private final ConfigFactory<DeviceId, SegmentRoutingDeviceConfig> deviceConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700317 new ConfigFactory<DeviceId, SegmentRoutingDeviceConfig>(
318 SubjectFactories.DEVICE_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700319 SegmentRoutingDeviceConfig.class, "segmentrouting") {
Charles Chand6832882015-10-05 17:50:33 -0700320 @Override
Charles Chan5270ed02016-01-30 23:22:37 -0800321 public SegmentRoutingDeviceConfig createConfig() {
322 return new SegmentRoutingDeviceConfig();
Charles Chand6832882015-10-05 17:50:33 -0700323 }
324 };
Pier Ventref34966c2016-11-07 16:21:04 -0800325
Charles Chand55e84d2016-03-30 17:54:24 -0700326 private final ConfigFactory<ApplicationId, SegmentRoutingAppConfig> appConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700327 new ConfigFactory<ApplicationId, SegmentRoutingAppConfig>(
328 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700329 SegmentRoutingAppConfig.class, "segmentrouting") {
Charles Chan5270ed02016-01-30 23:22:37 -0800330 @Override
331 public SegmentRoutingAppConfig createConfig() {
332 return new SegmentRoutingAppConfig();
333 }
334 };
Pier Ventref34966c2016-11-07 16:21:04 -0800335
Charles Chanfc5c7802016-05-17 13:13:55 -0700336 private final ConfigFactory<ApplicationId, XConnectConfig> xConnectConfigFactory =
337 new ConfigFactory<ApplicationId, XConnectConfig>(
338 SubjectFactories.APP_SUBJECT_FACTORY,
339 XConnectConfig.class, "xconnect") {
340 @Override
341 public XConnectConfig createConfig() {
342 return new XConnectConfig();
343 }
344 };
Pier Ventref34966c2016-11-07 16:21:04 -0800345
Charles Chand55e84d2016-03-30 17:54:24 -0700346 private ConfigFactory<ApplicationId, McastConfig> mcastConfigFactory =
Charles Chanfc5c7802016-05-17 13:13:55 -0700347 new ConfigFactory<ApplicationId, McastConfig>(
348 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chand55e84d2016-03-30 17:54:24 -0700349 McastConfig.class, "multicast") {
350 @Override
351 public McastConfig createConfig() {
352 return new McastConfig();
353 }
354 };
355
Charles Chan116188d2016-02-18 14:22:42 -0800356 /**
357 * Segment Routing App ID.
358 */
Charles Chan2c15aca2016-11-09 20:51:44 -0800359 public static final String APP_NAME = "org.onosproject.segmentrouting";
Charles Chan59cc16d2017-02-02 16:20:42 -0800360
Charles Chane849c192016-01-11 18:28:54 -0800361 /**
362 * The default VLAN ID assigned to the interfaces without subnet config.
363 */
Charles Chan59cc16d2017-02-02 16:20:42 -0800364 public static final VlanId INTERNAL_VLAN = VlanId.vlanId((short) 4094);
Saurav Das0e99e2b2015-10-28 12:39:42 -0700365
Jonghwan Hyun800d9d02018-04-09 09:40:50 -0700366 /**
367 * Minumum and maximum value of dummy VLAN ID to be allocated.
368 */
369 public static final int MIN_DUMMY_VLAN_ID = 2;
370 public static final int MAX_DUMMY_VLAN_ID = 4093;
371
Saurav Das9a554292018-04-27 18:42:30 -0700372 Instant lastEdgePortEvent = Instant.EPOCH;
373
sanghob35a6192015-04-01 13:05:26 -0700374 @Activate
Charles Chan47933752017-11-30 15:37:50 -0800375 protected void activate(ComponentContext context) {
Charles Chan2c15aca2016-11-09 20:51:44 -0800376 appId = coreService.registerApplication(APP_NAME);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700377
Charles Chan50bb6ef2018-04-18 18:41:05 -0700378 mainEventExecutor = Executors.newSingleThreadScheduledExecutor(groupedThreads("sr-event-main", "%d", log));
379 hostEventExecutor = Executors.newSingleThreadScheduledExecutor(groupedThreads("sr-event-host", "%d", log));
380 routeEventExecutor = Executors.newSingleThreadScheduledExecutor(groupedThreads("sr-event-route", "%d", log));
381 mcastEventExecutor = Executors.newSingleThreadScheduledExecutor(groupedThreads("sr-event-mcast", "%d", log));
Charles Chan07f15f22018-05-08 21:35:50 -0700382 packetExecutor = Executors.newSingleThreadExecutor(groupedThreads("sr-packet", "%d", log));
Charles Chan50bb6ef2018-04-18 18:41:05 -0700383
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700384 log.debug("Creating EC map nsnextobjectivestore");
Saurav Das7bcbe702017-06-13 15:35:54 -0700385 EventuallyConsistentMapBuilder<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700386 nsNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
Saurav Das7bcbe702017-06-13 15:35:54 -0700387 dsNextObjStore = nsNextObjMapBuilder
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700388 .withName("nsnextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700389 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700390 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700391 .build();
Saurav Das7bcbe702017-06-13 15:35:54 -0700392 log.trace("Current size {}", dsNextObjStore.size());
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700393
Charles Chan59cc16d2017-02-02 16:20:42 -0800394 log.debug("Creating EC map vlannextobjectivestore");
395 EventuallyConsistentMapBuilder<VlanNextObjectiveStoreKey, Integer>
396 vlanNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
397 vlanNextObjStore = vlanNextObjMapBuilder
398 .withName("vlannextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700399 .withSerializer(createSerializer())
Charles Chanc42e84e2015-10-20 16:24:19 -0700400 .withTimestampProvider((k, v) -> new WallClockTimestamp())
401 .build();
402
Saurav Das4ce45962015-11-24 23:21:05 -0800403 log.debug("Creating EC map subnetnextobjectivestore");
404 EventuallyConsistentMapBuilder<PortNextObjectiveStoreKey, Integer>
405 portNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
406 portNextObjStore = portNextObjMapBuilder
407 .withName("portnextobjectivestore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700408 .withSerializer(createSerializer())
Saurav Das4ce45962015-11-24 23:21:05 -0800409 .withTimestampProvider((k, v) -> new WallClockTimestamp())
410 .build();
411
Jonghwan Hyun800d9d02018-04-09 09:40:50 -0700412 EventuallyConsistentMapBuilder<DummyVlanIdStoreKey, VlanId>
413 dummyVlanIdMapBuilder = storageService.eventuallyConsistentMapBuilder();
414 dummyVlanIdStore = dummyVlanIdMapBuilder
415 .withName("dummyvlanidstore")
416 .withSerializer(createSerializer())
417 .withTimestampProvider((k, v) -> new WallClockTimestamp())
418 .build();
419
sangho0b2b6d12015-05-20 22:16:38 -0700420 EventuallyConsistentMapBuilder<String, Tunnel> tunnelMapBuilder =
421 storageService.eventuallyConsistentMapBuilder();
sangho0b2b6d12015-05-20 22:16:38 -0700422 tunnelStore = tunnelMapBuilder
423 .withName("tunnelstore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700424 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700425 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho0b2b6d12015-05-20 22:16:38 -0700426 .build();
427
428 EventuallyConsistentMapBuilder<String, Policy> policyMapBuilder =
429 storageService.eventuallyConsistentMapBuilder();
sangho0b2b6d12015-05-20 22:16:38 -0700430 policyStore = policyMapBuilder
431 .withName("policystore")
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700432 .withSerializer(createSerializer())
Madan Jampanibcf1a482015-06-24 19:05:56 -0700433 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho0b2b6d12015-05-20 22:16:38 -0700434 .build();
435
Saurav Das80980c72016-03-23 11:22:49 -0700436 compCfgService.preSetProperty("org.onosproject.net.group.impl.GroupManager",
Pier Luigi9e5c5ca2017-01-12 18:14:58 -0800437 "purgeOnDisconnection", "true");
Saurav Das80980c72016-03-23 11:22:49 -0700438 compCfgService.preSetProperty("org.onosproject.net.flow.impl.FlowRuleManager",
Pier Luigi9e5c5ca2017-01-12 18:14:58 -0800439 "purgeOnDisconnection", "true");
Pier Luigi9e5c5ca2017-01-12 18:14:58 -0800440 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
441 "requestInterceptsEnabled", "false");
Charles Chand3baaba2017-08-08 15:13:37 -0700442 compCfgService.preSetProperty("org.onosproject.net.neighbour.impl.NeighbourResolutionManager",
Pier Luigi7e415132017-01-12 22:46:39 -0800443 "requestInterceptsEnabled", "false");
Charles Chanc760f382017-07-24 15:56:10 -0700444 compCfgService.preSetProperty("org.onosproject.dhcprelay.DhcpRelayManager",
Pier Luigi7e415132017-01-12 22:46:39 -0800445 "arpEnabled", "false");
Pier Luigi9b1d6262017-02-02 22:31:34 -0800446 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
447 "greedyLearningIpv6", "true");
Charles Chanc6d227e2017-02-28 15:15:17 -0800448 compCfgService.preSetProperty("org.onosproject.routing.cpr.ControlPlaneRedirectManager",
449 "forceUnprovision", "true");
Charles Chanef624ed2017-08-10 16:57:28 -0700450 compCfgService.preSetProperty("org.onosproject.routeservice.store.RouteStoreImpl",
Charles Chan73316522017-07-20 16:16:25 -0700451 "distributed", "true");
Charles Chan35a32322017-08-14 11:42:11 -0700452 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
453 "multihomingEnabled", "true");
Charles Chan807d87a2017-11-29 19:54:20 -0800454 compCfgService.preSetProperty("org.onosproject.provider.lldp.impl.LldpLinkProvider",
455 "staleLinkAge", "15000");
456 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
457 "allowDuplicateIps", "false");
Charles Chan47933752017-11-30 15:37:50 -0800458 compCfgService.registerProperties(getClass());
459 modified(context);
Saurav Das80980c72016-03-23 11:22:49 -0700460
Charles Chanb8e10c82015-10-14 11:24:40 -0700461 processor = new InternalPacketProcessor();
462 linkListener = new InternalLinkListener();
463 deviceListener = new InternalDeviceListener();
Charles Chanfc5c7802016-05-17 13:13:55 -0700464 appCfgHandler = new AppConfigHandler(this);
465 xConnectHandler = new XConnectHandler(this);
Charles Chand2990362016-04-18 13:44:03 -0700466 mcastHandler = new McastHandler(this);
467 hostHandler = new HostHandler(this);
Saurav Das45f48152018-01-18 12:07:33 -0800468 linkHandler = new LinkHandler(this);
Charles Chan03a73e02016-10-24 14:52:01 -0700469 routeHandler = new RouteHandler(this);
Pier Ventre735b8c82016-12-02 08:16:05 -0800470 neighbourHandler = new SegmentRoutingNeighbourDispatcher(this);
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800471 l2TunnelHandler = new DefaultL2TunnelHandler(this);
Pier Luigi83f919b2018-02-15 16:33:08 +0100472 topologyHandler = new TopologyHandler(this);
Charles Chanb8e10c82015-10-14 11:24:40 -0700473
Charles Chan3e783d02016-02-26 22:19:52 -0800474 cfgService.addListener(cfgListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700475 cfgService.registerConfigFactory(deviceConfigFactory);
476 cfgService.registerConfigFactory(appConfigFactory);
Charles Chanfc5c7802016-05-17 13:13:55 -0700477 cfgService.registerConfigFactory(xConnectConfigFactory);
Charles Chand55e84d2016-03-30 17:54:24 -0700478 cfgService.registerConfigFactory(mcastConfigFactory);
Saurav Dase7f51012018-02-09 17:26:45 -0800479 log.info("Configuring network before adding listeners");
Andrea Campanella6468e1f2018-04-17 12:09:34 +0200480
Charles Chan132393a2018-01-04 14:26:07 -0800481 cfgListener.configureNetwork();
482
Charles Chan5270ed02016-01-30 23:22:37 -0800483 hostService.addListener(hostListener);
Charles Chanb8e10c82015-10-14 11:24:40 -0700484 packetService.addProcessor(processor, PacketProcessor.director(2));
485 linkService.addListener(linkListener);
486 deviceService.addListener(deviceListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700487 multicastRouteService.addListener(mcastListener);
Charles Chanc7a8a682017-06-19 00:43:31 -0700488 routeService.addListener(routeListener);
Pier Luigi83f919b2018-02-15 16:33:08 +0100489 topologyService.addListener(topologyListener);
Charles Chan50bb6ef2018-04-18 18:41:05 -0700490 mastershipService.addListener(mastershipListener);
Saurav Das201762d2018-04-21 17:19:48 -0700491 clusterService.addListener(clusterListener);
Charles Chanb8e10c82015-10-14 11:24:40 -0700492
Charles Chanb39777c2018-03-09 15:53:44 -0800493 linkHandler.init();
Andreas Pantelopoulos4a768c02018-01-11 07:53:48 -0800494 l2TunnelHandler.init();
495
Andrea Campanella6468e1f2018-04-17 12:09:34 +0200496 networkConfigCompletion.whenComplete((value, ex) -> {
497 //setting to null for easier fall through
498 networkConfigCompletion = null;
499 //process all queued events
Charles Chan10b2fee2018-04-21 00:44:29 -0700500 queuedEvents.forEach(event -> {
Andrea Campanella6468e1f2018-04-17 12:09:34 +0200501 mainEventExecutor.execute(new InternalEventHandler(event));
502 });
503 });
504
sanghob35a6192015-04-01 13:05:26 -0700505 log.info("Started");
506 }
507
Saurav Das45f48152018-01-18 12:07:33 -0800508 KryoNamespace.Builder createSerializer() {
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700509 return new KryoNamespace.Builder()
510 .register(KryoNamespaces.API)
Saurav Das7bcbe702017-06-13 15:35:54 -0700511 .register(DestinationSetNextObjectiveStoreKey.class,
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800512 VlanNextObjectiveStoreKey.class,
513 DestinationSet.class,
514 NextNeighbors.class,
515 Tunnel.class,
516 DefaultTunnel.class,
517 Policy.class,
518 TunnelPolicy.class,
519 Policy.Type.class,
520 PortNextObjectiveStoreKey.class,
521 XConnectStoreKey.class,
522 L2Tunnel.class,
523 L2TunnelPolicy.class,
524 DefaultL2Tunnel.class,
Jonghwan Hyun800d9d02018-04-09 09:40:50 -0700525 DefaultL2TunnelPolicy.class,
526 DummyVlanIdStoreKey.class
Jonathan Hartc19f7c12016-04-12 15:39:44 -0700527 );
528 }
529
sanghob35a6192015-04-01 13:05:26 -0700530 @Deactivate
531 protected void deactivate() {
Charles Chan50bb6ef2018-04-18 18:41:05 -0700532 mainEventExecutor.shutdown();
533 hostEventExecutor.shutdown();
534 routeEventExecutor.shutdown();
535 mcastEventExecutor.shutdown();
Charles Chan07f15f22018-05-08 21:35:50 -0700536 packetExecutor.shutdown();
Charles Chan50bb6ef2018-04-18 18:41:05 -0700537
Ray Milkey749996b2018-05-11 09:59:19 -0700538 mainEventExecutor = null;
539 hostEventExecutor = null;
540 routeEventExecutor = null;
541 mcastEventExecutor = null;
542 packetExecutor = null;
543
Charles Chand6832882015-10-05 17:50:33 -0700544 cfgService.removeListener(cfgListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700545 cfgService.unregisterConfigFactory(deviceConfigFactory);
546 cfgService.unregisterConfigFactory(appConfigFactory);
Charles Chan03a73e02016-10-24 14:52:01 -0700547 cfgService.unregisterConfigFactory(xConnectConfigFactory);
Charles Chand55e84d2016-03-30 17:54:24 -0700548 cfgService.unregisterConfigFactory(mcastConfigFactory);
Charles Chan47933752017-11-30 15:37:50 -0800549 compCfgService.unregisterProperties(getClass(), false);
Charles Chand6832882015-10-05 17:50:33 -0700550
Charles Chanc7a8a682017-06-19 00:43:31 -0700551 hostService.removeListener(hostListener);
sanghob35a6192015-04-01 13:05:26 -0700552 packetService.removeProcessor(processor);
Charles Chanb8e10c82015-10-14 11:24:40 -0700553 linkService.removeListener(linkListener);
554 deviceService.removeListener(deviceListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700555 multicastRouteService.removeListener(mcastListener);
Charles Chan03a73e02016-10-24 14:52:01 -0700556 routeService.removeListener(routeListener);
Pier Luigi83f919b2018-02-15 16:33:08 +0100557 topologyService.removeListener(topologyListener);
Charles Chan50bb6ef2018-04-18 18:41:05 -0700558 mastershipService.removeListener(mastershipListener);
Saurav Das201762d2018-04-21 17:19:48 -0700559 clusterService.removeListener(clusterListener);
Charles Chand55e84d2016-03-30 17:54:24 -0700560
Charles Chan0aa674e2017-02-23 15:44:08 -0800561 neighbourResolutionService.unregisterNeighbourHandlers(appId);
562
sanghob35a6192015-04-01 13:05:26 -0700563 processor = null;
Charles Chanb8e10c82015-10-14 11:24:40 -0700564 linkListener = null;
Charles Chand55e84d2016-03-30 17:54:24 -0700565 deviceListener = null;
Charles Chan6577f612018-04-19 13:10:01 -0700566 groupHandlerMap.forEach((k, v) -> v.shutdown());
Charles Chanb8e10c82015-10-14 11:24:40 -0700567 groupHandlerMap.clear();
Saurav Dasc6ff8f02018-04-23 18:42:12 -0700568 defaultRoutingHandler.shutdown();
Charles Chanb8e10c82015-10-14 11:24:40 -0700569
Saurav Das7bcbe702017-06-13 15:35:54 -0700570 dsNextObjStore.destroy();
Charles Chan59cc16d2017-02-02 16:20:42 -0800571 vlanNextObjStore.destroy();
Charles Chand55e84d2016-03-30 17:54:24 -0700572 portNextObjStore.destroy();
Jonghwan Hyun800d9d02018-04-09 09:40:50 -0700573 dummyVlanIdStore.destroy();
Charles Chand55e84d2016-03-30 17:54:24 -0700574 tunnelStore.destroy();
575 policyStore.destroy();
Pier Luigib72201b2018-01-25 16:16:02 +0100576
577 mcastHandler.terminate();
sanghob35a6192015-04-01 13:05:26 -0700578 log.info("Stopped");
579 }
580
Charles Chan47933752017-11-30 15:37:50 -0800581 @Modified
582 private void modified(ComponentContext context) {
583 Dictionary<?, ?> properties = context.getProperties();
584 if (properties == null) {
585 return;
586 }
587
588 String strActiveProving = Tools.get(properties, "activeProbing");
589 boolean expectActiveProbing = Boolean.parseBoolean(strActiveProving);
Charles Chan47933752017-11-30 15:37:50 -0800590 if (expectActiveProbing != activeProbing) {
591 activeProbing = expectActiveProbing;
592 log.info("{} active probing", activeProbing ? "Enabling" : "Disabling");
593 }
Saurav Das9a554292018-04-27 18:42:30 -0700594
595 String strSingleHomedDown = Tools.get(properties, "singleHomedDown");
596 boolean expectSingleHomedDown = Boolean.parseBoolean(strSingleHomedDown);
597 if (expectSingleHomedDown != singleHomedDown) {
598 singleHomedDown = expectSingleHomedDown;
599 log.info("{} downing of single homed hosts for lost uplinks",
600 singleHomedDown ? "Enabling" : "Disabling");
601 if (singleHomedDown && linkHandler != null) {
602 hostService.getHosts().forEach(host -> host.locations()
603 .forEach(loc -> {
604 if (interfaceService.isConfigured(loc)) {
605 linkHandler.checkUplinksForHost(loc);
606 }
607 }));
608 } else {
609 log.warn("Disabling singleHomedDown does not re-enable already "
610 + "downed ports for single-homed hosts");
611 }
612 }
Charles Chan47933752017-11-30 15:37:50 -0800613 }
614
sangho1e575652015-05-14 00:39:53 -0700615 @Override
616 public List<Tunnel> getTunnels() {
617 return tunnelHandler.getTunnels();
618 }
619
620 @Override
sangho71abe1b2015-06-29 14:58:47 -0700621 public TunnelHandler.Result createTunnel(Tunnel tunnel) {
622 return tunnelHandler.createTunnel(tunnel);
sangho1e575652015-05-14 00:39:53 -0700623 }
624
625 @Override
sangho71abe1b2015-06-29 14:58:47 -0700626 public TunnelHandler.Result removeTunnel(Tunnel tunnel) {
sangho1e575652015-05-14 00:39:53 -0700627 for (Policy policy: policyHandler.getPolicies()) {
628 if (policy.type() == Policy.Type.TUNNEL_FLOW) {
629 TunnelPolicy tunnelPolicy = (TunnelPolicy) policy;
630 if (tunnelPolicy.tunnelId().equals(tunnel.id())) {
631 log.warn("Cannot remove the tunnel used by a policy");
sangho71abe1b2015-06-29 14:58:47 -0700632 return TunnelHandler.Result.TUNNEL_IN_USE;
sangho1e575652015-05-14 00:39:53 -0700633 }
634 }
635 }
sangho71abe1b2015-06-29 14:58:47 -0700636 return tunnelHandler.removeTunnel(tunnel);
sangho1e575652015-05-14 00:39:53 -0700637 }
638
639 @Override
sangho71abe1b2015-06-29 14:58:47 -0700640 public PolicyHandler.Result removePolicy(Policy policy) {
641 return policyHandler.removePolicy(policy);
sangho1e575652015-05-14 00:39:53 -0700642 }
643
644 @Override
sangho71abe1b2015-06-29 14:58:47 -0700645 public PolicyHandler.Result createPolicy(Policy policy) {
646 return policyHandler.createPolicy(policy);
sangho1e575652015-05-14 00:39:53 -0700647 }
648
649 @Override
650 public List<Policy> getPolicies() {
651 return policyHandler.getPolicies();
652 }
653
Saurav Das59232cf2016-04-27 18:35:50 -0700654 @Override
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700655 public Set<L2TunnelDescription> getL2TunnelDescriptions(boolean pending) {
656 return l2TunnelHandler.getL2Descriptions(pending);
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700657 }
658
659 @Override
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800660 public List<L2Tunnel> getL2Tunnels() {
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700661 return l2TunnelHandler.getL2Tunnels();
662 }
663
664 @Override
Andreas Pantelopoulosb21547d2018-02-22 12:32:42 -0800665 public List<L2TunnelPolicy> getL2Policies() {
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700666 return l2TunnelHandler.getL2Policies();
667 }
668
Saurav Das5a356042018-04-06 20:16:01 -0700669 @Override
Andreas Pantelopoulosffe69742018-03-20 13:58:49 -0700670 @Deprecated
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700671 public L2TunnelHandler.Result addPseudowiresBulk(List<DefaultL2TunnelDescription> bulkPseudowires) {
672
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700673 // get both added and pending pseudowires
674 List<L2TunnelDescription> pseudowires = new ArrayList<>();
675 pseudowires.addAll(l2TunnelHandler.getL2Descriptions(false));
676 pseudowires.addAll(l2TunnelHandler.getL2Descriptions(true));
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700677 pseudowires.addAll(bulkPseudowires);
Andreas Pantelopoulos811bbae2018-03-15 16:56:09 -0700678
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700679 Set<L2TunnelDescription> newPseudowires = new HashSet(bulkPseudowires);
680
Andreas Pantelopoulosffe69742018-03-20 13:58:49 -0700681 L2TunnelHandler.Result retRes = L2TunnelHandler.Result.SUCCESS;
682 L2TunnelHandler.Result res;
683 for (DefaultL2TunnelDescription pw : bulkPseudowires) {
684 res = addPseudowire(pw);
685 if (res != L2TunnelHandler.Result.SUCCESS) {
686 log.error("Pseudowire with id {} can not be instantiated !", res);
687 retRes = res;
688 }
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700689 }
Andreas Pantelopoulosffe69742018-03-20 13:58:49 -0700690
691 return retRes;
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -0700692 }
693
694 @Override
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800695 public L2TunnelHandler.Result addPseudowire(L2TunnelDescription l2TunnelDescription) {
Andreas Pantelopoulos935d59d2018-03-21 16:44:18 -0700696 return l2TunnelHandler.deployPseudowire(l2TunnelDescription);
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700697 }
698
699 @Override
Andreas Pantelopouloscd339592018-02-23 14:18:00 -0800700 public L2TunnelHandler.Result removePseudowire(Integer pwId) {
Andreas Pantelopoulos935d59d2018-03-21 16:44:18 -0700701 return l2TunnelHandler.tearDownPseudowire(pwId);
Andreas Pantelopoulos27532cd2017-10-23 12:18:25 -0700702 }
703
704 @Override
Saurav Das59232cf2016-04-27 18:35:50 -0700705 public void rerouteNetwork() {
706 cfgListener.configureNetwork();
Saurav Das59232cf2016-04-27 18:35:50 -0700707 }
708
Charles Chanc81c45b2016-10-20 17:02:44 -0700709 @Override
Pier Ventre10bd8d12016-11-26 21:05:22 -0800710 public Map<DeviceId, Set<IpPrefix>> getDeviceSubnetMap() {
711 Map<DeviceId, Set<IpPrefix>> deviceSubnetMap = Maps.newHashMap();
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800712 deviceConfiguration.getRouters().forEach(device ->
713 deviceSubnetMap.put(device, deviceConfiguration.getSubnets(device)));
Charles Chanc81c45b2016-10-20 17:02:44 -0700714 return deviceSubnetMap;
715 }
716
Saurav Dasc88d4662017-05-15 15:34:25 -0700717
718 @Override
719 public ImmutableMap<DeviceId, EcmpShortestPathGraph> getCurrentEcmpSpg() {
720 if (defaultRoutingHandler != null) {
721 return defaultRoutingHandler.getCurrentEmcpSpgMap();
722 } else {
723 return null;
724 }
725 }
726
727 @Override
Saurav Das7bcbe702017-06-13 15:35:54 -0700728 public ImmutableMap<DestinationSetNextObjectiveStoreKey, NextNeighbors> getDestinationSet() {
729 if (dsNextObjStore != null) {
730 return ImmutableMap.copyOf(dsNextObjStore.entrySet());
Saurav Dasc88d4662017-05-15 15:34:25 -0700731 } else {
732 return ImmutableMap.of();
733 }
734 }
735
Saurav Dasceccf242017-08-03 18:30:35 -0700736 @Override
737 public void verifyGroups(DeviceId id) {
738 DefaultGroupHandler gh = groupHandlerMap.get(id);
739 if (gh != null) {
740 gh.triggerBucketCorrector();
741 }
742 }
743
Saurav Dasc568c342018-01-25 09:49:01 -0800744 @Override
745 public ImmutableMap<Link, Boolean> getSeenLinks() {
746 return linkHandler.getSeenLinks();
747 }
748
749 @Override
750 public ImmutableMap<DeviceId, Set<PortNumber>> getDownedPortState() {
751 return linkHandler.getDownedPorts();
752 }
753
Pier Luigib29144d2018-01-15 18:06:43 +0100754 @Override
755 public Map<McastStoreKey, Integer> getMcastNextIds(IpAddress mcastIp) {
756 return mcastHandler.getMcastNextIds(mcastIp);
757 }
758
759 @Override
Pier Luigi96fe0772018-02-28 12:10:50 +0100760 public Map<McastStoreKey, McastRole> getMcastRoles(IpAddress mcastIp) {
Pier Luigib29144d2018-01-15 18:06:43 +0100761 return mcastHandler.getMcastRoles(mcastIp);
762 }
763
764 @Override
Pier3e793752018-04-19 16:47:06 +0200765 public Map<McastRoleStoreKey, McastRole> getMcastRoles(IpAddress mcastIp, ConnectPoint sourcecp) {
766 return mcastHandler.getMcastRoles(mcastIp, sourcecp);
767 }
768
769 @Override
Pier Luigib29144d2018-01-15 18:06:43 +0100770 public Map<ConnectPoint, List<ConnectPoint>> getMcastPaths(IpAddress mcastIp) {
771 return mcastHandler.getMcastPaths(mcastIp);
772 }
773
Pier96f63cb2018-04-17 16:29:56 +0200774 @Override
Pierb1fe7382018-04-17 17:25:22 +0200775 public Multimap<ConnectPoint, List<ConnectPoint>> getMcastTrees(IpAddress mcastIp,
776 ConnectPoint sourcecp) {
777 return mcastHandler.getMcastTrees(mcastIp, sourcecp);
778 }
779
780 @Override
Pier96f63cb2018-04-17 16:29:56 +0200781 public Map<IpAddress, NodeId> getMcastLeaders(IpAddress mcastIp) {
782 return mcastHandler.getMcastLeaders(mcastIp);
783 }
784
Charles Chan8bc75ee2018-04-17 18:56:53 -0700785 @Override
786 public Map<Set<DeviceId>, NodeId> getShouldProgram() {
787 return defaultRoutingHandler == null ? ImmutableMap.of() :
788 ImmutableMap.copyOf(defaultRoutingHandler.shouldProgram);
789 }
790
791 @Override
792 public Map<DeviceId, Boolean> getShouldProgramCache() {
793 return defaultRoutingHandler == null ? ImmutableMap.of() :
794 ImmutableMap.copyOf(defaultRoutingHandler.shouldProgramCache);
795 }
796
sanghof9d0bf12015-05-19 11:57:42 -0700797 /**
Ray Milkeye4afdb52017-04-05 09:42:04 -0700798 * Extracts the application ID from the manager.
799 *
800 * @return application ID
801 */
802 public ApplicationId appId() {
803 return appId;
804 }
805
806 /**
807 * Returns the device configuration.
808 *
809 * @return device configuration
810 */
811 public DeviceConfiguration deviceConfiguration() {
812 return deviceConfiguration;
813 }
814
815 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700816 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan5bc32632017-08-22 15:07:34 -0700817 * Used to keep track on MPLS group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -0700818 *
819 * @return next objective ID store
820 */
Saurav Das7bcbe702017-06-13 15:35:54 -0700821 public EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
822 dsNextObjStore() {
823 return dsNextObjStore;
Ray Milkeye4afdb52017-04-05 09:42:04 -0700824 }
825
826 /**
Charles Chan5bc32632017-08-22 15:07:34 -0700827 * Per device next objective ID store with (device id + vlanid) as key.
828 * Used to keep track on L2 flood group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -0700829 *
830 * @return vlan next object store
831 */
832 public EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer> vlanNextObjStore() {
833 return vlanNextObjStore;
834 }
835
836 /**
Charles Chan5bc32632017-08-22 15:07:34 -0700837 * Per device next objective ID store with (device id + port + treatment + meta) as key.
838 * Used to keep track on L2 interface group and L3 unicast group information.
Ray Milkeye4afdb52017-04-05 09:42:04 -0700839 *
840 * @return port next object store.
841 */
842 public EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer> portNextObjStore() {
843 return portNextObjStore;
844 }
845
846 /**
Jonghwan Hyun800d9d02018-04-09 09:40:50 -0700847 * Per port dummy VLAN ID store with (connect point + ip address) as key.
848 * Used to keep track on dummy VLAN ID allocation.
849 *
850 * @return dummy vlan id store.
851 */
852 public EventuallyConsistentMap<DummyVlanIdStoreKey, VlanId> dummyVlanIdStore() {
853 return dummyVlanIdStore;
854 }
855
856 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700857 * Returns the MPLS-ECMP configuration which indicates whether ECMP on
858 * labeled packets should be programmed or not.
Pier Ventre98161782016-10-31 15:00:01 -0700859 *
860 * @return MPLS-ECMP value
861 */
862 public boolean getMplsEcmp() {
863 SegmentRoutingAppConfig segmentRoutingAppConfig = cfgService
864 .getConfig(this.appId, SegmentRoutingAppConfig.class);
865 return segmentRoutingAppConfig != null && segmentRoutingAppConfig.mplsEcmp();
866 }
867
868 /**
sanghof9d0bf12015-05-19 11:57:42 -0700869 * Returns the tunnel object with the tunnel ID.
870 *
871 * @param tunnelId Tunnel ID
872 * @return Tunnel reference
873 */
sangho1e575652015-05-14 00:39:53 -0700874 public Tunnel getTunnel(String tunnelId) {
875 return tunnelHandler.getTunnel(tunnelId);
876 }
877
Charles Chan7ffd81f2017-02-08 15:52:08 -0800878 /**
Charles Chanf9a52702017-06-16 15:19:24 -0700879 * Returns internal VLAN for untagged hosts on given connect point.
880 * <p>
881 * The internal VLAN is either vlan-untagged for an access port,
882 * or vlan-native for a trunk port.
883 *
884 * @param connectPoint connect point
885 * @return internal VLAN or null if both vlan-untagged and vlan-native are undefined
886 */
Pier Luigi96fe0772018-02-28 12:10:50 +0100887 public VlanId getInternalVlanId(ConnectPoint connectPoint) {
Charles Chan971d7ba2018-05-01 11:50:20 -0700888 VlanId untaggedVlanId = interfaceService.getUntaggedVlanId(connectPoint);
889 VlanId nativeVlanId = interfaceService.getNativeVlanId(connectPoint);
Charles Chanf9a52702017-06-16 15:19:24 -0700890 return untaggedVlanId != null ? untaggedVlanId : nativeVlanId;
891 }
892
893 /**
Charles Chan65238242017-06-22 18:03:14 -0700894 * Returns optional pair device ID of given device.
895 *
896 * @param deviceId device ID
897 * @return optional pair device ID. Might be empty if pair device is not configured
898 */
899 Optional<DeviceId> getPairDeviceId(DeviceId deviceId) {
900 SegmentRoutingDeviceConfig deviceConfig =
901 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
902 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairDeviceId);
903 }
904 /**
905 * Returns optional pair device local port of given device.
906 *
907 * @param deviceId device ID
908 * @return optional pair device ID. Might be empty if pair device is not configured
909 */
Saurav Das9a554292018-04-27 18:42:30 -0700910 public Optional<PortNumber> getPairLocalPort(DeviceId deviceId) {
Charles Chan65238242017-06-22 18:03:14 -0700911 SegmentRoutingDeviceConfig deviceConfig =
912 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
913 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairLocalPort);
914 }
915
916 /**
Charles Chan9640c812017-08-23 13:55:39 -0700917 * Returns locations of given resolved route.
918 *
919 * @param resolvedRoute resolved route
920 * @return locations of nexthop. Might be empty if next hop is not found
921 */
922 Set<ConnectPoint> nextHopLocations(ResolvedRoute resolvedRoute) {
923 HostId hostId = HostId.hostId(resolvedRoute.nextHopMac(), resolvedRoute.nextHopVlan());
924 return Optional.ofNullable(hostService.getHost(hostId))
925 .map(Host::locations).orElse(Sets.newHashSet())
926 .stream().map(l -> (ConnectPoint) l).collect(Collectors.toSet());
927 }
928
929 /**
Charles Chan7ffd81f2017-02-08 15:52:08 -0800930 * Returns vlan port map of given device.
931 *
932 * @param deviceId device id
933 * @return vlan-port multimap
934 */
935 public Multimap<VlanId, PortNumber> getVlanPortMap(DeviceId deviceId) {
936 HashMultimap<VlanId, PortNumber> vlanPortMap = HashMultimap.create();
937
938 interfaceService.getInterfaces().stream()
939 .filter(intf -> intf.connectPoint().deviceId().equals(deviceId))
940 .forEach(intf -> {
941 vlanPortMap.put(intf.vlanUntagged(), intf.connectPoint().port());
Charles Chan65238242017-06-22 18:03:14 -0700942 intf.vlanTagged().forEach(vlanTagged ->
943 vlanPortMap.put(vlanTagged, intf.connectPoint().port())
944 );
Charles Chan7ffd81f2017-02-08 15:52:08 -0800945 vlanPortMap.put(intf.vlanNative(), intf.connectPoint().port());
946 });
947 vlanPortMap.removeAll(VlanId.NONE);
948
949 return vlanPortMap;
950 }
951
952 /**
Charles Chan59cc16d2017-02-02 16:20:42 -0800953 * Returns the next objective ID for the given vlan id. It is expected
Saurav Das4ce45962015-11-24 23:21:05 -0800954 * that the next-objective has been pre-created from configuration.
Charles Chanc42e84e2015-10-20 16:24:19 -0700955 *
956 * @param deviceId Device ID
Charles Chan59cc16d2017-02-02 16:20:42 -0800957 * @param vlanId VLAN ID
Saurav Das4ce45962015-11-24 23:21:05 -0800958 * @return next objective ID or -1 if it was not found
Charles Chanc42e84e2015-10-20 16:24:19 -0700959 */
Charles Chan65238242017-06-22 18:03:14 -0700960 int getVlanNextObjectiveId(DeviceId deviceId, VlanId vlanId) {
Charles Chanc42e84e2015-10-20 16:24:19 -0700961 if (groupHandlerMap.get(deviceId) != null) {
Charles Chan59cc16d2017-02-02 16:20:42 -0800962 log.trace("getVlanNextObjectiveId query in device {}", deviceId);
963 return groupHandlerMap.get(deviceId).getVlanNextObjectiveId(vlanId);
Charles Chanc42e84e2015-10-20 16:24:19 -0700964 } else {
Charles Chan59cc16d2017-02-02 16:20:42 -0800965 log.warn("getVlanNextObjectiveId query - groupHandler for "
Saurav Das4ce45962015-11-24 23:21:05 -0800966 + "device {} not found", deviceId);
967 return -1;
968 }
969 }
970
971 /**
972 * Returns the next objective ID for the given portNumber, given the treatment.
973 * There could be multiple different treatments to the same outport, which
Saurav Das961beb22017-03-29 19:09:17 -0700974 * would result in different objectives. If the next object does not exist,
975 * and should be created, a new one is created and its id is returned.
Saurav Das4ce45962015-11-24 23:21:05 -0800976 *
977 * @param deviceId Device ID
978 * @param portNum port number on device for which NextObjective is queried
979 * @param treatment the actions to apply on the packets (should include outport)
980 * @param meta metadata passed into the creation of a Next Objective if necessary
Saurav Das961beb22017-03-29 19:09:17 -0700981 * @param createIfMissing true if a next object should be created if not found
Saurav Das59232cf2016-04-27 18:35:50 -0700982 * @return next objective ID or -1 if an error occurred during retrieval or creation
Saurav Das4ce45962015-11-24 23:21:05 -0800983 */
984 public int getPortNextObjectiveId(DeviceId deviceId, PortNumber portNum,
985 TrafficTreatment treatment,
Saurav Das961beb22017-03-29 19:09:17 -0700986 TrafficSelector meta,
987 boolean createIfMissing) {
Saurav Das4ce45962015-11-24 23:21:05 -0800988 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
989 if (ghdlr != null) {
Saurav Das961beb22017-03-29 19:09:17 -0700990 return ghdlr.getPortNextObjectiveId(portNum, treatment, meta, createIfMissing);
Saurav Das4ce45962015-11-24 23:21:05 -0800991 } else {
Charles Chane849c192016-01-11 18:28:54 -0800992 log.warn("getPortNextObjectiveId query - groupHandler for device {}"
993 + " not found", deviceId);
994 return -1;
995 }
996 }
997
Saurav Dasc88d4662017-05-15 15:34:25 -0700998 /**
999 * Returns the group handler object for the specified device id.
1000 *
1001 * @param devId the device identifier
1002 * @return the groupHandler object for the device id, or null if not found
1003 */
Charles Chan65238242017-06-22 18:03:14 -07001004 DefaultGroupHandler getGroupHandler(DeviceId devId) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001005 return groupHandlerMap.get(devId);
1006 }
1007
1008 /**
Saurav Dasceccf242017-08-03 18:30:35 -07001009 * Returns the default routing handler object.
1010 *
1011 * @return the default routing handler object
1012 */
1013 public DefaultRoutingHandler getRoutingHandler() {
1014 return defaultRoutingHandler;
1015 }
1016
Jonghwan Hyun800d9d02018-04-09 09:40:50 -07001017 /**
1018 * Returns new dummy VLAN ID.
1019 * Dummy VLAN ID should be unique in each connect point.
1020 *
1021 * @param cp connect point
1022 * @param ipAddress IP address
1023 * @return new dummy VLAN ID. Returns VlanId.NONE if no VLAN ID is available.
1024 */
1025 public synchronized VlanId allocateDummyVlanId(ConnectPoint cp, IpAddress ipAddress) {
1026 Set<VlanId> usedVlanId = Sets.union(getVlanPortMap(cp.deviceId()).keySet(),
1027 dummyVlanIdStore.entrySet().stream().filter(entry ->
1028 (entry.getKey()).connectPoint().equals(cp))
1029 .map(Map.Entry::getValue)
1030 .collect(Collectors.toSet()));
1031
1032 VlanId dummyVlanId = IntStream.range(MIN_DUMMY_VLAN_ID, MAX_DUMMY_VLAN_ID).mapToObj(
1033 i -> VlanId.vlanId((short) (i & 0xFFFF))
1034 ).filter(vlanId -> !usedVlanId.contains(vlanId)).findFirst().orElse(VlanId.NONE);
1035
1036 if (!dummyVlanId.equals(VlanId.NONE)) {
1037 this.dummyVlanIdStore.put(new DummyVlanIdStoreKey(cp, ipAddress), dummyVlanId);
1038 log.debug("Dummy VLAN ID {} is allocated to {}, {}", dummyVlanId, cp, ipAddress);
1039 } else {
1040 log.error("Failed to allocate dummy VLAN ID for {}, {}", cp, ipAddress);
1041 }
1042 return dummyVlanId;
1043 }
1044
1045
sanghob35a6192015-04-01 13:05:26 -07001046 private class InternalPacketProcessor implements PacketProcessor {
sanghob35a6192015-04-01 13:05:26 -07001047 @Override
1048 public void process(PacketContext context) {
Charles Chan07f15f22018-05-08 21:35:50 -07001049 packetExecutor.execute(() -> processPacketInternal(context));
1050 }
sanghob35a6192015-04-01 13:05:26 -07001051
Charles Chan07f15f22018-05-08 21:35:50 -07001052 private void processPacketInternal(PacketContext context) {
sanghob35a6192015-04-01 13:05:26 -07001053 if (context.isHandled()) {
1054 return;
1055 }
1056
1057 InboundPacket pkt = context.inPacket();
1058 Ethernet ethernet = pkt.parsed();
Pier Luigi7dad71c2017-02-01 13:50:04 -08001059
1060 if (ethernet == null) {
1061 return;
1062 }
1063
Saurav Das7bcbe702017-06-13 15:35:54 -07001064 log.trace("Rcvd pktin from {}: {}", context.inPacket().receivedFrom(),
1065 ethernet);
Pier Ventree0ae7a32016-11-23 09:57:42 -08001066 if (ethernet.getEtherType() == TYPE_ARP) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001067 log.warn("Received unexpected ARP packet on {}",
1068 context.inPacket().receivedFrom());
Saurav Das76ae6812017-03-15 15:15:14 -07001069 log.trace("{}", ethernet);
Pier Ventre968da122016-12-09 17:26:04 -08001070 return;
sanghob35a6192015-04-01 13:05:26 -07001071 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV4) {
Pier Ventre735b8c82016-12-02 08:16:05 -08001072 IPv4 ipv4Packet = (IPv4) ethernet.getPayload();
1073 //ipHandler.addToPacketBuffer(ipv4Packet);
1074 if (ipv4Packet.getProtocol() == IPv4.PROTOCOL_ICMP) {
1075 icmpHandler.processIcmp(ethernet, pkt.receivedFrom());
sanghob35a6192015-04-01 13:05:26 -07001076 } else {
Charles Chan50035632017-01-13 17:20:44 -08001077 // NOTE: We don't support IP learning at this moment so this
1078 // is not necessary. Also it causes duplication of DHCP packets.
Pier Ventre968da122016-12-09 17:26:04 -08001079 // ipHandler.processPacketIn(ipv4Packet, pkt.receivedFrom());
sanghob35a6192015-04-01 13:05:26 -07001080 }
Pier Ventre10bd8d12016-11-26 21:05:22 -08001081 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV6) {
1082 IPv6 ipv6Packet = (IPv6) ethernet.getPayload();
Pier Ventre735b8c82016-12-02 08:16:05 -08001083 //ipHandler.addToPacketBuffer(ipv6Packet);
Pier Luigi7dad71c2017-02-01 13:50:04 -08001084 // We deal with the packet only if the packet is a ICMP6 ECHO/REPLY
Pier Ventre735b8c82016-12-02 08:16:05 -08001085 if (ipv6Packet.getNextHeader() == IPv6.PROTOCOL_ICMP6) {
1086 ICMP6 icmp6Packet = (ICMP6) ipv6Packet.getPayload();
1087 if (icmp6Packet.getIcmpType() == ICMP6.ECHO_REQUEST ||
1088 icmp6Packet.getIcmpType() == ICMP6.ECHO_REPLY) {
1089 icmpHandler.processIcmpv6(ethernet, pkt.receivedFrom());
1090 } else {
Saurav Dasc88d4662017-05-15 15:34:25 -07001091 log.trace("Received ICMPv6 0x{} - not handled",
Charles Chan0ed44fb2017-03-13 13:10:30 -07001092 Integer.toHexString(icmp6Packet.getIcmpType() & 0xff));
Pier Ventre735b8c82016-12-02 08:16:05 -08001093 }
1094 } else {
1095 // NOTE: We don't support IP learning at this moment so this
1096 // is not necessary. Also it causes duplication of DHCPv6 packets.
1097 // ipHandler.processPacketIn(ipv6Packet, pkt.receivedFrom());
1098 }
sanghob35a6192015-04-01 13:05:26 -07001099 }
1100 }
1101 }
1102
sanghob35a6192015-04-01 13:05:26 -07001103 private class InternalEventHandler implements Runnable {
Charles Chan9b7217c2018-04-05 16:31:15 -07001104 private Event event;
1105
1106 InternalEventHandler(Event event) {
1107 this.event = event;
1108 }
1109
Srikanth Vavilapalli4db76e32015-04-07 15:12:32 -07001110 @Override
sanghob35a6192015-04-01 13:05:26 -07001111 public void run() {
Charles Chan9b7217c2018-04-05 16:31:15 -07001112 try {
1113 // TODO We should also change SR routing and PW to listen to TopologyEvents
1114 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1115 event.type() == LinkEvent.Type.LINK_UPDATED) {
1116 linkHandler.processLinkAdded((Link) event.subject());
1117 } else if (event.type() == LinkEvent.Type.LINK_REMOVED) {
1118 linkHandler.processLinkRemoved((Link) event.subject());
1119 } else if (event.type() == DeviceEvent.Type.DEVICE_ADDED ||
1120 event.type() == DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED ||
1121 event.type() == DeviceEvent.Type.DEVICE_UPDATED) {
1122 DeviceId deviceId = ((Device) event.subject()).id();
1123 if (deviceService.isAvailable(deviceId)) {
1124 log.info("** DEVICE UP Processing device event {} "
1125 + "for available device {}",
1126 event.type(), ((Device) event.subject()).id());
1127 processDeviceAdded((Device) event.subject());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001128 } else {
Charles Chan9b7217c2018-04-05 16:31:15 -07001129 log.info(" ** DEVICE DOWN Processing device event {}"
1130 + " for unavailable device {}",
1131 event.type(), ((Device) event.subject()).id());
1132 processDeviceRemoved((Device) event.subject());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001133 }
Charles Chan9b7217c2018-04-05 16:31:15 -07001134 } else if (event.type() == DeviceEvent.Type.PORT_ADDED) {
1135 // typically these calls come when device is added first time
1136 // so port filtering rules are handled at the device_added event.
1137 // port added calls represent all ports on the device,
1138 // enabled or not.
1139 log.trace("** PORT ADDED {}/{} -> {}",
1140 ((DeviceEvent) event).subject().id(),
1141 ((DeviceEvent) event).port().number(),
1142 event.type());
1143 } else if (event.type() == DeviceEvent.Type.PORT_UPDATED) {
1144 // these calls happen for every subsequent event
1145 // ports enabled, disabled, switch goes away, comes back
1146 log.info("** PORT UPDATED {}/{} -> {}",
1147 event.subject(),
1148 ((DeviceEvent) event).port(),
1149 event.type());
Saurav Das9a554292018-04-27 18:42:30 -07001150 processPortUpdatedInternal(((Device) event.subject()),
Charles Chan9b7217c2018-04-05 16:31:15 -07001151 ((DeviceEvent) event).port());
1152 } else if (event.type() == TopologyEvent.Type.TOPOLOGY_CHANGED) {
1153 // Process topology event, needed for all modules relying on
1154 // topology service for path computation
1155 TopologyEvent topologyEvent = (TopologyEvent) event;
1156 log.info("Processing topology event {}, topology age {}, reasons {}",
1157 event.type(), topologyEvent.subject().time(),
1158 topologyEvent.reasons().size());
1159 topologyHandler.processTopologyChange(topologyEvent.reasons());
1160 } else if (event.type() == HostEvent.Type.HOST_ADDED) {
1161 hostHandler.processHostAddedEvent((HostEvent) event);
1162 } else if (event.type() == HostEvent.Type.HOST_MOVED) {
1163 hostHandler.processHostMovedEvent((HostEvent) event);
1164 routeHandler.processHostMovedEvent((HostEvent) event);
1165 } else if (event.type() == HostEvent.Type.HOST_REMOVED) {
1166 hostHandler.processHostRemovedEvent((HostEvent) event);
1167 } else if (event.type() == HostEvent.Type.HOST_UPDATED) {
1168 hostHandler.processHostUpdatedEvent((HostEvent) event);
1169 } else if (event.type() == RouteEvent.Type.ROUTE_ADDED) {
1170 routeHandler.processRouteAdded((RouteEvent) event);
1171 } else if (event.type() == RouteEvent.Type.ROUTE_UPDATED) {
1172 routeHandler.processRouteUpdated((RouteEvent) event);
1173 } else if (event.type() == RouteEvent.Type.ROUTE_REMOVED) {
1174 routeHandler.processRouteRemoved((RouteEvent) event);
1175 } else if (event.type() == RouteEvent.Type.ALTERNATIVE_ROUTES_CHANGED) {
1176 routeHandler.processAlternativeRoutesChanged((RouteEvent) event);
1177 } else if (event.type() == McastEvent.Type.SOURCES_ADDED ||
1178 event.type() == McastEvent.Type.SOURCES_REMOVED ||
1179 event.type() == McastEvent.Type.SINKS_ADDED ||
1180 event.type() == McastEvent.Type.SINKS_REMOVED ||
1181 event.type() == McastEvent.Type.ROUTE_ADDED ||
1182 event.type() == McastEvent.Type.ROUTE_REMOVED) {
1183 mcastHandler.processMcastEvent((McastEvent) event);
1184 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED) {
1185 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1186 Class configClass = netcfgEvent.configClass();
1187 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1188 appCfgHandler.processAppConfigAdded(netcfgEvent);
1189 log.info("App config event .. configuring network");
1190 cfgListener.configureNetwork();
1191 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1192 log.info("Segment Routing Device Config added for {}", event.subject());
1193 cfgListener.configureNetwork();
1194 } else if (configClass.equals(XConnectConfig.class)) {
1195 xConnectHandler.processXConnectConfigAdded(netcfgEvent);
1196 } else if (configClass.equals(InterfaceConfig.class)) {
1197 log.info("Interface Config added for {}", event.subject());
1198 cfgListener.configureNetwork();
1199 } else {
1200 log.error("Unhandled config class: {}", configClass);
1201 }
1202 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED) {
1203 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1204 Class configClass = netcfgEvent.configClass();
1205 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1206 appCfgHandler.processAppConfigUpdated(netcfgEvent);
1207 log.info("App config event .. configuring network");
1208 cfgListener.configureNetwork();
1209 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1210 log.info("Segment Routing Device Config updated for {}", event.subject());
1211 createOrUpdateDeviceConfiguration();
1212 } else if (configClass.equals(XConnectConfig.class)) {
1213 xConnectHandler.processXConnectConfigUpdated(netcfgEvent);
1214 } else if (configClass.equals(InterfaceConfig.class)) {
1215 log.info("Interface Config updated for {}", event.subject());
1216 createOrUpdateDeviceConfiguration();
1217 updateInterface((InterfaceConfig) netcfgEvent.config().get(),
1218 (InterfaceConfig) netcfgEvent.prevConfig().get());
1219 } else {
1220 log.error("Unhandled config class: {}", configClass);
1221 }
1222 } else if (event.type() == NetworkConfigEvent.Type.CONFIG_REMOVED) {
1223 NetworkConfigEvent netcfgEvent = (NetworkConfigEvent) event;
1224 Class configClass = netcfgEvent.configClass();
1225 if (configClass.equals(SegmentRoutingAppConfig.class)) {
1226 appCfgHandler.processAppConfigRemoved(netcfgEvent);
1227 log.info("App config event .. configuring network");
1228 cfgListener.configureNetwork();
1229 } else if (configClass.equals(SegmentRoutingDeviceConfig.class)) {
1230 // TODO Handle sr device config removal
1231 log.info("SegmentRoutingDeviceConfig removal is not handled in current implementation");
1232 } else if (configClass.equals(XConnectConfig.class)) {
1233 xConnectHandler.processXConnectConfigRemoved(netcfgEvent);
1234 } else if (configClass.equals(InterfaceConfig.class)) {
1235 // TODO Handle interface removal
1236 log.info("InterfaceConfig removal is not handled in current implementation");
1237 } else {
1238 log.error("Unhandled config class: {}", configClass);
1239 }
Saurav Das201762d2018-04-21 17:19:48 -07001240 } else if (event.type() == MastershipEvent.Type.MASTER_CHANGED) {
1241 MastershipEvent me = (MastershipEvent) event;
1242 DeviceId deviceId = me.subject();
1243 Optional<DeviceId> pairDeviceId = getPairDeviceId(deviceId);
1244 log.info(" ** MASTERSHIP CHANGED Invalidating shouldProgram cache"
1245 + " for {}/pair={} due to change", deviceId, pairDeviceId);
1246 defaultRoutingHandler.invalidateShouldProgramCache(deviceId);
1247 pairDeviceId.ifPresent(defaultRoutingHandler::invalidateShouldProgramCache);
1248 defaultRoutingHandler.checkFullRerouteForMasterChange(deviceId, me);
Charles Chan9b7217c2018-04-05 16:31:15 -07001249 } else {
1250 log.warn("Unhandled event type: {}", event.type());
sanghob35a6192015-04-01 13:05:26 -07001251 }
Charles Chan9b7217c2018-04-05 16:31:15 -07001252 } catch (Exception e) {
1253 log.error("SegmentRouting event handler thread thrown an exception: {}",
1254 e.getMessage(), e);
sanghob35a6192015-04-01 13:05:26 -07001255 }
sanghob35a6192015-04-01 13:05:26 -07001256 }
1257 }
1258
Saurav Das45f48152018-01-18 12:07:33 -08001259 void processDeviceAdded(Device device) {
Saurav Dasb5c236e2016-06-07 10:08:06 -07001260 log.info("** DEVICE ADDED with ID {}", device.id());
Charles Chan91ccbf72017-06-27 18:48:32 -07001261
1262 // NOTE: Punt ARP/NDP even when the device is not configured.
1263 // Host learning without network config is required for CORD config generator.
1264 routingRulePopulator.populateIpPunts(device.id());
1265 routingRulePopulator.populateArpNdpPunts(device.id());
1266
Charles Chan0b4e6182015-11-03 10:42:14 -08001267 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001268 log.warn("Device configuration unavailable. Device {} will be "
1269 + "processed after configuration.", device.id());
Saurav Das2857f382015-11-03 14:39:27 -08001270 return;
1271 }
Charles Chan2199c302016-04-23 17:36:10 -07001272 processDeviceAddedInternal(device.id());
1273 }
1274
1275 private void processDeviceAddedInternal(DeviceId deviceId) {
Saurav Das837e0bb2015-10-30 17:45:38 -07001276 // Irrespective of whether the local is a MASTER or not for this device,
1277 // we need to create a SR-group-handler instance. This is because in a
1278 // multi-instance setup, any instance can initiate forwarding/next-objectives
1279 // for any switch (even if this instance is a SLAVE or not even connected
1280 // to the switch). To handle this, a default-group-handler instance is necessary
1281 // per switch.
Charles Chan2199c302016-04-23 17:36:10 -07001282 log.debug("Current groupHandlerMap devs: {}", groupHandlerMap.keySet());
1283 if (groupHandlerMap.get(deviceId) == null) {
Charles Chan0b4e6182015-11-03 10:42:14 -08001284 DefaultGroupHandler groupHandler;
1285 try {
1286 groupHandler = DefaultGroupHandler.
Charles Chan2199c302016-04-23 17:36:10 -07001287 createGroupHandler(deviceId,
1288 appId,
1289 deviceConfiguration,
1290 linkService,
1291 flowObjectiveService,
1292 this);
Charles Chan0b4e6182015-11-03 10:42:14 -08001293 } catch (DeviceConfigNotFoundException e) {
1294 log.warn(e.getMessage() + " Aborting processDeviceAdded.");
1295 return;
1296 }
Saurav Dasf14d9ef2017-12-05 15:00:23 -08001297 log.debug("updating groupHandlerMap with new grpHdlr for device: {}",
Charles Chan2199c302016-04-23 17:36:10 -07001298 deviceId);
1299 groupHandlerMap.put(deviceId, groupHandler);
Saurav Das2857f382015-11-03 14:39:27 -08001300 }
Saurav Dasb5c236e2016-06-07 10:08:06 -07001301
Charles Chan2199c302016-04-23 17:36:10 -07001302 if (mastershipService.isLocalMaster(deviceId)) {
Saurav Das018605f2017-02-18 14:05:44 -08001303 defaultRoutingHandler.populatePortAddressingRules(deviceId);
Charles Chanfc5c7802016-05-17 13:13:55 -07001304 xConnectHandler.init(deviceId);
Charles Chan2199c302016-04-23 17:36:10 -07001305 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
Charles Chan59cc16d2017-02-02 16:20:42 -08001306 groupHandler.createGroupsFromVlanConfig();
Charles Chan2199c302016-04-23 17:36:10 -07001307 routingRulePopulator.populateSubnetBroadcastRule(deviceId);
Charles Chanc42e84e2015-10-20 16:24:19 -07001308 }
Charles Chan5270ed02016-01-30 23:22:37 -08001309
Charles Chan03a73e02016-10-24 14:52:01 -07001310 appCfgHandler.init(deviceId);
Charles Chan94549652018-04-29 18:11:37 -07001311 hostEventExecutor.execute(() -> hostHandler.init(deviceId));
1312 routeEventExecutor.execute(() -> routeHandler.init(deviceId));
sanghob35a6192015-04-01 13:05:26 -07001313 }
1314
Saurav Das80980c72016-03-23 11:22:49 -07001315 private void processDeviceRemoved(Device device) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001316 dsNextObjStore.entrySet().stream()
Saurav Das80980c72016-03-23 11:22:49 -07001317 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan47933752017-11-30 15:37:50 -08001318 .forEach(entry -> dsNextObjStore.remove(entry.getKey()));
Charles Chan59cc16d2017-02-02 16:20:42 -08001319 vlanNextObjStore.entrySet().stream()
Saurav Das80980c72016-03-23 11:22:49 -07001320 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan65238242017-06-22 18:03:14 -07001321 .forEach(entry -> vlanNextObjStore.remove(entry.getKey()));
Saurav Das80980c72016-03-23 11:22:49 -07001322 portNextObjStore.entrySet().stream()
1323 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan65238242017-06-22 18:03:14 -07001324 .forEach(entry -> portNextObjStore.remove(entry.getKey()));
Saurav Das45f48152018-01-18 12:07:33 -08001325 linkHandler.processDeviceRemoved(device);
Charles Chaned3742352017-06-15 00:44:51 -07001326
Saurav Dasceccf242017-08-03 18:30:35 -07001327 DefaultGroupHandler gh = groupHandlerMap.remove(device.id());
1328 if (gh != null) {
1329 gh.shutdown();
1330 }
Saurav Dasc88d4662017-05-15 15:34:25 -07001331 // Note that a switch going down is associated with all of its links
1332 // going down as well, but it is treated as a single switch down event
Saurav Das5a356042018-04-06 20:16:01 -07001333 // while the link-downs are ignored. We cannot rely on the ordering of
1334 // events - i.e we cannot expect all link-downs to come before the
1335 // switch down - so we purge all seen-links for the switch before
1336 // handling route-path changes for the switch-down
Saurav Dasc88d4662017-05-15 15:34:25 -07001337 defaultRoutingHandler
Saurav Das604ab3a2018-03-18 21:28:15 -07001338 .populateRoutingRulesForLinkStatusChange(null, null, device.id(), true);
Saurav Dasc568c342018-01-25 09:49:01 -08001339 defaultRoutingHandler.purgeEcmpGraph(device.id());
Charles Chanfc5c7802016-05-17 13:13:55 -07001340 xConnectHandler.removeDevice(device.id());
Saurav Dasa4020382018-02-14 14:14:54 -08001341
1342 // Cleanup all internal groupHandler stores for this device. Should be
1343 // done after all rerouting or rehashing has been completed
1344 groupHandlerMap.entrySet()
1345 .forEach(entry -> entry.getValue().cleanUpForNeighborDown(device.id()));
Saurav Das80980c72016-03-23 11:22:49 -07001346 }
1347
Saurav Dasc6ff8f02018-04-23 18:42:12 -07001348 /**
1349 * Purge the destinationSet nextObjective store of entries with this device
1350 * as key. Erases app-level knowledge of hashed groups in this device.
1351 *
1352 * @param devId the device identifier
1353 */
Saurav Das201762d2018-04-21 17:19:48 -07001354 void purgeHashedNextObjectiveStore(DeviceId devId) {
Saurav Dasc6ff8f02018-04-23 18:42:12 -07001355 log.debug("Purging hashed next-obj store for dev:{}", devId);
Saurav Das201762d2018-04-21 17:19:48 -07001356 dsNextObjStore.entrySet().stream()
1357 .filter(entry -> entry.getKey().deviceId().equals(devId))
1358 .forEach(entry -> dsNextObjStore.remove(entry.getKey()));
1359 }
1360
Saurav Das9a554292018-04-27 18:42:30 -07001361 private void processPortUpdatedInternal(Device device, Port port) {
Saurav Das1a129a02016-11-18 15:21:57 -08001362 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
1363 log.warn("Device configuration uploading. Not handling port event for"
1364 + "dev: {} port: {}", device.id(), port.number());
1365 return;
1366 }
Saurav Das018605f2017-02-18 14:05:44 -08001367
Saurav Das9a554292018-04-27 18:42:30 -07001368 if (interfaceService.isConfigured(new ConnectPoint(device.id(), port.number()))) {
1369 lastEdgePortEvent = Instant.now();
1370 }
1371
Saurav Das018605f2017-02-18 14:05:44 -08001372 if (!mastershipService.isLocalMaster(device.id())) {
1373 log.debug("Not master for dev:{} .. not handling port updated event"
1374 + "for port {}", device.id(), port.number());
1375 return;
1376 }
Saurav Das9a554292018-04-27 18:42:30 -07001377 processPortUpdated(device.id(), port);
1378 }
Saurav Das018605f2017-02-18 14:05:44 -08001379
Saurav Das9a554292018-04-27 18:42:30 -07001380 /**
1381 * Adds or remove filtering rules for the given switchport. If switchport is
1382 * an edge facing port, additionally handles host probing and broadcast
1383 * rules. Must be called by local master of device.
1384 *
1385 * @param deviceId the device identifier
1386 * @param port the port to update
1387 */
1388 void processPortUpdated(DeviceId deviceId, Port port) {
Saurav Das018605f2017-02-18 14:05:44 -08001389 // first we handle filtering rules associated with the port
1390 if (port.isEnabled()) {
1391 log.info("Switchport {}/{} enabled..programming filters",
Saurav Das9a554292018-04-27 18:42:30 -07001392 deviceId, port.number());
1393 routingRulePopulator.processSinglePortFilters(deviceId, port.number(), true);
Saurav Das018605f2017-02-18 14:05:44 -08001394 } else {
1395 log.info("Switchport {}/{} disabled..removing filters",
Saurav Das9a554292018-04-27 18:42:30 -07001396 deviceId, port.number());
1397 routingRulePopulator.processSinglePortFilters(deviceId, port.number(), false);
Saurav Das018605f2017-02-18 14:05:44 -08001398 }
Saurav Das1a129a02016-11-18 15:21:57 -08001399
1400 // portUpdated calls are for ports that have gone down or up. For switch
1401 // to switch ports, link-events should take care of any re-routing or
1402 // group editing necessary for port up/down. Here we only process edge ports
1403 // that are already configured.
Saurav Das9a554292018-04-27 18:42:30 -07001404 ConnectPoint cp = new ConnectPoint(deviceId, port.number());
Charles Chan971d7ba2018-05-01 11:50:20 -07001405 VlanId untaggedVlan = interfaceService.getUntaggedVlanId(cp);
1406 VlanId nativeVlan = interfaceService.getNativeVlanId(cp);
1407 Set<VlanId> taggedVlans = interfaceService.getTaggedVlanId(cp);
Charles Chan59cc16d2017-02-02 16:20:42 -08001408
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001409 if (untaggedVlan == null && nativeVlan == null && taggedVlans.isEmpty()) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001410 log.debug("Not handling port updated event for non-edge port (unconfigured) "
Saurav Das9a554292018-04-27 18:42:30 -07001411 + "dev/port: {}/{}", deviceId, port.number());
Saurav Das1a129a02016-11-18 15:21:57 -08001412 return;
1413 }
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001414 if (untaggedVlan != null) {
Saurav Das9a554292018-04-27 18:42:30 -07001415 processEdgePort(deviceId, port, untaggedVlan, true);
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001416 }
1417 if (nativeVlan != null) {
Saurav Das9a554292018-04-27 18:42:30 -07001418 processEdgePort(deviceId, port, nativeVlan, true);
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001419 }
1420 if (!taggedVlans.isEmpty()) {
Saurav Das9a554292018-04-27 18:42:30 -07001421 taggedVlans.forEach(tag -> processEdgePort(deviceId, port, tag, false));
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001422 }
Saurav Das1a129a02016-11-18 15:21:57 -08001423 }
1424
Saurav Das9a554292018-04-27 18:42:30 -07001425 private void processEdgePort(DeviceId deviceId, Port port, VlanId vlanId,
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001426 boolean popVlan) {
Saurav Das1a129a02016-11-18 15:21:57 -08001427 boolean portUp = port.isEnabled();
1428 if (portUp) {
Saurav Das9a554292018-04-27 18:42:30 -07001429 log.info("Device:EdgePort {}:{} is enabled in vlan: {}", deviceId,
Charles Chan59cc16d2017-02-02 16:20:42 -08001430 port.number(), vlanId);
Charles Chan94549652018-04-29 18:11:37 -07001431 hostEventExecutor.execute(() -> hostHandler.processPortUp(new ConnectPoint(deviceId, port.number())));
Saurav Das1a129a02016-11-18 15:21:57 -08001432 } else {
Saurav Das9a554292018-04-27 18:42:30 -07001433 log.info("Device:EdgePort {}:{} is disabled in vlan: {}", deviceId,
Charles Chan59cc16d2017-02-02 16:20:42 -08001434 port.number(), vlanId);
Saurav Das1a129a02016-11-18 15:21:57 -08001435 }
1436
Saurav Das9a554292018-04-27 18:42:30 -07001437 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
sanghob35a6192015-04-01 13:05:26 -07001438 if (groupHandler != null) {
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001439 groupHandler.processEdgePort(port.number(), vlanId, popVlan, portUp);
Saurav Das1a129a02016-11-18 15:21:57 -08001440 } else {
1441 log.warn("Group handler not found for dev:{}. Not handling edge port"
Saurav Das9a554292018-04-27 18:42:30 -07001442 + " {} event for port:{}", deviceId,
Saurav Das1a129a02016-11-18 15:21:57 -08001443 (portUp) ? "UP" : "DOWN", port.number());
sanghob35a6192015-04-01 13:05:26 -07001444 }
1445 }
sangho1e575652015-05-14 00:39:53 -07001446
Charles Chan27fe1a52017-10-20 16:06:55 -07001447 private void createOrUpdateDeviceConfiguration() {
1448 if (deviceConfiguration == null) {
Saurav Dase7f51012018-02-09 17:26:45 -08001449 log.info("Creating new DeviceConfiguration");
Charles Chan27fe1a52017-10-20 16:06:55 -07001450 deviceConfiguration = new DeviceConfiguration(this);
1451 } else {
Saurav Dase7f51012018-02-09 17:26:45 -08001452 log.info("Updating DeviceConfiguration");
Charles Chan27fe1a52017-10-20 16:06:55 -07001453 deviceConfiguration.updateConfig();
1454 }
1455 }
1456
Charles Chan50bb6ef2018-04-18 18:41:05 -07001457 private void createOrUpdateDefaultRoutingHandler() {
1458 if (defaultRoutingHandler == null) {
1459 log.info("Creating new DefaultRoutingHandler");
1460 defaultRoutingHandler = new DefaultRoutingHandler(this);
1461 } else {
1462 log.info("Updating DefaultRoutingHandler");
1463 defaultRoutingHandler.update(this);
1464 }
1465 }
1466
Pier Ventre10bd8d12016-11-26 21:05:22 -08001467 /**
1468 * Registers the given connect point with the NRS, this is necessary
1469 * to receive the NDP and ARP packets from the NRS.
1470 *
1471 * @param portToRegister connect point to register
1472 */
1473 public void registerConnectPoint(ConnectPoint portToRegister) {
Charles Chan0aa674e2017-02-23 15:44:08 -08001474 neighbourResolutionService.registerNeighbourHandler(
Pier Ventre10bd8d12016-11-26 21:05:22 -08001475 portToRegister,
1476 neighbourHandler,
1477 appId
1478 );
1479 }
1480
Charles Chand6832882015-10-05 17:50:33 -07001481 private class InternalConfigListener implements NetworkConfigListener {
Saurav Das7bcbe702017-06-13 15:35:54 -07001482 private static final long PROGRAM_DELAY = 2;
Charles Chan2c15aca2016-11-09 20:51:44 -08001483 SegmentRoutingManager srManager;
Charles Chan4636be02015-10-07 14:21:45 -07001484
Charles Chane849c192016-01-11 18:28:54 -08001485 /**
1486 * Constructs the internal network config listener.
1487 *
Charles Chan2c15aca2016-11-09 20:51:44 -08001488 * @param srManager segment routing manager
Charles Chane849c192016-01-11 18:28:54 -08001489 */
Charles Chan65238242017-06-22 18:03:14 -07001490 InternalConfigListener(SegmentRoutingManager srManager) {
Charles Chan2c15aca2016-11-09 20:51:44 -08001491 this.srManager = srManager;
Charles Chan4636be02015-10-07 14:21:45 -07001492 }
1493
Charles Chane849c192016-01-11 18:28:54 -08001494 /**
1495 * Reads network config and initializes related data structure accordingly.
1496 */
Charles Chan47933752017-11-30 15:37:50 -08001497 void configureNetwork() {
Saurav Dase7f51012018-02-09 17:26:45 -08001498 log.info("Configuring network ...");
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001499
1500 // Setting handling of network configuration events completable future
1501 // The completable future is needed because of the async behaviour of the configureNetwork,
1502 // listener registration and event arrival
1503 // Enables us to buffer the events and execute them when the configure network is done.
1504 networkConfigCompletion = new CompletableFuture<>();
1505
1506 // add a small delay to absorb multiple network config added notifications
1507 if (!programmingScheduled.get()) {
1508 log.info("Buffering config calls for {} secs", PROGRAM_DELAY);
1509 programmingScheduled.set(true);
1510 mainEventExecutor.schedule(new ConfigChange(), PROGRAM_DELAY, TimeUnit.SECONDS);
1511 }
1512
Charles Chan27fe1a52017-10-20 16:06:55 -07001513 createOrUpdateDeviceConfiguration();
Charles Chan4636be02015-10-07 14:21:45 -07001514
Charles Chan2c15aca2016-11-09 20:51:44 -08001515 arpHandler = new ArpHandler(srManager);
1516 icmpHandler = new IcmpHandler(srManager);
1517 ipHandler = new IpHandler(srManager);
1518 routingRulePopulator = new RoutingRulePopulator(srManager);
Charles Chan50bb6ef2018-04-18 18:41:05 -07001519 createOrUpdateDefaultRoutingHandler();
Charles Chan4636be02015-10-07 14:21:45 -07001520
1521 tunnelHandler = new TunnelHandler(linkService, deviceConfiguration,
1522 groupHandlerMap, tunnelStore);
1523 policyHandler = new PolicyHandler(appId, deviceConfiguration,
1524 flowObjectiveService,
1525 tunnelHandler, policyStore);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001526 networkConfigCompletion.complete(true);
1527
Charles Chan2199c302016-04-23 17:36:10 -07001528 mcastHandler.init();
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001529
Charles Chan4636be02015-10-07 14:21:45 -07001530 }
1531
Charles Chand6832882015-10-05 17:50:33 -07001532 @Override
1533 public void event(NetworkConfigEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001534 if (mainEventExecutor == null) {
1535 return;
1536 }
Charles Chan7a888e82018-03-21 16:57:47 -07001537 checkState(appCfgHandler != null, "NetworkConfigEventHandler is not initialized");
1538 checkState(xConnectHandler != null, "XConnectHandler is not initialized");
1539 switch (event.type()) {
1540 case CONFIG_ADDED:
1541 case CONFIG_UPDATED:
1542 case CONFIG_REMOVED:
1543 log.trace("Schedule Network Config event {}", event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001544 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1545 mainEventExecutor.execute(new InternalEventHandler(event));
1546 } else {
Charles Chan10b2fee2018-04-21 00:44:29 -07001547 queuedEvents.add(event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001548 }
Charles Chan7a888e82018-03-21 16:57:47 -07001549 break;
1550 default:
1551 break;
Charles Chand6832882015-10-05 17:50:33 -07001552 }
1553 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001554
Charles Chan50443e82018-01-03 16:26:32 -08001555 @Override
1556 public boolean isRelevant(NetworkConfigEvent event) {
Saurav Dase7f51012018-02-09 17:26:45 -08001557 if (event.type() == CONFIG_REGISTERED ||
1558 event.type() == CONFIG_UNREGISTERED) {
1559 log.debug("Ignore event {} due to type mismatch", event);
1560 return false;
Charles Chan50443e82018-01-03 16:26:32 -08001561 }
Saurav Dase7f51012018-02-09 17:26:45 -08001562
1563 if (!event.configClass().equals(SegmentRoutingDeviceConfig.class) &&
1564 !event.configClass().equals(SegmentRoutingAppConfig.class) &&
1565 !event.configClass().equals(InterfaceConfig.class) &&
Andreas Pantelopouloscd339592018-02-23 14:18:00 -08001566 !event.configClass().equals(XConnectConfig.class)) {
Saurav Dase7f51012018-02-09 17:26:45 -08001567 log.debug("Ignore event {} due to class mismatch", event);
1568 return false;
1569 }
1570
1571 return true;
Charles Chan50443e82018-01-03 16:26:32 -08001572 }
1573
Saurav Das7bcbe702017-06-13 15:35:54 -07001574 private final class ConfigChange implements Runnable {
1575 @Override
1576 public void run() {
1577 programmingScheduled.set(false);
Saurav Dase7f51012018-02-09 17:26:45 -08001578 log.info("Reacting to config changes after buffer delay");
Saurav Das7bcbe702017-06-13 15:35:54 -07001579 for (Device device : deviceService.getDevices()) {
1580 processDeviceAdded(device);
1581 }
1582 defaultRoutingHandler.startPopulationProcess();
1583 }
1584 }
Charles Chand6832882015-10-05 17:50:33 -07001585 }
Charles Chan68aa62d2015-11-09 16:37:23 -08001586
Charles Chan7a888e82018-03-21 16:57:47 -07001587 private class InternalLinkListener implements LinkListener {
1588 @Override
1589 public void event(LinkEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001590 if (mainEventExecutor == null) {
1591 return;
1592 }
Charles Chan7a888e82018-03-21 16:57:47 -07001593 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1594 event.type() == LinkEvent.Type.LINK_UPDATED ||
1595 event.type() == LinkEvent.Type.LINK_REMOVED) {
1596 log.trace("Schedule Link event {}", event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001597 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1598 mainEventExecutor.execute(new InternalEventHandler(event));
1599 } else {
Charles Chan10b2fee2018-04-21 00:44:29 -07001600 queuedEvents.add(event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001601 }
Charles Chan7a888e82018-03-21 16:57:47 -07001602 }
1603 }
1604 }
1605
1606 private class InternalDeviceListener implements DeviceListener {
1607 @Override
1608 public void event(DeviceEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001609 if (mainEventExecutor == null) {
1610 return;
1611 }
Charles Chan7a888e82018-03-21 16:57:47 -07001612 switch (event.type()) {
1613 case DEVICE_ADDED:
1614 case PORT_UPDATED:
1615 case PORT_ADDED:
1616 case DEVICE_UPDATED:
1617 case DEVICE_AVAILABILITY_CHANGED:
1618 log.trace("Schedule Device event {}", event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001619 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1620 mainEventExecutor.execute(new InternalEventHandler(event));
1621 } else {
Charles Chan10b2fee2018-04-21 00:44:29 -07001622 queuedEvents.add(event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001623 }
Charles Chan7a888e82018-03-21 16:57:47 -07001624 break;
1625 default:
1626 }
1627 }
1628 }
1629
1630 private class InternalTopologyListener implements TopologyListener {
1631 @Override
1632 public void event(TopologyEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001633 if (mainEventExecutor == null) {
1634 return;
1635 }
Charles Chan7a888e82018-03-21 16:57:47 -07001636 switch (event.type()) {
1637 case TOPOLOGY_CHANGED:
1638 log.trace("Schedule Topology event {}", event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001639 if (networkConfigCompletion == null || networkConfigCompletion.isDone()) {
1640 mainEventExecutor.execute(new InternalEventHandler(event));
1641 } else {
Charles Chan10b2fee2018-04-21 00:44:29 -07001642 queuedEvents.add(event);
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001643 }
Charles Chan7a888e82018-03-21 16:57:47 -07001644 break;
1645 default:
1646 }
1647 }
1648 }
1649
Charles Chan68aa62d2015-11-09 16:37:23 -08001650 private class InternalHostListener implements HostListener {
Charles Chan68aa62d2015-11-09 16:37:23 -08001651 @Override
1652 public void event(HostEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001653 if (hostEventExecutor == null) {
1654 return;
1655 }
Charles Chan68aa62d2015-11-09 16:37:23 -08001656 switch (event.type()) {
1657 case HOST_ADDED:
Charles Chan68aa62d2015-11-09 16:37:23 -08001658 case HOST_MOVED:
Charles Chan68aa62d2015-11-09 16:37:23 -08001659 case HOST_REMOVED:
Charles Chan68aa62d2015-11-09 16:37:23 -08001660 case HOST_UPDATED:
Charles Chan7a888e82018-03-21 16:57:47 -07001661 log.trace("Schedule Host event {}", event);
Charles Chan4e49df82018-04-07 11:35:08 -07001662 hostEventExecutor.execute(new InternalEventHandler(event));
Charles Chan68aa62d2015-11-09 16:37:23 -08001663 break;
1664 default:
1665 log.warn("Unsupported host event type: {}", event.type());
1666 break;
1667 }
1668 }
1669 }
1670
Charles Chand55e84d2016-03-30 17:54:24 -07001671 private class InternalMcastListener implements McastListener {
1672 @Override
1673 public void event(McastEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001674 if (mcastEventExecutor == null) {
1675 return;
1676 }
Charles Chand55e84d2016-03-30 17:54:24 -07001677 switch (event.type()) {
Pier3ee24552018-03-14 16:47:32 -07001678 case SOURCES_ADDED:
1679 case SOURCES_REMOVED:
1680 case SINKS_ADDED:
1681 case SINKS_REMOVED:
Charles Chand55e84d2016-03-30 17:54:24 -07001682 case ROUTE_REMOVED:
Pier96f63cb2018-04-17 16:29:56 +02001683 case ROUTE_ADDED:
Charles Chan7a888e82018-03-21 16:57:47 -07001684 log.trace("Schedule Mcast event {}", event);
Charles Chan4e49df82018-04-07 11:35:08 -07001685 mcastEventExecutor.execute(new InternalEventHandler(event));
Pier Luigi9930da52018-02-02 16:19:11 +01001686 break;
Charles Chand55e84d2016-03-30 17:54:24 -07001687 default:
Charles Chan7a888e82018-03-21 16:57:47 -07001688 log.warn("Unsupported mcast event type: {}", event.type());
Charles Chand55e84d2016-03-30 17:54:24 -07001689 break;
1690 }
1691 }
1692 }
Charles Chan35fd1a72016-06-13 18:54:31 -07001693
Charles Chan03a73e02016-10-24 14:52:01 -07001694 private class InternalRouteEventListener implements RouteListener {
1695 @Override
1696 public void event(RouteEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001697 if (routeEventExecutor == null) {
1698 return;
1699 }
Charles Chan03a73e02016-10-24 14:52:01 -07001700 switch (event.type()) {
1701 case ROUTE_ADDED:
Charles Chan03a73e02016-10-24 14:52:01 -07001702 case ROUTE_UPDATED:
Charles Chan03a73e02016-10-24 14:52:01 -07001703 case ROUTE_REMOVED:
Charles Chan2fde6d42017-08-23 14:46:43 -07001704 case ALTERNATIVE_ROUTES_CHANGED:
Charles Chan7a888e82018-03-21 16:57:47 -07001705 log.trace("Schedule Route event {}", event);
Charles Chan4e49df82018-04-07 11:35:08 -07001706 routeEventExecutor.execute(new InternalEventHandler(event));
Charles Chan2fde6d42017-08-23 14:46:43 -07001707 break;
Charles Chan03a73e02016-10-24 14:52:01 -07001708 default:
Charles Chan7a888e82018-03-21 16:57:47 -07001709 log.warn("Unsupported route event type: {}", event.type());
Charles Chan03a73e02016-10-24 14:52:01 -07001710 break;
1711 }
1712 }
1713 }
Saurav Dasc88d4662017-05-15 15:34:25 -07001714
Charles Chan50bb6ef2018-04-18 18:41:05 -07001715 private class InternalMastershipListener implements MastershipListener {
1716 @Override
1717 public void event(MastershipEvent event) {
Ray Milkey749996b2018-05-11 09:59:19 -07001718 if (mainEventExecutor == null) {
1719 return;
1720 }
Charles Chan50bb6ef2018-04-18 18:41:05 -07001721 switch (event.type()) {
Saurav Das201762d2018-04-21 17:19:48 -07001722 case MASTER_CHANGED:
1723 log.debug("Mastership event: {}/{}", event.subject(),
1724 event.roleInfo());
1725 mainEventExecutor.execute(new InternalEventHandler(event));
1726 break;
1727 case BACKUPS_CHANGED:
1728 case SUSPENDED:
1729 default:
1730 log.debug("Mastership event type {} not handled", event.type());
1731 break;
Charles Chan50bb6ef2018-04-18 18:41:05 -07001732 }
1733 }
1734 }
1735
Saurav Das201762d2018-04-21 17:19:48 -07001736 class InternalClusterListener implements ClusterEventListener {
1737 private Instant lastClusterEvent = Instant.EPOCH;
1738
1739 long timeSinceLastClusterEvent() {
1740 return Instant.now().toEpochMilli() - lastClusterEvent.toEpochMilli();
1741 }
1742
1743 @Override
1744 public void event(ClusterEvent event) {
1745 switch (event.type()) {
1746 case INSTANCE_ACTIVATED:
1747 case INSTANCE_ADDED:
1748 case INSTANCE_READY:
1749 log.debug("Cluster event {} ignored", event.type());
1750 break;
1751 case INSTANCE_DEACTIVATED:
1752 case INSTANCE_REMOVED:
1753 log.info("** Cluster event {}", event.type());
1754 lastClusterEvent = Instant.now();
1755 break;
1756 default:
1757 break;
1758 }
1759
1760 }
1761
1762 }
1763
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001764 private void updateInterface(InterfaceConfig conf, InterfaceConfig prevConf) {
1765 try {
1766 Set<Interface> intfs = conf.getInterfaces();
1767 Set<Interface> prevIntfs = prevConf.getInterfaces();
1768
1769 // Now we only handle one interface config at each port.
1770 if (intfs.size() != 1 || prevIntfs.size() != 1) {
1771 log.warn("Interface update aborted - one at a time is allowed, " +
1772 "but {} / {}(prev) received.", intfs.size(), prevIntfs.size());
1773 return;
1774 }
1775
Andrea Campanella6468e1f2018-04-17 12:09:34 +02001776 //The system is in an incoherent state, abort
1777 if (defaultRoutingHandler == null) {
1778 log.warn("Interface update aborted, defaultRoutingHandler is null");
1779 return;
1780 }
1781
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001782 Interface intf = intfs.stream().findFirst().get();
1783 Interface prevIntf = prevIntfs.stream().findFirst().get();
1784
1785 DeviceId deviceId = intf.connectPoint().deviceId();
1786 PortNumber portNum = intf.connectPoint().port();
1787
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001788 removeSubnetConfig(prevIntf.connectPoint(),
1789 Sets.difference(new HashSet<>(prevIntf.ipAddressesList()),
1790 new HashSet<>(intf.ipAddressesList())));
1791
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001792 if (!prevIntf.vlanNative().equals(VlanId.NONE)
1793 && !prevIntf.vlanNative().equals(intf.vlanUntagged())
1794 && !prevIntf.vlanNative().equals(intf.vlanNative())) {
1795 if (intf.vlanTagged().contains(prevIntf.vlanNative())) {
1796 // Update filtering objective and L2IG group bucket
1797 updatePortVlanTreatment(deviceId, portNum, prevIntf.vlanNative(), false);
1798 } else {
1799 // RemoveVlanNative
1800 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanNative(), true, false);
1801 }
1802 }
1803
1804 if (!prevIntf.vlanUntagged().equals(VlanId.NONE)
1805 && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())
1806 && !prevIntf.vlanUntagged().equals(intf.vlanNative())) {
1807 if (intf.vlanTagged().contains(prevIntf.vlanUntagged())) {
1808 // Update filtering objective and L2IG group bucket
1809 updatePortVlanTreatment(deviceId, portNum, prevIntf.vlanUntagged(), false);
1810 } else {
1811 // RemoveVlanUntagged
1812 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanUntagged(), true, false);
1813 }
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001814 }
1815
1816 if (!prevIntf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
1817 // RemoveVlanTagged
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001818 Sets.difference(prevIntf.vlanTagged(), intf.vlanTagged()).stream()
1819 .filter(i -> !intf.vlanUntagged().equals(i))
1820 .filter(i -> !intf.vlanNative().equals(i))
1821 .forEach(vlanId -> updateVlanConfigInternal(
1822 deviceId, portNum, vlanId, false, false));
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001823 }
1824
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001825 if (!intf.vlanNative().equals(VlanId.NONE)
1826 && !prevIntf.vlanNative().equals(intf.vlanNative())
1827 && !prevIntf.vlanUntagged().equals(intf.vlanNative())) {
1828 if (prevIntf.vlanTagged().contains(intf.vlanNative())) {
1829 // Update filtering objective and L2IG group bucket
1830 updatePortVlanTreatment(deviceId, portNum, intf.vlanNative(), true);
1831 } else {
1832 // AddVlanNative
1833 updateVlanConfigInternal(deviceId, portNum, intf.vlanNative(), true, true);
1834 }
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001835 }
1836
1837 if (!intf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
1838 // AddVlanTagged
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001839 Sets.difference(intf.vlanTagged(), prevIntf.vlanTagged()).stream()
1840 .filter(i -> !prevIntf.vlanUntagged().equals(i))
1841 .filter(i -> !prevIntf.vlanNative().equals(i))
1842 .forEach(vlanId -> updateVlanConfigInternal(
1843 deviceId, portNum, vlanId, false, true)
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001844 );
1845 }
1846
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001847 if (!intf.vlanUntagged().equals(VlanId.NONE)
1848 && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())
1849 && !prevIntf.vlanNative().equals(intf.vlanUntagged())) {
1850 if (prevIntf.vlanTagged().contains(intf.vlanUntagged())) {
1851 // Update filtering objective and L2IG group bucket
1852 updatePortVlanTreatment(deviceId, portNum, intf.vlanUntagged(), true);
1853 } else {
1854 // AddVlanUntagged
1855 updateVlanConfigInternal(deviceId, portNum, intf.vlanUntagged(), true, true);
1856 }
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001857 }
1858 addSubnetConfig(prevIntf.connectPoint(),
1859 Sets.difference(new HashSet<>(intf.ipAddressesList()),
1860 new HashSet<>(prevIntf.ipAddressesList())));
1861 } catch (ConfigException e) {
1862 log.error("Error in configuration");
1863 }
1864 }
1865
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001866 private void updatePortVlanTreatment(DeviceId deviceId, PortNumber portNum,
1867 VlanId vlanId, boolean pushVlan) {
1868 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
1869 if (grpHandler == null) {
1870 log.warn("Failed to retrieve group handler for device {}", deviceId);
1871 return;
1872 }
1873
1874 // Update filtering objective for a single port
1875 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, !pushVlan, vlanId, false);
1876 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, true);
1877
1878 if (getVlanNextObjectiveId(deviceId, vlanId) != -1) {
1879 // Update L2IG bucket of the port
1880 grpHandler.updateL2InterfaceGroupBucket(portNum, vlanId, pushVlan);
1881 } else {
1882 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
1883 }
1884 }
1885
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001886 private void updateVlanConfigInternal(DeviceId deviceId, PortNumber portNum,
1887 VlanId vlanId, boolean pushVlan, boolean install) {
1888 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
1889 if (grpHandler == null) {
1890 log.warn("Failed to retrieve group handler for device {}", deviceId);
1891 return;
1892 }
1893
1894 // Update filtering objective for a single port
1895 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, install);
1896
1897 // Update filtering objective for multicast ingress port
1898 mcastHandler.updateFilterToDevice(deviceId, portNum, vlanId, install);
1899
1900 int nextId = getVlanNextObjectiveId(deviceId, vlanId);
1901
1902 if (nextId != -1 && !install) {
1903 // Update next objective for a single port as an output port
1904 // Remove a single port from L2FG
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001905 grpHandler.updateGroupFromVlanConfiguration(vlanId, portNum, nextId, install);
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001906 // Remove L2 Bridging rule and L3 Unicast rule to the host
Charles Chan94549652018-04-29 18:11:37 -07001907 hostEventExecutor.execute(() -> hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum,
1908 vlanId, pushVlan, install));
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001909 // Remove broadcast forwarding rule and corresponding L2FG for VLAN
1910 // only if there is no port configured on that VLAN ID
1911 if (!getVlanPortMap(deviceId).containsKey(vlanId)) {
1912 // Remove broadcast forwarding rule for the VLAN
1913 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
1914 // Remove L2FG for VLAN
1915 grpHandler.removeBcastGroupFromVlan(deviceId, portNum, vlanId, pushVlan);
1916 } else {
1917 // Remove L2IG of the port
1918 grpHandler.removePortNextObjective(deviceId, portNum, vlanId, pushVlan);
1919 }
1920 } else if (install) {
1921 if (nextId != -1) {
1922 // Add a single port to L2FG
Jonghwan Hyunf810a7a2018-02-12 16:43:45 +09001923 grpHandler.updateGroupFromVlanConfiguration(vlanId, portNum, nextId, install);
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001924 } else {
1925 // Create L2FG for VLAN
1926 grpHandler.createBcastGroupFromVlan(vlanId, Collections.singleton(portNum));
1927 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
1928 }
Charles Chan94549652018-04-29 18:11:37 -07001929 hostEventExecutor.execute(() -> hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum,
1930 vlanId, pushVlan, install));
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001931 } else {
1932 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
1933 }
1934 }
1935
1936 private void removeSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
1937 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
1938 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
1939
1940 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
1941 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
1942 .filter(intf -> !intf.connectPoint().equals(cp))
1943 .flatMap(intf -> intf.ipAddressesList().stream())
1944 .collect(Collectors.toSet());
1945 // 1. Partial subnet population
1946 // Remove routing rules for removed subnet from previous configuration,
1947 // which does not also exist in other interfaces in the same device
1948 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
1949 .map(InterfaceIpAddress::subnetAddress)
1950 .collect(Collectors.toSet());
1951
1952 defaultRoutingHandler.revokeSubnet(
1953 ipPrefixSet.stream()
1954 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
1955 .collect(Collectors.toSet()));
1956
1957 // 2. Interface IP punts
1958 // Remove IP punts for old Intf address
1959 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
1960 .map(InterfaceIpAddress::ipAddress)
1961 .collect(Collectors.toSet());
1962 ipAddressSet.stream()
1963 .map(InterfaceIpAddress::ipAddress)
1964 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
1965 .forEach(interfaceIpAddress ->
1966 routingRulePopulator.revokeSingleIpPunts(
1967 cp.deviceId(), interfaceIpAddress));
1968
1969 // 3. Host unicast routing rule
1970 // Remove unicast routing rule
Charles Chan94549652018-04-29 18:11:37 -07001971 hostEventExecutor.execute(() -> hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, false));
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001972 }
1973
1974 private void addSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
1975 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
1976 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
1977
1978 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
1979 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
1980 .filter(intf -> !intf.connectPoint().equals(cp))
1981 .flatMap(intf -> intf.ipAddressesList().stream())
1982 .collect(Collectors.toSet());
1983 // 1. Partial subnet population
1984 // Add routing rules for newly added subnet, which does not also exist in
1985 // other interfaces in the same device
1986 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
1987 .map(InterfaceIpAddress::subnetAddress)
1988 .collect(Collectors.toSet());
1989
1990 defaultRoutingHandler.populateSubnet(
1991 Collections.singleton(cp),
1992 ipPrefixSet.stream()
1993 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
1994 .collect(Collectors.toSet()));
1995
1996 // 2. Interface IP punts
1997 // Add IP punts for new Intf address
1998 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
1999 .map(InterfaceIpAddress::ipAddress)
2000 .collect(Collectors.toSet());
2001 ipAddressSet.stream()
2002 .map(InterfaceIpAddress::ipAddress)
2003 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
2004 .forEach(interfaceIpAddress ->
2005 routingRulePopulator.populateSingleIpPunts(
2006 cp.deviceId(), interfaceIpAddress));
2007
2008 // 3. Host unicast routing rule
2009 // Add unicast routing rule
Charles Chan94549652018-04-29 18:11:37 -07002010 hostEventExecutor.execute(() -> hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, true));
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07002011 }
sanghob35a6192015-04-01 13:05:26 -07002012}