The MySQL Backup Tool provides a comprehensive set of APIs for managing MySQL database backups through a distributed client-server architecture. This document covers all public interfaces, models, and services available in the system.
- Core Services
- Backup Management
- File Operations
- Notification System
- Scheduling
- Security
- Data Models
- Error Handling
Manages MySQL instance lifecycle operations including starting, stopping, and verifying database connections.
Stops a MySQL service instance.
Parameters:
serviceName(string): Name of the MySQL service to stop
Returns: Task<bool> - True if the service was successfully stopped
Example:
var mysqlManager = serviceProvider.GetService<IMySQLManager>();
bool stopped = await mysqlManager.StopInstanceAsync("MySQL80");Starts a MySQL service instance.
Parameters:
serviceName(string): Name of the MySQL service to start
Returns: Task<bool> - True if the service was successfully started
Verifies that a MySQL instance is available and accepting connections.
Parameters:
connection(MySQLConnectionInfo): Connection information for the MySQL instance
Returns: Task<bool> - True if the instance is available
Verifies MySQL instance availability with configurable timeout.
Parameters:
connection(MySQLConnectionInfo): Connection informationtimeoutSeconds(int): Connection timeout in seconds
Returns: Task<bool> - True if the instance is available
Handles file compression operations for backup files.
CompressDirectoryAsync(string sourcePath, string targetPath, IProgress<CompressionProgress>? progress = null)
Compresses a directory into a zip file.
Parameters:
sourcePath(string): Path to the directory to compresstargetPath(string): Path where the compressed file should be createdprogress(IProgress?, optional): Progress reporter
Returns: Task<string> - Path to the created compressed file
Example:
var compressionService = serviceProvider.GetService<ICompressionService>();
var progress = new Progress<CompressionProgress>(p =>
Console.WriteLine($"Compression: {p.PercentComplete:F1}%"));
string compressedFile = await compressionService.CompressDirectoryAsync(
@"C:\MySQL\Data",
@"C:\Backups\backup.zip",
progress);Cleans up temporary files created during compression.
Parameters:
filePath(string): Path to the file to clean up
Returns: Task
Manages file transfer operations between client and server.
TransferFileAsync(string filePath, TransferConfig config, CancellationToken cancellationToken = default)
Transfers a file to a remote server.
Parameters:
filePath(string): Path to the file to transferconfig(TransferConfig): Transfer configuration settingscancellationToken(CancellationToken, optional): Cancellation token
Returns: Task<TransferResult> - Result of the transfer operation
Resumes an interrupted file transfer.
Parameters:
resumeToken(string): Token identifying the interrupted transfercancellationToken(CancellationToken, optional): Cancellation token
Returns: Task<TransferResult> - Result of the resumed transfer
ResumeTransferAsync(string resumeToken, string filePath, TransferConfig config, CancellationToken cancellationToken = default)
Resumes an interrupted file transfer with full context.
Parameters:
resumeToken(string): Token identifying the interrupted transferfilePath(string): Path to the file to transferconfig(TransferConfig): Transfer configuration settingscancellationToken(CancellationToken, optional): Cancellation token
Returns: Task<TransferResult> - Result of the resumed transfer
Manages backup scheduling with cron expression support.
Starts the backup scheduler service.
Stops the backup scheduler service.
Adds or updates a schedule configuration.
Parameters:
scheduleConfig(ScheduleConfiguration): Schedule configuration to add or update
Returns: Task<ScheduleConfiguration> - The saved schedule configuration
Removes a schedule configuration.
Parameters:
scheduleId(int): ID of the schedule to remove
Gets all schedule configurations.
Returns: Task<IEnumerable<ScheduleConfiguration>> - List of all schedules
Gets schedule configurations for a specific backup configuration.
Parameters:
backupConfigId(int): Backup configuration ID
Returns: Task<List<ScheduleConfiguration>> - List of schedule configurations
Enables or disables a schedule.
Parameters:
scheduleId(int): Schedule IDenabled(bool): Whether to enable or disable the schedule
Gets the next scheduled backup time across all schedules.
Returns: Task<DateTime?> - The next scheduled backup time, or null if no schedules are enabled
Manually triggers a scheduled backup.
Parameters:
scheduleId(int): Schedule ID to trigger
Validates a schedule configuration.
Parameters:
scheduleConfig(ScheduleConfiguration): Schedule configuration to validate
Returns: Task<(bool IsValid, List<string> Errors)> - Validation result
Manages backup retention policies and automated cleanup.
Executes all enabled retention policies.
Returns: Task<RetentionExecutionResult> - Execution result
Applies a specific retention policy.
Parameters:
policy(RetentionPolicy): The retention policy to apply
Returns: Task<RetentionExecutionResult> - Execution result
Creates a new retention policy with validation.
Parameters:
policy(RetentionPolicy): The retention policy to create
Returns: Task<RetentionPolicy> - The created policy
Updates an existing retention policy.
Parameters:
policy(RetentionPolicy): The retention policy to update
Returns: Task<RetentionPolicy> - The updated policy
Deletes a retention policy.
Parameters:
policyId(int): ID of the policy to delete
Returns: Task<bool> - True if deletion was successful
Gets all retention policies.
Returns: Task<IEnumerable<RetentionPolicy>> - All retention policies
Gets all enabled retention policies.
Returns: Task<IEnumerable<RetentionPolicy>> - Enabled retention policies
Gets a retention policy by ID.
Parameters:
policyId(int): Policy ID
Returns: Task<RetentionPolicy?> - The policy, or null if not found
Gets a retention policy by name.
Parameters:
name(string): Policy name
Returns: Task<RetentionPolicy?> - The policy, or null if not found
Enables a retention policy.
Parameters:
policyId(int): Policy ID
Returns: Task<bool> - True if successful
Disables a retention policy.
Parameters:
policyId(int): Policy ID
Returns: Task<bool> - True if successful
Gets retention policy recommendations based on current backup patterns.
Returns: Task<List<RetentionPolicy>> - Recommended policies
Validates a retention policy configuration.
Parameters:
policy(RetentionPolicy): Policy to validate
Returns: Task<(bool IsValid, List<string> Errors)> - Validation result
Estimates the impact of applying a retention policy.
Parameters:
policy(RetentionPolicy): Policy to analyze
Returns: Task<RetentionImpactEstimate> - Impact estimate
Provides file encryption and decryption capabilities using AES-256.
EncryptAsync(string inputPath, string outputPath, string password, CancellationToken cancellationToken = default)
Encrypts a file using AES-256 encryption.
Parameters:
inputPath(string): Path to the file to encryptoutputPath(string): Path where the encrypted file will be savedpassword(string): Password for encryptioncancellationToken(CancellationToken, optional): Cancellation token
Returns: Task<EncryptionMetadata> - Encryption metadata
Example:
var encryptionService = serviceProvider.GetService<IEncryptionService>();
var metadata = await encryptionService.EncryptAsync(
@"C:\Backups\backup.zip",
@"C:\Backups\backup.zip.enc",
"SecurePassword123!");DecryptAsync(string inputPath, string outputPath, string password, CancellationToken cancellationToken = default)
Decrypts a file that was encrypted with AES-256.
Parameters:
inputPath(string): Path to the encrypted fileoutputPath(string): Path where the decrypted file will be savedpassword(string): Password for decryptioncancellationToken(CancellationToken, optional): Cancellation token
Returns: Task - Async operation
Validates if the provided password can decrypt the encrypted file.
Parameters:
encryptedFilePath(string): Path to the encrypted filepassword(string): Password to validate
Returns: Task<bool> - True if password is correct
Gets metadata from an encrypted file.
Parameters:
encryptedFilePath(string): Path to the encrypted file
Returns: Task<EncryptionMetadata> - Encryption metadata
Generates a secure random password.
Parameters:
length(int, optional): Length of the password (default: 32)
Returns: string - Secure random password
Provides backup file validation and integrity checking.
Validates a backup file for integrity and completeness.
Parameters:
filePath(string): Path to the backup file to validatecancellationToken(CancellationToken, optional): Cancellation token
Returns: Task<FileValidationResult> - Validation result with details
ValidateIntegrityAsync(string filePath, string expectedChecksum, ChecksumAlgorithm algorithm = ChecksumAlgorithm.SHA256)
Validates file integrity using checksum comparison.
Parameters:
filePath(string): Path to the file to validateexpectedChecksum(string): Expected checksum valuealgorithm(ChecksumAlgorithm, optional): Checksum algorithm to use
Returns: Task<bool> - True if checksums match
CalculateChecksumAsync(string filePath, ChecksumAlgorithm algorithm = ChecksumAlgorithm.SHA256, CancellationToken cancellationToken = default)
Calculates checksum for a file.
Parameters:
filePath(string): Path to the filealgorithm(ChecksumAlgorithm, optional): Checksum algorithm to usecancellationToken(CancellationToken, optional): Cancellation token
Returns: Task<string> - Calculated checksum as hex string
Generates a comprehensive validation report for a backup file.
Parameters:
filePath(string): Path to the backup filecancellationToken(CancellationToken, optional): Cancellation token
Returns: Task<ValidationReport> - Detailed validation report
Validates that a backup file can be successfully decompressed.
Parameters:
filePath(string): Path to the compressed backup filecancellationToken(CancellationToken, optional): Cancellation token
Returns: Task<bool> - True if file can be decompressed
ValidateEncryptionAsync(string filePath, string password, CancellationToken cancellationToken = default)
Validates that an encrypted backup file can be decrypted with the provided password.
Parameters:
filePath(string): Path to the encrypted backup filepassword(string): Password for decryptioncancellationToken(CancellationToken, optional): Cancellation token
Returns: Task<bool> - True if file can be decrypted
Provides email notification capabilities with SMTP support.
Gets the current SMTP configuration.
Type: SmtpConfig
Sends a single email message asynchronously.
Parameters:
message(EmailMessage): The email message to sendcancellationToken(CancellationToken, optional): Cancellation token
Returns: Task<bool> - True if the email was sent successfully
Exceptions:
ArgumentNullException: Thrown when message is nullInvalidOperationException: Thrown when SMTP configuration is invalid
Example:
var notificationService = serviceProvider.GetService<INotificationService>();
var message = new EmailMessage
{
To = "admin@example.com",
Subject = "Backup Completed Successfully",
Body = "The MySQL backup completed successfully at " + DateTime.Now,
IsHtml = false
};
bool sent = await notificationService.SendEmailAsync(message);SendBulkEmailAsync(IEnumerable<EmailMessage> messages, CancellationToken cancellationToken = default)
Sends multiple email messages in bulk.
Parameters:
messages(IEnumerable): Collection of email messages to sendcancellationToken(CancellationToken, optional): Cancellation token
Returns: Task<Dictionary<string, bool>> - Dictionary mapping message IDs to their send success status
Gets the delivery status of a specific notification.
Parameters:
notificationId(string): Unique identifier of the notificationcancellationToken(CancellationToken, optional): Cancellation token
Returns: Task<NotificationStatus?> - The current status, or null if not found
Retrieves all available email templates.
Returns: Task<IEnumerable<EmailTemplate>> - Collection of available email templates
Retrieves email templates by category.
Parameters:
category(string): Template category to filter by
Returns: Task<IEnumerable<EmailTemplate>> - Collection of email templates in the specified category
Gets a specific email template by name.
Parameters:
templateName(string): Name of the template to retrieve
Returns: Task<EmailTemplate?> - The email template, or null if not found
Tests the SMTP connection with the provided configuration.
Parameters:
config(SmtpConfig): SMTP configuration to test
Returns: Task<bool> - True if the connection test succeeds
CreateEmailFromTemplateAsync(string templateName, string recipient, Dictionary<string, object> variables, CancellationToken cancellationToken = default)
Creates an email message from a template with variable substitution.
Parameters:
templateName(string): Name of the template to userecipient(string): Recipient email addressvariables(Dictionary<string, object>): Dictionary of variables to substitute in the template
Returns: Task<EmailMessage?> - The created email message, or null if template not found
Updates the SMTP configuration.
Parameters:
config(SmtpConfig): New SMTP configuration
GetStatisticsAsync(DateTime? fromDate = null, DateTime? toDate = null, CancellationToken cancellationToken = default)
Gets statistics about notification delivery.
Parameters:
fromDate(DateTime?, optional): Start date for statisticstoDate(DateTime?, optional): End date for statisticscancellationToken(CancellationToken, optional): Cancellation token
Returns: Task<NotificationStatistics> - Notification delivery statistics
Backup schedules use cron expressions for flexible timing configuration.
The system supports standard cron expressions with the following format:
* * * * * *
│ │ │ │ │ │
│ │ │ │ │ └─── Day of Week (0-7, Sunday = 0 or 7)
│ │ │ │ └───── Month (1-12)
│ │ │ └─────── Day of Month (1-31)
│ │ └───────── Hour (0-23)
│ └─────────── Minute (0-59)
└───────────── Second (0-59)
0 0 2 * * *- Daily at 2:00 AM0 0 2 * * 0- Weekly on Sunday at 2:00 AM0 0 2 1 * *- Monthly on the 1st at 2:00 AM0 */30 * * * *- Every 30 minutes0 0 */6 * * *- Every 6 hours
The system provides several security-related interfaces:
Handles user authentication and session management.
Provides AES-256 encryption for backup files with the following security features:
- Key Derivation: PBKDF2 with configurable iterations (default: 100,000)
- Salt Generation: Cryptographically secure random salt for each encryption
- IV Generation: Unique initialization vector for each encryption
- Secure Memory: Proper cleanup of sensitive data in memory
- Password Strength: Use strong passwords for encryption (minimum 12 characters)
- Key Storage: Store encryption passwords securely, never in plain text
- Network Security: Use TLS for all network communications
- File Permissions: Ensure backup files have appropriate access restrictions
- Audit Logging: Enable comprehensive logging for security events
Represents a complete backup job configuration.
Key Properties:
Id(int): Unique identifierName(string): Configuration name (1-100 characters, alphanumeric + spaces/hyphens/underscores)MySQLConnection(MySQLConnectionInfo): Database connection detailsDataDirectoryPath(string): Path to MySQL data directoryServiceName(string): MySQL service nameTargetServer(ServerEndpoint): Destination server informationTargetDirectory(string): Backup destination directoryNamingStrategy(FileNamingStrategy): File naming configurationIsActive(bool): Whether the configuration is activeCreatedAt(DateTime): Creation timestamp
Validation:
- Implements
IValidatableObjectfor comprehensive validation - Validates directory paths and accessibility
- Checks connection parameters
- Ensures naming strategy validity
Database connection configuration.
Key Properties:
Server(string): MySQL server hostname/IPPort(int): MySQL server port (default: 3306)Username(string): Database usernamePassword(string): Database password (encrypted storage recommended)Database(string): Target database nameConnectionTimeout(int): Connection timeout in seconds
Target server configuration for backup storage.
Key Properties:
IPAddress(string): Server IP addressPort(int): Server portProtocol(string): Transfer protocol (TCP, HTTP, etc.)AuthenticationRequired(bool): Whether authentication is requiredCredentials(NetworkCredential): Authentication credentials
Represents an email notification.
Key Properties:
Id(string): Unique message identifierTo(string): Recipient email addressSubject(string): Email subject (max 200 characters)Body(string): Email body content (max 10,000 characters)IsHtml(bool): Whether body is HTML formattedAttachments(List): File attachment pathsHeaders(Dictionary<string, string>): Custom email headersPriority(EmailPriority): Email priority levelCreatedAt(DateTime): Creation timestamp
SMTP server configuration.
Key Properties:
Host(string): SMTP server hostnamePort(int): SMTP server port (default: 587)EnableSsl(bool): Whether to use SSL/TLSUsername(string): SMTP authentication usernamePassword(string): SMTP authentication passwordFromAddress(string): Sender email addressFromName(string): Sender display nameTimeoutSeconds(int): Connection timeout (5-300 seconds)
Email template for notifications.
Key Properties:
Name(string): Template identifierDescription(string): Template descriptionSubject(string): Email subject templateHtmlBody(string): HTML body templateTextBody(string): Plain text body templateRequiredVariables(List): Required template variablesCategory(string): Template categoryIsActive(bool): Whether template is active
Metadata for encrypted files.
Key Properties:
Algorithm(string): Encryption algorithm (default: "AES-256-CBC")KeyDerivation(string): Key derivation function (default: "PBKDF2")Iterations(int): PBKDF2 iterations (default: 100,000)Salt(string): Base64-encoded saltIV(string): Base64-encoded initialization vectorEncryptedAt(DateTime): Encryption timestampOriginalSize(long): Original file sizeOriginalChecksum(string): SHA256 checksum of original fileVersion(int): Encryption format version
Configuration for encryption operations.
Key Properties:
Password(string): Encryption passwordKeySize(int): Key size in bits (default: 256)Iterations(int): PBKDF2 iterations (default: 100,000)SecureDelete(bool): Whether to securely delete original fileBufferSize(int): Streaming buffer size (default: 64KB)CompressBeforeEncryption(bool): Whether to compress before encrypting
Progress information for compression operations.
Key Properties:
PercentComplete(double): Completion percentage (0-100)BytesProcessed(long): Bytes processed so farTotalBytes(long): Total bytes to processCurrentFile(string): Currently processing fileEstimatedTimeRemaining(TimeSpan?): Estimated time remaining
Result of a file transfer operation.
Key Properties:
Success(bool): Whether transfer was successfulBytesTransferred(long): Number of bytes transferredDuration(TimeSpan): Transfer durationAverageSpeed(double): Average transfer speed (bytes/second)ResumeToken(string): Token for resuming interrupted transfersErrorMessage(string): Error message if transfer failed
The system uses a structured exception hierarchy for comprehensive error handling:
Base exception class for all backup-related errors.
Properties:
OperationId(string): Unique identifier for the operationTimestamp(DateTime): When the error occurredContext(Dictionary<string, object>): Additional error context
Thrown when network retry attempts are exhausted.
Properties:
OperationName(string): Name of the failed operationAttemptsExhausted(int): Number of retry attempts madeTotalDuration(TimeSpan): Total time spent retrying
Thrown when validation fails.
Properties:
ValidationErrors(List): List of validation error messagesPropertyName(string): Name of the property that failed validation
The system uses standardized error codes for consistent error handling:
MYSQL_001: MySQL service start/stop failureMYSQL_002: MySQL connection failureCOMPRESS_001: Compression operation failureTRANSFER_001: File transfer failureENCRYPT_001: Encryption operation failureVALIDATE_001: File validation failureNOTIFY_001: Notification delivery failureSCHEDULE_001: Schedule configuration errorRETENTION_001: Retention policy execution error
All operations are logged with structured logging using Serilog:
// Example log entry structure
{
"Timestamp": "2024-01-25T10:30:00.000Z",
"Level": "Information",
"MessageTemplate": "Backup operation {OperationId} completed successfully",
"Properties": {
"OperationId": "backup-20240125-103000",
"ConfigurationId": 1,
"Duration": "00:05:30",
"BytesProcessed": 1073741824,
"CompressionRatio": 0.65
}
}// Configure services
var services = new ServiceCollection();
services.AddMySqlBackupTool();
var serviceProvider = services.BuildServiceProvider();
// Get required services
var mysqlManager = serviceProvider.GetService<IMySQLManager>();
var compressionService = serviceProvider.GetService<ICompressionService>();
var encryptionService = serviceProvider.GetService<IEncryptionService>();
var transferService = serviceProvider.GetService<IFileTransferService>();
var notificationService = serviceProvider.GetService<INotificationService>();
try
{
// 1. Stop MySQL service
await mysqlManager.StopInstanceAsync("MySQL80");
// 2. Compress data directory
var compressedFile = await compressionService.CompressDirectoryAsync(
@"C:\MySQL\Data",
@"C:\Temp\backup.zip");
// 3. Encrypt backup file
var encryptedFile = @"C:\Temp\backup.zip.enc";
await encryptionService.EncryptAsync(compressedFile, encryptedFile, "SecurePassword123!");
// 4. Transfer to server
var transferConfig = new TransferConfig
{
TargetServer = new ServerEndpoint { IPAddress = "192.168.1.100", Port = 8080 },
TargetDirectory = "/backups",
EnableResume = true
};
var transferResult = await transferService.TransferFileAsync(encryptedFile, transferConfig);
// 5. Send notification
var notification = new EmailMessage
{
To = "admin@example.com",
Subject = "Backup Completed Successfully",
Body = $"Backup completed. {transferResult.BytesTransferred} bytes transferred.",
IsHtml = false
};
await notificationService.SendEmailAsync(notification);
// 6. Cleanup temporary files
await compressionService.CleanupAsync(compressedFile);
File.Delete(encryptedFile);
}
finally
{
// 7. Restart MySQL service
await mysqlManager.StartInstanceAsync("MySQL80");
}var scheduler = serviceProvider.GetService<IBackupScheduler>();
// Create daily backup schedule
var schedule = new ScheduleConfiguration
{
Name = "Daily Backup",
CronExpression = "0 0 2 * * *", // Daily at 2:00 AM
BackupConfigurationId = 1,
IsEnabled = true,
Description = "Daily backup at 2 AM"
};
await scheduler.AddOrUpdateScheduleAsync(schedule);
await scheduler.StartAsync();var retentionService = serviceProvider.GetService<IRetentionPolicyService>();
// Create retention policy: keep daily backups for 30 days
var policy = new RetentionPolicy
{
Name = "30-Day Retention",
MaxAge = TimeSpan.FromDays(30),
MaxCount = 30,
BackupDirectory = @"C:\Backups",
IsEnabled = true
};
await retentionService.CreateRetentionPolicyAsync(policy);
// Execute retention policies
var result = await retentionService.ExecuteRetentionPoliciesAsync();
Console.WriteLine($"Deleted {result.FilesDeleted} old backup files");// Program.cs or Startup.cs
services.AddMySqlBackupTool(options =>
{
options.ConnectionString = "Data Source=backup.db";
options.EnableEncryption = true;
options.EnableNotifications = true;
options.DefaultCompressionLevel = CompressionLevel.Optimal;
});
// Configure SMTP for notifications
services.Configure<SmtpConfig>(options =>
{
options.Host = "smtp.gmail.com";
options.Port = 587;
options.EnableSsl = true;
options.Username = "backup@example.com";
options.Password = "app-password";
options.FromAddress = "backup@example.com";
options.FromName = "MySQL Backup Tool";
});{
"MySqlBackupTool": {
"ConnectionString": "Data Source=backup.db",
"EnableEncryption": true,
"EnableNotifications": true,
"DefaultCompressionLevel": "Optimal",
"MaxConcurrentBackups": 3,
"DefaultRetentionDays": 30
},
"SmtpConfig": {
"Host": "smtp.gmail.com",
"Port": 587,
"EnableSsl": true,
"Username": "backup@example.com",
"Password": "app-password",
"FromAddress": "backup@example.com",
"FromName": "MySQL Backup Tool",
"TimeoutSeconds": 30
},
"Logging": {
"LogLevel": {
"Default": "Information",
"MySqlBackupTool": "Debug"
}
}
}This API reference provides comprehensive documentation for all public interfaces and models in the MySQL Backup Tool. For implementation examples and advanced usage scenarios, refer to the integration tests and sample applications included with the project.