Skip to content

Gracefully terminate Windows processes with Ctrl-C event

What does this MR do?

Replaces use of taskkill for initial termination of processes on Windows, mimicking the behaviour of sending SIGINT on unix systems.

Why was this MR needed?

Cancelling jobs in Gitlab does not cause graceful termination of processes.

What's the best way to test this MR?

Run the following Python script in a job and then cancel it after the heartbeat messages start appearing in the job log. The final line in $CI_BUILDS_DIR/signal_handler.log should be along the lines of

[24896] 2023-02-15 13:57:16,459: terminated after 32.2s with SIGINT
import logging
import os
import signal
import sys
import time
import timeit

start_time = timeit.default_timer()

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

formatter = logging.Formatter('[%(process)d] %(asctime)s: %(message)s')

for handler in (
    logging.StreamHandler(sys.stdout),
    logging.FileHandler(f'{os.environ.get("CI_BUILDS_DIR", ".")}/signal_handler.log')
):
    handler.setLevel(logging.DEBUG)
    handler.setFormatter(formatter)
    logger.addHandler(handler)

logger.info('! ------- start ------- !')
for key in ('CI_PROJECT_ID', 'CI_PIPELINE_ID', 'CI_JOB_ID'):
    logger.info(f'{key}={os.environ.get(key)}')


def signal_handler(signum, frame):
    runtime = timeit.default_timer() - start_time
    logger.info(f'terminated after {runtime:.1f}s with {signal.Signals(signum).name}')
    exit(1)


for sig in (signal.SIGINT, signal.SIGABRT, signal.SIGSEGV, signal.SIGTERM):
    signal.signal(sig, signal_handler)

logger.debug(sys.argv)

while True:
    logger.debug(f'heartbeat: {timeit.default_timer() - start_time:.1f}')
    time.sleep(1)

What are the relevant issue numbers?

closes #27443 (closed)

Edited by Axel von Bertoldi

Merge request reports