blob: 4e3dbbb7851ab7a774adabb6046d469da23a1644 [file] [log] [blame]
Hyunsun Moon44aac662017-02-18 02:07:01 +09001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2017-present Open Networking Foundation
Hyunsun Moon44aac662017-02-18 02:07:01 +09003 *
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.openstacknetworking.impl;
17
18import com.google.common.base.Strings;
Daniel Parkd9d4c292018-06-26 20:33:58 +090019import com.google.common.collect.ImmutableList;
Hyunsun Moon44aac662017-02-18 02:07:01 +090020import com.google.common.collect.Lists;
Hyunsun Moon44aac662017-02-18 02:07:01 +090021import org.onlab.packet.DHCP;
Hyunsun Moon44aac662017-02-18 02:07:01 +090022import org.onlab.packet.Ethernet;
23import org.onlab.packet.IPv4;
24import org.onlab.packet.Ip4Address;
Daniel Park4d421002018-07-27 23:36:57 +090025import org.onlab.packet.IpAddress;
Hyunsun Moon44aac662017-02-18 02:07:01 +090026import org.onlab.packet.IpPrefix;
27import org.onlab.packet.MacAddress;
28import org.onlab.packet.TpPort;
29import org.onlab.packet.UDP;
daniel park796c2eb2018-03-22 17:01:51 +090030import org.onlab.packet.dhcp.DhcpOption;
Hyunsun Moon44aac662017-02-18 02:07:01 +090031import org.onlab.util.Tools;
32import org.onosproject.cfg.ComponentConfigService;
daniel park15506e82018-04-04 18:52:16 +090033import org.onosproject.cluster.ClusterService;
34import org.onosproject.cluster.LeadershipService;
35import org.onosproject.cluster.NodeId;
Hyunsun Moon44aac662017-02-18 02:07:01 +090036import org.onosproject.core.ApplicationId;
37import org.onosproject.core.CoreService;
38import org.onosproject.net.ConnectPoint;
39import org.onosproject.net.flow.DefaultTrafficSelector;
40import org.onosproject.net.flow.DefaultTrafficTreatment;
41import org.onosproject.net.flow.TrafficSelector;
42import org.onosproject.net.flow.TrafficTreatment;
43import org.onosproject.net.packet.DefaultOutboundPacket;
44import org.onosproject.net.packet.PacketContext;
Hyunsun Moon44aac662017-02-18 02:07:01 +090045import org.onosproject.net.packet.PacketProcessor;
46import org.onosproject.net.packet.PacketService;
47import org.onosproject.openstacknetworking.api.Constants;
48import org.onosproject.openstacknetworking.api.InstancePort;
49import org.onosproject.openstacknetworking.api.InstancePortService;
daniel park796c2eb2018-03-22 17:01:51 +090050import org.onosproject.openstacknetworking.api.OpenstackFlowRuleService;
Hyunsun Moon44aac662017-02-18 02:07:01 +090051import org.onosproject.openstacknetworking.api.OpenstackNetworkService;
daniel park15506e82018-04-04 18:52:16 +090052import org.onosproject.openstacknode.api.OpenstackNode;
53import org.onosproject.openstacknode.api.OpenstackNodeEvent;
54import org.onosproject.openstacknode.api.OpenstackNodeListener;
daniel park796c2eb2018-03-22 17:01:51 +090055import org.onosproject.openstacknode.api.OpenstackNodeService;
Daniel Parkd9d4c292018-06-26 20:33:58 +090056import org.openstack4j.model.network.HostRoute;
Hyunsun Moon44aac662017-02-18 02:07:01 +090057import org.openstack4j.model.network.IP;
Daniel Park468e7852018-07-28 00:38:45 +090058import org.openstack4j.model.network.Network;
Hyunsun Moon44aac662017-02-18 02:07:01 +090059import org.openstack4j.model.network.Port;
60import org.openstack4j.model.network.Subnet;
61import org.osgi.service.component.ComponentContext;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070062import org.osgi.service.component.annotations.Activate;
63import org.osgi.service.component.annotations.Component;
64import org.osgi.service.component.annotations.Deactivate;
65import org.osgi.service.component.annotations.Modified;
66import org.osgi.service.component.annotations.Reference;
67import org.osgi.service.component.annotations.ReferenceCardinality;
Hyunsun Moon44aac662017-02-18 02:07:01 +090068import org.slf4j.Logger;
69
70import java.nio.ByteBuffer;
71import java.util.Dictionary;
72import java.util.List;
daniel park15506e82018-04-04 18:52:16 +090073import java.util.Objects;
Jian Li32b03622018-11-06 17:54:24 +090074import java.util.concurrent.ExecutorService;
Hyunsun Moon44aac662017-02-18 02:07:01 +090075
Daniel Parkf8e422d2018-07-30 14:14:37 +090076import static com.google.common.base.Preconditions.checkNotNull;
Jian Li32b03622018-11-06 17:54:24 +090077import static java.util.concurrent.Executors.newSingleThreadExecutor;
daniel park796c2eb2018-03-22 17:01:51 +090078import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_BroadcastAddress;
Daniel Parkd9d4c292018-06-26 20:33:58 +090079import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_Classless_Static_Route;
daniel park796c2eb2018-03-22 17:01:51 +090080import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_DHCPServerIp;
81import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_DomainServer;
82import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_END;
83import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_LeaseTime;
84import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_MessageType;
Daniel Park48f10332018-08-02 10:57:27 +090085import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_RouterAddress;
daniel park796c2eb2018-03-22 17:01:51 +090086import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_SubnetMask;
Yi Tsengc7403c22017-06-19 16:23:22 -070087import static org.onlab.packet.DHCP.MsgType.DHCPACK;
88import static org.onlab.packet.DHCP.MsgType.DHCPOFFER;
Jian Li32b03622018-11-06 17:54:24 +090089import static org.onlab.util.Tools.groupedThreads;
Jian Li5c09e212018-10-24 18:23:58 +090090import static org.onosproject.openstacknetworking.api.Constants.DHCP_TABLE;
daniel park796c2eb2018-03-22 17:01:51 +090091import static org.onosproject.openstacknetworking.api.Constants.PRIORITY_DHCP_RULE;
Ray Milkey8e406512018-10-24 15:56:50 -070092import static org.onosproject.openstacknetworking.impl.OsgiPropertyConstants.DHCP_SERVER_MAC;
93import static org.onosproject.openstacknetworking.impl.OsgiPropertyConstants.DHCP_SERVER_MAC_DEFAULT;
Jian Lifb64d882018-11-27 10:57:40 +090094import static org.onosproject.openstacknode.api.OpenstackNode.NodeType.COMPUTE;
Hyunsun Moon44aac662017-02-18 02:07:01 +090095import static org.slf4j.LoggerFactory.getLogger;
96
97/**
98 * Handles DHCP requests for the virtual instances.
99 */
Ray Milkey8e406512018-10-24 15:56:50 -0700100@Component(
101 immediate = true,
102 property = {
103 DHCP_SERVER_MAC + "=" + DHCP_SERVER_MAC_DEFAULT
104 }
105)
Hyunsun Moon44aac662017-02-18 02:07:01 +0900106public class OpenstackSwitchingDhcpHandler {
107 protected final Logger log = getLogger(getClass());
108
Daniel Park4d421002018-07-27 23:36:57 +0900109 private static final Ip4Address DEFAULT_PRIMARY_DNS = Ip4Address.valueOf("8.8.8.8");
110 private static final Ip4Address DEFAULT_SECONDARY_DNS = Ip4Address.valueOf("8.8.4.4");
Hyunsun Moon44aac662017-02-18 02:07:01 +0900111 private static final byte PACKET_TTL = (byte) 127;
112 // TODO add MTU, static route option codes to ONOS DHCP and remove here
113 private static final byte DHCP_OPTION_MTU = (byte) 26;
114 private static final byte[] DHCP_DATA_LEASE_INFINITE =
115 ByteBuffer.allocate(4).putInt(-1).array();
Jian Li6a47fd02018-11-27 21:51:03 +0900116
Daniel Parkd9d4c292018-06-26 20:33:58 +0900117 private static final int OCTET_BIT_LENGTH = 8;
118 private static final int V4_BYTE_SIZE = 4;
Daniel Parkf8e422d2018-07-30 14:14:37 +0900119 private static final int V4_CIDR_LOWER_BOUND = -1;
Daniel Parkd9d4c292018-06-26 20:33:58 +0900120 private static final int V4_CIDR_UPPER_BOUND = 33;
121 private static final int PADDING_SIZE = 4;
Hyunsun Moon44aac662017-02-18 02:07:01 +0900122
Jian Li411bf2e2018-11-29 00:08:54 +0900123 private static final byte HARDWARE_ADDR_LENGTH = (byte) 6;
124 private static final byte DHCP_OPTION_DATA_LENGTH = (byte) 4;
125 private static final int DHCP_OPTION_DNS_LENGTH = 8;
126 private static final int DHCP_OPTION_MTU_LENGTH = 2;
127
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700128 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Hyunsun Moon44aac662017-02-18 02:07:01 +0900129 protected CoreService coreService;
130
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700131 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Hyunsun Moon44aac662017-02-18 02:07:01 +0900132 protected ComponentConfigService configService;
133
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700134 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Hyunsun Moon44aac662017-02-18 02:07:01 +0900135 protected PacketService packetService;
136
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700137 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Hyunsun Moon44aac662017-02-18 02:07:01 +0900138 protected InstancePortService instancePortService;
139
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700140 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Hyunsun Moon44aac662017-02-18 02:07:01 +0900141 protected OpenstackNetworkService osNetworkService;
142
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700143 @Reference(cardinality = ReferenceCardinality.MANDATORY)
daniel park796c2eb2018-03-22 17:01:51 +0900144 protected OpenstackNodeService osNodeService;
145
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700146 @Reference(cardinality = ReferenceCardinality.MANDATORY)
daniel park796c2eb2018-03-22 17:01:51 +0900147 protected OpenstackFlowRuleService osFlowRuleService;
148
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700149 @Reference(cardinality = ReferenceCardinality.MANDATORY)
daniel park15506e82018-04-04 18:52:16 +0900150 protected ClusterService clusterService;
151
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700152 @Reference(cardinality = ReferenceCardinality.MANDATORY)
daniel park15506e82018-04-04 18:52:16 +0900153 protected LeadershipService leadershipService;
154
Ray Milkey8e406512018-10-24 15:56:50 -0700155 /** Fake MAC address for virtual network subnet gateway. */
156 private String dhcpServerMac = DHCP_SERVER_MAC_DEFAULT;
Hyunsun Moon44aac662017-02-18 02:07:01 +0900157
158 private final PacketProcessor packetProcessor = new InternalPacketProcessor();
daniel park15506e82018-04-04 18:52:16 +0900159 private final OpenstackNodeListener osNodeListener = new InternalNodeEventListener();
Hyunsun Moon44aac662017-02-18 02:07:01 +0900160
Jian Li32b03622018-11-06 17:54:24 +0900161 private final ExecutorService eventExecutor = newSingleThreadExecutor(
162 groupedThreads(this.getClass().getSimpleName(), "event-handler"));
163
Hyunsun Moon44aac662017-02-18 02:07:01 +0900164 private ApplicationId appId;
daniel park15506e82018-04-04 18:52:16 +0900165 private NodeId localNodeId;
Hyunsun Moon44aac662017-02-18 02:07:01 +0900166
167 @Activate
168 protected void activate() {
169 appId = coreService.registerApplication(Constants.OPENSTACK_NETWORKING_APP_ID);
daniel park15506e82018-04-04 18:52:16 +0900170 localNodeId = clusterService.getLocalNode().id();
171 osNodeService.addListener(osNodeListener);
Hyunsun Moon44aac662017-02-18 02:07:01 +0900172 configService.registerProperties(getClass());
173 packetService.addProcessor(packetProcessor, PacketProcessor.director(0));
daniel park15506e82018-04-04 18:52:16 +0900174 leadershipService.runForLeadership(appId.name());
Hyunsun Moon44aac662017-02-18 02:07:01 +0900175
176 log.info("Started");
177 }
178
179 @Deactivate
180 protected void deactivate() {
Hyunsun Moon44aac662017-02-18 02:07:01 +0900181 packetService.removeProcessor(packetProcessor);
daniel park15506e82018-04-04 18:52:16 +0900182 osNodeService.removeListener(osNodeListener);
Hyunsun Moon44aac662017-02-18 02:07:01 +0900183 configService.unregisterProperties(getClass(), false);
daniel park15506e82018-04-04 18:52:16 +0900184 leadershipService.withdraw(appId.name());
Jian Li32b03622018-11-06 17:54:24 +0900185 eventExecutor.shutdown();
Hyunsun Moon44aac662017-02-18 02:07:01 +0900186
187 log.info("Stopped");
188 }
189
190 @Modified
191 protected void modified(ComponentContext context) {
192 Dictionary<?, ?> properties = context.getProperties();
193 String updatedMac;
194
195 updatedMac = Tools.get(properties, DHCP_SERVER_MAC);
Jian Lifb005492018-03-02 10:50:15 +0900196
Hyunsun Moon44aac662017-02-18 02:07:01 +0900197 if (!Strings.isNullOrEmpty(updatedMac) && !updatedMac.equals(dhcpServerMac)) {
198 dhcpServerMac = updatedMac;
199 }
200
201 log.info("Modified");
202 }
203
Hyunsun Moon44aac662017-02-18 02:07:01 +0900204 private class InternalPacketProcessor implements PacketProcessor {
205
206 @Override
207 public void process(PacketContext context) {
208 if (context.isHandled()) {
209 return;
210 }
211
212 Ethernet ethPacket = context.inPacket().parsed();
213 if (ethPacket == null || ethPacket.getEtherType() != Ethernet.TYPE_IPV4) {
214 return;
215 }
216 IPv4 ipv4Packet = (IPv4) ethPacket.getPayload();
217 if (ipv4Packet.getProtocol() != IPv4.PROTOCOL_UDP) {
218 return;
219 }
220 UDP udpPacket = (UDP) ipv4Packet.getPayload();
221 if (udpPacket.getDestinationPort() != UDP.DHCP_SERVER_PORT ||
222 udpPacket.getSourcePort() != UDP.DHCP_CLIENT_PORT) {
223 return;
224 }
225
226 DHCP dhcpPacket = (DHCP) udpPacket.getPayload();
Jian Li32b03622018-11-06 17:54:24 +0900227
228 eventExecutor.execute(() -> processDhcp(context, dhcpPacket));
Hyunsun Moon44aac662017-02-18 02:07:01 +0900229 }
230
231 private void processDhcp(PacketContext context, DHCP dhcpPacket) {
232 if (dhcpPacket == null) {
233 log.trace("DHCP packet without payload received, do nothing");
234 return;
235 }
236
Yi Tsengc7403c22017-06-19 16:23:22 -0700237 DHCP.MsgType inPacketType = getPacketType(dhcpPacket);
Hyunsun Moon44aac662017-02-18 02:07:01 +0900238 if (inPacketType == null || dhcpPacket.getClientHardwareAddress() == null) {
239 log.trace("Malformed DHCP packet received, ignore it");
240 return;
241 }
242
243 MacAddress clientMac = MacAddress.valueOf(dhcpPacket.getClientHardwareAddress());
244 InstancePort reqInstPort = instancePortService.instancePort(clientMac);
245 if (reqInstPort == null) {
246 log.trace("Failed to find host(MAC:{})", clientMac);
247 return;
248 }
249 Ethernet ethPacket = context.inPacket().parsed();
250 switch (inPacketType) {
251 case DHCPDISCOVER:
Jian Li6a47fd02018-11-27 21:51:03 +0900252 processDhcpDiscover(context, clientMac, reqInstPort, ethPacket);
Hyunsun Moon44aac662017-02-18 02:07:01 +0900253 break;
254 case DHCPREQUEST:
Jian Li6a47fd02018-11-27 21:51:03 +0900255 processDhcpRequest(context, clientMac, reqInstPort, ethPacket);
Hyunsun Moon44aac662017-02-18 02:07:01 +0900256 break;
257 case DHCPRELEASE:
258 log.trace("DHCP RELEASE received from {}", clientMac);
259 // do nothing
260 break;
261 default:
262 break;
263 }
264 }
265
Jian Li6a47fd02018-11-27 21:51:03 +0900266 private void processDhcpDiscover(PacketContext context, MacAddress clientMac,
267 InstancePort instPort, Ethernet ethPacket) {
268 log.trace("DHCP DISCOVER received from {}", clientMac);
269 Ethernet discoverReply = buildReply(ethPacket,
270 (byte) DHCPOFFER.getValue(),
271 instPort);
272 sendReply(context, discoverReply);
273 log.trace("DHCP OFFER({}) is sent for {}", instPort.ipAddress(), clientMac);
274 }
275
276 private void processDhcpRequest(PacketContext context, MacAddress clientMac,
277 InstancePort instPort, Ethernet ethPacket) {
278 log.trace("DHCP REQUEST received from {}", clientMac);
279 Ethernet requestReply = buildReply(ethPacket,
280 (byte) DHCPACK.getValue(),
281 instPort);
282 sendReply(context, requestReply);
283 log.trace("DHCP ACK({}) is sent for {}", instPort.ipAddress(), clientMac);
284 }
285
Yi Tsengc7403c22017-06-19 16:23:22 -0700286 private DHCP.MsgType getPacketType(DHCP dhcpPacket) {
287 DhcpOption optType = dhcpPacket.getOption(OptionCode_MessageType);
Hyunsun Moon44aac662017-02-18 02:07:01 +0900288 if (optType == null) {
289 log.trace("DHCP packet with no message type, ignore it");
290 return null;
291 }
292
Yi Tsengc7403c22017-06-19 16:23:22 -0700293 DHCP.MsgType inPacketType = DHCP.MsgType.getType(optType.getData()[0]);
Hyunsun Moon44aac662017-02-18 02:07:01 +0900294 if (inPacketType == null) {
295 log.trace("DHCP packet with no packet type, ignore it");
296 }
297 return inPacketType;
298 }
299
300 private Ethernet buildReply(Ethernet ethRequest, byte packetType,
301 InstancePort reqInstPort) {
Daniel Parke0945c12018-08-28 17:22:25 +0900302 log.trace("Build for DHCP reply msg for instance port {}", reqInstPort.toString());
Hyunsun Moon44aac662017-02-18 02:07:01 +0900303 Port osPort = osNetworkService.port(reqInstPort.portId());
Daniel Parke0945c12018-08-28 17:22:25 +0900304 if (osPort == null) {
305 log.error("Failed to retrieve openstack port information for instance port {}",
306 reqInstPort.toString());
Ray Milkey92815932018-08-28 10:32:17 -0700307 return null;
Daniel Parke0945c12018-08-28 17:22:25 +0900308 }
Hyunsun Moon44aac662017-02-18 02:07:01 +0900309 // pick one IP address to make a reply
310 IP fixedIp = osPort.getFixedIps().stream().findFirst().get();
311 Subnet osSubnet = osNetworkService.subnet(fixedIp.getSubnetId());
312
313 Ethernet ethReply = new Ethernet();
314 ethReply.setSourceMACAddress(dhcpServerMac);
315 ethReply.setDestinationMACAddress(ethRequest.getSourceMAC());
316 ethReply.setEtherType(Ethernet.TYPE_IPV4);
317
318 IPv4 ipv4Request = (IPv4) ethRequest.getPayload();
319 IPv4 ipv4Reply = new IPv4();
daniel park15506e82018-04-04 18:52:16 +0900320
321 ipv4Reply.setSourceAddress(clusterService.getLocalNode().ip().getIp4Address().toString());
Hyunsun Moon44aac662017-02-18 02:07:01 +0900322 ipv4Reply.setDestinationAddress(reqInstPort.ipAddress().getIp4Address().toInt());
323 ipv4Reply.setTtl(PACKET_TTL);
324
325 UDP udpRequest = (UDP) ipv4Request.getPayload();
326 UDP udpReply = new UDP();
327 udpReply.setSourcePort((byte) UDP.DHCP_SERVER_PORT);
328 udpReply.setDestinationPort((byte) UDP.DHCP_CLIENT_PORT);
329
330 DHCP dhcpRequest = (DHCP) udpRequest.getPayload();
331 DHCP dhcpReply = buildDhcpReply(
332 dhcpRequest,
333 packetType,
334 reqInstPort.ipAddress().getIp4Address(),
335 osSubnet);
336
337 udpReply.setPayload(dhcpReply);
338 ipv4Reply.setPayload(udpReply);
339 ethReply.setPayload(ipv4Reply);
340
341 return ethReply;
342 }
343
344 private void sendReply(PacketContext context, Ethernet ethReply) {
345 if (ethReply == null) {
346 return;
347 }
348 ConnectPoint srcPoint = context.inPacket().receivedFrom();
349 TrafficTreatment treatment = DefaultTrafficTreatment
350 .builder()
351 .setOutput(srcPoint.port())
352 .build();
353
354 packetService.emit(new DefaultOutboundPacket(
355 srcPoint.deviceId(),
356 treatment,
357 ByteBuffer.wrap(ethReply.serialize())));
358 context.block();
359 }
360
361 private DHCP buildDhcpReply(DHCP request, byte msgType, Ip4Address yourIp,
362 Subnet osSubnet) {
daniel park15506e82018-04-04 18:52:16 +0900363 Ip4Address gatewayIp = clusterService.getLocalNode().ip().getIp4Address();
Hyunsun Moon44aac662017-02-18 02:07:01 +0900364 int subnetPrefixLen = IpPrefix.valueOf(osSubnet.getCidr()).prefixLength();
365
366 DHCP dhcpReply = new DHCP();
367 dhcpReply.setOpCode(DHCP.OPCODE_REPLY);
368 dhcpReply.setHardwareType(DHCP.HWTYPE_ETHERNET);
Jian Li411bf2e2018-11-29 00:08:54 +0900369 dhcpReply.setHardwareAddressLength(HARDWARE_ADDR_LENGTH);
Hyunsun Moon44aac662017-02-18 02:07:01 +0900370 dhcpReply.setTransactionId(request.getTransactionId());
371 dhcpReply.setFlags(request.getFlags());
372 dhcpReply.setYourIPAddress(yourIp.toInt());
373 dhcpReply.setServerIPAddress(gatewayIp.toInt());
374 dhcpReply.setClientHardwareAddress(request.getClientHardwareAddress());
375
Yi Tsengc7403c22017-06-19 16:23:22 -0700376 List<DhcpOption> options = Lists.newArrayList();
Jian Li6a47fd02018-11-27 21:51:03 +0900377
Hyunsun Moon44aac662017-02-18 02:07:01 +0900378 // message type
Jian Li6a47fd02018-11-27 21:51:03 +0900379 options.add(doMsgType(msgType));
380
381 // server identifier
382 options.add(doServerId(gatewayIp));
383
384 // lease time
385 options.add(doLeaseTime());
386
387 // subnet mask
388 options.add(doSubnetMask(subnetPrefixLen));
389
390 // broadcast address
391 options.add(doBroadcastAddr(yourIp, subnetPrefixLen));
392
393 // domain server
394 options.add(doDomainServer(osSubnet));
395
396 // mtu
397 options.add(doMtu(osSubnet));
398
399 // classless static route
400 if (!osSubnet.getHostRoutes().isEmpty()) {
401 options.add(doClasslessSr(osSubnet));
402 }
403
404 // Sets the default router address up.
405 // Performs only if the gateway is set in subnet.
406 if (!Strings.isNullOrEmpty(osSubnet.getGateway())) {
407 options.add(doRouterAddr(osSubnet));
408 }
409
410 // end option
411 options.add(doEnd());
412
413 dhcpReply.setOptions(options);
414 return dhcpReply;
415 }
416
417
418 private DhcpOption doMsgType(byte msgType) {
Yi Tsengc7403c22017-06-19 16:23:22 -0700419 DhcpOption option = new DhcpOption();
Hyunsun Moon44aac662017-02-18 02:07:01 +0900420 option.setCode(OptionCode_MessageType.getValue());
421 option.setLength((byte) 1);
422 byte[] optionData = {msgType};
423 option.setData(optionData);
Jian Li6a47fd02018-11-27 21:51:03 +0900424 return option;
425 }
Hyunsun Moon44aac662017-02-18 02:07:01 +0900426
Jian Li6a47fd02018-11-27 21:51:03 +0900427 private DhcpOption doServerId(IpAddress gatewayIp) {
428 DhcpOption option = new DhcpOption();
Hyunsun Moon44aac662017-02-18 02:07:01 +0900429 option.setCode(OptionCode_DHCPServerIp.getValue());
Jian Li411bf2e2018-11-29 00:08:54 +0900430 option.setLength(DHCP_OPTION_DATA_LENGTH);
Hyunsun Moon44aac662017-02-18 02:07:01 +0900431 option.setData(gatewayIp.toOctets());
Jian Li6a47fd02018-11-27 21:51:03 +0900432 return option;
433 }
Hyunsun Moon44aac662017-02-18 02:07:01 +0900434
Jian Li6a47fd02018-11-27 21:51:03 +0900435 private DhcpOption doLeaseTime() {
436 DhcpOption option = new DhcpOption();
Hyunsun Moon44aac662017-02-18 02:07:01 +0900437 option.setCode(OptionCode_LeaseTime.getValue());
Jian Li411bf2e2018-11-29 00:08:54 +0900438 option.setLength(DHCP_OPTION_DATA_LENGTH);
Hyunsun Moon44aac662017-02-18 02:07:01 +0900439 option.setData(DHCP_DATA_LEASE_INFINITE);
Jian Li6a47fd02018-11-27 21:51:03 +0900440 return option;
441 }
Hyunsun Moon44aac662017-02-18 02:07:01 +0900442
Jian Li6a47fd02018-11-27 21:51:03 +0900443 private DhcpOption doSubnetMask(int subnetPrefixLen) {
Hyunsun Moon44aac662017-02-18 02:07:01 +0900444 Ip4Address subnetMask = Ip4Address.makeMaskPrefix(subnetPrefixLen);
Jian Li6a47fd02018-11-27 21:51:03 +0900445 DhcpOption option = new DhcpOption();
Hyunsun Moon44aac662017-02-18 02:07:01 +0900446 option.setCode(OptionCode_SubnetMask.getValue());
Jian Li411bf2e2018-11-29 00:08:54 +0900447 option.setLength(DHCP_OPTION_DATA_LENGTH);
Hyunsun Moon44aac662017-02-18 02:07:01 +0900448 option.setData(subnetMask.toOctets());
Jian Li6a47fd02018-11-27 21:51:03 +0900449 return option;
450 }
Hyunsun Moon44aac662017-02-18 02:07:01 +0900451
Jian Li6a47fd02018-11-27 21:51:03 +0900452 private DhcpOption doBroadcastAddr(Ip4Address yourIp, int subnetPrefixLen) {
Hyunsun Moon44aac662017-02-18 02:07:01 +0900453 Ip4Address broadcast = Ip4Address.makeMaskedAddress(yourIp, subnetPrefixLen);
Jian Li6a47fd02018-11-27 21:51:03 +0900454 DhcpOption option = new DhcpOption();
Hyunsun Moon44aac662017-02-18 02:07:01 +0900455 option.setCode(OptionCode_BroadcastAddress.getValue());
Jian Li411bf2e2018-11-29 00:08:54 +0900456 option.setLength(DHCP_OPTION_DATA_LENGTH);
Hyunsun Moon44aac662017-02-18 02:07:01 +0900457 option.setData(broadcast.toOctets());
Jian Li6a47fd02018-11-27 21:51:03 +0900458 return option;
459 }
Hyunsun Moon44aac662017-02-18 02:07:01 +0900460
Jian Li6a47fd02018-11-27 21:51:03 +0900461 private DhcpOption doDomainServer(Subnet osSubnet) {
462 DhcpOption option = new DhcpOption();
Daniel Park4d421002018-07-27 23:36:57 +0900463
464 List<String> dnsServers = osSubnet.getDnsNames();
Hyunsun Moon44aac662017-02-18 02:07:01 +0900465 option.setCode(OptionCode_DomainServer.getValue());
Daniel Park4d421002018-07-27 23:36:57 +0900466
467 if (dnsServers.isEmpty()) {
Jian Li411bf2e2018-11-29 00:08:54 +0900468 option.setLength((byte) DHCP_OPTION_DNS_LENGTH);
469 ByteBuffer dnsByteBuf = ByteBuffer.allocate(DHCP_OPTION_DNS_LENGTH);
Daniel Park4d421002018-07-27 23:36:57 +0900470 dnsByteBuf.put(DEFAULT_PRIMARY_DNS.toOctets());
471 dnsByteBuf.put(DEFAULT_SECONDARY_DNS.toOctets());
472
473 option.setData(dnsByteBuf.array());
474 } else {
475 int dnsLength = 4 * dnsServers.size();
476
477 option.setLength((byte) dnsLength);
478
Jian Li411bf2e2018-11-29 00:08:54 +0900479 ByteBuffer dnsByteBuf = ByteBuffer.allocate(DHCP_OPTION_DNS_LENGTH);
Daniel Park4d421002018-07-27 23:36:57 +0900480
Jian Li6a47fd02018-11-27 21:51:03 +0900481 for (String dnsServer : dnsServers) {
482 dnsByteBuf.put(IpAddress.valueOf(dnsServer).toOctets());
Daniel Park4d421002018-07-27 23:36:57 +0900483 }
484 option.setData(dnsByteBuf.array());
485 }
486
Jian Li6a47fd02018-11-27 21:51:03 +0900487 return option;
488 }
Hyunsun Moon44aac662017-02-18 02:07:01 +0900489
Jian Li6a47fd02018-11-27 21:51:03 +0900490 private DhcpOption doMtu(Subnet osSubnet) {
491 DhcpOption option = new DhcpOption();
Hyunsun Moon44aac662017-02-18 02:07:01 +0900492 option.setCode(DHCP_OPTION_MTU);
Jian Li411bf2e2018-11-29 00:08:54 +0900493 option.setLength((byte) DHCP_OPTION_MTU_LENGTH);
Daniel Park468e7852018-07-28 00:38:45 +0900494 Network osNetwork = osNetworkService.network(osSubnet.getNetworkId());
495 checkNotNull(osNetwork);
496 checkNotNull(osNetwork.getMTU());
497
Jian Li411bf2e2018-11-29 00:08:54 +0900498 option.setData(ByteBuffer.allocate(DHCP_OPTION_MTU_LENGTH)
499 .putShort(osNetwork.getMTU().shortValue()).array());
Hyunsun Moon44aac662017-02-18 02:07:01 +0900500
Jian Li6a47fd02018-11-27 21:51:03 +0900501 return option;
502 }
Daniel Parkd9d4c292018-06-26 20:33:58 +0900503
Jian Li6a47fd02018-11-27 21:51:03 +0900504 private DhcpOption doClasslessSr(Subnet osSubnet) {
505 DhcpOption option = new DhcpOption();
506 option.setCode(OptionCode_Classless_Static_Route.getValue());
Daniel Parkd9d4c292018-06-26 20:33:58 +0900507
Jian Li6a47fd02018-11-27 21:51:03 +0900508 int hostRoutesSize = hostRoutesSize(ImmutableList.copyOf(osSubnet.getHostRoutes()));
509 if (hostRoutesSize == 0) {
510 throw new IllegalArgumentException("Illegal CIDR hostRoutesSize value!");
Daniel Parkd9d4c292018-06-26 20:33:58 +0900511 }
512
Jian Li6a47fd02018-11-27 21:51:03 +0900513 log.trace("hostRouteSize: {}", hostRoutesSize);
Daniel Park48f10332018-08-02 10:57:27 +0900514
Jian Li6a47fd02018-11-27 21:51:03 +0900515 option.setLength((byte) hostRoutesSize);
516 ByteBuffer hostRouteByteBuf = ByteBuffer.allocate(hostRoutesSize);
517
518 osSubnet.getHostRoutes().forEach(h -> {
519 log.debug("processing host route information: {}", h.toString());
520
521 IpPrefix ipPrefix = IpPrefix.valueOf(h.getDestination());
522
523 hostRouteByteBuf.put(Objects.requireNonNull(bytesDestinationDescriptor(ipPrefix)));
524
525 hostRouteByteBuf.put(Ip4Address.valueOf(h.getNexthop()).toOctets());
526 });
527
528 option.setData(hostRouteByteBuf.array());
529 return option;
530 }
531
532 private DhcpOption doRouterAddr(Subnet osSubnet) {
533 DhcpOption option = new DhcpOption();
534 option.setCode(OptionCode_RouterAddress.getValue());
Jian Li411bf2e2018-11-29 00:08:54 +0900535 option.setLength(DHCP_OPTION_DATA_LENGTH);
Jian Li6a47fd02018-11-27 21:51:03 +0900536 option.setData(Ip4Address.valueOf(osSubnet.getGateway()).toOctets());
537 return option;
538 }
539
540 private DhcpOption doEnd() {
541 DhcpOption option = new DhcpOption();
Hyunsun Moon44aac662017-02-18 02:07:01 +0900542 option.setCode(OptionCode_END.getValue());
543 option.setLength((byte) 1);
Jian Li6a47fd02018-11-27 21:51:03 +0900544 return option;
Hyunsun Moon44aac662017-02-18 02:07:01 +0900545 }
Daniel Parkd9d4c292018-06-26 20:33:58 +0900546
547 private int hostRoutesSize(List<HostRoute> hostRoutes) {
548 int size = 0;
549 int preFixLen;
550
551 for (HostRoute h : hostRoutes) {
552 preFixLen = IpPrefix.valueOf(h.getDestination()).prefixLength();
553 if (Math.max(V4_CIDR_LOWER_BOUND, preFixLen) == V4_CIDR_LOWER_BOUND ||
554 Math.min(preFixLen, V4_CIDR_UPPER_BOUND) == V4_CIDR_UPPER_BOUND) {
555 throw new IllegalArgumentException("Illegal CIDR length value!");
556 }
557
Daniel Parkf8e422d2018-07-30 14:14:37 +0900558 for (int i = 0; i <= V4_BYTE_SIZE; i++) {
Daniel Parkd9d4c292018-06-26 20:33:58 +0900559 if (preFixLen == Math.min(preFixLen, i * OCTET_BIT_LENGTH)) {
560 size = size + i + 1 + PADDING_SIZE;
561 break;
562 }
563 }
564 }
565 return size;
566 }
567
568 private byte[] bytesDestinationDescriptor(IpPrefix ipPrefix) {
569 ByteBuffer byteBuffer;
570 int prefixLen = ipPrefix.prefixLength();
571
572 // retrieve ipPrefix to the destination descriptor format
573 // ex) 10.1.1.0/24 -> [10,1,1,0]
574 String[] ipPrefixString = ipPrefix.getIp4Prefix().toString()
575 .split("/")[0]
576 .split("\\.");
577
Daniel Parkf8e422d2018-07-30 14:14:37 +0900578 // retrieve destination descriptor and put this to bytebuffer according to RFC 3442
579 // ex) 0.0.0.0/0 -> 0
Daniel Parkd9d4c292018-06-26 20:33:58 +0900580 // ex) 10.0.0.0/8 -> 8.10
581 // ex) 10.17.0.0/16 -> 16.10.17
582 // ex) 10.27.129.0/24 -> 24.10.27.129
583 // ex) 10.229.0.128/25 -> 25.10.229.0.128
Daniel Parkf8e422d2018-07-30 14:14:37 +0900584 for (int i = 0; i <= V4_BYTE_SIZE; i++) {
Daniel Parkd9d4c292018-06-26 20:33:58 +0900585 if (prefixLen == Math.min(prefixLen, i * OCTET_BIT_LENGTH)) {
586 byteBuffer = ByteBuffer.allocate(i + 1);
587 byteBuffer.put((byte) prefixLen);
588
589 for (int j = 0; j < i; j++) {
590 byteBuffer.put((byte) Integer.parseInt(ipPrefixString[j]));
591 }
592 return byteBuffer.array();
593 }
594 }
595
596 return null;
597 }
Hyunsun Moon44aac662017-02-18 02:07:01 +0900598 }
daniel park15506e82018-04-04 18:52:16 +0900599
600 private class InternalNodeEventListener implements OpenstackNodeListener {
Jian Lifb64d882018-11-27 10:57:40 +0900601 @Override
602 public boolean isRelevant(OpenstackNodeEvent event) {
603 return event.subject().type() == COMPUTE;
604 }
605
Jian Li34220ea2018-11-14 01:30:24 +0900606 private boolean isRelevantHelper() {
607 return Objects.equals(localNodeId, leadershipService.getLeader(appId.name()));
daniel park15506e82018-04-04 18:52:16 +0900608 }
609
610 @Override
611 public void event(OpenstackNodeEvent event) {
612 OpenstackNode osNode = event.subject();
613 switch (event.type()) {
614 case OPENSTACK_NODE_COMPLETE:
Jian Li6a47fd02018-11-27 21:51:03 +0900615 eventExecutor.execute(() -> processNodeCompletion(osNode));
daniel park15506e82018-04-04 18:52:16 +0900616 break;
617 case OPENSTACK_NODE_INCOMPLETE:
Jian Li6a47fd02018-11-27 21:51:03 +0900618 eventExecutor.execute(() -> processNodeIncompletion(osNode));
daniel park15506e82018-04-04 18:52:16 +0900619 break;
620 case OPENSTACK_NODE_CREATED:
621 case OPENSTACK_NODE_UPDATED:
622 case OPENSTACK_NODE_REMOVED:
623 default:
624 break;
625 }
626 }
627
Jian Li6a47fd02018-11-27 21:51:03 +0900628 private void processNodeCompletion(OpenstackNode osNode) {
629 if (!isRelevantHelper()) {
630 return;
631 }
632 setDhcpRule(osNode, true);
633 }
634
635 private void processNodeIncompletion(OpenstackNode osNode) {
636 if (!isRelevantHelper()) {
637 return;
638 }
639 setDhcpRule(osNode, false);
640 }
641
daniel park15506e82018-04-04 18:52:16 +0900642 private void setDhcpRule(OpenstackNode openstackNode, boolean install) {
daniel park15506e82018-04-04 18:52:16 +0900643 TrafficSelector selector = DefaultTrafficSelector.builder()
644 .matchEthType(Ethernet.TYPE_IPV4)
645 .matchIPProtocol(IPv4.PROTOCOL_UDP)
646 .matchUdpDst(TpPort.tpPort(UDP.DHCP_SERVER_PORT))
647 .matchUdpSrc(TpPort.tpPort(UDP.DHCP_CLIENT_PORT))
648 .build();
649
650 TrafficTreatment treatment = DefaultTrafficTreatment.builder()
651 .punt()
652 .build();
653
654 osFlowRuleService.setRule(
655 appId,
656 openstackNode.intgBridge(),
657 selector,
658 treatment,
659 PRIORITY_DHCP_RULE,
Jian Li5c09e212018-10-24 18:23:58 +0900660 DHCP_TABLE,
daniel park15506e82018-04-04 18:52:16 +0900661 install);
662 }
663 }
Hyunsun Moon44aac662017-02-18 02:07:01 +0900664}