blob: 252dcf0b4d3c1ce1f40daab8de0bb2ea60a746c8 [file] [log] [blame]
lishuai6c56f5e2015-11-17 16:38:19 +08001/*
2 * Copyright 2015 Open Networking Laboratory
3 *
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.vtn.manager.impl;
17
jiangruic69a7fd2015-11-19 15:40:01 +080018import static org.onosproject.net.flow.instructions.ExtensionTreatmentType.ExtensionTreatmentTypes.NICIRA_SET_TUNNEL_DST;
lishuai6c56f5e2015-11-17 16:38:19 +080019import static org.slf4j.LoggerFactory.getLogger;
20
lishuai858efd32015-12-04 14:30:36 +080021import java.util.ArrayList;
lishuaib43dbf72016-01-06 11:11:35 +080022import java.util.Arrays;
lishuai6c56f5e2015-11-17 16:38:19 +080023import java.util.Collection;
24import java.util.HashMap;
25import java.util.HashSet;
26import java.util.Iterator;
jiangruic69a7fd2015-11-19 15:40:01 +080027import java.util.List;
lishuai6c56f5e2015-11-17 16:38:19 +080028import java.util.Map;
29import java.util.Set;
lishuai74f2d532015-12-10 17:03:34 +080030import java.util.concurrent.ConcurrentHashMap;
lishuai858efd32015-12-04 14:30:36 +080031import java.util.stream.Collectors;
lishuai6c56f5e2015-11-17 16:38:19 +080032
33import org.apache.felix.scr.annotations.Activate;
34import org.apache.felix.scr.annotations.Component;
35import org.apache.felix.scr.annotations.Deactivate;
36import org.apache.felix.scr.annotations.Reference;
37import org.apache.felix.scr.annotations.ReferenceCardinality;
38import org.apache.felix.scr.annotations.Service;
jiangruic69a7fd2015-11-19 15:40:01 +080039import org.onlab.packet.Ip4Address;
lishuai6c56f5e2015-11-17 16:38:19 +080040import org.onlab.packet.IpAddress;
41import org.onlab.packet.MacAddress;
42import org.onlab.util.KryoNamespace;
43import org.onosproject.core.ApplicationId;
44import org.onosproject.core.CoreService;
45import org.onosproject.mastership.MastershipService;
lishuai858efd32015-12-04 14:30:36 +080046import org.onosproject.net.AnnotationKeys;
lishuai6c56f5e2015-11-17 16:38:19 +080047import org.onosproject.net.Device;
48import org.onosproject.net.DeviceId;
49import org.onosproject.net.Host;
lishuai858efd32015-12-04 14:30:36 +080050import org.onosproject.net.HostId;
lishuai6c56f5e2015-11-17 16:38:19 +080051import org.onosproject.net.Port;
52import org.onosproject.net.PortNumber;
53import org.onosproject.net.behaviour.BridgeConfig;
54import org.onosproject.net.behaviour.BridgeDescription;
jiangruic69a7fd2015-11-19 15:40:01 +080055import org.onosproject.net.behaviour.ExtensionTreatmentResolver;
lishuai6c56f5e2015-11-17 16:38:19 +080056import org.onosproject.net.config.NetworkConfigService;
57import org.onosproject.net.config.basics.BasicDeviceConfig;
58import org.onosproject.net.device.DeviceEvent;
59import org.onosproject.net.device.DeviceListener;
60import org.onosproject.net.device.DeviceService;
61import org.onosproject.net.driver.DriverHandler;
62import org.onosproject.net.driver.DriverService;
jiangruic69a7fd2015-11-19 15:40:01 +080063import org.onosproject.net.flow.DefaultTrafficTreatment;
64import org.onosproject.net.flow.TrafficTreatment.Builder;
65import org.onosproject.net.flow.instructions.ExtensionTreatment;
lishuai6c56f5e2015-11-17 16:38:19 +080066import org.onosproject.net.flowobjective.Objective;
jiangruic69a7fd2015-11-19 15:40:01 +080067import org.onosproject.net.group.DefaultGroupBucket;
68import org.onosproject.net.group.DefaultGroupDescription;
69import org.onosproject.net.group.DefaultGroupKey;
70import org.onosproject.net.group.GroupBucket;
71import org.onosproject.net.group.GroupBuckets;
72import org.onosproject.net.group.GroupDescription;
73import org.onosproject.net.group.GroupKey;
74import org.onosproject.net.group.GroupService;
lishuai6c56f5e2015-11-17 16:38:19 +080075import org.onosproject.net.host.HostEvent;
76import org.onosproject.net.host.HostListener;
77import org.onosproject.net.host.HostService;
78import org.onosproject.store.serializers.KryoNamespaces;
lishuaib43dbf72016-01-06 11:11:35 +080079import org.onosproject.store.service.ConsistentMap;
lishuai6c56f5e2015-11-17 16:38:19 +080080import org.onosproject.store.service.EventuallyConsistentMap;
81import org.onosproject.store.service.LogicalClockService;
lishuaib43dbf72016-01-06 11:11:35 +080082import org.onosproject.store.service.Serializer;
lishuai6c56f5e2015-11-17 16:38:19 +080083import org.onosproject.store.service.StorageService;
lishuaib43dbf72016-01-06 11:11:35 +080084import org.onosproject.store.service.Versioned;
lishuai6c56f5e2015-11-17 16:38:19 +080085import org.onosproject.vtn.manager.VTNService;
lishuai858efd32015-12-04 14:30:36 +080086import org.onosproject.vtn.table.ArpService;
lishuai6c56f5e2015-11-17 16:38:19 +080087import org.onosproject.vtn.table.ClassifierService;
lishuai858efd32015-12-04 14:30:36 +080088import org.onosproject.vtn.table.DnatService;
lishuai6c56f5e2015-11-17 16:38:19 +080089import org.onosproject.vtn.table.L2ForwardService;
lishuai858efd32015-12-04 14:30:36 +080090import org.onosproject.vtn.table.L3ForwardService;
91import org.onosproject.vtn.table.SnatService;
lishuai74f2d532015-12-10 17:03:34 +080092import org.onosproject.vtn.table.impl.ArpServiceImpl;
lishuai6c56f5e2015-11-17 16:38:19 +080093import org.onosproject.vtn.table.impl.ClassifierServiceImpl;
lishuai74f2d532015-12-10 17:03:34 +080094import org.onosproject.vtn.table.impl.DnatServiceImpl;
lishuai6c56f5e2015-11-17 16:38:19 +080095import org.onosproject.vtn.table.impl.L2ForwardServiceImpl;
lishuai74f2d532015-12-10 17:03:34 +080096import org.onosproject.vtn.table.impl.L3ForwardServiceImpl;
97import org.onosproject.vtn.table.impl.SnatServiceImpl;
lishuai6c56f5e2015-11-17 16:38:19 +080098import org.onosproject.vtn.util.DataPathIdGenerator;
99import org.onosproject.vtn.util.VtnConfig;
100import org.onosproject.vtn.util.VtnData;
lishuai7dc63d92015-11-27 17:15:25 +0800101import org.onosproject.vtnrsc.AllowedAddressPair;
102import org.onosproject.vtnrsc.BindingHostId;
103import org.onosproject.vtnrsc.DefaultVirtualPort;
104import org.onosproject.vtnrsc.FixedIp;
lishuai858efd32015-12-04 14:30:36 +0800105import org.onosproject.vtnrsc.FloatingIp;
lishuai858efd32015-12-04 14:30:36 +0800106import org.onosproject.vtnrsc.RouterInterface;
lishuai7dc63d92015-11-27 17:15:25 +0800107import org.onosproject.vtnrsc.SecurityGroup;
lishuai6c56f5e2015-11-17 16:38:19 +0800108import org.onosproject.vtnrsc.SegmentationId;
109import org.onosproject.vtnrsc.SubnetId;
110import org.onosproject.vtnrsc.TenantId;
111import org.onosproject.vtnrsc.TenantNetwork;
112import org.onosproject.vtnrsc.TenantNetworkId;
113import org.onosproject.vtnrsc.VirtualPort;
114import org.onosproject.vtnrsc.VirtualPortId;
lishuai858efd32015-12-04 14:30:36 +0800115import org.onosproject.vtnrsc.event.VtnRscEvent;
116import org.onosproject.vtnrsc.event.VtnRscEventFeedback;
117import org.onosproject.vtnrsc.event.VtnRscListener;
118import org.onosproject.vtnrsc.floatingip.FloatingIpService;
lishuai858efd32015-12-04 14:30:36 +0800119import org.onosproject.vtnrsc.routerinterface.RouterInterfaceService;
120import org.onosproject.vtnrsc.service.VtnRscService;
121import org.onosproject.vtnrsc.subnet.SubnetService;
lishuai6c56f5e2015-11-17 16:38:19 +0800122import org.onosproject.vtnrsc.tenantnetwork.TenantNetworkService;
123import org.onosproject.vtnrsc.virtualport.VirtualPortService;
124import org.slf4j.Logger;
125
jiangruic69a7fd2015-11-19 15:40:01 +0800126import com.google.common.collect.Lists;
lishuai6c56f5e2015-11-17 16:38:19 +0800127import com.google.common.collect.Sets;
128
129/**
130 * Provides implementation of VTNService.
131 */
132@Component(immediate = true)
133@Service
134public class VTNManager implements VTNService {
135 private final Logger log = getLogger(getClass());
136 private static final String APP_ID = "org.onosproject.app.vtn";
137
138 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
139 protected NetworkConfigService configService;
140
141 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
142 protected DeviceService deviceService;
143
144 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
145 protected HostService hostService;
146
147 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
148 protected CoreService coreService;
149
150 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
151 protected StorageService storageService;
152
153 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
154 protected TenantNetworkService tenantNetworkService;
155
156 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
157 protected VirtualPortService virtualPortService;
158
159 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
160 protected DriverService driverService;
161
162 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
163 protected LogicalClockService clockService;
164
165 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
166 protected MastershipService mastershipService;
167
jiangruic69a7fd2015-11-19 15:40:01 +0800168 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
169 protected GroupService groupService;
170
lishuai858efd32015-12-04 14:30:36 +0800171 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
172 protected SubnetService subnetService;
173
174 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
175 protected VtnRscService vtnRscService;
176
177 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
178 protected FloatingIpService floatingIpService;
179
180 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
lishuai858efd32015-12-04 14:30:36 +0800181 protected RouterInterfaceService routerInterfaceService;
182
lishuai6c56f5e2015-11-17 16:38:19 +0800183 private ApplicationId appId;
184 private ClassifierService classifierService;
185 private L2ForwardService l2ForwardService;
lishuai858efd32015-12-04 14:30:36 +0800186 private ArpService arpService;
187 private L3ForwardService l3ForwardService;
188 private SnatService snatService;
189 private DnatService dnatService;
lishuai6c56f5e2015-11-17 16:38:19 +0800190
191 private final HostListener hostListener = new InnerHostListener();
192 private final DeviceListener deviceListener = new InnerDeviceListener();
lishuai858efd32015-12-04 14:30:36 +0800193 private final VtnRscListener l3EventListener = new VtnL3EventListener();
lishuai6c56f5e2015-11-17 16:38:19 +0800194
lishuaib43dbf72016-01-06 11:11:35 +0800195 private static final String EX_PORT_KEY = "exPortKey";
lishuai6c56f5e2015-11-17 16:38:19 +0800196 private static final String IFACEID = "ifaceid";
197 private static final String CONTROLLER_IP_KEY = "ipaddress";
198 public static final String DRIVER_NAME = "onosfw";
lishuai7dc63d92015-11-27 17:15:25 +0800199 private static final String VIRTUALPORT = "vtn-virtual-port";
lishuai6c56f5e2015-11-17 16:38:19 +0800200 private static final String SWITCHES_OF_CONTROLLER = "switchesOfController";
201 private static final String SWITCH_OF_LOCAL_HOST_PORTS = "switchOfLocalHostPorts";
lishuai858efd32015-12-04 14:30:36 +0800202 private static final String ROUTERINF_FLAG_OF_TENANT = "routerInfFlagOfTenant";
203 private static final String HOSTS_OF_SUBNET = "hostsOfSubnet";
204 private static final String EX_PORT_OF_DEVICE = "exPortOfDevice";
lishuaib43dbf72016-01-06 11:11:35 +0800205 private static final String EX_PORT_MAP = "exPortMap";
jiangruic69a7fd2015-11-19 15:40:01 +0800206 private static final String DEFAULT_IP = "0.0.0.0";
lishuai858efd32015-12-04 14:30:36 +0800207 private static final int SUBNET_NUM = 2;
lishuai6c56f5e2015-11-17 16:38:19 +0800208
lishuai7dc63d92015-11-27 17:15:25 +0800209 private EventuallyConsistentMap<VirtualPortId, VirtualPort> vPortStore;
lishuai6c56f5e2015-11-17 16:38:19 +0800210 private EventuallyConsistentMap<IpAddress, Boolean> switchesOfController;
jiangruic69a7fd2015-11-19 15:40:01 +0800211 private EventuallyConsistentMap<DeviceId, NetworkOfLocalHostPorts> switchOfLocalHostPorts;
lishuai858efd32015-12-04 14:30:36 +0800212 private EventuallyConsistentMap<SubnetId, Map<HostId, Host>> hostsOfSubnet;
213 private EventuallyConsistentMap<TenantId, Boolean> routerInfFlagOfTenant;
214 private EventuallyConsistentMap<DeviceId, Port> exPortOfDevice;
lishuaib43dbf72016-01-06 11:11:35 +0800215 private static ConsistentMap<String, String> exPortMap;
lishuai6c56f5e2015-11-17 16:38:19 +0800216
217 @Activate
218 public void activate() {
219 appId = coreService.registerApplication(APP_ID);
220 classifierService = new ClassifierServiceImpl(appId);
221 l2ForwardService = new L2ForwardServiceImpl(appId);
lishuai74f2d532015-12-10 17:03:34 +0800222 arpService = new ArpServiceImpl(appId);
223 l3ForwardService = new L3ForwardServiceImpl(appId);
224 snatService = new SnatServiceImpl(appId);
225 dnatService = new DnatServiceImpl(appId);
lishuai6c56f5e2015-11-17 16:38:19 +0800226
227 deviceService.addListener(deviceListener);
228 hostService.addListener(hostListener);
lishuai74f2d532015-12-10 17:03:34 +0800229 vtnRscService.addListener(l3EventListener);
lishuai6c56f5e2015-11-17 16:38:19 +0800230
231 KryoNamespace.Builder serializer = KryoNamespace.newBuilder()
232 .register(KryoNamespaces.API)
233 .register(NetworkOfLocalHostPorts.class)
234 .register(TenantNetworkId.class)
235 .register(Host.class)
236 .register(TenantNetwork.class)
237 .register(TenantId.class)
lishuai7dc63d92015-11-27 17:15:25 +0800238 .register(SubnetId.class)
239 .register(VirtualPortId.class)
240 .register(VirtualPort.State.class)
241 .register(AllowedAddressPair.class)
242 .register(FixedIp.class)
243 .register(BindingHostId.class)
244 .register(SecurityGroup.class)
245 .register(IpAddress.class)
246 .register(DefaultVirtualPort.class);
247
248 vPortStore = storageService
249 .<VirtualPortId, VirtualPort>eventuallyConsistentMapBuilder()
250 .withName(VIRTUALPORT).withSerializer(serializer)
251 .withTimestampProvider((k, v) -> clockService.getTimestamp())
252 .build();
lishuai6c56f5e2015-11-17 16:38:19 +0800253
254 switchesOfController = storageService
255 .<IpAddress, Boolean>eventuallyConsistentMapBuilder()
256 .withName(SWITCHES_OF_CONTROLLER).withSerializer(serializer)
257 .withTimestampProvider((k, v) -> clockService.getTimestamp())
258 .build();
259
260 switchOfLocalHostPorts = storageService
jiangruic69a7fd2015-11-19 15:40:01 +0800261 .<DeviceId, NetworkOfLocalHostPorts>eventuallyConsistentMapBuilder()
262 .withName(SWITCH_OF_LOCAL_HOST_PORTS).withSerializer(serializer)
263 .withTimestampProvider((k, v) -> clockService.getTimestamp())
lishuai6c56f5e2015-11-17 16:38:19 +0800264 .build();
265
lishuai858efd32015-12-04 14:30:36 +0800266 hostsOfSubnet = storageService
267 .<SubnetId, Map<HostId, Host>>eventuallyConsistentMapBuilder()
268 .withName(HOSTS_OF_SUBNET).withSerializer(serializer)
269 .withTimestampProvider((k, v) -> clockService.getTimestamp())
270 .build();
271
272 routerInfFlagOfTenant = storageService
273 .<TenantId, Boolean>eventuallyConsistentMapBuilder()
274 .withName(ROUTERINF_FLAG_OF_TENANT).withSerializer(serializer)
275 .withTimestampProvider((k, v) -> clockService.getTimestamp())
276 .build();
277
278 exPortOfDevice = storageService
279 .<DeviceId, Port>eventuallyConsistentMapBuilder()
280 .withName(EX_PORT_OF_DEVICE).withSerializer(serializer)
281 .withTimestampProvider((k, v) -> clockService.getTimestamp())
282 .build();
283
lishuaib43dbf72016-01-06 11:11:35 +0800284 exPortMap = storageService
285 .<String, String>consistentMapBuilder()
286 .withName(EX_PORT_MAP)
287 .withApplicationId(appId)
288 .withPurgeOnUninstall()
289 .withSerializer(Serializer.using(Arrays.asList(KryoNamespaces.API)))
290 .build();
291
lishuai6c56f5e2015-11-17 16:38:19 +0800292 log.info("Started");
293 }
294
295 @Deactivate
296 public void deactivate() {
297 deviceService.removeListener(deviceListener);
298 hostService.removeListener(hostListener);
lishuai858efd32015-12-04 14:30:36 +0800299 vtnRscService.removeListener(l3EventListener);
lishuai6c56f5e2015-11-17 16:38:19 +0800300 log.info("Stopped");
301 }
302
303 @Override
304 public void onControllerDetected(Device controllerDevice) {
305 if (controllerDevice == null) {
306 log.error("The controller device is null");
307 return;
308 }
309 String localIpAddress = controllerDevice.annotations()
310 .value(CONTROLLER_IP_KEY);
311 IpAddress localIp = IpAddress.valueOf(localIpAddress);
312 DeviceId controllerDeviceId = controllerDevice.id();
313 DriverHandler handler = driverService.createHandler(controllerDeviceId);
314 if (mastershipService.isLocalMaster(controllerDeviceId)) {
315 // Get DataPathIdGenerator
316 String ipaddress = controllerDevice.annotations().value("ipaddress");
317 DataPathIdGenerator dpidGenerator = DataPathIdGenerator.builder()
318 .addIpAddress(ipaddress).build();
319 DeviceId deviceId = dpidGenerator.getDeviceId();
320 String dpid = dpidGenerator.getDpId();
321 // Inject pipeline driver name
322 BasicDeviceConfig config = configService.addConfig(deviceId,
323 BasicDeviceConfig.class);
324 config.driver(DRIVER_NAME);
325 configService.applyConfig(deviceId, BasicDeviceConfig.class, config.node());
326 // Add Bridge
lishuaib43dbf72016-01-06 11:11:35 +0800327 Versioned<String> exPortVersioned = exPortMap.get(EX_PORT_KEY);
328 if (exPortVersioned != null) {
329 VtnConfig.applyBridgeConfig(handler, dpid, exPortVersioned.value());
330 log.info("A new ovs is created in node {}", localIp.toString());
331 }
lishuai6c56f5e2015-11-17 16:38:19 +0800332 switchesOfController.put(localIp, true);
333 }
334 // Create tunnel in br-int on all controllers
335 programTunnelConfig(controllerDeviceId, localIp, handler);
336 }
337
338 @Override
339 public void onControllerVanished(Device controllerDevice) {
340 if (controllerDevice == null) {
341 log.error("The device is null");
342 return;
343 }
344 String dstIp = controllerDevice.annotations().value(CONTROLLER_IP_KEY);
345 IpAddress dstIpAddress = IpAddress.valueOf(dstIp);
346 DeviceId controllerDeviceId = controllerDevice.id();
347 if (mastershipService.isLocalMaster(controllerDeviceId)) {
348 switchesOfController.remove(dstIpAddress);
349 }
lishuai6c56f5e2015-11-17 16:38:19 +0800350 }
351
352 @Override
353 public void onOvsDetected(Device device) {
354 // Create tunnel out flow rules
355 applyTunnelOut(device, Objective.Operation.ADD);
356 }
357
358 @Override
359 public void onOvsVanished(Device device) {
360 // Remove Tunnel out flow rules
361 applyTunnelOut(device, Objective.Operation.REMOVE);
362 }
363
364 @Override
365 public void onHostDetected(Host host) {
lishuai858efd32015-12-04 14:30:36 +0800366 DeviceId deviceId = host.location().deviceId();
367 if (!mastershipService.isLocalMaster(deviceId)) {
368 return;
369 }
370 String ifaceId = host.annotations().value(IFACEID);
371 if (ifaceId == null) {
372 log.error("The ifaceId of Host is null");
373 return;
374 }
lishuaib43dbf72016-01-06 11:11:35 +0800375 programSffAndClassifierHost(host, Objective.Operation.ADD);
lishuai6c56f5e2015-11-17 16:38:19 +0800376 // apply L2 openflow rules
377 applyHostMonitoredL2Rules(host, Objective.Operation.ADD);
lishuai858efd32015-12-04 14:30:36 +0800378 // apply L3 openflow rules
379 applyHostMonitoredL3Rules(host, Objective.Operation.ADD);
lishuai6c56f5e2015-11-17 16:38:19 +0800380 }
381
382 @Override
383 public void onHostVanished(Host host) {
lishuai858efd32015-12-04 14:30:36 +0800384 DeviceId deviceId = host.location().deviceId();
385 if (!mastershipService.isLocalMaster(deviceId)) {
386 return;
387 }
388 String ifaceId = host.annotations().value(IFACEID);
389 if (ifaceId == null) {
390 log.error("The ifaceId of Host is null");
391 return;
392 }
lishuaib43dbf72016-01-06 11:11:35 +0800393 programSffAndClassifierHost(host, Objective.Operation.REMOVE);
lishuai6c56f5e2015-11-17 16:38:19 +0800394 // apply L2 openflow rules
395 applyHostMonitoredL2Rules(host, Objective.Operation.REMOVE);
lishuai858efd32015-12-04 14:30:36 +0800396 // apply L3 openflow rules
397 applyHostMonitoredL3Rules(host, Objective.Operation.REMOVE);
lishuai590d93a2015-12-11 13:05:14 +0800398 VirtualPortId virtualPortId = VirtualPortId.portId(ifaceId);
399 vPortStore.remove(virtualPortId);
lishuai6c56f5e2015-11-17 16:38:19 +0800400 }
401
402 private void programTunnelConfig(DeviceId localDeviceId, IpAddress localIp,
403 DriverHandler localHandler) {
jiangruic69a7fd2015-11-19 15:40:01 +0800404 if (mastershipService.isLocalMaster(localDeviceId)) {
405 VtnConfig.applyTunnelConfig(localHandler, localIp, IpAddress.valueOf(DEFAULT_IP));
406 log.info("Add tunnel on {}", localIp);
407 }
lishuai6c56f5e2015-11-17 16:38:19 +0800408 }
409
410 private void applyTunnelOut(Device device, Objective.Operation type) {
411 if (device == null) {
412 log.error("The device is null");
413 return;
414 }
415 if (!mastershipService.isLocalMaster(device.id())) {
416 return;
417 }
418 String controllerIp = VtnData.getControllerIpOfSwitch(device);
419 if (controllerIp == null) {
420 log.error("Can't find controller of device: {}",
421 device.id().toString());
422 return;
423 }
424 IpAddress ipAddress = IpAddress.valueOf(controllerIp);
425 if (!switchesOfController.containsKey(ipAddress)) {
426 log.error("Can't find controller of device: {}",
427 device.id().toString());
428 return;
429 }
430 if (type == Objective.Operation.ADD) {
lishuaia3e32342015-12-07 10:59:17 +0800431 // Save external port
432 Port export = getExPort(device.id());
lishuaid6f0c9e2015-12-16 11:40:01 +0800433 if (export != null) {
434 exPortOfDevice.put(device.id(), export);
435 }
lishuai6c56f5e2015-11-17 16:38:19 +0800436 switchOfLocalHostPorts.put(device.id(), new NetworkOfLocalHostPorts());
437 } else if (type == Objective.Operation.REMOVE) {
lishuaia3e32342015-12-07 10:59:17 +0800438 exPortOfDevice.remove(device.id());
lishuai6c56f5e2015-11-17 16:38:19 +0800439 switchOfLocalHostPorts.remove(device.id());
440 }
441 Iterable<Device> devices = deviceService.getAvailableDevices();
442 DeviceId localControllerId = VtnData.getControllerId(device, devices);
443 DriverHandler handler = driverService.createHandler(localControllerId);
444 Set<PortNumber> ports = VtnConfig.getPortNumbers(handler);
445 Iterable<Host> allHosts = hostService.getHosts();
jiangruic69a7fd2015-11-19 15:40:01 +0800446 String tunnelName = "vxlan-" + DEFAULT_IP;
lishuai6c56f5e2015-11-17 16:38:19 +0800447 if (allHosts != null) {
448 Sets.newHashSet(allHosts).stream().forEach(host -> {
449 MacAddress hostMac = host.mac();
450 String ifaceId = host.annotations().value(IFACEID);
451 if (ifaceId == null) {
452 log.error("The ifaceId of Host is null");
453 return;
454 }
455 VirtualPortId virtualPortId = VirtualPortId.portId(ifaceId);
456 VirtualPort virtualPort = virtualPortService
457 .getPort(virtualPortId);
458 TenantNetwork network = tenantNetworkService
459 .getNetwork(virtualPort.networkId());
460 SegmentationId segmentationId = network.segmentationId();
461 DeviceId remoteDeviceId = host.location().deviceId();
462 Device remoteDevice = deviceService.getDevice(remoteDeviceId);
463 String remoteControllerIp = VtnData
464 .getControllerIpOfSwitch(remoteDevice);
465 if (remoteControllerIp == null) {
466 log.error("Can't find remote controller of device: {}",
467 remoteDeviceId.toString());
468 return;
469 }
470 IpAddress remoteIpAddress = IpAddress
471 .valueOf(remoteControllerIp);
lishuai6c56f5e2015-11-17 16:38:19 +0800472 ports.stream()
473 .filter(p -> p.name().equalsIgnoreCase(tunnelName))
474 .forEach(p -> {
475 l2ForwardService
476 .programTunnelOut(device.id(), segmentationId, p,
jiangruic69a7fd2015-11-19 15:40:01 +0800477 hostMac, type, remoteIpAddress);
lishuai6c56f5e2015-11-17 16:38:19 +0800478 });
479 });
480 }
481 }
482
lishuaib43dbf72016-01-06 11:11:35 +0800483 private void programSffAndClassifierHost(Host host, Objective.Operation type) {
484 DeviceId deviceId = host.location().deviceId();
485 String ifaceId = host.annotations().value(IFACEID);
486 VirtualPortId virtualPortId = VirtualPortId.portId(ifaceId);
487 VirtualPort virtualPort = virtualPortService.getPort(virtualPortId);
488 if (virtualPort == null) {
489 virtualPort = VtnData.getPort(vPortStore, virtualPortId);
490 }
491 TenantId tenantId = virtualPort.tenantId();
492 if (Objective.Operation.ADD == type) {
493 vtnRscService.addDeviceIdOfOvsMap(virtualPortId, tenantId, deviceId);
494 } else if (Objective.Operation.REMOVE == type) {
495 vtnRscService.removeDeviceIdOfOvsMap(host, tenantId, deviceId);
496 }
497 }
498
lishuai6c56f5e2015-11-17 16:38:19 +0800499 private void applyHostMonitoredL2Rules(Host host, Objective.Operation type) {
500 DeviceId deviceId = host.location().deviceId();
501 if (!mastershipService.isLocalMaster(deviceId)) {
502 return;
503 }
504 String ifaceId = host.annotations().value(IFACEID);
505 if (ifaceId == null) {
506 log.error("The ifaceId of Host is null");
507 return;
508 }
509 VirtualPortId virtualPortId = VirtualPortId.portId(ifaceId);
510 VirtualPort virtualPort = virtualPortService.getPort(virtualPortId);
511 if (virtualPort == null) {
lishuai858efd32015-12-04 14:30:36 +0800512 virtualPort = VtnData.getPort(vPortStore, virtualPortId);
lishuai6c56f5e2015-11-17 16:38:19 +0800513 }
lishuai74f2d532015-12-10 17:03:34 +0800514 Iterator<FixedIp> fixip = virtualPort.fixedIps().iterator();
515 SubnetId subnetId = null;
516 if (fixip.hasNext()) {
517 subnetId = fixip.next().subnetId();
518 }
519 if (subnetId != null) {
520 Map<HostId, Host> hosts = new ConcurrentHashMap();
521 if (hostsOfSubnet.get(subnetId) != null) {
522 hosts = hostsOfSubnet.get(subnetId);
523 }
524 if (type == Objective.Operation.ADD) {
525 hosts.put(host.id(), host);
526 hostsOfSubnet.put(subnetId, hosts);
527 } else if (type == Objective.Operation.REMOVE) {
528 hosts.remove(host.id());
529 if (hosts.size() != 0) {
530 hostsOfSubnet.put(subnetId, hosts);
531 } else {
532 hostsOfSubnet.remove(subnetId);
533 }
534 }
535 }
lishuai6c56f5e2015-11-17 16:38:19 +0800536
537 Iterable<Device> devices = deviceService.getAvailableDevices();
538 PortNumber inPort = host.location().port();
539 MacAddress mac = host.mac();
540 Device device = deviceService.getDevice(deviceId);
541 String controllerIp = VtnData.getControllerIpOfSwitch(device);
542 IpAddress ipAddress = IpAddress.valueOf(controllerIp);
543 TenantNetwork network = tenantNetworkService.getNetwork(virtualPort.networkId());
544 if (network == null) {
545 log.error("Can't find network of the host");
546 return;
547 }
548 SegmentationId segmentationId = network.segmentationId();
549 // Get all the tunnel PortNumber in the current node
550 Iterable<Port> ports = deviceService.getPorts(deviceId);
551 Collection<PortNumber> localTunnelPorts = VtnData.getLocalTunnelPorts(ports);
552 // Get all the local vm's PortNumber in the current node
553 Map<TenantNetworkId, Set<PortNumber>> localHostPorts = switchOfLocalHostPorts
jiangruic69a7fd2015-11-19 15:40:01 +0800554 .get(deviceId).getNetworkOfLocalHostPorts();
lishuai6c56f5e2015-11-17 16:38:19 +0800555 Set<PortNumber> networkOflocalHostPorts = localHostPorts.get(network.id());
jiangruic69a7fd2015-11-19 15:40:01 +0800556 for (PortNumber p : localTunnelPorts) {
557 programGroupTable(deviceId, appId, p, devices, type);
558 }
lishuai6c56f5e2015-11-17 16:38:19 +0800559
560 if (type == Objective.Operation.ADD) {
lishuai7dc63d92015-11-27 17:15:25 +0800561 vPortStore.put(virtualPortId, virtualPort);
lishuai6c56f5e2015-11-17 16:38:19 +0800562 if (networkOflocalHostPorts == null) {
563 networkOflocalHostPorts = new HashSet<PortNumber>();
564 localHostPorts.putIfAbsent(network.id(), networkOflocalHostPorts);
565 }
566 networkOflocalHostPorts.add(inPort);
jiangruic69a7fd2015-11-19 15:40:01 +0800567 l2ForwardService.programLocalBcastRules(deviceId, segmentationId,
568 inPort, networkOflocalHostPorts,
569 localTunnelPorts,
570 type);
lishuai6c56f5e2015-11-17 16:38:19 +0800571 classifierService.programTunnelIn(deviceId, segmentationId,
572 localTunnelPorts,
573 type);
574 } else if (type == Objective.Operation.REMOVE) {
jiangruic69a7fd2015-11-19 15:40:01 +0800575 if (networkOflocalHostPorts != null) {
576 l2ForwardService.programLocalBcastRules(deviceId, segmentationId,
577 inPort, networkOflocalHostPorts,
578 localTunnelPorts,
579 type);
580 networkOflocalHostPorts.remove(inPort);
581 if (networkOflocalHostPorts.isEmpty()) {
582 classifierService.programTunnelIn(deviceId, segmentationId,
583 localTunnelPorts,
584 type);
585 switchOfLocalHostPorts.get(deviceId).getNetworkOfLocalHostPorts()
586 .remove(virtualPort.networkId());
587 }
lishuai6c56f5e2015-11-17 16:38:19 +0800588 }
589 }
590
jiangruic69a7fd2015-11-19 15:40:01 +0800591 l2ForwardService.programLocalOut(deviceId, segmentationId, inPort, mac,
592 type);
593
lishuai6c56f5e2015-11-17 16:38:19 +0800594 l2ForwardService.programTunnelBcastRules(deviceId, segmentationId,
595 networkOflocalHostPorts,
596 localTunnelPorts,
597 type);
598
599 programTunnelOuts(devices, ipAddress, segmentationId, mac,
600 type);
601
602 classifierService.programLocalIn(deviceId, segmentationId, inPort, mac,
603 appId, type);
604 }
605
606 private void programTunnelOuts(Iterable<Device> devices,
607 IpAddress ipAddress,
608 SegmentationId segmentationId,
609 MacAddress dstMac,
610 Objective.Operation type) {
jiangruic69a7fd2015-11-19 15:40:01 +0800611 String tunnelName = "vxlan-" + DEFAULT_IP;
lishuai6c56f5e2015-11-17 16:38:19 +0800612 Sets.newHashSet(devices).stream()
jiangruic69a7fd2015-11-19 15:40:01 +0800613 .filter(d -> d.type() == Device.Type.CONTROLLER)
614 .filter(d -> !("ovsdb:" + ipAddress).equals(d.id().toString()))
615 .forEach(d -> {
lishuai6c56f5e2015-11-17 16:38:19 +0800616 DriverHandler handler = driverService.createHandler(d.id());
617 BridgeConfig bridgeConfig = handler
618 .behaviour(BridgeConfig.class);
619 Collection<BridgeDescription> bridgeDescriptions = bridgeConfig
620 .getBridges();
lishuai6c56f5e2015-11-17 16:38:19 +0800621 Iterator<BridgeDescription> it = bridgeDescriptions
622 .iterator();
lishuai70304d12015-12-14 17:15:26 +0800623 while (it.hasNext()) {
lishuai6c56f5e2015-11-17 16:38:19 +0800624 BridgeDescription sw = it.next();
lishuai70304d12015-12-14 17:15:26 +0800625 if (sw.bridgeName().name().equals(VtnConfig.DEFAULT_BRIDGE_NAME)) {
626 List<Port> ports = deviceService.getPorts(sw.deviceId());
627 ports.stream()
628 .filter(p -> p.annotations().value(AnnotationKeys.PORT_NAME)
629 .equalsIgnoreCase(tunnelName))
630 .forEach(p -> {
631 l2ForwardService.programTunnelOut(sw.deviceId(),
632 segmentationId, p.number(),
633 dstMac, type, ipAddress);
634 });
635 break;
636 }
lishuai6c56f5e2015-11-17 16:38:19 +0800637 }
638 });
639 }
640
641 private class InnerDeviceListener implements DeviceListener {
642
643 @Override
644 public void event(DeviceEvent event) {
645 Device device = event.subject();
646 if (Device.Type.CONTROLLER == device.type()) {
647 if (DeviceEvent.Type.DEVICE_ADDED == event.type()) {
648 onControllerDetected(device);
649 }
650 if (DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED == event.type()) {
651 if (deviceService.isAvailable(device.id())) {
652 onControllerDetected(device);
653 } else {
654 onControllerVanished(device);
655 }
656 }
657 } else if (Device.Type.SWITCH == device.type()) {
658 if (DeviceEvent.Type.DEVICE_ADDED == event.type()) {
659 onOvsDetected(device);
660 }
661 if (DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED == event.type()) {
662 if (deviceService.isAvailable(device.id())) {
663 onOvsDetected(device);
664 } else {
665 onOvsVanished(device);
666 }
667 }
668 } else {
669 log.info("Do nothing for this device type");
670 }
671 }
672 }
673
674 private class InnerHostListener implements HostListener {
675
676 @Override
677 public void event(HostEvent event) {
678 Host host = event.subject();
679 if (HostEvent.Type.HOST_ADDED == event.type()) {
680 onHostDetected(host);
681 } else if (HostEvent.Type.HOST_REMOVED == event.type()) {
682 onHostVanished(host);
683 } else if (HostEvent.Type.HOST_UPDATED == event.type()) {
684 onHostVanished(host);
685 onHostDetected(host);
686 }
687 }
688
689 }
690
691 // Local Host Ports of Network.
692 private class NetworkOfLocalHostPorts {
693 private final Map<TenantNetworkId, Set<PortNumber>> networkOfLocalHostPorts =
694 new HashMap<TenantNetworkId, Set<PortNumber>>();
695
696 public Map<TenantNetworkId, Set<PortNumber>> getNetworkOfLocalHostPorts() {
697 return networkOfLocalHostPorts;
698 }
699 }
700
jiangruic69a7fd2015-11-19 15:40:01 +0800701 private void programGroupTable(DeviceId deviceId, ApplicationId appid,
702 PortNumber portNumber, Iterable<Device> devices, Objective.Operation type) {
703 if (type.equals(Objective.Operation.REMOVE)) {
704 return;
705 }
706
707 List<GroupBucket> buckets = Lists.newArrayList();
708 Sets.newHashSet(devices)
709 .stream()
710 .filter(d -> d.type() == Device.Type.CONTROLLER)
711 .filter(d -> !deviceId.equals(d.id()))
712 .forEach(d -> {
713 String ipAddress = d.annotations()
714 .value(CONTROLLER_IP_KEY);
715 Ip4Address dst = Ip4Address.valueOf(ipAddress);
716 Builder builder = DefaultTrafficTreatment.builder();
717
718 DriverHandler handler = driverService.createHandler(deviceId);
719 ExtensionTreatmentResolver resolver = handler.behaviour(ExtensionTreatmentResolver.class);
720 ExtensionTreatment treatment = resolver.getExtensionInstruction(NICIRA_SET_TUNNEL_DST.type());
721 try {
722 treatment.setPropertyValue("tunnelDst", dst);
723 } catch (Exception e) {
724 log.error("Failed to get extension instruction to set tunnel dst {}", deviceId);
725 }
726
727 builder.extension(treatment, deviceId);
728 builder.setOutput(portNumber);
729 GroupBucket bucket = DefaultGroupBucket
730 .createAllGroupBucket(builder.build());
731 buckets.add(bucket);
732 });
733 final GroupKey key = new DefaultGroupKey(APP_ID.getBytes());
734 GroupDescription groupDescription = new DefaultGroupDescription(deviceId,
735 GroupDescription.Type.ALL,
736 new GroupBuckets(buckets),
737 key,
738 L2ForwardServiceImpl.GROUP_ID,
739 appid);
740 groupService.addGroup(groupDescription);
741 }
lishuai858efd32015-12-04 14:30:36 +0800742
743 private class VtnL3EventListener implements VtnRscListener {
744 @Override
745 public void event(VtnRscEvent event) {
746 VtnRscEventFeedback l3Feedback = event.subject();
747 if (VtnRscEvent.Type.ROUTER_INTERFACE_PUT == event.type()) {
748 onRouterInterfaceDetected(l3Feedback);
749 } else
750 if (VtnRscEvent.Type.ROUTER_INTERFACE_DELETE == event.type()) {
751 onRouterInterfaceVanished(l3Feedback);
lishuai762df812016-01-08 11:51:15 +0800752 } else if (VtnRscEvent.Type.FLOATINGIP_BIND == event.type()) {
lishuai858efd32015-12-04 14:30:36 +0800753 onFloatingIpDetected(l3Feedback);
lishuai762df812016-01-08 11:51:15 +0800754 } else if (VtnRscEvent.Type.FLOATINGIP_UNBIND == event.type()) {
lishuai858efd32015-12-04 14:30:36 +0800755 onFloatingIpVanished(l3Feedback);
756 }
757 }
758
759 }
760
761 @Override
762 public void onRouterInterfaceDetected(VtnRscEventFeedback l3Feedback) {
763 Objective.Operation operation = Objective.Operation.ADD;
764 RouterInterface routerInf = l3Feedback.routerInterface();
lishuai762df812016-01-08 11:51:15 +0800765 VirtualPort gwPort = virtualPortService.getPort(routerInf.portId());
766 vPortStore.put(gwPort.portId(), gwPort);
lishuai858efd32015-12-04 14:30:36 +0800767 Iterable<RouterInterface> interfaces = routerInterfaceService
768 .getRouterInterfaces();
769 Set<RouterInterface> interfacesSet = Sets.newHashSet(interfaces)
770 .stream().filter(r -> r.tenantId().equals(routerInf.tenantId()))
771 .collect(Collectors.toSet());
772 if (routerInfFlagOfTenant.get(routerInf.tenantId()) != null) {
773 programRouterInterface(routerInf, operation);
774 } else {
775 if (interfacesSet.size() >= SUBNET_NUM) {
776 programInterfacesSet(interfacesSet, operation);
777 }
778 }
779 }
780
781 @Override
782 public void onRouterInterfaceVanished(VtnRscEventFeedback l3Feedback) {
783 Objective.Operation operation = Objective.Operation.REMOVE;
784 RouterInterface routerInf = l3Feedback.routerInterface();
785 Iterable<RouterInterface> interfaces = routerInterfaceService
786 .getRouterInterfaces();
787 Set<RouterInterface> interfacesSet = Sets.newHashSet(interfaces)
788 .stream().filter(r -> r.tenantId().equals(routerInf.tenantId()))
789 .collect(Collectors.toSet());
790 if (routerInfFlagOfTenant.get(routerInf.tenantId()) != null) {
791 programRouterInterface(routerInf, operation);
792 if (interfacesSet.size() == 1) {
793 routerInfFlagOfTenant.remove(routerInf.tenantId());
794 interfacesSet.stream().forEach(r -> {
795 programRouterInterface(r, operation);
796 });
797 }
798 }
lishuai762df812016-01-08 11:51:15 +0800799 VirtualPort gwPort = virtualPortService.getPort(routerInf.portId());
800 if (gwPort == null) {
801 gwPort = VtnData.getPort(vPortStore, routerInf.portId());
802 }
803 vPortStore.remove(gwPort.portId());
lishuai858efd32015-12-04 14:30:36 +0800804 }
805
806 @Override
807 public void onFloatingIpDetected(VtnRscEventFeedback l3Feedback) {
lishuai762df812016-01-08 11:51:15 +0800808 programFloatingIpEvent(l3Feedback, VtnRscEvent.Type.FLOATINGIP_BIND);
lishuai858efd32015-12-04 14:30:36 +0800809 }
810
811 @Override
812 public void onFloatingIpVanished(VtnRscEventFeedback l3Feedback) {
lishuai762df812016-01-08 11:51:15 +0800813 programFloatingIpEvent(l3Feedback, VtnRscEvent.Type.FLOATINGIP_UNBIND);
lishuai858efd32015-12-04 14:30:36 +0800814 }
815
816 private void programInterfacesSet(Set<RouterInterface> interfacesSet,
817 Objective.Operation operation) {
818 int subnetVmNum = 0;
819 for (RouterInterface r : interfacesSet) {
820 // Get all the host of the subnet
821 Map<HostId, Host> hosts = hostsOfSubnet.get(r.subnetId());
lishuaid6f0c9e2015-12-16 11:40:01 +0800822 if (hosts != null && hosts.size() > 0) {
lishuai858efd32015-12-04 14:30:36 +0800823 subnetVmNum++;
824 if (subnetVmNum >= SUBNET_NUM) {
825 routerInfFlagOfTenant.put(r.tenantId(), true);
826 interfacesSet.stream().forEach(f -> {
827 programRouterInterface(f, operation);
828 });
829 break;
830 }
831 }
832 }
833 }
834
835 private void programRouterInterface(RouterInterface routerInf,
836 Objective.Operation operation) {
837 SegmentationId l3vni = vtnRscService.getL3vni(routerInf.tenantId());
838 // Get all the host of the subnet
839 Map<HostId, Host> hosts = hostsOfSubnet.get(routerInf.subnetId());
840 hosts.values().stream().forEach(h -> {
841 applyEastWestL3Flows(h, l3vni, operation);
842 });
843 }
844
845 private void applyEastWestL3Flows(Host h, SegmentationId l3vni,
846 Objective.Operation operation) {
847 if (!mastershipService.isLocalMaster(h.location().deviceId())) {
848 log.debug("not master device:{}", h.location().deviceId());
849 return;
850 }
851 String ifaceId = h.annotations().value(IFACEID);
852 VirtualPort hPort = virtualPortService
853 .getPort(VirtualPortId.portId(ifaceId));
854 if (hPort == null) {
855 hPort = VtnData.getPort(vPortStore, VirtualPortId.portId(ifaceId));
856 }
857 IpAddress srcIp = null;
858 IpAddress srcGwIp = null;
859 MacAddress srcVmGwMac = null;
860 SubnetId srcSubnetId = null;
861 Iterator<FixedIp> srcIps = hPort.fixedIps().iterator();
862 if (srcIps.hasNext()) {
863 FixedIp fixedIp = srcIps.next();
864 srcIp = fixedIp.ip();
865 srcSubnetId = fixedIp.subnetId();
866 srcGwIp = subnetService.getSubnet(srcSubnetId).gatewayIp();
867 FixedIp fixedGwIp = FixedIp.fixedIp(srcSubnetId, srcGwIp);
868 VirtualPort gwPort = virtualPortService.getPort(fixedGwIp);
869 if (gwPort == null) {
870 gwPort = VtnData.getPort(vPortStore, fixedGwIp);
871 }
872 srcVmGwMac = gwPort.macAddress();
873 }
874 TenantNetwork network = tenantNetworkService
875 .getNetwork(hPort.networkId());
876 // Classifier rules
877 classifierService
878 .programL3InPortClassifierRules(h.location().deviceId(),
879 h.location().port(), h.mac(),
880 srcVmGwMac, l3vni, operation);
881 // Arp rules
882 if (operation == Objective.Operation.ADD) {
883 classifierService.programArpClassifierRules(h.location().deviceId(),
884 srcGwIp,
885 network.segmentationId(),
886 operation);
887 DriverHandler handler = driverService.createHandler(h.location().deviceId());
888 arpService.programArpRules(handler, h.location().deviceId(), srcGwIp,
889 network.segmentationId(), srcVmGwMac,
890 operation);
891 }
892 Iterable<Device> devices = deviceService.getAvailableDevices();
893 IpAddress srcArpIp = srcIp;
894 MacAddress srcArpGwMac = srcVmGwMac;
895 Sets.newHashSet(devices).stream()
896 .filter(d -> Device.Type.SWITCH == d.type()).forEach(d -> {
897 // L3FWD rules
898 l3ForwardService.programRouteRules(d.id(), l3vni, srcArpIp,
899 network.segmentationId(),
900 srcArpGwMac, h.mac(),
901 operation);
902 });
903 }
904
905 private void programFloatingIpEvent(VtnRscEventFeedback l3Feedback,
906 VtnRscEvent.Type type) {
907 FloatingIp floaingIp = l3Feedback.floatingIp();
908 if (floaingIp != null) {
909 VirtualPortId vmPortId = floaingIp.portId();
910 VirtualPort vmPort = virtualPortService.getPort(vmPortId);
911 VirtualPort fipPort = virtualPortService
912 .getPort(floaingIp.networkId(), floaingIp.floatingIp());
913 if (vmPort == null) {
914 vmPort = VtnData.getPort(vPortStore, vmPortId);
915 }
916 if (fipPort == null) {
917 fipPort = VtnData.getPort(vPortStore, floaingIp.networkId(),
918 floaingIp.floatingIp());
919 }
920 Set<Host> hostSet = hostService.getHostsByMac(vmPort.macAddress());
921 Host host = null;
922 for (Host h : hostSet) {
923 String ifaceid = h.annotations().value(IFACEID);
924 if (ifaceid != null && ifaceid.equals(vmPortId.portId())) {
925 host = h;
926 break;
927 }
928 }
929 if (host != null && vmPort != null && fipPort != null) {
930 DeviceId deviceId = host.location().deviceId();
931 Port exPort = exPortOfDevice.get(deviceId);
932 SegmentationId l3vni = vtnRscService
933 .getL3vni(vmPort.tenantId());
934 // Floating ip BIND
lishuai762df812016-01-08 11:51:15 +0800935 if (type == VtnRscEvent.Type.FLOATINGIP_BIND) {
lishuai16c05af2016-01-21 18:39:05 +0800936 vPortStore.put(fipPort.portId(), fipPort);
lishuai858efd32015-12-04 14:30:36 +0800937 applyNorthSouthL3Flows(deviceId, host, vmPort, fipPort,
938 floaingIp, l3vni, exPort,
939 Objective.Operation.ADD);
lishuai762df812016-01-08 11:51:15 +0800940 } else if (type == VtnRscEvent.Type.FLOATINGIP_UNBIND) {
lishuai858efd32015-12-04 14:30:36 +0800941 // Floating ip UNBIND
942 applyNorthSouthL3Flows(deviceId, host, vmPort, fipPort,
943 floaingIp, l3vni, exPort,
944 Objective.Operation.REMOVE);
lishuai16c05af2016-01-21 18:39:05 +0800945 vPortStore.remove(fipPort.portId());
lishuai858efd32015-12-04 14:30:36 +0800946 }
947 }
948 }
949 }
950
951 private void applyNorthSouthL3Flows(DeviceId deviceId, Host host,
952 VirtualPort vmPort, VirtualPort fipPort,
953 FloatingIp floatingIp,
954 SegmentationId l3Vni, Port exPort,
955 Objective.Operation operation) {
956 if (!mastershipService.isLocalMaster(deviceId)) {
957 log.debug("not master device:{}", deviceId);
958 return;
959 }
960 List gwIpMac = getGwIpAndMac(vmPort);
961 IpAddress dstVmGwIp = (IpAddress) gwIpMac.get(0);
962 MacAddress dstVmGwMac = (MacAddress) gwIpMac.get(1);
lishuai74f2d532015-12-10 17:03:34 +0800963 List fGwIpMac = getGwIpAndMac(fipPort);
964 MacAddress fGwMac = (MacAddress) fGwIpMac.get(1);
lishuai858efd32015-12-04 14:30:36 +0800965 TenantNetwork vmNetwork = tenantNetworkService
966 .getNetwork(vmPort.networkId());
967 TenantNetwork fipNetwork = tenantNetworkService
968 .getNetwork(fipPort.networkId());
969 // L3 downlink traffic flow
lishuaia3e32342015-12-07 10:59:17 +0800970 MacAddress exPortMac = MacAddress.valueOf(exPort.annotations()
971 .value(AnnotationKeys.PORT_MAC));
lishuai858efd32015-12-04 14:30:36 +0800972 classifierService.programArpClassifierRules(deviceId, floatingIp.floatingIp(),
973 fipNetwork.segmentationId(),
974 operation);
975 classifierService.programL3ExPortClassifierRules(deviceId, exPort.number(),
976 floatingIp.floatingIp(), operation);
977 DriverHandler handler = driverService.createHandler(deviceId);
978 arpService.programArpRules(handler, deviceId, floatingIp.floatingIp(),
979 fipNetwork.segmentationId(), exPortMac,
980 operation);
981 dnatService.programRules(deviceId, floatingIp.floatingIp(),
982 fGwMac, floatingIp.fixedIp(),
983 l3Vni, operation);
984 l3ForwardService
985 .programRouteRules(deviceId, l3Vni, floatingIp.fixedIp(),
986 vmNetwork.segmentationId(), dstVmGwMac,
987 vmPort.macAddress(), operation);
988
989 // L3 uplink traffic flow
990 classifierService.programL3InPortClassifierRules(deviceId,
991 host.location().port(),
992 host.mac(), dstVmGwMac,
993 l3Vni, operation);
994 snatService.programRules(deviceId, l3Vni, floatingIp.fixedIp(),
995 fGwMac, exPortMac,
996 floatingIp.floatingIp(),
997 fipNetwork.segmentationId(), operation);
998 if (operation == Objective.Operation.ADD) {
999 classifierService.programArpClassifierRules(deviceId, dstVmGwIp,
1000 vmNetwork.segmentationId(),
1001 operation);
1002 arpService.programArpRules(handler, deviceId, dstVmGwIp,
1003 vmNetwork.segmentationId(), dstVmGwMac,
1004 operation);
1005 l2ForwardService.programLocalOut(deviceId,
1006 fipNetwork.segmentationId(),
1007 exPort.number(), fGwMac, operation);
1008 }
1009 }
1010
1011 private Port getExPort(DeviceId deviceId) {
1012 List<Port> ports = deviceService.getPorts(deviceId);
1013 Port exPort = null;
1014 for (Port port : ports) {
1015 String portName = port.annotations().value(AnnotationKeys.PORT_NAME);
lishuaib43dbf72016-01-06 11:11:35 +08001016 Versioned<String> exPortVersioned = exPortMap.get(EX_PORT_KEY);
1017 if (portName != null && exPortVersioned != null && portName.
1018 equals(exPortVersioned.value())) {
lishuai858efd32015-12-04 14:30:36 +08001019 exPort = port;
1020 break;
1021 }
1022 }
1023 return exPort;
1024 }
1025
1026 private List getGwIpAndMac(VirtualPort port) {
1027 List list = new ArrayList();
1028 MacAddress gwMac = null;
1029 SubnetId subnetId = null;
1030 IpAddress gwIp = null;
1031 Iterator<FixedIp> fixips = port.fixedIps().iterator();
1032 if (fixips.hasNext()) {
1033 FixedIp fixip = fixips.next();
1034 subnetId = fixip.subnetId();
1035 gwIp = subnetService.getSubnet(subnetId).gatewayIp();
1036 FixedIp fixedGwIp = FixedIp.fixedIp(fixip.subnetId(), gwIp);
1037 VirtualPort gwPort = virtualPortService.getPort(fixedGwIp);
1038 if (gwPort == null) {
1039 gwPort = VtnData.getPort(vPortStore, fixedGwIp);
1040 }
1041 gwMac = gwPort.macAddress();
1042 }
1043 list.add(gwIp);
1044 list.add(gwMac);
1045 return list;
1046 }
1047
lishuai858efd32015-12-04 14:30:36 +08001048 private void applyHostMonitoredL3Rules(Host host,
1049 Objective.Operation operation) {
1050 String ifaceId = host.annotations().value(IFACEID);
1051 DeviceId deviceId = host.location().deviceId();
1052 VirtualPortId portId = VirtualPortId.portId(ifaceId);
1053 VirtualPort port = virtualPortService.getPort(portId);
1054 if (port == null) {
1055 port = VtnData.getPort(vPortStore, portId);
1056 }
1057 TenantId tenantId = port.tenantId();
1058 Port exPort = exPortOfDevice.get(deviceId);
1059 SegmentationId l3vni = vtnRscService.getL3vni(tenantId);
1060 Iterator<FixedIp> fixips = port.fixedIps().iterator();
1061 SubnetId sid = null;
1062 IpAddress hostIp = null;
1063 if (fixips.hasNext()) {
1064 FixedIp fixip = fixips.next();
1065 sid = fixip.subnetId();
1066 hostIp = fixip.ip();
1067 }
1068 final SubnetId subnetId = sid;
1069 // L3 internal network access to each other
1070 Iterable<RouterInterface> interfaces = routerInterfaceService
1071 .getRouterInterfaces();
1072 Set<RouterInterface> interfacesSet = Sets.newHashSet(interfaces)
1073 .stream().filter(r -> r.tenantId().equals(tenantId))
1074 .collect(Collectors.toSet());
1075 long count = interfacesSet.stream()
1076 .filter(r -> !r.subnetId().equals(subnetId)).count();
1077 if (count > 0) {
1078 if (operation == Objective.Operation.ADD) {
1079 if (routerInfFlagOfTenant.get(tenantId) != null) {
1080 applyEastWestL3Flows(host, l3vni, operation);
1081 } else {
1082 if (interfacesSet.size() > 1) {
1083 programInterfacesSet(interfacesSet, operation);
1084 }
1085 }
1086 } else if (operation == Objective.Operation.REMOVE) {
1087 if (routerInfFlagOfTenant.get(tenantId) != null) {
1088 applyEastWestL3Flows(host, l3vni, operation);
1089 }
1090 }
1091 }
1092 // L3 external and internal network access to each other
1093 FloatingIp floatingIp = null;
1094 Iterable<FloatingIp> floatingIps = floatingIpService.getFloatingIps();
1095 Set<FloatingIp> floatingIpSet = Sets.newHashSet(floatingIps).stream()
1096 .filter(f -> f.tenantId().equals(tenantId))
1097 .collect(Collectors.toSet());
1098 for (FloatingIp f : floatingIpSet) {
1099 IpAddress fixedIp = f.fixedIp();
1100 if (fixedIp.equals(hostIp)) {
1101 floatingIp = f;
1102 break;
1103 }
1104 }
1105 if (floatingIp != null) {
1106 VirtualPort fipPort = virtualPortService
1107 .getPort(floatingIp.networkId(), floatingIp.floatingIp());
1108 if (fipPort == null) {
1109 fipPort = VtnData.getPort(vPortStore, floatingIp.networkId(),
1110 floatingIp.floatingIp());
1111 }
1112 applyNorthSouthL3Flows(deviceId, host, port, fipPort, floatingIp,
1113 l3vni, exPort, operation);
1114 }
1115 }
lishuai74f2d532015-12-10 17:03:34 +08001116
1117 public static void setExPortName(String name) {
lishuaib43dbf72016-01-06 11:11:35 +08001118 exPortMap.put(EX_PORT_KEY, name);
lishuai74f2d532015-12-10 17:03:34 +08001119 }
lishuai6c56f5e2015-11-17 16:38:19 +08001120}