بررسی اطلاعات ایمیج
اطلاعات دقیق ایمیج را از رجیستری دور یا محلی دریافت میکند.
🧩 دستور کلی
async inspectAnImage(imageName, postData)
شرح عملکرد
این متد اطلاعات جزئی ایمیج را دریافت میکند. شامل:
- اعتبارسنجی پارامترهای inspection
- بررسی ایمیج از رجیستری
- مدیریت خطاهای مختلف (not found, auth, network)
- دریافت metadata کامل (Digest, Architecture, Layers, etc)
- logging عملیات
مهم: این متد فقط اطلاعات را بررسی میکند و دانلود نمیکند. برای دانلود از pullAnImage() استفاده کنید.
ورودیها
| پارامتر | نوع | اجباری | توضیح |
|---|---|---|---|
imageName | String | بله | نام ایمیج (مثلاً alpine, nginx, myrepo/myimage) |
postData | Object | بله | اطلاعات inspection (imageName, imageTag, transport) |
postData.imageName | String | بله | نام ایمیج |
postData.imageTag | String | خیر | تگ ایمیج (پیشفرض: latest) |
postData.containerImageTransport | String | خیر | نوع transport (docker, oci, etc) |
خروجی
نوع: Object
ساختار خروجی:
{
Digest: 'sha256:85f2b723e106c34644cd5851d7e81ee87da98ac54672b29947c052a45d31dc2f',
RepoTags: [],
Created: '2025-10-08T11:04:56Z',
DockerVersion: '',
Labels: null,
Architecture: 'amd64',
Os: 'linux',
Layers: [
'sha256:2d35ebdb57d9971fea0cac1582aa78935adf8058b2cc32db163c98822e5dfa1b'
],
LayersData: [
{
MIMEType: 'application/vnd.oci.image.layer.v1.tar+gzip',
Digest: 'sha256:2d35ebdb57d9971fea0cac1582aa78935adf8058b2cc32db163c98822e5dfa1b',
Size: 3802452,
Annotations: null
}
],
Env: [
'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
]
}
توضیح فیلدها:
| فیلد | نوع | توضیح |
|---|---|---|
Digest | String | شناسه یکتای ایمیج (SHA256 hash) |
RepoTags | Array | تگهای ایمیج در رجیستری |
Created | String | تاریخ ایجاد ایمیج (ISO format) |
DockerVersion | String | نسخه Docker استفاده شده |
Labels | Object/null | برچسبهای metadata |
Architecture | String | معماری (amd64, arm64, etc) |
Os | String | سیستم عامل (linux, windows) |
Layers | Array | لیست digestهای layer ها |
LayersData | Array | اطلاعات دقیق هر layer |
Env | Array | متغیرهای محیطی تعریف شده |
استثناها (Errors)
InvalidInspectParameters (422)
پیام: "Invalid inspection parameters."
زمان رخ دادن: پارامترهای inspection نامعتبر باشند
جزئیات:
{
"type": "VALIDATION_ERROR",
"statusCode": 422,
"imageName": "invalid@image",
"error": "Image name contains invalid characters"
}
راهنمای حل:
- نام ایمیج را بررسی کنید
- postData را بررسی کنید
- فرمت صحیح:
{imageName: 'alpine', imageTag: 'latest'}
ImageNotFoundInRegistry (404)
پیام: "Image not found in registry."
زمان رخ دادن: ایمیج در رجیستری موجود نیست
جزئیات:
{
"type": "NOT_FOUND",
"statusCode": 404,
"imageName": "nonexistent-app",
"error": "manifest unknown"
}
راهنمای حل:
- نام ایمیج را بررسی کنید
- تگ را بررسی کنید
- ایمیج واقعاً در رجیستری موجود است؟
listImages()استفاده کنید
RegistryAuthenticationFailure (401)
پیام: "Failed to authenticate with registry."
زمان رخ دادن: احراز هویت با رجیستری ناموفق
جزئیات:
{
"type": "NETWORK_ERROR",
"statusCode": 401,
"imageName": "private-repo/private-image",
"error": "unauthorized: authentication required"
}
راهنمای حل:
- credentials را بررسی کنید
- authentication token را تجدید کنید
- اجازه دسترسی را تأیید کنید
- registry private است؟
RegistryConnectionFailure (500)
پیام: "Failed to connect to registry."
زمان رخ دادن: خطا در اتصال به رجیستری
جزئیات:
{
"type": "NETWORK_ERROR",
"statusCode": 500,
"imageName": "alpine",
"error": "connection timeout"
}
راهنمای حل:
- اتصال اینترنت را بررسی کنید
- رجیستری دستیاب است یا خیر؟
- firewall/proxy مسدود نمیکند؟
- DNS resolution درست است؟
InspectImageFailure (500)
پیام: "Failed to inspect image."
زمان رخ دادن: خطای عمومی در inspection
جزئیات:
{
"type": "IMAGE_SERVICE_ERROR",
"statusCode": 500,
"imageName": "nginx",
"error": "Registry inspection failed"
}
راهنمای حل:
- registry manager را بررسی کنید
- لاگهای سیستم را بررسی کنید
- عملیات را دوباره تلاش کنید
GenericFailure (500)
پیام: "Generic failure during image inspection."
زمان رخ دادن: خطای عمومی
جزئیات:
{
"type": "GENERIC_ERROR",
"statusCode": 500,
"error": "Inspect operation failed"
}
راهنمای حل:
- سیستم لاگ را بررسی کنید
- تمام سرویسها را restart کنید
- دوباره تلاش کنید
مثالهای استفاده
مثال 1: Inspect ایمیج ساده
const K3Core = require('k3-core');
(async () => {
const k3 = new K3Core();
try {
const imageInfo = await k3.imageCore.inspectAnImage('alpine', {
imageName: 'alpine',
imageTag: 'latest'
});
console.log('Image Digest:', imageInfo.Digest);
console.log('Architecture:', imageInfo.Architecture);
console.log('OS:', imageInfo.Os);
console.log('Layers:', imageInfo.Layers.length);
} catch (error) {
console.log(error.createFullMessage());
}
})();
مثال 2: Inspect و بررسی اندازه
(async () => {
const k3 = new K3Core();
try {
const imageInfo = await k3.imageCore.inspectAnImage('nginx', {
imageName: 'nginx',
imageTag: '1.25'
});
const totalSize = imageInfo.LayersData.reduce((sum, layer) =>
sum + (layer.Size || 0), 0
);
console.log('Image Name:', 'nginx:1.25');
console.log('Total Size:', (totalSize / 1024 / 1024).toFixed(2), 'MB');
console.log('Created:', imageInfo.Created);
console.log('Architecture:', imageInfo.Architecture);
} catch (error) {
console.log('ERROR: Failed to inspect image');
console.log(error.message);
}
})();
مثال 3: Inspect و نمایش layers
(async () => {
const k3 = new K3Core();
try {
const imageInfo = await k3.imageCore.inspectAnImage('ubuntu', {
imageName: 'ubuntu',
imageTag: '22.04'
});
console.log(`Image: ubuntu:22.04`);
console.log(`Total Layers: ${imageInfo.LayersData.length}\n`);
imageInfo.LayersData.forEach((layer, index) => {
console.log(`Layer ${index + 1}:`);
console.log(` Digest: ${layer.Digest.substring(0, 20)}...`);
console.log(` Size: ${(layer.Size / 1024 / 1024).toFixed(2)} MB`);
console.log(` MIME Type: ${layer.MIMEType}`);
});
} catch (error) {
console.log('ERROR: Failed to inspect image');
}
})();
مثال 4: Inspect و بررسی environment variables
(async () => {
const k3 = new K3Core();
try {
const imageInfo = await k3.imageCore.inspectAnImage('node', {
imageName: 'node',
imageTag: '18'
});
console.log('Image Environment Variables:');
if (imageInfo.Env && imageInfo.Env.length > 0) {
imageInfo.Env.forEach(env => {
const [key, value] = env.split('=');
console.log(` ${key}: ${value}`);
});
} else {
console.log(' No environment variables set');
}
} catch (error) {
console.log('ERROR: Failed to inspect image');
}
})();
مثال 5: Inspect قبل از pull
(async () => {
const k3 = new K3Core();
try {
// Step 1: Inspect
console.log('Inspecting image...');
const imageInfo = await k3.imageCore.inspectAnImage('postgres', {
imageName: 'postgres',
imageTag: '15'
});
// Step 2: Check requirements
const totalSize = imageInfo.LayersData.reduce((sum, layer) =>
sum + (layer.Size || 0), 0
);
console.log('Image Size:', (totalSize / 1024 / 1024).toFixed(2), 'MB');
console.log('Architecture:', imageInfo.Architecture);
console.log('OS:', imageInfo.Os);
// Step 3: Pull if conditions met
if (imageInfo.Architecture === 'amd64' && imageInfo.Os === 'linux') {
console.log('Conditions met, pulling image...');
const pullResult = await k3.imageCore.pullAnImage('postgres', '15');
console.log(pullResult);
} else {
console.log('WARNING: Image architecture or OS not compatible');
}
} catch (error) {
console.log('ERROR:', error.message);
}
})();
مثال 6: Inspect با مدیریت خطاهای مختلف
(async () => {
const k3 = new K3Core();
const inspectWithErrorHandling = async (imageName, imageTag) => {
try {
const imageInfo = await k3.imageCore.inspectAnImage(imageName, {
imageName: imageName,
imageTag: imageTag
});
return { success: true, data: imageInfo };
} catch (error) {
if (error.statusCode === 404) {
console.log(`Image ${imageName}:${imageTag} not found in registry`);
return { success: false, error: 'Not found' };
} else if (error.statusCode === 401) {
console.log(`Authentication failed for ${imageName}:${imageTag}`);
return { success: false, error: 'Authentication failed' };
} else if (error.statusCode === 500) {
console.log(`Connection error while inspecting ${imageName}:${imageTag}`);
return { success: false, error: 'Connection error' };
} else {
console.log(`Failed to inspect ${imageName}:${imageTag}`);
return { success: false, error: error.message };
}
}
};
const result = await inspectWithErrorHandling('myapp', 'v1.0');
console.log('Inspection result:', result);
})();
مثال 7: Inspect چند ایمیج
(async () => {
const k3 = new K3Core();
const images = [
{ name: 'alpine', tag: 'latest' },
{ name: 'nginx', tag: '1.25' },
{ name: 'node', tag: '18' }
];
const results = [];
for (const img of images) {
try {
const imageInfo = await k3.imageCore.inspectAnImage(img.name, {
imageName: img.name,
imageTag: img.tag
});
const size = imageInfo.LayersData.reduce((sum, layer) =>
sum + (layer.Size || 0), 0
);
results.push({
image: `${img.name}:${img.tag}`,
size: (size / 1024 / 1024).toFixed(2) + ' MB',
architecture: imageInfo.Architecture,
os: imageInfo.Os,
layers: imageInfo.LayersData.length
});
console.log(`✓ Inspected ${img.name}:${img.tag}`);
} catch (error) {
console.log(`✗ Failed to inspect ${img.name}:${img.tag} - ${error.message}`);
}
}
console.log('\nInspection Results:');
console.table(results);
})();
مثال 8: Inspect و تجزیه فایل metadata
(async () => {
const k3 = new K3Core();
try {
const imageInfo = await k3.imageCore.inspectAnImage('alpine', {
imageName: 'alpine',
imageTag: 'latest'
});
// Extract metadata
const metadata = {
digest: imageInfo.Digest,
created: new Date(imageInfo.Created),
arch: imageInfo.Architecture,
os: imageInfo.Os,
totalLayers: imageInfo.LayersData.length,
totalSize: imageInfo.LayersData.reduce((sum, l) => sum + (l.Size || 0), 0),
layers: imageInfo.LayersData.map((l, i) => ({
index: i,
digest: l.Digest.substring(0, 12),
size: (l.Size / 1024).toFixed(0) + ' KB'
}))
};
console.log('=== Image Metadata ===');
console.log('Digest:', metadata.digest);
console.log('Created:', metadata.created);
console.log('Architecture:', metadata.arch);
console.log('OS:', metadata.os);
console.log('Total Layers:', metadata.totalLayers);
console.log('Total Size:', (metadata.totalSize / 1024 / 1024).toFixed(2), 'MB');
console.log('\nLayers:');
console.table(metadata.layers);
} catch (error) {
console.log('ERROR: Failed to inspect image');
}
})();
الگوهای خطا و راهنمای حل
الگو 1: ایمیج در رجیستری یافت نشد
خطا: ImageNotFoundInRegistry (404)
راهنمای حل:
const inspectWithFallback = async (imageName, imageTag) => {
try {
const imageInfo = await k3.imageCore.inspectAnImage(imageName, {
imageName: imageName,
imageTag: imageTag
});
console.log('Inspect successful');
return imageInfo;
} catch (error) {
if (error.statusCode === 404) {
console.log(`Image ${imageName}:${imageTag} not found`);
console.log('Trying alternative sources...');
const alternatives = [
{ name: 'gcr.io/' + imageName, tag: imageTag },
{ name: 'quay.io/' + imageName, tag: imageTag },
{ name: imageName, tag: 'latest' }
];
for (const alt of alternatives) {
try {
const info = await k3.imageCore.inspectAnImage(alt.name, {
imageName: alt.name,
imageTag: alt.tag
});
console.log(`Found at: ${alt.name}:${alt.tag}`);
return info;
} catch (e) {
console.log(`Not found at ${alt.name}:${alt.tag}`);
}
}
throw new Error(`Could not find ${imageName}:${imageTag} anywhere`);
}
throw error;
}
};
await inspectWithFallback('myapp', 'v1.0');
الگو 2: احراز هویت ناموفق
خطا: RegistryAuthenticationFailure (401)
راهنمای حل:
const inspectPrivateImage = async (imageName, imageTag, credentials) => {
try {
// First attempt without auth
const imageInfo = await k3.imageCore.inspectAnImage(imageName, {
imageName: imageName,
imageTag: imageTag
});
console.log('Inspect successful without authentication');
return imageInfo;
} catch (error) {
if (error.statusCode === 401) {
console.log('Authentication required');
if (!credentials) {
throw new Error('Credentials required for private image');
}
// Retry with credentials
console.log('Attempting with credentials...');
try {
// Note: Implementation depends on system support
const imageInfo = await k3.imageCore.inspectAnImage(imageName, {
imageName: imageName,
imageTag: imageTag,
credentials: credentials
});
console.log('Inspect successful with authentication');
return imageInfo;
} catch (authError) {
throw new Error('Authentication failed with provided credentials');
}
}
throw error;
}
};
const result = await inspectPrivateImage('private-repo/app', 'v1.0', {
username: 'user',
password: 'pass'
});
الگو 3: خطای شبکه
خطا: RegistryConnectionFailure (500)
راهنمای حل:
const inspectWithRetry = async (imageName, imageTag, maxRetries = 3) => {
let lastError;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
console.log(`Inspect attempt ${attempt}/${maxRetries}`);
const imageInfo = await k3.imageCore.inspectAnImage(imageName, {
imageName: imageName,
imageTag: imageTag
});
console.log('Inspect successful');
return imageInfo;
} catch (error) {
if (error.statusCode === 500 && error.message.includes('connection')) {
lastError = error;
if (attempt < maxRetries) {
const waitTime = Math.pow(2, attempt) * 1000;
console.log(`Connection error, retrying in ${waitTime / 1000}s...`);
await new Promise(resolve => setTimeout(resolve, waitTime));
}
} else {
throw error;
}
}
}
throw lastError;
};
const result = await inspectWithRetry('nginx', '1.25');
الگو 4: Inspect و cache نتایج
راهنمای حل:
class ImageInspectCache {
constructor(k3, cacheTime = 3600000) { // 1 hour default
this.k3 = k3;
this.cache = new Map();
this.cacheTime = cacheTime;
}
async inspect(imageName, imageTag) {
const cacheKey = `${imageName}:${imageTag}`;
// Check cache
if (this.cache.has(cacheKey)) {
const cached = this.cache.get(cacheKey);
if (Date.now() - cached.timestamp < this.cacheTime) {
console.log(`Using cached inspection for ${cacheKey}`);
return cached.data;
}
}
// Inspect
console.log(`Inspecting ${cacheKey}...`);
const imageInfo = await this.k3.imageCore.inspectAnImage(imageName, {
imageName: imageName,
imageTag: imageTag
});
// Cache result
this.cache.set(cacheKey, {
data: imageInfo,
timestamp: Date.now()
});
console.log(`Cached inspection for ${cacheKey}`);
return imageInfo;
}
invalidate(imageName, imageTag) {
const cacheKey = `${imageName}:${imageTag}`;
this.cache.delete(cacheKey);
console.log(`Cache invalidated for ${cacheKey}`);
}
}
const cache = new ImageInspectCache(k3);
const info1 = await cache.inspect('alpine', 'latest');
const info2 = await cache.inspect('alpine', 'latest'); // From cache
الگو 5: Inspect و قرارداد compatibility
راهنمای حل:
class CompatibilityChecker {
constructor(k3) {
this.k3 = k3;
this.requiredArch = 'amd64';
this.requiredOs = 'linux';
}
async checkCompatibility(imageName, imageTag) {
try {
const imageInfo = await this.k3.imageCore.inspectAnImage(imageName, {
imageName: imageName,
imageTag: imageTag
});
const compatible = {
arch: imageInfo.Architecture === this.requiredArch,
os: imageInfo.Os === this.requiredOs,
overall: imageInfo.Architecture === this.requiredArch &&
imageInfo.Os === this.requiredOs
};
console.log(`Image: ${imageName}:${imageTag}`);
console.log(` Architecture: ${imageInfo.Architecture} (Required: ${this.requiredArch}) - ${compatible.arch ? 'OK' : 'INCOMPATIBLE'}`);
console.log(` OS: ${imageInfo.Os} (Required: ${this.requiredOs}) - ${compatible.os ? 'OK' : 'INCOMPATIBLE'}`);
console.log(` Overall: ${compatible.overall ? 'COMPATIBLE' : 'NOT COMPATIBLE'}`);
return compatible;
} catch (error) {
console.log(`Failed to check compatibility: ${error.message}`);
return { arch: false, os: false, overall: false, error: error.message };
}
}
}
const checker = new CompatibilityChecker(k3);
await checker.checkCompatibility('alpine', 'latest');
نکات عملی
-
Performance:
- Inspect سریعتر از pull است
- بدون دانلود، صرفاً metadata
- میتوانید قبل از pull بررسی کنید
-
اتصال شبکه:
- اتصال به رجیستری نیاز است
- firewall/proxy مسدود نباید کند
- timeout ممکن است برای رجیستریهای بعید
-
احراز هویت:
- برخی ایمیجها private است
- نیاز به credentials دارند
- public images بدون auth کار میکنند
-
معماری:
- مختلف معماریها موجود است (amd64, arm64, etc)
- compatibility چک کنید قبل از pull
-
Caching:
- نتایج را cache کنید برای بهتری
- cache time را مناسب تنظیم کنید
-
Layer Information:
- LayersData شامل تفاصیل هر layer
- Size برای bandwidth calculation مهم
- Digest برای verification استفاده میشود
دنباله عملیات
- اعتبارسنجی پارامترها
- بررسی ایمیج از رجیستری
- مدیریت خطاهای مختلف
- درج metadata
- دریافت layer information
- Logging موفقیت
مرجع سریع
| وضعیت | کد | توضیح |
|---|---|---|
| موفق | 200 | Inspect موفق |
| پارامتر نامعتبر | 422 | InvalidInspectParameters |
| ایمیج یافت نشد | 404 | ImageNotFoundInRegistry |
| احراز هویت ناموفق | 401 | RegistryAuthenticationFailure |
| خطای شبکه | 500 | RegistryConnectionFailure |
| خطای inspection | 500 | InspectImageFailure |
| خطای عمومی | 500 | GenericFailure |
موارد استفاده
Pre-Pull Verification
const info = await inspectAnImage('app', { imageName: 'app', imageTag: 'v1.0' });
Compatibility Check
if (info.Architecture === 'amd64') await pullAnImage(...);
Size Estimation
const size = info.LayersData.reduce((s, l) => s + l.Size, 0);
Metadata Analysis
console.log('Created:', info.Created);
console.log('Layers:', info.LayersData.length);
نسخه: 1.3
تاریخ آپدیت: 10 آذرماه ۱۴۰۴
تیم توسعه: K3 Development Team