Initial implementation of managing IPs for kubevirt spawned VMIs
Change-Id: I68127e1fe42a142765e7696d8ce80de16d3d94a9
diff --git a/apps/kubevirt-networking/BUILD b/apps/kubevirt-networking/BUILD
index af30386..4dfceee 100644
--- a/apps/kubevirt-networking/BUILD
+++ b/apps/kubevirt-networking/BUILD
@@ -2,6 +2,7 @@
"//apps/kubevirt-networking/api:onos-apps-kubevirt-networking-api",
"//apps/kubevirt-networking/app:onos-apps-kubevirt-networking-app",
"@commons_net//jar",
+ "@ipaddress//jar",
"@jersey_client//jar",
"@json//jar",
"@k8s_client//jar",
diff --git a/apps/kubevirt-networking/api/BUILD b/apps/kubevirt-networking/api/BUILD
index e1e477c..3f1c431 100644
--- a/apps/kubevirt-networking/api/BUILD
+++ b/apps/kubevirt-networking/api/BUILD
@@ -1,6 +1,7 @@
COMPILE_DEPS = CORE_DEPS + [
"@k8s_client//jar",
"@k8s_model//jar",
+ "@ipaddress//jar",
"@okhttp//jar",
"@okio//jar",
"@logging_interceptor//jar",
diff --git a/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/Constants.java b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/Constants.java
index 9f8201a..7a5d873 100644
--- a/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/Constants.java
+++ b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/Constants.java
@@ -59,6 +59,7 @@
public static final int CLI_NAME_LENGTH = 30;
public static final int CLI_IP_ADDRESSES_LENGTH = 50;
public static final int CLI_IP_ADDRESS_LENGTH = 25;
+ public static final int CLI_IP_ADDRESS_AVAILABILITY = 15;
public static final int CLI_MAC_ADDRESS_LENGTH = 25;
public static final int CLI_PORTS_LENGTH = 20;
public static final int CLI_NAMESPACE_LENGTH = 15;
diff --git a/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/DefaultKubevirtPort.java b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/DefaultKubevirtPort.java
index 049a336..410c098 100644
--- a/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/DefaultKubevirtPort.java
+++ b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/DefaultKubevirtPort.java
@@ -32,6 +32,7 @@
private static final String NOT_NULL_MSG = "Port % cannot be null";
+ private final String networkId;
private final MacAddress macAddress;
private final IpAddress ipAddress;
private final DeviceId deviceId;
@@ -40,13 +41,15 @@
/**
* Default constructor.
*
+ * @param networkId network identifier
* @param macAddress MAC address
* @param ipAddress IP address
* @param deviceId device identifier
* @param portNumber port number
*/
- public DefaultKubevirtPort(MacAddress macAddress, IpAddress ipAddress,
+ public DefaultKubevirtPort(String networkId, MacAddress macAddress, IpAddress ipAddress,
DeviceId deviceId, PortNumber portNumber) {
+ this.networkId = networkId;
this.macAddress = macAddress;
this.ipAddress = ipAddress;
this.deviceId = deviceId;
@@ -54,6 +57,11 @@
}
@Override
+ public String networkId() {
+ return networkId;
+ }
+
+ @Override
public MacAddress macAddress() {
return macAddress;
}
@@ -92,18 +100,20 @@
return false;
}
DefaultKubevirtPort that = (DefaultKubevirtPort) o;
- return macAddress.equals(that.macAddress) && ipAddress.equals(that.ipAddress) &&
- deviceId.equals(that.deviceId) && portNumber.equals(that.portNumber);
+ return networkId.equals(that.networkId) && macAddress.equals(that.macAddress) &&
+ ipAddress.equals(that.ipAddress) && deviceId.equals(that.deviceId) &&
+ portNumber.equals(that.portNumber);
}
@Override
public int hashCode() {
- return Objects.hash(macAddress, ipAddress, deviceId, portNumber);
+ return Objects.hash(networkId, macAddress, ipAddress, deviceId, portNumber);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
+ .add("networkId", networkId)
.add("macAddress", macAddress)
.add("ipAddress", ipAddress)
.add("deviceId", deviceId)
@@ -125,6 +135,7 @@
*/
public static final class Builder implements KubevirtPort.Builder {
+ private String networkId;
private MacAddress macAddress;
private IpAddress ipAddress;
private DeviceId deviceId;
@@ -136,10 +147,18 @@
@Override
public KubevirtPort build() {
+ checkArgument(networkId != null, NOT_NULL_MSG, "networkId");
checkArgument(macAddress != null, NOT_NULL_MSG, "macAddress");
checkArgument(ipAddress != null, NOT_NULL_MSG, "ipAddress");
- return new DefaultKubevirtPort(macAddress, ipAddress, deviceId, portNumber);
+ return new DefaultKubevirtPort(networkId, macAddress, ipAddress,
+ deviceId, portNumber);
+ }
+
+ @Override
+ public Builder networkId(String networkId) {
+ this.networkId = networkId;
+ return this;
}
@Override
diff --git a/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtIpPool.java b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtIpPool.java
index 64874fd..fb2906e 100644
--- a/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtIpPool.java
+++ b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtIpPool.java
@@ -16,9 +16,19 @@
package org.onosproject.kubevirtnetworking.api;
import com.google.common.base.MoreObjects;
+import com.google.common.collect.ImmutableSet;
+import inet.ipaddr.AddressStringException;
+import inet.ipaddr.IPAddress;
+import inet.ipaddr.IPAddressSeqRange;
+import inet.ipaddr.IPAddressString;
import org.onlab.packet.IpAddress;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
import java.util.Objects;
+import java.util.Set;
/**
* Kubevirt IP Pool.
@@ -27,16 +37,25 @@
private final IpAddress start;
private final IpAddress end;
+ private final Set<IpAddress> allocatedIps;
+ private final Set<IpAddress> availableIps;
/**
* Default constructor.
*
- * @param start start address of IP pool
- * @param end end address of IP pool
+ * @param start start address of IP pool
+ * @param end end address of IP pool
*/
public KubevirtIpPool(IpAddress start, IpAddress end) {
this.start = start;
this.end = end;
+ this.allocatedIps = new HashSet<>();
+ this.availableIps = new HashSet<>();
+ try {
+ this.availableIps.addAll(getRangedIps(start.toString(), end.toString()));
+ } catch (AddressStringException e) {
+ e.printStackTrace();
+ }
}
/**
@@ -57,6 +76,61 @@
return end;
}
+ /**
+ * Returns the set of IP addresses that have been allocated.
+ *
+ * @return set of IP addresses that have been allocated
+ */
+ public Set<IpAddress> allocatedIps() {
+ return ImmutableSet.copyOf(allocatedIps);
+ }
+
+ /**
+ * Returns the set of IP addresses for allocation.
+ *
+ * @return set of IP addresses for allocation.
+ */
+ public Set<IpAddress> availableIps() {
+ return ImmutableSet.copyOf(availableIps);
+ }
+
+ /**
+ * Allocates a random IP address.
+ *
+ * @return allocated IP address
+ * @throws Exception exception
+ */
+ public synchronized IpAddress allocateIp() throws Exception {
+ if (availableIps.size() <= 0) {
+ throw new Exception("No IP address is available for allocation.");
+ }
+
+ List<IpAddress> sortedList = new ArrayList<>(availableIps);
+ Collections.sort(sortedList);
+
+ IpAddress ip = sortedList.get(0);
+
+ availableIps.remove(ip);
+ allocatedIps.add(ip);
+
+ return ip;
+ }
+
+ /**
+ * Releases the given IP address.
+ *
+ * @param ip IP address to be released
+ * @throws Exception exception
+ */
+ public synchronized void releaseIp(IpAddress ip) throws Exception {
+ if (!allocatedIps.contains(ip)) {
+ throw new Exception("The given IP address is not able to be released.");
+ }
+
+ allocatedIps.remove(ip);
+ availableIps.add(ip);
+ }
+
@Override
public boolean equals(Object o) {
if (this == o) {
@@ -81,4 +155,24 @@
.add("end", end)
.toString();
}
+
+ /**
+ * Obtains the IP address list from the given start and end range.
+ *
+ * @param start start range
+ * @param end end range
+ * @return IP address list from the given start and end range
+ * @throws AddressStringException exception
+ */
+ public Set<IpAddress> getRangedIps(String start, String end) throws AddressStringException {
+ Set<IpAddress> ips = new HashSet<>();
+ IPAddress lower = new IPAddressString(start).toAddress();
+ IPAddress upper = new IPAddressString(end).toAddress();
+ IPAddressSeqRange range = lower.toSequentialRange(upper);
+ for (IPAddress addr : range.getIterable()) {
+ ips.add(IpAddress.valueOf(addr.toString()));
+ }
+
+ return ips;
+ }
}
diff --git a/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtPort.java b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtPort.java
index d7c1ff2..a7ae75e 100644
--- a/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtPort.java
+++ b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtPort.java
@@ -26,6 +26,13 @@
public interface KubevirtPort {
/**
+ * Returns the network identifier associated with the port.
+ *
+ * @return network identifier
+ */
+ String networkId();
+
+ /**
* Returns the MAC address of the port.
*
* @return MAC address
@@ -82,6 +89,14 @@
KubevirtPort build();
/**
+ * Returns port builder with supplied network identifier.
+ *
+ * @param networkId network identifier
+ * @return port builder
+ */
+ Builder networkId(String networkId);
+
+ /**
* Returns port builder with supplied MAC address.
*
* @param macAddress MAC address
diff --git a/apps/kubevirt-networking/api/src/test/java/org/onosproject/kubevirtnetworking/api/DefaultKubevirtInstanceTest.java b/apps/kubevirt-networking/api/src/test/java/org/onosproject/kubevirtnetworking/api/DefaultKubevirtInstanceTest.java
index c1e59b6..c391eb4 100644
--- a/apps/kubevirt-networking/api/src/test/java/org/onosproject/kubevirtnetworking/api/DefaultKubevirtInstanceTest.java
+++ b/apps/kubevirt-networking/api/src/test/java/org/onosproject/kubevirtnetworking/api/DefaultKubevirtInstanceTest.java
@@ -36,6 +36,8 @@
private static final String UID_2 = "2";
private static final String NAME_1 = "instance-1";
private static final String NAME_2 = "instance-2";
+ private static final String NETWORK_ID_1 = "net-1";
+ private static final String NETWORK_ID_2 = "net-2";
private static final MacAddress MAC_1 = MacAddress.valueOf("11:22:33:44:55:66");
private static final MacAddress MAC_2 = MacAddress.valueOf("66:55:44:33:22:11");
private static final IpAddress IP_1 = IpAddress.valueOf("10.10.10.10");
@@ -44,8 +46,8 @@
private static final DeviceId DID_2 = DeviceId.deviceId("did2");
private static final PortNumber PN_1 = PortNumber.portNumber(1);
private static final PortNumber PN_2 = PortNumber.portNumber(2);
- private static final KubevirtPort PORT_1 = createPort(MAC_1, IP_1, DID_1, PN_1);
- private static final KubevirtPort PORT_2 = createPort(MAC_2, IP_2, DID_2, PN_2);
+ private static final KubevirtPort PORT_1 = createPort(NETWORK_ID_1, MAC_1, IP_1, DID_1, PN_1);
+ private static final KubevirtPort PORT_2 = createPort(NETWORK_ID_2, MAC_2, IP_2, DID_2, PN_2);
private KubevirtInstance instance1;
private KubevirtInstance sameAsInstance1;
@@ -105,8 +107,10 @@
assertEquals(ImmutableSet.of(PORT_1), instance1.ports());
}
- static KubevirtPort createPort(MacAddress mac, IpAddress ip, DeviceId did, PortNumber pn) {
+ static KubevirtPort createPort(String networkId, MacAddress mac, IpAddress ip,
+ DeviceId did, PortNumber pn) {
return DefaultKubevirtPort.builder()
+ .networkId(networkId)
.macAddress(mac)
.ipAddress(ip)
.deviceId(did)
diff --git a/apps/kubevirt-networking/api/src/test/java/org/onosproject/kubevirtnetworking/api/DefaultKubevirtNetworkTest.java b/apps/kubevirt-networking/api/src/test/java/org/onosproject/kubevirtnetworking/api/DefaultKubevirtNetworkTest.java
index 32ca958..1b39db8 100644
--- a/apps/kubevirt-networking/api/src/test/java/org/onosproject/kubevirtnetworking/api/DefaultKubevirtNetworkTest.java
+++ b/apps/kubevirt-networking/api/src/test/java/org/onosproject/kubevirtnetworking/api/DefaultKubevirtNetworkTest.java
@@ -22,6 +22,7 @@
import org.onlab.packet.IpAddress;
import static junit.framework.TestCase.assertEquals;
+import static junit.framework.TestCase.assertTrue;
import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable;
import static org.onosproject.kubevirtnetworking.api.KubevirtNetwork.Type.FLAT;
import static org.onosproject.kubevirtnetworking.api.KubevirtNetwork.Type.VXLAN;
@@ -128,4 +129,31 @@
assertEquals(CIDR_1, network.cidr());
assertEquals(new KubevirtIpPool(IP_POOL_START_1, IP_POOL_END_1), network.ipPool());
}
+
+ /**
+ * Test IP address initialization.
+ */
+ @Test
+ public void testIpInitialization() {
+ KubevirtIpPool ipPool1 = network1.ipPool();
+ assertEquals(101, ipPool1.availableIps().size());
+ assertEquals(0, ipPool1.allocatedIps().size());
+ }
+
+ /**
+ * Test IP address allocation.
+ */
+ @Test
+ public void testIpAllocationAndRelease() throws Exception {
+ KubevirtIpPool ipPool1 = network1.ipPool();
+ IpAddress ip = ipPool1.allocateIp();
+ assertEquals(100, ipPool1.availableIps().size());
+ assertEquals(1, ipPool1.allocatedIps().size());
+ assertEquals(IpAddress.valueOf("10.10.10.100"), ip);
+
+ ipPool1.releaseIp(ip);
+ assertEquals(101, ipPool1.availableIps().size());
+ assertEquals(0, ipPool1.allocatedIps().size());
+ assertTrue(ipPool1.availableIps().contains(ip));
+ }
}
diff --git a/apps/kubevirt-networking/api/src/test/java/org/onosproject/kubevirtnetworking/api/DefaultKubevirtPortTest.java b/apps/kubevirt-networking/api/src/test/java/org/onosproject/kubevirtnetworking/api/DefaultKubevirtPortTest.java
index 00f3cd4..f91ad2e 100644
--- a/apps/kubevirt-networking/api/src/test/java/org/onosproject/kubevirtnetworking/api/DefaultKubevirtPortTest.java
+++ b/apps/kubevirt-networking/api/src/test/java/org/onosproject/kubevirtnetworking/api/DefaultKubevirtPortTest.java
@@ -30,6 +30,8 @@
* Unit tests for the default kubevirt port class.
*/
public class DefaultKubevirtPortTest {
+ private static final String NETWORK_ID_1 = "net-1";
+ private static final String NETWORK_ID_2 = "net-2";
private static final MacAddress MAC_ADDRESS_1 = MacAddress.valueOf("00:11:22:33:44:55");
private static final MacAddress MAC_ADDRESS_2 = MacAddress.valueOf("11:22:33:44:55:66");
private static final IpAddress IP_ADDRESS_1 = IpAddress.valueOf("10.10.10.10");
@@ -57,6 +59,7 @@
@Before
public void setUp() {
port1 = DefaultKubevirtPort.builder()
+ .networkId(NETWORK_ID_1)
.macAddress(MAC_ADDRESS_1)
.ipAddress(IP_ADDRESS_1)
.deviceId(DEVICE_ID_1)
@@ -64,6 +67,7 @@
.build();
sameAsPort1 = DefaultKubevirtPort.builder()
+ .networkId(NETWORK_ID_1)
.macAddress(MAC_ADDRESS_1)
.ipAddress(IP_ADDRESS_1)
.deviceId(DEVICE_ID_1)
@@ -71,6 +75,7 @@
.build();
port2 = DefaultKubevirtPort.builder()
+ .networkId(NETWORK_ID_2)
.macAddress(MAC_ADDRESS_2)
.ipAddress(IP_ADDRESS_2)
.deviceId(DEVICE_ID_2)
@@ -95,6 +100,7 @@
public void testConstruction() {
KubevirtPort port = port1;
+ assertEquals(NETWORK_ID_1, port.networkId());
assertEquals(MAC_ADDRESS_1, port.macAddress());
assertEquals(IP_ADDRESS_1, port.ipAddress());
assertEquals(DEVICE_ID_1, port.deviceId());
diff --git a/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/cli/KubevirtListIpAddressCommand.java b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/cli/KubevirtListIpAddressCommand.java
new file mode 100644
index 0000000..343997b
--- /dev/null
+++ b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/cli/KubevirtListIpAddressCommand.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright 2021-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.kubevirtnetworking.cli;
+
+import com.google.common.collect.ImmutableList;
+import org.apache.karaf.shell.api.action.Argument;
+import org.apache.karaf.shell.api.action.Command;
+import org.apache.karaf.shell.api.action.Completion;
+import org.apache.karaf.shell.api.action.lifecycle.Service;
+import org.onlab.packet.IpAddress;
+import org.onosproject.cli.AbstractShellCommand;
+import org.onosproject.kubevirtnetworking.api.KubevirtIpPool;
+import org.onosproject.kubevirtnetworking.api.KubevirtNetwork;
+import org.onosproject.kubevirtnetworking.api.KubevirtNetworkService;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import static org.onosproject.kubevirtnetworking.api.Constants.CLI_IP_ADDRESS_AVAILABILITY;
+import static org.onosproject.kubevirtnetworking.api.Constants.CLI_IP_ADDRESS_LENGTH;
+import static org.onosproject.kubevirtnetworking.util.KubevirtNetworkingUtil.genFormatString;
+
+/**
+ * Lists all IP addresses.
+ */
+@Service
+@Command(scope = "onos", name = "kubevirt-ips",
+ description = "Lists all IP addresses")
+public class KubevirtListIpAddressCommand extends AbstractShellCommand {
+
+ @Argument(name = "networkId", description = "Network ID")
+ @Completion(KubevirtNetworkIdCompleter.class)
+ private String networkId = null;
+
+ @Override
+ protected void doExecute() throws Exception {
+ KubevirtNetworkService service = get(KubevirtNetworkService.class);
+ KubevirtNetwork network = service.network(networkId);
+
+ if (network == null) {
+ print("No network was found with the given network ID");
+ return;
+ }
+
+ KubevirtIpPool pool = network.ipPool();
+ if (pool == null) {
+ print("No IP pool was found with the given network ID");
+ return;
+ }
+
+ String format = genFormatString(ImmutableList.of(
+ CLI_IP_ADDRESS_LENGTH, CLI_IP_ADDRESS_AVAILABILITY));
+ print(format, "IP Address", "Availability");
+
+ List<IpAddress> sortedAllocatedIps = new ArrayList<>(pool.allocatedIps());
+ Collections.sort(sortedAllocatedIps);
+ for (IpAddress ip : sortedAllocatedIps) {
+ print(format, ip.toString(), "[ X ]");
+ }
+
+ List<IpAddress> sortedAvailableIps = new ArrayList<>(pool.availableIps());
+ Collections.sort(sortedAvailableIps);
+ for (IpAddress ip : sortedAvailableIps) {
+ print(format, ip.toString(), "[ O ]");
+ }
+ }
+}
diff --git a/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/cli/KubevirtNetworkIdCompleter.java b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/cli/KubevirtNetworkIdCompleter.java
new file mode 100644
index 0000000..91b011b
--- /dev/null
+++ b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/cli/KubevirtNetworkIdCompleter.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright 2021-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.kubevirtnetworking.cli;
+
+import org.apache.karaf.shell.api.action.lifecycle.Service;
+import org.apache.karaf.shell.api.console.CommandLine;
+import org.apache.karaf.shell.api.console.Completer;
+import org.apache.karaf.shell.api.console.Session;
+import org.apache.karaf.shell.support.completers.StringsCompleter;
+import org.onosproject.kubevirtnetworking.api.KubevirtNetwork;
+import org.onosproject.kubevirtnetworking.api.KubevirtNetworkService;
+
+import java.util.List;
+import java.util.Set;
+import java.util.SortedSet;
+import java.util.stream.Collectors;
+
+import static org.onosproject.cli.AbstractShellCommand.get;
+
+/**
+ * Kubevirt network ID completer.
+ */
+@Service
+public class KubevirtNetworkIdCompleter implements Completer {
+ @Override
+ public int complete(Session session, CommandLine commandLine, List<String> candidates) {
+ StringsCompleter delegate = new StringsCompleter();
+ KubevirtNetworkService networkService = get(KubevirtNetworkService.class);
+
+ Set<String> netIds = networkService.networks().stream().map(KubevirtNetwork::networkId)
+ .collect(Collectors.toSet());
+ SortedSet<String> strings = delegate.getStrings();
+
+ strings.addAll(netIds);
+
+ return delegate.complete(session, commandLine, candidates);
+ }
+}
diff --git a/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/codec/KubevirtNetworkCodec.java b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/codec/KubevirtNetworkCodec.java
index 3416ba2..c8cc377 100644
--- a/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/codec/KubevirtNetworkCodec.java
+++ b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/codec/KubevirtNetworkCodec.java
@@ -115,6 +115,13 @@
.gatewayIp(IpAddress.valueOf(gatewayIp))
.cidr(cidr);
+ if (!type.equals(KubevirtNetwork.Type.FLAT.name())) {
+ JsonNode segmentIdJson = json.get(SEGMENT_ID);
+ if (segmentIdJson != null) {
+ networkBuilder.segmentId(segmentIdJson.asText());
+ }
+ }
+
JsonNode ipPoolJson = json.get(IP_POOL);
if (ipPoolJson != null) {
final JsonCodec<KubevirtIpPool>
diff --git a/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/impl/KubevirtDhcpHandler.java b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/impl/KubevirtDhcpHandler.java
new file mode 100644
index 0000000..74b7c8a
--- /dev/null
+++ b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/impl/KubevirtDhcpHandler.java
@@ -0,0 +1,622 @@
+/*
+ * Copyright 2021-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.kubevirtnetworking.impl;
+
+import com.google.common.base.Strings;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+import org.onlab.packet.DHCP;
+import org.onlab.packet.Ethernet;
+import org.onlab.packet.IPv4;
+import org.onlab.packet.Ip4Address;
+import org.onlab.packet.IpAddress;
+import org.onlab.packet.IpPrefix;
+import org.onlab.packet.MacAddress;
+import org.onlab.packet.UDP;
+import org.onlab.packet.dhcp.DhcpOption;
+import org.onlab.util.Tools;
+import org.onosproject.cfg.ComponentConfigService;
+import org.onosproject.cluster.ClusterService;
+import org.onosproject.cluster.LeadershipService;
+import org.onosproject.cluster.NodeId;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.kubevirtnetworking.api.KubevirtFlowRuleService;
+import org.onosproject.kubevirtnetworking.api.KubevirtHostRoute;
+import org.onosproject.kubevirtnetworking.api.KubevirtNetwork;
+import org.onosproject.kubevirtnetworking.api.KubevirtNetworkService;
+import org.onosproject.kubevirtnetworking.api.KubevirtPort;
+import org.onosproject.kubevirtnetworking.api.KubevirtPortService;
+import org.onosproject.kubevirtnode.api.KubevirtNodeEvent;
+import org.onosproject.kubevirtnode.api.KubevirtNodeListener;
+import org.onosproject.kubevirtnode.api.KubevirtNodeService;
+import org.onosproject.net.ConnectPoint;
+import org.onosproject.net.flow.DefaultTrafficTreatment;
+import org.onosproject.net.flow.TrafficTreatment;
+import org.onosproject.net.packet.DefaultOutboundPacket;
+import org.onosproject.net.packet.PacketContext;
+import org.onosproject.net.packet.PacketProcessor;
+import org.onosproject.net.packet.PacketService;
+import org.osgi.service.component.ComponentContext;
+import org.osgi.service.component.annotations.Activate;
+import org.osgi.service.component.annotations.Component;
+import org.osgi.service.component.annotations.Deactivate;
+import org.osgi.service.component.annotations.Modified;
+import org.osgi.service.component.annotations.Reference;
+import org.osgi.service.component.annotations.ReferenceCardinality;
+import org.slf4j.Logger;
+
+import java.nio.ByteBuffer;
+import java.util.Dictionary;
+import java.util.List;
+import java.util.Objects;
+import java.util.concurrent.ExecutorService;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+import static java.util.concurrent.Executors.newSingleThreadExecutor;
+import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_BroadcastAddress;
+import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_Classless_Static_Route;
+import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_DHCPServerIp;
+import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_DomainServer;
+import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_END;
+import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_LeaseTime;
+import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_MessageType;
+import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_RouterAddress;
+import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_SubnetMask;
+import static org.onlab.packet.DHCP.MsgType.DHCPACK;
+import static org.onlab.packet.DHCP.MsgType.DHCPOFFER;
+import static org.onlab.util.Tools.groupedThreads;
+import static org.onosproject.kubevirtnetworking.api.Constants.KUBEVIRT_NETWORKING_APP_ID;
+import static org.onosproject.kubevirtnetworking.impl.OsgiPropertyConstants.DHCP_SERVER_MAC;
+import static org.onosproject.kubevirtnetworking.impl.OsgiPropertyConstants.DHCP_SERVER_MAC_DEFAULT;
+import static org.onosproject.kubevirtnetworking.util.KubevirtNetworkingUtil.getBroadcastAddr;
+import static org.onosproject.kubevirtnode.api.KubevirtNode.Type.WORKER;
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Handles DHCP requests for the virtual instances.
+ */
+@Component(
+ immediate = true,
+ property = {
+ DHCP_SERVER_MAC + "=" + DHCP_SERVER_MAC_DEFAULT
+ }
+)
+public class KubevirtDhcpHandler {
+ protected final Logger log = getLogger(getClass());
+
+ private static final Ip4Address DEFAULT_PRIMARY_DNS = Ip4Address.valueOf("8.8.8.8");
+ private static final Ip4Address DEFAULT_SECONDARY_DNS = Ip4Address.valueOf("8.8.4.4");
+ private static final byte PACKET_TTL = (byte) 127;
+
+ // TODO add MTU, static route option codes to ONOS DHCP and remove here
+ private static final byte DHCP_OPTION_MTU = (byte) 26;
+ private static final byte[] DHCP_DATA_LEASE_INFINITE =
+ ByteBuffer.allocate(4).putInt(-1).array();
+
+ private static final int OCTET_BIT_LENGTH = 8;
+ private static final int V4_BYTE_SIZE = 4;
+ private static final int V4_CIDR_LOWER_BOUND = -1;
+ private static final int V4_CIDR_UPPER_BOUND = 33;
+ private static final int PADDING_SIZE = 4;
+
+ private static final byte HARDWARE_ADDR_LENGTH = (byte) 6;
+ private static final byte DHCP_OPTION_DATA_LENGTH = (byte) 4;
+ private static final int DHCP_OPTION_DNS_LENGTH = 8;
+ private static final int DHCP_OPTION_MTU_LENGTH = 2;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY)
+ protected CoreService coreService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY)
+ protected ComponentConfigService configService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY)
+ protected PacketService packetService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY)
+ protected ClusterService clusterService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY)
+ protected LeadershipService leadershipService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY)
+ protected KubevirtNodeService nodeService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY)
+ protected KubevirtPortService portService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY)
+ protected KubevirtNetworkService networkService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY)
+ protected KubevirtFlowRuleService flowService;
+
+ /** Fake MAC address for virtual network subnet gateway. */
+ private String dhcpServerMac = DHCP_SERVER_MAC_DEFAULT;
+
+ private final PacketProcessor packetProcessor = new InternalPacketProcessor();
+ private final KubevirtNodeListener nodeListener = new InternalNodeEventListener();
+
+ private final ExecutorService eventExecutor = newSingleThreadExecutor(
+ groupedThreads(this.getClass().getSimpleName(), "event-handler"));
+
+ private ApplicationId appId;
+ private NodeId localNodeId;
+
+ @Activate
+ protected void activate() {
+ appId = coreService.registerApplication(KUBEVIRT_NETWORKING_APP_ID);
+ localNodeId = clusterService.getLocalNode().id();
+ nodeService.addListener(nodeListener);
+ configService.registerProperties(getClass());
+ packetService.addProcessor(packetProcessor, PacketProcessor.director(0));
+ leadershipService.runForLeadership(appId.name());
+
+ log.info("Started");
+ }
+
+ @Deactivate
+ protected void deactivate() {
+ packetService.removeProcessor(packetProcessor);
+ nodeService.removeListener(nodeListener);
+ configService.unregisterProperties(getClass(), false);
+ leadershipService.withdraw(appId.name());
+ eventExecutor.shutdown();
+
+ log.info("Stopped");
+ }
+
+ @Modified
+ protected void modified(ComponentContext context) {
+ Dictionary<?, ?> properties = context.getProperties();
+ String updatedMac;
+
+ updatedMac = Tools.get(properties, DHCP_SERVER_MAC);
+
+ if (!Strings.isNullOrEmpty(updatedMac) && !updatedMac.equals(dhcpServerMac)) {
+ dhcpServerMac = updatedMac;
+ }
+
+ log.info("Modified");
+ }
+
+ private class InternalPacketProcessor implements PacketProcessor {
+
+ @Override
+ public void process(PacketContext context) {
+ if (context.isHandled()) {
+ return;
+ }
+
+ Ethernet ethPacket = context.inPacket().parsed();
+ if (ethPacket == null || ethPacket.getEtherType() != Ethernet.TYPE_IPV4) {
+ return;
+ }
+ IPv4 ipv4Packet = (IPv4) ethPacket.getPayload();
+ if (ipv4Packet.getProtocol() != IPv4.PROTOCOL_UDP) {
+ return;
+ }
+ UDP udpPacket = (UDP) ipv4Packet.getPayload();
+ if (udpPacket.getDestinationPort() != UDP.DHCP_SERVER_PORT ||
+ udpPacket.getSourcePort() != UDP.DHCP_CLIENT_PORT) {
+ return;
+ }
+
+ DHCP dhcpPacket = (DHCP) udpPacket.getPayload();
+
+ eventExecutor.execute(() -> processDhcp(context, dhcpPacket));
+ }
+
+ private void processDhcp(PacketContext context, DHCP dhcpPacket) {
+ if (dhcpPacket == null) {
+ log.trace("DHCP packet without payload received, do nothing");
+ return;
+ }
+
+ DHCP.MsgType inPacketType = getPacketType(dhcpPacket);
+ if (inPacketType == null || dhcpPacket.getClientHardwareAddress() == null) {
+ log.trace("Malformed DHCP packet received, ignore it");
+ return;
+ }
+
+ MacAddress clientMac = MacAddress.valueOf(dhcpPacket.getClientHardwareAddress());
+
+ KubevirtPort port = portService.ports().stream()
+ .filter(p -> p.macAddress().equals(clientMac))
+ .findAny().orElse(null);
+
+ if (port == null) {
+ log.debug("Ignore DHCP request, since it comes from unmanaged VM {}", clientMac);
+ return;
+ }
+
+ IpAddress fixedIp = port.ipAddress();
+
+ if (fixedIp == null) {
+ log.warn("There is no IP addresses are assigned with the port {}", port.macAddress());
+ return;
+ }
+
+ Ethernet ethPacket = context.inPacket().parsed();
+ switch (inPacketType) {
+ case DHCPDISCOVER:
+ processDhcpDiscover(context, clientMac, port, ethPacket);
+ break;
+ case DHCPREQUEST:
+ processDhcpRequest(context, clientMac, port, ethPacket);
+ break;
+ case DHCPRELEASE:
+ log.trace("DHCP RELEASE received from {}", clientMac);
+ // do nothing
+ break;
+ default:
+ break;
+ }
+ }
+
+ private void processDhcpDiscover(PacketContext context, MacAddress clientMac,
+ KubevirtPort port, Ethernet ethPacket) {
+ log.trace("DHCP DISCOVER received from {}", clientMac);
+ Ethernet discoverReply = buildReply(ethPacket,
+ (byte) DHCPOFFER.getValue(),
+ port);
+ sendReply(context, discoverReply);
+ log.trace("DHCP OFFER({}) is sent for {}", port.ipAddress().toString(), clientMac);
+ }
+
+ private void processDhcpRequest(PacketContext context, MacAddress clientMac,
+ KubevirtPort port, Ethernet ethPacket) {
+ log.trace("DHCP REQUEST received from {}", clientMac);
+ Ethernet requestReply = buildReply(ethPacket,
+ (byte) DHCPACK.getValue(),
+ port);
+ sendReply(context, requestReply);
+ log.trace("DHCP ACK({}) is sent for {}", port.ipAddress(), clientMac);
+ }
+
+ private DHCP.MsgType getPacketType(DHCP dhcpPacket) {
+ DhcpOption optType = dhcpPacket.getOption(OptionCode_MessageType);
+ if (optType == null) {
+ log.trace("DHCP packet with no message type, ignore it");
+ return null;
+ }
+
+ DHCP.MsgType inPacketType = DHCP.MsgType.getType(optType.getData()[0]);
+ if (inPacketType == null) {
+ log.trace("DHCP packet with no packet type, ignore it");
+ }
+ return inPacketType;
+ }
+
+ private Ethernet buildReply(Ethernet ethRequest, byte packetType,
+ KubevirtPort port) {
+ log.trace("Build for DHCP reply msg for openstack port {}", port.toString());
+
+ // pick one IP address to make a reply
+ // since we check the validity of fixed IP address at parent method,
+ // so no need to double check the fixed IP existence here
+ IpAddress fixedIp = port.ipAddress();
+
+ KubevirtNetwork network = networkService.network(port.networkId());
+
+ Ethernet ethReply = new Ethernet();
+ ethReply.setSourceMACAddress(dhcpServerMac);
+ ethReply.setDestinationMACAddress(ethRequest.getSourceMAC());
+ ethReply.setEtherType(Ethernet.TYPE_IPV4);
+
+ IPv4 ipv4Request = (IPv4) ethRequest.getPayload();
+ IPv4 ipv4Reply = new IPv4();
+
+ ipv4Reply.setSourceAddress(
+ clusterService.getLocalNode().ip().getIp4Address().toString());
+ ipv4Reply.setDestinationAddress(fixedIp.toString());
+ ipv4Reply.setTtl(PACKET_TTL);
+
+ UDP udpRequest = (UDP) ipv4Request.getPayload();
+ UDP udpReply = new UDP();
+ udpReply.setSourcePort((byte) UDP.DHCP_SERVER_PORT);
+ udpReply.setDestinationPort((byte) UDP.DHCP_CLIENT_PORT);
+
+ DHCP dhcpRequest = (DHCP) udpRequest.getPayload();
+ DHCP dhcpReply = buildDhcpReply(
+ dhcpRequest,
+ packetType,
+ Ip4Address.valueOf(fixedIp.toString()), port, network);
+
+ udpReply.setPayload(dhcpReply);
+ ipv4Reply.setPayload(udpReply);
+ ethReply.setPayload(ipv4Reply);
+
+ return ethReply;
+ }
+
+ private void sendReply(PacketContext context, Ethernet ethReply) {
+ if (ethReply == null) {
+ return;
+ }
+ ConnectPoint srcPoint = context.inPacket().receivedFrom();
+ TrafficTreatment treatment = DefaultTrafficTreatment
+ .builder()
+ .setOutput(srcPoint.port())
+ .build();
+
+ packetService.emit(new DefaultOutboundPacket(
+ srcPoint.deviceId(),
+ treatment,
+ ByteBuffer.wrap(ethReply.serialize())));
+ context.block();
+ }
+
+ private DHCP buildDhcpReply(DHCP request, byte msgType, Ip4Address yourIp,
+ KubevirtPort port, KubevirtNetwork network) {
+ Ip4Address gatewayIp = clusterService.getLocalNode().ip().getIp4Address();
+ int subnetPrefixLen = IpPrefix.valueOf(network.cidr()).prefixLength();
+
+ DHCP dhcpReply = new DHCP();
+ dhcpReply.setOpCode(DHCP.OPCODE_REPLY);
+ dhcpReply.setHardwareType(DHCP.HWTYPE_ETHERNET);
+ dhcpReply.setHardwareAddressLength(HARDWARE_ADDR_LENGTH);
+ dhcpReply.setTransactionId(request.getTransactionId());
+ dhcpReply.setFlags(request.getFlags());
+ dhcpReply.setYourIPAddress(yourIp.toInt());
+ dhcpReply.setServerIPAddress(gatewayIp.toInt());
+ dhcpReply.setClientHardwareAddress(request.getClientHardwareAddress());
+
+ List<DhcpOption> options = Lists.newArrayList();
+
+ // message type
+ options.add(doMsgType(msgType));
+
+ // server identifier
+ options.add(doServerId(gatewayIp));
+
+ // lease time
+ options.add(doLeaseTime());
+
+ // subnet mask
+ options.add(doSubnetMask(subnetPrefixLen));
+
+ // broadcast address
+ options.add(doBroadcastAddr(yourIp, subnetPrefixLen));
+
+ // domain server
+ options.add(doDomainServer(network));
+
+ // mtu
+ options.add(doMtu(network));
+
+ // classless static route
+ if (!network.hostRoutes().isEmpty()) {
+ options.add(doClasslessSr(network));
+ }
+
+ // Sets the default router address up.
+ // Performs only if the gateway is set in subnet.
+ if (network.gatewayIp() != null) {
+ options.add(doRouterAddr(network));
+ }
+
+ // end option
+ options.add(doEnd());
+
+ dhcpReply.setOptions(options);
+ return dhcpReply;
+ }
+
+
+ private DhcpOption doMsgType(byte msgType) {
+ DhcpOption option = new DhcpOption();
+ option.setCode(OptionCode_MessageType.getValue());
+ option.setLength((byte) 1);
+ byte[] optionData = {msgType};
+ option.setData(optionData);
+ return option;
+ }
+
+ private DhcpOption doServerId(IpAddress gatewayIp) {
+ DhcpOption option = new DhcpOption();
+ option.setCode(OptionCode_DHCPServerIp.getValue());
+ option.setLength(DHCP_OPTION_DATA_LENGTH);
+ option.setData(gatewayIp.toOctets());
+ return option;
+ }
+
+ private DhcpOption doLeaseTime() {
+ DhcpOption option = new DhcpOption();
+ option.setCode(OptionCode_LeaseTime.getValue());
+ option.setLength(DHCP_OPTION_DATA_LENGTH);
+ option.setData(DHCP_DATA_LEASE_INFINITE);
+ return option;
+ }
+
+ private DhcpOption doSubnetMask(int subnetPrefixLen) {
+ Ip4Address subnetMask = Ip4Address.makeMaskPrefix(subnetPrefixLen);
+ DhcpOption option = new DhcpOption();
+ option.setCode(OptionCode_SubnetMask.getValue());
+ option.setLength(DHCP_OPTION_DATA_LENGTH);
+ option.setData(subnetMask.toOctets());
+ return option;
+ }
+
+ private DhcpOption doBroadcastAddr(Ip4Address yourIp, int subnetPrefixLen) {
+ String broadcast = getBroadcastAddr(yourIp.toString(), subnetPrefixLen);
+
+ DhcpOption option = new DhcpOption();
+ option.setCode(OptionCode_BroadcastAddress.getValue());
+ option.setLength(DHCP_OPTION_DATA_LENGTH);
+ option.setData(IpAddress.valueOf(broadcast).toOctets());
+
+ return option;
+ }
+
+ private DhcpOption doDomainServer(KubevirtNetwork network) {
+ DhcpOption option = new DhcpOption();
+
+ option.setCode(OptionCode_DomainServer.getValue());
+
+ option.setLength((byte) DHCP_OPTION_DNS_LENGTH);
+ ByteBuffer dnsByteBuf = ByteBuffer.allocate(DHCP_OPTION_DNS_LENGTH);
+ dnsByteBuf.put(DEFAULT_PRIMARY_DNS.toOctets());
+ dnsByteBuf.put(DEFAULT_SECONDARY_DNS.toOctets());
+
+ option.setData(dnsByteBuf.array());
+
+ // TODO: need to customize the DNS server list
+// if (dnsServers.isEmpty()) {
+//
+// } else {
+// int dnsLength = 4 * dnsServers.size();
+//
+// option.setLength((byte) dnsLength);
+//
+// ByteBuffer dnsByteBuf = ByteBuffer.allocate(DHCP_OPTION_DNS_LENGTH);
+//
+// for (String dnsServer : dnsServers) {
+// dnsByteBuf.put(IpAddress.valueOf(dnsServer).toOctets());
+// }
+// option.setData(dnsByteBuf.array());
+// }
+
+ return option;
+ }
+
+ private DhcpOption doMtu(KubevirtNetwork network) {
+ DhcpOption option = new DhcpOption();
+ option.setCode(DHCP_OPTION_MTU);
+ option.setLength((byte) DHCP_OPTION_MTU_LENGTH);
+ checkNotNull(network);
+ checkNotNull(network.mtu());
+
+ option.setData(ByteBuffer.allocate(DHCP_OPTION_MTU_LENGTH)
+ .putShort(network.mtu().shortValue()).array());
+
+ return option;
+ }
+
+ private DhcpOption doClasslessSr(KubevirtNetwork network) {
+ DhcpOption option = new DhcpOption();
+ option.setCode(OptionCode_Classless_Static_Route.getValue());
+
+ int hostRoutesSize = hostRoutesSize(ImmutableList.copyOf(network.hostRoutes()));
+ if (hostRoutesSize == 0) {
+ throw new IllegalArgumentException("Illegal CIDR hostRoutesSize value!");
+ }
+
+ log.trace("hostRouteSize: {}", hostRoutesSize);
+
+ option.setLength((byte) hostRoutesSize);
+ ByteBuffer hostRouteByteBuf = ByteBuffer.allocate(hostRoutesSize);
+
+ network.hostRoutes().forEach(h -> {
+ log.debug("processing host route information: {}", h.toString());
+
+ IpPrefix ipPrefix = h.destination();
+
+ hostRouteByteBuf.put(Objects.requireNonNull(bytesDestinationDescriptor(ipPrefix)));
+ hostRouteByteBuf.put(h.nexthop().toOctets());
+ });
+
+ option.setData(hostRouteByteBuf.array());
+ return option;
+ }
+
+ private DhcpOption doRouterAddr(KubevirtNetwork network) {
+ DhcpOption option = new DhcpOption();
+ option.setCode(OptionCode_RouterAddress.getValue());
+ option.setLength(DHCP_OPTION_DATA_LENGTH);
+ option.setData(Ip4Address.valueOf(network.gatewayIp().toString()).toOctets());
+ return option;
+ }
+
+ private DhcpOption doEnd() {
+ DhcpOption option = new DhcpOption();
+ option.setCode(OptionCode_END.getValue());
+ option.setLength((byte) 1);
+ return option;
+ }
+
+ private int hostRoutesSize(List<KubevirtHostRoute> hostRoutes) {
+ int size = 0;
+ int preFixLen;
+
+ for (KubevirtHostRoute h : hostRoutes) {
+ preFixLen = h.destination().prefixLength();
+ if (Math.max(V4_CIDR_LOWER_BOUND, preFixLen) == V4_CIDR_LOWER_BOUND ||
+ Math.min(preFixLen, V4_CIDR_UPPER_BOUND) == V4_CIDR_UPPER_BOUND) {
+ throw new IllegalArgumentException("Illegal CIDR length value!");
+ }
+
+ for (int i = 0; i <= V4_BYTE_SIZE; i++) {
+ if (preFixLen == Math.min(preFixLen, i * OCTET_BIT_LENGTH)) {
+ size = size + i + 1 + PADDING_SIZE;
+ break;
+ }
+ }
+ }
+ return size;
+ }
+
+ private byte[] bytesDestinationDescriptor(IpPrefix ipPrefix) {
+ ByteBuffer byteBuffer;
+ int prefixLen = ipPrefix.prefixLength();
+
+ // retrieve ipPrefix to the destination descriptor format
+ // ex) 10.1.1.0/24 -> [10,1,1,0]
+ String[] ipPrefixString = ipPrefix.getIp4Prefix().toString()
+ .split("/")[0]
+ .split("\\.");
+
+ // retrieve destination descriptor and put this to byte buffer
+ // according to RFC 3442
+ // ex) 0.0.0.0/0 -> 0
+ // ex) 10.0.0.0/8 -> 8.10
+ // ex) 10.17.0.0/16 -> 16.10.17
+ // ex) 10.27.129.0/24 -> 24.10.27.129
+ // ex) 10.229.0.128/25 -> 25.10.229.0.128
+ for (int i = 0; i <= V4_BYTE_SIZE; i++) {
+ if (prefixLen == Math.min(prefixLen, i * OCTET_BIT_LENGTH)) {
+ byteBuffer = ByteBuffer.allocate(i + 1);
+ byteBuffer.put((byte) prefixLen);
+
+ for (int j = 0; j < i; j++) {
+ byteBuffer.put((byte) Integer.parseInt(ipPrefixString[j]));
+ }
+ return byteBuffer.array();
+ }
+ }
+
+ return null;
+ }
+ }
+
+ private class InternalNodeEventListener implements KubevirtNodeListener {
+
+ @Override
+ public boolean isRelevant(KubevirtNodeEvent event) {
+ return event.subject().type() == WORKER;
+ }
+
+ private boolean isRelevantHelper() {
+ return Objects.equals(localNodeId, leadershipService.getLeader(appId.name()));
+ }
+
+ @Override
+ public void event(KubevirtNodeEvent event) {
+
+ }
+ }
+}
diff --git a/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/util/KubevirtNetworkingUtil.java b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/util/KubevirtNetworkingUtil.java
index e00eb52..c7051bb 100644
--- a/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/util/KubevirtNetworkingUtil.java
+++ b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/util/KubevirtNetworkingUtil.java
@@ -17,14 +17,19 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
+import org.apache.commons.net.util.SubnetUtils;
+import org.onlab.packet.IpAddress;
import org.onosproject.cfg.ConfigProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
+import java.util.Arrays;
+import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
+import java.util.stream.Collectors;
/**
* An utility that used in KubeVirt networking app.
@@ -105,4 +110,39 @@
}
return null;
}
+
+ /**
+ * Obtains valid IP addresses of the given subnet.
+ *
+ * @param cidr CIDR
+ * @return set of IP addresses
+ */
+ public static Set<IpAddress> getSubnetIps(String cidr) {
+ SubnetUtils utils = new SubnetUtils(cidr);
+ utils.setInclusiveHostCount(false);
+ SubnetUtils.SubnetInfo info = utils.getInfo();
+ Set<String> allAddresses =
+ new HashSet<>(Arrays.asList(info.getAllAddresses()));
+
+ if (allAddresses.size() > 2) {
+ allAddresses.remove(info.getLowAddress());
+ allAddresses.remove(info.getHighAddress());
+ }
+
+ return allAddresses.stream()
+ .map(IpAddress::valueOf).collect(Collectors.toSet());
+ }
+
+ /**
+ * Calculate the broadcast address from given IP address and subnet prefix length.
+ *
+ * @param ipAddr IP address
+ * @param prefixLength subnet prefix length
+ * @return broadcast address
+ */
+ public static String getBroadcastAddr(String ipAddr, int prefixLength) {
+ String subnet = ipAddr + "/" + prefixLength;
+ SubnetUtils utils = new SubnetUtils(subnet);
+ return utils.getInfo().getBroadcastAddress();
+ }
}
diff --git a/deps/deps.json b/deps/deps.json
index eaf4bb3..e3698bb 100644
--- a/deps/deps.json
+++ b/deps/deps.json
@@ -166,6 +166,7 @@
"httpclient-osgi": "mvn:org.apache.httpcomponents:httpclient-osgi:4.5.1",
"httpcore-osgi": "mvn:org.apache.httpcomponents:httpcore-osgi:4.4.4",
"influxdb-java": "mvn:org.influxdb:influxdb-java:2.9",
+ "ipaddress": "mvn:com.github.seancfoley:ipaddress:5.3.3",
"simpleclient": "mvn:io.prometheus:simpleclient:0.5.0",
"simpleclient_common": "mvn:io.prometheus:simpleclient_common:0.5.0",
"simpleclient_hotspot": "mvn:io.prometheus:simpleclient_hotspot:0.5.0",
diff --git a/tools/build/bazel/generate_workspace.bzl b/tools/build/bazel/generate_workspace.bzl
index ae2d9b5..ba444f3 100644
--- a/tools/build/bazel/generate_workspace.bzl
+++ b/tools/build/bazel/generate_workspace.bzl
@@ -382,6 +382,12 @@
jar_sha256 = "c2c35eff56e5b101028a52f5fa2bc25e7b5e0f6c7b7fdf9f5c8ed503621547eb",
licenses = ["notice"],
jar_urls = ["https://repo1.maven.org/maven2/org/influxdb/influxdb-java/2.9/influxdb-java-2.9.jar"], )
+ if "ipaddress" not in native.existing_rules():
+ java_import_external(
+ name = "ipaddress",
+ jar_sha256 = "a8485113300d367306258a2663491fba8b1b746d00ca0df88d3943994cc0f7b9",
+ licenses = ["notice"],
+ jar_urls = ["https://repo1.maven.org/maven2/com/github/seancfoley/ipaddress/5.3.3/ipaddress-5.3.3.jar"], )
if "simpleclient" not in native.existing_rules():
java_import_external(
name = "simpleclient",
@@ -1386,6 +1392,7 @@
artifact_map["@httpclient_osgi//:httpclient_osgi"] = "mvn:org.apache.httpcomponents:httpclient-osgi:jar:4.5.1"
artifact_map["@httpcore_osgi//:httpcore_osgi"] = "mvn:org.apache.httpcomponents:httpcore-osgi:jar:4.4.4"
artifact_map["@influxdb_java//:influxdb_java"] = "mvn:org.influxdb:influxdb-java:jar:NON-OSGI:2.9"
+artifact_map["@ipaddress//:ipaddress"] = "mvn:com.github.seancfoley:ipaddress:jar:5.3.3"
artifact_map["@simpleclient//:simpleclient"] = "mvn:io.prometheus:simpleclient:jar:0.5.0"
artifact_map["@simpleclient_common//:simpleclient_common"] = "mvn:io.prometheus:simpleclient_common:jar:0.5.0"
artifact_map["@simpleclient_hotspot//:simpleclient_hotspot"] = "mvn:io.prometheus:simpleclient_hotspot:jar:0.5.0"