diff --git a/client/pom.xml b/client/pom.xml
index cc031a4912b1..8f9c7c58cb83 100644
--- a/client/pom.xml
+++ b/client/pom.xml
@@ -281,6 +281,11 @@
cloud-plugin-network-netscaler
${project.version}
+
+ org.apache.cloudstack
+ cloud-plugin-network-aviz-ones
+ ${project.version}
+
org.apache.cloudstack
cloud-plugin-network-ovs
diff --git a/engine/schema/src/main/resources/META-INF/db/schema-42300to2400.sql b/engine/schema/src/main/resources/META-INF/db/schema-42300to2400.sql
index fe4a6aa3ffa9..ba706d9dd006 100644
--- a/engine/schema/src/main/resources/META-INF/db/schema-42300to2400.sql
+++ b/engine/schema/src/main/resources/META-INF/db/schema-42300to2400.sql
@@ -304,3 +304,29 @@ JOIN (
GROUP BY object_store_id
) buckets_quota_sum_view ON `object_store`.id = buckets_quota_sum_view.object_store_id
SET `object_store`.allocated_size = buckets_quota_sum_view.total_quota;
+
+-- Aviz ONES network plugin: one row per ONES Fabric Manager registered with addOnesProvider, scoped to a physical network
+CREATE TABLE IF NOT EXISTS `cloud`.`ones_providers` (
+ `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
+ `uuid` varchar(40) DEFAULT NULL,
+ `host_id` bigint unsigned NOT NULL COMMENT 'the pseudo host (type L2Networking) representing the controller',
+ `physical_network_id` bigint unsigned NOT NULL,
+ `provider_name` varchar(255) NOT NULL,
+ `device_name` varchar(255) NOT NULL,
+ `url` varchar(255) NOT NULL COMMENT 'ONES Fabric Manager API base URL',
+ `fabric_name` varchar(255) NOT NULL,
+ `login_url` varchar(1024) NOT NULL,
+ `username` varchar(255) NOT NULL,
+ `password` varchar(1024) NOT NULL COMMENT 'encrypted with the database key',
+ `client_cert_path` varchar(1024) DEFAULT NULL,
+ `client_key_path` varchar(1024) DEFAULT NULL,
+ `ca_cert_path` varchar(1024) DEFAULT NULL,
+ `gateway_url` varchar(1024) DEFAULT NULL COMMENT 'Aviz Gateway REST API',
+ `gateway_token` varchar(1024) DEFAULT NULL COMMENT 'its API token, encrypted with the database key',
+ `gateway_ca_cert_path` varchar(1024) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `uc_ones_providers__uuid` (`uuid`),
+ UNIQUE KEY `uc_ones_providers__physical_network_id` (`physical_network_id`),
+ CONSTRAINT `fk_ones_providers__host_id` FOREIGN KEY (`host_id`) REFERENCES `host` (`id`) ON DELETE CASCADE,
+ CONSTRAINT `fk_ones_providers__physical_network_id` FOREIGN KEY (`physical_network_id`) REFERENCES `physical_network` (`id`) ON DELETE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
diff --git a/plugins/network-elements/aviz-ones/README.md b/plugins/network-elements/aviz-ones/README.md
new file mode 100644
index 000000000000..0a3c08635fe9
--- /dev/null
+++ b/plugins/network-elements/aviz-ones/README.md
@@ -0,0 +1,174 @@
+
+
+# Aviz ONES Network Plugin
+
+Integrates Apache CloudStack with the **Aviz ONES** fabric manager, which runs the leaf-spine
+fabric of GPU clusters built on the NVIDIA Spectrum-X reference architecture. An isolated guest
+network in CloudStack is one **ONES tenant**: ONES isolates the tenant on the fabric (its own
+VRF, VXLAN VNIs and north-south VLAN) and chooses its subnet; CloudStack runs the VMs and the
+virtual router on it.
+
+Scope: tenant lifecycle (create, delete) and the membership of hypervisor hosts in a tenant,
+including the tenant's VF on a host's DPU where the hosts sit behind DPUs. InfiniBand (UFM) and
+NVLink (NMX-C) configuration through ONES are out of scope.
+
+## How a network maps onto a tenant
+
+ONES, not CloudStack, chooses everything about a tenant: VLAN, VNIs, subnet, compute IP pool
+and gateway. The plugin therefore creates the tenant when the network is created and takes the
+network's addressing from ONES:
+
+| CloudStack | From ONES |
+|---|---|
+| broadcast URI `vlan://` | the tenant's north-south VLAN, which ONES trunks to the hypervisors' leaf ports and maps into the tenant's VRF; the KVM host tags it like any VLAN guest network |
+| CIDR | the tenant subnet |
+| gateway | the gateway ONES reports for the tenant |
+| NIC addresses | only from the tenant's compute IP pool, a part of the subnet; the rest belongs to the fabric |
+
+CloudStack asks for `gateway`/`netmask` when an isolated network is created from an offering
+without SourceNat, before ONES has chosen the subnet. There a placeholder is passed: a gateway
+outside the subnet ONES assigns (e.g. `10.255.255.1`/`255.255.255.0`) is ignored and the network
+takes ONES's subnet and gateway; a gateway inside that subnet is used as given. Offerings with
+SourceNat need neither.
+
+Lifecycle:
+
+| Network event | ONES |
+|---|---|
+| design (createNetwork) | create the tenant and wait for the operation to finish; on any later failure the tenant is deleted again |
+| setup | record tenant name, VLAN, pool and L3 VNI in `network_details` |
+| implement | put the network on the tenant's VLAN |
+| allocate | pick NIC addresses from the tenant's pool |
+| element prepare (a VM on a host) | add the host to the tenant, once per host, as a shared server (one hypervisor carries many tenants); on a host behind a DPU, also give the tenant one free VF of that DPU |
+| shutdown | take the network's hosts out of the tenant, releasing their DPU VFs |
+| trash (deleteNetwork) | delete the tenant |
+
+In compute pools of a /27 or bigger the first nine addresses are left unused for the operator;
+smaller pools are used from the first address. Tenant names are `cs` followed by ten hex digits
+(ONES allows at most twelve characters).
+
+## Design
+
+The ONES controller is registered per physical network as a device, represented by a
+pseudo-host (type `L2Networking`); every call to ONES goes through the agent Command/Answer
+framework, as in the other SDN provider plugins.
+
+| Class | Role |
+|---|---|
+| `OnesProviderVO` / `OnesProviderDao` | one row per registered controller in `ones_providers`; password and tokens stored encrypted |
+| `AddOnesProviderCmd`, `UpdateOnesProviderCmd`, `DeleteOnesProviderCmd`, `ListOnesProvidersCmd` | provider API |
+| `OnesResource` | the controller's `ServerResource`; dispatches the commands to the REST client |
+| `CreateOnesTenantCommand`, `DeleteOnesTenantCommand`, `AllocateOnesServersCommand`, `DeallocateOnesServersCommand` | the southbound operations |
+| `OnesApiClientImpl` | ONES REST client: logs in with a ONES user (and again on a 401); every change is sent asynchronously (`Prefer: respond-async`) and its operation polled until it finishes; TLS is always verified, optionally with a client certificate |
+| `OnesGuestNetworkGuru` | the network lifecycle above |
+| `OnesElement` | provider and services; adds hosts to the tenant as VMs are placed; keeps the tenant's edge in step |
+| `OnesEdgeBuilder`, `ConfigureOnesEdgeCommand`, `RemoveOnesEdgeCommand` | the tenant's edge as CloudStack wants it, sent through the resource |
+| `AvizGatewayClient` | Aviz Gateway REST client (API token, verified TLS) |
+
+Host membership is kept in `network_details` (`onestenantname`, `onesallocatedhosts`), not in a
+table of its own.
+
+## Configuration
+
+1. Physical network: isolation method `ONES`, and the `AvizOnes` service provider added and
+ enabled:
+
+ ```
+ addNetworkServiceProvider name=AvizOnes physicalnetworkid=
+ updateNetworkServiceProvider id= state=Enabled
+ ```
+
+2. Register the ONES controller. The URL's host name must match the ONES server certificate
+ (the default ONES certificate names `ones-fm`); give `cacertpath` when that certificate is
+ not trusted by the JVM:
+
+ ```
+ addOnesProvider physicalnetworkid= name=ones1 url=https://ones.example.com:8443 \
+ fabricname= username= password= \
+ cacertpath=/etc/cloudstack/management/ones-ca.pem
+ ```
+
+ `clientcertpath`/`clientkeypath` add a TLS client certificate; `loginurl` overrides the
+ login endpoint (default `https:///api/user/login`: the ONES UI on the default
+ HTTPS port, not the Fabric Manager port of `url`).
+
+3. Network offering: guest type Isolated, `Connectivity` by `AvizOnes`; `Dhcp`, `Dns` and
+ `UserData` by `VirtualRouter`.
+
+4. Create networks from that offering with a placeholder `gateway`/`netmask` (see above); with
+ SourceNat in the offering, without them.
+
+## Edge services on the Aviz Gateway (optional, experimental)
+
+A ONES tenant reaches the outside through an Aviz Gateway: ONES puts each tenant on the gateway
+(its edge configurator) once a server joined the tenant. On top of that the plugin offers, by
+the `AvizOnes` provider:
+
+| Service | On the gateway |
+|---|---|
+| SourceNat | the tenant's internet access, translating outbound traffic onto the network's source NAT address |
+| PortForwarding | one inbound mapping per port of each rule (at most 256 ports per rule) |
+| Lb | one VIP per load-balancer rule with every member as a backend; round robin, tcp or udp, `SourceBased` stickiness. The gateway health-checks the members when ONES gave the tenant a loopback on the gateway, else the VIP goes unchecked. A VIP cannot use the source NAT address, and a member's private port serves one VIP only (no second VIP and no port forward to it) |
+| Firewall | ingress rules: the gateway filters after translation, so each mapped VM address and port gets a deny for any source and a permit per allowed source CIDR. A mapping no ingress rule covers stays closed |
+
+All public addresses are CloudStack's own: give the zone a public IP range the gateway's uplink
+announces. The plugin works out the tenant's whole edge from CloudStack's records whenever an
+address, port forward, load-balancer or firewall rule changes (and when the network's first host
+joins the tenant), and sends it in one command; anything of the tenant's it made and that is no
+longer wanted is removed. VIPs and firewall rules an operator adds on the gateway by hand are
+never touched. Shutting the network down takes its edge off the gateway.
+
+Configuration: give the provider the gateway, with an API token of role `operator` created for
+CloudStack on the gateway (`POST /api/v1/tokens`):
+
+```
+updateOnesProvider id= gatewayurl=https://gateway.example.com:8090 \
+ gatewaytoken= gatewaycacertpath=/etc/cloudstack/management/gateway-ca.pem
+```
+
+and put the services wanted by `AvizOnes` in the network offering. Only Connectivity is required;
+PortForwarding needs SourceNat (the gateway keeps port forwards in the tenant's internet access);
+without Firewall, forwarded ports and load balancers are open to every source. Gateway firewall
+rules are named after their position in the network's rule set and rewritten as a whole on every
+change.
+
+## Limitations of this version
+
+- The provider APIs are for root administrators only.
+- Live migration is not supported yet: the destination host is not added to the tenant, so an
+ instance migrated to a host with no other instance of its network loses connectivity.
+- Deploy the instances of one network one at a time: parallel deploys can pick the same address.
+- The ONES login and controller settings cannot be changed after the provider is added.
+- Hosts leave a tenant only when the network shuts down.
+- A network spans at most about 40 hosts (the size of the `onesallocatedhosts` detail).
+
+## Requirements on ONES
+
+- The fabric runs with ONES tenant IPAM off: CloudStack, not ONES, configures the hypervisors.
+- The tenant gateway ONES reports must be the address the fabric routes the tenant on.
+
+## Tests
+
+```
+mvn -pl plugins/network-elements/aviz-ones test
+```
+
+The REST client is tested against a local fake ONES over TLS with throwaway certificates; the
+guru, element and resource with mocks. No ONES controller is needed.
diff --git a/plugins/network-elements/aviz-ones/pom.xml b/plugins/network-elements/aviz-ones/pom.xml
new file mode 100644
index 000000000000..8a2dc5294b2e
--- /dev/null
+++ b/plugins/network-elements/aviz-ones/pom.xml
@@ -0,0 +1,39 @@
+
+
+ 4.0.0
+ cloud-plugin-network-aviz-ones
+ Apache CloudStack Plugin - Network Aviz ONES
+
+ org.apache.cloudstack
+ cloudstack-plugins
+ 24.0.0-SNAPSHOT
+ ../../pom.xml
+
+
+
+ org.apache.cloudstack
+ cloud-utils
+ ${project.version}
+ test-jar
+ test
+
+
+
diff --git a/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/agent/api/AllocateOnesServersCommand.java b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/agent/api/AllocateOnesServersCommand.java
new file mode 100644
index 000000000000..7e443019ead7
--- /dev/null
+++ b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/agent/api/AllocateOnesServersCommand.java
@@ -0,0 +1,64 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.apache.cloudstack.network.ones.agent.api;
+
+import java.util.List;
+
+import com.cloud.agent.api.Command;
+
+/**
+ * Maps to ONES "Allocate Servers" (operation=ADD):
+ * PATCH /fabrics/{fabricName}/tenants/{tenantName}
+ */
+public class AllocateOnesServersCommand extends Command {
+
+ private final String fabricName;
+ private final String tenantName;
+ private final List serverNames;
+ private final boolean shared;
+
+ public AllocateOnesServersCommand(final String fabricName, final String tenantName, final List serverNames, final boolean shared) {
+ this.fabricName = fabricName;
+ this.tenantName = tenantName;
+ this.serverNames = serverNames;
+ this.shared = shared;
+ }
+
+ @Override
+ public boolean executeInSequence() {
+ return true;
+ }
+
+ public String getFabricName() {
+ return fabricName;
+ }
+
+ public String getTenantName() {
+ return tenantName;
+ }
+
+ public List getServerNames() {
+ return serverNames;
+ }
+
+ public boolean isShared() {
+ return shared;
+ }
+}
diff --git a/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/agent/api/ConfigureOnesEdgeCommand.java b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/agent/api/ConfigureOnesEdgeCommand.java
new file mode 100644
index 000000000000..f3e0c82629f4
--- /dev/null
+++ b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/agent/api/ConfigureOnesEdgeCommand.java
@@ -0,0 +1,243 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.apache.cloudstack.network.ones.agent.api;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+
+import com.cloud.agent.api.Command;
+
+/**
+ * The whole edge of one ONES tenant on the Aviz Gateway, as CloudStack wants it: outbound
+ * translation onto the network's source NAT address, port forwards, load-balancer VIPs and the
+ * firewall rules that guard them. The resource makes the gateway match it; anything of the
+ * tenant's that is not listed (VIPs, firewall rules this plugin made) is removed.
+ */
+public class ConfigureOnesEdgeCommand extends Command {
+
+ /** One inbound mapping: external:externalPort -> local:localPort. */
+ public static class PortMapping {
+ private final String external;
+ private final String local;
+ private final String protocol;
+ private final int externalPort;
+ private final int localPort;
+
+ public PortMapping(final String external, final String local, final String protocol, final int externalPort, final int localPort) {
+ this.external = external;
+ this.local = local;
+ this.protocol = protocol;
+ this.externalPort = externalPort;
+ this.localPort = localPort;
+ }
+
+ public String getExternal() {
+ return external;
+ }
+
+ public String getLocal() {
+ return local;
+ }
+
+ public String getProtocol() {
+ return protocol;
+ }
+
+ public int getExternalPort() {
+ return externalPort;
+ }
+
+ public int getLocalPort() {
+ return localPort;
+ }
+
+ @Override
+ public boolean equals(final Object o) {
+ if (!(o instanceof PortMapping)) {
+ return false;
+ }
+ PortMapping m = (PortMapping) o;
+ return externalPort == m.externalPort && localPort == m.localPort && Objects.equals(external, m.external)
+ && Objects.equals(local, m.local) && Objects.equals(protocol, m.protocol);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(external, local, protocol, externalPort, localPort);
+ }
+
+ @Override
+ public String toString() {
+ return external + ":" + externalPort + "/" + protocol + " -> " + local + ":" + localPort;
+ }
+ }
+
+ /** A load-balanced address and port in front of the tenant's servers. */
+ public static class Vip {
+ private final String name;
+ private final String address;
+ private final int port;
+ private final String protocol;
+ private final int backendPort;
+ private final List backends;
+ private final boolean sourceSticky;
+
+ public Vip(final String name, final String address, final int port, final String protocol, final int backendPort,
+ final List backends, final boolean sourceSticky) {
+ this.name = name;
+ this.address = address;
+ this.port = port;
+ this.protocol = protocol;
+ this.backendPort = backendPort;
+ this.backends = new ArrayList<>(backends);
+ this.sourceSticky = sourceSticky;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getAddress() {
+ return address;
+ }
+
+ public int getPort() {
+ return port;
+ }
+
+ public String getProtocol() {
+ return protocol;
+ }
+
+ public int getBackendPort() {
+ return backendPort;
+ }
+
+ public List getBackends() {
+ return backends;
+ }
+
+ public boolean isSourceSticky() {
+ return sourceSticky;
+ }
+
+ @Override
+ public String toString() {
+ return name + " " + address + ":" + port + "/" + protocol + " -> " + backends + ":" + backendPort;
+ }
+ }
+
+ /**
+ * A gateway firewall rule. The gateway filters inbound traffic after translation, so a rule
+ * names the local address and port a mapping leads to, not the public ones.
+ */
+ public static class FirewallRule {
+ private final String name;
+ private final String source;
+ private final String destination;
+ private final String protocol;
+ private final int port;
+ private final boolean permit;
+
+ public FirewallRule(final String name, final String source, final String destination, final String protocol, final int port,
+ final boolean permit) {
+ this.name = name;
+ this.source = source;
+ this.destination = destination;
+ this.protocol = protocol;
+ this.port = port;
+ this.permit = permit;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getSource() {
+ return source;
+ }
+
+ public String getDestination() {
+ return destination;
+ }
+
+ public String getProtocol() {
+ return protocol;
+ }
+
+ public int getPort() {
+ return port;
+ }
+
+ public boolean isPermit() {
+ return permit;
+ }
+
+ @Override
+ public String toString() {
+ return name + ": " + (permit ? "permit " : "deny ") + source + " -> " + destination + " " + protocol + "/" + port;
+ }
+ }
+
+ private final String tenantName;
+ private final String sourceNatAddress;
+ private final List portMappings;
+ private final List vips;
+ private final List firewallRules;
+
+ /**
+ * @param sourceNatAddress the address outbound traffic leaves on; null takes the tenant's
+ * internet access away (and with it every port mapping)
+ */
+ public ConfigureOnesEdgeCommand(final String tenantName, final String sourceNatAddress, final List portMappings,
+ final List vips, final List firewallRules) {
+ this.tenantName = tenantName;
+ this.sourceNatAddress = sourceNatAddress;
+ this.portMappings = new ArrayList<>(portMappings);
+ this.vips = new ArrayList<>(vips);
+ this.firewallRules = new ArrayList<>(firewallRules);
+ }
+
+ @Override
+ public boolean executeInSequence() {
+ return true;
+ }
+
+ public String getTenantName() {
+ return tenantName;
+ }
+
+ public String getSourceNatAddress() {
+ return sourceNatAddress;
+ }
+
+ public List getPortMappings() {
+ return portMappings;
+ }
+
+ public List getVips() {
+ return vips;
+ }
+
+ public List getFirewallRules() {
+ return firewallRules;
+ }
+}
diff --git a/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/agent/api/CreateOnesTenantAnswer.java b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/agent/api/CreateOnesTenantAnswer.java
new file mode 100644
index 000000000000..9b5efb08bb60
--- /dev/null
+++ b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/agent/api/CreateOnesTenantAnswer.java
@@ -0,0 +1,89 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.apache.cloudstack.network.ones.agent.api;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.Command;
+
+/**
+ * What ONES allocated for a tenant, read back with GET /fabrics/{f}/tenants/{t} once the
+ * (async) create operation has finished.
+ *
+ * vlanId the north-south VLAN: the VLAN the leaf ports trunk to the hypervisors, i.e.
+ * the VLAN CloudStack puts the guest network on (vlan://vlanId)
+ * l2Vni east-west VXLAN VNI (ONES "vniId"), internal to the fabric
+ * l3Vni the tenant VRF's L3 VNI (ONES "nsVniId")
+ * subnet the tenant subnet (ONES "vlanSubnetCPU", e.g. 192.1.0.0/16): the guest CIDR
+ * ipPool the part of the subnet meant for compute (ONES "tenantIpPool", e.g.
+ * 192.1.64.0/18); VM addresses are taken from here only
+ * gateway the tenant gateway ONES reports (bare IP)
+ */
+public class CreateOnesTenantAnswer extends Answer {
+
+ private final Integer vlanId;
+ private final Integer l2Vni;
+ private final Integer l3Vni;
+ private final String subnet;
+ private final String ipPool;
+ private final String gateway;
+
+ public CreateOnesTenantAnswer(final Command command, final String details, final Integer vlanId, final Integer l2Vni,
+ final Integer l3Vni, final String subnet, final String ipPool, final String gateway) {
+ super(command, true, details);
+ this.vlanId = vlanId;
+ this.l2Vni = l2Vni;
+ this.l3Vni = l3Vni;
+ this.subnet = subnet;
+ this.ipPool = ipPool;
+ this.gateway = gateway;
+ }
+
+ public CreateOnesTenantAnswer(final Command command, final Exception e) {
+ super(command, e);
+ this.vlanId = null;
+ this.l2Vni = null;
+ this.l3Vni = null;
+ this.subnet = null;
+ this.ipPool = null;
+ this.gateway = null;
+ }
+
+ public Integer getVlanId() {
+ return vlanId;
+ }
+
+ public Integer getL2Vni() {
+ return l2Vni;
+ }
+
+ public Integer getL3Vni() {
+ return l3Vni;
+ }
+
+ public String getSubnet() {
+ return subnet;
+ }
+
+ public String getIpPool() {
+ return ipPool;
+ }
+
+ public String getGateway() {
+ return gateway;
+ }
+}
diff --git a/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/agent/api/CreateOnesTenantCommand.java b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/agent/api/CreateOnesTenantCommand.java
new file mode 100644
index 000000000000..1a19a3bc03ca
--- /dev/null
+++ b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/agent/api/CreateOnesTenantCommand.java
@@ -0,0 +1,61 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.apache.cloudstack.network.ones.agent.api;
+
+import com.cloud.agent.api.Command;
+
+/**
+ * Maps to ONES "Create Tenant": POST /fabrics/{fabricName}/tenants
+ */
+public class CreateOnesTenantCommand extends Command {
+
+ private final String fabricName;
+ private final String tenantName;
+ private final String description;
+ private final int maxGpusAllowed;
+
+ public CreateOnesTenantCommand(final String fabricName, final String tenantName, final String description, final int maxGpusAllowed) {
+ this.fabricName = fabricName;
+ this.tenantName = tenantName;
+ this.description = description;
+ this.maxGpusAllowed = maxGpusAllowed;
+ }
+
+ @Override
+ public boolean executeInSequence() {
+ return true;
+ }
+
+ public String getFabricName() {
+ return fabricName;
+ }
+
+ public String getTenantName() {
+ return tenantName;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public int getMaxGpusAllowed() {
+ return maxGpusAllowed;
+ }
+}
diff --git a/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/agent/api/DeallocateOnesServersCommand.java b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/agent/api/DeallocateOnesServersCommand.java
new file mode 100644
index 000000000000..98e37bc57719
--- /dev/null
+++ b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/agent/api/DeallocateOnesServersCommand.java
@@ -0,0 +1,58 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.apache.cloudstack.network.ones.agent.api;
+
+import java.util.List;
+
+import com.cloud.agent.api.Command;
+
+/**
+ * Maps to ONES "Deallocate Servers" (operation=DELETE):
+ * PATCH /fabrics/{fabricName}/tenants/{tenantName}
+ */
+public class DeallocateOnesServersCommand extends Command {
+
+ private final String fabricName;
+ private final String tenantName;
+ private final List serverNames;
+
+ public DeallocateOnesServersCommand(final String fabricName, final String tenantName, final List serverNames) {
+ this.fabricName = fabricName;
+ this.tenantName = tenantName;
+ this.serverNames = serverNames;
+ }
+
+ @Override
+ public boolean executeInSequence() {
+ return true;
+ }
+
+ public String getFabricName() {
+ return fabricName;
+ }
+
+ public String getTenantName() {
+ return tenantName;
+ }
+
+ public List getServerNames() {
+ return serverNames;
+ }
+}
diff --git a/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/agent/api/DeleteOnesTenantCommand.java b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/agent/api/DeleteOnesTenantCommand.java
new file mode 100644
index 000000000000..570ea70a8278
--- /dev/null
+++ b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/agent/api/DeleteOnesTenantCommand.java
@@ -0,0 +1,49 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.apache.cloudstack.network.ones.agent.api;
+
+import com.cloud.agent.api.Command;
+
+/**
+ * Maps to ONES "Delete Tenant": DELETE /fabrics/{fabricName}/tenants/{tenantName}
+ */
+public class DeleteOnesTenantCommand extends Command {
+
+ private final String fabricName;
+ private final String tenantName;
+
+ public DeleteOnesTenantCommand(final String fabricName, final String tenantName) {
+ this.fabricName = fabricName;
+ this.tenantName = tenantName;
+ }
+
+ @Override
+ public boolean executeInSequence() {
+ return true;
+ }
+
+ public String getFabricName() {
+ return fabricName;
+ }
+
+ public String getTenantName() {
+ return tenantName;
+ }
+}
diff --git a/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/agent/api/RemoveOnesEdgeCommand.java b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/agent/api/RemoveOnesEdgeCommand.java
new file mode 100644
index 000000000000..e1b5f6e4ffff
--- /dev/null
+++ b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/agent/api/RemoveOnesEdgeCommand.java
@@ -0,0 +1,44 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.apache.cloudstack.network.ones.agent.api;
+
+import com.cloud.agent.api.Command;
+
+/**
+ * Takes a ONES tenant's edge off the Aviz Gateway: its firewall rules made by this plugin, its
+ * VIPs and its internet access. What is already gone is fine.
+ */
+public class RemoveOnesEdgeCommand extends Command {
+
+ private final String tenantName;
+
+ public RemoveOnesEdgeCommand(final String tenantName) {
+ this.tenantName = tenantName;
+ }
+
+ @Override
+ public boolean executeInSequence() {
+ return true;
+ }
+
+ public String getTenantName() {
+ return tenantName;
+ }
+}
diff --git a/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/agent/api/StartupOnesCommand.java b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/agent/api/StartupOnesCommand.java
new file mode 100644
index 000000000000..460fe0a0ff82
--- /dev/null
+++ b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/agent/api/StartupOnesCommand.java
@@ -0,0 +1,31 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.apache.cloudstack.network.ones.agent.api;
+
+import com.cloud.agent.api.StartupCommand;
+import com.cloud.host.Host;
+
+public class StartupOnesCommand extends StartupCommand {
+
+ public StartupOnesCommand() {
+ super(Host.Type.L2Networking);
+ }
+
+}
diff --git a/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/api/command/AddOnesProviderCmd.java b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/api/command/AddOnesProviderCmd.java
new file mode 100644
index 000000000000..02dda20b2b62
--- /dev/null
+++ b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/api/command/AddOnesProviderCmd.java
@@ -0,0 +1,172 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.apache.cloudstack.network.ones.api.command;
+
+import javax.inject.Inject;
+
+import org.apache.cloudstack.acl.RoleType;
+import org.apache.cloudstack.api.APICommand;
+import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.ApiErrorCode;
+import org.apache.cloudstack.api.BaseCmd;
+import org.apache.cloudstack.api.Parameter;
+import org.apache.cloudstack.api.ServerApiException;
+import org.apache.cloudstack.api.response.PhysicalNetworkResponse;
+import org.apache.cloudstack.context.CallContext;
+import org.apache.cloudstack.network.ones.api.response.OnesProviderResponse;
+import org.apache.cloudstack.network.ones.dao.OnesProviderVO;
+import org.apache.cloudstack.network.ones.service.OnesElementService;
+
+import com.cloud.exception.ConcurrentOperationException;
+import com.cloud.exception.InvalidParameterValueException;
+import com.cloud.utils.exception.CloudRuntimeException;
+
+/**
+ * Registers an Aviz ONES Spectrum-X fabric controller against a physical network, the same
+ * way addNiciraNvpDevice/addBigSwitchBcfDevice register their SDN controllers.
+ */
+@APICommand(name = "addOnesProvider", responseObject = OnesProviderResponse.class, description = "Adds an Aviz ONES Spectrum-X fabric provider",
+ requestHasSensitiveInfo = true, responseHasSensitiveInfo = false,
+ authorized = {RoleType.Admin}, since = "24.0.0")
+public class AddOnesProviderCmd extends BaseCmd {
+
+ @Inject
+ protected OnesElementService onesElementService;
+
+ /////////////////////////////////////////////////////
+ //////////////// API parameters /////////////////////
+ /////////////////////////////////////////////////////
+
+ @Parameter(name = ApiConstants.PHYSICAL_NETWORK_ID,
+ type = CommandType.UUID,
+ entityType = PhysicalNetworkResponse.class,
+ required = true,
+ description = "the Physical Network ID")
+ private Long physicalNetworkId;
+
+ @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, required = true, description = "Name of this Aviz ONES provider")
+ private String name;
+
+ @Parameter(name = "url", type = CommandType.STRING, required = true, description = "Base URL of the ONES Fabric Manager API, e.g. https://ones.example.com:8443; the host name must match the ONES server certificate")
+ private String url;
+
+ @Parameter(name = "fabricname", type = CommandType.STRING, required = true, description = "Name of the ONES fabric this provider orchestrates tenants on")
+ private String fabricName;
+
+ @Parameter(name = ApiConstants.USERNAME, type = CommandType.STRING, required = true,
+ description = "ONES user the plugin logs in as")
+ private String username;
+
+ @Parameter(name = ApiConstants.PASSWORD, type = CommandType.STRING, required = true,
+ description = "password of that ONES user; stored encrypted")
+ private String password;
+
+ @Parameter(name = "loginurl", type = CommandType.STRING, length = 1024,
+ description = "ONES login endpoint; default https:///api/user/login")
+ private String loginUrl;
+
+ @Parameter(name = "clientcertpath", type = CommandType.STRING, length = 1024,
+ description = "Optional: local filesystem path (on the management server) to a TLS client certificate, for a ONES controller that requires one")
+ private String clientCertPath;
+
+ @Parameter(name = "clientkeypath", type = CommandType.STRING, length = 1024,
+ description = "Optional: local filesystem path (on the management server) to the mTLS client private key. Required if clientcertpath is set")
+ private String clientKeyPath;
+
+ @Parameter(name = "cacertpath", type = CommandType.STRING, length = 1024,
+ description = "Optional: local filesystem path (on the management server) to a CA bundle used to verify the ONES controller. If omitted, the JVM's default trust store is used")
+ private String caCertPath;
+
+ /////////////////////////////////////////////////////
+ /////////////////// Accessors ///////////////////////
+ /////////////////////////////////////////////////////
+
+ public Long getPhysicalNetworkId() {
+ return physicalNetworkId;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getUrl() {
+ return url;
+ }
+
+ public String getFabricName() {
+ return fabricName;
+ }
+
+ public String getUsername() {
+ return username;
+ }
+
+ public String getPassword() {
+ return password;
+ }
+
+ public String getLoginUrl() {
+ if (loginUrl != null && !loginUrl.isEmpty()) {
+ return loginUrl;
+ }
+ java.net.URI u = java.net.URI.create(url);
+ return u.getScheme() + "://" + u.getHost() + "/api/user/login";
+ }
+
+ public String getClientCertPath() {
+ return clientCertPath;
+ }
+
+ public String getClientKeyPath() {
+ return clientKeyPath;
+ }
+
+ public String getCaCertPath() {
+ return caCertPath;
+ }
+
+ /////////////////////////////////////////////////////
+ /////////////// API Implementation///////////////////
+ /////////////////////////////////////////////////////
+
+ @Override
+ public void execute() throws ServerApiException, ConcurrentOperationException {
+ try {
+ OnesProviderVO onesProviderVO = onesElementService.addOnesProvider(this);
+ if (onesProviderVO != null) {
+ OnesProviderResponse response = onesElementService.createOnesProviderResponse(onesProviderVO);
+ response.setObjectName("onesprovider");
+ response.setResponseName(getCommandName());
+ setResponseObject(response);
+ } else {
+ throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add Aviz ONES provider due to internal error.");
+ }
+ } catch (InvalidParameterValueException invalidParamExcp) {
+ throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage());
+ } catch (CloudRuntimeException runtimeExcp) {
+ throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage());
+ }
+ }
+
+ @Override
+ public long getEntityOwnerId() {
+ return CallContext.current().getCallingAccount().getId();
+ }
+}
diff --git a/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/api/command/DeleteOnesProviderCmd.java b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/api/command/DeleteOnesProviderCmd.java
new file mode 100644
index 000000000000..b06452672888
--- /dev/null
+++ b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/api/command/DeleteOnesProviderCmd.java
@@ -0,0 +1,90 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.apache.cloudstack.network.ones.api.command;
+
+import javax.inject.Inject;
+
+import org.apache.cloudstack.acl.RoleType;
+import org.apache.cloudstack.api.APICommand;
+import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.ApiErrorCode;
+import org.apache.cloudstack.api.BaseCmd;
+import org.apache.cloudstack.api.Parameter;
+import org.apache.cloudstack.api.ServerApiException;
+import org.apache.cloudstack.api.response.SuccessResponse;
+import org.apache.cloudstack.context.CallContext;
+import org.apache.cloudstack.network.ones.api.response.OnesProviderResponse;
+import org.apache.cloudstack.network.ones.service.OnesElementService;
+
+import com.cloud.exception.ConcurrentOperationException;
+import com.cloud.exception.InvalidParameterValueException;
+import com.cloud.utils.exception.CloudRuntimeException;
+
+@APICommand(name = "deleteOnesProvider", responseObject = SuccessResponse.class, description = "Deletes an Aviz ONES Spectrum-X fabric provider",
+ requestHasSensitiveInfo = false, responseHasSensitiveInfo = false,
+ authorized = {RoleType.Admin}, since = "24.0.0")
+public class DeleteOnesProviderCmd extends BaseCmd {
+
+ @Inject
+ protected OnesElementService onesElementService;
+
+ /////////////////////////////////////////////////////
+ //////////////// API parameters /////////////////////
+ /////////////////////////////////////////////////////
+
+ @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = OnesProviderResponse.class,
+ required = true, description = "Aviz ONES provider ID")
+ private Long id;
+
+ /////////////////////////////////////////////////////
+ /////////////////// Accessors ///////////////////////
+ /////////////////////////////////////////////////////
+
+ public Long getId() {
+ return id;
+ }
+
+ /////////////////////////////////////////////////////
+ /////////////// API Implementation///////////////////
+ /////////////////////////////////////////////////////
+
+ @Override
+ public void execute() throws ServerApiException, ConcurrentOperationException {
+ try {
+ boolean result = onesElementService.deleteOnesProvider(this);
+ if (result) {
+ SuccessResponse response = new SuccessResponse(getCommandName());
+ response.setResponseName(getCommandName());
+ setResponseObject(response);
+ } else {
+ throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete Aviz ONES provider.");
+ }
+ } catch (InvalidParameterValueException invalidParamExcp) {
+ throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage());
+ } catch (CloudRuntimeException runtimeExcp) {
+ throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage());
+ }
+ }
+
+ @Override
+ public long getEntityOwnerId() {
+ return CallContext.current().getCallingAccount().getId();
+ }
+}
diff --git a/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/api/command/ListOnesProvidersCmd.java b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/api/command/ListOnesProvidersCmd.java
new file mode 100644
index 000000000000..7b8c034c64f7
--- /dev/null
+++ b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/api/command/ListOnesProvidersCmd.java
@@ -0,0 +1,109 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.apache.cloudstack.network.ones.api.command;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.inject.Inject;
+
+import org.apache.cloudstack.acl.RoleType;
+import org.apache.cloudstack.api.APICommand;
+import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.ApiErrorCode;
+import org.apache.cloudstack.api.BaseListCmd;
+import org.apache.cloudstack.api.Parameter;
+import org.apache.cloudstack.api.ServerApiException;
+import org.apache.cloudstack.api.response.ListResponse;
+import org.apache.cloudstack.api.response.PhysicalNetworkResponse;
+import org.apache.cloudstack.network.ones.api.response.OnesProviderResponse;
+import org.apache.cloudstack.network.ones.dao.OnesProviderVO;
+import org.apache.cloudstack.network.ones.service.OnesElementService;
+
+import com.cloud.exception.InsufficientCapacityException;
+import com.cloud.exception.InvalidParameterValueException;
+import com.cloud.exception.ResourceAllocationException;
+import com.cloud.exception.ResourceUnavailableException;
+import com.cloud.utils.exception.CloudRuntimeException;
+
+@APICommand(name = "listOnesProviders", responseObject = OnesProviderResponse.class, description = "Lists Aviz ONES providers",
+ requestHasSensitiveInfo = false, responseHasSensitiveInfo = false,
+ authorized = {RoleType.Admin}, since = "24.0.0")
+public class ListOnesProvidersCmd extends BaseListCmd {
+ private static final String s_name = "listonesprovidersresponse";
+
+ @Inject
+ protected OnesElementService onesElementService;
+
+ /////////////////////////////////////////////////////
+ //////////////// API parameters /////////////////////
+ /////////////////////////////////////////////////////
+
+ @Parameter(name = ApiConstants.PHYSICAL_NETWORK_ID, type = CommandType.UUID, entityType = PhysicalNetworkResponse.class,
+ description = "the Physical Network ID")
+ private Long physicalNetworkId;
+
+ @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = OnesProviderResponse.class, description = "Aviz ONES provider ID")
+ private Long id;
+
+ /////////////////////////////////////////////////////
+ /////////////////// Accessors ///////////////////////
+ /////////////////////////////////////////////////////
+
+ public Long getId() {
+ return id;
+ }
+
+ public Long getPhysicalNetworkId() {
+ return physicalNetworkId;
+ }
+
+ /////////////////////////////////////////////////////
+ /////////////// API Implementation///////////////////
+ /////////////////////////////////////////////////////
+
+ @Override
+ public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException {
+ try {
+ List onesProviders = onesElementService.listOnesProviders(this);
+ ListResponse response = new ListResponse();
+ List onesProviderResponses = new ArrayList();
+
+ if (onesProviders != null && !onesProviders.isEmpty()) {
+ for (OnesProviderVO onesProviderVO : onesProviders) {
+ onesProviderResponses.add(onesElementService.createOnesProviderResponse(onesProviderVO));
+ }
+ }
+
+ response.setResponses(onesProviderResponses);
+ response.setResponseName(getCommandName());
+ setResponseObject(response);
+ } catch (InvalidParameterValueException invalidParamExcp) {
+ throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage());
+ } catch (CloudRuntimeException runtimeExcp) {
+ throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage());
+ }
+ }
+
+ @Override
+ public String getCommandName() {
+ return s_name;
+ }
+}
diff --git a/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/api/command/UpdateOnesProviderCmd.java b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/api/command/UpdateOnesProviderCmd.java
new file mode 100644
index 000000000000..02a27a53fc3c
--- /dev/null
+++ b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/api/command/UpdateOnesProviderCmd.java
@@ -0,0 +1,97 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.apache.cloudstack.network.ones.api.command;
+
+import javax.inject.Inject;
+
+import org.apache.cloudstack.acl.RoleType;
+import org.apache.cloudstack.api.APICommand;
+import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.ApiErrorCode;
+import org.apache.cloudstack.api.BaseCmd;
+import org.apache.cloudstack.api.Parameter;
+import org.apache.cloudstack.api.ServerApiException;
+import org.apache.cloudstack.context.CallContext;
+import org.apache.cloudstack.network.ones.api.response.OnesProviderResponse;
+import org.apache.cloudstack.network.ones.dao.OnesProviderVO;
+import org.apache.cloudstack.network.ones.service.OnesElementService;
+
+import com.cloud.exception.InvalidParameterValueException;
+import com.cloud.utils.exception.CloudRuntimeException;
+
+/** Edge (Aviz Gateway) settings of a registered ONES provider. An empty value clears a setting. */
+@APICommand(name = "updateOnesProvider", responseObject = OnesProviderResponse.class,
+ description = "Updates an Aviz ONES provider's Aviz Gateway settings (the edge of its networks)",
+ requestHasSensitiveInfo = true, responseHasSensitiveInfo = false,
+ authorized = {RoleType.Admin}, since = "24.0.0")
+public class UpdateOnesProviderCmd extends BaseCmd {
+
+ @Inject
+ protected OnesElementService onesElementService;
+
+ @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = OnesProviderResponse.class,
+ required = true, description = "Aviz ONES provider ID")
+ private Long id;
+
+ @Parameter(name = "gatewayurl", type = CommandType.STRING, length = 1024,
+ description = "Aviz Gateway REST API, e.g. https://gateway.example.com:8090; the host name must match the gateway certificate")
+ private String gatewayUrl;
+
+ @Parameter(name = "gatewaytoken", type = CommandType.STRING, length = 1024,
+ description = "Aviz Gateway API token (role operator); stored encrypted")
+ private String gatewayToken;
+
+ @Parameter(name = "gatewaycacertpath", type = CommandType.STRING, length = 1024,
+ description = "path on the management server to the certificate that verifies the gateway")
+ private String gatewayCaCertPath;
+
+ public Long getId() {
+ return id;
+ }
+
+ public String getGatewayUrl() {
+ return gatewayUrl;
+ }
+
+ public String getGatewayToken() {
+ return gatewayToken;
+ }
+
+ public String getGatewayCaCertPath() {
+ return gatewayCaCertPath;
+ }
+
+ @Override
+ public void execute() {
+ try {
+ OnesProviderVO vo = onesElementService.updateOnesProvider(this);
+ OnesProviderResponse response = onesElementService.createOnesProviderResponse(vo);
+ response.setResponseName(getCommandName());
+ setResponseObject(response);
+ } catch (InvalidParameterValueException e) {
+ throw new ServerApiException(ApiErrorCode.PARAM_ERROR, e.getMessage());
+ } catch (CloudRuntimeException e) {
+ throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage());
+ }
+ }
+
+ @Override
+ public long getEntityOwnerId() {
+ return CallContext.current().getCallingAccount().getId();
+ }
+}
diff --git a/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/api/response/OnesProviderResponse.java b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/api/response/OnesProviderResponse.java
new file mode 100644
index 000000000000..88ff8218a9af
--- /dev/null
+++ b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/api/response/OnesProviderResponse.java
@@ -0,0 +1,96 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.apache.cloudstack.network.ones.api.response;
+
+import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.BaseResponse;
+import org.apache.cloudstack.api.EntityReference;
+import org.apache.cloudstack.network.ones.dao.OnesProviderVO;
+
+import com.cloud.serializer.Param;
+import com.google.gson.annotations.SerializedName;
+
+@EntityReference(value = OnesProviderVO.class)
+public class OnesProviderResponse extends BaseResponse {
+
+ @SerializedName(ApiConstants.ID)
+ @Param(description = "device id of the Aviz ONES provider")
+ private String id;
+
+ @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID)
+ @Param(description = "the physical network this Aviz ONES provider belongs to")
+ private String physicalNetworkId;
+
+ @SerializedName(ApiConstants.PROVIDER)
+ @Param(description = "name of the provider")
+ private String providerName;
+
+ @SerializedName("devicename")
+ @Param(description = "device name")
+ private String deviceName;
+
+ @SerializedName("url")
+ @Param(description = "the Aviz ONES controller URL")
+ private String url;
+
+ @SerializedName("fabricname")
+ @Param(description = "the Aviz ONES fabric name this provider orchestrates tenants on")
+ private String fabricName;
+
+ @SerializedName("gatewayurl")
+ @Param(description = "Aviz Gateway REST API")
+ private String gatewayUrl;
+
+ @SerializedName("gatewaytokenset")
+ @Param(description = "whether a gateway API token is stored")
+ private Boolean gatewayTokenSet;
+
+ public void setGatewayUrl(final String v) {
+ gatewayUrl = v;
+ }
+
+ public void setGatewayTokenSet(final Boolean v) {
+ gatewayTokenSet = v;
+ }
+
+ public void setId(final String id) {
+ this.id = id;
+ }
+
+ public void setPhysicalNetworkId(final String physicalNetworkId) {
+ this.physicalNetworkId = physicalNetworkId;
+ }
+
+ public void setProviderName(final String providerName) {
+ this.providerName = providerName;
+ }
+
+ public void setDeviceName(final String deviceName) {
+ this.deviceName = deviceName;
+ }
+
+ public void setUrl(final String url) {
+ this.url = url;
+ }
+
+ public void setFabricName(final String fabricName) {
+ this.fabricName = fabricName;
+ }
+}
diff --git a/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/client/AvizGatewayClient.java b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/client/AvizGatewayClient.java
new file mode 100644
index 000000000000..e543b3b04d78
--- /dev/null
+++ b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/client/AvizGatewayClient.java
@@ -0,0 +1,409 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.apache.cloudstack.network.ones.client;
+
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.security.KeyStore;
+import java.security.SecureRandom;
+import java.security.cert.CertificateFactory;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.TrustManagerFactory;
+
+import org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand.FirewallRule;
+import org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand.PortMapping;
+import org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand.Vip;
+import org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand;
+import org.apache.cloudstack.network.ones.agent.api.RemoveOnesEdgeCommand;
+import org.apache.http.HttpEntity;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpDelete;
+import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.client.methods.HttpPut;
+import org.apache.http.client.methods.HttpRequestBase;
+import org.apache.http.client.utils.URIBuilder;
+import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.util.EntityUtils;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+
+/**
+ * Client for the Aviz Gateway REST API (/api/v1): a ONES tenant's edge, i.e. its internet access
+ * (outbound translation and port forwards), load-balancer VIPs and firewall rules. The tenant
+ * itself reaches the gateway through ONES; this adds what CloudStack decides on top of it.
+ * Authenticates with a gateway API token (role operator); TLS is always verified.
+ *
+ * Only what this plugin made is ever changed or removed: VIPs named {@value #VIP_PREFIX}... and
+ * firewall rules named after the tenant plus {@value #FIREWALL_INFIX}..., so rules an operator
+ * adds by hand stay.
+ */
+public class AvizGatewayClient {
+
+ private static final Logger LOG = LogManager.getLogger(AvizGatewayClient.class);
+
+ public static final String VIP_PREFIX = "cs-lb-";
+ public static final String FIREWALL_INFIX = "-fw-";
+ /** Outbound translation sessions one tenant may hold on the gateway. */
+ static final int SESSION_LIMIT = 10000;
+
+ private final String base;
+ private final String token;
+ private final CloseableHttpClient http;
+ long tenantWaitMs = 180_000;
+ long tenantPollMs = 5_000;
+
+ public AvizGatewayClient(final String url, final String token, final String caCertPath) {
+ this.base = (url.endsWith("/") ? url.substring(0, url.length() - 1) : url) + "/api/v1";
+ this.token = token;
+ try {
+ SSLContext ssl = SSLContext.getInstance("TLS");
+ TrustManagerFactory tmf = null;
+ if (caCertPath != null) {
+ KeyStore ks = KeyStore.getInstance("PKCS12");
+ ks.load(null, null);
+ try (InputStream in = new FileInputStream(caCertPath)) {
+ int i = 0;
+ for (java.security.cert.Certificate c : CertificateFactory.getInstance("X.509").generateCertificates(in)) {
+ ks.setCertificateEntry("gw-" + i++, c);
+ }
+ }
+ tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
+ tmf.init(ks);
+ }
+ ssl.init(null, tmf != null ? tmf.getTrustManagers() : null, new SecureRandom());
+ this.http = HttpClients.custom()
+ .setSSLSocketFactory(new SSLConnectionSocketFactory(ssl))
+ .setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(10000).setSocketTimeout(60000).build())
+ .build();
+ } catch (Exception e) {
+ throw new CloudRuntimeException("Failed to set up the Aviz Gateway client: " + e.getMessage(), e);
+ }
+ }
+
+ // ---------------------------------------------------------------- commands
+
+ /**
+ * Makes the tenant's edge on the gateway what the command says. Order keeps nothing open by
+ * accident: the firewall rules go first, then the mappings and VIPs, and stale rules last.
+ */
+ public Answer configureEdge(final ConfigureOnesEdgeCommand cmd) {
+ String tenant = cmd.getTenantName();
+ try {
+ boolean healthChecks = hasLoopback(waitForTenant(tenant));
+ Set wantedRules = new HashSet<>();
+ for (FirewallRule r : cmd.getFirewallRules()) {
+ putFirewallRule(tenant, r);
+ wantedRules.add(r.getName());
+ }
+ if (cmd.getSourceNatAddress() != null) {
+ putInternetAccess(tenant, cmd.getSourceNatAddress(), cmd.getPortMappings());
+ } else {
+ if (!cmd.getPortMappings().isEmpty()) {
+ throw new IOException("port forwards need the network's source NAT address, and it has none");
+ }
+ deleteInternetAccess(tenant);
+ }
+ if (!healthChecks && !cmd.getVips().isEmpty()) {
+ LOG.info("ONES tenant {} has no loopback on the Aviz Gateway, which its health probes need: its VIP members are not "
+ + "health-checked until the tenant gets one", tenant);
+ }
+ syncVips(tenant, cmd.getVips(), healthChecks);
+ for (String name : firewallRuleNames(tenant)) {
+ if (!wantedRules.contains(name)) {
+ deleteFirewallRule(name);
+ }
+ }
+ LOG.info("Aviz Gateway edge of ONES tenant {}: source NAT {}, {} port mapping(s), {} VIP(s), {} firewall rule(s)",
+ tenant, cmd.getSourceNatAddress(), cmd.getPortMappings().size(), cmd.getVips().size(), cmd.getFirewallRules().size());
+ return new Answer(cmd, true, null);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ return new Answer(cmd, false, "interrupted while configuring the Aviz Gateway for ONES tenant " + tenant);
+ } catch (Exception e) {
+ LOG.warn("Could not configure the Aviz Gateway for ONES tenant {}: {}", tenant, e.getMessage());
+ return new Answer(cmd, false, "Aviz Gateway, ONES tenant " + tenant + ": " + e.getMessage());
+ }
+ }
+
+ /** Takes the tenant's edge away: mappings and VIPs first, then the rules that guarded them. */
+ public Answer removeEdge(final RemoveOnesEdgeCommand cmd) {
+ String tenant = cmd.getTenantName();
+ try {
+ deleteInternetAccess(tenant);
+ for (String name : vipNames(tenant)) {
+ deleteVip(tenant, name);
+ }
+ for (String name : firewallRuleNames(tenant)) {
+ deleteFirewallRule(name);
+ }
+ LOG.info("Aviz Gateway edge of ONES tenant {} removed", tenant);
+ return new Answer(cmd, true, null);
+ } catch (Exception e) {
+ LOG.warn("Could not remove the Aviz Gateway edge of ONES tenant {}: {}", tenant, e.getMessage());
+ return new Answer(cmd, false, "Aviz Gateway, ONES tenant " + tenant + ": " + e.getMessage());
+ }
+ }
+
+ // ---------------------------------------------------------------- tenant
+
+ /** ONES puts the tenant on the gateway (FM tenant webhook) once a server joined it: wait for that. */
+ JsonObject waitForTenant(final String tenant) throws IOException, InterruptedException {
+ long deadline = System.currentTimeMillis() + tenantWaitMs;
+ while (true) {
+ Reply r = call(new HttpGet(base + "/tenants/" + tenant));
+ if (r.status == 200) {
+ JsonElement root = parse(r.body);
+ return root != null && root.isJsonObject() ? root.getAsJsonObject() : new JsonObject();
+ }
+ if (r.status != 404) {
+ throw new IOException("GET tenant " + tenant + ": HTTP " + r.status + ": " + abbreviate(r.body));
+ }
+ if (System.currentTimeMillis() > deadline) {
+ throw new IOException("the gateway does not have the tenant after " + tenantWaitMs / 1000
+ + " s (ONES puts it there once a server joined it)");
+ }
+ Thread.sleep(tenantPollMs);
+ }
+ }
+
+ /**
+ * The gateway health-checks VIP members from the tenant's loopback; an EVPN tenant without one
+ * (ONES does not always give it one) refuses health checks, so its VIPs go without.
+ */
+ static boolean hasLoopback(final JsonObject tenant) {
+ return tenant.has("loopback") && !tenant.get("loopback").isJsonNull() && !tenant.get("loopback").getAsString().isEmpty();
+ }
+
+ // ---------------------------------------------------------------- internet access
+
+ void putInternetAccess(final String tenant, final String sourceNatAddress, final List mappings) throws IOException {
+ JsonObject body = new JsonObject();
+ body.addProperty("enabled", true);
+ JsonArray pool = new JsonArray();
+ pool.add(sourceNatAddress);
+ body.add("pool", pool);
+ body.addProperty("session_limit", SESSION_LIMIT);
+ body.addProperty("announce_pool", true);
+ JsonArray elastic = new JsonArray();
+ for (PortMapping m : mappings) {
+ JsonObject e = new JsonObject();
+ e.addProperty("external", m.getExternal());
+ e.addProperty("local", m.getLocal());
+ e.addProperty("protocol", m.getProtocol());
+ e.addProperty("external_port", m.getExternalPort());
+ e.addProperty("local_port", m.getLocalPort());
+ e.addProperty("announce", true);
+ elastic.add(e);
+ }
+ body.add("elastic_ips", elastic);
+ expectOk(send(new HttpPut(base + "/tenants/" + tenant + "/internet-access"), body), "internet access");
+ }
+
+ void deleteInternetAccess(final String tenant) throws IOException {
+ Reply r = call(new HttpDelete(base + "/tenants/" + tenant + "/internet-access"));
+ if (r.status != 404) {
+ expectOk(r, "remove internet access");
+ }
+ }
+
+ // ---------------------------------------------------------------- VIPs
+
+ List vipNames(final String tenant) throws IOException {
+ Reply r = call(new HttpGet(base + "/tenants/" + tenant + "/lb/vips"));
+ if (r.status == 404) {
+ return new ArrayList<>();
+ }
+ expectOk(r, "list VIPs");
+ return names(r.body, VIP_PREFIX);
+ }
+
+ void syncVips(final String tenant, final List wanted, final boolean healthChecks) throws IOException {
+ Set have = new HashSet<>(vipNames(tenant));
+ Set keep = new HashSet<>();
+ for (Vip v : wanted) {
+ keep.add(v.getName());
+ }
+ for (String name : have) {
+ if (!keep.contains(name)) {
+ deleteVip(tenant, name);
+ }
+ }
+ for (Vip v : wanted) {
+ JsonObject body = new JsonObject();
+ body.addProperty("name", v.getName());
+ body.addProperty("address", v.getAddress());
+ body.addProperty("port", v.getPort());
+ body.addProperty("protocol", v.getProtocol());
+ body.addProperty("backend_port", v.getBackendPort());
+ JsonArray backends = new JsonArray();
+ for (String b : v.getBackends()) {
+ JsonObject o = new JsonObject();
+ o.addProperty("address", b);
+ backends.add(o);
+ }
+ body.add("backends", backends);
+ body.addProperty("src_ip_sticky", v.isSourceSticky());
+ if (!healthChecks) {
+ JsonObject none = new JsonObject();
+ none.addProperty("type", "none");
+ body.add("health", none);
+ }
+ body.addProperty("announce", true);
+ HttpEntityEnclosingRequestBase req = have.contains(v.getName())
+ ? new HttpPut(base + "/tenants/" + tenant + "/lb/vips/" + v.getName())
+ : new HttpPost(base + "/tenants/" + tenant + "/lb/vips");
+ expectOk(send(req, body), "VIP " + v);
+ }
+ }
+
+ void deleteVip(final String tenant, final String name) throws IOException {
+ Reply r = call(new HttpDelete(base + "/tenants/" + tenant + "/lb/vips/" + name));
+ if (r.status != 404) {
+ expectOk(r, "delete VIP " + name);
+ }
+ }
+
+ // ---------------------------------------------------------------- firewall
+
+ /** The plugin's rules of this tenant (rule names are global on the gateway, so they carry the tenant). */
+ List firewallRuleNames(final String tenant) throws IOException {
+ URIBuilder uri;
+ try {
+ uri = new URIBuilder(base + "/firewall/rules").addParameter("tenant", tenant);
+ Reply r = call(new HttpGet(uri.build()));
+ expectOk(r, "list firewall rules");
+ return names(r.body, tenant + FIREWALL_INFIX);
+ } catch (java.net.URISyntaxException e) {
+ throw new IOException(e);
+ }
+ }
+
+ void putFirewallRule(final String tenant, final FirewallRule rule) throws IOException {
+ JsonObject body = new JsonObject();
+ body.addProperty("name", rule.getName());
+ body.addProperty("tenant", tenant);
+ body.addProperty("src", rule.getSource());
+ body.addProperty("dst", rule.getDestination());
+ body.addProperty("protocol", rule.getProtocol());
+ body.addProperty("dst_ports", String.valueOf(rule.getPort()));
+ body.addProperty("action", rule.isPermit() ? "permit" : "deny");
+ body.addProperty("established", rule.isPermit()); // stateful permits; the gateway refuses it on a deny
+ body.addProperty("comment", "CloudStack");
+ expectOk(send(new HttpPut(base + "/firewall/rules/" + rule.getName()), body), "firewall rule " + rule);
+ }
+
+ void deleteFirewallRule(final String name) throws IOException {
+ Reply r = call(new HttpDelete(base + "/firewall/rules/" + name));
+ if (r.status != 404) {
+ expectOk(r, "delete firewall rule " + name);
+ }
+ }
+
+ // ---------------------------------------------------------------- HTTP
+
+ static final class Reply {
+ final int status;
+ final String body;
+
+ Reply(final int status, final String body) {
+ this.status = status;
+ this.body = body;
+ }
+ }
+
+ private Reply send(final HttpEntityEnclosingRequestBase req, final JsonObject body) throws IOException {
+ req.setEntity(new StringEntity(body.toString(), "UTF-8"));
+ return call(req);
+ }
+
+ private Reply call(final HttpRequestBase req) throws IOException {
+ req.setHeader("Authorization", "Bearer " + token);
+ req.setHeader("Content-Type", "application/json");
+ req.setHeader("Accept", "application/json");
+ try (CloseableHttpResponse r = http.execute(req)) {
+ HttpEntity e = r.getEntity();
+ return new Reply(r.getStatusLine().getStatusCode(), e != null ? EntityUtils.toString(e) : "");
+ }
+ }
+
+ /**
+ * 2xx, and a change the gateway could apply: a write answers with its apply report, and
+ * "failed" > 0 there means the gateway stored the intent but could not program it.
+ */
+ private static void expectOk(final Reply r, final String what) throws IOException {
+ if (r.status < 200 || r.status > 299) {
+ throw new IOException(what + ": HTTP " + r.status + ": " + abbreviate(r.body));
+ }
+ JsonElement root = parse(r.body);
+ if (root != null && root.isJsonObject() && root.getAsJsonObject().has("failed")
+ && root.getAsJsonObject().get("failed").isJsonPrimitive() && root.getAsJsonObject().get("failed").getAsInt() > 0) {
+ throw new IOException(what + ": the gateway could not apply it: " + abbreviate(r.body));
+ }
+ }
+
+ private static JsonElement parse(final String body) {
+ try {
+ return body == null || body.isEmpty() ? null : JsonParser.parseString(body);
+ } catch (Exception e) {
+ return null;
+ }
+ }
+
+ /** The "name" of every object in a JSON array that starts with the prefix. */
+ static List names(final String body, final String prefix) {
+ List out = new ArrayList<>();
+ JsonElement root = parse(body);
+ if (root == null || !root.isJsonArray()) {
+ return out;
+ }
+ for (JsonElement e : root.getAsJsonArray()) {
+ if (e.isJsonObject() && e.getAsJsonObject().has("name")) {
+ String n = e.getAsJsonObject().get("name").getAsString();
+ if (n.startsWith(prefix)) {
+ out.add(n);
+ }
+ }
+ }
+ return out;
+ }
+
+ private static String abbreviate(final CharSequence s) {
+ return s.length() > 300 ? s.subSequence(0, 300) + "..." : s.toString();
+ }
+}
diff --git a/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/client/OnesApiClient.java b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/client/OnesApiClient.java
new file mode 100644
index 000000000000..5f82dbb1641b
--- /dev/null
+++ b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/client/OnesApiClient.java
@@ -0,0 +1,48 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.apache.cloudstack.network.ones.client;
+
+import org.apache.cloudstack.network.ones.agent.api.AllocateOnesServersCommand;
+import org.apache.cloudstack.network.ones.agent.api.CreateOnesTenantAnswer;
+import org.apache.cloudstack.network.ones.agent.api.CreateOnesTenantCommand;
+import org.apache.cloudstack.network.ones.agent.api.DeallocateOnesServersCommand;
+import org.apache.cloudstack.network.ones.agent.api.DeleteOnesTenantCommand;
+
+import com.cloud.agent.api.Answer;
+
+/**
+ * REST client for the Aviz ONES Fabric Manager tenant API: logs in with a ONES user and sends
+ * the session token as a bearer token over verified TLS, optionally with a client certificate.
+ */
+public interface OnesApiClient {
+
+ CreateOnesTenantAnswer createTenant(CreateOnesTenantCommand cmd);
+
+ Answer deleteTenant(DeleteOnesTenantCommand cmd);
+
+ Answer allocateServers(AllocateOnesServersCommand cmd);
+
+ Answer deallocateServers(DeallocateOnesServersCommand cmd);
+
+ /**
+ * GET /fabrics - used as a lightweight reachability/credential check when a provider is registered.
+ */
+ boolean isReachable();
+}
diff --git a/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/client/OnesApiClientImpl.java b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/client/OnesApiClientImpl.java
new file mode 100644
index 000000000000..70ebd3d53201
--- /dev/null
+++ b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/client/OnesApiClientImpl.java
@@ -0,0 +1,585 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.apache.cloudstack.network.ones.client;
+
+import java.io.FileInputStream;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.security.KeyStore;
+import java.security.PrivateKey;
+import java.security.SecureRandom;
+import java.security.Security;
+import java.security.cert.CertificateFactory;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.TrustManagerFactory;
+
+import org.apache.cloudstack.network.ones.agent.api.AllocateOnesServersCommand;
+import org.apache.cloudstack.network.ones.agent.api.CreateOnesTenantAnswer;
+import org.apache.cloudstack.network.ones.agent.api.CreateOnesTenantCommand;
+import org.apache.cloudstack.network.ones.agent.api.DeallocateOnesServersCommand;
+import org.apache.cloudstack.network.ones.agent.api.DeleteOnesTenantCommand;
+import org.apache.http.HttpEntity;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpDelete;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPatch;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.client.methods.HttpRequestBase;
+import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.util.EntityUtils;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+import org.bouncycastle.jce.provider.BouncyCastleProvider;
+import org.bouncycastle.openssl.PEMKeyPair;
+import org.bouncycastle.openssl.PEMParser;
+import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.Command;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+
+/**
+ * Client for the ONES Fabric Manager (FM) tenant API.
+ *
+ * Auth: logs in with a user name and password at the ONES UI's login endpoint
+ * (POST https://<ones>/api/user/login, the same login the ONES UI and ones-gfx-sdk use) and
+ * sends the returned JWT as a Bearer token to FM (https://<ones>:8443). ONES JWTs are short
+ * lived, so on a 401 the client logs in again and retries once.
+ *
+ * Every state-changing call is made ASYNC ("Prefer: respond-async") and the client then polls
+ * GET /operations/{id} until it finishes. Besides not holding an HTTP request open for minutes,
+ * this matters for correctness: FM sends its tenant webhooks (which is how the edge gateway
+ * learns about a tenant) only for async operations.
+ */
+public class OnesApiClientImpl implements OnesApiClient {
+
+ private static final Logger LOG = LogManager.getLogger(OnesApiClientImpl.class);
+
+ private static final int CONNECT_TIMEOUT_MS = 15000;
+ private static final int SOCKET_TIMEOUT_MS = 120000;
+ static final long OPERATION_TIMEOUT_MS = 900_000;
+ static final long OPERATION_POLL_MS = 5_000;
+ private static final char[] KEYSTORE_PASSWORD = "avizones".toCharArray();
+
+ private final String fmUrl;
+ private final String loginUrl;
+ private final String username;
+ private final String password;
+ private final CloseableHttpClient httpClient;
+ private volatile String token;
+ long operationPollMs = OPERATION_POLL_MS;
+
+ public OnesApiClientImpl(final String fmUrl, final String loginUrl, final String username, final String password,
+ final String clientCertPath, final String clientKeyPath, final String caCertPath) {
+ this.fmUrl = stripSlash(fmUrl);
+ this.loginUrl = loginUrl;
+ this.username = username;
+ this.password = password;
+ this.httpClient = buildHttpClient(clientCertPath, clientKeyPath, caCertPath);
+ }
+
+ private static String stripSlash(final String url) {
+ return url.endsWith("/") ? url.substring(0, url.length() - 1) : url;
+ }
+
+ // ---------------------------------------------------------------- TLS
+
+ private CloseableHttpClient buildHttpClient(final String clientCertPath, final String clientKeyPath, final String caCertPath) {
+ try {
+ if (Security.getProvider("BC") == null) {
+ Security.addProvider(new BouncyCastleProvider());
+ }
+ // Optional mTLS client certificate; optional CA bundle (else the JVM trust store).
+ // Host names are always verified: ONES's stock certificate names "ones-fm" and
+ // "localhost", not an IP, so point the URLs at a name the certificate carries.
+ KeyManager[] keyManagers = (clientCertPath != null && clientKeyPath != null)
+ ? buildKeyManagers(clientCertPath, clientKeyPath) : null;
+ TrustManager[] trustManagers = (caCertPath != null) ? buildTrustManagers(caCertPath) : null;
+
+ SSLContext sslContext = SSLContext.getInstance("TLS");
+ sslContext.init(keyManagers, trustManagers, new SecureRandom());
+
+ RequestConfig requestConfig = RequestConfig.custom()
+ .setConnectTimeout(CONNECT_TIMEOUT_MS)
+ .setSocketTimeout(SOCKET_TIMEOUT_MS)
+ .build();
+ return HttpClients.custom()
+ .setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext))
+ .setDefaultRequestConfig(requestConfig)
+ .build();
+ } catch (Exception e) {
+ throw new CloudRuntimeException("Failed to initialize the HTTPS client for Aviz ONES: " + e.getMessage(), e);
+ }
+ }
+
+ private KeyManager[] buildKeyManagers(final String certPath, final String keyPath) throws Exception {
+ CertificateFactory cf = CertificateFactory.getInstance("X.509");
+ X509Certificate clientCert;
+ try (InputStream in = new FileInputStream(certPath)) {
+ clientCert = (X509Certificate) cf.generateCertificate(in);
+ }
+ PrivateKey privateKey;
+ try (PEMParser pemParser = new PEMParser(new FileReader(keyPath))) {
+ Object obj = pemParser.readObject();
+ JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
+ if (obj instanceof PEMKeyPair) {
+ privateKey = converter.getKeyPair((PEMKeyPair) obj).getPrivate();
+ } else if (obj instanceof org.bouncycastle.asn1.pkcs.PrivateKeyInfo) {
+ privateKey = converter.getPrivateKey((org.bouncycastle.asn1.pkcs.PrivateKeyInfo) obj);
+ } else {
+ throw new CloudRuntimeException("Unsupported (or encrypted) private key format in " + keyPath);
+ }
+ }
+ KeyStore keyStore = KeyStore.getInstance("PKCS12");
+ keyStore.load(null, null);
+ keyStore.setKeyEntry("ones-client", privateKey, KEYSTORE_PASSWORD, new X509Certificate[]{clientCert});
+ KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
+ kmf.init(keyStore, KEYSTORE_PASSWORD);
+ return kmf.getKeyManagers();
+ }
+
+ private TrustManager[] buildTrustManagers(final String caCertPath) throws Exception {
+ CertificateFactory cf = CertificateFactory.getInstance("X.509");
+ KeyStore trustStore = KeyStore.getInstance("PKCS12");
+ trustStore.load(null, null);
+ try (InputStream in = new FileInputStream(caCertPath)) {
+ int i = 0;
+ for (java.security.cert.Certificate c : cf.generateCertificates(in)) {
+ trustStore.setCertificateEntry("ones-ca-" + i++, c);
+ }
+ }
+ TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
+ tmf.init(trustStore);
+ return tmf.getTrustManagers();
+ }
+
+ // ---------------------------------------------------------------- HTTP
+
+ /** HTTP status + body. */
+ static final class Reply {
+ final int status;
+ final String body;
+
+ Reply(final int status, final String body) {
+ this.status = status;
+ this.body = body;
+ }
+
+ boolean ok() {
+ return status >= 200 && status < 300;
+ }
+ }
+
+ private Reply send(final HttpRequestBase request) throws IOException {
+ request.setHeader("Content-Type", "application/json");
+ request.setHeader("Accept", "application/json");
+ try (CloseableHttpResponse response = httpClient.execute(request)) {
+ HttpEntity entity = response.getEntity();
+ return new Reply(response.getStatusLine().getStatusCode(), entity != null ? EntityUtils.toString(entity) : "");
+ }
+ }
+
+ private synchronized String login() throws IOException {
+ HttpPost post = new HttpPost(loginUrl);
+ JsonObject body = new JsonObject();
+ body.addProperty("username", username);
+ body.addProperty("password", password);
+ post.setEntity(new StringEntity(body.toString(), "UTF-8"));
+ Reply r = send(post);
+ if (!r.ok()) {
+ throw new IOException("ONES login at " + loginUrl + " as " + username + " failed: HTTP " + r.status);
+ }
+ JsonObject data = asObject(parse(r.body), "data");
+ String t = data != null ? str(data, "token") : null;
+ if (t == null) {
+ throw new IOException("ONES login at " + loginUrl + " returned no token");
+ }
+ token = t;
+ return t;
+ }
+
+ /** One FM call with the Bearer token; logs in first if needed and once more on a 401. */
+ Reply call(final HttpRequestBase request, final boolean async) throws IOException {
+ if (async) {
+ request.setHeader("Prefer", "respond-async");
+ }
+ for (int attempt = 0; ; attempt++) {
+ String t = token != null ? token : login();
+ request.setHeader("Authorization", "Bearer " + t);
+ Reply r = send(request);
+ if (r.status == 401 && attempt == 0) {
+ token = null;
+ continue;
+ }
+ return r;
+ }
+ }
+
+ private Reply callOk(final HttpRequestBase request, final boolean async, final String what) throws IOException {
+ Reply r = call(request, async);
+ if (!r.ok()) {
+ throw new IOException(what + ": ONES returned HTTP " + r.status + ": " + abbreviate(r.body));
+ }
+ return r;
+ }
+
+ /**
+ * Waits for the async operation an FM reply names, if any. FM wraps replies as
+ * {success, message, data} where data is an object or a JSON-encoded string.
+ */
+ void awaitOperation(final Reply reply, final String what) throws IOException {
+ String op = findOperationId(parse(reply.body));
+ if (op == null) {
+ return; // FM answered synchronously
+ }
+ long deadline = System.currentTimeMillis() + OPERATION_TIMEOUT_MS;
+ while (System.currentTimeMillis() < deadline) {
+ Reply r = callOk(new HttpGet(fmUrl + "/operations/" + op), false, what + " (operation " + op + ")");
+ JsonElement root = parse(r.body);
+ JsonObject o = asObject(root, "data");
+ if (o == null && root != null && root.isJsonObject()) {
+ o = root.getAsJsonObject();
+ }
+ String status = o != null ? str(o, "status") : null;
+ if ("SUCCESS".equals(status)) {
+ return;
+ }
+ if ("FAILED".equals(status) || "CANCELLED".equals(status)) {
+ throw new IOException(what + ": ONES operation " + op + " " + status + ": " + abbreviate(String.valueOf(str(o, "errorMessage"))));
+ }
+ try {
+ Thread.sleep(operationPollMs);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new IOException(what + ": interrupted waiting for ONES operation " + op);
+ }
+ }
+ throw new IOException(what + ": ONES operation " + op + " did not finish in " + OPERATION_TIMEOUT_MS / 1000 + " s");
+ }
+
+ private static String findOperationId(final JsonElement root) {
+ if (root == null || !root.isJsonObject()) {
+ return null;
+ }
+ JsonObject o = root.getAsJsonObject();
+ String id = str(o, "operationId");
+ if (id != null) {
+ return id;
+ }
+ JsonObject data = asObject(root, "data");
+ return data != null ? str(data, "operationId") : null;
+ }
+
+ // ---------------------------------------------------------------- API
+
+ @Override
+ public boolean isReachable() {
+ try {
+ callOk(new HttpGet(fmUrl + "/getAllFabrics"), false, "list fabrics");
+ return true;
+ } catch (Exception e) {
+ LOG.warn("Aviz ONES at {} is not reachable: {}", fmUrl, e.getMessage());
+ return false;
+ }
+ }
+
+ @Override
+ public CreateOnesTenantAnswer createTenant(final CreateOnesTenantCommand cmd) {
+ String what = "create ONES tenant " + cmd.getTenantName() + " on fabric " + cmd.getFabricName();
+ try {
+ JsonObject tenant = getTenant(cmd.getFabricName(), cmd.getTenantName());
+ if (tenant == null) {
+ JsonObject body = new JsonObject();
+ body.addProperty("tenantName", cmd.getTenantName());
+ body.addProperty("description", cmd.getDescription() != null ? cmd.getDescription() : "");
+ body.addProperty("maxGpusAllowed", cmd.getMaxGpusAllowed());
+ // no tenant-level "shared": ONES refuses it unless the fabric is externally
+ // controlled; sharing is per server (see patchServers)
+ HttpPost post = new HttpPost(fmUrl + "/fabrics/" + cmd.getFabricName() + "/tenants");
+ post.setEntity(new StringEntity(body.toString(), "UTF-8"));
+ awaitOperation(callOk(post, true, what), what);
+ tenant = getTenant(cmd.getFabricName(), cmd.getTenantName());
+ }
+ if (tenant == null) {
+ throw new IOException(what + ": the tenant is not there after the create finished");
+ }
+ String gateway = null;
+ String pool = str(tenant, "tenantIpPool");
+ JsonObject vnets = asObject(tenant, "vnets");
+ JsonObject ipPool = vnets != null ? asObject(vnets, "tenant IP Pool") : null;
+ if (ipPool != null) {
+ gateway = stripPrefix(str(ipPool, "gateway"));
+ pool = pool != null ? pool : str(ipPool, "subnet");
+ }
+ return new CreateOnesTenantAnswer(cmd, tenant.toString(), integer(tenant, "vlanId"), integer(tenant, "vniId"),
+ integer(tenant, "nsVniId"), str(tenant, "vlanSubnetCPU"), pool, gateway);
+ } catch (Exception e) {
+ LOG.error("Failed to {}: {}", what, e.getMessage());
+ return new CreateOnesTenantAnswer(cmd, e);
+ }
+ }
+
+ /** GET /fabrics/{f}/tenants/{t}: the tenant record, or null if there is none. */
+ JsonObject getTenant(final String fabric, final String tenant) throws IOException {
+ Reply r = call(new HttpGet(fmUrl + "/fabrics/" + fabric + "/tenants/" + tenant), false);
+ if (r.status == 404) {
+ return null;
+ }
+ if (!r.ok()) {
+ throw new IOException("get ONES tenant " + tenant + ": HTTP " + r.status + ": " + abbreviate(r.body));
+ }
+ JsonElement root = parse(r.body);
+ JsonObject t = asObject(root, "tenant");
+ if (t == null) {
+ JsonObject data = asObject(root, "data");
+ t = data != null ? asObject(data, "tenant") : null;
+ }
+ return t;
+ }
+
+ @Override
+ public Answer deleteTenant(final DeleteOnesTenantCommand cmd) {
+ String what = "delete ONES tenant " + cmd.getTenantName() + " on fabric " + cmd.getFabricName();
+ try {
+ Reply r = call(new HttpDelete(fmUrl + "/fabrics/" + cmd.getFabricName() + "/tenants/" + cmd.getTenantName()), true);
+ if (r.status == 404) {
+ return new Answer(cmd, true, "already gone");
+ }
+ if (!r.ok()) {
+ throw new IOException(what + ": HTTP " + r.status + ": " + abbreviate(r.body));
+ }
+ awaitOperation(r, what);
+ return new Answer(cmd, true, r.body);
+ } catch (Exception e) {
+ LOG.error("Failed to {}: {}", what, e.getMessage());
+ return new Answer(cmd, e);
+ }
+ }
+
+ @Override
+ public Answer allocateServers(final AllocateOnesServersCommand cmd) {
+ Answer added = patchServers(cmd, cmd.getFabricName(), cmd.getTenantName(), "ADD", cmd.getServerNames(), cmd.isShared());
+ if (!added.getResult()) {
+ return added;
+ }
+ // Behind a DPU (HBN fabric) the tenant ends at the DPU: the server joining the tenant puts
+ // the tenant's VRF/VLAN/SVI on its DPU, and one host-facing DPU port (a "VF") carries the
+ // tenant to the hypervisor, untagged. A hypervisor holds several tenants, so each tenant
+ // gets its own VF on every server it uses.
+ String what = "DPU VF for ONES tenant " + cmd.getTenantName() + " on " + cmd.getServerNames();
+ try {
+ for (String server : cmd.getServerNames()) {
+ assignDpuVf(cmd.getFabricName(), server, cmd.getTenantName());
+ }
+ return added;
+ } catch (Exception e) {
+ LOG.error("Failed to assign {}: {}", what, e.getMessage());
+ return new Answer(cmd, e);
+ }
+ }
+
+ /**
+ * Servers leave a tenant the way OnesElement adds them: shared. (A server given to one tenant
+ * exclusively would be added with shared=false; this plugin never does that.) Their DPU VFs for
+ * the tenant are released first.
+ */
+ @Override
+ public Answer deallocateServers(final DeallocateOnesServersCommand cmd) {
+ for (String server : cmd.getServerNames()) {
+ try {
+ releaseDpuVfs(cmd.getFabricName(), server, cmd.getTenantName());
+ } catch (Exception e) {
+ // keep the server in the tenant: removing it now would leave its VF assigned for good
+ LOG.error("Releasing the DPU VFs of {} on ONES tenant {} failed; the server stays in the tenant: {}",
+ server, cmd.getTenantName(), e.getMessage());
+ return new Answer(cmd, false, "could not release the DPU VFs of " + server + " on ONES tenant " + cmd.getTenantName()
+ + ": " + e.getMessage());
+ }
+ }
+ return patchServers(cmd, cmd.getFabricName(), cmd.getTenantName(), "DELETE", cmd.getServerNames(), true);
+ }
+
+ /**
+ * The server's DPU VFs as FM lists them; empty when the server has no DPU (FM answers an empty
+ * "dpus" list) or FM has no VF API (404). Any other failure is an error: taking it for "no DPU"
+ * would add the server to the tenant without the VF its traffic needs.
+ */
+ List dpuVfs(final String fabric, final String server) throws IOException {
+ List vfs = new ArrayList<>();
+ Reply r = call(new HttpGet(fmUrl + "/fabrics/" + fabric + "/servers/" + server + "/vf-interfaces"), false);
+ if (r.status == 404) {
+ return vfs;
+ }
+ if (!r.ok()) {
+ throw new IOException("list the DPU VFs of " + server + ": ONES returned HTTP " + r.status + ": " + abbreviate(r.body));
+ }
+ JsonElement root = parse(r.body);
+ JsonObject o = root != null && root.isJsonObject() ? root.getAsJsonObject() : null;
+ JsonObject data = asObject(root, "data");
+ if (data != null && data.has("dpus")) {
+ o = data;
+ }
+ if (o == null || !o.has("dpus") || !o.get("dpus").isJsonArray()) {
+ return vfs;
+ }
+ for (JsonElement dpu : o.getAsJsonArray("dpus")) {
+ if (dpu.isJsonObject() && dpu.getAsJsonObject().has("vfInterfaces")) {
+ for (JsonElement vf : dpu.getAsJsonObject().getAsJsonArray("vfInterfaces")) {
+ if (vf.isJsonObject()) {
+ vfs.add(vf.getAsJsonObject());
+ }
+ }
+ }
+ }
+ return vfs;
+ }
+
+ /** Gives the tenant one VF on the server's DPU, unless it has one already. */
+ void assignDpuVf(final String fabric, final String server, final String tenant) throws IOException {
+ List vfs = dpuVfs(fabric, server);
+ if (vfs.isEmpty()) {
+ return; // no DPU: the leaf carries the tenant (trunked by the server ADD)
+ }
+ JsonObject free = null;
+ for (JsonObject vf : vfs) {
+ if ("provisioned".equalsIgnoreCase(str(vf, "status")) && tenant.equals(str(vf, "tenantName"))) {
+ LOG.info("ONES tenant {} already has DPU VF {} ({}) on {}", tenant, str(vf, "ifName"), str(vf, "serverIf"), server);
+ return;
+ }
+ if (free == null && "free".equalsIgnoreCase(str(vf, "status"))) {
+ free = vf;
+ }
+ }
+ if (free == null) {
+ throw new IOException("server " + server + " has no free DPU VF for ONES tenant " + tenant
+ + " (each tenant on a hypervisor needs its own VF)");
+ }
+ String what = "assign DPU VF " + str(free, "ifName") + " (" + str(free, "serverIf") + ") of " + server + " to ONES tenant " + tenant;
+ JsonObject body = new JsonObject();
+ body.addProperty("tenantName", tenant);
+ HttpPost post = new HttpPost(fmUrl + "/fabrics/" + fabric + "/servers/" + server + "/vf-interfaces/" + str(free, "ifName") + "/assign");
+ post.setEntity(new StringEntity(body.toString(), "UTF-8"));
+ Reply r = call(post, false);
+ if (!r.ok() && r.status != 207) { // 207: VF assigned, the host IP step (unused here) reported a problem
+ throw new IOException(what + ": ONES returned HTTP " + r.status + ": " + abbreviate(r.body));
+ }
+ LOG.info("{}: HTTP {}", what, r.status);
+ }
+
+ /** Returns every VF the tenant holds on the server's DPU. */
+ void releaseDpuVfs(final String fabric, final String server, final String tenant) throws IOException {
+ for (JsonObject vf : dpuVfs(fabric, server)) {
+ if ("provisioned".equalsIgnoreCase(str(vf, "status")) && tenant.equals(str(vf, "tenantName"))) {
+ String what = "release DPU VF " + str(vf, "ifName") + " of " + server + " from ONES tenant " + tenant;
+ Reply r = call(new HttpDelete(fmUrl + "/fabrics/" + fabric + "/servers/" + server + "/vf-interfaces/" + str(vf, "ifName") + "/assign"), false);
+ if (!r.ok() && r.status != 404) {
+ throw new IOException(what + ": ONES returned HTTP " + r.status + ": " + abbreviate(r.body));
+ }
+ LOG.info("{}: HTTP {}", what, r.status);
+ }
+ }
+ }
+
+ /**
+ * PATCH a tenant's servers. "shared" means ONES trunks the tenant's VLAN on the server's leaf
+ * port next to other tenants' (a hypervisor carries many guest networks) instead of giving the
+ * port to this tenant alone.
+ */
+ private Answer patchServers(final Command cmd, final String fabric, final String tenant, final String operation,
+ final List serverNames, final boolean shared) {
+ String what = operation + (shared ? " shared" : " dedicated") + " servers " + serverNames + " on ONES tenant " + tenant;
+ try {
+ JsonObject body = new JsonObject();
+ body.addProperty("operation", operation);
+ JsonArray servers = new JsonArray();
+ for (String serverName : serverNames) {
+ JsonObject server = new JsonObject();
+ server.addProperty("serverName", serverName);
+ server.addProperty("shared", shared);
+ servers.add(server);
+ }
+ body.add("servers", servers);
+ HttpPatch patch = new HttpPatch(fmUrl + "/fabrics/" + fabric + "/tenants/" + tenant);
+ patch.setEntity(new StringEntity(body.toString(), "UTF-8"));
+ Reply r = callOk(patch, true, what);
+ awaitOperation(r, what);
+ return new Answer(cmd, true, r.body);
+ } catch (Exception e) {
+ LOG.error("Failed to {}: {}", what, e.getMessage());
+ return new Answer(cmd, e);
+ }
+ }
+
+ // ---------------------------------------------------------------- JSON helpers
+
+ static JsonElement parse(final String body) {
+ try {
+ return JsonParser.parseString(body);
+ } catch (Exception e) {
+ return null;
+ }
+ }
+
+ /** obj[field] as an object, decoding it first if FM sent it as a JSON-encoded string. */
+ static JsonObject asObject(final JsonElement root, final String field) {
+ if (root == null || !root.isJsonObject()) {
+ return null;
+ }
+ JsonElement e = root.getAsJsonObject().get(field);
+ if (e != null && e.isJsonPrimitive() && e.getAsJsonPrimitive().isString()) {
+ e = parse(e.getAsString());
+ }
+ return e != null && e.isJsonObject() ? e.getAsJsonObject() : null;
+ }
+
+ static String str(final JsonObject o, final String field) {
+ return o != null && o.has(field) && !o.get(field).isJsonNull() ? o.get(field).getAsString() : null;
+ }
+
+ static Integer integer(final JsonObject o, final String field) {
+ return o != null && o.has(field) && !o.get(field).isJsonNull() ? o.get(field).getAsInt() : null;
+ }
+
+ static String stripPrefix(final String cidr) {
+ if (cidr == null) {
+ return null;
+ }
+ int slash = cidr.indexOf('/');
+ return slash >= 0 ? cidr.substring(0, slash) : cidr;
+ }
+
+ private static String abbreviate(final String s) {
+ return s == null ? "" : s.length() > 300 ? s.substring(0, 300) + "..." : s;
+ }
+}
diff --git a/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/dao/OnesProviderDao.java b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/dao/OnesProviderDao.java
new file mode 100644
index 000000000000..ebbcc1e4dbbd
--- /dev/null
+++ b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/dao/OnesProviderDao.java
@@ -0,0 +1,31 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.apache.cloudstack.network.ones.dao;
+
+import java.util.List;
+
+import com.cloud.utils.db.GenericDao;
+
+public interface OnesProviderDao extends GenericDao {
+ /**
+ * List all Aviz ONES providers registered against this physical network.
+ */
+ List listByPhysicalNetwork(long physicalNetworkId);
+}
diff --git a/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/dao/OnesProviderDaoImpl.java b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/dao/OnesProviderDaoImpl.java
new file mode 100644
index 000000000000..9a874127e71e
--- /dev/null
+++ b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/dao/OnesProviderDaoImpl.java
@@ -0,0 +1,48 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.apache.cloudstack.network.ones.dao;
+
+import java.util.List;
+
+import org.springframework.stereotype.Component;
+
+import com.cloud.utils.db.GenericDaoBase;
+import com.cloud.utils.db.SearchBuilder;
+import com.cloud.utils.db.SearchCriteria.Op;
+import com.cloud.utils.db.SearchCriteria;
+
+@Component
+public class OnesProviderDaoImpl extends GenericDaoBase implements OnesProviderDao {
+
+ protected final SearchBuilder physicalNetworkIdSearch;
+
+ public OnesProviderDaoImpl() {
+ physicalNetworkIdSearch = createSearchBuilder();
+ physicalNetworkIdSearch.and("physicalNetworkId", physicalNetworkIdSearch.entity().getPhysicalNetworkId(), Op.EQ);
+ physicalNetworkIdSearch.done();
+ }
+
+ @Override
+ public List listByPhysicalNetwork(final long physicalNetworkId) {
+ SearchCriteria sc = physicalNetworkIdSearch.create();
+ sc.setParameters("physicalNetworkId", physicalNetworkId);
+ return search(sc, null);
+ }
+}
diff --git a/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/dao/OnesProviderVO.java b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/dao/OnesProviderVO.java
new file mode 100644
index 000000000000..b1bf3780dc8f
--- /dev/null
+++ b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/dao/OnesProviderVO.java
@@ -0,0 +1,214 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.apache.cloudstack.network.ones.dao;
+
+import java.util.UUID;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+import org.apache.cloudstack.api.InternalIdentity;
+
+import com.cloud.utils.db.Encrypt;
+
+/**
+ * Represents one registered Aviz ONES Spectrum-X fabric controller, bound to a physical
+ * network (mirrors how NiciraNvp/BigSwitch/Ovs controllers are registered in CloudStack 4.19),
+ * and represented internally as a pseudo-agent host ({@link org.apache.cloudstack.network.ones.resource.OnesResource}).
+ */
+@Entity
+@Table(name = "ones_providers")
+public class OnesProviderVO implements InternalIdentity {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ @Column(name = "id")
+ private long id;
+
+ @Column(name = "uuid")
+ private String uuid;
+
+ @Column(name = "host_id")
+ private long hostId;
+
+ @Column(name = "physical_network_id")
+ private long physicalNetworkId;
+
+ @Column(name = "provider_name")
+ private String providerName;
+
+ @Column(name = "device_name")
+ private String deviceName;
+
+ /** Base URL of the ONES Fabric Manager API, e.g. https://ones.example.com:8443 */
+ @Column(name = "url")
+ private String url;
+
+ /** Name of the ONES fabric this provider orchestrates tenants on. */
+ @Column(name = "fabric_name")
+ private String fabricName;
+
+ /** ONES login endpoint, e.g. https://ones.example.com/api/user/login. */
+ @Column(name = "login_url", length = 1024)
+ private String loginUrl;
+
+ /** ONES user the plugin logs in as. */
+ @Column(name = "username")
+ private String username;
+
+ /** That user's password, encrypted at rest with CloudStack's database key. */
+ @Column(name = "password", length = 1024)
+ @Encrypt
+ private String password;
+
+ /** Local filesystem paths to the mTLS client cert/key and CA bundle used to reach the controller. */
+ @Column(name = "client_cert_path", length = 1024)
+ private String clientCertPath;
+
+ @Column(name = "client_key_path", length = 1024)
+ private String clientKeyPath;
+
+ @Column(name = "ca_cert_path", length = 1024)
+ private String caCertPath;
+
+ /** Aviz Gateway REST API (e.g. https://gateway.example.com:8090); null = no internet access handling. */
+ @Column(name = "gateway_url", length = 1024)
+ private String gatewayUrl;
+
+ /** Its API token (role operator), encrypted at rest. */
+ @Column(name = "gateway_token", length = 1024)
+ @Encrypt
+ private String gatewayToken;
+
+ @Column(name = "gateway_ca_cert_path", length = 1024)
+ private String gatewayCaCertPath;
+
+ public OnesProviderVO() {
+ uuid = UUID.randomUUID().toString();
+ }
+
+ public OnesProviderVO(final long hostId, final long physicalNetworkId, final String providerName, final String deviceName,
+ final String url, final String fabricName, final String loginUrl, final String username, final String password,
+ final String clientCertPath, final String clientKeyPath, final String caCertPath) {
+ super();
+ this.hostId = hostId;
+ this.physicalNetworkId = physicalNetworkId;
+ this.providerName = providerName;
+ this.deviceName = deviceName;
+ this.url = url;
+ this.fabricName = fabricName;
+ this.loginUrl = loginUrl;
+ this.username = username;
+ this.password = password;
+ this.clientCertPath = clientCertPath;
+ this.clientKeyPath = clientKeyPath;
+ this.caCertPath = caCertPath;
+ uuid = UUID.randomUUID().toString();
+ }
+
+ @Override
+ public long getId() {
+ return id;
+ }
+
+ public String getUuid() {
+ return uuid;
+ }
+
+ public void setUuid(String uuid) {
+ this.uuid = uuid;
+ }
+
+ public long getHostId() {
+ return hostId;
+ }
+
+ public long getPhysicalNetworkId() {
+ return physicalNetworkId;
+ }
+
+ public String getProviderName() {
+ return providerName;
+ }
+
+ public String getDeviceName() {
+ return deviceName;
+ }
+
+ public String getUrl() {
+ return url;
+ }
+
+ public String getFabricName() {
+ return fabricName;
+ }
+
+ public String getLoginUrl() {
+ return loginUrl;
+ }
+
+ public String getUsername() {
+ return username;
+ }
+
+ public String getPassword() {
+ return password;
+ }
+
+ public String getClientCertPath() {
+ return clientCertPath;
+ }
+
+ public String getClientKeyPath() {
+ return clientKeyPath;
+ }
+
+ public String getCaCertPath() {
+ return caCertPath;
+ }
+
+ public String getGatewayUrl() {
+ return gatewayUrl;
+ }
+
+ public void setGatewayUrl(final String gatewayUrl) {
+ this.gatewayUrl = gatewayUrl;
+ }
+
+ public String getGatewayToken() {
+ return gatewayToken;
+ }
+
+ public void setGatewayToken(final String gatewayToken) {
+ this.gatewayToken = gatewayToken;
+ }
+
+ public String getGatewayCaCertPath() {
+ return gatewayCaCertPath;
+ }
+
+ public void setGatewayCaCertPath(final String gatewayCaCertPath) {
+ this.gatewayCaCertPath = gatewayCaCertPath;
+ }
+}
diff --git a/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/resource/OnesResource.java b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/resource/OnesResource.java
new file mode 100644
index 000000000000..d6b305195028
--- /dev/null
+++ b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/resource/OnesResource.java
@@ -0,0 +1,274 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.apache.cloudstack.network.ones.resource;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.naming.ConfigurationException;
+
+import org.apache.cloudstack.network.ones.agent.api.AllocateOnesServersCommand;
+import org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand;
+import org.apache.cloudstack.network.ones.agent.api.CreateOnesTenantCommand;
+import org.apache.cloudstack.network.ones.agent.api.DeallocateOnesServersCommand;
+import org.apache.cloudstack.network.ones.agent.api.DeleteOnesTenantCommand;
+import org.apache.cloudstack.network.ones.agent.api.RemoveOnesEdgeCommand;
+import org.apache.cloudstack.network.ones.agent.api.StartupOnesCommand;
+import org.apache.cloudstack.network.ones.client.AvizGatewayClient;
+import org.apache.cloudstack.network.ones.client.OnesApiClient;
+import org.apache.cloudstack.network.ones.client.OnesApiClientImpl;
+import org.apache.cloudstack.network.ones.dao.OnesProviderDao;
+import org.apache.cloudstack.network.ones.dao.OnesProviderVO;
+
+import com.cloud.agent.IAgentControl;
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.CheckHealthCommand;
+import com.cloud.agent.api.Command;
+import com.cloud.agent.api.PingCommand;
+import com.cloud.agent.api.ReadyCommand;
+import com.cloud.agent.api.StartupCommand;
+import com.cloud.host.Host;
+import com.cloud.resource.ServerResource;
+import com.cloud.utils.exception.CloudRuntimeException;
+
+/**
+ * Represents one Aviz ONES Spectrum-X fabric controller as a pseudo-agent host, mirroring how
+ * NiciraNvpResource/BigSwitchBcfResource represent their SDN controllers. All ONES REST calls are
+ * routed through the normal agent Command/Answer framework via {@link #executeRequest(Command)}.
+ */
+public class OnesResource implements ServerResource {
+
+ protected String name;
+ protected String guid;
+ protected String zoneId;
+ protected String url;
+ protected String loginUrl;
+ protected String username;
+ protected String password;
+ protected String clientCertPath;
+ protected String clientKeyPath;
+ protected String caCertPath;
+
+ protected OnesApiClient onesApiClient;
+ protected String physicalNetworkId;
+ private IAgentControl agentControl;
+
+ /**
+ * ServerResources are re-created by plain reflection when the management server restarts, so
+ * they get no Spring injection (and ComponentContext only sees the root context, not this
+ * plugin's module context). The Spring-managed OnesElement hands us the DAO here instead -
+ * the same static-holder pattern HypervDirectConnectResource uses.
+ */
+ private static volatile OnesProviderDao s_providerDao;
+
+ public static void setProviderDao(final OnesProviderDao dao) {
+ s_providerDao = dao;
+ }
+
+ /**
+ * Builds the REST client on first use. After a management-server restart the resource is
+ * re-created from host_details, which deliberately does not hold the password; it is read
+ * from the (encrypted) ones_providers row instead.
+ */
+ private synchronized OnesApiClient getApiClient() {
+ if (onesApiClient == null) {
+ if (password == null && physicalNetworkId != null && s_providerDao != null) {
+ for (OnesProviderVO provider : s_providerDao.listByPhysicalNetwork(Long.parseLong(physicalNetworkId))) {
+ username = provider.getUsername();
+ password = provider.getPassword();
+ loginUrl = provider.getLoginUrl();
+ break;
+ }
+ }
+ if (password == null) {
+ throw new CloudRuntimeException("No Aviz ONES login is on record for physical network " + physicalNetworkId);
+ }
+ onesApiClient = new OnesApiClientImpl(url, loginUrl, username, password, clientCertPath, clientKeyPath, caCertPath);
+ }
+ return onesApiClient;
+ }
+
+ /**
+ * A client for the provider's Aviz Gateway, from its current settings: they can change any time
+ * through updateOnesProvider, and the token is only in the (encrypted) ones_providers row.
+ */
+ protected AvizGatewayClient getGatewayClient() {
+ OnesProviderVO provider = null;
+ if (physicalNetworkId != null && s_providerDao != null) {
+ for (OnesProviderVO p : s_providerDao.listByPhysicalNetwork(Long.parseLong(physicalNetworkId))) {
+ provider = p;
+ break;
+ }
+ }
+ if (provider == null || provider.getGatewayUrl() == null || provider.getGatewayToken() == null) {
+ throw new CloudRuntimeException("The Aviz ONES provider of physical network " + physicalNetworkId
+ + " has no Aviz Gateway (set gatewayurl and gatewaytoken with updateOnesProvider)");
+ }
+ return new AvizGatewayClient(provider.getGatewayUrl(), provider.getGatewayToken(), provider.getGatewayCaCertPath());
+ }
+
+ @Override
+ public Host.Type getType() {
+ return Host.Type.L2Networking;
+ }
+
+ @Override
+ public StartupCommand[] initialize() {
+ StartupOnesCommand sc = new StartupOnesCommand();
+ sc.setGuid(guid);
+ sc.setName(name);
+ sc.setDataCenter(zoneId != null ? zoneId : "");
+ sc.setPod("");
+ sc.setPrivateIpAddress("");
+ sc.setStorageIpAddress("");
+ sc.setVersion("");
+ return new StartupCommand[]{sc};
+ }
+
+ @Override
+ public PingCommand getCurrentStatus(final long id) {
+ return new PingCommand(Host.Type.L2Networking, id);
+ }
+
+ @Override
+ public Answer executeRequest(final Command cmd) {
+ if (cmd instanceof ReadyCommand) {
+ return new Answer(cmd);
+ }
+ try {
+ if (cmd instanceof CheckHealthCommand) {
+ return new Answer(cmd, getApiClient().isReachable(), "");
+ } else if (cmd instanceof CreateOnesTenantCommand) {
+ return getApiClient().createTenant((CreateOnesTenantCommand) cmd);
+ } else if (cmd instanceof DeleteOnesTenantCommand) {
+ return getApiClient().deleteTenant((DeleteOnesTenantCommand) cmd);
+ } else if (cmd instanceof AllocateOnesServersCommand) {
+ return getApiClient().allocateServers((AllocateOnesServersCommand) cmd);
+ } else if (cmd instanceof DeallocateOnesServersCommand) {
+ return getApiClient().deallocateServers((DeallocateOnesServersCommand) cmd);
+ } else if (cmd instanceof ConfigureOnesEdgeCommand) {
+ return getGatewayClient().configureEdge((ConfigureOnesEdgeCommand) cmd);
+ } else if (cmd instanceof RemoveOnesEdgeCommand) {
+ return getGatewayClient().removeEdge((RemoveOnesEdgeCommand) cmd);
+ }
+ } catch (CloudRuntimeException e) {
+ return new Answer(cmd, e);
+ }
+ return Answer.createUnsupportedCommandAnswer(cmd);
+ }
+
+ @Override
+ public void disconnected() {
+ // Do nothing
+ }
+
+ @Override
+ public IAgentControl getAgentControl() {
+ return agentControl;
+ }
+
+ @Override
+ public void setAgentControl(final IAgentControl agentControl) {
+ this.agentControl = agentControl;
+ }
+
+ @Override
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public void setName(final String name) {
+ this.name = name;
+ }
+
+ @Override
+ public void setConfigParams(final Map params) {
+ // Do nothing
+ }
+
+ @Override
+ public Map getConfigParams() {
+ return new HashMap<>();
+ }
+
+ @Override
+ public int getRunLevel() {
+ return 0;
+ }
+
+ @Override
+ public void setRunLevel(final int level) {
+ // Do nothing
+ }
+
+ @Override
+ public boolean configure(final String name, final Map params) throws ConfigurationException {
+ this.name = (String) params.get("name");
+ if (this.name == null) {
+ throw new ConfigurationException("Unable to find the Aviz ONES provider name");
+ }
+
+ guid = (String) params.get("guid");
+ if (guid == null) {
+ throw new ConfigurationException("Unable to find the Aviz ONES resource guid");
+ }
+
+ zoneId = (String) params.get("zoneId");
+
+ url = (String) params.get("url");
+ if (url == null) {
+ throw new ConfigurationException("Missing the Aviz ONES controller URL (url)");
+ }
+
+ // The password is only here on the first configure (addOnesProvider); on a restart it
+ // is resolved lazily from ones_providers via the physical network id.
+ loginUrl = (String) params.get("loginUrl");
+ username = (String) params.get("username");
+ password = (String) params.get("password");
+ physicalNetworkId = (String) params.get("physicalNetworkId");
+ if (password == null && physicalNetworkId == null) {
+ throw new ConfigurationException("Missing the Aviz ONES login and the physical network id");
+ }
+
+ // The TLS client certificate is optional: most ONES deployments need only the login.
+ clientCertPath = (String) params.get("clientCertPath");
+ clientKeyPath = (String) params.get("clientKeyPath");
+ caCertPath = (String) params.get("caCertPath");
+ if ((clientCertPath == null) != (clientKeyPath == null)) {
+ throw new ConfigurationException("clientCertPath and clientKeyPath must both be set, or both omitted");
+ }
+
+ if (password != null) {
+ onesApiClient = new OnesApiClientImpl(url, loginUrl, username, password, clientCertPath, clientKeyPath, caCertPath);
+ }
+ return true;
+ }
+
+ @Override
+ public boolean start() {
+ return true;
+ }
+
+ @Override
+ public boolean stop() {
+ return true;
+ }
+}
diff --git a/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/service/OnesEdgeBuilder.java b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/service/OnesEdgeBuilder.java
new file mode 100644
index 000000000000..01fc8311b521
--- /dev/null
+++ b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/service/OnesEdgeBuilder.java
@@ -0,0 +1,297 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.apache.cloudstack.network.ones.service;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+
+import org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand.FirewallRule;
+import org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand.PortMapping;
+import org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand.Vip;
+import org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand;
+import org.apache.cloudstack.network.ones.client.AvizGatewayClient;
+
+import com.cloud.network.IpAddress;
+import com.cloud.network.Network;
+import com.cloud.network.NetworkModel;
+import com.cloud.network.dao.FirewallRulesCidrsDao;
+import com.cloud.network.dao.FirewallRulesDao;
+import com.cloud.network.dao.IPAddressDao;
+import com.cloud.network.dao.IPAddressVO;
+import com.cloud.network.dao.LBStickinessPolicyDao;
+import com.cloud.network.dao.LBStickinessPolicyVO;
+import com.cloud.network.dao.LoadBalancerDao;
+import com.cloud.network.dao.LoadBalancerVMMapDao;
+import com.cloud.network.dao.LoadBalancerVMMapVO;
+import com.cloud.network.dao.LoadBalancerVO;
+import com.cloud.network.rules.FirewallRule.Purpose;
+import com.cloud.network.rules.FirewallRule.State;
+import com.cloud.network.rules.FirewallRule.TrafficType;
+import com.cloud.network.rules.FirewallRuleVO;
+import com.cloud.network.rules.LbStickinessMethod.StickinessMethodType;
+import com.cloud.network.rules.LoadBalancerContainer.Scheme;
+import com.cloud.network.rules.PortForwardingRuleVO;
+import com.cloud.network.rules.dao.PortForwardingRulesDao;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.vm.Nic;
+
+/**
+ * What a ONES network's edge on the Aviz Gateway should be, read from CloudStack's own records:
+ * the network's source NAT address, its live port forwards and public load-balancer rules, and
+ * the ingress firewall rules on their public addresses.
+ *
+ * Firewall: the gateway filters inbound traffic after translation, so every mapped local
+ * address:port gets a deny for any source, and a permit for each source CIDR an ingress rule
+ * allows on the public address:port that leads there. The permit's narrower source puts it ahead
+ * of the deny. A mapping no ingress rule covers stays closed, as on any CloudStack network.
+ */
+public class OnesEdgeBuilder {
+
+ /** Port forwards are mapped port by port on the gateway: more than this in one rule is refused. */
+ static final int MAX_PORTS_PER_FORWARD = 256;
+ static final String ANY = "0.0.0.0/0";
+
+ private final IPAddressDao ipAddressDao;
+ private final PortForwardingRulesDao portForwardingRulesDao;
+ private final LoadBalancerDao loadBalancerDao;
+ private final LoadBalancerVMMapDao lbVmMapDao;
+ private final LBStickinessPolicyDao lbStickinessPolicyDao;
+ private final FirewallRulesDao firewallRulesDao;
+ private final FirewallRulesCidrsDao firewallRulesCidrsDao;
+ private final NetworkModel networkModel;
+
+ public OnesEdgeBuilder(final IPAddressDao ipAddressDao, final PortForwardingRulesDao portForwardingRulesDao, final LoadBalancerDao loadBalancerDao,
+ final LoadBalancerVMMapDao lbVmMapDao, final LBStickinessPolicyDao lbStickinessPolicyDao, final FirewallRulesDao firewallRulesDao,
+ final FirewallRulesCidrsDao firewallRulesCidrsDao, final NetworkModel networkModel) {
+ this.ipAddressDao = ipAddressDao;
+ this.portForwardingRulesDao = portForwardingRulesDao;
+ this.loadBalancerDao = loadBalancerDao;
+ this.lbVmMapDao = lbVmMapDao;
+ this.lbStickinessPolicyDao = lbStickinessPolicyDao;
+ this.firewallRulesDao = firewallRulesDao;
+ this.firewallRulesCidrsDao = firewallRulesCidrsDao;
+ this.networkModel = networkModel;
+ }
+
+ static boolean live(final State state) {
+ return state == State.Add || state == State.Active;
+ }
+
+ static String protocolOf(final String p) {
+ return p != null && "udp".equalsIgnoreCase(p) ? "udp" : "tcp";
+ }
+
+ /** The address the network's outbound traffic is translated onto; null when it has none. */
+ String sourceNatAddress(final long networkId) {
+ for (IPAddressVO ip : ipAddressDao.listByAssociatedNetwork(networkId, true)) {
+ if (ip.getState() == IpAddress.State.Allocated || ip.getState() == IpAddress.State.Allocating) {
+ return ip.getAddress().addr();
+ }
+ }
+ return null;
+ }
+
+ private String addressOf(final long ipId) {
+ IPAddressVO ip = ipAddressDao.findById(ipId);
+ if (ip == null) {
+ throw new CloudRuntimeException("public IP " + ipId + " is gone");
+ }
+ return ip.getAddress().addr();
+ }
+
+ List portMappings(final long networkId, final boolean withPortForwarding) {
+ List out = new ArrayList<>();
+ if (!withPortForwarding) {
+ return out;
+ }
+ for (PortForwardingRuleVO r : portForwardingRulesDao.listByNetwork(networkId)) {
+ if (!live(r.getState())) {
+ continue;
+ }
+ int ports = r.getSourcePortEnd() - r.getSourcePortStart() + 1;
+ if (ports > MAX_PORTS_PER_FORWARD) {
+ throw new CloudRuntimeException("Port forward " + r.getUuid() + " covers " + ports + " ports; the Aviz Gateway maps at most "
+ + MAX_PORTS_PER_FORWARD + " per rule");
+ }
+ String external = addressOf(r.getSourceIpAddressId());
+ for (int i = 0; i < ports; i++) {
+ out.add(new PortMapping(external, r.getDestinationIpAddress().addr(), protocolOf(r.getProtocol()),
+ r.getSourcePortStart() + i, r.getDestinationPortStart() + i));
+ }
+ }
+ return out;
+ }
+
+ private String memberAddress(final LoadBalancerVMMapVO m, final long networkId) {
+ if (m.getInstanceIp() != null) {
+ return m.getInstanceIp();
+ }
+ Nic nic = networkModel.getNicInNetwork(m.getInstanceId(), networkId);
+ return nic != null ? nic.getIPv4Address() : null;
+ }
+
+ List vips(final long networkId, final boolean withLb) {
+ List out = new ArrayList<>();
+ if (!withLb) {
+ return out;
+ }
+ for (LoadBalancerVO lb : loadBalancerDao.listByNetworkIdAndScheme(networkId, Scheme.Public)) {
+ if (!live(lb.getState())) {
+ continue;
+ }
+ List backends = new ArrayList<>();
+ for (LoadBalancerVMMapVO m : lbVmMapDao.listByLoadBalancerId(lb.getId(), false)) {
+ String member = memberAddress(m, networkId);
+ if (member != null && !backends.contains(member)) {
+ backends.add(member);
+ }
+ }
+ boolean sticky = false;
+ for (LBStickinessPolicyVO p : lbStickinessPolicyDao.listByLoadBalancerId(lb.getId(), false)) {
+ sticky |= StickinessMethodType.SourceBased.getName().equalsIgnoreCase(p.getMethodName());
+ }
+ out.add(new Vip(AvizGatewayClient.VIP_PREFIX + lb.getId(), addressOf(lb.getSourceIpAddressId()), lb.getSourcePortStart(),
+ protocolOf(lb.getLbProtocol()), lb.getDefaultPortStart(), backends, sticky));
+ }
+ return out;
+ }
+
+ /** One place a public address:port leads to inside the tenant. */
+ private static final class Target {
+ final String publicAddress;
+ final String protocol;
+ final int publicPort;
+ final String local;
+ final int localPort;
+
+ Target(final String publicAddress, final String protocol, final int publicPort, final String local, final int localPort) {
+ this.publicAddress = publicAddress;
+ this.protocol = protocol;
+ this.publicPort = publicPort;
+ this.local = local;
+ this.localPort = localPort;
+ }
+ }
+
+ private static boolean covers(final FirewallRuleVO rule, final String ruleAddress, final Target t) {
+ if (!ruleAddress.equals(t.publicAddress)) {
+ return false;
+ }
+ String p = rule.getProtocol() == null ? "all" : rule.getProtocol().toLowerCase(Locale.ROOT);
+ if (!"all".equals(p) && !p.equals(t.protocol)) {
+ return false;
+ }
+ if (rule.getSourcePortStart() == null) {
+ return true;
+ }
+ int end = rule.getSourcePortEnd() != null ? rule.getSourcePortEnd() : rule.getSourcePortStart();
+ return t.publicPort >= rule.getSourcePortStart() && t.publicPort <= end;
+ }
+
+ List firewallRules(final long networkId, final String tenant, final List mappings, final List vips) {
+ List targets = new ArrayList<>();
+ for (PortMapping m : mappings) {
+ targets.add(new Target(m.getExternal(), m.getProtocol(), m.getExternalPort(), m.getLocal(), m.getLocalPort()));
+ }
+ for (Vip v : vips) {
+ for (String b : v.getBackends()) {
+ targets.add(new Target(v.getAddress(), v.getProtocol(), v.getPort(), b, v.getBackendPort()));
+ }
+ }
+ List ingress = new ArrayList<>();
+ Map ruleAddress = new LinkedHashMap<>();
+ Map> ruleSources = new LinkedHashMap<>();
+ for (FirewallRuleVO r : firewallRulesDao.listByNetworkPurposeTrafficType(networkId, Purpose.Firewall, TrafficType.Ingress)) {
+ if (!live(r.getState()) || r.getSourceIpAddressId() == null) {
+ continue;
+ }
+ ingress.add(r);
+ ruleAddress.put(r.getId(), addressOf(r.getSourceIpAddressId()));
+ List cidrs = firewallRulesCidrsDao.getSourceCidrs(r.getId());
+ ruleSources.put(r.getId(), cidrs == null || cidrs.isEmpty() ? List.of(ANY) : cidrs);
+ }
+
+ // keyed by what the rule does, so a local address:port reached two ways is filtered once
+ Map wanted = new LinkedHashMap<>();
+ for (Target t : targets) {
+ String dst = t.local + "/32";
+ for (FirewallRuleVO r : ingress) {
+ if (covers(r, ruleAddress.get(r.getId()), t)) {
+ for (String cidr : ruleSources.get(r.getId())) {
+ wanted.putIfAbsent("permit " + cidr + " " + dst + " " + t.protocol + " " + t.localPort,
+ new String[]{"permit", cidr, dst, t.protocol, String.valueOf(t.localPort)});
+ }
+ }
+ }
+ wanted.putIfAbsent("deny " + ANY + " " + dst + " " + t.protocol + " " + t.localPort,
+ new String[]{"deny", ANY, dst, t.protocol, String.valueOf(t.localPort)});
+ }
+ List out = new ArrayList<>();
+ int n = 0;
+ for (String[] w : wanted.values()) {
+ out.add(new FirewallRule(tenant + AvizGatewayClient.FIREWALL_INFIX + n++, w[1], w[2], w[3], Integer.parseInt(w[4]), "permit".equals(w[0])));
+ }
+ return out;
+ }
+
+ /**
+ * The gateway's load balancer maps replies back by backend address, port and protocol alone,
+ * so one VM address:port can serve one VIP, and nothing else: a port forward or a second VIP
+ * to it would have its replies taken for the first VIP's.
+ */
+ static void checkBackendPorts(final List mappings, final List vips) {
+ Map owner = new LinkedHashMap<>();
+ for (Vip v : vips) {
+ for (String b : v.getBackends()) {
+ String key = b + ":" + v.getBackendPort() + "/" + v.getProtocol();
+ String other = owner.putIfAbsent(key, "load balancer " + v.getAddress() + ":" + v.getPort());
+ if (other != null) {
+ throw new CloudRuntimeException(key + " is behind " + other + " and load balancer " + v.getAddress() + ":" + v.getPort()
+ + "; on the Aviz Gateway a VM port serves one load balancer: give the second its own private port");
+ }
+ }
+ }
+ for (PortMapping m : mappings) {
+ String key = m.getLocal() + ":" + m.getLocalPort() + "/" + m.getProtocol();
+ if (owner.containsKey(key)) {
+ throw new CloudRuntimeException(key + " is behind " + owner.get(key) + " and port forward " + m.getExternal() + ":"
+ + m.getExternalPort() + "; on the Aviz Gateway a VM port behind a load balancer cannot also be port forwarded");
+ }
+ }
+ }
+
+ /**
+ * @param withFirewall whether the network has Firewall by this provider; without it nothing is
+ * filtered (mapped ports are open), as on any network without a firewall
+ */
+ public ConfigureOnesEdgeCommand build(final Network network, final String tenant, final boolean withSourceNat,
+ final boolean withPortForwarding, final boolean withLb, final boolean withFirewall) {
+ long id = network.getId();
+ String sourceNat = withSourceNat ? sourceNatAddress(id) : null;
+ List mappings = portMappings(id, withPortForwarding);
+ List vips = vips(id, withLb);
+ checkBackendPorts(mappings, vips);
+ List rules = withFirewall ? firewallRules(id, tenant, mappings, vips) : new ArrayList<>();
+ return new ConfigureOnesEdgeCommand(tenant, sourceNat, mappings, vips, rules);
+ }
+}
diff --git a/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/service/OnesElement.java b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/service/OnesElement.java
new file mode 100644
index 000000000000..0dfea3516272
--- /dev/null
+++ b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/service/OnesElement.java
@@ -0,0 +1,777 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.apache.cloudstack.network.ones.service;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.function.BooleanSupplier;
+
+import javax.inject.Inject;
+import javax.naming.ConfigurationException;
+
+import org.apache.cloudstack.network.ones.agent.api.AllocateOnesServersCommand;
+import org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand;
+import org.apache.cloudstack.network.ones.agent.api.RemoveOnesEdgeCommand;
+import org.apache.cloudstack.network.ones.agent.api.StartupOnesCommand;
+import org.apache.cloudstack.network.ones.api.command.AddOnesProviderCmd;
+import org.apache.cloudstack.network.ones.api.command.DeleteOnesProviderCmd;
+import org.apache.cloudstack.network.ones.api.command.ListOnesProvidersCmd;
+import org.apache.cloudstack.network.ones.api.command.UpdateOnesProviderCmd;
+import org.apache.cloudstack.network.ones.api.response.OnesProviderResponse;
+import org.apache.cloudstack.network.ones.dao.OnesProviderDao;
+import org.apache.cloudstack.network.ones.dao.OnesProviderVO;
+import org.apache.cloudstack.network.ones.resource.OnesResource;
+import org.springframework.stereotype.Component;
+
+import com.cloud.agent.AgentManager;
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.StartupCommand;
+import com.cloud.agent.api.to.LoadBalancerTO;
+import com.cloud.api.ApiDBUtils;
+import com.cloud.deploy.DeployDestination;
+import com.cloud.exception.ConcurrentOperationException;
+import com.cloud.exception.InsufficientCapacityException;
+import com.cloud.exception.InvalidParameterValueException;
+import com.cloud.exception.ResourceUnavailableException;
+import com.cloud.host.DetailVO;
+import com.cloud.host.Host;
+import com.cloud.host.HostVO;
+import com.cloud.host.dao.HostDao;
+import com.cloud.host.dao.HostDetailsDao;
+import com.cloud.network.Network.Capability;
+import com.cloud.network.Network.Provider;
+import com.cloud.network.Network.Service;
+import com.cloud.network.Network;
+import com.cloud.network.NetworkModel;
+import com.cloud.network.PhysicalNetwork;
+import com.cloud.network.PhysicalNetworkServiceProvider;
+import com.cloud.network.PublicIpAddress;
+import com.cloud.network.dao.FirewallRulesCidrsDao;
+import com.cloud.network.dao.FirewallRulesDao;
+import com.cloud.network.dao.IPAddressDao;
+import com.cloud.network.dao.IPAddressVO;
+import com.cloud.network.dao.LBStickinessPolicyDao;
+import com.cloud.network.dao.LoadBalancerDao;
+import com.cloud.network.dao.LoadBalancerVMMapDao;
+import com.cloud.network.dao.NetworkDao;
+import com.cloud.network.dao.NetworkDetailVO;
+import com.cloud.network.dao.NetworkDetailsDao;
+import com.cloud.network.dao.NetworkServiceMapDao;
+import com.cloud.network.dao.NetworkVO;
+import com.cloud.network.dao.PhysicalNetworkDao;
+import com.cloud.network.dao.PhysicalNetworkServiceProviderDao;
+import com.cloud.network.dao.PhysicalNetworkServiceProviderVO;
+import com.cloud.network.dao.PhysicalNetworkVO;
+import com.cloud.network.element.ConnectivityProvider;
+import com.cloud.network.element.FirewallServiceProvider;
+import com.cloud.network.element.IpDeployer;
+import com.cloud.network.element.LoadBalancingServiceProvider;
+import com.cloud.network.element.PortForwardingServiceProvider;
+import com.cloud.network.element.SourceNatServiceProvider;
+import com.cloud.network.lb.LoadBalancingRule;
+import com.cloud.network.rules.FirewallRule;
+import com.cloud.network.rules.LbStickinessMethod.StickinessMethodType;
+import com.cloud.network.rules.LbStickinessMethod;
+import com.cloud.network.rules.LoadBalancerContainer;
+import com.cloud.network.rules.PortForwardingRule;
+import com.cloud.network.rules.dao.PortForwardingRulesDao;
+import com.cloud.offering.NetworkOffering;
+import com.cloud.resource.ResourceManager;
+import com.cloud.resource.ResourceState;
+import com.cloud.resource.ResourceStateAdapter;
+import com.cloud.resource.ServerResource;
+import com.cloud.resource.UnableDeleteHostException;
+import com.cloud.utils.component.AdapterBase;
+import com.cloud.utils.db.DB;
+import com.cloud.utils.db.GlobalLock;
+import com.cloud.utils.db.Transaction;
+import com.cloud.utils.db.TransactionCallback;
+import com.cloud.utils.db.TransactionStatus;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.vm.NicProfile;
+import com.cloud.vm.ReservationContext;
+import com.cloud.vm.VirtualMachineProfile;
+import com.google.gson.Gson;
+
+/**
+ * NetworkElement for the Aviz ONES Spectrum-X fabric: registers/manages the ONES controller as
+ * a pseudo-agent host (see {@link OnesResource}), and drives per-host GPU-server tenant
+ * membership as VMs are placed on/removed from hypervisor hosts within a ONES-backed guest
+ * network. Tenant creation/CIDR assignment itself happens in {@link org.apache.cloudstack.network.ones.service.OnesGuestNetworkGuru},
+ * since ONES computes the guest IP pool server-side as part of "Create Tenant".
+ */
+@Component
+public class OnesElement extends AdapterBase implements ConnectivityProvider, OnesElementService, ResourceStateAdapter,
+ SourceNatServiceProvider, FirewallServiceProvider, PortForwardingServiceProvider, LoadBalancingServiceProvider, IpDeployer {
+
+ /**
+ * The network service provider this plugin adds. CloudStack core has no "AvizOnes" constant;
+ * creating a Provider registers it in Provider's list of supported providers, so
+ * addNetworkServiceProvider name=AvizOnes works once this class is loaded.
+ */
+ public static final Provider AVIZ_ONES = new Provider("AvizOnes", false);
+
+ public static final String DETAIL_TENANT_NAME = "onestenantname";
+ public static final String DETAIL_ALLOCATED_HOSTS = "onesallocatedhosts";
+
+ /** The resource may wait up to 180 s for ONES to put the tenant on the gateway, then applies. */
+ static final int EDGE_WAIT_S = 600;
+ static final int EDGE_LOCK_S = 600;
+
+ private static final Map> CAPABILITIES = setCapabilities();
+
+ @Inject
+ protected ResourceManager resourceMgr;
+ @Inject
+ protected PhysicalNetworkDao physicalNetworkDao;
+ @Inject
+ protected PhysicalNetworkServiceProviderDao physicalNetworkServiceProviderDao;
+ @Inject
+ protected OnesProviderDao onesProviderDao;
+ @Inject
+ protected HostDetailsDao hostDetailsDao;
+ @Inject
+ protected HostDao hostDao;
+ @Inject
+ protected AgentManager agentMgr;
+ @Inject
+ protected NetworkDao networkDao;
+ @Inject
+ protected NetworkDetailsDao networkDetailsDao;
+ @Inject
+ protected NetworkModel networkModel;
+ @Inject
+ protected NetworkServiceMapDao ntwkSrvcDao;
+ @Inject
+ protected IPAddressDao ipAddressDao;
+ @Inject
+ protected PortForwardingRulesDao portForwardingRulesDao;
+ @Inject
+ protected LoadBalancerDao loadBalancerDao;
+ @Inject
+ protected LoadBalancerVMMapDao lbVmMapDao;
+ @Inject
+ protected LBStickinessPolicyDao lbStickinessPolicyDao;
+ @Inject
+ protected FirewallRulesDao firewallRulesDao;
+ @Inject
+ protected FirewallRulesCidrsDao firewallRulesCidrsDao;
+
+ @Override
+ public Map> getCapabilities() {
+ return CAPABILITIES;
+ }
+
+ @Override
+ public Provider getProvider() {
+ return AVIZ_ONES;
+ }
+
+ private static Map> setCapabilities() {
+ Map> capabilities = new HashMap<>();
+ // Connectivity: the ONES tenant. ONES picks its subnet and gateway when it is created.
+ capabilities.put(Service.Connectivity, null);
+ // The rest is the tenant's edge on the Aviz Gateway: outbound translation onto the
+ // network's source NAT address, port forwards, load-balancer VIPs, ingress filtering.
+ Map sourceNat = new HashMap<>();
+ sourceNat.put(Capability.SupportedSourceNatTypes, "peraccount");
+ sourceNat.put(Capability.RedundantRouter, "false");
+ capabilities.put(Service.SourceNat, sourceNat);
+ Map firewall = new HashMap<>();
+ firewall.put(Capability.SupportedProtocols, "tcp,udp");
+ firewall.put(Capability.MultipleIps, "true");
+ firewall.put(Capability.SupportedTrafficDirection, "ingress");
+ capabilities.put(Service.Firewall, firewall);
+ capabilities.put(Service.PortForwarding, null);
+ Map lb = new HashMap<>();
+ lb.put(Capability.SupportedLBAlgorithms, "roundrobin");
+ lb.put(Capability.SupportedLBIsolation, "dedicated");
+ lb.put(Capability.SupportedProtocols, "tcp, udp");
+ lb.put(Capability.SupportedStickinessMethods, sourceStickinessOnly());
+ lb.put(Capability.LbSchemes, LoadBalancerContainer.Scheme.Public.name());
+ capabilities.put(Service.Lb, lb);
+ return capabilities;
+ }
+
+ /** The gateway can keep a client on one server by its source address, nothing else. */
+ private static String sourceStickinessOnly() {
+ LbStickinessMethod method = new LbStickinessMethod(StickinessMethodType.SourceBased,
+ "Keeps every connection from one client address on the same server.");
+ return new Gson().toJson(Collections.singletonList(method));
+ }
+
+ protected boolean canHandle(final Network network, final Service service) {
+ if (!networkModel.isProviderForNetwork(getProvider(), network.getId())) {
+ return false;
+ }
+ return ntwkSrvcDao.canProviderSupportServiceInNetwork(network.getId(), service, AVIZ_ONES);
+ }
+
+ private OnesProviderVO findProviderOrThrow(final Network network) {
+ List devices = onesProviderDao.listByPhysicalNetwork(network.getPhysicalNetworkId());
+ if (devices.isEmpty()) {
+ throw new CloudRuntimeException("No Aviz ONES provider configured on physical network " + network.getPhysicalNetworkId());
+ }
+ return devices.get(0);
+ }
+
+ private String getTenantName(final Network network) {
+ NetworkDetailVO detail = networkDetailsDao.findDetail(network.getId(), DETAIL_TENANT_NAME);
+ if (detail == null) {
+ throw new CloudRuntimeException("No Aviz ONES tenant is on record for network " + network.getUuid()
+ + " - was it implemented through the Aviz ONES guest network guru?");
+ }
+ return detail.getValue();
+ }
+
+ private List getAllocatedHosts(final long networkId) {
+ NetworkDetailVO detail = networkDetailsDao.findDetail(networkId, DETAIL_ALLOCATED_HOSTS);
+ if (detail == null || detail.getValue() == null || detail.getValue().isEmpty()) {
+ return new ArrayList<>();
+ }
+ return new ArrayList<>(Arrays.asList(detail.getValue().split(",")));
+ }
+
+ private void setAllocatedHosts(final long networkId, final List hostNames) {
+ networkDetailsDao.removeDetail(networkId, DETAIL_ALLOCATED_HOSTS);
+ networkDetailsDao.addDetail(networkId, DETAIL_ALLOCATED_HOSTS, String.join(",", hostNames), false);
+ }
+
+ @Override
+ public boolean configure(final String name, final Map params) throws ConfigurationException {
+ super.configure(name, params);
+ resourceMgr.registerResourceStateAdapter(name, this);
+ // OnesResource instances are re-created reflectively on restart and get no injection.
+ OnesResource.setProviderDao(onesProviderDao);
+ return true;
+ }
+
+ @Override
+ public boolean implement(final Network network, final NetworkOffering offering, final DeployDestination dest, final ReservationContext context)
+ throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
+ // Tenant creation and CIDR/gateway assignment happens in OnesGuestNetworkGuru.implement(),
+ // since ONES - not CloudStack - computes the guest IP pool. Nothing further to do here.
+ return canHandle(network, Service.Connectivity);
+ }
+
+ @Override
+ public boolean prepare(final Network network, final NicProfile nic, final VirtualMachineProfile vm, final DeployDestination dest,
+ final ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
+ if (!canHandle(network, Service.Connectivity) || dest.getHost() == null) {
+ return false;
+ }
+
+ OnesProviderVO device = findProviderOrThrow(network);
+ HostVO onesHost = hostDao.findById(device.getHostId());
+ String tenantName = getTenantName(network);
+ String serverName = dest.getHost().getName();
+
+ // Read, add on ONES and record under one per-network lock: two VMs starting at once on
+ // different hosts would otherwise each write back a list without the other's host, and
+ // that host would stay in the tenant unrecorded (never taken out again).
+ boolean[] firstHost = {false};
+ boolean locked = underLock("ones.hosts." + network.getId(), () -> {
+ List allocatedHosts = getAllocatedHosts(network.getId());
+ if (allocatedHosts.contains(serverName)) {
+ return true;
+ }
+ // shared: a hypervisor carries many guest networks, so ONES trunks the tenant's VLAN on
+ // the host's leaf port instead of dedicating the port to this tenant.
+ AllocateOnesServersCommand cmd = new AllocateOnesServersCommand(device.getFabricName(), tenantName, Arrays.asList(serverName), true);
+ cmd.setWait(900);
+ Answer answer = agentMgr.easySend(onesHost.getId(), cmd);
+ if (answer == null || !answer.getResult()) {
+ throw new CloudRuntimeException("Failed to add host " + serverName + " to Aviz ONES tenant " + tenantName + ": "
+ + (answer != null ? answer.getDetails() : "no answer from Aviz ONES resource"));
+ }
+ firstHost[0] = allocatedHosts.isEmpty();
+ allocatedHosts.add(serverName);
+ setAllocatedHosts(network.getId(), allocatedHosts);
+ return true;
+ });
+ if (!locked) {
+ throw new CloudRuntimeException("Could not lock the Aviz ONES hosts of network " + network.getUuid());
+ }
+ if (firstHost[0] && hasEdge(network)) {
+ // ONES now puts the tenant on the gateway (FM tenant webhook): its edge can follow.
+ // A failure here leaves the network east-west only; the VM deployment goes on.
+ if (!syncEdge(network)) {
+ logger.warn("Network {} is up without its Aviz Gateway edge (internet access, port forwards, VIPs); "
+ + "it is applied again with the next rule change or restartNetwork", network);
+ }
+ }
+ return true;
+ }
+
+ @Override
+ public boolean release(final Network network, final NicProfile nic, final VirtualMachineProfile vm, final ReservationContext context)
+ throws ConcurrentOperationException, ResourceUnavailableException {
+ if (!canHandle(network, Service.Connectivity)) {
+ return false;
+ }
+ // Deallocation of a no-longer-used host from the tenant happens in destroy(), once we can
+ // be sure no other NICs/VMs on this network are still active on that host; per-NIC release
+ // is intentionally a no-op to avoid pulling a host out from under a sibling VM on the same
+ // network and host.
+ return true;
+ }
+
+ @Override
+ public boolean shutdown(final Network network, final ReservationContext context, final boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException {
+ if (!canHandle(network, Service.Connectivity)) {
+ return false;
+ }
+ removeEdge(network); // before the guru takes the hosts out of the tenant
+ return true;
+ }
+
+ @Override
+ public boolean destroy(final Network network, final ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException {
+ // Tenant deletion happens in OnesGuestNetworkGuru.trash(), mirroring how
+ // NiciraNvpElement/NiciraNvpGuestNetworkGuru split whole-network teardown to the guru.
+ if (!canHandle(network, Service.Connectivity)) {
+ return false;
+ }
+ removeEdge(network);
+ return true;
+ }
+
+ @Override
+ public boolean isReady(final PhysicalNetworkServiceProvider provider) {
+ return true;
+ }
+
+ @Override
+ public boolean shutdownProviderInstances(final PhysicalNetworkServiceProvider provider, final ReservationContext context)
+ throws ConcurrentOperationException, ResourceUnavailableException {
+ return true;
+ }
+
+ @Override
+ public boolean canEnableIndividualServices() {
+ return true;
+ }
+
+ @Override
+ public boolean verifyServicesCombination(final Set services) {
+ if (!services.contains(Service.Connectivity)) {
+ logger.warn("Unable to provide services without Connectivity service enabled for the Aviz ONES element");
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public List> getCommands() {
+ List> cmdList = new ArrayList<>();
+ cmdList.add(AddOnesProviderCmd.class);
+ cmdList.add(DeleteOnesProviderCmd.class);
+ cmdList.add(ListOnesProvidersCmd.class);
+ cmdList.add(UpdateOnesProviderCmd.class);
+ return cmdList;
+ }
+
+ @Override
+ @DB
+ public OnesProviderVO addOnesProvider(final AddOnesProviderCmd cmd) {
+ final Long physicalNetworkId = cmd.getPhysicalNetworkId();
+ PhysicalNetworkVO physicalNetwork = physicalNetworkDao.findById(physicalNetworkId);
+ if (physicalNetwork == null) {
+ throw new InvalidParameterValueException("Could not find physical network with ID: " + physicalNetworkId);
+ }
+ long zoneId = physicalNetwork.getDataCenterId();
+
+ final PhysicalNetworkServiceProviderVO ntwkSvcProvider =
+ physicalNetworkServiceProviderDao.findByServiceProvider(physicalNetwork.getId(), AVIZ_ONES.getName());
+ if (ntwkSvcProvider == null) {
+ throw new CloudRuntimeException("Network Service Provider " + AVIZ_ONES.getName() + " is not enabled on physical network "
+ + physicalNetworkId + " - enable it first via addNetworkServiceProvider");
+ } else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) {
+ throw new CloudRuntimeException("Network Service Provider " + ntwkSvcProvider.getProviderName() + " is in Shutdown state on physical network "
+ + physicalNetworkId);
+ }
+
+ if (!onesProviderDao.listByPhysicalNetwork(physicalNetworkId).isEmpty()) {
+ throw new CloudRuntimeException("An Aviz ONES provider is already configured on this physical network");
+ }
+
+ final String deviceName = AVIZ_ONES.getName();
+ final String name = cmd.getName();
+ final String url = cmd.getUrl();
+ final String fabricName = cmd.getFabricName();
+ final String loginUrl = cmd.getLoginUrl();
+ final String username = cmd.getUsername();
+ final String password = cmd.getPassword();
+ final String clientCertPath = cmd.getClientCertPath();
+ final String clientKeyPath = cmd.getClientKeyPath();
+ final String caCertPath = cmd.getCaCertPath();
+
+ Map params = new HashMap<>();
+ params.put("guid", UUID.randomUUID().toString());
+ params.put("zoneId", String.valueOf(zoneId));
+ params.put("physicalNetworkId", String.valueOf(physicalNetworkId));
+ params.put("name", name);
+ params.put("url", url);
+ params.put("loginUrl", loginUrl);
+ params.put("username", username);
+ // The password is deliberately NOT in `params`: that map is persisted in clear text in
+ // the generic host_details table. It goes only to the in-memory configure() below and
+ // into ones_providers (encrypted); after a restart OnesResource reads it from there.
+ // The TLS client certificate is optional: only pass these through when supplied, since
+ // CloudStack's host-details persistence does not tolerate null values in this map.
+ if (clientCertPath != null) {
+ params.put("clientCertPath", clientCertPath);
+ }
+ if (clientKeyPath != null) {
+ params.put("clientKeyPath", clientKeyPath);
+ }
+ if (caCertPath != null) {
+ params.put("caCertPath", caCertPath);
+ }
+
+ Map hostDetails = new HashMap<>(params);
+ hostDetails.put("password", password);
+ ServerResource resource = new OnesResource();
+
+ try {
+ resource.configure(name, hostDetails);
+ final Host host = resourceMgr.addHost(zoneId, resource, resource.getType(), params);
+ if (host == null) {
+ throw new CloudRuntimeException("Failed to add Aviz ONES provider due to internal error.");
+ }
+ return Transaction.execute((TransactionCallback) (TransactionStatus status) -> {
+ OnesProviderVO onesProviderVO = new OnesProviderVO(host.getId(), physicalNetworkId, ntwkSvcProvider.getProviderName(), deviceName,
+ url, fabricName, loginUrl, username, password, clientCertPath, clientKeyPath, caCertPath);
+ onesProviderDao.persist(onesProviderVO);
+
+ DetailVO detail = new DetailVO(host.getId(), "onesproviderid", String.valueOf(onesProviderVO.getId()));
+ hostDetailsDao.persist(detail);
+
+ return onesProviderVO;
+ });
+ } catch (ConfigurationException e) {
+ throw new CloudRuntimeException(e.getMessage());
+ }
+ }
+
+ @Override
+ public OnesProviderResponse createOnesProviderResponse(final OnesProviderVO onesProviderVO) {
+ OnesProviderResponse response = new OnesProviderResponse();
+ response.setId(onesProviderVO.getUuid());
+ PhysicalNetwork pnw = ApiDBUtils.findPhysicalNetworkById(onesProviderVO.getPhysicalNetworkId());
+ if (pnw != null) {
+ response.setPhysicalNetworkId(pnw.getUuid());
+ }
+ response.setProviderName(onesProviderVO.getProviderName());
+ response.setDeviceName(onesProviderVO.getDeviceName());
+ response.setUrl(onesProviderVO.getUrl());
+ response.setFabricName(onesProviderVO.getFabricName());
+ response.setGatewayUrl(onesProviderVO.getGatewayUrl());
+ response.setGatewayTokenSet(onesProviderVO.getGatewayToken() != null);
+ response.setObjectName("onesprovider");
+ return response;
+ }
+
+ @Override
+ public boolean deleteOnesProvider(final DeleteOnesProviderCmd cmd) {
+ OnesProviderVO device = onesProviderDao.findById(cmd.getId());
+ if (device == null) {
+ throw new InvalidParameterValueException("Could not find an Aviz ONES provider with id " + cmd.getId());
+ }
+
+ Long physicalNetworkId = device.getPhysicalNetworkId();
+ List networkList = networkDao.listByPhysicalNetwork(physicalNetworkId);
+ if (networkList != null) {
+ for (NetworkVO network : networkList) {
+ // a Shutdown network still owns its ONES tenant, and needs this provider to delete it
+ if (networkModel.isProviderForNetwork(AVIZ_ONES, network.getId())
+ && (network.getState() != Network.State.Destroy
+ || networkDetailsDao.findDetail(network.getId(), DETAIL_TENANT_NAME) != null)) {
+ throw new CloudRuntimeException("This Aviz ONES provider cannot be deleted: guest network " + network.getUuid()
+ + " still uses it (delete the network first)");
+ }
+ }
+ }
+
+ HostVO onesHost = hostDao.findById(device.getHostId());
+ if (onesHost != null) {
+ onesHost.setResourceState(ResourceState.Maintenance);
+ hostDao.update(onesHost.getId(), onesHost);
+ resourceMgr.deleteHost(onesHost.getId(), false, false);
+ }
+
+ onesProviderDao.remove(device.getId());
+ return true;
+ }
+
+ private static String orNull(final String v, final String current) {
+ return v == null ? current : (v.trim().isEmpty() ? null : v.trim());
+ }
+
+ @Override
+ public OnesProviderVO updateOnesProvider(final UpdateOnesProviderCmd cmd) {
+ OnesProviderVO vo = onesProviderDao.findById(cmd.getId());
+ if (vo == null) {
+ throw new InvalidParameterValueException("Could not find an Aviz ONES provider with id " + cmd.getId());
+ }
+ vo.setGatewayUrl(orNull(cmd.getGatewayUrl(), vo.getGatewayUrl()));
+ vo.setGatewayToken(orNull(cmd.getGatewayToken(), vo.getGatewayToken()));
+ vo.setGatewayCaCertPath(orNull(cmd.getGatewayCaCertPath(), vo.getGatewayCaCertPath()));
+ onesProviderDao.update(vo.getId(), vo);
+ return onesProviderDao.findById(vo.getId());
+ }
+
+ @Override
+ public List listOnesProviders(final ListOnesProvidersCmd cmd) {
+ Long physicalNetworkId = cmd.getPhysicalNetworkId();
+ Long id = cmd.getId();
+ List responseList = new ArrayList<>();
+
+ if (physicalNetworkId == null && id == null) {
+ throw new InvalidParameterValueException("Either physical network Id or Aviz ONES provider Id must be specified");
+ }
+
+ if (id != null) {
+ OnesProviderVO device = onesProviderDao.findById(id);
+ if (device == null) {
+ throw new InvalidParameterValueException("Could not find an Aviz ONES provider with id: " + id);
+ }
+ responseList.add(device);
+ } else {
+ PhysicalNetworkVO physicalNetwork = physicalNetworkDao.findById(physicalNetworkId);
+ if (physicalNetwork == null) {
+ throw new InvalidParameterValueException("Could not find a physical network with id: " + physicalNetworkId);
+ }
+ responseList = onesProviderDao.listByPhysicalNetwork(physicalNetworkId);
+ }
+
+ return responseList;
+ }
+
+ @Override
+ public HostVO createHostVOForConnectedAgent(final HostVO host, final StartupCommand[] cmd) {
+ return null;
+ }
+
+ @Override
+ public HostVO createHostVOForDirectConnectAgent(final HostVO host, final StartupCommand[] startup, final ServerResource resource,
+ final Map details, final List hostTags) {
+ if (!(startup[0] instanceof StartupOnesCommand)) {
+ return null;
+ }
+ host.setType(Host.Type.L2Networking);
+ return host;
+ }
+
+ @Override
+ public DeleteHostAnswer deleteHost(final HostVO host, final boolean isForced, final boolean isForceDeleteStorage) throws UnableDeleteHostException {
+ if (host.getType() != Host.Type.L2Networking) {
+ return null;
+ }
+ return new DeleteHostAnswer(true);
+ }
+
+ // ------------------------------------------------------------------ edge services on the Aviz Gateway
+
+ protected OnesEdgeBuilder edgeBuilder() {
+ return new OnesEdgeBuilder(ipAddressDao, portForwardingRulesDao, loadBalancerDao, lbVmMapDao, lbStickinessPolicyDao,
+ firewallRulesDao, firewallRulesCidrsDao, networkModel);
+ }
+
+ private boolean hasEdge(final Network network) {
+ return canHandle(network, Service.SourceNat) || canHandle(network, Service.PortForwarding) || canHandle(network, Service.Lb);
+ }
+
+ private static boolean gatewayConfigured(final OnesProviderVO device) {
+ return device.getGatewayUrl() != null && device.getGatewayToken() != null;
+ }
+
+ /**
+ * Puts the network's whole edge (from CloudStack's records) on the Aviz Gateway. Nothing to do
+ * before the network's first host joined the tenant: until then the gateway does not have the
+ * tenant, and prepare() calls this once it does.
+ */
+ protected boolean syncEdge(final Network network) {
+ String error = edgeSync(network);
+ if (error != null) {
+ logger.error("Aviz Gateway edge of network {}: {}", network, error);
+ }
+ return error == null;
+ }
+
+ /** As syncEdge, for a rule change: CloudStack reads false as "not this provider's", so a failure throws. */
+ protected boolean applyEdge(final Network network) throws ResourceUnavailableException {
+ String error = edgeSync(network);
+ if (error != null) {
+ throw new ResourceUnavailableException("Aviz Gateway edge of network " + network.getUuid() + ": " + error, Network.class, network.getId());
+ }
+ return true;
+ }
+
+ /** @return null when the gateway has the network's edge, else what went wrong */
+ private String edgeSync(final Network network) {
+ if (getAllocatedHosts(network.getId()).isEmpty()) {
+ return null;
+ }
+ OnesProviderVO device = findProviderOrThrow(network);
+ if (!gatewayConfigured(device)) {
+ return "the network uses Aviz ONES edge services but its provider has no Aviz Gateway (updateOnesProvider gatewayurl, gatewaytoken)";
+ }
+ String[] error = new String[1];
+ try {
+ boolean locked = underLock("ones.edge." + network.getId(), () -> {
+ ConfigureOnesEdgeCommand cmd = edgeBuilder().build(network, getTenantName(network), canHandle(network, Service.SourceNat),
+ canHandle(network, Service.PortForwarding), canHandle(network, Service.Lb), canHandle(network, Service.Firewall));
+ cmd.setWait(EDGE_WAIT_S);
+ Answer answer = agentMgr.easySend(device.getHostId(), cmd);
+ if (answer == null || !answer.getResult()) {
+ error[0] = answer != null ? answer.getDetails() : "no answer from the Aviz ONES resource";
+ }
+ return true;
+ });
+ return locked ? error[0] : "could not lock the network's edge";
+ } catch (CloudRuntimeException e) {
+ return e.getMessage();
+ }
+ }
+
+ /**
+ * Runs work under a cluster-wide lock (one change per network at a time, across management
+ * servers): "ones.hosts.<id>" for the network's host list, "ones.edge.<id>" for its edge.
+ * @return false when the lock could not be had
+ */
+ protected boolean underLock(final String name, final BooleanSupplier work) {
+ GlobalLock lock = GlobalLock.getInternLock(name);
+ try {
+ if (!lock.lock(EDGE_LOCK_S)) {
+ logger.warn("Could not get lock {}", name);
+ return false;
+ }
+ try {
+ return work.getAsBoolean();
+ } finally {
+ lock.unlock();
+ }
+ } finally {
+ lock.releaseRef();
+ }
+ }
+
+ protected void removeEdge(final Network network) {
+ String tenant = networkDetailsDao.findDetail(network.getId(), DETAIL_TENANT_NAME) != null ? getTenantName(network) : null;
+ if (tenant == null || !hasEdge(network)) {
+ return;
+ }
+ OnesProviderVO device = findProviderOrThrow(network);
+ if (!gatewayConfigured(device)) {
+ return;
+ }
+ RemoveOnesEdgeCommand cmd = new RemoveOnesEdgeCommand(tenant);
+ cmd.setWait(EDGE_WAIT_S);
+ Answer answer = agentMgr.easySend(device.getHostId(), cmd);
+ if (answer == null || !answer.getResult()) {
+ logger.warn("Could not remove the Aviz Gateway edge of network {}: {}", network, answer != null ? answer.getDetails() : "no answer");
+ }
+ }
+
+ @Override
+ public IpDeployer getIpDeployer(final Network network) {
+ return this;
+ }
+
+ /** A public address joining or leaving the network (the source NAT address among them). */
+ @Override
+ public boolean applyIps(final Network network, final List extends PublicIpAddress> ipAddress, final Set services)
+ throws ResourceUnavailableException {
+ if (!hasEdge(network)) {
+ return false;
+ }
+ return applyEdge(network);
+ }
+
+ @Override
+ public boolean applyFWRules(final Network network, final List extends FirewallRule> rules) throws ResourceUnavailableException {
+ if (!canHandle(network, Service.Firewall)) {
+ return false;
+ }
+ return applyEdge(network);
+ }
+
+ @Override
+ public boolean applyPFRules(final Network network, final List rules) throws ResourceUnavailableException {
+ if (!canHandle(network, Service.PortForwarding)) {
+ return false;
+ }
+ return applyEdge(network);
+ }
+
+ @Override
+ public boolean applyLBRules(final Network network, final List rules) throws ResourceUnavailableException {
+ if (!canHandle(network, Service.Lb)) {
+ return false;
+ }
+ return applyEdge(network);
+ }
+
+ /**
+ * What the gateway's VIPs can do: round robin, tcp or udp, one public port, and an address
+ * of its own (the gateway refuses a VIP on the source NAT address).
+ */
+ @Override
+ public boolean validateLBRule(final Network network, final LoadBalancingRule rule) {
+ if (!canHandle(network, Service.Lb)) {
+ return true;
+ }
+ if (rule.getAlgorithm() != null && !"roundrobin".equalsIgnoreCase(rule.getAlgorithm())) {
+ throw new InvalidParameterValueException("The Aviz Gateway balances round robin only, not " + rule.getAlgorithm());
+ }
+ String protocol = rule.getLbProtocol();
+ if (protocol != null && !protocol.isEmpty() && !"tcp".equalsIgnoreCase(protocol) && !"udp".equalsIgnoreCase(protocol)) {
+ throw new InvalidParameterValueException("The Aviz Gateway balances tcp or udp, not " + protocol);
+ }
+ if (rule.getSourcePortStart() != null && rule.getSourcePortEnd() != null && !rule.getSourcePortStart().equals(rule.getSourcePortEnd())) {
+ throw new InvalidParameterValueException("An Aviz Gateway VIP has one public port");
+ }
+ Long ipId = rule.getLb() != null ? rule.getLb().getSourceIpAddressId() : null;
+ IPAddressVO ip = ipId != null ? ipAddressDao.findById(ipId) : null;
+ if (ip != null && ip.isSourceNat()) {
+ throw new InvalidParameterValueException("The source NAT address " + ip.getAddress() + " cannot carry a load balancer on the Aviz Gateway; "
+ + "acquire another public IP for it");
+ }
+ return true;
+ }
+
+ /** The gateway checks backends itself (TCP, every 5 s); CloudStack health check policies are not offered. */
+ @Override
+ public List updateHealthChecks(final Network network, final List lbrules) {
+ return null;
+ }
+
+ @Override
+ public boolean handlesOnlyRulesInTransitionState() {
+ return false;
+ }
+}
diff --git a/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/service/OnesElementService.java b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/service/OnesElementService.java
new file mode 100644
index 000000000000..75a19cbae364
--- /dev/null
+++ b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/service/OnesElementService.java
@@ -0,0 +1,44 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.apache.cloudstack.network.ones.service;
+
+import java.util.List;
+
+import org.apache.cloudstack.network.ones.api.command.AddOnesProviderCmd;
+import org.apache.cloudstack.network.ones.api.command.DeleteOnesProviderCmd;
+import org.apache.cloudstack.network.ones.api.command.ListOnesProvidersCmd;
+import org.apache.cloudstack.network.ones.api.command.UpdateOnesProviderCmd;
+import org.apache.cloudstack.network.ones.api.response.OnesProviderResponse;
+import org.apache.cloudstack.network.ones.dao.OnesProviderVO;
+
+import com.cloud.utils.component.PluggableService;
+
+public interface OnesElementService extends PluggableService {
+
+ OnesProviderVO addOnesProvider(AddOnesProviderCmd cmd);
+
+ OnesProviderResponse createOnesProviderResponse(OnesProviderVO onesProviderVO);
+
+ boolean deleteOnesProvider(DeleteOnesProviderCmd cmd);
+
+ OnesProviderVO updateOnesProvider(UpdateOnesProviderCmd cmd);
+
+ List listOnesProviders(ListOnesProvidersCmd cmd);
+}
diff --git a/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/service/OnesGuestNetworkGuru.java b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/service/OnesGuestNetworkGuru.java
new file mode 100644
index 000000000000..31634196306b
--- /dev/null
+++ b/plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/service/OnesGuestNetworkGuru.java
@@ -0,0 +1,347 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.apache.cloudstack.network.ones.service;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+
+import javax.inject.Inject;
+
+import org.apache.cloudstack.network.ones.agent.api.CreateOnesTenantAnswer;
+import org.apache.cloudstack.network.ones.agent.api.CreateOnesTenantCommand;
+import org.apache.cloudstack.network.ones.agent.api.DeallocateOnesServersCommand;
+import org.apache.cloudstack.network.ones.agent.api.DeleteOnesTenantCommand;
+import org.apache.cloudstack.network.ones.dao.OnesProviderDao;
+import org.apache.cloudstack.network.ones.dao.OnesProviderVO;
+
+import com.cloud.agent.AgentManager;
+import com.cloud.agent.api.Answer;
+import com.cloud.dc.DataCenter.NetworkType;
+import com.cloud.deploy.DeployDestination;
+import com.cloud.deploy.DeploymentPlan;
+import com.cloud.exception.InsufficientAddressCapacityException;
+import com.cloud.exception.InsufficientVirtualNetworkCapacityException;
+import com.cloud.host.dao.HostDao;
+import com.cloud.network.Network.GuestType;
+import com.cloud.network.Network.State;
+import com.cloud.network.Network;
+import com.cloud.network.NetworkProfile;
+import com.cloud.network.Networks.BroadcastDomainType;
+import com.cloud.network.PhysicalNetwork.IsolationMethod;
+import com.cloud.network.PhysicalNetwork;
+import com.cloud.network.dao.NetworkDetailVO;
+import com.cloud.network.dao.NetworkDetailsDao;
+import com.cloud.network.dao.NetworkVO;
+import com.cloud.network.dao.PhysicalNetworkVO;
+import com.cloud.network.guru.GuestNetworkGuru;
+import com.cloud.offering.NetworkOffering;
+import com.cloud.offerings.dao.NetworkOfferingServiceMapDao;
+import com.cloud.user.Account;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.utils.net.NetUtils;
+import com.cloud.vm.NicProfile;
+import com.cloud.vm.ReservationContext;
+import com.cloud.vm.VirtualMachineProfile;
+
+/**
+ * One CloudStack isolated guest network = one ONES tenant.
+ *
+ * ONES, not CloudStack, chooses everything about a tenant (VLAN, VNIs, subnet, compute IP pool),
+ * so the tenant is created when the network is created (design), and the network takes ONES's
+ * values from the start:
+ *
+ * broadcast vlan://<tenant vlanId>: the VLAN ONES trunks to the hypervisors' leaf ports.
+ * The hypervisor's guest bridge tags it like any CloudStack VLAN network; the leaf
+ * maps it into the tenant's VRF/VNIs.
+ * cidr the tenant subnet (ONES vlanSubnetCPU, e.g. 192.1.0.0/16)
+ * gateway the gateway ONES reports, or one given with createNetwork if it lies in that
+ * subnet. CloudStack makes createNetwork carry gateway/netmask for an isolated
+ * network without SourceNat, before ONES has chosen the subnet: a gateway outside
+ * the subnet ONES assigns is taken as a placeholder, and ONES's gateway is used.
+ * VM addresses only from the tenant's compute pool (ONES tenantIpPool, e.g. 192.1.64.0/18);
+ * the rest of the subnet is ONES's (leaf SVIs and the like)
+ *
+ * The network's lifecycle maps onto the tenant like this:
+ * design create the tenant (async; waits for ONES)
+ * setup record tenant name, VLAN, pool in network_details
+ * implement put the network on the tenant's VLAN
+ * allocate pick NIC addresses from the tenant pool
+ * (element prepare adds a VM's host to the tenant, shared)
+ * shutdown take the hosts out of the tenant (the network has no running VMs)
+ * trash delete the tenant
+ */
+public class OnesGuestNetworkGuru extends GuestNetworkGuru {
+
+ public static final String DETAIL_VLAN = "onesvlan";
+ public static final String DETAIL_POOL = "onesippool";
+ public static final String DETAIL_L3VNI = "onesl3vni";
+
+ /** ONES: ^[A-Za-z][A-Za-z0-9_-]{0,11}$ */
+ private static final int TENANT_NAME_HEX = 10;
+ private static final int ONES_TIMEOUT_S = 900;
+ /** Pool addresses at the bottom (.1 to .9) left to the operator, in pools big enough to spare them. */
+ static final int OPERATOR_RESERVED = 9;
+
+ /** Tenant made in design(), waiting for setup() to know the network id. Keyed by CIDR. */
+ private static final Map PENDING = new ConcurrentHashMap<>();
+ private static final Map PENDING_NAMES = new ConcurrentHashMap<>();
+
+ @Inject
+ protected OnesProviderDao onesProviderDao;
+ @Inject
+ protected HostDao hostDao;
+ @Inject
+ protected AgentManager agentMgr;
+ @Inject
+ protected NetworkDetailsDao networkDetailsDao;
+ @Inject
+ protected NetworkOfferingServiceMapDao ntwkOfferingSrvcDao;
+
+ public OnesGuestNetworkGuru() {
+ super();
+ // Its own isolation-method tag: CloudStack picks a guru by the physical network's
+ // isolation method, so a ONES physical network (isolationmethods=ONES) is never claimed
+ // by the stock VLAN gurus, and ordinary VLAN physical networks are never claimed by this.
+ _isolationMethods = new IsolationMethod[]{new IsolationMethod("ONES", OnesElement.AVIZ_ONES.getName())};
+ }
+
+ @Override
+ protected boolean canHandle(final NetworkOffering offering, final NetworkType networkType, final PhysicalNetwork physicalNetwork) {
+ return networkType == NetworkType.Advanced
+ && isMyTrafficType(offering.getTrafficType())
+ && offering.getGuestType() == GuestType.Isolated
+ && isMyIsolationMethod(physicalNetwork)
+ && ntwkOfferingSrvcDao.canProviderSupportServiceInNetworkOffering(offering.getId(), Network.Service.Connectivity,
+ OnesElement.AVIZ_ONES);
+ }
+
+ private OnesProviderVO findProviderOrThrow(final long physicalNetworkId) {
+ List devices = onesProviderDao.listByPhysicalNetwork(physicalNetworkId);
+ if (devices.isEmpty()) {
+ throw new CloudRuntimeException("No Aviz ONES provider is configured on physical network " + physicalNetworkId);
+ }
+ return devices.get(0);
+ }
+
+ private String detail(final long networkId, final String key) {
+ NetworkDetailVO d = networkDetailsDao.findDetail(networkId, key);
+ return d != null ? d.getValue() : null;
+ }
+
+ static String newTenantName() {
+ return "cs" + UUID.randomUUID().toString().replace("-", "").substring(0, TENANT_NAME_HEX);
+ }
+
+ @Override
+ public Network design(final NetworkOffering offering, final DeploymentPlan plan, final Network userSpecified, final String name,
+ final Long vpcId, final Account owner) {
+ PhysicalNetworkVO physnet = _physicalNetworkDao.findById(plan.getPhysicalNetworkId());
+ if (physnet == null || !canHandle(offering, _dcDao.findById(plan.getDataCenterId()).getNetworkType(), physnet)) {
+ logger.debug("Aviz ONES guru is not designing network {}", name);
+ return null;
+ }
+ OnesProviderVO device = findProviderOrThrow(physnet.getId());
+
+ NetworkVO network = (NetworkVO) super.design(offering, plan, userSpecified, name, vpcId, owner);
+ if (network == null) {
+ return null;
+ }
+
+ String tenantName = newTenantName();
+ CreateOnesTenantCommand cmd = new CreateOnesTenantCommand(device.getFabricName(), tenantName,
+ "CloudStack network " + (name != null ? name : ""), -1);
+ cmd.setWait(ONES_TIMEOUT_S);
+ Answer raw = agentMgr.easySend(device.getHostId(), cmd);
+ if (!(raw instanceof CreateOnesTenantAnswer) || !raw.getResult()) {
+ throw new CloudRuntimeException("Aviz ONES could not create tenant " + tenantName + " for network " + name + ": "
+ + (raw != null ? raw.getDetails() : "no answer from the Aviz ONES resource"));
+ }
+ CreateOnesTenantAnswer t = (CreateOnesTenantAnswer) raw;
+ String gateway;
+ try {
+ gateway = chooseGateway(tenantName, t, userSpecified != null ? userSpecified.getGateway() : null);
+ } catch (RuntimeException e) {
+ deleteTenant(device, tenantName); // never leave an orphan tenant in ONES
+ throw e;
+ }
+ String subnet = t.getSubnet();
+ network.setBroadcastDomainType(BroadcastDomainType.Vlan);
+ network.setCidr(subnet);
+ network.setNetworkCidr(null);
+ network.setGateway(gateway);
+ PENDING.put(subnet, t);
+ PENDING_NAMES.put(subnet, tenantName);
+ logger.info("ONES tenant {} for network {}: vlan {}, subnet {}, pool {}, gateway {}, l3vni {}", tenantName, name,
+ t.getVlanId(), subnet, t.getIpPool(), gateway, t.getL3Vni());
+ return network;
+ }
+
+ /**
+ * The network's gateway: one given with createNetwork if it lies in the subnet ONES assigned,
+ * else the gateway ONES reports for the tenant. A requested gateway outside that subnet is the
+ * placeholder createNetwork needs for an isolated network without SourceNat.
+ */
+ private String chooseGateway(final String tenantName, final CreateOnesTenantAnswer t, final String requested) {
+ if (t.getVlanId() == null || t.getSubnet() == null || t.getIpPool() == null) {
+ throw new CloudRuntimeException("Aviz ONES tenant " + tenantName + " has no VLAN, subnet or compute IP pool: " + t.getDetails());
+ }
+ String subnet = t.getSubnet();
+ if (requested != null && NetUtils.isIpWithInCidrRange(requested, subnet)) {
+ return requested;
+ }
+ if (requested != null) {
+ logger.info("Gateway {} is outside the subnet {} ONES assigned to tenant {}: taken as a placeholder, using ONES's gateway {}",
+ requested, subnet, tenantName, t.getGateway());
+ }
+ String gateway = t.getGateway();
+ if (gateway == null || !NetUtils.isIpWithInCidrRange(gateway, subnet)) {
+ throw new CloudRuntimeException("No usable gateway for ONES tenant " + tenantName + " (subnet " + subnet
+ + ", ONES gateway " + gateway + "); pass gateway= inside the subnet to createNetwork");
+ }
+ return gateway;
+ }
+
+ private void deleteTenant(final OnesProviderVO device, final String tenantName) {
+ DeleteOnesTenantCommand cmd = new DeleteOnesTenantCommand(device.getFabricName(), tenantName);
+ cmd.setWait(ONES_TIMEOUT_S);
+ Answer a = agentMgr.easySend(device.getHostId(), cmd);
+ if (a == null || !a.getResult()) {
+ logger.error("Could not delete ONES tenant {}: {}", tenantName, a != null ? a.getDetails() : "no answer");
+ }
+ }
+
+ @Override
+ public void setup(final Network network, final long networkId) {
+ super.setup(network, networkId);
+ CreateOnesTenantAnswer t = network.getCidr() != null ? PENDING.remove(network.getCidr()) : null;
+ String tenantName = network.getCidr() != null ? PENDING_NAMES.remove(network.getCidr()) : null;
+ if (t == null || tenantName == null) {
+ return;
+ }
+ networkDetailsDao.addDetail(networkId, OnesElement.DETAIL_TENANT_NAME, tenantName, false);
+ networkDetailsDao.addDetail(networkId, DETAIL_VLAN, String.valueOf(t.getVlanId()), false);
+ networkDetailsDao.addDetail(networkId, DETAIL_POOL, t.getIpPool(), false);
+ if (t.getL3Vni() != null) {
+ networkDetailsDao.addDetail(networkId, DETAIL_L3VNI, String.valueOf(t.getL3Vni()), false);
+ }
+ }
+
+ @Override
+ public Network implement(final Network network, final NetworkOffering offering, final DeployDestination dest, final ReservationContext context)
+ throws InsufficientVirtualNetworkCapacityException {
+ assert network.getState() == State.Implementing : "Why are we implementing " + network;
+ String vlan = detail(network.getId(), DETAIL_VLAN);
+ if (vlan == null) {
+ throw new CloudRuntimeException("No ONES VLAN is on record for network " + network.getUuid());
+ }
+ NetworkVO implemented = new NetworkVO(network.getTrafficType(), network.getMode(), BroadcastDomainType.Vlan, network.getNetworkOfferingId(),
+ State.Allocated, network.getDataCenterId(), network.getPhysicalNetworkId(), offering.isRedundantRouter());
+ implemented.setCidr(network.getCidr());
+ implemented.setGateway(network.getGateway());
+ implemented.setBroadcastUri(BroadcastDomainType.Vlan.toUri(vlan));
+ return implemented;
+ }
+
+ /** NIC addresses come from the tenant's compute pool, never from the rest of the subnet. */
+ @Override
+ public NicProfile allocate(final Network network, final NicProfile nic, final VirtualMachineProfile vm)
+ throws InsufficientVirtualNetworkCapacityException, InsufficientAddressCapacityException {
+ String pool = detail(network.getId(), DETAIL_POOL);
+ if (nic != null && nic.getRequestedIPv4() == null && pool != null && network.getGateway() != null) {
+ nic.setRequestedIPv4(freeAddress(network, pool));
+ }
+ return super.allocate(network, nic, vm);
+ }
+
+ /**
+ * The first free address in the pool. The pool's bottom {@value #OPERATOR_RESERVED} addresses
+ * (.1 to .9) are left to the operator, but only in a pool big enough to spare them (at least
+ * twice as many usable addresses, i.e. a /27 or bigger); a smaller pool is used from .1.
+ */
+ String freeAddress(final Network network, final String pool) throws InsufficientAddressCapacityException {
+ Set used = new HashSet<>(_nicDao.listIpAddressInNetwork(network.getId()));
+ used.add(network.getGateway());
+ String[] range = NetUtils.getIpRangeFromCidr(pool.split("/")[0], Integer.parseInt(pool.split("/")[1]));
+ long first = NetUtils.ip2Long(range[0]);
+ long last = NetUtils.ip2Long(range[1]);
+ long usable = last - first + 1;
+ long start = usable >= 2L * OPERATOR_RESERVED ? first + OPERATOR_RESERVED : first;
+ for (long ip = start; ip <= last; ip++) {
+ String a = NetUtils.long2Ip(ip);
+ if (!used.contains(a)) {
+ return a;
+ }
+ }
+ throw new InsufficientAddressCapacityException("ONES tenant pool " + pool + " is full", Network.class, network.getId());
+ }
+
+ private List allocatedHosts(final long networkId) {
+ String v = detail(networkId, OnesElement.DETAIL_ALLOCATED_HOSTS);
+ return v == null || v.isEmpty() ? new ArrayList<>() : new ArrayList<>(Arrays.asList(v.split(",")));
+ }
+
+ /** Takes every host this network added out of the tenant. */
+ private void removeHosts(final long networkId, final OnesProviderVO device, final String tenantName) {
+ List hosts = allocatedHosts(networkId);
+ if (hosts.isEmpty()) {
+ return;
+ }
+ DeallocateOnesServersCommand cmd = new DeallocateOnesServersCommand(device.getFabricName(), tenantName, hosts);
+ cmd.setWait(ONES_TIMEOUT_S);
+ Answer a = agentMgr.easySend(device.getHostId(), cmd);
+ if (a == null || !a.getResult()) {
+ logger.warn("Could not remove hosts {} from ONES tenant {}: {}", hosts, tenantName, a != null ? a.getDetails() : "no answer");
+ return;
+ }
+ networkDetailsDao.removeDetail(networkId, OnesElement.DETAIL_ALLOCATED_HOSTS);
+ }
+
+ @Override
+ public void shutdown(final NetworkProfile profile, final NetworkOffering offering) {
+ String tenantName = detail(profile.getId(), OnesElement.DETAIL_TENANT_NAME);
+ if (tenantName != null) {
+ OnesProviderVO device = findProviderOrThrow(profile.getPhysicalNetworkId());
+ removeHosts(profile.getId(), device, tenantName);
+ }
+ super.shutdown(profile, offering);
+ }
+
+ @Override
+ public boolean trash(final Network network, final NetworkOffering offering) {
+ String tenantName = detail(network.getId(), OnesElement.DETAIL_TENANT_NAME);
+ if (tenantName != null) {
+ OnesProviderVO device = findProviderOrThrow(network.getPhysicalNetworkId());
+ removeHosts(network.getId(), device, tenantName);
+ DeleteOnesTenantCommand cmd = new DeleteOnesTenantCommand(device.getFabricName(), tenantName);
+ cmd.setWait(ONES_TIMEOUT_S);
+ Answer a = agentMgr.easySend(device.getHostId(), cmd);
+ if (a == null || !a.getResult()) {
+ logger.error("Could not delete ONES tenant {}: {}", tenantName, a != null ? a.getDetails() : "no answer");
+ return false;
+ }
+ networkDetailsDao.removeDetails(network.getId());
+ }
+ return super.trash(network, offering);
+ }
+}
diff --git a/plugins/network-elements/aviz-ones/src/main/resources/META-INF/cloudstack/ones/module.properties b/plugins/network-elements/aviz-ones/src/main/resources/META-INF/cloudstack/ones/module.properties
new file mode 100644
index 000000000000..73597205730d
--- /dev/null
+++ b/plugins/network-elements/aviz-ones/src/main/resources/META-INF/cloudstack/ones/module.properties
@@ -0,0 +1,21 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you 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.
+#
+
+name=ones
+parent=network
diff --git a/plugins/network-elements/aviz-ones/src/main/resources/META-INF/cloudstack/ones/spring-ones-context.xml b/plugins/network-elements/aviz-ones/src/main/resources/META-INF/cloudstack/ones/spring-ones-context.xml
new file mode 100644
index 000000000000..b9be1f1b2edc
--- /dev/null
+++ b/plugins/network-elements/aviz-ones/src/main/resources/META-INF/cloudstack/ones/spring-ones-context.xml
@@ -0,0 +1,38 @@
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/plugins/network-elements/aviz-ones/src/test/java/org/apache/cloudstack/network/ones/client/AvizGatewayClientTest.java b/plugins/network-elements/aviz-ones/src/test/java/org/apache/cloudstack/network/ones/client/AvizGatewayClientTest.java
new file mode 100644
index 000000000000..81b0a03fb018
--- /dev/null
+++ b/plugins/network-elements/aviz-ones/src/test/java/org/apache/cloudstack/network/ones/client/AvizGatewayClientTest.java
@@ -0,0 +1,416 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.apache.cloudstack.network.ones.client;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.security.KeyPair;
+import java.security.KeyStore;
+import java.security.SecureRandom;
+import java.security.Security;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+
+import org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand.FirewallRule;
+import org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand.PortMapping;
+import org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand.Vip;
+import org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand;
+import org.apache.cloudstack.network.ones.agent.api.RemoveOnesEdgeCommand;
+import org.bouncycastle.jce.provider.BouncyCastleProvider;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import com.cloud.agent.api.Answer;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpsConfigurator;
+import com.sun.net.httpserver.HttpsServer;
+
+/** AvizGatewayClient against a fake Aviz Gateway (/api/v1) over verified TLS. */
+public class AvizGatewayClientTest {
+
+ private static final String TOKEN = "op-token";
+ private static final String TENANT = "cs0123456789";
+
+ private static KeyPair caKeys;
+ private static X509Certificate caCert;
+ private static File caPem;
+
+ private HttpsServer server;
+ private String url;
+
+ // fake gateway state
+ private final Set tenants = ConcurrentHashMap.newKeySet();
+ private final AtomicInteger tenantMissingFor = new AtomicInteger();
+ private final Map internetAccess = new ConcurrentHashMap<>();
+ private final Map vips = new ConcurrentHashMap<>(); // name -> VIP (one tenant)
+ private final Map firewallRules = new ConcurrentHashMap<>();
+ private final List requests = Collections.synchronizedList(new ArrayList<>());
+ private volatile boolean cannotApply;
+ private volatile String tenantLoopback = "10.1.255.1/32";
+
+ @BeforeClass
+ public static void makeCertificates() throws Exception {
+ if (Security.getProvider("BC") == null) {
+ Security.addProvider(new BouncyCastleProvider());
+ }
+ caKeys = TestCertificates.keyPair();
+ caCert = TestCertificates.certificate(caKeys, null, caKeys.getPublic(), "CN=Test gateway CA", true, false);
+ File dir = Files.createTempDirectory("gw-test-").toFile();
+ caPem = TestCertificates.pem(new File(dir, "ca.crt"), caCert);
+ }
+
+ @Before
+ public void startFakeGateway() throws Exception {
+ KeyPair serverKeys = TestCertificates.keyPair();
+ X509Certificate serverCert = TestCertificates.certificate(caKeys, caCert, serverKeys.getPublic(), "CN=localhost", false, true);
+ KeyStore keyStore = KeyStore.getInstance("PKCS12");
+ keyStore.load(null, null);
+ keyStore.setKeyEntry("server", serverKeys.getPrivate(), "changeit".toCharArray(), new X509Certificate[]{serverCert, caCert});
+ KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
+ kmf.init(keyStore, "changeit".toCharArray());
+ SSLContext ssl = SSLContext.getInstance("TLS");
+ ssl.init(kmf.getKeyManagers(), null, new SecureRandom());
+
+ server = HttpsServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ server.setHttpsConfigurator(new HttpsConfigurator(ssl));
+ server.createContext("/", this::handle);
+ server.start();
+ url = "https://127.0.0.1:" + server.getAddress().getPort() + "/";
+ tenants.add(TENANT);
+ }
+
+ @After
+ public void stopFakeGateway() {
+ server.stop(0);
+ }
+
+ // ------------------------------------------------------------------ fake gateway
+
+ private static final String APPLIED = "{\"revision\": 1, \"converged\": true, \"applied\": 1, \"failed\": 0, \"blocked\": 0, \"detail\": []}";
+
+ private void handle(final HttpExchange ex) throws IOException {
+ String method = ex.getRequestMethod();
+ String path = ex.getRequestURI().getPath();
+ String query = ex.getRequestURI().getQuery();
+ String body = new String(ex.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
+ requests.add(method + " " + path);
+ if (!("Bearer " + TOKEN).equals(ex.getRequestHeaders().getFirst("Authorization"))) {
+ reply(ex, 401, "{\"detail\": \"not authenticated\"}");
+ return;
+ }
+ String tenantBase = "/api/v1/tenants/" + TENANT;
+ String applied = cannotApply ? APPLIED.replace("\"failed\": 0", "\"failed\": 1") : APPLIED;
+ if ("GET".equals(method) && path.equals(tenantBase)) {
+ boolean there = tenants.contains(TENANT) && tenantMissingFor.getAndDecrement() <= 0;
+ JsonObject t = new JsonObject();
+ t.addProperty("name", TENANT);
+ t.addProperty("loopback", tenantLoopback);
+ reply(ex, there ? 200 : 404, there ? t.toString() : "{\"detail\": \"no such tenant\"}");
+ } else if (path.equals(tenantBase + "/internet-access")) {
+ if ("PUT".equals(method)) {
+ internetAccess.put(TENANT, JsonParser.parseString(body).getAsJsonObject());
+ reply(ex, 200, applied);
+ } else if ("DELETE".equals(method)) {
+ reply(ex, internetAccess.remove(TENANT) != null ? 200 : 404, internetAccess.isEmpty() ? applied : "{}");
+ }
+ } else if (path.equals(tenantBase + "/lb/vips")) {
+ if ("GET".equals(method)) {
+ JsonArray a = new JsonArray();
+ vips.values().forEach(a::add);
+ reply(ex, 200, a.toString());
+ } else {
+ JsonObject v = JsonParser.parseString(body).getAsJsonObject();
+ String name = v.get("name").getAsString();
+ boolean checked = !v.has("health") || !"none".equals(v.getAsJsonObject("health").get("type").getAsString());
+ if (checked && tenantLoopback == null) {
+ reply(ex, 422, "{\"detail\": \"health checks on an L3VNI tenant need the tenant's loopback\"}");
+ return;
+ }
+ if (vips.containsKey(name)) {
+ reply(ex, 409, "{\"detail\": \"exists\"}");
+ return;
+ }
+ vips.put(name, v);
+ reply(ex, 201, applied);
+ }
+ } else if (path.startsWith(tenantBase + "/lb/vips/")) {
+ String name = path.substring((tenantBase + "/lb/vips/").length());
+ if ("PUT".equals(method)) {
+ if (!vips.containsKey(name)) {
+ reply(ex, 404, "{\"detail\": \"no such VIP\"}");
+ return;
+ }
+ vips.put(name, JsonParser.parseString(body).getAsJsonObject());
+ reply(ex, 200, applied);
+ } else if ("DELETE".equals(method)) {
+ reply(ex, vips.remove(name) != null ? 200 : 404, applied);
+ }
+ } else if ("GET".equals(method) && path.equals("/api/v1/firewall/rules")) {
+ JsonArray a = new JsonArray();
+ for (JsonObject r : firewallRules.values()) {
+ if (query == null || query.equals("tenant=" + r.get("tenant").getAsString())) {
+ a.add(r);
+ }
+ }
+ reply(ex, 200, a.toString());
+ } else if (path.startsWith("/api/v1/firewall/rules/")) {
+ String name = path.substring("/api/v1/firewall/rules/".length());
+ if ("PUT".equals(method)) {
+ JsonObject rule = JsonParser.parseString(body).getAsJsonObject();
+ if (rule.get("established").getAsBoolean() && !"permit".equals(rule.get("action").getAsString())) {
+ reply(ex, 422, "{\"detail\": \"established (reflect) only makes sense on a permit\"}");
+ return;
+ }
+ firewallRules.put(name, rule);
+ reply(ex, 200, applied);
+ } else if ("DELETE".equals(method)) {
+ reply(ex, firewallRules.remove(name) != null ? 200 : 404, applied);
+ }
+ } else {
+ reply(ex, 404, "{\"detail\": \"not found\"}");
+ }
+ }
+
+ private static void reply(final HttpExchange ex, final int status, final String body) throws IOException {
+ byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
+ ex.getResponseHeaders().set("Content-Type", "application/json");
+ ex.sendResponseHeaders(status, bytes.length);
+ try (OutputStream os = ex.getResponseBody()) {
+ os.write(bytes);
+ }
+ }
+
+ private void existingVip(final String name) {
+ JsonObject v = new JsonObject();
+ v.addProperty("name", name);
+ vips.put(name, v);
+ }
+
+ private void existingRule(final String name, final String tenant) {
+ JsonObject r = new JsonObject();
+ r.addProperty("name", name);
+ r.addProperty("tenant", tenant);
+ firewallRules.put(name, r);
+ }
+
+ private AvizGatewayClient client(final String token) {
+ AvizGatewayClient c = new AvizGatewayClient(url, token, caPem.getAbsolutePath());
+ c.tenantPollMs = 10;
+ c.tenantWaitMs = 500;
+ return c;
+ }
+
+ private static ConfigureOnesEdgeCommand edge(final String sourceNat, final List mappings) {
+ return new ConfigureOnesEdgeCommand(TENANT, sourceNat, mappings,
+ Collections.singletonList(new Vip("cs-lb-9", "203.0.113.102", 80, "tcp", 8080, Arrays.asList("10.1.64.10", "10.1.64.12"), true)),
+ Arrays.asList(new FirewallRule(TENANT + "-fw-0", "198.51.100.0/24", "10.1.64.10/32", "tcp", 22, true),
+ new FirewallRule(TENANT + "-fw-1", "0.0.0.0/0", "10.1.64.10/32", "tcp", 22, false)));
+ }
+
+ private static List ssh() {
+ return Collections.singletonList(new PortMapping("203.0.113.101", "10.1.64.10", "tcp", 2222, 22));
+ }
+
+ private int indexOf(final String request) {
+ int i = requests.indexOf(request);
+ Assert.assertTrue(request + " not in " + requests, i >= 0);
+ return i;
+ }
+
+ // ------------------------------------------------------------------ configure
+
+ @Test
+ public void configurePutsTheWholeEdgeOnTheGateway() {
+ Answer a = client(TOKEN).configureEdge(edge("203.0.113.100", ssh()));
+
+ Assert.assertTrue(a.getDetails(), a.getResult());
+ JsonObject access = internetAccess.get(TENANT);
+ Assert.assertEquals("203.0.113.100", access.getAsJsonArray("pool").get(0).getAsString());
+ Assert.assertTrue(access.get("enabled").getAsBoolean());
+ JsonObject e = access.getAsJsonArray("elastic_ips").get(0).getAsJsonObject();
+ Assert.assertEquals("203.0.113.101", e.get("external").getAsString());
+ Assert.assertEquals("10.1.64.10", e.get("local").getAsString());
+ Assert.assertEquals(2222, e.get("external_port").getAsInt());
+ Assert.assertEquals(22, e.get("local_port").getAsInt());
+
+ JsonObject vip = vips.get("cs-lb-9");
+ Assert.assertEquals("203.0.113.102", vip.get("address").getAsString());
+ Assert.assertEquals(8080, vip.get("backend_port").getAsInt());
+ Assert.assertEquals(2, vip.getAsJsonArray("backends").size());
+ Assert.assertTrue(vip.get("src_ip_sticky").getAsBoolean());
+
+ JsonObject permit = firewallRules.get(TENANT + "-fw-0");
+ Assert.assertEquals(TENANT, permit.get("tenant").getAsString());
+ Assert.assertEquals("198.51.100.0/24", permit.get("src").getAsString());
+ Assert.assertEquals("10.1.64.10/32", permit.get("dst").getAsString());
+ Assert.assertEquals("22", permit.get("dst_ports").getAsString());
+ Assert.assertEquals("permit", permit.get("action").getAsString());
+ Assert.assertTrue(permit.get("established").getAsBoolean());
+ Assert.assertEquals("deny", firewallRules.get(TENANT + "-fw-1").get("action").getAsString());
+ Assert.assertFalse(firewallRules.get(TENANT + "-fw-1").get("established").getAsBoolean());
+ }
+
+ @Test
+ public void firewallRulesGoOnBeforeAnythingIsMapped() {
+ client(TOKEN).configureEdge(edge("203.0.113.100", ssh()));
+
+ int lastRule = indexOf("PUT /api/v1/firewall/rules/" + TENANT + "-fw-1");
+ Assert.assertTrue(requests.toString(), lastRule < indexOf("PUT /api/v1/tenants/" + TENANT + "/internet-access"));
+ Assert.assertTrue(requests.toString(), lastRule < indexOf("POST /api/v1/tenants/" + TENANT + "/lb/vips"));
+ }
+
+ @Test
+ public void staleObjectsOfThePluginGoAndTheOperatorsStay() {
+ existingVip("cs-lb-3");
+ existingVip("manual-web");
+ existingRule(TENANT + "-fw-7", TENANT);
+ existingRule("ops-allow-ssh", TENANT);
+ existingRule("cs9999999999-fw-0", "cs9999999999"); // another tenant's
+
+ Assert.assertTrue(client(TOKEN).configureEdge(edge("203.0.113.100", ssh())).getResult());
+
+ Assert.assertEquals(new java.util.HashSet<>(Arrays.asList("cs-lb-9", "manual-web")), vips.keySet());
+ Assert.assertEquals(new java.util.HashSet<>(Arrays.asList(TENANT + "-fw-0", TENANT + "-fw-1", "ops-allow-ssh", "cs9999999999-fw-0")),
+ firewallRules.keySet());
+ Assert.assertTrue(requests.toString(), indexOf("DELETE /api/v1/firewall/rules/" + TENANT + "-fw-7")
+ > indexOf("PUT /api/v1/tenants/" + TENANT + "/internet-access"));
+ }
+
+ @Test
+ public void anExistingVipIsReplaced() {
+ existingVip("cs-lb-9");
+
+ Assert.assertTrue(client(TOKEN).configureEdge(edge("203.0.113.100", ssh())).getResult());
+
+ indexOf("PUT /api/v1/tenants/" + TENANT + "/lb/vips/cs-lb-9");
+ Assert.assertEquals(8080, vips.get("cs-lb-9").get("backend_port").getAsInt());
+ }
+
+ @Test
+ public void vipMembersAreHealthCheckedWhenTheTenantHasALoopback() {
+ Assert.assertTrue(client(TOKEN).configureEdge(edge("203.0.113.100", ssh())).getResult());
+ Assert.assertFalse(vips.get("cs-lb-9").has("health")); // the gateway's default TCP check
+ }
+
+ @Test
+ public void withoutATenantLoopbackVipsGoWithoutHealthChecks() {
+ tenantLoopback = null;
+
+ Answer a = client(TOKEN).configureEdge(edge("203.0.113.100", ssh()));
+
+ Assert.assertTrue(a.getDetails(), a.getResult());
+ Assert.assertEquals("none", vips.get("cs-lb-9").getAsJsonObject("health").get("type").getAsString());
+ }
+
+ @Test
+ public void itWaitsForOnesToPutTheTenantOnTheGateway() {
+ tenantMissingFor.set(3);
+
+ Assert.assertTrue(client(TOKEN).configureEdge(edge("203.0.113.100", ssh())).getResult());
+ Assert.assertEquals(4, Collections.frequency(requests, "GET /api/v1/tenants/" + TENANT));
+ }
+
+ @Test
+ public void aTenantThatNeverArrivesFailsAndChangesNothing() {
+ tenants.clear();
+
+ Answer a = client(TOKEN).configureEdge(edge("203.0.113.100", ssh()));
+
+ Assert.assertFalse(a.getResult());
+ Assert.assertTrue(a.getDetails(), a.getDetails().contains("does not have the tenant"));
+ Assert.assertTrue(internetAccess.isEmpty() && vips.isEmpty() && firewallRules.isEmpty());
+ }
+
+ @Test
+ public void withoutASourceNatAddressInternetAccessGoes() {
+ JsonObject old = new JsonObject();
+ internetAccess.put(TENANT, old);
+
+ Assert.assertTrue(client(TOKEN).configureEdge(edge(null, Collections.emptyList())).getResult());
+ Assert.assertFalse(internetAccess.containsKey(TENANT));
+ }
+
+ @Test
+ public void portForwardsWithoutASourceNatAddressFail() {
+ Answer a = client(TOKEN).configureEdge(edge(null, ssh()));
+
+ Assert.assertFalse(a.getResult());
+ Assert.assertTrue(a.getDetails(), a.getDetails().contains("source NAT"));
+ }
+
+ @Test
+ public void whatTheGatewayCannotApplyFails() {
+ cannotApply = true;
+
+ Answer a = client(TOKEN).configureEdge(edge("203.0.113.100", ssh()));
+
+ Assert.assertFalse(a.getResult());
+ Assert.assertTrue(a.getDetails(), a.getDetails().contains("could not apply"));
+ }
+
+ @Test
+ public void aWrongTokenFails() {
+ Answer a = client("stolen").configureEdge(edge("203.0.113.100", ssh()));
+
+ Assert.assertFalse(a.getResult());
+ Assert.assertTrue(a.getDetails(), a.getDetails().contains("401"));
+ }
+
+ // ------------------------------------------------------------------ remove
+
+ @Test
+ public void removeTakesThePluginsEdgeAway() {
+ client(TOKEN).configureEdge(edge("203.0.113.100", ssh()));
+ existingVip("manual-web");
+ existingRule("ops-allow-ssh", TENANT);
+
+ Answer a = client(TOKEN).removeEdge(new RemoveOnesEdgeCommand(TENANT));
+
+ Assert.assertTrue(a.getDetails(), a.getResult());
+ Assert.assertTrue(internetAccess.isEmpty());
+ Assert.assertEquals(Collections.singleton("manual-web"), vips.keySet());
+ Assert.assertEquals(Collections.singleton("ops-allow-ssh"), firewallRules.keySet());
+ }
+
+ @Test
+ public void removingWhatIsAlreadyGoneSucceeds() {
+ Assert.assertTrue(client(TOKEN).removeEdge(new RemoveOnesEdgeCommand(TENANT)).getResult());
+ }
+}
diff --git a/plugins/network-elements/aviz-ones/src/test/java/org/apache/cloudstack/network/ones/client/OnesApiClientImplTest.java b/plugins/network-elements/aviz-ones/src/test/java/org/apache/cloudstack/network/ones/client/OnesApiClientImplTest.java
new file mode 100644
index 000000000000..a04f12bdb60a
--- /dev/null
+++ b/plugins/network-elements/aviz-ones/src/test/java/org/apache/cloudstack/network/ones/client/OnesApiClientImplTest.java
@@ -0,0 +1,618 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.apache.cloudstack.network.ones.client;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.security.KeyPair;
+import java.security.KeyStore;
+import java.security.SecureRandom;
+import java.security.Security;
+import java.security.cert.X509Certificate;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Deque;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLParameters;
+import javax.net.ssl.TrustManagerFactory;
+
+import org.apache.cloudstack.network.ones.agent.api.AllocateOnesServersCommand;
+import org.apache.cloudstack.network.ones.agent.api.CreateOnesTenantAnswer;
+import org.apache.cloudstack.network.ones.agent.api.CreateOnesTenantCommand;
+import org.apache.cloudstack.network.ones.agent.api.DeallocateOnesServersCommand;
+import org.apache.cloudstack.network.ones.agent.api.DeleteOnesTenantCommand;
+import org.bouncycastle.jce.provider.BouncyCastleProvider;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import com.cloud.agent.api.Answer;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpsConfigurator;
+import com.sun.net.httpserver.HttpsParameters;
+import com.sun.net.httpserver.HttpsServer;
+
+/**
+ * Runs OnesApiClientImpl against a fake ONES (UI login + Fabric Manager tenant API) served over
+ * mutual TLS, with a throwaway CA, server and client certificate made at test time. The fake
+ * follows the contract the client relies on: a JWT from POST /api/user/login, Bearer auth on FM
+ * (401 once the token is no longer current), "Prefer: respond-async" answered with 202 and an
+ * operationId, and GET /operations/{id} reporting the operation's status.
+ */
+public class OnesApiClientImplTest {
+
+ private static final String FABRIC = "fab1";
+ private static final String TENANT = "cs0123456789";
+
+ private static KeyPair caKeys;
+ private static X509Certificate caCert;
+ private static File pemDir;
+ private static File clientCert;
+ private static File clientKey;
+ private static File caPem;
+
+ private HttpsServer server;
+ private String fmUrl;
+ private String loginUrl;
+
+ // fake ONES state
+ private final Map tenants = new ConcurrentHashMap<>();
+ // server -> its DPU's host-facing ports ("VFs"); a server not in here has no DPU (404)
+ private final Map> vfs = new ConcurrentHashMap<>();
+ private final List requests = Collections.synchronizedList(new ArrayList<>());
+ private final List asyncRequests = Collections.synchronizedList(new ArrayList<>());
+ private final Map bodies = new ConcurrentHashMap<>();
+ private final Deque operationStatuses = new ArrayDeque<>();
+ private volatile String currentToken;
+ private volatile int logins;
+ private volatile int operations;
+ private volatile int operationPolls;
+ private volatile boolean loginRejected;
+ private volatile boolean fmRejectsEveryToken;
+ private volatile boolean asyncSupported = true;
+ private volatile int vfListStatus = 200; // anything else: FM fails the VF listing
+
+ @BeforeClass
+ public static void makeCertificates() throws Exception {
+ if (Security.getProvider("BC") == null) {
+ Security.addProvider(new BouncyCastleProvider());
+ }
+ caKeys = TestCertificates.keyPair();
+ caCert = TestCertificates.certificate(caKeys, null, caKeys.getPublic(), "CN=Test ONES CA", true, false);
+ KeyPair clientKeys = TestCertificates.keyPair();
+ X509Certificate client = TestCertificates.certificate(caKeys, caCert, clientKeys.getPublic(), "CN=cloudstack", false, false);
+
+ pemDir = Files.createTempDirectory("ones-test-").toFile();
+ clientCert = TestCertificates.pem(new File(pemDir, "client.crt"), client);
+ clientKey = TestCertificates.pem(new File(pemDir, "client.key"), clientKeys.getPrivate());
+ caPem = TestCertificates.pem(new File(pemDir, "ca.crt"), caCert);
+ }
+
+ @Before
+ public void startFakeOnes() throws Exception {
+ KeyPair serverKeys = TestCertificates.keyPair();
+ X509Certificate serverCert = TestCertificates.certificate(caKeys, caCert, serverKeys.getPublic(), "CN=localhost", false, true);
+
+ KeyStore keyStore = KeyStore.getInstance("PKCS12");
+ keyStore.load(null, null);
+ keyStore.setKeyEntry("server", serverKeys.getPrivate(), "changeit".toCharArray(), new X509Certificate[]{serverCert, caCert});
+ KeyStore trustStore = KeyStore.getInstance("PKCS12");
+ trustStore.load(null, null);
+ trustStore.setCertificateEntry("ca", caCert);
+ KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
+ kmf.init(keyStore, "changeit".toCharArray());
+ TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
+ tmf.init(trustStore);
+ final SSLContext ssl = SSLContext.getInstance("TLS");
+ ssl.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
+
+ server = HttpsServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ server.setHttpsConfigurator(new HttpsConfigurator(ssl) {
+ @Override
+ public void configure(final HttpsParameters params) {
+ SSLParameters p = ssl.getDefaultSSLParameters();
+ p.setNeedClientAuth(true);
+ params.setSSLParameters(p);
+ }
+ });
+ server.createContext("/", this::handle);
+ server.start();
+ String base = "https://127.0.0.1:" + server.getAddress().getPort();
+ loginUrl = base + "/api/user/login";
+ fmUrl = base + "/fm/"; // trailing slash: the client must strip it
+ }
+
+ @After
+ public void stopFakeOnes() {
+ server.stop(0);
+ }
+
+ // ------------------------------------------------------------------ fake ONES
+
+ private void handle(final HttpExchange ex) throws IOException {
+ String method = ex.getRequestMethod();
+ String path = ex.getRequestURI().getPath();
+ String body = new String(ex.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
+ requests.add(method + " " + path);
+ bodies.put(method + " " + path, body);
+
+ if ("/api/user/login".equals(path)) {
+ JsonObject creds = JsonParser.parseString(body).getAsJsonObject();
+ if (loginRejected || !"admin".equals(creds.get("username").getAsString())
+ || !"secret".equals(creds.get("password").getAsString())) {
+ reply(ex, 401, "{\"success\":false}");
+ return;
+ }
+ logins++;
+ currentToken = "jwt-" + logins;
+ reply(ex, 200, "{\"success\":true,\"data\":{\"token\":\"" + currentToken + "\"}}");
+ return;
+ }
+
+ String auth = ex.getRequestHeaders().getFirst("Authorization");
+ if (fmRejectsEveryToken || auth == null || !auth.equals("Bearer " + currentToken)) {
+ reply(ex, 401, "{\"message\":\"token expired\"}");
+ return;
+ }
+ boolean async = "respond-async".equals(ex.getRequestHeaders().getFirst("Prefer"));
+ if (async) {
+ asyncRequests.add(method + " " + path);
+ }
+
+ String fm = path.substring("/fm".length());
+ String tenantsPrefix = "/fabrics/" + FABRIC + "/tenants";
+ if ("GET".equals(method) && "/getAllFabrics".equals(fm)) {
+ reply(ex, 200, "{\"data\":[{\"fabricName\":\"" + FABRIC + "\"}]}");
+ } else if ("POST".equals(method) && tenantsPrefix.equals(fm)) {
+ String name = JsonParser.parseString(body).getAsJsonObject().get("tenantName").getAsString();
+ tenants.put(name, tenantRecord(name));
+ accepted(ex, async);
+ } else if (fm.startsWith(tenantsPrefix + "/")) {
+ String name = fm.substring(tenantsPrefix.length() + 1);
+ JsonObject t = tenants.get(name);
+ if ("GET".equals(method)) {
+ if (t == null) {
+ reply(ex, 404, "{\"message\":\"no such tenant\"}");
+ } else {
+ // FM sends data as a JSON-encoded string: the client must decode it
+ JsonObject wrapped = new JsonObject();
+ wrapped.add("tenant", t);
+ JsonObject r = new JsonObject();
+ r.addProperty("success", true);
+ r.addProperty("data", wrapped.toString());
+ reply(ex, 200, r.toString());
+ }
+ } else if (t == null) {
+ reply(ex, 404, "{\"message\":\"no such tenant\"}");
+ } else if ("DELETE".equals(method)) {
+ tenants.remove(name);
+ accepted(ex, async);
+ } else if ("PATCH".equals(method)) {
+ accepted(ex, async);
+ } else {
+ reply(ex, 405, "{}");
+ }
+ } else if (fm.startsWith("/fabrics/" + FABRIC + "/servers/") && fm.contains("/vf-interfaces")) {
+ // /fabrics/F/servers/S/vf-interfaces[/VF/assign]
+ String[] p = fm.substring(("/fabrics/" + FABRIC + "/servers/").length()).split("/");
+ List serverVfs = vfs.get(p[0]);
+ if (serverVfs == null) {
+ reply(ex, 404, "{\"code\":\"SERVER_NOT_FOUND\"}");
+ } else if ("GET".equals(method) && p.length == 2 && vfListStatus != 200) {
+ reply(ex, vfListStatus, "{\"status\":\"error\"}");
+ } else if ("GET".equals(method) && p.length == 2) {
+ JsonArray list = new JsonArray();
+ serverVfs.forEach(list::add);
+ JsonObject dpu = new JsonObject();
+ dpu.addProperty("dpuName", p[0] + "-dpu-00");
+ dpu.add("vfInterfaces", list);
+ JsonArray dpus = new JsonArray();
+ dpus.add(dpu);
+ JsonObject r = new JsonObject();
+ r.addProperty("serverName", p[0]);
+ r.add("dpus", dpus);
+ reply(ex, 200, r.toString());
+ } else if (p.length == 4 && "assign".equals(p[3])) {
+ JsonObject vf = serverVfs.stream().filter(v -> p[2].equals(v.get("ifName").getAsString())).findFirst().orElse(null);
+ if (vf == null) {
+ reply(ex, 404, "{\"code\":\"VF_NOT_FOUND\"}");
+ } else if ("POST".equals(method)) {
+ vf.addProperty("status", "provisioned");
+ vf.addProperty("tenantName", JsonParser.parseString(body).getAsJsonObject().get("tenantName").getAsString());
+ reply(ex, 200, "{\"vfId\":\"" + p[2] + "\"}");
+ } else {
+ vf.addProperty("status", "free");
+ vf.remove("tenantName");
+ reply(ex, 200, "{}");
+ }
+ } else {
+ reply(ex, 405, "{}");
+ }
+ } else if ("GET".equals(method) && fm.startsWith("/operations/")) {
+ operationPolls++;
+ String status;
+ synchronized (operationStatuses) {
+ status = operationStatuses.isEmpty() ? "SUCCESS" : operationStatuses.poll();
+ }
+ JsonObject op = new JsonObject();
+ op.addProperty("operationId", fm.substring("/operations/".length()));
+ op.addProperty("status", status);
+ if ("FAILED".equals(status)) {
+ op.addProperty("errorMessage", "VLAN pool exhausted");
+ }
+ reply(ex, 200, "{\"data\":" + op + "}");
+ } else {
+ reply(ex, 404, "{}");
+ }
+ }
+
+ private void accepted(final HttpExchange ex, final boolean async) throws IOException {
+ if (async && asyncSupported) {
+ operations++;
+ reply(ex, 202, "{\"success\":true,\"data\":{\"operationId\":\"op-" + operations + "\"}}");
+ } else {
+ reply(ex, 200, "{\"success\":true,\"message\":\"done\"}");
+ }
+ }
+
+ private static JsonObject tenantRecord(final String name) {
+ JsonObject pool = new JsonObject();
+ pool.addProperty("gateway", "192.1.255.253/16");
+ pool.addProperty("subnet", "192.1.0.0/16");
+ JsonObject vnets = new JsonObject();
+ vnets.add("tenant IP Pool", pool);
+ JsonObject t = new JsonObject();
+ t.addProperty("tenantName", name);
+ t.addProperty("vlanId", 1001);
+ t.addProperty("vniId", 20001);
+ t.addProperty("nsVniId", 30001);
+ t.addProperty("vlanSubnetCPU", "192.1.0.0/16");
+ t.addProperty("tenantIpPool", "192.1.64.0/18");
+ t.add("vnets", vnets);
+ return t;
+ }
+
+ private static void reply(final HttpExchange ex, final int status, final String body) throws IOException {
+ byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
+ ex.getResponseHeaders().set("Content-Type", "application/json");
+ ex.sendResponseHeaders(status, bytes.length);
+ try (OutputStream os = ex.getResponseBody()) {
+ os.write(bytes);
+ }
+ }
+
+ private OnesApiClientImpl client() {
+ return client("secret", clientCert, clientKey, caPem);
+ }
+
+ private OnesApiClientImpl client(final String password, final File cert, final File key, final File ca) {
+ OnesApiClientImpl c = new OnesApiClientImpl(fmUrl, loginUrl, "admin", password,
+ cert != null ? cert.getAbsolutePath() : null, key != null ? key.getAbsolutePath() : null,
+ ca != null ? ca.getAbsolutePath() : null);
+ c.operationPollMs = 10;
+ return c;
+ }
+
+ // ------------------------------------------------------------------ login and 401
+
+ @Test
+ public void logsInOnceAndReusesTheToken() {
+ OnesApiClientImpl c = client();
+ Assert.assertTrue(c.isReachable());
+ Assert.assertTrue(c.isReachable());
+ Assert.assertEquals(1, logins);
+ Assert.assertEquals(Arrays.asList("POST /api/user/login", "GET /fm/getAllFabrics", "GET /fm/getAllFabrics"), requests);
+ }
+
+ @Test
+ public void expiredTokenLogsInAgainAndRetriesOnce() {
+ OnesApiClientImpl c = client();
+ Assert.assertTrue(c.isReachable());
+ currentToken = "rotated"; // ONES no longer accepts jwt-1
+
+ Assert.assertTrue(c.isReachable());
+ Assert.assertEquals(2, logins);
+ Assert.assertEquals(Arrays.asList("POST /api/user/login", "GET /fm/getAllFabrics",
+ "GET /fm/getAllFabrics", "POST /api/user/login", "GET /fm/getAllFabrics"), requests);
+ }
+
+ @Test
+ public void persistent401DoesNotLoop() {
+ fmRejectsEveryToken = true;
+ Assert.assertFalse(client().isReachable());
+ Assert.assertEquals(2, logins); // first login + exactly one re-login
+ }
+
+ @Test
+ public void failedLoginFailsTheCommandWithoutAnFmCall() {
+ CreateOnesTenantCommand cmd = new CreateOnesTenantCommand(FABRIC, TENANT, "net", -1);
+ CreateOnesTenantAnswer a = client("wrong", clientCert, clientKey, caPem).createTenant(cmd);
+
+ Assert.assertFalse(a.getResult());
+ Assert.assertTrue(a.getDetails(), a.getDetails().contains("login"));
+ Assert.assertEquals(Collections.singletonList("POST /api/user/login"), requests);
+ Assert.assertTrue(tenants.isEmpty());
+ }
+
+ // ------------------------------------------------------------------ tenants
+
+ @Test
+ public void createTenantIsAsyncWaitsForTheOperationAndReturnsOnesValues() {
+ synchronized (operationStatuses) {
+ operationStatuses.addAll(Arrays.asList("PENDING", "RUNNING", "SUCCESS"));
+ }
+ CreateOnesTenantCommand cmd = new CreateOnesTenantCommand(FABRIC, TENANT, "CloudStack network n1", -1);
+ CreateOnesTenantAnswer a = client().createTenant(cmd);
+
+ Assert.assertTrue(a.getDetails(), a.getResult());
+ Assert.assertEquals(Integer.valueOf(1001), a.getVlanId());
+ Assert.assertEquals(Integer.valueOf(20001), a.getL2Vni());
+ Assert.assertEquals(Integer.valueOf(30001), a.getL3Vni());
+ Assert.assertEquals("192.1.0.0/16", a.getSubnet());
+ Assert.assertEquals("192.1.64.0/18", a.getIpPool());
+ Assert.assertEquals("192.1.255.253", a.getGateway()); // prefix length stripped
+
+ Assert.assertEquals(Collections.singletonList("POST /fm/fabrics/" + FABRIC + "/tenants"), asyncRequests);
+ Assert.assertEquals(3, operationPolls);
+ JsonObject sent = JsonParser.parseString(bodies.get("POST /fm/fabrics/" + FABRIC + "/tenants")).getAsJsonObject();
+ Assert.assertEquals(TENANT, sent.get("tenantName").getAsString());
+ Assert.assertEquals(-1, sent.get("maxGpusAllowed").getAsInt());
+ Assert.assertFalse("tenant-level shared is refused by ONES", sent.has("shared"));
+ }
+
+ @Test
+ public void createTenantThatAlreadyExistsDoesNotCreateItAgain() {
+ tenants.put(TENANT, tenantRecord(TENANT));
+ CreateOnesTenantAnswer a = client().createTenant(new CreateOnesTenantCommand(FABRIC, TENANT, null, -1));
+
+ Assert.assertTrue(a.getResult());
+ Assert.assertEquals(Integer.valueOf(1001), a.getVlanId());
+ Assert.assertFalse(requests.contains("POST /fm/fabrics/" + FABRIC + "/tenants"));
+ }
+
+ @Test
+ public void createTenantFailsWhenTheOperationFails() {
+ synchronized (operationStatuses) {
+ operationStatuses.addAll(Arrays.asList("RUNNING", "FAILED"));
+ }
+ CreateOnesTenantAnswer a = client().createTenant(new CreateOnesTenantCommand(FABRIC, TENANT, "n", -1));
+
+ Assert.assertFalse(a.getResult());
+ Assert.assertTrue(a.getDetails(), a.getDetails().contains("FAILED"));
+ Assert.assertTrue(a.getDetails(), a.getDetails().contains("VLAN pool exhausted"));
+ Assert.assertNull(a.getVlanId());
+ }
+
+ @Test
+ public void createTenantAcceptsASynchronousReply() {
+ asyncSupported = false; // FM answers 200 with no operationId: nothing to poll
+ CreateOnesTenantAnswer a = client().createTenant(new CreateOnesTenantCommand(FABRIC, TENANT, "n", -1));
+
+ Assert.assertTrue(a.getResult());
+ Assert.assertEquals(0, operationPolls);
+ }
+
+ @Test
+ public void deleteTenantIsAsyncAndRemovesIt() {
+ tenants.put(TENANT, tenantRecord(TENANT));
+ Answer a = client().deleteTenant(new DeleteOnesTenantCommand(FABRIC, TENANT));
+
+ Assert.assertTrue(a.getResult());
+ Assert.assertTrue(tenants.isEmpty());
+ Assert.assertEquals(Collections.singletonList("DELETE /fm/fabrics/" + FABRIC + "/tenants/" + TENANT), asyncRequests);
+ Assert.assertEquals(1, operationPolls);
+ }
+
+ @Test
+ public void deletingAMissingTenantSucceeds() {
+ Answer a = client().deleteTenant(new DeleteOnesTenantCommand(FABRIC, TENANT));
+
+ Assert.assertTrue(a.getResult());
+ Assert.assertEquals("already gone", a.getDetails());
+ }
+
+ // ------------------------------------------------------------------ servers
+
+ @Test
+ public void allocateServersPatchesAddWithSharedServers() {
+ tenants.put(TENANT, tenantRecord(TENANT));
+ AllocateOnesServersCommand cmd = new AllocateOnesServersCommand(FABRIC, TENANT, Arrays.asList("gpu-01", "gpu-02"), true);
+ Answer a = client().allocateServers(cmd);
+
+ Assert.assertTrue(a.getDetails(), a.getResult());
+ String key = "PATCH /fm/fabrics/" + FABRIC + "/tenants/" + TENANT;
+ Assert.assertEquals(Collections.singletonList(key), asyncRequests);
+ JsonObject sent = JsonParser.parseString(bodies.get(key)).getAsJsonObject();
+ Assert.assertEquals("ADD", sent.get("operation").getAsString());
+ JsonArray servers = sent.getAsJsonArray("servers");
+ Assert.assertEquals(2, servers.size());
+ Assert.assertEquals("gpu-01", servers.get(0).getAsJsonObject().get("serverName").getAsString());
+ Assert.assertTrue(servers.get(0).getAsJsonObject().get("shared").getAsBoolean());
+ Assert.assertEquals(1, operationPolls);
+ }
+
+ @Test
+ public void allocateServersHonoursADedicatedRequest() {
+ tenants.put(TENANT, tenantRecord(TENANT));
+ Answer a = client().allocateServers(new AllocateOnesServersCommand(FABRIC, TENANT, Collections.singletonList("gpu-01"), false));
+
+ Assert.assertTrue(a.getDetails(), a.getResult());
+ JsonObject sent = JsonParser.parseString(bodies.get("PATCH /fm/fabrics/" + FABRIC + "/tenants/" + TENANT)).getAsJsonObject();
+ Assert.assertFalse(sent.getAsJsonArray("servers").get(0).getAsJsonObject().get("shared").getAsBoolean());
+ }
+
+ @Test
+ public void deallocateServersPatchesDeleteShared() {
+ tenants.put(TENANT, tenantRecord(TENANT));
+ Answer a = client().deallocateServers(new DeallocateOnesServersCommand(FABRIC, TENANT, Collections.singletonList("gpu-01")));
+
+ Assert.assertTrue(a.getResult());
+ JsonObject sent = JsonParser.parseString(bodies.get("PATCH /fm/fabrics/" + FABRIC + "/tenants/" + TENANT)).getAsJsonObject();
+ Assert.assertEquals("DELETE", sent.get("operation").getAsString());
+ Assert.assertTrue(sent.getAsJsonArray("servers").get(0).getAsJsonObject().get("shared").getAsBoolean());
+ }
+
+ private static JsonObject vf(final String ifName, final String serverIf, final String status, final String tenant) {
+ JsonObject v = new JsonObject();
+ v.addProperty("ifName", ifName);
+ v.addProperty("serverIf", serverIf);
+ v.addProperty("status", status);
+ if (tenant != null) {
+ v.addProperty("tenantName", tenant);
+ }
+ return v;
+ }
+
+ @Test
+ public void allocateServersBehindADpuAssignsAFreeVfToTheTenant() {
+ tenants.put(TENANT, tenantRecord(TENANT));
+ vfs.put("gpu-01", new ArrayList<>(Arrays.asList(vf("swp1", "ens2", "provisioned", "csother"), vf("swp2", "ens4", "free", null))));
+ Answer a = client().allocateServers(new AllocateOnesServersCommand(FABRIC, TENANT, Collections.singletonList("gpu-01"), true));
+
+ Assert.assertTrue(a.getDetails(), a.getResult());
+ String assign = "POST /fm/fabrics/" + FABRIC + "/servers/gpu-01/vf-interfaces/swp2/assign";
+ Assert.assertTrue(requests.toString(), requests.contains(assign));
+ Assert.assertEquals(TENANT, JsonParser.parseString(bodies.get(assign)).getAsJsonObject().get("tenantName").getAsString());
+ // the server joins the tenant before its VF is assigned (FM: SERVER_NOT_IN_TENANT otherwise)
+ Assert.assertTrue(requests.indexOf("PATCH /fm/fabrics/" + FABRIC + "/tenants/" + TENANT) < requests.indexOf(assign));
+ }
+
+ @Test
+ public void allocateServersKeepsTheVfTheTenantAlreadyHas() {
+ tenants.put(TENANT, tenantRecord(TENANT));
+ vfs.put("gpu-01", new ArrayList<>(Arrays.asList(vf("swp1", "ens2", "provisioned", TENANT), vf("swp2", "ens4", "free", null))));
+ Answer a = client().allocateServers(new AllocateOnesServersCommand(FABRIC, TENANT, Collections.singletonList("gpu-01"), true));
+
+ Assert.assertTrue(a.getDetails(), a.getResult());
+ Assert.assertTrue(requests.toString(), requests.stream().noneMatch(r -> r.startsWith("POST") && r.endsWith("/assign")));
+ }
+
+ @Test
+ public void allocateServersFailsWhenTheDpuHasNoFreeVf() {
+ tenants.put(TENANT, tenantRecord(TENANT));
+ vfs.put("gpu-01", new ArrayList<>(Collections.singletonList(vf("swp1", "ens2", "provisioned", "csother"))));
+ Answer a = client().allocateServers(new AllocateOnesServersCommand(FABRIC, TENANT, Collections.singletonList("gpu-01"), true));
+
+ Assert.assertFalse(a.getResult());
+ Assert.assertTrue(a.getDetails(), a.getDetails().contains("no free DPU VF"));
+ }
+
+ @Test
+ public void allocateServersFailsWhenTheVfListingFails() {
+ tenants.put(TENANT, tenantRecord(TENANT));
+ vfs.put("gpu-01", new ArrayList<>(Collections.singletonList(vf("swp1", "ens2", "free", null))));
+ vfListStatus = 503; // not "no DPU": the server would join the tenant without its VF
+
+ Answer a = client().allocateServers(new AllocateOnesServersCommand(FABRIC, TENANT, Collections.singletonList("gpu-01"), true));
+
+ Assert.assertFalse(a.getResult());
+ Assert.assertTrue(a.getDetails(), a.getDetails().contains("503"));
+ }
+
+ @Test
+ public void deallocateServersKeepsAServerWhoseVfCannotBeReleased() {
+ tenants.put(TENANT, tenantRecord(TENANT));
+ vfs.put("gpu-01", new ArrayList<>(Collections.singletonList(vf("swp1", "ens2", "provisioned", TENANT))));
+ vfListStatus = 503;
+
+ Answer a = client().deallocateServers(new DeallocateOnesServersCommand(FABRIC, TENANT, Collections.singletonList("gpu-01")));
+
+ Assert.assertFalse(a.getResult());
+ Assert.assertFalse(requests.toString(), requests.contains("PATCH /fm/fabrics/" + FABRIC + "/tenants/" + TENANT));
+ }
+
+ @Test
+ public void deallocateServersReleasesTheTenantsVfsFirst() {
+ tenants.put(TENANT, tenantRecord(TENANT));
+ vfs.put("gpu-01", new ArrayList<>(Arrays.asList(vf("swp1", "ens2", "provisioned", TENANT), vf("swp2", "ens4", "provisioned", "csother"))));
+ Answer a = client().deallocateServers(new DeallocateOnesServersCommand(FABRIC, TENANT, Collections.singletonList("gpu-01")));
+
+ Assert.assertTrue(a.getDetails(), a.getResult());
+ String release = "DELETE /fm/fabrics/" + FABRIC + "/servers/gpu-01/vf-interfaces/swp1/assign";
+ Assert.assertTrue(requests.toString(), requests.contains(release));
+ Assert.assertFalse(requests.contains("DELETE /fm/fabrics/" + FABRIC + "/servers/gpu-01/vf-interfaces/swp2/assign"));
+ Assert.assertTrue(requests.indexOf(release) < requests.indexOf("PATCH /fm/fabrics/" + FABRIC + "/tenants/" + TENANT));
+ }
+
+ @Test
+ public void allocateServersOnAMissingTenantFails() {
+ Answer a = client().allocateServers(new AllocateOnesServersCommand(FABRIC, TENANT, Collections.singletonList("gpu-01"), true));
+
+ Assert.assertFalse(a.getResult());
+ Assert.assertTrue(a.getDetails(), a.getDetails().contains("HTTP 404"));
+ }
+
+ // ------------------------------------------------------------------ TLS
+
+ @Test
+ public void clientCertificateFromAnotherCaIsRejected() throws Exception {
+ KeyPair rogueCaKeys = TestCertificates.keyPair();
+ X509Certificate rogueCa = TestCertificates.certificate(rogueCaKeys, null, rogueCaKeys.getPublic(), "CN=Rogue CA", true, false);
+ KeyPair rogueKeys = TestCertificates.keyPair();
+ X509Certificate rogue = TestCertificates.certificate(rogueCaKeys, rogueCa, rogueKeys.getPublic(), "CN=rogue", false, false);
+ File cert = TestCertificates.pem(new File(pemDir, "rogue.crt"), rogue);
+ File key = TestCertificates.pem(new File(pemDir, "rogue.key"), rogueKeys.getPrivate());
+
+ Assert.assertFalse(client("secret", cert, key, caPem).isReachable());
+ Assert.assertEquals(0, logins);
+ }
+
+ @Test
+ public void serverCertificateFromAnUntrustedCaIsRejected() throws Exception {
+ KeyPair otherCaKeys = TestCertificates.keyPair();
+ X509Certificate otherCa = TestCertificates.certificate(otherCaKeys, null, otherCaKeys.getPublic(), "CN=Other CA", true, false);
+ File otherCaPem = TestCertificates.pem(new File(pemDir, "other-ca.crt"), otherCa);
+
+ Assert.assertFalse(client("secret", clientCert, clientKey, otherCaPem).isReachable());
+ Assert.assertEquals(0, logins);
+ }
+
+ // ------------------------------------------------------------------ JSON helpers
+
+ @Test
+ public void jsonHelpers() {
+ Assert.assertEquals("10.0.0.1", OnesApiClientImpl.stripPrefix("10.0.0.1/24"));
+ Assert.assertEquals("10.0.0.1", OnesApiClientImpl.stripPrefix("10.0.0.1"));
+ Assert.assertNull(OnesApiClientImpl.stripPrefix(null));
+ Assert.assertNull(OnesApiClientImpl.parse("not json {"));
+ JsonObject o = OnesApiClientImpl.asObject(JsonParser.parseString("{\"data\":\"{\\\"a\\\":1}\"}"), "data");
+ Assert.assertEquals(Integer.valueOf(1), OnesApiClientImpl.integer(o, "a"));
+ Assert.assertNull(OnesApiClientImpl.str(o, "missing"));
+ Assert.assertNull(OnesApiClientImpl.asObject(JsonParser.parseString("{\"data\":[1]}"), "data"));
+ }
+
+ // ------------------------------------------------------------------ certificates
+}
diff --git a/plugins/network-elements/aviz-ones/src/test/java/org/apache/cloudstack/network/ones/client/TestCertificates.java b/plugins/network-elements/aviz-ones/src/test/java/org/apache/cloudstack/network/ones/client/TestCertificates.java
new file mode 100644
index 000000000000..605716b1e5b1
--- /dev/null
+++ b/plugins/network-elements/aviz-ones/src/test/java/org/apache/cloudstack/network/ones/client/TestCertificates.java
@@ -0,0 +1,80 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.apache.cloudstack.network.ones.client;
+
+import java.io.File;
+import java.io.FileWriter;
+import java.math.BigInteger;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.PublicKey;
+import java.security.cert.X509Certificate;
+import java.util.Date;
+
+import org.bouncycastle.asn1.x500.X500Name;
+import org.bouncycastle.asn1.x509.BasicConstraints;
+import org.bouncycastle.asn1.x509.Extension;
+import org.bouncycastle.asn1.x509.GeneralName;
+import org.bouncycastle.asn1.x509.GeneralNames;
+import org.bouncycastle.asn1.x509.KeyUsage;
+import org.bouncycastle.cert.X509v3CertificateBuilder;
+import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
+import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
+import org.bouncycastle.openssl.jcajce.JcaPEMWriter;
+import org.bouncycastle.operator.ContentSigner;
+import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
+
+/** Throwaway keys and certificates for the TLS tests (BouncyCastle must be registered). */
+final class TestCertificates {
+
+ private TestCertificates() {
+ }
+
+ static KeyPair keyPair() throws Exception {
+ KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
+ gen.initialize(2048);
+ return gen.generateKeyPair();
+ }
+
+ static X509Certificate certificate(final KeyPair signer, final X509Certificate signerCert, final PublicKey subjectKey,
+ final String subject, final boolean ca, final boolean server) throws Exception {
+ X500Name issuer = signerCert != null ? new X500Name(signerCert.getSubjectX500Principal().getName()) : new X500Name(subject);
+ X509v3CertificateBuilder b = new JcaX509v3CertificateBuilder(issuer, BigInteger.valueOf(System.nanoTime()),
+ new Date(System.currentTimeMillis() - 60_000L), new Date(System.currentTimeMillis() + 3_600_000L),
+ new X500Name(subject), subjectKey);
+ b.addExtension(Extension.basicConstraints, true, new BasicConstraints(ca));
+ if (ca) {
+ b.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign));
+ }
+ if (server) {
+ b.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(new GeneralName[]{
+ new GeneralName(GeneralName.iPAddress, "127.0.0.1"), new GeneralName(GeneralName.dNSName, "localhost")}));
+ }
+ ContentSigner s = new JcaContentSignerBuilder("SHA256withRSA").setProvider("BC").build(signer.getPrivate());
+ return new JcaX509CertificateConverter().setProvider("BC").getCertificate(b.build(s));
+ }
+
+ static File pem(final File file, final Object object) throws Exception {
+ try (JcaPEMWriter w = new JcaPEMWriter(new FileWriter(file))) {
+ w.writeObject(object);
+ }
+ return file;
+ }
+}
diff --git a/plugins/network-elements/aviz-ones/src/test/java/org/apache/cloudstack/network/ones/resource/OnesResourceTest.java b/plugins/network-elements/aviz-ones/src/test/java/org/apache/cloudstack/network/ones/resource/OnesResourceTest.java
new file mode 100644
index 000000000000..12c8516a2422
--- /dev/null
+++ b/plugins/network-elements/aviz-ones/src/test/java/org/apache/cloudstack/network/ones/resource/OnesResourceTest.java
@@ -0,0 +1,292 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.apache.cloudstack.network.ones.resource;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.naming.ConfigurationException;
+
+import org.apache.cloudstack.network.ones.agent.api.AllocateOnesServersCommand;
+import org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand;
+import org.apache.cloudstack.network.ones.agent.api.CreateOnesTenantAnswer;
+import org.apache.cloudstack.network.ones.agent.api.CreateOnesTenantCommand;
+import org.apache.cloudstack.network.ones.agent.api.DeallocateOnesServersCommand;
+import org.apache.cloudstack.network.ones.agent.api.DeleteOnesTenantCommand;
+import org.apache.cloudstack.network.ones.agent.api.RemoveOnesEdgeCommand;
+import org.apache.cloudstack.network.ones.agent.api.StartupOnesCommand;
+import org.apache.cloudstack.network.ones.client.AvizGatewayClient;
+import org.apache.cloudstack.network.ones.client.OnesApiClient;
+import org.apache.cloudstack.network.ones.dao.OnesProviderDao;
+import org.apache.cloudstack.network.ones.dao.OnesProviderVO;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.junit.MockitoJUnitRunner;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.CheckHealthCommand;
+import com.cloud.agent.api.MaintainCommand;
+import com.cloud.agent.api.ReadyCommand;
+import com.cloud.agent.api.StartupCommand;
+import com.cloud.agent.api.UnsupportedAnswer;
+import com.cloud.host.Host;
+
+@RunWith(MockitoJUnitRunner.class)
+public class OnesResourceTest {
+
+ @Mock
+ private OnesApiClient client;
+ @Mock
+ private OnesProviderDao providerDao;
+
+ private OnesResource resource;
+
+ private static Map params() {
+ Map p = new HashMap<>();
+ p.put("name", "ones1");
+ p.put("guid", "guid-1");
+ p.put("zoneId", "1");
+ p.put("url", "https://ones-fm:8443");
+ p.put("loginUrl", "https://ones-fm/api/user/login");
+ p.put("username", "admin");
+ p.put("password", "secret");
+ p.put("physicalNetworkId", "200");
+ return p;
+ }
+
+ @Before
+ public void setUp() throws ConfigurationException {
+ resource = new OnesResource();
+ Assert.assertTrue(resource.configure("ones1", params()));
+ resource.onesApiClient = client;
+ }
+
+ @After
+ public void tearDown() {
+ OnesResource.setProviderDao(null);
+ }
+
+ // ------------------------------------------------------------------ configure
+
+ private static void assertConfigureFails(final Map p) {
+ try {
+ new OnesResource().configure("ones1", p);
+ Assert.fail("configure accepted " + p);
+ } catch (ConfigurationException expected) {
+ // ok
+ }
+ }
+
+ @Test
+ public void configureRequiresNameGuidAndUrl() {
+ for (String key : new String[]{"name", "guid", "url"}) {
+ Map p = params();
+ p.remove(key);
+ assertConfigureFails(p);
+ }
+ }
+
+ @Test
+ public void configureRequiresAPasswordOrAPhysicalNetwork() throws ConfigurationException {
+ Map p = params();
+ p.remove("password");
+ p.remove("physicalNetworkId");
+ assertConfigureFails(p);
+
+ // after a restart: no password in host_details, resolved later from ones_providers
+ p.put("physicalNetworkId", "200");
+ OnesResource r = new OnesResource();
+ Assert.assertTrue(r.configure("ones1", p));
+ Assert.assertNull(r.onesApiClient);
+ }
+
+ @Test
+ public void configureErrorsNeverCarryThePassword() {
+ Map p = params();
+ p.put("clientCertPath", "/etc/ones/client.crt");
+ try {
+ new OnesResource().configure("ones1", p);
+ Assert.fail("configure accepted a certificate without its key");
+ } catch (ConfigurationException e) {
+ Assert.assertFalse(e.getMessage(), e.getMessage().contains("secret"));
+ }
+ p = params();
+ p.remove("url");
+ try {
+ new OnesResource().configure("ones1", p);
+ Assert.fail("configure accepted no url");
+ } catch (ConfigurationException e) {
+ Assert.assertFalse(e.getMessage(), e.getMessage().contains("secret"));
+ }
+ }
+
+ @Test
+ public void configureRequiresClientCertAndKeyTogether() {
+ Map p = params();
+ p.put("clientCertPath", "/etc/ones/client.crt");
+ assertConfigureFails(p);
+ p.remove("clientCertPath");
+ p.put("clientKeyPath", "/etc/ones/client.key");
+ assertConfigureFails(p);
+ }
+
+ @Test
+ public void initializeReportsAnL2NetworkingHost() {
+ StartupCommand[] startup = resource.initialize();
+
+ Assert.assertEquals(1, startup.length);
+ Assert.assertTrue(startup[0] instanceof StartupOnesCommand);
+ Assert.assertEquals("guid-1", startup[0].getGuid());
+ Assert.assertEquals("ones1", startup[0].getName());
+ Assert.assertEquals("1", startup[0].getDataCenter());
+ Assert.assertEquals(Host.Type.L2Networking, resource.getType());
+ Assert.assertEquals(Host.Type.L2Networking, resource.getCurrentStatus(5L).getHostType());
+ }
+
+ // ------------------------------------------------------------------ dispatch
+
+ @Test
+ public void createTenantGoesToTheClient() {
+ CreateOnesTenantCommand cmd = new CreateOnesTenantCommand("fab1", "cs0123456789", "n", -1);
+ CreateOnesTenantAnswer expected = new CreateOnesTenantAnswer(cmd, "{}", 1001, 1, 2, "192.1.0.0/16", "192.1.64.0/18", "192.1.0.1");
+ Mockito.when(client.createTenant(cmd)).thenReturn(expected);
+
+ Assert.assertSame(expected, resource.executeRequest(cmd));
+ }
+
+ @Test
+ public void deleteTenantGoesToTheClient() {
+ DeleteOnesTenantCommand cmd = new DeleteOnesTenantCommand("fab1", "cs0123456789");
+ Answer expected = new Answer(cmd);
+ Mockito.when(client.deleteTenant(cmd)).thenReturn(expected);
+
+ Assert.assertSame(expected, resource.executeRequest(cmd));
+ }
+
+ @Test
+ public void allocateAndDeallocateGoToTheClient() {
+ AllocateOnesServersCommand add = new AllocateOnesServersCommand("fab1", "t", Collections.singletonList("gpu-01"), true);
+ DeallocateOnesServersCommand remove = new DeallocateOnesServersCommand("fab1", "t", Collections.singletonList("gpu-01"));
+ Answer added = new Answer(add);
+ Answer removed = new Answer(remove);
+ Mockito.when(client.allocateServers(add)).thenReturn(added);
+ Mockito.when(client.deallocateServers(remove)).thenReturn(removed);
+
+ Assert.assertSame(added, resource.executeRequest(add));
+ Assert.assertSame(removed, resource.executeRequest(remove));
+ }
+
+ @Test
+ public void healthCheckAsksWhetherOnesIsReachable() {
+ Mockito.when(client.isReachable()).thenReturn(true, false);
+
+ Assert.assertTrue(resource.executeRequest(new CheckHealthCommand()).getResult());
+ Assert.assertFalse(resource.executeRequest(new CheckHealthCommand()).getResult());
+ }
+
+ @Test
+ public void readyNeedsNoClientAndOtherCommandsAreUnsupported() {
+ Assert.assertTrue(resource.executeRequest(new ReadyCommand(1L)).getResult());
+ Answer a = resource.executeRequest(new MaintainCommand());
+ Assert.assertTrue(a instanceof UnsupportedAnswer);
+ Assert.assertFalse(a.getResult());
+ Mockito.verifyNoInteractions(client);
+ }
+
+ // ------------------------------------------------------------------ lazy client after a restart
+
+ private OnesResource restartedResource() throws ConfigurationException {
+ Map p = params();
+ p.remove("password");
+ OnesResource r = new OnesResource();
+ r.configure("ones1", p);
+ return r;
+ }
+
+ @Test
+ public void afterARestartTheLoginComesFromTheProviderRow() throws ConfigurationException {
+ OnesProviderVO provider = Mockito.mock(OnesProviderVO.class);
+ Mockito.when(provider.getUsername()).thenReturn("admin");
+ Mockito.when(provider.getPassword()).thenReturn("secret");
+ Mockito.when(provider.getLoginUrl()).thenReturn("https://127.0.0.1:1/api/user/login");
+ Mockito.when(providerDao.listByPhysicalNetwork(200L)).thenReturn(Collections.singletonList(provider));
+ OnesResource.setProviderDao(providerDao);
+ OnesResource r = restartedResource();
+
+ // ReadyCommand is answered without building a client
+ Assert.assertTrue(r.executeRequest(new ReadyCommand(1L)).getResult());
+ Assert.assertNull(r.onesApiClient);
+ // any ONES command builds it from the ones_providers row (nothing listens: not reachable)
+ r.executeRequest(new CheckHealthCommand());
+ Assert.assertNotNull(r.onesApiClient);
+ Assert.assertEquals("secret", r.password);
+ Mockito.verify(providerDao).listByPhysicalNetwork(200L);
+ }
+
+ @Test
+ public void afterARestartWithoutAProviderRowCommandsFailCleanly() throws ConfigurationException {
+ Mockito.when(providerDao.listByPhysicalNetwork(200L)).thenReturn(Collections.emptyList());
+ OnesResource.setProviderDao(providerDao);
+ OnesResource r = restartedResource();
+
+ Answer a = r.executeRequest(new DeleteOnesTenantCommand("fab1", "t"));
+ Assert.assertFalse(a.getResult());
+ Assert.assertTrue(a.getDetails(), a.getDetails().contains("No Aviz ONES login is on record for physical network 200"));
+ }
+
+ // ------------------------------------------------------------------ edge on the Aviz Gateway
+
+ @Test
+ public void edgeCommandsGoToAGatewayClientFromTheProviderRow() {
+ AvizGatewayClient gateway = Mockito.mock(AvizGatewayClient.class);
+ OnesResource r = new OnesResource() {
+ @Override
+ protected AvizGatewayClient getGatewayClient() {
+ return gateway;
+ }
+ };
+ ConfigureOnesEdgeCommand configure = new ConfigureOnesEdgeCommand("cs0123456789", null, Collections.emptyList(),
+ Collections.emptyList(), Collections.emptyList());
+ RemoveOnesEdgeCommand remove = new RemoveOnesEdgeCommand("cs0123456789");
+ Mockito.when(gateway.configureEdge(configure)).thenReturn(new Answer(configure));
+ Mockito.when(gateway.removeEdge(remove)).thenReturn(new Answer(remove));
+
+ Assert.assertTrue(r.executeRequest(configure).getResult());
+ Assert.assertTrue(r.executeRequest(remove).getResult());
+ }
+
+ @Test
+ public void edgeCommandsWithoutAGatewayFailCleanly() {
+ OnesProviderVO row = new OnesProviderVO();
+ Mockito.when(providerDao.listByPhysicalNetwork(200L)).thenReturn(Collections.singletonList(row));
+ OnesResource.setProviderDao(providerDao);
+
+ Answer a = resource.executeRequest(new RemoveOnesEdgeCommand("cs0123456789"));
+
+ Assert.assertFalse(a.getResult());
+ Assert.assertTrue(a.getDetails(), a.getDetails().contains("no Aviz Gateway"));
+ }
+}
diff --git a/plugins/network-elements/aviz-ones/src/test/java/org/apache/cloudstack/network/ones/service/OnesEdgeBuilderTest.java b/plugins/network-elements/aviz-ones/src/test/java/org/apache/cloudstack/network/ones/service/OnesEdgeBuilderTest.java
new file mode 100644
index 000000000000..359a3fe23575
--- /dev/null
+++ b/plugins/network-elements/aviz-ones/src/test/java/org/apache/cloudstack/network/ones/service/OnesEdgeBuilderTest.java
@@ -0,0 +1,297 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.apache.cloudstack.network.ones.service;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand.FirewallRule;
+import org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand.PortMapping;
+import org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand.Vip;
+import org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.junit.MockitoJUnitRunner;
+
+import com.cloud.network.IpAddress;
+import com.cloud.network.Network;
+import com.cloud.network.NetworkModel;
+import com.cloud.network.dao.FirewallRulesCidrsDao;
+import com.cloud.network.dao.FirewallRulesDao;
+import com.cloud.network.dao.IPAddressDao;
+import com.cloud.network.dao.IPAddressVO;
+import com.cloud.network.dao.LBStickinessPolicyDao;
+import com.cloud.network.dao.LBStickinessPolicyVO;
+import com.cloud.network.dao.LoadBalancerDao;
+import com.cloud.network.dao.LoadBalancerVMMapDao;
+import com.cloud.network.dao.LoadBalancerVMMapVO;
+import com.cloud.network.dao.LoadBalancerVO;
+import com.cloud.network.rules.FirewallRule.Purpose;
+import com.cloud.network.rules.FirewallRule.State;
+import com.cloud.network.rules.FirewallRule.TrafficType;
+import com.cloud.network.rules.FirewallRuleVO;
+import com.cloud.network.rules.LoadBalancerContainer.Scheme;
+import com.cloud.network.rules.PortForwardingRuleVO;
+import com.cloud.network.rules.dao.PortForwardingRulesDao;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.utils.net.Ip;
+
+@RunWith(MockitoJUnitRunner.Silent.class)
+public class OnesEdgeBuilderTest {
+
+ private static final long NETWORK_ID = 42L;
+ private static final String TENANT = "cs0123456789";
+ private static final long SNAT_ID = 1L;
+ private static final long PF_IP_ID = 2L;
+ private static final long LB_IP_ID = 3L;
+
+ @Mock
+ private IPAddressDao ipAddressDao;
+ @Mock
+ private PortForwardingRulesDao portForwardingRulesDao;
+ @Mock
+ private LoadBalancerDao loadBalancerDao;
+ @Mock
+ private LoadBalancerVMMapDao lbVmMapDao;
+ @Mock
+ private LBStickinessPolicyDao lbStickinessPolicyDao;
+ @Mock
+ private FirewallRulesDao firewallRulesDao;
+ @Mock
+ private FirewallRulesCidrsDao firewallRulesCidrsDao;
+ @Mock
+ private NetworkModel networkModel;
+ @Mock
+ private Network network;
+
+ private OnesEdgeBuilder builder;
+ private final List forwards = new ArrayList<>();
+ private final List ingress = new ArrayList<>();
+
+ @Before
+ public void setUp() {
+ builder = new OnesEdgeBuilder(ipAddressDao, portForwardingRulesDao, loadBalancerDao, lbVmMapDao, lbStickinessPolicyDao,
+ firewallRulesDao, firewallRulesCidrsDao, networkModel);
+ Mockito.when(network.getId()).thenReturn(NETWORK_ID);
+ IPAddressVO snat = ip(SNAT_ID, "203.0.113.100");
+ Mockito.when(snat.getState()).thenReturn(IpAddress.State.Allocated);
+ Mockito.when(ipAddressDao.listByAssociatedNetwork(NETWORK_ID, true)).thenReturn(Collections.singletonList(snat));
+ ip(PF_IP_ID, "203.0.113.101");
+ ip(LB_IP_ID, "203.0.113.102");
+ Mockito.when(portForwardingRulesDao.listByNetwork(NETWORK_ID)).thenReturn(forwards);
+ Mockito.when(firewallRulesDao.listByNetworkPurposeTrafficType(NETWORK_ID, Purpose.Firewall, TrafficType.Ingress)).thenReturn(ingress);
+ Mockito.when(loadBalancerDao.listByNetworkIdAndScheme(NETWORK_ID, Scheme.Public)).thenReturn(new ArrayList<>());
+ }
+
+ private IPAddressVO ip(final long id, final String address) {
+ IPAddressVO ip = Mockito.mock(IPAddressVO.class);
+ Mockito.when(ip.getAddress()).thenReturn(new Ip(address));
+ Mockito.when(ipAddressDao.findById(id)).thenReturn(ip);
+ return ip;
+ }
+
+ private void forward(final State state, final String protocol, final int publicStart, final int publicEnd, final String vm, final int privateStart) {
+ PortForwardingRuleVO r = Mockito.mock(PortForwardingRuleVO.class);
+ Mockito.when(r.getState()).thenReturn(state);
+ Mockito.when(r.getProtocol()).thenReturn(protocol);
+ Mockito.when(r.getSourceIpAddressId()).thenReturn(PF_IP_ID);
+ Mockito.when(r.getSourcePortStart()).thenReturn(publicStart);
+ Mockito.when(r.getSourcePortEnd()).thenReturn(publicEnd);
+ Mockito.when(r.getDestinationIpAddress()).thenReturn(new Ip(vm));
+ Mockito.when(r.getDestinationPortStart()).thenReturn(privateStart);
+ Mockito.when(r.getUuid()).thenReturn("pf-uuid");
+ forwards.add(r);
+ }
+
+ private void allow(final long id, final long ipId, final String protocol, final Integer start, final Integer end, final String... cidrs) {
+ FirewallRuleVO r = Mockito.mock(FirewallRuleVO.class);
+ Mockito.when(r.getId()).thenReturn(id);
+ Mockito.when(r.getState()).thenReturn(State.Active);
+ Mockito.when(r.getSourceIpAddressId()).thenReturn(ipId);
+ Mockito.when(r.getProtocol()).thenReturn(protocol);
+ Mockito.when(r.getSourcePortStart()).thenReturn(start);
+ Mockito.when(r.getSourcePortEnd()).thenReturn(end);
+ Mockito.when(firewallRulesCidrsDao.getSourceCidrs(id)).thenReturn(Arrays.asList(cidrs));
+ ingress.add(r);
+ }
+
+ private LoadBalancerVO loadBalancer(final long id, final String protocol, final int publicPort, final int privatePort, final String... members) {
+ LoadBalancerVO lb = Mockito.mock(LoadBalancerVO.class);
+ Mockito.when(lb.getId()).thenReturn(id);
+ Mockito.when(lb.getState()).thenReturn(State.Active);
+ Mockito.when(lb.getSourceIpAddressId()).thenReturn(LB_IP_ID);
+ Mockito.when(lb.getSourcePortStart()).thenReturn(publicPort);
+ Mockito.when(lb.getDefaultPortStart()).thenReturn(privatePort);
+ Mockito.when(lb.getLbProtocol()).thenReturn(protocol);
+ List maps = new ArrayList<>();
+ for (String m : members) {
+ LoadBalancerVMMapVO map = Mockito.mock(LoadBalancerVMMapVO.class);
+ Mockito.when(map.getInstanceIp()).thenReturn(m);
+ maps.add(map);
+ }
+ Mockito.when(lbVmMapDao.listByLoadBalancerId(id, false)).thenReturn(maps);
+ Mockito.when(loadBalancerDao.listByNetworkIdAndScheme(NETWORK_ID, Scheme.Public)).thenReturn(Collections.singletonList(lb));
+ return lb;
+ }
+
+ private ConfigureOnesEdgeCommand build(final boolean firewall) {
+ return builder.build(network, TENANT, true, true, true, firewall);
+ }
+
+ private static List rules(final ConfigureOnesEdgeCommand cmd) {
+ List out = new ArrayList<>();
+ for (FirewallRule r : cmd.getFirewallRules()) {
+ out.add((r.isPermit() ? "permit " : "deny ") + r.getSource() + " " + r.getDestination() + " " + r.getProtocol() + " " + r.getPort());
+ }
+ return out;
+ }
+
+ @Test
+ public void outboundTranslationUsesTheNetworksSourceNatAddress() {
+ Assert.assertEquals("203.0.113.100", build(false).getSourceNatAddress());
+ Assert.assertNull(builder.build(network, TENANT, false, true, true, false).getSourceNatAddress());
+ }
+
+ @Test
+ public void aReleasedSourceNatAddressIsNotUsed() {
+ IPAddressVO releasing = Mockito.mock(IPAddressVO.class);
+ Mockito.when(releasing.getState()).thenReturn(IpAddress.State.Releasing);
+ Mockito.when(ipAddressDao.listByAssociatedNetwork(NETWORK_ID, true)).thenReturn(Collections.singletonList(releasing));
+
+ Assert.assertNull(build(false).getSourceNatAddress());
+ }
+
+ @Test
+ public void portForwardsAreMappedPortByPortAndRevokedOnesLeftOut() {
+ forward(State.Active, "TCP", 2222, 2223, "10.1.64.10", 22);
+ forward(State.Revoke, "tcp", 8080, 8080, "10.1.64.12", 80);
+
+ List m = build(false).getPortMappings();
+
+ Assert.assertEquals(Arrays.asList(new PortMapping("203.0.113.101", "10.1.64.10", "tcp", 2222, 22),
+ new PortMapping("203.0.113.101", "10.1.64.10", "tcp", 2223, 23)), m);
+ }
+
+ @Test
+ public void aPortForwardTooWideForTheGatewayIsRefused() {
+ forward(State.Add, "udp", 10000, 10000 + OnesEdgeBuilder.MAX_PORTS_PER_FORWARD, "10.1.64.10", 10000);
+
+ CloudRuntimeException e = Assert.assertThrows(CloudRuntimeException.class, () -> build(false));
+ Assert.assertTrue(e.getMessage(), e.getMessage().contains("at most " + OnesEdgeBuilder.MAX_PORTS_PER_FORWARD));
+ }
+
+ @Test
+ public void aLoadBalancerIsOneVipWithEveryMemberAndSourceStickiness() {
+ loadBalancer(9L, "tcp", 80, 8080, "10.1.64.10", "10.1.64.12", "10.1.64.10");
+ LBStickinessPolicyVO sticky = Mockito.mock(LBStickinessPolicyVO.class);
+ Mockito.when(sticky.getMethodName()).thenReturn("SourceBased");
+ Mockito.when(lbStickinessPolicyDao.listByLoadBalancerId(9L, false)).thenReturn(Collections.singletonList(sticky));
+
+ List vips = build(false).getVips();
+
+ Assert.assertEquals(1, vips.size());
+ Vip v = vips.get(0);
+ Assert.assertEquals("cs-lb-9", v.getName());
+ Assert.assertEquals("203.0.113.102", v.getAddress());
+ Assert.assertEquals(80, v.getPort());
+ Assert.assertEquals(8080, v.getBackendPort());
+ Assert.assertEquals("tcp", v.getProtocol());
+ Assert.assertEquals(Arrays.asList("10.1.64.10", "10.1.64.12"), v.getBackends());
+ Assert.assertTrue(v.isSourceSticky());
+ }
+
+ @Test
+ public void aMappingNoIngressRuleCoversStaysClosed() {
+ forward(State.Active, "tcp", 22, 22, "10.1.64.10", 22);
+
+ Assert.assertEquals(Collections.singletonList("deny 0.0.0.0/0 10.1.64.10/32 tcp 22"), rules(build(true)));
+ }
+
+ @Test
+ public void ingressRulesBecomePermitsOnTheTranslatedAddressAheadOfADeny() {
+ forward(State.Active, "tcp", 2222, 2222, "10.1.64.10", 22);
+ allow(1L, PF_IP_ID, "tcp", 2222, 2222, "198.51.100.0/24", "192.0.2.7/32");
+
+ ConfigureOnesEdgeCommand cmd = build(true);
+
+ Assert.assertEquals(Arrays.asList("permit 198.51.100.0/24 10.1.64.10/32 tcp 22", "permit 192.0.2.7/32 10.1.64.10/32 tcp 22",
+ "deny 0.0.0.0/0 10.1.64.10/32 tcp 22"), rules(cmd));
+ Assert.assertEquals(TENANT + "-fw-0", cmd.getFirewallRules().get(0).getName());
+ }
+
+ @Test
+ public void ingressRulesMatchByAddressProtocolAndPortRange() {
+ forward(State.Active, "udp", 5000, 5001, "10.1.64.10", 5000);
+ allow(1L, PF_IP_ID, "tcp", 5000, 5001, "198.51.100.0/24"); // wrong protocol
+ allow(2L, LB_IP_ID, "udp", 5000, 5001, "198.51.100.1/32"); // another address
+ allow(3L, PF_IP_ID, "all", null, null); // every port, any source
+
+ Assert.assertEquals(Arrays.asList("permit 0.0.0.0/0 10.1.64.10/32 udp 5000", "deny 0.0.0.0/0 10.1.64.10/32 udp 5000",
+ "permit 0.0.0.0/0 10.1.64.10/32 udp 5001", "deny 0.0.0.0/0 10.1.64.10/32 udp 5001"), rules(build(true)));
+ }
+
+ @Test
+ public void vipBackendsAreGuardedOnTheirBackendPort() {
+ loadBalancer(9L, "tcp", 443, 8443, "10.1.64.10", "10.1.64.12");
+ allow(1L, LB_IP_ID, "tcp", 443, 443, "198.51.100.0/24");
+
+ Assert.assertEquals(Arrays.asList("permit 198.51.100.0/24 10.1.64.10/32 tcp 8443", "deny 0.0.0.0/0 10.1.64.10/32 tcp 8443",
+ "permit 198.51.100.0/24 10.1.64.12/32 tcp 8443", "deny 0.0.0.0/0 10.1.64.12/32 tcp 8443"), rules(build(true)));
+ }
+
+ @Test
+ public void aVmPortBehindALoadBalancerCannotAlsoBePortForwarded() {
+ forward(State.Active, "tcp", 2222, 2222, "10.1.64.10", 22);
+ loadBalancer(9L, "tcp", 2223, 22, "10.1.64.10", "10.1.64.12");
+
+ CloudRuntimeException e = Assert.assertThrows(CloudRuntimeException.class, () -> build(false));
+ Assert.assertTrue(e.getMessage(), e.getMessage().contains("10.1.64.10:22/tcp"));
+ }
+
+ @Test
+ public void aPortForwardToAnotherPortOrProtocolOfAMemberIsFine() {
+ forward(State.Active, "tcp", 2222, 2222, "10.1.64.10", 2222);
+ forward(State.Active, "udp", 53, 53, "10.1.64.10", 22);
+ loadBalancer(9L, "tcp", 2223, 22, "10.1.64.10", "10.1.64.12");
+
+ Assert.assertEquals(2, build(false).getPortMappings().size());
+ }
+
+ @Test
+ public void twoVipsCannotShareAMemberPort() {
+ Vip a = new Vip("cs-lb-1", "203.0.113.102", 80, "tcp", 8080, Collections.singletonList("10.1.64.10"), false);
+ Vip b = new Vip("cs-lb-2", "203.0.113.103", 81, "tcp", 8080, Collections.singletonList("10.1.64.10"), false);
+
+ Assert.assertThrows(CloudRuntimeException.class, () -> OnesEdgeBuilder.checkBackendPorts(Collections.emptyList(), Arrays.asList(a, b)));
+ }
+
+ @Test
+ public void withoutTheFirewallServiceNothingIsFiltered() {
+ forward(State.Active, "tcp", 22, 22, "10.1.64.10", 22);
+
+ Assert.assertTrue(build(false).getFirewallRules().isEmpty());
+ }
+}
diff --git a/plugins/network-elements/aviz-ones/src/test/java/org/apache/cloudstack/network/ones/service/OnesElementTest.java b/plugins/network-elements/aviz-ones/src/test/java/org/apache/cloudstack/network/ones/service/OnesElementTest.java
new file mode 100644
index 000000000000..6057a336718e
--- /dev/null
+++ b/plugins/network-elements/aviz-ones/src/test/java/org/apache/cloudstack/network/ones/service/OnesElementTest.java
@@ -0,0 +1,492 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.apache.cloudstack.network.ones.service;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.function.BooleanSupplier;
+
+import org.apache.cloudstack.network.ones.agent.api.AllocateOnesServersCommand;
+import org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand;
+import org.apache.cloudstack.network.ones.agent.api.RemoveOnesEdgeCommand;
+import org.apache.cloudstack.network.ones.api.command.DeleteOnesProviderCmd;
+import org.apache.cloudstack.network.ones.api.command.ListOnesProvidersCmd;
+import org.apache.cloudstack.network.ones.api.command.UpdateOnesProviderCmd;
+import org.apache.cloudstack.network.ones.dao.OnesProviderDao;
+import org.apache.cloudstack.network.ones.dao.OnesProviderVO;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.ArgumentMatchers;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import com.cloud.agent.AgentManager;
+import com.cloud.agent.api.Answer;
+import com.cloud.deploy.DeployDestination;
+import com.cloud.exception.InvalidParameterValueException;
+import com.cloud.exception.ResourceUnavailableException;
+import com.cloud.host.Host;
+import com.cloud.host.HostVO;
+import com.cloud.host.dao.HostDao;
+import com.cloud.network.Network.Capability;
+import com.cloud.network.Network.Service;
+import com.cloud.network.Network;
+import com.cloud.network.NetworkModel;
+import com.cloud.network.dao.IPAddressDao;
+import com.cloud.network.dao.IPAddressVO;
+import com.cloud.network.dao.LoadBalancerDao;
+import com.cloud.network.dao.LoadBalancerVMMapDao;
+import com.cloud.network.dao.NetworkDao;
+import com.cloud.network.dao.NetworkDetailVO;
+import com.cloud.network.dao.NetworkDetailsDao;
+import com.cloud.network.dao.NetworkServiceMapDao;
+import com.cloud.network.dao.NetworkVO;
+import com.cloud.network.lb.LoadBalancingRule;
+import com.cloud.network.rules.LoadBalancer;
+import com.cloud.network.rules.dao.PortForwardingRulesDao;
+import com.cloud.utils.exception.CloudRuntimeException;
+
+@RunWith(MockitoJUnitRunner.Silent.class)
+public class OnesElementTest {
+
+ private static final long NETWORK_ID = 42L;
+ private static final long PHYSNET_ID = 200L;
+ private static final long ONES_HOST_ID = 5L;
+ private static final String TENANT = "cs0123456789";
+
+ @Mock
+ private OnesProviderDao onesProviderDao;
+ @Mock
+ private HostDao hostDao;
+ @Mock
+ private AgentManager agentMgr;
+ @Mock
+ private NetworkDetailsDao networkDetailsDao;
+ @Mock
+ private NetworkModel networkModel;
+ @Mock
+ private NetworkServiceMapDao ntwkSrvcDao;
+
+ @Mock
+ private OnesProviderVO provider;
+ @Mock
+ private HostVO onesHost;
+ @Mock
+ private Network network;
+ @Mock
+ private DeployDestination dest;
+ @Mock
+ private Host gpuHost;
+
+ @Mock
+ private PortForwardingRulesDao portForwardingRulesDao;
+ @Mock
+ private LoadBalancerDao loadBalancerDao;
+ @Mock
+ private LoadBalancerVMMapDao lbVmMapDao;
+ @Mock
+ private IPAddressDao ipAddressDao;
+
+ @Mock
+ private OnesEdgeBuilder edgeBuilder;
+ @Mock
+ private NetworkDao networkDao;
+
+ private OnesElement element;
+ private final List locks = new java.util.ArrayList<>();
+
+ @Before
+ public void setUp() {
+ element = new OnesElement() {
+ @Override
+ protected OnesEdgeBuilder edgeBuilder() {
+ return edgeBuilder;
+ }
+
+ @Override
+ protected boolean underLock(final String name, final BooleanSupplier work) {
+ locks.add(name);
+ return work.getAsBoolean(); // GlobalLock needs the database
+ }
+ };
+ element.onesProviderDao = onesProviderDao;
+ element.hostDao = hostDao;
+ element.agentMgr = agentMgr;
+ element.networkDetailsDao = networkDetailsDao;
+ element.networkModel = networkModel;
+ element.ntwkSrvcDao = ntwkSrvcDao;
+ element.portForwardingRulesDao = portForwardingRulesDao;
+ element.loadBalancerDao = loadBalancerDao;
+ element.lbVmMapDao = lbVmMapDao;
+ element.ipAddressDao = ipAddressDao;
+ element.networkDao = networkDao;
+
+ Mockito.when(network.getId()).thenReturn(NETWORK_ID);
+ Mockito.when(network.getPhysicalNetworkId()).thenReturn(PHYSNET_ID);
+ Mockito.when(networkModel.isProviderForNetwork(OnesElement.AVIZ_ONES, NETWORK_ID)).thenReturn(true);
+ Mockito.when(ntwkSrvcDao.canProviderSupportServiceInNetwork(NETWORK_ID, Service.Connectivity, OnesElement.AVIZ_ONES)).thenReturn(true);
+ Mockito.when(provider.getHostId()).thenReturn(ONES_HOST_ID);
+ Mockito.when(provider.getFabricName()).thenReturn("fab1");
+ Mockito.when(onesProviderDao.listByPhysicalNetwork(PHYSNET_ID)).thenReturn(Collections.singletonList(provider));
+ Mockito.when(onesHost.getId()).thenReturn(ONES_HOST_ID);
+ Mockito.when(hostDao.findById(ONES_HOST_ID)).thenReturn(onesHost);
+ Mockito.when(gpuHost.getName()).thenReturn("gpu-02");
+ Mockito.when(dest.getHost()).thenReturn(gpuHost);
+ detail(OnesElement.DETAIL_TENANT_NAME, TENANT);
+ Mockito.when(agentMgr.easySend(ArgumentMatchers.eq(ONES_HOST_ID), ArgumentMatchers.any(AllocateOnesServersCommand.class)))
+ .thenAnswer(i -> new Answer(i.getArgument(1)));
+ }
+
+ private void detail(final String key, final String value) {
+ Mockito.when(networkDetailsDao.findDetail(NETWORK_ID, key)).thenReturn(new NetworkDetailVO(NETWORK_ID, key, value, false));
+ }
+
+ private AllocateOnesServersCommand allocateSent() {
+ ArgumentCaptor c = ArgumentCaptor.forClass(AllocateOnesServersCommand.class);
+ Mockito.verify(agentMgr).easySend(ArgumentMatchers.eq(ONES_HOST_ID), c.capture());
+ return c.getValue();
+ }
+
+ // ------------------------------------------------------------------ prepare: hosts join the tenant
+
+ @Test
+ public void theFirstVmOnAHostAddsTheHostToTheTenantShared() throws Exception {
+ Assert.assertTrue(element.prepare(network, null, null, dest, null));
+
+ AllocateOnesServersCommand cmd = allocateSent();
+ Assert.assertEquals("fab1", cmd.getFabricName());
+ Assert.assertEquals(TENANT, cmd.getTenantName());
+ Assert.assertEquals(Collections.singletonList("gpu-02"), cmd.getServerNames());
+ Assert.assertTrue(cmd.isShared());
+ Assert.assertEquals(900, cmd.getWait());
+ Mockito.verify(networkDetailsDao).removeDetail(NETWORK_ID, OnesElement.DETAIL_ALLOCATED_HOSTS);
+ Mockito.verify(networkDetailsDao).addDetail(NETWORK_ID, OnesElement.DETAIL_ALLOCATED_HOSTS, "gpu-02", false);
+ }
+
+ @Test
+ public void theHostListIsReadAllocatedAndWrittenUnderTheNetworksLock() throws Exception {
+ Assert.assertTrue(element.prepare(network, null, null, dest, null));
+
+ Assert.assertEquals(Collections.singletonList("ones.hosts." + NETWORK_ID), locks);
+ }
+
+ @Test
+ public void aSecondHostIsAppended() throws Exception {
+ detail(OnesElement.DETAIL_ALLOCATED_HOSTS, "gpu-01");
+
+ Assert.assertTrue(element.prepare(network, null, null, dest, null));
+
+ Assert.assertEquals(Collections.singletonList("gpu-02"), allocateSent().getServerNames());
+ Mockito.verify(networkDetailsDao).addDetail(NETWORK_ID, OnesElement.DETAIL_ALLOCATED_HOSTS, "gpu-01,gpu-02", false);
+ }
+
+ @Test
+ public void aHostAlreadyInTheTenantIsNotAddedAgain() throws Exception {
+ detail(OnesElement.DETAIL_ALLOCATED_HOSTS, "gpu-01,gpu-02");
+
+ Assert.assertTrue(element.prepare(network, null, null, dest, null));
+
+ Mockito.verifyNoInteractions(agentMgr);
+ Mockito.verify(networkDetailsDao, Mockito.never()).addDetail(ArgumentMatchers.anyLong(), ArgumentMatchers.anyString(),
+ ArgumentMatchers.anyString(), ArgumentMatchers.anyBoolean());
+ }
+
+ @Test
+ public void aRefusedAllocationFailsTheDeploymentAndRecordsNothing() {
+ Mockito.when(agentMgr.easySend(ArgumentMatchers.eq(ONES_HOST_ID), ArgumentMatchers.any(AllocateOnesServersCommand.class)))
+ .thenAnswer(i -> new Answer(i.getArgument(1), false, "server not in fabric"));
+
+ CloudRuntimeException e = Assert.assertThrows(CloudRuntimeException.class,
+ () -> element.prepare(network, null, null, dest, null));
+ Assert.assertTrue(e.getMessage(), e.getMessage().contains("server not in fabric"));
+ Mockito.verify(networkDetailsDao, Mockito.never()).addDetail(ArgumentMatchers.anyLong(), ArgumentMatchers.anyString(),
+ ArgumentMatchers.anyString(), ArgumentMatchers.anyBoolean());
+ }
+
+ @Test
+ public void noAnswerFromTheResourceFailsTheDeployment() {
+ Mockito.when(agentMgr.easySend(ArgumentMatchers.eq(ONES_HOST_ID), ArgumentMatchers.any(AllocateOnesServersCommand.class)))
+ .thenReturn(null);
+
+ CloudRuntimeException e = Assert.assertThrows(CloudRuntimeException.class,
+ () -> element.prepare(network, null, null, dest, null));
+ Assert.assertTrue(e.getMessage(), e.getMessage().contains("no answer"));
+ }
+
+ @Test
+ public void aNetworkWithoutATenantRecordFails() {
+ Mockito.when(networkDetailsDao.findDetail(NETWORK_ID, OnesElement.DETAIL_TENANT_NAME)).thenReturn(null);
+
+ Assert.assertThrows(CloudRuntimeException.class, () -> element.prepare(network, null, null, dest, null));
+ Mockito.verifyNoInteractions(agentMgr);
+ }
+
+ @Test
+ public void networksOfOtherProvidersAreLeftAlone() throws Exception {
+ Mockito.when(networkModel.isProviderForNetwork(OnesElement.AVIZ_ONES, NETWORK_ID)).thenReturn(false);
+
+ Assert.assertFalse(element.prepare(network, null, null, dest, null));
+ Assert.assertFalse(element.implement(network, null, null, null));
+ Assert.assertFalse(element.release(network, null, null, null));
+ Mockito.verifyNoInteractions(agentMgr);
+ }
+
+ @Test
+ public void aPlacementWithoutAHostDoesNothing() throws Exception {
+ Mockito.when(dest.getHost()).thenReturn(null);
+
+ Assert.assertFalse(element.prepare(network, null, null, dest, null));
+ Mockito.verifyNoInteractions(agentMgr);
+ }
+
+ @Test
+ public void releasingANicNeverTakesTheHostOut() throws Exception {
+ detail(OnesElement.DETAIL_ALLOCATED_HOSTS, "gpu-02");
+
+ Assert.assertTrue(element.release(network, null, null, null));
+ Assert.assertTrue(element.shutdown(network, null, true));
+ Assert.assertTrue(element.destroy(network, null));
+ Mockito.verifyNoInteractions(agentMgr);
+ }
+
+ // ------------------------------------------------------------------ edge on the Aviz Gateway
+
+ private void edgeServices(final Service... services) {
+ for (Service svc : services) {
+ Mockito.when(ntwkSrvcDao.canProviderSupportServiceInNetwork(NETWORK_ID, svc, OnesElement.AVIZ_ONES)).thenReturn(true);
+ }
+ }
+
+ private void gateway() {
+ Mockito.when(provider.getGatewayUrl()).thenReturn("https://gw.example.com:8090");
+ Mockito.when(provider.getGatewayToken()).thenReturn("token");
+ }
+
+ private ConfigureOnesEdgeCommand edge() {
+ ConfigureOnesEdgeCommand cmd = new ConfigureOnesEdgeCommand(TENANT, "203.0.113.100", Collections.emptyList(),
+ Collections.emptyList(), Collections.emptyList());
+ Mockito.when(edgeBuilder.build(ArgumentMatchers.eq(network), ArgumentMatchers.eq(TENANT), ArgumentMatchers.anyBoolean(),
+ ArgumentMatchers.anyBoolean(), ArgumentMatchers.anyBoolean(), ArgumentMatchers.anyBoolean())).thenReturn(cmd);
+ return cmd;
+ }
+
+ private void gatewayAnswers(final boolean ok) {
+ Mockito.when(agentMgr.easySend(ArgumentMatchers.eq(ONES_HOST_ID), ArgumentMatchers.any(ConfigureOnesEdgeCommand.class)))
+ .thenAnswer(i -> new Answer(i.getArgument(1), ok, ok ? null : "gateway said no"));
+ }
+
+ @Test
+ public void rulesBeforeTheFirstHostWaitForIt() throws Exception {
+ edgeServices(Service.PortForwarding);
+
+ Assert.assertTrue(element.applyPFRules(network, Collections.emptyList()));
+ Mockito.verifyNoInteractions(agentMgr, edgeBuilder);
+ }
+
+ @Test
+ public void aPortForwardPutsTheWholeEdgeOnTheGateway() throws Exception {
+ edgeServices(Service.SourceNat, Service.PortForwarding, Service.Firewall);
+ detail(OnesElement.DETAIL_ALLOCATED_HOSTS, "gpu-02");
+ gateway();
+ ConfigureOnesEdgeCommand cmd = edge();
+ gatewayAnswers(true);
+
+ Assert.assertTrue(element.applyPFRules(network, Collections.emptyList()));
+
+ Mockito.verify(edgeBuilder).build(network, TENANT, true, true, false, true);
+ Mockito.verify(agentMgr).easySend(ONES_HOST_ID, cmd);
+ Assert.assertEquals(OnesElement.EDGE_WAIT_S, cmd.getWait());
+ }
+
+ @Test
+ public void aGatewayFailureFailsTheRule() throws Exception {
+ edgeServices(Service.Lb);
+ detail(OnesElement.DETAIL_ALLOCATED_HOSTS, "gpu-02");
+ gateway();
+ edge();
+ gatewayAnswers(false);
+
+ ResourceUnavailableException e = Assert.assertThrows(ResourceUnavailableException.class,
+ () -> element.applyLBRules(network, Collections.emptyList())); // false would read as "not mine"
+ Assert.assertTrue(e.getMessage(), e.getMessage().contains("gateway said no"));
+ }
+
+ @Test
+ public void edgeServicesWithoutAGatewayFail() throws Exception {
+ edgeServices(Service.PortForwarding);
+ detail(OnesElement.DETAIL_ALLOCATED_HOSTS, "gpu-02");
+
+ ResourceUnavailableException e = Assert.assertThrows(ResourceUnavailableException.class,
+ () -> element.applyPFRules(network, Collections.emptyList()));
+ Assert.assertTrue(e.getMessage(), e.getMessage().contains("no Aviz Gateway"));
+ Mockito.verifyNoInteractions(agentMgr, edgeBuilder);
+ }
+
+ @Test
+ public void rulesOfAServiceTheNetworkDoesNotGetFromUsAreNotOurs() throws Exception {
+ Assert.assertFalse(element.applyPFRules(network, Collections.emptyList()));
+ Assert.assertFalse(element.applyLBRules(network, Collections.emptyList()));
+ Assert.assertFalse(element.applyFWRules(network, Collections.emptyList()));
+ Mockito.verifyNoInteractions(agentMgr);
+ }
+
+ @Test
+ public void theFirstHostBringsTheEdgeAndItsFailureDoesNotFailTheVm() throws Exception {
+ edgeServices(Service.SourceNat);
+ gateway();
+ edge();
+ gatewayAnswers(false);
+ Mockito.when(networkDetailsDao.findDetail(NETWORK_ID, OnesElement.DETAIL_ALLOCATED_HOSTS))
+ .thenReturn(null, new NetworkDetailVO(NETWORK_ID, OnesElement.DETAIL_ALLOCATED_HOSTS, "gpu-02", false));
+
+ Assert.assertTrue(element.prepare(network, null, null, dest, null));
+
+ Mockito.verify(agentMgr).easySend(ArgumentMatchers.eq(ONES_HOST_ID), ArgumentMatchers.any(ConfigureOnesEdgeCommand.class));
+ }
+
+ @Test
+ public void shutdownTakesTheEdgeOffTheGateway() throws Exception {
+ edgeServices(Service.SourceNat);
+ gateway();
+ Mockito.when(agentMgr.easySend(ArgumentMatchers.eq(ONES_HOST_ID), ArgumentMatchers.any(RemoveOnesEdgeCommand.class)))
+ .thenAnswer(i -> new Answer(i.getArgument(1)));
+
+ Assert.assertTrue(element.shutdown(network, null, true));
+
+ ArgumentCaptor c = ArgumentCaptor.forClass(RemoveOnesEdgeCommand.class);
+ Mockito.verify(agentMgr).easySend(ArgumentMatchers.eq(ONES_HOST_ID), c.capture());
+ Assert.assertEquals(TENANT, c.getValue().getTenantName());
+ }
+
+ private LoadBalancingRule lbRule(final String algorithm, final String protocol, final boolean onSourceNat) {
+ LoadBalancer lb = Mockito.mock(LoadBalancer.class);
+ Mockito.lenient().when(lb.getSourceIpAddressId()).thenReturn(77L);
+ IPAddressVO ip = Mockito.mock(IPAddressVO.class);
+ Mockito.lenient().when(ip.isSourceNat()).thenReturn(onSourceNat);
+ Mockito.lenient().when(ipAddressDao.findById(77L)).thenReturn(ip);
+ LoadBalancingRule rule = Mockito.mock(LoadBalancingRule.class);
+ Mockito.lenient().when(rule.getLb()).thenReturn(lb);
+ Mockito.lenient().when(rule.getAlgorithm()).thenReturn(algorithm);
+ Mockito.lenient().when(rule.getLbProtocol()).thenReturn(protocol);
+ Mockito.lenient().when(rule.getSourcePortStart()).thenReturn(80);
+ Mockito.lenient().when(rule.getSourcePortEnd()).thenReturn(80);
+ return rule;
+ }
+
+ @Test
+ public void loadBalancerRulesMustFitTheGatewayVips() {
+ edgeServices(Service.Lb);
+
+ Assert.assertTrue(element.validateLBRule(network, lbRule("roundrobin", "tcp", false)));
+ Assert.assertThrows(InvalidParameterValueException.class, () -> element.validateLBRule(network, lbRule("leastconn", "tcp", false)));
+ Assert.assertThrows(InvalidParameterValueException.class, () -> element.validateLBRule(network, lbRule("roundrobin", "ssl", false)));
+ Assert.assertThrows(InvalidParameterValueException.class, () -> element.validateLBRule(network, lbRule("roundrobin", "tcp", true)));
+ }
+
+ // ------------------------------------------------------------------ provider description
+
+ @Test
+ public void describesItsServices() {
+ Assert.assertEquals("AvizOnes", element.getProvider().getName());
+ Assert.assertEquals(new HashSet<>(Arrays.asList(Service.Connectivity, Service.SourceNat, Service.Firewall, Service.PortForwarding,
+ Service.Lb)), element.getCapabilities().keySet());
+ String stickiness = element.getCapabilities().get(Service.Lb).get(Capability.SupportedStickinessMethods);
+ Assert.assertTrue(stickiness, stickiness.contains("SourceBased") && !stickiness.contains("LbCookie") && !stickiness.contains("AppCookie"));
+ Assert.assertEquals("roundrobin", element.getCapabilities().get(Service.Lb).get(Capability.SupportedLBAlgorithms));
+ Assert.assertFalse(element.getCapabilities().get(Service.Firewall).containsKey(Capability.TrafficStatistics));
+ Assert.assertTrue(element.verifyServicesCombination(new HashSet<>(Arrays.asList(Service.Connectivity, Service.Dhcp))));
+ Assert.assertFalse(element.verifyServicesCombination(Collections.singleton(Service.Dhcp)));
+ Assert.assertEquals(4, element.getCommands().size());
+ }
+
+ // ------------------------------------------------------------------ provider API
+
+ private UpdateOnesProviderCmd update(final String gatewayUrl) {
+ UpdateOnesProviderCmd cmd = Mockito.mock(UpdateOnesProviderCmd.class);
+ Mockito.when(cmd.getId()).thenReturn(7L);
+ Mockito.when(cmd.getGatewayUrl()).thenReturn(gatewayUrl);
+ return cmd;
+ }
+
+ @Test
+ public void updateStoresKeepsAndClearsAGatewaySetting() {
+ OnesProviderVO vo = new OnesProviderVO();
+ ReflectionTestUtils.setField(vo, "id", 7L); // as the DAO would return it
+ Mockito.when(onesProviderDao.findById(7L)).thenReturn(vo);
+
+ element.updateOnesProvider(update(" https://gw.example.com:8090 "));
+ Assert.assertEquals("https://gw.example.com:8090", vo.getGatewayUrl());
+ Mockito.verify(onesProviderDao).update(7L, vo);
+
+ element.updateOnesProvider(update(null)); // not given: unchanged
+ Assert.assertEquals("https://gw.example.com:8090", vo.getGatewayUrl());
+
+ element.updateOnesProvider(update("")); // blank: cleared
+ Assert.assertNull(vo.getGatewayUrl());
+ }
+
+ private DeleteOnesProviderCmd deleteProvider(final Network.State state) {
+ NetworkVO n = Mockito.mock(NetworkVO.class);
+ Mockito.when(n.getId()).thenReturn(NETWORK_ID);
+ Mockito.lenient().when(n.getState()).thenReturn(state);
+ Mockito.when(provider.getPhysicalNetworkId()).thenReturn(PHYSNET_ID);
+ Mockito.when(onesProviderDao.findById(7L)).thenReturn(provider);
+ Mockito.when(networkDao.listByPhysicalNetwork(PHYSNET_ID)).thenReturn(Collections.singletonList(n));
+ DeleteOnesProviderCmd cmd = Mockito.mock(DeleteOnesProviderCmd.class);
+ Mockito.when(cmd.getId()).thenReturn(7L);
+ return cmd;
+ }
+
+ @Test
+ public void aProviderWhoseNetworkIsOnlyShutDownCannotBeDeleted() {
+ // a Shutdown network still owns its ONES tenant, and deleting it needs the provider
+ CloudRuntimeException e = Assert.assertThrows(CloudRuntimeException.class,
+ () -> element.deleteOnesProvider(deleteProvider(Network.State.Shutdown)));
+ Assert.assertTrue(e.getMessage(), e.getMessage().contains("still uses it"));
+ Mockito.verify(onesProviderDao, Mockito.never()).remove(ArgumentMatchers.anyLong());
+ }
+
+ @Test
+ public void aDestroyedNetworkThatStillHasItsTenantBlocksTheDeleteToo() {
+ Assert.assertThrows(CloudRuntimeException.class, () -> element.deleteOnesProvider(deleteProvider(Network.State.Destroy)));
+ }
+
+ @Test
+ public void updateOfAnUnknownProviderFails() {
+ Assert.assertThrows(InvalidParameterValueException.class, () -> element.updateOnesProvider(update(null)));
+ }
+
+ @Test
+ public void listNeedsAnIdOrAPhysicalNetwork() {
+ ListOnesProvidersCmd cmd = Mockito.mock(ListOnesProvidersCmd.class);
+ Assert.assertThrows(InvalidParameterValueException.class, () -> element.listOnesProviders(cmd));
+
+ Mockito.when(cmd.getId()).thenReturn(7L);
+ Mockito.when(onesProviderDao.findById(7L)).thenReturn(provider);
+ Assert.assertEquals(Collections.singletonList(provider), element.listOnesProviders(cmd));
+ }
+}
diff --git a/plugins/network-elements/aviz-ones/src/test/java/org/apache/cloudstack/network/ones/service/OnesGuestNetworkGuruTest.java b/plugins/network-elements/aviz-ones/src/test/java/org/apache/cloudstack/network/ones/service/OnesGuestNetworkGuruTest.java
new file mode 100644
index 000000000000..d0f8b3eceec3
--- /dev/null
+++ b/plugins/network-elements/aviz-ones/src/test/java/org/apache/cloudstack/network/ones/service/OnesGuestNetworkGuruTest.java
@@ -0,0 +1,513 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you 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.apache.cloudstack.network.ones.service;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.cloudstack.network.ones.agent.api.CreateOnesTenantAnswer;
+import org.apache.cloudstack.network.ones.agent.api.CreateOnesTenantCommand;
+import org.apache.cloudstack.network.ones.agent.api.DeallocateOnesServersCommand;
+import org.apache.cloudstack.network.ones.agent.api.DeleteOnesTenantCommand;
+import org.apache.cloudstack.network.ones.dao.OnesProviderDao;
+import org.apache.cloudstack.network.ones.dao.OnesProviderVO;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.ArgumentMatchers;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import com.cloud.agent.AgentManager;
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.Command;
+import com.cloud.dc.DataCenter.NetworkType;
+import com.cloud.dc.DataCenterVO;
+import com.cloud.dc.dao.DataCenterDao;
+import com.cloud.deploy.DeploymentPlan;
+import com.cloud.exception.InsufficientAddressCapacityException;
+import com.cloud.network.Network.GuestType;
+import com.cloud.network.Network;
+import com.cloud.network.NetworkProfile;
+import com.cloud.network.Networks.BroadcastDomainType;
+import com.cloud.network.Networks.Mode;
+import com.cloud.network.Networks.TrafficType;
+import com.cloud.network.dao.NetworkDetailVO;
+import com.cloud.network.dao.NetworkDetailsDao;
+import com.cloud.network.dao.NetworkVO;
+import com.cloud.network.dao.PhysicalNetworkDao;
+import com.cloud.network.dao.PhysicalNetworkVO;
+import com.cloud.offering.NetworkOffering;
+import com.cloud.offerings.dao.NetworkOfferingServiceMapDao;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.vm.dao.NicDao;
+
+@RunWith(MockitoJUnitRunner.Silent.class)
+public class OnesGuestNetworkGuruTest {
+
+ private static final long ZONE_ID = 1L;
+ private static final long PHYSNET_ID = 200L;
+ private static final long OFFERING_ID = 10L;
+ private static final long ONES_HOST_ID = 5L;
+ private static final long NETWORK_ID = 42L;
+ private static final String FABRIC = "fab1";
+
+ @Mock
+ private OnesProviderDao onesProviderDao;
+ @Mock
+ private AgentManager agentMgr;
+ @Mock
+ private NetworkDetailsDao networkDetailsDao;
+ @Mock
+ private NetworkOfferingServiceMapDao offeringServiceMapDao;
+ @Mock
+ private PhysicalNetworkDao physicalNetworkDao;
+ @Mock
+ private DataCenterDao dataCenterDao;
+ @Mock
+ private NicDao nicDao;
+
+ @Mock
+ private OnesProviderVO provider;
+ @Mock
+ private PhysicalNetworkVO physicalNetwork;
+ @Mock
+ private DataCenterVO zone;
+ @Mock
+ private DeploymentPlan plan;
+ @Mock
+ private NetworkOffering offering;
+
+ private OnesGuestNetworkGuru guru;
+
+ @Before
+ public void setUp() {
+ guru = new OnesGuestNetworkGuru();
+ guru.onesProviderDao = onesProviderDao;
+ guru.agentMgr = agentMgr;
+ guru.networkDetailsDao = networkDetailsDao;
+ guru.ntwkOfferingSrvcDao = offeringServiceMapDao;
+ ReflectionTestUtils.setField(guru, "_physicalNetworkDao", physicalNetworkDao); // GuestNetworkGuru's, protected
+ ReflectionTestUtils.setField(guru, "_dcDao", dataCenterDao); // GuestNetworkGuru's, protected
+ ReflectionTestUtils.setField(guru, "_nicDao", nicDao); // GuestNetworkGuru's, protected
+
+ Mockito.when(provider.getHostId()).thenReturn(ONES_HOST_ID);
+ Mockito.when(provider.getFabricName()).thenReturn(FABRIC);
+ Mockito.when(onesProviderDao.listByPhysicalNetwork(PHYSNET_ID)).thenReturn(Collections.singletonList(provider));
+
+ Mockito.when(physicalNetwork.getId()).thenReturn(PHYSNET_ID);
+ Mockito.when(physicalNetwork.getIsolationMethods()).thenReturn(Collections.singletonList("ONES"));
+ Mockito.when(physicalNetworkDao.findById(PHYSNET_ID)).thenReturn(physicalNetwork);
+ Mockito.when(zone.getNetworkType()).thenReturn(NetworkType.Advanced);
+ Mockito.when(zone.getGuestNetworkCidr()).thenReturn("10.1.1.0/24");
+ Mockito.when(dataCenterDao.findById(ZONE_ID)).thenReturn(zone);
+ Mockito.when(plan.getPhysicalNetworkId()).thenReturn(PHYSNET_ID);
+ Mockito.when(plan.getDataCenterId()).thenReturn(ZONE_ID);
+ Mockito.when(offering.getId()).thenReturn(OFFERING_ID);
+ Mockito.when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
+ Mockito.when(offering.getGuestType()).thenReturn(GuestType.Isolated);
+ Mockito.when(offeringServiceMapDao.canProviderSupportServiceInNetworkOffering(OFFERING_ID, Network.Service.Connectivity,
+ OnesElement.AVIZ_ONES)).thenReturn(true);
+ }
+
+ // ------------------------------------------------------------------ helpers
+
+ private CreateOnesTenantAnswer onesSays(final String subnet, final String gateway) {
+ CreateOnesTenantAnswer a = new CreateOnesTenantAnswer(new CreateOnesTenantCommand(FABRIC, "x", null, -1), "{}",
+ 1001, 20001, 30001, subnet, subnet.replace("0.0/16", "64.0/18"), gateway);
+ Mockito.when(agentMgr.easySend(ArgumentMatchers.eq(ONES_HOST_ID), ArgumentMatchers.any(CreateOnesTenantCommand.class))).thenReturn(a);
+ Mockito.when(agentMgr.easySend(ArgumentMatchers.eq(ONES_HOST_ID), ArgumentMatchers.any(DeleteOnesTenantCommand.class)))
+ .thenAnswer(i -> new Answer(i.getArgument(1)));
+ return a;
+ }
+
+ private List sent(final Class type) {
+ ArgumentCaptor c = ArgumentCaptor.forClass(type);
+ Mockito.verify(agentMgr, Mockito.atLeast(0)).easySend(ArgumentMatchers.eq(ONES_HOST_ID), c.capture());
+ List out = new java.util.ArrayList<>();
+ for (Object o : c.getAllValues()) {
+ if (type.isInstance(o)) {
+ out.add(type.cast(o));
+ }
+ }
+ return out;
+ }
+
+ private void detail(final long networkId, final String key, final String value) {
+ NetworkDetailVO d = new NetworkDetailVO(networkId, key, value, false);
+ Mockito.when(networkDetailsDao.findDetail(networkId, key)).thenReturn(d);
+ }
+
+ private static Network userSpecified(final String cidr, final String gateway) {
+ Network n = Mockito.mock(Network.class);
+ Mockito.when(n.getCidr()).thenReturn(cidr);
+ Mockito.when(n.getGateway()).thenReturn(gateway);
+ return n;
+ }
+
+ // ------------------------------------------------------------------ tenant names
+
+ @Test
+ public void tenantNamesFitOnesRules() {
+ Set seen = new HashSet<>();
+ for (int i = 0; i < 1000; i++) {
+ String name = OnesGuestNetworkGuru.newTenantName();
+ Assert.assertTrue(name, name.matches("^cs[0-9a-f]{10}$"));
+ Assert.assertTrue(name, name.matches("^[A-Za-z][A-Za-z0-9_-]{0,11}$")); // ONES's own pattern
+ Assert.assertTrue("duplicate tenant name " + name, seen.add(name));
+ }
+ }
+
+ // ------------------------------------------------------------------ canHandle / design
+
+ @Test
+ public void ignoresPhysicalNetworksWithoutTheOnesIsolationMethod() {
+ Mockito.when(physicalNetwork.getIsolationMethods()).thenReturn(Collections.singletonList("VLAN"));
+
+ Assert.assertNull(guru.design(offering, plan, null, "n1", null, null));
+ Mockito.verifyNoInteractions(agentMgr);
+ }
+
+ @Test
+ public void ignoresOfferingsWithoutAvizOnesConnectivity() {
+ Mockito.when(offeringServiceMapDao.canProviderSupportServiceInNetworkOffering(OFFERING_ID, Network.Service.Connectivity,
+ OnesElement.AVIZ_ONES)).thenReturn(false);
+
+ Assert.assertNull(guru.design(offering, plan, null, "n1", null, null));
+ Mockito.verifyNoInteractions(agentMgr);
+ }
+
+ @Test
+ public void ignoresSharedAndL2Offerings() {
+ Assert.assertFalse(guru.canHandle(offering, NetworkType.Basic, physicalNetwork));
+ Mockito.when(offering.getGuestType()).thenReturn(GuestType.Shared);
+ Assert.assertFalse(guru.canHandle(offering, NetworkType.Advanced, physicalNetwork));
+ Mockito.when(offering.getGuestType()).thenReturn(GuestType.Isolated);
+ Assert.assertTrue(guru.canHandle(offering, NetworkType.Advanced, physicalNetwork));
+ }
+
+ @Test
+ public void designCreatesTheTenantAndTakesItsSubnetAndGateway() {
+ onesSays("192.1.0.0/16", "192.1.0.1");
+
+ Network n = guru.design(offering, plan, null, "n1", null, null);
+
+ List creates = sent(CreateOnesTenantCommand.class);
+ Assert.assertEquals(1, creates.size());
+ CreateOnesTenantCommand cmd = creates.get(0);
+ Assert.assertEquals(FABRIC, cmd.getFabricName());
+ Assert.assertTrue(cmd.getTenantName(), cmd.getTenantName().matches("^cs[0-9a-f]{10}$"));
+ Assert.assertEquals(-1, cmd.getMaxGpusAllowed());
+ Assert.assertEquals(900, cmd.getWait());
+ Assert.assertEquals("192.1.0.0/16", n.getCidr());
+ Assert.assertEquals("192.1.0.1", n.getGateway());
+ Assert.assertNull(n.getNetworkCidr());
+ Assert.assertEquals(BroadcastDomainType.Vlan, n.getBroadcastDomainType());
+ Assert.assertTrue(sent(DeleteOnesTenantCommand.class).isEmpty());
+ }
+
+ @Test
+ public void designKeepsARequestedGatewayInsideTheTenantSubnet() {
+ onesSays("192.2.0.0/16", "192.2.255.253");
+
+ Network n = guru.design(offering, plan, userSpecified("192.2.0.0/16", "192.2.128.3"), "n1", null, null);
+
+ Assert.assertEquals("192.2.0.0/16", n.getCidr());
+ Assert.assertEquals("192.2.128.3", n.getGateway());
+ }
+
+ @Test
+ public void designTakesARequestedGatewayOutsideTheSubnetAsAPlaceholder() {
+ onesSays("192.3.0.0/16", "192.3.0.1");
+
+ Network n = guru.design(offering, plan, userSpecified("10.255.255.0/24", "10.255.255.1"), "n1", null, null);
+
+ Assert.assertEquals("192.3.0.0/16", n.getCidr());
+ Assert.assertEquals("192.3.0.1", n.getGateway());
+ Assert.assertTrue(sent(DeleteOnesTenantCommand.class).isEmpty());
+ }
+
+ @Test
+ public void designDeletesTheTenantWhenThereIsNoUsableGateway() {
+ onesSays("192.5.0.0/16", "10.9.9.9"); // ONES's gateway is outside its own subnet
+
+ try {
+ guru.design(offering, plan, null, "n1", null, null);
+ Assert.fail("designed a network with no usable gateway");
+ } catch (CloudRuntimeException e) {
+ Assert.assertTrue(e.getMessage(), e.getMessage().contains("No usable gateway"));
+ }
+ List creates = sent(CreateOnesTenantCommand.class);
+ List deletes = sent(DeleteOnesTenantCommand.class);
+ Assert.assertEquals(1, deletes.size());
+ Assert.assertEquals(creates.get(0).getTenantName(), deletes.get(0).getTenantName());
+ }
+
+ @Test
+ public void designDeletesTheTenantWhenOnesGaveNoVlan() {
+ CreateOnesTenantAnswer noVlan = new CreateOnesTenantAnswer(new CreateOnesTenantCommand(FABRIC, "x", null, -1), "{}",
+ null, null, null, "192.6.0.0/16", "192.6.64.0/18", "192.6.0.1");
+ onesSays("192.6.0.0/16", "192.6.0.1");
+ Mockito.when(agentMgr.easySend(ArgumentMatchers.eq(ONES_HOST_ID), ArgumentMatchers.any(CreateOnesTenantCommand.class))).thenReturn(noVlan);
+
+ Assert.assertThrows(CloudRuntimeException.class, () -> guru.design(offering, plan, null, "n1", null, null));
+ Assert.assertEquals(1, sent(DeleteOnesTenantCommand.class).size());
+ }
+
+ @Test
+ public void designFailsWhenOnesCannotCreateTheTenant() {
+ Mockito.when(agentMgr.easySend(ArgumentMatchers.eq(ONES_HOST_ID), ArgumentMatchers.any(CreateOnesTenantCommand.class)))
+ .thenAnswer(i -> new CreateOnesTenantAnswer(i.getArgument(1), new Exception("fabric busy")));
+
+ CloudRuntimeException e = Assert.assertThrows(CloudRuntimeException.class,
+ () -> guru.design(offering, plan, null, "n1", null, null));
+ Assert.assertTrue(e.getMessage(), e.getMessage().contains("could not create tenant"));
+ Assert.assertTrue(sent(DeleteOnesTenantCommand.class).isEmpty());
+ }
+
+ @Test
+ public void designFailsWithoutAProvider() {
+ Mockito.when(onesProviderDao.listByPhysicalNetwork(PHYSNET_ID)).thenReturn(Collections.emptyList());
+
+ Assert.assertThrows(CloudRuntimeException.class, () -> guru.design(offering, plan, null, "n1", null, null));
+ Mockito.verifyNoInteractions(agentMgr);
+ }
+
+ // ------------------------------------------------------------------ setup / implement
+
+ @Test
+ public void setupRecordsTheTenantOnTheNetwork() {
+ onesSays("192.7.0.0/16", "192.7.0.1");
+ Network designed = guru.design(offering, plan, null, "n1", null, null);
+ String tenant = sent(CreateOnesTenantCommand.class).get(0).getTenantName();
+
+ guru.setup(designed, NETWORK_ID);
+
+ Mockito.verify(networkDetailsDao).addDetail(NETWORK_ID, OnesElement.DETAIL_TENANT_NAME, tenant, false);
+ Mockito.verify(networkDetailsDao).addDetail(NETWORK_ID, OnesGuestNetworkGuru.DETAIL_VLAN, "1001", false);
+ Mockito.verify(networkDetailsDao).addDetail(NETWORK_ID, OnesGuestNetworkGuru.DETAIL_POOL, "192.7.64.0/18", false);
+ Mockito.verify(networkDetailsDao).addDetail(NETWORK_ID, OnesGuestNetworkGuru.DETAIL_L3VNI, "30001", false);
+
+ // a second setup of the same CIDR (e.g. a retry) finds nothing pending
+ Mockito.clearInvocations(networkDetailsDao);
+ guru.setup(designed, NETWORK_ID + 1);
+ Mockito.verifyNoInteractions(networkDetailsDao);
+ }
+
+ @Test
+ public void setupOfANetworkThisGuruDidNotDesignDoesNothing() {
+ NetworkVO other = new NetworkVO(TrafficType.Guest, Mode.Dhcp, BroadcastDomainType.Vlan, OFFERING_ID,
+ Network.State.Allocated, ZONE_ID, PHYSNET_ID, false);
+ other.setCidr("172.16.0.0/24");
+
+ guru.setup(other, NETWORK_ID);
+
+ Mockito.verifyNoInteractions(networkDetailsDao);
+ }
+
+ private Network implementing() {
+ Network n = Mockito.mock(Network.class);
+ Mockito.when(n.getId()).thenReturn(NETWORK_ID);
+ Mockito.when(n.getUuid()).thenReturn("net-uuid");
+ Mockito.when(n.getState()).thenReturn(Network.State.Implementing);
+ Mockito.when(n.getTrafficType()).thenReturn(TrafficType.Guest);
+ Mockito.when(n.getMode()).thenReturn(Mode.Dhcp);
+ Mockito.when(n.getNetworkOfferingId()).thenReturn(OFFERING_ID);
+ Mockito.when(n.getDataCenterId()).thenReturn(ZONE_ID);
+ Mockito.when(n.getPhysicalNetworkId()).thenReturn(PHYSNET_ID);
+ Mockito.when(n.getCidr()).thenReturn("192.1.0.0/16");
+ Mockito.when(n.getGateway()).thenReturn("192.1.128.3");
+ return n;
+ }
+
+ @Test
+ public void implementPutsTheNetworkOnTheTenantVlan() throws Exception {
+ detail(NETWORK_ID, OnesGuestNetworkGuru.DETAIL_VLAN, "1001");
+
+ Network n = guru.implement(implementing(), offering, null, null);
+
+ Assert.assertEquals("vlan://1001", n.getBroadcastUri().toString());
+ Assert.assertEquals(BroadcastDomainType.Vlan, n.getBroadcastDomainType());
+ Assert.assertEquals("192.1.0.0/16", n.getCidr());
+ Assert.assertEquals("192.1.128.3", n.getGateway());
+ }
+
+ @Test
+ public void implementFailsWithoutARecordedVlan() {
+ CloudRuntimeException e = Assert.assertThrows(CloudRuntimeException.class,
+ () -> guru.implement(implementing(), offering, null, null));
+ Assert.assertTrue(e.getMessage(), e.getMessage().contains("net-uuid"));
+ }
+
+ // ------------------------------------------------------------------ NIC addresses
+
+ @Test
+ public void nicAddressesStartAtDotTenOfThePoolAndSkipUsedOnes() throws Exception {
+ Network n = implementing();
+ Mockito.when(nicDao.listIpAddressInNetwork(NETWORK_ID)).thenReturn(Arrays.asList("192.1.64.10", "192.1.64.11"));
+
+ Assert.assertEquals("192.1.64.12", guru.freeAddress(n, "192.1.64.0/18"));
+ }
+
+ @Test
+ public void nicAddressesNeverTakeTheGateway() throws Exception {
+ Network n = implementing();
+ Mockito.when(n.getGateway()).thenReturn("192.1.64.10");
+ Mockito.when(nicDao.listIpAddressInNetwork(NETWORK_ID)).thenReturn(Collections.emptyList());
+
+ Assert.assertEquals("192.1.64.11", guru.freeAddress(n, "192.1.64.0/18"));
+ }
+
+ @Test
+ public void aSlash27PoolStillKeepsTheBottomNineForTheOperator() throws Exception {
+ Network n = implementing();
+ Mockito.when(nicDao.listIpAddressInNetwork(NETWORK_ID)).thenReturn(Collections.emptyList());
+
+ Assert.assertEquals("10.0.0.10", guru.freeAddress(n, "10.0.0.0/27")); // 30 usable: .1-.9 reserved
+ }
+
+ @Test
+ public void smallPoolsAreUsedFromDotOne() throws Exception {
+ Network n = implementing();
+ Mockito.when(nicDao.listIpAddressInNetwork(NETWORK_ID)).thenReturn(Collections.emptyList());
+
+ Assert.assertEquals("10.0.0.1", guru.freeAddress(n, "10.0.0.0/28")); // 14 usable
+ Assert.assertEquals("10.0.0.1", guru.freeAddress(n, "10.0.0.0/29")); // 6 usable: used to be always "full"
+ Assert.assertEquals("10.0.0.1", guru.freeAddress(n, "10.0.0.0/30")); // 2 usable
+ }
+
+ @Test
+ public void aSmallPoolStillSkipsTheGatewayAndUsedAddresses() throws Exception {
+ Network n = implementing();
+ Mockito.when(n.getGateway()).thenReturn("10.0.0.1");
+ Mockito.when(nicDao.listIpAddressInNetwork(NETWORK_ID)).thenReturn(Arrays.asList("10.0.0.2", "10.0.0.3"));
+
+ Assert.assertEquals("10.0.0.4", guru.freeAddress(n, "10.0.0.0/29"));
+ }
+
+ @Test
+ public void aFullPoolIsReported() {
+ Network n = implementing();
+ Mockito.when(nicDao.listIpAddressInNetwork(NETWORK_ID)).thenReturn(Arrays.asList("10.0.0.1", "10.0.0.2"));
+
+ Assert.assertThrows(InsufficientAddressCapacityException.class, () -> guru.freeAddress(n, "10.0.0.0/30"));
+ }
+
+ @Test
+ public void aFullLargePoolIsReported() {
+ Network n = implementing();
+ Mockito.when(nicDao.listIpAddressInNetwork(NETWORK_ID)).thenReturn(Arrays.asList("10.0.0.10", "10.0.0.11", "10.0.0.12",
+ "10.0.0.13", "10.0.0.14", "10.0.0.15", "10.0.0.16", "10.0.0.17", "10.0.0.18", "10.0.0.19", "10.0.0.20", "10.0.0.21",
+ "10.0.0.22", "10.0.0.23", "10.0.0.24", "10.0.0.25", "10.0.0.26", "10.0.0.27", "10.0.0.28", "10.0.0.29", "10.0.0.30"));
+
+ Assert.assertThrows(InsufficientAddressCapacityException.class, () -> guru.freeAddress(n, "10.0.0.0/27"));
+ }
+
+ // ------------------------------------------------------------------ shutdown / trash
+
+ private NetworkProfile profile() {
+ NetworkProfile p = Mockito.mock(NetworkProfile.class);
+ Mockito.when(p.getId()).thenReturn(NETWORK_ID);
+ Mockito.when(p.getPhysicalNetworkId()).thenReturn(PHYSNET_ID);
+ return p;
+ }
+
+ @Test
+ public void shutdownTakesTheNetworksHostsOutOfTheTenant() {
+ detail(NETWORK_ID, OnesElement.DETAIL_TENANT_NAME, "cs0123456789");
+ detail(NETWORK_ID, OnesElement.DETAIL_ALLOCATED_HOSTS, "gpu-01,gpu-02");
+ Mockito.when(agentMgr.easySend(ArgumentMatchers.eq(ONES_HOST_ID), ArgumentMatchers.any(DeallocateOnesServersCommand.class)))
+ .thenAnswer(i -> new Answer(i.getArgument(1)));
+
+ guru.shutdown(profile(), offering);
+
+ DeallocateOnesServersCommand cmd = sent(DeallocateOnesServersCommand.class).get(0);
+ Assert.assertEquals(FABRIC, cmd.getFabricName());
+ Assert.assertEquals("cs0123456789", cmd.getTenantName());
+ Assert.assertEquals(Arrays.asList("gpu-01", "gpu-02"), cmd.getServerNames());
+ Mockito.verify(networkDetailsDao).removeDetail(NETWORK_ID, OnesElement.DETAIL_ALLOCATED_HOSTS);
+ Assert.assertTrue(sent(DeleteOnesTenantCommand.class).isEmpty()); // the tenant stays until trash
+ }
+
+ @Test
+ public void shutdownKeepsTheHostListWhenOnesFails() {
+ detail(NETWORK_ID, OnesElement.DETAIL_TENANT_NAME, "cs0123456789");
+ detail(NETWORK_ID, OnesElement.DETAIL_ALLOCATED_HOSTS, "gpu-01");
+ Mockito.when(agentMgr.easySend(ArgumentMatchers.eq(ONES_HOST_ID), ArgumentMatchers.any(DeallocateOnesServersCommand.class)))
+ .thenAnswer(i -> new Answer(i.getArgument(1), false, "fabric busy"));
+
+ guru.shutdown(profile(), offering);
+
+ Mockito.verify(networkDetailsDao, Mockito.never()).removeDetail(NETWORK_ID, OnesElement.DETAIL_ALLOCATED_HOSTS);
+ }
+
+ @Test
+ public void shutdownWithNoHostsSendsNothing() {
+ detail(NETWORK_ID, OnesElement.DETAIL_TENANT_NAME, "cs0123456789");
+
+ guru.shutdown(profile(), offering);
+
+ Mockito.verifyNoInteractions(agentMgr);
+ }
+
+ private Network trashed() {
+ Network n = Mockito.mock(Network.class);
+ Mockito.when(n.getId()).thenReturn(NETWORK_ID);
+ Mockito.when(n.getPhysicalNetworkId()).thenReturn(PHYSNET_ID);
+ return n;
+ }
+
+ @Test
+ public void trashDeletesTheTenant() {
+ detail(NETWORK_ID, OnesElement.DETAIL_TENANT_NAME, "cs0123456789");
+ Mockito.when(agentMgr.easySend(ArgumentMatchers.eq(ONES_HOST_ID), ArgumentMatchers.any(DeleteOnesTenantCommand.class)))
+ .thenAnswer(i -> new Answer(i.getArgument(1)));
+
+ Assert.assertTrue(guru.trash(trashed(), offering));
+
+ DeleteOnesTenantCommand cmd = sent(DeleteOnesTenantCommand.class).get(0);
+ Assert.assertEquals(FABRIC, cmd.getFabricName());
+ Assert.assertEquals("cs0123456789", cmd.getTenantName());
+ Mockito.verify(networkDetailsDao).removeDetails(NETWORK_ID);
+ }
+
+ @Test
+ public void trashFailsAndKeepsTheDetailsWhenOnesCannotDelete() {
+ detail(NETWORK_ID, OnesElement.DETAIL_TENANT_NAME, "cs0123456789");
+ Mockito.when(agentMgr.easySend(ArgumentMatchers.eq(ONES_HOST_ID), ArgumentMatchers.any(DeleteOnesTenantCommand.class)))
+ .thenReturn(null);
+
+ Assert.assertFalse(guru.trash(trashed(), offering));
+ Mockito.verify(networkDetailsDao, Mockito.never()).removeDetails(NETWORK_ID);
+ }
+
+ @Test
+ public void trashOfANetworkWithoutATenantSendsNothing() {
+ Assert.assertTrue(guru.trash(trashed(), offering));
+ Mockito.verifyNoInteractions(agentMgr);
+ }
+}
diff --git a/plugins/pom.xml b/plugins/pom.xml
index 92768827f658..fb87ea527043 100755
--- a/plugins/pom.xml
+++ b/plugins/pom.xml
@@ -101,6 +101,7 @@
metrics
+ network-elements/aviz-ones
network-elements/bigswitch
network-elements/dns-notifier
network-elements/elastic-loadbalancer
diff --git a/tools/apidoc/gen_toc.py b/tools/apidoc/gen_toc.py
index 30b97bedabd1..d73e259d9c2d 100644
--- a/tools/apidoc/gen_toc.py
+++ b/tools/apidoc/gen_toc.py
@@ -101,6 +101,7 @@
'addNsxController': 'NSX',
'deleteNsxController': 'NSX',
'NetrisProvider': 'Netris',
+ 'OnesProvider': 'Aviz ONES',
'Vpn': 'VPN',
'Limit': 'Resource Limit',
'Netscaler': 'Netscaler',