blob: 387fdad9bf710b397bdbe34e4482f69efeb439fd [file] [log] [blame]
sangho6a9ff0d2017-03-27 11:23:37 +09001/*
Jian Li26949762018-03-30 15:46:37 +09002 * Copyright 2017-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 */
sangho6a9ff0d2017-03-27 11:23:37 +090016
17package org.onosproject.openstacknetworking.impl;
18
19import com.google.common.base.Strings;
sangho2e97be02017-07-03 18:18:27 +090020import com.google.common.collect.Maps;
21import com.google.common.collect.Sets;
sangho6a9ff0d2017-03-27 11:23:37 +090022import org.apache.felix.scr.annotations.Activate;
23import org.apache.felix.scr.annotations.Component;
24import org.apache.felix.scr.annotations.Deactivate;
sangho0248ca22017-05-31 13:22:47 +090025import org.apache.felix.scr.annotations.Modified;
26import org.apache.felix.scr.annotations.Property;
sangho6a9ff0d2017-03-27 11:23:37 +090027import org.apache.felix.scr.annotations.Reference;
28import org.apache.felix.scr.annotations.ReferenceCardinality;
29import org.onlab.packet.Ethernet;
30import org.onlab.packet.IPv4;
31import org.onlab.packet.Ip4Address;
32import org.onlab.packet.Ip4Prefix;
33import org.onlab.packet.IpPrefix;
34import org.onlab.packet.TpPort;
sangho0248ca22017-05-31 13:22:47 +090035import org.onlab.util.Tools;
36import org.onosproject.cfg.ComponentConfigService;
sangho1aaa7882017-05-31 13:22:47 +090037import org.onosproject.cluster.ClusterService;
38import org.onosproject.cluster.LeadershipService;
39import org.onosproject.cluster.NodeId;
sangho6a9ff0d2017-03-27 11:23:37 +090040import org.onosproject.core.ApplicationId;
41import org.onosproject.core.CoreService;
42import org.onosproject.mastership.MastershipService;
sangho1aaa7882017-05-31 13:22:47 +090043import org.onosproject.net.DeviceId;
44import org.onosproject.net.driver.DriverService;
sangho6a9ff0d2017-03-27 11:23:37 +090045import org.onosproject.net.flow.DefaultTrafficSelector;
46import org.onosproject.net.flow.DefaultTrafficTreatment;
47import org.onosproject.net.flow.TrafficSelector;
sangho1aaa7882017-05-31 13:22:47 +090048import org.onosproject.net.flow.TrafficTreatment;
49import org.onosproject.net.flow.criteria.ExtensionSelector;
sangho6a9ff0d2017-03-27 11:23:37 +090050import org.onosproject.openstacknetworking.api.InstancePort;
51import org.onosproject.openstacknetworking.api.InstancePortEvent;
52import org.onosproject.openstacknetworking.api.InstancePortListener;
53import org.onosproject.openstacknetworking.api.InstancePortService;
sanghodc375372017-06-08 10:41:30 +090054import org.onosproject.openstacknetworking.api.OpenstackFlowRuleService;
sangho6a9ff0d2017-03-27 11:23:37 +090055import org.onosproject.openstacknetworking.api.OpenstackNetworkEvent;
56import org.onosproject.openstacknetworking.api.OpenstackNetworkListener;
57import org.onosproject.openstacknetworking.api.OpenstackNetworkService;
58import org.onosproject.openstacknetworking.api.OpenstackSecurityGroupEvent;
59import org.onosproject.openstacknetworking.api.OpenstackSecurityGroupListener;
60import org.onosproject.openstacknetworking.api.OpenstackSecurityGroupService;
Jian Li26949762018-03-30 15:46:37 +090061import org.onosproject.openstacknetworking.util.RulePopulatorUtil;
sangho3dd2a8b2017-07-19 15:54:31 +090062import org.onosproject.openstacknode.api.OpenstackNode;
sangho1aaa7882017-05-31 13:22:47 +090063import org.onosproject.openstacknode.api.OpenstackNodeEvent;
64import org.onosproject.openstacknode.api.OpenstackNodeListener;
sangho3dd2a8b2017-07-19 15:54:31 +090065import org.onosproject.openstacknode.api.OpenstackNodeService;
sangho6a9ff0d2017-03-27 11:23:37 +090066import org.openstack4j.model.network.Port;
67import org.openstack4j.model.network.SecurityGroup;
68import org.openstack4j.model.network.SecurityGroupRule;
69import org.openstack4j.openstack.networking.domain.NeutronSecurityGroupRule;
sangho0248ca22017-05-31 13:22:47 +090070import org.osgi.service.component.ComponentContext;
sangho6a9ff0d2017-03-27 11:23:37 +090071import org.slf4j.Logger;
72
sangho6a9ff0d2017-03-27 11:23:37 +090073import java.util.Collections;
sangho0248ca22017-05-31 13:22:47 +090074import java.util.Dictionary;
sangho2e97be02017-07-03 18:18:27 +090075import java.util.Map;
sangho6a9ff0d2017-03-27 11:23:37 +090076import java.util.Objects;
77import java.util.Set;
78import java.util.concurrent.ExecutorService;
79import java.util.stream.Collectors;
80
81import static java.util.concurrent.Executors.newSingleThreadExecutor;
82import static org.onlab.util.Tools.groupedThreads;
sanghodc375372017-06-08 10:41:30 +090083import static org.onosproject.openstacknetworking.api.Constants.ACL_TABLE;
sangho3dd2a8b2017-07-19 15:54:31 +090084import static org.onosproject.openstacknetworking.api.Constants.JUMP_TABLE;
sangho1aaa7882017-05-31 13:22:47 +090085import static org.onosproject.openstacknetworking.api.Constants.CT_TABLE;
86import static org.onosproject.openstacknetworking.api.Constants.ERROR_TABLE;
sangho6a9ff0d2017-03-27 11:23:37 +090087import static org.onosproject.openstacknetworking.api.Constants.OPENSTACK_NETWORKING_APP_ID;
88import static org.onosproject.openstacknetworking.api.Constants.PRIORITY_ACL_RULE;
sangho1aaa7882017-05-31 13:22:47 +090089import static org.onosproject.openstacknetworking.api.Constants.PRIORITY_CT_DROP_RULE;
90import static org.onosproject.openstacknetworking.api.Constants.PRIORITY_CT_HOOK_RULE;
91import static org.onosproject.openstacknetworking.api.Constants.PRIORITY_CT_RULE;
92import static org.onosproject.openstacknode.api.OpenstackNode.NodeType.COMPUTE;
sangho6a9ff0d2017-03-27 11:23:37 +090093import static org.slf4j.LoggerFactory.getLogger;
94
95/**
96 * Populates flow rules to handle OpenStack SecurityGroups.
97 */
98@Component(immediate = true)
99public class OpenstackSecurityGroupHandler {
100
101 private final Logger log = getLogger(getClass());
102
sangho0248ca22017-05-31 13:22:47 +0900103 private static final boolean USE_SECURITY_GROUP = false;
104
105 @Property(name = "useSecurityGroup", boolValue = USE_SECURITY_GROUP,
106 label = "Apply OpenStack security group rule for VM traffic")
107 private boolean useSecurityGroup = USE_SECURITY_GROUP;
108
sangho6a9ff0d2017-03-27 11:23:37 +0900109 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
110 protected CoreService coreService;
111
112 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
113 protected InstancePortService instancePortService;
114
115 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
116 protected MastershipService mastershipService;
117
118 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Hyunsun Moonae51e732017-04-25 17:46:21 +0900119 protected OpenstackNetworkService osNetService;
sangho6a9ff0d2017-03-27 11:23:37 +0900120
121 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
122 protected OpenstackSecurityGroupService securityGroupService;
123
124 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
sanghodc375372017-06-08 10:41:30 +0900125 protected OpenstackFlowRuleService osFlowRuleService;
sangho6a9ff0d2017-03-27 11:23:37 +0900126
sangho0248ca22017-05-31 13:22:47 +0900127 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
128 protected ComponentConfigService configService;
129
sangho3dd2a8b2017-07-19 15:54:31 +0900130 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
131 protected OpenstackNodeService osNodeService;
132
sanghoe6457a32017-08-24 14:31:19 +0900133 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
sangho1aaa7882017-05-31 13:22:47 +0900134 protected DriverService driverService;
135
136 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
137 protected LeadershipService leadershipService;
138
139 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
140 protected ClusterService clusterService;
141
sangho6a9ff0d2017-03-27 11:23:37 +0900142 private final InstancePortListener instancePortListener = new InternalInstancePortListener();
143 private final OpenstackNetworkListener portListener = new InternalOpenstackPortListener();
144 private final OpenstackSecurityGroupListener securityGroupListener = new InternalSecurityGroupListener();
sangho1aaa7882017-05-31 13:22:47 +0900145 private final OpenstackNodeListener osNodeListener = new InternalNodeListener();
sangho6a9ff0d2017-03-27 11:23:37 +0900146 private ApplicationId appId;
sangho1aaa7882017-05-31 13:22:47 +0900147 private NodeId localNodeId;
sangho6a9ff0d2017-03-27 11:23:37 +0900148
149 private final ExecutorService eventExecutor = newSingleThreadExecutor(
150 groupedThreads(this.getClass().getSimpleName(), "event-handler"));
151
152 private static final String PROTO_ICMP = "ICMP";
153 private static final String PROTO_TCP = "TCP";
154 private static final String PROTO_UDP = "UDP";
155 private static final String ETHTYPE_IPV4 = "IPV4";
156 private static final String EGRESS = "EGRESS";
157 private static final String INGRESS = "INGRESS";
158 private static final IpPrefix IP_PREFIX_ANY = Ip4Prefix.valueOf("0.0.0.0/0");
159
sangho1aaa7882017-05-31 13:22:47 +0900160 // We expose pipeline structure to SONA application considering removing pipeline soon.
161 private static final int GOTO_CONNTRACK_TABLE = 2;
162 private static final int GOTO_JUMP_TABLE = 3;
163
164 private static final int CT_COMMIT = 0;
165 private static final int CT_NO_COMMIT = 1;
166 private static final short CT_NO_RECIRC = -1;
167
168 private static final int ACTION_NONE = 0;
169 private static final int ACTION_DROP = -1;
170
sangho6a9ff0d2017-03-27 11:23:37 +0900171 @Activate
172 protected void activate() {
173 appId = coreService.registerApplication(OPENSTACK_NETWORKING_APP_ID);
sangho1aaa7882017-05-31 13:22:47 +0900174 localNodeId = clusterService.getLocalNode().id();
sangho6a9ff0d2017-03-27 11:23:37 +0900175 instancePortService.addListener(instancePortListener);
176 securityGroupService.addListener(securityGroupListener);
Hyunsun Moonae51e732017-04-25 17:46:21 +0900177 osNetService.addListener(portListener);
sangho0248ca22017-05-31 13:22:47 +0900178 configService.registerProperties(getClass());
sangho1aaa7882017-05-31 13:22:47 +0900179 osNodeService.addListener(osNodeListener);
sangho6a9ff0d2017-03-27 11:23:37 +0900180
181 log.info("Started");
182 }
183
184 @Deactivate
185 protected void deactivate() {
186 instancePortService.removeListener(instancePortListener);
187 securityGroupService.removeListener(securityGroupListener);
Hyunsun Moonae51e732017-04-25 17:46:21 +0900188 osNetService.removeListener(portListener);
sangho0248ca22017-05-31 13:22:47 +0900189 configService.unregisterProperties(getClass(), false);
sangho1aaa7882017-05-31 13:22:47 +0900190 osNodeService.removeListener(osNodeListener);
sangho6a9ff0d2017-03-27 11:23:37 +0900191 eventExecutor.shutdown();
192
193 log.info("Stopped");
194 }
195
sangho0248ca22017-05-31 13:22:47 +0900196 @Modified
197 protected void modified(ComponentContext context) {
198 Dictionary<?, ?> properties = context.getProperties();
199 Boolean flag;
200
201 flag = Tools.isPropertyEnabled(properties, "useSecurityGroup");
202 if (flag == null) {
203 log.info("useSecurityGroup is not configured, " +
204 "using current value of {}", useSecurityGroup);
205 } else {
206 useSecurityGroup = flag;
207 log.info("Configured. useSecurityGroup is {}",
208 useSecurityGroup ? "enabled" : "disabled");
209 }
210
sanghoe6457a32017-08-24 14:31:19 +0900211 securityGroupService.setSecurityGroupEnabled(useSecurityGroup);
sangho0248ca22017-05-31 13:22:47 +0900212 resetSecurityGroupRules();
213 }
214
sangho1aaa7882017-05-31 13:22:47 +0900215 private void initializeConnTrackTable(DeviceId deviceId, boolean install) {
216
217 //table=1,ip,ct_state=-trk, actions=ct(table:2)
218 long ctState = RulePopulatorUtil.computeCtStateFlag(false, false, false);
219 long ctMask = RulePopulatorUtil.computeCtMaskFlag(true, false, false);
220 setConnTrackRule(deviceId, ctState, ctMask, CT_NO_COMMIT, (short) GOTO_CONNTRACK_TABLE,
221 ACTION_NONE, PRIORITY_CT_HOOK_RULE, install);
222
223 //table=2,ip,nw_dst=10.10.0.2,ct_state=+trk+est,action=goto_table:3
224 ctState = RulePopulatorUtil.computeCtStateFlag(true, false, true);
225 ctMask = RulePopulatorUtil.computeCtMaskFlag(true, false, true);
226 setConnTrackRule(deviceId, ctState, ctMask, CT_NO_COMMIT, CT_NO_RECIRC,
227 GOTO_JUMP_TABLE, PRIORITY_CT_RULE, install);
228
229 //table=2,ip,nw_dst=10.10.0.2,ct_state=+trk+new,action=drop
230 ctState = RulePopulatorUtil.computeCtStateFlag(true, true, false);
231 ctMask = RulePopulatorUtil.computeCtMaskFlag(true, true, false);
232 setConnTrackRule(deviceId, ctState, ctMask, CT_NO_COMMIT, CT_NO_RECIRC,
233 ACTION_DROP, PRIORITY_CT_DROP_RULE, install);
234 }
235
sangho6a9ff0d2017-03-27 11:23:37 +0900236 private void setSecurityGroupRules(InstancePort instPort, Port port, boolean install) {
237 port.getSecurityGroups().forEach(sgId -> {
sangho6a9ff0d2017-03-27 11:23:37 +0900238 SecurityGroup sg = securityGroupService.securityGroup(sgId);
239 if (sg == null) {
240 log.error("Security Group Not Found : {}", sgId);
241 return;
242 }
243 sg.getRules().forEach(sgRule -> updateSecurityGroupRule(instPort, port, sgRule, install));
Hyunsun Moonae51e732017-04-25 17:46:21 +0900244 final String action = install ? "Installed " : "Removed ";
245 log.debug(action + "security group rule ID : " + sgId);
sangho6a9ff0d2017-03-27 11:23:37 +0900246 });
247 }
248
249 private void updateSecurityGroupRule(InstancePort instPort, Port port, SecurityGroupRule sgRule, boolean install) {
sangho2e97be02017-07-03 18:18:27 +0900250
sangho6a9ff0d2017-03-27 11:23:37 +0900251 if (sgRule.getRemoteGroupId() != null && !sgRule.getRemoteGroupId().isEmpty()) {
252 getRemoteInstPorts(port.getTenantId(), sgRule.getRemoteGroupId())
253 .forEach(rInstPort -> {
254 populateSecurityGroupRule(sgRule, instPort, rInstPort.ipAddress().toIpPrefix(), install);
255 populateSecurityGroupRule(sgRule, rInstPort, instPort.ipAddress().toIpPrefix(), install);
256
257 SecurityGroupRule rSgRule = new NeutronSecurityGroupRule.SecurityGroupRuleConcreteBuilder()
258 .from(sgRule)
259 .direction(sgRule.getDirection().toUpperCase().equals(EGRESS) ? INGRESS : EGRESS).build();
260 populateSecurityGroupRule(rSgRule, instPort, rInstPort.ipAddress().toIpPrefix(), install);
261 populateSecurityGroupRule(rSgRule, rInstPort, instPort.ipAddress().toIpPrefix(), install);
262 });
263 } else {
264 populateSecurityGroupRule(sgRule, instPort, sgRule.getRemoteIpPrefix() == null ? IP_PREFIX_ANY :
265 IpPrefix.valueOf(sgRule.getRemoteIpPrefix()), install);
266 }
267 }
268
269 private void populateSecurityGroupRule(SecurityGroupRule sgRule, InstancePort instPort,
270 IpPrefix remoteIp, boolean install) {
sangho2e97be02017-07-03 18:18:27 +0900271 Set<TrafficSelector> selectors = buildSelectors(sgRule,
272 Ip4Address.valueOf(instPort.ipAddress().toInetAddress()), remoteIp);
273 if (selectors == null || selectors.isEmpty()) {
sangho6a9ff0d2017-03-27 11:23:37 +0900274 return;
275 }
276
sangho2e97be02017-07-03 18:18:27 +0900277 selectors.forEach(selector -> {
278 osFlowRuleService.setRule(appId,
279 instPort.deviceId(),
280 selector,
sangho3dd2a8b2017-07-19 15:54:31 +0900281 DefaultTrafficTreatment.builder().transition(JUMP_TABLE).build(),
sangho2e97be02017-07-03 18:18:27 +0900282 PRIORITY_ACL_RULE,
283 ACL_TABLE,
284 install);
285 });
sangho6a9ff0d2017-03-27 11:23:37 +0900286 }
287
288 /**
sangho1aaa7882017-05-31 13:22:47 +0900289 * Sets connection tracking rule using OVS extension commands.
290 * It is not so graceful, but I don't want to make it more general because it is going to be used
Ray Milkeyc108a6b2017-08-23 15:23:50 -0700291 * only here. The following is the usage of the function.
sangho1aaa7882017-05-31 13:22:47 +0900292 *
293 * @param deviceId Device ID
294 * @param ctState ctState: please use RulePopulatorUtil.computeCtStateFlag() to build the value
295 * @param ctMask crMask: please use RulePopulatorUtil.computeCtMaskFlag() to build the value
296 * @param commit CT_COMMIT for commit action, CT_NO_COMMIT otherwise
297 * @param recircTable table number for recirculation after CT actions. CT_NO_RECIRC with no recirculation
298 * @param action Additional actions. ACTION_DROP, ACTION_NONE, GOTO_XXX_TABLE are supported.
299 * @param priority priority value for the rule
300 * @param install true for insertion, false for removal
301 */
302 private void setConnTrackRule(DeviceId deviceId, long ctState, long ctMask,
303 int commit, short recircTable,
304 int action, int priority, boolean install) {
305
306 ExtensionSelector esCtSate = RulePopulatorUtil.buildCtExtensionSelector(driverService, deviceId,
307 ctState, ctMask);
308 TrafficSelector selector = DefaultTrafficSelector.builder()
309 .extension(esCtSate, deviceId)
310 .matchEthType(Ethernet.TYPE_IPV4)
311 .build();
312
313 TrafficTreatment.Builder tb = DefaultTrafficTreatment.builder();
314
315 if (commit == CT_COMMIT || recircTable > 0) {
316 RulePopulatorUtil.NiriraConnTrackTreatmentBuilder natTreatmentBuilder =
317 RulePopulatorUtil.niciraConnTrackTreatmentBuilder(driverService, deviceId);
318 natTreatmentBuilder.natAction(false);
319 if (commit == CT_COMMIT) {
320 natTreatmentBuilder.commit(true);
321 } else {
322 natTreatmentBuilder.commit(false);
323 }
324 if (recircTable > 0) {
325 natTreatmentBuilder.table(recircTable);
326 }
327 tb.extension(natTreatmentBuilder.build(), deviceId);
328 } else if (action == ACTION_DROP) {
329 tb.drop();
330 }
331
332 if (action != ACTION_NONE) {
333 tb.transition(action);
334 }
335
336 int tableType = ERROR_TABLE;
337 if (priority == PRIORITY_CT_RULE || priority == PRIORITY_CT_DROP_RULE) {
338 tableType = CT_TABLE;
339 } else if (priority == PRIORITY_CT_HOOK_RULE) {
340 tableType = ACL_TABLE;
341 } else {
342 log.error("Cannot an appropriate table for the conn track rule.");
343 }
344
345 osFlowRuleService.setRule(
346 appId,
347 deviceId,
348 selector,
349 tb.build(),
350 priority,
351 tableType,
352 install);
353 }
354
355 /**
sangho6a9ff0d2017-03-27 11:23:37 +0900356 * Returns a set of host IP addresses engaged with supplied security group ID.
357 * It only searches a VM in the same tenant boundary.
358 *
359 * @param tenantId tenant id
360 * @param sgId security group id
361 * @return set of ip addresses
362 */
363 private Set<InstancePort> getRemoteInstPorts(String tenantId, String sgId) {
364 Set<InstancePort> remoteInstPorts;
365
Hyunsun Moonae51e732017-04-25 17:46:21 +0900366 remoteInstPorts = osNetService.ports().stream()
sangho6a9ff0d2017-03-27 11:23:37 +0900367 .filter(port -> port.getTenantId().equals(tenantId))
368 .filter(port -> port.getSecurityGroups().contains(sgId))
369 .map(port -> instancePortService.instancePort(port.getId()))
370 .filter(instPort -> instPort != null && instPort.ipAddress() != null)
371 .collect(Collectors.toSet());
372
373 return Collections.unmodifiableSet(remoteInstPorts);
374 }
375
sangho2e97be02017-07-03 18:18:27 +0900376 private Set<TrafficSelector> buildSelectors(SecurityGroupRule sgRule,
377 Ip4Address vmIp,
378 IpPrefix remoteIp) {
379 if (remoteIp != null && remoteIp.equals(IpPrefix.valueOf(vmIp, 32))) {
380 // do nothing if the remote IP is my IP
381 return null;
382 }
383
384 Set<TrafficSelector> selectorSet = Sets.newHashSet();
385
386 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
387 buildMatchs(sBuilder, sgRule, vmIp, remoteIp);
388
389 if (sgRule.getPortRangeMax() != null && sgRule.getPortRangeMin() != null &&
390 sgRule.getPortRangeMin() < sgRule.getPortRangeMax()) {
391 Map<TpPort, TpPort> portRangeMatchMap = buildPortRangeMatches(sgRule.getPortRangeMin(),
392 sgRule.getPortRangeMax());
393 portRangeMatchMap.entrySet().forEach(entry -> {
394
395 if (sgRule.getProtocol().toUpperCase().equals(PROTO_TCP)) {
396 if (sgRule.getDirection().toUpperCase().equals(EGRESS)) {
397 sBuilder.matchTcpSrcMasked(entry.getKey(), entry.getValue());
398 } else {
399 sBuilder.matchTcpDstMasked(entry.getKey(), entry.getValue());
400 }
401 } else if (sgRule.getProtocol().toUpperCase().equals(PROTO_UDP)) {
402 if (sgRule.getDirection().toUpperCase().equals(EGRESS)) {
403 sBuilder.matchUdpSrcMasked(entry.getKey(), entry.getValue());
404 } else {
405 sBuilder.matchUdpDstMasked(entry.getKey(), entry.getValue());
406 }
407 }
408
409 selectorSet.add(sBuilder.build());
410 }
411 );
412 } else {
413 selectorSet.add(sBuilder.build());
414 }
415
416 return selectorSet;
417 }
418
sangho6a9ff0d2017-03-27 11:23:37 +0900419 private void buildMatchs(TrafficSelector.Builder sBuilder, SecurityGroupRule sgRule,
420 Ip4Address vmIp, IpPrefix remoteIp) {
421 buildMatchEthType(sBuilder, sgRule.getEtherType());
422 buildMatchDirection(sBuilder, sgRule.getDirection(), vmIp);
423 buildMatchProto(sBuilder, sgRule.getProtocol());
424 buildMatchPort(sBuilder, sgRule.getProtocol(), sgRule.getDirection(),
sangho2e97be02017-07-03 18:18:27 +0900425 sgRule.getPortRangeMin() == null ? 0 : sgRule.getPortRangeMin(),
426 sgRule.getPortRangeMax() == null ? 0 : sgRule.getPortRangeMax());
sangho6a9ff0d2017-03-27 11:23:37 +0900427 buildMatchRemoteIp(sBuilder, remoteIp, sgRule.getDirection());
428 if (sgRule.getRemoteGroupId() != null && sgRule.getRemoteGroupId().isEmpty()) {
429 buildMatchRemoteIp(sBuilder, remoteIp, sgRule.getDirection());
430 }
431 }
432
433 private void buildMatchDirection(TrafficSelector.Builder sBuilder,
434 String direction,
435 Ip4Address vmIp) {
436 if (direction.toUpperCase().equals(EGRESS)) {
437 sBuilder.matchIPSrc(IpPrefix.valueOf(vmIp, 32));
438 } else {
439 sBuilder.matchIPDst(IpPrefix.valueOf(vmIp, 32));
440 }
441 }
442
443 private void buildMatchEthType(TrafficSelector.Builder sBuilder, String etherType) {
444 // Either IpSrc or IpDst (or both) is set by default, and we need to set EthType as IPv4.
445 sBuilder.matchEthType(Ethernet.TYPE_IPV4);
446 if (etherType != null && !Objects.equals(etherType, "null") &&
447 !etherType.toUpperCase().equals(ETHTYPE_IPV4)) {
448 log.debug("EthType {} is not supported yet in Security Group", etherType);
449 }
450 }
451
452 private void buildMatchRemoteIp(TrafficSelector.Builder sBuilder, IpPrefix remoteIpPrefix, String direction) {
453 if (remoteIpPrefix != null && !remoteIpPrefix.getIp4Prefix().equals(IP_PREFIX_ANY)) {
454 if (direction.toUpperCase().equals(EGRESS)) {
455 sBuilder.matchIPDst(remoteIpPrefix);
456 } else {
457 sBuilder.matchIPSrc(remoteIpPrefix);
458 }
459 }
460 }
461
462 private void buildMatchProto(TrafficSelector.Builder sBuilder, String protocol) {
463 if (protocol != null) {
464 switch (protocol.toUpperCase()) {
465 case PROTO_ICMP:
466 sBuilder.matchIPProtocol(IPv4.PROTOCOL_ICMP);
467 break;
468 case PROTO_TCP:
469 sBuilder.matchIPProtocol(IPv4.PROTOCOL_TCP);
470 break;
471 case PROTO_UDP:
472 sBuilder.matchIPProtocol(IPv4.PROTOCOL_UDP);
473 break;
474 default:
475 }
476 }
477 }
478
479 private void buildMatchPort(TrafficSelector.Builder sBuilder, String protocol, String direction,
480 int portMin, int portMax) {
481 if (portMin > 0 && portMax > 0 && portMin == portMax) {
482 if (protocol.toUpperCase().equals(PROTO_TCP)) {
483 if (direction.toUpperCase().equals(EGRESS)) {
484 sBuilder.matchTcpSrc(TpPort.tpPort(portMax));
485 } else {
486 sBuilder.matchTcpDst(TpPort.tpPort(portMax));
487 }
488 } else if (protocol.toUpperCase().equals(PROTO_UDP)) {
489 if (direction.toUpperCase().equals(EGRESS)) {
490 sBuilder.matchUdpSrc(TpPort.tpPort(portMax));
491 } else {
492 sBuilder.matchUdpDst(TpPort.tpPort(portMax));
493 }
494 }
495 }
496 }
497
sangho0248ca22017-05-31 13:22:47 +0900498 private void resetSecurityGroupRules() {
499
500 if (useSecurityGroup) {
sangho3dd2a8b2017-07-19 15:54:31 +0900501 osNodeService.completeNodes(OpenstackNode.NodeType.COMPUTE)
502 .forEach(node -> osFlowRuleService.setUpTableMissEntry(node.intgBridge(), ACL_TABLE));
sangho0248ca22017-05-31 13:22:47 +0900503 securityGroupService.securityGroups().forEach(securityGroup ->
504 securityGroup.getRules().forEach(this::securityGroupRuleAdded));
sangho1aaa7882017-05-31 13:22:47 +0900505 osNodeService.nodes().stream()
506 .filter(node -> node.type().equals(OpenstackNode.NodeType.COMPUTE))
507 .forEach(node -> initializeConnTrackTable(node .intgBridge(), true));
sangho0248ca22017-05-31 13:22:47 +0900508 } else {
sangho3dd2a8b2017-07-19 15:54:31 +0900509 osNodeService.completeNodes(OpenstackNode.NodeType.COMPUTE)
510 .forEach(node -> osFlowRuleService.connectTables(node.intgBridge(), ACL_TABLE, JUMP_TABLE));
sangho0248ca22017-05-31 13:22:47 +0900511 securityGroupService.securityGroups().forEach(securityGroup ->
512 securityGroup.getRules().forEach(this::securityGroupRuleRemoved));
sangho1aaa7882017-05-31 13:22:47 +0900513 osNodeService.nodes().stream()
514 .filter(node -> node.type().equals(OpenstackNode.NodeType.COMPUTE))
515 .forEach(node -> initializeConnTrackTable(node.intgBridge(), false));
sangho0248ca22017-05-31 13:22:47 +0900516 }
517
518 log.info("Reset security group info " + (useSecurityGroup ? " with " : " without") + " Security Group");
519 }
520
521 private void securityGroupRuleAdded(SecurityGroupRule sgRule) {
522 osNetService.ports().stream()
523 .filter(port -> port.getSecurityGroups().contains(sgRule.getSecurityGroupId()))
524 .forEach(port -> {
525 updateSecurityGroupRule(
526 instancePortService.instancePort(port.getId()),
527 port, sgRule, true);
528 log.debug("Applied security group rule {} to port {}",
529 sgRule.getId(), port.getId());
530 });
531 }
532
533 private void securityGroupRuleRemoved(SecurityGroupRule sgRule) {
534 osNetService.ports().stream()
535 .filter(port -> port.getSecurityGroups().contains(sgRule.getSecurityGroupId()))
536 .forEach(port -> {
537 updateSecurityGroupRule(
538 instancePortService.instancePort(port.getId()),
539 port, sgRule, false);
540 log.debug("Removed security group rule {} from port {}",
541 sgRule.getId(), port.getId());
542 });
543 }
544
sangho2e97be02017-07-03 18:18:27 +0900545 private int binLower(String binStr, int bits) {
546 String outBin = binStr.substring(0, 16 - bits);
547 for (int i = 0; i < bits; i++) {
548 outBin += "0";
549 }
550
551 return Integer.parseInt(outBin, 2);
552 }
553
554 private int binHigher(String binStr, int bits) {
555 String outBin = binStr.substring(0, 16 - bits);
556 for (int i = 0; i < bits; i++) {
557 outBin += "1";
558 }
559
560 return Integer.parseInt(outBin, 2);
561 }
562
563 private int testMasks(String binStr, int start, int end) {
564 int mask = 0;
565 for (; mask <= 16; mask++) {
566 int maskStart = binLower(binStr, mask);
567 int maskEnd = binHigher(binStr, mask);
568 if (maskStart < start || maskEnd > end) {
569 return mask - 1;
570 }
571 }
572
573 return mask;
574 }
575
576 private String getMask(int bits) {
577 switch (bits) {
578 case 0: return "ffff";
579 case 1: return "fffe";
580 case 2: return "fffc";
581 case 3: return "fff8";
582 case 4: return "fff0";
583 case 5: return "ffe0";
584 case 6: return "ffc0";
585 case 7: return "ff80";
586 case 8: return "ff00";
587 case 9: return "fe00";
588 case 10: return "fc00";
589 case 11: return "f800";
590 case 12: return "f000";
591 case 13: return "e000";
592 case 14: return "c000";
593 case 15: return "8000";
594 case 16: return "0000";
595 default: return null;
596 }
597 }
598
599 private Map<TpPort, TpPort> buildPortRangeMatches(int portMin, int portMax) {
600
601 boolean processing = true;
602 int start = portMin;
603 Map<TpPort, TpPort> portMaskMap = Maps.newHashMap();
604 while (processing) {
605 String minStr = Integer.toBinaryString(start);
606 String binStrMinPadded = "0000000000000000".substring(minStr.length()) + minStr;
607
608 int mask = testMasks(binStrMinPadded, start, portMax);
609 int maskStart = binLower(binStrMinPadded, mask);
610 int maskEnd = binHigher(binStrMinPadded, mask);
611
612 log.debug("start : {} port/mask = {} / {} ", start, getMask(mask), maskStart);
613 portMaskMap.put(TpPort.tpPort(maskStart), TpPort.tpPort(Integer.parseInt(getMask(mask), 16)));
614
615 start = maskEnd + 1;
616 if (start > portMax) {
617 processing = false;
618 }
619 }
620
621 return portMaskMap;
622 }
623
sangho6a9ff0d2017-03-27 11:23:37 +0900624 private class InternalInstancePortListener implements InstancePortListener {
625
626 @Override
627 public boolean isRelevant(InstancePortEvent event) {
628 InstancePort instPort = event.subject();
sangho0248ca22017-05-31 13:22:47 +0900629 if (!useSecurityGroup) {
630 return false;
631 }
sangho6a9ff0d2017-03-27 11:23:37 +0900632 return mastershipService.isLocalMaster(instPort.deviceId());
633 }
634
635 @Override
636 public void event(InstancePortEvent event) {
637 InstancePort instPort = event.subject();
638 switch (event.type()) {
639 case OPENSTACK_INSTANCE_PORT_UPDATED:
640 case OPENSTACK_INSTANCE_PORT_DETECTED:
Hyunsun Moonae51e732017-04-25 17:46:21 +0900641 log.debug("Instance port detected MAC:{} IP:{}",
642 instPort.macAddress(),
643 instPort.ipAddress());
sangho6a9ff0d2017-03-27 11:23:37 +0900644 eventExecutor.execute(() -> {
Hyunsun Moonae51e732017-04-25 17:46:21 +0900645 setSecurityGroupRules(instPort,
646 osNetService.port(event.subject().portId()),
647 true);
sangho6a9ff0d2017-03-27 11:23:37 +0900648 });
649 break;
650 case OPENSTACK_INSTANCE_PORT_VANISHED:
Hyunsun Moonae51e732017-04-25 17:46:21 +0900651 log.debug("Instance port vanished MAC:{} IP:{}",
652 instPort.macAddress(),
653 instPort.ipAddress());
sangho6a9ff0d2017-03-27 11:23:37 +0900654 eventExecutor.execute(() -> {
Hyunsun Moonae51e732017-04-25 17:46:21 +0900655 setSecurityGroupRules(instPort,
656 osNetService.port(event.subject().portId()),
657 false);
sangho6a9ff0d2017-03-27 11:23:37 +0900658 });
659 break;
660 default:
661 break;
662 }
663 }
sangho6a9ff0d2017-03-27 11:23:37 +0900664 }
665
666 private class InternalOpenstackPortListener implements OpenstackNetworkListener {
667
668 @Override
669 public boolean isRelevant(OpenstackNetworkEvent event) {
Hyunsun Moonae51e732017-04-25 17:46:21 +0900670 if (event.port() == null || !Strings.isNullOrEmpty(event.port().getId())) {
sangho6a9ff0d2017-03-27 11:23:37 +0900671 return false;
672 }
Hyunsun Moonae51e732017-04-25 17:46:21 +0900673 if (event.securityGroupId() == null ||
674 securityGroupService.securityGroup(event.securityGroupId()) == null) {
675 return false;
676 }
677 if (instancePortService.instancePort(event.port().getId()) == null) {
678 return false;
679 }
sangho0248ca22017-05-31 13:22:47 +0900680 if (!useSecurityGroup) {
681 return false;
682 }
Hyunsun Moonae51e732017-04-25 17:46:21 +0900683 return true;
sangho6a9ff0d2017-03-27 11:23:37 +0900684 }
685
686 @Override
687 public void event(OpenstackNetworkEvent event) {
Hyunsun Moonae51e732017-04-25 17:46:21 +0900688 Port osPort = event.port();
689 InstancePort instPort = instancePortService.instancePort(osPort.getId());
690 SecurityGroup osSg = securityGroupService.securityGroup(event.securityGroupId());
691
sangho6a9ff0d2017-03-27 11:23:37 +0900692 switch (event.type()) {
Hyunsun Moonae51e732017-04-25 17:46:21 +0900693 case OPENSTACK_PORT_SECURITY_GROUP_ADDED:
694 eventExecutor.execute(() -> {
695 osSg.getRules().forEach(sgRule -> {
696 updateSecurityGroupRule(instPort, osPort, sgRule, true);
697 });
698 log.info("Added security group {} to port {}",
699 event.securityGroupId(), event.port().getId());
700 });
sangho6a9ff0d2017-03-27 11:23:37 +0900701 break;
Hyunsun Moonae51e732017-04-25 17:46:21 +0900702 case OPENSTACK_PORT_SECURITY_GROUP_REMOVED:
703 eventExecutor.execute(() -> {
704 osSg.getRules().forEach(sgRule -> {
705 updateSecurityGroupRule(instPort, osPort, sgRule, false);
706 });
707 log.info("Removed security group {} from port {}",
708 event.securityGroupId(), event.port().getId());
709 });
sangho6a9ff0d2017-03-27 11:23:37 +0900710 break;
711 default:
Hyunsun Moonae51e732017-04-25 17:46:21 +0900712 // do nothing for the other events
sangho6a9ff0d2017-03-27 11:23:37 +0900713 break;
714 }
715 }
sangho6a9ff0d2017-03-27 11:23:37 +0900716 }
717
718 private class InternalSecurityGroupListener implements OpenstackSecurityGroupListener {
719
720 @Override
sangho0248ca22017-05-31 13:22:47 +0900721 public boolean isRelevant(OpenstackSecurityGroupEvent event) {
722 if (!useSecurityGroup) {
723 return false;
724 }
725 return true;
726 }
727
728 @Override
sangho6a9ff0d2017-03-27 11:23:37 +0900729 public void event(OpenstackSecurityGroupEvent event) {
730 switch (event.type()) {
sangho6a9ff0d2017-03-27 11:23:37 +0900731 case OPENSTACK_SECURITY_GROUP_RULE_CREATED:
732 SecurityGroupRule securityGroupRuleToAdd = event.securityGroupRule();
733 eventExecutor.execute(() -> {
sangho6a9ff0d2017-03-27 11:23:37 +0900734 securityGroupRuleAdded(securityGroupRuleToAdd);
Hyunsun Moonae51e732017-04-25 17:46:21 +0900735 log.info("Applied new security group rule {} to ports",
736 securityGroupRuleToAdd.getId());
sangho6a9ff0d2017-03-27 11:23:37 +0900737 });
738 break;
739
740 case OPENSTACK_SECURITY_GROUP_RULE_REMOVED:
741 SecurityGroupRule securityGroupRuleToRemove = event.securityGroupRule();
742 eventExecutor.execute(() -> {
sangho6a9ff0d2017-03-27 11:23:37 +0900743 securityGroupRuleRemoved(securityGroupRuleToRemove);
Hyunsun Moonae51e732017-04-25 17:46:21 +0900744 log.info("Removed security group rule {} from ports",
745 securityGroupRuleToRemove.getId());
sangho6a9ff0d2017-03-27 11:23:37 +0900746 });
747 break;
Hyunsun Moonae51e732017-04-25 17:46:21 +0900748 case OPENSTACK_SECURITY_GROUP_CREATED:
749 case OPENSTACK_SECURITY_GROUP_REMOVED:
sangho6a9ff0d2017-03-27 11:23:37 +0900750 default:
Hyunsun Moonae51e732017-04-25 17:46:21 +0900751 // do nothing
752 break;
sangho6a9ff0d2017-03-27 11:23:37 +0900753 }
754 }
sangho6a9ff0d2017-03-27 11:23:37 +0900755 }
sangho1aaa7882017-05-31 13:22:47 +0900756
757 private class InternalNodeListener implements OpenstackNodeListener {
758
759 @Override
760 public boolean isRelevant(OpenstackNodeEvent event) {
761 // do not allow to proceed without leadership
762 NodeId leader = leadershipService.getLeader(appId.name());
763 if (!Objects.equals(localNodeId, leader)) {
764 return false;
765 }
766 return event.subject().type() == COMPUTE;
767 }
768
769 @Override
770 public void event(OpenstackNodeEvent event) {
771 OpenstackNode osNode = event.subject();
772
773 switch (event.type()) {
774 case OPENSTACK_NODE_COMPLETE:
775 eventExecutor.execute(() -> {
776 try {
777 if (useSecurityGroup) {
778 initializeConnTrackTable(osNode.intgBridge(), true);
779 log.warn("SG table initialization : {} is done", osNode.intgBridge());
780 }
781 } catch (IllegalArgumentException e) {
782 log.error("ACL table initialization error : {}", e.getMessage());
783 }
784 });
785 break;
786 case OPENSTACK_NODE_CREATED:
787 case OPENSTACK_NODE_REMOVED:
788 case OPENSTACK_NODE_UPDATED:
789 case OPENSTACK_NODE_INCOMPLETE:
790 default:
791 break;
792 }
793 }
794 }
sangho6a9ff0d2017-03-27 11:23:37 +0900795}