Skip to content

Commit a11a3d4

Browse files
Add compression job log correlation fields
1 parent bc6cb86 commit a11a3d4

4 files changed

Lines changed: 102 additions & 74 deletions

File tree

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,20 @@
1-
from celery import Celery
1+
import logging
2+
3+
from celery import Celery, signals
4+
from clp_py_utils.clp_logging import set_formatter_on_handlers
25

36
from job_orchestration.executor.compress import celeryconfig
47

58
app = Celery("compress")
69
app.config_from_object(celeryconfig)
710

11+
12+
@signals.after_setup_logger.connect
13+
@signals.after_setup_task_logger.connect
14+
def configure_logger_formatters(logger: logging.Logger | None = None, **_kwargs: object) -> None:
15+
if logger is not None:
16+
set_formatter_on_handlers(logger)
17+
18+
819
if "__main__" == __name__:
920
app.start()

components/job-orchestration/job_orchestration/executor/compress/celery_compress.py

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from celery.app.task import Task
33
from celery.exceptions import SoftTimeLimitExceeded
44
from celery.utils.log import get_task_logger
5+
from clp_py_utils.clp_logging import bind_log_context
56

67
from job_orchestration.executor.compress.celery import app
78
from job_orchestration.executor.compress.compression_task import compression_entry_point
@@ -24,17 +25,22 @@ def compress(
2425
paths_to_compress_json: str,
2526
clp_metadata_db_connection_config,
2627
):
27-
try:
28-
return compression_entry_point(
29-
job_id,
30-
task_id,
31-
clp_io_config_json,
32-
paths_to_compress_json,
33-
clp_metadata_db_connection_config,
34-
logger,
35-
)
36-
except SoftTimeLimitExceeded:
37-
logger.exception(
38-
f"Compression task job_id={job_id} task_id={task_id} exceeded soft time limit."
39-
)
40-
raise
28+
with bind_log_context(
29+
job_id=job_id,
30+
task_id=task_id,
31+
celery_task_id=self.request.id,
32+
):
33+
try:
34+
return compression_entry_point(
35+
job_id,
36+
task_id,
37+
clp_io_config_json,
38+
paths_to_compress_json,
39+
clp_metadata_db_connection_config,
40+
logger,
41+
)
42+
except SoftTimeLimitExceeded:
43+
logger.exception(
44+
f"Compression task job_id={job_id} task_id={task_id} exceeded soft time limit."
45+
)
46+
raise

components/job-orchestration/job_orchestration/executor/compress/compression_task.py

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
StorageType,
2121
WorkerConfig,
2222
)
23-
from clp_py_utils.clp_logging import set_logging_level
23+
from clp_py_utils.clp_logging import bind_log_context, set_logging_level
2424
from clp_py_utils.clp_metadata_db_utils import (
2525
get_archives_table_name,
2626
)
@@ -432,8 +432,12 @@ def cleanup_temporary_files():
432432
# Open log files
433433
compression_log_path = logs_dir / f"{instance_id_str}-stderr.log"
434434
compression_log_file = open(compression_log_path, "w")
435+
compression_log_file.write(f"job_id={job_id} task_id={task_id} task_name=compression\n")
436+
compression_log_file.flush()
435437
conversion_log_path = logs_dir / f"{instance_id_str}-conversion-stderr.log"
436438
conversion_log_file = open(conversion_log_path, "w")
439+
conversion_log_file.write(f"job_id={job_id} task_id={task_id} task_name=log-converter\n")
440+
conversion_log_file.flush()
437441

438442
conversion_return_code = 0
439443
if conversion_cmd is not None:
@@ -444,7 +448,8 @@ def cleanup_temporary_files():
444448
stderr=conversion_log_file,
445449
env=conversion_env,
446450
)
447-
conversion_return_code = conversion_proc.wait()
451+
with bind_log_context(clp_subprocess_pid=conversion_proc.pid):
452+
conversion_return_code = conversion_proc.wait()
448453
conversion_log_file.close()
449454

450455
try:
@@ -560,14 +565,15 @@ def cleanup_temporary_files():
560565
last_archive_stats = stats
561566

562567
# Wait for compression to finish
563-
return_code = proc.wait()
568+
with bind_log_context(clp_subprocess_pid=proc.pid):
569+
return_code = proc.wait()
564570

565-
if 0 != return_code:
566-
logger.error(f"Failed to compress, return_code={return_code!s}")
567-
else:
568-
compression_successful = True
571+
if 0 != return_code:
572+
logger.error(f"Failed to compress, return_code={return_code!s}")
573+
else:
574+
compression_successful = True
569575

570-
logger.debug("Compressed.")
576+
logger.debug("Compressed.")
571577
finally:
572578
cleanup_temporary_files()
573579
compression_log_file.close()

components/job-orchestration/job_orchestration/scheduler/compress/compression_scheduler.py

Lines changed: 56 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
OrchestrationType,
2121
StorageEngine,
2222
)
23-
from clp_py_utils.clp_logging import configure_logging, get_logger
23+
from clp_py_utils.clp_logging import bind_log_context, configure_logging, get_logger
2424
from clp_py_utils.clp_metadata_db_utils import (
2525
add_dataset,
2626
fetch_existing_datasets,
@@ -308,14 +308,15 @@ def search_and_schedule_new_tasks(
308308
# TODO: revisit why we need to commit here. To end long transactions?
309309
db_context.connection.commit()
310310
for job_row in jobs:
311-
_schedule_job(
312-
clp_config,
313-
clp_metadata_db_connection_config,
314-
task_manager,
315-
db_context,
316-
job_row,
317-
existing_datasets,
318-
)
311+
with bind_log_context(job_id=job_row["id"]):
312+
_schedule_job(
313+
clp_config,
314+
clp_metadata_db_connection_config,
315+
task_manager,
316+
db_context,
317+
job_row,
318+
existing_datasets,
319+
)
319320

320321

321322
def _schedule_job(
@@ -474,54 +475,58 @@ def poll_running_jobs(
474475
logger.debug("Poll running jobs")
475476
jobs_to_delete = []
476477
for job_id, job in scheduled_jobs.items():
477-
job_success = True
478-
duration = 0.0
479-
error_messages: list[str] = []
480-
num_tasks_in_batch = 0
478+
with bind_log_context(job_id=job_id):
479+
job_success = True
480+
duration = 0.0
481+
error_messages: list[str] = []
482+
num_tasks_in_batch = 0
481483

482-
try:
483-
returned_results = job.result_handle.get_result()
484-
if returned_results is None:
485-
continue
484+
try:
485+
returned_results = job.result_handle.get_result()
486+
if returned_results is None:
487+
continue
486488

487-
duration = (
488-
datetime.datetime.now(datetime.timezone.utc) - job.start_time
489-
).total_seconds()
490-
# Check for finished jobs
491-
num_tasks_in_batch = len(returned_results)
492-
for task_result in returned_results:
493-
if task_result.status == CompressionTaskStatus.SUCCEEDED:
494-
logger.info(
495-
f"Compression task job-{job_id}-task-{task_result.task_id} completed in"
496-
f" {task_result.duration} second(s)."
497-
)
498-
else:
499-
job_success = False
500-
error_messages.append(
501-
f"task {task_result.task_id}: {task_result.error_message}"
502-
)
503-
logger.error(
504-
f"Compression task job-{job_id}-task-{task_result.task_id} failed with"
505-
f" error: {task_result.error_message}."
506-
)
489+
duration = (
490+
datetime.datetime.now(datetime.timezone.utc) - job.start_time
491+
).total_seconds()
492+
# Check for finished jobs
493+
num_tasks_in_batch = len(returned_results)
494+
for task_result in returned_results:
495+
with bind_log_context(task_id=task_result.task_id):
496+
if task_result.status == CompressionTaskStatus.SUCCEEDED:
497+
logger.info(
498+
f"Compression task job-{job_id}-task-{task_result.task_id} completed in"
499+
f" {task_result.duration} second(s)."
500+
)
501+
else:
502+
job_success = False
503+
error_messages.append(
504+
f"task {task_result.task_id}: {task_result.error_message}"
505+
)
506+
logger.error(
507+
f"Compression task job-{job_id}-task-{task_result.task_id} failed with"
508+
f" error: {task_result.error_message}."
509+
)
507510

508-
except Exception:
509-
logger.exception("Error while getting results for job %s", job_id)
510-
job_success = False
511+
except Exception:
512+
logger.exception("Error while getting results for job %s", job_id)
513+
job_success = False
511514

512-
if not job_success:
513-
_handle_failed_compression_job(logs_directory, db_context, job_id, error_messages)
514-
jobs_to_delete.append(job_id)
515-
continue
515+
if not job_success:
516+
_handle_failed_compression_job(logs_directory, db_context, job_id, error_messages)
517+
jobs_to_delete.append(job_id)
518+
continue
516519

517-
job.num_tasks_completed += num_tasks_in_batch
520+
job.num_tasks_completed += num_tasks_in_batch
518521

519-
if len(job.remaining_tasks) > 0:
520-
_dispatch_next_task_batch(task_manager, db_context, job, max_concurrent_tasks_per_job)
521-
else:
522-
# All tasks completed successfully
523-
_complete_compression_job(db_context, job_id, job.num_tasks_total, duration)
524-
jobs_to_delete.append(job_id)
522+
if len(job.remaining_tasks) > 0:
523+
_dispatch_next_task_batch(
524+
task_manager, db_context, job, max_concurrent_tasks_per_job
525+
)
526+
else:
527+
# All tasks completed successfully
528+
_complete_compression_job(db_context, job_id, job.num_tasks_total, duration)
529+
jobs_to_delete.append(job_id)
525530

526531
for job_id in jobs_to_delete:
527532
del scheduled_jobs[job_id]

0 commit comments

Comments
 (0)