blob: c5513690ad1c377a05c582f65506198383576395 [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
Jian Li8f944d42021-03-23 00:43:29 +090081import static java.util.concurrent.Executors.newSingleThreadExecutor;
82import static org.onlab.util.Tools.groupedThreads;
Jian Lif89d9602021-04-27 19:05:49 +090083import static org.onosproject.kubevirtnetworking.api.Constants.ACL_CT_TABLE;
84import static org.onosproject.kubevirtnetworking.api.Constants.ACL_EGRESS_TABLE;
85import static org.onosproject.kubevirtnetworking.api.Constants.ACL_INGRESS_TABLE;
86import static org.onosproject.kubevirtnetworking.api.Constants.ACL_RECIRC_TABLE;
Jian Li8f944d42021-03-23 00:43:29 +090087import static org.onosproject.kubevirtnetworking.api.Constants.ERROR_TABLE;
Jian Lif89d9602021-04-27 19:05:49 +090088import static org.onosproject.kubevirtnetworking.api.Constants.FORWARDING_TABLE;
Jian Li8f944d42021-03-23 00:43:29 +090089import static org.onosproject.kubevirtnetworking.api.Constants.KUBEVIRT_NETWORKING_APP_ID;
90import static org.onosproject.kubevirtnetworking.api.Constants.PRIORITY_ACL_INGRESS_RULE;
91import static org.onosproject.kubevirtnetworking.api.Constants.PRIORITY_ACL_RULE;
92import static org.onosproject.kubevirtnetworking.api.Constants.PRIORITY_CT_DROP_RULE;
93import static org.onosproject.kubevirtnetworking.api.Constants.PRIORITY_CT_HOOK_RULE;
94import static org.onosproject.kubevirtnetworking.api.Constants.PRIORITY_CT_RULE;
95import static org.onosproject.kubevirtnetworking.api.Constants.TENANT_ACL_CT_TABLE;
96import static org.onosproject.kubevirtnetworking.api.Constants.TENANT_ACL_EGRESS_TABLE;
97import static org.onosproject.kubevirtnetworking.api.Constants.TENANT_ACL_INGRESS_TABLE;
98import static org.onosproject.kubevirtnetworking.api.Constants.TENANT_ACL_RECIRC_TABLE;
99import static org.onosproject.kubevirtnetworking.api.Constants.TENANT_FORWARDING_TABLE;
Jian Lif89d9602021-04-27 19:05:49 +0900100import static org.onosproject.kubevirtnetworking.api.KubevirtNetwork.Type.FLAT;
Jian Li8f944d42021-03-23 00:43:29 +0900101import static org.onosproject.kubevirtnetworking.api.KubevirtNetwork.Type.VLAN;
Jian Li8f944d42021-03-23 00:43:29 +0900102import static org.onosproject.kubevirtnetworking.impl.OsgiPropertyConstants.USE_SECURITY_GROUP;
103import static org.onosproject.kubevirtnetworking.impl.OsgiPropertyConstants.USE_SECURITY_GROUP_DEFAULT;
104import static org.onosproject.kubevirtnetworking.util.KubevirtNetworkingUtil.getPropertyValueAsBoolean;
Jian Li0c656f02021-06-07 13:32:39 +0900105import static org.onosproject.kubevirtnetworking.util.KubevirtNetworkingUtil.waitFor;
Jian Li8f944d42021-03-23 00:43:29 +0900106import 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
Jian Li8f944d42021-03-23 00:43:29 +0900157 /** Apply EdgeStack security group rule for VM traffic. */
158 private boolean useSecurityGroup = USE_SECURITY_GROUP_DEFAULT;
159
160 @Reference(cardinality = ReferenceCardinality.MANDATORY)
161 protected CoreService coreService;
162
163 @Reference(cardinality = ReferenceCardinality.MANDATORY)
164 protected MastershipService mastershipService;
165
166 @Reference(cardinality = ReferenceCardinality.MANDATORY)
167 protected DriverService driverService;
168
169 @Reference(cardinality = ReferenceCardinality.MANDATORY)
170 protected DeviceService deviceService;
171
172 @Reference(cardinality = ReferenceCardinality.MANDATORY)
173 protected LeadershipService leadershipService;
174
175 @Reference(cardinality = ReferenceCardinality.MANDATORY)
176 protected ClusterService clusterService;
177
178 @Reference(cardinality = ReferenceCardinality.MANDATORY)
179 protected StorageService storageService;
180
181 @Reference(cardinality = ReferenceCardinality.MANDATORY)
182 protected ComponentConfigService configService;
183
184 @Reference(cardinality = ReferenceCardinality.MANDATORY)
185 protected KubevirtNodeService nodeService;
186
187 @Reference(cardinality = ReferenceCardinality.MANDATORY)
188 protected KubevirtNetworkService networkService;
189
190 @Reference(cardinality = ReferenceCardinality.MANDATORY)
191 protected KubevirtPortService portService;
192
193 @Reference(cardinality = ReferenceCardinality.MANDATORY)
194 protected KubevirtFlowRuleService flowRuleService;
195
196 @Reference(cardinality = ReferenceCardinality.MANDATORY)
197 protected KubevirtSecurityGroupService securityGroupService;
198
199 private final KubevirtPortListener portListener =
200 new InternalKubevirtPortListener();
201 private final KubevirtSecurityGroupListener securityGroupListener =
202 new InternalSecurityGroupListener();
203 private final KubevirtNodeListener nodeListener =
204 new InternalNodeListener();
205 private final KubevirtNetworkListener networkListener =
206 new InternalNetworkListener();
207
208 private final ExecutorService eventExecutor = newSingleThreadExecutor(
209 groupedThreads(this.getClass().getSimpleName(), "event-handler"));
210
211 private ApplicationId appId;
212 private NodeId localNodeId;
213
214 @Activate
215 protected void activate() {
216 appId = coreService.registerApplication(KUBEVIRT_NETWORKING_APP_ID);
217 localNodeId = clusterService.getLocalNode().id();
218 securityGroupService.addListener(securityGroupListener);
219 portService.addListener(portListener);
220 networkService.addListener(networkListener);
221 configService.registerProperties(getClass());
222 nodeService.addListener(nodeListener);
223
224 log.info("Started");
225 }
226
227 @Deactivate
228 protected void deactivate() {
229 securityGroupService.removeListener(securityGroupListener);
230 portService.removeListener(portListener);
231 configService.unregisterProperties(getClass(), false);
232 nodeService.removeListener(nodeListener);
233 networkService.removeListener(networkListener);
234 eventExecutor.shutdown();
235
236 log.info("Stopped");
237 }
238
239 @Modified
240 protected void modified(ComponentContext context) {
241 Dictionary<?, ?> properties = context.getProperties();
242 Boolean flag;
243
244 flag = Tools.isPropertyEnabled(properties, USE_SECURITY_GROUP);
245 if (flag == null) {
246 log.info("useSecurityGroup is not configured, " +
247 "using current value of {}", useSecurityGroup);
248 } else {
249 useSecurityGroup = flag;
250 log.info("Configured. useSecurityGroup is {}",
251 useSecurityGroup ? "enabled" : "disabled");
252 }
253
254 securityGroupService.setSecurityGroupEnabled(useSecurityGroup);
255 resetSecurityGroupRules();
256 }
257
258 private boolean getUseSecurityGroupFlag() {
259 Set<ConfigProperty> properties =
260 configService.getProperties(getClass().getName());
261 return getPropertyValueAsBoolean(properties, USE_SECURITY_GROUP);
262 }
263
Jian Lif89d9602021-04-27 19:05:49 +0900264 private void initializeProviderConnTrackTable(DeviceId deviceId, boolean install) {
265 initializeConnTrackTable(deviceId, ACL_CT_TABLE, FORWARDING_TABLE, install);
266 }
267
268 private void initializeTenantConnTrackTable(DeviceId deviceId, boolean install) {
269 initializeConnTrackTable(deviceId, TENANT_ACL_CT_TABLE, TENANT_FORWARDING_TABLE, install);
270 }
271
272 private void initializeConnTrackTable(DeviceId deviceId, int ctTable,
273 int forwardTable, boolean install) {
Jian Li8f944d42021-03-23 00:43:29 +0900274
275 // table={ACL_INGRESS_TABLE(44)},ip,ct_state=-trk, actions=ct(table:{ACL_CT_TABLE(45)})
276 long ctState = computeCtStateFlag(false, false, false);
277 long ctMask = computeCtMaskFlag(true, false, false);
Jian Lif89d9602021-04-27 19:05:49 +0900278 setConnTrackRule(deviceId, ctState, ctMask, CT_NO_COMMIT, (short) ctTable,
Jian Li8f944d42021-03-23 00:43:29 +0900279 ACTION_NONE, PRIORITY_CT_HOOK_RULE, install);
280
281 //table={ACL_CT_TABLE(45)},ip,nw_dst=10.10.0.2,ct_state=+trk+est,action=goto_table:{NORMAL_TABLE(80)}
282 ctState = computeCtStateFlag(true, false, true);
283 ctMask = computeCtMaskFlag(true, false, true);
284 setConnTrackRule(deviceId, ctState, ctMask, CT_NO_COMMIT, CT_NO_RECIRC,
Jian Lif89d9602021-04-27 19:05:49 +0900285 forwardTable, PRIORITY_CT_RULE, install);
Jian Li8f944d42021-03-23 00:43:29 +0900286
287 //table={ACL_CT_TABLE(45)},ip,nw_dst=10.10.0.2,ct_state=+trk+new,action=drop
288 ctState = computeCtStateFlag(true, true, false);
289 ctMask = computeCtMaskFlag(true, true, false);
290 setConnTrackRule(deviceId, ctState, ctMask, CT_NO_COMMIT, CT_NO_RECIRC,
291 ACTION_DROP, PRIORITY_CT_DROP_RULE, install);
292 }
293
Jian Li1bc914c2021-06-08 14:09:14 +0900294 private void initializeProviderAclTable(DeviceId deviceId, boolean install) {
295 initializeAclTable(deviceId, ACL_RECIRC_TABLE, PortNumber.NORMAL, install);
Jian Lif89d9602021-04-27 19:05:49 +0900296 }
297
298 private void initializeTenantAclTable(KubevirtNetwork network,
299 DeviceId deviceId, boolean install) {
300 PortNumber patchPort = network.tenantToTunnelPort(deviceId);
301 initializeAclTable(deviceId, TENANT_ACL_RECIRC_TABLE, patchPort, install);
302 }
303
304 private void initializeAclTable(DeviceId deviceId, int recircTable,
305 PortNumber outport, boolean install) {
Jian Li8f944d42021-03-23 00:43:29 +0900306
307 ExtensionTreatment ctTreatment =
308 niciraConnTrackTreatmentBuilder(driverService, deviceId)
309 .commit(true)
310 .build();
311
312 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
313 sBuilder.matchEthType(Ethernet.TYPE_IPV4);
314
315 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
316 tBuilder.extension(ctTreatment, deviceId)
Jian Lif89d9602021-04-27 19:05:49 +0900317 .setOutput(outport);
Jian Li8f944d42021-03-23 00:43:29 +0900318
319 flowRuleService.setRule(appId,
320 deviceId,
321 sBuilder.build(),
322 tBuilder.build(),
323 PRIORITY_ACL_INGRESS_RULE,
Jian Lif89d9602021-04-27 19:05:49 +0900324 recircTable,
Jian Li8f944d42021-03-23 00:43:29 +0900325 install);
326 }
327
Jian Lif89d9602021-04-27 19:05:49 +0900328 private void initializeProviderEgressTable(DeviceId deviceId, boolean install) {
329 initializeEgressTable(deviceId, ACL_EGRESS_TABLE, FORWARDING_TABLE, install);
330 }
331
332 private void initializeTenantEgressTable(DeviceId deviceId, boolean install) {
333 initializeEgressTable(deviceId, TENANT_ACL_EGRESS_TABLE, TENANT_FORWARDING_TABLE, install);
334 }
335
336 private void initializeEgressTable(DeviceId deviceId, int egressTable,
337 int forwardTable, boolean install) {
Jian Li8f944d42021-03-23 00:43:29 +0900338 if (install) {
339 flowRuleService.setUpTableMissEntry(deviceId, TENANT_ACL_EGRESS_TABLE);
340 } else {
Jian Lif89d9602021-04-27 19:05:49 +0900341 flowRuleService.connectTables(deviceId, egressTable, forwardTable);
Jian Li8f944d42021-03-23 00:43:29 +0900342 }
343 }
344
Jian Lif89d9602021-04-27 19:05:49 +0900345 private void initializeProviderIngressTable(DeviceId deviceId, boolean install) {
346 initializeIngressTable(deviceId, ACL_INGRESS_TABLE, FORWARDING_TABLE, install);
347 }
348
349 private void initializeTenantIngressTable(DeviceId deviceId, boolean install) {
350 initializeIngressTable(deviceId, TENANT_ACL_INGRESS_TABLE, TENANT_FORWARDING_TABLE, install);
351 }
352
353 private void initializeIngressTable(DeviceId deviceId, int ingressTable,
354 int forwardTable, boolean install) {
Jian Li8f944d42021-03-23 00:43:29 +0900355 if (install) {
Jian Lif89d9602021-04-27 19:05:49 +0900356 flowRuleService.setUpTableMissEntry(deviceId, ingressTable);
Jian Li8f944d42021-03-23 00:43:29 +0900357 } else {
Jian Lif89d9602021-04-27 19:05:49 +0900358 flowRuleService.connectTables(deviceId, ingressTable, forwardTable);
Jian Li8f944d42021-03-23 00:43:29 +0900359 }
360 }
361
Jian Lif89d9602021-04-27 19:05:49 +0900362 private void initializeProviderPipeline(KubevirtNode node, boolean install) {
363 initializeProviderIngressTable(node.intgBridge(), install);
364 initializeProviderEgressTable(node.intgBridge(), install);
365 initializeProviderConnTrackTable(node.intgBridge(), install);
Jian Li1bc914c2021-06-08 14:09:14 +0900366 initializeProviderAclTable(node.intgBridge(), install);
Jian Lif89d9602021-04-27 19:05:49 +0900367 }
368
369 private void initializeTenantPipeline(KubevirtNetwork network,
370 KubevirtNode node, boolean install) {
371 DeviceId deviceId = network.tenantDeviceId(node.hostname());
372 if (deviceId == null) {
373 return;
374 }
Jian Li567b25c2021-05-27 15:17:59 +0900375
376 // we check whether the given device is available from the store
377 // if not we will wait until the device is eventually created
378 // FIXME: it would be better to listen to device event to perform
379 // pipeline initialization rather on network events.
380 while (true) {
381 if (deviceService.getDevice(deviceId) != null) {
382 break;
383 } else {
Jian Li0c656f02021-06-07 13:32:39 +0900384 waitFor(5);
Jian Li567b25c2021-05-27 15:17:59 +0900385 }
386 }
387
Jian Lif89d9602021-04-27 19:05:49 +0900388 initializeTenantIngressTable(deviceId, install);
389 initializeTenantEgressTable(deviceId, install);
390 initializeTenantConnTrackTable(deviceId, install);
391 initializeTenantAclTable(network, deviceId, install);
392 }
393
Jian Li8f944d42021-03-23 00:43:29 +0900394 private void updateSecurityGroupRule(KubevirtPort port,
395 KubevirtSecurityGroupRule sgRule, boolean install) {
396
397 if (port == null || sgRule == null) {
398 return;
399 }
400
401 if (sgRule.remoteGroupId() != null && !sgRule.remoteGroupId().isEmpty()) {
402 getRemotePorts(port, sgRule.remoteGroupId())
403 .forEach(rPort -> {
404 populateSecurityGroupRule(sgRule, port,
405 rPort.ipAddress().toIpPrefix(), install);
406 populateSecurityGroupRule(sgRule, rPort,
407 port.ipAddress().toIpPrefix(), install);
408
409 KubevirtSecurityGroupRule rSgRule = sgRule.updateDirection(
410 sgRule.direction().equalsIgnoreCase(EGRESS) ? INGRESS : EGRESS);
411 populateSecurityGroupRule(rSgRule, port,
412 rPort.ipAddress().toIpPrefix(), install);
413 populateSecurityGroupRule(rSgRule, rPort,
414 port.ipAddress().toIpPrefix(), install);
415 });
416 } else {
417 populateSecurityGroupRule(sgRule, port,
418 sgRule.remoteIpPrefix() == null ? IP_PREFIX_ANY :
419 sgRule.remoteIpPrefix(), install);
420 }
421 }
422
423 private boolean checkProtocol(String protocol) {
424 if (protocol == null) {
425 log.debug("No protocol was specified, use default IP(v4/v6) protocol.");
426 return true;
427 } else {
428 String protocolUpper = protocol.toUpperCase();
429 if (protocolUpper.equals(PROTO_TCP) ||
430 protocolUpper.equals(PROTO_UDP) ||
431 protocolUpper.equals(PROTO_ICMP) ||
432 protocolUpper.equals(PROTO_SCTP) ||
433 protocolUpper.equals(PROTO_ANY) ||
434 protocol.equals(PROTO_TCP_NUM) ||
435 protocol.equals(PROTO_UDP_NUM) ||
436 protocol.equals(PROTO_ICMP_NUM) ||
437 protocol.equals(PROTO_SCTP_NUM) ||
438 protocol.equals(PROTO_ANY_NUM)) {
439 return true;
440 } else {
441 log.error("Unsupported protocol {}, we only support " +
442 "TCP/UDP/ICMP/SCTP protocols.", protocol);
443 return false;
444 }
445 }
446 }
447
448 private void populateSecurityGroupRule(KubevirtSecurityGroupRule sgRule,
449 KubevirtPort port,
450 IpPrefix remoteIp,
451 boolean install) {
452 if (!checkProtocol(sgRule.protocol())) {
453 return;
454 }
455
456 DeviceId deviceId = port.isTenant() ? port.tenantDeviceId() : port.deviceId();
457
Jian Lif89d9602021-04-27 19:05:49 +0900458 Set<TrafficSelector> ctSelectors = buildSelectors(
459 sgRule,
Jian Li8f944d42021-03-23 00:43:29 +0900460 Ip4Address.valueOf(port.ipAddress().toInetAddress()),
Jian Lif89d9602021-04-27 19:05:49 +0900461 port.macAddress(),
Jian Li8f944d42021-03-23 00:43:29 +0900462 remoteIp, port.networkId());
Jian Lif89d9602021-04-27 19:05:49 +0900463 if (ctSelectors == null || ctSelectors.isEmpty()) {
Jian Li8f944d42021-03-23 00:43:29 +0900464 return;
465 }
466
467 // if the device is not available we do not perform any action
468 if (deviceId == null || !deviceService.isAvailable(deviceId)) {
469 return;
470 }
471
472 // XXX All egress traffic needs to go through connection tracking module,
473 // which might hurt its performance.
474 ExtensionTreatment ctTreatment =
475 niciraConnTrackTreatmentBuilder(driverService, deviceId)
476 .commit(true)
477 .build();
478
479 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
480
Jian Lif89d9602021-04-27 19:05:49 +0900481 KubevirtNetwork net = networkService.network(port.networkId());
482
Jian Li8f944d42021-03-23 00:43:29 +0900483 int aclTable;
484 if (sgRule.direction().equalsIgnoreCase(EGRESS)) {
Jian Lif89d9602021-04-27 19:05:49 +0900485
486 if (net.type() == FLAT || net.type() == VLAN) {
487 aclTable = ACL_EGRESS_TABLE;
488 } else {
489 aclTable = TENANT_ACL_EGRESS_TABLE;
490 }
491
Jian Li8f944d42021-03-23 00:43:29 +0900492 tBuilder.transition(TENANT_ACL_RECIRC_TABLE);
493 } else {
Jian Lif89d9602021-04-27 19:05:49 +0900494
495 if (net.type() == FLAT || net.type() == VLAN) {
496 aclTable = ACL_INGRESS_TABLE;
497 } else {
498 aclTable = TENANT_ACL_INGRESS_TABLE;
499 }
500
Jian Li8f944d42021-03-23 00:43:29 +0900501 tBuilder.extension(ctTreatment, deviceId)
502 .transition(TENANT_FORWARDING_TABLE);
503 }
504
505 int finalAclTable = aclTable;
Jian Lif89d9602021-04-27 19:05:49 +0900506 ctSelectors.forEach(selector -> {
Jian Li8f944d42021-03-23 00:43:29 +0900507 flowRuleService.setRule(appId,
508 deviceId,
509 selector, tBuilder.build(),
510 PRIORITY_ACL_RULE,
511 finalAclTable,
512 install);
513 });
Jian Lif89d9602021-04-27 19:05:49 +0900514
515 TrafficSelector tSelector = DefaultTrafficSelector.builder()
516 .matchEthType(Ethernet.TYPE_IPV4)
517 .matchEthDst(port.macAddress())
518 .matchIPDst(IpPrefix.valueOf(port.ipAddress(), 32))
519 .build();
520 TrafficTreatment tTreatment = DefaultTrafficTreatment.builder()
521 .transition(TENANT_ACL_INGRESS_TABLE)
522 .build();
523
524 flowRuleService.setRule(appId,
525 deviceId,
526 tSelector,
527 tTreatment,
528 PRIORITY_ACL_RULE,
529 TENANT_ACL_RECIRC_TABLE,
530 install);
Jian Li8f944d42021-03-23 00:43:29 +0900531 }
532
533 /**
534 * Sets connection tracking rule using OVS extension commands.
535 * It is not so graceful, but I don't want to make it more general because
536 * it is going to be used only here.
537 * The following is the usage of the function.
538 *
539 * @param deviceId Device ID
540 * @param ctState ctState: please use RulePopulatorUtil.computeCtStateFlag()
541 * to build the value
542 * @param ctMask crMask: please use RulePopulatorUtil.computeCtMaskFlag()
543 * to build the value
544 * @param commit CT_COMMIT for commit action, CT_NO_COMMIT otherwise
545 * @param recircTable table number for recirculation after CT actions.
546 * CT_NO_RECIRC with no recirculation
547 * @param action Additional actions. ACTION_DROP, ACTION_NONE,
548 * GOTO_XXX_TABLE are supported.
549 * @param priority priority value for the rule
550 * @param install true for insertion, false for removal
551 */
552 private void setConnTrackRule(DeviceId deviceId, long ctState, long ctMask,
553 int commit, short recircTable,
554 int action, int priority, boolean install) {
555
556 ExtensionSelector esCtSate = RulePopulatorUtil
557 .buildCtExtensionSelector(driverService, deviceId, ctState, ctMask);
558 TrafficSelector selector = DefaultTrafficSelector.builder()
559 .extension(esCtSate, deviceId)
560 .matchEthType(Ethernet.TYPE_IPV4)
561 .build();
562
563 TrafficTreatment.Builder tb = DefaultTrafficTreatment.builder();
564
565 if (commit == CT_COMMIT || recircTable > 0) {
566 RulePopulatorUtil.NiciraConnTrackTreatmentBuilder natTreatmentBuilder =
567 niciraConnTrackTreatmentBuilder(driverService, deviceId);
568 natTreatmentBuilder.natAction(false);
569 natTreatmentBuilder.commit(commit == CT_COMMIT);
570 if (recircTable > 0) {
571 natTreatmentBuilder.table(recircTable);
572 }
573 tb.extension(natTreatmentBuilder.build(), deviceId);
574 } else if (action == ACTION_DROP) {
575 tb.drop();
576 }
577
578 if (action != ACTION_NONE && action != ACTION_DROP) {
579 tb.transition(action);
580 }
581
582 int tableType = ERROR_TABLE;
583 if (priority == PRIORITY_CT_RULE || priority == PRIORITY_CT_DROP_RULE) {
584 tableType = TENANT_ACL_CT_TABLE;
585 } else if (priority == PRIORITY_CT_HOOK_RULE) {
586 tableType = TENANT_ACL_INGRESS_TABLE;
587 } else {
588 log.error("Cannot an appropriate table for the conn track rule.");
589 }
590
591 flowRuleService.setRule(
592 appId,
593 deviceId,
594 selector,
595 tb.build(),
596 priority,
597 tableType,
598 install);
599 }
600
601 /**
602 * Returns a set of host IP addresses engaged with supplied security group ID.
603 * It only searches a VM in the same tenant boundary.
604 *
605 * @param srcPort edgestack port
606 * @param sgId security group id
607 * @return set of ip addresses
608 */
609 private Set<KubevirtPort> getRemotePorts(KubevirtPort srcPort, String sgId) {
610 return portService.ports().stream()
611 .filter(port -> !port.macAddress().equals(srcPort.macAddress()))
612 .filter(port -> port.securityGroups().contains(sgId))
613 .filter(port -> port.ipAddress() != null)
614 .collect(Collectors.toSet());
615 }
616
617 private Set<TrafficSelector> buildSelectors(KubevirtSecurityGroupRule sgRule,
618 Ip4Address vmIp,
Jian Lif89d9602021-04-27 19:05:49 +0900619 MacAddress vmMac,
Jian Li8f944d42021-03-23 00:43:29 +0900620 IpPrefix remoteIp,
621 String netId) {
622 if (remoteIp != null && remoteIp.equals(IpPrefix.valueOf(vmIp, VM_IP_PREFIX))) {
623 // do nothing if the remote IP is my IP
624 return null;
625 }
626
627 Set<TrafficSelector> selectorSet = Sets.newHashSet();
628
629 if (sgRule.portRangeMax() != null && sgRule.portRangeMin() != null &&
630 sgRule.portRangeMin() < sgRule.portRangeMax()) {
631 Map<TpPort, TpPort> portRangeMatchMap =
632 buildPortRangeMatches(sgRule.portRangeMin(),
633 sgRule.portRangeMax());
634 portRangeMatchMap.forEach((key, value) -> {
635
636 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
Jian Lif89d9602021-04-27 19:05:49 +0900637 buildMatches(sBuilder, sgRule, vmIp, vmMac, remoteIp);
Jian Li8f944d42021-03-23 00:43:29 +0900638
639 if (sgRule.protocol().equalsIgnoreCase(PROTO_TCP) ||
640 sgRule.protocol().equals(PROTO_TCP_NUM)) {
641 if (sgRule.direction().equalsIgnoreCase(EGRESS)) {
642 if (value.toInt() == TpPort.MAX_PORT) {
643 sBuilder.matchTcpSrc(key);
644 } else {
645 sBuilder.matchTcpSrcMasked(key, value);
646 }
647 } else {
648 if (value.toInt() == TpPort.MAX_PORT) {
649 sBuilder.matchTcpDst(key);
650 } else {
651 sBuilder.matchTcpDstMasked(key, value);
652 }
653 }
654 } else if (sgRule.protocol().equalsIgnoreCase(PROTO_UDP) ||
655 sgRule.protocol().equals(PROTO_UDP_NUM)) {
656 if (sgRule.direction().equalsIgnoreCase(EGRESS)) {
657 if (value.toInt() == TpPort.MAX_PORT) {
658 sBuilder.matchUdpSrc(key);
659 } else {
660 sBuilder.matchUdpSrcMasked(key, value);
661 }
662 } else {
663 if (value.toInt() == TpPort.MAX_PORT) {
664 sBuilder.matchUdpDst(key);
665 } else {
666 sBuilder.matchUdpDstMasked(key, value);
667 }
668 }
669 } else if (sgRule.protocol().equalsIgnoreCase(PROTO_SCTP) ||
670 sgRule.protocol().equals(PROTO_SCTP_NUM)) {
671 if (sgRule.direction().equalsIgnoreCase(EGRESS)) {
672 if (value.toInt() == TpPort.MAX_PORT) {
673 sBuilder.matchSctpSrc(key);
674 } else {
675 sBuilder.matchSctpSrcMasked(key, value);
676 }
677 } else {
678 if (value.toInt() == TpPort.MAX_PORT) {
679 sBuilder.matchSctpDst(key);
680 } else {
681 sBuilder.matchSctpDstMasked(key, value);
682 }
683 }
684 }
685
686 selectorSet.add(sBuilder.build());
687 });
688 } else {
689
690 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
Jian Lif89d9602021-04-27 19:05:49 +0900691 buildMatches(sBuilder, sgRule, vmIp, vmMac, remoteIp);
Jian Li8f944d42021-03-23 00:43:29 +0900692
693 selectorSet.add(sBuilder.build());
694 }
695
696 return selectorSet;
697 }
698
699 private void buildMatches(TrafficSelector.Builder sBuilder,
700 KubevirtSecurityGroupRule sgRule, Ip4Address vmIp,
Jian Lif89d9602021-04-27 19:05:49 +0900701 MacAddress vmMac, IpPrefix remoteIp) {
Jian Li8f944d42021-03-23 00:43:29 +0900702 buildMatchEthType(sBuilder, sgRule.etherType());
Jian Lif89d9602021-04-27 19:05:49 +0900703 buildMatchDirection(sBuilder, sgRule.direction(), vmIp, vmMac);
Jian Li8f944d42021-03-23 00:43:29 +0900704 buildMatchProto(sBuilder, sgRule.protocol());
705 buildMatchPort(sBuilder, sgRule.protocol(), sgRule.direction(),
706 sgRule.portRangeMin() == null ? 0 : sgRule.portRangeMin(),
707 sgRule.portRangeMax() == null ? 0 : sgRule.portRangeMax());
708 buildMatchIcmp(sBuilder, sgRule.protocol(),
709 sgRule.portRangeMin(), sgRule.portRangeMax());
710 buildMatchRemoteIp(sBuilder, remoteIp, sgRule.direction());
711 }
712
Jian Li8f944d42021-03-23 00:43:29 +0900713 private void buildMatchDirection(TrafficSelector.Builder sBuilder,
714 String direction,
Jian Lif89d9602021-04-27 19:05:49 +0900715 Ip4Address vmIp,
716 MacAddress vmMac) {
Jian Li8f944d42021-03-23 00:43:29 +0900717 if (direction.equalsIgnoreCase(EGRESS)) {
718 sBuilder.matchIPSrc(IpPrefix.valueOf(vmIp, VM_IP_PREFIX));
Jian Lif89d9602021-04-27 19:05:49 +0900719 sBuilder.matchEthSrc(vmMac);
Jian Li8f944d42021-03-23 00:43:29 +0900720 } else {
721 sBuilder.matchIPDst(IpPrefix.valueOf(vmIp, VM_IP_PREFIX));
Jian Lif89d9602021-04-27 19:05:49 +0900722 sBuilder.matchEthDst(vmMac);
Jian Li8f944d42021-03-23 00:43:29 +0900723 }
724 }
725
726 private void buildMatchEthType(TrafficSelector.Builder sBuilder, String etherType) {
727 // Either IpSrc or IpDst (or both) is set by default, and we need to set EthType as IPv4.
728 sBuilder.matchEthType(Ethernet.TYPE_IPV4);
729 if (etherType != null && !Objects.equals(etherType, STR_NULL) &&
730 !etherType.equalsIgnoreCase(ETHTYPE_IPV4)) {
731 log.debug("EthType {} is not supported yet in Security Group", etherType);
732 }
733 }
734
735 private void buildMatchRemoteIp(TrafficSelector.Builder sBuilder,
736 IpPrefix remoteIpPrefix, String direction) {
737 if (remoteIpPrefix != null &&
738 !remoteIpPrefix.getIp4Prefix().equals(IP_PREFIX_ANY)) {
739 if (direction.equalsIgnoreCase(EGRESS)) {
740 sBuilder.matchIPDst(remoteIpPrefix);
741 } else {
742 sBuilder.matchIPSrc(remoteIpPrefix);
743 }
744 }
745 }
746
747 private void buildMatchProto(TrafficSelector.Builder sBuilder, String protocol) {
748 if (protocol != null) {
749 switch (protocol.toUpperCase()) {
750 case PROTO_ICMP:
751 case PROTO_ICMP_NUM:
752 sBuilder.matchIPProtocol(IPv4.PROTOCOL_ICMP);
753 break;
754 case PROTO_TCP:
755 case PROTO_TCP_NUM:
756 sBuilder.matchIPProtocol(IPv4.PROTOCOL_TCP);
757 break;
758 case PROTO_UDP:
759 case PROTO_UDP_NUM:
760 sBuilder.matchIPProtocol(IPv4.PROTOCOL_UDP);
761 break;
762 case PROTO_SCTP:
763 case PROTO_SCTP_NUM:
764 sBuilder.matchIPProtocol(PROTOCOL_SCTP);
765 break;
766 default:
767 break;
768 }
769 }
770 }
771
772 private void buildMatchPort(TrafficSelector.Builder sBuilder,
773 String protocol, String direction,
774 int portMin, int portMax) {
775 if (portMax > 0 && portMin == portMax) {
776 if (protocol.equalsIgnoreCase(PROTO_TCP) ||
777 protocol.equals(PROTO_TCP_NUM)) {
778 if (direction.equalsIgnoreCase(EGRESS)) {
779 sBuilder.matchTcpSrc(TpPort.tpPort(portMax));
780 } else {
781 sBuilder.matchTcpDst(TpPort.tpPort(portMax));
782 }
783 } else if (protocol.equalsIgnoreCase(PROTO_UDP) ||
784 protocol.equals(PROTO_UDP_NUM)) {
785 if (direction.equalsIgnoreCase(EGRESS)) {
786 sBuilder.matchUdpSrc(TpPort.tpPort(portMax));
787 } else {
788 sBuilder.matchUdpDst(TpPort.tpPort(portMax));
789 }
790 } else if (protocol.equalsIgnoreCase(PROTO_SCTP) ||
791 protocol.equals(PROTO_SCTP_NUM)) {
792 if (direction.equalsIgnoreCase(EGRESS)) {
793 sBuilder.matchSctpSrc(TpPort.tpPort(portMax));
794 } else {
795 sBuilder.matchSctpDst(TpPort.tpPort(portMax));
796 }
797 }
798 }
799 }
800
801 private void buildMatchIcmp(TrafficSelector.Builder sBuilder,
802 String protocol, Integer icmpCode, Integer icmpType) {
803 if (protocol != null) {
804 if (protocol.equalsIgnoreCase(PROTO_ICMP) ||
805 protocol.equals(PROTO_ICMP_NUM)) {
806 if (icmpCode != null && icmpCode >= ICMP_CODE_MIN &&
807 icmpCode <= ICMP_CODE_MAX) {
808 sBuilder.matchIcmpCode(icmpCode.byteValue());
809 }
810 if (icmpType != null && icmpType >= ICMP_TYPE_MIN &&
811 icmpType <= ICMP_TYPE_MAX) {
812 sBuilder.matchIcmpType(icmpType.byteValue());
813 }
814 }
815 }
816 }
817
818 private void resetSecurityGroupRules() {
819
820 if (getUseSecurityGroupFlag()) {
821 nodeService.completeNodes(WORKER).forEach(node -> {
Jian Lif89d9602021-04-27 19:05:49 +0900822 initializeProviderPipeline(node, true);
Jian Li8f944d42021-03-23 00:43:29 +0900823
824 for (KubevirtNetwork network : networkService.tenantNetworks()) {
Jian Lif89d9602021-04-27 19:05:49 +0900825 initializeTenantPipeline(network, node, true);
Jian Li8f944d42021-03-23 00:43:29 +0900826 }
827 });
828
829 securityGroupService.securityGroups().forEach(securityGroup ->
830 securityGroup.rules().forEach(this::securityGroupRuleAdded));
831 } else {
832 nodeService.completeNodes(WORKER).forEach(node -> {
Jian Lif89d9602021-04-27 19:05:49 +0900833 initializeProviderPipeline(node, false);
Jian Li8f944d42021-03-23 00:43:29 +0900834
835 for (KubevirtNetwork network : networkService.tenantNetworks()) {
Jian Lif89d9602021-04-27 19:05:49 +0900836 initializeTenantPipeline(network, node, false);
Jian Li8f944d42021-03-23 00:43:29 +0900837 }
838 });
839
840 securityGroupService.securityGroups().forEach(securityGroup ->
841 securityGroup.rules().forEach(this::securityGroupRuleRemoved));
842 }
843
844 log.info("Reset security group info " +
845 (getUseSecurityGroupFlag() ? "with" : "without") + " Security Group");
846 }
847
848 private void securityGroupRuleAdded(KubevirtSecurityGroupRule sgRule) {
849 portService.ports().stream()
850 .filter(port -> port.securityGroups().contains(sgRule.securityGroupId()))
851 .forEach(port -> {
852 updateSecurityGroupRule(port, sgRule, true);
853 log.info("Applied security group rule {} to port {}",
854 sgRule.id(), port.macAddress());
855 });
856 }
857
858 private void securityGroupRuleRemoved(KubevirtSecurityGroupRule sgRule) {
859 portService.ports().stream()
860 .filter(port -> port.securityGroups().contains(sgRule.securityGroupId()))
861 .forEach(port -> {
862 updateSecurityGroupRule(port, sgRule, false);
863 log.info("Removed security group rule {} from port {}",
864 sgRule.id(), port.macAddress());
865 });
866 }
867
868 private class InternalKubevirtPortListener implements KubevirtPortListener {
869
870 @Override
871 public boolean isRelevant(KubevirtPortEvent event) {
872 return getUseSecurityGroupFlag();
873 }
874
875 private boolean isRelevantHelper(KubevirtPortEvent event) {
876 DeviceId deviceId = event.subject().deviceId();
877
878 if (deviceId == null) {
879 return false;
880 }
881
882 return mastershipService.isLocalMaster(deviceId);
883 }
884
885 @Override
886 public void event(KubevirtPortEvent event) {
887 log.debug("security group event received {}", event);
888
889 switch (event.type()) {
890 case KUBEVIRT_PORT_SECURITY_GROUP_ADDED:
891 eventExecutor.execute(() -> processPortSgAdd(event));
892 break;
893 case KUBEVIRT_PORT_SECURITY_GROUP_REMOVED:
894 eventExecutor.execute(() -> processPortSgRemove(event));
895 break;
896 case KUBEVIRT_PORT_REMOVED:
897 eventExecutor.execute(() -> processPortRemove(event));
898 break;
899 case KUBEVIRT_PORT_DEVICE_ADDED:
900 eventExecutor.execute(() -> processPortDeviceAdded(event));
901 break;
902 default:
903 // do nothing for the other events
904 break;
905 }
906 }
907
908 private void processPortSgAdd(KubevirtPortEvent event) {
909 if (!isRelevantHelper(event)) {
910 return;
911 }
912
913 if (event.securityGroupId() == null ||
914 securityGroupService.securityGroup(event.securityGroupId()) == null) {
915 return;
916 }
917
918 KubevirtPort port = event.subject();
919 KubevirtSecurityGroup sg = securityGroupService.securityGroup(event.securityGroupId());
920
921 sg.rules().forEach(sgRule -> {
922 updateSecurityGroupRule(port, sgRule, true);
923 });
924 log.info("Added security group {} to port {}",
925 event.securityGroupId(), event.subject().macAddress());
926 }
927
928 private void processPortSgRemove(KubevirtPortEvent event) {
929 if (!isRelevantHelper(event)) {
930 return;
931 }
932
933 if (event.securityGroupId() == null ||
934 securityGroupService.securityGroup(event.securityGroupId()) == null) {
935 return;
936 }
937
938 KubevirtPort port = event.subject();
939 KubevirtSecurityGroup sg = securityGroupService.securityGroup(event.securityGroupId());
940
941 sg.rules().forEach(sgRule -> {
942 updateSecurityGroupRule(port, sgRule, false);
943 });
944 log.info("Removed security group {} from port {}",
945 event.securityGroupId(), event.subject().macAddress());
946 }
947
948 private void processPortRemove(KubevirtPortEvent event) {
949 if (!isRelevantHelper(event)) {
950 return;
951 }
952
953 KubevirtPort port = event.subject();
954 for (String sgStr : port.securityGroups()) {
955 KubevirtSecurityGroup sg = securityGroupService.securityGroup(sgStr);
956 sg.rules().forEach(sgRule -> {
957 updateSecurityGroupRule(port, sgRule, false);
958 });
959 log.info("Removed security group {} from port {}",
960 sgStr, event.subject().macAddress());
961 }
962 }
963
964 private void processPortDeviceAdded(KubevirtPortEvent event) {
965 if (!isRelevantHelper(event)) {
966 return;
967 }
968
969 for (String sgId : event.subject().securityGroups()) {
970 KubevirtSecurityGroup sg = securityGroupService.securityGroup(sgId);
971
972 sg.rules().forEach(sgRule -> {
973 updateSecurityGroupRule(event.subject(), sgRule, true);
974 });
975 log.info("Added security group {} to port {}",
Jian Lif89d9602021-04-27 19:05:49 +0900976 sg.id(), event.subject().macAddress());
Jian Li8f944d42021-03-23 00:43:29 +0900977 }
978 }
979 }
980
981 private class InternalNetworkListener implements KubevirtNetworkListener {
982
983 private boolean isRelevantHelper() {
984 return Objects.equals(localNodeId, leadershipService.getLeader(appId.name()));
985 }
986
987 @Override
988 public void event(KubevirtNetworkEvent event) {
989 switch (event.type()) {
990 case KUBEVIRT_NETWORK_CREATED:
991 eventExecutor.execute(() -> processNetworkCreation(event.subject()));
992 break;
993 case KUBEVIRT_NETWORK_REMOVED:
994 case KUBEVIRT_NETWORK_UPDATED:
995 default:
996 // do thing
997 break;
998 }
999 }
1000
1001 private void processNetworkCreation(KubevirtNetwork network) {
1002 if (!isRelevantHelper()) {
1003 return;
1004 }
1005
1006 Set<KubevirtNode> nodes = nodeService.completeNodes(WORKER);
1007
1008 if (nodes.size() > 0) {
1009 // now we wait 5s for all tenant bridges are created,
1010 // FIXME: we need to fina a better way to wait all tenant bridges
1011 // are created before installing default security group rules
Jian Li0c656f02021-06-07 13:32:39 +09001012 waitFor(5);
Jian Li8f944d42021-03-23 00:43:29 +09001013
1014 for (KubevirtNode node : nodes) {
Jian Lif89d9602021-04-27 19:05:49 +09001015 initializeTenantPipeline(network, node, true);
Jian Li8f944d42021-03-23 00:43:29 +09001016 }
1017 }
1018 }
1019 }
1020
1021 private class InternalSecurityGroupListener implements KubevirtSecurityGroupListener {
1022
1023 @Override
1024 public boolean isRelevant(KubevirtSecurityGroupEvent event) {
1025 return getUseSecurityGroupFlag();
1026 }
1027
1028 private boolean isRelevantHelper() {
1029 return Objects.equals(localNodeId, leadershipService.getLeader(appId.name()));
1030 }
1031
1032 @Override
1033 public void event(KubevirtSecurityGroupEvent event) {
1034 switch (event.type()) {
1035 case KUBEVIRT_SECURITY_GROUP_RULE_CREATED:
1036 eventExecutor.execute(() -> processSgRuleCreate(event));
1037 break;
1038 case KUBEVIRT_SECURITY_GROUP_RULE_REMOVED:
1039 eventExecutor.execute(() -> processSgRuleRemove(event));
1040 break;
1041 default:
1042 // do nothing
1043 break;
1044 }
1045 }
1046
1047 private void processSgRuleCreate(KubevirtSecurityGroupEvent event) {
1048 if (!isRelevantHelper()) {
1049 return;
1050 }
1051
1052 KubevirtSecurityGroupRule sgRuleToAdd = event.rule();
1053 securityGroupRuleAdded(sgRuleToAdd);
1054 log.info("Applied new security group rule {} to ports", sgRuleToAdd.id());
1055 }
1056
1057 private void processSgRuleRemove(KubevirtSecurityGroupEvent event) {
1058 if (!isRelevantHelper()) {
1059 return;
1060 }
1061
1062 KubevirtSecurityGroupRule sgRuleToRemove = event.rule();
1063 securityGroupRuleRemoved(sgRuleToRemove);
1064 log.info("Removed security group rule {} from ports", sgRuleToRemove.id());
1065 }
1066 }
1067
1068 private class InternalNodeListener implements KubevirtNodeListener {
1069
1070 @Override
1071 public boolean isRelevant(KubevirtNodeEvent event) {
1072 return event.subject().type() == WORKER;
1073 }
1074
1075 private boolean isRelevantHelper() {
1076 return Objects.equals(localNodeId, leadershipService.getLeader(appId.name()));
1077 }
1078
1079 @Override
1080 public void event(KubevirtNodeEvent event) {
1081 switch (event.type()) {
1082 case KUBEVIRT_NODE_COMPLETE:
1083 eventExecutor.execute(() -> processNodeComplete(event.subject()));
1084 break;
1085 default:
1086 break;
1087 }
1088 }
1089
1090 private void processNodeComplete(KubevirtNode node) {
1091 if (!isRelevantHelper()) {
1092 return;
1093 }
1094
Jian Lif89d9602021-04-27 19:05:49 +09001095 // FIXME: we wait all port get its deviceId updated
Jian Li0c656f02021-06-07 13:32:39 +09001096 waitFor(5);
Jian Lif89d9602021-04-27 19:05:49 +09001097
Jian Li8f944d42021-03-23 00:43:29 +09001098 resetSecurityGroupRulesByNode(node);
1099 }
1100
1101 private void resetSecurityGroupRulesByNode(KubevirtNode node) {
1102 if (getUseSecurityGroupFlag()) {
Jian Lif89d9602021-04-27 19:05:49 +09001103 initializeProviderPipeline(node, true);
Jian Li8f944d42021-03-23 00:43:29 +09001104
1105 for (KubevirtNetwork network : networkService.tenantNetworks()) {
Jian Lif89d9602021-04-27 19:05:49 +09001106 initializeTenantPipeline(network, node, true);
Jian Li8f944d42021-03-23 00:43:29 +09001107 }
1108
1109 securityGroupService.securityGroups().forEach(securityGroup ->
1110 securityGroup.rules().forEach(
1111 KubevirtSecurityGroupHandler.this::securityGroupRuleAdded));
1112 } else {
Jian Lif89d9602021-04-27 19:05:49 +09001113 initializeProviderPipeline(node, false);
Jian Li8f944d42021-03-23 00:43:29 +09001114
1115 for (KubevirtNetwork network : networkService.tenantNetworks()) {
Jian Lif89d9602021-04-27 19:05:49 +09001116 initializeTenantPipeline(network, node, false);
Jian Li8f944d42021-03-23 00:43:29 +09001117 }
1118
1119 securityGroupService.securityGroups().forEach(securityGroup ->
1120 securityGroup.rules().forEach(
1121 KubevirtSecurityGroupHandler.this::securityGroupRuleRemoved));
1122 }
1123
1124 log.info("Reset security group info " +
1125 (getUseSecurityGroupFlag() ? "with" : "without") + " Security Group");
1126 }
1127 }
1128}