blob: d97ac47ecb865c6056ddcd95f2e6b74a0ba1a4e9 [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 Lif89d9602021-04-27 19:05:49 +0900294 private void initializeProviderAclTable(KubevirtNode node,
295 DeviceId deviceId, boolean install) {
296 // FIXME: we need to use group table to multi-cast traffic to all
297 // physPatchPorts later, we only choose one of the physPatchPorts to
298 // stream the outbound traffic for now
299 node.physPatchPorts().stream().findFirst().ifPresent(p ->
300 initializeAclTable(deviceId, ACL_RECIRC_TABLE, p, install));
301 }
302
303 private void initializeTenantAclTable(KubevirtNetwork network,
304 DeviceId deviceId, boolean install) {
305 PortNumber patchPort = network.tenantToTunnelPort(deviceId);
306 initializeAclTable(deviceId, TENANT_ACL_RECIRC_TABLE, patchPort, install);
307 }
308
309 private void initializeAclTable(DeviceId deviceId, int recircTable,
310 PortNumber outport, boolean install) {
Jian Li8f944d42021-03-23 00:43:29 +0900311
312 ExtensionTreatment ctTreatment =
313 niciraConnTrackTreatmentBuilder(driverService, deviceId)
314 .commit(true)
315 .build();
316
317 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
318 sBuilder.matchEthType(Ethernet.TYPE_IPV4);
319
320 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
321 tBuilder.extension(ctTreatment, deviceId)
Jian Lif89d9602021-04-27 19:05:49 +0900322 .setOutput(outport);
Jian Li8f944d42021-03-23 00:43:29 +0900323
324 flowRuleService.setRule(appId,
325 deviceId,
326 sBuilder.build(),
327 tBuilder.build(),
328 PRIORITY_ACL_INGRESS_RULE,
Jian Lif89d9602021-04-27 19:05:49 +0900329 recircTable,
Jian Li8f944d42021-03-23 00:43:29 +0900330 install);
331 }
332
Jian Lif89d9602021-04-27 19:05:49 +0900333 private void initializeProviderEgressTable(DeviceId deviceId, boolean install) {
334 initializeEgressTable(deviceId, ACL_EGRESS_TABLE, FORWARDING_TABLE, install);
335 }
336
337 private void initializeTenantEgressTable(DeviceId deviceId, boolean install) {
338 initializeEgressTable(deviceId, TENANT_ACL_EGRESS_TABLE, TENANT_FORWARDING_TABLE, install);
339 }
340
341 private void initializeEgressTable(DeviceId deviceId, int egressTable,
342 int forwardTable, boolean install) {
Jian Li8f944d42021-03-23 00:43:29 +0900343 if (install) {
344 flowRuleService.setUpTableMissEntry(deviceId, TENANT_ACL_EGRESS_TABLE);
345 } else {
Jian Lif89d9602021-04-27 19:05:49 +0900346 flowRuleService.connectTables(deviceId, egressTable, forwardTable);
Jian Li8f944d42021-03-23 00:43:29 +0900347 }
348 }
349
Jian Lif89d9602021-04-27 19:05:49 +0900350 private void initializeProviderIngressTable(DeviceId deviceId, boolean install) {
351 initializeIngressTable(deviceId, ACL_INGRESS_TABLE, FORWARDING_TABLE, install);
352 }
353
354 private void initializeTenantIngressTable(DeviceId deviceId, boolean install) {
355 initializeIngressTable(deviceId, TENANT_ACL_INGRESS_TABLE, TENANT_FORWARDING_TABLE, install);
356 }
357
358 private void initializeIngressTable(DeviceId deviceId, int ingressTable,
359 int forwardTable, boolean install) {
Jian Li8f944d42021-03-23 00:43:29 +0900360 if (install) {
Jian Lif89d9602021-04-27 19:05:49 +0900361 flowRuleService.setUpTableMissEntry(deviceId, ingressTable);
Jian Li8f944d42021-03-23 00:43:29 +0900362 } else {
Jian Lif89d9602021-04-27 19:05:49 +0900363 flowRuleService.connectTables(deviceId, ingressTable, forwardTable);
Jian Li8f944d42021-03-23 00:43:29 +0900364 }
365 }
366
Jian Lif89d9602021-04-27 19:05:49 +0900367 private void initializeProviderPipeline(KubevirtNode node, boolean install) {
368 initializeProviderIngressTable(node.intgBridge(), install);
369 initializeProviderEgressTable(node.intgBridge(), install);
370 initializeProviderConnTrackTable(node.intgBridge(), install);
371 initializeProviderAclTable(node, node.intgBridge(), install);
372 }
373
374 private void initializeTenantPipeline(KubevirtNetwork network,
375 KubevirtNode node, boolean install) {
376 DeviceId deviceId = network.tenantDeviceId(node.hostname());
377 if (deviceId == null) {
378 return;
379 }
Jian Li567b25c2021-05-27 15:17:59 +0900380
381 // we check whether the given device is available from the store
382 // if not we will wait until the device is eventually created
383 // FIXME: it would be better to listen to device event to perform
384 // pipeline initialization rather on network events.
385 while (true) {
386 if (deviceService.getDevice(deviceId) != null) {
387 break;
388 } else {
Jian Li0c656f02021-06-07 13:32:39 +0900389 waitFor(5);
Jian Li567b25c2021-05-27 15:17:59 +0900390 }
391 }
392
Jian Lif89d9602021-04-27 19:05:49 +0900393 initializeTenantIngressTable(deviceId, install);
394 initializeTenantEgressTable(deviceId, install);
395 initializeTenantConnTrackTable(deviceId, install);
396 initializeTenantAclTable(network, deviceId, install);
397 }
398
Jian Li8f944d42021-03-23 00:43:29 +0900399 private void updateSecurityGroupRule(KubevirtPort port,
400 KubevirtSecurityGroupRule sgRule, boolean install) {
401
402 if (port == null || sgRule == null) {
403 return;
404 }
405
406 if (sgRule.remoteGroupId() != null && !sgRule.remoteGroupId().isEmpty()) {
407 getRemotePorts(port, sgRule.remoteGroupId())
408 .forEach(rPort -> {
409 populateSecurityGroupRule(sgRule, port,
410 rPort.ipAddress().toIpPrefix(), install);
411 populateSecurityGroupRule(sgRule, rPort,
412 port.ipAddress().toIpPrefix(), install);
413
414 KubevirtSecurityGroupRule rSgRule = sgRule.updateDirection(
415 sgRule.direction().equalsIgnoreCase(EGRESS) ? INGRESS : EGRESS);
416 populateSecurityGroupRule(rSgRule, port,
417 rPort.ipAddress().toIpPrefix(), install);
418 populateSecurityGroupRule(rSgRule, rPort,
419 port.ipAddress().toIpPrefix(), install);
420 });
421 } else {
422 populateSecurityGroupRule(sgRule, port,
423 sgRule.remoteIpPrefix() == null ? IP_PREFIX_ANY :
424 sgRule.remoteIpPrefix(), install);
425 }
426 }
427
428 private boolean checkProtocol(String protocol) {
429 if (protocol == null) {
430 log.debug("No protocol was specified, use default IP(v4/v6) protocol.");
431 return true;
432 } else {
433 String protocolUpper = protocol.toUpperCase();
434 if (protocolUpper.equals(PROTO_TCP) ||
435 protocolUpper.equals(PROTO_UDP) ||
436 protocolUpper.equals(PROTO_ICMP) ||
437 protocolUpper.equals(PROTO_SCTP) ||
438 protocolUpper.equals(PROTO_ANY) ||
439 protocol.equals(PROTO_TCP_NUM) ||
440 protocol.equals(PROTO_UDP_NUM) ||
441 protocol.equals(PROTO_ICMP_NUM) ||
442 protocol.equals(PROTO_SCTP_NUM) ||
443 protocol.equals(PROTO_ANY_NUM)) {
444 return true;
445 } else {
446 log.error("Unsupported protocol {}, we only support " +
447 "TCP/UDP/ICMP/SCTP protocols.", protocol);
448 return false;
449 }
450 }
451 }
452
453 private void populateSecurityGroupRule(KubevirtSecurityGroupRule sgRule,
454 KubevirtPort port,
455 IpPrefix remoteIp,
456 boolean install) {
457 if (!checkProtocol(sgRule.protocol())) {
458 return;
459 }
460
461 DeviceId deviceId = port.isTenant() ? port.tenantDeviceId() : port.deviceId();
462
Jian Lif89d9602021-04-27 19:05:49 +0900463 Set<TrafficSelector> ctSelectors = buildSelectors(
464 sgRule,
Jian Li8f944d42021-03-23 00:43:29 +0900465 Ip4Address.valueOf(port.ipAddress().toInetAddress()),
Jian Lif89d9602021-04-27 19:05:49 +0900466 port.macAddress(),
Jian Li8f944d42021-03-23 00:43:29 +0900467 remoteIp, port.networkId());
Jian Lif89d9602021-04-27 19:05:49 +0900468 if (ctSelectors == null || ctSelectors.isEmpty()) {
Jian Li8f944d42021-03-23 00:43:29 +0900469 return;
470 }
471
472 // if the device is not available we do not perform any action
473 if (deviceId == null || !deviceService.isAvailable(deviceId)) {
474 return;
475 }
476
477 // XXX All egress traffic needs to go through connection tracking module,
478 // which might hurt its performance.
479 ExtensionTreatment ctTreatment =
480 niciraConnTrackTreatmentBuilder(driverService, deviceId)
481 .commit(true)
482 .build();
483
484 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
485
Jian Lif89d9602021-04-27 19:05:49 +0900486 KubevirtNetwork net = networkService.network(port.networkId());
487
Jian Li8f944d42021-03-23 00:43:29 +0900488 int aclTable;
489 if (sgRule.direction().equalsIgnoreCase(EGRESS)) {
Jian Lif89d9602021-04-27 19:05:49 +0900490
491 if (net.type() == FLAT || net.type() == VLAN) {
492 aclTable = ACL_EGRESS_TABLE;
493 } else {
494 aclTable = TENANT_ACL_EGRESS_TABLE;
495 }
496
Jian Li8f944d42021-03-23 00:43:29 +0900497 tBuilder.transition(TENANT_ACL_RECIRC_TABLE);
498 } else {
Jian Lif89d9602021-04-27 19:05:49 +0900499
500 if (net.type() == FLAT || net.type() == VLAN) {
501 aclTable = ACL_INGRESS_TABLE;
502 } else {
503 aclTable = TENANT_ACL_INGRESS_TABLE;
504 }
505
Jian Li8f944d42021-03-23 00:43:29 +0900506 tBuilder.extension(ctTreatment, deviceId)
507 .transition(TENANT_FORWARDING_TABLE);
508 }
509
510 int finalAclTable = aclTable;
Jian Lif89d9602021-04-27 19:05:49 +0900511 ctSelectors.forEach(selector -> {
Jian Li8f944d42021-03-23 00:43:29 +0900512 flowRuleService.setRule(appId,
513 deviceId,
514 selector, tBuilder.build(),
515 PRIORITY_ACL_RULE,
516 finalAclTable,
517 install);
518 });
Jian Lif89d9602021-04-27 19:05:49 +0900519
520 TrafficSelector tSelector = DefaultTrafficSelector.builder()
521 .matchEthType(Ethernet.TYPE_IPV4)
522 .matchEthDst(port.macAddress())
523 .matchIPDst(IpPrefix.valueOf(port.ipAddress(), 32))
524 .build();
525 TrafficTreatment tTreatment = DefaultTrafficTreatment.builder()
526 .transition(TENANT_ACL_INGRESS_TABLE)
527 .build();
528
529 flowRuleService.setRule(appId,
530 deviceId,
531 tSelector,
532 tTreatment,
533 PRIORITY_ACL_RULE,
534 TENANT_ACL_RECIRC_TABLE,
535 install);
Jian Li8f944d42021-03-23 00:43:29 +0900536 }
537
538 /**
539 * Sets connection tracking rule using OVS extension commands.
540 * It is not so graceful, but I don't want to make it more general because
541 * it is going to be used only here.
542 * The following is the usage of the function.
543 *
544 * @param deviceId Device ID
545 * @param ctState ctState: please use RulePopulatorUtil.computeCtStateFlag()
546 * to build the value
547 * @param ctMask crMask: please use RulePopulatorUtil.computeCtMaskFlag()
548 * to build the value
549 * @param commit CT_COMMIT for commit action, CT_NO_COMMIT otherwise
550 * @param recircTable table number for recirculation after CT actions.
551 * CT_NO_RECIRC with no recirculation
552 * @param action Additional actions. ACTION_DROP, ACTION_NONE,
553 * GOTO_XXX_TABLE are supported.
554 * @param priority priority value for the rule
555 * @param install true for insertion, false for removal
556 */
557 private void setConnTrackRule(DeviceId deviceId, long ctState, long ctMask,
558 int commit, short recircTable,
559 int action, int priority, boolean install) {
560
561 ExtensionSelector esCtSate = RulePopulatorUtil
562 .buildCtExtensionSelector(driverService, deviceId, ctState, ctMask);
563 TrafficSelector selector = DefaultTrafficSelector.builder()
564 .extension(esCtSate, deviceId)
565 .matchEthType(Ethernet.TYPE_IPV4)
566 .build();
567
568 TrafficTreatment.Builder tb = DefaultTrafficTreatment.builder();
569
570 if (commit == CT_COMMIT || recircTable > 0) {
571 RulePopulatorUtil.NiciraConnTrackTreatmentBuilder natTreatmentBuilder =
572 niciraConnTrackTreatmentBuilder(driverService, deviceId);
573 natTreatmentBuilder.natAction(false);
574 natTreatmentBuilder.commit(commit == CT_COMMIT);
575 if (recircTable > 0) {
576 natTreatmentBuilder.table(recircTable);
577 }
578 tb.extension(natTreatmentBuilder.build(), deviceId);
579 } else if (action == ACTION_DROP) {
580 tb.drop();
581 }
582
583 if (action != ACTION_NONE && action != ACTION_DROP) {
584 tb.transition(action);
585 }
586
587 int tableType = ERROR_TABLE;
588 if (priority == PRIORITY_CT_RULE || priority == PRIORITY_CT_DROP_RULE) {
589 tableType = TENANT_ACL_CT_TABLE;
590 } else if (priority == PRIORITY_CT_HOOK_RULE) {
591 tableType = TENANT_ACL_INGRESS_TABLE;
592 } else {
593 log.error("Cannot an appropriate table for the conn track rule.");
594 }
595
596 flowRuleService.setRule(
597 appId,
598 deviceId,
599 selector,
600 tb.build(),
601 priority,
602 tableType,
603 install);
604 }
605
606 /**
607 * Returns a set of host IP addresses engaged with supplied security group ID.
608 * It only searches a VM in the same tenant boundary.
609 *
610 * @param srcPort edgestack port
611 * @param sgId security group id
612 * @return set of ip addresses
613 */
614 private Set<KubevirtPort> getRemotePorts(KubevirtPort srcPort, String sgId) {
615 return portService.ports().stream()
616 .filter(port -> !port.macAddress().equals(srcPort.macAddress()))
617 .filter(port -> port.securityGroups().contains(sgId))
618 .filter(port -> port.ipAddress() != null)
619 .collect(Collectors.toSet());
620 }
621
622 private Set<TrafficSelector> buildSelectors(KubevirtSecurityGroupRule sgRule,
623 Ip4Address vmIp,
Jian Lif89d9602021-04-27 19:05:49 +0900624 MacAddress vmMac,
Jian Li8f944d42021-03-23 00:43:29 +0900625 IpPrefix remoteIp,
626 String netId) {
627 if (remoteIp != null && remoteIp.equals(IpPrefix.valueOf(vmIp, VM_IP_PREFIX))) {
628 // do nothing if the remote IP is my IP
629 return null;
630 }
631
632 Set<TrafficSelector> selectorSet = Sets.newHashSet();
633
634 if (sgRule.portRangeMax() != null && sgRule.portRangeMin() != null &&
635 sgRule.portRangeMin() < sgRule.portRangeMax()) {
636 Map<TpPort, TpPort> portRangeMatchMap =
637 buildPortRangeMatches(sgRule.portRangeMin(),
638 sgRule.portRangeMax());
639 portRangeMatchMap.forEach((key, value) -> {
640
641 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
Jian Lif89d9602021-04-27 19:05:49 +0900642 buildMatches(sBuilder, sgRule, vmIp, vmMac, remoteIp);
Jian Li8f944d42021-03-23 00:43:29 +0900643
644 if (sgRule.protocol().equalsIgnoreCase(PROTO_TCP) ||
645 sgRule.protocol().equals(PROTO_TCP_NUM)) {
646 if (sgRule.direction().equalsIgnoreCase(EGRESS)) {
647 if (value.toInt() == TpPort.MAX_PORT) {
648 sBuilder.matchTcpSrc(key);
649 } else {
650 sBuilder.matchTcpSrcMasked(key, value);
651 }
652 } else {
653 if (value.toInt() == TpPort.MAX_PORT) {
654 sBuilder.matchTcpDst(key);
655 } else {
656 sBuilder.matchTcpDstMasked(key, value);
657 }
658 }
659 } else if (sgRule.protocol().equalsIgnoreCase(PROTO_UDP) ||
660 sgRule.protocol().equals(PROTO_UDP_NUM)) {
661 if (sgRule.direction().equalsIgnoreCase(EGRESS)) {
662 if (value.toInt() == TpPort.MAX_PORT) {
663 sBuilder.matchUdpSrc(key);
664 } else {
665 sBuilder.matchUdpSrcMasked(key, value);
666 }
667 } else {
668 if (value.toInt() == TpPort.MAX_PORT) {
669 sBuilder.matchUdpDst(key);
670 } else {
671 sBuilder.matchUdpDstMasked(key, value);
672 }
673 }
674 } else if (sgRule.protocol().equalsIgnoreCase(PROTO_SCTP) ||
675 sgRule.protocol().equals(PROTO_SCTP_NUM)) {
676 if (sgRule.direction().equalsIgnoreCase(EGRESS)) {
677 if (value.toInt() == TpPort.MAX_PORT) {
678 sBuilder.matchSctpSrc(key);
679 } else {
680 sBuilder.matchSctpSrcMasked(key, value);
681 }
682 } else {
683 if (value.toInt() == TpPort.MAX_PORT) {
684 sBuilder.matchSctpDst(key);
685 } else {
686 sBuilder.matchSctpDstMasked(key, value);
687 }
688 }
689 }
690
691 selectorSet.add(sBuilder.build());
692 });
693 } else {
694
695 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
Jian Lif89d9602021-04-27 19:05:49 +0900696 buildMatches(sBuilder, sgRule, vmIp, vmMac, remoteIp);
Jian Li8f944d42021-03-23 00:43:29 +0900697
698 selectorSet.add(sBuilder.build());
699 }
700
701 return selectorSet;
702 }
703
704 private void buildMatches(TrafficSelector.Builder sBuilder,
705 KubevirtSecurityGroupRule sgRule, Ip4Address vmIp,
Jian Lif89d9602021-04-27 19:05:49 +0900706 MacAddress vmMac, IpPrefix remoteIp) {
Jian Li8f944d42021-03-23 00:43:29 +0900707 buildMatchEthType(sBuilder, sgRule.etherType());
Jian Lif89d9602021-04-27 19:05:49 +0900708 buildMatchDirection(sBuilder, sgRule.direction(), vmIp, vmMac);
Jian Li8f944d42021-03-23 00:43:29 +0900709 buildMatchProto(sBuilder, sgRule.protocol());
710 buildMatchPort(sBuilder, sgRule.protocol(), sgRule.direction(),
711 sgRule.portRangeMin() == null ? 0 : sgRule.portRangeMin(),
712 sgRule.portRangeMax() == null ? 0 : sgRule.portRangeMax());
713 buildMatchIcmp(sBuilder, sgRule.protocol(),
714 sgRule.portRangeMin(), sgRule.portRangeMax());
715 buildMatchRemoteIp(sBuilder, remoteIp, sgRule.direction());
716 }
717
Jian Li8f944d42021-03-23 00:43:29 +0900718 private void buildMatchDirection(TrafficSelector.Builder sBuilder,
719 String direction,
Jian Lif89d9602021-04-27 19:05:49 +0900720 Ip4Address vmIp,
721 MacAddress vmMac) {
Jian Li8f944d42021-03-23 00:43:29 +0900722 if (direction.equalsIgnoreCase(EGRESS)) {
723 sBuilder.matchIPSrc(IpPrefix.valueOf(vmIp, VM_IP_PREFIX));
Jian Lif89d9602021-04-27 19:05:49 +0900724 sBuilder.matchEthSrc(vmMac);
Jian Li8f944d42021-03-23 00:43:29 +0900725 } else {
726 sBuilder.matchIPDst(IpPrefix.valueOf(vmIp, VM_IP_PREFIX));
Jian Lif89d9602021-04-27 19:05:49 +0900727 sBuilder.matchEthDst(vmMac);
Jian Li8f944d42021-03-23 00:43:29 +0900728 }
729 }
730
731 private void buildMatchEthType(TrafficSelector.Builder sBuilder, String etherType) {
732 // Either IpSrc or IpDst (or both) is set by default, and we need to set EthType as IPv4.
733 sBuilder.matchEthType(Ethernet.TYPE_IPV4);
734 if (etherType != null && !Objects.equals(etherType, STR_NULL) &&
735 !etherType.equalsIgnoreCase(ETHTYPE_IPV4)) {
736 log.debug("EthType {} is not supported yet in Security Group", etherType);
737 }
738 }
739
740 private void buildMatchRemoteIp(TrafficSelector.Builder sBuilder,
741 IpPrefix remoteIpPrefix, String direction) {
742 if (remoteIpPrefix != null &&
743 !remoteIpPrefix.getIp4Prefix().equals(IP_PREFIX_ANY)) {
744 if (direction.equalsIgnoreCase(EGRESS)) {
745 sBuilder.matchIPDst(remoteIpPrefix);
746 } else {
747 sBuilder.matchIPSrc(remoteIpPrefix);
748 }
749 }
750 }
751
752 private void buildMatchProto(TrafficSelector.Builder sBuilder, String protocol) {
753 if (protocol != null) {
754 switch (protocol.toUpperCase()) {
755 case PROTO_ICMP:
756 case PROTO_ICMP_NUM:
757 sBuilder.matchIPProtocol(IPv4.PROTOCOL_ICMP);
758 break;
759 case PROTO_TCP:
760 case PROTO_TCP_NUM:
761 sBuilder.matchIPProtocol(IPv4.PROTOCOL_TCP);
762 break;
763 case PROTO_UDP:
764 case PROTO_UDP_NUM:
765 sBuilder.matchIPProtocol(IPv4.PROTOCOL_UDP);
766 break;
767 case PROTO_SCTP:
768 case PROTO_SCTP_NUM:
769 sBuilder.matchIPProtocol(PROTOCOL_SCTP);
770 break;
771 default:
772 break;
773 }
774 }
775 }
776
777 private void buildMatchPort(TrafficSelector.Builder sBuilder,
778 String protocol, String direction,
779 int portMin, int portMax) {
780 if (portMax > 0 && portMin == portMax) {
781 if (protocol.equalsIgnoreCase(PROTO_TCP) ||
782 protocol.equals(PROTO_TCP_NUM)) {
783 if (direction.equalsIgnoreCase(EGRESS)) {
784 sBuilder.matchTcpSrc(TpPort.tpPort(portMax));
785 } else {
786 sBuilder.matchTcpDst(TpPort.tpPort(portMax));
787 }
788 } else if (protocol.equalsIgnoreCase(PROTO_UDP) ||
789 protocol.equals(PROTO_UDP_NUM)) {
790 if (direction.equalsIgnoreCase(EGRESS)) {
791 sBuilder.matchUdpSrc(TpPort.tpPort(portMax));
792 } else {
793 sBuilder.matchUdpDst(TpPort.tpPort(portMax));
794 }
795 } else if (protocol.equalsIgnoreCase(PROTO_SCTP) ||
796 protocol.equals(PROTO_SCTP_NUM)) {
797 if (direction.equalsIgnoreCase(EGRESS)) {
798 sBuilder.matchSctpSrc(TpPort.tpPort(portMax));
799 } else {
800 sBuilder.matchSctpDst(TpPort.tpPort(portMax));
801 }
802 }
803 }
804 }
805
806 private void buildMatchIcmp(TrafficSelector.Builder sBuilder,
807 String protocol, Integer icmpCode, Integer icmpType) {
808 if (protocol != null) {
809 if (protocol.equalsIgnoreCase(PROTO_ICMP) ||
810 protocol.equals(PROTO_ICMP_NUM)) {
811 if (icmpCode != null && icmpCode >= ICMP_CODE_MIN &&
812 icmpCode <= ICMP_CODE_MAX) {
813 sBuilder.matchIcmpCode(icmpCode.byteValue());
814 }
815 if (icmpType != null && icmpType >= ICMP_TYPE_MIN &&
816 icmpType <= ICMP_TYPE_MAX) {
817 sBuilder.matchIcmpType(icmpType.byteValue());
818 }
819 }
820 }
821 }
822
823 private void resetSecurityGroupRules() {
824
825 if (getUseSecurityGroupFlag()) {
826 nodeService.completeNodes(WORKER).forEach(node -> {
Jian Lif89d9602021-04-27 19:05:49 +0900827 initializeProviderPipeline(node, true);
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, true);
Jian Li8f944d42021-03-23 00:43:29 +0900831 }
832 });
833
834 securityGroupService.securityGroups().forEach(securityGroup ->
835 securityGroup.rules().forEach(this::securityGroupRuleAdded));
836 } else {
837 nodeService.completeNodes(WORKER).forEach(node -> {
Jian Lif89d9602021-04-27 19:05:49 +0900838 initializeProviderPipeline(node, false);
Jian Li8f944d42021-03-23 00:43:29 +0900839
840 for (KubevirtNetwork network : networkService.tenantNetworks()) {
Jian Lif89d9602021-04-27 19:05:49 +0900841 initializeTenantPipeline(network, node, false);
Jian Li8f944d42021-03-23 00:43:29 +0900842 }
843 });
844
845 securityGroupService.securityGroups().forEach(securityGroup ->
846 securityGroup.rules().forEach(this::securityGroupRuleRemoved));
847 }
848
849 log.info("Reset security group info " +
850 (getUseSecurityGroupFlag() ? "with" : "without") + " Security Group");
851 }
852
853 private void securityGroupRuleAdded(KubevirtSecurityGroupRule sgRule) {
854 portService.ports().stream()
855 .filter(port -> port.securityGroups().contains(sgRule.securityGroupId()))
856 .forEach(port -> {
857 updateSecurityGroupRule(port, sgRule, true);
858 log.info("Applied security group rule {} to port {}",
859 sgRule.id(), port.macAddress());
860 });
861 }
862
863 private void securityGroupRuleRemoved(KubevirtSecurityGroupRule sgRule) {
864 portService.ports().stream()
865 .filter(port -> port.securityGroups().contains(sgRule.securityGroupId()))
866 .forEach(port -> {
867 updateSecurityGroupRule(port, sgRule, false);
868 log.info("Removed security group rule {} from port {}",
869 sgRule.id(), port.macAddress());
870 });
871 }
872
873 private class InternalKubevirtPortListener implements KubevirtPortListener {
874
875 @Override
876 public boolean isRelevant(KubevirtPortEvent event) {
877 return getUseSecurityGroupFlag();
878 }
879
880 private boolean isRelevantHelper(KubevirtPortEvent event) {
881 DeviceId deviceId = event.subject().deviceId();
882
883 if (deviceId == null) {
884 return false;
885 }
886
887 return mastershipService.isLocalMaster(deviceId);
888 }
889
890 @Override
891 public void event(KubevirtPortEvent event) {
892 log.debug("security group event received {}", event);
893
894 switch (event.type()) {
895 case KUBEVIRT_PORT_SECURITY_GROUP_ADDED:
896 eventExecutor.execute(() -> processPortSgAdd(event));
897 break;
898 case KUBEVIRT_PORT_SECURITY_GROUP_REMOVED:
899 eventExecutor.execute(() -> processPortSgRemove(event));
900 break;
901 case KUBEVIRT_PORT_REMOVED:
902 eventExecutor.execute(() -> processPortRemove(event));
903 break;
904 case KUBEVIRT_PORT_DEVICE_ADDED:
905 eventExecutor.execute(() -> processPortDeviceAdded(event));
906 break;
907 default:
908 // do nothing for the other events
909 break;
910 }
911 }
912
913 private void processPortSgAdd(KubevirtPortEvent event) {
914 if (!isRelevantHelper(event)) {
915 return;
916 }
917
918 if (event.securityGroupId() == null ||
919 securityGroupService.securityGroup(event.securityGroupId()) == null) {
920 return;
921 }
922
923 KubevirtPort port = event.subject();
924 KubevirtSecurityGroup sg = securityGroupService.securityGroup(event.securityGroupId());
925
926 sg.rules().forEach(sgRule -> {
927 updateSecurityGroupRule(port, sgRule, true);
928 });
929 log.info("Added security group {} to port {}",
930 event.securityGroupId(), event.subject().macAddress());
931 }
932
933 private void processPortSgRemove(KubevirtPortEvent event) {
934 if (!isRelevantHelper(event)) {
935 return;
936 }
937
938 if (event.securityGroupId() == null ||
939 securityGroupService.securityGroup(event.securityGroupId()) == null) {
940 return;
941 }
942
943 KubevirtPort port = event.subject();
944 KubevirtSecurityGroup sg = securityGroupService.securityGroup(event.securityGroupId());
945
946 sg.rules().forEach(sgRule -> {
947 updateSecurityGroupRule(port, sgRule, false);
948 });
949 log.info("Removed security group {} from port {}",
950 event.securityGroupId(), event.subject().macAddress());
951 }
952
953 private void processPortRemove(KubevirtPortEvent event) {
954 if (!isRelevantHelper(event)) {
955 return;
956 }
957
958 KubevirtPort port = event.subject();
959 for (String sgStr : port.securityGroups()) {
960 KubevirtSecurityGroup sg = securityGroupService.securityGroup(sgStr);
961 sg.rules().forEach(sgRule -> {
962 updateSecurityGroupRule(port, sgRule, false);
963 });
964 log.info("Removed security group {} from port {}",
965 sgStr, event.subject().macAddress());
966 }
967 }
968
969 private void processPortDeviceAdded(KubevirtPortEvent event) {
970 if (!isRelevantHelper(event)) {
971 return;
972 }
973
974 for (String sgId : event.subject().securityGroups()) {
975 KubevirtSecurityGroup sg = securityGroupService.securityGroup(sgId);
976
977 sg.rules().forEach(sgRule -> {
978 updateSecurityGroupRule(event.subject(), sgRule, true);
979 });
980 log.info("Added security group {} to port {}",
Jian Lif89d9602021-04-27 19:05:49 +0900981 sg.id(), event.subject().macAddress());
Jian Li8f944d42021-03-23 00:43:29 +0900982 }
983 }
984 }
985
986 private class InternalNetworkListener implements KubevirtNetworkListener {
987
988 private boolean isRelevantHelper() {
989 return Objects.equals(localNodeId, leadershipService.getLeader(appId.name()));
990 }
991
992 @Override
993 public void event(KubevirtNetworkEvent event) {
994 switch (event.type()) {
995 case KUBEVIRT_NETWORK_CREATED:
996 eventExecutor.execute(() -> processNetworkCreation(event.subject()));
997 break;
998 case KUBEVIRT_NETWORK_REMOVED:
999 case KUBEVIRT_NETWORK_UPDATED:
1000 default:
1001 // do thing
1002 break;
1003 }
1004 }
1005
1006 private void processNetworkCreation(KubevirtNetwork network) {
1007 if (!isRelevantHelper()) {
1008 return;
1009 }
1010
1011 Set<KubevirtNode> nodes = nodeService.completeNodes(WORKER);
1012
1013 if (nodes.size() > 0) {
1014 // now we wait 5s for all tenant bridges are created,
1015 // FIXME: we need to fina a better way to wait all tenant bridges
1016 // are created before installing default security group rules
Jian Li0c656f02021-06-07 13:32:39 +09001017 waitFor(5);
Jian Li8f944d42021-03-23 00:43:29 +09001018
1019 for (KubevirtNode node : nodes) {
Jian Lif89d9602021-04-27 19:05:49 +09001020 initializeTenantPipeline(network, node, true);
Jian Li8f944d42021-03-23 00:43:29 +09001021 }
1022 }
1023 }
1024 }
1025
1026 private class InternalSecurityGroupListener implements KubevirtSecurityGroupListener {
1027
1028 @Override
1029 public boolean isRelevant(KubevirtSecurityGroupEvent event) {
1030 return getUseSecurityGroupFlag();
1031 }
1032
1033 private boolean isRelevantHelper() {
1034 return Objects.equals(localNodeId, leadershipService.getLeader(appId.name()));
1035 }
1036
1037 @Override
1038 public void event(KubevirtSecurityGroupEvent event) {
1039 switch (event.type()) {
1040 case KUBEVIRT_SECURITY_GROUP_RULE_CREATED:
1041 eventExecutor.execute(() -> processSgRuleCreate(event));
1042 break;
1043 case KUBEVIRT_SECURITY_GROUP_RULE_REMOVED:
1044 eventExecutor.execute(() -> processSgRuleRemove(event));
1045 break;
1046 default:
1047 // do nothing
1048 break;
1049 }
1050 }
1051
1052 private void processSgRuleCreate(KubevirtSecurityGroupEvent event) {
1053 if (!isRelevantHelper()) {
1054 return;
1055 }
1056
1057 KubevirtSecurityGroupRule sgRuleToAdd = event.rule();
1058 securityGroupRuleAdded(sgRuleToAdd);
1059 log.info("Applied new security group rule {} to ports", sgRuleToAdd.id());
1060 }
1061
1062 private void processSgRuleRemove(KubevirtSecurityGroupEvent event) {
1063 if (!isRelevantHelper()) {
1064 return;
1065 }
1066
1067 KubevirtSecurityGroupRule sgRuleToRemove = event.rule();
1068 securityGroupRuleRemoved(sgRuleToRemove);
1069 log.info("Removed security group rule {} from ports", sgRuleToRemove.id());
1070 }
1071 }
1072
1073 private class InternalNodeListener implements KubevirtNodeListener {
1074
1075 @Override
1076 public boolean isRelevant(KubevirtNodeEvent event) {
1077 return event.subject().type() == WORKER;
1078 }
1079
1080 private boolean isRelevantHelper() {
1081 return Objects.equals(localNodeId, leadershipService.getLeader(appId.name()));
1082 }
1083
1084 @Override
1085 public void event(KubevirtNodeEvent event) {
1086 switch (event.type()) {
1087 case KUBEVIRT_NODE_COMPLETE:
1088 eventExecutor.execute(() -> processNodeComplete(event.subject()));
1089 break;
1090 default:
1091 break;
1092 }
1093 }
1094
1095 private void processNodeComplete(KubevirtNode node) {
1096 if (!isRelevantHelper()) {
1097 return;
1098 }
1099
Jian Lif89d9602021-04-27 19:05:49 +09001100 // FIXME: we wait all port get its deviceId updated
Jian Li0c656f02021-06-07 13:32:39 +09001101 waitFor(5);
Jian Lif89d9602021-04-27 19:05:49 +09001102
Jian Li8f944d42021-03-23 00:43:29 +09001103 resetSecurityGroupRulesByNode(node);
1104 }
1105
1106 private void resetSecurityGroupRulesByNode(KubevirtNode node) {
1107 if (getUseSecurityGroupFlag()) {
Jian Lif89d9602021-04-27 19:05:49 +09001108 initializeProviderPipeline(node, true);
Jian Li8f944d42021-03-23 00:43:29 +09001109
1110 for (KubevirtNetwork network : networkService.tenantNetworks()) {
Jian Lif89d9602021-04-27 19:05:49 +09001111 initializeTenantPipeline(network, node, true);
Jian Li8f944d42021-03-23 00:43:29 +09001112 }
1113
1114 securityGroupService.securityGroups().forEach(securityGroup ->
1115 securityGroup.rules().forEach(
1116 KubevirtSecurityGroupHandler.this::securityGroupRuleAdded));
1117 } else {
Jian Lif89d9602021-04-27 19:05:49 +09001118 initializeProviderPipeline(node, false);
Jian Li8f944d42021-03-23 00:43:29 +09001119
1120 for (KubevirtNetwork network : networkService.tenantNetworks()) {
Jian Lif89d9602021-04-27 19:05:49 +09001121 initializeTenantPipeline(network, node, false);
Jian Li8f944d42021-03-23 00:43:29 +09001122 }
1123
1124 securityGroupService.securityGroups().forEach(securityGroup ->
1125 securityGroup.rules().forEach(
1126 KubevirtSecurityGroupHandler.this::securityGroupRuleRemoved));
1127 }
1128
1129 log.info("Reset security group info " +
1130 (getUseSecurityGroupFlag() ? "with" : "without") + " Security Group");
1131 }
1132 }
1133}