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

لیست Volume‌ها

تمام volume‌های موجود در سیستم را نمایش می‌دهد.


🧩 دستور کلی

async listVolume()

شرح عملکرد

این متد لیست تمام volume‌های موجود را دریافت می‌کند. شامل:

  • دریافت لیست volume‌ها از VolumeManager
  • بررسی وجود volume‌ها
  • بررسی خطاهای VolumeManager
  • Logging عملیات

نکته: اگر volume‌ی موجود نباشد، خطای NoVolumesFound می‌دهد.


ورودی‌ها

بدون ورودی

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

خروجی

نوع: Array<Object>

پاسخ موفق - آرایه‌ای از volume‌ها:

[
{
Name: "vlo1",
Size: "100MB",
Type: "custom",
CreatedAt: "2025-12-02T06:43:16.035Z",
MountDirectory: "/var/lib/k3/volume/mount_cb6c19ef1a9dac77"
}
]

شرح فیلدهای خروجی

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

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

// چند volume
[
{
Name: "app-data",
Size: "10GB",
Type: "custom",
CreatedAt: "2025-12-01T10:30:00.000Z",
MountDirectory: "/var/lib/k3/volume/mount_a1b2c3d4"
},
{
Name: "cache-vol",
Size: "512MB",
Type: "custom",
CreatedAt: "2025-12-02T08:15:22.123Z",
MountDirectory: "/var/lib/k3/volume/mount_e5f6g7h8"
},
{
Name: "db-storage",
Size: "50GB",
Type: "custom",
CreatedAt: "2025-11-30T15:45:10.456Z",
MountDirectory: "/var/lib/k3/volume/mount_i9j0k1l2"
}
]

مثال - Volume‌های مختلف

// یک نمونه کامل با انواع مختلف
[
{
Name: "postgres-data",
Size: "50GB",
Type: "custom",
CreatedAt: "2025-12-02T06:43:16.035Z",
MountDirectory: "/var/lib/k3/volume/mount_cb6c19ef1a9dac77"
},
{
Name: "cache-layer",
Size: "2GB",
Type: "custom",
CreatedAt: "2025-12-02T07:15:22.145Z",
MountDirectory: "/var/lib/k3/volume/mount_a1b2c3d4e5f6"
},
{
Name: "app-logs",
Size: "10GB",
Type: "custom",
CreatedAt: "2025-12-02T05:30:10.789Z",
MountDirectory: "/var/lib/k3/volume/mount_xyz789abc123"
}
]

استثناها (Errors)

ListVolumesFailure (500)

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

زمان رخ دادن: خطا در دریافت لیست volume‌ها از VolumeManager

جزئیات:

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

راهنمای حل:

  • VolumeManager را بررسی کنید
  • سرویس را restart کنید
  • لاگ‌های سیستم را بررسی کنید
  • اتصال سیستم پرونده را تأیید کنید

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

try {
const volumes = await k3.volumeCore.listVolume();
} catch (error) {
console.log(error.createFullMessage());
// Output:
// ERROR [VOLUME_SERVICE_ERROR] (500)
// Type: ListVolumesFailure
// Message: Failed to list volumes.
// Details: VolumeManager service unavailable
// Timestamp: 2025-12-02T09:30:45Z
// Request ID: req-list01
}

NoVolumesFound (404)

پیام: "No volumes found in the system."

زمان رخ دادن: هیچ volume‌ی در سیستم وجود ندارد

جزئیات:

{
"type": "NOT_FOUND",
"statusCode": 404,
"error": "Volume list is empty"
}

راهنمای حل:

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

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

try {
const volumes = await k3.volumeCore.listVolume();
} catch (error) {
console.log(error.createFullMessage());
// Output:
// ERROR [NOT_FOUND] (404)
// Type: NoVolumesFound
// Message: No volumes found in the system.
// Details: No volumes have been created yet
// Suggestion: Create volumes using createVolume() method
// Timestamp: 2025-12-02T09:30:45Z
// Request ID: req-notfound02
}

GenericFailure (500)

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

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

جزئیات:

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

راهنمای حل:

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

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

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

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

مثال 1: لیست تمام Volume‌ها

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

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

try {
const volumes = await k3.volumeCore.listVolume();

console.log('✓ Volumes found:', volumes.length);
volumes.forEach(vol => {
console.log(` - ${vol.Name} (${vol.Size})`);
});
} catch (error) {
console.log(error.createFullMessage());
}
})();

خروجی:

✓ Volumes found: 3
- vlo1 (100MB)
- app-data (10GB)
- db-storage (50GB)

مثال 2: لیست و جزئیات

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

try {
const volumes = await k3.volumeCore.listVolume();

console.log(' Volume Details:\n');

volumes.forEach((vol, index) => {
console.log(`${index + 1}. ${vol.Name}`);
console.log(` Size: ${vol.Size}`);
console.log(` Type: ${vol.Type}`);
console.log(` Created: ${new Date(vol.CreatedAt).toLocaleString()}`);
console.log(` Path: ${vol.MountDirectory}\n`);
});
} catch (error) {
console.log(error.createFullMessage());
}
})();

خروجی:

 Volume Details:

1. vlo1
Size: 100MB
Type: custom
Created: 2025-12-02 10:13:16 AM
Path: /var/lib/k3/volume/mount_cb6c19ef1a9dac77

2. app-data
Size: 10GB
Type: custom
Created: 2025-12-01 10:30:00 AM
Path: /var/lib/k3/volume/mount_a1b2c3d4

3. cache-vol
Size: 512MB
Type: custom
Created: 2025-12-02 8:15:22 AM
Path: /var/lib/k3/volume/mount_e5f6g7h8

مثال 4: محاسبه کل اندازه

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

try {
const volumes = await k3.volumeCore.listVolume();

// تابع تبدیل size به bytes
const toBytes = (sizeStr) => {
const units = { KB: 1024, MB: 1024**2, GB: 1024**3, TB: 1024**4 };
const match = sizeStr.match(/^([\d.]+)\s*([A-Z]+)$/i);

if (!match) return 0;
const [, num, unit] = match;
return parseFloat(num) * (units[unit.toUpperCase()] || 1);
};

const totalBytes = volumes.reduce((sum, v) => sum + toBytes(v.Size), 0);
const totalGB = (totalBytes / (1024**3)).toFixed(2);

console.log(' Storage Summary:\n');
console.log(`Total Volume Size: ${totalGB}GB`);
console.log(`Number of Volumes: ${volumes.length}`);
console.log(`Average Size: ${(totalBytes / volumes.length / (1024**3)).toFixed(2)}GB`);
} catch (error) {
console.log(error.createFullMessage());
}
})();

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

try {
const volumes = await k3.volumeCore.listVolume();
const searchTerm = 'data';

const results = volumes.filter(v =>
v.Name.toLowerCase().includes(searchTerm.toLowerCase())
);

if (results.length === 0) {
console.log(` No volumes found matching "${searchTerm}"`);
return;
}

console.log(`✓ Found ${results.length} volume(s) matching "${searchTerm}":\n`);
results.forEach(vol => {
console.log(` ${vol.Name} (${vol.Size})`);
});
} catch (error) {
console.log(error.createFullMessage());
}
})();

مثال 6: لیست به جدول

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

try {
const volumes = await k3.volumeCore.listVolume();

// تبدیل به جدول
const tableData = volumes.map(v => ({
Name: v.Name,
Size: v.Size,
Type: v.Type,
Created: new Date(v.CreatedAt).toLocaleDateString(),
Path: v.MountDirectory.split('/').slice(-1)[0]
}));

console.log(' Volumes Table:');
console.table(tableData);
} catch (error) {
console.log(error.createFullMessage());
}
})();

مثال 7: لیست با شرط

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

try {
const volumes = await k3.volumeCore.listVolume();

if (volumes.length === 0) {
console.log('No volumes available');
return;
}

// بزرگترین volume
const largest = volumes.reduce((max, v) => {
const maxSize = parseInt(max.Size);
const vSize = parseInt(v.Size);
return vSize > maxSize ? v : max;
});

// کوچکترین volume
const smallest = volumes.reduce((min, v) => {
const minSize = parseInt(min.Size);
const vSize = parseInt(v.Size);
return vSize < minSize ? v : min;
});

console.log(' Volume Statistics:\n');
console.log(`Total Volumes: ${volumes.length}`);
console.log(`Largest: ${largest.Name} (${largest.Size})`);
console.log(`Smallest: ${smallest.Name} (${smallest.Size})`);
} catch (error) {
console.log(error.createFullMessage());
}
})();

مثال 8: Export لیست Volume‌ها

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

try {
const volumes = await k3.volumeCore.listVolume();

// Export به JSON
const report = {
exportedAt: new Date().toISOString(),
totalVolumes: volumes.length,
volumes: volumes
};

fs.writeFileSync('volumes-report.json', JSON.stringify(report, null, 2));
console.log('✓ Report saved to volumes-report.json');

// Export به CSV
const csv = [
'Name,Size,Type,CreatedAt,MountDirectory',
...volumes.map(v => `"${v.Name}","${v.Size}","${v.Type}","${v.CreatedAt}","${v.MountDirectory}"`)
].join('\n');

fs.writeFileSync('volumes-report.csv', csv);
console.log('✓ CSV saved to volumes-report.csv');
} catch (error) {
console.log(error.createFullMessage());
}
})();

مثال 9: مراقبت Volume‌ها

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

try {
const volumes = await k3.volumeCore.listVolume();

const now = new Date();
const thirtyDaysAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);

// Volume‌های قدیمی
const oldVolumes = volumes.filter(v =>
new Date(v.CreatedAt) < thirtyDaysAgo
);

console.log(' Volume Monitoring:\n');
console.log(`Recent Volumes: ${volumes.length - oldVolumes.length}`);
console.log(`Old Volumes (>30 days): ${oldVolumes.length}`);

if (oldVolumes.length > 0) {
console.log('\n Old volumes to review:');
oldVolumes.forEach(v => {
const days = Math.floor((now - new Date(v.CreatedAt)) / (24 * 60 * 60 * 1000));
console.log(` - ${v.Name} (${days} days old)`);
});
}
} catch (error) {
console.log(error.createFullMessage());
}
})();

مثال 10: مقایسه Volume‌ها

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

try {
const volumes = await k3.volumeCore.listVolume();

console.log(' Volume Comparison:\n');

// دسته‌بندی بر اساس Type
const byType = {};
volumes.forEach(v => {
if (!byType[v.Type]) {
byType[v.Type] = {
count: 0,
volumes: []
};
}
byType[v.Type].count++;
byType[v.Type].volumes.push(v);
});

Object.entries(byType).forEach(([type, data]) => {
console.log(`${type.toUpperCase()}:`);
console.log(` Count: ${data.count}`);
data.volumes.forEach(v => {
console.log(` - ${v.Name} (${v.Size})`);
});
console.log();
});
} catch (error) {
console.log(error.createFullMessage());
}
})();

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

الگو 1: لیست با Error Handling

const listVolumesWithFallback = async () => {
try {
return await k3.volumeCore.listVolume();
} catch (error) {
if (error.statusCode === 404) {
console.log('No volumes exist yet');
return [];
}
console.log(error.createFullMessage());
return null;
}
};

const volumes = await listVolumesWithFallback();

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

async findByName(name) {
const volumes = await this.k3.volumeCore.listVolume();
return volumes.filter(v =>
v.Name.toLowerCase().includes(name.toLowerCase())
);
}

async findByType(type) {
const volumes = await this.k3.volumeCore.listVolume();
return volumes.filter(v => v.Type === type);
}

async findBySize(minSize, maxSize) {
const volumes = await this.k3.volumeCore.listVolume();
return volumes.filter(v => {
const size = parseInt(v.Size);
return size >= minSize && size <= maxSize;
});
}
}

const searcher = new VolumeSearcher(k3);
const dataVolumes = await searcher.findByName('data');

الگو 3: لیست و تحلیل

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

async analyze() {
try {
const volumes = await this.k3.volumeCore.listVolume();

return {
total: volumes.length,
byType: this.groupByType(volumes),
stats: this.getStats(volumes),
recent: this.getRecent(volumes, 7)
};
} catch (error) {
console.log(error.createFullMessage());
return null;
}
}

groupByType(volumes) {
return volumes.reduce((acc, v) => {
acc[v.Type] = (acc[v.Type] || 0) + 1;
return acc;
}, {});
}

getStats(volumes) {
return {
oldest: volumes.reduce((min, v) =>
new Date(v.CreatedAt) < new Date(min.CreatedAt) ? v : min
).CreatedAt,
newest: volumes.reduce((max, v) =>
new Date(v.CreatedAt) > new Date(max.CreatedAt) ? v : max
).CreatedAt
};
}

getRecent(volumes, days) {
const since = new Date(Date.now() - days * 24 * 60 * 60 * 1000);
return volumes.filter(v => new Date(v.CreatedAt) > since);
}
}

const analyzer = new VolumeAnalyzer(k3);
const analysis = await analyzer.analyze();

نکات عملی

  1. بررسی وجود Volume:

    • اگر خطای 404 دریافت کردید، هیچ volume‌ی وجود ندارد
    • ابتدا volume‌ها را ایجاد کنید
  2. Filtering:

    • می‌توانید داده‌ها را بعد از دریافت فیلتر کنید
    • بر اساس: نام، اندازه، نوع، تاریخ
  3. Performance:

    • لیست‌کردن سریع است
    • برای اندازه‌های بزرگ: هنوز قابل قبول
  4. Error Handling:

    • همیشه try-catch استفاده کنید
    • بخصوص NoVolumesFound
  5. Best Practices:

    • بصورت مرتب لیست را بررسی کنید
    • Volume‌های قدیمی را شناسایی کنید
    • Space usage را مراقبت کنید

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

  1. تماس با VolumeManager
  2. دریافت لیست volume‌ها
  3. بررسی خطاهای VolumeManager
  4. بررسی خالی بودن لیست
  5. Logging عملیات
  6. بازگشت آرایه volume‌ها

مرجع سریع

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

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

لیست سادهٔ

const volumes = await k3.volumeCore.listVolume();

فیلتر بر اساس نوع

const persistent = volumes.filter(v => v.Type === 'persistent');

جستجو بر اساس نام

const found = volumes.find(v => v.Name === 'app-data');

محاسبهٔ کل اندازه

const total = volumes.reduce((sum, v) => sum + parseInt(v.Size), 0);


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