Copilot commented on code in PR #14902:
URL: https://github.com/apache/cloudstack/pull/14902#discussion_r4734863232


##########
plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/client/AvizGatewayClient.java:
##########
@@ -0,0 +1,426 @@
+//
+// 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.Closeable;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.security.KeyStore;
+import java.security.SecureRandom;
+import java.security.cert.CertificateFactory;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.TrustManagerFactory;
+
+import 
org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand.FirewallRule;
+import 
org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand.PortMapping;
+import 
org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand.Vip;
+import org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand;
+import org.apache.cloudstack.network.ones.agent.api.RemoveOnesEdgeCommand;
+import org.apache.http.HttpEntity;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpDelete;
+import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.client.methods.HttpPut;
+import org.apache.http.client.methods.HttpRequestBase;
+import org.apache.http.client.utils.URIBuilder;
+import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.util.EntityUtils;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+
+/**
+ * Client for the Aviz Gateway REST API (/api/v1): a ONES tenant's edge, i.e. 
its internet access
+ * (outbound translation and port forwards), load-balancer VIPs and firewall 
rules. The tenant
+ * itself reaches the gateway through ONES; this adds what CloudStack decides 
on top of it.
+ * Authenticates with a gateway API token (role operator); TLS is always 
verified.
+ *
+ * Only what this plugin made is ever changed or removed: VIPs named {@value 
#VIP_PREFIX}... and
+ * firewall rules named after the tenant plus {@value #FIREWALL_INFIX}..., so 
rules an operator
+ * adds by hand stay. A client holds a connection pool: close it after use.
+ */
+public class AvizGatewayClient implements Closeable {
+
+    private static final Logger LOG = 
LogManager.getLogger(AvizGatewayClient.class);
+
+    public static final String VIP_PREFIX = "cs-lb-";
+    public static final String FIREWALL_INFIX = "-fw-";
+    /** Outbound translation sessions one tenant may hold on the gateway. */
+    static final int SESSION_LIMIT = 10000;
+
+    private final String base;
+    private final String token;
+    private final CloseableHttpClient http;
+    long tenantWaitMs = 180_000;
+    long tenantPollMs = 5_000;
+
+    public AvizGatewayClient(final String url, final String token, final 
String caCertPath) {
+        this.base = (url.endsWith("/") ? url.substring(0, url.length() - 1) : 
url) + "/api/v1";
+        this.token = token;
+        try {
+            SSLContext ssl = SSLContext.getInstance("TLS");
+            TrustManagerFactory tmf = null;
+            if (caCertPath != null) {
+                KeyStore ks = KeyStore.getInstance("PKCS12");
+                ks.load(null, null);
+                try (InputStream in = new FileInputStream(caCertPath)) {
+                    int i = 0;
+                    for (java.security.cert.Certificate c : 
CertificateFactory.getInstance("X.509").generateCertificates(in)) {
+                        ks.setCertificateEntry("gw-" + i++, c);
+                    }
+                }
+                tmf = 
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
+                tmf.init(ks);
+            }
+            ssl.init(null, tmf != null ? tmf.getTrustManagers() : null, new 
SecureRandom());
+            this.http = HttpClients.custom()
+                    .setSSLSocketFactory(new SSLConnectionSocketFactory(ssl))
+                    
.setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(10000).setSocketTimeout(60000).build())
+                    .build();
+        } catch (Exception e) {
+            throw new CloudRuntimeException("Failed to set up the Aviz Gateway 
client: " + e.getMessage(), e);
+        }
+    }
+
+    /** Closes the client's connection pool. */
+    @Override
+    public void close() {
+        try {
+            http.close();
+        } catch (IOException e) {
+            LOG.debug("Closing the Aviz Gateway client at {}: {}", base, 
e.getMessage());
+        }
+    }
+
+    // ---------------------------------------------------------------- 
commands
+
+    /**
+     * Makes the tenant's edge on the gateway what the command says. Order 
keeps nothing open by
+     * accident: denies go first, then permits, then the mappings and VIPs, 
and stale rules last.
+     * Rules are named after what they do, so a PUT never turns an existing 
guard into something
+     * else, and a failure part way leaves every old rule in place.
+     */
+    public Answer configureEdge(final ConfigureOnesEdgeCommand cmd) {
+        String tenant = cmd.getTenantName();
+        try {
+            boolean healthChecks = hasLoopback(waitForTenant(tenant));
+            Set<String> wantedRules = new HashSet<>();
+            for (boolean permits : new boolean[]{false, true}) {
+                for (FirewallRule r : cmd.getFirewallRules()) {
+                    if (r.isPermit() == permits) {
+                        putFirewallRule(tenant, r);
+                        wantedRules.add(r.getName());
+                    }
+                }
+            }
+            if (cmd.getSourceNatAddress() != null) {
+                putInternetAccess(tenant, cmd.getSourceNatAddress(), 
cmd.getPortMappings());
+            } else {
+                if (!cmd.getPortMappings().isEmpty()) {
+                    throw new IOException("port forwards need the network's 
source NAT address, and it has none");
+                }
+                deleteInternetAccess(tenant);
+            }
+            if (!healthChecks && !cmd.getVips().isEmpty()) {
+                LOG.info("ONES tenant {} has no loopback on the Aviz Gateway, 
which its health probes need: its VIP members are not "
+                        + "health-checked until the tenant gets one", tenant);
+            }
+            syncVips(tenant, cmd.getVips(), healthChecks);
+            for (String name : firewallRuleNames(tenant)) {
+                if (!wantedRules.contains(name)) {
+                    deleteFirewallRule(name);
+                }
+            }
+            LOG.info("Aviz Gateway edge of ONES tenant {}: source NAT {}, {} 
port mapping(s), {} VIP(s), {} firewall rule(s)",
+                    tenant, cmd.getSourceNatAddress(), 
cmd.getPortMappings().size(), cmd.getVips().size(), 
cmd.getFirewallRules().size());
+            return new Answer(cmd, true, null);
+        } catch (InterruptedException e) {
+            Thread.currentThread().interrupt();
+            return new Answer(cmd, false, "interrupted while configuring the 
Aviz Gateway for ONES tenant " + tenant);
+        } catch (Exception e) {
+            LOG.warn("Could not configure the Aviz Gateway for ONES tenant {}: 
{}", tenant, e.getMessage());
+            return new Answer(cmd, false, "Aviz Gateway, ONES tenant " + 
tenant + ": " + e.getMessage());
+        }
+    }
+
+    /** Takes the tenant's edge away: mappings and VIPs first, then the rules 
that guarded them. */
+    public Answer removeEdge(final RemoveOnesEdgeCommand cmd) {
+        String tenant = cmd.getTenantName();
+        try {
+            deleteInternetAccess(tenant);
+            for (String name : vipNames(tenant)) {
+                deleteVip(tenant, name);
+            }
+            for (String name : firewallRuleNames(tenant)) {
+                deleteFirewallRule(name);
+            }
+            LOG.info("Aviz Gateway edge of ONES tenant {} removed", tenant);
+            return new Answer(cmd, true, null);
+        } catch (Exception e) {
+            LOG.warn("Could not remove the Aviz Gateway edge of ONES tenant 
{}: {}", tenant, e.getMessage());
+            return new Answer(cmd, false, "Aviz Gateway, ONES tenant " + 
tenant + ": " + e.getMessage());
+        }
+    }
+
+    // ---------------------------------------------------------------- tenant
+
+    /** ONES puts the tenant on the gateway (FM tenant webhook) once a server 
joined it: wait for that. */
+    JsonObject waitForTenant(final String tenant) throws IOException, 
InterruptedException {
+        long deadline = System.currentTimeMillis() + tenantWaitMs;
+        while (true) {
+            Reply r = call(new HttpGet(base + "/tenants/" + tenant));
+            if (r.status == 200) {
+                JsonElement root = parse(r.body);
+                return root != null && root.isJsonObject() ? 
root.getAsJsonObject() : new JsonObject();
+            }
+            if (r.status != 404) {
+                throw new IOException("GET tenant " + tenant + ": HTTP " + 
r.status + ": " + abbreviate(r.body));
+            }
+            if (System.currentTimeMillis() > deadline) {
+                throw new IOException("the gateway does not have the tenant 
after " + tenantWaitMs / 1000
+                        + " s (ONES puts it there once a server joined it)");
+            }
+            Thread.sleep(tenantPollMs);
+        }
+    }
+
+    /**
+     * The gateway health-checks VIP members from the tenant's loopback; an 
EVPN tenant without one
+     * (ONES does not always give it one) refuses health checks, so its VIPs 
go without.
+     */
+    static boolean hasLoopback(final JsonObject tenant) {
+        return tenant.has("loopback") && !tenant.get("loopback").isJsonNull() 
&& !tenant.get("loopback").getAsString().isEmpty();
+    }
+
+    // ---------------------------------------------------------------- 
internet access
+
+    void putInternetAccess(final String tenant, final String sourceNatAddress, 
final List<PortMapping> mappings) throws IOException {
+        JsonObject body = new JsonObject();
+        body.addProperty("enabled", true);
+        JsonArray pool = new JsonArray();
+        pool.add(sourceNatAddress);
+        body.add("pool", pool);
+        body.addProperty("session_limit", SESSION_LIMIT);
+        body.addProperty("announce_pool", true);
+        JsonArray elastic = new JsonArray();
+        for (PortMapping m : mappings) {
+            JsonObject e = new JsonObject();
+            e.addProperty("external", m.getExternal());
+            e.addProperty("local", m.getLocal());
+            e.addProperty("protocol", m.getProtocol());
+            e.addProperty("external_port", m.getExternalPort());
+            e.addProperty("local_port", m.getLocalPort());
+            e.addProperty("announce", true);
+            elastic.add(e);
+        }
+        body.add("elastic_ips", elastic);
+        expectOk(send(new HttpPut(base + "/tenants/" + tenant + 
"/internet-access"), body), "internet access");
+    }
+
+    void deleteInternetAccess(final String tenant) throws IOException {
+        Reply r = call(new HttpDelete(base + "/tenants/" + tenant + 
"/internet-access"));
+        if (r.status != 404) {
+            expectOk(r, "remove internet access");
+        }
+    }
+
+    // ---------------------------------------------------------------- VIPs
+
+    List<String> vipNames(final String tenant) throws IOException {
+        Reply r = call(new HttpGet(base + "/tenants/" + tenant + "/lb/vips"));
+        if (r.status == 404) {
+            return new ArrayList<>();
+        }
+        expectOk(r, "list VIPs");
+        return names(r.body, VIP_PREFIX);
+    }
+
+    void syncVips(final String tenant, final List<Vip> wanted, final boolean 
healthChecks) throws IOException {
+        Set<String> have = new HashSet<>(vipNames(tenant));
+        Set<String> keep = new HashSet<>();
+        for (Vip v : wanted) {
+            keep.add(v.getName());
+        }
+        for (String name : have) {
+            if (!keep.contains(name)) {
+                deleteVip(tenant, name);
+            }
+        }
+        for (Vip v : wanted) {
+            JsonObject body = new JsonObject();
+            body.addProperty("name", v.getName());
+            body.addProperty("address", v.getAddress());
+            body.addProperty("port", v.getPort());
+            body.addProperty("protocol", v.getProtocol());
+            body.addProperty("backend_port", v.getBackendPort());
+            JsonArray backends = new JsonArray();
+            for (String b : v.getBackends()) {
+                JsonObject o = new JsonObject();
+                o.addProperty("address", b);
+                backends.add(o);
+            }
+            body.add("backends", backends);
+            body.addProperty("src_ip_sticky", v.isSourceSticky());
+            if (!healthChecks) {
+                JsonObject none = new JsonObject();
+                none.addProperty("type", "none");
+                body.add("health", none);
+            }
+            body.addProperty("announce", true);
+            HttpEntityEnclosingRequestBase req = have.contains(v.getName())
+                    ? new HttpPut(base + "/tenants/" + tenant + "/lb/vips/" + 
v.getName())
+                    : new HttpPost(base + "/tenants/" + tenant + "/lb/vips");
+            expectOk(send(req, body), "VIP " + v);
+        }
+    }
+
+    void deleteVip(final String tenant, final String name) throws IOException {
+        Reply r = call(new HttpDelete(base + "/tenants/" + tenant + 
"/lb/vips/" + name));
+        if (r.status != 404) {
+            expectOk(r, "delete VIP " + name);
+        }
+    }
+
+    // ---------------------------------------------------------------- 
firewall
+
+    /** The plugin's rules of this tenant (rule names are global on the 
gateway, so they carry the tenant). */
+    List<String> firewallRuleNames(final String tenant) throws IOException {
+        URIBuilder uri;
+        try {
+            uri = new URIBuilder(base + 
"/firewall/rules").addParameter("tenant", tenant);
+            Reply r = call(new HttpGet(uri.build()));
+            expectOk(r, "list firewall rules");
+            return names(r.body, tenant + FIREWALL_INFIX);
+        } catch (java.net.URISyntaxException e) {
+            throw new IOException(e);
+        }
+    }
+
+    void putFirewallRule(final String tenant, final FirewallRule rule) throws 
IOException {
+        JsonObject body = new JsonObject();
+        body.addProperty("name", rule.getName());
+        body.addProperty("tenant", tenant);
+        body.addProperty("src", rule.getSource());
+        body.addProperty("dst", rule.getDestination());
+        body.addProperty("protocol", rule.getProtocol());
+        body.addProperty("dst_ports", String.valueOf(rule.getPort()));
+        body.addProperty("action", rule.isPermit() ? "permit" : "deny");
+        body.addProperty("established", rule.isPermit());     // stateful 
permits; the gateway refuses it on a deny
+        body.addProperty("comment", "CloudStack");
+        expectOk(send(new HttpPut(base + "/firewall/rules/" + rule.getName()), 
body), "firewall rule " + rule);
+    }
+
+    void deleteFirewallRule(final String name) throws IOException {
+        Reply r = call(new HttpDelete(base + "/firewall/rules/" + name));
+        if (r.status != 404) {
+            expectOk(r, "delete firewall rule " + name);
+        }
+    }
+
+    // ---------------------------------------------------------------- HTTP
+
+    static final class Reply {
+        final int status;
+        final String body;
+
+        Reply(final int status, final String body) {
+            this.status = status;
+            this.body = body;
+        }
+    }
+
+    private Reply send(final HttpEntityEnclosingRequestBase req, final 
JsonObject body) throws IOException {
+        req.setEntity(new StringEntity(body.toString(), "UTF-8"));
+        return call(req);
+    }
+
+    private Reply call(final HttpRequestBase req) throws IOException {
+        req.setHeader("Authorization", "Bearer " + token);
+        req.setHeader("Content-Type", "application/json");
+        req.setHeader("Accept", "application/json");
+        try (CloseableHttpResponse r = http.execute(req)) {
+            HttpEntity e = r.getEntity();
+            return new Reply(r.getStatusLine().getStatusCode(), e != null ? 
EntityUtils.toString(e) : "");
+        }
+    }
+
+    /**
+     * 2xx, and a change the gateway could apply: a write answers with its 
apply report, and
+     * "failed" > 0 there means the gateway stored the intent but could not 
program it.
+     */
+    private static void expectOk(final Reply r, final String what) throws 
IOException {
+        if (r.status < 200 || r.status > 299) {
+            throw new IOException(what + ": HTTP " + r.status + ": " + 
abbreviate(r.body));
+        }
+        JsonElement root = parse(r.body);
+        if (root != null && root.isJsonObject() && 
root.getAsJsonObject().has("failed")
+                && root.getAsJsonObject().get("failed").isJsonPrimitive() && 
root.getAsJsonObject().get("failed").getAsInt() > 0) {
+            throw new IOException(what + ": the gateway could not apply it: " 
+ abbreviate(r.body));
+        }

Review Comment:
   An apply report with `failed=0`, `blocked=1`, and `converged=false` passes 
this check, so configuration or teardown can be reported successful before the 
gateway applies the change. This also lets configuration proceed to mappings 
and removal of old firewall rules while required gateway work remains 
incomplete. Treat blocked or explicitly nonconverged reports as failures, or 
wait for convergence before proceeding.



##########
plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/client/OnesApiClientImpl.java:
##########
@@ -0,0 +1,603 @@
+//
+// 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();
+        boolean created = false;
+        try {
+            JsonObject tenant = getTenant(cmd.getFabricName(), 
cmd.getTenantName());
+            if (tenant == null) {
+                created = true;     // from here on a failure may leave the 
tenant behind
+                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());
+            String details = e.getMessage();
+            if (created) {
+                // the caller gets no tenant to clean up, so this call does it
+                Answer undone = deleteTenant(new 
DeleteOnesTenantCommand(cmd.getFabricName(), cmd.getTenantName()));
+                if (!undone.getResult()) {
+                    details += "; deleting the tenant again failed too, delete 
" + cmd.getTenantName() + " in ONES: " + undone.getDetails();
+                }
+            }
+            return new CreateOnesTenantAnswer(cmd, new 
CloudRuntimeException(details, e));
+        }
+    }
+
+    /** GET /fabrics/{f}/tenants/{t}: the tenant record, or null if there is 
none. */
+    JsonObject getTenant(final String fabric, final String tenant) throws 
IOException {
+        Reply r = call(new HttpGet(fmUrl + "/fabrics/" + fabric + "/tenants/" 
+ tenant), false);
+        if (r.status == 404) {
+            return null;
+        }
+        if (!r.ok()) {
+            throw new IOException("get ONES tenant " + tenant + ": HTTP " + 
r.status + ": " + abbreviate(r.body));
+        }
+        JsonElement root = parse(r.body);
+        JsonObject t = asObject(root, "tenant");
+        if (t == null) {
+            JsonObject data = asObject(root, "data");
+            t = data != null ? asObject(data, "tenant") : null;
+        }
+        return t;
+    }
+
+    @Override
+    public Answer deleteTenant(final DeleteOnesTenantCommand cmd) {
+        String what = "delete ONES tenant " + cmd.getTenantName() + " on 
fabric " + cmd.getFabricName();
+        try {
+            Reply r = call(new HttpDelete(fmUrl + "/fabrics/" + 
cmd.getFabricName() + "/tenants/" + cmd.getTenantName()), true);
+            if (r.status == 404) {
+                return new Answer(cmd, true, "already gone");
+            }
+            if (!r.ok()) {
+                throw new IOException(what + ": HTTP " + r.status + ": " + 
abbreviate(r.body));
+            }
+            awaitOperation(r, what);
+            return new Answer(cmd, true, r.body);
+        } catch (Exception e) {
+            LOG.error("Failed to {}: {}", what, e.getMessage());
+            return new Answer(cmd, e);
+        }
+    }
+
+    @Override
+    public Answer allocateServers(final AllocateOnesServersCommand cmd) {
+        Answer added = patchServers(cmd, cmd.getFabricName(), 
cmd.getTenantName(), "ADD", cmd.getServerNames(), cmd.isShared());
+        if (!added.getResult()) {
+            return added;
+        }
+        // Behind a DPU (HBN fabric) the tenant ends at the DPU: the server 
joining the tenant puts
+        // the tenant's VRF/VLAN/SVI on its DPU, and one host-facing DPU port 
(a "VF") carries the
+        // tenant to the hypervisor, untagged. A hypervisor holds several 
tenants, so each tenant
+        // gets its own VF on every server it uses.
+        String what = "DPU VF for ONES tenant " + cmd.getTenantName() + " on " 
+ cmd.getServerNames();
+        try {
+            for (String server : cmd.getServerNames()) {
+                assignDpuVf(cmd.getFabricName(), server, cmd.getTenantName());
+            }
+            return added;

Review Comment:
   On a DPU host, the assigned virtual function (VF) carries the tenant 
untagged, but its `serverIf` is only logged and never passed to KVM. The guru 
still supplies `vlan://<tenant VLAN>`, so `BridgeVifDriver` connects the NIC 
through the normal tagged guest bridge rather than the chosen VF, leaving the 
VM disconnected unless the host is separately wired. Return the per-host VF 
mapping and configure the corresponding host-side bridge, or reject DPU hosts 
until that wiring is supported.



##########
plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/service/OnesGuestNetworkGuru.java:
##########
@@ -0,0 +1,392 @@
+//
+// 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.HashSet;
+import java.util.IdentityHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+
+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.exception.InvalidParameterValueException;
+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.Nic.ReservationStrategy;
+import com.cloud.vm.NicProfile;
+import com.cloud.vm.ReservationContext;
+import com.cloud.vm.VirtualMachine;
+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;
+
+    /** A tenant made in design(), waiting for setup() to know the network's 
id. */
+    static final class PendingTenant {
+        final String name;
+        final CreateOnesTenantAnswer answer;
+
+        PendingTenant(final String name, final CreateOnesTenantAnswer answer) {
+            this.name = name;
+            this.answer = answer;
+        }
+    }
+
+    /**
+     * Keyed by the very Network object design() returns: 
NetworkOrchestrator.setupNetwork() hands
+     * that same object to setup(). Nothing else identifies the network yet 
(it has no id, and two
+     * fabrics can give two new networks the same CIDR).
+     */
+    private static final Map<Network, PendingTenant> PENDING = 
Collections.synchronizedMap(new IdentityHashMap<>());
+
+    @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);

Review Comment:
   The compute-pool restriction only applies in `inPool()`, but secondary-IP 
allocation and `updateVmNicIp` call `IpAddressManager.allocateGuestIP()` 
directly. That allocator uses `network.getCidr()`, so with subnet 
`192.1.0.0/16` and pool `192.1.64.0/18`, a request for `192.1.128.10` is 
accepted even though it belongs to the fabric, not the compute pool. Use the 
pool as CloudStack's allocation CIDR and retain the full tenant subnet in 
`networkCidr`, which `getValidNetworkCidr()` already uses for the NIC netmask.



##########
plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/client/OnesApiClientImpl.java:
##########
@@ -0,0 +1,603 @@
+//
+// 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();
+        boolean created = false;
+        try {
+            JsonObject tenant = getTenant(cmd.getFabricName(), 
cmd.getTenantName());
+            if (tenant == null) {
+                created = true;     // from here on a failure may leave the 
tenant behind
+                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());
+            String details = e.getMessage();
+            if (created) {
+                // the caller gets no tenant to clean up, so this call does it
+                Answer undone = deleteTenant(new 
DeleteOnesTenantCommand(cmd.getFabricName(), cmd.getTenantName()));
+                if (!undone.getResult()) {
+                    details += "; deleting the tenant again failed too, delete 
" + cmd.getTenantName() + " in ONES: " + undone.getDetails();
+                }
+            }
+            return new CreateOnesTenantAnswer(cmd, new 
CloudRuntimeException(details, e));
+        }
+    }
+
+    /** GET /fabrics/{f}/tenants/{t}: the tenant record, or null if there is 
none. */
+    JsonObject getTenant(final String fabric, final String tenant) throws 
IOException {
+        Reply r = call(new HttpGet(fmUrl + "/fabrics/" + fabric + "/tenants/" 
+ tenant), false);
+        if (r.status == 404) {
+            return null;
+        }
+        if (!r.ok()) {
+            throw new IOException("get ONES tenant " + tenant + ": HTTP " + 
r.status + ": " + abbreviate(r.body));
+        }
+        JsonElement root = parse(r.body);
+        JsonObject t = asObject(root, "tenant");
+        if (t == null) {
+            JsonObject data = asObject(root, "data");
+            t = data != null ? asObject(data, "tenant") : null;
+        }
+        return t;
+    }
+
+    @Override
+    public Answer deleteTenant(final DeleteOnesTenantCommand cmd) {
+        String what = "delete ONES tenant " + cmd.getTenantName() + " on 
fabric " + cmd.getFabricName();
+        try {
+            Reply r = call(new HttpDelete(fmUrl + "/fabrics/" + 
cmd.getFabricName() + "/tenants/" + cmd.getTenantName()), true);
+            if (r.status == 404) {
+                return new Answer(cmd, true, "already gone");
+            }
+            if (!r.ok()) {
+                throw new IOException(what + ": HTTP " + r.status + ": " + 
abbreviate(r.body));
+            }
+            awaitOperation(r, what);
+            return new Answer(cmd, true, r.body);
+        } catch (Exception e) {
+            LOG.error("Failed to {}: {}", what, e.getMessage());
+            return new Answer(cmd, e);
+        }
+    }
+
+    @Override
+    public Answer allocateServers(final AllocateOnesServersCommand cmd) {
+        Answer added = patchServers(cmd, cmd.getFabricName(), 
cmd.getTenantName(), "ADD", cmd.getServerNames(), cmd.isShared());
+        if (!added.getResult()) {
+            return added;

Review Comment:
   If ONES accepts the asynchronous ADD but polling fails or times out, this 
branch returns failure without recording or removing the host. ONES can still 
complete the ADD, leaving membership that CloudStack's shutdown cannot find. 
Track accepted operations and reconcile or undo newly added membership, 
retaining cleanup information when recovery cannot finish.



##########
plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/service/OnesGuestNetworkGuru.java:
##########
@@ -0,0 +1,392 @@
+//
+// 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.HashSet;
+import java.util.IdentityHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+
+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.exception.InvalidParameterValueException;
+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.Nic.ReservationStrategy;
+import com.cloud.vm.NicProfile;
+import com.cloud.vm.ReservationContext;
+import com.cloud.vm.VirtualMachine;
+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;
+
+    /** A tenant made in design(), waiting for setup() to know the network's 
id. */
+    static final class PendingTenant {
+        final String name;
+        final CreateOnesTenantAnswer answer;
+
+        PendingTenant(final String name, final CreateOnesTenantAnswer answer) {
+            this.name = name;
+            this.answer = answer;
+        }
+    }
+
+    /**
+     * Keyed by the very Network object design() returns: 
NetworkOrchestrator.setupNetwork() hands
+     * that same object to setup(). Nothing else identifies the network yet 
(it has no id, and two
+     * fabrics can give two new networks the same CIDR).
+     */
+    private static final Map<Network, PendingTenant> PENDING = 
Collections.synchronizedMap(new IdentityHashMap<>());
+
+    @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(network, new PendingTenant(tenantName, t));
+        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);
+        PendingTenant pending = PENDING.remove(network);
+        if (pending == null) {
+            return;
+        }
+        String tenantName = pending.name;
+        CreateOnesTenantAnswer t = pending.answer;
+        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 (ONES
+     * keeps that for the fabric). An instance may ask for a pool address; the 
virtual router's
+     * address is left to the superclass (the gateway, or the one it held 
before).
+     */
+    @Override
+    public NicProfile allocate(final Network network, final NicProfile nic, 
final VirtualMachineProfile vm)
+            throws InsufficientVirtualNetworkCapacityException, 
InsufficientAddressCapacityException {
+        return super.allocate(network, inPool(network, nic, vm), vm);
+    }
+
+    /** The NIC to allocate, with a pool address requested for it unless it 
asks for one itself. */
+    NicProfile inPool(final Network network, final NicProfile requested, final 
VirtualMachineProfile vm) throws InsufficientAddressCapacityException {
+        String pool = detail(network.getId(), DETAIL_POOL);
+        if (pool == null) {
+            throw new CloudRuntimeException("No ONES compute IP pool is on 
record for network " + network.getUuid());
+        }
+        NicProfile nic = requested != null ? requested : new 
NicProfile(ReservationStrategy.Start, null, null, null, null);
+        if (nic.getIPv4Address() == null) {
+            String ip = nic.getRequestedIPv4();
+            if (ip == null) {
+                nic.setRequestedIPv4(freeAddress(network, pool));
+            } else if (vm.getType() != VirtualMachine.Type.DomainRouter && 
!NetUtils.isIpWithInCidrRange(ip, pool)) {
+                throw new InvalidParameterValueException("Address " + ip + " 
is outside the ONES compute IP pool " + pool + " of network "
+                        + network.getName() + "; instances take addresses from 
that pool only");
+            }
+        }
+        return nic;
+    }
+
+    /**
+     * 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<>(_networkModel.getUsedIpsInNetwork(network));
+        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.
+     * @return false when hosts stay recorded (ONES refused, or a DPU VF could 
not be released)
+     */
+    private boolean removeHosts(final long networkId, final OnesProviderVO 
device, final String tenantName) {
+        List<String> hosts = allocatedHosts(networkId);
+        if (hosts.isEmpty()) {
+            return true;
+        }
+        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 false;
+        }
+        networkDetailsDao.removeDetail(networkId, 
OnesElement.DETAIL_ALLOCATED_HOSTS);
+        return true;
+    }
+
+    @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);

Review Comment:
   If deallocation releases a host's DPU VF and then fails, this ignored 
`false` still lets CloudStack complete shutdown while retaining the old host 
list. A later `prepare()` skips that recorded host, so the VF is not restored 
and its VMs lose connectivity. Propagate the failure before `super.shutdown()` 
so cleanup remains retryable.



##########
plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/service/OnesEdgeBuilder.java:
##########
@@ -0,0 +1,337 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package org.apache.cloudstack.network.ones.service;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+
+import 
org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand.FirewallRule;
+import 
org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand.PortMapping;
+import 
org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand.Vip;
+import org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand;
+import org.apache.cloudstack.network.ones.client.AvizGatewayClient;
+import org.apache.commons.codec.digest.DigestUtils;
+
+import com.cloud.network.IpAddress;
+import com.cloud.network.Network;
+import com.cloud.network.NetworkModel;
+import com.cloud.network.dao.FirewallRulesCidrsDao;
+import com.cloud.network.dao.FirewallRulesDao;
+import com.cloud.network.dao.IPAddressDao;
+import com.cloud.network.dao.IPAddressVO;
+import com.cloud.network.dao.LBStickinessPolicyDao;
+import com.cloud.network.dao.LBStickinessPolicyVO;
+import com.cloud.network.dao.LoadBalancerDao;
+import com.cloud.network.dao.LoadBalancerVMMapDao;
+import com.cloud.network.dao.LoadBalancerVMMapVO;
+import com.cloud.network.dao.LoadBalancerVO;
+import com.cloud.network.rules.FirewallRule.Purpose;
+import com.cloud.network.rules.FirewallRule.State;
+import com.cloud.network.rules.FirewallRule.TrafficType;
+import com.cloud.network.rules.FirewallRuleVO;
+import com.cloud.network.rules.LbStickinessMethod.StickinessMethodType;
+import com.cloud.network.rules.LoadBalancerContainer.Scheme;
+import com.cloud.network.rules.PortForwardingRuleVO;
+import com.cloud.network.rules.dao.PortForwardingRulesDao;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.vm.Nic;
+
+/**
+ * What a ONES network's edge on the Aviz Gateway should be, read from 
CloudStack's own records:
+ * the network's source NAT address, its live port forwards and public 
load-balancer rules, and
+ * the ingress firewall rules on their public addresses.
+ *
+ * Firewall: the gateway filters inbound traffic after translation, so every 
mapped local
+ * address:port gets a deny for any source, and a permit for each source CIDR 
an ingress rule
+ * allows on the public address:port that leads there. The permit's narrower 
source puts it ahead
+ * of the deny; a port open to any source gets just the permit. A mapping no 
ingress rule covers
+ * stays closed, as on any CloudStack network.
+ */
+public class OnesEdgeBuilder {
+
+    /** Port forwards are mapped port by port on the gateway: more than this 
in one rule is refused. */
+    static final int MAX_PORTS_PER_FORWARD = 256;
+    static final String ANY = "0.0.0.0/0";
+    /** Gateway rule names: [a-z0-9-], at most 40 characters; tenant (12) + 
"-fw-" + this many hex digits. */
+    static final int RULE_HASH_HEX = 16;
+
+    private final IPAddressDao ipAddressDao;
+    private final PortForwardingRulesDao portForwardingRulesDao;
+    private final LoadBalancerDao loadBalancerDao;
+    private final LoadBalancerVMMapDao lbVmMapDao;
+    private final LBStickinessPolicyDao lbStickinessPolicyDao;
+    private final FirewallRulesDao firewallRulesDao;
+    private final FirewallRulesCidrsDao firewallRulesCidrsDao;
+    private final NetworkModel networkModel;
+
+    public OnesEdgeBuilder(final IPAddressDao ipAddressDao, final 
PortForwardingRulesDao portForwardingRulesDao, final LoadBalancerDao 
loadBalancerDao,
+            final LoadBalancerVMMapDao lbVmMapDao, final LBStickinessPolicyDao 
lbStickinessPolicyDao, final FirewallRulesDao firewallRulesDao,
+            final FirewallRulesCidrsDao firewallRulesCidrsDao, final 
NetworkModel networkModel) {
+        this.ipAddressDao = ipAddressDao;
+        this.portForwardingRulesDao = portForwardingRulesDao;
+        this.loadBalancerDao = loadBalancerDao;
+        this.lbVmMapDao = lbVmMapDao;
+        this.lbStickinessPolicyDao = lbStickinessPolicyDao;
+        this.firewallRulesDao = firewallRulesDao;
+        this.firewallRulesCidrsDao = firewallRulesCidrsDao;
+        this.networkModel = networkModel;
+    }
+
+    static boolean live(final State state) {
+        return state == State.Add || state == State.Active;
+    }
+
+    static String protocolOf(final String p) {
+        return p != null && "udp".equalsIgnoreCase(p) ? "udp" : "tcp";
+    }
+
+    /** The address the network's outbound traffic is translated onto; null 
when it has none. */
+    String sourceNatAddress(final long networkId) {
+        for (IPAddressVO ip : ipAddressDao.listByAssociatedNetwork(networkId, 
true)) {
+            if (ip.getState() == IpAddress.State.Allocated || ip.getState() == 
IpAddress.State.Allocating) {
+                return ip.getAddress().addr();
+            }
+        }
+        return null;
+    }
+
+    private String addressOf(final long ipId) {
+        IPAddressVO ip = ipAddressDao.findById(ipId);
+        if (ip == null) {
+            throw new CloudRuntimeException("public IP " + ipId + " is gone");
+        }
+        return ip.getAddress().addr();
+    }
+
+    List<PortMapping> portMappings(final long networkId, final boolean 
withPortForwarding) {
+        List<PortMapping> out = new ArrayList<>();
+        if (!withPortForwarding) {
+            return out;
+        }
+        for (PortForwardingRuleVO r : 
portForwardingRulesDao.listByNetwork(networkId)) {
+            if (!live(r.getState())) {
+                continue;
+            }
+            int ports = r.getSourcePortEnd() - r.getSourcePortStart() + 1;
+            if (ports > MAX_PORTS_PER_FORWARD) {
+                throw new CloudRuntimeException("Port forward " + r.getUuid() 
+ " covers " + ports + " ports; the Aviz Gateway maps at most "
+                        + MAX_PORTS_PER_FORWARD + " per rule");
+            }
+            String external = addressOf(r.getSourceIpAddressId());
+            for (int i = 0; i < ports; i++) {
+                out.add(new PortMapping(external, 
r.getDestinationIpAddress().addr(), protocolOf(r.getProtocol()),
+                        r.getSourcePortStart() + i, 
r.getDestinationPortStart() + i));
+            }
+        }
+        return out;
+    }
+
+    private String memberAddress(final LoadBalancerVMMapVO m, final long 
networkId) {
+        if (m.getInstanceIp() != null) {
+            return m.getInstanceIp();
+        }
+        Nic nic = networkModel.getNicInNetwork(m.getInstanceId(), networkId);
+        return nic != null ? nic.getIPv4Address() : null;
+    }
+
+    List<Vip> vips(final long networkId, final boolean withLb) {
+        List<Vip> out = new ArrayList<>();
+        if (!withLb) {
+            return out;
+        }
+        for (LoadBalancerVO lb : 
loadBalancerDao.listByNetworkIdAndScheme(networkId, Scheme.Public)) {
+            if (!live(lb.getState())) {
+                continue;
+            }
+            List<String> backends = new ArrayList<>();
+            for (LoadBalancerVMMapVO m : 
lbVmMapDao.listByLoadBalancerId(lb.getId(), false)) {
+                String member = memberAddress(m, networkId);
+                if (member != null && !backends.contains(member)) {
+                    backends.add(member);
+                }
+            }
+            boolean sticky = false;
+            for (LBStickinessPolicyVO p : 
lbStickinessPolicyDao.listByLoadBalancerId(lb.getId(), false)) {
+                sticky |= 
StickinessMethodType.SourceBased.getName().equalsIgnoreCase(p.getMethodName());
+            }
+            out.add(new Vip(AvizGatewayClient.VIP_PREFIX + lb.getId(), 
addressOf(lb.getSourceIpAddressId()), lb.getSourcePortStart(),
+                    protocolOf(lb.getLbProtocol()), lb.getDefaultPortStart(), 
backends, sticky));
+        }
+        return out;
+    }
+
+    /** One place a public address:port leads to inside the tenant. */
+    private static final class Target {
+        final String publicAddress;
+        final String protocol;
+        final int publicPort;
+        final String local;
+        final int localPort;
+
+        Target(final String publicAddress, final String protocol, final int 
publicPort, final String local, final int localPort) {
+            this.publicAddress = publicAddress;
+            this.protocol = protocol;
+            this.publicPort = publicPort;
+            this.local = local;
+            this.localPort = localPort;
+        }
+    }
+
+    private static boolean covers(final FirewallRuleVO rule, final String 
ruleAddress, final Target t) {
+        if (!ruleAddress.equals(t.publicAddress)) {
+            return false;
+        }
+        String p = rule.getProtocol() == null ? "all" : 
rule.getProtocol().toLowerCase(Locale.ROOT);
+        if (!"all".equals(p) && !p.equals(t.protocol)) {
+            return false;
+        }
+        if (rule.getSourcePortStart() == null) {
+            return true;
+        }
+        int end = rule.getSourcePortEnd() != null ? rule.getSourcePortEnd() : 
rule.getSourcePortStart();
+        return t.publicPort >= rule.getSourcePortStart() && t.publicPort <= 
end;
+    }
+
+    List<FirewallRule> firewallRules(final long networkId, final String 
tenant, final List<PortMapping> mappings, final List<Vip> vips) {
+        List<Target> targets = new ArrayList<>();
+        for (PortMapping m : mappings) {
+            targets.add(new Target(m.getExternal(), m.getProtocol(), 
m.getExternalPort(), m.getLocal(), m.getLocalPort()));
+        }
+        for (Vip v : vips) {
+            for (String b : v.getBackends()) {
+                targets.add(new Target(v.getAddress(), v.getProtocol(), 
v.getPort(), b, v.getBackendPort()));
+            }
+        }
+        List<FirewallRuleVO> ingress = new ArrayList<>();
+        Map<Long, String> ruleAddress = new LinkedHashMap<>();
+        Map<Long, List<String>> ruleSources = new LinkedHashMap<>();
+        for (FirewallRuleVO r : 
firewallRulesDao.listByNetworkPurposeTrafficType(networkId, Purpose.Firewall, 
TrafficType.Ingress)) {
+            if (!live(r.getState()) || r.getSourceIpAddressId() == null) {
+                continue;
+            }
+            ingress.add(r);
+            ruleAddress.put(r.getId(), addressOf(r.getSourceIpAddressId()));
+            List<String> cidrs = 
firewallRulesCidrsDao.getSourceCidrs(r.getId());
+            ruleSources.put(r.getId(), cidrs == null || cidrs.isEmpty() ? 
List.of(ANY) : cidrs);
+        }
+
+        // What each mapped local address:port admits, from every public 
endpoint that leads there.
+        // The gateway filters after translation, where those endpoints are 
indistinguishable: two
+        // that lead to one local port must admit the same sources, or each 
would admit the other's.
+        Map<String, Set<String>> admitted = new LinkedHashMap<>();
+        Map<String, String> admittedBy = new LinkedHashMap<>();
+        Map<String, Target> local = new LinkedHashMap<>();
+        for (Target t : targets) {
+            Set<String> sources = new TreeSet<>();
+            for (FirewallRuleVO r : ingress) {
+                if (covers(r, ruleAddress.get(r.getId()), t)) {
+                    sources.addAll(ruleSources.get(r.getId()));
+                }
+            }
+            String key = t.local + ":" + t.localPort + "/" + t.protocol;
+            String endpoint = t.publicAddress + ":" + t.publicPort;
+            Set<String> other = admitted.putIfAbsent(key, sources);
+            if (other != null && !other.equals(sources)) {
+                throw new CloudRuntimeException(key + " is reached from " + 
admittedBy.get(key) + " (allowed sources " + describe(other)
+                        + ") and from " + endpoint + " (allowed sources " + 
describe(sources) + "); on the Aviz Gateway the firewall sees "
+                        + "only the VM port, so both must allow the same 
sources");
+            }
+            admittedBy.putIfAbsent(key, endpoint);
+            local.putIfAbsent(key, t);
+        }
+
+        // A deny for any source closes the port; a permit per allowed CIDR 
opens it, ahead of the
+        // deny because its source is longer. A port open to any source needs 
no deny: a permit and
+        // a deny for 0.0.0.0/0 would tie, and the gateway would order them by 
name.
+        List<FirewallRule> out = new ArrayList<>();
+        for (Map.Entry<String, Set<String>> e : admitted.entrySet()) {
+            Target t = local.get(e.getKey());
+            String dst = t.local + "/32";
+            if (!e.getValue().contains(ANY)) {
+                out.add(rule(tenant, ANY, dst, t.protocol, t.localPort, 
false));
+            }
+            for (String cidr : e.getValue()) {
+                out.add(rule(tenant, cidr, dst, t.protocol, t.localPort, 
true));
+            }
+        }
+        return out;
+    }
+
+    private static String describe(final Set<String> sources) {
+        return sources.isEmpty() ? "none" : String.join(",", sources);
+    }
+
+    /**
+     * A gateway rule named after what it does (tenant, then a hash of action, 
source, destination,
+     * protocol and port). An update never turns an existing rule into a 
different one: new rules are
+     * added under new names and old ones deleted once nothing needs them.
+     */
+    static FirewallRule rule(final String tenant, final String src, final 
String dst, final String protocol, final int port, final boolean permit) {
+        String what = (permit ? "permit" : "deny") + "|" + src + "|" + dst + 
"|" + protocol + "|" + port;
+        String hash = DigestUtils.sha256Hex(what).substring(0, RULE_HASH_HEX);
+        return new FirewallRule(tenant + AvizGatewayClient.FIREWALL_INFIX + 
hash, src, dst, protocol, port, permit);
+    }
+
+    /**
+     * The gateway's load balancer maps replies back by backend address, port 
and protocol alone,
+     * so one VM address:port can serve one VIP, and nothing else: a port 
forward or a second VIP
+     * to it would have its replies taken for the first VIP's.
+     */
+    static void checkBackendPorts(final List<PortMapping> mappings, final 
List<Vip> vips) {
+        Map<String, String> owner = new LinkedHashMap<>();
+        for (Vip v : vips) {
+            for (String b : v.getBackends()) {
+                String key = b + ":" + v.getBackendPort() + "/" + 
v.getProtocol();
+                String other = owner.putIfAbsent(key, "load balancer " + 
v.getAddress() + ":" + v.getPort());
+                if (other != null) {
+                    throw new CloudRuntimeException(key + " is behind " + 
other + " and load balancer " + v.getAddress() + ":" + v.getPort()
+                            + "; on the Aviz Gateway a VM port serves one load 
balancer: give the second its own private port");
+                }
+            }
+        }
+        for (PortMapping m : mappings) {
+            String key = m.getLocal() + ":" + m.getLocalPort() + "/" + 
m.getProtocol();
+            if (owner.containsKey(key)) {
+                throw new CloudRuntimeException(key + " is behind " + 
owner.get(key) + " and port forward " + m.getExternal() + ":"
+                        + m.getExternalPort() + "; on the Aviz Gateway a VM 
port behind a load balancer cannot also be port forwarded");
+            }
+        }
+    }
+
+    /**
+     * @param withFirewall whether the network has Firewall by this provider; 
without it nothing is
+     *                     filtered (mapped ports are open), as on any network 
without a firewall
+     */
+    public ConfigureOnesEdgeCommand build(final Network network, final String 
tenant, final boolean withSourceNat,
+            final boolean withPortForwarding, final boolean withLb, final 
boolean withFirewall) {
+        long id = network.getId();
+        String sourceNat = withSourceNat ? sourceNatAddress(id) : null;
+        List<PortMapping> mappings = portMappings(id, withPortForwarding);

Review Comment:
   Before any host joins, `edgeSync()` treats a successful build as successful 
rule application. A port forward without AvizOnes SourceNat therefore becomes 
Active, even though `AvizGatewayClient` later rejects it and first-host 
preparation only logs the failure. Reject nonempty port mappings with a null 
source NAT address here, before returning the command.



-- 
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