Debian Codegraph @

cylc/flow/scripts/cat_log.py

raw
1 #!/usr/bin/env python3
2
3 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
4 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18
19 """cylc cat-log [OPTIONS] ARGS
20
21 View Cylc workflow and job log files.
22
23 Print, tail-follow, print path, or list directory, of local or remote job
24 and scheduler logs. Job runner view commands (e.g. 'qcat') are used if defined
25 in global config and the job is running.
26
27 For standard log types use the short-cut option argument or full filename (e.g.
28 for job stdout "-f o" or "-f job.out" will do).
29
30 To list the local job log directory of a remote task, choose "-m l" (directory
31 list mode) and a local file, e.g. "-f a" (job-activity.log).
32
33 If remote job logs are retrieved to the workflow host on completion (global
34 config '[JOB-HOST]retrieve job logs = True') and the job is not currently
35 running, the local (retrieved) log will be accessed unless '-o/--force-remote'
36 is used.
37
38 The correct cycle point format of the workflow must be used for job logs,
39 but can be discovered with '--mode=d' (print-dir).
40
41 Examples:
42 # for a task "2020/bar" in workflow "foo"
43
44 # Print workflow log:
45 $ cylc cat-log foo
46
47 # Print specific workflow log:
48 $ cylc cat-log foo -f scheduler/02-start-01.log
49
50 # Print task stdout:
51 $ cylc cat-log foo//2020/bar
52 $ cylc cat-log -f o foo//2020/bar
53
54 # Print task stderr:
55 $ cylc cat-log -f e foo//2020/bar
56
57 # Print a custom file in a job's log directory:
58 $ cylc cat-log -f my-log-file foo//2020/bar
59
60 # Follow a log file:
61 $ cylc cat-log foo//2020/bar -m f
62 """
63
64 import os
65 from contextlib import suppress
66 from glob import glob
67 from pathlib import Path
68 import shlex
69 from subprocess import Popen, PIPE, DEVNULL
70 import sys
71 from typing import TYPE_CHECKING
72
73 from cylc.flow.exceptions import InputError
74 import cylc.flow.flags
75 from cylc.flow.hostuserutil import is_remote_platform
76 from cylc.flow.id_cli import parse_id
77 from cylc.flow.log_level import verbosity_to_opts
78 from cylc.flow.option_parsers import (
79 ID_MULTI_ARG_DOC,
80 CylcOptionParser as COP,
81 )
82 from cylc.flow.pathutil import (
83 expand_path,
84 get_remote_workflow_run_job_dir,
85 get_workflow_run_job_dir,
86 get_workflow_run_pub_db_path,
87 get_workflow_run_dir,
88 )
89 from cylc.flow.remote import remote_cylc_cmd, watch_and_kill
90 from cylc.flow.rundb import CylcWorkflowDAO
91 from cylc.flow.task_job_logs import (
92 JOB_LOG_OUT, JOB_LOG_ERR, JOB_LOG_OPTS, NN, JOB_LOG_ACTIVITY)
93 from cylc.flow.terminal import cli_function
94 from cylc.flow.platforms import get_platform
95
96
97 if TYPE_CHECKING:
98 from optparse import Values
99
100
101 WORKFLOW_LOG_OPTS = {
102 'c': ('workflow configuration file (raw)', r'config/*-start-*.cylc'),
103 'p': (
104 'workflow configuration file (processed)',
105 r'config/flow-processed.cylc'
106 ),
107 'i': ('install log', r'install/*-*install.log'),
108 's': ('scheduler log', r'scheduler/*-*start*.log'),
109 'v': ('version control info (JSON)', r'version/*'),
110 }
111
112
113 # add workflow and job log file options to the CLI help output
114 __doc__ += r'''
115
116 Log Files:
117 Select the log file to view with the --file option.
118 Either provide the file path or use one of the short options:
119
120 Job Logs:
121 ''' + ' ' + '\n '.join(
122 f'{key:4} {value}'
123 for key, value in JOB_LOG_OPTS.items()
124 ) + '''
125
126 Workflow Logs:
127 ''' + ' ' + '\n '.join(
128 f'{key:4} {value[0]}'
129 for key, value in WORKFLOW_LOG_OPTS.items()
130 ) + '\n\n Use "--mode=l" to list available log files for a workflow/job.'
131
132
133 # Immortal tail-follow processes on job hosts can be cleaned up by killing
134 # my subprocesses if my PPID or PPPID changes (due to parent ssh connection
135 # dying). This works even if the sshd-invoked
136 # "$(SHELL) -c <remote-command>" does not
137 # exec <remote-command> (affects whether my parent process or I get inherited
138 # by init).
139 #
140 # Example: On host A: cylc cat-log --host=B <workflow> <task-on-C>
141 # => on host A: cat-log spawns subprocess
142 # ssh B "cylc cat-log <workflow> <task-on-C>"
143 # => on host B: cat-log spawns subprocess
144 # ssh C "cylc cat-log --remote <workflow> <task-on-C>"
145 # => on host C: cat-log spawns subprocess
146 # tail -f <task-on-C>.out
147 #
148 # Then Ctrl-C (or exit log viewer) on host-A:
149 # => ssh from A to B dies
150 # => on B: cat-log detects the previous,
151 # and kills its ssh subprocess to C
152 # => on C: cat-log detects the previous,
153 # and kills its tail subprocess, then exits as finished
154
155
156 MODES = {
157 'p': 'print',
158 'l': 'list-dir',
159 'd': 'print-dir',
160 'c': 'cat',
161 't': 'tail',
162 }
163
164
165 BUFSIZE = 1024 * 1024
166
167
168 def colorise_cat_log(cat_proc, color=False, stdout=None):
169 """Print a Cylc log file in color at it would appear in the terminal.
170
171 Args:
172 cat_proc (subprocess.Process):
173 A process which outputs a Cylc log file i.e. `cat`.
174 color (bool):
175 If `True` log will appear in color, if `False` no control
176 characters will be added.
177 stdout:
178 Set the stdout argument of "Popen" if "color=True".
179
180 """
181 if color:
182 color_proc = Popen( # nosec
183 [
184 sys.executable, '-c',
185 '; '.join([
186 'import sys',
187 'from cylc.flow.loggingutil import re_formatter',
188 'print(re_formatter(sys.stdin.read()), end="")'
189 ]),
190 # * there is no untrusted input, everything is hardcoded
191 ],
192 stdin=PIPE,
193 stdout=stdout,
194 )
195 return color_proc.communicate(cat_proc.communicate()[0])
196 else:
197 cat_proc.wait()
198
199
200 def _check_fs_path(path):
201 """Ensure a path is relative and normalised.
202
203 Useful for checking input paths which are intended to be
204 relative to a specified directory.
205
206 Examples:
207 # good paths
208 >>> _check_fs_path('a')
209 >>> _check_fs_path('a/b')
210 >>> _check_fs_path('a/b/')
211
212 # bad paths
213 >>> _check_fs_path('/a')
214 Traceback (most recent call last):
215 cylc.flow.exceptions.InputError: ...
216 >>> _check_fs_path('a/../b')
217 Traceback (most recent call last):
218 cylc.flow.exceptions.InputError: ...
219 >>> _check_fs_path('../a')
220 Traceback (most recent call last):
221 cylc.flow.exceptions.InputError: ...
222 >>> _check_fs_path('./a')
223 Traceback (most recent call last):
224 cylc.flow.exceptions.InputError: ...
225
226 Raises:
227 InputError
228
229 """
230 # join the path onto something to test normalisation
231 _path = os.path.join('x', path).rstrip(os.sep)
232 if os.path.isabs(path) or os.path.normpath(_path) != _path:
233 raise InputError(
234 f'File paths must be relative to the job log directory: {path}'
235 )
236
237
238 def view_log(
239 logpath,
240 mode,
241 tailer_tmpl,
242 batchview_cmd=None,
243 remote=False,
244 color=False,
245 prepend_path=False,
246 ):
247 """View (by mode) local log file. This is only called on the file host.
248
249 batchview_cmd is a job-runner-specific job stdout or stderr cat or tail
250 command (e.g. 'qcat') that may be implemented for job runners that don't
251 write logs to their final locations until after the job completes.
252
253 If remote is True, we are executing on a remote host for a log file there.
254
255 """
256 # The log file path may contain '$USER' to be evaluated on the job host.
257 if mode == 'print':
258 # Print location even if the workflow does not exist yet.
259 print(logpath)
260 return 0
261 if mode == 'print-dir':
262 print(os.path.dirname(logpath))
263 return 0
264 if mode == 'list-dir':
265 dirname = os.path.dirname(logpath)
266 if not os.path.exists(dirname):
267 sys.stderr.write(f"Directory not found: {dirname}\n")
268 return 1
269 for entry in sorted(os.listdir(dirname)):
270 print(entry)
271 return 0
272 if not os.path.exists(logpath) and batchview_cmd is None:
273 # Note: batchview_cmd may not need to have access to logpath, so don't
274 # test for existence of path if it is set.
275 sys.stderr.write('File not found: %s\n' % logpath)
276 return 1
277 if prepend_path:
278 from cylc.flow.hostuserutil import get_host
279 print(f'# {get_host()}:{logpath}')
280 if mode == 'cat':
281 # print file contents to stdout.
282 if batchview_cmd is not None:
283 cmd = shlex.split(batchview_cmd)
284 else:
285 cmd = ['cat', logpath]
286 proc1 = Popen( # nosec
287 cmd,
288 stdin=DEVNULL,
289 stdout=PIPE if color else None
290 )
291 # * batchview command is user configurable
292 colorise_cat_log(proc1, color=color)
293 return 0
294 if mode == 'tail':
295 if batchview_cmd is not None:
296 cmd = batchview_cmd
297 else:
298 cmd = tailer_tmpl % {"filename": shlex.quote(str(logpath))}
299 proc = Popen(shlex.split(cmd), stdin=DEVNULL) # nosec
300 # * batchview command is user configurable
301 with suppress(KeyboardInterrupt):
302 watch_and_kill(proc)
303 return proc.wait()
304
305
306 def get_option_parser() -> COP:
307 """Set up the CLI option parser."""
308 parser = COP(
309 __doc__,
310 argdoc=[
311 ID_MULTI_ARG_DOC,
312 ]
313 )
314
315 parser.add_option(
316 "-f", "--file",
317 help=(
318 'The file to view. Default for job logs "out", default for'
319 ' workflow logs "scheduler/log". See "Log Files" above for'
320 ' possible values.'
321 ),
322 metavar="LOG",
323 action="store",
324 default=None,
325 dest="filename",
326 )
327
328 parser.add_option(
329 "-m", "--mode",
330 help="Mode: %s. Default c(cat)." % (
331 ', '.join(['%s(%s)' % (i, j) for i, j in MODES.items()])),
332 action="store", choices=list(MODES.keys()) + list(MODES.values()),
333 default='c', dest="mode")
334
335 parser.add_option(
336 "-r", "--rotation",
337 help="Workflow log integer rotation number. 0 for current, 1 for "
338 "next oldest, etc.",
339 metavar="INT", action="store", dest="rotation_num", type=int)
340
341 parser.add_option(
342 "-o", "--force-remote",
343 help="View remote logs remotely even if they have been retrieved"
344 " to the workflow host (default False).",
345 action="store_true", default=False, dest="force_remote")
346
347 parser.add_option(
348 "-s", "--submit-number", "-t", "--try-number",
349 help="Job submit number (default=%s, i.e. latest)." % NN,
350 metavar="INT", action="store", dest="submit_num", default=None)
351
352 parser.add_option(
353 "--remote-arg",
354 help="(for internal use: continue processing on job host)",
355 action="append", dest="remote_args")
356
357 parser.add_option(
358 '--prepend-path',
359 help='Prepend the file path to the output in the format <host>:<path>',
360 action='store_true',
361 default=False,
362 )
363
364 return parser
365
366
367 def get_task_job_attrs(workflow_id, point, task, submit_num):
368 """Retrieve job info from the database.
369
370 * live_job_id is the job ID if job is running, else None.
371 * submit_failed is True if the the submission failed.
372
373 Returns:
374 tuple - (platform, job_runner_name, live_job_id, submit_failed)
375
376 """
377 with CylcWorkflowDAO(
378 get_workflow_run_pub_db_path(workflow_id), is_public=True
379 ) as dao:
380 task_job_data = dao.select_task_job(point, task, submit_num)
381 if task_job_data is None:
382 return (None, None, None, None)
383 job_runner_name = task_job_data["job_runner_name"]
384 job_id = task_job_data["job_id"]
385 if (not job_runner_name or not job_id
386 or not task_job_data["time_run"]
387 or task_job_data["time_run_exit"]):
388 live_job_id = None
389 else:
390 live_job_id = job_id
391 return (
392 task_job_data["platform_name"],
393 job_runner_name,
394 live_job_id,
395 bool(task_job_data['submit_status']),
396 )
397
398
399 @cli_function(get_option_parser)
400 def main(
401 parser: COP,
402 options: 'Values',
403 *ids,
404 color: bool = False
405 ):
406 """Wrapper around the main script for simpler testing.
407 """
408 _main(parser, options, *ids, color=color)
409
410
411 def _main(
412 parser: COP,
413 options: 'Values',
414 *ids,
415 color: bool = False
416 ) -> None:
417 """Implement cylc cat-log CLI.
418
419 Determine log path, user@host, batchview_cmd, and action (print, dir-list,
420 cat, or tail), and then if the log path is:
421 a) local: perform action on log path, or
422 b) remote: re-invoke cylc cat-log as a) on the remote account
423
424 """
425 if options.filename is not None:
426 _check_fs_path(options.filename)
427
428 if options.remote_args:
429 # Invoked on job hosts for job logs only, as a wrapper to view_log().
430 # Tail and batchview commands from global config on workflow host).
431 logpath, mode, tail_tmpl = options.remote_args[0:3]
432 _check_fs_path(logpath)
433 logpath = expand_path(logpath)
434 tail_tmpl = expand_path(tail_tmpl)
435 try:
436 batchview_cmd = options.remote_args[3]
437 except IndexError:
438 batchview_cmd = None
439 res = view_log(
440 logpath,
441 mode,
442 tail_tmpl,
443 batchview_cmd,
444 remote=True,
445 color=color,
446 prepend_path=options.prepend_path,
447 )
448 if res == 1:
449 sys.exit(res)
450 return
451
452 workflow_id, tokens, _ = parse_id(*ids, constraint='mixed')
453
454 # Get long-format mode.
455 try:
456 mode = MODES[options.mode]
457 except KeyError:
458 mode = options.mode
459
460 if tokens and tokens.get('cycle') and not tokens.get('task'):
461 print('Please provide a workflow, task or job ID', file=sys.stderr)
462 sys.exit(1)
463
464 if not tokens or not tokens.get('task'):
465 # no task provided - user has requested a workflow log
466 log_dir: str = get_workflow_run_dir(workflow_id, 'log')
467 file_name: str = options.filename or 's'
468 log_file_path: Path
469
470 if mode == 'list-dir':
471 # list workflow logs
472 print('\n'.join(sorted(
473 str(path.relative_to(log_dir))
474 for dirpath in {
475 # set of log/<x> directories to scan for files in
476 Path(log_dir, _file_name).parent
477 for _, _file_name in WORKFLOW_LOG_OPTS.values()
478 # don't try to list directories which aren't there
479 if Path(log_dir, _file_name).parent.exists()
480 }
481 for path in dirpath.iterdir()
482 # strip out file aliases such as scheduler/log
483 if not path.is_symlink()
484 )))
485 return
486
487 if file_name in WORKFLOW_LOG_OPTS:
488 rotation_number = options.rotation_num or 0
489 pattern = WORKFLOW_LOG_OPTS[file_name][1]
490 logs = sorted(
491 glob(
492 str(Path(log_dir, pattern))
493 ),
494 reverse=True
495 )
496 if logs:
497 try:
498 log_file_path = Path(logs[rotation_number])
499 except IndexError:
500 raise InputError(
501 f"--rotation {rotation_number} invalid "
502 f"(max value is {len(logs) - 1})"
503 ) from None
504 else:
505 raise InputError('Log file not found.')
506 else:
507 log_file_path = Path(log_dir, file_name)
508
509 tail_tmpl = os.path.expandvars(
510 get_platform()["tail command template"]
511 )
512 out = view_log(
513 log_file_path,
514 mode,
515 tail_tmpl,
516 color=color,
517 prepend_path=options.prepend_path,
518 )
519 sys.exit(out)
520
521 else:
522 # Cat task job logs, may be on workflow or job host.
523 if options.rotation_num is not None:
524 raise InputError(
525 "only workflow (not job) logs get rotated")
526 task = tokens['task']
527 point = tokens['cycle']
528
529 submit_num = options.submit_num or tokens.get('job') or NN
530 if submit_num != NN:
531 try:
532 submit_num = "%02d" % int(submit_num)
533 except ValueError:
534 parser.error("Illegal submit number: %s" % submit_num)
535 if options.filename is None:
536 options.filename = JOB_LOG_OUT
537 else:
538 # Convert short filename args to long (e.g. 'o' to 'job.out').
539 with suppress(KeyError):
540 options.filename = JOB_LOG_OPTS[options.filename]
541 # KeyError: Is already long form (standard log, or custom).
542 platform_name, _, live_job_id, submit_failed = get_task_job_attrs(
543 workflow_id, point, task, submit_num)
544 platform = get_platform(platform_name)
545 batchview_cmd = None
546 if live_job_id is not None:
547 # Job is currently running. Get special job runner log view
548 # command (e.g. qcat) if one exists, and the log is out or err.
549 conf_key = None
550 if options.filename == JOB_LOG_OUT:
551 if mode == 'cat':
552 conf_key = "out viewer"
553 elif mode == 'tail':
554 conf_key = "out tailer"
555 elif options.filename == JOB_LOG_ERR:
556 if mode == 'cat':
557 conf_key = "err viewer"
558 elif mode == 'tail':
559 conf_key = "err tailer"
560 if conf_key is not None:
561 batchview_cmd_tmpl = None
562 with suppress(KeyError):
563 batchview_cmd_tmpl = platform[conf_key]
564 if batchview_cmd_tmpl is not None:
565 batchview_cmd = batchview_cmd_tmpl % {
566 "job_id": str(live_job_id)}
567
568 local_log_dir = get_workflow_run_job_dir(
569 workflow_id, point, task, submit_num
570 )
571
572 log_is_remote = (is_remote_platform(platform)
573 and (options.filename != JOB_LOG_ACTIVITY))
574 log_is_retrieved = (platform['retrieve job logs']
575 and live_job_id is None)
576 if (
577 # only go remote for log files we can't get locally
578 log_is_remote
579 # don't look for remote log files for submit-failed tasks
580 # (there might not be any at all)
581 and not submit_failed
582 # don't go remote if the log should be retrieved (unless
583 # --force-remote is specified)
584 and (not log_is_retrieved or options.force_remote)
585 ):
586 logpath = os.path.normpath(get_remote_workflow_run_job_dir(
587 workflow_id, point, task, submit_num,
588 options.filename))
589 tail_tmpl = platform["tail command template"]
590 # Reinvoke the cat-log command on the remote account.
591 cmd = ['cat-log', *verbosity_to_opts(cylc.flow.flags.verbosity)]
592 for item in [logpath, mode, tail_tmpl]:
593 cmd.append('--remote-arg=%s' % shlex.quote(item))
594 if batchview_cmd:
595 cmd.append('--remote-arg=%s' % shlex.quote(batchview_cmd))
596 if options.prepend_path:
597 cmd.append('--prepend-path')
598 cmd.append(workflow_id)
599 # TODO: Add Intelligent Host selection to this
600 proc = None
601 with suppress(KeyboardInterrupt):
602 # (Ctrl-C while tailing)
603 # NOTE: This will raise NoHostsError if the platform is not
604 # contactable
605 proc = remote_cylc_cmd(
606 cmd,
607 platform,
608 capture_process=(mode == 'list-dir'),
609 manage=(mode == 'tail'),
610 text=(mode == 'list-dir'),
611 )
612
613 # add and missing items to file listing results
614 if isinstance(proc, Popen):
615 # i.e: if mode=='list-dir' and ctrl+c not pressed
616 out, err = proc.communicate()
617 files = out.splitlines()
618
619 # add files which can be accessed via a tailer
620 if live_job_id is not None:
621 if (
622 # NOTE: only list the file if it can be viewed in
623 # both modes
624 (platform['out tailer'] and platform['out viewer'])
625 and 'job.out' not in files
626 ):
627 files.append('job.out')
628 if (
629 (platform['err tailer'] and platform['err viewer'])
630 and 'job.err' not in files
631 ):
632 files.append('job.err')
633
634 # add the job-activity.log file which is always local
635 if os.path.exists(
636 os.path.join(local_log_dir, 'job-activity.log')
637 ):
638 files.append('job-activity.log')
639
640 files.sort()
641 print('\n'.join(files))
642 print(err, file=sys.stderr)
643 sys.exit(proc.returncode)
644 else:
645 sys.exit(proc)
646
647 else:
648 # Local task job or local job log.
649 logpath = os.path.join(local_log_dir, options.filename)
650 tail_tmpl = os.path.expandvars(platform["tail command template"])
651 out = view_log(
652 logpath,
653 mode,
654 tail_tmpl,
655 batchview_cmd,
656 color=color,
657 prepend_path=options.prepend_path,
658 )
659 sys.exit(out)