صادر کردن کانتینر به فایل TAR
کانتینر را صادر کرده و فایلهای آن را در یک فایل TAR ذخیره میکند.
🧩 دستور کلی
async exportContainer(containerId, filePath)
شرح عملکرد
این متد کانتینر را صادر کرده و فایلهای آن را TAR میکند. شامل:
- اعتبارسنجی پارامترهای صادرات
- تحقق هویت کانتینر
- دریافت اطلاعات کانتینر و مسیر bundle
- استخراج hash ID کانتینر
- صادرات فایلهای کانتینر به TAR
- مدیریت خطاهای فایل سیستم
- logging عملیات
مهم: کانتینر باید موجود باشد. صادرات تمام فایلهای کانتینر را شامل میشود (فایلهای سیستم، فایلهای تغییریافته، و metadata).
ورودیها
| پارامتر | نوع | اجباری | توضیح |
|---|---|---|---|
containerId | String | بله | شناسه یا نام کانتینر (میتواند partial match) |
filePath | String | بله | مسیر کامل فایل TAR خروجی (مثلاً /tmp/container.tar, /backup/container.tar.gz) |
خروجی
نوع: String
پیام موفقیت:
my-container has exported successfully to /tmp/my-container.tar
یا:
web-server has exported successfully to /backup/web-server.tar.gz
استثناها (Errors)
InvalidExportContainerParameters (422)
پیام: "Invalid export container parameters."
زمان رخ دادن: پارامترهای صادرات نامعتبر باشند
جزئیات:
{
"type": "VALIDATION_ERROR",
"statusCode": 422,
"containerId": "invalid@container",
"filePath": "/tmp/container.tar",
"error": "Container ID contains invalid characters"
}
راهنمای حل:
- شناسه کانتینر: فقط حروف، اعداد، '-', '_' مجاز
- مسیر فایل: معتبر و کامل باشد
- پارامترها باید معتبر باشند
ResolveContainerName (500)
پیام: "Failed to resolve container name."
زمان رخ دادن: خطا در تحقق هویت کانتینر
جزئیات:
{
"type": "DB_ERROR",
"statusCode": 500,
"containerId": "my-container",
"error": "Database query failed"
}
راهنمای حل:
- اتصال دیتابیس را بررسی کنید
- دیتابیس را restart کنید
ContainerNotFound (404)
پیام: "Container not found."
زمان رخ دادن: کانتینر موجود نیست
جزئیات:
{
"type": "NOT_FOUND",
"statusCode": 404,
"containerId": "nonexistent-container",
"error": "Container not found"
}
راهنمای حل:
- نام کانتینر را بررسی کنید
- کانتینر واقعاً موجود است؟
listContainers()استفاده کنید
FetchContainerInfoFailure (500)
پیام: "Failed to fetch container information."
زمان رخ دادن: خطا در دریافت اطلاعات کانتینر
جزئیات:
{
"type": "CONTAINER_SERVICE_ERROR",
"statusCode": 500,
"containerId": "my-container",
"error": "Container manager communication failed"
}
راهنمای حل:
- Container Manager را بررسی کنید
- اتصال سرویس را تأیید کنید
- لاگهای سیستم را بررسی کنید
ExportContainerPermissionDenied (403)
پیام: "Permission denied to export container."
زمان رخ دادن: اجازههای نوشتن در مسیر فایل موجود نیست
جزئیات:
{
"type": "FILE_SYSTEM_ERROR",
"statusCode": 403,
"containerId": "my-container",
"filePath": "/root/protected/container.tar",
"error": "Permission denied (EACCES)"
}
راهنمای حل:
- اجازههای فایل سیستم را بررسی کنید
- مسیری با اجازههای نوشتن استفاده کنید
- chmod یا chown استفاده کنید
InsufficientDiskSpaceForExport (507)
پیام: "Insufficient disk space to export container."
زمان رخ دادن: فضای دیسک برای صادرات کانتینر کافی نیست
جزئیات:
{
"type": "FILE_SYSTEM_ERROR",
"statusCode": 507,
"containerId": "my-container",
"filePath": "/tmp/container.tar",
"requiredSpace": "5 GB",
"availableSpace": "2 GB",
"error": "No space left on device (ENOSPC)"
}
راهنمای حل:
- فضای دیسک کافی کنید
- فایلهای غیر ضروری را حذف کنید
- مسیر دیسک دیگری استفاده کنید
ReadOnlyFileSystem (500)
پیام: "File system is read-only."
زمان رخ دادن: فایل سیستم read-only است
جزئیات:
{
"type": "FILE_SYSTEM_ERROR",
"statusCode": 500,
"filePath": "/mnt/readonly/container.tar",
"error": "Read-only file system (EROFS)"
}
راهنمای حل:
- فایل سیستم را remount کنید (writable)
- مسیر دیگری استفاده کنید
- اجازههای mount را بررسی کنید
ContainerBundleNotFound (500)
پیام: "Container bundle not found."
زمان رخ دادن: فایلهای bundle کانتینر یافت نشدند
جزئیات:
{
"type": "IMAGE_SERVICE_ERROR",
"statusCode": 500,
"containerId": "my-container",
"bundleHashId": "abc123def456",
"error": "Bundle directory not found"
}
راهنمای حل:
- دایرکتوری bundle را بررسی کنید
- فایلهای کانتینر موجود هستند؟
- لاگهای سیستم را بررسی کنید
ExportContainerIOFailure (500)
پیام: "IO failure during container export."
زمان رخ دادن: خطای IO درخواندن یا نوشتن
جزئیات:
{
"type": "FILE_SYSTEM_ERROR",
"statusCode": 500,
"containerId": "my-container",
"filePath": "/tmp/container.tar",
"error": "IO exception"
}
راهنمای حل:
- سلامت هارد دیسک را بررسی کنید
- سیستم فایل را بررسی کنید (fsck)
- لاگهای سیستم را بررسی کنید
ExportContainerFailure (500)
پیام: "Failed to export container."
زمان رخ دادن: خطای عمومی در صادرات کانتینر
جزئیات:
{
"type": "IMAGE_SERVICE_ERROR",
"statusCode": 500,
"containerId": "my-container",
"filePath": "/tmp/container.tar",
"error": "Export operation failed"
}
راهنمای حل:
- ImageManager را بررسی کنید
- لاگهای سیستم را بررسی کنید
- دوباره تلاش کنید
GenericFailure (500)
پیام: "Generic failure during container export."
زمان رخ دادن: خطای عمومی
جزئیات:
{
"type": "GENERIC_ERROR",
"statusCode": 500,
"error": "Container export failed"
}
راهنمای حل:
- سیستم لاگ را بررسی کنید
- تمام سرویسها را restart کنید
- دوباره تلاش کنید
مثالهای استفاده
مثال 1: صادر کردن کانتینر ساده
const K3Core = require('k3-core');
(async () => {
const k3 = new K3Core();
try {
const result = await k3.containerCore.exportContainer(
'my-container',
'/tmp/my-container.tar'
);
console.log('Success:', result);
// Output: my-container has exported successfully to /tmp/my-container.tar
} catch (error) {
console.log('ERROR:', error.createFullMessage());
}
})();
مثال 2: صادر کردن کانتینر در حال اجرا
(async () => {
const k3 = new K3Core();
try {
// List running containers
const containers = await k3.containerCore.listContainers({ state: 'running' });
console.log('Running containers:', containers.length);
if (containers.length > 0) {
const container = containers[0];
// Export container
const result = await k3.containerCore.exportContainer(
container.Id,
`/backup/${container.Name}.tar`
);
console.log('Export result:', result);
console.log(`Container exported: ${container.Name}`);
}
} catch (error) {
console.log('ERROR:', error.message);
}
})();
مثال 3: صادر کردن و verify
(async () => {
const k3 = new K3Core();
const fs = require('fs');
try {
// Step 1: Export
console.log('Exporting container...');
const exportResult = await k3.containerCore.exportContainer(
'web-server',
'/tmp/web-server-backup.tar'
);
console.log('Export result:', exportResult);
// Step 2: Verify
console.log('Verifying file...');
const stats = fs.statSync('/tmp/web-server-backup.tar');
console.log('File verified:');
console.log(` Size: ${(stats.size / 1024 / 1024).toFixed(2)} MB`);
console.log(` Created: ${stats.birthtime}`);
} catch (error) {
console.log('ERROR:', error.message);
}
})();
مثال 4: صادر کردن چند کانتینر
(async () => {
const k3 = new K3Core();
const containersToExport = [
{ name: 'web-server', path: '/backup/web-server.tar' },
{ name: 'database', path: '/backup/database.tar' },
{ name: 'cache', path: '/backup/cache.tar' }
];
const results = [];
for (const container of containersToExport) {
try {
const result = await k3.containerCore.exportContainer(
container.name,
container.path
);
results.push({
container: container.name,
status: 'success',
message: result
});
console.log(`✓ ${container.name} exported`);
} catch (error) {
results.push({
container: container.name,
status: 'failed',
error: error.message
});
console.log(`✗ Failed to export ${container.name}`);
}
}
console.log('\nExport Summary:');
console.table(results);
})();
مثال 5: صادر کردن با مدیریت خطاهای مختلف
(async () => {
const k3 = new K3Core();
const fs = require('fs');
const exportWithErrorHandling = async (containerId, filePath) => {
try {
// Check disk space
const dirPath = filePath.substring(0, filePath.lastIndexOf('/'));
const stats = fs.statSync(dirPath);
const availableSpace = stats.bavail * stats.bsize;
console.log(`Available space: ${(availableSpace / 1024 / 1024 / 1024).toFixed(2)} GB`);
const result = await k3.containerCore.exportContainer(containerId, filePath);
return { success: true, message: result };
} catch (error) {
if (error.statusCode === 404) {
console.log(`ERROR: Container ${containerId} not found`);
return { success: false, error: 'Container not found' };
} else if (error.statusCode === 403) {
console.log(`ERROR: Permission denied for ${filePath}`);
return { success: false, error: 'Permission denied' };
} else if (error.statusCode === 507) {
console.log(`ERROR: Insufficient disk space`);
return { success: false, error: 'Insufficient disk space' };
} else if (error.statusCode === 422) {
console.log('ERROR: Invalid parameters');
return { success: false, error: 'Invalid parameters' };
} else {
console.log(`ERROR: Export failed - ${error.message}`);
return { success: false, error: error.message };
}
}
};
const result = await exportWithErrorHandling('my-container', '/tmp/my-container.tar');
console.log('Result:', result);
})();
مثال 6: صادر کردن برای backup
(async () => {
const k3 = new K3Core();
const fs = require('fs');
const path = require('path');
const createContainerBackup = async (containerId) => {
try {
// Create backup directory
const backupDir = '/backups/containers';
if (!fs.existsSync(backupDir)) {
fs.mkdirSync(backupDir, { recursive: true });
}
// Generate backup filename
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const backupFile = path.join(backupDir, `${containerId}-${timestamp}.tar`);
console.log(`Creating backup: ${backupFile}`);
const result = await k3.containerCore.exportContainer(containerId, backupFile);
// Get file info
const stats = fs.statSync(backupFile);
console.log('Backup created:');
console.log(` File: ${backupFile}`);
console.log(` Size: ${(stats.size / 1024 / 1024).toFixed(2)} MB`);
return { success: true, backupFile: backupFile, size: stats.size };
} catch (error) {
console.log('ERROR:', error.message);
return { success: false, error: error.message };
}
};
const backup = await createContainerBackup('my-container');
console.log('Backup result:', backup);
})();
مثال 7: صادر کردن برای انتقال
(async () => {
const k3 = new K3Core();
try {
// Step 1: Get container info
console.log('Step 1: Getting container info...');
const containers = await k3.containerCore.listContainers({ name: 'app-server' });
if (containers.length === 0) {
throw new Error('Container not found');
}
const container = containers[0];
console.log(`Container: ${container.Name}`);
console.log(`Status: ${container.State}`);
// Step 2: Export
console.log('Step 2: Exporting container...');
const exportFile = `/transfer/${container.Name}-migration.tar.gz`;
const result = await k3.containerCore.exportContainer(container.Id, exportFile);
console.log('✓ Export completed');
// Step 3: Create checksum
console.log('Step 3: Creating checksum...');
const crypto = require('crypto');
const fs = require('fs');
const hash = crypto.createHash('sha256');
const stream = fs.createReadStream(exportFile);
stream.on('data', data => hash.update(data));
stream.on('end', () => {
const checksum = hash.digest('hex');
console.log(`✓ Checksum: ${checksum}`);
console.log(`\nReady for transfer:`);
console.log(` File: ${exportFile}`);
console.log(` Checksum: ${checksum}`);
});
} catch (error) {
console.log('ERROR:', error.message);
}
})();
مثال 8: صادر کردن و cleanup
(async () => {
const k3 = new K3Core();
const fs = require('fs');
try {
// Step 1: Export
console.log('Step 1: Exporting container...');
const exportResult = await k3.containerCore.exportContainer(
'old-service',
'/tmp/old-service-export.tar'
);
console.log('✓ Container exported');
// Step 2: Verify export
console.log('Step 2: Verifying export...');
const stats = fs.statSync('/tmp/old-service-export.tar');
console.log(`✓ Export verified (${(stats.size / 1024 / 1024).toFixed(2)} MB)`);
// Step 3: Move to permanent location
console.log('Step 3: Moving to archive...');
const archivePath = `/archive/old-service-${Date.now()}.tar`;
fs.renameSync('/tmp/old-service-export.tar', archivePath);
console.log(`✓ Moved to ${archivePath}`);
// Step 4: Remove container (optional)
console.log('Step 4: Removing old container...');
await k3.containerCore.removeContainer('old-service');
console.log('✓ Old container removed');
console.log('\n✓ Successfully archived and removed old container');
} catch (error) {
console.log('ERROR:', error.message);
}
})();
الگوهای خطا و راهنمای حل
الگو 1: کانتینر یافت نشد
خطا: ContainerNotFound (404)
راهنمای حل:
const exportWithContainerCheck = async (containerId, filePath) => {
try {
const result = await k3.containerCore.exportContainer(containerId, filePath);
return result;
} catch (error) {
if (error.statusCode === 404) {
console.log(`Container ${containerId} not found`);
// Get available containers
const containers = await k3.containerCore.listContainers();
console.log('Available containers:');
containers.forEach(c => {
console.log(` - ${c.Name} (${c.State})`);
});
throw new Error(`Container ${containerId} not found. Use one from list above.`);
}
throw error;
}
};
await exportWithContainerCheck('my-container', '/tmp/my-container.tar');
الگو 2: فضای دیسک ناکافی
خطا: InsufficientDiskSpaceForExport (507)
راهنمای حل:
const exportWithDiskCheck = async (containerId, filePath) => {
const fs = require('fs');
try {
// Check available space
const dirPath = filePath.substring(0, filePath.lastIndexOf('/'));
const stats = fs.statSync(dirPath);
const availableSpace = stats.bavail * stats.bsize;
console.log(`Available space: ${(availableSpace / 1024 / 1024 / 1024).toFixed(2)} GB`);
if (availableSpace < 1 * 1024 * 1024 * 1024) {
console.log('WARNING: Less than 1GB available');
console.log('Attempting to free space...');
// Try to clean up temp directory
const tmpDir = '/tmp';
const files = fs.readdirSync(tmpDir).filter(f => f.endsWith('.tar'));
for (const file of files.slice(0, 3)) { // Remove only a few files
fs.unlinkSync(`${tmpDir}/${file}`);
console.log(`Removed ${file}`);
}
}
const result = await k3.containerCore.exportContainer(containerId, filePath);
return { success: true, message: result };
} catch (error) {
if (error.statusCode === 507) {
console.log('ERROR: Insufficient disk space');
return { success: false, error: 'Insufficient disk space' };
}
throw error;
}
};
await exportWithDiskCheck('my-container', '/tmp/my-container.tar');
الگو 3: اجازههای فایل
خطا: ExportContainerPermissionDenied (403)
راهنمای حل:
const exportWithPermissionCheck = async (containerId, filePath) => {
const fs = require('fs');
try {
// Check if directory is writable
const dir = filePath.substring(0, filePath.lastIndexOf('/'));
try {
fs.accessSync(dir, fs.constants.W_OK);
console.log(`Directory is writable: ${dir}`);
} catch (err) {
console.log(`ERROR: Directory not writable: ${dir}`);
console.log('Available alternatives:');
console.log(' - /tmp (usually writable)');
console.log(' - /home/user (your home directory)');
throw new Error('Directory not writable');
}
const result = await k3.containerCore.exportContainer(containerId, filePath);
return { success: true, message: result };
} catch (error) {
if (error.statusCode === 403) {
console.log('ERROR: Permission denied');
return { success: false, error: 'Permission denied' };
}
throw error;
}
};
await exportWithPermissionCheck('my-container', '/tmp/my-container.tar');
نکات عملی
-
فضای دیسک:
- کانتینر بزرگ نیاز به فضا دارد
- حداقل 2x اندازه کانتینر نیاز است
- بررسی فضای دیسک قبل از صادرات
-
اجازههای فایل:
- مسیر باید writable باشد
- /tmp معمولاً writable است
- /root احتمالاً نیاز به sudo دارد
-
شناسه کانتینر:
- partial match پذیرفته میشود
- میتواند نام یا ID باشد
- single container باید match شود
-
Performance:
- کانتینرهای بزرگ زمانبر هستند
- SSD سریعتر از HDD است
- compression سرعت را کاهش میدهد
-
Backup:
- timestamp استفاده کنید برای backup
- چند نسخه نگهداری کنید
- مسیر دایمالوصول استفاده کنید
-
فایلهای کانتینر:
- تمام فایلها صادر میشود
- فایلهای تغییریافته شامل میشود
- metadata نیز شامل میشود
دنباله عملیات
- اعتبارسنجی پارامترها
- تحقق هویت کانتینر
- دریافت اطلاعات کانتینر
- استخراج hash ID
- صادرات فایلهای کانتینر
- مدیریت خطاهای فایل سیستم
- Logging موفقیت
مرجع سریع
| وضعیت | کد | توضیح |
|---|---|---|
| موفق | 200 | صادرات موفق |
| پارامتر نامعتبر | 422 | InvalidExportContainerParameters |
| resolve خطا | 500 | ResolveContainerName |
| کانتینر یافت نشد | 404 | ContainerNotFound |
| اطلاعات خطا | 500 | FetchContainerInfoFailure |
| اجازه رد شد | 403 | ExportContainerPermissionDenied |
| فضای کم | 507 | InsufficientDiskSpaceForExport |
| فایل سیستم read-only | 500 | ReadOnlyFileSystem |
| bundle یافت نشد | 500 | ContainerBundleNotFound |
| خطای IO | 500 | ExportContainerIOFailure |
| خطای export | 500 | ExportContainerFailure |
| خطای عمومی | 500 | GenericFailure |
موارد استفاده
Container Backup
const result = await exportContainer('my-container', '/backups/my-container.tar');
Migration
const result = await exportContainer('web-app', '/transfer/web-app-migration.tar');
Archive Creation
const result = await exportContainer('old-service', '/archive/old-service.tar');
Data Preservation
const result = await exportContainer('database', '/preserve/database-snapshot.tar');
نسخه: 1.3
تاریخ آپدیت: 10 آذرماه ۱۴۰۴
تیم توسعه: K3 Development Team