blob: c4802a63f555b1ff3a167ecbe49712c58f1fe087 [file] [log] [blame]
Jian Li8f944d42021-03-23 00:43:29 +09001/*
2 * Copyright 2020-present Open Networking Foundation
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.kubevirtnetworking.impl;
17
18import com.google.common.collect.Sets;
19import org.onlab.packet.Ethernet;
20import org.onlab.packet.IPv4;
21import org.onlab.packet.Ip4Address;
22import org.onlab.packet.Ip4Prefix;
23import org.onlab.packet.IpPrefix;
Jian Lif89d9602021-04-27 19:05:49 +090024import org.onlab.packet.MacAddress;
Jian Li8f944d42021-03-23 00:43:29 +090025import org.onlab.packet.TpPort;
Jian Li8f944d42021-03-23 00:43:29 +090026import org.onlab.util.Tools;
27import org.onosproject.cfg.ComponentConfigService;
28import org.onosproject.cfg.ConfigProperty;
29import org.onosproject.cluster.ClusterService;
30import org.onosproject.cluster.LeadershipService;
31import org.onosproject.cluster.NodeId;
32import org.onosproject.core.ApplicationId;
33import org.onosproject.core.CoreService;
34import org.onosproject.kubevirtnetworking.api.KubevirtFlowRuleService;
35import org.onosproject.kubevirtnetworking.api.KubevirtNetwork;
Jian Li8f944d42021-03-23 00:43:29 +090036import org.onosproject.kubevirtnetworking.api.KubevirtNetworkEvent;
37import org.onosproject.kubevirtnetworking.api.KubevirtNetworkListener;
38import org.onosproject.kubevirtnetworking.api.KubevirtNetworkService;
39import org.onosproject.kubevirtnetworking.api.KubevirtPort;
40import org.onosproject.kubevirtnetworking.api.KubevirtPortEvent;
41import org.onosproject.kubevirtnetworking.api.KubevirtPortListener;
42import org.onosproject.kubevirtnetworking.api.KubevirtPortService;
43import org.onosproject.kubevirtnetworking.api.KubevirtSecurityGroup;
44import org.onosproject.kubevirtnetworking.api.KubevirtSecurityGroupEvent;
45import org.onosproject.kubevirtnetworking.api.KubevirtSecurityGroupListener;
46import org.onosproject.kubevirtnetworking.api.KubevirtSecurityGroupRule;
47import org.onosproject.kubevirtnetworking.api.KubevirtSecurityGroupService;
48import org.onosproject.kubevirtnetworking.util.RulePopulatorUtil;
49import org.onosproject.kubevirtnode.api.KubevirtNode;
50import org.onosproject.kubevirtnode.api.KubevirtNodeEvent;
51import org.onosproject.kubevirtnode.api.KubevirtNodeListener;
52import org.onosproject.kubevirtnode.api.KubevirtNodeService;
53import org.onosproject.mastership.MastershipService;
54import org.onosproject.net.DeviceId;
Jian Lif89d9602021-04-27 19:05:49 +090055import org.onosproject.net.PortNumber;
Jian Li8f944d42021-03-23 00:43:29 +090056import org.onosproject.net.device.DeviceService;
57import org.onosproject.net.driver.DriverService;
58import org.onosproject.net.flow.DefaultTrafficSelector;
59import org.onosproject.net.flow.DefaultTrafficTreatment;
60import org.onosproject.net.flow.TrafficSelector;
61import org.onosproject.net.flow.TrafficTreatment;
62import org.onosproject.net.flow.criteria.ExtensionSelector;
63import org.onosproject.net.flow.instructions.ExtensionTreatment;
64import org.onosproject.store.service.StorageService;
65import org.osgi.service.component.ComponentContext;
66import org.osgi.service.component.annotations.Activate;
67import org.osgi.service.component.annotations.Component;
68import org.osgi.service.component.annotations.Deactivate;
69import org.osgi.service.component.annotations.Modified;
70import org.osgi.service.component.annotations.Reference;
71import org.osgi.service.component.annotations.ReferenceCardinality;
72import org.slf4j.Logger;
73
74import java.util.Dictionary;
75import java.util.Map;
76import java.util.Objects;
77import java.util.Set;
78import java.util.concurrent.ExecutorService;
79import java.util.stream.Collectors;
80
81import static java.lang.Thread.sleep;
82import static java.util.concurrent.Executors.newSingleThreadExecutor;
83import static org.onlab.util.Tools.groupedThreads;
Jian Lif89d9602021-04-27 19:05:49 +090084import static org.onosproject.kubevirtnetworking.api.Constants.ACL_CT_TABLE;
85import static org.onosproject.kubevirtnetworking.api.Constants.ACL_EGRESS_TABLE;
86import static org.onosproject.kubevirtnetworking.api.Constants.ACL_INGRESS_TABLE;
87import static org.onosproject.kubevirtnetworking.api.Constants.ACL_RECIRC_TABLE;
Jian Li8f944d42021-03-23 00:43:29 +090088import static org.onosproject.kubevirtnetworking.api.Constants.ERROR_TABLE;
Jian Lif89d9602021-04-27 19:05:49 +090089import static org.onosproject.kubevirtnetworking.api.Constants.FORWARDING_TABLE;
Jian Li8f944d42021-03-23 00:43:29 +090090import static org.onosproject.kubevirtnetworking.api.Constants.KUBEVIRT_NETWORKING_APP_ID;
91import static org.onosproject.kubevirtnetworking.api.Constants.PRIORITY_ACL_INGRESS_RULE;
92import static org.onosproject.kubevirtnetworking.api.Constants.PRIORITY_ACL_RULE;
93import static org.onosproject.kubevirtnetworking.api.Constants.PRIORITY_CT_DROP_RULE;
94import static org.onosproject.kubevirtnetworking.api.Constants.PRIORITY_CT_HOOK_RULE;
95import static org.onosproject.kubevirtnetworking.api.Constants.PRIORITY_CT_RULE;
96import static org.onosproject.kubevirtnetworking.api.Constants.TENANT_ACL_CT_TABLE;
97import static org.onosproject.kubevirtnetworking.api.Constants.TENANT_ACL_EGRESS_TABLE;
98import static org.onosproject.kubevirtnetworking.api.Constants.TENANT_ACL_INGRESS_TABLE;
99import static org.onosproject.kubevirtnetworking.api.Constants.TENANT_ACL_RECIRC_TABLE;
100import static org.onosproject.kubevirtnetworking.api.Constants.TENANT_FORWARDING_TABLE;
Jian Lif89d9602021-04-27 19:05:49 +0900101import static org.onosproject.kubevirtnetworking.api.KubevirtNetwork.Type.FLAT;
Jian Li8f944d42021-03-23 00:43:29 +0900102import static org.onosproject.kubevirtnetworking.api.KubevirtNetwork.Type.VLAN;
Jian Li8f944d42021-03-23 00:43:29 +0900103import static org.onosproject.kubevirtnetworking.impl.OsgiPropertyConstants.USE_SECURITY_GROUP;
104import static org.onosproject.kubevirtnetworking.impl.OsgiPropertyConstants.USE_SECURITY_GROUP_DEFAULT;
105import static org.onosproject.kubevirtnetworking.util.KubevirtNetworkingUtil.getPropertyValueAsBoolean;
106import static org.onosproject.kubevirtnetworking.util.RulePopulatorUtil.buildPortRangeMatches;
107import static org.onosproject.kubevirtnetworking.util.RulePopulatorUtil.computeCtMaskFlag;
108import static org.onosproject.kubevirtnetworking.util.RulePopulatorUtil.computeCtStateFlag;
109import static org.onosproject.kubevirtnetworking.util.RulePopulatorUtil.niciraConnTrackTreatmentBuilder;
110import static org.onosproject.kubevirtnode.api.KubevirtNode.Type.WORKER;
111import static org.slf4j.LoggerFactory.getLogger;
112
113/**
114 * Populates flow rules to handle EdgeStack SecurityGroups.
115 */
116@Component(
117 immediate = true,
118 property = {
119 USE_SECURITY_GROUP + ":Boolean=" + USE_SECURITY_GROUP_DEFAULT
120 }
121)
122public class KubevirtSecurityGroupHandler {
123
124 private final Logger log = getLogger(getClass());
125
126 private static final int VM_IP_PREFIX = 32;
127
128 private static final String STR_NULL = "null";
129 private static final String PROTO_ICMP = "ICMP";
130 private static final String PROTO_ICMP_NUM = "1";
131 private static final String PROTO_TCP = "TCP";
132 private static final String PROTO_TCP_NUM = "6";
133 private static final String PROTO_UDP = "UDP";
134 private static final String PROTO_UDP_NUM = "17";
135 private static final String PROTO_SCTP = "SCTP";
136 private static final String PROTO_SCTP_NUM = "132";
137 private static final byte PROTOCOL_SCTP = (byte) 0x84;
138 private static final String PROTO_ANY = "ANY";
139 private static final String PROTO_ANY_NUM = "0";
140 private static final String ETHTYPE_IPV4 = "IPV4";
141 private static final String EGRESS = "EGRESS";
142 private static final String INGRESS = "INGRESS";
143 private static final IpPrefix IP_PREFIX_ANY = Ip4Prefix.valueOf("0.0.0.0/0");
144
145 private static final int ICMP_CODE_MIN = 0;
146 private static final int ICMP_CODE_MAX = 255;
147 private static final int ICMP_TYPE_MIN = 0;
148 private static final int ICMP_TYPE_MAX = 255;
149
150 private static final int CT_COMMIT = 0;
151 private static final int CT_NO_COMMIT = 1;
152 private static final short CT_NO_RECIRC = -1;
153
154 private static final int ACTION_NONE = 0;
155 private static final int ACTION_DROP = -1;
156
157 private static final long SLEEP_MS = 5000;
158
159 /** Apply EdgeStack security group rule for VM traffic. */
160 private boolean useSecurityGroup = USE_SECURITY_GROUP_DEFAULT;
161
162 @Reference(cardinality = ReferenceCardinality.MANDATORY)
163 protected CoreService coreService;
164
165 @Reference(cardinality = ReferenceCardinality.MANDATORY)
166 protected MastershipService mastershipService;
167
168 @Reference(cardinality = ReferenceCardinality.MANDATORY)
169 protected DriverService driverService;
170
171 @Reference(cardinality = ReferenceCardinality.MANDATORY)
172 protected DeviceService deviceService;
173
174 @Reference(cardinality = ReferenceCardinality.MANDATORY)
175 protected LeadershipService leadershipService;
176
177 @Reference(cardinality = ReferenceCardinality.MANDATORY)
178 protected ClusterService clusterService;
179
180 @Reference(cardinality = ReferenceCardinality.MANDATORY)
181 protected StorageService storageService;
182
183 @Reference(cardinality = ReferenceCardinality.MANDATORY)
184 protected ComponentConfigService configService;
185
186 @Reference(cardinality = ReferenceCardinality.MANDATORY)
187 protected KubevirtNodeService nodeService;
188
189 @Reference(cardinality = ReferenceCardinality.MANDATORY)
190 protected KubevirtNetworkService networkService;
191
192 @Reference(cardinality = ReferenceCardinality.MANDATORY)
193 protected KubevirtPortService portService;
194
195 @Reference(cardinality = ReferenceCardinality.MANDATORY)
196 protected KubevirtFlowRuleService flowRuleService;
197
198 @Reference(cardinality = ReferenceCardinality.MANDATORY)
199 protected KubevirtSecurityGroupService securityGroupService;
200
201 private final KubevirtPortListener portListener =
202 new InternalKubevirtPortListener();
203 private final KubevirtSecurityGroupListener securityGroupListener =
204 new InternalSecurityGroupListener();
205 private final KubevirtNodeListener nodeListener =
206 new InternalNodeListener();
207 private final KubevirtNetworkListener networkListener =
208 new InternalNetworkListener();
209
210 private final ExecutorService eventExecutor = newSingleThreadExecutor(
211 groupedThreads(this.getClass().getSimpleName(), "event-handler"));
212
213 private ApplicationId appId;
214 private NodeId localNodeId;
215
216 @Activate
217 protected void activate() {
218 appId = coreService.registerApplication(KUBEVIRT_NETWORKING_APP_ID);
219 localNodeId = clusterService.getLocalNode().id();
220 securityGroupService.addListener(securityGroupListener);
221 portService.addListener(portListener);
222 networkService.addListener(networkListener);
223 configService.registerProperties(getClass());
224 nodeService.addListener(nodeListener);
225
226 log.info("Started");
227 }
228
229 @Deactivate
230 protected void deactivate() {
231 securityGroupService.removeListener(securityGroupListener);
232 portService.removeListener(portListener);
233 configService.unregisterProperties(getClass(), false);
234 nodeService.removeListener(nodeListener);
235 networkService.removeListener(networkListener);
236 eventExecutor.shutdown();
237
238 log.info("Stopped");
239 }
240
241 @Modified
242 protected void modified(ComponentContext context) {
243 Dictionary<?, ?> properties = context.getProperties();
244 Boolean flag;
245
246 flag = Tools.isPropertyEnabled(properties, USE_SECURITY_GROUP);
247 if (flag == null) {
248 log.info("useSecurityGroup is not configured, " +
249 "using current value of {}", useSecurityGroup);
250 } else {
251 useSecurityGroup = flag;
252 log.info("Configured. useSecurityGroup is {}",
253 useSecurityGroup ? "enabled" : "disabled");
254 }
255
256 securityGroupService.setSecurityGroupEnabled(useSecurityGroup);
257 resetSecurityGroupRules();
258 }
259
260 private boolean getUseSecurityGroupFlag() {
261 Set<ConfigProperty> properties =
262 configService.getProperties(getClass().getName());
263 return getPropertyValueAsBoolean(properties, USE_SECURITY_GROUP);
264 }
265
Jian Lif89d9602021-04-27 19:05:49 +0900266 private void initializeProviderConnTrackTable(DeviceId deviceId, boolean install) {
267 initializeConnTrackTable(deviceId, ACL_CT_TABLE, FORWARDING_TABLE, install);
268 }
269
270 private void initializeTenantConnTrackTable(DeviceId deviceId, boolean install) {
271 initializeConnTrackTable(deviceId, TENANT_ACL_CT_TABLE, TENANT_FORWARDING_TABLE, install);
272 }
273
274 private void initializeConnTrackTable(DeviceId deviceId, int ctTable,
275 int forwardTable, boolean install) {
Jian Li8f944d42021-03-23 00:43:29 +0900276
277 // table={ACL_INGRESS_TABLE(44)},ip,ct_state=-trk, actions=ct(table:{ACL_CT_TABLE(45)})
278 long ctState = computeCtStateFlag(false, false, false);
279 long ctMask = computeCtMaskFlag(true, false, false);
Jian Lif89d9602021-04-27 19:05:49 +0900280 setConnTrackRule(deviceId, ctState, ctMask, CT_NO_COMMIT, (short) ctTable,
Jian Li8f944d42021-03-23 00:43:29 +0900281 ACTION_NONE, PRIORITY_CT_HOOK_RULE, install);
282
283 //table={ACL_CT_TABLE(45)},ip,nw_dst=10.10.0.2,ct_state=+trk+est,action=goto_table:{NORMAL_TABLE(80)}
284 ctState = computeCtStateFlag(true, false, true);
285 ctMask = computeCtMaskFlag(true, false, true);
286 setConnTrackRule(deviceId, ctState, ctMask, CT_NO_COMMIT, CT_NO_RECIRC,
Jian Lif89d9602021-04-27 19:05:49 +0900287 forwardTable, PRIORITY_CT_RULE, install);
Jian Li8f944d42021-03-23 00:43:29 +0900288
289 //table={ACL_CT_TABLE(45)},ip,nw_dst=10.10.0.2,ct_state=+trk+new,action=drop
290 ctState = computeCtStateFlag(true, true, false);
291 ctMask = computeCtMaskFlag(true, true, false);
292 setConnTrackRule(deviceId, ctState, ctMask, CT_NO_COMMIT, CT_NO_RECIRC,
293 ACTION_DROP, PRIORITY_CT_DROP_RULE, install);
294 }
295
Jian Lif89d9602021-04-27 19:05:49 +0900296 private void initializeProviderAclTable(KubevirtNode node,
297 DeviceId deviceId, boolean install) {
298 // FIXME: we need to use group table to multi-cast traffic to all
299 // physPatchPorts later, we only choose one of the physPatchPorts to
300 // stream the outbound traffic for now
301 node.physPatchPorts().stream().findFirst().ifPresent(p ->
302 initializeAclTable(deviceId, ACL_RECIRC_TABLE, p, install));
303 }
304
305 private void initializeTenantAclTable(KubevirtNetwork network,
306 DeviceId deviceId, boolean install) {
307 PortNumber patchPort = network.tenantToTunnelPort(deviceId);
308 initializeAclTable(deviceId, TENANT_ACL_RECIRC_TABLE, patchPort, install);
309 }
310
311 private void initializeAclTable(DeviceId deviceId, int recircTable,
312 PortNumber outport, boolean install) {
Jian Li8f944d42021-03-23 00:43:29 +0900313
314 ExtensionTreatment ctTreatment =
315 niciraConnTrackTreatmentBuilder(driverService, deviceId)
316 .commit(true)
317 .build();
318
319 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
320 sBuilder.matchEthType(Ethernet.TYPE_IPV4);
321
322 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
323 tBuilder.extension(ctTreatment, deviceId)
Jian Lif89d9602021-04-27 19:05:49 +0900324 .setOutput(outport);
Jian Li8f944d42021-03-23 00:43:29 +0900325
326 flowRuleService.setRule(appId,
327 deviceId,
328 sBuilder.build(),
329 tBuilder.build(),
330 PRIORITY_ACL_INGRESS_RULE,
Jian Lif89d9602021-04-27 19:05:49 +0900331 recircTable,
Jian Li8f944d42021-03-23 00:43:29 +0900332 install);
333 }
334
Jian Lif89d9602021-04-27 19:05:49 +0900335 private void initializeProviderEgressTable(DeviceId deviceId, boolean install) {
336 initializeEgressTable(deviceId, ACL_EGRESS_TABLE, FORWARDING_TABLE, install);
337 }
338
339 private void initializeTenantEgressTable(DeviceId deviceId, boolean install) {
340 initializeEgressTable(deviceId, TENANT_ACL_EGRESS_TABLE, TENANT_FORWARDING_TABLE, install);
341 }
342
343 private void initializeEgressTable(DeviceId deviceId, int egressTable,
344 int forwardTable, boolean install) {
Jian Li8f944d42021-03-23 00:43:29 +0900345 if (install) {
346 flowRuleService.setUpTableMissEntry(deviceId, TENANT_ACL_EGRESS_TABLE);
347 } else {
Jian Lif89d9602021-04-27 19:05:49 +0900348 flowRuleService.connectTables(deviceId, egressTable, forwardTable);
Jian Li8f944d42021-03-23 00:43:29 +0900349 }
350 }
351
Jian Lif89d9602021-04-27 19:05:49 +0900352 private void initializeProviderIngressTable(DeviceId deviceId, boolean install) {
353 initializeIngressTable(deviceId, ACL_INGRESS_TABLE, FORWARDING_TABLE, install);
354 }
355
356 private void initializeTenantIngressTable(DeviceId deviceId, boolean install) {
357 initializeIngressTable(deviceId, TENANT_ACL_INGRESS_TABLE, TENANT_FORWARDING_TABLE, install);
358 }
359
360 private void initializeIngressTable(DeviceId deviceId, int ingressTable,
361 int forwardTable, boolean install) {
Jian Li8f944d42021-03-23 00:43:29 +0900362 if (install) {
Jian Lif89d9602021-04-27 19:05:49 +0900363 flowRuleService.setUpTableMissEntry(deviceId, ingressTable);
Jian Li8f944d42021-03-23 00:43:29 +0900364 } else {
Jian Lif89d9602021-04-27 19:05:49 +0900365 flowRuleService.connectTables(deviceId, ingressTable, forwardTable);
Jian Li8f944d42021-03-23 00:43:29 +0900366 }
367 }
368
Jian Lif89d9602021-04-27 19:05:49 +0900369 private void initializeProviderPipeline(KubevirtNode node, boolean install) {
370 initializeProviderIngressTable(node.intgBridge(), install);
371 initializeProviderEgressTable(node.intgBridge(), install);
372 initializeProviderConnTrackTable(node.intgBridge(), install);
373 initializeProviderAclTable(node, node.intgBridge(), install);
374 }
375
376 private void initializeTenantPipeline(KubevirtNetwork network,
377 KubevirtNode node, boolean install) {
378 DeviceId deviceId = network.tenantDeviceId(node.hostname());
379 if (deviceId == null) {
380 return;
381 }
382 initializeTenantIngressTable(deviceId, install);
383 initializeTenantEgressTable(deviceId, install);
384 initializeTenantConnTrackTable(deviceId, install);
385 initializeTenantAclTable(network, deviceId, install);
386 }
387
Jian Li8f944d42021-03-23 00:43:29 +0900388 private void updateSecurityGroupRule(KubevirtPort port,
389 KubevirtSecurityGroupRule sgRule, boolean install) {
390
391 if (port == null || sgRule == null) {
392 return;
393 }
394
395 if (sgRule.remoteGroupId() != null && !sgRule.remoteGroupId().isEmpty()) {
396 getRemotePorts(port, sgRule.remoteGroupId())
397 .forEach(rPort -> {
398 populateSecurityGroupRule(sgRule, port,
399 rPort.ipAddress().toIpPrefix(), install);
400 populateSecurityGroupRule(sgRule, rPort,
401 port.ipAddress().toIpPrefix(), install);
402
403 KubevirtSecurityGroupRule rSgRule = sgRule.updateDirection(
404 sgRule.direction().equalsIgnoreCase(EGRESS) ? INGRESS : EGRESS);
405 populateSecurityGroupRule(rSgRule, port,
406 rPort.ipAddress().toIpPrefix(), install);
407 populateSecurityGroupRule(rSgRule, rPort,
408 port.ipAddress().toIpPrefix(), install);
409 });
410 } else {
411 populateSecurityGroupRule(sgRule, port,
412 sgRule.remoteIpPrefix() == null ? IP_PREFIX_ANY :
413 sgRule.remoteIpPrefix(), install);
414 }
415 }
416
417 private boolean checkProtocol(String protocol) {
418 if (protocol == null) {
419 log.debug("No protocol was specified, use default IP(v4/v6) protocol.");
420 return true;
421 } else {
422 String protocolUpper = protocol.toUpperCase();
423 if (protocolUpper.equals(PROTO_TCP) ||
424 protocolUpper.equals(PROTO_UDP) ||
425 protocolUpper.equals(PROTO_ICMP) ||
426 protocolUpper.equals(PROTO_SCTP) ||
427 protocolUpper.equals(PROTO_ANY) ||
428 protocol.equals(PROTO_TCP_NUM) ||
429 protocol.equals(PROTO_UDP_NUM) ||
430 protocol.equals(PROTO_ICMP_NUM) ||
431 protocol.equals(PROTO_SCTP_NUM) ||
432 protocol.equals(PROTO_ANY_NUM)) {
433 return true;
434 } else {
435 log.error("Unsupported protocol {}, we only support " +
436 "TCP/UDP/ICMP/SCTP protocols.", protocol);
437 return false;
438 }
439 }
440 }
441
442 private void populateSecurityGroupRule(KubevirtSecurityGroupRule sgRule,
443 KubevirtPort port,
444 IpPrefix remoteIp,
445 boolean install) {
446 if (!checkProtocol(sgRule.protocol())) {
447 return;
448 }
449
450 DeviceId deviceId = port.isTenant() ? port.tenantDeviceId() : port.deviceId();
451
Jian Lif89d9602021-04-27 19:05:49 +0900452 Set<TrafficSelector> ctSelectors = buildSelectors(
453 sgRule,
Jian Li8f944d42021-03-23 00:43:29 +0900454 Ip4Address.valueOf(port.ipAddress().toInetAddress()),
Jian Lif89d9602021-04-27 19:05:49 +0900455 port.macAddress(),
Jian Li8f944d42021-03-23 00:43:29 +0900456 remoteIp, port.networkId());
Jian Lif89d9602021-04-27 19:05:49 +0900457 if (ctSelectors == null || ctSelectors.isEmpty()) {
Jian Li8f944d42021-03-23 00:43:29 +0900458 return;
459 }
460
461 // if the device is not available we do not perform any action
462 if (deviceId == null || !deviceService.isAvailable(deviceId)) {
463 return;
464 }
465
466 // XXX All egress traffic needs to go through connection tracking module,
467 // which might hurt its performance.
468 ExtensionTreatment ctTreatment =
469 niciraConnTrackTreatmentBuilder(driverService, deviceId)
470 .commit(true)
471 .build();
472
473 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
474
Jian Lif89d9602021-04-27 19:05:49 +0900475 KubevirtNetwork net = networkService.network(port.networkId());
476
Jian Li8f944d42021-03-23 00:43:29 +0900477 int aclTable;
478 if (sgRule.direction().equalsIgnoreCase(EGRESS)) {
Jian Lif89d9602021-04-27 19:05:49 +0900479
480 if (net.type() == FLAT || net.type() == VLAN) {
481 aclTable = ACL_EGRESS_TABLE;
482 } else {
483 aclTable = TENANT_ACL_EGRESS_TABLE;
484 }
485
Jian Li8f944d42021-03-23 00:43:29 +0900486 tBuilder.transition(TENANT_ACL_RECIRC_TABLE);
487 } else {
Jian Lif89d9602021-04-27 19:05:49 +0900488
489 if (net.type() == FLAT || net.type() == VLAN) {
490 aclTable = ACL_INGRESS_TABLE;
491 } else {
492 aclTable = TENANT_ACL_INGRESS_TABLE;
493 }
494
Jian Li8f944d42021-03-23 00:43:29 +0900495 tBuilder.extension(ctTreatment, deviceId)
496 .transition(TENANT_FORWARDING_TABLE);
497 }
498
499 int finalAclTable = aclTable;
Jian Lif89d9602021-04-27 19:05:49 +0900500 ctSelectors.forEach(selector -> {
Jian Li8f944d42021-03-23 00:43:29 +0900501 flowRuleService.setRule(appId,
502 deviceId,
503 selector, tBuilder.build(),
504 PRIORITY_ACL_RULE,
505 finalAclTable,
506 install);
507 });
Jian Lif89d9602021-04-27 19:05:49 +0900508
509 TrafficSelector tSelector = DefaultTrafficSelector.builder()
510 .matchEthType(Ethernet.TYPE_IPV4)
511 .matchEthDst(port.macAddress())
512 .matchIPDst(IpPrefix.valueOf(port.ipAddress(), 32))
513 .build();
514 TrafficTreatment tTreatment = DefaultTrafficTreatment.builder()
515 .transition(TENANT_ACL_INGRESS_TABLE)
516 .build();
517
518 flowRuleService.setRule(appId,
519 deviceId,
520 tSelector,
521 tTreatment,
522 PRIORITY_ACL_RULE,
523 TENANT_ACL_RECIRC_TABLE,
524 install);
Jian Li8f944d42021-03-23 00:43:29 +0900525 }
526
527 /**
528 * Sets connection tracking rule using OVS extension commands.
529 * It is not so graceful, but I don't want to make it more general because
530 * it is going to be used only here.
531 * The following is the usage of the function.
532 *
533 * @param deviceId Device ID
534 * @param ctState ctState: please use RulePopulatorUtil.computeCtStateFlag()
535 * to build the value
536 * @param ctMask crMask: please use RulePopulatorUtil.computeCtMaskFlag()
537 * to build the value
538 * @param commit CT_COMMIT for commit action, CT_NO_COMMIT otherwise
539 * @param recircTable table number for recirculation after CT actions.
540 * CT_NO_RECIRC with no recirculation
541 * @param action Additional actions. ACTION_DROP, ACTION_NONE,
542 * GOTO_XXX_TABLE are supported.
543 * @param priority priority value for the rule
544 * @param install true for insertion, false for removal
545 */
546 private void setConnTrackRule(DeviceId deviceId, long ctState, long ctMask,
547 int commit, short recircTable,
548 int action, int priority, boolean install) {
549
550 ExtensionSelector esCtSate = RulePopulatorUtil
551 .buildCtExtensionSelector(driverService, deviceId, ctState, ctMask);
552 TrafficSelector selector = DefaultTrafficSelector.builder()
553 .extension(esCtSate, deviceId)
554 .matchEthType(Ethernet.TYPE_IPV4)
555 .build();
556
557 TrafficTreatment.Builder tb = DefaultTrafficTreatment.builder();
558
559 if (commit == CT_COMMIT || recircTable > 0) {
560 RulePopulatorUtil.NiciraConnTrackTreatmentBuilder natTreatmentBuilder =
561 niciraConnTrackTreatmentBuilder(driverService, deviceId);
562 natTreatmentBuilder.natAction(false);
563 natTreatmentBuilder.commit(commit == CT_COMMIT);
564 if (recircTable > 0) {
565 natTreatmentBuilder.table(recircTable);
566 }
567 tb.extension(natTreatmentBuilder.build(), deviceId);
568 } else if (action == ACTION_DROP) {
569 tb.drop();
570 }
571
572 if (action != ACTION_NONE && action != ACTION_DROP) {
573 tb.transition(action);
574 }
575
576 int tableType = ERROR_TABLE;
577 if (priority == PRIORITY_CT_RULE || priority == PRIORITY_CT_DROP_RULE) {
578 tableType = TENANT_ACL_CT_TABLE;
579 } else if (priority == PRIORITY_CT_HOOK_RULE) {
580 tableType = TENANT_ACL_INGRESS_TABLE;
581 } else {
582 log.error("Cannot an appropriate table for the conn track rule.");
583 }
584
585 flowRuleService.setRule(
586 appId,
587 deviceId,
588 selector,
589 tb.build(),
590 priority,
591 tableType,
592 install);
593 }
594
595 /**
596 * Returns a set of host IP addresses engaged with supplied security group ID.
597 * It only searches a VM in the same tenant boundary.
598 *
599 * @param srcPort edgestack port
600 * @param sgId security group id
601 * @return set of ip addresses
602 */
603 private Set<KubevirtPort> getRemotePorts(KubevirtPort srcPort, String sgId) {
604 return portService.ports().stream()
605 .filter(port -> !port.macAddress().equals(srcPort.macAddress()))
606 .filter(port -> port.securityGroups().contains(sgId))
607 .filter(port -> port.ipAddress() != null)
608 .collect(Collectors.toSet());
609 }
610
611 private Set<TrafficSelector> buildSelectors(KubevirtSecurityGroupRule sgRule,
612 Ip4Address vmIp,
Jian Lif89d9602021-04-27 19:05:49 +0900613 MacAddress vmMac,
Jian Li8f944d42021-03-23 00:43:29 +0900614 IpPrefix remoteIp,
615 String netId) {
616 if (remoteIp != null && remoteIp.equals(IpPrefix.valueOf(vmIp, VM_IP_PREFIX))) {
617 // do nothing if the remote IP is my IP
618 return null;
619 }
620
621 Set<TrafficSelector> selectorSet = Sets.newHashSet();
622
623 if (sgRule.portRangeMax() != null && sgRule.portRangeMin() != null &&
624 sgRule.portRangeMin() < sgRule.portRangeMax()) {
625 Map<TpPort, TpPort> portRangeMatchMap =
626 buildPortRangeMatches(sgRule.portRangeMin(),
627 sgRule.portRangeMax());
628 portRangeMatchMap.forEach((key, value) -> {
629
630 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
Jian Lif89d9602021-04-27 19:05:49 +0900631 buildMatches(sBuilder, sgRule, vmIp, vmMac, remoteIp);
Jian Li8f944d42021-03-23 00:43:29 +0900632
633 if (sgRule.protocol().equalsIgnoreCase(PROTO_TCP) ||
634 sgRule.protocol().equals(PROTO_TCP_NUM)) {
635 if (sgRule.direction().equalsIgnoreCase(EGRESS)) {
636 if (value.toInt() == TpPort.MAX_PORT) {
637 sBuilder.matchTcpSrc(key);
638 } else {
639 sBuilder.matchTcpSrcMasked(key, value);
640 }
641 } else {
642 if (value.toInt() == TpPort.MAX_PORT) {
643 sBuilder.matchTcpDst(key);
644 } else {
645 sBuilder.matchTcpDstMasked(key, value);
646 }
647 }
648 } else if (sgRule.protocol().equalsIgnoreCase(PROTO_UDP) ||
649 sgRule.protocol().equals(PROTO_UDP_NUM)) {
650 if (sgRule.direction().equalsIgnoreCase(EGRESS)) {
651 if (value.toInt() == TpPort.MAX_PORT) {
652 sBuilder.matchUdpSrc(key);
653 } else {
654 sBuilder.matchUdpSrcMasked(key, value);
655 }
656 } else {
657 if (value.toInt() == TpPort.MAX_PORT) {
658 sBuilder.matchUdpDst(key);
659 } else {
660 sBuilder.matchUdpDstMasked(key, value);
661 }
662 }
663 } else if (sgRule.protocol().equalsIgnoreCase(PROTO_SCTP) ||
664 sgRule.protocol().equals(PROTO_SCTP_NUM)) {
665 if (sgRule.direction().equalsIgnoreCase(EGRESS)) {
666 if (value.toInt() == TpPort.MAX_PORT) {
667 sBuilder.matchSctpSrc(key);
668 } else {
669 sBuilder.matchSctpSrcMasked(key, value);
670 }
671 } else {
672 if (value.toInt() == TpPort.MAX_PORT) {
673 sBuilder.matchSctpDst(key);
674 } else {
675 sBuilder.matchSctpDstMasked(key, value);
676 }
677 }
678 }
679
680 selectorSet.add(sBuilder.build());
681 });
682 } else {
683
684 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
Jian Lif89d9602021-04-27 19:05:49 +0900685 buildMatches(sBuilder, sgRule, vmIp, vmMac, remoteIp);
Jian Li8f944d42021-03-23 00:43:29 +0900686
687 selectorSet.add(sBuilder.build());
688 }
689
690 return selectorSet;
691 }
692
693 private void buildMatches(TrafficSelector.Builder sBuilder,
694 KubevirtSecurityGroupRule sgRule, Ip4Address vmIp,
Jian Lif89d9602021-04-27 19:05:49 +0900695 MacAddress vmMac, IpPrefix remoteIp) {
Jian Li8f944d42021-03-23 00:43:29 +0900696 buildMatchEthType(sBuilder, sgRule.etherType());
Jian Lif89d9602021-04-27 19:05:49 +0900697 buildMatchDirection(sBuilder, sgRule.direction(), vmIp, vmMac);
Jian Li8f944d42021-03-23 00:43:29 +0900698 buildMatchProto(sBuilder, sgRule.protocol());
699 buildMatchPort(sBuilder, sgRule.protocol(), sgRule.direction(),
700 sgRule.portRangeMin() == null ? 0 : sgRule.portRangeMin(),
701 sgRule.portRangeMax() == null ? 0 : sgRule.portRangeMax());
702 buildMatchIcmp(sBuilder, sgRule.protocol(),
703 sgRule.portRangeMin(), sgRule.portRangeMax());
704 buildMatchRemoteIp(sBuilder, remoteIp, sgRule.direction());
705 }
706
Jian Li8f944d42021-03-23 00:43:29 +0900707 private void buildMatchDirection(TrafficSelector.Builder sBuilder,
708 String direction,
Jian Lif89d9602021-04-27 19:05:49 +0900709 Ip4Address vmIp,
710 MacAddress vmMac) {
Jian Li8f944d42021-03-23 00:43:29 +0900711 if (direction.equalsIgnoreCase(EGRESS)) {
712 sBuilder.matchIPSrc(IpPrefix.valueOf(vmIp, VM_IP_PREFIX));
Jian Lif89d9602021-04-27 19:05:49 +0900713 sBuilder.matchEthSrc(vmMac);
Jian Li8f944d42021-03-23 00:43:29 +0900714 } else {
715 sBuilder.matchIPDst(IpPrefix.valueOf(vmIp, VM_IP_PREFIX));
Jian Lif89d9602021-04-27 19:05:49 +0900716 sBuilder.matchEthDst(vmMac);
Jian Li8f944d42021-03-23 00:43:29 +0900717 }
718 }
719
720 private void buildMatchEthType(TrafficSelector.Builder sBuilder, String etherType) {
721 // Either IpSrc or IpDst (or both) is set by default, and we need to set EthType as IPv4.
722 sBuilder.matchEthType(Ethernet.TYPE_IPV4);
723 if (etherType != null && !Objects.equals(etherType, STR_NULL) &&
724 !etherType.equalsIgnoreCase(ETHTYPE_IPV4)) {
725 log.debug("EthType {} is not supported yet in Security Group", etherType);
726 }
727 }
728
729 private void buildMatchRemoteIp(TrafficSelector.Builder sBuilder,
730 IpPrefix remoteIpPrefix, String direction) {
731 if (remoteIpPrefix != null &&
732 !remoteIpPrefix.getIp4Prefix().equals(IP_PREFIX_ANY)) {
733 if (direction.equalsIgnoreCase(EGRESS)) {
734 sBuilder.matchIPDst(remoteIpPrefix);
735 } else {
736 sBuilder.matchIPSrc(remoteIpPrefix);
737 }
738 }
739 }
740
741 private void buildMatchProto(TrafficSelector.Builder sBuilder, String protocol) {
742 if (protocol != null) {
743 switch (protocol.toUpperCase()) {
744 case PROTO_ICMP:
745 case PROTO_ICMP_NUM:
746 sBuilder.matchIPProtocol(IPv4.PROTOCOL_ICMP);
747 break;
748 case PROTO_TCP:
749 case PROTO_TCP_NUM:
750 sBuilder.matchIPProtocol(IPv4.PROTOCOL_TCP);
751 break;
752 case PROTO_UDP:
753 case PROTO_UDP_NUM:
754 sBuilder.matchIPProtocol(IPv4.PROTOCOL_UDP);
755 break;
756 case PROTO_SCTP:
757 case PROTO_SCTP_NUM:
758 sBuilder.matchIPProtocol(PROTOCOL_SCTP);
759 break;
760 default:
761 break;
762 }
763 }
764 }
765
766 private void buildMatchPort(TrafficSelector.Builder sBuilder,
767 String protocol, String direction,
768 int portMin, int portMax) {
769 if (portMax > 0 && portMin == portMax) {
770 if (protocol.equalsIgnoreCase(PROTO_TCP) ||
771 protocol.equals(PROTO_TCP_NUM)) {
772 if (direction.equalsIgnoreCase(EGRESS)) {
773 sBuilder.matchTcpSrc(TpPort.tpPort(portMax));
774 } else {
775 sBuilder.matchTcpDst(TpPort.tpPort(portMax));
776 }
777 } else if (protocol.equalsIgnoreCase(PROTO_UDP) ||
778 protocol.equals(PROTO_UDP_NUM)) {
779 if (direction.equalsIgnoreCase(EGRESS)) {
780 sBuilder.matchUdpSrc(TpPort.tpPort(portMax));
781 } else {
782 sBuilder.matchUdpDst(TpPort.tpPort(portMax));
783 }
784 } else if (protocol.equalsIgnoreCase(PROTO_SCTP) ||
785 protocol.equals(PROTO_SCTP_NUM)) {
786 if (direction.equalsIgnoreCase(EGRESS)) {
787 sBuilder.matchSctpSrc(TpPort.tpPort(portMax));
788 } else {
789 sBuilder.matchSctpDst(TpPort.tpPort(portMax));
790 }
791 }
792 }
793 }
794
795 private void buildMatchIcmp(TrafficSelector.Builder sBuilder,
796 String protocol, Integer icmpCode, Integer icmpType) {
797 if (protocol != null) {
798 if (protocol.equalsIgnoreCase(PROTO_ICMP) ||
799 protocol.equals(PROTO_ICMP_NUM)) {
800 if (icmpCode != null && icmpCode >= ICMP_CODE_MIN &&
801 icmpCode <= ICMP_CODE_MAX) {
802 sBuilder.matchIcmpCode(icmpCode.byteValue());
803 }
804 if (icmpType != null && icmpType >= ICMP_TYPE_MIN &&
805 icmpType <= ICMP_TYPE_MAX) {
806 sBuilder.matchIcmpType(icmpType.byteValue());
807 }
808 }
809 }
810 }
811
812 private void resetSecurityGroupRules() {
813
814 if (getUseSecurityGroupFlag()) {
815 nodeService.completeNodes(WORKER).forEach(node -> {
Jian Lif89d9602021-04-27 19:05:49 +0900816 initializeProviderPipeline(node, true);
Jian Li8f944d42021-03-23 00:43:29 +0900817
818 for (KubevirtNetwork network : networkService.tenantNetworks()) {
Jian Lif89d9602021-04-27 19:05:49 +0900819 initializeTenantPipeline(network, node, true);
Jian Li8f944d42021-03-23 00:43:29 +0900820 }
821 });
822
823 securityGroupService.securityGroups().forEach(securityGroup ->
824 securityGroup.rules().forEach(this::securityGroupRuleAdded));
825 } else {
826 nodeService.completeNodes(WORKER).forEach(node -> {
Jian Lif89d9602021-04-27 19:05:49 +0900827 initializeProviderPipeline(node, false);
Jian Li8f944d42021-03-23 00:43:29 +0900828
829 for (KubevirtNetwork network : networkService.tenantNetworks()) {
Jian Lif89d9602021-04-27 19:05:49 +0900830 initializeTenantPipeline(network, node, false);
Jian Li8f944d42021-03-23 00:43:29 +0900831 }
832 });
833
834 securityGroupService.securityGroups().forEach(securityGroup ->
835 securityGroup.rules().forEach(this::securityGroupRuleRemoved));
836 }
837
838 log.info("Reset security group info " +
839 (getUseSecurityGroupFlag() ? "with" : "without") + " Security Group");
840 }
841
842 private void securityGroupRuleAdded(KubevirtSecurityGroupRule sgRule) {
843 portService.ports().stream()
844 .filter(port -> port.securityGroups().contains(sgRule.securityGroupId()))
845 .forEach(port -> {
846 updateSecurityGroupRule(port, sgRule, true);
847 log.info("Applied security group rule {} to port {}",
848 sgRule.id(), port.macAddress());
849 });
850 }
851
852 private void securityGroupRuleRemoved(KubevirtSecurityGroupRule sgRule) {
853 portService.ports().stream()
854 .filter(port -> port.securityGroups().contains(sgRule.securityGroupId()))
855 .forEach(port -> {
856 updateSecurityGroupRule(port, sgRule, false);
857 log.info("Removed security group rule {} from port {}",
858 sgRule.id(), port.macAddress());
859 });
860 }
861
862 private class InternalKubevirtPortListener implements KubevirtPortListener {
863
864 @Override
865 public boolean isRelevant(KubevirtPortEvent event) {
866 return getUseSecurityGroupFlag();
867 }
868
869 private boolean isRelevantHelper(KubevirtPortEvent event) {
870 DeviceId deviceId = event.subject().deviceId();
871
872 if (deviceId == null) {
873 return false;
874 }
875
876 return mastershipService.isLocalMaster(deviceId);
877 }
878
879 @Override
880 public void event(KubevirtPortEvent event) {
881 log.debug("security group event received {}", event);
882
883 switch (event.type()) {
884 case KUBEVIRT_PORT_SECURITY_GROUP_ADDED:
885 eventExecutor.execute(() -> processPortSgAdd(event));
886 break;
887 case KUBEVIRT_PORT_SECURITY_GROUP_REMOVED:
888 eventExecutor.execute(() -> processPortSgRemove(event));
889 break;
890 case KUBEVIRT_PORT_REMOVED:
891 eventExecutor.execute(() -> processPortRemove(event));
892 break;
893 case KUBEVIRT_PORT_DEVICE_ADDED:
894 eventExecutor.execute(() -> processPortDeviceAdded(event));
895 break;
896 default:
897 // do nothing for the other events
898 break;
899 }
900 }
901
902 private void processPortSgAdd(KubevirtPortEvent event) {
903 if (!isRelevantHelper(event)) {
904 return;
905 }
906
907 if (event.securityGroupId() == null ||
908 securityGroupService.securityGroup(event.securityGroupId()) == null) {
909 return;
910 }
911
912 KubevirtPort port = event.subject();
913 KubevirtSecurityGroup sg = securityGroupService.securityGroup(event.securityGroupId());
914
915 sg.rules().forEach(sgRule -> {
916 updateSecurityGroupRule(port, sgRule, true);
917 });
918 log.info("Added security group {} to port {}",
919 event.securityGroupId(), event.subject().macAddress());
920 }
921
922 private void processPortSgRemove(KubevirtPortEvent event) {
923 if (!isRelevantHelper(event)) {
924 return;
925 }
926
927 if (event.securityGroupId() == null ||
928 securityGroupService.securityGroup(event.securityGroupId()) == null) {
929 return;
930 }
931
932 KubevirtPort port = event.subject();
933 KubevirtSecurityGroup sg = securityGroupService.securityGroup(event.securityGroupId());
934
935 sg.rules().forEach(sgRule -> {
936 updateSecurityGroupRule(port, sgRule, false);
937 });
938 log.info("Removed security group {} from port {}",
939 event.securityGroupId(), event.subject().macAddress());
940 }
941
942 private void processPortRemove(KubevirtPortEvent event) {
943 if (!isRelevantHelper(event)) {
944 return;
945 }
946
947 KubevirtPort port = event.subject();
948 for (String sgStr : port.securityGroups()) {
949 KubevirtSecurityGroup sg = securityGroupService.securityGroup(sgStr);
950 sg.rules().forEach(sgRule -> {
951 updateSecurityGroupRule(port, sgRule, false);
952 });
953 log.info("Removed security group {} from port {}",
954 sgStr, event.subject().macAddress());
955 }
956 }
957
958 private void processPortDeviceAdded(KubevirtPortEvent event) {
959 if (!isRelevantHelper(event)) {
960 return;
961 }
962
963 for (String sgId : event.subject().securityGroups()) {
964 KubevirtSecurityGroup sg = securityGroupService.securityGroup(sgId);
965
966 sg.rules().forEach(sgRule -> {
967 updateSecurityGroupRule(event.subject(), sgRule, true);
968 });
969 log.info("Added security group {} to port {}",
Jian Lif89d9602021-04-27 19:05:49 +0900970 sg.id(), event.subject().macAddress());
Jian Li8f944d42021-03-23 00:43:29 +0900971 }
972 }
973 }
974
975 private class InternalNetworkListener implements KubevirtNetworkListener {
976
977 private boolean isRelevantHelper() {
978 return Objects.equals(localNodeId, leadershipService.getLeader(appId.name()));
979 }
980
981 @Override
982 public void event(KubevirtNetworkEvent event) {
983 switch (event.type()) {
984 case KUBEVIRT_NETWORK_CREATED:
985 eventExecutor.execute(() -> processNetworkCreation(event.subject()));
986 break;
987 case KUBEVIRT_NETWORK_REMOVED:
988 case KUBEVIRT_NETWORK_UPDATED:
989 default:
990 // do thing
991 break;
992 }
993 }
994
995 private void processNetworkCreation(KubevirtNetwork network) {
996 if (!isRelevantHelper()) {
997 return;
998 }
999
1000 Set<KubevirtNode> nodes = nodeService.completeNodes(WORKER);
1001
1002 if (nodes.size() > 0) {
1003 // now we wait 5s for all tenant bridges are created,
1004 // FIXME: we need to fina a better way to wait all tenant bridges
1005 // are created before installing default security group rules
1006 try {
1007 sleep(SLEEP_MS);
1008 } catch (InterruptedException e) {
1009 log.error("Failed to install security group default rules.");
1010 }
1011
1012 for (KubevirtNode node : nodes) {
Jian Lif89d9602021-04-27 19:05:49 +09001013 initializeTenantPipeline(network, node, true);
Jian Li8f944d42021-03-23 00:43:29 +09001014 }
1015 }
1016 }
1017 }
1018
1019 private class InternalSecurityGroupListener implements KubevirtSecurityGroupListener {
1020
1021 @Override
1022 public boolean isRelevant(KubevirtSecurityGroupEvent event) {
1023 return getUseSecurityGroupFlag();
1024 }
1025
1026 private boolean isRelevantHelper() {
1027 return Objects.equals(localNodeId, leadershipService.getLeader(appId.name()));
1028 }
1029
1030 @Override
1031 public void event(KubevirtSecurityGroupEvent event) {
1032 switch (event.type()) {
1033 case KUBEVIRT_SECURITY_GROUP_RULE_CREATED:
1034 eventExecutor.execute(() -> processSgRuleCreate(event));
1035 break;
1036 case KUBEVIRT_SECURITY_GROUP_RULE_REMOVED:
1037 eventExecutor.execute(() -> processSgRuleRemove(event));
1038 break;
1039 default:
1040 // do nothing
1041 break;
1042 }
1043 }
1044
1045 private void processSgRuleCreate(KubevirtSecurityGroupEvent event) {
1046 if (!isRelevantHelper()) {
1047 return;
1048 }
1049
1050 KubevirtSecurityGroupRule sgRuleToAdd = event.rule();
1051 securityGroupRuleAdded(sgRuleToAdd);
1052 log.info("Applied new security group rule {} to ports", sgRuleToAdd.id());
1053 }
1054
1055 private void processSgRuleRemove(KubevirtSecurityGroupEvent event) {
1056 if (!isRelevantHelper()) {
1057 return;
1058 }
1059
1060 KubevirtSecurityGroupRule sgRuleToRemove = event.rule();
1061 securityGroupRuleRemoved(sgRuleToRemove);
1062 log.info("Removed security group rule {} from ports", sgRuleToRemove.id());
1063 }
1064 }
1065
1066 private class InternalNodeListener implements KubevirtNodeListener {
1067
1068 @Override
1069 public boolean isRelevant(KubevirtNodeEvent event) {
1070 return event.subject().type() == WORKER;
1071 }
1072
1073 private boolean isRelevantHelper() {
1074 return Objects.equals(localNodeId, leadershipService.getLeader(appId.name()));
1075 }
1076
1077 @Override
1078 public void event(KubevirtNodeEvent event) {
1079 switch (event.type()) {
1080 case KUBEVIRT_NODE_COMPLETE:
1081 eventExecutor.execute(() -> processNodeComplete(event.subject()));
1082 break;
1083 default:
1084 break;
1085 }
1086 }
1087
1088 private void processNodeComplete(KubevirtNode node) {
1089 if (!isRelevantHelper()) {
1090 return;
1091 }
1092
Jian Lif89d9602021-04-27 19:05:49 +09001093 // FIXME: we wait all port get its deviceId updated
1094 try {
1095 sleep(SLEEP_MS);
1096 } catch (InterruptedException e) {
1097 log.error("Failed to install security group default rules.");
1098 }
1099
Jian Li8f944d42021-03-23 00:43:29 +09001100 resetSecurityGroupRulesByNode(node);
1101 }
1102
1103 private void resetSecurityGroupRulesByNode(KubevirtNode node) {
1104 if (getUseSecurityGroupFlag()) {
Jian Lif89d9602021-04-27 19:05:49 +09001105 initializeProviderPipeline(node, true);
Jian Li8f944d42021-03-23 00:43:29 +09001106
1107 for (KubevirtNetwork network : networkService.tenantNetworks()) {
Jian Lif89d9602021-04-27 19:05:49 +09001108 initializeTenantPipeline(network, node, true);
Jian Li8f944d42021-03-23 00:43:29 +09001109 }
1110
1111 securityGroupService.securityGroups().forEach(securityGroup ->
1112 securityGroup.rules().forEach(
1113 KubevirtSecurityGroupHandler.this::securityGroupRuleAdded));
1114 } else {
Jian Lif89d9602021-04-27 19:05:49 +09001115 initializeProviderPipeline(node, false);
Jian Li8f944d42021-03-23 00:43:29 +09001116
1117 for (KubevirtNetwork network : networkService.tenantNetworks()) {
Jian Lif89d9602021-04-27 19:05:49 +09001118 initializeTenantPipeline(network, node, false);
Jian Li8f944d42021-03-23 00:43:29 +09001119 }
1120
1121 securityGroupService.securityGroups().forEach(securityGroup ->
1122 securityGroup.rules().forEach(
1123 KubevirtSecurityGroupHandler.this::securityGroupRuleRemoved));
1124 }
1125
1126 log.info("Reset security group info " +
1127 (getUseSecurityGroupFlag() ? "with" : "without") + " Security Group");
1128 }
1129 }
1130}