blob: b34617338f44a642b3982c0719f0a9f1e085f335 [file] [log] [blame]
sangho80f11cb2015-04-01 13:05:26 -07001/*
Brian O'Connor0947d7e2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
sangho80f11cb2015-04-01 13:05:26 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.segmentrouting;
17
Andreas Pantelopoulosafc637f2017-12-20 18:04:27 -080018import com.fasterxml.jackson.databind.ObjectMapper;
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -070019import com.fasterxml.jackson.databind.node.ObjectNode;
Jonathan Hart61e24e12017-11-30 18:23:42 -080020import com.google.common.collect.HashMultimap;
21import com.google.common.collect.ImmutableMap;
22import com.google.common.collect.Maps;
23import com.google.common.collect.Multimap;
Charles Chanf0ae41e2017-08-23 13:55:39 -070024import com.google.common.collect.Sets;
sangho80f11cb2015-04-01 13:05:26 -070025import org.apache.felix.scr.annotations.Activate;
26import org.apache.felix.scr.annotations.Component;
27import org.apache.felix.scr.annotations.Deactivate;
Charles Chan873661e2017-11-30 15:37:50 -080028import org.apache.felix.scr.annotations.Modified;
29import org.apache.felix.scr.annotations.Property;
sangho80f11cb2015-04-01 13:05:26 -070030import org.apache.felix.scr.annotations.Reference;
31import org.apache.felix.scr.annotations.ReferenceCardinality;
sangho27462c62015-05-14 00:39:53 -070032import org.apache.felix.scr.annotations.Service;
sangho80f11cb2015-04-01 13:05:26 -070033import org.onlab.packet.Ethernet;
Pier Ventreb6b81d52016-12-02 08:16:05 -080034import org.onlab.packet.ICMP6;
Charles Chan77277672015-10-20 16:24:19 -070035import org.onlab.packet.IPv4;
Pier Ventreb6a7f342016-11-26 21:05:22 -080036import org.onlab.packet.IPv6;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -070037import org.onlab.packet.IpAddress;
Charles Chan77277672015-10-20 16:24:19 -070038import org.onlab.packet.IpPrefix;
Jonathan Hart54541d12016-04-12 15:39:44 -070039import org.onlab.packet.VlanId;
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -070040import org.onlab.util.KryoNamespace;
Charles Chan873661e2017-11-30 15:37:50 -080041import org.onlab.util.Tools;
Saurav Dasc3604f12016-03-23 11:22:49 -070042import org.onosproject.cfg.ComponentConfigService;
sangho80f11cb2015-04-01 13:05:26 -070043import org.onosproject.core.ApplicationId;
44import org.onosproject.core.CoreService;
45import org.onosproject.event.Event;
Jonathan Hart54541d12016-04-12 15:39:44 -070046import org.onosproject.mastership.MastershipService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080047import org.onosproject.net.ConnectPoint;
Jonathan Hart54541d12016-04-12 15:39:44 -070048import org.onosproject.net.Device;
49import org.onosproject.net.DeviceId;
Charles Chanf0ae41e2017-08-23 13:55:39 -070050import org.onosproject.net.Host;
51import org.onosproject.net.HostId;
Jonathan Hart54541d12016-04-12 15:39:44 -070052import org.onosproject.net.Link;
53import org.onosproject.net.Port;
Charles Chanf4586112015-11-09 16:37:23 -080054import org.onosproject.net.PortNumber;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -070055import org.onosproject.net.config.ConfigException;
Charles Chan72f556a2015-10-05 17:50:33 -070056import org.onosproject.net.config.ConfigFactory;
57import org.onosproject.net.config.NetworkConfigEvent;
Charles Chan72f556a2015-10-05 17:50:33 -070058import org.onosproject.net.config.NetworkConfigListener;
Jonathan Hart54541d12016-04-12 15:39:44 -070059import org.onosproject.net.config.NetworkConfigRegistry;
Ray Milkeyae0068a2017-08-15 11:02:29 -070060import org.onosproject.net.config.basics.InterfaceConfig;
61import org.onosproject.net.config.basics.McastConfig;
Charles Chan72f556a2015-10-05 17:50:33 -070062import org.onosproject.net.config.basics.SubjectFactories;
Saurav Dase6c448a2018-01-18 12:07:33 -080063import org.onosproject.net.device.DeviceAdminService;
Jonathan Hart54541d12016-04-12 15:39:44 -070064import org.onosproject.net.device.DeviceEvent;
65import org.onosproject.net.device.DeviceListener;
66import org.onosproject.net.device.DeviceService;
Charles Chanf4586112015-11-09 16:37:23 -080067import org.onosproject.net.flow.TrafficSelector;
68import org.onosproject.net.flow.TrafficTreatment;
Jonathan Hart54541d12016-04-12 15:39:44 -070069import org.onosproject.net.flowobjective.FlowObjectiveService;
Charles Chanf4586112015-11-09 16:37:23 -080070import org.onosproject.net.host.HostEvent;
71import org.onosproject.net.host.HostListener;
Charles Chan873661e2017-11-30 15:37:50 -080072import org.onosproject.net.host.HostLocationProbingService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080073import org.onosproject.net.host.HostService;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -070074import org.onosproject.net.host.InterfaceIpAddress;
Ray Milkeyae0068a2017-08-15 11:02:29 -070075import org.onosproject.net.intf.Interface;
76import org.onosproject.net.intf.InterfaceService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080077import org.onosproject.net.link.LinkEvent;
78import org.onosproject.net.link.LinkListener;
79import org.onosproject.net.link.LinkService;
Charles Chanc91c8782016-03-30 17:54:24 -070080import org.onosproject.net.mcast.McastEvent;
81import org.onosproject.net.mcast.McastListener;
82import org.onosproject.net.mcast.MulticastRouteService;
Ray Milkeyae0068a2017-08-15 11:02:29 -070083import org.onosproject.net.neighbour.NeighbourResolutionService;
Pier Ventreb6a7f342016-11-26 21:05:22 -080084import org.onosproject.net.packet.InboundPacket;
85import org.onosproject.net.packet.PacketContext;
86import org.onosproject.net.packet.PacketProcessor;
87import org.onosproject.net.packet.PacketService;
Charles Chanc91c8782016-03-30 17:54:24 -070088import org.onosproject.net.topology.TopologyService;
Charles Chanf0ae41e2017-08-23 13:55:39 -070089import org.onosproject.routeservice.ResolvedRoute;
Ray Milkeyae0068a2017-08-15 11:02:29 -070090import org.onosproject.routeservice.RouteEvent;
91import org.onosproject.routeservice.RouteListener;
92import org.onosproject.routeservice.RouteService;
Charles Chanc91c8782016-03-30 17:54:24 -070093import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
94import org.onosproject.segmentrouting.config.DeviceConfiguration;
Pier Ventre6b19e482016-11-07 16:21:04 -080095import org.onosproject.segmentrouting.config.PwaasConfig;
Pier Ventre6b19e482016-11-07 16:21:04 -080096import org.onosproject.segmentrouting.config.SegmentRoutingAppConfig;
Ray Milkeyae0068a2017-08-15 11:02:29 -070097import org.onosproject.segmentrouting.config.SegmentRoutingDeviceConfig;
Charles Chan82f19972016-05-17 13:13:55 -070098import org.onosproject.segmentrouting.config.XConnectConfig;
Charles Chanc91c8782016-03-30 17:54:24 -070099import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
Saurav Das261c3002017-06-13 15:35:54 -0700100import org.onosproject.segmentrouting.grouphandler.DestinationSet;
101import org.onosproject.segmentrouting.grouphandler.NextNeighbors;
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700102import org.onosproject.segmentrouting.pwaas.DefaultL2Tunnel;
103import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelPolicy;
Ray Milkeyae0068a2017-08-15 11:02:29 -0700104import org.onosproject.segmentrouting.pwaas.L2TunnelHandler;
Saurav Das261c3002017-06-13 15:35:54 -0700105import org.onosproject.segmentrouting.storekey.DestinationSetNextObjectiveStoreKey;
Charles Chan1eaf4802016-04-18 13:44:03 -0700106import org.onosproject.segmentrouting.storekey.PortNextObjectiveStoreKey;
Charles Chan10b0fb72017-02-02 16:20:42 -0800107import org.onosproject.segmentrouting.storekey.VlanNextObjectiveStoreKey;
Charles Chan82f19972016-05-17 13:13:55 -0700108import org.onosproject.segmentrouting.storekey.XConnectStoreKey;
Jonathan Hart54541d12016-04-12 15:39:44 -0700109import org.onosproject.store.serializers.KryoNamespaces;
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700110import org.onosproject.store.service.EventuallyConsistentMap;
111import org.onosproject.store.service.EventuallyConsistentMapBuilder;
112import org.onosproject.store.service.StorageService;
113import org.onosproject.store.service.WallClockTimestamp;
Charles Chan873661e2017-11-30 15:37:50 -0800114import org.osgi.service.component.ComponentContext;
sangho80f11cb2015-04-01 13:05:26 -0700115import org.slf4j.Logger;
116import org.slf4j.LoggerFactory;
117
Jonathan Hart61e24e12017-11-30 18:23:42 -0800118import java.util.Collections;
Charles Chan873661e2017-11-30 15:37:50 -0800119import java.util.Dictionary;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800120import java.util.HashSet;
121import java.util.List;
122import java.util.Map;
Jonathan Hart61e24e12017-11-30 18:23:42 -0800123import java.util.Optional;
124import java.util.Set;
125import java.util.concurrent.ConcurrentHashMap;
126import java.util.concurrent.ConcurrentLinkedQueue;
127import java.util.concurrent.Executors;
128import java.util.concurrent.ScheduledExecutorService;
129import java.util.concurrent.ScheduledFuture;
130import java.util.concurrent.TimeUnit;
131import java.util.concurrent.atomic.AtomicBoolean;
132import java.util.stream.Collectors;
sangho80f11cb2015-04-01 13:05:26 -0700133
Charles Chand6d25332016-02-26 22:19:52 -0800134import static com.google.common.base.Preconditions.checkState;
Pier Ventreadb4ae62016-11-23 09:57:42 -0800135import static org.onlab.packet.Ethernet.TYPE_ARP;
Yuta HIGUCHIebee2f12016-07-21 16:54:33 -0700136import static org.onlab.util.Tools.groupedThreads;
Charles Chand6d25332016-02-26 22:19:52 -0800137
Charles Chanb7f75ac2016-01-11 18:28:54 -0800138/**
139 * Segment routing manager.
140 */
Jonathan Hart54541d12016-04-12 15:39:44 -0700141@Service
142@Component(immediate = true)
sangho27462c62015-05-14 00:39:53 -0700143public class SegmentRoutingManager implements SegmentRoutingService {
sangho80f11cb2015-04-01 13:05:26 -0700144
Charles Chan46fdfaf2016-11-09 20:51:44 -0800145 private static Logger log = LoggerFactory.getLogger(SegmentRoutingManager.class);
Charles Chan910be6a2017-08-23 14:46:43 -0700146 private static final String NOT_MASTER = "Current instance is not the master of {}. Ignore.";
sangho80f11cb2015-04-01 13:05:26 -0700147
148 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700149 private ComponentConfigService compCfgService;
sangho80f11cb2015-04-01 13:05:26 -0700150
151 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventreb6a7f342016-11-26 21:05:22 -0800152 private NeighbourResolutionService neighbourResolutionService;
153
154 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700155 CoreService coreService;
sangho80f11cb2015-04-01 13:05:26 -0700156
157 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700158 PacketService packetService;
sangho80f11cb2015-04-01 13:05:26 -0700159
160 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700161 HostService hostService;
sangho80f11cb2015-04-01 13:05:26 -0700162
163 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan873661e2017-11-30 15:37:50 -0800164 HostLocationProbingService probingService;
165
166 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700167 DeviceService deviceService;
sangho80f11cb2015-04-01 13:05:26 -0700168
169 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Saurav Dase6c448a2018-01-18 12:07:33 -0800170 DeviceAdminService deviceAdminService;
171
172 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventref3cf5b92016-11-09 14:17:26 -0800173 public FlowObjectiveService flowObjectiveService;
sangho80f11cb2015-04-01 13:05:26 -0700174
175 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700176 LinkService linkService;
sangho27462c62015-05-14 00:39:53 -0700177
Charles Chan82ab1932016-01-30 23:22:37 -0800178 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventref3cf5b92016-11-09 14:17:26 -0800179 public MastershipService mastershipService;
Charles Chandebfea32016-10-24 14:52:01 -0700180
181 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Pier Ventref3cf5b92016-11-09 14:17:26 -0800182 public StorageService storageService;
Charles Chandebfea32016-10-24 14:52:01 -0700183
184 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
185 MulticastRouteService multicastRouteService;
186
187 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan83163812018-01-09 13:45:07 -0800188 public TopologyService topologyService;
Charles Chandebfea32016-10-24 14:52:01 -0700189
190 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chandebfea32016-10-24 14:52:01 -0700191 RouteService routeService;
Charles Chan82ab1932016-01-30 23:22:37 -0800192
193 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan46fdfaf2016-11-09 20:51:44 -0800194 public NetworkConfigRegistry cfgService;
Charles Chan82ab1932016-01-30 23:22:37 -0800195
Saurav Dasc3604f12016-03-23 11:22:49 -0700196 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chan46fdfaf2016-11-09 20:51:44 -0800197 public InterfaceService interfaceService;
198
Charles Chan873661e2017-11-30 15:37:50 -0800199 @Property(name = "activeProbing", boolValue = true,
200 label = "Enable active probing to discover dual-homed hosts.")
201 boolean activeProbing = true;
202
Charles Chandebfea32016-10-24 14:52:01 -0700203 ArpHandler arpHandler = null;
204 IcmpHandler icmpHandler = null;
205 IpHandler ipHandler = null;
206 RoutingRulePopulator routingRulePopulator = null;
Ray Milkeyb85de082017-04-05 09:42:04 -0700207 ApplicationId appId;
208 DeviceConfiguration deviceConfiguration = null;
sangho80f11cb2015-04-01 13:05:26 -0700209
Charles Chandebfea32016-10-24 14:52:01 -0700210 DefaultRoutingHandler defaultRoutingHandler = null;
sangho27462c62015-05-14 00:39:53 -0700211 private TunnelHandler tunnelHandler = null;
212 private PolicyHandler policyHandler = null;
Charles Chan2b078ae2015-10-14 11:24:40 -0700213 private InternalPacketProcessor processor = null;
214 private InternalLinkListener linkListener = null;
215 private InternalDeviceListener deviceListener = null;
Charles Chan82f19972016-05-17 13:13:55 -0700216 private AppConfigHandler appCfgHandler = null;
Charles Chandebfea32016-10-24 14:52:01 -0700217 XConnectHandler xConnectHandler = null;
Saurav Dase6c448a2018-01-18 12:07:33 -0800218 McastHandler mcastHandler = null;
219 HostHandler hostHandler = null;
Pier Ventreb6a7f342016-11-26 21:05:22 -0800220 private RouteHandler routeHandler = null;
Saurav Dase6c448a2018-01-18 12:07:33 -0800221 LinkHandler linkHandler = null;
Pier Ventreb6b81d52016-12-02 08:16:05 -0800222 private SegmentRoutingNeighbourDispatcher neighbourHandler = null;
Pier Ventre6b19e482016-11-07 16:21:04 -0800223 private L2TunnelHandler l2TunnelHandler = null;
sangho80f11cb2015-04-01 13:05:26 -0700224 private InternalEventHandler eventHandler = new InternalEventHandler();
Charles Chan82ab1932016-01-30 23:22:37 -0800225 private final InternalHostListener hostListener = new InternalHostListener();
Charles Chanc91c8782016-03-30 17:54:24 -0700226 private final InternalConfigListener cfgListener = new InternalConfigListener(this);
227 private final InternalMcastListener mcastListener = new InternalMcastListener();
Charles Chandebfea32016-10-24 14:52:01 -0700228 private final InternalRouteEventListener routeListener = new InternalRouteEventListener();
sangho80f11cb2015-04-01 13:05:26 -0700229
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700230 private ScheduledExecutorService executorService = Executors
Yuta HIGUCHIebee2f12016-07-21 16:54:33 -0700231 .newScheduledThreadPool(1, groupedThreads("SegmentRoutingManager", "event-%d", log));
sangho80f11cb2015-04-01 13:05:26 -0700232
Saurav Das2d94d312015-11-24 23:21:05 -0800233 @SuppressWarnings("unused")
sangho80f11cb2015-04-01 13:05:26 -0700234 private static ScheduledFuture<?> eventHandlerFuture = null;
Saurav Das2d94d312015-11-24 23:21:05 -0800235 @SuppressWarnings("rawtypes")
Yuta HIGUCHIebee2f12016-07-21 16:54:33 -0700236 private ConcurrentLinkedQueue<Event> eventQueue = new ConcurrentLinkedQueue<>();
Saurav Dase6c448a2018-01-18 12:07:33 -0800237 Map<DeviceId, DefaultGroupHandler> groupHandlerMap =
Charles Chanb7f75ac2016-01-11 18:28:54 -0800238 new ConcurrentHashMap<>();
239 /**
Saurav Das261c3002017-06-13 15:35:54 -0700240 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan53de91f2017-08-22 15:07:34 -0700241 * Used to keep track on MPLS group information.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800242 */
Charles Chan873661e2017-11-30 15:37:50 -0800243 private EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Saurav Das261c3002017-06-13 15:35:54 -0700244 dsNextObjStore = null;
Charles Chanb7f75ac2016-01-11 18:28:54 -0800245 /**
Charles Chan53de91f2017-08-22 15:07:34 -0700246 * Per device next objective ID store with (device id + vlanid) as key.
247 * Used to keep track on L2 flood group information.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800248 */
Charles Chan873661e2017-11-30 15:37:50 -0800249 private EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer>
Charles Chan10b0fb72017-02-02 16:20:42 -0800250 vlanNextObjStore = null;
Charles Chanb7f75ac2016-01-11 18:28:54 -0800251 /**
Charles Chan53de91f2017-08-22 15:07:34 -0700252 * Per device next objective ID store with (device id + port + treatment + meta) as key.
253 * Used to keep track on L2 interface group and L3 unicast group information.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800254 */
Charles Chan873661e2017-11-30 15:37:50 -0800255 private EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer>
Saurav Das2d94d312015-11-24 23:21:05 -0800256 portNextObjStore = null;
Charles Chan10b0fb72017-02-02 16:20:42 -0800257
Saurav Das2d94d312015-11-24 23:21:05 -0800258 private EventuallyConsistentMap<String, Tunnel> tunnelStore = null;
259 private EventuallyConsistentMap<String, Policy> policyStore = null;
sangho4a5c42a2015-05-20 22:16:38 -0700260
Saurav Das261c3002017-06-13 15:35:54 -0700261 private AtomicBoolean programmingScheduled = new AtomicBoolean();
262
Charles Chanc91c8782016-03-30 17:54:24 -0700263 private final ConfigFactory<DeviceId, SegmentRoutingDeviceConfig> deviceConfigFactory =
Charles Chan82f19972016-05-17 13:13:55 -0700264 new ConfigFactory<DeviceId, SegmentRoutingDeviceConfig>(
265 SubjectFactories.DEVICE_SUBJECT_FACTORY,
Charles Chanc91c8782016-03-30 17:54:24 -0700266 SegmentRoutingDeviceConfig.class, "segmentrouting") {
Charles Chan72f556a2015-10-05 17:50:33 -0700267 @Override
Charles Chan82ab1932016-01-30 23:22:37 -0800268 public SegmentRoutingDeviceConfig createConfig() {
269 return new SegmentRoutingDeviceConfig();
Charles Chan72f556a2015-10-05 17:50:33 -0700270 }
271 };
Pier Ventre6b19e482016-11-07 16:21:04 -0800272
Charles Chanc91c8782016-03-30 17:54:24 -0700273 private final ConfigFactory<ApplicationId, SegmentRoutingAppConfig> appConfigFactory =
Charles Chan82f19972016-05-17 13:13:55 -0700274 new ConfigFactory<ApplicationId, SegmentRoutingAppConfig>(
275 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chanc91c8782016-03-30 17:54:24 -0700276 SegmentRoutingAppConfig.class, "segmentrouting") {
Charles Chan82ab1932016-01-30 23:22:37 -0800277 @Override
278 public SegmentRoutingAppConfig createConfig() {
279 return new SegmentRoutingAppConfig();
280 }
281 };
Pier Ventre6b19e482016-11-07 16:21:04 -0800282
Charles Chan82f19972016-05-17 13:13:55 -0700283 private final ConfigFactory<ApplicationId, XConnectConfig> xConnectConfigFactory =
284 new ConfigFactory<ApplicationId, XConnectConfig>(
285 SubjectFactories.APP_SUBJECT_FACTORY,
286 XConnectConfig.class, "xconnect") {
287 @Override
288 public XConnectConfig createConfig() {
289 return new XConnectConfig();
290 }
291 };
Pier Ventre6b19e482016-11-07 16:21:04 -0800292
Charles Chanc91c8782016-03-30 17:54:24 -0700293 private ConfigFactory<ApplicationId, McastConfig> mcastConfigFactory =
Charles Chan82f19972016-05-17 13:13:55 -0700294 new ConfigFactory<ApplicationId, McastConfig>(
295 SubjectFactories.APP_SUBJECT_FACTORY,
Charles Chanc91c8782016-03-30 17:54:24 -0700296 McastConfig.class, "multicast") {
297 @Override
298 public McastConfig createConfig() {
299 return new McastConfig();
300 }
301 };
302
Pier Ventre6b19e482016-11-07 16:21:04 -0800303 private final ConfigFactory<ApplicationId, PwaasConfig> pwaasConfigFactory =
304 new ConfigFactory<ApplicationId, PwaasConfig>(
305 SubjectFactories.APP_SUBJECT_FACTORY,
306 PwaasConfig.class, "pwaas") {
307 @Override
308 public PwaasConfig createConfig() {
309 return new PwaasConfig();
310 }
311 };
312
Charles Chan3ed34d82017-06-22 18:03:14 -0700313 private static final Object THREAD_SCHED_LOCK = new Object();
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -0700314 private static int numOfEventsQueued = 0;
315 private static int numOfEventsExecuted = 0;
sangho80f11cb2015-04-01 13:05:26 -0700316 private static int numOfHandlerExecution = 0;
317 private static int numOfHandlerScheduled = 0;
318
Charles Chan1963f4f2016-02-18 14:22:42 -0800319 /**
320 * Segment Routing App ID.
321 */
Charles Chan46fdfaf2016-11-09 20:51:44 -0800322 public static final String APP_NAME = "org.onosproject.segmentrouting";
Charles Chan10b0fb72017-02-02 16:20:42 -0800323
Charles Chanb7f75ac2016-01-11 18:28:54 -0800324 /**
325 * The default VLAN ID assigned to the interfaces without subnet config.
326 */
Charles Chan10b0fb72017-02-02 16:20:42 -0800327 public static final VlanId INTERNAL_VLAN = VlanId.vlanId((short) 4094);
Saurav Das7c305372015-10-28 12:39:42 -0700328
sangho80f11cb2015-04-01 13:05:26 -0700329 @Activate
Charles Chan873661e2017-11-30 15:37:50 -0800330 protected void activate(ComponentContext context) {
Charles Chan46fdfaf2016-11-09 20:51:44 -0800331 appId = coreService.registerApplication(APP_NAME);
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700332
333 log.debug("Creating EC map nsnextobjectivestore");
Saurav Das261c3002017-06-13 15:35:54 -0700334 EventuallyConsistentMapBuilder<DestinationSetNextObjectiveStoreKey, NextNeighbors>
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700335 nsNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
Saurav Das261c3002017-06-13 15:35:54 -0700336 dsNextObjStore = nsNextObjMapBuilder
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700337 .withName("nsnextobjectivestore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700338 .withSerializer(createSerializer())
Madan Jampani675ae202015-06-24 19:05:56 -0700339 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700340 .build();
Saurav Das261c3002017-06-13 15:35:54 -0700341 log.trace("Current size {}", dsNextObjStore.size());
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700342
Charles Chan10b0fb72017-02-02 16:20:42 -0800343 log.debug("Creating EC map vlannextobjectivestore");
344 EventuallyConsistentMapBuilder<VlanNextObjectiveStoreKey, Integer>
345 vlanNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
346 vlanNextObjStore = vlanNextObjMapBuilder
347 .withName("vlannextobjectivestore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700348 .withSerializer(createSerializer())
Charles Chan77277672015-10-20 16:24:19 -0700349 .withTimestampProvider((k, v) -> new WallClockTimestamp())
350 .build();
351
Saurav Das2d94d312015-11-24 23:21:05 -0800352 log.debug("Creating EC map subnetnextobjectivestore");
353 EventuallyConsistentMapBuilder<PortNextObjectiveStoreKey, Integer>
354 portNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
355 portNextObjStore = portNextObjMapBuilder
356 .withName("portnextobjectivestore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700357 .withSerializer(createSerializer())
Saurav Das2d94d312015-11-24 23:21:05 -0800358 .withTimestampProvider((k, v) -> new WallClockTimestamp())
359 .build();
360
sangho4a5c42a2015-05-20 22:16:38 -0700361 EventuallyConsistentMapBuilder<String, Tunnel> tunnelMapBuilder =
362 storageService.eventuallyConsistentMapBuilder();
sangho4a5c42a2015-05-20 22:16:38 -0700363 tunnelStore = tunnelMapBuilder
364 .withName("tunnelstore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700365 .withSerializer(createSerializer())
Madan Jampani675ae202015-06-24 19:05:56 -0700366 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho4a5c42a2015-05-20 22:16:38 -0700367 .build();
368
369 EventuallyConsistentMapBuilder<String, Policy> policyMapBuilder =
370 storageService.eventuallyConsistentMapBuilder();
sangho4a5c42a2015-05-20 22:16:38 -0700371 policyStore = policyMapBuilder
372 .withName("policystore")
Jonathan Hart54541d12016-04-12 15:39:44 -0700373 .withSerializer(createSerializer())
Madan Jampani675ae202015-06-24 19:05:56 -0700374 .withTimestampProvider((k, v) -> new WallClockTimestamp())
sangho4a5c42a2015-05-20 22:16:38 -0700375 .build();
376
Saurav Dasc3604f12016-03-23 11:22:49 -0700377 compCfgService.preSetProperty("org.onosproject.net.group.impl.GroupManager",
Pier Luigib9632ba2017-01-12 18:14:58 -0800378 "purgeOnDisconnection", "true");
Saurav Dasc3604f12016-03-23 11:22:49 -0700379 compCfgService.preSetProperty("org.onosproject.net.flow.impl.FlowRuleManager",
Pier Luigib9632ba2017-01-12 18:14:58 -0800380 "purgeOnDisconnection", "true");
Pier Luigib9632ba2017-01-12 18:14:58 -0800381 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
382 "requestInterceptsEnabled", "false");
Charles Chanc1909e12017-08-08 15:13:37 -0700383 compCfgService.preSetProperty("org.onosproject.net.neighbour.impl.NeighbourResolutionManager",
Pier Luigibc976df2017-01-12 22:46:39 -0800384 "requestInterceptsEnabled", "false");
Charles Chan9597f8d2017-07-24 15:56:10 -0700385 compCfgService.preSetProperty("org.onosproject.dhcprelay.DhcpRelayManager",
Pier Luigibc976df2017-01-12 22:46:39 -0800386 "arpEnabled", "false");
Pier Luigi0ebeb312017-02-02 22:31:34 -0800387 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
388 "greedyLearningIpv6", "true");
Charles Chancf8ea472017-02-28 15:15:17 -0800389 compCfgService.preSetProperty("org.onosproject.routing.cpr.ControlPlaneRedirectManager",
390 "forceUnprovision", "true");
Charles Chanc7b73c72017-08-10 16:57:28 -0700391 compCfgService.preSetProperty("org.onosproject.routeservice.store.RouteStoreImpl",
Charles Chan4c95c0d2017-07-20 16:16:25 -0700392 "distributed", "true");
Charles Chan804772f2017-08-14 11:42:11 -0700393 compCfgService.preSetProperty("org.onosproject.provider.host.impl.HostLocationProvider",
394 "multihomingEnabled", "true");
Charles Chan0c9c19f2017-11-29 19:54:20 -0800395 compCfgService.preSetProperty("org.onosproject.provider.lldp.impl.LldpLinkProvider",
396 "staleLinkAge", "15000");
397 compCfgService.preSetProperty("org.onosproject.net.host.impl.HostManager",
398 "allowDuplicateIps", "false");
Charles Chan873661e2017-11-30 15:37:50 -0800399 compCfgService.registerProperties(getClass());
400 modified(context);
Saurav Dasc3604f12016-03-23 11:22:49 -0700401
Charles Chan2b078ae2015-10-14 11:24:40 -0700402 processor = new InternalPacketProcessor();
403 linkListener = new InternalLinkListener();
404 deviceListener = new InternalDeviceListener();
Charles Chan82f19972016-05-17 13:13:55 -0700405 appCfgHandler = new AppConfigHandler(this);
406 xConnectHandler = new XConnectHandler(this);
Charles Chan1eaf4802016-04-18 13:44:03 -0700407 mcastHandler = new McastHandler(this);
408 hostHandler = new HostHandler(this);
Saurav Dase6c448a2018-01-18 12:07:33 -0800409 linkHandler = new LinkHandler(this);
Charles Chandebfea32016-10-24 14:52:01 -0700410 routeHandler = new RouteHandler(this);
Pier Ventreb6b81d52016-12-02 08:16:05 -0800411 neighbourHandler = new SegmentRoutingNeighbourDispatcher(this);
Pier Ventre6b19e482016-11-07 16:21:04 -0800412 l2TunnelHandler = new L2TunnelHandler(this);
Charles Chan2b078ae2015-10-14 11:24:40 -0700413
Charles Chand6d25332016-02-26 22:19:52 -0800414 cfgService.addListener(cfgListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700415 cfgService.registerConfigFactory(deviceConfigFactory);
416 cfgService.registerConfigFactory(appConfigFactory);
Charles Chan82f19972016-05-17 13:13:55 -0700417 cfgService.registerConfigFactory(xConnectConfigFactory);
Charles Chanc91c8782016-03-30 17:54:24 -0700418 cfgService.registerConfigFactory(mcastConfigFactory);
Pier Ventre6b19e482016-11-07 16:21:04 -0800419 cfgService.registerConfigFactory(pwaasConfigFactory);
Charles Chan6961f222018-01-04 14:26:07 -0800420
421 cfgListener.configureNetwork();
422
Charles Chan82ab1932016-01-30 23:22:37 -0800423 hostService.addListener(hostListener);
Charles Chan2b078ae2015-10-14 11:24:40 -0700424 packetService.addProcessor(processor, PacketProcessor.director(2));
425 linkService.addListener(linkListener);
426 deviceService.addListener(deviceListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700427 multicastRouteService.addListener(mcastListener);
Charles Chanfd48c222017-06-19 00:43:31 -0700428 routeService.addListener(routeListener);
Charles Chan2b078ae2015-10-14 11:24:40 -0700429
Andreas Pantelopoulos75eef062018-01-11 07:53:48 -0800430 l2TunnelHandler.init();
431
sangho80f11cb2015-04-01 13:05:26 -0700432 log.info("Started");
433 }
434
Saurav Dase6c448a2018-01-18 12:07:33 -0800435 KryoNamespace.Builder createSerializer() {
Jonathan Hart54541d12016-04-12 15:39:44 -0700436 return new KryoNamespace.Builder()
437 .register(KryoNamespaces.API)
Saurav Das261c3002017-06-13 15:35:54 -0700438 .register(DestinationSetNextObjectiveStoreKey.class,
Charles Chan10b0fb72017-02-02 16:20:42 -0800439 VlanNextObjectiveStoreKey.class,
Saurav Das261c3002017-06-13 15:35:54 -0700440 DestinationSet.class,
441 NextNeighbors.class,
Jonathan Hart54541d12016-04-12 15:39:44 -0700442 Tunnel.class,
443 DefaultTunnel.class,
444 Policy.class,
445 TunnelPolicy.class,
446 Policy.Type.class,
447 PortNextObjectiveStoreKey.class,
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700448 XConnectStoreKey.class,
449 DefaultL2Tunnel.class,
450 DefaultL2TunnelPolicy.class
Jonathan Hart54541d12016-04-12 15:39:44 -0700451 );
452 }
453
sangho80f11cb2015-04-01 13:05:26 -0700454 @Deactivate
455 protected void deactivate() {
Charles Chan72f556a2015-10-05 17:50:33 -0700456 cfgService.removeListener(cfgListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700457 cfgService.unregisterConfigFactory(deviceConfigFactory);
458 cfgService.unregisterConfigFactory(appConfigFactory);
Charles Chandebfea32016-10-24 14:52:01 -0700459 cfgService.unregisterConfigFactory(xConnectConfigFactory);
Charles Chanc91c8782016-03-30 17:54:24 -0700460 cfgService.unregisterConfigFactory(mcastConfigFactory);
Pier Ventre6b19e482016-11-07 16:21:04 -0800461 cfgService.unregisterConfigFactory(pwaasConfigFactory);
Charles Chan873661e2017-11-30 15:37:50 -0800462 compCfgService.unregisterProperties(getClass(), false);
Charles Chan72f556a2015-10-05 17:50:33 -0700463
Charles Chanfd48c222017-06-19 00:43:31 -0700464 hostService.removeListener(hostListener);
sangho80f11cb2015-04-01 13:05:26 -0700465 packetService.removeProcessor(processor);
Charles Chan2b078ae2015-10-14 11:24:40 -0700466 linkService.removeListener(linkListener);
467 deviceService.removeListener(deviceListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700468 multicastRouteService.removeListener(mcastListener);
Charles Chandebfea32016-10-24 14:52:01 -0700469 routeService.removeListener(routeListener);
Charles Chanc91c8782016-03-30 17:54:24 -0700470
Charles Chan2e71ef32017-02-23 15:44:08 -0800471 neighbourResolutionService.unregisterNeighbourHandlers(appId);
472
sangho80f11cb2015-04-01 13:05:26 -0700473 processor = null;
Charles Chan2b078ae2015-10-14 11:24:40 -0700474 linkListener = null;
Charles Chanc91c8782016-03-30 17:54:24 -0700475 deviceListener = null;
Charles Chan2b078ae2015-10-14 11:24:40 -0700476 groupHandlerMap.clear();
477
Saurav Das261c3002017-06-13 15:35:54 -0700478 dsNextObjStore.destroy();
Charles Chan10b0fb72017-02-02 16:20:42 -0800479 vlanNextObjStore.destroy();
Charles Chanc91c8782016-03-30 17:54:24 -0700480 portNextObjStore.destroy();
Charles Chanc91c8782016-03-30 17:54:24 -0700481 tunnelStore.destroy();
482 policyStore.destroy();
sangho80f11cb2015-04-01 13:05:26 -0700483 log.info("Stopped");
484 }
485
Charles Chan873661e2017-11-30 15:37:50 -0800486 @Modified
487 private void modified(ComponentContext context) {
488 Dictionary<?, ?> properties = context.getProperties();
489 if (properties == null) {
490 return;
491 }
492
493 String strActiveProving = Tools.get(properties, "activeProbing");
494 boolean expectActiveProbing = Boolean.parseBoolean(strActiveProving);
495
496 if (expectActiveProbing != activeProbing) {
497 activeProbing = expectActiveProbing;
498 log.info("{} active probing", activeProbing ? "Enabling" : "Disabling");
499 }
500 }
501
sangho27462c62015-05-14 00:39:53 -0700502 @Override
503 public List<Tunnel> getTunnels() {
504 return tunnelHandler.getTunnels();
505 }
506
507 @Override
sanghobd812f82015-06-29 14:58:47 -0700508 public TunnelHandler.Result createTunnel(Tunnel tunnel) {
509 return tunnelHandler.createTunnel(tunnel);
sangho27462c62015-05-14 00:39:53 -0700510 }
511
512 @Override
sanghobd812f82015-06-29 14:58:47 -0700513 public TunnelHandler.Result removeTunnel(Tunnel tunnel) {
sangho27462c62015-05-14 00:39:53 -0700514 for (Policy policy: policyHandler.getPolicies()) {
515 if (policy.type() == Policy.Type.TUNNEL_FLOW) {
516 TunnelPolicy tunnelPolicy = (TunnelPolicy) policy;
517 if (tunnelPolicy.tunnelId().equals(tunnel.id())) {
518 log.warn("Cannot remove the tunnel used by a policy");
sanghobd812f82015-06-29 14:58:47 -0700519 return TunnelHandler.Result.TUNNEL_IN_USE;
sangho27462c62015-05-14 00:39:53 -0700520 }
521 }
522 }
sanghobd812f82015-06-29 14:58:47 -0700523 return tunnelHandler.removeTunnel(tunnel);
sangho27462c62015-05-14 00:39:53 -0700524 }
525
526 @Override
sanghobd812f82015-06-29 14:58:47 -0700527 public PolicyHandler.Result removePolicy(Policy policy) {
528 return policyHandler.removePolicy(policy);
sangho27462c62015-05-14 00:39:53 -0700529 }
530
531 @Override
sanghobd812f82015-06-29 14:58:47 -0700532 public PolicyHandler.Result createPolicy(Policy policy) {
533 return policyHandler.createPolicy(policy);
sangho27462c62015-05-14 00:39:53 -0700534 }
535
536 @Override
537 public List<Policy> getPolicies() {
538 return policyHandler.getPolicies();
539 }
540
Saurav Das07c74602016-04-27 18:35:50 -0700541 @Override
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700542 public List<DefaultL2Tunnel> getL2Tunnels() {
543 return l2TunnelHandler.getL2Tunnels();
544 }
545
546 @Override
547 public List<DefaultL2TunnelPolicy> getL2Policies() {
548 return l2TunnelHandler.getL2Policies();
549 }
550
551 @Override
552 public L2TunnelHandler.Result addPseudowire(String tunnelId, String pwLabel, String cP1,
553 String cP1InnerVlan, String cP1OuterVlan, String cP2,
554 String cP2InnerVlan, String cP2OuterVlan,
555 String mode, String sdTag) {
Andreas Pantelopoulosafc637f2017-12-20 18:04:27 -0800556 // Try to inject an empty Pwaas config if it is not found for the first time
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700557 PwaasConfig config = cfgService.getConfig(appId(), PwaasConfig.class);
558 if (config == null) {
Andreas Pantelopoulosafc637f2017-12-20 18:04:27 -0800559 log.debug("Pwaas config not found. Try to create an empty one.");
560 cfgService.applyConfig(appId(), PwaasConfig.class, new ObjectMapper().createObjectNode());
561 config = cfgService.getConfig(appId(), PwaasConfig.class);
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700562 }
563
564 ObjectNode object = config.addPseudowire(tunnelId, pwLabel,
565 cP1, cP1InnerVlan, cP1OuterVlan,
566 cP2, cP2InnerVlan, cP2OuterVlan,
567 mode, sdTag);
568 if (object == null) {
569 log.warn("Could not add pseudowire to the configuration!");
570 return L2TunnelHandler.Result.ADDITION_ERROR;
571 }
572
573 // inform everyone about the valid change in the pw configuration
574 cfgService.applyConfig(appId(), PwaasConfig.class, object);
575 return L2TunnelHandler.Result.SUCCESS;
576 }
577
578 @Override
579 public L2TunnelHandler.Result removePseudowire(String pwId) {
580
581 PwaasConfig config = cfgService.getConfig(appId(), PwaasConfig.class);
582 if (config == null) {
583 log.warn("Configuration for Pwaas class could not be found!");
584 return L2TunnelHandler.Result.CONFIG_NOT_FOUND;
585 }
586
587 ObjectNode object = config.removePseudowire(pwId);
588 if (object == null) {
589 log.warn("Could not delete pseudowire from configuration!");
590 return L2TunnelHandler.Result.REMOVAL_ERROR;
591 }
592
593 // sanity check, this should never fail since we removed a pw
594 // and we always check when we update the configuration
595 config.isValid();
596
597 // inform everyone
598 cfgService.applyConfig(appId(), PwaasConfig.class, object);
599
600 return L2TunnelHandler.Result.SUCCESS;
601 }
602
603 @Override
Saurav Das07c74602016-04-27 18:35:50 -0700604 public void rerouteNetwork() {
605 cfgListener.configureNetwork();
Saurav Das07c74602016-04-27 18:35:50 -0700606 }
607
Charles Chand7844e52016-10-20 17:02:44 -0700608 @Override
Pier Ventreb6a7f342016-11-26 21:05:22 -0800609 public Map<DeviceId, Set<IpPrefix>> getDeviceSubnetMap() {
610 Map<DeviceId, Set<IpPrefix>> deviceSubnetMap = Maps.newHashMap();
Jonathan Hart61e24e12017-11-30 18:23:42 -0800611 deviceConfiguration.getRouters().forEach(device ->
612 deviceSubnetMap.put(device, deviceConfiguration.getSubnets(device)));
Charles Chand7844e52016-10-20 17:02:44 -0700613 return deviceSubnetMap;
614 }
615
Saurav Das62ae6792017-05-15 15:34:25 -0700616
617 @Override
618 public ImmutableMap<DeviceId, EcmpShortestPathGraph> getCurrentEcmpSpg() {
619 if (defaultRoutingHandler != null) {
620 return defaultRoutingHandler.getCurrentEmcpSpgMap();
621 } else {
622 return null;
623 }
624 }
625
626 @Override
Saurav Das261c3002017-06-13 15:35:54 -0700627 public ImmutableMap<DestinationSetNextObjectiveStoreKey, NextNeighbors> getDestinationSet() {
628 if (dsNextObjStore != null) {
629 return ImmutableMap.copyOf(dsNextObjStore.entrySet());
Saurav Das62ae6792017-05-15 15:34:25 -0700630 } else {
631 return ImmutableMap.of();
632 }
633 }
634
Saurav Dasfbe74572017-08-03 18:30:35 -0700635 @Override
636 public void verifyGroups(DeviceId id) {
637 DefaultGroupHandler gh = groupHandlerMap.get(id);
638 if (gh != null) {
639 gh.triggerBucketCorrector();
640 }
641 }
642
Saurav Das6430f412018-01-25 09:49:01 -0800643 @Override
644 public ImmutableMap<Link, Boolean> getSeenLinks() {
645 return linkHandler.getSeenLinks();
646 }
647
648 @Override
649 public ImmutableMap<DeviceId, Set<PortNumber>> getDownedPortState() {
650 return linkHandler.getDownedPorts();
651 }
652
sangho80f1f892015-05-19 11:57:42 -0700653 /**
Ray Milkeyb85de082017-04-05 09:42:04 -0700654 * Extracts the application ID from the manager.
655 *
656 * @return application ID
657 */
658 public ApplicationId appId() {
659 return appId;
660 }
661
662 /**
663 * Returns the device configuration.
664 *
665 * @return device configuration
666 */
667 public DeviceConfiguration deviceConfiguration() {
668 return deviceConfiguration;
669 }
670
671 /**
Saurav Das261c3002017-06-13 15:35:54 -0700672 * Per device next objective ID store with (device id + destination set) as key.
Charles Chan53de91f2017-08-22 15:07:34 -0700673 * Used to keep track on MPLS group information.
Ray Milkeyb85de082017-04-05 09:42:04 -0700674 *
675 * @return next objective ID store
676 */
Saurav Das261c3002017-06-13 15:35:54 -0700677 public EventuallyConsistentMap<DestinationSetNextObjectiveStoreKey, NextNeighbors>
678 dsNextObjStore() {
679 return dsNextObjStore;
Ray Milkeyb85de082017-04-05 09:42:04 -0700680 }
681
682 /**
Charles Chan53de91f2017-08-22 15:07:34 -0700683 * Per device next objective ID store with (device id + vlanid) as key.
684 * Used to keep track on L2 flood group information.
Ray Milkeyb85de082017-04-05 09:42:04 -0700685 *
686 * @return vlan next object store
687 */
688 public EventuallyConsistentMap<VlanNextObjectiveStoreKey, Integer> vlanNextObjStore() {
689 return vlanNextObjStore;
690 }
691
692 /**
Charles Chan53de91f2017-08-22 15:07:34 -0700693 * Per device next objective ID store with (device id + port + treatment + meta) as key.
694 * Used to keep track on L2 interface group and L3 unicast group information.
Ray Milkeyb85de082017-04-05 09:42:04 -0700695 *
696 * @return port next object store.
697 */
698 public EventuallyConsistentMap<PortNextObjectiveStoreKey, Integer> portNextObjStore() {
699 return portNextObjStore;
700 }
701
702 /**
Saurav Das261c3002017-06-13 15:35:54 -0700703 * Returns the MPLS-ECMP configuration which indicates whether ECMP on
704 * labeled packets should be programmed or not.
Pier Ventre7a78de22016-10-31 15:00:01 -0700705 *
706 * @return MPLS-ECMP value
707 */
708 public boolean getMplsEcmp() {
709 SegmentRoutingAppConfig segmentRoutingAppConfig = cfgService
710 .getConfig(this.appId, SegmentRoutingAppConfig.class);
711 return segmentRoutingAppConfig != null && segmentRoutingAppConfig.mplsEcmp();
712 }
713
714 /**
sangho80f1f892015-05-19 11:57:42 -0700715 * Returns the tunnel object with the tunnel ID.
716 *
717 * @param tunnelId Tunnel ID
718 * @return Tunnel reference
719 */
sangho27462c62015-05-14 00:39:53 -0700720 public Tunnel getTunnel(String tunnelId) {
721 return tunnelHandler.getTunnel(tunnelId);
722 }
723
Charles Chan90772a72017-02-08 15:52:08 -0800724 // TODO Consider moving these to InterfaceService
sangho80f11cb2015-04-01 13:05:26 -0700725 /**
Charles Chan10b0fb72017-02-02 16:20:42 -0800726 * Returns untagged VLAN configured on given connect point.
Charles Chan90772a72017-02-08 15:52:08 -0800727 * <p>
728 * Only returns the first match if there are multiple untagged VLAN configured
729 * on the connect point.
sangho80f11cb2015-04-01 13:05:26 -0700730 *
Charles Chan10b0fb72017-02-02 16:20:42 -0800731 * @param connectPoint connect point
732 * @return untagged VLAN or null if not configured
sangho80f11cb2015-04-01 13:05:26 -0700733 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700734 VlanId getUntaggedVlanId(ConnectPoint connectPoint) {
Charles Chan10b0fb72017-02-02 16:20:42 -0800735 return interfaceService.getInterfacesByPort(connectPoint).stream()
736 .filter(intf -> !intf.vlanUntagged().equals(VlanId.NONE))
737 .map(Interface::vlanUntagged)
738 .findFirst().orElse(null);
sangho80f11cb2015-04-01 13:05:26 -0700739 }
740
sangho27462c62015-05-14 00:39:53 -0700741 /**
Charles Chan90772a72017-02-08 15:52:08 -0800742 * Returns tagged VLAN configured on given connect point.
743 * <p>
744 * Returns all matches if there are multiple tagged VLAN configured
745 * on the connect point.
746 *
747 * @param connectPoint connect point
748 * @return tagged VLAN or empty set if not configured
749 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700750 Set<VlanId> getTaggedVlanId(ConnectPoint connectPoint) {
Charles Chan90772a72017-02-08 15:52:08 -0800751 Set<Interface> interfaces = interfaceService.getInterfacesByPort(connectPoint);
752 return interfaces.stream()
753 .map(Interface::vlanTagged)
Charles Chan3ed34d82017-06-22 18:03:14 -0700754 .flatMap(Set::stream)
Charles Chan90772a72017-02-08 15:52:08 -0800755 .collect(Collectors.toSet());
756 }
757
758 /**
759 * Returns native VLAN configured on given connect point.
760 * <p>
761 * Only returns the first match if there are multiple native VLAN configured
762 * on the connect point.
763 *
764 * @param connectPoint connect point
765 * @return native VLAN or null if not configured
766 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700767 VlanId getNativeVlanId(ConnectPoint connectPoint) {
Charles Chan90772a72017-02-08 15:52:08 -0800768 Set<Interface> interfaces = interfaceService.getInterfacesByPort(connectPoint);
769 return interfaces.stream()
770 .filter(intf -> !intf.vlanNative().equals(VlanId.NONE))
771 .map(Interface::vlanNative)
772 .findFirst()
773 .orElse(null);
774 }
775
776 /**
Charles Chand9265a32017-06-16 15:19:24 -0700777 * Returns internal VLAN for untagged hosts on given connect point.
778 * <p>
779 * The internal VLAN is either vlan-untagged for an access port,
780 * or vlan-native for a trunk port.
781 *
782 * @param connectPoint connect point
783 * @return internal VLAN or null if both vlan-untagged and vlan-native are undefined
784 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700785 VlanId getInternalVlanId(ConnectPoint connectPoint) {
Charles Chand9265a32017-06-16 15:19:24 -0700786 VlanId untaggedVlanId = getUntaggedVlanId(connectPoint);
787 VlanId nativeVlanId = getNativeVlanId(connectPoint);
788 return untaggedVlanId != null ? untaggedVlanId : nativeVlanId;
789 }
790
791 /**
Charles Chan3ed34d82017-06-22 18:03:14 -0700792 * Returns optional pair device ID of given device.
793 *
794 * @param deviceId device ID
795 * @return optional pair device ID. Might be empty if pair device is not configured
796 */
797 Optional<DeviceId> getPairDeviceId(DeviceId deviceId) {
798 SegmentRoutingDeviceConfig deviceConfig =
799 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
800 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairDeviceId);
801 }
802 /**
803 * Returns optional pair device local port of given device.
804 *
805 * @param deviceId device ID
806 * @return optional pair device ID. Might be empty if pair device is not configured
807 */
808 Optional<PortNumber> getPairLocalPorts(DeviceId deviceId) {
809 SegmentRoutingDeviceConfig deviceConfig =
810 cfgService.getConfig(deviceId, SegmentRoutingDeviceConfig.class);
811 return Optional.ofNullable(deviceConfig).map(SegmentRoutingDeviceConfig::pairLocalPort);
812 }
813
814 /**
Charles Chan910be6a2017-08-23 14:46:43 -0700815 * Determine if current instance is the master of given connect point.
816 *
817 * @param cp connect point
818 * @return true if current instance is the master of given connect point
819 */
Andreas Pantelopoulos5e7be3d2017-10-23 12:18:25 -0700820 public boolean isMasterOf(ConnectPoint cp) {
Charles Chan910be6a2017-08-23 14:46:43 -0700821 boolean isMaster = mastershipService.isLocalMaster(cp.deviceId());
822 if (!isMaster) {
823 log.debug(NOT_MASTER, cp);
824 }
825 return isMaster;
826 }
827
828 /**
Charles Chanf0ae41e2017-08-23 13:55:39 -0700829 * Returns locations of given resolved route.
830 *
831 * @param resolvedRoute resolved route
832 * @return locations of nexthop. Might be empty if next hop is not found
833 */
834 Set<ConnectPoint> nextHopLocations(ResolvedRoute resolvedRoute) {
835 HostId hostId = HostId.hostId(resolvedRoute.nextHopMac(), resolvedRoute.nextHopVlan());
836 return Optional.ofNullable(hostService.getHost(hostId))
837 .map(Host::locations).orElse(Sets.newHashSet())
838 .stream().map(l -> (ConnectPoint) l).collect(Collectors.toSet());
839 }
840
841 /**
Charles Chan90772a72017-02-08 15:52:08 -0800842 * Returns vlan port map of given device.
843 *
844 * @param deviceId device id
845 * @return vlan-port multimap
846 */
847 public Multimap<VlanId, PortNumber> getVlanPortMap(DeviceId deviceId) {
848 HashMultimap<VlanId, PortNumber> vlanPortMap = HashMultimap.create();
849
850 interfaceService.getInterfaces().stream()
851 .filter(intf -> intf.connectPoint().deviceId().equals(deviceId))
852 .forEach(intf -> {
853 vlanPortMap.put(intf.vlanUntagged(), intf.connectPoint().port());
Charles Chan3ed34d82017-06-22 18:03:14 -0700854 intf.vlanTagged().forEach(vlanTagged ->
855 vlanPortMap.put(vlanTagged, intf.connectPoint().port())
856 );
Charles Chan90772a72017-02-08 15:52:08 -0800857 vlanPortMap.put(intf.vlanNative(), intf.connectPoint().port());
858 });
859 vlanPortMap.removeAll(VlanId.NONE);
860
861 return vlanPortMap;
862 }
863
864 /**
Charles Chan10b0fb72017-02-02 16:20:42 -0800865 * Returns the next objective ID for the given vlan id. It is expected
Saurav Das2d94d312015-11-24 23:21:05 -0800866 * that the next-objective has been pre-created from configuration.
Charles Chan77277672015-10-20 16:24:19 -0700867 *
868 * @param deviceId Device ID
Charles Chan10b0fb72017-02-02 16:20:42 -0800869 * @param vlanId VLAN ID
Saurav Das2d94d312015-11-24 23:21:05 -0800870 * @return next objective ID or -1 if it was not found
Charles Chan77277672015-10-20 16:24:19 -0700871 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700872 int getVlanNextObjectiveId(DeviceId deviceId, VlanId vlanId) {
Charles Chan77277672015-10-20 16:24:19 -0700873 if (groupHandlerMap.get(deviceId) != null) {
Charles Chan10b0fb72017-02-02 16:20:42 -0800874 log.trace("getVlanNextObjectiveId query in device {}", deviceId);
875 return groupHandlerMap.get(deviceId).getVlanNextObjectiveId(vlanId);
Charles Chan77277672015-10-20 16:24:19 -0700876 } else {
Charles Chan10b0fb72017-02-02 16:20:42 -0800877 log.warn("getVlanNextObjectiveId query - groupHandler for "
Saurav Das2d94d312015-11-24 23:21:05 -0800878 + "device {} not found", deviceId);
879 return -1;
880 }
881 }
882
883 /**
884 * Returns the next objective ID for the given portNumber, given the treatment.
885 * There could be multiple different treatments to the same outport, which
Saurav Das2cb38292017-03-29 19:09:17 -0700886 * would result in different objectives. If the next object does not exist,
887 * and should be created, a new one is created and its id is returned.
Saurav Das2d94d312015-11-24 23:21:05 -0800888 *
889 * @param deviceId Device ID
890 * @param portNum port number on device for which NextObjective is queried
891 * @param treatment the actions to apply on the packets (should include outport)
892 * @param meta metadata passed into the creation of a Next Objective if necessary
Saurav Das2cb38292017-03-29 19:09:17 -0700893 * @param createIfMissing true if a next object should be created if not found
Saurav Das07c74602016-04-27 18:35:50 -0700894 * @return next objective ID or -1 if an error occurred during retrieval or creation
Saurav Das2d94d312015-11-24 23:21:05 -0800895 */
896 public int getPortNextObjectiveId(DeviceId deviceId, PortNumber portNum,
897 TrafficTreatment treatment,
Saurav Das2cb38292017-03-29 19:09:17 -0700898 TrafficSelector meta,
899 boolean createIfMissing) {
Saurav Das2d94d312015-11-24 23:21:05 -0800900 DefaultGroupHandler ghdlr = groupHandlerMap.get(deviceId);
901 if (ghdlr != null) {
Saurav Das2cb38292017-03-29 19:09:17 -0700902 return ghdlr.getPortNextObjectiveId(portNum, treatment, meta, createIfMissing);
Saurav Das2d94d312015-11-24 23:21:05 -0800903 } else {
Charles Chanb7f75ac2016-01-11 18:28:54 -0800904 log.warn("getPortNextObjectiveId query - groupHandler for device {}"
905 + " not found", deviceId);
906 return -1;
907 }
908 }
909
Saurav Das62ae6792017-05-15 15:34:25 -0700910 /**
911 * Returns the group handler object for the specified device id.
912 *
913 * @param devId the device identifier
914 * @return the groupHandler object for the device id, or null if not found
915 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700916 DefaultGroupHandler getGroupHandler(DeviceId devId) {
Saurav Das62ae6792017-05-15 15:34:25 -0700917 return groupHandlerMap.get(devId);
918 }
919
920 /**
Saurav Dasfbe74572017-08-03 18:30:35 -0700921 * Returns the default routing handler object.
922 *
923 * @return the default routing handler object
924 */
925 public DefaultRoutingHandler getRoutingHandler() {
926 return defaultRoutingHandler;
927 }
928
sangho80f11cb2015-04-01 13:05:26 -0700929 private class InternalPacketProcessor implements PacketProcessor {
sangho80f11cb2015-04-01 13:05:26 -0700930 @Override
931 public void process(PacketContext context) {
932
933 if (context.isHandled()) {
934 return;
935 }
936
937 InboundPacket pkt = context.inPacket();
938 Ethernet ethernet = pkt.parsed();
Pier Luigi37a35432017-02-01 13:50:04 -0800939
940 if (ethernet == null) {
941 return;
942 }
943
Saurav Das261c3002017-06-13 15:35:54 -0700944 log.trace("Rcvd pktin from {}: {}", context.inPacket().receivedFrom(),
945 ethernet);
Pier Ventreadb4ae62016-11-23 09:57:42 -0800946 if (ethernet.getEtherType() == TYPE_ARP) {
Saurav Das62ae6792017-05-15 15:34:25 -0700947 log.warn("Received unexpected ARP packet on {}",
948 context.inPacket().receivedFrom());
Saurav Das368cf212017-03-15 15:15:14 -0700949 log.trace("{}", ethernet);
Pier Ventre6b2c1b32016-12-09 17:26:04 -0800950 return;
sangho80f11cb2015-04-01 13:05:26 -0700951 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV4) {
Pier Ventreb6b81d52016-12-02 08:16:05 -0800952 IPv4 ipv4Packet = (IPv4) ethernet.getPayload();
953 //ipHandler.addToPacketBuffer(ipv4Packet);
954 if (ipv4Packet.getProtocol() == IPv4.PROTOCOL_ICMP) {
955 icmpHandler.processIcmp(ethernet, pkt.receivedFrom());
sangho80f11cb2015-04-01 13:05:26 -0700956 } else {
Charles Chand041ad82017-01-13 17:20:44 -0800957 // NOTE: We don't support IP learning at this moment so this
958 // is not necessary. Also it causes duplication of DHCP packets.
Pier Ventre6b2c1b32016-12-09 17:26:04 -0800959 // ipHandler.processPacketIn(ipv4Packet, pkt.receivedFrom());
sangho80f11cb2015-04-01 13:05:26 -0700960 }
Pier Ventreb6a7f342016-11-26 21:05:22 -0800961 } else if (ethernet.getEtherType() == Ethernet.TYPE_IPV6) {
962 IPv6 ipv6Packet = (IPv6) ethernet.getPayload();
Pier Ventreb6b81d52016-12-02 08:16:05 -0800963 //ipHandler.addToPacketBuffer(ipv6Packet);
Pier Luigi37a35432017-02-01 13:50:04 -0800964 // We deal with the packet only if the packet is a ICMP6 ECHO/REPLY
Pier Ventreb6b81d52016-12-02 08:16:05 -0800965 if (ipv6Packet.getNextHeader() == IPv6.PROTOCOL_ICMP6) {
966 ICMP6 icmp6Packet = (ICMP6) ipv6Packet.getPayload();
967 if (icmp6Packet.getIcmpType() == ICMP6.ECHO_REQUEST ||
968 icmp6Packet.getIcmpType() == ICMP6.ECHO_REPLY) {
969 icmpHandler.processIcmpv6(ethernet, pkt.receivedFrom());
970 } else {
Saurav Das62ae6792017-05-15 15:34:25 -0700971 log.trace("Received ICMPv6 0x{} - not handled",
Charles Chand3727b72017-03-13 13:10:30 -0700972 Integer.toHexString(icmp6Packet.getIcmpType() & 0xff));
Pier Ventreb6b81d52016-12-02 08:16:05 -0800973 }
974 } else {
975 // NOTE: We don't support IP learning at this moment so this
976 // is not necessary. Also it causes duplication of DHCPv6 packets.
977 // ipHandler.processPacketIn(ipv6Packet, pkt.receivedFrom());
978 }
sangho80f11cb2015-04-01 13:05:26 -0700979 }
980 }
981 }
982
983 private class InternalLinkListener implements LinkListener {
984 @Override
985 public void event(LinkEvent event) {
Charles Chan0cff8aa2017-03-29 16:39:05 -0700986 if (event.type() == LinkEvent.Type.LINK_ADDED ||
987 event.type() == LinkEvent.Type.LINK_UPDATED ||
988 event.type() == LinkEvent.Type.LINK_REMOVED) {
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -0700989 log.debug("Event {} received from Link Service", event.type());
sangho80f11cb2015-04-01 13:05:26 -0700990 scheduleEventHandlerIfNotScheduled(event);
991 }
992 }
993 }
994
995 private class InternalDeviceListener implements DeviceListener {
sangho80f11cb2015-04-01 13:05:26 -0700996 @Override
997 public void event(DeviceEvent event) {
sangho80f11cb2015-04-01 13:05:26 -0700998 switch (event.type()) {
999 case DEVICE_ADDED:
Saurav Dasf0f592d2016-11-18 15:21:57 -08001000 case PORT_UPDATED:
1001 case PORT_ADDED:
sanghofb7c7292015-04-13 15:15:58 -07001002 case DEVICE_UPDATED:
1003 case DEVICE_AVAILABILITY_CHANGED:
Saurav Das62ae6792017-05-15 15:34:25 -07001004 log.trace("Event {} received from Device Service", event.type());
sangho80f11cb2015-04-01 13:05:26 -07001005 scheduleEventHandlerIfNotScheduled(event);
1006 break;
1007 default:
1008 }
1009 }
1010 }
1011
Saurav Das2d94d312015-11-24 23:21:05 -08001012 @SuppressWarnings("rawtypes")
sangho80f11cb2015-04-01 13:05:26 -07001013 private void scheduleEventHandlerIfNotScheduled(Event event) {
Charles Chan3ed34d82017-06-22 18:03:14 -07001014 synchronized (THREAD_SCHED_LOCK) {
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -07001015 eventQueue.add(event);
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001016 numOfEventsQueued++;
1017
1018 if ((numOfHandlerScheduled - numOfHandlerExecution) == 0) {
1019 //No pending scheduled event handling threads. So start a new one.
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -07001020 eventHandlerFuture = executorService
1021 .schedule(eventHandler, 100, TimeUnit.MILLISECONDS);
1022 numOfHandlerScheduled++;
1023 }
Jonathan Hart54541d12016-04-12 15:39:44 -07001024 log.trace("numOfEventsQueued {}, numOfEventHandlerScheduled {}",
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001025 numOfEventsQueued,
1026 numOfHandlerScheduled);
sangho80f11cb2015-04-01 13:05:26 -07001027 }
sangho80f11cb2015-04-01 13:05:26 -07001028 }
1029
1030 private class InternalEventHandler implements Runnable {
Srikanth Vavilapalli37a461b2015-04-07 15:12:32 -07001031 @Override
sangho80f11cb2015-04-01 13:05:26 -07001032 public void run() {
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -07001033 try {
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001034 while (true) {
Saurav Das2d94d312015-11-24 23:21:05 -08001035 @SuppressWarnings("rawtypes")
Charles Chan3ed34d82017-06-22 18:03:14 -07001036 Event event;
1037 synchronized (THREAD_SCHED_LOCK) {
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001038 if (!eventQueue.isEmpty()) {
1039 event = eventQueue.poll();
1040 numOfEventsExecuted++;
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -07001041 } else {
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001042 numOfHandlerExecution++;
1043 log.debug("numOfHandlerExecution {} numOfEventsExecuted {}",
1044 numOfHandlerExecution, numOfEventsExecuted);
1045 break;
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -07001046 }
sanghofb7c7292015-04-13 15:15:58 -07001047 }
Charles Chan0cff8aa2017-03-29 16:39:05 -07001048 if (event.type() == LinkEvent.Type.LINK_ADDED ||
1049 event.type() == LinkEvent.Type.LINK_UPDATED) {
Saurav Das62ae6792017-05-15 15:34:25 -07001050 // Note: do not update seenLinks here, otherwise every
1051 // link, even one seen for the first time, will be appear
1052 // to be a previously seen link
Saurav Dase6c448a2018-01-18 12:07:33 -08001053 linkHandler.processLinkAdded((Link) event.subject());
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001054 } else if (event.type() == LinkEvent.Type.LINK_REMOVED) {
Saurav Dase6c448a2018-01-18 12:07:33 -08001055 linkHandler.processLinkRemoved((Link) event.subject());
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001056 } else if (event.type() == DeviceEvent.Type.DEVICE_ADDED ||
1057 event.type() == DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED ||
1058 event.type() == DeviceEvent.Type.DEVICE_UPDATED) {
Saurav Das62af8802015-12-04 10:52:59 -08001059 DeviceId deviceId = ((Device) event.subject()).id();
1060 if (deviceService.isAvailable(deviceId)) {
Saurav Dasc28b3432015-10-30 17:45:38 -07001061 log.info("Processing device event {} for available device {}",
1062 event.type(), ((Device) event.subject()).id());
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001063 processDeviceAdded((Device) event.subject());
Saurav Dasc3604f12016-03-23 11:22:49 -07001064 } else {
1065 log.info("Processing device event {} for unavailable device {}",
1066 event.type(), ((Device) event.subject()).id());
1067 processDeviceRemoved((Device) event.subject());
1068 }
Saurav Dasf0f592d2016-11-18 15:21:57 -08001069 } else if (event.type() == DeviceEvent.Type.PORT_ADDED) {
Saurav Dasd1872b02016-12-02 15:43:47 -08001070 // typically these calls come when device is added first time
1071 // so port filtering rules are handled at the device_added event.
1072 // port added calls represent all ports on the device,
1073 // enabled or not.
Saurav Das62ae6792017-05-15 15:34:25 -07001074 log.trace("** PORT ADDED {}/{} -> {}",
Saurav Dasd1872b02016-12-02 15:43:47 -08001075 ((DeviceEvent) event).subject().id(),
1076 ((DeviceEvent) event).port().number(),
1077 event.type());
Saurav Dasf0f592d2016-11-18 15:21:57 -08001078 } else if (event.type() == DeviceEvent.Type.PORT_UPDATED) {
Saurav Dasd1872b02016-12-02 15:43:47 -08001079 // these calls happen for every subsequent event
1080 // ports enabled, disabled, switch goes away, comes back
Saurav Dasf0f592d2016-11-18 15:21:57 -08001081 log.info("** PORT UPDATED {}/{} -> {}",
1082 event.subject(),
1083 ((DeviceEvent) event).port(),
1084 event.type());
1085 processPortUpdated(((Device) event.subject()),
1086 ((DeviceEvent) event).port());
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001087 } else {
1088 log.warn("Unhandled event type: {}", event.type());
1089 }
sangho80f11cb2015-04-01 13:05:26 -07001090 }
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -07001091 } catch (Exception e) {
1092 log.error("SegmentRouting event handler "
1093 + "thread thrown an exception: {}", e);
sangho80f11cb2015-04-01 13:05:26 -07001094 }
sangho80f11cb2015-04-01 13:05:26 -07001095 }
1096 }
1097
Saurav Dase6c448a2018-01-18 12:07:33 -08001098 void processDeviceAdded(Device device) {
Saurav Dasb149be12016-06-07 10:08:06 -07001099 log.info("** DEVICE ADDED with ID {}", device.id());
Charles Chan9bd6aea2017-06-27 18:48:32 -07001100
1101 // NOTE: Punt ARP/NDP even when the device is not configured.
1102 // Host learning without network config is required for CORD config generator.
1103 routingRulePopulator.populateIpPunts(device.id());
1104 routingRulePopulator.populateArpNdpPunts(device.id());
1105
Charles Chan319d1a22015-11-03 10:42:14 -08001106 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
Saurav Das261c3002017-06-13 15:35:54 -07001107 log.warn("Device configuration unavailable. Device {} will be "
1108 + "processed after configuration.", device.id());
Saurav Das8ec0ec42015-11-03 14:39:27 -08001109 return;
1110 }
Charles Chan72779502016-04-23 17:36:10 -07001111 processDeviceAddedInternal(device.id());
1112 }
1113
1114 private void processDeviceAddedInternal(DeviceId deviceId) {
Saurav Dasc28b3432015-10-30 17:45:38 -07001115 // Irrespective of whether the local is a MASTER or not for this device,
1116 // we need to create a SR-group-handler instance. This is because in a
1117 // multi-instance setup, any instance can initiate forwarding/next-objectives
1118 // for any switch (even if this instance is a SLAVE or not even connected
1119 // to the switch). To handle this, a default-group-handler instance is necessary
1120 // per switch.
Charles Chan72779502016-04-23 17:36:10 -07001121 log.debug("Current groupHandlerMap devs: {}", groupHandlerMap.keySet());
1122 if (groupHandlerMap.get(deviceId) == null) {
Charles Chan319d1a22015-11-03 10:42:14 -08001123 DefaultGroupHandler groupHandler;
1124 try {
1125 groupHandler = DefaultGroupHandler.
Charles Chan72779502016-04-23 17:36:10 -07001126 createGroupHandler(deviceId,
1127 appId,
1128 deviceConfiguration,
1129 linkService,
1130 flowObjectiveService,
1131 this);
Charles Chan319d1a22015-11-03 10:42:14 -08001132 } catch (DeviceConfigNotFoundException e) {
1133 log.warn(e.getMessage() + " Aborting processDeviceAdded.");
1134 return;
1135 }
Saurav Das2b6a00f2017-12-05 15:00:23 -08001136 log.debug("updating groupHandlerMap with new grpHdlr for device: {}",
Charles Chan72779502016-04-23 17:36:10 -07001137 deviceId);
1138 groupHandlerMap.put(deviceId, groupHandler);
Saurav Das8ec0ec42015-11-03 14:39:27 -08001139 }
Saurav Dasb149be12016-06-07 10:08:06 -07001140
Charles Chan72779502016-04-23 17:36:10 -07001141 if (mastershipService.isLocalMaster(deviceId)) {
Saurav Dasf9332192017-02-18 14:05:44 -08001142 defaultRoutingHandler.populatePortAddressingRules(deviceId);
Charles Chandebfea32016-10-24 14:52:01 -07001143 hostHandler.init(deviceId);
Charles Chan82f19972016-05-17 13:13:55 -07001144 xConnectHandler.init(deviceId);
Charles Chan72779502016-04-23 17:36:10 -07001145 DefaultGroupHandler groupHandler = groupHandlerMap.get(deviceId);
Charles Chan10b0fb72017-02-02 16:20:42 -08001146 groupHandler.createGroupsFromVlanConfig();
Charles Chan72779502016-04-23 17:36:10 -07001147 routingRulePopulator.populateSubnetBroadcastRule(deviceId);
Charles Chan77277672015-10-20 16:24:19 -07001148 }
Charles Chan82ab1932016-01-30 23:22:37 -08001149
Charles Chandebfea32016-10-24 14:52:01 -07001150 appCfgHandler.init(deviceId);
1151 routeHandler.init(deviceId);
sangho80f11cb2015-04-01 13:05:26 -07001152 }
1153
Saurav Dasc3604f12016-03-23 11:22:49 -07001154 private void processDeviceRemoved(Device device) {
Saurav Das261c3002017-06-13 15:35:54 -07001155 dsNextObjStore.entrySet().stream()
Saurav Dasc3604f12016-03-23 11:22:49 -07001156 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan873661e2017-11-30 15:37:50 -08001157 .forEach(entry -> dsNextObjStore.remove(entry.getKey()));
Charles Chan10b0fb72017-02-02 16:20:42 -08001158 vlanNextObjStore.entrySet().stream()
Saurav Dasc3604f12016-03-23 11:22:49 -07001159 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan3ed34d82017-06-22 18:03:14 -07001160 .forEach(entry -> vlanNextObjStore.remove(entry.getKey()));
Saurav Dasc3604f12016-03-23 11:22:49 -07001161 portNextObjStore.entrySet().stream()
1162 .filter(entry -> entry.getKey().deviceId().equals(device.id()))
Charles Chan3ed34d82017-06-22 18:03:14 -07001163 .forEach(entry -> portNextObjStore.remove(entry.getKey()));
Saurav Dase6c448a2018-01-18 12:07:33 -08001164 linkHandler.processDeviceRemoved(device);
Charles Chan17d75d82017-06-15 00:44:51 -07001165
Saurav Dasfbe74572017-08-03 18:30:35 -07001166 DefaultGroupHandler gh = groupHandlerMap.remove(device.id());
1167 if (gh != null) {
1168 gh.shutdown();
1169 }
Saurav Das62ae6792017-05-15 15:34:25 -07001170 // Note that a switch going down is associated with all of its links
1171 // going down as well, but it is treated as a single switch down event
1172 // while the link-downs are ignored.
1173 defaultRoutingHandler
1174 .populateRoutingRulesForLinkStatusChange(null, null, device.id());
Saurav Das6430f412018-01-25 09:49:01 -08001175 defaultRoutingHandler.purgeEcmpGraph(device.id());
Charles Chan72779502016-04-23 17:36:10 -07001176 mcastHandler.removeDevice(device.id());
Charles Chan82f19972016-05-17 13:13:55 -07001177 xConnectHandler.removeDevice(device.id());
Saurav Dasc3604f12016-03-23 11:22:49 -07001178 }
1179
Saurav Dasf0f592d2016-11-18 15:21:57 -08001180 private void processPortUpdated(Device device, Port port) {
1181 if (deviceConfiguration == null || !deviceConfiguration.isConfigured(device.id())) {
1182 log.warn("Device configuration uploading. Not handling port event for"
1183 + "dev: {} port: {}", device.id(), port.number());
1184 return;
1185 }
Saurav Dasf9332192017-02-18 14:05:44 -08001186
1187 if (!mastershipService.isLocalMaster(device.id())) {
1188 log.debug("Not master for dev:{} .. not handling port updated event"
1189 + "for port {}", device.id(), port.number());
1190 return;
1191 }
1192
1193 // first we handle filtering rules associated with the port
1194 if (port.isEnabled()) {
1195 log.info("Switchport {}/{} enabled..programming filters",
1196 device.id(), port.number());
Charles Chan43be46b2017-02-26 22:59:35 -08001197 routingRulePopulator.processSinglePortFilters(device.id(), port.number(), true);
Saurav Dasf9332192017-02-18 14:05:44 -08001198 } else {
1199 log.info("Switchport {}/{} disabled..removing filters",
1200 device.id(), port.number());
Charles Chan43be46b2017-02-26 22:59:35 -08001201 routingRulePopulator.processSinglePortFilters(device.id(), port.number(), false);
Saurav Dasf9332192017-02-18 14:05:44 -08001202 }
Saurav Dasf0f592d2016-11-18 15:21:57 -08001203
1204 // portUpdated calls are for ports that have gone down or up. For switch
1205 // to switch ports, link-events should take care of any re-routing or
1206 // group editing necessary for port up/down. Here we only process edge ports
1207 // that are already configured.
Saurav Das3fb28272017-03-04 16:08:47 -08001208 ConnectPoint cp = new ConnectPoint(device.id(), port.number());
1209 VlanId untaggedVlan = getUntaggedVlanId(cp);
1210 VlanId nativeVlan = getNativeVlanId(cp);
1211 Set<VlanId> taggedVlans = getTaggedVlanId(cp);
Charles Chan10b0fb72017-02-02 16:20:42 -08001212
Saurav Das3fb28272017-03-04 16:08:47 -08001213 if (untaggedVlan == null && nativeVlan == null && taggedVlans.isEmpty()) {
Saurav Das62ae6792017-05-15 15:34:25 -07001214 log.debug("Not handling port updated event for non-edge port (unconfigured) "
Saurav Dasf0f592d2016-11-18 15:21:57 -08001215 + "dev/port: {}/{}", device.id(), port.number());
1216 return;
1217 }
Saurav Das3fb28272017-03-04 16:08:47 -08001218 if (untaggedVlan != null) {
1219 processEdgePort(device, port, untaggedVlan, true);
1220 }
1221 if (nativeVlan != null) {
1222 processEdgePort(device, port, nativeVlan, true);
1223 }
1224 if (!taggedVlans.isEmpty()) {
1225 taggedVlans.forEach(tag -> processEdgePort(device, port, tag, false));
1226 }
Saurav Dasf0f592d2016-11-18 15:21:57 -08001227 }
1228
Saurav Das3fb28272017-03-04 16:08:47 -08001229 private void processEdgePort(Device device, Port port, VlanId vlanId,
1230 boolean popVlan) {
Saurav Dasf0f592d2016-11-18 15:21:57 -08001231 boolean portUp = port.isEnabled();
1232 if (portUp) {
Saurav Das3fb28272017-03-04 16:08:47 -08001233 log.info("Device:EdgePort {}:{} is enabled in vlan: {}", device.id(),
Charles Chan10b0fb72017-02-02 16:20:42 -08001234 port.number(), vlanId);
Charles Chan873661e2017-11-30 15:37:50 -08001235 hostHandler.processPortUp(new ConnectPoint(device.id(), port.number()));
Saurav Dasf0f592d2016-11-18 15:21:57 -08001236 } else {
Saurav Das3fb28272017-03-04 16:08:47 -08001237 log.info("Device:EdgePort {}:{} is disabled in vlan: {}", device.id(),
Charles Chan10b0fb72017-02-02 16:20:42 -08001238 port.number(), vlanId);
Saurav Dasf0f592d2016-11-18 15:21:57 -08001239 }
1240
Srikanth Vavilapalli64505482015-04-21 13:04:13 -07001241 DefaultGroupHandler groupHandler = groupHandlerMap.get(device.id());
sangho80f11cb2015-04-01 13:05:26 -07001242 if (groupHandler != null) {
Saurav Das3fb28272017-03-04 16:08:47 -08001243 groupHandler.processEdgePort(port.number(), vlanId, popVlan, portUp);
Saurav Dasf0f592d2016-11-18 15:21:57 -08001244 } else {
1245 log.warn("Group handler not found for dev:{}. Not handling edge port"
1246 + " {} event for port:{}", device.id(),
1247 (portUp) ? "UP" : "DOWN", port.number());
sangho80f11cb2015-04-01 13:05:26 -07001248 }
1249 }
sangho27462c62015-05-14 00:39:53 -07001250
Charles Chan8ca5a122017-10-20 16:06:55 -07001251 private void createOrUpdateDeviceConfiguration() {
1252 if (deviceConfiguration == null) {
1253 deviceConfiguration = new DeviceConfiguration(this);
1254 } else {
1255 deviceConfiguration.updateConfig();
1256 }
1257 }
1258
Pier Ventreb6a7f342016-11-26 21:05:22 -08001259 /**
1260 * Registers the given connect point with the NRS, this is necessary
1261 * to receive the NDP and ARP packets from the NRS.
1262 *
1263 * @param portToRegister connect point to register
1264 */
1265 public void registerConnectPoint(ConnectPoint portToRegister) {
Charles Chan2e71ef32017-02-23 15:44:08 -08001266 neighbourResolutionService.registerNeighbourHandler(
Pier Ventreb6a7f342016-11-26 21:05:22 -08001267 portToRegister,
1268 neighbourHandler,
1269 appId
1270 );
1271 }
1272
Charles Chan72f556a2015-10-05 17:50:33 -07001273 private class InternalConfigListener implements NetworkConfigListener {
Saurav Das261c3002017-06-13 15:35:54 -07001274 private static final long PROGRAM_DELAY = 2;
Charles Chan46fdfaf2016-11-09 20:51:44 -08001275 SegmentRoutingManager srManager;
Charles Chane7c61022015-10-07 14:21:45 -07001276
Charles Chanb7f75ac2016-01-11 18:28:54 -08001277 /**
1278 * Constructs the internal network config listener.
1279 *
Charles Chan46fdfaf2016-11-09 20:51:44 -08001280 * @param srManager segment routing manager
Charles Chanb7f75ac2016-01-11 18:28:54 -08001281 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001282 InternalConfigListener(SegmentRoutingManager srManager) {
Charles Chan46fdfaf2016-11-09 20:51:44 -08001283 this.srManager = srManager;
Charles Chane7c61022015-10-07 14:21:45 -07001284 }
1285
Charles Chanb7f75ac2016-01-11 18:28:54 -08001286 /**
1287 * Reads network config and initializes related data structure accordingly.
1288 */
Charles Chan873661e2017-11-30 15:37:50 -08001289 void configureNetwork() {
Charles Chan8ca5a122017-10-20 16:06:55 -07001290 createOrUpdateDeviceConfiguration();
Charles Chane7c61022015-10-07 14:21:45 -07001291
Charles Chan46fdfaf2016-11-09 20:51:44 -08001292 arpHandler = new ArpHandler(srManager);
1293 icmpHandler = new IcmpHandler(srManager);
1294 ipHandler = new IpHandler(srManager);
1295 routingRulePopulator = new RoutingRulePopulator(srManager);
1296 defaultRoutingHandler = new DefaultRoutingHandler(srManager);
Charles Chane7c61022015-10-07 14:21:45 -07001297
1298 tunnelHandler = new TunnelHandler(linkService, deviceConfiguration,
1299 groupHandlerMap, tunnelStore);
1300 policyHandler = new PolicyHandler(appId, deviceConfiguration,
1301 flowObjectiveService,
1302 tunnelHandler, policyStore);
Saurav Das261c3002017-06-13 15:35:54 -07001303 // add a small delay to absorb multiple network config added notifications
1304 if (!programmingScheduled.get()) {
1305 programmingScheduled.set(true);
1306 executorService.schedule(new ConfigChange(), PROGRAM_DELAY,
1307 TimeUnit.SECONDS);
Charles Chane7c61022015-10-07 14:21:45 -07001308 }
Charles Chan72779502016-04-23 17:36:10 -07001309 mcastHandler.init();
Charles Chane7c61022015-10-07 14:21:45 -07001310 }
1311
Charles Chan72f556a2015-10-05 17:50:33 -07001312 @Override
1313 public void event(NetworkConfigEvent event) {
Charles Chan82ab1932016-01-30 23:22:37 -08001314 // TODO move this part to NetworkConfigEventHandler
1315 if (event.configClass().equals(SegmentRoutingDeviceConfig.class)) {
1316 switch (event.type()) {
1317 case CONFIG_ADDED:
Charles Chan68363b12017-06-26 15:25:09 -07001318 log.info("Segment Routing Device Config added for {}", event.subject());
Charles Chan82ab1932016-01-30 23:22:37 -08001319 configureNetwork();
1320 break;
1321 case CONFIG_UPDATED:
Charles Chan68363b12017-06-26 15:25:09 -07001322 log.info("Segment Routing Config updated for {}", event.subject());
Charles Chan8ca5a122017-10-20 16:06:55 -07001323 createOrUpdateDeviceConfiguration();
Charles Chan68363b12017-06-26 15:25:09 -07001324 // TODO support dynamic configuration
1325 break;
1326 default:
1327 break;
1328 }
1329 } else if (event.configClass().equals(InterfaceConfig.class)) {
1330 switch (event.type()) {
1331 case CONFIG_ADDED:
1332 log.info("Interface Config added for {}", event.subject());
1333 configureNetwork();
1334 break;
1335 case CONFIG_UPDATED:
1336 log.info("Interface Config updated for {}", event.subject());
Charles Chan8ca5a122017-10-20 16:06:55 -07001337 createOrUpdateDeviceConfiguration();
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001338
1339 // Following code will be uncommented when [CORD-634] is fully implemented.
1340 // [CORD-634] Add dynamic config support for interfaces
1341 updateInterface((InterfaceConfig) event.config().get(),
1342 (InterfaceConfig) event.prevConfig().get());
Charles Chan82ab1932016-01-30 23:22:37 -08001343 // TODO support dynamic configuration
1344 break;
1345 default:
1346 break;
Charles Chan2b078ae2015-10-14 11:24:40 -07001347 }
Charles Chan82ab1932016-01-30 23:22:37 -08001348 } else if (event.configClass().equals(SegmentRoutingAppConfig.class)) {
Charles Chan82f19972016-05-17 13:13:55 -07001349 checkState(appCfgHandler != null, "NetworkConfigEventHandler is not initialized");
Charles Chan82ab1932016-01-30 23:22:37 -08001350 switch (event.type()) {
1351 case CONFIG_ADDED:
Charles Chan82f19972016-05-17 13:13:55 -07001352 appCfgHandler.processAppConfigAdded(event);
Charles Chan82ab1932016-01-30 23:22:37 -08001353 break;
1354 case CONFIG_UPDATED:
Charles Chan82f19972016-05-17 13:13:55 -07001355 appCfgHandler.processAppConfigUpdated(event);
Charles Chan82ab1932016-01-30 23:22:37 -08001356 break;
1357 case CONFIG_REMOVED:
Charles Chan82f19972016-05-17 13:13:55 -07001358 appCfgHandler.processAppConfigRemoved(event);
1359 break;
1360 default:
1361 break;
1362 }
Charles Chandebfea32016-10-24 14:52:01 -07001363 configureNetwork();
Charles Chan82f19972016-05-17 13:13:55 -07001364 } else if (event.configClass().equals(XConnectConfig.class)) {
1365 checkState(xConnectHandler != null, "XConnectHandler is not initialized");
1366 switch (event.type()) {
1367 case CONFIG_ADDED:
1368 xConnectHandler.processXConnectConfigAdded(event);
1369 break;
1370 case CONFIG_UPDATED:
1371 xConnectHandler.processXConnectConfigUpdated(event);
1372 break;
1373 case CONFIG_REMOVED:
1374 xConnectHandler.processXConnectConfigRemoved(event);
Charles Chan82ab1932016-01-30 23:22:37 -08001375 break;
1376 default:
1377 break;
Charles Chan2b078ae2015-10-14 11:24:40 -07001378 }
Pier Ventre6b19e482016-11-07 16:21:04 -08001379 } else if (event.configClass().equals(PwaasConfig.class)) {
1380 checkState(l2TunnelHandler != null, "L2TunnelHandler is not initialized");
1381 switch (event.type()) {
1382 case CONFIG_ADDED:
1383 l2TunnelHandler.processPwaasConfigAdded(event);
1384 break;
1385 case CONFIG_UPDATED:
1386 l2TunnelHandler.processPwaasConfigUpdated(event);
1387 break;
1388 case CONFIG_REMOVED:
1389 l2TunnelHandler.processPwaasConfigRemoved(event);
1390 break;
1391 default:
1392 break;
1393 }
Charles Chan72f556a2015-10-05 17:50:33 -07001394 }
1395 }
Saurav Das261c3002017-06-13 15:35:54 -07001396
Charles Chanc4a68c32018-01-03 16:26:32 -08001397 @Override
1398 public boolean isRelevant(NetworkConfigEvent event) {
1399 if (event.configClass().equals(SegmentRoutingDeviceConfig.class) ||
1400 event.configClass().equals(SegmentRoutingAppConfig.class) ||
1401 event.configClass().equals(InterfaceConfig.class) ||
1402 event.configClass().equals(XConnectConfig.class) ||
1403 event.configClass().equals(PwaasConfig.class)) {
1404 return true;
1405 }
1406 log.debug("Ignore irrelevant event class {}", event.configClass().getName());
1407 return false;
1408 }
1409
Saurav Das261c3002017-06-13 15:35:54 -07001410 private final class ConfigChange implements Runnable {
1411 @Override
1412 public void run() {
1413 programmingScheduled.set(false);
1414 for (Device device : deviceService.getDevices()) {
1415 processDeviceAdded(device);
1416 }
1417 defaultRoutingHandler.startPopulationProcess();
1418 }
1419 }
Charles Chan72f556a2015-10-05 17:50:33 -07001420 }
Charles Chanf4586112015-11-09 16:37:23 -08001421
1422 private class InternalHostListener implements HostListener {
Charles Chanf4586112015-11-09 16:37:23 -08001423 @Override
1424 public void event(HostEvent event) {
Charles Chanf4586112015-11-09 16:37:23 -08001425 switch (event.type()) {
1426 case HOST_ADDED:
Charles Chan1eaf4802016-04-18 13:44:03 -07001427 hostHandler.processHostAddedEvent(event);
Charles Chanf4586112015-11-09 16:37:23 -08001428 break;
1429 case HOST_MOVED:
Charles Chan1eaf4802016-04-18 13:44:03 -07001430 hostHandler.processHostMovedEvent(event);
Charles Chan910be6a2017-08-23 14:46:43 -07001431 routeHandler.processHostMovedEvent(event);
Charles Chanf4586112015-11-09 16:37:23 -08001432 break;
1433 case HOST_REMOVED:
Charles Chand9265a32017-06-16 15:19:24 -07001434 hostHandler.processHostRemovedEvent(event);
Charles Chanf4586112015-11-09 16:37:23 -08001435 break;
1436 case HOST_UPDATED:
Charles Chan1eaf4802016-04-18 13:44:03 -07001437 hostHandler.processHostUpdatedEvent(event);
Charles Chanf4586112015-11-09 16:37:23 -08001438 break;
1439 default:
1440 log.warn("Unsupported host event type: {}", event.type());
1441 break;
1442 }
1443 }
1444 }
1445
Charles Chanc91c8782016-03-30 17:54:24 -07001446 private class InternalMcastListener implements McastListener {
1447 @Override
1448 public void event(McastEvent event) {
1449 switch (event.type()) {
1450 case SOURCE_ADDED:
Charles Chan1eaf4802016-04-18 13:44:03 -07001451 mcastHandler.processSourceAdded(event);
Charles Chanc91c8782016-03-30 17:54:24 -07001452 break;
1453 case SINK_ADDED:
Charles Chan1eaf4802016-04-18 13:44:03 -07001454 mcastHandler.processSinkAdded(event);
Charles Chanc91c8782016-03-30 17:54:24 -07001455 break;
1456 case SINK_REMOVED:
Charles Chan1eaf4802016-04-18 13:44:03 -07001457 mcastHandler.processSinkRemoved(event);
Charles Chanc91c8782016-03-30 17:54:24 -07001458 break;
1459 case ROUTE_ADDED:
1460 case ROUTE_REMOVED:
1461 default:
1462 break;
1463 }
1464 }
1465 }
Charles Chan41f5ec02016-06-13 18:54:31 -07001466
Charles Chandebfea32016-10-24 14:52:01 -07001467 private class InternalRouteEventListener implements RouteListener {
1468 @Override
1469 public void event(RouteEvent event) {
1470 switch (event.type()) {
1471 case ROUTE_ADDED:
1472 routeHandler.processRouteAdded(event);
1473 break;
1474 case ROUTE_UPDATED:
1475 routeHandler.processRouteUpdated(event);
1476 break;
1477 case ROUTE_REMOVED:
1478 routeHandler.processRouteRemoved(event);
1479 break;
Charles Chan910be6a2017-08-23 14:46:43 -07001480 case ALTERNATIVE_ROUTES_CHANGED:
1481 routeHandler.processAlternativeRoutesChanged(event);
1482 break;
Charles Chandebfea32016-10-24 14:52:01 -07001483 default:
1484 break;
1485 }
1486 }
1487 }
Saurav Das62ae6792017-05-15 15:34:25 -07001488
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001489 private void updateInterface(InterfaceConfig conf, InterfaceConfig prevConf) {
1490 try {
1491 Set<Interface> intfs = conf.getInterfaces();
1492 Set<Interface> prevIntfs = prevConf.getInterfaces();
1493
1494 // Now we only handle one interface config at each port.
1495 if (intfs.size() != 1 || prevIntfs.size() != 1) {
1496 log.warn("Interface update aborted - one at a time is allowed, " +
1497 "but {} / {}(prev) received.", intfs.size(), prevIntfs.size());
1498 return;
1499 }
1500
1501 Interface intf = intfs.stream().findFirst().get();
1502 Interface prevIntf = prevIntfs.stream().findFirst().get();
1503
1504 DeviceId deviceId = intf.connectPoint().deviceId();
1505 PortNumber portNum = intf.connectPoint().port();
1506
1507 if (!mastershipService.isLocalMaster(deviceId)) {
1508 log.debug("CONFIG_UPDATED event for interfaces should be " +
1509 "handled by master node for device {}", deviceId);
1510 return;
1511 }
1512
1513 removeSubnetConfig(prevIntf.connectPoint(),
1514 Sets.difference(new HashSet<>(prevIntf.ipAddressesList()),
1515 new HashSet<>(intf.ipAddressesList())));
1516
1517 if (prevIntf.vlanNative() != VlanId.NONE && !intf.vlanNative().equals(prevIntf.vlanNative())) {
1518 // RemoveVlanNative
1519 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanNative(), true, false);
1520 }
1521
1522 if (!prevIntf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
1523 // RemoveVlanTagged
1524 prevIntf.vlanTagged().stream().filter(i -> !intf.vlanTagged().contains(i)).forEach(
1525 vlanId -> updateVlanConfigInternal(deviceId, portNum, vlanId, false, false)
1526 );
1527 }
1528
1529 if (prevIntf.vlanUntagged() != VlanId.NONE && !intf.vlanUntagged().equals(prevIntf.vlanUntagged())) {
1530 // RemoveVlanUntagged
1531 updateVlanConfigInternal(deviceId, portNum, prevIntf.vlanUntagged(), true, false);
1532 }
1533
1534 if (intf.vlanNative() != VlanId.NONE && !prevIntf.vlanNative().equals(intf.vlanNative())) {
1535 // AddVlanNative
1536 updateVlanConfigInternal(deviceId, portNum, intf.vlanNative(), true, true);
1537 }
1538
1539 if (!intf.vlanTagged().isEmpty() && !intf.vlanTagged().equals(prevIntf.vlanTagged())) {
1540 // AddVlanTagged
1541 intf.vlanTagged().stream().filter(i -> !prevIntf.vlanTagged().contains(i)).forEach(
1542 vlanId -> updateVlanConfigInternal(deviceId, portNum, vlanId, false, true)
1543 );
1544 }
1545
1546 if (intf.vlanUntagged() != VlanId.NONE && !prevIntf.vlanUntagged().equals(intf.vlanUntagged())) {
1547 // AddVlanUntagged
1548 updateVlanConfigInternal(deviceId, portNum, intf.vlanUntagged(), true, true);
1549 }
1550 addSubnetConfig(prevIntf.connectPoint(),
1551 Sets.difference(new HashSet<>(intf.ipAddressesList()),
1552 new HashSet<>(prevIntf.ipAddressesList())));
1553 } catch (ConfigException e) {
1554 log.error("Error in configuration");
1555 }
1556 }
1557
1558 private void updateVlanConfigInternal(DeviceId deviceId, PortNumber portNum,
1559 VlanId vlanId, boolean pushVlan, boolean install) {
1560 DefaultGroupHandler grpHandler = getGroupHandler(deviceId);
1561 if (grpHandler == null) {
1562 log.warn("Failed to retrieve group handler for device {}", deviceId);
1563 return;
1564 }
1565
1566 // Update filtering objective for a single port
1567 routingRulePopulator.updateSinglePortFilters(deviceId, portNum, pushVlan, vlanId, install);
1568
1569 // Update filtering objective for multicast ingress port
1570 mcastHandler.updateFilterToDevice(deviceId, portNum, vlanId, install);
1571
1572 int nextId = getVlanNextObjectiveId(deviceId, vlanId);
1573
1574 if (nextId != -1 && !install) {
1575 // Update next objective for a single port as an output port
1576 // Remove a single port from L2FG
1577 grpHandler.updateGroupFromVlanConfiguration(portNum, Collections.singleton(vlanId), nextId, install);
1578 // Remove L2 Bridging rule and L3 Unicast rule to the host
1579 hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum, vlanId, pushVlan, install);
1580 // Remove broadcast forwarding rule and corresponding L2FG for VLAN
1581 // only if there is no port configured on that VLAN ID
1582 if (!getVlanPortMap(deviceId).containsKey(vlanId)) {
1583 // Remove broadcast forwarding rule for the VLAN
1584 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
1585 // Remove L2FG for VLAN
1586 grpHandler.removeBcastGroupFromVlan(deviceId, portNum, vlanId, pushVlan);
1587 } else {
1588 // Remove L2IG of the port
1589 grpHandler.removePortNextObjective(deviceId, portNum, vlanId, pushVlan);
1590 }
1591 } else if (install) {
1592 if (nextId != -1) {
1593 // Add a single port to L2FG
1594 grpHandler.updateGroupFromVlanConfiguration(portNum, Collections.singleton(vlanId), nextId, install);
1595 } else {
1596 // Create L2FG for VLAN
1597 grpHandler.createBcastGroupFromVlan(vlanId, Collections.singleton(portNum));
1598 routingRulePopulator.updateSubnetBroadcastRule(deviceId, vlanId, install);
1599 }
1600 hostHandler.processIntfVlanUpdatedEvent(deviceId, portNum, vlanId, pushVlan, install);
1601 } else {
1602 log.warn("Failed to retrieve next objective for vlan {} in device {}:{}", vlanId, deviceId, portNum);
1603 }
1604 }
1605
1606 private void removeSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
1607 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
1608 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
1609
1610 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
1611 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
1612 .filter(intf -> !intf.connectPoint().equals(cp))
1613 .flatMap(intf -> intf.ipAddressesList().stream())
1614 .collect(Collectors.toSet());
1615 // 1. Partial subnet population
1616 // Remove routing rules for removed subnet from previous configuration,
1617 // which does not also exist in other interfaces in the same device
1618 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
1619 .map(InterfaceIpAddress::subnetAddress)
1620 .collect(Collectors.toSet());
1621
1622 defaultRoutingHandler.revokeSubnet(
1623 ipPrefixSet.stream()
1624 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
1625 .collect(Collectors.toSet()));
1626
1627 // 2. Interface IP punts
1628 // Remove IP punts for old Intf address
1629 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
1630 .map(InterfaceIpAddress::ipAddress)
1631 .collect(Collectors.toSet());
1632 ipAddressSet.stream()
1633 .map(InterfaceIpAddress::ipAddress)
1634 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
1635 .forEach(interfaceIpAddress ->
1636 routingRulePopulator.revokeSingleIpPunts(
1637 cp.deviceId(), interfaceIpAddress));
1638
1639 // 3. Host unicast routing rule
1640 // Remove unicast routing rule
1641 hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, false);
1642 }
1643
1644 private void addSubnetConfig(ConnectPoint cp, Set<InterfaceIpAddress> ipAddressSet) {
1645 Set<IpPrefix> ipPrefixSet = ipAddressSet.stream().
1646 map(InterfaceIpAddress::subnetAddress).collect(Collectors.toSet());
1647
1648 Set<InterfaceIpAddress> deviceIntfIpAddrs = interfaceService.getInterfaces().stream()
1649 .filter(intf -> intf.connectPoint().deviceId().equals(cp.deviceId()))
1650 .filter(intf -> !intf.connectPoint().equals(cp))
1651 .flatMap(intf -> intf.ipAddressesList().stream())
1652 .collect(Collectors.toSet());
1653 // 1. Partial subnet population
1654 // Add routing rules for newly added subnet, which does not also exist in
1655 // other interfaces in the same device
1656 Set<IpPrefix> deviceIpPrefixSet = deviceIntfIpAddrs.stream()
1657 .map(InterfaceIpAddress::subnetAddress)
1658 .collect(Collectors.toSet());
1659
1660 defaultRoutingHandler.populateSubnet(
1661 Collections.singleton(cp),
1662 ipPrefixSet.stream()
1663 .filter(ipPrefix -> !deviceIpPrefixSet.contains(ipPrefix))
1664 .collect(Collectors.toSet()));
1665
1666 // 2. Interface IP punts
1667 // Add IP punts for new Intf address
1668 Set<IpAddress> deviceIpAddrs = deviceIntfIpAddrs.stream()
1669 .map(InterfaceIpAddress::ipAddress)
1670 .collect(Collectors.toSet());
1671 ipAddressSet.stream()
1672 .map(InterfaceIpAddress::ipAddress)
1673 .filter(interfaceIpAddress -> !deviceIpAddrs.contains(interfaceIpAddress))
1674 .forEach(interfaceIpAddress ->
1675 routingRulePopulator.populateSingleIpPunts(
1676 cp.deviceId(), interfaceIpAddress));
1677
1678 // 3. Host unicast routing rule
1679 // Add unicast routing rule
1680 hostHandler.processIntfIpUpdatedEvent(cp, ipPrefixSet, true);
1681 }
sangho80f11cb2015-04-01 13:05:26 -07001682}