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

حذف Volume

Volume موجود را حذف می‌کند. Volume باید از تمام کانتینرها جدا شده باشد.


🧩 دستور کلی

async removeVolume(volumeName)

شرح عملکرد

این متد یک volume را حذف می‌کند. شامل:

  • اعتبارسنجی نام volume
  • بررسی وجود volume
  • بررسی استفاده توسط کانتینرها
  • حذف داده‌های volume
  • حذف mount directory
  • حذف metadata از سیستم
  • Logging عملیات

نکته مهم:

  • volume باید از کانتینرها جدا شده باشد
  • اگر کانتینری از volume استفاده می‌کند، حذف ناممکن است
  • تمام داده‌ها حذف می‌شوند (بازیافت‌ناپذیر)

ورودی‌ها

پارامترنوعاجباریتوضیح
volumeNameStringبلهنام volume برای حذف

مثال‌های volumeName

// نام ساده
"vlo1"

// نام معنادار
"app-data"
"cache-vol"
"temp-storage"

// نام با prefix
"test-volume"

خروجی

نوع: Object

بازگشت اطلاعات volume حذف‌شده:

{
Name: "vlo1",
Size: "100MB",
Type: "custom",
CreatedAt: "2025-12-02T07:41:12.447Z",
MountDirectory: "/var/lib/k3/volume/mount_7fa7ebe223626d24"
}

شرح خروجی

خروجی همان اطلاعات volume قبل از حذف است:

  • تأیید هویت volume حذف‌شده
  • ثبت داده‌های آخری
  • ردتrace برای audit purposes

مثال‌های خروجی دیگر

// persistent volume حذف‌شده
{
Name: "app-data",
Size: "10GB",
Type: "persistent",
CreatedAt: "2025-12-01T10:30:00.000Z",
MountDirectory: "/var/lib/k3/volume/mount_a1b2c3d4e5f6"
}

// tmpfs volume حذف‌شده
{
Name: "cache-vol",
Size: "512MB",
Type: "tmpfs",
CreatedAt: "2025-12-02T08:15:22.123Z",
MountDirectory: "/var/lib/k3/volume/mount_x9y0z1a2b3c4"
}

استثناها (Errors)

NoVolumesFound (404)

پیام: "Volume not found."

زمان رخ دادن: volume با نام مشخص‌شده وجود ندارد

جزئیات:

{
"type": "NOT_FOUND",
"statusCode": 404,
"volumeName": "nonexistent-vol",
"error": "VolumeDon'tExist"
}

راهنمای حل:

  • نام volume را بررسی کنید
  • listVolume() استفاده کنید تا نام صحیح را پیدا کنید
  • volume قبلاً حذف شده است

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

try {
await k3.volumeCore.removeVolume("nonexistent-vol");
} catch (error) {
console.log(error.createFullMessage());
// Output:
// ERROR [NOT_FOUND] (404)
// Type: NoVolumesFound
// Message: Volume not found.
// Volume Name: nonexistent-vol
// Details: Volume doesn't exist in the system
// Suggestion: Use listVolume() to find available volumes
// Timestamp: 2025-12-02T10:30:45Z
// Request ID: req-notfound01
}

VolumeInUse (409)

پیام: "Volume is in use by containers. Cannot remove."

زمان رخ دادن: volume هنوز توسط یک یا چند کانتینر استفاده می‌شود

جزئیات:

{
"type": "INVALID_STATE_ERROR",
"statusCode": 409,
"volumeName": "app-data",
"error": "this volume is attach to containers"
}

راهنمای حل:

  • ابتدا کانتینرها را متوقف کنید
  • یا volume را از کانتینرها جدا کنید
  • یا کانتینرها را حذف کنید
  • سپس volume را حذف کنید

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

try {
await k3.volumeCore.removeVolume("app-data");
} catch (error) {
console.log(error.createFullMessage());
// Output:
// ERROR [INVALID_STATE_ERROR] (409)
// Type: VolumeInUse
// Message: Volume is in use by containers. Cannot remove.
// Volume Name: app-data
// Details: This volume is attached to containers
// Solution: Disconnect containers first or delete them
// Timestamp: 2025-12-02T10:30:45Z
// Request ID: req-inuse02
}

RemoveVolumeFailure (500)

پیام: "Failed to remove volume."

زمان رخ دادن: خطا در حذف volume (دسترسی، محدودیت سیستم، و غیره)

جزئیات:

{
"type": "VOLUME_SERVICE_ERROR",
"statusCode": 500,
"volumeName": "app-data",
"error": "Permission denied or system error"
}

راهنمای حل:

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

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

try {
await k3.volumeCore.removeVolume("app-data");
} catch (error) {
console.log(error.createFullMessage());
// Output:
// ERROR [VOLUME_SERVICE_ERROR] (500)
// Type: RemoveVolumeFailure
// Message: Failed to remove volume.
// Volume Name: app-data
// Details: Permission denied when removing mount directory
// Timestamp: 2025-12-02T10:30:45Z
// Request ID: req-remove03
}

GenericFailure (500)

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

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

جزئیات:

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

راهنمای حل:

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

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

try {
await k3.volumeCore.removeVolume("app-data");
} catch (error) {
console.log(error.createFullMessage());
// Output:
// ERROR [GENERIC_ERROR] (500)
// Type: GenericFailure
// Message: Generic failure during volume removal.
// Action: removeVolume
// Details: Unexpected error in VolumeManager
// Timestamp: 2025-12-02T10:30:45Z
// Request ID: req-generic04
}

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

مثال 1: حذف Volume ساده

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

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

try {
const result = await k3.volumeCore.removeVolume('vlo1');

console.log(' Volume removed successfully');
console.log(` Name: ${result.Name}`);
console.log(` Size: ${result.Size}`);
} catch (error) {
console.log(error.createFullMessage());
}
})();

خروجی:

✓ Volume removed successfully
Name: vlo1
Size: 100MB

مثال 2: بررسی قبل از حذف

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

try {
const volumeName = 'app-data';

console.log(' Checking volume...');
const details = await k3.volumeCore.inspectVolume(volumeName);

console.log(`Volume: ${details.Name}`);
console.log(`Size: ${details.Size}`);
console.log(`Type: ${details.Type}`);

console.log('\n Removing volume...');
const removed = await k3.volumeCore.removeVolume(volumeName);

console.log(' Volume removed');
} catch (error) {
console.log(error.createFullMessage());
}
})();

مثال 3: حذف و بررسی

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

try {
console.log(' Removing volume...');
const removed = await k3.volumeCore.removeVolume('test-vol');

console.log('✓ Volume removed');
console.log(` Name: ${removed.Name}`);
console.log(` Created: ${new Date(removed.CreatedAt).toLocaleString()}`);

// Verify removal
console.log('\n Verifying removal...');
try {
await k3.volumeCore.inspectVolume('test-vol');
console.log(' Volume still exists!');
} catch (error) {
if (error.statusCode === 404) {
console.log('✓ Volume successfully deleted');
}
}
} catch (error) {
console.log(error.createFullMessage());
}
})();

مثال 4: حذف چند Volume

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

try {
const volumesToDelete = ['test-1', 'test-2', 'test-3'];
const results = [];

console.log(' Removing volumes...\n');

for (const name of volumesToDelete) {
try {
const removed = await k3.volumeCore.removeVolume(name);
results.push({
name: name,
status: 'deleted',
size: removed.Size
});
console.log(`${name} deleted`);
} catch (error) {
results.push({
name: name,
status: 'failed',
error: error.message
});
console.log(` Failed to delete ${name}`);
}
}

console.log('\n=== Deletion Summary ===');
console.table(results);
} catch (error) {
console.log(error.createFullMessage());
}
})();

مثال 5: حذف با Handle Volume In Use

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

try {
const volumeName = 'app-data';

console.log(' Attempting to remove volume...');

try {
await k3.volumeCore.removeVolume(volumeName);
console.log(' Volume removed');
} catch (error) {
if (error.statusCode === 409) {
console.log(' Volume is in use by containers');
console.log(' Options:');
console.log(' 1. Stop/delete containers');
console.log(' 2. Disconnect volume from containers');
console.log(' 3. Try again after cleanup');
} else {
console.log(error.createFullMessage());
}
}
} catch (error) {
console.log(error.createFullMessage());
}
})();

مثال 6: حذف Volume و Log

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

try {
const volumeName = 'temp-storage';

// Get details before removal
const details = await k3.volumeCore.inspectVolume(volumeName);

// Log removal action
const log = {
action: 'volume_removal',
timestamp: new Date().toISOString(),
volumeName: details.Name,
size: details.Size,
type: details.Type,
createdAt: details.CreatedAt,
mountDirectory: details.MountDirectory
};

console.log(' Logging removal...');
fs.appendFileSync('volume-operations.log', JSON.stringify(log) + '\n');

// Remove volue
console.log(' Removing volume...');
await k3.volumeCore.removeVolume(volumeName);

console.log(' Volume removed and logged');
} catch (error) {
console.log(error.createFullMessage());
}
})();

مثال 7: حذف Volume‌های قدیمی

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

try {
console.log(' Cleanup: Removing old volumes...\n');

const volumes = await k3.volumeCore.listVolume();
const now = new Date();
const thirtyDaysAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);

for (const vol of volumes) {
const createdDate = new Date(vol.CreatedAt);

if (createdDate < thirtyDaysAgo) {
try {
const details = await k3.volumeCore.inspectVolume(vol.Name);
await k3.volumeCore.removeVolume(vol.Name);

const age = Math.floor((now - createdDate) / (24 * 60 * 60 * 1000));
console.log(` ${vol.Name} removed (${age} days old)`);
} catch (error) {
console.log(` ${vol.Name} failed (${error.statusCode})`);
}
}
}

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

مثال 8: حذف Volume با Backup

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

try {
const volumeName = 'app-data';

console.log(' Creating backup...');

// Get details and create backup
const volume = await k3.volumeCore.inspectVolume(volumeName);
const backup = {
volume: volume,
backupDate: new Date().toISOString(),
status: 'backed_up_before_deletion'
};

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

console.log(' Backup created');

console.log(' Removing volume...');
await k3.volumeCore.removeVolume(volumeName);

console.log(' Volume removed');
} catch (error) {
console.log(error.createFullMessage());
}
})();

مثال 9: حذف Volume‌های موقتی

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

try {
console.log(' Cleaning temporary volumes...\n');

const volumes = await k3.volumeCore.listVolume();
const tempVolumes = volumes.filter(v =>
v.Name.includes('temp') ||
v.Name.includes('test') ||
v.Type === 'tmpfs'
);

console.log(`Found ${tempVolumes.length} temporary volume(s)\n`);

for (const vol of tempVolumes) {
try {
await k3.volumeCore.removeVolume(vol.Name);
console.log(`${vol.Name} removed`);
} catch (error) {
console.log(` ${vol.Name} failed`);
}
}

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

مثال 10: حذف با تأیید

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

const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});

try {
const volumeName = 'app-data';

const volume = await k3.volumeCore.inspectVolume(volumeName);

console.log(' Volume Details:');
console.log(` Name: ${volume.Name}`);
console.log(` Size: ${volume.Size}`);
console.log(` Type: ${volume.Type}`);
console.log(` Created: ${new Date(volume.CreatedAt).toLocaleString()}`);

rl.question('\n Delete this volume? (yes/no): ', async (answer) => {
if (answer.toLowerCase() === 'yes') {
try {
await k3.volumeCore.removeVolume(volumeName);
console.log('✓ Volume deleted');
} catch (error) {
console.log(error.createFullMessage());
}
} else {
console.log('✗ Deletion cancelled');
}
rl.close();
});
} catch (error) {
console.log(error.createFullMessage());
rl.close();
}
})();

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

الگو 1: حذف ایمن

const safeRemoveVolume = async (volumeName) => {
try {
// Check if exists
const volumes = await k3.volumeCore.listVolume();
if (!volumes.find(v => v.Name === volumeName)) {
console.log(`Volume ${volumeName} not found`);
return false;
}

// Remove
await k3.volumeCore.removeVolume(volumeName);
console.log(`Volume ${volumeName} removed`);
return true;
} catch (error) {
if (error.statusCode === 409) {
console.log('Volume is in use, cannot remove');
} else {
console.log(error.createFullMessage());
}
return false;
}
};

await safeRemoveVolume('app-data');

الگو 2: حذف دسته‌ای

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

async removeMultiple(volumeNames) {
const results = {
succeeded: [],
failed: []
};

for (const name of volumeNames) {
try {
await this.k3.volumeCore.removeVolume(name);
results.succeeded.push(name);
} catch (error) {
results.failed.push({ name, error: error.statusCode });
}
}

return results;
}

async removeByPattern(pattern) {
const volumes = await this.k3.volumeCore.listVolume();
const matching = volumes
.filter(v => v.Name.includes(pattern))
.map(v => v.Name);

return this.removeMultiple(matching);
}
}

const cleaner = new VolumeCleaner(k3);
const results = await cleaner.removeByPattern('test-');

الگو 3: حذف با Audit

class AuditedVolumeCleaner {
constructor(k3, auditLog) {
this.k3 = k3;
this.auditLog = auditLog;
}

async remove(volumeName) {
try {
const volume = await this.k3.volumeCore.inspectVolume(volumeName);

const result = await this.k3.volumeCore.removeVolume(volumeName);

// Log success
this.auditLog({
action: 'volume_removed',
name: volumeName,
size: volume.Size,
type: volume.Type,
status: 'success',
timestamp: new Date()
});

return result;
} catch (error) {
// Log failure
this.auditLog({
action: 'volume_remove_failed',
name: volumeName,
error: error.statusCode,
status: 'failed',
timestamp: new Date()
});

throw error;
}
}
}

نکات عملی

  1. بررسی قبل از حذف:

    • ابتدا inspectVolume() استفاده کنید
    • مطمئن شوید نام صحیح است
    • داده‌های مهم را backup کنید
  2. Volume In Use:

    • اگر خطای 409 دریافت کردید، volume استفاده‌شده است
    • کانتینرها را ابتدا متوقف/حذف کنید
    • سپس volume را حذف کنید
  3. حذف دائمی:

    • حذف غیرقابل بازگشت است
    • تمام داده‌ها از بین می‌رود
    • backup تهیه کنید
  4. Logging:

    • تمام عملیات‌های حذف را log کنید
    • برای audit trail
    • برای recovery
  5. Best Practices:

    • همیشه try-catch استفاده کنید
    • بررسی error code کنید
    • backup تهیه کنید

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

  1. اعتبارسنجی volumeName
  2. تماس با VolumeManager
  3. بررسی وجود volume
  4. بررسی استفاده توسط کانتینرها
  5. حذف mount directory
  6. حذف metadata
  7. Logging عملیات
  8. بازگشت اطلاعات volume

مرجع سریع

فیلدتوضیح
Nameنام volume
Sizeاندازه (مثل 100MB، 10GB)
Typeنوع (tmpfs، persistent، custom)
CreatedAtزمان ایجاد ISO format
MountDirectoryمسیر mount سیستم

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

حذف ساده

await k3.volumeCore.removeVolume('test-vol');

بررسی و حذف

const details = await k3.volumeCore.inspectVolume('test-vol');
await k3.volumeCore.removeVolume('test-vol');

حذف دسته‌ای

const list = await k3.volumeCore.listVolume();
for (const v of list) {
await k3.volumeCore.removeVolume(v.Name);
}

حذف با Handle Error

try {
await k3.volumeCore.removeVolume('app-data');
} catch (error) {
if (error.statusCode === 409) {
console.log('Volume is in use');
}
}

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