Implement kubevirt router store, manager and codec with unit tests
Change-Id: Ib93a71326aa35b4817f0e6b6c97d5f57b26fe470
diff --git a/apps/kubevirt-networking/api/BUILD b/apps/kubevirt-networking/api/BUILD
index d935077..968dd56 100644
--- a/apps/kubevirt-networking/api/BUILD
+++ b/apps/kubevirt-networking/api/BUILD
@@ -24,6 +24,7 @@
"@okhttp//jar",
"@okio//jar",
"@logging_interceptor//jar",
+ "@jackson_databind//jar",
"@jackson_dataformat_yaml//jar",
"@jackson_datatype_jsr310//jar",
"@snakeyaml//jar",
diff --git a/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/AbstractWatcher.java b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/AbstractWatcher.java
new file mode 100644
index 0000000..f7fcfc1
--- /dev/null
+++ b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/AbstractWatcher.java
@@ -0,0 +1,47 @@
+/*
+ * 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.api;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.onlab.osgi.DefaultServiceDirectory;
+import org.onlab.osgi.ServiceDirectory;
+import org.onosproject.codec.CodecContext;
+import org.onosproject.codec.CodecService;
+import org.onosproject.codec.JsonCodec;
+
+/**
+ * Abstract watcher.
+ */
+public class AbstractWatcher implements CodecContext {
+
+ private static ServiceDirectory services = new DefaultServiceDirectory();
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ @Override
+ public ObjectMapper mapper() {
+ return mapper;
+ }
+
+ @Override
+ public <T> JsonCodec<T> codec(Class<T> entityClass) {
+ return services.get(CodecService.class).getCodec(entityClass);
+ }
+
+ @Override
+ public <T> T getService(Class<T> serviceClass) {
+ return services.get(serviceClass);
+ }
+}
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 3f5620e..0c97fb6 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
@@ -87,6 +87,7 @@
public static final int CLI_SEG_ID_LENGTH = 10;
public static final int CLI_LABELS_LENGTH = 30;
public static final int CLI_CONTAINERS_LENGTH = 30;
+ public static final int CLI_FLAG_LENGTH = 10;
public static final int CLI_MARGIN_LENGTH = 2;
public static final int PRIORITY_STATEFUL_SNAT_RULE = 40500;
diff --git a/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/DefaultKubevirtRouter.java b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/DefaultKubevirtRouter.java
index e606275..4bf04a2 100644
--- a/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/DefaultKubevirtRouter.java
+++ b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/DefaultKubevirtRouter.java
@@ -18,7 +18,6 @@
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
-import org.onlab.packet.IpAddress;
import java.util.HashMap;
import java.util.HashSet;
@@ -39,7 +38,7 @@
private final String description;
private final boolean enableSnat;
private final Set<String> internal;
- private final Map<IpAddress, String> external;
+ private final Map<String, String> external;
private final KubevirtPeerRouter peerRouter;
/**
@@ -54,7 +53,7 @@
*/
public DefaultKubevirtRouter(String name, String description, boolean enableSnat,
Set<String> internal,
- Map<IpAddress, String> external,
+ Map<String, String> external,
KubevirtPeerRouter peerRouter) {
this.name = name;
this.description = description;
@@ -85,7 +84,7 @@
}
@Override
- public Map<IpAddress, String> external() {
+ public Map<String, String> external() {
return ImmutableMap.copyOf(external);
}
@@ -95,6 +94,18 @@
}
@Override
+ public KubevirtRouter updatePeerRouter(KubevirtPeerRouter updated) {
+ return DefaultKubevirtRouter.builder()
+ .name(name)
+ .enableSnat(enableSnat)
+ .description(description)
+ .internal(internal)
+ .external(external)
+ .peerRouter(updated)
+ .build();
+ }
+
+ @Override
public boolean equals(Object o) {
if (this == o) {
return true;
@@ -140,7 +151,7 @@
private String description;
private boolean enableSnat;
private Set<String> internal;
- private Map<IpAddress, String> external;
+ private Map<String, String> external;
private KubevirtPeerRouter peerRouter;
@Override
@@ -176,7 +187,7 @@
}
@Override
- public Builder external(Map<IpAddress, String> external) {
+ public Builder external(Map<String, String> external) {
this.external = Objects.requireNonNullElseGet(external, HashMap::new);
return this;
}
diff --git a/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtPeerRouter.java b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtPeerRouter.java
index 00dbc2f..4ebe556 100644
--- a/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtPeerRouter.java
+++ b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtPeerRouter.java
@@ -35,7 +35,7 @@
* @param ipAddress IP address
* @param macAddress MAC address
*/
- KubevirtPeerRouter(IpAddress ipAddress, MacAddress macAddress) {
+ public KubevirtPeerRouter(IpAddress ipAddress, MacAddress macAddress) {
this.ipAddress = ipAddress;
this.macAddress = macAddress;
}
diff --git a/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtRouter.java b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtRouter.java
index c10116f..e9f5e88 100644
--- a/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtRouter.java
+++ b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtRouter.java
@@ -15,8 +15,6 @@
*/
package org.onosproject.kubevirtnetworking.api;
-import org.onlab.packet.IpAddress;
-
import java.util.Map;
import java.util.Set;
@@ -59,7 +57,7 @@
*
* @return external network paired with external router IP address
*/
- Map<IpAddress, String> external();
+ Map<String, String> external();
/**
* Returns external peer router.
@@ -68,6 +66,14 @@
*/
KubevirtPeerRouter peerRouter();
+ /**
+ * Updates the peer router.
+ *
+ * @param updated updated peer router
+ * @return kubevirt router with the updated peer router
+ */
+ KubevirtRouter updatePeerRouter(KubevirtPeerRouter updated);
+
interface Builder {
/**
@@ -115,7 +121,7 @@
* @param external external network with IP
* @return router builder
*/
- Builder external(Map<IpAddress, String> external);
+ Builder external(Map<String, String> external);
/**
* Returns kubevirt router builder with supplied peer router.
diff --git a/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtRouterAdminService.java b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtRouterAdminService.java
index c963551..1ec1cee 100644
--- a/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtRouterAdminService.java
+++ b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtRouterAdminService.java
@@ -15,6 +15,8 @@
*/
package org.onosproject.kubevirtnetworking.api;
+import org.onlab.packet.MacAddress;
+
/**
* Service for administering the inventory of kubevirt router service.
*/
@@ -42,6 +44,14 @@
void removeRouter(String name);
/**
+ * Updates the MAC address of the peer router.
+ *
+ * @param name router name
+ * @param mac peer router MAC address
+ */
+ void updatePeerRouterMac(String name, MacAddress mac);
+
+ /**
* Removes all routers.
*/
void clear();
diff --git a/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtRouterEvent.java b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtRouterEvent.java
index 52d4824..b195ecb 100644
--- a/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtRouterEvent.java
+++ b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtRouterEvent.java
@@ -28,7 +28,7 @@
* @param type kubevirt router event type
* @param subject kubevirt router
*/
- protected KubevirtRouterEvent(Type type, KubevirtRouter subject) {
+ public KubevirtRouterEvent(Type type, KubevirtRouter subject) {
super(type, subject);
}
diff --git a/apps/kubevirt-networking/api/src/test/java/org/onosproject/kubevirtnetworking/api/DefaultKubevirtRouterTest.java b/apps/kubevirt-networking/api/src/test/java/org/onosproject/kubevirtnetworking/api/DefaultKubevirtRouterTest.java
index 2ced87e..91ff8ad 100644
--- a/apps/kubevirt-networking/api/src/test/java/org/onosproject/kubevirtnetworking/api/DefaultKubevirtRouterTest.java
+++ b/apps/kubevirt-networking/api/src/test/java/org/onosproject/kubevirtnetworking/api/DefaultKubevirtRouterTest.java
@@ -73,7 +73,7 @@
.description(DESCRIPTION_1)
.enableSnat(ENABLE_SNAT_1)
.internal(ImmutableSet.of(NETWORK_NAME_1))
- .external(ImmutableMap.of(IpAddress.valueOf("10.10.10.10"), NETWORK_NAME_1))
+ .external(ImmutableMap.of("10.10.10.10", NETWORK_NAME_1))
.peerRouter(PEER_ROUTER_1)
.build();
sameAsRouter1 = DefaultKubevirtRouter.builder()
@@ -81,7 +81,7 @@
.description(DESCRIPTION_1)
.enableSnat(ENABLE_SNAT_1)
.internal(ImmutableSet.of(NETWORK_NAME_1))
- .external(ImmutableMap.of(IpAddress.valueOf("10.10.10.10"), NETWORK_NAME_1))
+ .external(ImmutableMap.of("10.10.10.10", NETWORK_NAME_1))
.peerRouter(PEER_ROUTER_1)
.build();
router2 = DefaultKubevirtRouter.builder()
@@ -89,7 +89,7 @@
.description(DESCRIPTION_2)
.enableSnat(ENABLE_SNAT_2)
.internal(ImmutableSet.of(NETWORK_NAME_2))
- .external(ImmutableMap.of(IpAddress.valueOf("20.20.20.20"), NETWORK_NAME_2))
+ .external(ImmutableMap.of("20.20.20.20", NETWORK_NAME_2))
.peerRouter(PEER_ROUTER_2)
.build();
}
@@ -115,7 +115,7 @@
assertEquals(DESCRIPTION_1, router.description());
assertEquals(ENABLE_SNAT_1, router.enableSnat());
assertEquals(ImmutableSet.of(NETWORK_NAME_1), router.internal());
- assertEquals(ImmutableMap.of(IpAddress.valueOf("10.10.10.10"), NETWORK_NAME_1), router.external());
+ assertEquals(ImmutableMap.of("10.10.10.10", NETWORK_NAME_1), router.external());
assertEquals(PEER_ROUTER_1, router.peerRouter());
}
}
diff --git a/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/cli/KubevirtListRouterCommand.java b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/cli/KubevirtListRouterCommand.java
new file mode 100644
index 0000000..4ebd21b
--- /dev/null
+++ b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/cli/KubevirtListRouterCommand.java
@@ -0,0 +1,92 @@
+/*
+ * 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.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+import org.apache.commons.lang.StringUtils;
+import org.apache.karaf.shell.api.action.Command;
+import org.apache.karaf.shell.api.action.lifecycle.Service;
+import org.onosproject.cli.AbstractShellCommand;
+import org.onosproject.kubevirtnetworking.api.KubevirtNetworkService;
+import org.onosproject.kubevirtnetworking.api.KubevirtRouter;
+import org.onosproject.kubevirtnetworking.api.KubevirtRouterService;
+
+import java.util.Comparator;
+import java.util.List;
+import java.util.Set;
+
+import static org.onosproject.kubevirtnetworking.api.Constants.CLI_FLAG_LENGTH;
+import static org.onosproject.kubevirtnetworking.api.Constants.CLI_IP_ADDRESSES_LENGTH;
+import static org.onosproject.kubevirtnetworking.api.Constants.CLI_IP_ADDRESS_LENGTH;
+import static org.onosproject.kubevirtnetworking.api.Constants.CLI_MARGIN_LENGTH;
+import static org.onosproject.kubevirtnetworking.api.Constants.CLI_NAME_LENGTH;
+import static org.onosproject.kubevirtnetworking.util.KubevirtNetworkingUtil.genFormatString;
+import static org.onosproject.kubevirtnetworking.util.KubevirtNetworkingUtil.prettyJson;
+
+@Service
+@Command(scope = "onos", name = "kubevirt-routers",
+ description = "Lists all kubevirt routers")
+public class KubevirtListRouterCommand extends AbstractShellCommand {
+
+ @Override
+ protected void doExecute() throws Exception {
+ KubevirtRouterService service = get(KubevirtRouterService.class);
+ KubevirtNetworkService netService = get(KubevirtNetworkService.class);
+ List<KubevirtRouter> routers = Lists.newArrayList(service.routers());
+ routers.sort(Comparator.comparing(KubevirtRouter::name));
+
+ String format = genFormatString(ImmutableList.of(CLI_NAME_LENGTH,
+ CLI_FLAG_LENGTH, CLI_IP_ADDRESSES_LENGTH, CLI_IP_ADDRESS_LENGTH));
+
+ if (outputJson()) {
+ print("%s", json(routers));
+ } else {
+ print(format, "Name", "SNAT", "Internal", "External");
+
+ for (KubevirtRouter router : routers) {
+ Set<String> internalCidrs = router.internal();
+ Set<String> externalIps = router.external().keySet();
+
+ String internal = internalCidrs.size() == 0 ? "[]" : internalCidrs.toString();
+ String external = externalIps.size() == 0 ? "[]" : externalIps.toString();
+
+ print(format, StringUtils.substring(router.name(), 0,
+ CLI_NAME_LENGTH - CLI_MARGIN_LENGTH),
+ StringUtils.substring(String.valueOf(router.enableSnat()), 0,
+ CLI_FLAG_LENGTH - CLI_MARGIN_LENGTH),
+ StringUtils.substring(internal, 0,
+ CLI_IP_ADDRESSES_LENGTH - CLI_MARGIN_LENGTH),
+ StringUtils.substring(external, 0,
+ CLI_IP_ADDRESS_LENGTH - CLI_MARGIN_LENGTH)
+ );
+ }
+ }
+ }
+
+ private String json(List<KubevirtRouter> routers) {
+ ObjectMapper mapper = new ObjectMapper();
+ ArrayNode result = mapper.createArrayNode();
+
+ for (KubevirtRouter router : routers) {
+ result.add(jsonForEntity(router, KubevirtRouter.class));
+ }
+
+ return prettyJson(mapper, result.toString());
+ }
+}
diff --git a/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/codec/KubevirtRouterCodec.java b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/codec/KubevirtRouterCodec.java
new file mode 100644
index 0000000..4937535
--- /dev/null
+++ b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/codec/KubevirtRouterCodec.java
@@ -0,0 +1,163 @@
+/*
+ * 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.codec;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.google.common.collect.ImmutableMap;
+import org.onlab.packet.IpAddress;
+import org.onlab.packet.MacAddress;
+import org.onosproject.codec.CodecContext;
+import org.onosproject.codec.JsonCodec;
+import org.onosproject.kubevirtnetworking.api.DefaultKubevirtRouter;
+import org.onosproject.kubevirtnetworking.api.KubevirtPeerRouter;
+import org.onosproject.kubevirtnetworking.api.KubevirtRouter;
+import org.slf4j.Logger;
+
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+import static org.onlab.util.Tools.nullIsIllegal;
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Kubevirt router codec used for serializing and de-serializing JSON string.
+ */
+public final class KubevirtRouterCodec extends JsonCodec<KubevirtRouter> {
+
+ private final Logger log = getLogger(getClass());
+
+ private static final String NAME = "name";
+ private static final String DESCRIPTION = "description";
+ private static final String ENABLE_SNAT = "enableSnat";
+ private static final String INTERNAL = "internal";
+ private static final String EXTERNAL = "external";
+ private static final String PEER_ROUTER = "peerRouter";
+ private static final String IP_ADDRESS = "ip";
+ private static final String MAC_ADDRESS = "mac";
+ private static final String NETWORK = "network";
+
+ private static final String MISSING_MESSAGE = " is required in KubevirtRouter";
+
+ @Override
+ public ObjectNode encode(KubevirtRouter router, CodecContext context) {
+ checkNotNull(router, "Kubevirt router pool cannot be null");
+
+ ObjectNode result = context.mapper().createObjectNode()
+ .put(NAME, router.name())
+ .put(ENABLE_SNAT, router.enableSnat());
+
+ if (router.description() != null) {
+ result.put(DESCRIPTION, router.description());
+ }
+
+ if (router.internal() != null && !router.internal().isEmpty()) {
+ ArrayNode internal = context.mapper().createArrayNode();
+ router.internal().forEach(internal::add);
+
+ result.set(INTERNAL, internal);
+ }
+
+ if (router.external() != null && !router.external().isEmpty()) {
+ ArrayNode external = context.mapper().createArrayNode();
+ router.external().forEach((k, v) -> {
+ ObjectNode item = context.mapper().createObjectNode();
+ item.put(IP_ADDRESS, k);
+ item.put(NETWORK, v);
+ external.add(item);
+ });
+ result.set(EXTERNAL, external);
+ }
+
+ if (router.peerRouter() != null) {
+ ObjectNode peerRouter = context.mapper().createObjectNode();
+ peerRouter.put(IP_ADDRESS, router.peerRouter().ipAddress().toString());
+
+ if (router.peerRouter().macAddress() != null) {
+ peerRouter.put(MAC_ADDRESS, router.peerRouter().macAddress().toString());
+ }
+
+ result.set(PEER_ROUTER, peerRouter);
+ }
+
+ return result;
+ }
+
+ @Override
+ public KubevirtRouter decode(ObjectNode json, CodecContext context) {
+ if (json == null || !json.isObject()) {
+ return null;
+ }
+
+ String name = nullIsIllegal(json.get(NAME).asText(),
+ NAME + MISSING_MESSAGE);
+
+ KubevirtRouter.Builder builder = DefaultKubevirtRouter.builder()
+ .name(name);
+
+ JsonNode descriptionJson = json.get(DESCRIPTION);
+ if (descriptionJson != null) {
+ builder.description(descriptionJson.asText());
+ }
+
+ JsonNode enableSnatJson = json.get(ENABLE_SNAT);
+ if (enableSnatJson != null) {
+ builder.enableSnat(enableSnatJson.asBoolean());
+ }
+
+ ArrayNode internalJson = (ArrayNode) json.get(INTERNAL);
+ Set<String> internal = new HashSet<>();
+ if (internalJson != null) {
+ for (int i = 0; i < internalJson.size(); i++) {
+ internal.add(internalJson.get(i).asText());
+ }
+ builder.internal(internal);
+ }
+
+ ObjectNode externalJson = (ObjectNode) json.get(EXTERNAL);
+ if (externalJson != null) {
+ Map<String, String> external = ImmutableMap.of(
+ externalJson.get(IP_ADDRESS).asText(),
+ externalJson.get(NETWORK).asText());
+ builder.external(external);
+ }
+
+ ObjectNode peerRouterJson = (ObjectNode) json.get(PEER_ROUTER);
+ if (peerRouterJson != null) {
+ JsonNode ipJson = peerRouterJson.get(IP_ADDRESS);
+ JsonNode macJson = peerRouterJson.get(MAC_ADDRESS);
+
+ if (ipJson != null && macJson != null) {
+ IpAddress ip = IpAddress.valueOf(ipJson.asText());
+ MacAddress mac = MacAddress.valueOf(macJson.asText());
+ KubevirtPeerRouter peer = new KubevirtPeerRouter(ip, mac);
+ builder.peerRouter(peer);
+ }
+
+ // if mac address is not specified, we will not add mac address to peer router
+ if (ipJson != null && macJson == null) {
+ IpAddress ip = IpAddress.valueOf(ipJson.asText());
+ KubevirtPeerRouter peer = new KubevirtPeerRouter(ip, null);
+ builder.peerRouter(peer);
+ }
+ }
+
+ return builder.build();
+ }
+}
diff --git a/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/impl/DistributedKubevirtPortStore.java b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/impl/DistributedKubevirtPortStore.java
index 2c5cd3f..5104bc8 100644
--- a/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/impl/DistributedKubevirtPortStore.java
+++ b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/impl/DistributedKubevirtPortStore.java
@@ -172,8 +172,9 @@
// if the event object has invalid port value, we do not
// propagate KUBEVIRT_PORT_REMOVED event.
if (event.oldValue() != null && event.oldValue().value() != null) {
- notifyDelegate(new KubevirtPortEvent(
- KUBEVIRT_PORT_REMOVED, event.oldValue().value()));
+ eventExecutor.execute(() ->
+ notifyDelegate(new KubevirtPortEvent(
+ KUBEVIRT_PORT_REMOVED, event.oldValue().value())));
}
break;
default:
diff --git a/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/impl/DistributedKubevirtRouterStore.java b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/impl/DistributedKubevirtRouterStore.java
new file mode 100644
index 0000000..537d91c
--- /dev/null
+++ b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/impl/DistributedKubevirtRouterStore.java
@@ -0,0 +1,183 @@
+/*
+ * 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.collect.ImmutableSet;
+import org.onlab.util.KryoNamespace;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.kubevirtnetworking.api.DefaultKubevirtRouter;
+import org.onosproject.kubevirtnetworking.api.KubevirtPeerRouter;
+import org.onosproject.kubevirtnetworking.api.KubevirtRouter;
+import org.onosproject.kubevirtnetworking.api.KubevirtRouterEvent;
+import org.onosproject.kubevirtnetworking.api.KubevirtRouterStore;
+import org.onosproject.kubevirtnetworking.api.KubevirtRouterStoreDelegate;
+import org.onosproject.store.AbstractStore;
+import org.onosproject.store.serializers.KryoNamespaces;
+import org.onosproject.store.service.ConsistentMap;
+import org.onosproject.store.service.MapEvent;
+import org.onosproject.store.service.MapEventListener;
+import org.onosproject.store.service.Serializer;
+import org.onosproject.store.service.StorageService;
+import org.onosproject.store.service.Versioned;
+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.Reference;
+import org.osgi.service.component.annotations.ReferenceCardinality;
+import org.slf4j.Logger;
+
+import java.util.Collection;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+
+import static com.google.common.base.Preconditions.checkArgument;
+import static java.util.concurrent.Executors.newSingleThreadExecutor;
+import static org.onlab.util.Tools.groupedThreads;
+import static org.onosproject.kubevirtnetworking.api.KubevirtRouterEvent.Type.KUBEVIRT_ROUTER_CREATED;
+import static org.onosproject.kubevirtnetworking.api.KubevirtRouterEvent.Type.KUBEVIRT_ROUTER_REMOVED;
+import static org.onosproject.kubevirtnetworking.api.KubevirtRouterEvent.Type.KUBEVIRT_ROUTER_UPDATED;
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Implementation of kubevirt router store using consistent map.
+ */
+@Component(immediate = true, service = KubevirtRouterStore.class)
+public class DistributedKubevirtRouterStore
+ extends AbstractStore<KubevirtRouterEvent, KubevirtRouterStoreDelegate>
+ implements KubevirtRouterStore {
+
+ private final Logger log = getLogger(getClass());
+
+ private static final String ERR_NOT_FOUND = " does not exist";
+ private static final String ERR_DUPLICATE = " already exists";
+ private static final String APP_ID = "org.onosproject.kubevirtnetwork";
+
+ private static final KryoNamespace
+ SERIALIZER_KUBEVIRT_ROUTER = KryoNamespace.newBuilder()
+ .register(KryoNamespaces.API)
+ .register(KubevirtRouter.class)
+ .register(DefaultKubevirtRouter.class)
+ .register(KubevirtPeerRouter.class)
+ .register(Collection.class)
+ .build();
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY)
+ protected CoreService coreService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY)
+ protected StorageService storageService;
+
+ private final ExecutorService eventExecutor = newSingleThreadExecutor(
+ groupedThreads(this.getClass().getSimpleName(), "event-handler", log));
+
+ private final MapEventListener<String, KubevirtRouter> routerMapListener =
+ new KubevirtRouterMapListener();
+
+ private ConsistentMap<String, KubevirtRouter> routerStore;
+
+ @Activate
+ protected void activate() {
+ ApplicationId appId = coreService.registerApplication(APP_ID);
+ routerStore = storageService.<String, KubevirtRouter>consistentMapBuilder()
+ .withSerializer(Serializer.using(SERIALIZER_KUBEVIRT_ROUTER))
+ .withName("kubevirt-routerstore")
+ .withApplicationId(appId)
+ .build();
+ routerStore.addListener(routerMapListener);
+ log.info("Started");
+ }
+
+ @Deactivate
+ protected void deactivate() {
+ routerStore.removeListener(routerMapListener);
+ eventExecutor.shutdown();
+ log.info("Stopped");
+ }
+
+ @Override
+ public void createRouter(KubevirtRouter router) {
+ routerStore.compute(router.name(), (name, existing) -> {
+ final String error = router.name() + ERR_DUPLICATE;
+ checkArgument(existing == null, error);
+ return router;
+ });
+ }
+
+ @Override
+ public void updateRouter(KubevirtRouter router) {
+ routerStore.compute(router.name(), (name, existing) -> {
+ final String error = router.name() + ERR_NOT_FOUND;
+ checkArgument(existing != null, error);
+ return router;
+ });
+ }
+
+ @Override
+ public KubevirtRouter removeRouter(String name) {
+ Versioned<KubevirtRouter> router = routerStore.remove(name);
+ if (router == null) {
+ final String error = name + ERR_NOT_FOUND;
+ throw new IllegalArgumentException(error);
+ }
+ return router.value();
+ }
+
+ @Override
+ public KubevirtRouter router(String name) {
+ return routerStore.asJavaMap().get(name);
+ }
+
+ @Override
+ public Set<KubevirtRouter> routers() {
+ return ImmutableSet.copyOf(routerStore.asJavaMap().values());
+ }
+
+ @Override
+ public void clear() {
+ routerStore.clear();
+ }
+
+ private class KubevirtRouterMapListener implements MapEventListener<String, KubevirtRouter> {
+
+ @Override
+ public void event(MapEvent<String, KubevirtRouter> event) {
+ switch (event.type()) {
+ case INSERT:
+ log.debug("Kubevirt router created");
+ eventExecutor.execute(() ->
+ notifyDelegate(new KubevirtRouterEvent(
+ KUBEVIRT_ROUTER_CREATED, event.newValue().value())));
+ break;
+ case UPDATE:
+ log.debug("Kubevirt router updated");
+ eventExecutor.execute(() ->
+ notifyDelegate(new KubevirtRouterEvent(
+ KUBEVIRT_ROUTER_UPDATED, event.newValue().value())));
+ break;
+ case REMOVE:
+ log.debug("Kubevirt router removed");
+ eventExecutor.execute(() ->
+ notifyDelegate(new KubevirtRouterEvent(
+ KUBEVIRT_ROUTER_REMOVED, event.oldValue().value())));
+ break;
+ default:
+ // do nothing
+ break;
+ }
+ }
+ }
+}
diff --git a/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/impl/KubevirtPortManager.java b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/impl/KubevirtPortManager.java
index b8160e2..f7bf516 100644
--- a/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/impl/KubevirtPortManager.java
+++ b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/impl/KubevirtPortManager.java
@@ -56,7 +56,7 @@
protected final Logger log = getLogger(getClass());
- private static final String MSG_PORT = "Kubernetes port %s %s";
+ private static final String MSG_PORT = "Kubevirt port %s %s";
private static final String MSG_CREATED = "created";
private static final String MSG_UPDATED = "updated";
private static final String MSG_REMOVED = "removed";
@@ -158,7 +158,7 @@
@Override
public void notify(KubevirtPortEvent event) {
if (event != null) {
- log.trace("send kubevirt networking event {}", event);
+ log.trace("send kubevirt port event {}", event);
process(event);
}
}
diff --git a/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/impl/KubevirtRouterManager.java b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/impl/KubevirtRouterManager.java
new file mode 100644
index 0000000..bae3ff9
--- /dev/null
+++ b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/impl/KubevirtRouterManager.java
@@ -0,0 +1,172 @@
+/*
+ * 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.ImmutableSet;
+import org.onlab.packet.MacAddress;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.event.ListenerRegistry;
+import org.onosproject.kubevirtnetworking.api.KubevirtPeerRouter;
+import org.onosproject.kubevirtnetworking.api.KubevirtRouter;
+import org.onosproject.kubevirtnetworking.api.KubevirtRouterAdminService;
+import org.onosproject.kubevirtnetworking.api.KubevirtRouterEvent;
+import org.onosproject.kubevirtnetworking.api.KubevirtRouterListener;
+import org.onosproject.kubevirtnetworking.api.KubevirtRouterService;
+import org.onosproject.kubevirtnetworking.api.KubevirtRouterStore;
+import org.onosproject.kubevirtnetworking.api.KubevirtRouterStoreDelegate;
+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.Reference;
+import org.osgi.service.component.annotations.ReferenceCardinality;
+import org.slf4j.Logger;
+
+import java.util.Set;
+
+import static com.google.common.base.Preconditions.checkArgument;
+import static com.google.common.base.Preconditions.checkNotNull;
+import static org.onosproject.kubevirtnetworking.api.Constants.KUBEVIRT_NETWORKING_APP_ID;
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Provides implementation of administering and interfacing kubevirt router.
+ */
+@Component(
+ immediate = true,
+ service = {KubevirtRouterAdminService.class, KubevirtRouterService.class }
+)
+public class KubevirtRouterManager
+ extends ListenerRegistry<KubevirtRouterEvent, KubevirtRouterListener>
+ implements KubevirtRouterAdminService, KubevirtRouterService {
+
+ protected final Logger log = getLogger(getClass());
+
+ private static final String MSG_ROUTER = "Kubevirt router %s %s";
+ private static final String MSG_CREATED = "created";
+ private static final String MSG_UPDATED = "updated";
+ private static final String MSG_REMOVED = "removed";
+
+ private static final String ERR_NULL_ROUTER = "Kubevirt router cannot be null";
+ private static final String ERR_NULL_ROUTER_NAME = "Kubevirt router name cannot be null";
+ private static final String ERR_IN_USE = " still in use";
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY)
+ protected CoreService coreService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY)
+ protected KubevirtRouterStore kubevirtRouterStore;
+
+ private final InternalRouterStorageDelegate delegate = new InternalRouterStorageDelegate();
+
+ private ApplicationId appId;
+
+ @Activate
+ protected void activate() {
+ appId = coreService.registerApplication(KUBEVIRT_NETWORKING_APP_ID);
+
+ kubevirtRouterStore.setDelegate(delegate);
+ log.info("Started");
+ }
+
+ @Deactivate
+ protected void deactivate() {
+ kubevirtRouterStore.unsetDelegate(delegate);
+ log.info("Stopped");
+ }
+
+ @Override
+ public void createRouter(KubevirtRouter router) {
+ checkNotNull(router, ERR_NULL_ROUTER);
+ checkArgument(!Strings.isNullOrEmpty(router.name()), ERR_NULL_ROUTER_NAME);
+
+ kubevirtRouterStore.createRouter(router);
+ log.info(String.format(MSG_ROUTER, router.name(), MSG_CREATED));
+ }
+
+ @Override
+ public void updateRouter(KubevirtRouter router) {
+ checkNotNull(router, ERR_NULL_ROUTER);
+ checkArgument(!Strings.isNullOrEmpty(router.name()), ERR_NULL_ROUTER_NAME);
+
+ kubevirtRouterStore.updateRouter(router);
+ log.info(String.format(MSG_ROUTER, router.name(), MSG_UPDATED));
+ }
+
+ @Override
+ public void removeRouter(String name) {
+ checkArgument(name != null, ERR_NULL_ROUTER_NAME);
+ synchronized (this) {
+ if (isRouterInUse(name)) {
+ final String error = String.format(MSG_ROUTER, name, ERR_IN_USE);
+ throw new IllegalStateException(error);
+ }
+
+ KubevirtRouter router = kubevirtRouterStore.removeRouter(name);
+ if (router != null) {
+ log.info(String.format(MSG_ROUTER, router.name(), MSG_REMOVED));
+ }
+ }
+ }
+
+ @Override
+ public void updatePeerRouterMac(String name, MacAddress mac) {
+ KubevirtRouter router = kubevirtRouterStore.router(name);
+ if (router == null) {
+ log.warn("The router is not found with the given name {}", name);
+ return;
+ }
+
+ KubevirtPeerRouter existing = router.peerRouter();
+ if (existing == null) {
+ log.warn("The peer router is not found with the given name {}", name);
+ return;
+ }
+
+ KubevirtPeerRouter updated = new KubevirtPeerRouter(existing.ipAddress(), mac);
+ kubevirtRouterStore.updateRouter(router.updatePeerRouter(updated));
+ }
+
+ @Override
+ public void clear() {
+ kubevirtRouterStore.clear();
+ }
+
+ @Override
+ public KubevirtRouter router(String name) {
+ checkArgument(name != null, ERR_NULL_ROUTER_NAME);
+ return kubevirtRouterStore.router(name);
+ }
+
+ @Override
+ public Set<KubevirtRouter> routers() {
+ return ImmutableSet.copyOf(kubevirtRouterStore.routers());
+ }
+
+ private boolean isRouterInUse(String name) {
+ return false;
+ }
+
+ private class InternalRouterStorageDelegate implements KubevirtRouterStoreDelegate {
+
+ @Override
+ public void notify(KubevirtRouterEvent event) {
+ log.trace("send kubevirt router event {}", event);
+ process(event);
+ }
+ }
+}
diff --git a/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/impl/KubevirtRouterWatcher.java b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/impl/KubevirtRouterWatcher.java
new file mode 100644
index 0000000..501099f
--- /dev/null
+++ b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/impl/KubevirtRouterWatcher.java
@@ -0,0 +1,258 @@
+/*
+ * 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.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.fabric8.kubernetes.client.KubernetesClient;
+import io.fabric8.kubernetes.client.Watcher;
+import io.fabric8.kubernetes.client.WatcherException;
+import io.fabric8.kubernetes.client.dsl.base.CustomResourceDefinitionContext;
+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.AbstractWatcher;
+import org.onosproject.kubevirtnetworking.api.KubevirtRouter;
+import org.onosproject.kubevirtnetworking.api.KubevirtRouterAdminService;
+import org.onosproject.kubevirtnode.api.KubevirtApiConfigEvent;
+import org.onosproject.kubevirtnode.api.KubevirtApiConfigListener;
+import org.onosproject.kubevirtnode.api.KubevirtApiConfigService;
+import org.onosproject.mastership.MastershipService;
+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.Reference;
+import org.osgi.service.component.annotations.ReferenceCardinality;
+import org.slf4j.Logger;
+
+import java.io.IOException;
+import java.util.Objects;
+import java.util.concurrent.ExecutorService;
+
+import static java.util.concurrent.Executors.newSingleThreadExecutor;
+import static org.onlab.util.Tools.groupedThreads;
+import static org.onosproject.kubevirtnetworking.api.Constants.KUBEVIRT_NETWORKING_APP_ID;
+import static org.onosproject.kubevirtnetworking.util.KubevirtNetworkingUtil.k8sClient;
+import static org.onosproject.kubevirtnetworking.util.KubevirtNetworkingUtil.parseResourceName;
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Kubevirt virtual router watcher used for feeding kubevirt router information.
+ */
+@Component(immediate = true)
+public class KubevirtRouterWatcher extends AbstractWatcher {
+
+ private final Logger log = getLogger(getClass());
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY)
+ protected CoreService coreService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY)
+ protected MastershipService mastershipService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY)
+ protected ClusterService clusterService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY)
+ protected LeadershipService leadershipService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY)
+ protected KubevirtRouterAdminService adminService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY)
+ protected KubevirtApiConfigService configService;
+
+ private final ExecutorService eventExecutor = newSingleThreadExecutor(
+ groupedThreads(this.getClass().getSimpleName(), "event-handler"));
+
+ private final InternalVirtualRouterWatcher
+ watcher = new InternalVirtualRouterWatcher();
+ private final InternalKubevirtApiConfigListener
+ configListener = new InternalKubevirtApiConfigListener();
+
+ CustomResourceDefinitionContext routerCrdCxt = new CustomResourceDefinitionContext
+ .Builder()
+ .withGroup("kubevirt.io")
+ .withScope("Cluster")
+ .withVersion("v1")
+ .withPlural("virtualrouters")
+ .build();
+
+ private ApplicationId appId;
+ private NodeId localNodeId;
+
+ @Activate
+ protected void activate() {
+ appId = coreService.registerApplication(KUBEVIRT_NETWORKING_APP_ID);
+ localNodeId = clusterService.getLocalNode().id();
+ leadershipService.runForLeadership(appId.name());
+ configService.addListener(configListener);
+
+ log.info("Started");
+ }
+
+ @Deactivate
+ protected void deactivate() {
+ configService.removeListener(configListener);
+ leadershipService.withdraw(appId.name());
+ eventExecutor.shutdown();
+
+ log.info("Stopped");
+ }
+
+ private void instantiateWatcher() {
+ KubernetesClient client = k8sClient(configService);
+
+ if (client != null) {
+ try {
+ client.customResource(routerCrdCxt).watch(watcher);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ private KubevirtRouter parseKubevirtRouter(String resource) {
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ JsonNode json = mapper.readTree(resource);
+ ObjectNode spec = (ObjectNode) json.get("spec");
+ return codec(KubevirtRouter.class).decode(spec, this);
+ } catch (IOException e) {
+ log.error("Failed to parse kubevirt router object");
+ }
+
+ return null;
+ }
+
+ private class InternalKubevirtApiConfigListener implements KubevirtApiConfigListener {
+
+ private boolean isRelevantHelper() {
+ return Objects.equals(localNodeId, leadershipService.getLeader(appId.name()));
+ }
+
+ @Override
+ public void event(KubevirtApiConfigEvent event) {
+
+ switch (event.type()) {
+ case KUBEVIRT_API_CONFIG_UPDATED:
+ eventExecutor.execute(this::processConfigUpdate);
+ break;
+ case KUBEVIRT_API_CONFIG_CREATED:
+ case KUBEVIRT_API_CONFIG_REMOVED:
+ default:
+ // do nothing
+ break;
+ }
+ }
+
+ private void processConfigUpdate() {
+ if (!isRelevantHelper()) {
+ return;
+ }
+
+ instantiateWatcher();
+ }
+ }
+
+ private class InternalVirtualRouterWatcher implements Watcher<String> {
+
+ @Override
+ public void eventReceived(Action action, String resource) {
+ switch (action) {
+ case ADDED:
+ eventExecutor.execute(() -> processAddition(resource));
+ break;
+ case MODIFIED:
+ eventExecutor.execute(() -> processModification(resource));
+ break;
+ case DELETED:
+ eventExecutor.execute(() -> processDeletion(resource));
+ break;
+ case ERROR:
+ log.warn("Failures processing virtual router manipulation.");
+ break;
+ default:
+ // do nothing
+ break;
+ }
+ }
+
+ @Override
+ public void onClose(WatcherException e) {
+ // due to the bugs in fabric8, the watcher might be closed,
+ // we will re-instantiate the watcher in this case
+ // FIXME: https://github.com/fabric8io/kubernetes-client/issues/2135
+ log.warn("Virtual Router watcher OnClose, re-instantiate the watcher...");
+
+ instantiateWatcher();
+ }
+
+ private void processAddition(String resource) {
+ if (!isMaster()) {
+ return;
+ }
+
+ String name = parseResourceName(resource);
+
+ log.trace("Process Virtual Router {} creating event from API server.",
+ name);
+
+ KubevirtRouter router = parseKubevirtRouter(resource);
+ if (router != null) {
+ if (adminService.router(router.name()) == null) {
+ adminService.createRouter(router);
+ }
+ }
+ }
+
+ private void processModification(String resource) {
+ if (!isMaster()) {
+ return;
+ }
+
+ String name = parseResourceName(resource);
+
+ log.trace("Process Virtual Router {} updating event from API server.",
+ name);
+
+ KubevirtRouter router = parseKubevirtRouter(resource);
+ if (router != null) {
+ adminService.updateRouter(router);
+ }
+ }
+
+ private void processDeletion(String resource) {
+ if (!isMaster()) {
+ return;
+ }
+
+ String name = parseResourceName(resource);
+
+ log.trace("Process Virtual Router {} removal event from API server.",
+ name);
+
+ adminService.removeRouter(name);
+ }
+
+ private boolean isMaster() {
+ return Objects.equals(localNodeId, leadershipService.getLeader(appId.name()));
+ }
+ }
+}
diff --git a/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/impl/NetworkAttachmentDefinitionWatcher.java b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/impl/NetworkAttachmentDefinitionWatcher.java
index 32bed58..d3a8ee4 100644
--- a/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/impl/NetworkAttachmentDefinitionWatcher.java
+++ b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/impl/NetworkAttachmentDefinitionWatcher.java
@@ -58,6 +58,7 @@
import static org.onosproject.kubevirtnetworking.api.Constants.KUBEVIRT_NETWORKING_APP_ID;
import static org.onosproject.kubevirtnetworking.api.KubevirtNetwork.Type.FLAT;
import static org.onosproject.kubevirtnetworking.util.KubevirtNetworkingUtil.k8sClient;
+import static org.onosproject.kubevirtnetworking.util.KubevirtNetworkingUtil.parseResourceName;
import static org.slf4j.LoggerFactory.getLogger;
/**
@@ -218,7 +219,7 @@
return;
}
- String name = parseName(resource);
+ String name = parseResourceName(resource);
log.trace("Process NetworkAttachmentDefinition {} creating event from API server.",
name);
@@ -236,7 +237,7 @@
return;
}
- String name = parseName(resource);
+ String name = parseResourceName(resource);
log.trace("Process NetworkAttachmentDefinition {} updating event from API server.",
name);
@@ -252,7 +253,7 @@
return;
}
- String name = parseName(resource);
+ String name = parseResourceName(resource);
log.trace("Process NetworkAttachmentDefinition {} removal event from API server.",
name);
@@ -264,20 +265,10 @@
return Objects.equals(localNodeId, leadershipService.getLeader(appId.name()));
}
- private String parseName(String resource) {
- try {
- JSONObject json = new JSONObject(resource);
- return json.getJSONObject("metadata").getString("name");
- } catch (JSONException e) {
- log.error("");
- }
- return "";
- }
-
private KubevirtNetwork parseKubevirtNetwork(String resource) {
try {
JSONObject json = new JSONObject(resource);
- String name = parseName(resource);
+ String name = parseResourceName(resource);
JSONObject annots = json.getJSONObject("metadata").getJSONObject("annotations");
String networkConfig = annots.getString(NETWORK_CONFIG);
if (networkConfig != null) {
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 04b6dba..d852ca4 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
@@ -413,6 +413,16 @@
}
}
+ public static String parseResourceName(String resource) {
+ try {
+ JSONObject json = new JSONObject(resource);
+ return json.getJSONObject("metadata").getString("name");
+ } catch (JSONException e) {
+ log.error("");
+ }
+ return "";
+ }
+
private static PortNumber portNumber(DeviceId deviceId, String portName) {
DeviceService deviceService = DefaultServiceDirectory.getService(DeviceService.class);
Port port = deviceService.getPorts(deviceId).stream()
diff --git a/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/web/KubevirtNetworkingCodecRegister.java b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/web/KubevirtNetworkingCodecRegister.java
index 4691b8b..2539dff 100644
--- a/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/web/KubevirtNetworkingCodecRegister.java
+++ b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/web/KubevirtNetworkingCodecRegister.java
@@ -20,10 +20,12 @@
import org.onosproject.kubevirtnetworking.api.KubevirtIpPool;
import org.onosproject.kubevirtnetworking.api.KubevirtNetwork;
import org.onosproject.kubevirtnetworking.api.KubevirtPort;
+import org.onosproject.kubevirtnetworking.api.KubevirtRouter;
import org.onosproject.kubevirtnetworking.codec.KubevirtHostRouteCodec;
import org.onosproject.kubevirtnetworking.codec.KubevirtIpPoolCodec;
import org.onosproject.kubevirtnetworking.codec.KubevirtNetworkCodec;
import org.onosproject.kubevirtnetworking.codec.KubevirtPortCodec;
+import org.onosproject.kubevirtnetworking.codec.KubevirtRouterCodec;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
@@ -51,6 +53,7 @@
codecService.registerCodec(KubevirtIpPool.class, new KubevirtIpPoolCodec());
codecService.registerCodec(KubevirtNetwork.class, new KubevirtNetworkCodec());
codecService.registerCodec(KubevirtPort.class, new KubevirtPortCodec());
+ codecService.registerCodec(KubevirtRouter.class, new KubevirtRouterCodec());
log.info("Started");
}
@@ -62,6 +65,7 @@
codecService.unregisterCodec(KubevirtIpPool.class);
codecService.unregisterCodec(KubevirtNetwork.class);
codecService.unregisterCodec(KubevirtPort.class);
+ codecService.unregisterCodec(KubevirtRouter.class);
log.info("Stopped");
}
diff --git a/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/web/KubevirtNetworkingWebApplication.java b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/web/KubevirtNetworkingWebApplication.java
index 29fe7bc..d2a45af 100644
--- a/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/web/KubevirtNetworkingWebApplication.java
+++ b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/web/KubevirtNetworkingWebApplication.java
@@ -27,7 +27,8 @@
public Set<Class<?>> getClasses() {
return getClasses(
KubevirtNetworkWebResource.class,
- KubevirtManagementWebResource.class
+ KubevirtManagementWebResource.class,
+ KubevirtRouterWebResource.class
);
}
}
diff --git a/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/web/KubevirtRouterWebResource.java b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/web/KubevirtRouterWebResource.java
new file mode 100644
index 0000000..731b0d4
--- /dev/null
+++ b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/web/KubevirtRouterWebResource.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.web;
+
+import org.onosproject.kubevirtnetworking.api.KubevirtRouter;
+import org.onosproject.kubevirtnetworking.api.KubevirtRouterService;
+import org.onosproject.rest.AbstractWebResource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+/**
+ * Handles REST API call for kubevirt router.
+ */
+@Path("router")
+public class KubevirtRouterWebResource extends AbstractWebResource {
+
+ protected final Logger log = LoggerFactory.getLogger(getClass());
+
+ /**
+ * Returns set of all routers.
+ *
+ * @return 200 OK with set of all routers
+ * @onos.rsModel KubevirtRouters
+ */
+ @GET
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response getRouters() {
+ KubevirtRouterService service = get(KubevirtRouterService.class);
+ final Iterable<KubevirtRouter> routers = service.routers();
+ return ok(encodeArray(KubevirtRouter.class, "routers", routers)).build();
+ }
+}
diff --git a/apps/kubevirt-networking/app/src/main/resources/definitions/KubevirtNetworks.json b/apps/kubevirt-networking/app/src/main/resources/definitions/KubevirtNetworks.json
index f838b60..5ce66f0 100644
--- a/apps/kubevirt-networking/app/src/main/resources/definitions/KubevirtNetworks.json
+++ b/apps/kubevirt-networking/app/src/main/resources/definitions/KubevirtNetworks.json
@@ -1,14 +1,14 @@
{
"type": "object",
- "title": "regions",
+ "title": "networks",
"required": [
- "regions"
+ "networks"
],
"properties": {
- "regions": {
+ "networks": {
"type": "array",
"xml": {
- "name": "regions",
+ "name": "networks",
"wrapped": true
},
"items": {
diff --git a/apps/kubevirt-networking/app/src/main/resources/definitions/KubevirtRouters.json b/apps/kubevirt-networking/app/src/main/resources/definitions/KubevirtRouters.json
new file mode 100644
index 0000000..3546dff
--- /dev/null
+++ b/apps/kubevirt-networking/app/src/main/resources/definitions/KubevirtRouters.json
@@ -0,0 +1,91 @@
+{
+ "type": "object",
+ "title": "routers",
+ "required": [
+ "routers"
+ ],
+ "properties": {
+ "routers": {
+ "type": "array",
+ "xml": {
+ "name": "routers",
+ "wrapped": true
+ },
+ "items": {
+ "type": "object",
+ "description": "A router object.",
+ "required": [
+ "name",
+ "enableSnat",
+ "internal",
+ "external",
+ "peerRouter"
+ ],
+ "properties": {
+ "name": {
+ "type": "string",
+ "example": "router-1",
+ "description": "The name of router."
+ },
+ "enableSnat": {
+ "type": "boolean",
+ "example": "true",
+ "description": "Enable SNAT flag."
+ },
+ "internal": {
+ "type": "array",
+ "xml": {
+ "name": "internal",
+ "wrapped": true
+ },
+ "items": {
+ "type": "string",
+ "example": "vxlan-1",
+ "description": "name of internal network"
+ }
+ },
+ "external": {
+ "type": "object",
+ "description": "external networks",
+ "required": [
+ "ip",
+ "name"
+ ],
+ "properties": {
+ "ipaddress": {
+ "type": "string",
+ "example": "10.10.10.5",
+ "description": "Router IP address of the external network"
+ },
+ "name": {
+ "type": "string",
+ "example": "flat",
+ "description": "Name of the external network"
+ }
+ }
+ },
+ "peerRouter": {
+ "type": "object",
+ "description": "peer router",
+ "required": [
+ "ip",
+ "mac"
+ ],
+ "properties": {
+ "ipaddress": {
+ "type": "string",
+ "example": "10.10.10.1",
+ "description": "IP address of the peer router"
+ },
+ "macaddress": {
+ "type": "string",
+ "example": "11:22:33:44:55:66",
+ "description": "MAC address of the peer router"
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/apps/kubevirt-networking/app/src/test/java/org/onosproject/kubevirtnetworking/codec/KubevirtRouterCodecTest.java b/apps/kubevirt-networking/app/src/test/java/org/onosproject/kubevirtnetworking/codec/KubevirtRouterCodecTest.java
new file mode 100644
index 0000000..f2b2470
--- /dev/null
+++ b/apps/kubevirt-networking/app/src/test/java/org/onosproject/kubevirtnetworking/codec/KubevirtRouterCodecTest.java
@@ -0,0 +1,113 @@
+/*
+ * 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.codec;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import org.hamcrest.MatcherAssert;
+import org.junit.Before;
+import org.junit.Test;
+import org.onlab.packet.IpAddress;
+import org.onlab.packet.MacAddress;
+import org.onosproject.codec.JsonCodec;
+import org.onosproject.codec.impl.MockCodecContext;
+import org.onosproject.core.CoreService;
+import org.onosproject.kubevirtnetworking.api.DefaultKubevirtRouter;
+import org.onosproject.kubevirtnetworking.api.KubevirtPeerRouter;
+import org.onosproject.kubevirtnetworking.api.KubevirtRouter;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+import static junit.framework.TestCase.assertEquals;
+import static junit.framework.TestCase.assertTrue;
+import static org.easymock.EasyMock.createMock;
+import static org.easymock.EasyMock.expect;
+import static org.easymock.EasyMock.replay;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.notNullValue;
+import static org.onosproject.kubevirtnetworking.codec.KubevirtRouterJsonMatcher.matchesKubevirtRouter;
+import static org.onosproject.net.NetTestTools.APP_ID;
+
+/**
+ * Unit tests for KubevirtRouter codec.
+ */
+public final class KubevirtRouterCodecTest {
+
+ MockCodecContext context;
+
+ JsonCodec<KubevirtRouter> kubevirtRouterCodec;
+
+ final CoreService mockCoreService = createMock(CoreService.class);
+ private static final String REST_APP_ID = "org.onosproject.rest";
+
+ @Before
+ public void setUp() {
+ context = new MockCodecContext();
+ kubevirtRouterCodec = new KubevirtRouterCodec();
+
+ assertThat(kubevirtRouterCodec, notNullValue());
+ expect(mockCoreService.registerApplication(REST_APP_ID))
+ .andReturn(APP_ID).anyTimes();
+ replay(mockCoreService);
+ context.registerService(CoreService.class, mockCoreService);
+ }
+
+ /**
+ * Tests the kubevirt router encoding.
+ */
+ @Test
+ public void testKubevirtRouterEncode() {
+ KubevirtPeerRouter peerRouter = new KubevirtPeerRouter(IpAddress.valueOf("10.10.10.10"),
+ MacAddress.valueOf("11:22:33:44:55:66"));
+
+ KubevirtRouter router = DefaultKubevirtRouter.builder()
+ .name("router-1")
+ .enableSnat(true)
+ .description("router-1")
+ .internal(ImmutableSet.of("vlan-1"))
+ .external(ImmutableMap.of("10.10.10.20", "flat-1"))
+ .peerRouter(peerRouter)
+ .build();
+
+ ObjectNode routerJson = kubevirtRouterCodec.encode(router, context);
+ assertThat(routerJson, matchesKubevirtRouter(router));
+ }
+
+ @Test
+ public void testKubevirtRouterDecode() throws IOException {
+ KubevirtRouter router = getKubevirtRouter("KubevirtRouter.json");
+
+ assertEquals("router-1", router.name());
+ assertEquals("Example Virtual Router", router.description());
+ assertTrue(router.enableSnat());
+ assertEquals("external-network", router.external().get("192.168.10.5"));
+ assertTrue(router.internal().contains("vxlan-network-1"));
+ assertTrue(router.internal().contains("vxlan-network-2"));
+ assertEquals("192.168.10.1", router.peerRouter().ipAddress().toString());
+ }
+
+ private KubevirtRouter getKubevirtRouter(String resourceName) throws IOException {
+ InputStream jsonStream = KubevirtRouterCodecTest.class.getResourceAsStream(resourceName);
+ JsonNode json = context.mapper().readTree(jsonStream);
+ MatcherAssert.assertThat(json, notNullValue());
+ KubevirtRouter router = kubevirtRouterCodec.decode((ObjectNode) json, context);
+ assertThat(router, notNullValue());
+ return router;
+ }
+}
diff --git a/apps/kubevirt-networking/app/src/test/java/org/onosproject/kubevirtnetworking/codec/KubevirtRouterJsonMatcher.java b/apps/kubevirt-networking/app/src/test/java/org/onosproject/kubevirtnetworking/codec/KubevirtRouterJsonMatcher.java
new file mode 100644
index 0000000..1b394e7
--- /dev/null
+++ b/apps/kubevirt-networking/app/src/test/java/org/onosproject/kubevirtnetworking/codec/KubevirtRouterJsonMatcher.java
@@ -0,0 +1,164 @@
+/*
+ * 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.codec;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import org.hamcrest.Description;
+import org.hamcrest.TypeSafeDiagnosingMatcher;
+import org.onosproject.kubevirtnetworking.api.KubevirtRouter;
+
+/**
+ * Hamcrest matcher for kubevirt router interface.
+ */
+public final class KubevirtRouterJsonMatcher extends TypeSafeDiagnosingMatcher<JsonNode> {
+
+ private final KubevirtRouter router;
+ private static final String NAME = "name";
+ private static final String DESCRIPTION = "description";
+ private static final String ENABLE_SNAT = "enableSnat";
+ private static final String INTERNAL = "internal";
+ private static final String EXTERNAL = "external";
+ private static final String PEER_ROUTER = "peerRouter";
+ private static final String IP_ADDRESS = "ip";
+ private static final String MAC_ADDRESS = "mac";
+ private static final String NETWORK = "network";
+
+ private KubevirtRouterJsonMatcher(KubevirtRouter router) {
+ this.router = router;
+ }
+
+ @Override
+ protected boolean matchesSafely(JsonNode jsonNode, Description description) {
+
+ // check name
+ String jsonName = jsonNode.get(NAME).asText();
+ String name = router.name();
+ if (!jsonName.equals(name)) {
+ description.appendText("Name was " + jsonName);
+ return false;
+ }
+
+ // check description
+ JsonNode jsonDescription = jsonNode.get(DESCRIPTION);
+ if (jsonDescription != null) {
+ String myDescription = router.description();
+ if (!jsonDescription.asText().equals(myDescription)) {
+ description.appendText("Description was " + jsonDescription);
+ return false;
+ }
+ }
+
+ // check enable snat
+ JsonNode jsonEnableSnat = jsonNode.get(ENABLE_SNAT);
+ if (jsonEnableSnat != null) {
+ boolean enableSnat = router.enableSnat();
+ if (jsonEnableSnat.asBoolean() != enableSnat) {
+ description.appendText("EnableSNAT was " + jsonEnableSnat);
+ return false;
+ }
+ }
+
+ // check internal
+ JsonNode jsonInternal = jsonNode.get(INTERNAL);
+ if (jsonInternal != null) {
+ if (jsonInternal.size() != router.internal().size()) {
+ description.appendText("Internal networks size was " + jsonInternal.size());
+ return false;
+ }
+
+ for (int networkIndex = 0; networkIndex < jsonInternal.size(); networkIndex++) {
+ boolean networkFound = false;
+ String jsonNetwork = jsonInternal.get(networkIndex).asText();
+ if (router.internal().contains(jsonNetwork)) {
+ networkFound = true;
+ }
+
+ if (!networkFound) {
+ description.appendText("network not found " + jsonNetwork);
+ return false;
+ }
+ }
+ }
+
+ // check external
+ ArrayNode jsonExternal = (ArrayNode) jsonNode.get(EXTERNAL);
+ if (jsonExternal != null) {
+ if (jsonExternal.size() != router.external().size()) {
+ description.appendText("External networks size was " + jsonExternal.size());
+ return false;
+ }
+
+ for (int itemIndex = 0; itemIndex < jsonExternal.size(); itemIndex++) {
+ boolean itemFound = false;
+ ObjectNode jsonItem = (ObjectNode) jsonExternal.get(itemIndex);
+ String jsonIp = jsonItem.get(IP_ADDRESS).asText();
+ String jsonNetwork = jsonItem.get(NETWORK).asText();
+
+ if (router.external().containsKey(jsonIp)) {
+ if (router.external().get(jsonIp).equals(jsonNetwork)) {
+ itemFound = true;
+ }
+ }
+
+ if (!itemFound) {
+ description.appendText("External not found " + jsonItem.toString());
+ return false;
+ }
+ }
+ }
+
+ // check peer router
+ ObjectNode jsonPeerRouter = (ObjectNode) jsonNode.get(PEER_ROUTER);
+ if (jsonPeerRouter != null) {
+ JsonNode jsonIp = jsonPeerRouter.get(IP_ADDRESS);
+
+ if (jsonIp != null) {
+ if (!jsonIp.asText().equals(router.peerRouter().ipAddress().toString())) {
+ description.appendText("Peer router IP was " + jsonIp);
+ return false;
+ }
+ }
+
+ JsonNode jsonMac = jsonPeerRouter.get(MAC_ADDRESS);
+
+ if (jsonMac != null) {
+ if (!jsonMac.asText().equals(router.peerRouter().macAddress().toString())) {
+ description.appendText("Peer router MAC was " + jsonMac);
+ return false;
+ }
+ }
+ }
+
+ return true;
+ }
+
+ @Override
+ public void describeTo(Description description) {
+ description.appendText(router.toString());
+ }
+
+ /**
+ * Factory to allocate a kubevirt router matcher.
+ *
+ * @param router kubevirt router object we are looking for
+ * @return matcher
+ */
+ public static KubevirtRouterJsonMatcher matchesKubevirtRouter(KubevirtRouter router) {
+ return new KubevirtRouterJsonMatcher(router);
+ }
+}
diff --git a/apps/kubevirt-networking/app/src/test/java/org/onosproject/kubevirtnetworking/impl/KubevirtRouterManagerTest.java b/apps/kubevirt-networking/app/src/test/java/org/onosproject/kubevirtnetworking/impl/KubevirtRouterManagerTest.java
new file mode 100644
index 0000000..8a7e553
--- /dev/null
+++ b/apps/kubevirt-networking/app/src/test/java/org/onosproject/kubevirtnetworking/impl/KubevirtRouterManagerTest.java
@@ -0,0 +1,236 @@
+/*
+ * 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.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import com.google.common.util.concurrent.MoreExecutors;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.onlab.junit.TestUtils;
+import org.onlab.packet.IpAddress;
+import org.onlab.packet.MacAddress;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreServiceAdapter;
+import org.onosproject.core.DefaultApplicationId;
+import org.onosproject.event.Event;
+import org.onosproject.kubevirtnetworking.api.DefaultKubevirtRouter;
+import org.onosproject.kubevirtnetworking.api.KubevirtPeerRouter;
+import org.onosproject.kubevirtnetworking.api.KubevirtRouter;
+import org.onosproject.kubevirtnetworking.api.KubevirtRouterEvent;
+import org.onosproject.kubevirtnetworking.api.KubevirtRouterListener;
+import org.onosproject.store.service.TestStorageService;
+
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.onosproject.kubevirtnetworking.api.KubevirtRouterEvent.Type.KUBEVIRT_ROUTER_CREATED;
+import static org.onosproject.kubevirtnetworking.api.KubevirtRouterEvent.Type.KUBEVIRT_ROUTER_REMOVED;
+import static org.onosproject.kubevirtnetworking.api.KubevirtRouterEvent.Type.KUBEVIRT_ROUTER_UPDATED;
+
+/**
+ * Unit tests for kubernetes router manager.
+ */
+public class KubevirtRouterManagerTest {
+
+ private static final ApplicationId TEST_APP_ID = new DefaultApplicationId(1, "test");
+
+ private static final String ROUTER_NAME = "router-1";
+ private static final String UPDATED_DESCRIPTION = "router-updated";
+
+ private static final MacAddress UPDATED_MAC = MacAddress.valueOf("FF:FF:FF:FF:FF:FF");
+
+ private static final KubevirtRouter ROUTER = DefaultKubevirtRouter.builder()
+ .name(ROUTER_NAME)
+ .description(ROUTER_NAME)
+ .internal(ImmutableSet.of("vxlan-1", "vxlan-2"))
+ .external(ImmutableMap.of("10.10.10.10", "flat"))
+ .enableSnat(true)
+ .peerRouter(new KubevirtPeerRouter(IpAddress.valueOf("20.20.20.20"),
+ MacAddress.valueOf("11:22:33:44:55:66")))
+ .build();
+
+ private static final KubevirtRouter ROUTER_UPDATED = DefaultKubevirtRouter.builder()
+ .name(ROUTER_NAME)
+ .description(UPDATED_DESCRIPTION)
+ .internal(ImmutableSet.of("vxlan-1", "vxlan-2"))
+ .external(ImmutableMap.of("10.10.10.10", "flat"))
+ .enableSnat(true)
+ .peerRouter(new KubevirtPeerRouter(IpAddress.valueOf("20.20.20.20"),
+ MacAddress.valueOf("11:22:33:44:55:66")))
+ .build();
+
+ private final TestKubevirtRouterListener testListener = new TestKubevirtRouterListener();
+
+ private KubevirtRouterManager target;
+ private DistributedKubevirtRouterStore kubevirtRouterStore;
+
+ @Before
+ public void setUp() throws Exception {
+ kubevirtRouterStore = new DistributedKubevirtRouterStore();
+ TestUtils.setField(kubevirtRouterStore, "coreService", new TestCoreService());
+ TestUtils.setField(kubevirtRouterStore, "storageService", new TestStorageService());
+ TestUtils.setField(kubevirtRouterStore, "eventExecutor", MoreExecutors.newDirectExecutorService());
+ kubevirtRouterStore.activate();
+
+ target = new KubevirtRouterManager();
+ TestUtils.setField(target, "coreService", new TestCoreService());
+ target.kubevirtRouterStore = kubevirtRouterStore;
+ target.addListener(testListener);
+ target.activate();
+ }
+
+ @After
+ public void tearDown() {
+ target.removeListener(testListener);
+ kubevirtRouterStore.deactivate();
+ target.deactivate();
+ kubevirtRouterStore = null;
+ target = null;
+ }
+
+ /**
+ * Tests if getting all routers returns correct set of values.
+ */
+ @Test
+ public void testGetRouters() {
+ createBasicRouters();
+ assertEquals("Number of router did not match", 1, target.routers().size());
+ }
+
+ /**
+ * Tests if getting a router with name returns correct value.
+ */
+ @Test
+ public void testGetRouterByName() {
+ createBasicRouters();
+ assertNotNull("Router did not match", target.router(ROUTER_NAME));
+ }
+
+ /**
+ * Tests creating and removing a router, and checks if proper event is triggered.
+ */
+ @Test
+ public void testCreateAndRemoveRouter() {
+ target.createRouter(ROUTER);
+ assertEquals("Number of router did not match", 1, target.routers().size());
+ assertNotNull("Router was not created", target.router(ROUTER_NAME));
+
+ target.removeRouter(ROUTER_NAME);
+ assertEquals("Number of router did not match", 0, target.routers().size());
+ assertNull("Router was not created", target.router(ROUTER_NAME));
+
+ validateEvents(KUBEVIRT_ROUTER_CREATED, KUBEVIRT_ROUTER_REMOVED);
+ }
+
+ /**
+ * Tests creating and updating a port, and checks if proper event is triggered.
+ */
+ @Test
+ public void testCreateAndUpdateRouter() {
+ target.createRouter(ROUTER);
+ assertEquals("Number of router did not match", 1, target.routers().size());
+
+ target.updateRouter(ROUTER_UPDATED);
+ assertEquals("Number of router did not match", 1, target.routers().size());
+ assertEquals("Router did not match", UPDATED_DESCRIPTION, target.router(ROUTER_NAME).description());
+
+ validateEvents(KUBEVIRT_ROUTER_CREATED, KUBEVIRT_ROUTER_UPDATED);
+ }
+
+ /**
+ * Tests updating peer router MAC address.
+ */
+ @Test
+ public void testPeerRouterMacUpdate() {
+ target.createRouter(ROUTER);
+
+ target.updatePeerRouterMac(ROUTER_NAME, UPDATED_MAC);
+ assertEquals("MAC address was not updated", UPDATED_MAC,
+ target.router(ROUTER_NAME).peerRouter().macAddress());
+
+ validateEvents(KUBEVIRT_ROUTER_CREATED, KUBEVIRT_ROUTER_UPDATED);
+ }
+
+ /**
+ * Tests if creating a null router fails with an exception.
+ */
+ @Test(expected = NullPointerException.class)
+ public void testCreateNullRouter() {
+ target.createRouter(null);
+ }
+
+ /**
+ * Tests if creating a duplicate router fails with an exception.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void createDuplicateRouter() {
+ target.createRouter(ROUTER);
+ target.createRouter(ROUTER);
+ }
+
+ /**
+ * Tests if updating an unregistered router fails with an exception.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void testUpdateUnregisteredRouter() {
+ target.updateRouter(ROUTER);
+ }
+
+ /**
+ * Tests if updating a null router fails with an exception.
+ */
+ @Test(expected = NullPointerException.class)
+ public void testUpdateNullRouter() {
+ target.updateRouter(null);
+ }
+
+ private void createBasicRouters() {
+ target.createRouter(ROUTER);
+ }
+
+ private static class TestCoreService extends CoreServiceAdapter {
+
+ @Override
+ public ApplicationId registerApplication(String name) {
+ return TEST_APP_ID;
+ }
+ }
+
+ private static class TestKubevirtRouterListener implements KubevirtRouterListener {
+
+ private List<KubevirtRouterEvent> events = Lists.newArrayList();
+
+ @Override
+ public void event(KubevirtRouterEvent event) {
+ events.add(event);
+ }
+ }
+
+ private void validateEvents(Enum... types) {
+ int i = 0;
+ assertEquals("Number of events did not match", types.length, testListener.events.size());
+ for (Event event : testListener.events) {
+ assertEquals("Incorrect event received", types[i], event.type());
+ i++;
+ }
+ testListener.events.clear();
+ }
+}
diff --git a/apps/kubevirt-networking/app/src/test/resources/org/onosproject/kubevirtnetworking/codec/KubevirtRouter.json b/apps/kubevirt-networking/app/src/test/resources/org/onosproject/kubevirtnetworking/codec/KubevirtRouter.json
new file mode 100644
index 0000000..44fd556
--- /dev/null
+++ b/apps/kubevirt-networking/app/src/test/resources/org/onosproject/kubevirtnetworking/codec/KubevirtRouter.json
@@ -0,0 +1,16 @@
+{
+ "name": "router-1",
+ "description": "Example Virtual Router",
+ "enableSnat": true,
+ "external": {
+ "ip": "192.168.10.5",
+ "network": "external-network"
+ },
+ "internal": [
+ "vxlan-network-1",
+ "vxlan-network-2"
+ ],
+ "peerRouter": {
+ "ip": "192.168.10.1"
+ }
+}
\ No newline at end of file