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

ارسال سیگنال برای کانتینر

کانتینری که درخواست شده را برای ارسال سیگنال POSIX کوئری می‌کند.


🧩 دستور کلی

async killContainer(containerId, signal = '9', options = {})

شرح عملکرد

این متد سیگنال POSIX مشخص شده را به کانتینر معین ارسال می‌کند. سیگنال پیش‌فرض SIGKILL است که باعث خاتمه فوری کانتینر می‌شود.

می‌توانید:

  • زمان انتظار قبل از ارسال سیگنال تنظیم کنید
  • انتخاب کنید که تمام پردازش‌ها یا کل کانتینر کشته شود
  • حالت debug را فعال کنید

ورودی‌ها

پارامترنوعاجباریتوضیح
containerIdStringبلهشناسه یا نام کانتینر برای ارسال سیگنال
signalString/Numberبلهسیگنال POSIX (مثل: SIGKILL، SIGTERM، 9، 15)
optionsObjectخیرگزینه‌های اختیاری
options.timeNumberخیرمدت انتظار قبل از ارسال سیگنال (ثانیه)
options.allBooleanخیرکشتن تمام پردازش‌ها درون کانتینر
options.debugBooleanخیرفعال کردن حالت debug

خروجی

نوع: String (پیام نتیجه عملیات)

خروجی:

Using debug verbosity

یا نتیجه معمولی از runtime.


استثناها (Errors)

ContainerNotFound (404)

پیام: "No container exists with the specified name or ID prefix."

زمان رخ دادن: کانتینری با شناسه/نام درخواستی یافت نشود

جزئیات:

{
"type": "NOT_FOUND",
"statusCode": 404,
"containerId": "invalid-id"
}

راهنمای حل:

  • شناسه کانتینر را بررسی کنید
  • listContainers() استفاده کنید تا تمام کانتینرها را ببینید
  • نام یا ID صحیح را وارد کنید

ResolveContainerName (500)

پیام: "Database error occurred while resolving container name or ID."

زمان رخ دادن: خطای دیتابیس در تطابق شناسه/نام کانتینر

جزئیات:

{
"type": "DB_ERROR",
"statusCode": 500,
"input": "container-id",
"error": "Database connection lost"
}

راهنمای حل:

  • اتصال دیتابیس را بررسی کنید
  • لاگ‌های دیتابیس را مطالعه کنید
  • دیتابیس را راه‌اندازی کنید

FetchContainerState (500)

پیام: "Database error occurred while fetching container state."

زمان رخ دادن: خطای دیتابیس هنگام خواندن وضعیت کانتینر

جزئیات:

{
"type": "DB_ERROR",
"statusCode": 500,
"containerId": "abc123def456",
"error": "Query timeout"
}

راهنمای حل:

  • دیتابیس را بررسی کنید
  • اتصال را تأیید کنید

ContainerAlreadyKilled (400)

پیام: "Container is already killed."

زمان رخ دادن: کانتینر قبلاً کشته شده است

جزئیات:

{
"type": "INVALID_STATE",
"statusCode": 400,
"containerId": "abc123def456"
}

راهنمای حل:

  • کانتینر قبلاً کشته شده است
  • برای شروع دوباره از startContainer() استفاده کنید

OptionConflict (422)

پیام: "Failed to validate kill options."

زمان رخ دادن: گزینه‌های ورودی نامعتبر باشند

جزئیات:

{
"type": "VALIDATION_ERROR",
"statusCode": 422,
"containerId": "abc123def456",
"error": "Invalid schema"
}

راهنمای حل:

  • گزینه‌های ورودی را بررسی کنید
  • time باید Number باشد
  • all و debug باید Boolean باشند

BuildKillDTO (422)

پیام: "Failed to build kill container DTO options."

زمان رخ دادن: خطا در ساخت دستورات kill

جزئیات:

{
"type": "VALIDATION_ERROR",
"statusCode": 422,
"containerId": "abc123def456",
"error": "Invalid signal format"
}

راهنمای حل:

  • سیگنال را بررسی کنید
  • از سیگنال‌های معتبر استفاده کنید (SIGKILL، SIGTERM، ...)

KillFailure (500)

پیام: "Failed to kill container through ContainerManager."

زمان رخ دادن: خطا در کشتن کانتینر

جزئیات:

{
"type": "CONTAINER_SERVICE_ERROR",
"statusCode": 500,
"containerId": "abc123def456",
"error": "Runtime error"
}

راهنمای حل:

  • سرویس K3 فعال است یا خیر؟
  • لاگ‌های سرویس را مطالعه کنید

PIDNotFound (404)

پیام: "No process found for the specified container."

زمان رخ دادن: PID پروسس کانتینر یافت نشود

جزئیات:

{
"type": "NOT_FOUND",
"statusCode": 404,
"containerId": "abc123def456",
"error": "No process found"
}

راهنمای حل:

  • کانتینر ممکن است تمام پردازش‌ها را اتمام داده باشد
  • وضعیت کانتینر را بررسی کنید

UpdateContainerStateFailure (500)

پیام: "Failed to update container state after kill."

زمان رخ دادن: خطا در بروزرسانی وضعیت دیتابیس بعد از kill

جزئیات:

{
"type": "DB_ERROR",
"statusCode": 500,
"containerId": "abc123def456",
"pid": 24006,
"error": "Database write failed"
}

راهنمای حل:

  • دیتابیس را بررسی کنید
  • اتصال را تأیید کنید

FetchContainerStatusFailure (500)

پیام: "Failed to fetch container status."

زمان رخ دادن: خطای عمومی در دریافت وضعیت

جزئیات:

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

راهنمای حل:

  • سرویس‌های K3 را دوباره شروع کنید
  • لاگ‌ها را بررسی کنید

سیگنال‌های POSIX

سیگنالشمارهتوضیح
SIGHUP1Hangup detected on controlling terminal
SIGINT2Interrupt from keyboard (Ctrl+C)
SIGQUIT3Quit from keyboard
SIGABRT6Abort signal from abort()
SIGKILL9Kill signal (نمی‌توان بلاک یا صید کرد)
SIGTERM15Termination signal (graceful shutdown)
SIGSTOP19Stop process (نمی‌توان صید کرد)

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

مثال 1: ارسال سیگنال SIGKILL ساده

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

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

try {
const result = await k3.containerCore.killContainer('my-container', 'SIGKILL');
console.log('Container killed successfully');
console.log(result);
} catch (error) {
console.log(error.createFullMessage());
}
})();

مثال 2: ارسال سیگنال با شماره

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

try {
// SIGTERM (15) برای خاتمه مرتب
const result = await k3.containerCore.killContainer('app-container', 15);
console.log('Graceful termination sent');
} catch (error) {
console.log(error.createFullMessage());
}
})();

مثال 3: ارسال سیگنال با تأخیر

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

try {
// 10 ثانیه صبر قبل از کشتن
const result = await k3.containerCore.killContainer('worker-container', 'SIGKILL', {
time: 10
});
console.log('Container killed with grace period');
} catch (error) {
console.log(error.createFullMessage());
}
})();

مثال 4: کشتن تمام پردازش‌ها (all mode)

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

try {
// کشتن تمام پردازش‌های درون کانتینر
const result = await k3.containerCore.killContainer('multi-process-container', 'SIGKILL', {
all: true
});
console.log('All processes terminated');
} catch (error) {
console.log(error.createFullMessage());
}
})();

مثال 5: ارسال سیگنال با debug mode

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

try {
const result = await k3.containerCore.killContainer('debug-container', 'SIGTERM', {
debug: true,
time: 5
});
console.log('Debug output:');
console.log(result);
} catch (error) {
console.log(error.createFullMessage());
}
})();

مثال 6: Graceful shutdown pattern

(async () => {
const k3 = new K3Core();
const containerId = 'web-server';

try {
console.log('Initiating graceful shutdown...');

// Step 1: Send SIGTERM (graceful termination)
const result1 = await k3.containerCore.killContainer(containerId, 'SIGTERM', {
time: 30 // 30 second grace period
});
console.log('SIGTERM sent, waiting for graceful shutdown');

// Step 2: Wait a bit and check status
await new Promise(resolve => setTimeout(resolve, 5000));

const inspect = await k3.containerCore.inspectContainer(containerId);

if (inspect?.state?.running) {
console.log('Container still running, sending SIGKILL');

// Step 3: Send SIGKILL if still running
const result2 = await k3.containerCore.killContainer(containerId, 'SIGKILL');
console.log('SIGKILL sent');
} else {
console.log('Container gracefully shut down');
}

} catch (error) {
console.log(error.createFullMessage());
}
})();

مثال 7: بررسی وضعیت قبل از کشتن

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

try {
const containerId = 'target-container';

// Check current state
const inspect = await k3.containerCore.inspectContainer(containerId);

if (!inspect) {
console.log('Container not found');
return;
}

if (!inspect.state?.running) {
console.log(`Container is ${inspect.state?.running ? 'running' : 'not running'}`);
return;
}

console.log(`Killing container ${inspect.name} (PID: ${inspect.state.pid})`);

// Kill with appropriate signal
const result = await k3.containerCore.killContainer(containerId, 'SIGTERM', {
time: 15
});

console.log('Kill signal sent successfully');

} catch (error) {
console.log(error.createFullMessage());
}
})();

الگوهای خطا و راهنمای حل

الگو 1: کانتینر یافت نشد

خطا: ContainerNotFound (404)

راهنمای حل:

try {
await k3.containerCore.killContainer('invalid-container', 'SIGKILL');
} catch (error) {
if (error.type === 'NOT_FOUND') {
// Get list of all containers
const allContainers = await k3.containerCore.listContainers({ all: true });
console.log('Available containers:', allContainers.map(c => c.name));

// Find and kill the correct container
const container = allContainers.find(c => c.name.includes('target'));
if (container) {
await k3.containerCore.killContainer(container.id, 'SIGKILL');
}
} else {
console.log(error.createFullMessage());
}
}

الگو 2: کانتینر قبلاً کشته شده است

خطا: ContainerAlreadyKilled (400)

راهنمای حل:

try {
await k3.containerCore.killContainer('my-container', 'SIGKILL');
} catch (error) {
if (error.type === 'INVALID_STATE') {
console.log('Container is already killed');

// If you want to restart it
const inspect = await k3.containerCore.inspectContainer('my-container');
console.log(`Current state: ${inspect.state?.running ? 'running' : 'stopped'}`);

// Start container if needed
if (!inspect.state?.running) {
await k3.containerCore.startContainer('my-container');
}
} else {
console.log(error.createFullMessage());
}
}

الگو 3: سیگنال نامعتبر

خطا: BuildKillDTO (422)

راهنمای حل:

const validSignals = [
'SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGABRT',
'SIGKILL', 'SIGTERM', 'SIGSTOP',
1, 2, 3, 6, 9, 15, 19
];

try {
const signal = 'SIGKILL';

if (!validSignals.includes(signal)) {
console.log('Invalid signal. Valid signals:', validSignals);
return;
}

await k3.containerCore.killContainer('my-container', signal);
} catch (error) {
console.log(error.createFullMessage());
}

الگو 4: Graceful shutdown with retry

راهنمای حل:

const gracefulKill = async (containerId, maxAttempts = 2) => {
const signals = ['SIGTERM', 'SIGKILL'];

for (let i = 0; i < Math.min(maxAttempts, signals.length); i++) {
try {
const signal = signals[i];
console.log(`Attempt ${i + 1}: Sending ${signal}`);

await k3.containerCore.killContainer(containerId, signal, {
time: 15
});

console.log(`${signal} sent successfully`);
return true;

} catch (error) {
if (error.type === 'INVALID_STATE') {
console.log('Container already killed');
return true;
}

if (i < Math.min(maxAttempts, signals.length) - 1) {
console.log(`${signals[i]} failed, trying next signal...`);
await new Promise(resolve => setTimeout(resolve, 2000));
} else {
console.log(error.createFullMessage());
throw error;
}
}
}
};

await gracefulKill('my-container');

نکات عملی

  1. انتخاب سیگنال:

    • SIGTERM (15): برای خاتمه مرتب (graceful shutdown)
    • SIGKILL (9): برای خاتمه فوری (حتمی کشتن)
    • SIGINT (2): مثل Ctrl+C
  2. Time Parameter:

    • time = 0: فوری (پیش‌فرض)
    • time > 0: صبر برای grace period
  3. All Parameter:

    • all: false (پیش‌فرض): کل کانتینر کشته شود
    • all: true: فقط پردازش‌های درون کانتینر کشته شوند
  4. بهترین شیوه:

    • ابتدا SIGTERM ارسال کنید
    • منتظر 15-30 ثانیه شوید
    • اگر هنوز اجرا شد، SIGKILL ارسال کنید
  5. کاربردهای اصلی:

    • خاتمه کانتینرهای مشکل‌دار
    • مدیریت lifecycle کانتینرها
    • cleanup و maintenance

مرجع سریع

وضعیتکدتوضیح
موفق200سیگنال ارسال شد
یافت نشد404ContainerNotFound
قبلاً کشته شده400ContainerAlreadyKilled
سیگنال نامعتبر422BuildKillDTO
خطای کشتن500KillFailure
خطای دیتابیس500UpdateContainerStateFailure

نسخه: 1.3
تاریخ آپدیت: 9 آذرماه ۱۴۰۴
تیم توسعه: K3 Development Team