Pearl1594 commented on code in PR #12900: URL: https://github.com/apache/cloudstack/pull/12900#discussion_r3969324077
########## plugins/backup/nas/src/main/java/org/apache/cloudstack/backup/InfrastructureBackupTask.java: ########## @@ -0,0 +1,414 @@ +// 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.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.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileReader; +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 are read from /etc/cloudstack/management/db.properties. + * 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 DB_PROPERTIES_PATH = "/etc/cloudstack/management/db.properties"; + 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("Failed to create backup directory: {}", backupDir); + 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); + + LOG.info("Infrastructure backup completed successfully: {}", backupDir); + + } catch (Exception e) { + LOG.error("Infrastructure backup failed: {}", e.getMessage(), e); + } finally { + releaseRunLock(lock); + } + } + + /** + * Name of the sub-directory that keeps this management server's backups apart from those of the + * other servers in the cluster. Management configs and certificates are per server, so they must + * not overwrite each other, and the retention count applies per server. Uses the host name and + * falls back to the management server id. + */ + protected String getManagementServerLabel() { + String label = null; + try { + label = InetAddress.getLocalHost().getHostName(); + } catch (UnknownHostException e) { + LOG.debug("Could not determine the local host name for the infrastructure backup directory: {}", e.getMessage()); + } + if (label == null || label.isBlank()) { + label = "ms-" + ManagementServerNode.getManagementServerId(); + } + return label.replaceAll("[^A-Za-z0-9._-]", "_"); + } + + /** + * Dumps the cloud database, and the usage database when requested, into {@code backupDir}. + * The database component is opt-in ({@code nas.infra.backup.include.database}): production + * deployments typically run their own mysqldump jobs and leave it off; it exists for small and + * edge deployments that want unified disaster recovery on the same NAS as their VM backups. + */ + protected void backupDatabases(String backupDir, String timestamp, boolean includeDatabase, boolean includeUsageDb) { + if (!includeDatabase) { + LOG.debug("Database backup skipped (nas.infra.backup.include.database=false). " + + "Manage DB backups externally for production deployments."); + return; + } + Properties dbProps = loadDbProperties(); Review Comment: When the DB password is encrypted in db.properties file, backup of DB fails as there's no decryption logic in place. Worth checking if we could use the `com.cloud.utils.db.DbProperties.getDbProperties();` which has the decryption logic. I saw the following error in the MS log: ``` ... 2026-09-09 13:34:00,736 ERROR [o.a.c.b.InfrastructureBackupTask] (BackgroundTaskPollManager-6:[ctx-cdc8ed08]) (logid:937a2066) Database backup failed for cloud with exit code 2 ... 2026-09-09 13:34:00,807 ERROR [o.a.c.b.InfrastructureBackupTask] (BackgroundTaskPollManager-6:[ctx-cdc8ed08]) (logid:937a2066) Database backup failed for cloud_usage with exit code 2 ``` Also noticed this in `/var/log/cloudstack/management/management-server.err`: ``` mysqldump: Got error: 1045: Access denied for user 'cloud'@'10.0.33.135' (using password: YES) when trying to connect mysqldump: Got error: 1045: Access denied for user 'cloud'@'10.0.33.135' (using password: YES) when trying to connect ``` ########## plugins/backup/nas/src/main/java/org/apache/cloudstack/backup/NASBackupProvider.java: ########## @@ -85,6 +86,59 @@ public class NASBackupProvider extends AdapterBase implements BackupProvider, Co true, BackupFrameworkEnabled.key()); + static final ConfigKey<Boolean> NASInfraBackupEnabled = new ConfigKey<>("Advanced", Boolean.class, + "nas.infra.backup.enabled", + "false", + "Enable automated infrastructure backup to NAS storage. When enabled, the management " + + "server will perform a daily backup of CloudStack configuration files and SSL " + + "certificates to the configured NAS location. The CloudStack database is NOT included " + + "by default — for production deployments, manage database backups externally (e.g. via " + + "a cron job running mysqldump). To opt in to bundling the database with this backup " + + "(useful only for small / edge / single-MS deployments without separate ops tooling), " + + "also set nas.infra.backup.include.database=true.", + true, + ConfigKey.Scope.Global, + BackupFrameworkEnabled.key()); + + static final ConfigKey<Boolean> NASInfraBackupIncludeDatabase = new ConfigKey<>("Advanced", Boolean.class, + "nas.infra.backup.include.database", + "false", + "Include the CloudStack database in the daily infrastructure backup. Defaults to false " + + "because production deployments typically manage DB backups via external tooling (e.g. " + + "cron + mysqldump, replication, dedicated backup appliance) and are better served " + + "doing so. Only set true when you want one-knob disaster recovery for a small/edge " + + "deployment and the same NAS that already holds your VM backups is an acceptable " + + "target. Has no effect unless nas.infra.backup.enabled is also true.", + true, + ConfigKey.Scope.Global, + BackupFrameworkEnabled.key()); + + static final ConfigKey<String> NASInfraBackupLocation = new ConfigKey<>("Advanced", String.class, + "nas.infra.backup.location", + "", + "NAS mount path where infrastructure backups are stored (e.g. /mnt/nas-backup). " + + "Backups will be written to {location}/infra-backup/{timestamp}/.", + true, + ConfigKey.Scope.Global, + BackupFrameworkEnabled.key()); + + static final ConfigKey<Integer> NASInfraBackupRetention = new ConfigKey<>("Advanced", Integer.class, + "nas.infra.backup.retention", + "7", + "Number of infrastructure backup sets to retain. Older backups are automatically removed.", + true, + ConfigKey.Scope.Global, + BackupFrameworkEnabled.key()); + + static final ConfigKey<Boolean> NASInfraBackupUsageDb = new ConfigKey<>("Advanced", Boolean.class, + "nas.infra.backup.include.usage.db", + "true", Review Comment: Is this supposed to be true by default? -- 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]
