Ashok-Aviz commented on code in PR #14902: URL: https://github.com/apache/cloudstack/pull/14902#discussion_r4734820712
########## plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/client/AvizGatewayClient.java: ########## @@ -0,0 +1,409 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.ones.client; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.security.KeyStore; +import java.security.SecureRandom; +import java.security.cert.CertificateFactory; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManagerFactory; + +import org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand.FirewallRule; +import org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand.PortMapping; +import org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand.Vip; +import org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand; +import org.apache.cloudstack.network.ones.agent.api.RemoveOnesEdgeCommand; +import org.apache.http.HttpEntity; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.client.methods.HttpRequestBase; +import org.apache.http.client.utils.URIBuilder; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import com.cloud.agent.api.Answer; +import com.cloud.utils.exception.CloudRuntimeException; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +/** + * Client for the Aviz Gateway REST API (/api/v1): a ONES tenant's edge, i.e. its internet access + * (outbound translation and port forwards), load-balancer VIPs and firewall rules. The tenant + * itself reaches the gateway through ONES; this adds what CloudStack decides on top of it. + * Authenticates with a gateway API token (role operator); TLS is always verified. + * + * Only what this plugin made is ever changed or removed: VIPs named {@value #VIP_PREFIX}... and + * firewall rules named after the tenant plus {@value #FIREWALL_INFIX}..., so rules an operator + * adds by hand stay. + */ +public class AvizGatewayClient { + + private static final Logger LOG = LogManager.getLogger(AvizGatewayClient.class); + + public static final String VIP_PREFIX = "cs-lb-"; + public static final String FIREWALL_INFIX = "-fw-"; + /** Outbound translation sessions one tenant may hold on the gateway. */ + static final int SESSION_LIMIT = 10000; + + private final String base; + private final String token; + private final CloseableHttpClient http; + long tenantWaitMs = 180_000; + long tenantPollMs = 5_000; + + public AvizGatewayClient(final String url, final String token, final String caCertPath) { + this.base = (url.endsWith("/") ? url.substring(0, url.length() - 1) : url) + "/api/v1"; + this.token = token; + try { + SSLContext ssl = SSLContext.getInstance("TLS"); + TrustManagerFactory tmf = null; + if (caCertPath != null) { + KeyStore ks = KeyStore.getInstance("PKCS12"); + ks.load(null, null); + try (InputStream in = new FileInputStream(caCertPath)) { + int i = 0; + for (java.security.cert.Certificate c : CertificateFactory.getInstance("X.509").generateCertificates(in)) { + ks.setCertificateEntry("gw-" + i++, c); + } + } + tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + tmf.init(ks); + } + ssl.init(null, tmf != null ? tmf.getTrustManagers() : null, new SecureRandom()); + this.http = HttpClients.custom() + .setSSLSocketFactory(new SSLConnectionSocketFactory(ssl)) + .setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(10000).setSocketTimeout(60000).build()) + .build(); + } catch (Exception e) { + throw new CloudRuntimeException("Failed to set up the Aviz Gateway client: " + e.getMessage(), e); + } + } + + // ---------------------------------------------------------------- commands + + /** + * Makes the tenant's edge on the gateway what the command says. Order keeps nothing open by + * accident: the firewall rules go first, then the mappings and VIPs, and stale rules last. + */ + public Answer configureEdge(final ConfigureOnesEdgeCommand cmd) { + String tenant = cmd.getTenantName(); + try { + boolean healthChecks = hasLoopback(waitForTenant(tenant)); + Set<String> wantedRules = new HashSet<>(); + for (FirewallRule r : cmd.getFirewallRules()) { + putFirewallRule(tenant, r); + wantedRules.add(r.getName()); Review Comment: Fixed in 4a1aef6687. Gateway rules are now named after what they do (tenant + `-fw-` + a hash of action, source, destination, protocol and port), so a PUT never turns an existing guard into a different rule. `configureEdge` puts denies first, then permits, then the internet access and VIPs, and removes stale rules last, so an update that fails part way leaves every old guard in place. A port open to any source now gets only a permit, because a permit and a deny both for 0.0.0.0/0 would tie in the gateway's sort and be ordered by name. Tests: `AvizGatewayClientTest.deniesGoOnBeforePermits`, `anUpdateThatStopsPartWayKeepsTheOldGuards`, `OnesEdgeBuilderTest.ruleNamesSayWhatTheRuleDoesNotWhereItIs`; also verified live on the gateway. ########## plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/client/OnesApiClientImpl.java: ########## @@ -0,0 +1,585 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.network.ones.client; + +import java.io.FileInputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.SecureRandom; +import java.security.Security; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.List; + +import javax.net.ssl.KeyManager; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; + +import org.apache.cloudstack.network.ones.agent.api.AllocateOnesServersCommand; +import org.apache.cloudstack.network.ones.agent.api.CreateOnesTenantAnswer; +import org.apache.cloudstack.network.ones.agent.api.CreateOnesTenantCommand; +import org.apache.cloudstack.network.ones.agent.api.DeallocateOnesServersCommand; +import org.apache.cloudstack.network.ones.agent.api.DeleteOnesTenantCommand; +import org.apache.http.HttpEntity; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPatch; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpRequestBase; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.openssl.PEMKeyPair; +import org.bouncycastle.openssl.PEMParser; +import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; + +import com.cloud.agent.api.Answer; +import com.cloud.agent.api.Command; +import com.cloud.utils.exception.CloudRuntimeException; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +/** + * Client for the ONES Fabric Manager (FM) tenant API. + * + * Auth: logs in with a user name and password at the ONES UI's login endpoint + * (POST https://<ones>/api/user/login, the same login the ONES UI and ones-gfx-sdk use) and + * sends the returned JWT as a Bearer token to FM (https://<ones>:8443). ONES JWTs are short + * lived, so on a 401 the client logs in again and retries once. + * + * Every state-changing call is made ASYNC ("Prefer: respond-async") and the client then polls + * GET /operations/{id} until it finishes. Besides not holding an HTTP request open for minutes, + * this matters for correctness: FM sends its tenant webhooks (which is how the edge gateway + * learns about a tenant) only for async operations. + */ +public class OnesApiClientImpl implements OnesApiClient { + + private static final Logger LOG = LogManager.getLogger(OnesApiClientImpl.class); + + private static final int CONNECT_TIMEOUT_MS = 15000; + private static final int SOCKET_TIMEOUT_MS = 120000; + static final long OPERATION_TIMEOUT_MS = 900_000; + static final long OPERATION_POLL_MS = 5_000; + private static final char[] KEYSTORE_PASSWORD = "avizones".toCharArray(); + + private final String fmUrl; + private final String loginUrl; + private final String username; + private final String password; + private final CloseableHttpClient httpClient; + private volatile String token; + long operationPollMs = OPERATION_POLL_MS; + + public OnesApiClientImpl(final String fmUrl, final String loginUrl, final String username, final String password, + final String clientCertPath, final String clientKeyPath, final String caCertPath) { + this.fmUrl = stripSlash(fmUrl); + this.loginUrl = loginUrl; + this.username = username; + this.password = password; + this.httpClient = buildHttpClient(clientCertPath, clientKeyPath, caCertPath); + } + + private static String stripSlash(final String url) { + return url.endsWith("/") ? url.substring(0, url.length() - 1) : url; + } + + // ---------------------------------------------------------------- TLS + + private CloseableHttpClient buildHttpClient(final String clientCertPath, final String clientKeyPath, final String caCertPath) { + try { + if (Security.getProvider("BC") == null) { + Security.addProvider(new BouncyCastleProvider()); + } + // Optional mTLS client certificate; optional CA bundle (else the JVM trust store). + // Host names are always verified: ONES's stock certificate names "ones-fm" and + // "localhost", not an IP, so point the URLs at a name the certificate carries. + KeyManager[] keyManagers = (clientCertPath != null && clientKeyPath != null) + ? buildKeyManagers(clientCertPath, clientKeyPath) : null; + TrustManager[] trustManagers = (caCertPath != null) ? buildTrustManagers(caCertPath) : null; + + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(keyManagers, trustManagers, new SecureRandom()); + + RequestConfig requestConfig = RequestConfig.custom() + .setConnectTimeout(CONNECT_TIMEOUT_MS) + .setSocketTimeout(SOCKET_TIMEOUT_MS) + .build(); + return HttpClients.custom() + .setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext)) + .setDefaultRequestConfig(requestConfig) + .build(); + } catch (Exception e) { + throw new CloudRuntimeException("Failed to initialize the HTTPS client for Aviz ONES: " + e.getMessage(), e); + } + } + + private KeyManager[] buildKeyManagers(final String certPath, final String keyPath) throws Exception { + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + X509Certificate clientCert; + try (InputStream in = new FileInputStream(certPath)) { + clientCert = (X509Certificate) cf.generateCertificate(in); + } + PrivateKey privateKey; + try (PEMParser pemParser = new PEMParser(new FileReader(keyPath))) { + Object obj = pemParser.readObject(); + JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC"); + if (obj instanceof PEMKeyPair) { + privateKey = converter.getKeyPair((PEMKeyPair) obj).getPrivate(); + } else if (obj instanceof org.bouncycastle.asn1.pkcs.PrivateKeyInfo) { + privateKey = converter.getPrivateKey((org.bouncycastle.asn1.pkcs.PrivateKeyInfo) obj); + } else { + throw new CloudRuntimeException("Unsupported (or encrypted) private key format in " + keyPath); + } + } + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + keyStore.load(null, null); + keyStore.setKeyEntry("ones-client", privateKey, KEYSTORE_PASSWORD, new X509Certificate[]{clientCert}); + KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + kmf.init(keyStore, KEYSTORE_PASSWORD); + return kmf.getKeyManagers(); + } + + private TrustManager[] buildTrustManagers(final String caCertPath) throws Exception { + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + KeyStore trustStore = KeyStore.getInstance("PKCS12"); + trustStore.load(null, null); + try (InputStream in = new FileInputStream(caCertPath)) { + int i = 0; + for (java.security.cert.Certificate c : cf.generateCertificates(in)) { + trustStore.setCertificateEntry("ones-ca-" + i++, c); + } + } + TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + tmf.init(trustStore); + return tmf.getTrustManagers(); + } + + // ---------------------------------------------------------------- HTTP + + /** HTTP status + body. */ + static final class Reply { + final int status; + final String body; + + Reply(final int status, final String body) { + this.status = status; + this.body = body; + } + + boolean ok() { + return status >= 200 && status < 300; + } + } + + private Reply send(final HttpRequestBase request) throws IOException { + request.setHeader("Content-Type", "application/json"); + request.setHeader("Accept", "application/json"); + try (CloseableHttpResponse response = httpClient.execute(request)) { + HttpEntity entity = response.getEntity(); + return new Reply(response.getStatusLine().getStatusCode(), entity != null ? EntityUtils.toString(entity) : ""); + } + } + + private synchronized String login() throws IOException { + HttpPost post = new HttpPost(loginUrl); + JsonObject body = new JsonObject(); + body.addProperty("username", username); + body.addProperty("password", password); + post.setEntity(new StringEntity(body.toString(), "UTF-8")); + Reply r = send(post); + if (!r.ok()) { + throw new IOException("ONES login at " + loginUrl + " as " + username + " failed: HTTP " + r.status); + } + JsonObject data = asObject(parse(r.body), "data"); + String t = data != null ? str(data, "token") : null; + if (t == null) { + throw new IOException("ONES login at " + loginUrl + " returned no token"); + } + token = t; + return t; + } + + /** One FM call with the Bearer token; logs in first if needed and once more on a 401. */ + Reply call(final HttpRequestBase request, final boolean async) throws IOException { + if (async) { + request.setHeader("Prefer", "respond-async"); + } + for (int attempt = 0; ; attempt++) { + String t = token != null ? token : login(); + request.setHeader("Authorization", "Bearer " + t); + Reply r = send(request); + if (r.status == 401 && attempt == 0) { + token = null; + continue; + } + return r; + } + } + + private Reply callOk(final HttpRequestBase request, final boolean async, final String what) throws IOException { + Reply r = call(request, async); + if (!r.ok()) { + throw new IOException(what + ": ONES returned HTTP " + r.status + ": " + abbreviate(r.body)); + } + return r; + } + + /** + * Waits for the async operation an FM reply names, if any. FM wraps replies as + * {success, message, data} where data is an object or a JSON-encoded string. + */ + void awaitOperation(final Reply reply, final String what) throws IOException { + String op = findOperationId(parse(reply.body)); + if (op == null) { + return; // FM answered synchronously + } + long deadline = System.currentTimeMillis() + OPERATION_TIMEOUT_MS; + while (System.currentTimeMillis() < deadline) { + Reply r = callOk(new HttpGet(fmUrl + "/operations/" + op), false, what + " (operation " + op + ")"); + JsonElement root = parse(r.body); + JsonObject o = asObject(root, "data"); + if (o == null && root != null && root.isJsonObject()) { + o = root.getAsJsonObject(); + } + String status = o != null ? str(o, "status") : null; + if ("SUCCESS".equals(status)) { + return; + } + if ("FAILED".equals(status) || "CANCELLED".equals(status)) { + throw new IOException(what + ": ONES operation " + op + " " + status + ": " + abbreviate(String.valueOf(str(o, "errorMessage")))); + } + try { + Thread.sleep(operationPollMs); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IOException(what + ": interrupted waiting for ONES operation " + op); + } + } + throw new IOException(what + ": ONES operation " + op + " did not finish in " + OPERATION_TIMEOUT_MS / 1000 + " s"); + } + + private static String findOperationId(final JsonElement root) { + if (root == null || !root.isJsonObject()) { + return null; + } + JsonObject o = root.getAsJsonObject(); + String id = str(o, "operationId"); + if (id != null) { + return id; + } + JsonObject data = asObject(root, "data"); + return data != null ? str(data, "operationId") : null; + } + + // ---------------------------------------------------------------- API + + @Override + public boolean isReachable() { + try { + callOk(new HttpGet(fmUrl + "/getAllFabrics"), false, "list fabrics"); + return true; + } catch (Exception e) { + LOG.warn("Aviz ONES at {} is not reachable: {}", fmUrl, e.getMessage()); + return false; + } + } + + @Override + public CreateOnesTenantAnswer createTenant(final CreateOnesTenantCommand cmd) { + String what = "create ONES tenant " + cmd.getTenantName() + " on fabric " + cmd.getFabricName(); + try { + JsonObject tenant = getTenant(cmd.getFabricName(), cmd.getTenantName()); + if (tenant == null) { + JsonObject body = new JsonObject(); + body.addProperty("tenantName", cmd.getTenantName()); + body.addProperty("description", cmd.getDescription() != null ? cmd.getDescription() : ""); + body.addProperty("maxGpusAllowed", cmd.getMaxGpusAllowed()); + // no tenant-level "shared": ONES refuses it unless the fabric is externally + // controlled; sharing is per server (see patchServers) + HttpPost post = new HttpPost(fmUrl + "/fabrics/" + cmd.getFabricName() + "/tenants"); + post.setEntity(new StringEntity(body.toString(), "UTF-8")); + awaitOperation(callOk(post, true, what), what); + tenant = getTenant(cmd.getFabricName(), cmd.getTenantName()); + } + if (tenant == null) { + throw new IOException(what + ": the tenant is not there after the create finished"); + } + String gateway = null; + String pool = str(tenant, "tenantIpPool"); + JsonObject vnets = asObject(tenant, "vnets"); + JsonObject ipPool = vnets != null ? asObject(vnets, "tenant IP Pool") : null; + if (ipPool != null) { + gateway = stripPrefix(str(ipPool, "gateway")); + pool = pool != null ? pool : str(ipPool, "subnet"); + } + return new CreateOnesTenantAnswer(cmd, tenant.toString(), integer(tenant, "vlanId"), integer(tenant, "vniId"), + integer(tenant, "nsVniId"), str(tenant, "vlanSubnetCPU"), pool, gateway); + } catch (Exception e) { + LOG.error("Failed to {}: {}", what, e.getMessage()); + return new CreateOnesTenantAnswer(cmd, e); + } + } + + /** GET /fabrics/{f}/tenants/{t}: the tenant record, or null if there is none. */ + JsonObject getTenant(final String fabric, final String tenant) throws IOException { + Reply r = call(new HttpGet(fmUrl + "/fabrics/" + fabric + "/tenants/" + tenant), false); + if (r.status == 404) { + return null; + } + if (!r.ok()) { + throw new IOException("get ONES tenant " + tenant + ": HTTP " + r.status + ": " + abbreviate(r.body)); + } + JsonElement root = parse(r.body); + JsonObject t = asObject(root, "tenant"); + if (t == null) { + JsonObject data = asObject(root, "data"); + t = data != null ? asObject(data, "tenant") : null; + } + return t; + } + + @Override + public Answer deleteTenant(final DeleteOnesTenantCommand cmd) { + String what = "delete ONES tenant " + cmd.getTenantName() + " on fabric " + cmd.getFabricName(); + try { + Reply r = call(new HttpDelete(fmUrl + "/fabrics/" + cmd.getFabricName() + "/tenants/" + cmd.getTenantName()), true); + if (r.status == 404) { + return new Answer(cmd, true, "already gone"); + } + if (!r.ok()) { + throw new IOException(what + ": HTTP " + r.status + ": " + abbreviate(r.body)); + } + awaitOperation(r, what); + return new Answer(cmd, true, r.body); + } catch (Exception e) { + LOG.error("Failed to {}: {}", what, e.getMessage()); + return new Answer(cmd, e); + } + } + + @Override + public Answer allocateServers(final AllocateOnesServersCommand cmd) { + Answer added = patchServers(cmd, cmd.getFabricName(), cmd.getTenantName(), "ADD", cmd.getServerNames(), cmd.isShared()); + if (!added.getResult()) { + return added; + } + // Behind a DPU (HBN fabric) the tenant ends at the DPU: the server joining the tenant puts + // the tenant's VRF/VLAN/SVI on its DPU, and one host-facing DPU port (a "VF") carries the + // tenant to the hypervisor, untagged. A hypervisor holds several tenants, so each tenant + // gets its own VF on every server it uses. + String what = "DPU VF for ONES tenant " + cmd.getTenantName() + " on " + cmd.getServerNames(); + try { + for (String server : cmd.getServerNames()) { + assignDpuVf(cmd.getFabricName(), server, cmd.getTenantName()); + } + return added; + } catch (Exception e) { + LOG.error("Failed to assign {}: {}", what, e.getMessage()); + return new Answer(cmd, e); Review Comment: Fixed in 4a1aef6687. If assigning a VF fails after the server ADD, `allocateServers` now calls `deallocateServers` for the same servers: it releases any VFs this call got, then removes the servers from the tenant, and returns the failure. If that rollback fails as well, the answer says so and names the servers to remove in ONES. Tests: `allocateServersFailsWhenTheDpuHasNoFreeVf` (ADD then DELETE), `aFailedVfAssignmentReleasesWhatThisCallGotBeforeTakingTheServerOut`, `aRollbackThatFailsTooIsReported`. ########## plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/service/OnesEdgeBuilder.java: ########## @@ -0,0 +1,297 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.ones.service; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand.FirewallRule; +import org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand.PortMapping; +import org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand.Vip; +import org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand; +import org.apache.cloudstack.network.ones.client.AvizGatewayClient; + +import com.cloud.network.IpAddress; +import com.cloud.network.Network; +import com.cloud.network.NetworkModel; +import com.cloud.network.dao.FirewallRulesCidrsDao; +import com.cloud.network.dao.FirewallRulesDao; +import com.cloud.network.dao.IPAddressDao; +import com.cloud.network.dao.IPAddressVO; +import com.cloud.network.dao.LBStickinessPolicyDao; +import com.cloud.network.dao.LBStickinessPolicyVO; +import com.cloud.network.dao.LoadBalancerDao; +import com.cloud.network.dao.LoadBalancerVMMapDao; +import com.cloud.network.dao.LoadBalancerVMMapVO; +import com.cloud.network.dao.LoadBalancerVO; +import com.cloud.network.rules.FirewallRule.Purpose; +import com.cloud.network.rules.FirewallRule.State; +import com.cloud.network.rules.FirewallRule.TrafficType; +import com.cloud.network.rules.FirewallRuleVO; +import com.cloud.network.rules.LbStickinessMethod.StickinessMethodType; +import com.cloud.network.rules.LoadBalancerContainer.Scheme; +import com.cloud.network.rules.PortForwardingRuleVO; +import com.cloud.network.rules.dao.PortForwardingRulesDao; +import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.vm.Nic; + +/** + * What a ONES network's edge on the Aviz Gateway should be, read from CloudStack's own records: + * the network's source NAT address, its live port forwards and public load-balancer rules, and + * the ingress firewall rules on their public addresses. + * + * Firewall: the gateway filters inbound traffic after translation, so every mapped local + * address:port gets a deny for any source, and a permit for each source CIDR an ingress rule + * allows on the public address:port that leads there. The permit's narrower source puts it ahead + * of the deny. A mapping no ingress rule covers stays closed, as on any CloudStack network. + */ +public class OnesEdgeBuilder { + + /** Port forwards are mapped port by port on the gateway: more than this in one rule is refused. */ + static final int MAX_PORTS_PER_FORWARD = 256; + static final String ANY = "0.0.0.0/0"; + + private final IPAddressDao ipAddressDao; + private final PortForwardingRulesDao portForwardingRulesDao; + private final LoadBalancerDao loadBalancerDao; + private final LoadBalancerVMMapDao lbVmMapDao; + private final LBStickinessPolicyDao lbStickinessPolicyDao; + private final FirewallRulesDao firewallRulesDao; + private final FirewallRulesCidrsDao firewallRulesCidrsDao; + private final NetworkModel networkModel; + + public OnesEdgeBuilder(final IPAddressDao ipAddressDao, final PortForwardingRulesDao portForwardingRulesDao, final LoadBalancerDao loadBalancerDao, + final LoadBalancerVMMapDao lbVmMapDao, final LBStickinessPolicyDao lbStickinessPolicyDao, final FirewallRulesDao firewallRulesDao, + final FirewallRulesCidrsDao firewallRulesCidrsDao, final NetworkModel networkModel) { + this.ipAddressDao = ipAddressDao; + this.portForwardingRulesDao = portForwardingRulesDao; + this.loadBalancerDao = loadBalancerDao; + this.lbVmMapDao = lbVmMapDao; + this.lbStickinessPolicyDao = lbStickinessPolicyDao; + this.firewallRulesDao = firewallRulesDao; + this.firewallRulesCidrsDao = firewallRulesCidrsDao; + this.networkModel = networkModel; + } + + static boolean live(final State state) { + return state == State.Add || state == State.Active; + } + + static String protocolOf(final String p) { + return p != null && "udp".equalsIgnoreCase(p) ? "udp" : "tcp"; + } + + /** The address the network's outbound traffic is translated onto; null when it has none. */ + String sourceNatAddress(final long networkId) { + for (IPAddressVO ip : ipAddressDao.listByAssociatedNetwork(networkId, true)) { + if (ip.getState() == IpAddress.State.Allocated || ip.getState() == IpAddress.State.Allocating) { + return ip.getAddress().addr(); + } + } + return null; + } + + private String addressOf(final long ipId) { + IPAddressVO ip = ipAddressDao.findById(ipId); + if (ip == null) { + throw new CloudRuntimeException("public IP " + ipId + " is gone"); + } + return ip.getAddress().addr(); + } + + List<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); + } + + // keyed by what the rule does, so a local address:port reached two ways is filtered once + Map<String, String[]> wanted = new LinkedHashMap<>(); + for (Target t : targets) { + String dst = t.local + "/32"; + for (FirewallRuleVO r : ingress) { + if (covers(r, ruleAddress.get(r.getId()), t)) { + for (String cidr : ruleSources.get(r.getId())) { + wanted.putIfAbsent("permit " + cidr + " " + dst + " " + t.protocol + " " + t.localPort, + new String[]{"permit", cidr, dst, t.protocol, String.valueOf(t.localPort)}); Review Comment: Fixed in 4a1aef6687. `OnesEdgeBuilder` collects the allowed sources of every public endpoint that leads to the same local address, port and protocol, and refuses the edge if two endpoints allow different sources. Aliases with the same policy are still allowed. Test: `twoForwardsToOneVmPortMustAllowTheSameSources`. Verified live: a second forward to a restricted VM port with no ingress rule is refused, and the reason is in the management server log. ########## plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/service/OnesElement.java: ########## @@ -0,0 +1,777 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.ones.service; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.function.BooleanSupplier; + +import javax.inject.Inject; +import javax.naming.ConfigurationException; + +import org.apache.cloudstack.network.ones.agent.api.AllocateOnesServersCommand; +import org.apache.cloudstack.network.ones.agent.api.ConfigureOnesEdgeCommand; +import org.apache.cloudstack.network.ones.agent.api.RemoveOnesEdgeCommand; +import org.apache.cloudstack.network.ones.agent.api.StartupOnesCommand; +import org.apache.cloudstack.network.ones.api.command.AddOnesProviderCmd; +import org.apache.cloudstack.network.ones.api.command.DeleteOnesProviderCmd; +import org.apache.cloudstack.network.ones.api.command.ListOnesProvidersCmd; +import org.apache.cloudstack.network.ones.api.command.UpdateOnesProviderCmd; +import org.apache.cloudstack.network.ones.api.response.OnesProviderResponse; +import org.apache.cloudstack.network.ones.dao.OnesProviderDao; +import org.apache.cloudstack.network.ones.dao.OnesProviderVO; +import org.apache.cloudstack.network.ones.resource.OnesResource; +import org.springframework.stereotype.Component; + +import com.cloud.agent.AgentManager; +import com.cloud.agent.api.Answer; +import com.cloud.agent.api.StartupCommand; +import com.cloud.agent.api.to.LoadBalancerTO; +import com.cloud.api.ApiDBUtils; +import com.cloud.deploy.DeployDestination; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.host.DetailVO; +import com.cloud.host.Host; +import com.cloud.host.HostVO; +import com.cloud.host.dao.HostDao; +import com.cloud.host.dao.HostDetailsDao; +import com.cloud.network.Network.Capability; +import com.cloud.network.Network.Provider; +import com.cloud.network.Network.Service; +import com.cloud.network.Network; +import com.cloud.network.NetworkModel; +import com.cloud.network.PhysicalNetwork; +import com.cloud.network.PhysicalNetworkServiceProvider; +import com.cloud.network.PublicIpAddress; +import com.cloud.network.dao.FirewallRulesCidrsDao; +import com.cloud.network.dao.FirewallRulesDao; +import com.cloud.network.dao.IPAddressDao; +import com.cloud.network.dao.IPAddressVO; +import com.cloud.network.dao.LBStickinessPolicyDao; +import com.cloud.network.dao.LoadBalancerDao; +import com.cloud.network.dao.LoadBalancerVMMapDao; +import com.cloud.network.dao.NetworkDao; +import com.cloud.network.dao.NetworkDetailVO; +import com.cloud.network.dao.NetworkDetailsDao; +import com.cloud.network.dao.NetworkServiceMapDao; +import com.cloud.network.dao.NetworkVO; +import com.cloud.network.dao.PhysicalNetworkDao; +import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; +import com.cloud.network.dao.PhysicalNetworkServiceProviderVO; +import com.cloud.network.dao.PhysicalNetworkVO; +import com.cloud.network.element.ConnectivityProvider; +import com.cloud.network.element.FirewallServiceProvider; +import com.cloud.network.element.IpDeployer; +import com.cloud.network.element.LoadBalancingServiceProvider; +import com.cloud.network.element.PortForwardingServiceProvider; +import com.cloud.network.element.SourceNatServiceProvider; +import com.cloud.network.lb.LoadBalancingRule; +import com.cloud.network.rules.FirewallRule; +import com.cloud.network.rules.LbStickinessMethod.StickinessMethodType; +import com.cloud.network.rules.LbStickinessMethod; +import com.cloud.network.rules.LoadBalancerContainer; +import com.cloud.network.rules.PortForwardingRule; +import com.cloud.network.rules.dao.PortForwardingRulesDao; +import com.cloud.offering.NetworkOffering; +import com.cloud.resource.ResourceManager; +import com.cloud.resource.ResourceState; +import com.cloud.resource.ResourceStateAdapter; +import com.cloud.resource.ServerResource; +import com.cloud.resource.UnableDeleteHostException; +import com.cloud.utils.component.AdapterBase; +import com.cloud.utils.db.DB; +import com.cloud.utils.db.GlobalLock; +import com.cloud.utils.db.Transaction; +import com.cloud.utils.db.TransactionCallback; +import com.cloud.utils.db.TransactionStatus; +import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.vm.NicProfile; +import com.cloud.vm.ReservationContext; +import com.cloud.vm.VirtualMachineProfile; +import com.google.gson.Gson; + +/** + * NetworkElement for the Aviz ONES Spectrum-X fabric: registers/manages the ONES controller as + * a pseudo-agent host (see {@link OnesResource}), and drives per-host GPU-server tenant + * membership as VMs are placed on/removed from hypervisor hosts within a ONES-backed guest + * network. Tenant creation/CIDR assignment itself happens in {@link org.apache.cloudstack.network.ones.service.OnesGuestNetworkGuru}, + * since ONES computes the guest IP pool server-side as part of "Create Tenant". + */ +@Component +public class OnesElement extends AdapterBase implements ConnectivityProvider, OnesElementService, ResourceStateAdapter, + SourceNatServiceProvider, FirewallServiceProvider, PortForwardingServiceProvider, LoadBalancingServiceProvider, IpDeployer { + + /** + * The network service provider this plugin adds. CloudStack core has no "AvizOnes" constant; + * creating a Provider registers it in Provider's list of supported providers, so + * addNetworkServiceProvider name=AvizOnes works once this class is loaded. + */ + public static final Provider AVIZ_ONES = new Provider("AvizOnes", false); + + public static final String DETAIL_TENANT_NAME = "onestenantname"; + public static final String DETAIL_ALLOCATED_HOSTS = "onesallocatedhosts"; + + /** The resource may wait up to 180 s for ONES to put the tenant on the gateway, then applies. */ + static final int EDGE_WAIT_S = 600; + static final int EDGE_LOCK_S = 600; + + private static final Map<Service, Map<Capability, String>> CAPABILITIES = setCapabilities(); + + @Inject + protected ResourceManager resourceMgr; + @Inject + protected PhysicalNetworkDao physicalNetworkDao; + @Inject + protected PhysicalNetworkServiceProviderDao physicalNetworkServiceProviderDao; + @Inject + protected OnesProviderDao onesProviderDao; + @Inject + protected HostDetailsDao hostDetailsDao; + @Inject + protected HostDao hostDao; + @Inject + protected AgentManager agentMgr; + @Inject + protected NetworkDao networkDao; + @Inject + protected NetworkDetailsDao networkDetailsDao; + @Inject + protected NetworkModel networkModel; + @Inject + protected NetworkServiceMapDao ntwkSrvcDao; + @Inject + protected IPAddressDao ipAddressDao; + @Inject + protected PortForwardingRulesDao portForwardingRulesDao; + @Inject + protected LoadBalancerDao loadBalancerDao; + @Inject + protected LoadBalancerVMMapDao lbVmMapDao; + @Inject + protected LBStickinessPolicyDao lbStickinessPolicyDao; + @Inject + protected FirewallRulesDao firewallRulesDao; + @Inject + protected FirewallRulesCidrsDao firewallRulesCidrsDao; + + @Override + public Map<Service, Map<Capability, String>> getCapabilities() { + return CAPABILITIES; + } + + @Override + public Provider getProvider() { + return AVIZ_ONES; + } + + private static Map<Service, Map<Capability, String>> setCapabilities() { + Map<Service, Map<Capability, String>> capabilities = new HashMap<>(); + // Connectivity: the ONES tenant. ONES picks its subnet and gateway when it is created. + capabilities.put(Service.Connectivity, null); + // The rest is the tenant's edge on the Aviz Gateway: outbound translation onto the + // network's source NAT address, port forwards, load-balancer VIPs, ingress filtering. + Map<Capability, String> sourceNat = new HashMap<>(); + sourceNat.put(Capability.SupportedSourceNatTypes, "peraccount"); + sourceNat.put(Capability.RedundantRouter, "false"); + capabilities.put(Service.SourceNat, sourceNat); + Map<Capability, String> firewall = new HashMap<>(); + firewall.put(Capability.SupportedProtocols, "tcp,udp"); + firewall.put(Capability.MultipleIps, "true"); + firewall.put(Capability.SupportedTrafficDirection, "ingress"); + capabilities.put(Service.Firewall, firewall); + capabilities.put(Service.PortForwarding, null); + Map<Capability, String> lb = new HashMap<>(); + lb.put(Capability.SupportedLBAlgorithms, "roundrobin"); + lb.put(Capability.SupportedLBIsolation, "dedicated"); + lb.put(Capability.SupportedProtocols, "tcp, udp"); + lb.put(Capability.SupportedStickinessMethods, sourceStickinessOnly()); + lb.put(Capability.LbSchemes, LoadBalancerContainer.Scheme.Public.name()); + capabilities.put(Service.Lb, lb); + return capabilities; + } + + /** The gateway can keep a client on one server by its source address, nothing else. */ + private static String sourceStickinessOnly() { + LbStickinessMethod method = new LbStickinessMethod(StickinessMethodType.SourceBased, + "Keeps every connection from one client address on the same server."); + return new Gson().toJson(Collections.singletonList(method)); + } + + protected boolean canHandle(final Network network, final Service service) { + if (!networkModel.isProviderForNetwork(getProvider(), network.getId())) { + return false; + } + return ntwkSrvcDao.canProviderSupportServiceInNetwork(network.getId(), service, AVIZ_ONES); + } + + private OnesProviderVO findProviderOrThrow(final Network network) { + List<OnesProviderVO> devices = onesProviderDao.listByPhysicalNetwork(network.getPhysicalNetworkId()); + if (devices.isEmpty()) { + throw new CloudRuntimeException("No Aviz ONES provider configured on physical network " + network.getPhysicalNetworkId()); + } + return devices.get(0); + } + + private String getTenantName(final Network network) { + NetworkDetailVO detail = networkDetailsDao.findDetail(network.getId(), DETAIL_TENANT_NAME); + if (detail == null) { + throw new CloudRuntimeException("No Aviz ONES tenant is on record for network " + network.getUuid() + + " - was it implemented through the Aviz ONES guest network guru?"); + } + return detail.getValue(); + } + + private List<String> getAllocatedHosts(final long networkId) { + NetworkDetailVO detail = networkDetailsDao.findDetail(networkId, DETAIL_ALLOCATED_HOSTS); + if (detail == null || detail.getValue() == null || detail.getValue().isEmpty()) { + return new ArrayList<>(); + } + return new ArrayList<>(Arrays.asList(detail.getValue().split(","))); + } + + private void setAllocatedHosts(final long networkId, final List<String> hostNames) { + networkDetailsDao.removeDetail(networkId, DETAIL_ALLOCATED_HOSTS); + networkDetailsDao.addDetail(networkId, DETAIL_ALLOCATED_HOSTS, String.join(",", hostNames), false); + } + + @Override + public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException { + super.configure(name, params); + resourceMgr.registerResourceStateAdapter(name, this); + // OnesResource instances are re-created reflectively on restart and get no injection. + OnesResource.setProviderDao(onesProviderDao); + return true; + } + + @Override + public boolean implement(final Network network, final NetworkOffering offering, final DeployDestination dest, final ReservationContext context) + throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { + // Tenant creation and CIDR/gateway assignment happens in OnesGuestNetworkGuru.implement(), + // since ONES - not CloudStack - computes the guest IP pool. Nothing further to do here. + return canHandle(network, Service.Connectivity); + } + + @Override + public boolean prepare(final Network network, final NicProfile nic, final VirtualMachineProfile vm, final DeployDestination dest, + final ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { + if (!canHandle(network, Service.Connectivity) || dest.getHost() == null) { + return false; + } + + OnesProviderVO device = findProviderOrThrow(network); + HostVO onesHost = hostDao.findById(device.getHostId()); + String tenantName = getTenantName(network); + String serverName = dest.getHost().getName(); + + // Read, add on ONES and record under one per-network lock: two VMs starting at once on + // different hosts would otherwise each write back a list without the other's host, and + // that host would stay in the tenant unrecorded (never taken out again). + boolean[] firstHost = {false}; + boolean locked = underLock("ones.hosts." + network.getId(), () -> { + List<String> allocatedHosts = getAllocatedHosts(network.getId()); + if (allocatedHosts.contains(serverName)) { + return true; + } + // shared: a hypervisor carries many guest networks, so ONES trunks the tenant's VLAN on + // the host's leaf port instead of dedicating the port to this tenant. + AllocateOnesServersCommand cmd = new AllocateOnesServersCommand(device.getFabricName(), tenantName, Arrays.asList(serverName), true); + cmd.setWait(900); + Answer answer = agentMgr.easySend(onesHost.getId(), cmd); + if (answer == null || !answer.getResult()) { + throw new CloudRuntimeException("Failed to add host " + serverName + " to Aviz ONES tenant " + tenantName + ": " + + (answer != null ? answer.getDetails() : "no answer from Aviz ONES resource")); + } + firstHost[0] = allocatedHosts.isEmpty(); + allocatedHosts.add(serverName); + setAllocatedHosts(network.getId(), allocatedHosts); + return true; + }); + if (!locked) { + throw new CloudRuntimeException("Could not lock the Aviz ONES hosts of network " + network.getUuid()); + } + if (firstHost[0] && hasEdge(network)) { + // ONES now puts the tenant on the gateway (FM tenant webhook): its edge can follow. + // A failure here leaves the network east-west only; the VM deployment goes on. + if (!syncEdge(network)) { + logger.warn("Network {} is up without its Aviz Gateway edge (internet access, port forwards, VIPs); " + + "it is applied again with the next rule change or restartNetwork", network); + } + } + return true; + } + + @Override + public boolean release(final Network network, final NicProfile nic, final VirtualMachineProfile vm, final ReservationContext context) + throws ConcurrentOperationException, ResourceUnavailableException { + if (!canHandle(network, Service.Connectivity)) { + return false; + } + // Deallocation of a no-longer-used host from the tenant happens in destroy(), once we can + // be sure no other NICs/VMs on this network are still active on that host; per-NIC release + // is intentionally a no-op to avoid pulling a host out from under a sibling VM on the same + // network and host. + return true; + } + + @Override + public boolean shutdown(final Network network, final ReservationContext context, final boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException { + if (!canHandle(network, Service.Connectivity)) { + return false; + } + removeEdge(network); // before the guru takes the hosts out of the tenant + return true; + } + + @Override + public boolean destroy(final Network network, final ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { + // Tenant deletion happens in OnesGuestNetworkGuru.trash(), mirroring how + // NiciraNvpElement/NiciraNvpGuestNetworkGuru split whole-network teardown to the guru. + if (!canHandle(network, Service.Connectivity)) { + return false; + } + removeEdge(network); + return true; + } + + @Override + public boolean isReady(final PhysicalNetworkServiceProvider provider) { + return true; + } + + @Override + public boolean shutdownProviderInstances(final PhysicalNetworkServiceProvider provider, final ReservationContext context) + throws ConcurrentOperationException, ResourceUnavailableException { + return true; + } + + @Override + public boolean canEnableIndividualServices() { + return true; + } + + @Override + public boolean verifyServicesCombination(final Set<Service> services) { + if (!services.contains(Service.Connectivity)) { + logger.warn("Unable to provide services without Connectivity service enabled for the Aviz ONES element"); + return false; + } + return true; + } + + @Override + public List<Class<?>> getCommands() { + List<Class<?>> cmdList = new ArrayList<>(); + cmdList.add(AddOnesProviderCmd.class); + cmdList.add(DeleteOnesProviderCmd.class); + cmdList.add(ListOnesProvidersCmd.class); + cmdList.add(UpdateOnesProviderCmd.class); + return cmdList; + } + + @Override + @DB + public OnesProviderVO addOnesProvider(final AddOnesProviderCmd cmd) { + final Long physicalNetworkId = cmd.getPhysicalNetworkId(); + PhysicalNetworkVO physicalNetwork = physicalNetworkDao.findById(physicalNetworkId); + if (physicalNetwork == null) { + throw new InvalidParameterValueException("Could not find physical network with ID: " + physicalNetworkId); + } + long zoneId = physicalNetwork.getDataCenterId(); + + final PhysicalNetworkServiceProviderVO ntwkSvcProvider = + physicalNetworkServiceProviderDao.findByServiceProvider(physicalNetwork.getId(), AVIZ_ONES.getName()); + if (ntwkSvcProvider == null) { + throw new CloudRuntimeException("Network Service Provider " + AVIZ_ONES.getName() + " is not enabled on physical network " + + physicalNetworkId + " - enable it first via addNetworkServiceProvider"); + } else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) { + throw new CloudRuntimeException("Network Service Provider " + ntwkSvcProvider.getProviderName() + " is in Shutdown state on physical network " + + physicalNetworkId); + } + + if (!onesProviderDao.listByPhysicalNetwork(physicalNetworkId).isEmpty()) { + throw new CloudRuntimeException("An Aviz ONES provider is already configured on this physical network"); + } + + final String deviceName = AVIZ_ONES.getName(); + final String name = cmd.getName(); + final String url = cmd.getUrl(); + final String fabricName = cmd.getFabricName(); + final String loginUrl = cmd.getLoginUrl(); + final String username = cmd.getUsername(); + final String password = cmd.getPassword(); + final String clientCertPath = cmd.getClientCertPath(); + final String clientKeyPath = cmd.getClientKeyPath(); + final String caCertPath = cmd.getCaCertPath(); + + Map<String, String> params = new HashMap<>(); + params.put("guid", UUID.randomUUID().toString()); + params.put("zoneId", String.valueOf(zoneId)); + params.put("physicalNetworkId", String.valueOf(physicalNetworkId)); + params.put("name", name); + params.put("url", url); + params.put("loginUrl", loginUrl); + params.put("username", username); + // The password is deliberately NOT in `params`: that map is persisted in clear text in + // the generic host_details table. It goes only to the in-memory configure() below and + // into ones_providers (encrypted); after a restart OnesResource reads it from there. + // The TLS client certificate is optional: only pass these through when supplied, since + // CloudStack's host-details persistence does not tolerate null values in this map. + if (clientCertPath != null) { + params.put("clientCertPath", clientCertPath); + } + if (clientKeyPath != null) { + params.put("clientKeyPath", clientKeyPath); + } + if (caCertPath != null) { + params.put("caCertPath", caCertPath); + } + + Map<String, Object> hostDetails = new HashMap<>(params); + hostDetails.put("password", password); + ServerResource resource = new OnesResource(); + + try { + resource.configure(name, hostDetails); + final Host host = resourceMgr.addHost(zoneId, resource, resource.getType(), params); + if (host == null) { + throw new CloudRuntimeException("Failed to add Aviz ONES provider due to internal error."); + } + return Transaction.execute((TransactionCallback<OnesProviderVO>) (TransactionStatus status) -> { + OnesProviderVO onesProviderVO = new OnesProviderVO(host.getId(), physicalNetworkId, ntwkSvcProvider.getProviderName(), deviceName, + url, fabricName, loginUrl, username, password, clientCertPath, clientKeyPath, caCertPath); + onesProviderDao.persist(onesProviderVO); + + DetailVO detail = new DetailVO(host.getId(), "onesproviderid", String.valueOf(onesProviderVO.getId())); + hostDetailsDao.persist(detail); + + return onesProviderVO; + }); + } catch (ConfigurationException e) { + throw new CloudRuntimeException(e.getMessage()); + } + } + + @Override + public OnesProviderResponse createOnesProviderResponse(final OnesProviderVO onesProviderVO) { + OnesProviderResponse response = new OnesProviderResponse(); + response.setId(onesProviderVO.getUuid()); + PhysicalNetwork pnw = ApiDBUtils.findPhysicalNetworkById(onesProviderVO.getPhysicalNetworkId()); + if (pnw != null) { + response.setPhysicalNetworkId(pnw.getUuid()); + } + response.setProviderName(onesProviderVO.getProviderName()); + response.setDeviceName(onesProviderVO.getDeviceName()); + response.setUrl(onesProviderVO.getUrl()); + response.setFabricName(onesProviderVO.getFabricName()); + response.setGatewayUrl(onesProviderVO.getGatewayUrl()); + response.setGatewayTokenSet(onesProviderVO.getGatewayToken() != null); + response.setObjectName("onesprovider"); + return response; + } + + @Override + public boolean deleteOnesProvider(final DeleteOnesProviderCmd cmd) { + OnesProviderVO device = onesProviderDao.findById(cmd.getId()); + if (device == null) { + throw new InvalidParameterValueException("Could not find an Aviz ONES provider with id " + cmd.getId()); + } + + Long physicalNetworkId = device.getPhysicalNetworkId(); + List<NetworkVO> networkList = networkDao.listByPhysicalNetwork(physicalNetworkId); + if (networkList != null) { + for (NetworkVO network : networkList) { + // a Shutdown network still owns its ONES tenant, and needs this provider to delete it + if (networkModel.isProviderForNetwork(AVIZ_ONES, network.getId()) + && (network.getState() != Network.State.Destroy + || networkDetailsDao.findDetail(network.getId(), DETAIL_TENANT_NAME) != null)) { + throw new CloudRuntimeException("This Aviz ONES provider cannot be deleted: guest network " + network.getUuid() + + " still uses it (delete the network first)"); + } + } + } + + HostVO onesHost = hostDao.findById(device.getHostId()); + if (onesHost != null) { + onesHost.setResourceState(ResourceState.Maintenance); + hostDao.update(onesHost.getId(), onesHost); + resourceMgr.deleteHost(onesHost.getId(), false, false); + } + + onesProviderDao.remove(device.getId()); + return true; + } + + private static String orNull(final String v, final String current) { + return v == null ? current : (v.trim().isEmpty() ? null : v.trim()); + } + + @Override + public OnesProviderVO updateOnesProvider(final UpdateOnesProviderCmd cmd) { + OnesProviderVO vo = onesProviderDao.findById(cmd.getId()); + if (vo == null) { + throw new InvalidParameterValueException("Could not find an Aviz ONES provider with id " + cmd.getId()); + } + vo.setGatewayUrl(orNull(cmd.getGatewayUrl(), vo.getGatewayUrl())); + vo.setGatewayToken(orNull(cmd.getGatewayToken(), vo.getGatewayToken())); + vo.setGatewayCaCertPath(orNull(cmd.getGatewayCaCertPath(), vo.getGatewayCaCertPath())); + onesProviderDao.update(vo.getId(), vo); + return onesProviderDao.findById(vo.getId()); + } + + @Override + public List<OnesProviderVO> listOnesProviders(final ListOnesProvidersCmd cmd) { + Long physicalNetworkId = cmd.getPhysicalNetworkId(); + Long id = cmd.getId(); + List<OnesProviderVO> responseList = new ArrayList<>(); + + if (physicalNetworkId == null && id == null) { + throw new InvalidParameterValueException("Either physical network Id or Aviz ONES provider Id must be specified"); + } + + if (id != null) { + OnesProviderVO device = onesProviderDao.findById(id); + if (device == null) { + throw new InvalidParameterValueException("Could not find an Aviz ONES provider with id: " + id); + } + responseList.add(device); + } else { + PhysicalNetworkVO physicalNetwork = physicalNetworkDao.findById(physicalNetworkId); + if (physicalNetwork == null) { + throw new InvalidParameterValueException("Could not find a physical network with id: " + physicalNetworkId); + } + responseList = onesProviderDao.listByPhysicalNetwork(physicalNetworkId); + } + + return responseList; + } + + @Override + public HostVO createHostVOForConnectedAgent(final HostVO host, final StartupCommand[] cmd) { + return null; + } + + @Override + public HostVO createHostVOForDirectConnectAgent(final HostVO host, final StartupCommand[] startup, final ServerResource resource, + final Map<String, String> details, final List<String> hostTags) { + if (!(startup[0] instanceof StartupOnesCommand)) { + return null; + } + host.setType(Host.Type.L2Networking); + return host; + } + + @Override + public DeleteHostAnswer deleteHost(final HostVO host, final boolean isForced, final boolean isForceDeleteStorage) throws UnableDeleteHostException { + if (host.getType() != Host.Type.L2Networking) { + return null; + } + return new DeleteHostAnswer(true); + } + + // ------------------------------------------------------------------ edge services on the Aviz Gateway + + protected OnesEdgeBuilder edgeBuilder() { + return new OnesEdgeBuilder(ipAddressDao, portForwardingRulesDao, loadBalancerDao, lbVmMapDao, lbStickinessPolicyDao, + firewallRulesDao, firewallRulesCidrsDao, networkModel); + } + + private boolean hasEdge(final Network network) { + return canHandle(network, Service.SourceNat) || canHandle(network, Service.PortForwarding) || canHandle(network, Service.Lb); + } + + private static boolean gatewayConfigured(final OnesProviderVO device) { + return device.getGatewayUrl() != null && device.getGatewayToken() != null; + } + + /** + * Puts the network's whole edge (from CloudStack's records) on the Aviz Gateway. Nothing to do + * before the network's first host joined the tenant: until then the gateway does not have the + * tenant, and prepare() calls this once it does. + */ + protected boolean syncEdge(final Network network) { + String error = edgeSync(network); + if (error != null) { + logger.error("Aviz Gateway edge of network {}: {}", network, error); + } + return error == null; + } + + /** As syncEdge, for a rule change: CloudStack reads false as "not this provider's", so a failure throws. */ + protected boolean applyEdge(final Network network) throws ResourceUnavailableException { + String error = edgeSync(network); + if (error != null) { + throw new ResourceUnavailableException("Aviz Gateway edge of network " + network.getUuid() + ": " + error, Network.class, network.getId()); + } + return true; + } + + /** @return null when the gateway has the network's edge, else what went wrong */ + private String edgeSync(final Network network) { + if (getAllocatedHosts(network.getId()).isEmpty()) { + return null; + } + OnesProviderVO device = findProviderOrThrow(network); + if (!gatewayConfigured(device)) { + return "the network uses Aviz ONES edge services but its provider has no Aviz Gateway (updateOnesProvider gatewayurl, gatewaytoken)"; + } + String[] error = new String[1]; + try { + boolean locked = underLock("ones.edge." + network.getId(), () -> { + ConfigureOnesEdgeCommand cmd = edgeBuilder().build(network, getTenantName(network), canHandle(network, Service.SourceNat), + canHandle(network, Service.PortForwarding), canHandle(network, Service.Lb), canHandle(network, Service.Firewall)); + cmd.setWait(EDGE_WAIT_S); + Answer answer = agentMgr.easySend(device.getHostId(), cmd); + if (answer == null || !answer.getResult()) { + error[0] = answer != null ? answer.getDetails() : "no answer from the Aviz ONES resource"; + } + return true; + }); + return locked ? error[0] : "could not lock the network's edge"; + } catch (CloudRuntimeException e) { + return e.getMessage(); + } + } + + /** + * Runs work under a cluster-wide lock (one change per network at a time, across management + * servers): "ones.hosts.<id>" for the network's host list, "ones.edge.<id>" for its edge. + * @return false when the lock could not be had + */ + protected boolean underLock(final String name, final BooleanSupplier work) { + GlobalLock lock = GlobalLock.getInternLock(name); + try { + if (!lock.lock(EDGE_LOCK_S)) { + logger.warn("Could not get lock {}", name); + return false; + } + try { + return work.getAsBoolean(); + } finally { + lock.unlock(); + } + } finally { + lock.releaseRef(); + } + } + + protected void removeEdge(final Network network) { + String tenant = networkDetailsDao.findDetail(network.getId(), DETAIL_TENANT_NAME) != null ? getTenantName(network) : null; + if (tenant == null || !hasEdge(network)) { + return; + } + OnesProviderVO device = findProviderOrThrow(network); + if (!gatewayConfigured(device)) { + return; + } + RemoveOnesEdgeCommand cmd = new RemoveOnesEdgeCommand(tenant); + cmd.setWait(EDGE_WAIT_S); + Answer answer = agentMgr.easySend(device.getHostId(), cmd); + if (answer == null || !answer.getResult()) { + logger.warn("Could not remove the Aviz Gateway edge of network {}: {}", network, answer != null ? answer.getDetails() : "no answer"); + } + } Review Comment: Fixed in 4a1aef6687. `removeEdge` now throws `ResourceUnavailableException` when the gateway does not confirm the removal, so `shutdown` and `destroy` fail and NetworkOrchestrator keeps the network for a retry. To give up on a gateway that is gone for good, an operator clears `gatewayurl` with `updateOnesProvider` (documented). Test: `aGatewayCleanupFailureFailsTheTeardownSoItIsRetried`. Verified live: with the gateway unreachable, deleteNetwork fails and keeps the network and its tenant; once the gateway is back, the delete succeeds and leaves nothing on the gateway or in ONES. ########## plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/service/OnesGuestNetworkGuru.java: ########## @@ -0,0 +1,347 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.network.ones.service; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +import javax.inject.Inject; + +import org.apache.cloudstack.network.ones.agent.api.CreateOnesTenantAnswer; +import org.apache.cloudstack.network.ones.agent.api.CreateOnesTenantCommand; +import org.apache.cloudstack.network.ones.agent.api.DeallocateOnesServersCommand; +import org.apache.cloudstack.network.ones.agent.api.DeleteOnesTenantCommand; +import org.apache.cloudstack.network.ones.dao.OnesProviderDao; +import org.apache.cloudstack.network.ones.dao.OnesProviderVO; + +import com.cloud.agent.AgentManager; +import com.cloud.agent.api.Answer; +import com.cloud.dc.DataCenter.NetworkType; +import com.cloud.deploy.DeployDestination; +import com.cloud.deploy.DeploymentPlan; +import com.cloud.exception.InsufficientAddressCapacityException; +import com.cloud.exception.InsufficientVirtualNetworkCapacityException; +import com.cloud.host.dao.HostDao; +import com.cloud.network.Network.GuestType; +import com.cloud.network.Network.State; +import com.cloud.network.Network; +import com.cloud.network.NetworkProfile; +import com.cloud.network.Networks.BroadcastDomainType; +import com.cloud.network.PhysicalNetwork.IsolationMethod; +import com.cloud.network.PhysicalNetwork; +import com.cloud.network.dao.NetworkDetailVO; +import com.cloud.network.dao.NetworkDetailsDao; +import com.cloud.network.dao.NetworkVO; +import com.cloud.network.dao.PhysicalNetworkVO; +import com.cloud.network.guru.GuestNetworkGuru; +import com.cloud.offering.NetworkOffering; +import com.cloud.offerings.dao.NetworkOfferingServiceMapDao; +import com.cloud.user.Account; +import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.utils.net.NetUtils; +import com.cloud.vm.NicProfile; +import com.cloud.vm.ReservationContext; +import com.cloud.vm.VirtualMachineProfile; + +/** + * One CloudStack isolated guest network = one ONES tenant. + * + * ONES, not CloudStack, chooses everything about a tenant (VLAN, VNIs, subnet, compute IP pool), + * so the tenant is created when the network is created (design), and the network takes ONES's + * values from the start: + * + * broadcast vlan://<tenant vlanId>: the VLAN ONES trunks to the hypervisors' leaf ports. + * The hypervisor's guest bridge tags it like any CloudStack VLAN network; the leaf + * maps it into the tenant's VRF/VNIs. + * cidr the tenant subnet (ONES vlanSubnetCPU, e.g. 192.1.0.0/16) + * gateway the gateway ONES reports, or one given with createNetwork if it lies in that + * subnet. CloudStack makes createNetwork carry gateway/netmask for an isolated + * network without SourceNat, before ONES has chosen the subnet: a gateway outside + * the subnet ONES assigns is taken as a placeholder, and ONES's gateway is used. + * VM addresses only from the tenant's compute pool (ONES tenantIpPool, e.g. 192.1.64.0/18); + * the rest of the subnet is ONES's (leaf SVIs and the like) + * + * The network's lifecycle maps onto the tenant like this: + * design create the tenant (async; waits for ONES) + * setup record tenant name, VLAN, pool in network_details + * implement put the network on the tenant's VLAN + * allocate pick NIC addresses from the tenant pool + * (element prepare adds a VM's host to the tenant, shared) + * shutdown take the hosts out of the tenant (the network has no running VMs) + * trash delete the tenant + */ +public class OnesGuestNetworkGuru extends GuestNetworkGuru { + + public static final String DETAIL_VLAN = "onesvlan"; + public static final String DETAIL_POOL = "onesippool"; + public static final String DETAIL_L3VNI = "onesl3vni"; + + /** ONES: ^[A-Za-z][A-Za-z0-9_-]{0,11}$ */ + private static final int TENANT_NAME_HEX = 10; + private static final int ONES_TIMEOUT_S = 900; + /** Pool addresses at the bottom (.1 to .9) left to the operator, in pools big enough to spare them. */ + static final int OPERATOR_RESERVED = 9; + + /** Tenant made in design(), waiting for setup() to know the network id. Keyed by CIDR. */ + private static final Map<String, CreateOnesTenantAnswer> PENDING = new ConcurrentHashMap<>(); + private static final Map<String, String> PENDING_NAMES = new ConcurrentHashMap<>(); + + @Inject + protected OnesProviderDao onesProviderDao; + @Inject + protected HostDao hostDao; + @Inject + protected AgentManager agentMgr; + @Inject + protected NetworkDetailsDao networkDetailsDao; + @Inject + protected NetworkOfferingServiceMapDao ntwkOfferingSrvcDao; + + public OnesGuestNetworkGuru() { + super(); + // Its own isolation-method tag: CloudStack picks a guru by the physical network's + // isolation method, so a ONES physical network (isolationmethods=ONES) is never claimed + // by the stock VLAN gurus, and ordinary VLAN physical networks are never claimed by this. + _isolationMethods = new IsolationMethod[]{new IsolationMethod("ONES", OnesElement.AVIZ_ONES.getName())}; + } + + @Override + protected boolean canHandle(final NetworkOffering offering, final NetworkType networkType, final PhysicalNetwork physicalNetwork) { + return networkType == NetworkType.Advanced + && isMyTrafficType(offering.getTrafficType()) + && offering.getGuestType() == GuestType.Isolated + && isMyIsolationMethod(physicalNetwork) + && ntwkOfferingSrvcDao.canProviderSupportServiceInNetworkOffering(offering.getId(), Network.Service.Connectivity, + OnesElement.AVIZ_ONES); + } + + private OnesProviderVO findProviderOrThrow(final long physicalNetworkId) { + List<OnesProviderVO> devices = onesProviderDao.listByPhysicalNetwork(physicalNetworkId); + if (devices.isEmpty()) { + throw new CloudRuntimeException("No Aviz ONES provider is configured on physical network " + physicalNetworkId); + } + return devices.get(0); + } + + private String detail(final long networkId, final String key) { + NetworkDetailVO d = networkDetailsDao.findDetail(networkId, key); + return d != null ? d.getValue() : null; + } + + static String newTenantName() { + return "cs" + UUID.randomUUID().toString().replace("-", "").substring(0, TENANT_NAME_HEX); + } + + @Override + public Network design(final NetworkOffering offering, final DeploymentPlan plan, final Network userSpecified, final String name, + final Long vpcId, final Account owner) { + PhysicalNetworkVO physnet = _physicalNetworkDao.findById(plan.getPhysicalNetworkId()); + if (physnet == null || !canHandle(offering, _dcDao.findById(plan.getDataCenterId()).getNetworkType(), physnet)) { + logger.debug("Aviz ONES guru is not designing network {}", name); + return null; + } + OnesProviderVO device = findProviderOrThrow(physnet.getId()); + + NetworkVO network = (NetworkVO) super.design(offering, plan, userSpecified, name, vpcId, owner); + if (network == null) { + return null; + } + + String tenantName = newTenantName(); + CreateOnesTenantCommand cmd = new CreateOnesTenantCommand(device.getFabricName(), tenantName, + "CloudStack network " + (name != null ? name : ""), -1); + cmd.setWait(ONES_TIMEOUT_S); + Answer raw = agentMgr.easySend(device.getHostId(), cmd); + if (!(raw instanceof CreateOnesTenantAnswer) || !raw.getResult()) { + throw new CloudRuntimeException("Aviz ONES could not create tenant " + tenantName + " for network " + name + ": " + + (raw != null ? raw.getDetails() : "no answer from the Aviz ONES resource")); + } + CreateOnesTenantAnswer t = (CreateOnesTenantAnswer) raw; + String gateway; + try { + gateway = chooseGateway(tenantName, t, userSpecified != null ? userSpecified.getGateway() : null); + } catch (RuntimeException e) { + deleteTenant(device, tenantName); // never leave an orphan tenant in ONES + throw e; + } + String subnet = t.getSubnet(); + network.setBroadcastDomainType(BroadcastDomainType.Vlan); + network.setCidr(subnet); + network.setNetworkCidr(null); + network.setGateway(gateway); + PENDING.put(subnet, t); + PENDING_NAMES.put(subnet, tenantName); Review Comment: Fixed in 4a1aef6687. `NetworkOrchestrator.setupNetwork()` passes `setup()` the same `Network` object `design()` returned, so the pending tenant is now one record (name and answer together) in an identity map keyed by that object. CIDR is no longer the key. Test: `twoNewNetworksWithTheSameCidrEachGetTheirOwnTenant`. ########## plugins/network-elements/aviz-ones/src/main/java/org/apache/cloudstack/network/ones/service/OnesGuestNetworkGuru.java: ########## @@ -0,0 +1,347 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.network.ones.service; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +import javax.inject.Inject; + +import org.apache.cloudstack.network.ones.agent.api.CreateOnesTenantAnswer; +import org.apache.cloudstack.network.ones.agent.api.CreateOnesTenantCommand; +import org.apache.cloudstack.network.ones.agent.api.DeallocateOnesServersCommand; +import org.apache.cloudstack.network.ones.agent.api.DeleteOnesTenantCommand; +import org.apache.cloudstack.network.ones.dao.OnesProviderDao; +import org.apache.cloudstack.network.ones.dao.OnesProviderVO; + +import com.cloud.agent.AgentManager; +import com.cloud.agent.api.Answer; +import com.cloud.dc.DataCenter.NetworkType; +import com.cloud.deploy.DeployDestination; +import com.cloud.deploy.DeploymentPlan; +import com.cloud.exception.InsufficientAddressCapacityException; +import com.cloud.exception.InsufficientVirtualNetworkCapacityException; +import com.cloud.host.dao.HostDao; +import com.cloud.network.Network.GuestType; +import com.cloud.network.Network.State; +import com.cloud.network.Network; +import com.cloud.network.NetworkProfile; +import com.cloud.network.Networks.BroadcastDomainType; +import com.cloud.network.PhysicalNetwork.IsolationMethod; +import com.cloud.network.PhysicalNetwork; +import com.cloud.network.dao.NetworkDetailVO; +import com.cloud.network.dao.NetworkDetailsDao; +import com.cloud.network.dao.NetworkVO; +import com.cloud.network.dao.PhysicalNetworkVO; +import com.cloud.network.guru.GuestNetworkGuru; +import com.cloud.offering.NetworkOffering; +import com.cloud.offerings.dao.NetworkOfferingServiceMapDao; +import com.cloud.user.Account; +import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.utils.net.NetUtils; +import com.cloud.vm.NicProfile; +import com.cloud.vm.ReservationContext; +import com.cloud.vm.VirtualMachineProfile; + +/** + * One CloudStack isolated guest network = one ONES tenant. + * + * ONES, not CloudStack, chooses everything about a tenant (VLAN, VNIs, subnet, compute IP pool), + * so the tenant is created when the network is created (design), and the network takes ONES's + * values from the start: + * + * broadcast vlan://<tenant vlanId>: the VLAN ONES trunks to the hypervisors' leaf ports. + * The hypervisor's guest bridge tags it like any CloudStack VLAN network; the leaf + * maps it into the tenant's VRF/VNIs. + * cidr the tenant subnet (ONES vlanSubnetCPU, e.g. 192.1.0.0/16) + * gateway the gateway ONES reports, or one given with createNetwork if it lies in that + * subnet. CloudStack makes createNetwork carry gateway/netmask for an isolated + * network without SourceNat, before ONES has chosen the subnet: a gateway outside + * the subnet ONES assigns is taken as a placeholder, and ONES's gateway is used. + * VM addresses only from the tenant's compute pool (ONES tenantIpPool, e.g. 192.1.64.0/18); + * the rest of the subnet is ONES's (leaf SVIs and the like) + * + * The network's lifecycle maps onto the tenant like this: + * design create the tenant (async; waits for ONES) + * setup record tenant name, VLAN, pool in network_details + * implement put the network on the tenant's VLAN + * allocate pick NIC addresses from the tenant pool + * (element prepare adds a VM's host to the tenant, shared) + * shutdown take the hosts out of the tenant (the network has no running VMs) + * trash delete the tenant + */ +public class OnesGuestNetworkGuru extends GuestNetworkGuru { + + public static final String DETAIL_VLAN = "onesvlan"; + public static final String DETAIL_POOL = "onesippool"; + public static final String DETAIL_L3VNI = "onesl3vni"; + + /** ONES: ^[A-Za-z][A-Za-z0-9_-]{0,11}$ */ + private static final int TENANT_NAME_HEX = 10; + private static final int ONES_TIMEOUT_S = 900; + /** Pool addresses at the bottom (.1 to .9) left to the operator, in pools big enough to spare them. */ + static final int OPERATOR_RESERVED = 9; + + /** Tenant made in design(), waiting for setup() to know the network id. Keyed by CIDR. */ + private static final Map<String, CreateOnesTenantAnswer> PENDING = new ConcurrentHashMap<>(); + private static final Map<String, String> PENDING_NAMES = new ConcurrentHashMap<>(); + + @Inject + protected OnesProviderDao onesProviderDao; + @Inject + protected HostDao hostDao; + @Inject + protected AgentManager agentMgr; + @Inject + protected NetworkDetailsDao networkDetailsDao; + @Inject + protected NetworkOfferingServiceMapDao ntwkOfferingSrvcDao; + + public OnesGuestNetworkGuru() { + super(); + // Its own isolation-method tag: CloudStack picks a guru by the physical network's + // isolation method, so a ONES physical network (isolationmethods=ONES) is never claimed + // by the stock VLAN gurus, and ordinary VLAN physical networks are never claimed by this. + _isolationMethods = new IsolationMethod[]{new IsolationMethod("ONES", OnesElement.AVIZ_ONES.getName())}; + } + + @Override + protected boolean canHandle(final NetworkOffering offering, final NetworkType networkType, final PhysicalNetwork physicalNetwork) { + return networkType == NetworkType.Advanced + && isMyTrafficType(offering.getTrafficType()) + && offering.getGuestType() == GuestType.Isolated + && isMyIsolationMethod(physicalNetwork) + && ntwkOfferingSrvcDao.canProviderSupportServiceInNetworkOffering(offering.getId(), Network.Service.Connectivity, + OnesElement.AVIZ_ONES); + } + + private OnesProviderVO findProviderOrThrow(final long physicalNetworkId) { + List<OnesProviderVO> devices = onesProviderDao.listByPhysicalNetwork(physicalNetworkId); + if (devices.isEmpty()) { + throw new CloudRuntimeException("No Aviz ONES provider is configured on physical network " + physicalNetworkId); + } + return devices.get(0); + } + + private String detail(final long networkId, final String key) { + NetworkDetailVO d = networkDetailsDao.findDetail(networkId, key); + return d != null ? d.getValue() : null; + } + + static String newTenantName() { + return "cs" + UUID.randomUUID().toString().replace("-", "").substring(0, TENANT_NAME_HEX); + } + + @Override + public Network design(final NetworkOffering offering, final DeploymentPlan plan, final Network userSpecified, final String name, + final Long vpcId, final Account owner) { + PhysicalNetworkVO physnet = _physicalNetworkDao.findById(plan.getPhysicalNetworkId()); + if (physnet == null || !canHandle(offering, _dcDao.findById(plan.getDataCenterId()).getNetworkType(), physnet)) { + logger.debug("Aviz ONES guru is not designing network {}", name); + return null; + } + OnesProviderVO device = findProviderOrThrow(physnet.getId()); + + NetworkVO network = (NetworkVO) super.design(offering, plan, userSpecified, name, vpcId, owner); + if (network == null) { + return null; + } + + String tenantName = newTenantName(); + CreateOnesTenantCommand cmd = new CreateOnesTenantCommand(device.getFabricName(), tenantName, + "CloudStack network " + (name != null ? name : ""), -1); + cmd.setWait(ONES_TIMEOUT_S); + Answer raw = agentMgr.easySend(device.getHostId(), cmd); + if (!(raw instanceof CreateOnesTenantAnswer) || !raw.getResult()) { + throw new CloudRuntimeException("Aviz ONES could not create tenant " + tenantName + " for network " + name + ": " + + (raw != null ? raw.getDetails() : "no answer from the Aviz ONES resource")); + } + CreateOnesTenantAnswer t = (CreateOnesTenantAnswer) raw; + String gateway; + try { + gateway = chooseGateway(tenantName, t, userSpecified != null ? userSpecified.getGateway() : null); + } catch (RuntimeException e) { + deleteTenant(device, tenantName); // never leave an orphan tenant in ONES + throw e; + } + String subnet = t.getSubnet(); + network.setBroadcastDomainType(BroadcastDomainType.Vlan); + network.setCidr(subnet); + network.setNetworkCidr(null); + network.setGateway(gateway); + PENDING.put(subnet, t); + PENDING_NAMES.put(subnet, tenantName); + logger.info("ONES tenant {} for network {}: vlan {}, subnet {}, pool {}, gateway {}, l3vni {}", tenantName, name, + t.getVlanId(), subnet, t.getIpPool(), gateway, t.getL3Vni()); + return network; + } + + /** + * The network's gateway: one given with createNetwork if it lies in the subnet ONES assigned, + * else the gateway ONES reports for the tenant. A requested gateway outside that subnet is the + * placeholder createNetwork needs for an isolated network without SourceNat. + */ + private String chooseGateway(final String tenantName, final CreateOnesTenantAnswer t, final String requested) { + if (t.getVlanId() == null || t.getSubnet() == null || t.getIpPool() == null) { + throw new CloudRuntimeException("Aviz ONES tenant " + tenantName + " has no VLAN, subnet or compute IP pool: " + t.getDetails()); + } + String subnet = t.getSubnet(); + if (requested != null && NetUtils.isIpWithInCidrRange(requested, subnet)) { + return requested; + } + if (requested != null) { + logger.info("Gateway {} is outside the subnet {} ONES assigned to tenant {}: taken as a placeholder, using ONES's gateway {}", + requested, subnet, tenantName, t.getGateway()); + } + String gateway = t.getGateway(); + if (gateway == null || !NetUtils.isIpWithInCidrRange(gateway, subnet)) { + throw new CloudRuntimeException("No usable gateway for ONES tenant " + tenantName + " (subnet " + subnet + + ", ONES gateway " + gateway + "); pass gateway= inside the subnet to createNetwork"); + } + return gateway; + } + + private void deleteTenant(final OnesProviderVO device, final String tenantName) { + DeleteOnesTenantCommand cmd = new DeleteOnesTenantCommand(device.getFabricName(), tenantName); + cmd.setWait(ONES_TIMEOUT_S); + Answer a = agentMgr.easySend(device.getHostId(), cmd); + if (a == null || !a.getResult()) { + logger.error("Could not delete ONES tenant {}: {}", tenantName, a != null ? a.getDetails() : "no answer"); + } + } + + @Override + public void setup(final Network network, final long networkId) { + super.setup(network, networkId); + CreateOnesTenantAnswer t = network.getCidr() != null ? PENDING.remove(network.getCidr()) : null; + String tenantName = network.getCidr() != null ? PENDING_NAMES.remove(network.getCidr()) : null; + if (t == null || tenantName == null) { + return; + } + networkDetailsDao.addDetail(networkId, OnesElement.DETAIL_TENANT_NAME, tenantName, false); + networkDetailsDao.addDetail(networkId, DETAIL_VLAN, String.valueOf(t.getVlanId()), false); + networkDetailsDao.addDetail(networkId, DETAIL_POOL, t.getIpPool(), false); + if (t.getL3Vni() != null) { + networkDetailsDao.addDetail(networkId, DETAIL_L3VNI, String.valueOf(t.getL3Vni()), false); + } + } + + @Override + public Network implement(final Network network, final NetworkOffering offering, final DeployDestination dest, final ReservationContext context) + throws InsufficientVirtualNetworkCapacityException { + assert network.getState() == State.Implementing : "Why are we implementing " + network; + String vlan = detail(network.getId(), DETAIL_VLAN); + if (vlan == null) { + throw new CloudRuntimeException("No ONES VLAN is on record for network " + network.getUuid()); + } + NetworkVO implemented = new NetworkVO(network.getTrafficType(), network.getMode(), BroadcastDomainType.Vlan, network.getNetworkOfferingId(), + State.Allocated, network.getDataCenterId(), network.getPhysicalNetworkId(), offering.isRedundantRouter()); + implemented.setCidr(network.getCidr()); + implemented.setGateway(network.getGateway()); + implemented.setBroadcastUri(BroadcastDomainType.Vlan.toUri(vlan)); + return implemented; + } + + /** NIC addresses come from the tenant's compute pool, never from the rest of the subnet. */ + @Override + public NicProfile allocate(final Network network, final NicProfile nic, final VirtualMachineProfile vm) + throws InsufficientVirtualNetworkCapacityException, InsufficientAddressCapacityException { + String pool = detail(network.getId(), DETAIL_POOL); + if (nic != null && nic.getRequestedIPv4() == null && pool != null && network.getGateway() != null) { + nic.setRequestedIPv4(freeAddress(network, pool)); + } + return super.allocate(network, nic, vm); Review Comment: Fixed in 4a1aef6687. A null NIC profile is replaced by a new one, as the superclass does. A requested address is refused for a user instance if it is outside the recorded pool, and allocation fails if no pool is on record. The router's address is still left to the superclass (gateway or placeholder NIC). Tests: `aNicWithoutAProfileStillGetsAPoolAddress`, `anInstanceMayAskForAPoolAddressOnly`, `theRoutersOwnAddressIsLeftToCloudStack`, `noPoolOnRecordIsAnError`. Verified live: a request for an address in the subnet but outside the pool is refused, and an in-pool request gets that address. -- 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]
