Debian Codegraph @

cylc/flow/task_remote_cmd.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 """Implement "cylc remote-init" and "cylc remote-tidy"."""
17
18 import os
19 import re
20 import sys
21 import tarfile
22 from typing import TYPE_CHECKING
23
24 import zmq
25
26 import cylc.flow.flags
27 from cylc.flow.pathutil import make_symlink_dir
28 from cylc.flow.resources import get_resources
29 from cylc.flow.task_remote_mgr import (
30 REMOTE_INIT_DONE,
31 REMOTE_INIT_FAILED,
32 )
33 from cylc.flow.workflow_files import (
34 KeyInfo,
35 KeyOwner,
36 KeyType,
37 WorkflowFiles,
38 )
39
40
41 if TYPE_CHECKING:
42 from pathlib import Path
43
44
45 def remove_keys_on_client(srvd, install_target, full_clean=False):
46 """Removes client authentication keys"""
47 keys = {
48 "client_private_key": KeyInfo(
49 KeyType.PRIVATE,
50 KeyOwner.CLIENT,
51 workflow_srv_dir=srvd),
52 "client_public_key": KeyInfo(
53 KeyType.PUBLIC,
54 KeyOwner.CLIENT,
55 workflow_srv_dir=srvd,
56 install_target=install_target,
57 server_held=False),
58 }
59 # WARNING, DESTRUCTIVE. Removes old keys if they already exist.
60 if full_clean:
61 keys.update({"server_public_key": KeyInfo(
62 KeyType.PUBLIC, KeyOwner.SERVER, workflow_srv_dir=srvd)})
63 for k in keys.values():
64 if os.path.exists(k.full_key_path):
65 os.remove(k.full_key_path)
66
67
68 def create_client_keys(srvd, install_target):
69 """Create or renew authentication keys for workflow 'id_' in the .service
70 directory.
71 Generate a pair of ZMQ authentication keys"""
72
73 cli_pub_key = KeyInfo(
74 KeyType.PUBLIC,
75 KeyOwner.CLIENT,
76 workflow_srv_dir=srvd,
77 install_target=install_target,
78 server_held=False)
79 # ZMQ keys generated in .service directory.
80 # ZMQ keys need to be created with stricter file permissions, changing
81 # umask default denials.
82 old_umask = os.umask(0o177) # u=rw only set as default for file creation
83 client_public_full_key_path, _client_private_full_key_path = (
84 zmq.auth.create_certificates(
85 srvd, KeyOwner.CLIENT.value))
86
87 os.rename(client_public_full_key_path, cli_pub_key.full_key_path)
88 # Return file permissions to default settings.
89 os.umask(old_umask)
90
91
92 def remote_init(
93 install_target: str, rund: 'Path | str', *dirs_to_symlink: str
94 ) -> int:
95 """cylc remote-init
96
97 Arguments:
98 install_target: target to be initialised
99 rund: workflow run directory
100 dirs_to_symlink: directories to be symlinked in form
101 [directory=symlink_location, ...]
102 """
103 rund = os.path.expandvars(rund)
104 for item in dirs_to_symlink:
105 key, val = item.split("=", 1)
106 if key == 'run':
107 path = rund
108 else:
109 path = os.path.join(rund, key)
110 target = os.path.expandvars(val)
111 if '$' in target:
112 print(REMOTE_INIT_FAILED)
113 print(f'Error occurred when symlinking.'
114 f' {target} contains an invalid environment variable.')
115 return 1
116 make_symlink_dir(path, target)
117 srvd = os.path.join(rund, WorkflowFiles.Service.DIRNAME)
118 os.makedirs(srvd, exist_ok=True)
119
120 client_pub_keyinfo = KeyInfo(
121 KeyType.PUBLIC,
122 KeyOwner.CLIENT,
123 workflow_srv_dir=srvd,
124 install_target=install_target,
125 server_held=False
126 )
127 # Check for existence of client key dir (should only exist on server)
128 # Fail if one exists - this may occur on mis-configuration of install
129 # target in global.cylc
130 client_key_dir = os.path.join(
131 srvd, f"{KeyOwner.CLIENT.value}_{KeyType.PUBLIC.value}_keys")
132 if os.path.exists(client_key_dir):
133 print(REMOTE_INIT_FAILED)
134 print(f"Unexpected key directory exists: {client_key_dir}"
135 " Check global.cylc install target is configured correctly "
136 "for this platform.")
137 return 2
138 pattern = re.compile(r"^client_\S*key$")
139 for filepath in os.listdir(srvd):
140 if pattern.match(filepath) and f"{install_target}" not in filepath:
141 # client key for a different install target exists
142 print(REMOTE_INIT_FAILED)
143 print(f"Unexpected authentication key '{filepath}' exists. "
144 "Check global.cylc install target is configured correctly "
145 "for this platform.")
146 return 2
147 try:
148 remove_keys_on_client(srvd, install_target)
149 create_client_keys(srvd, install_target)
150 except Exception:
151 # Catching all exceptions as need to fail remote init if any problems
152 # with key generation.
153 print(REMOTE_INIT_FAILED)
154 return 3
155 oldcwd = os.getcwd()
156 os.chdir(rund)
157 # Extract job.sh from library, for use in job scripts.
158 get_resources(
159 'job.sh',
160 os.path.join(WorkflowFiles.Service.DIRNAME, 'etc')
161 )
162 # Extract sent contact file from stdin:
163 try:
164 with tarfile.open(fileobj=sys.stdin.buffer, mode='r|') as tarhandle:
165 tarhandle.extractall() # nosec B202 - there should not be any
166 # untrusted members in the tar stream, only the contact file
167 finally:
168 os.chdir(oldcwd)
169 print("KEYSTART", end='')
170 with open(client_pub_keyinfo.full_key_path) as keyfile:
171 print(keyfile.read(), end='KEYEND')
172 print(REMOTE_INIT_DONE)
173 return 0
174
175
176 def remote_tidy(install_target, rund):
177 """cylc remote-tidy
178
179 Arguments:
180 install_target (str): install target name
181 rund (str): workflow run directory
182 """
183 rund = os.path.expandvars(rund)
184 srvd = os.path.join(rund, WorkflowFiles.Service.DIRNAME)
185 fname = os.path.join(srvd, WorkflowFiles.Service.CONTACT)
186 try:
187 os.unlink(fname)
188 except OSError:
189 if os.path.exists(fname):
190 raise
191 else:
192 if cylc.flow.flags.verbosity > 1:
193 print('Deleted: %s' % fname)
194 remove_keys_on_client(srvd, install_target, full_clean=True)
195 try:
196 os.rmdir(srvd) # remove directory if empty
197 except OSError:
198 pass
199 else:
200 if cylc.flow.flags.verbosity > 1:
201 print('Deleted: %s' % srvd)