Implement kubevirt loadbalancer service with unit tests
Change-Id: I1c29e75aa5196b497f8f12f1d182788e3d173244
(cherry picked from commit 870abf8c7a7904c5953e20807ee7c681d8b5cd0b)
diff --git a/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/DefaultKubevirtLoadBalancer.java b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/DefaultKubevirtLoadBalancer.java
new file mode 100644
index 0000000..bf4a21d
--- /dev/null
+++ b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/DefaultKubevirtLoadBalancer.java
@@ -0,0 +1,193 @@
+/*
+ * 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.google.common.base.MoreObjects;
+import com.google.common.collect.ImmutableSet;
+import org.onlab.packet.IpAddress;
+
+import java.util.Objects;
+import java.util.Set;
+
+import static com.google.common.base.Preconditions.checkArgument;
+
+/**
+ * Default implementation of kubevirt load balancer.
+ */
+public final class DefaultKubevirtLoadBalancer implements KubevirtLoadBalancer {
+
+ private static final String NOT_NULL_MSG = "Loadbalancer % cannot be null";
+
+ private final String name;
+ private final String description;
+ private final String networkId;
+ private final IpAddress vip;
+ private final Set<IpAddress> members;
+ private final Set<KubevirtLoadBalancerRule> rules;
+
+ /**
+ * Default constructor.
+ *
+ * @param name load balancer name
+ * @param description load balancer description
+ * @param networkId load balancer network identifier
+ * @param vip load balancer virtual IP address
+ * @param members load balancer members
+ * @param rules load balancer rules
+ */
+ public DefaultKubevirtLoadBalancer(String name, String description, String networkId,
+ IpAddress vip, Set<IpAddress> members,
+ Set<KubevirtLoadBalancerRule> rules) {
+ this.name = name;
+ this.description = description;
+ this.networkId = networkId;
+ this.vip = vip;
+ this.members = members;
+ this.rules = rules;
+ }
+
+ @Override
+ public String name() {
+ return name;
+ }
+
+ @Override
+ public String description() {
+ return description;
+ }
+
+ @Override
+ public String networkId() {
+ return networkId;
+ }
+
+ @Override
+ public IpAddress vip() {
+ return vip;
+ }
+
+ @Override
+ public Set<IpAddress> members() {
+ if (members == null) {
+ return ImmutableSet.of();
+ } else {
+ return ImmutableSet.copyOf(members);
+ }
+ }
+
+ @Override
+ public Set<KubevirtLoadBalancerRule> rules() {
+ if (rules == null) {
+ return ImmutableSet.of();
+ } else {
+ return ImmutableSet.copyOf(rules);
+ }
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ DefaultKubevirtLoadBalancer that = (DefaultKubevirtLoadBalancer) o;
+ return name.equals(that.name) && Objects.equals(description, that.description) &&
+ networkId.equals(that.networkId) && vip.equals(that.vip) &&
+ Objects.equals(members, that.members) && Objects.equals(rules, that.rules);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(name, description, networkId, vip, members, rules);
+ }
+
+ @Override
+ public String toString() {
+ return MoreObjects.toStringHelper(this)
+ .add("name", name)
+ .add("description", description)
+ .add("networkId", networkId)
+ .add("vip", vip)
+ .add("members", members)
+ .add("rules", rules)
+ .toString();
+ }
+
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ public static final class Builder implements KubevirtLoadBalancer.Builder {
+
+ private String name;
+ private String description;
+ private String networkId;
+ private IpAddress vip;
+ private Set<IpAddress> members;
+ private Set<KubevirtLoadBalancerRule> rules;
+
+ // private constructor not intended to use from external
+ private Builder() {
+ }
+
+ @Override
+ public KubevirtLoadBalancer build() {
+ checkArgument(networkId != null, NOT_NULL_MSG, "networkId");
+ checkArgument(name != null, NOT_NULL_MSG, "name");
+ checkArgument(vip != null, NOT_NULL_MSG, "vip");
+
+ return new DefaultKubevirtLoadBalancer(name, description, networkId, vip, members, rules);
+ }
+
+ @Override
+ public Builder name(String name) {
+ this.name = name;
+ return this;
+ }
+
+ @Override
+ public Builder description(String description) {
+ this.description = description;
+ return this;
+ }
+
+ @Override
+ public Builder networkId(String networkId) {
+ this.networkId = networkId;
+ return this;
+ }
+
+ @Override
+ public Builder vip(IpAddress vip) {
+ this.vip = vip;
+ return this;
+ }
+
+ @Override
+ public Builder members(Set<IpAddress> members) {
+ this.members = members;
+ return this;
+ }
+
+ @Override
+ public Builder rules(Set<KubevirtLoadBalancerRule> rules) {
+ this.rules = rules;
+ return this;
+ }
+ }
+}
diff --git a/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/DefaultKubevirtLoadBalancerRule.java b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/DefaultKubevirtLoadBalancerRule.java
new file mode 100644
index 0000000..453610e
--- /dev/null
+++ b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/DefaultKubevirtLoadBalancerRule.java
@@ -0,0 +1,134 @@
+/*
+ * 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.google.common.base.MoreObjects;
+
+import java.util.Objects;
+
+import static com.google.common.base.Preconditions.checkArgument;
+
+/**
+ * Default implementation class of kubevirt load balancer rule.
+ */
+public final class DefaultKubevirtLoadBalancerRule implements KubevirtLoadBalancerRule {
+ private static final String NOT_NULL_MSG = "Load Balancer Rule % cannot be null";
+
+ private final String protocol;
+ private final Integer portRangeMax;
+ private final Integer portRangeMin;
+
+ /**
+ * A default constructor.
+ *
+ * @param protocol protocol
+ * @param portRangeMax port range max
+ * @param portRangeMin port range min
+ */
+ public DefaultKubevirtLoadBalancerRule(String protocol,
+ Integer portRangeMax,
+ Integer portRangeMin) {
+ this.protocol = protocol;
+ this.portRangeMax = portRangeMax;
+ this.portRangeMin = portRangeMin;
+ }
+
+ @Override
+ public String protocol() {
+ return protocol;
+ }
+
+ @Override
+ public Integer portRangeMax() {
+ return portRangeMax;
+ }
+
+ @Override
+ public Integer portRangeMin() {
+ return portRangeMin;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ DefaultKubevirtLoadBalancerRule that = (DefaultKubevirtLoadBalancerRule) o;
+ return protocol.equals(that.protocol) &&
+ portRangeMax.equals(that.portRangeMax) &&
+ portRangeMin.equals(that.portRangeMin);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(protocol, portRangeMax, portRangeMin);
+ }
+
+ @Override
+ public String toString() {
+ return MoreObjects.toStringHelper(this)
+ .add("protocol", protocol)
+ .add("portRangeMax", portRangeMax)
+ .add("portRangeMin", portRangeMin)
+ .toString();
+ }
+
+ /**
+ * Returns new builder instance.
+ *
+ * @return kubevirt load balancer rule builder
+ */
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ public static final class Builder implements KubevirtLoadBalancerRule.Builder {
+
+ private String protocol;
+ private Integer portRangeMax;
+ private Integer portRangeMin;
+
+ @Override
+ public KubevirtLoadBalancerRule build() {
+ checkArgument(protocol != null, NOT_NULL_MSG, "protocol");
+ checkArgument(portRangeMax != null, NOT_NULL_MSG, "portRangeMax");
+ checkArgument(portRangeMin != null, NOT_NULL_MSG, "portRangeMin");
+
+ return new DefaultKubevirtLoadBalancerRule(protocol, portRangeMax, portRangeMin);
+ }
+
+ @Override
+ public Builder portRangeMax(Integer portRangeMax) {
+ this.portRangeMax = portRangeMax;
+ return this;
+ }
+
+ @Override
+ public Builder portRangeMin(Integer portRangeMin) {
+ this.portRangeMin = portRangeMin;
+ return this;
+ }
+
+ @Override
+ public Builder protocol(String protocol) {
+ this.protocol = protocol;
+ return this;
+ }
+ }
+}
diff --git a/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtLoadBalancer.java b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtLoadBalancer.java
new file mode 100644
index 0000000..7547547
--- /dev/null
+++ b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtLoadBalancer.java
@@ -0,0 +1,128 @@
+/*
+ * 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 org.onlab.packet.IpAddress;
+
+import java.util.Set;
+
+/**
+ * Representation of load balancer.
+ */
+public interface KubevirtLoadBalancer {
+
+ /**
+ * Returns the load balancer name.
+ *
+ * @return load balancer name
+ */
+ String name();
+
+ /**
+ * Returns the load balancer description.
+ *
+ * @return load balancer description
+ */
+ String description();
+
+ /**
+ * Returns the network identifier.
+ *
+ * @return network identifier
+ */
+ String networkId();
+
+ /**
+ * Returns the load balancer virtual IP address.
+ *
+ * @return load balancer virtual IP address
+ */
+ IpAddress vip();
+
+ /**
+ * Returns the IP address of members.
+ *
+ * @return IP addresses
+ */
+ Set<IpAddress> members();
+
+ /**
+ * Returns the load balancer rules.
+ *
+ * @return load balancer rules
+ */
+ Set<KubevirtLoadBalancerRule> rules();
+
+ /**
+ * A default builder interface.
+ */
+ interface Builder {
+ /**
+ * Builds an immutable load balancer instance.
+ *
+ * @return kubevirt load balancer
+ */
+ KubevirtLoadBalancer build();
+
+ /**
+ * Returns kubevirt load balancer builder with supplied load balancer name.
+ *
+ * @param name load balancer name
+ * @return load balancer builder
+ */
+ Builder name(String name);
+
+ /**
+ * Returns kubevirt load balancer builder with supplied load balancer description.
+ *
+ * @param description load balancer description
+ * @return load balancer builder
+ */
+ Builder description(String description);
+
+ /**
+ * Returns kubevirt load balancer builder with supplied load balancer network identifier.
+ *
+ * @param networkId load balancer network identifier
+ * @return load balancer builder
+ */
+ Builder networkId(String networkId);
+
+ /**
+ * Returns kubevirt load balancer builder with supplied load balancer vip.
+ *
+ * @param vip load balancer vip
+ * @return load balancer builder
+ */
+ Builder vip(IpAddress vip);
+
+ /**
+ * Returns kubevirt load balancer builder with supplied load balancer members.
+ *
+ * @param members load balancer members
+ * @return load balancer builder
+ */
+ Builder members(Set<IpAddress> members);
+
+ /**
+ * Returns kubevirt load balancer builder with supplied load balancer rules.
+ *
+ * @param rules load balancer rules
+ * @return load balancer builder
+ */
+ Builder rules(Set<KubevirtLoadBalancerRule> rules);
+ }
+}
diff --git a/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtLoadBalancerAdminService.java b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtLoadBalancerAdminService.java
new file mode 100644
index 0000000..a81adb8
--- /dev/null
+++ b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtLoadBalancerAdminService.java
@@ -0,0 +1,48 @@
+/*
+ * 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;
+
+/**
+ * Service for administering the inventory of kubevirt load balancer service.
+ */
+public interface KubevirtLoadBalancerAdminService extends KubevirtLoadBalancerService {
+
+ /**
+ * Create a kubevirt load balancer with the given information.
+ *
+ * @param lb a new load balancer
+ */
+ void createLoadBalancer(KubevirtLoadBalancer lb);
+
+ /**
+ * Updates the kubevirt load balancer with the given information.
+ *
+ * @param lb the updated load balancer
+ */
+ void updateLoadBalancer(KubevirtLoadBalancer lb);
+
+ /**
+ * Removes the load balancer.
+ *
+ * @param name load balancer name
+ */
+ void removeLoadBalancer(String name);
+
+ /**
+ * Removes all load balancers.
+ */
+ void clear();
+}
diff --git a/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtLoadBalancerEvent.java b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtLoadBalancerEvent.java
new file mode 100644
index 0000000..ad09091
--- /dev/null
+++ b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtLoadBalancerEvent.java
@@ -0,0 +1,49 @@
+/*
+ * 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 org.onosproject.event.AbstractEvent;
+
+public class KubevirtLoadBalancerEvent
+ extends AbstractEvent<KubevirtLoadBalancerEvent.Type, KubevirtLoadBalancer> {
+
+ /**
+ * LoadBalancerEvent constructor.
+ *
+ * @param type LoadBalancerEvent type
+ * @param lb LoadBalancer object
+ */
+ public KubevirtLoadBalancerEvent(Type type, KubevirtLoadBalancer lb) {
+ super(type, lb);
+ }
+
+ public enum Type {
+ /**
+ * Signifies that a new kubevirt load balancer is created.
+ */
+ KUBEVIRT_LOAD_BALANCER_CREATED,
+
+ /**
+ * Signifies that a new kubevirt load balancer is removed.
+ */
+ KUBEVIRT_LOAD_BALANCER_REMOVED,
+
+ /**
+ * Signifies that a new kubevirt load balancer is updated.
+ */
+ KUBEVIRT_LOAD_BALANCER_UPDATED,
+ }
+}
diff --git a/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtLoadBalancerListener.java b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtLoadBalancerListener.java
new file mode 100644
index 0000000..2711831
--- /dev/null
+++ b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtLoadBalancerListener.java
@@ -0,0 +1,24 @@
+/*
+ * 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 org.onosproject.event.EventListener;
+
+/**
+ * Listener for kubevirt load balancer event.
+ */
+public interface KubevirtLoadBalancerListener extends EventListener<KubevirtLoadBalancerEvent> {
+}
diff --git a/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtLoadBalancerRule.java b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtLoadBalancerRule.java
new file mode 100644
index 0000000..665024a
--- /dev/null
+++ b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtLoadBalancerRule.java
@@ -0,0 +1,80 @@
+/*
+ * 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;
+
+/**
+ * Representation of load balancer rule.
+ */
+public interface KubevirtLoadBalancerRule {
+
+ /**
+ * Returns the maximum port range.
+ *
+ * @return maximum port range
+ */
+ Integer portRangeMax();
+
+ /**
+ * Returns the minimum port range.
+ *
+ * @return minimum port range
+ */
+ Integer portRangeMin();
+
+ /**
+ * Returns the network protocol.
+ *
+ * @return network protocol
+ */
+ String protocol();
+
+ /**
+ * A default builder interface.
+ */
+ interface Builder {
+ /**
+ * Builds an immutable load balancer rule instance.
+ *
+ * @return kubevirt load balancer rule
+ */
+ KubevirtLoadBalancerRule build();
+
+ /**
+ * Returns kubevirt load balancer rule builder with supplied maximum port range.
+ *
+ * @param portRangeMax maximum port range
+ * @return balancer rule rule builder
+ */
+ Builder portRangeMax(Integer portRangeMax);
+
+ /**
+ * Returns kubevirt load balancer rule builder with supplied minimum port range.
+ *
+ * @param portRangeMin minimum port range
+ * @return balancer rule rule builder
+ */
+ Builder portRangeMin(Integer portRangeMin);
+
+ /**
+ * Returns kubevirt load balancer rule builder with supplied protocol.
+ *
+ * @param protocol network protocol
+ * @return balancer rule rule builder
+ */
+ Builder protocol(String protocol);
+
+ }
+}
diff --git a/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtLoadBalancerService.java b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtLoadBalancerService.java
new file mode 100644
index 0000000..732bb91a
--- /dev/null
+++ b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtLoadBalancerService.java
@@ -0,0 +1,42 @@
+/*
+ * 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 org.onosproject.event.ListenerService;
+
+import java.util.Set;
+
+/**
+ * Service for interacting with the inventory of kubevirt load balancer.
+ */
+public interface KubevirtLoadBalancerService
+ extends ListenerService<KubevirtLoadBalancerEvent, KubevirtLoadBalancerListener> {
+
+ /**
+ * Returns the kubevirt load balancer with the supplied load balancer name.
+ *
+ * @param name load balancer name
+ * @return kubevirt load balancer
+ */
+ KubevirtLoadBalancer loadBalancer(String name);
+
+ /**
+ * Returns all kubevirt load balancers registered in the service.
+ *
+ * @return set of kubevirt load balancers
+ */
+ Set<KubevirtLoadBalancer> loadBalancers();
+}
diff --git a/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtLoadBalancerStore.java b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtLoadBalancerStore.java
new file mode 100644
index 0000000..b6a2021
--- /dev/null
+++ b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtLoadBalancerStore.java
@@ -0,0 +1,69 @@
+/*
+ * 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 org.onosproject.store.Store;
+
+import java.util.Set;
+
+/**
+ * Manages inventory of kubevirt load balancer states; not intended for direct use.
+ */
+public interface KubevirtLoadBalancerStore
+ extends Store<KubevirtLoadBalancerEvent, KubevirtLoadBalancerStoreDelegate> {
+
+ /**
+ * Creates a new kubevirt load balancer.
+ *
+ * @param lb kubevirt load balancer
+ */
+ void createLoadBalancer(KubevirtLoadBalancer lb);
+
+ /**
+ * Updates the kubevirt load balancer.
+ *
+ * @param lb kubevirt load balancer
+ */
+ void updateLoadBalancer(KubevirtLoadBalancer lb);
+
+ /**
+ * Removes the kubevirt load balancer with the given load balancer name.
+ *
+ * @param name load balancer name
+ * @return remove kubevirt load balancer; null if failed
+ */
+ KubevirtLoadBalancer removeLoadBalancer(String name);
+
+ /**
+ * Returns the kubevirt load balancer with the given load balancer name.
+ *
+ * @param name load balancer name
+ * @return load balancer; null if failed
+ */
+ KubevirtLoadBalancer loadBalancer(String name);
+
+ /**
+ * Returns all kubevirt load balancers.
+ *
+ * @return set of kubevirt load balancers
+ */
+ Set<KubevirtLoadBalancer> loadBalancers();
+
+ /**
+ * Removes all kubevirt load balancers.
+ */
+ void clear();
+}
diff --git a/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtLoadBalancerStoreDelegate.java b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtLoadBalancerStoreDelegate.java
new file mode 100644
index 0000000..f5e8370
--- /dev/null
+++ b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtLoadBalancerStoreDelegate.java
@@ -0,0 +1,24 @@
+/*
+ * 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 org.onosproject.store.StoreDelegate;
+
+/**
+ * Kubevirt load balancer store delegate abstraction.
+ */
+public interface KubevirtLoadBalancerStoreDelegate extends StoreDelegate<KubevirtLoadBalancerEvent> {
+}
diff --git a/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtRouterStore.java b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtRouterStore.java
index 7313aa9..ff25a02 100644
--- a/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtRouterStore.java
+++ b/apps/kubevirt-networking/api/src/main/java/org/onosproject/kubevirtnetworking/api/KubevirtRouterStore.java
@@ -51,7 +51,7 @@
* Returns the kubevirt router with the given router name.
*
* @param name router name
- * @return removed kubevirt router; null if failed
+ * @return kubevirt router; null if failed
*/
KubevirtRouter router(String name);
diff --git a/apps/kubevirt-networking/api/src/test/java/org/onosproject/kubevirtnetworking/api/DefaultKubevirtLoadBalancerTest.java b/apps/kubevirt-networking/api/src/test/java/org/onosproject/kubevirtnetworking/api/DefaultKubevirtLoadBalancerTest.java
new file mode 100644
index 0000000..e9ec471
--- /dev/null
+++ b/apps/kubevirt-networking/api/src/test/java/org/onosproject/kubevirtnetworking/api/DefaultKubevirtLoadBalancerTest.java
@@ -0,0 +1,138 @@
+/*
+ * 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.google.common.collect.ImmutableSet;
+import com.google.common.testing.EqualsTester;
+import org.junit.Before;
+import org.junit.Test;
+import org.onlab.packet.IpAddress;
+
+import java.util.Set;
+
+import static junit.framework.TestCase.assertEquals;
+import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable;
+
+/**
+ * Unit tests for the default kubevirt load balancer class.
+ */
+public class DefaultKubevirtLoadBalancerTest {
+
+ private static final String NAME_1 = "lb-1";
+ private static final String NAME_2 = "lb-2";
+ private static final String DESCRIPTION_1 = "dummy lb 1";
+ private static final String DESCRIPTION_2 = "dummy lb 2";
+ private static final String NETWORK_ID_1 = "net-1";
+ private static final String NETWORK_ID_2 = "net-2";
+ private static final IpAddress VIP_1 = IpAddress.valueOf("10.10.10.10");
+ private static final IpAddress VIP_2 = IpAddress.valueOf("20.20.20.20");
+ private static final Integer PORT_RANGE_MAX_1 = 80;
+ private static final Integer PORT_RANGE_MAX_2 = 8080;
+ private static final Integer PORT_RANGE_MIN_1 = 80;
+ private static final Integer PORT_RANGE_MIN_2 = 8080;
+ private static final String PROTOCOL_1 = "tcp";
+ private static final String PROTOCOL_2 = "udp";
+ private static final Set<IpAddress> MEMBERS_1 =
+ ImmutableSet.of(IpAddress.valueOf("10.10.10.11"),
+ IpAddress.valueOf("10.10.10.12"));
+ private static final Set<IpAddress> MEMBERS_2 =
+ ImmutableSet.of(IpAddress.valueOf("20.20.20.21"),
+ IpAddress.valueOf("20.20.20.22"));
+ private static final KubevirtLoadBalancerRule RULE_1 =
+ DefaultKubevirtLoadBalancerRule.builder()
+ .protocol(PROTOCOL_1)
+ .portRangeMax(PORT_RANGE_MAX_1)
+ .portRangeMin(PORT_RANGE_MIN_1)
+ .build();
+ private static final KubevirtLoadBalancerRule RULE_2 =
+ DefaultKubevirtLoadBalancerRule.builder()
+ .protocol(PROTOCOL_2)
+ .portRangeMax(PORT_RANGE_MAX_2)
+ .portRangeMin(PORT_RANGE_MIN_2)
+ .build();
+ private static final Set<KubevirtLoadBalancerRule> RULES_1 = ImmutableSet.of(RULE_1);
+ private static final Set<KubevirtLoadBalancerRule> RULES_2 = ImmutableSet.of(RULE_2);
+
+ private KubevirtLoadBalancer lb1;
+ private KubevirtLoadBalancer sameAsLb1;
+ private KubevirtLoadBalancer lb2;
+
+ /**
+ * Tests class immutability.
+ */
+ @Test
+ public void testImmutability() {
+ assertThatClassIsImmutable(DefaultKubevirtLoadBalancer.class);
+ }
+
+ /**
+ * Initial setup for this unit test.
+ */
+ @Before
+ public void setUp() {
+ lb1 = DefaultKubevirtLoadBalancer.builder()
+ .name(NAME_1)
+ .description(DESCRIPTION_1)
+ .networkId(NETWORK_ID_1)
+ .vip(VIP_1)
+ .members(MEMBERS_1)
+ .rules(RULES_1)
+ .build();
+
+ sameAsLb1 = DefaultKubevirtLoadBalancer.builder()
+ .name(NAME_1)
+ .description(DESCRIPTION_1)
+ .networkId(NETWORK_ID_1)
+ .vip(VIP_1)
+ .members(MEMBERS_1)
+ .rules(RULES_1)
+ .build();
+
+ lb2 = DefaultKubevirtLoadBalancer.builder()
+ .name(NAME_2)
+ .description(DESCRIPTION_2)
+ .networkId(NETWORK_ID_2)
+ .vip(VIP_2)
+ .members(MEMBERS_2)
+ .rules(RULES_2)
+ .build();
+ }
+
+ /**
+ * Tests object equality.
+ */
+ @Test
+ public void testEquality() {
+ new EqualsTester().addEqualityGroup(lb1, sameAsLb1)
+ .addEqualityGroup(lb2)
+ .testEquals();
+ }
+
+ /**
+ * Test object construction.
+ */
+ @Test
+ public void testConstruction() {
+ KubevirtLoadBalancer lb = lb1;
+
+ assertEquals(NAME_1, lb.name());
+ assertEquals(DESCRIPTION_1, lb.description());
+ assertEquals(NETWORK_ID_1, lb.networkId());
+ assertEquals(VIP_1, lb.vip());
+ assertEquals(MEMBERS_1, lb.members());
+ assertEquals(RULES_1, lb.rules());
+ }
+}
diff --git a/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/cli/KubevirtListLoadBalancerCommand.java b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/cli/KubevirtListLoadBalancerCommand.java
new file mode 100644
index 0000000..94bf069
--- /dev/null
+++ b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/cli/KubevirtListLoadBalancerCommand.java
@@ -0,0 +1,83 @@
+/*
+ * 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.KubevirtLoadBalancer;
+import org.onosproject.kubevirtnetworking.api.KubevirtLoadBalancerService;
+
+import java.util.Comparator;
+import java.util.List;
+
+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;
+
+/**
+ * Lists kubevirt load balancers.
+ */
+@Service
+@Command(scope = "onos", name = "kubevirt-lbs",
+ description = "Lists all kubevirt load balancers")
+public class KubevirtListLoadBalancerCommand extends AbstractShellCommand {
+ @Override
+ protected void doExecute() throws Exception {
+ KubevirtLoadBalancerService service = get(KubevirtLoadBalancerService.class);
+ List<KubevirtLoadBalancer> lbs = Lists.newArrayList(service.loadBalancers());
+ lbs.sort(Comparator.comparing(KubevirtLoadBalancer::name));
+
+ String format = genFormatString(ImmutableList.of(CLI_NAME_LENGTH, CLI_NAME_LENGTH,
+ CLI_IP_ADDRESS_LENGTH, CLI_IP_ADDRESSES_LENGTH));
+
+ if (outputJson()) {
+ print("%s", json(lbs));
+ } else {
+ print(format, "Name", "NetworkId", "Virtual IP", "Members");
+
+ for (KubevirtLoadBalancer lb : lbs) {
+ print(format,
+ StringUtils.substring(lb.name(),
+ 0, CLI_NAME_LENGTH - CLI_MARGIN_LENGTH),
+ StringUtils.substring(lb.networkId(),
+ 0, CLI_NAME_LENGTH - CLI_MARGIN_LENGTH),
+ StringUtils.substring(lb.vip().toString(),
+ 0, CLI_IP_ADDRESS_LENGTH - CLI_MARGIN_LENGTH),
+ lb.members().toString());
+ }
+ }
+ }
+
+ private String json(List<KubevirtLoadBalancer> lbs) {
+ ObjectMapper mapper = new ObjectMapper();
+ ArrayNode result = mapper.createArrayNode();
+
+ for (KubevirtLoadBalancer lb : lbs) {
+ result.add(jsonForEntity(lb, KubevirtLoadBalancer.class));
+ }
+
+ return prettyJson(mapper, result.toString());
+ }
+}
diff --git a/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/codec/KubevirtLoadBalancerCodec.java b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/codec/KubevirtLoadBalancerCodec.java
new file mode 100644
index 0000000..c11d829
--- /dev/null
+++ b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/codec/KubevirtLoadBalancerCodec.java
@@ -0,0 +1,130 @@
+/*
+ * 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.onlab.packet.IpAddress;
+import org.onosproject.codec.CodecContext;
+import org.onosproject.codec.JsonCodec;
+import org.onosproject.kubevirtnetworking.api.DefaultKubevirtLoadBalancer;
+import org.onosproject.kubevirtnetworking.api.KubevirtLoadBalancer;
+import org.onosproject.kubevirtnetworking.api.KubevirtLoadBalancerRule;
+import org.slf4j.Logger;
+
+import java.util.HashSet;
+import java.util.Set;
+import java.util.stream.IntStream;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+import static org.onlab.util.Tools.nullIsIllegal;
+import static org.slf4j.LoggerFactory.getLogger;
+
+public final class KubevirtLoadBalancerCodec extends JsonCodec<KubevirtLoadBalancer> {
+
+ private final Logger log = getLogger(getClass());
+
+ private static final String NAME = "name";
+ private static final String DESCRIPTION = "description";
+ private static final String VIP = "vip";
+ private static final String NETWORK_ID = "networkId";
+ private static final String MEMBERS = "members";
+ private static final String RULES = "rules";
+
+ private static final String MISSING_MESSAGE = " is required in KubevirtLoadBalancer";
+
+ @Override
+ public ObjectNode encode(KubevirtLoadBalancer lb, CodecContext context) {
+ checkNotNull(lb, "Kubevirt load balancer cannot be null");
+
+ ObjectNode result = context.mapper().createObjectNode()
+ .put(NAME, lb.name())
+ .put(VIP, lb.vip().toString())
+ .put(NETWORK_ID, lb.networkId());
+
+ if (lb.description() != null) {
+ result.put(DESCRIPTION, lb.description());
+ }
+
+ if (lb.members() != null && !lb.members().isEmpty()) {
+ ArrayNode members = context.mapper().createArrayNode();
+ for (IpAddress ip : lb.members()) {
+ members.add(ip.toString());
+ }
+ result.set(MEMBERS, members);
+ }
+
+ if (lb.rules() != null && !lb.rules().isEmpty()) {
+ ArrayNode rules = context.mapper().createArrayNode();
+ for (KubevirtLoadBalancerRule rule : lb.rules()) {
+ ObjectNode ruleJson = context.codec(
+ KubevirtLoadBalancerRule.class).encode(rule, context);
+ rules.add(ruleJson);
+ }
+ result.set(RULES, rules);
+ }
+
+ return result;
+ }
+
+ @Override
+ public KubevirtLoadBalancer decode(ObjectNode json, CodecContext context) {
+ if (json == null || !json.isObject()) {
+ return null;
+ }
+
+ String name = nullIsIllegal(json.get(NAME).asText(), NAME + MISSING_MESSAGE);
+ IpAddress vip = IpAddress.valueOf(nullIsIllegal(json.get(VIP).asText(),
+ VIP + MISSING_MESSAGE));
+ String networkId = nullIsIllegal(json.get(NETWORK_ID).asText(),
+ NETWORK_ID + MISSING_MESSAGE);
+
+ KubevirtLoadBalancer.Builder builder = DefaultKubevirtLoadBalancer.builder()
+ .name(name)
+ .vip(vip)
+ .networkId(networkId);
+
+ JsonNode description = json.get(DESCRIPTION);
+ if (description != null) {
+ builder.description(description.asText());
+ }
+
+ ArrayNode membersJson = (ArrayNode) json.get(MEMBERS);
+ if (membersJson != null) {
+ Set<IpAddress> members = new HashSet<>();
+ for (JsonNode memberJson : membersJson) {
+ members.add(IpAddress.valueOf(memberJson.asText()));
+ }
+ builder.members(members);
+ }
+
+ JsonNode rulesJson = json.get(RULES);
+ if (rulesJson != null) {
+ Set<KubevirtLoadBalancerRule> rules = new HashSet<>();
+ IntStream.range(0, rulesJson.size())
+ .forEach(i -> {
+ ObjectNode ruleJson = get(rulesJson, i);
+ KubevirtLoadBalancerRule rule = context.codec(
+ KubevirtLoadBalancerRule.class).decode(ruleJson, context);
+ rules.add(rule);
+ });
+ builder.rules(rules);
+ }
+
+ return builder.build();
+ }
+}
diff --git a/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/codec/KubevirtLoadBalancerRuleCodec.java b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/codec/KubevirtLoadBalancerRuleCodec.java
new file mode 100644
index 0000000..8977284
--- /dev/null
+++ b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/codec/KubevirtLoadBalancerRuleCodec.java
@@ -0,0 +1,68 @@
+/*
+ * 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.node.ObjectNode;
+import org.onosproject.codec.CodecContext;
+import org.onosproject.codec.JsonCodec;
+import org.onosproject.kubevirtnetworking.api.DefaultKubevirtLoadBalancerRule;
+import org.onosproject.kubevirtnetworking.api.KubevirtLoadBalancerRule;
+import org.slf4j.Logger;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+import static org.onlab.util.Tools.nullIsIllegal;
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Kubevirt load balancer rule codec used for serializing and de-serializing JSON string.
+ */
+public final class KubevirtLoadBalancerRuleCodec extends JsonCodec<KubevirtLoadBalancerRule> {
+
+ private final Logger log = getLogger(getClass());
+
+ private static final String PROTOCOL = "protocol";
+ private static final String PORT_RANGE_MAX = "portRangeMax";
+ private static final String PORT_RANGE_MIN = "portRangeMin";
+
+ private static final String MISSING_MESSAGE = " is required in KubevirtLoadBalancerRule";
+
+ @Override
+ public ObjectNode encode(KubevirtLoadBalancerRule rule, CodecContext context) {
+ checkNotNull(rule, "Kubevirt load balancer rule cannot be null");
+
+ return context.mapper().createObjectNode()
+ .put(PROTOCOL, rule.protocol())
+ .put(PORT_RANGE_MAX, rule.portRangeMax())
+ .put(PORT_RANGE_MIN, rule.portRangeMin());
+ }
+
+ @Override
+ public KubevirtLoadBalancerRule decode(ObjectNode json, CodecContext context) {
+ if (json == null || !json.isObject()) {
+ return null;
+ }
+
+ String protocol = nullIsIllegal(json.get(PROTOCOL).asText(), PROTOCOL + MISSING_MESSAGE);
+ Integer portRangeMax = json.get(PORT_RANGE_MAX).asInt();
+ Integer portRangeMin = json.get(PORT_RANGE_MIN).asInt();
+
+ return DefaultKubevirtLoadBalancerRule.builder()
+ .protocol(protocol)
+ .portRangeMax(portRangeMax)
+ .portRangeMin(portRangeMin)
+ .build();
+ }
+}
diff --git a/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/impl/DistributedKubevirtLoadBalancerStore.java b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/impl/DistributedKubevirtLoadBalancerStore.java
new file mode 100644
index 0000000..fd90e8a
--- /dev/null
+++ b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/impl/DistributedKubevirtLoadBalancerStore.java
@@ -0,0 +1,187 @@
+/*
+ * 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.DefaultKubevirtLoadBalancer;
+import org.onosproject.kubevirtnetworking.api.DefaultKubevirtLoadBalancerRule;
+import org.onosproject.kubevirtnetworking.api.KubevirtLoadBalancer;
+import org.onosproject.kubevirtnetworking.api.KubevirtLoadBalancerEvent;
+import org.onosproject.kubevirtnetworking.api.KubevirtLoadBalancerRule;
+import org.onosproject.kubevirtnetworking.api.KubevirtLoadBalancerStore;
+import org.onosproject.kubevirtnetworking.api.KubevirtLoadBalancerStoreDelegate;
+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.KubevirtLoadBalancerEvent.Type.KUBEVIRT_LOAD_BALANCER_CREATED;
+import static org.onosproject.kubevirtnetworking.api.KubevirtLoadBalancerEvent.Type.KUBEVIRT_LOAD_BALANCER_REMOVED;
+import static org.onosproject.kubevirtnetworking.api.KubevirtLoadBalancerEvent.Type.KUBEVIRT_LOAD_BALANCER_UPDATED;
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Implementation of kubevirt load balancer store using consistent map.
+ */
+@Component(immediate = true, service = KubevirtLoadBalancerStore.class)
+public class DistributedKubevirtLoadBalancerStore
+ extends AbstractStore<KubevirtLoadBalancerEvent, KubevirtLoadBalancerStoreDelegate>
+ implements KubevirtLoadBalancerStore {
+
+ 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_LOAD_BALANCER = KryoNamespace.newBuilder()
+ .register(KryoNamespaces.API)
+ .register(KubevirtLoadBalancer.class)
+ .register(DefaultKubevirtLoadBalancer.class)
+ .register(KubevirtLoadBalancerRule.class)
+ .register(DefaultKubevirtLoadBalancerRule.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, KubevirtLoadBalancer> loadBalancerMapListener =
+ new KubevirtLoadBalancerMapListener();
+
+ private ConsistentMap<String, KubevirtLoadBalancer> loadBalancerStore;
+
+ @Activate
+ protected void activate() {
+ ApplicationId appId = coreService.registerApplication(APP_ID);
+ loadBalancerStore = storageService.<String, KubevirtLoadBalancer>consistentMapBuilder()
+ .withSerializer(Serializer.using(SERIALIZER_KUBEVIRT_LOAD_BALANCER))
+ .withName("kubevirt-loadbalancerstore")
+ .withApplicationId(appId)
+ .build();
+ loadBalancerStore.addListener(loadBalancerMapListener);
+ log.info("Started");
+ }
+
+ @Deactivate
+ protected void deactivate() {
+ loadBalancerStore.removeListener(loadBalancerMapListener);
+ eventExecutor.shutdown();
+ log.info("Stopped");
+ }
+
+ @Override
+ public void createLoadBalancer(KubevirtLoadBalancer lb) {
+ loadBalancerStore.compute(lb.name(), (name, existing) -> {
+ final String error = lb.name() + ERR_DUPLICATE;
+ checkArgument(existing == null, error);
+ return lb;
+ });
+ }
+
+ @Override
+ public void updateLoadBalancer(KubevirtLoadBalancer lb) {
+ loadBalancerStore.compute(lb.name(), (name, existing) -> {
+ final String error = lb.name() + ERR_NOT_FOUND;
+ checkArgument(existing != null, error);
+ return lb;
+ });
+ }
+
+ @Override
+ public KubevirtLoadBalancer removeLoadBalancer(String name) {
+ Versioned<KubevirtLoadBalancer> lb = loadBalancerStore.remove(name);
+ if (lb == null) {
+ final String error = name + ERR_NOT_FOUND;
+ throw new IllegalArgumentException(error);
+ }
+ return lb.value();
+ }
+
+ @Override
+ public KubevirtLoadBalancer loadBalancer(String name) {
+ return loadBalancerStore.asJavaMap().get(name);
+ }
+
+ @Override
+ public Set<KubevirtLoadBalancer> loadBalancers() {
+ return ImmutableSet.copyOf(loadBalancerStore.asJavaMap().values());
+ }
+
+ @Override
+ public void clear() {
+ loadBalancerStore.clear();
+ }
+
+ private class KubevirtLoadBalancerMapListener
+ implements MapEventListener<String, KubevirtLoadBalancer> {
+
+ @Override
+ public void event(MapEvent<String, KubevirtLoadBalancer> event) {
+ switch (event.type()) {
+ case INSERT:
+ log.debug("Kubevirt load balancer created");
+ eventExecutor.execute(() ->
+ notifyDelegate(new KubevirtLoadBalancerEvent(
+ KUBEVIRT_LOAD_BALANCER_CREATED, event.newValue().value())));
+ break;
+ case UPDATE:
+ log.debug("Kubevirt load balancer updated");
+ eventExecutor.execute(() ->
+ notifyDelegate(new KubevirtLoadBalancerEvent(
+ KUBEVIRT_LOAD_BALANCER_UPDATED, event.newValue().value())));
+ break;
+ case REMOVE:
+ log.debug("Kubevirt load balancer removed");
+ eventExecutor.execute(() ->
+ notifyDelegate(new KubevirtLoadBalancerEvent(
+ KUBEVIRT_LOAD_BALANCER_REMOVED, event.oldValue().value())));
+ break;
+ default:
+ // do nothing
+ break;
+ }
+ }
+ }
+}
diff --git a/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/impl/KubevirtLoadBalancerManager.java b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/impl/KubevirtLoadBalancerManager.java
new file mode 100644
index 0000000..624dd68
--- /dev/null
+++ b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/impl/KubevirtLoadBalancerManager.java
@@ -0,0 +1,154 @@
+/*
+ * 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.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.event.ListenerRegistry;
+import org.onosproject.kubevirtnetworking.api.KubevirtLoadBalancer;
+import org.onosproject.kubevirtnetworking.api.KubevirtLoadBalancerAdminService;
+import org.onosproject.kubevirtnetworking.api.KubevirtLoadBalancerEvent;
+import org.onosproject.kubevirtnetworking.api.KubevirtLoadBalancerListener;
+import org.onosproject.kubevirtnetworking.api.KubevirtLoadBalancerService;
+import org.onosproject.kubevirtnetworking.api.KubevirtLoadBalancerStore;
+import org.onosproject.kubevirtnetworking.api.KubevirtLoadBalancerStoreDelegate;
+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 load balancer.
+ */
+@Component(
+ immediate = true,
+ service = {KubevirtLoadBalancerAdminService.class, KubevirtLoadBalancerService.class}
+)
+public class KubevirtLoadBalancerManager
+ extends ListenerRegistry<KubevirtLoadBalancerEvent, KubevirtLoadBalancerListener>
+ implements KubevirtLoadBalancerAdminService, KubevirtLoadBalancerService {
+
+ protected final Logger log = getLogger(getClass());
+
+ private static final String MSG_LOAD_BALANCER = "Kubevirt load balancer %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_LOAD_BALANCER = "Kubevirt load balancer cannot be null";
+ private static final String ERR_NULL_LOAD_BALANCER_NAME = "Kubevirt load balancer 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 KubevirtLoadBalancerStore kubevirtLoadBalancerStore;
+
+ private final InternalKubevirtLoadBalancerStorageDelegate delegate =
+ new InternalKubevirtLoadBalancerStorageDelegate();
+
+ private ApplicationId appId;
+
+ @Activate
+ protected void activate() {
+ appId = coreService.registerApplication(KUBEVIRT_NETWORKING_APP_ID);
+
+ kubevirtLoadBalancerStore.setDelegate(delegate);
+ log.info("Started");
+ }
+
+ @Deactivate
+ protected void deactivate() {
+ kubevirtLoadBalancerStore.unsetDelegate(delegate);
+ log.info("Stopped");
+ }
+
+ @Override
+ public void createLoadBalancer(KubevirtLoadBalancer lb) {
+ checkNotNull(lb, ERR_NULL_LOAD_BALANCER);
+ checkArgument(!Strings.isNullOrEmpty(lb.name()), ERR_NULL_LOAD_BALANCER_NAME);
+
+ kubevirtLoadBalancerStore.createLoadBalancer(lb);
+ log.info(String.format(MSG_LOAD_BALANCER, lb.name(), MSG_CREATED));
+ }
+
+ @Override
+ public void updateLoadBalancer(KubevirtLoadBalancer lb) {
+ checkNotNull(lb, ERR_NULL_LOAD_BALANCER);
+ checkArgument(!Strings.isNullOrEmpty(lb.name()), ERR_NULL_LOAD_BALANCER_NAME);
+
+ kubevirtLoadBalancerStore.updateLoadBalancer(lb);
+ log.info(String.format(MSG_LOAD_BALANCER, lb.name(), MSG_UPDATED));
+ }
+
+ @Override
+ public void removeLoadBalancer(String name) {
+ checkArgument(name != null, ERR_NULL_LOAD_BALANCER_NAME);
+ synchronized (this) {
+ if (isLoadBalancerInUse(name)) {
+ final String error = String.format(MSG_LOAD_BALANCER, name, ERR_IN_USE);
+ throw new IllegalStateException(error);
+ }
+ }
+
+ KubevirtLoadBalancer lb = kubevirtLoadBalancerStore.removeLoadBalancer(name);
+ if (lb != null) {
+ log.info(String.format(MSG_LOAD_BALANCER, lb.name(), MSG_REMOVED));
+ }
+ }
+
+ @Override
+ public void clear() {
+ kubevirtLoadBalancerStore.clear();
+ }
+
+ @Override
+ public KubevirtLoadBalancer loadBalancer(String name) {
+ checkArgument(name != null, ERR_NULL_LOAD_BALANCER_NAME);
+ return kubevirtLoadBalancerStore.loadBalancer(name);
+ }
+
+ @Override
+ public Set<KubevirtLoadBalancer> loadBalancers() {
+ return ImmutableSet.copyOf(kubevirtLoadBalancerStore.loadBalancers());
+ }
+
+ private boolean isLoadBalancerInUse(String name) {
+ return false;
+ }
+
+ private class InternalKubevirtLoadBalancerStorageDelegate
+ implements KubevirtLoadBalancerStoreDelegate {
+
+ @Override
+ public void notify(KubevirtLoadBalancerEvent event) {
+ log.trace("send kubevirt load balancer event {}", event);
+ process(event);
+ }
+ }
+}
diff --git a/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/impl/KubevirtLoadBalancerWatcher.java b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/impl/KubevirtLoadBalancerWatcher.java
new file mode 100644
index 0000000..5b0dd75
--- /dev/null
+++ b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/impl/KubevirtLoadBalancerWatcher.java
@@ -0,0 +1,257 @@
+/*
+ * 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.KubevirtLoadBalancer;
+import org.onosproject.kubevirtnetworking.api.KubevirtLoadBalancerAdminService;
+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 load balancer watcher used for feeding kubevirt load balancer information.
+ */
+@Component(immediate = true)
+public class KubevirtLoadBalancerWatcher 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 KubevirtLoadBalancerAdminService adminService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY)
+ protected KubevirtApiConfigService configService;
+
+ private final ExecutorService eventExecutor = newSingleThreadExecutor(
+ groupedThreads(this.getClass().getSimpleName(), "event-handler"));
+
+ private final InternalLoadBalancerWatcher watcher = new InternalLoadBalancerWatcher();
+ private final InternalKubevirtApiConfigListener
+ configListener = new InternalKubevirtApiConfigListener();
+
+ CustomResourceDefinitionContext lbCrdCxt = new CustomResourceDefinitionContext
+ .Builder()
+ .withGroup("kubevirt.io")
+ .withScope("Cluster")
+ .withVersion("v1")
+ .withPlural("loadbalancers")
+ .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(lbCrdCxt).watch(watcher);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ private KubevirtLoadBalancer parseKubevirtLoadBalancer(String resource) {
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ JsonNode json = mapper.readTree(resource);
+ ObjectNode spec = (ObjectNode) json.get("spec");
+ return codec(KubevirtLoadBalancer.class).decode(spec, this);
+ } catch (IOException e) {
+ log.error("Failed to parse kubevirt load balancer 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 InternalLoadBalancerWatcher 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 load balancer 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("Load Balancer watcher OnClose, re-instantiate the watcher...");
+
+ instantiateWatcher();
+ }
+
+ private void processAddition(String resource) {
+ if (!isMaster()) {
+ return;
+ }
+
+ String name = parseResourceName(resource);
+
+ log.trace("Process Load Balancer {} creating event from API server.",
+ name);
+
+ KubevirtLoadBalancer lb = parseKubevirtLoadBalancer(resource);
+ if (lb != null) {
+ if (adminService.loadBalancer(lb.name()) == null) {
+ adminService.createLoadBalancer(lb);
+ }
+ }
+ }
+
+ private void processModification(String resource) {
+ if (!isMaster()) {
+ return;
+ }
+
+ String name = parseResourceName(resource);
+
+ log.trace("Process Load Balancer {} updating event from API server.",
+ name);
+
+ KubevirtLoadBalancer lb = parseKubevirtLoadBalancer(resource);
+ if (lb != null) {
+ adminService.updateLoadBalancer(lb);
+ }
+ }
+
+ private void processDeletion(String resource) {
+ if (!isMaster()) {
+ return;
+ }
+
+ String name = parseResourceName(resource);
+
+ log.trace("Process Load Balancer {} removal event from API server.",
+ name);
+
+ adminService.removeLoadBalancer(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/web/KubevirtLoadBalancerWebResource.java b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/web/KubevirtLoadBalancerWebResource.java
new file mode 100644
index 0000000..8fa61a2
--- /dev/null
+++ b/apps/kubevirt-networking/app/src/main/java/org/onosproject/kubevirtnetworking/web/KubevirtLoadBalancerWebResource.java
@@ -0,0 +1,52 @@
+/*
+ * 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.KubevirtLoadBalancer;
+import org.onosproject.kubevirtnetworking.api.KubevirtLoadBalancerService;
+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 load balancer.
+ */
+@Path("loadbalancer")
+public class KubevirtLoadBalancerWebResource extends AbstractWebResource {
+
+ protected final Logger log = LoggerFactory.getLogger(getClass());
+ private static final String LOAD_BALANCERS = "loadBalancers";
+
+ /**
+ * Returns set of all load balancers.
+ *
+ * @return 200 OK with set of all load balancers
+ * @onos.rsModel KubevirtLoadBalancers
+ */
+ @GET
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response getLoadBalancers() {
+ KubevirtLoadBalancerService service = get(KubevirtLoadBalancerService.class);
+ final Iterable<KubevirtLoadBalancer> lbs = service.loadBalancers();
+ return ok(encodeArray(KubevirtLoadBalancer.class, LOAD_BALANCERS, lbs)).build();
+ }
+}
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 b8f27e3..0280c6a 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
@@ -19,6 +19,8 @@
import org.onosproject.kubevirtnetworking.api.KubevirtFloatingIp;
import org.onosproject.kubevirtnetworking.api.KubevirtHostRoute;
import org.onosproject.kubevirtnetworking.api.KubevirtIpPool;
+import org.onosproject.kubevirtnetworking.api.KubevirtLoadBalancer;
+import org.onosproject.kubevirtnetworking.api.KubevirtLoadBalancerRule;
import org.onosproject.kubevirtnetworking.api.KubevirtNetwork;
import org.onosproject.kubevirtnetworking.api.KubevirtPort;
import org.onosproject.kubevirtnetworking.api.KubevirtRouter;
@@ -27,6 +29,8 @@
import org.onosproject.kubevirtnetworking.codec.KubevirtFloatingIpCodec;
import org.onosproject.kubevirtnetworking.codec.KubevirtHostRouteCodec;
import org.onosproject.kubevirtnetworking.codec.KubevirtIpPoolCodec;
+import org.onosproject.kubevirtnetworking.codec.KubevirtLoadBalancerCodec;
+import org.onosproject.kubevirtnetworking.codec.KubevirtLoadBalancerRuleCodec;
import org.onosproject.kubevirtnetworking.codec.KubevirtNetworkCodec;
import org.onosproject.kubevirtnetworking.codec.KubevirtPortCodec;
import org.onosproject.kubevirtnetworking.codec.KubevirtRouterCodec;
@@ -63,6 +67,8 @@
codecService.registerCodec(KubevirtFloatingIp.class, new KubevirtFloatingIpCodec());
codecService.registerCodec(KubevirtSecurityGroup.class, new KubevirtSecurityGroupCodec());
codecService.registerCodec(KubevirtSecurityGroupRule.class, new KubevirtSecurityGroupRuleCodec());
+ codecService.registerCodec(KubevirtLoadBalancer.class, new KubevirtLoadBalancerCodec());
+ codecService.registerCodec(KubevirtLoadBalancerRule.class, new KubevirtLoadBalancerRuleCodec());
log.info("Started");
}
@@ -78,6 +84,8 @@
codecService.unregisterCodec(KubevirtFloatingIp.class);
codecService.unregisterCodec(KubevirtSecurityGroup.class);
codecService.unregisterCodec(KubevirtSecurityGroupRule.class);
+ codecService.unregisterCodec(KubevirtLoadBalancer.class);
+ codecService.unregisterCodec(KubevirtLoadBalancerRule.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 139b92d..45dcdae 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
@@ -30,7 +30,8 @@
KubevirtManagementWebResource.class,
KubevirtRouterWebResource.class,
KubevirtFloatingIpsWebResource.class,
- KubevirtSecurityGroupWebResource.class
+ KubevirtSecurityGroupWebResource.class,
+ KubevirtLoadBalancerWebResource.class
);
}
}
diff --git a/apps/kubevirt-networking/app/src/main/resources/definitions/KubevirtLoadBalancers.json b/apps/kubevirt-networking/app/src/main/resources/definitions/KubevirtLoadBalancers.json
new file mode 100644
index 0000000..f06aedf
--- /dev/null
+++ b/apps/kubevirt-networking/app/src/main/resources/definitions/KubevirtLoadBalancers.json
@@ -0,0 +1,94 @@
+{
+ "type": "object",
+ "title": "loadBalancers",
+ "required": [
+ "loadBalancers"
+ ],
+ "properties": {
+ "loadBalancers": {
+ "type": "array",
+ "xml": {
+ "name": "loadBalancers",
+ "wrapped": true
+ },
+ "items": {
+ "type": "object",
+ "description": "A load balancer object.",
+ "required": [
+ "name",
+ "description",
+ "networkId",
+ "vip",
+ "members",
+ "rules"
+ ],
+ "properties": {
+ "name": {
+ "type": "string",
+ "example": "lb-1",
+ "description": "The name of load balancer."
+ },
+ "description": {
+ "type": "string",
+ "example": "Example load balancer",
+ "description": "The description of load balancer."
+ },
+ "networkId": {
+ "type": "string",
+ "example": "net-1",
+ "description": "The name of network where the load balancer is attached to."
+ },
+ "vip": {
+ "type": "string",
+ "example": "10.10.10.10",
+ "description": "The virtual IP address of the load balancer."
+ },
+ "members": {
+ "type": "array",
+ "xml": {
+ "name": "members",
+ "wrapped": true
+ },
+ "items": {
+ "type": "string",
+ "example": "10.10.10.11",
+ "description": "IP address of member instance."
+ }
+ },
+ "rules": {
+ "type": "array",
+ "description": "A list of load balancer rule objects.",
+ "items": {
+ "type": "object",
+ "description": "A load balancer rule object.",
+ "required": [
+ "portRangeMax",
+ "portRangeMin",
+ "protocol"
+ ],
+ "properties": {
+ "portRangeMax": {
+ "type": "integer",
+ "format": "int32",
+ "example": 80,
+ "description": "The maximum port number in the range that is matched by the rule."
+ },
+ "portRangeMin": {
+ "type": "integer",
+ "format": "int32",
+ "example": 80,
+ "description": "The minimum port number in the range that is matched by the rule."
+ },
+ "protocol": {
+ "type": "string",
+ "example": "tcp",
+ "description": "The IP protocol can be represented by a string, an integer, or null."
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/apps/kubevirt-networking/app/src/test/java/org/onosproject/kubevirtnetworking/codec/KubevirtLoadBalancerCodecTest.java b/apps/kubevirt-networking/app/src/test/java/org/onosproject/kubevirtnetworking/codec/KubevirtLoadBalancerCodecTest.java
new file mode 100644
index 0000000..7aed6f8
--- /dev/null
+++ b/apps/kubevirt-networking/app/src/test/java/org/onosproject/kubevirtnetworking/codec/KubevirtLoadBalancerCodecTest.java
@@ -0,0 +1,177 @@
+/*
+ * 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.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+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.onosproject.codec.CodecContext;
+import org.onosproject.codec.JsonCodec;
+import org.onosproject.codec.impl.CodecManager;
+import org.onosproject.core.CoreService;
+import org.onosproject.kubevirtnetworking.api.DefaultKubevirtLoadBalancer;
+import org.onosproject.kubevirtnetworking.api.DefaultKubevirtLoadBalancerRule;
+import org.onosproject.kubevirtnetworking.api.KubevirtLoadBalancer;
+import org.onosproject.kubevirtnetworking.api.KubevirtLoadBalancerRule;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+
+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.is;
+import static org.hamcrest.Matchers.notNullValue;
+import static org.onosproject.kubevirtnetworking.codec.KubevirtLoadBalancerJsonMatcher.matchesKubevirtLoadBalancer;
+import static org.onosproject.net.NetTestTools.APP_ID;
+
+/**
+ * Unit tests for KubevirtLoadBalancer codec.
+ */
+public final class KubevirtLoadBalancerCodecTest {
+
+ MockCodecContext context;
+
+ JsonCodec<KubevirtLoadBalancer> kubevirtLoadBalancerCodec;
+ JsonCodec<KubevirtLoadBalancerRule> kubevirtLoadBalancerRuleCodec;
+
+ private static final KubevirtLoadBalancerRule RULE1 = DefaultKubevirtLoadBalancerRule.builder()
+ .protocol("tcp")
+ .portRangeMax(8000)
+ .portRangeMin(7000)
+ .build();
+ private static final KubevirtLoadBalancerRule RULE2 = DefaultKubevirtLoadBalancerRule.builder()
+ .protocol("udp")
+ .portRangeMax(9000)
+ .portRangeMin(8000)
+ .build();
+
+ final CoreService mockCoreService = createMock(CoreService.class);
+ private static final String REST_APP_ID = "org.onosproject.rest";
+
+ @Before
+ public void setUp() {
+ context = new MockCodecContext();
+ kubevirtLoadBalancerCodec = new KubevirtLoadBalancerCodec();
+ kubevirtLoadBalancerRuleCodec = new KubevirtLoadBalancerRuleCodec();
+
+ assertThat(kubevirtLoadBalancerCodec, notNullValue());
+ assertThat(kubevirtLoadBalancerRuleCodec, notNullValue());
+
+ expect(mockCoreService.registerApplication(REST_APP_ID))
+ .andReturn(APP_ID).anyTimes();
+ replay(mockCoreService);
+ context.registerService(CoreService.class, mockCoreService);
+ }
+
+ /**
+ * Tests the kubevirt load balancer encoding.
+ */
+ @Test
+ public void testKubevirtLoadBalancerEncode() {
+ KubevirtLoadBalancer lb = DefaultKubevirtLoadBalancer.builder()
+ .name("lb-1")
+ .networkId("net-1")
+ .vip(IpAddress.valueOf("10.10.10.10"))
+ .members(ImmutableSet.of(IpAddress.valueOf("10.10.10.11"),
+ IpAddress.valueOf("10.10.10.12")))
+ .rules(ImmutableSet.of(RULE1, RULE2))
+ .description("network load balancer")
+ .build();
+
+ ObjectNode lbJson = kubevirtLoadBalancerCodec.encode(lb, context);
+ assertThat(lbJson, matchesKubevirtLoadBalancer(lb));
+ }
+
+ /**
+ * Tests the kubevirt load balancer decoding.
+ */
+ @Test
+ public void testKubevirtLoadBalancerDecode() throws IOException {
+ KubevirtLoadBalancer lb = getKubevirtLoadBalancer("KubevirtLoadBalancer.json");
+
+ assertThat(lb.name(), is("lb-1"));
+ assertThat(lb.description(), is("Example Load Balancer"));
+ assertThat(lb.networkId(), is("net-1"));
+ assertThat(lb.vip(), is(IpAddress.valueOf("10.10.10.10")));
+
+ Set<IpAddress> expectedMembers = ImmutableSet.of(IpAddress.valueOf("10.10.10.11"),
+ IpAddress.valueOf("10.10.10.12"));
+ Set<IpAddress> realMembers = lb.members();
+ assertThat(true, is(expectedMembers.containsAll(realMembers)));
+ assertThat(true, is(realMembers.containsAll(expectedMembers)));
+
+ Set<KubevirtLoadBalancerRule> expectedRules = ImmutableSet.of(RULE1, RULE2);
+ Set<KubevirtLoadBalancerRule> realRules = lb.rules();
+ assertThat(true, is(expectedRules.containsAll(realRules)));
+ assertThat(true, is(realRules.containsAll(expectedRules)));
+ }
+
+ private KubevirtLoadBalancer getKubevirtLoadBalancer(String resourceName) throws IOException {
+ InputStream jsonStream = KubevirtLoadBalancerCodecTest.class.getResourceAsStream(resourceName);
+ JsonNode json = context.mapper().readTree(jsonStream);
+ MatcherAssert.assertThat(json, notNullValue());
+ KubevirtLoadBalancer lb = kubevirtLoadBalancerCodec.decode((ObjectNode) json, context);
+ assertThat(lb, notNullValue());
+ return lb;
+ }
+
+ private class MockCodecContext implements CodecContext {
+
+ private final ObjectMapper mapper = new ObjectMapper();
+ private final CodecManager manager = new CodecManager();
+ private final Map<Class<?>, Object> services = new HashMap<>();
+
+ /**
+ * Constructs a new mock codec context.
+ */
+ public MockCodecContext() {
+ manager.activate();
+ }
+
+ @Override
+ public ObjectMapper mapper() {
+ return mapper;
+ }
+
+ @Override
+ public <T> JsonCodec<T> codec(Class<T> entityClass) {
+ if (entityClass == KubevirtLoadBalancerRule.class) {
+ return (JsonCodec<T>) kubevirtLoadBalancerRuleCodec;
+ }
+ return manager.getCodec(entityClass);
+ }
+
+ @Override
+ public <T> T getService(Class<T> serviceClass) {
+ return (T) services.get(serviceClass);
+ }
+
+ // for registering mock services
+ public <T> void registerService(Class<T> serviceClass, T impl) {
+ services.put(serviceClass, impl);
+ }
+ }
+}
diff --git a/apps/kubevirt-networking/app/src/test/java/org/onosproject/kubevirtnetworking/codec/KubevirtLoadBalancerJsonMatcher.java b/apps/kubevirt-networking/app/src/test/java/org/onosproject/kubevirtnetworking/codec/KubevirtLoadBalancerJsonMatcher.java
new file mode 100644
index 0000000..9122bd0
--- /dev/null
+++ b/apps/kubevirt-networking/app/src/test/java/org/onosproject/kubevirtnetworking/codec/KubevirtLoadBalancerJsonMatcher.java
@@ -0,0 +1,144 @@
+/*
+ * 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 org.hamcrest.Description;
+import org.hamcrest.TypeSafeDiagnosingMatcher;
+import org.onlab.packet.IpAddress;
+import org.onosproject.kubevirtnetworking.api.KubevirtLoadBalancer;
+import org.onosproject.kubevirtnetworking.api.KubevirtLoadBalancerRule;
+
+/**
+ * Hamcrest matcher for load balancer.
+ */
+public final class KubevirtLoadBalancerJsonMatcher extends TypeSafeDiagnosingMatcher<JsonNode> {
+
+ private static final String NAME = "name";
+ private static final String DESCRIPTION = "description";
+ private static final String VIP = "vip";
+ private static final String NETWORK_ID = "networkId";
+ private static final String MEMBERS = "members";
+ private static final String RULES = "rules";
+
+ private final KubevirtLoadBalancer lb;
+
+ private KubevirtLoadBalancerJsonMatcher(KubevirtLoadBalancer lb) {
+ this.lb = lb;
+ }
+
+ @Override
+ protected boolean matchesSafely(JsonNode jsonNode, Description description) {
+ // check name
+ String jsonName = jsonNode.get(NAME).asText();
+ String name = lb.name();
+ if (!jsonName.equals(name)) {
+ description.appendText("Name was " + jsonName);
+ return false;
+ }
+
+ // check description
+ JsonNode jsonDescription = jsonNode.get(DESCRIPTION);
+ if (jsonDescription != null) {
+ String myDescription = lb.description();
+ if (!jsonDescription.asText().equals(myDescription)) {
+ description.appendText("Description was " + jsonDescription);
+ return false;
+ }
+ }
+
+ // check VIP
+ String jsonVip = jsonNode.get(VIP).asText();
+ String vip = lb.vip().toString();
+ if (!jsonVip.equals(vip)) {
+ description.appendText("VIP was " + jsonVip);
+ return false;
+ }
+
+ // check network ID
+ String jsonNetworkId = jsonNode.get(NETWORK_ID).asText();
+ String networkId = lb.networkId();
+ if (!jsonNetworkId.equals(networkId)) {
+ description.appendText("NetworkId was " + jsonNetworkId);
+ return false;
+ }
+
+ // check members
+ ArrayNode jsonMembers = (ArrayNode) jsonNode.get(MEMBERS);
+ if (jsonMembers != null) {
+ // check size of members array
+ if (jsonMembers.size() != lb.members().size()) {
+ description.appendText("Members was " + jsonMembers.size());
+ return false;
+ }
+
+ for (JsonNode jsonMember : jsonMembers) {
+ IpAddress member = IpAddress.valueOf(jsonMember.asText());
+ if (!lb.members().contains(member)) {
+ description.appendText("Member not found " + jsonMember.toString());
+ return false;
+ }
+ }
+ }
+
+ ArrayNode jsonRules = (ArrayNode) jsonNode.get(RULES);
+ if (jsonRules != null) {
+ // check size of rules array
+ if (jsonRules.size() != lb.rules().size()) {
+ description.appendText("Rules was " + jsonRules.size());
+ return false;
+ }
+
+ // check rules
+ for (KubevirtLoadBalancerRule rule : lb.rules()) {
+ boolean ruleFound = false;
+ for (int ruleIndex = 0; ruleIndex < jsonRules.size(); ruleIndex++) {
+ KubevirtLoadBalancerRuleJsonMatcher ruleMatcher =
+ KubevirtLoadBalancerRuleJsonMatcher
+ .matchesKubevirtLoadBalancerRule(rule);
+ if (ruleMatcher.matches(jsonRules.get(ruleIndex))) {
+ ruleFound = true;
+ break;
+ }
+ }
+
+ if (!ruleFound) {
+ description.appendText("Rule not found " + rule.toString());
+ return false;
+ }
+ }
+ }
+
+ return true;
+ }
+
+ @Override
+ public void describeTo(Description description) {
+ description.appendText(lb.toString());
+ }
+
+ /**
+ * Factory to allocate a kubevirt load balancer matcher.
+ *
+ * @param lb kubevirt load balancer object we are looking for
+ * @return matcher
+ */
+ public static KubevirtLoadBalancerJsonMatcher
+ matchesKubevirtLoadBalancer(KubevirtLoadBalancer lb) {
+ return new KubevirtLoadBalancerJsonMatcher(lb);
+ }
+}
diff --git a/apps/kubevirt-networking/app/src/test/java/org/onosproject/kubevirtnetworking/codec/KubevirtLoadBalancerRuleJsonMatcher.java b/apps/kubevirt-networking/app/src/test/java/org/onosproject/kubevirtnetworking/codec/KubevirtLoadBalancerRuleJsonMatcher.java
new file mode 100644
index 0000000..404d1ee
--- /dev/null
+++ b/apps/kubevirt-networking/app/src/test/java/org/onosproject/kubevirtnetworking/codec/KubevirtLoadBalancerRuleJsonMatcher.java
@@ -0,0 +1,89 @@
+/*
+ * 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 org.hamcrest.Description;
+import org.hamcrest.TypeSafeDiagnosingMatcher;
+import org.onosproject.kubevirtnetworking.api.KubevirtLoadBalancerRule;
+
+/**
+ * Hamcrest matcher for kubevirt load balancer.
+ */
+public final class KubevirtLoadBalancerRuleJsonMatcher extends TypeSafeDiagnosingMatcher<JsonNode> {
+
+ private final KubevirtLoadBalancerRule rule;
+
+ private static final String PROTOCOL = "protocol";
+ private static final String PORT_RANGE_MAX = "portRangeMax";
+ private static final String PORT_RANGE_MIN = "portRangeMin";
+
+ private KubevirtLoadBalancerRuleJsonMatcher(KubevirtLoadBalancerRule rule) {
+ this.rule = rule;
+ }
+
+ @Override
+ protected boolean matchesSafely(JsonNode jsonNode, Description description) {
+ // check protocol
+ JsonNode jsonProtocol = jsonNode.get(PROTOCOL);
+ if (jsonProtocol != null) {
+ String protocol = rule.protocol();
+ if (!jsonProtocol.asText().equals(protocol)) {
+ description.appendText("Protocol was " + jsonProtocol);
+ return false;
+ }
+ }
+
+ // check port range max
+ JsonNode jsonPortRangeMax = jsonNode.get(PORT_RANGE_MAX);
+ if (jsonPortRangeMax != null) {
+ int portRangeMax = rule.portRangeMax();
+ if (portRangeMax != jsonPortRangeMax.asInt()) {
+ description.appendText("PortRangeMax was " + jsonPortRangeMax);
+ return false;
+ }
+ }
+
+ // check port range min
+ JsonNode jsonPortRangeMin = jsonNode.get(PORT_RANGE_MIN);
+ if (jsonPortRangeMin != null) {
+ int portRangeMin = rule.portRangeMin();
+ if (portRangeMin != jsonPortRangeMin.asInt()) {
+ description.appendText("PortRangeMin was " + jsonPortRangeMin);
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ @Override
+ public void describeTo(Description description) {
+ description.appendText(rule.toString());
+ }
+
+ /**
+ * Factory to allocate an kubevirt load balancer rule matcher.
+ *
+ * @param rule kubevirt load balancer rule object we are looking for
+ * @return matcher
+ */
+ public static KubevirtLoadBalancerRuleJsonMatcher
+ matchesKubevirtLoadBalancerRule(KubevirtLoadBalancerRule rule) {
+ return new KubevirtLoadBalancerRuleJsonMatcher(rule);
+ }
+}
diff --git a/apps/kubevirt-networking/app/src/test/java/org/onosproject/kubevirtnetworking/impl/KubevirtLoadBalancerManagerTest.java b/apps/kubevirt-networking/app/src/test/java/org/onosproject/kubevirtnetworking/impl/KubevirtLoadBalancerManagerTest.java
new file mode 100644
index 0000000..73e1c35
--- /dev/null
+++ b/apps/kubevirt-networking/app/src/test/java/org/onosproject/kubevirtnetworking/impl/KubevirtLoadBalancerManagerTest.java
@@ -0,0 +1,229 @@
+/*
+ * 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 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.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreServiceAdapter;
+import org.onosproject.core.DefaultApplicationId;
+import org.onosproject.event.Event;
+import org.onosproject.kubevirtnetworking.api.DefaultKubevirtLoadBalancer;
+import org.onosproject.kubevirtnetworking.api.KubevirtLoadBalancer;
+import org.onosproject.kubevirtnetworking.api.KubevirtLoadBalancerEvent;
+import org.onosproject.kubevirtnetworking.api.KubevirtLoadBalancerListener;
+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.KubevirtLoadBalancerEvent.Type.KUBEVIRT_LOAD_BALANCER_CREATED;
+import static org.onosproject.kubevirtnetworking.api.KubevirtLoadBalancerEvent.Type.KUBEVIRT_LOAD_BALANCER_REMOVED;
+import static org.onosproject.kubevirtnetworking.api.KubevirtLoadBalancerEvent.Type.KUBEVIRT_LOAD_BALANCER_UPDATED;
+
+/**
+ * Unit tests for kubernetes load balancer manager.
+ */
+public class KubevirtLoadBalancerManagerTest {
+
+ private static final ApplicationId TEST_APP_ID = new DefaultApplicationId(1, "test");
+
+ private static final String LB_NAME = "lb-1";
+ private static final String NETWORK_NAME = "vxlan-1";
+ private static final String UPDATED_DESCRIPTION = "lb-updated";
+ private static final String UNKNOWN_ID = "unknown";
+
+ private static final KubevirtLoadBalancer LB = DefaultKubevirtLoadBalancer.builder()
+ .name(LB_NAME)
+ .description(LB_NAME)
+ .networkId(NETWORK_NAME)
+ .vip(IpAddress.valueOf("10.10.10.10"))
+ .members(ImmutableSet.of())
+ .rules(ImmutableSet.of())
+ .build();
+
+ private static final KubevirtLoadBalancer LB_UPDATED = DefaultKubevirtLoadBalancer.builder()
+ .name(LB_NAME)
+ .description(UPDATED_DESCRIPTION)
+ .networkId(NETWORK_NAME)
+ .vip(IpAddress.valueOf("10.10.10.10"))
+ .members(ImmutableSet.of())
+ .rules(ImmutableSet.of())
+ .build();
+
+ private static final KubevirtLoadBalancer LB_WITH_MEMBERS = DefaultKubevirtLoadBalancer.builder()
+ .name(LB_NAME)
+ .description(LB_NAME)
+ .networkId(NETWORK_NAME)
+ .vip(IpAddress.valueOf("10.10.10.10"))
+ .members(ImmutableSet.of(IpAddress.valueOf("10.10.10.11"),
+ IpAddress.valueOf("10.10.10.12")))
+ .rules(ImmutableSet.of())
+ .build();
+
+ private final TestKubevirtLoadBalancerListener testListener = new TestKubevirtLoadBalancerListener();
+
+ private KubevirtLoadBalancerManager target;
+ private DistributedKubevirtLoadBalancerStore lbStore;
+
+ @Before
+ public void setUp() throws Exception {
+ lbStore = new DistributedKubevirtLoadBalancerStore();
+ TestUtils.setField(lbStore, "coreService", new TestCoreService());
+ TestUtils.setField(lbStore, "storageService", new TestStorageService());
+ TestUtils.setField(lbStore, "eventExecutor", MoreExecutors.newDirectExecutorService());
+ lbStore.activate();
+
+ target = new KubevirtLoadBalancerManager();
+ TestUtils.setField(target, "coreService", new TestCoreService());
+ target.kubevirtLoadBalancerStore = lbStore;
+ target.addListener(testListener);
+ target.activate();
+ }
+
+ @After
+ public void tearDown() {
+ target.removeListener(testListener);
+ lbStore.deactivate();
+ target.deactivate();
+ lbStore = null;
+ target = null;
+ }
+
+ /**
+ * Tests if getting all load balancers returns the correct set of load balancers.
+ */
+ @Test
+ public void testGetLoadBalancers() {
+ createBasicLoadBalancers();
+ assertEquals("Number of load balancers did not match", 1, target.loadBalancers().size());
+ }
+
+ /**
+ * Tests if getting a load balancer with ID returns the correct load balancer.
+ */
+ @Test
+ public void testGetLoadBalancerByName() {
+ createBasicLoadBalancers();
+ assertNotNull("Load balancer did not match", target.loadBalancer(LB_NAME));
+ assertNull("Load balancer did not match", target.loadBalancer(UNKNOWN_ID));
+ }
+
+ /**
+ * Tests creating and removing a load balancer, and checks if it triggers proper events.
+ */
+ @Test
+ public void testCreateAndRemoveLoadBalancer() {
+ target.createLoadBalancer(LB);
+ assertEquals("Number of load balancers did not match", 1, target.loadBalancers().size());
+ assertNotNull("Load balancer was not created", target.loadBalancer(LB_NAME));
+
+ target.removeLoadBalancer(LB_NAME);
+ assertEquals("Number of load balancers did not match", 0, target.loadBalancers().size());
+ assertNull("Load balancer was not removed", target.loadBalancer(LB_NAME));
+
+ validateEvents(KUBEVIRT_LOAD_BALANCER_CREATED, KUBEVIRT_LOAD_BALANCER_REMOVED);
+ }
+
+ /**
+ * Tests updating a load balancer, and checks if it triggers proper events.
+ */
+ @Test
+ public void testCreateAndUpdateLoadBalancer() {
+ target.createLoadBalancer(LB);
+ assertEquals("Number of load balancers did not match", 1, target.loadBalancers().size());
+ assertEquals("Load balancer did not match", LB_NAME, target.loadBalancer(LB_NAME).name());
+
+ target.updateLoadBalancer(LB_UPDATED);
+ assertEquals("Number of load balancers did not match", 1, target.loadBalancers().size());
+ assertEquals("Load balancer did not match", LB_NAME, target.loadBalancer(LB_NAME).name());
+
+ validateEvents(KUBEVIRT_LOAD_BALANCER_CREATED, KUBEVIRT_LOAD_BALANCER_UPDATED);
+ }
+
+ /**
+ * Tests if creating a null load balancer fails with an exception.
+ */
+ @Test(expected = NullPointerException.class)
+ public void testCreateNullLoadBalancer() {
+ target.createLoadBalancer(null);
+ }
+
+ /**
+ * Tests if creating a duplicate load balancer fails with an exception.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void testCreateDuplicateLoadBalancer() {
+ target.createLoadBalancer(LB);
+ target.createLoadBalancer(LB);
+ }
+
+ /**
+ * Tests if removing load balancer with null ID fails with an exception.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void testRemoveLoadBalancerWithNull() {
+ target.removeLoadBalancer(null);
+ }
+
+ /**
+ * Tests if updating an unregistered load balancer fails with an exception.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void testUpdateUnregisteredLoadBalancer() {
+ target.updateLoadBalancer(LB);
+ }
+
+ private void createBasicLoadBalancers() {
+ target.createLoadBalancer(LB);
+ }
+
+ private static class TestCoreService extends CoreServiceAdapter {
+
+ @Override
+ public ApplicationId registerApplication(String name) {
+ return TEST_APP_ID;
+ }
+ }
+
+ private static class TestKubevirtLoadBalancerListener implements KubevirtLoadBalancerListener {
+
+ private List<KubevirtLoadBalancerEvent> events = Lists.newArrayList();
+
+ @Override
+ public void event(KubevirtLoadBalancerEvent 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/KubevirtLoadBalancer.json b/apps/kubevirt-networking/app/src/test/resources/org/onosproject/kubevirtnetworking/codec/KubevirtLoadBalancer.json
new file mode 100644
index 0000000..daf43e2
--- /dev/null
+++ b/apps/kubevirt-networking/app/src/test/resources/org/onosproject/kubevirtnetworking/codec/KubevirtLoadBalancer.json
@@ -0,0 +1,22 @@
+{
+ "name": "lb-1",
+ "description": "Example Load Balancer",
+ "networkId": "net-1",
+ "vip": "10.10.10.10",
+ "members": [
+ "10.10.10.11",
+ "10.10.10.12"
+ ],
+ "rules": [
+ {
+ "protocol": "tcp",
+ "portRangeMax": 8000,
+ "portRangeMin": 7000
+ },
+ {
+ "protocol": "udp",
+ "portRangeMax": 9000,
+ "portRangeMin": 8000
+ }
+ ]
+}
\ No newline at end of file