Debian Codegraph @

gavo/utils/ostricks.py

raw
1 """
2 OS abstractions and related.
3
4 This module contains, in particular, the interface for having "easy subcommands"
5 using argparse. The idea is to use the exposedFunction decorator on functions
6 that should be callable from the command line as subcommands; the functions
7 must all have the same signature. For example, if they all took the stuff
8 returned by argparse, you could say in the module containing them::
9
10 args = makeCLIParser(globals()).parse_args()
11 args.subAction(args)
12
13 To specify the command line arguments to the function, use Args. See
14 admin.py for an example.
15 """
16
17 #c Copyright 2008-2025, the GAVO project <[email protected]>
18 #c
19 #c This program is free software, covered by the GNU GPL. See the
20 #c COPYING file in the source distribution.
21
22
23 import argparse
24 import contextlib
25 import grp
26 import os
27 import sys
28 import tempfile
29 import urllib.request, urllib.parse
30
31 from gavo.utils import codetricks
32 from gavo.utils import excs
33 from gavo.utils import misctricks
34
35
36 from gavo.utils.dachstypes import (Any, BinaryIO, Callable, Dict, Filename,
37 Generator, IO, List, Optional, TextIO, Tuple, Union)
38
39
40 def safeclose(f: IO) -> None:
41 """syncs and closes the python file f.
42
43 You generally want to use this rather than a plain close() before
44 overwriting a file with a new version.
45 """
46 f.flush()
47 os.fsync(f.fileno())
48 f.close()
49
50
51 @contextlib.contextmanager
52 def safeReplaced(fName: Filename, *, binary: bool=True) -> Generator:
53 """opens fName for "safe replacement".
54
55 Safe replacement means that you can write to the object returned, and
56 when everything works out all right, what you have written replaces
57 the old content of fName, where the old mode is preserved if possible.
58 When there are errors, however, the old content remains.
59 """
60 mode = "wb" if binary else "w"
61
62 targetDir = os.path.abspath(os.path.dirname(fName))
63 try:
64 oldMode = os.stat(fName)[0]
65 except os.error:
66 oldMode = None
67
68 handle, tempName = tempfile.mkstemp(".temp", "", dir=targetDir)
69 targetFile = os.fdopen(handle, mode)
70
71 try:
72 yield targetFile
73 except:
74 safeclose(targetFile)
75 try:
76 os.unlink(tempName)
77 except os.error:
78 pass
79 raise
80
81 else:
82 safeclose(targetFile)
83 os.rename(tempName, fName)
84 if oldMode is not None:
85 try:
86 os.chmod(fName, oldMode)
87 except os.error:
88 pass
89
90
91 class _UrlopenRemotePasswordMgr(urllib.request.HTTPPasswordMgr):
92 """A password manager that grabs credentials from upwards in
93 its call stack.
94
95 This is for cooperation with urlopenRemote, which defines a name
96 _temp_credentials. If this is non-None, it's supposed to be
97 a pair of user password presented to *any* realm. This means
98 that, at least with http basic auth, password stealing is
99 almost trivial.
100 """
101 def find_user_password(self, realm: str, authuri: str
102 ) -> Tuple[Optional[str], Optional[str]]:
103 creds = codetricks.stealVar("_temp_credentials")
104 if creds is not None:
105 return creds
106 return (None, None)
107
108
109 try:
110 import ssl
111
112 class HTTPSHandler(urllib.request.HTTPSHandler):
113 # We're overriding the https handler so we don't actually
114 # check certificates. Yes, that may seem somewhat daring,
115 # but then expired certs are normal in our business, whereas
116 # man-in-the-middle attacks are not.
117 def __init__(self,
118 debuglevel: int=0,
119 context: Optional[ssl.SSLContext]=None):
120 if context is None:
121 context = ssl.create_default_context(
122 purpose=ssl.Purpose.SERVER_AUTH,
123 cafile="/etc/ssl/certs/ca-certificates.crt")
124 context.check_hostname = False
125 context.verify_mode = ssl.CERT_NONE
126 urllib.request.HTTPSHandler.__init__(self, debuglevel, context)
127 except (ImportError, IOError):
128 # probably the ssl bundle isn't where I think it is; just use
129 # the normal, certificate-checking https handler.
130 from urllib.request import HTTPSHandler # type: ignore
131
132
133 _restrictedURLOpener = urllib.request.OpenerDirector()
134 _restrictedURLOpener.add_handler(urllib.request.HTTPRedirectHandler())
135 _restrictedURLOpener.add_handler(urllib.request.HTTPHandler())
136
137 try:
138 _restrictedURLOpener.add_handler(HTTPSHandler())
139 except IOError:
140 # some versions of ssl only check for the CA bundle at HTTPSHandler
141 # construction time. If that happens, fall back to urllib default handler
142 _restrictedURLOpener.add_handler(urllib.request.HTTPSHandler())
143
144 _restrictedURLOpener.add_handler(
145 urllib.request.HTTPBasicAuthHandler(_UrlopenRemotePasswordMgr()))
146 _restrictedURLOpener.add_handler(urllib.request.HTTPErrorProcessor())
147 _restrictedURLOpener.add_handler(urllib.request.FTPHandler())
148 _restrictedURLOpener.add_handler(urllib.request.UnknownHandler())
149 _restrictedURLOpener.addheaders = [("user-agent",
150 "GAVO DaCHS HTTP client")]
151
152 def setUserAgent(userAgent: str) -> None:
153 """sets the user agent string for requests through urlopenRemote.
154
155 This is a global setting and thus, in particular, nowhere near
156 thread-safe.
157 """
158 assert len(_restrictedURLOpener.addheaders)==1
159 _restrictedURLOpener.addheaders = [("user-agent", userAgent)]
160
161
162 def urlopenRemote(url: str, *,
163 data: Union[None,dict,str,bytes] = None,
164 creds: Tuple[Optional[str], Optional[str]]=(None, None),
165 timeout: int=100) -> BinaryIO:
166 """works like urllib.urlopen, except only http, https, and ftp URLs
167 are handled.
168
169 The function also massages the error messages of urllib a bit. urllib
170 errors always become IOErrors (which is more convenient within DaCHS).
171
172 creds may be a pair of username and password. Those credentials
173 will be presented in http basic authentication to any server
174 that cares to ask. For both reasons, don't use any valuable credentials
175 here.
176 """
177 # The name in the next line is used in _UrlopenRemotePasswrodMgr
178 _temp_credentials = creds #noflake: Picked up from down the call chain
179 if isinstance(data, dict):
180 data = urllib.parse.urlencode(data, encoding="utf-8")
181 if isinstance(data, str):
182 data = data.encode("ascii")
183
184 try:
185 res = _restrictedURLOpener.open(url, data, timeout=timeout)
186 if res is None:
187 raise IOError("Could not open URL %s -- does the resource exist?"%
188 url)
189 return res
190 except (urllib.error.URLError, ValueError) as msg:
191 msgStr = str(msg)
192 try:
193 msgStr = msg.args[0]
194 if isinstance(msgStr, Exception):
195 try: # maybe it's an os/socket type error
196 msgStr = msgStr.args[1]
197 except IndexError: # maybe not...
198 pass
199 if not isinstance(msgStr, str):
200 msgStr = str(msg)
201 except:
202 # there's going to be an error message, albeit maybe a weird one
203 pass
204 raise IOError("Could not open URL %s: %s"%(url, msgStr))
205
206
207 def fgetmtime(fileobj: IO) -> float:
208 """returns the mtime of the file below fileobj (like os.path.getmtime,
209 but without having to have a file name).
210
211 This raises an os.error if that file cannot be fstated.
212 """
213 try:
214 return os.fstat(fileobj.fileno()).st_mtime
215 except AttributeError:
216 raise misctricks.logOldExc(os.error("Not a file: %s"%repr(fileobj)))
217
218
219 def cat(srcF: IO, destF: IO, chunkSize: int=1<<20) -> None:
220 """reads srcF into destF in chunks.
221 """
222 while True:
223 data = srcF.read(chunkSize)
224 if not data:
225 break
226 destF.write(data)
227
228
229 def ensureDir(dirPath: str, *,
230 mode: Optional[int]=None,
231 setGroupTo: Optional[Union[str,int]]=None) -> None:
232 """makes sure that dirPath exists and is a directory.
233
234 If dirPath does not exist, it is created, and its permissions are
235 set to mode with group ownership setGroupTo if those are given.
236
237 If given, setGroupTo can be either numerical gid or a group name.
238
239 This function may raise all kinds of os.errors if something goes
240 wrong. These probably should be handed through all the way to the
241 user since when something fails here, there's usually little
242 the program can safely do to recover.
243 """
244 if os.path.exists(dirPath):
245 return
246 os.mkdir(dirPath)
247 if mode is not None:
248 os.chmod(dirPath, mode)
249 if setGroupTo:
250 if isinstance(setGroupTo, str):
251 setGroupTo = grp.getgrnam(setGroupTo).gr_gid
252 os.chown(dirPath, -1, setGroupTo)
253
254
255 class Arg:
256 """an argument/option to a subcommand.
257
258 These are constructed with positional and keyword parameters to
259 the argparse's add_argument.
260 """
261 def __init__(self, *args, **kwargs):
262 self.args, self.kwargs = args, kwargs
263
264 def add(self, parser):
265 parser.add_argument(*self.args, **self.kwargs)
266
267
268 def exposedFunction(argSpecs: List[Arg]=[], help: Optional[str]=None
269 ) -> Callable:
270 """a decorator exposing a function to parseArgs.
271
272 argSpecs is a sequence of Arg objects. This defines the command line
273 interface to the function.
274
275 The decorated function itself must accept a single argument,
276 the args object returned by argparse's parse_args.
277 """
278 def deco(func):
279 func.subparseArgs = argSpecs
280 func.subparseHelp = help
281 return func
282 return deco
283
284
285 class _PrefixMatchDict(dict):
286 """A dictionary matching on unique prefixes.
287
288 Is is just barely enough to enable longest-prefix matching for
289 argparse.
290 """
291 def __getitem__(self, key: str) -> Any: # type: ignore[override]
292 matches = [s for s in list(self.keys()) if s.startswith(key)]
293 if len(matches)==0:
294 raise KeyError(key)
295 elif len(matches)==1:
296 return dict.__getitem__(self, matches[0])
297 else:
298 raise excs.ReportableError("Ambiguous subcommand specification;"
299 " choose between %s."%repr(matches))
300
301 def __contains__(self, key: str) -> bool: # type: ignore[override]
302 for s in list(self.keys()):
303 if s.startswith(key):
304 return True
305 return False
306
307
308 def makeCLIParser(functions: Dict[str, Any]) -> argparse.ArgumentParser:
309 """returns a command line parser parsing subcommands from functions.
310
311 functions is a dictionary (as returned from globals()). Subcommands
312 will be generated from all objects that have a subparseArgs attribute;
313 furnish them using the commandWithArgs decorator.
314
315 This attribute must contain a sequence of Arg items (see above).
316 """
317 parser = argparse.ArgumentParser()
318 parser.set_defaults(subAction=lambda *args: parser.print_help())
319
320 subparsers = parser.add_subparsers()
321 for name, val in functions.items():
322 args = getattr(val, "subparseArgs", None)
323 if args is not None:
324 subForName = subparsers.add_parser(
325 name,
326 description=val.subparseHelp,
327 help=val.subparseHelp)
328 for arg in args:
329 arg.add(subForName)
330 subForName.set_defaults(subAction=val)
331
332 # Now monkeypatch matching of unique prefixes into argparse guts.
333 # If the guts change, don't fail hard, just turn off prefix matching
334 try:
335 for action in parser._actions:
336 if isinstance(action, argparse._SubParsersAction):
337 action.choices = action._name_parser_map = \
338 _PrefixMatchDict(action._name_parser_map)
339 break
340 except Exception as msg:
341 # no prefix matching, then
342 misctricks.sendUIEvent("Warning",
343 "Couldn't teach prefix matching to argparse: %s"%repr(msg))
344
345 return parser
346
347
348 class StatusDisplay:
349 """A context manager for updating a one-line display.
350
351 This shouldn't be used from DaCHS proper (which should use base.ui.notify*),
352 but it's sometimes handy in helper scripts.
353
354 In short::
355
356 with StatusDisplay() as d:
357 for i in range(300):
358 d.update(str(i))
359 """
360 def __init__(self, dest_f: TextIO=sys.stdout):
361 self.dest_f = dest_f
362 self.clearer = "\r\n"
363
364 def update(self, new_content: str) -> None:
365 self.dest_f.write(self.clearer+new_content)
366 self.dest_f.flush()
367 self.clearer = "\r"+(" "*len(new_content))+"\r"
368
369 def __enter__(self):
370 self.dest_f.write(self.clearer)
371 self.dest_f.flush()
372 return self
373
374 def __exit__(self, *args):
375 self.dest_f.write("\r\n")
376 self.dest_f.flush()