mhkadhum commented on code in PR #12124:
URL: https://github.com/apache/cloudstack/pull/12124#discussion_r2646865355


##########
plugins/storage/object/ECS/src/main/java/org/apache/cloudstack/storage/datastore/driver/EcsObjectStoreDriverImpl.java:
##########
@@ -0,0 +1,1556 @@
+/*
+ * 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.storage.datastore.driver;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Base64;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.concurrent.ConcurrentHashMap;
+
+import javax.inject.Inject;
+import javax.net.ssl.SSLContext;
+
+import org.apache.http.auth.UsernamePasswordCredentials;
+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.HttpPost;
+import org.apache.http.client.methods.HttpPut;
+import org.apache.http.conn.ssl.NoopHostnameVerifier;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.auth.BasicScheme;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.ssl.SSLContextBuilder;
+import org.apache.http.ssl.TrustStrategy;
+import org.apache.http.util.EntityUtils;
+
+import org.apache.cloudstack.context.CallContext;
+import org.apache.cloudstack.engine.subsystem.api.storage.DataStore;
+import org.apache.cloudstack.storage.datastore.db.ObjectStoreDetailsDao;
+import org.apache.cloudstack.storage.object.BaseObjectStoreDriverImpl;
+import org.apache.cloudstack.storage.object.Bucket;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+import com.amazonaws.services.s3.model.AccessControlList;
+import com.amazonaws.services.s3.model.BucketPolicy;
+import com.cloud.agent.api.to.BucketTO;
+import com.cloud.agent.api.to.DataStoreTO;
+import com.cloud.storage.BucketVO;
+import com.cloud.storage.dao.BucketDao;
+import com.cloud.user.Account;
+import com.cloud.user.AccountDetailsDao;
+import com.cloud.user.AccountDetailVO;
+import com.cloud.user.dao.AccountDao;
+import com.cloud.utils.exception.CloudRuntimeException;
+
+public class EcsObjectStoreDriverImpl extends BaseObjectStoreDriverImpl {
+    private static final Logger logger = 
LogManager.getLogger(EcsObjectStoreDriverImpl.class);
+
+    // Object store details keys
+    private static final String MGMT_URL   = "mgmt_url";      // e.g. 
https://ecs-api.example.com
+    private static final String SA_USER    = "sa_user";       // service 
account user
+    private static final String SA_PASS    = "sa_password";   // service 
account password
+    private static final String NAMESPACE  = "namespace";     // e.g. 
cloudstack
+    private static final String INSECURE   = "insecure";      // "true" to 
ignore TLS cert/host
+    private static final String S3_HOST    = "s3_host";       // S3 endpoint 
host (or URL if UI provides it)
+
+    // Per-account keys
+    private static final String AD_KEY_ACCESS = "ecs.accesskey";
+    private static final String AD_KEY_SECRET = "ecs.secretkey";
+
+    // ---- ECS token caching ----
+    private static final long DEFAULT_TOKEN_MAX_AGE_SEC = 300; // fallback if 
header missing
+    private static final long EXPIRY_SKEW_SEC = 30;           // refresh early
+    private static final ConcurrentHashMap<TokenKey, TokenEntry> TOKEN_CACHE = 
new ConcurrentHashMap<>();
+    private static final ConcurrentHashMap<TokenKey, Object> TOKEN_LOCKS = new 
ConcurrentHashMap<>();
+
+    private static final class TokenKey {
+        final String mgmtUrl;
+        final String user;
+        TokenKey(final String mgmtUrl, final String user) {
+            this.mgmtUrl = mgmtUrl;
+            this.user = user;
+        }
+        @Override public boolean equals(final Object o) {
+            if (this == o) return true;
+            if (!(o instanceof TokenKey)) return false;
+            final TokenKey k = (TokenKey) o;
+            return Objects.equals(mgmtUrl, k.mgmtUrl) && Objects.equals(user, 
k.user);
+        }
+        @Override public int hashCode() { return Objects.hash(mgmtUrl, user); }
+    }
+
+    private static final class TokenEntry {
+        final String token;
+        final long expiresAtMs;
+        TokenEntry(final String token, final long expiresAtMs) {
+            this.token = token;
+            this.expiresAtMs = expiresAtMs;
+        }
+        boolean validNow() {
+            return token != null && !token.isBlank() && 
System.currentTimeMillis() < expiresAtMs;
+        }
+    }
+
+    private static final class EcsUnauthorizedException extends 
RuntimeException {
+        EcsUnauthorizedException(final String msg) { super(msg); }
+    }
+
+    @FunctionalInterface
+    private interface WithToken<T> { T run(String token) throws Exception; }
+
+    @Inject private AccountDao accountDao;
+    @Inject private AccountDetailsDao accountDetailsDao;
+    @Inject private BucketDao bucketDao;
+    @Inject private ObjectStoreDetailsDao storeDetailsDao;
+
+    public EcsObjectStoreDriverImpl() { }
+
+    @Override
+    public DataStoreTO getStoreTO(final DataStore store) {
+        return null;
+    }
+
+    // ---------------- create bucket ----------------
+
+    @Override
+    public Bucket createBucket(final Bucket bucket, final boolean objectLock) {
+        final long storeId = bucket.getObjectStoreId();
+        final String name  = bucket.getName();
+
+        if (objectLock) {
+            throw new CloudRuntimeException("Dell ECS doesn't support this 
feature: object locking");
+        }
+
+        final Map<String, String> ds = storeDetailsDao.getDetails(storeId);
+        final EcsCfg cfg = ecsCfgFromDetails(ds, storeId);
+
+        // Resolve owner username for this bucket
+        final BucketVO vo = bucketDao.findById(bucket.getId());
+        final long accountId = vo.getAccountId();
+        final Account acct = accountDao.findById(accountId);
+        if (acct == null) {
+            throw new CloudRuntimeException("ECS createBucket: account not 
found: id=" + accountId);
+        }
+        final String ownerUser = "cs-" + acct.getUuid();
+
+        // Ensure per-account credentials exist (single-key policy with 
adopt-if-exists)
+        ensureAccountUserAndSecret(accountId, ownerUser, cfg.mgmtUrl, 
cfg.saUser, cfg.saPass, cfg.ns, cfg.insecure);
+
+        // Quota from UI (INT GB)
+        Integer quotaGb = null;
+        try {
+            quotaGb = safeIntFromGetter(bucket, "getQuota");
+            if (quotaGb == null) quotaGb = safeIntFromGetter(bucket, 
"getSize");
+        } catch (Throwable ignored) { }
+
+        final int blockSizeGb = quotaGb != null && quotaGb > 0 ? quotaGb : 2;
+        final int notifSizeGb = quotaGb != null && quotaGb > 0 ? quotaGb : 1;
+
+        // Encryption flag from request/VO best-effort
+        boolean encryptionEnabled =
+            getBooleanFlagLoose(bucket, "getEncryption", "isEncryption", 
false) ||
+            getBooleanFlagLoose(bucket, "getEncryptionEnabled", 
"isEncryptionEnabled", false);
+
+        if (!encryptionEnabled && vo != null) {
+            encryptionEnabled =
+                getBooleanFlagLoose(vo, "getEncryption", "isEncryption", 
false) ||
+                getBooleanFlagLoose(vo, "getEncryptionEnabled", 
"isEncryptionEnabled", false);
+        }
+
+        logger.info("ECS createBucket flags for '{}': encryptionEnabled={}", 
name, encryptionEnabled);
+
+        final String createBody =
+            "<object_bucket_create>" +
+            "<blockSize>" + blockSizeGb + "</blockSize>" +
+            "<notificationSize>" + notifSizeGb + "</notificationSize>" +
+            "<name>" + name + "</name>" +
+            "<head_type>s3</head_type>" +
+            "<namespace>" + cfg.ns + "</namespace>" +
+            "<owner>" + ownerUser + "</owner>" +
+            "<is_encryption_enabled>" + (encryptionEnabled ? "true" : "false") 
+ "</is_encryption_enabled>" +
+            "</object_bucket_create>";
+
+        if (logger.isDebugEnabled()) {
+            logger.debug("ECS createBucket XML for '{}': {}", name, 
createBody);
+        }
+
+        try {
+            // Execute mgmt call with cached token (+ refresh on 401, once)
+            mgmtCallWithRetry401(cfg, token -> {
+                try (CloseableHttpClient http = buildHttpClient(cfg.insecure)) 
{
+                    final HttpPost post = new HttpPost(cfg.mgmtUrl + 
"/object/bucket");
+                    post.setHeader("X-SDS-AUTH-TOKEN", token);
+                    post.setHeader("Content-Type", "application/xml");
+                    post.setEntity(new StringEntity(createBody, 
StandardCharsets.UTF_8));
+
+                    try (CloseableHttpResponse resp = http.execute(post)) {
+                        final int status = 
resp.getStatusLine().getStatusCode();
+                        final String respBody = resp.getEntity() != null
+                                ? EntityUtils.toString(resp.getEntity(), 
StandardCharsets.UTF_8)
+                                : "";
+
+                        if (status == 401) {
+                            throw new EcsUnauthorizedException("ECS 
createBucket got 401");
+                        }
+
+                        if (status != 200 && status != 201) {
+                            String reason = "HTTP " + status;
+                            if (status == 400) {
+                                final String lb = respBody == null ? "" : 
respBody.toLowerCase(Locale.ROOT);
+                                if (lb.contains("already exist")
+                                        || lb.contains("already_exists")
+                                        || lb.contains("already-exists")
+                                        || lb.contains("name already in use")
+                                        || lb.contains("bucket exists")
+                                        || lb.contains("duplicate")) {
+                                    reason = "HTTP 400 bucket name already 
exists";
+                                }
+                            }
+                            logger.error("ECS create bucket failed: {} 
body={}", reason, respBody);
+                            throw new CloudRuntimeException("Failed to create 
ECS bucket " + name + ": " + reason);
+                        }
+                    }
+                }
+                return null;
+            });
+
+            // UI URL should show S3 endpoint
+            final String s3Host = resolveS3HostForUI(storeId, ds);
+            final String s3UrlForUI = "https://"; + s3Host + "/" + name;
+
+            logger.info("ECS bucket created: name='{}' owner='{}' ns='{}' 
quota={}GB enc={} (UI URL: {})",
+                    name, ownerUser, cfg.ns, quotaGb != null ? quotaGb : 
blockSizeGb, encryptionEnabled, s3UrlForUI);
+
+            // Persist UI-visible details on the bucket record
+            final String accKey = 
valueOrNull(accountDetailsDao.findDetail(accountId, AD_KEY_ACCESS));
+            final String secKey = 
valueOrNull(accountDetailsDao.findDetail(accountId, AD_KEY_SECRET));
+            if (vo != null) {
+                vo.setBucketURL(s3UrlForUI);
+                if (!isBlank(accKey)) vo.setAccessKey(accKey);
+                if (!isBlank(secKey)) vo.setSecretKey(secKey);
+                bucketDao.update(vo.getId(), vo);
+            }
+
+            return bucket;
+        } catch (CloudRuntimeException e) {
+            throw e;
+        } catch (Exception e) {
+            throw new CloudRuntimeException("Failed to create ECS bucket " + 
name + ": " + e.getMessage(), e);
+        }
+    }
+
+    @Override
+    public boolean createUser(final long accountId, final long storeId) {
+        final Account acct = accountDao.findById(accountId);
+        if (acct == null) throw new CloudRuntimeException("ECS createUser: 
account not found: id=" + accountId);
+
+        final Map<String, String> ds = storeDetailsDao.getDetails(storeId);
+        final EcsCfg cfg = ecsCfgFromDetails(ds, storeId);
+
+        final String username = "cs-" + acct.getUuid();

Review Comment:
   This feature is done and i also updated the FE.
   <img width="1413" height="946" alt="image" 
src="https://github.com/user-attachments/assets/0242556c-2917-416d-8b3d-c27a0348d033";
 />
   



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