ایجاد Volume جدید
Volume جدیدی برای کانتینرها ایجاد میکند تا دادهها در آن ذخیره شوند.
🧩 دستور کلی
async createVolume(volumeName, options)
شرح عملکرد
این متد یک volume جدید ایجاد میکند. شامل:
- اعتبارسنجی نام volume و پارامترها
- بررسی schema پیکربندی
- ایجاد دایرکتوری mount
- تخصیص فضای دیسک
- ثبت اطلاعات volume در سیستم
- Logging عملیات
ورودیها
| پارامتر | نوع | اجباری | توضیح |
|---|---|---|---|
volumeName | String | بله | نام منحصربهفرد volume |
options | Object | بله | پیکربندی volume |
options.size | String/Number | بله | اندازه volume (مثل '10G', '100MB', یا بایت) |
options.type | String | بله | نوع volume (tmpfs یا persistent) |
options.mount | String | بله | مسیر mount درون کانتینر (مثل /data) |
مثالهای options
{
size: "256MB",
mount: "/dev/shm"
}
{
size: "5G",
type: "persistent",
mount: "/data"
}
// Custom با اندازه بزرگ
{
size: "100GB",
type: "custom",
mount: "/var/lib/data"
}
فرمتهای اندازه معتبر
"10MB" // مگابایت
"100MB" // 100 مگابایت
"1GB" // 1 گیگابایت
"2.5G" // 2.5 گیگابایت
"512KB" // کیلوبایت
خروجی
نوع: Object
پاسخ موفق:
{
Name: "vlo1",
Size: "100MB",
Type: "custom",
CreatedAt: "2025-12-02T06:43:16.035Z",
MountDirectory: "/var/lib/k3/volume/mount_cb6c19ef1a9dac77"
}
شرح فیلدهای خروجی
| فیلد | توضیح |
|---|---|
| Name | نام volume |
| Size | اندازه انتخابشده |
| Type | نوع volume (custom یا lvm) |
| CreatedAt | زمان ایجاد (ISO format) |
| MountDirectory | مسیر واقعی mount در سیستم |
مثالهای خروجی دیگر
// tmpfs volume
{
Name: "cache-vol",
Size: "256MB",
Type: "custom",
CreatedAt: "2025-12-02T07:15:22.145Z",
MountDirectory: "/var/lib/k3/volume/mount_a1b2c3d4e5f6"
}
// persistent volume بزرگ
{
Name: "database",
Size: "10GB",
Type: "custom",
CreatedAt: "2025-12-02T08:20:33.456Z",
MountDirectory: "/var/lib/k3/volume/mount_xyz789abc123"
}
استثناها (Errors)
InvalidVolumeSchema (422)
پیام: "Invalid volume schema or configuration."
زمان رخ دادن: پارامترهای volume نامعتبر یا ناقص
جزئیات:
{
"type": "VALIDATION_ERROR",
"statusCode": 422,
"volumeName": "my-vol",
"error": "Invalid size format or missing required fields"
}
راهنمای حل:
- تمام فیلدهای الزامی را مشخص کنید (size، type، mount)
- فرمت size را بررسی کنید (مثل "10G" یا "512MB")
- type باید tmpfs یا persistent باشد
- mount یک مسیر معتبر باشد (شروع با /)
مثال خطا در کنسول:
try {
await k3.volumeCore.createVolume('my-vol', {
size: "invalid" // فرمت نامعتبر
});
} catch (error) {
console.log(error.createFullMessage());
// Output:
// ERROR [VALIDATION_ERROR] (422)
// Type: InvalidVolumeSchema
// Message: Invalid volume schema or configuration.
// Volume: my-vol
// Details: Invalid size format (must be like 10G, 100MB)
// Timestamp: 2025-12-02T09:30:45Z
// Request ID: req-schema01
}
VolumeAlreadyExists (409)
پیام: "Volume with this name already exists."
زمان رخ دادن: Volume با این نام قبلاً موجود است
جزئیات:
{
"type": "INVALID_STATE_ERROR",
"statusCode": 409,
"volumeName": "vlo1",
"error": "VolumeAlreadyExist"
}
راهنمای حل:
- نام volume منحصربهفرد انتخاب کنید
- لیست volumeها را بررسی کنید (
listVolumes()) - volume قدیمی را حذف کنید (
deleteVolume())
مثال خطا در کنسول:
try {
// اولین بار
await k3.volumeCore.createVolume('data-vol', {
size: "10G",
type: "custom",
mount: "/data"
});
// دوبارهء
await k3.volumeCore.createVolume('data-vol', {
size: "5G",
type: "custom",
mount: "/backup"
});
} catch (error) {
console.log(error.createFullMessage());
// Output:
// ERROR [INVALID_STATE_ERROR] (409)
// Type: VolumeAlreadyExists
// Message: Volume with this name already exists.
// Volume Name: data-vol
// Suggestion: Use a different name or delete the existing volume
// Timestamp: 2025-12-02T09:30:45Z
// Request ID: req-exists02
}
CreateVolumeFailure (500)
پیام: "Failed to create volume."
زمان رخ دادن: خطا در ایجاد volume (دسترسی، فضای دیسک، و غیره)
جزئیات:
{
"type": "VOLUME_SERVICE_ERROR",
"statusCode": 500,
"volumeName": "my-vol",
"options": {
"size": "50G",
"type": "custom",
"mount": "/data"
},
"error": "Insufficient disk space or permission denied"
}
راهنمای حل:
- فضای دیسک کافی است؟
- اجازههای نوشتن موجود است؟
- VolumeManager را بررسی کنید
- اندازه volume را کاهش دهید
مثال خطا در کنسول:
try {
await k3.volumeCore.createVolume('huge-vol', {
size: "1TB",
type: "custom",
mount: "/data"
});
} catch (error) {
console.log(error.createFullMessage());
// Output:
// ERROR [VOLUME_SERVICE_ERROR] (500)
// Type: CreateVolumeFailure
// Message: Failed to create volume.
// Volume Name: huge-vol
// Size: 1TB
// Details: Insufficient disk space (need 1TB, available 500GB)
// Timestamp: 2025-12-02T09:30:45Z
// Request ID: req-create03
}
GenericFailure (500)
پیام: "Generic failure during volume creation."
زمان رخ دادن: خطای عمومی نامشخص
جزئیات:
{
"type": "GENERIC_ERROR",
"statusCode": 500,
"error": "Unknown error occurred"
}
راهنمای حل:
- لاگهای سیستم را بررسی کنید
- سرویسها را restart کنید
- دوباره تلاش کنید
مثال خطا در کنسول:
try {
await k3.volumeCore.createVolume('my-vol', {
size: "10G",
type: "custom",
mount: "/data"
});
} catch (error) {
console.log(error.createFullMessage());
// Output:
// ERROR [GENERIC_ERROR] (500)
// Type: GenericFailure
// Message: Generic failure during volume creation.
// Action: createVolume
// Details: Unexpected error in VolumeManager
// Timestamp: 2025-12-02T09:30:45Z
// Request ID: req-generic04
}
مثالهای استفاده
مثال 1: ایجاد Volume Persistent ساده
const K3Core = require('k3-core');
(async () => {
const k3 = new K3Core();
try {
const volume = await k3.volumeCore.createVolume('app-data', {
size: "10GB",
type: "custom",
mount: "/app/data"
});
console.log('✓ Volume created successfully');
console.log(` Name: ${volume.Name}`);
console.log(` Size: ${volume.Size}`);
console.log(` Type: ${volume.Type}`);
console.log(` Mount: ${volume.MountDirectory}`);
} catch (error) {
console.log(error.createFullMessage());
}
})();
خروجی:
✓ Volume created successfully
Name: app-data
Size: 10GB
Type: custom
Mount: /var/lib/k3/volume/mount_a1b2c3d4e5f6
مثال 2: ایجاد Volume Tmpfs
(async () => {
const k3 = new K3Core();
try {
const volume = await k3.volumeCore.createVolume('cache-vol', {
size: "512MB",
type: "custom",
mount: "/cache"
});
console.log(' custom volume created');
console.log(` Size: ${volume.Size}`);
console.log(` Type: ${volume.Type}`);
} catch (error) {
console.log(error.createFullMessage());
}
})();
مثال 3: ایجاد Volume برای Database
(async () => {
const k3 = new K3Core();
try {
console.log(' Creating database volume...');
const volume = await k3.volumeCore.createVolume('postgres-data', {
size: "50GB",
type: "custom",
mount: "/var/lib/postgresql/data"
});
console.log('✓ Database volume created');
console.log(` Mount Directory: ${volume.MountDirectory}`);
console.log(` Created At: ${volume.CreatedAt}`);
} catch (error) {
console.log(error.createFullMessage());
}
})();
مثال 4: ایجاد چند Volume
(async () => {
const k3 = new K3Core();
try {
const volumes = [
{ name: 'app-code', size: '5GB', type: 'custom', mount: '/app' },
{ name: 'app-logs', size: '2GB', type: 'custom', mount: '/logs' },
{ name: 'app-cache', size: '1GB', type: 'custom', mount: '/cache' }
];
const results = [];
for (const vol of volumes) {
try {
const created = await k3.volumeCore.createVolume(vol.name, {
size: vol.size,
type: vol.type,
mount: vol.mount
});
results.push({
name: vol.name,
status: 'created',
size: created.Size
});
console.log(`✓ ${vol.name} created`);
} catch (error) {
results.push({
name: vol.name,
status: 'failed',
error: error.message
});
console.log(` ${vol.name} failed`);
}
}
console.log('\n=== Creation Summary ===');
console.table(results);
} catch (error) {
console.log(error.createFullMessage());
}
})();
مثال 5: ایجاد Volume با بررسی قبلی
(async () => {
const k3 = new K3Core();
try {
const volumeName = 'app-data';
// Check if exists
console.log(' Checking existing volumes...');
const existing = await k3.volumeCore.listVolumes();
const volumeExists = existing.find(v => v.Name === volumeName);
if (volumeExists) {
console.log(` Volume ${volumeName} already exists`);
console.log(` Size: ${volumeExists.Size}`);
console.log(` Type: ${volumeExists.Type}`);
return;
}
// Create new
console.log(` Creating ${volumeName}...`);
const volume = await k3.volumeCore.createVolume(volumeName, {
size: '20GB',
type: 'custom',
mount: '/data'
});
console.log('✓ Volume created');
} catch (error) {
console.log(error.createFullMessage());
}
})();
مثال 6: ایجاد Volume و اتصال به کانتینر
(async () => {
const k3 = new K3Core();
try {
// Step 1: Create volume
console.log(' Creating volume...');
const volume = await k3.volumeCore.createVolume('app-storage', {
size: '15GB',
type: 'custom',
mount: '/storage'
});
console.log(`✓ Volume created: ${volume.Name}`);
// Step 2: Create container with volume
console.log(' Creating container...');
const container = await k3.containerCore.createContainer({
containerId: 'app-server',
imageName: 'node',
imageTag: 'latest',
volumes: [
{
volumeName: volume.Name,
mountPath: volume.MountDirectory
}
]
});
console.log(`✓ Container created with volume`);
console.log('\n✓ Setup complete');
} catch (error) {
console.log(error.createFullMessage());
}
})();
مثال 7: ایجاد Volume برای Microservices
(async () => {
const k3 = new K3Core();
try {
const services = {
'api': { size: '5GB', mount: '/api/data' },
'database': { size: '50GB', mount: '/db/data' },
'cache': { size: '2GB', mount: '/cache' },
'logs': { size: '10GB', mount: '/logs' }
};
console.log(' Setting up microservices volumes...\n');
for (const [service, config] of Object.entries(services)) {
try {
const volume = await k3.volumeCore.createVolume(`${service}-vol`, {
size: config.size,
type: 'custom',
mount: config.mount
});
console.log(`✓ ${service}`);
console.log(` Size: ${volume.Size}`);
console.log(` Path: ${volume.MountDirectory}\n`);
} catch (error) {
console.log(` ${service} failed\n`);
}
}
console.log('✓ All volumes created');
} catch (error) {
console.log(error.createFullMessage());
}
})();
مثال 8: ایجاد Volume با اندازه متغیر
(async () => {
const k3 = new K3Core();
try {
const getVolumeSize = (environment) => {
switch (environment) {
case 'development':
return '5GB';
case 'staging':
return '25GB';
case 'production':
return '100GB';
default:
return '10GB';
}
};
const env = process.env.ENVIRONMENT || 'development';
const size = getVolumeSize(env);
console.log(` Creating volume for ${env}...`);
const volume = await k3.volumeCore.createVolume(`data-${env}`, {
size: size,
type: 'custom',
mount: '/data'
});
console.log(`✓ ${env.toUpperCase()} volume created`);
console.log(` Size: ${volume.Size}`);
} catch (error) {
console.log(error.createFullMessage());
}
})();
مثال 9: ایجاد Volume و Log کردن
(async () => {
const k3 = new K3Core();
const fs = require('fs');
try {
const volumeName = 'prod-data';
const volumeLog = {
action: 'volume_creation',
timestamp: new Date().toISOString(),
name: volumeName
};
console.log(' Creating volume with logging...');
const volume = await k3.volumeCore.createVolume(volumeName, {
size: '50GB',
type: 'custom',
mount: '/prod/data'
});
// Log success
volumeLog.status = 'success';
volumeLog.volumeId = volume.Name;
volumeLog.size = volume.Size;
volumeLog.mountPoint = volume.MountDirectory;
fs.appendFileSync('volume-operations.log', JSON.stringify(volumeLog) + '\n');
console.log('✓ Volume created and logged');
} catch (error) {
console.log(error.createFullMessage());
}
})();
مثال 10: ایجاد Volume با Validation
(async () => {
const k3 = new K3Core();
const validateVolumeConfig = (config) => {
if (!config.size || !config.type || !config.mount) {
throw new Error('Missing required fields');
}
if (!['custom', 'custom'].includes(config.type)) {
throw new Error('Invalid type (must be tmpfs or persistent)');
}
if (!config.mount.startsWith('/')) {
throw new Error('Mount path must start with /');
}
return true;
};
try {
const config = {
size: '20GB',
type: 'custom',
mount: '/app/data'
};
console.log(' Validating configuration...');
validateVolumeConfig(config);
console.log('✓ Configuration valid');
console.log(' Creating volume...');
const volume = await k3.volumeCore.createVolume('app-vol', config);
console.log('✓ Volume created successfully');
console.log(` Name: ${volume.Name}`);
console.log(` Size: ${volume.Size}`);
} catch (error) {
console.log(` Error: ${error.message}`);
}
})();
الگوهای استفاده
الگو 1: ایجاد ایمن
const safeCreateVolume = async (name, config) => {
try {
// Check if exists
const existing = await k3.volumeCore.listVolumes();
if (existing.find(v => v.Name === name)) {
console.log(`Volume ${name} already exists`);
return existing.find(v => v.Name === name);
}
// Create new
return await k3.volumeCore.createVolume(name, config);
} catch (error) {
console.log(error.createFullMessage());
return null;
}
};
الگو 2: ایجاد متناسب با محیط
class VolumeFactory {
constructor(k3) {
this.k3 = k3;
this.env = process.env.NODE_ENV || 'development';
}
getConfig(service) {
const configs = {
development: { size: '5GB', type: 'custom' },
staging: { size: '20GB', type: 'custom' },
production: { size: '100GB', type: 'custom' }
};
return configs[this.env] || configs.development;
}
async createServiceVolume(service) {
const config = this.getConfig(service);
return await this.k3.volumeCore.createVolume(`${service}-vol`, {
size: config.size,
type: config.type,
mount: `/${service}/data`
});
}
}
const factory = new VolumeFactory(k3);
await factory.createServiceVolume('api');
الگو 3: ایجاد دستهای
class VolumeBatch {
constructor(k3) {
this.k3 = k3;
}
async createMultiple(volumes) {
const results = {
succeeded: [],
failed: []
};
for (const vol of volumes) {
try {
const created = await this.k3.volumeCore.createVolume(vol.name, {
size: vol.size,
type: vol.type,
mount: vol.mount
});
results.succeeded.push(created);
} catch (error) {
results.failed.push({
name: vol.name,
error: error.message
});
}
}
return results;
}
}
const batch = new VolumeBatch(k3);
const result = await batch.createMultiple([
{ name: 'vol1', size: '10GB', type: 'custom', mount: '/data1' },
{ name: 'vol2', size: '5GB', type: 'custom', mount: '/data2' }
]);
نکات عملی
-
اندازه Volume:
- برای توسعه: 5-10GB کافی است
- برای production: بسته به نیاز محاسبه کنید
- در نظر گیرید: رشد آتی دادهها
-
نوع Volume:
- custom: برای cache و دادههای موقتی
- custom: برای database و فایلهای مهم
-
Mount Path:
- باید مسیر معتبری باشد
- معمولاً: /data، /app/data، /var/lib/...
- مسیری که کانتینر مینویسد
-
نامگذاری:
- نام معنادار انتخاب کنید
- مثلاً: service-name-vol، db-data-vol
-
Disk Space:
- فضای کافی در سیستم الزامی است
- بزرگتر از اندازه volume انتخابشده
- در نظر گیرید: بقیه volumeها
دنباله عملیات
- اعتبارسنجی نام volume
- اعتبارسنجی schema options
- استخراج size، type، mount
- بررسی فضای دیسک
- ایجاد دایرکتوری mount
- تخصیص فضا
- ثبت metadata
- Logging عملیات
- بازگشت اطلاعات volume
مرجع سریع
| فیلد | نمونه | توضیح |
|---|---|---|
| Name | vlo1 | نام منحصربهفرد |
| Size | 100MB | اندازه (نیاز به فرمت معتبر) |
| Type | persistent | custom یا custom |
| mount | /data | مسیر درون کانتینر |
| CreatedAt | 2025-12-02T06:43:16Z | زمان ایجاد |
| MountDirectory | /var/lib/k3/volume/... | مسیر واقعی |
موارد استفاده
Database Storage
await k3.volumeCore.createVolume('db-vol', {
size: '50GB',
type: 'custom',
mount: '/var/lib/postgresql/data'
});
Application Cache
await k3.volumeCore.createVolume('cache-vol', {
size: '2GB',
type: 'custom',
mount: '/cache'
});
Log Files
await k3.volumeCore.createVolume('logs-vol', {
size: '10GB',
type: 'custom',
mount: '/var/log'
});
User Data
await k3.volumeCore.createVolume('user-data', {
size: '100GB',
type: 'custom',
mount: '/app/data/users'
});
نسخه: 1.3
تاریخ آپدیت: 11 آذر 1404
تیم توسعه: K3 Development Team