jmsperu commented on code in PR #12900:
URL: https://github.com/apache/cloudstack/pull/12900#discussion_r4333499253


##########
plugins/backup/nas/src/main/java/org/apache/cloudstack/backup/InfrastructureBackupTask.java:
##########
@@ -0,0 +1,428 @@
+// 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.backup;
+
+import com.cloud.utils.db.DbProperties;
+import com.cloud.utils.db.GlobalLock;
+
+import org.apache.cloudstack.managed.context.ManagedContextRunnable;
+import org.apache.cloudstack.poll.BackgroundPollTask;
+import org.apache.cloudstack.utils.identity.ManagementServerNode;
+import org.apache.logging.log4j.Logger;
+import org.apache.logging.log4j.LogManager;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.Writer;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.nio.file.attribute.PosixFilePermission;
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.EnumSet;
+import java.util.Properties;
+import java.util.concurrent.TimeUnit;
+import java.util.zip.GZIPOutputStream;
+
+/**
+ * Scheduled task that backs up CloudStack infrastructure to NAS storage:
+ * <ul>
+ *   <li>MySQL databases (cloud, cloud_usage if enabled)</li>
+ *   <li>Management server configuration files</li>
+ *   <li>Agent configuration files</li>
+ *   <li>SSL certificates and keystores</li>
+ * </ul>
+ *
+ * Database credentials come from the management server's db.properties (via 
{@link DbProperties},
+ * which decrypts ENC(...) values when db.properties encryption is in use).
+ * Backups are stored under {nasBackupPath}/infra-backup/{timestamp}/ with
+ * automatic retention management.
+ */
+public class InfrastructureBackupTask extends ManagedContextRunnable 
implements BackgroundPollTask {
+
+    private static final Logger LOG = 
LogManager.getLogger(InfrastructureBackupTask.class);
+
+    private static final String MANAGEMENT_CONFIG_PATH = 
"/etc/cloudstack/management";
+    private static final String AGENT_CONFIG_PATH = "/etc/cloudstack/agent";
+    private static final String SSL_CERT_PATH = 
"/etc/cloudstack/management/cert";
+
+    /** 24 hours in milliseconds */
+    private static final long DAILY_INTERVAL_MS = 86400L * 1000L;
+
+    @Override
+    public Long getDelay() {
+        return DAILY_INTERVAL_MS;
+    }
+
+    /** Indirection so tests can override without standing up the ConfigDepot. 
*/
+    protected boolean isEnabled() {
+        return 
Boolean.TRUE.equals(NASBackupProvider.NASInfraBackupEnabled.value());
+    }
+
+    protected String getBackupLocation() {
+        return NASBackupProvider.NASInfraBackupLocation.value();
+    }
+
+    protected int getRetentionCount() {
+        return NASBackupProvider.NASInfraBackupRetention.value();
+    }
+
+    protected boolean isDatabaseIncluded() {
+        return 
Boolean.TRUE.equals(NASBackupProvider.NASInfraBackupIncludeDatabase.value());
+    }
+
+    protected boolean isUsageDbIncluded() {
+        return 
Boolean.TRUE.equals(NASBackupProvider.NASInfraBackupUsageDb.value());
+    }
+
+    @Override
+    protected void runInContext() {
+        if (!isEnabled()) {
+            LOG.debug("Infrastructure backup is disabled 
(nas.infra.backup.enabled=false)");
+            return;
+        }
+
+        String nasBackupPath = getBackupLocation();
+        if (nasBackupPath == null || nasBackupPath.isEmpty()) {
+            LOG.error("Infrastructure backup location not configured 
(nas.infra.backup.location is empty)");
+            return;
+        }
+
+        int retentionCount = getRetentionCount();
+        boolean includeDatabase = isDatabaseIncluded();
+        boolean includeUsageDb = isUsageDbIncluded();
+
+        String timestamp = 
LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss"));
+        String infraBackupRoot = nasBackupPath + "/infra-backup/" + 
getManagementServerLabel();
+        String backupDir = infraBackupRoot + "/" + timestamp;
+
+        LOG.info("Starting infrastructure backup to {} (database included: 
{})", backupDir, includeDatabase);
+
+        // Cluster-wide lock: in multi-management-server deployments only one 
MS should run the
+        // infrastructure backup at a time, otherwise they would write/delete 
concurrently in the
+        // same NAS infra-backup path (duplicate backups, retention races, 
accidental deletes).
+        GlobalLock lock = acquireRunLock();
+        if (lock == null) {
+            LOG.info("Another management server is performing the 
infrastructure backup; skipping this run");
+            return;
+        }
+
+        try {
+            File dir = new File(backupDir);
+            if (!dir.exists() && !dir.mkdirs()) {
+                LOG.error(describeDirectoryCreationFailure(backupDir, 
nasBackupPath));
+                return;
+            }
+
+            backupDatabases(backupDir, timestamp, includeDatabase, 
includeUsageDb);
+            backupDirectory(MANAGEMENT_CONFIG_PATH, backupDir, 
"management-config");
+            backupDirectoryIfPresent(AGENT_CONFIG_PATH, backupDir, 
"agent-config");
+            backupDirectoryIfPresent(SSL_CERT_PATH, backupDir, "ssl-certs");
+            cleanupOldBackups(infraBackupRoot, retentionCount);

Review Comment:
   Good catch, thanks. Fixed in b99a0c25e9: each step now reports success, and 
a run where the DB dump or any archive failed is removed and skips retention 
entirely. A complete run writes a `BACKUP_COMPLETE` marker last, and retention 
only counts marked sets, so failed or partial runs can never push good backups 
out. Unmarked leftovers (a crash mid-run, or backups from before this change) 
are only removed once a full window of complete sets exists and they are older 
than the oldest one kept. Added tests for a failed dump, a failed archive and a 
week of failed runs keeping every good backup.



##########
plugins/backup/nas/src/main/java/org/apache/cloudstack/backup/InfrastructureBackupTask.java:
##########
@@ -0,0 +1,428 @@
+// 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.backup;
+
+import com.cloud.utils.db.DbProperties;
+import com.cloud.utils.db.GlobalLock;
+
+import org.apache.cloudstack.managed.context.ManagedContextRunnable;
+import org.apache.cloudstack.poll.BackgroundPollTask;
+import org.apache.cloudstack.utils.identity.ManagementServerNode;
+import org.apache.logging.log4j.Logger;
+import org.apache.logging.log4j.LogManager;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.Writer;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.nio.file.attribute.PosixFilePermission;
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.EnumSet;
+import java.util.Properties;
+import java.util.concurrent.TimeUnit;
+import java.util.zip.GZIPOutputStream;
+
+/**
+ * Scheduled task that backs up CloudStack infrastructure to NAS storage:
+ * <ul>
+ *   <li>MySQL databases (cloud, cloud_usage if enabled)</li>
+ *   <li>Management server configuration files</li>
+ *   <li>Agent configuration files</li>
+ *   <li>SSL certificates and keystores</li>
+ * </ul>
+ *
+ * Database credentials come from the management server's db.properties (via 
{@link DbProperties},
+ * which decrypts ENC(...) values when db.properties encryption is in use).
+ * Backups are stored under {nasBackupPath}/infra-backup/{timestamp}/ with
+ * automatic retention management.
+ */
+public class InfrastructureBackupTask extends ManagedContextRunnable 
implements BackgroundPollTask {
+
+    private static final Logger LOG = 
LogManager.getLogger(InfrastructureBackupTask.class);
+
+    private static final String MANAGEMENT_CONFIG_PATH = 
"/etc/cloudstack/management";
+    private static final String AGENT_CONFIG_PATH = "/etc/cloudstack/agent";
+    private static final String SSL_CERT_PATH = 
"/etc/cloudstack/management/cert";
+
+    /** 24 hours in milliseconds */
+    private static final long DAILY_INTERVAL_MS = 86400L * 1000L;
+
+    @Override
+    public Long getDelay() {
+        return DAILY_INTERVAL_MS;
+    }
+
+    /** Indirection so tests can override without standing up the ConfigDepot. 
*/
+    protected boolean isEnabled() {
+        return 
Boolean.TRUE.equals(NASBackupProvider.NASInfraBackupEnabled.value());
+    }
+
+    protected String getBackupLocation() {
+        return NASBackupProvider.NASInfraBackupLocation.value();
+    }
+
+    protected int getRetentionCount() {
+        return NASBackupProvider.NASInfraBackupRetention.value();
+    }
+
+    protected boolean isDatabaseIncluded() {
+        return 
Boolean.TRUE.equals(NASBackupProvider.NASInfraBackupIncludeDatabase.value());
+    }
+
+    protected boolean isUsageDbIncluded() {
+        return 
Boolean.TRUE.equals(NASBackupProvider.NASInfraBackupUsageDb.value());
+    }
+
+    @Override
+    protected void runInContext() {
+        if (!isEnabled()) {
+            LOG.debug("Infrastructure backup is disabled 
(nas.infra.backup.enabled=false)");
+            return;
+        }
+
+        String nasBackupPath = getBackupLocation();
+        if (nasBackupPath == null || nasBackupPath.isEmpty()) {
+            LOG.error("Infrastructure backup location not configured 
(nas.infra.backup.location is empty)");
+            return;
+        }
+
+        int retentionCount = getRetentionCount();
+        boolean includeDatabase = isDatabaseIncluded();
+        boolean includeUsageDb = isUsageDbIncluded();
+
+        String timestamp = 
LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss"));
+        String infraBackupRoot = nasBackupPath + "/infra-backup/" + 
getManagementServerLabel();
+        String backupDir = infraBackupRoot + "/" + timestamp;
+
+        LOG.info("Starting infrastructure backup to {} (database included: 
{})", backupDir, includeDatabase);
+
+        // Cluster-wide lock: in multi-management-server deployments only one 
MS should run the
+        // infrastructure backup at a time, otherwise they would write/delete 
concurrently in the
+        // same NAS infra-backup path (duplicate backups, retention races, 
accidental deletes).
+        GlobalLock lock = acquireRunLock();
+        if (lock == null) {
+            LOG.info("Another management server is performing the 
infrastructure backup; skipping this run");
+            return;
+        }
+
+        try {
+            File dir = new File(backupDir);
+            if (!dir.exists() && !dir.mkdirs()) {
+                LOG.error(describeDirectoryCreationFailure(backupDir, 
nasBackupPath));
+                return;
+            }
+
+            backupDatabases(backupDir, timestamp, includeDatabase, 
includeUsageDb);
+            backupDirectory(MANAGEMENT_CONFIG_PATH, backupDir, 
"management-config");

Review Comment:
   Yes, agreed. In b99a0c25e9 the backup directories are created 0700 and the 
dumps, archives and marker 0600, with the mode set at creation (the files are 
created owner-only before mysqldump, the gzip or tar write into them), so there 
is no window where they are readable by others. They are owned by the user the 
management server runs as. Existing `infra-backup` directories from earlier 
runs are tightened to 0700 too, and a file system without POSIX permissions 
logs a warning asking to restrict the location on the NAS. Tests check the 
modes.



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