Debian Codegraph @

cylc/flow/task_remote_mgr.py

raw
1 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
2 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 """Manage task remotes.
17
18 This module provides logic to:
19 - Set up the directory structure on remote job hosts.
20 - Copy workflow service files to remote job hosts for communication clients.
21 - Clean up of service files on workflow shutdown.
22 - Implement basic host select functionality.
23 """
24
25 from collections import deque
26 from contextlib import suppress
27 from pathlib import Path
28 import os
29 from shlex import quote
30 import re
31 from subprocess import Popen, PIPE, DEVNULL
32 import tarfile
33 from time import sleep, time
34 from typing import (
35 Any,
36 Deque,
37 Dict,
38 List,
39 NamedTuple,
40 Set,
41 TYPE_CHECKING,
42 Tuple,
43 cast,
44 )
45
46 from cylc.flow import LOG
47 from cylc.flow.exceptions import (
48 PlatformError, PlatformLookupError, NoHostsError, NoPlatformsError
49 )
50 import cylc.flow.flags
51 from cylc.flow.hostuserutil import is_remote_host
52 from cylc.flow.log_level import verbosity_to_opts
53 from cylc.flow.loggingutil import get_next_log_number, get_sorted_logs_by_time
54 from cylc.flow.network.client_factory import CommsMeth
55 from cylc.flow.pathutil import (
56 get_dirs_to_symlink,
57 get_remote_workflow_run_dir,
58 get_workflow_file_install_log_dir,
59 get_workflow_run_dir,
60 )
61 from cylc.flow.platforms import (
62 HOST_REC_COMMAND,
63 PLATFORM_REC_COMMAND,
64 get_host_from_platform,
65 get_install_target_from_platform,
66 get_install_target_to_platforms_map,
67 get_localhost_install_target,
68 log_platform_event,
69 )
70 from cylc.flow.remote import construct_rsync_over_ssh_cmd, construct_ssh_cmd
71 from cylc.flow.subprocctx import SubProcContext
72 from cylc.flow.util import format_cmd
73 from cylc.flow.workflow_files import (
74 KeyInfo,
75 KeyOwner,
76 KeyType,
77 WorkflowFiles,
78 get_contact_file_path,
79 get_workflow_srv_dir,
80 )
81
82 if TYPE_CHECKING:
83 from cylc.flow.network.server import WorkflowRuntimeServer
84
85 # Remote installation literals
86 REMOTE_INIT_DONE = 'REMOTE INIT DONE'
87 REMOTE_INIT_FAILED = 'REMOTE INIT FAILED'
88 REMOTE_INIT_IN_PROGRESS = 'REMOTE INIT IN PROGRESS'
89 REMOTE_FILE_INSTALL_DONE = 'REMOTE FILE INSTALL DONE'
90 REMOTE_FILE_INSTALL_IN_PROGRESS = 'REMOTE FILE INSTALL IN PROGRESS'
91 REMOTE_FILE_INSTALL_FAILED = 'REMOTE FILE INSTALL FAILED'
92 REMOTE_INIT_255 = 'REMOTE INIT 255'
93 REMOTE_FILE_INSTALL_255 = 'REMOTE FILE INSTALL 255'
94
95
96 class RemoteTidyQueueTuple(NamedTuple):
97 platform: Dict[str, Any]
98 host: str
99 proc: 'Popen[str]'
100
101
102 class TaskRemoteMgr:
103 """Manage task remote initialisation, tidy, selection."""
104
105 def __init__(self, workflow, proc_pool, bad_hosts, db_mgr, server):
106 self.workflow = workflow
107 self.proc_pool = proc_pool
108 # self.remote_command_map = {command: host|PlatformError|None}
109 self.remote_command_map = {}
110 # self.remote_init_map = {(install target): status, ...}
111 self.remote_init_map = {}
112 # This flag is turned on when a host init/select command completes
113 self.ready = False
114 self.rsync_includes = None
115 self.bad_hosts = bad_hosts
116 self.is_reload = False
117 self.is_restart = False
118 self.db_mgr = db_mgr
119 self.server: WorkflowRuntimeServer = server
120
121 def _subshell_eval(
122 self, eval_str: str | None, command_pattern: re.Pattern
123 ) -> str | None:
124 """Evaluate a platform or host from a possible subshell string.
125
126 Arguments:
127 eval_str:
128 An explicit host/platform name, a command, or an environment
129 variable holding a host/patform name.
130 command_pattern:
131 A compiled regex pattern designed to match subshell strings.
132
133 Return:
134 - None if evaluation of command is still taking place.
135 - 'localhost' if string is empty/not defined.
136 - Otherwise, return the evaluated host/platform name on success.
137
138 Raise PlatformError on error.
139
140 """
141 if not eval_str:
142 return 'localhost'
143
144 # Host selection command: $(command) or `command`
145 match = command_pattern.search(eval_str)
146 if match:
147 cmd_str = match.group(2)
148 if cmd_str in self.remote_command_map:
149 # Command recently launched
150 value = self.remote_command_map[cmd_str]
151 if isinstance(value, PlatformError):
152 raise value # command failed
153 if value is None:
154 return None # command not yet ready
155 # command succeeded
156 eval_str = eval_str.replace(match.group(0), value)
157 else:
158 # Command not launched (or already reset)
159 self.proc_pool.put_command(
160 SubProcContext(
161 'remote-host-select',
162 ['bash', '-c', cmd_str],
163 env=dict(os.environ)
164 ),
165 callback=self._subshell_eval_callback,
166 callback_args=[cmd_str]
167 )
168 self.remote_command_map[cmd_str] = None
169 return None
170
171 # Environment variable substitution
172 return os.path.expandvars(eval_str)
173
174 # BACK COMPAT: references to "host"
175 # remove at:
176 # Cylc8.x
177 def eval_host(self, host_str: str | None) -> str | None:
178 """Evaluate a host from a possible subshell string.
179
180 Args:
181 host_str: An explicit host name, a command in back-tick or
182 $(command) format, or an environment variable holding
183 a hostname.
184
185 Returns 'localhost' if evaluated name is equivalent
186 (e.g. localhost4.localdomain4).
187 """
188 host = self._subshell_eval(host_str, HOST_REC_COMMAND)
189 if host is not None and not is_remote_host(host):
190 return 'localhost'
191 return host
192
193 def eval_platform(self, platform_str: str | None) -> str | None:
194 """Evaluate a platform from a possible subshell string.
195
196 Args:
197 platform_str: An explicit platform name, a command in $(command)
198 format, or an environment variable holding a platform name.
199 """
200 return self._subshell_eval(platform_str, PLATFORM_REC_COMMAND)
201
202 def subshell_eval_reset(self):
203 """Reset remote eval subshell results.
204
205 This is normally called after the results are consumed.
206 """
207 for key, value in list(self.remote_command_map.copy().items()):
208 if value is not None:
209 del self.remote_command_map[key]
210
211 def remote_init(self, platform: Dict[str, Any]) -> None:
212 """Initialise a remote host if necessary.
213
214 Call "cylc remote-init" to install workflow items to remote:
215 ".service/contact": For TCP task communication
216 "python/": if source exists
217
218 Args:
219 platform: A dict containing settings relating to platform used in
220 this remote installation.
221
222 """
223 install_target = platform['install target']
224 if install_target == get_localhost_install_target():
225 self.remote_init_map[install_target] = REMOTE_FILE_INSTALL_DONE
226 return
227
228 # Set status of install target to in progress while waiting for remote
229 # initialisation to finish
230 self.remote_init_map[install_target] = REMOTE_INIT_IN_PROGRESS
231
232 # Determine what items to install
233 comms_meth: CommsMeth = CommsMeth(platform['communication method'])
234 remote_init_items = self._remote_init_items(comms_meth)
235
236 # Create a TAR archive with the service files,
237 # so they can be sent later via SSH's STDIN to the task remote.
238 tmphandle = self.proc_pool.get_temporary_file()
239 with tarfile.open(fileobj=tmphandle, mode='w') as tarhandle:
240 for path, arcname in remote_init_items:
241 tarhandle.add(path, arcname=arcname)
242 tmphandle.seek(0)
243 # Build the remote-init command to be run over ssh
244 cmd = [
245 'remote-init',
246 *verbosity_to_opts(cylc.flow.flags.verbosity),
247 str(install_target),
248 get_remote_workflow_run_dir(self.workflow)
249 ]
250 dirs_to_symlink = get_dirs_to_symlink(install_target, self.workflow)
251 for key, value in dirs_to_symlink.items():
252 if value is not None:
253 cmd.append(f"{key}={quote(value)}")
254 # Create the ssh command
255 try:
256 host = get_host_from_platform(
257 platform, bad_hosts=self.bad_hosts
258 )
259 except NoHostsError as exc:
260 LOG.error(
261 PlatformError(
262 f'{PlatformError.MSG_INIT}\n{exc}',
263 platform['name'],
264 )
265 )
266 self.remote_init_map[
267 platform['install target']] = REMOTE_INIT_FAILED
268 # reset the bad hosts to allow remote-init to retry
269 self.bad_hosts -= set(platform['hosts'])
270 self.ready = True
271 else:
272 log_platform_event('remote init', platform, host)
273 cmd = construct_ssh_cmd(cmd, platform, host)
274 self.proc_pool.put_command(
275 SubProcContext(
276 'remote-init', cmd, stdin_files=[tmphandle], host=host
277 ),
278 bad_hosts=self.bad_hosts,
279 callback=self._remote_init_callback,
280 callback_args=[platform, tmphandle],
281 callback_255=self._remote_init_callback_255,
282 callback_255_args=[platform],
283 )
284
285 def construct_remote_tidy_ssh_cmd(
286 self, platform: Dict[str, Any]
287 ) -> Tuple[List[str], str]:
288 """Return a remote-tidy SSH command.
289
290 Rasies:
291 NoHostsError: If the platform is not contactable.
292 """
293 cmd = ['remote-tidy']
294 cmd.extend(verbosity_to_opts(cylc.flow.flags.verbosity))
295 cmd.append(get_install_target_from_platform(platform))
296 cmd.append(get_remote_workflow_run_dir(self.workflow))
297 host = get_host_from_platform(
298 platform, bad_hosts=self.bad_hosts
299 )
300 cmd = construct_ssh_cmd(cmd, platform, host, timeout='10s')
301 return cmd, host
302
303 @staticmethod
304 def _get_remote_tidy_targets(
305 platform_names: List[str],
306 install_targets: Set[str]
307 ) -> Dict[str, List[Dict[str, Any]]]:
308 """Finds valid platforms for install targets, warns about in invalid
309 install targets.
310
311 logs:
312 A list of install targets where no platform can be found.
313
314 returns:
315 A mapping of install targets to valid platforms only where
316 platforms are available.
317 """
318 if install_targets and not platform_names:
319 install_targets_map: Dict[str, List[Dict[str, Any]]] = {
320 t: [] for t in install_targets}
321 unreachable_targets = install_targets
322 else:
323 install_targets_map = get_install_target_to_platforms_map(
324 platform_names
325 )
326 # If we couldn't find a platform for a target, we cannot tidy it -
327 # raise an Error:
328 unreachable_targets = install_targets.difference(
329 install_targets_map)
330
331 if unreachable_targets:
332 msg = 'No platforms available to remote tidy install targets:'
333 for unreachable_target in unreachable_targets:
334 msg += f'\n * {unreachable_target}'
335 LOG.error(msg)
336
337 return install_targets_map
338
339 def remote_tidy(self) -> None:
340 """Remove workflow contact files and keys from initialised remotes.
341
342 Call "cylc remote-tidy".
343 This method is called on workflow shutdown, so we want nothing to hang.
344 Timeout any incomplete commands after 10 seconds.
345 """
346 # Get a list of all platforms used from workflow database:
347 with self.db_mgr.get_pri_dao() as pri_dao:
348 platforms_used = pri_dao.select_task_job_platforms()
349
350 # For each install target compile a list of platforms:
351 install_targets = {
352 target for target, msg
353 in self.remote_init_map.items()
354 if msg == REMOTE_FILE_INSTALL_DONE
355 }
356 install_targets_map = self._get_remote_tidy_targets(
357 platforms_used, install_targets)
358
359 # Issue all SSH commands in parallel
360 queue: Deque[RemoteTidyQueueTuple] = deque()
361 for install_target, platforms in install_targets_map.items():
362 if install_target == get_localhost_install_target():
363 continue
364 for platform in platforms:
365 try:
366 cmd, host = self.construct_remote_tidy_ssh_cmd(platform)
367 except NoHostsError as exc:
368 LOG.warning(
369 PlatformError(
370 f'{PlatformError.MSG_TIDY}\n{exc}',
371 platform['name'],
372 )
373 )
374 else:
375 log_platform_event('remote tidy', platform, host)
376 queue.append(
377 RemoteTidyQueueTuple(
378 platform,
379 host,
380 Popen( # nosec
381 cmd, stdout=PIPE, stderr=PIPE, stdin=DEVNULL,
382 text=True
383 ) # * command constructed by internal interface
384 )
385 )
386 break
387 else:
388 LOG.error(
389 NoPlatformsError(
390 install_target,
391 set(),
392 'install target',
393 'remote tidy'))
394 # Wait for commands to complete for a max of 10 seconds
395 timeout = time() + 10.0
396 while queue and time() < timeout:
397 item = queue.popleft()
398 if item.proc.poll() is None: # proc still running
399 queue.append(item)
400 continue
401 out, err = item.proc.communicate()
402 # 255 error has to be handled here because remote tidy doesn't
403 # use SubProcPool.
404 if item.proc.returncode == 255:
405 timeout = time() + 10.0
406 self.bad_hosts.add(item.host)
407 try:
408 retry_cmd, retry_host = self.construct_remote_tidy_ssh_cmd(
409 item.platform
410 )
411 except (NoHostsError, PlatformLookupError) as exc:
412 LOG.warning(
413 PlatformError(
414 f'{PlatformError.MSG_TIDY}\n{exc}',
415 item.platform['name']
416 )
417 )
418 else:
419 queue.append(
420 item._replace(
421 host=retry_host,
422 proc=Popen( # nosec
423 retry_cmd, stdout=PIPE, stderr=PIPE,
424 stdin=DEVNULL, text=True
425 ) # * command constructed by internal interface
426 )
427 )
428 elif item.proc.returncode:
429 LOG.warning(
430 PlatformError(
431 PlatformError.MSG_TIDY,
432 item.platform['name'],
433 cmd=cast('List[str]', item.proc.args),
434 ret_code=item.proc.returncode,
435 out=out,
436 err=err
437 )
438 )
439 sleep(0.1)
440 # Terminate any remaining commands
441 for item in queue:
442 with suppress(OSError):
443 item.proc.terminate()
444 out, err = item.proc.communicate()
445 if item.proc.wait():
446 LOG.warning(
447 PlatformError(
448 PlatformError.MSG_TIDY,
449 item.platform['name'],
450 cmd=cast('List[str]', item.proc.args),
451 ret_code=item.proc.returncode,
452 out=out,
453 err=err,
454 )
455 )
456
457 def _subshell_eval_callback(self, proc_ctx, cmd_str):
458 """Callback when subshell eval command exits"""
459 self.ready = True
460 if proc_ctx.ret_code == 0 and proc_ctx.out:
461 self.remote_command_map[cmd_str] = proc_ctx.out.splitlines()[0]
462 else:
463 # Bad status
464 LOG.error(proc_ctx)
465 self.remote_command_map[cmd_str] = PlatformError(
466 PlatformError.MSG_SELECT,
467 None,
468 ctx=proc_ctx,
469 )
470
471 def _remote_init_callback_255(self, proc_ctx, platform):
472 """Callback when "cylc remote-init" exits with 255 error.
473 """
474 install_target = platform['install target']
475 self.remote_init_map[install_target] = REMOTE_INIT_255
476 self.bad_hosts.add(proc_ctx.host)
477 self.ready = True
478 return
479
480 def _remote_init_callback(self, proc_ctx, platform, tmphandle):
481 """Callback when "cylc remote-init" exits.
482
483 Write public key for install target into client public key
484 directory.
485 Set remote_init__map status to REMOTE_INIT_DONE on success which
486 in turn will trigger file installation to start.
487 Set remote_init_map status to REMOTE_INIT_FAILED on error.
488
489 """
490 with suppress(OSError): # E.g. ignore bad unlink, etc
491 tmphandle.close()
492 install_target = platform['install target']
493 if proc_ctx.ret_code == 0 and "KEYSTART" in proc_ctx.out:
494 regex_result = re.search(
495 'KEYSTART((.|\n|\r)*)KEYEND', proc_ctx.out)
496 key = regex_result.group(1)
497 workflow_srv_dir = get_workflow_srv_dir(self.workflow)
498 public_key = KeyInfo(
499 KeyType.PUBLIC,
500 KeyOwner.CLIENT,
501 workflow_srv_dir=workflow_srv_dir,
502 install_target=install_target
503 )
504 old_umask = os.umask(0o177)
505 with open(public_key.full_key_path, 'w', encoding='utf8') as f:
506 f.write(key)
507 os.umask(old_umask)
508 # configure_curve must be called every time certificates are
509 # added or removed, in order to update the Authenticator's
510 # state.
511 self.server.configure_curve()
512 self.remote_init_map[install_target] = REMOTE_INIT_DONE
513 self.ready = True
514 return
515 # Bad status
516 LOG.error(
517 PlatformError(
518 PlatformError.MSG_INIT,
519 platform['name'],
520 cmd=proc_ctx.cmd,
521 ret_code=proc_ctx.ret_code,
522 out=proc_ctx.out,
523 err=proc_ctx.err,
524 )
525 )
526
527 self.remote_init_map[platform['install target']] = REMOTE_INIT_FAILED
528 self.ready = True
529
530 def file_install(self, platform):
531 """Install required files on the remote install target.
532
533 Included by default in the file installation:
534 Files:
535 .service/server.key (required for ZMQ authentication)
536 Directories:
537 app/
538 bin/
539 etc/
540 lib/
541 """
542 install_target = platform['install target']
543 self.remote_init_map[install_target] = REMOTE_FILE_INSTALL_IN_PROGRESS
544 src_path = get_workflow_run_dir(self.workflow)
545 dst_path = get_remote_workflow_run_dir(self.workflow)
546 install_target = platform['install target']
547 try:
548 cmd, host = construct_rsync_over_ssh_cmd(
549 src_path,
550 dst_path,
551 platform,
552 self.rsync_includes,
553 bad_hosts=self.bad_hosts
554 )
555 ctx = SubProcContext(
556 'file-install',
557 cmd,
558 host
559 )
560 except NoHostsError as exc:
561 LOG.error(
562 PlatformError(
563 f'{PlatformError.MSG_INIT}\n{exc}',
564 platform['name'],
565 )
566 )
567 self.remote_init_map[
568 platform['install target']] = REMOTE_FILE_INSTALL_FAILED
569 self.bad_hosts -= set(platform['hosts'])
570 self.ready = True
571 else:
572 log_platform_event('remote file install', platform, host)
573 self.proc_pool.put_command(
574 ctx,
575 bad_hosts=self.bad_hosts,
576 callback=self._file_install_callback,
577 callback_args=[platform, install_target],
578 callback_255=self._file_install_callback_255,
579 )
580
581 def _file_install_callback_255(self, ctx, platform, install_target):
582 """Callback when file installation exits.
583
584 Sets remote_init_map to REMOTE_FILE_INSTALL_255.
585 """
586 self.remote_init_map[install_target] = REMOTE_FILE_INSTALL_255
587 self.ready = True
588
589 def _file_install_callback(self, ctx, platform, install_target):
590 """Callback when file installation exits.
591
592 Sets remote_init_map to REMOTE_FILE_INSTALL_DONE on success and to
593 REMOTE_FILE_INSTALL_FAILED on error.
594 """
595 install_log_dir = get_workflow_file_install_log_dir(
596 self.workflow)
597 file_name = self.get_log_file_name(
598 install_target, install_log_dir
599 )
600 install_log_path = get_workflow_file_install_log_dir(
601 self.workflow, file_name)
602
603 if ctx.out:
604 Path(install_log_path).parent.mkdir(parents=True, exist_ok=True)
605 with open(install_log_path, 'a') as install_log:
606 install_log.write(
607 f'$ {format_cmd(ctx.cmd, maxlen=80)}'
608 '\n\n### STDOUT:'
609 f'\n{ctx.out}'
610 )
611 if ctx.err:
612 install_log.write(
613 '\n\n### STDERR:'
614 f'\n{ctx.err}'
615 )
616 if ctx.ret_code == 0:
617 # Both file installation and remote init success
618 log_platform_event('remote file install complete', platform)
619 self.remote_init_map[install_target] = REMOTE_FILE_INSTALL_DONE
620 self.ready = True
621 return
622 else:
623 self.remote_init_map[install_target] = REMOTE_FILE_INSTALL_FAILED
624 LOG.error(
625 PlatformError(
626 PlatformError.MSG_INIT,
627 platform['name'],
628 ctx=ctx,
629 )
630 )
631 self.ready = True
632
633 def get_log_file_name(
634 self,
635 install_target,
636 install_log_dir
637 ):
638 log_files = get_sorted_logs_by_time(install_log_dir, '*.log')
639 log_num = get_next_log_number(log_files[-1]) if log_files else 1
640 load_type = "start"
641 if self.is_reload:
642 load_type = "reload"
643 self.is_reload = False # reset marker
644 elif self.is_restart:
645 load_type = "restart"
646 self.is_restart = False # reset marker
647 file_name = f"{log_num:02d}-{load_type}-{install_target}.log"
648 return file_name
649
650 def _remote_init_items(
651 self, comms_meth: CommsMeth
652 ) -> List[Tuple[str, str]]:
653 """Return list of items to install based on communication method.
654
655 (At the moment this is only the contact file.)
656
657 Return (list):
658 Each item is (source_path, dest_path) where:
659 - source_path is the path to the source file to install.
660 - dest_path is relative path under workflow run directory
661 at target remote.
662 """
663 if comms_meth not in {CommsMeth.SSH, CommsMeth.ZMQ}:
664 return []
665 return [
666 (
667 get_contact_file_path(self.workflow),
668 os.path.join(
669 WorkflowFiles.Service.DIRNAME,
670 WorkflowFiles.Service.CONTACT
671 )
672 )
673 ]