Ashok-Aviz commented on code in PR #14902:
URL: https://github.com/apache/cloudstack/pull/14902#discussion_r4734821841


##########
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<String, CreateOnesTenantAnswer> PENDING = new 
ConcurrentHashMap<>();
+    private static final Map<String, String> 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<OnesProviderVO> 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<String> 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<String> 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<String> 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);

Review Comment:
   Fixed in 4a1aef6687. `removeHosts` now returns whether the hosts were 
removed, and `trash` returns false without deleting the tenant or its details 
while hosts remain recorded, so the cleanup can be retried. Test: 
`trashKeepsTheTenantWhileHostsCannotBeTakenOut`.



##########
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://&lt;ones&gt;/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://&lt;ones&gt;: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);

Review Comment:
   Fixed in 4a1aef6687. `createTenant` records whether this call created the 
tenant. If a later step fails (for example reading the tenant back), it deletes 
the tenant again, and if that deletion also fails, the answer names the tenant 
to delete in ONES. A tenant that already existed is never deleted. Tests: 
`createTenantDeletesATenantItMadeWhenReadingItBackFails`, 
`createTenantNeverDeletesATenantItDidNotMake`.



##########
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());

Review Comment:
   Fixed in 4a1aef6687. `AvizGatewayClient` is now `Closeable` (it closes its 
connection pool), and `OnesResource` opens and closes it around each edge 
command with try-with-resources. A new client per command is kept on purpose, 
because the gateway settings can change at any time through 
`updateOnesProvider`.



##########
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<Service, Map<Capability, String>> 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<Service, Map<Capability, String>> getCapabilities() {
+        return CAPABILITIES;
+    }
+
+    @Override
+    public Provider getProvider() {
+        return AVIZ_ONES;
+    }
+
+    private static Map<Service, Map<Capability, String>> setCapabilities() {
+        Map<Service, Map<Capability, String>> 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<Capability, String> sourceNat = new HashMap<>();
+        sourceNat.put(Capability.SupportedSourceNatTypes, "peraccount");
+        sourceNat.put(Capability.RedundantRouter, "false");
+        capabilities.put(Service.SourceNat, sourceNat);
+        Map<Capability, String> 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<Capability, String> 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<OnesProviderVO> 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<String> 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<String> 
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<String, Object> 
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<String> 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<Service> 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<Class<?>> getCommands() {
+        List<Class<?>> 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<String, String> 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<String, Object> 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<OnesProviderVO>) 
(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<NetworkVO> 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<OnesProviderVO> listOnesProviders(final ListOnesProvidersCmd 
cmd) {
+        Long physicalNetworkId = cmd.getPhysicalNetworkId();
+        Long id = cmd.getId();
+        List<OnesProviderVO> 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<String, String> details, final List<String> 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();
+        }

Review Comment:
   Fixed in 4a1aef6687. Before the first host joins, `edgeSync` still builds 
the edge command, which runs every check, and only skips sending it. A rule the 
gateway could not take is therefore refused when it is created. Tests: 
`rulesBeforeTheFirstHostWaitForItButAreCheckedNow`, 
`aRuleTheGatewayCouldNotTakeIsRefusedBeforeTheFirstHost`.



##########
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://&lt;tenant vlanId&gt;: 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<String, CreateOnesTenantAnswer> PENDING = new 
ConcurrentHashMap<>();
+    private static final Map<String, String> 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<OnesProviderVO> 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;

Review Comment:
   Agreed that this can happen, and the plugin alone cannot fully close it. The 
tenant has to exist in `design()` because the network takes its CIDR and 
gateway from ONES when it is created. If persisting the network then fails, 
core does not call the guru back (`setup()` is not reached and `trash()` is 
never called). A real fix needs a core hook, or a way to create the network 
before its CIDR is known; we kept this PR plugin-only, so it is now a 
documented limitation (README, docs and the PR description). Meanwhile the 
tenant name is logged when it is created, and the tenant's description names 
the network, so an operator can find and delete it in ONES. We would be glad to 
propose a small core hook (for example a guru callback when `setupNetwork` 
fails after `design`) in a separate PR if maintainers think that is the right 
direction.



##########
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://&lt;tenant vlanId&gt;: 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<String, CreateOnesTenantAnswer> PENDING = new 
ConcurrentHashMap<>();
+    private static final Map<String, String> 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<OnesProviderVO> 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<String> used = new 
HashSet<>(_nicDao.listIpAddressInNetwork(network.getId()));

Review Comment:
   Fixed in 4a1aef6687. `freeAddress` now uses 
`NetworkModel.getUsedIpsInNetwork(network)`, which covers NIC, secondary NIC, 
internal LB and trunk addresses, plus the gateway. The allocator tests mock 
that complete set. Test: `secondaryAndOtherReservedAddressesAreSkipped`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to