Automatic Google Drive Trash Cleanup for HestiaCP Backups RCLONE

Automatic Google Drive Trash Cleanup for HestiaCP Backups

The Problem

Hello HestiaCP community!

I’ve been using HestiaCP with rclone for automated Google Drive backups. While this works great, I quickly ran into an issue: Google Drive’s trash only auto-empties after 30 days, but my 100GB quota was filling up within just 3 days due to the large .tar backup files.

Manually emptying the trash folder every few days was becoming tedious, so I developed a simple automated solution that I’d like to share.

The Solution: Google Apps Script Automated Trash Cleaner

I created a simple Google Apps Script that automatically deletes files from the Google Drive trash that are older than a specified number of days (e.g., 3 days). This way, your Google Drive space is freed up quickly without manual intervention.

How to Set It Up (5 Minutes)

  1. Go to script.google.com
  2. Create a new project
  3. Copy and paste the code below:
/**
 * Google Drive Trash Cleanup Script for HestiaCP Backups
 * Automatically deletes .tar files from trash that are older than X days
 */

// Main function to empty trash for files older than specified days
function cleanupOldBackups(days) {
  try {
    // Default to 3 days if not specified
    days = days || 3;
    
    var cutoffDate = new Date();
    cutoffDate.setDate(cutoffDate.getDate() - days);
    
    // Find trashed files that match our criteria
    var query = "trashed = true and mimeType contains 'application/x-tar' and modifiedTime < '" + 
                 cutoffDate.toISOString() + "'";
    
    var files = Drive.Files.list({
      q: query,
      fields: 'files(id,name,modifiedTime)'
    });
    
    var deletedCount = 0;
    var deletedSize = 0;
    var fileList = [];
    
    // Permanently delete matching files from trash
    if (files.files && files.files.length > 0) {
      for (var i = 0; i < files.files.length; i++) {
        var file = files.files[i];
        fileList.push({
          name: file.name,
          modified: file.modifiedTime
        });
        
        // Permanently delete the file
        Drive.Files.remove(file.id);
        deletedCount++;
      }
    }
    
    // Log the results
    Logger.log('Deleted ' + deletedCount + ' backup files older than ' + days + ' days from trash');
    Logger.log('Files deleted: ' + JSON.stringify(fileList));
    
    return {
      status: 'Success',
      deletedCount: deletedCount,
      olderThan: days + ' days'
    };
  } catch (error) {
    Logger.log('Error: ' + error.toString());
    return {
      status: 'Error',
      message: error.toString()
    };
  }
}

// Default function to run with 3-day setting
function runDefault() {
  cleanupOldBackups(3);
}
  1. Enable the Drive API:

    • Click on “Services” (+ icon) in the left sidebar
    • Find and add “Drive API”
  2. Set up a trigger to run automatically:

    • Click on “Triggers” (clock icon) in the left sidebar
    • Click “+ Add Trigger” button at the bottom
    • Set function to run: runDefault
    • Set trigger type: Time-driven
    • Set frequency: Daily (recommended)
    • Set time of day: Choose a time when your server is less busy
    • Click Save
  3. Authorize the script when prompted

That’s it! Your Google Drive trash will now automatically clean up HestiaCP backup .tar files that are older than 3 days.

Customizing the Script

Changing the Retention Period

If you want to change how long backup files are kept in trash before being permanently deleted:

  1. Edit the trigger you created
  2. Change the function from runDefault to cleanupOldBackups
  3. Add a parameter with the number of days (e.g., cleanupOldBackups(7) for 7 days)

Or create a custom function like:

function keepFor5Days() {
  cleanupOldBackups(5);
}

Filtering Other File Types

The script currently targets .tar files (common for backups). If you need to target different file types, modify the query in the script:

var query = "trashed = true and mimeType contains 'YOUR_MIME_TYPE' and modifiedTime < '" + 
             cutoffDate.toISOString() + "'";

Benefits

  • Automated solution: No need to manually empty trash
  • Server-side execution: Runs on Google’s servers, not yours
  • No additional software: No need to install anything on your HestiaCP server
  • Customizable retention: Set your preferred deletion timeframe
  • Space optimization: Keep your Google Drive under quota limits

Hope this helps others who are experiencing the same issue!

What other automated solutions are you using with your HestiaCP + Google Drive backup workflow?

For example:
rclone delete --min-age 3d gdrive:/backup --drive-use-trash=false

2 Likes

You declare a variable named deletedSize but never use it anywhere in the code. Why did you introduce this variable if it remains unused? Consider whether you actually need to track the total size of deleted files. If you do, you should:

  1. Retrieve each file’s size (e.g., by adding size to your fields in Drive.Files.list).
  2. Increment deletedSize inside the deletion loop, so that it accurately reflects the cumulative bytes freed.
  3. Include deletedSize in your log output or return object, making its purpose clear.

If you do not intend to track deleted file sizes, simply remove the deletedSize declaration to avoid confusion and keep the code clean. What was your original intention for deletedSize, and how would you like it to be used?

1 Like

:waving_hand: Hey [@eXe], great point!

I originally added deletedSize not just for tracking, but to potentially use it as a condition — for example, only deleting files if the total size in trash exceeds a certain threshold. :light_bulb::bar_chart:

In the end, I didn’t proceed with that logic, and simply forgot to remove the variable. :sweat_smile:

You’re right that it’s unused in the current state, so it can either be removed or extended for smarter cleanup decisions. Feel free to build on it if you’re interested! :wrench::brain:

Thanks again for the valuable feedback! :raising_hands:

1 Like