پرش به مطلب اصلی

تمیزکاری Volume‌های بلااستفاده

Volume‌های استفاده‌نشده و فایل‌های orphan مرتبط را حذف می‌کند.


🧩 دستور کلی

async pruneVolumes()

شرح عملکرد

این متد volume‌های بلااستفاده را پاکسازی می‌کند. شامل:

  • شناسایی volume‌های بلااستفاده
  • شناسایی فایل‌های orphan
  • حذف volume‌های بدون کانتینر فعال
  • حذف metadata و mount directories
  • تمیزکاری فضای دیسک
  • Logging عملیات

نکته:

  • هیچ ورودی قبول نمی‌کند
  • volume‌های موجود را حفظ می‌کند
  • فقط بلااستفاده‌ها را حذف می‌کند

ورودی‌ها

بدون ورودی

// استفاده ساده - بدون پارامتر
const count = await k3.volumeCore.pruneVolumes();

خروجی

نوع: Number

تعداد volume‌های حذف‌شده:

5  // 5 volume بلااستفاده حذف شد

نمونه‌های خروجی

0   // هیچ volume بلااستفاده‌ای نیست
3 // 3 volume حذف شد
12 // 12 volume حذف شد

استثناها (Errors)

PruneVolumesFailure (500)

پیام: "Failed to prune volumes."

زمان رخ دادن: خطا در پاکسازی یا حذف volume‌ها

جزئیات:

{
"type": "VOLUME_SERVICE_ERROR",
"statusCode": 500,
"error": "VolumeManager pruning operation failed"
}

راهنمای حل:

  • VolumeManager را بررسی کنید
  • فضای دیسک کافی است
  • اجازه‌های حذف را بررسی کنید
  • سرویس را restart کنید

مثال خطا در کنسول:

try {
const removed = await k3.volumeCore.pruneVolumes();
} catch (error) {
console.log(error.createFullMessage());
// Output:
// ERROR [VOLUME_SERVICE_ERROR] (500)
// Type: PruneVolumesFailure
// Message: Failed to prune volumes.
// Details: Permission denied during cleanup
// Timestamp: 2025-12-02T10:30:45Z
// Request ID: req-prune01
}

GenericFailure (500)

پیام: "Generic failure during volume pruning."

زمان رخ دادن: خطای عمومی نامشخص

جزئیات:

{
"type": "GENERIC_ERROR",
"statusCode": 500,
"error": "Unknown error occurred"
}

راهنمای حل:

  • لاگ‌های سیستم و سرویس را بررسی کنید
  • تمام سرویس‌ها را restart کنید
  • دوباره تلاش کنید

مثال خطا در کنسول:

try {
const removed = await k3.volumeCore.pruneVolumes();
} catch (error) {
console.log(error.createFullMessage());
// Output:
// ERROR [GENERIC_ERROR] (500)
// Type: GenericFailure
// Message: Generic failure during volume pruning.
// Action: pruneVolumes
// Details: Unexpected error in VolumeManager
// Timestamp: 2025-12-02T10:30:45Z
// Request ID: req-generic02
}

مثال‌های استفاده

مثال 1: تمیزکاری ساده

const K3Core = require('k3-core');

(async () => {
const k3 = new K3Core();

try {
console.log(' Pruning volumes...');

const removed = await k3.volumeCore.pruneVolumes();

console.log(` Pruning complete`);
console.log(` Volumes removed: ${removed}`);
} catch (error) {
console.log(error.createFullMessage());
}
})();

خروجی:

 Pruning volumes...
✓ Pruning complete
Volumes removed: 5

مثال 2: تمیزکاری و گزارش

(async () => {
const k3 = new K3Core();

try {
console.log(' Storage Report Before Pruning:');
const volumesBefore = await k3.volumeCore.listVolume();
console.log(` Total volumes: ${volumesBefore.length}`);

console.log('\n Pruning volumes...');
const removed = await k3.volumeCore.pruneVolumes();

console.log('\n Storage Report After Pruning:');
try {
const volumesAfter = await k3.volumeCore.listVolume();
console.log(` Total volumes: ${volumesAfter.length}`);
} catch (error) {
console.log(' No volumes remaining');
}

console.log(`\n Summary:`);
console.log(` Removed: ${removed}`);
console.log(` Remaining: ${volumesBefore.length - removed}`);
} catch (error) {
console.log(error.createFullMessage());
}
})();

خروجی:

 Storage Report Before Pruning:
Total volumes: 8

🧹 Pruning volumes...

Storage Report After Pruning:
Total volumes: 3

✓ Summary:
Removed: 5
Remaining: 3

مثال 3: تمیزکاری مرتب

(async () => {
const k3 = new K3Core();
const fs = require('fs');

try {
console.log(' Scheduled Cleanup\n');

const timestamp = new Date().toISOString();
console.log(`Time: ${timestamp}`);

const removed = await k3.volumeCore.pruneVolumes();

// Log cleanup
const log = {
timestamp: timestamp,
action: 'scheduled_prune',
volumesRemoved: removed,
status: 'success'
};

fs.appendFileSync('cleanup.log', JSON.stringify(log) + '\n');

console.log(` Cleanup complete - ${removed} volumes removed`);
console.log(` Logged to cleanup.log`);
} catch (error) {
console.log(error.createFullMessage());
}
})();

مثال 4: تمیزکاری با Monitoring

(async () => {
const k3 = new K3Core();

try {
console.log(' Pre-Cleanup Analysis:\n');

// Get before stats
let volumes = await k3.volumeCore.listVolume();
const beforeCount = volumes.length;

// Calculate sizes
const toBytes = (s) => {
const u = {KB: 1024, MB: 1024**2, GB: 1024**3};
const m = s.match(/^([\d.]+)([A-Z]+)$/i);
return m ? parseFloat(m[1]) * u[m[2].toUpperCase()] : 0;
};

const beforeSize = volumes.reduce((sum, v) => sum + toBytes(v.Size), 0);

console.log(`Volumes before: ${beforeCount}`);
console.log(`Space before: ${(beforeSize / (1024**3)).toFixed(2)}GB`);

// Prune
console.log('\n Pruning...');
const removed = await k3.volumeCore.pruneVolumes();

// Get after stats
try {
volumes = await k3.volumeCore.listVolume();
} catch {
volumes = [];
}

const afterCount = volumes.length;
const afterSize = volumes.reduce((sum, v) => sum + toBytes(v.Size), 0);

console.log('\n Post-Cleanup Analysis:\n');
console.log(`Volumes after: ${afterCount}`);
console.log(`Space after: ${(afterSize / (1024**3)).toFixed(2)}GB`);
console.log(`\n✓ Summary:`);
console.log(` Removed: ${removed}`);
console.log(` Space freed: ${((beforeSize - afterSize) / (1024**3)).toFixed(2)}GB`);
} catch (error) {
console.log(error.createFullMessage());
}
})();

مثال 5: تمیزکاری خودکار

(async () => {
const k3 = new K3Core();

const scheduleCleanup = (interval) => {
setInterval(async () => {
try {
console.log(`[${new Date().toLocaleTimeString()}] Running cleanup...`);
const removed = await k3.volumeCore.pruneVolumes();
console.log(` Removed ${removed} volumes`);
} catch (error) {
console.log(` Cleanup failed`);
}
}, interval);
};

// Run every 1 hour
scheduleCleanup(60 * 60 * 1000);

console.log('✓ Automatic cleanup scheduled (every 1 hour)');
})();

مثال 6: تمیزکاری با Safe Guard

(async () => {
const k3 = new K3Core();

try {
console.log('🔍 Checking system health...\n');

// Check available space
const os = require('os');
const totalMem = os.totalmem();
const freeMem = os.freemem();
const usedPercent = ((totalMem - freeMem) / totalMem * 100).toFixed(2);

console.log(`System usage: ${usedPercent}%`);

if (usedPercent > 90) {
console.log(' System is running low on space');
console.log(' Running aggressive cleanup...\n');

const removed = await k3.volumeCore.pruneVolumes();
console.log(` Removed ${removed} volumes`);
} else {
console.log(' System has sufficient space');

const removed = await k3.volumeCore.pruneVolumes();
console.log(` Regular cleanup removed ${removed} volumes`);
}
} catch (error) {
console.log(error.createFullMessage());
}
})();

مثال 7: تمیزکاری و Backup

(async () => {
const k3 = new K3Core();
const fs = require('fs');

try {
console.log(' Creating backup before cleanup...');

// Backup current state
const volumes = await k3.volumeCore.listVolume();
const backup = {
timestamp: new Date().toISOString(),
volumes: volumes,
count: volumes.length
};

fs.writeFileSync(
`volumes-backup-${Date.now()}.json`,
JSON.stringify(backup, null, 2)
);

console.log(`✓ Backup created with ${volumes.length} volumes`);

// Prune
console.log('\n Pruning volumes...');
const removed = await k3.volumeCore.pruneVolumes();

console.log(`${removed} volumes removed`);
console.log(`✓ Backup available if needed`);
} catch (error) {
console.log(error.createFullMessage());
}
})();

مثال 8: تمیزکاری دوره‌ای

(async () => {
const k3 = new K3Core();

class VolumeMaintenanceScheduler {
constructor(k3) {
this.k3 = k3;
this.lastCleanup = null;
}

async runMaintenance() {
try {
console.log('🔧 Running volume maintenance...');

const before = await this.k3.volumeCore.listVolume()
.catch(() => []).then(v => v.length);

const removed = await this.k3.volumeCore.pruneVolumes();

const after = await this.k3.volumeCore.listVolume()
.catch(() => []).then(v => v.length);

this.lastCleanup = new Date();

console.log('✓ Maintenance complete');
console.log(` Before: ${before}, After: ${after}, Removed: ${removed}`);

return { before, after, removed };
} catch (error) {
console.log(error.createFullMessage());
return null;
}
}

getLastCleanupTime() {
return this.lastCleanup;
}
}

const scheduler = new VolumeMaintenanceScheduler(k3);
await scheduler.runMaintenance();
})();

مثال 9: تمیزکاری با تفصیلات

(async () => {
const k3 = new K3Core();

try {
console.log(' Volume Cleanup Detailed Report\n');
console.log('='.repeat(50));

// Before
console.log('\nBEFORE CLEANUP:');
try {
const beforeList = await k3.volumeCore.listVolume();
console.log(` Total volumes: ${beforeList.length}`);
console.log(` Types:`);

const byType = {};
beforeList.forEach(v => {
byType[v.Type] = (byType[v.Type] || 0) + 1;
});

Object.entries(byType).forEach(([type, count]) => {
console.log(` - ${type}: ${count}`);
});
} catch {
console.log(' (No volumes)');
}

// Cleanup
console.log('\nCLEANUP RUNNING...');
const removed = await k3.volumeCore.pruneVolumes();
console.log(` Removed: ${removed}`);

// After
console.log('\nAFTER CLEANUP:');
try {
const afterList = await k3.volumeCore.listVolume();
console.log(` Total volumes: ${afterList.length}`);
} catch {
console.log(' Total volumes: 0');
}

console.log('\n' + '='.repeat(50));
} catch (error) {
console.log(error.createFullMessage());
}
})();

مثال 10: تمیزکاری ایمن

(async () => {
const k3 = new K3Core();

const safePrune = async () => {
try {
console.log(' Safe Volume Pruning\n');

// List current volumes
console.log(' Listing current volumes...');
const before = await k3.volumeCore.listVolume();
console.log(` Found: ${before.length} volumes`);

// Show details
console.log('\n Volumes to keep:');
before.forEach(v => {
console.log(` - ${v.Name} (${v.Size})`);
});

// Prune
console.log('\n3️ Pruning orphaned volumes...');
const removed = await k3.volumeCore.pruneVolumes();
console.log(` Removed: ${removed}`);

// Verify
console.log('\n4️ Verifying...');
try {
const after = await k3.volumeCore.listVolume();
console.log(` Remaining: ${after.length} volumes`);

after.forEach(v => {
console.log(`${v.Name}`);
});
} catch {
console.log(' All volumes cleaned up');
}

console.log('\n✓ Safe pruning complete');
} catch (error) {
console.log(error.createFullMessage());
}
};

await safePrune();
})();

الگوهای استفاده

الگو 1: تمیزکاری خودکار

class AutoCleanup {
constructor(k3, intervalHours = 1) {
this.k3 = k3;
this.interval = intervalHours * 60 * 60 * 1000;
this.stats = { total: 0, last: null };
}

start() {
this.timer = setInterval(async () => {
try {
const removed = await this.k3.volumeCore.pruneVolumes();
this.stats.total += removed;
this.stats.last = {
removed,
timestamp: new Date(),
count: removed
};
console.log(`[${new Date().toLocaleTimeString()}] Cleanup: ${removed} removed`);
} catch (error) {
console.log('Cleanup failed');
}
}, this.interval);
}

stop() {
if (this.timer) clearInterval(this.timer);
}

getStats() {
return this.stats;
}
}

const cleanup = new AutoCleanup(k3, 1); // Every 1 hour
cleanup.start();

الگو 2: تمیزکاری هوشمند

class SmartPruner {
constructor(k3) {
this.k3 = k3;
}

async pruneIfNeeded(thresholdGB = 10) {
const os = require('os');
const freeDisk = os.freemem() / (1024**3);

if (freeDisk < thresholdGB) {
console.log(`Low space: ${freeDisk.toFixed(2)}GB, pruning...`);
return await this.k3.volumeCore.pruneVolumes();
}

return 0;
}

async aggressivePrune() {
// Remove all unused volumes
return await this.k3.volumeCore.pruneVolumes();
}
}

const pruner = new SmartPruner(k3);
const removed = await pruner.pruneIfNeeded();

الگو 3: تمیزکاری با Report

class PruneReporter {
constructor(k3) {
this.k3 = k3;
this.history = [];
}

async pruneWithReport() {
const before = await this.getVolumeStats();
const removed = await this.k3.volumeCore.pruneVolumes();
const after = await this.getVolumeStats();

const report = {
timestamp: new Date(),
before,
after,
removed,
freed: before.totalSize - after.totalSize
};

this.history.push(report);
return report;
}

async getVolumeStats() {
try {
const volumes = await this.k3.volumeCore.listVolume();
return {
count: volumes.length,
totalSize: this.calculateTotalSize(volumes)
};
} catch {
return { count: 0, totalSize: 0 };
}
}

calculateTotalSize(volumes) {
const toBytes = (s) => {
const u = {KB: 1024, MB: 1024**2, GB: 1024**3};
const m = s.match(/^([\d.]+)([A-Z]+)$/i);
return m ? parseFloat(m[1]) * u[m[2].toUpperCase()] : 0;
};
return volumes.reduce((sum, v) => sum + toBytes(v.Size), 0);
}
}

const reporter = new PruneReporter(k3);
const report = await reporter.pruneWithReport();

نکات عملی

  1. تمیزکاری خودکار:

    • می‌توانید dوره‌ای اجرا کنید
    • برای خودکار: هر ساعت یا روزانه
    • برای بررسی فضا
  2. Orphan Files:

    • فایل‌های بدون volume شناسایی می‌شوند
    • metadata بلااستفاده حذف می‌شود
    • mount directories تمیز می‌شوند
  3. Safety:

    • فقط volume‌های bلااستفاده حذف می‌شوند
    • volume‌های فعال محفوظ‌اند
    • قابل اجرا بدون ریسک
  4. Space Management:

    • فضای دیسک را بهتر می‌کند
    • داده‌های قدیمی را حذف می‌کند
    • درنتیجه بهتر است
  5. Best Practices:

    • مرتب اجرا کنید
    • backup تهیه کنید
    • عملیات را log کنید

دنباله عملیات

  1. شناسایی volume‌های بلااستفاده
  2. شناسایی mount directories orphan
  3. شناسایی metadata بلااستفاده
  4. حذف volume entries
  5. حذف mount directories
  6. حذف metadata
  7. Logging عملیات
  8. بازگشت تعداد حذف‌شده

مرجع سریع

موضوعتوضیح
خروجیتعداد volume حذف‌شده
ورودیبدون ورودی
Error 500خطا در VolumeManager
Use Caseتمیزکاری مرتب

موارد استفاده

تمیزکاری ساده

const removed = await k3.volumeCore.pruneVolumes();

تمیزکاری مرتب

setInterval(async () => {
await k3.volumeCore.pruneVolumes();
}, 60 * 60 * 1000); // هر ساعت

تمیزکاری با Report

const before = await k3.volumeCore.listVolume();
const removed = await k3.volumeCore.pruneVolumes();
const after = await k3.volumeCore.listVolume();

تمیزکاری خودکار

// در Cron یا Scheduler
await k3.volumeCore.pruneVolumes();

نسخه: 1.3
تاریخ آپدیت: 11 آذر 1404
تیم توسعه: K3 Development Team