Debian Codegraph @

gavo/base/osinter.py

raw ◀ ▶
1 Debian patch touch this file
1 """
2 Basic OS interface/utility functions that depend on our configuration.
3
4 (everything that doesn't need getConfig is somewhere in gavo.utils)
5 """
6
7 #c Copyright 2008-2025, the GAVO project <[email protected]>
8 #c
9 #c This program is free software, covered by the GNU GPL. See the
10 #c COPYING file in the source distribution.
11
12
13 import functools
14 import grp
15 import inspect
16 import re
17 import os
18 import subprocess
19 import time
20 import types
21 import urllib.parse
22 from email import charset
23 from email import utils as emailutils
24 from email.header import Header
25 from email.parser import Parser
26 from email.mime.nonmultipart import MIMENonMultipart
27
•28 from gavo import pkg_resources
29
30 from twisted import copyright as twcopyright
31
32 from gavo.base import config
33 from gavo.base import parsecontext
34 from gavo import utils
35
36 from gavo.utils.dachstypes import cast, IO, Optional, TYPE_CHECKING
37
38 if TYPE_CHECKING:
39 from gavo.base.meta import MetaMixin #noflake: for type annotation
40
41
42 def getGroupId() -> int:
43 gavoGroup = config.get("group")
44 try:
45 return grp.getgrnam(gavoGroup)[2]
46 except KeyError as ex:
47 raise utils.ReportableError("Group %s does not exist"%str(ex),
48 hint="You should have created this (unix) group when you"
49 " created the server user (usually, 'gavo'). Just do it"
50 " now and re-run this program.")
51
52
53 def makeSharedDir(path: str, writable: bool = True) -> None:
54 """creates a directory with group ownership [general]group.
55
56 There's much that can to wrong; we try to raise useful error messages.
57 """
58 if not os.path.isdir(path):
59 try:
60 os.makedirs(path)
61 except os.error as err:
62 raise utils.ReportableError(
63 "Could not create directory %s"%path,
64 hint="The operating system reported: %s"%err)
65 except Exception as msg:
66 raise utils.ReportableError(
67 "Could not create directory %s (%s)"%(path, msg))
68
69 gavoGroup = getGroupId()
70 stats = os.stat(path)
71 if stats.st_mode&0o060!=0o60 or stats.st_gid!=gavoGroup:
72 try:
73 os.chown(path, -1, gavoGroup)
74 if writable:
75 os.chmod(path, stats.st_mode | 0o060)
76 except Exception as msg:
77 raise utils.ReportableError(
78 "Cannot set %s to group ownership %s, group writable"%(
79 path, gavoGroup),
80 hint="Certain directories must be writable by multiple user ids."
81 " They must therefore belong to the group %s and be group"
82 " writeable. The attempt to make sure that's so just failed"
83 " with the error message %s."
84 " Either grant the directory in question to yourself, or"
85 " fix permissions manually. If you own the directory and"
86 " sill see permission errors, try 'newgrp %s'"%(
87 config.get("group"), msg, config.get("group")))
88
89
90 @functools.lru_cache(1)
91 def getHTTPBase() -> str:
92 """returns the server's base URL for the http protocol.
93
94 This is just serverURL from the configuration, unless serverURL is https;
95 in that case, we replace https with http. serverPort is ignored here
96 under the assumption that there's a reverse proxy. If that bites you,
97 we could introduce an alternativeServerURL config item.
98 """
99 serverURL = config.get("web", "serverurl")
100 if serverURL.startswith("https:"):
101 return "http:"+serverURL[6:]
102 else:
103 return serverURL
104
105
106 @functools.lru_cache(1)
107 def getHTTPSBase() -> str:
108 """return the server's base URL for the https protocol.
109
110 If serverURL already is https, that's what's returned. If not, the URL is
111 parsed, any port specification is removed (i.e., we only support https on
112 port 443), the protocol is changed to https, and the result is returned.
113 """
114 serverURL = config.get("web", "serverurl")
115 if serverURL.startswith("https:"):
116 return serverURL
117 else:
118 parts = urllib.parse.urlparse(serverURL)
119 return urllib.parse.urlunparse(("https", parts.hostname, parts.path,
120 parts.params, parts.query, parts.fragment))
121
122
123 def switchProtocol(url: str) -> str:
124 """tries to make an https URL from an http one and vice versa.
125
126 This function will raise a ValueError if url doesn't start with either
127 HTTPBase or HTTPSBase. Otherwise, it will replace one by the other.
128 """
129 httpBase = getHTTPBase()
130 httpsBase = getHTTPSBase()
131
132 if url.startswith(httpBase):
133 return httpsBase+url[len(httpBase):]
134 elif url.startswith(httpsBase):
135 return httpBase+url[len(httpsBase):]
136 else:
137 raise ValueError("Cannot switch protocol on a URL not configured"
138 " in [web]serverURL")
139
140
141 def getCurrentServerURL() -> str:
142 """returns the server URL pertinent for the current request.
143
144 This looks upstack for a renderer object having an isSecure attribute.
145 If it finds one, it will assume it's a twisted request, call isSecure
146 and return HTTPBase() or HTTPSBase() as appropriate. If not, it will return
147 [web]serverurl
148 """
149 if config.get("web", "adaptProtocol"):
150 frame = cast(types.FrameType, inspect.currentframe()).f_back
151 frame = cast(types.FrameType, frame).f_back
152 while frame:
153 if "request" in frame.f_locals:
154 if hasattr(frame.f_locals["request"], "isSecure"):
155 if frame.f_locals["request"].isSecure():
156 return getHTTPSBase()
157 else:
158 return getHTTPBase()
159 break
160 frame = frame.f_back
161
162 return config.get("web", "serverurl")
163
164
165 @utils.document
166 def makeSitePath(path: str) -> str:
167 """returns a rooted local part for a server-internal URL.
168
169 uri itself needs to be server-absolute; a leading slash is recommended
170 for clarity but not mandatory.
171 """
172 return str(config.get("web", "nevowRoot")+path.lstrip("/"))
173
174
175 @utils.document
176 def makeAbsoluteURL(path: str, canonical: bool = False) -> str:
177 """returns a fully qualified URL for a rooted local part.
178
179 This will reflect the http/https access mode unless you pass
180 canonical=True, in which case [web]serverURL will be used unconditionally.
181 """
182 path = utils.debytify(path)
183 if canonical:
184 serverURL = config.get("web", "serverurl")
185 else:
186 serverURL = getCurrentServerURL()
187 return str(serverURL+makeSitePath(path))
188
189
190 def makeLinkForIvoid(ivoid: str) -> str:
191 """returns an http URL for ivoid.
192
193 This is using GAVO's ivoid resolver it it's not our authority, and
194 it will guess an info link otherwise. If ivoid does not look like an
195 ivoid, this will raise a ValueError.
196 """
197 mat = re.match("ivo://([^/]+)(/.*)?", ivoid)
198 if not mat:
199 raise ValueError(f"Not an ivoid: '{ivoid}'")
200
201 authority = mat.group(1)
202 if authority.lower()==config.get("ivoa", "authority"):
203 # it's ours; see if we can resolve the local part to something
204 # that has a reference URL
205 parts = mat.group(2).strip("/").split("/")
206 try:
207 regOb = cast("MetaMixin", parsecontext.resolveCrossId(
208 "/".join(parts[:-1])+"#"+parts[-1]))
209 except utils.NotFoundError:
210 # fall through to making a landing page
211 pass
212 else:
213 return str(regOb.getMeta("referenceURL"))
214
215 # it's someone else's, so link to our landing page generator
216 return "https://dc.g-vo.org/LP/"+ivoid
217
218
219 def getBinaryName(baseName: str) -> str:
220 """returns the name of a binary it thinks is appropriate for the platform.
221
222 To do this, it asks config for the platform name, sees if there's a binary
223 <bin>-<platname> if platform is nonempty. If it exists, it returns that name,
224 in all other cases, it returns baseName unchanged.
225 """
226 platform = config.get("platform")
227 if platform:
228 platName = baseName+"-"+platform
229 if os.path.exists(platName):
230 return platName
231 return baseName
232
233
234 def getPathForDistFile(name: str) -> str:
235 """returns a path for a "dist resource", i.e., a file distributed
236 with DaCHS.
237
238 name is the file relative to resources.
239
240 This is essentially pkg_resources.resource_filename with a dash
241 of built-in configuration.
242 """
243 return pkg_resources.resource_filename('gavo', "resources/"+name)
244
245
246 def openDistFile(name: str, mode: str = "r", encoding: Optional[str] = None
247 ) -> IO:
248 """returns an open file for a "dist resource", i.e., a file distributed
249 with DaCHS.
250
251 see getPathForDistFile
252 """
253 return open(getPathForDistFile(name), mode, encoding=encoding)
254
255
256 @functools.lru_cache(1)
257 def getVersion() -> str:
258 """returns (as a string) the DaCHS version running.
259
260 The information is obtained from setuptools.
261 """
262 return pkg_resources.require("gavodachs")[0].version
263
264
265 # Our software id as per https://ivoa.net/documents/Notes/softid/
266 SERVER_SOFTWARE = "DaCHS/%s twistedWeb/%s"%(
267 getVersion(),
268 twcopyright.version)
269
270
271 def formatMail(mailText: str) -> str:
272 """returns a mail with headers and content properly formatted as
273 a bytestring and MIME.
274 """
275 rawHeaders, rawBody = mailText.split("\n\n", 1)
276 cs = charset.Charset("utf-8")
277 cs.body_encoding = charset.QP
278 cs.header_encoding = charset.QP
279 # they've botched MIMEText so bad it can't really generate
280 # quoted-printable UTF-8 any more. So, let's forget MIMEText:
281 msg = MIMENonMultipart("text", "plain", charset="utf-8")
282 msg.set_payload(rawBody, charset=cs)
283
284 for key, value in list(Parser().parsestr(rawHeaders).items()):
285 if key.lower()=="date":
286 continue
287
288 if re.match("[ -~]*$", value):
289 # it's plain ASCII, don't needlessly uglify output
290 msg[key] = value
291 else:
292 msg[key] = Header(value, cs) # type: ignore # mimelib annotation bug
293
294 if "From" not in msg:
295 msg["From"] = '"DaCHS server %s" <%s>'%(
296 config.get("web", "siteName").replace('"', "'"),
297 config.get("maintainerAddress"))
298 msg["Date"] = emailutils.formatdate(time.time(),
299 localtime=False, usegmt=True)
300 msg["X-Mailer"] = "DaCHS VO Server"
301 return msg.as_string()
302
303
304 # only send each sort of mail once per hour
305 MAIL_LIMITER = utils.RateLimiter(3600)
306
307
308 def sendMail(mailText: str, rateLimitKey: Optional[str] = None) -> bool:
309 """sends mailText (which has to have all the headers) via sendmail.
310
311 (which is configured in [general]sendmail).
312
313 This will return True when sendmail has accepted the mail, False
314 otherwise.
315 """
316 if rateLimitKey:
317 if MAIL_LIMITER.inDeadtime(rateLimitKey):
318 return False
319
320 if not config.get("sendmail"):
321 utils.sendUIEvent("Warning", "Wanted to send maintainer mail but"
322 " could not since [general]sendmail is not configured.")
323
324 mailText = formatMail(mailText)
325
326 pipe = subprocess.Popen(
327 config.get("sendmail"), shell=True, stdin=subprocess.PIPE)
328 cast(IO, pipe.stdin).write(mailText.encode("ascii", "ignore"))
329 cast(IO, pipe.stdin).close()
330
331 if pipe.wait():
332 utils.sendUIEvent("Error", "Wanted to send mail starting with"
333 " '%s', but sendmail returned an error message"
334 " (check the [general]sendmail setting)."%
335 utils.makeEllipsis(mailText, 300))
336 return False
337
338 return True
339
340
341 def tryRemoteReload(rdId: str) -> None:
342 """tries to reload the rdId on a running service
343
344 This only works if there's [web]adminpasswd and[web]serverURL
345 set, and both match what the actual server uses.
346 """
347 pw = config.get("web", "adminpasswd")
348 # don't bother if admin passwd has not been set or when running unit tests.
349 if pw=="" or pw=="this_is_the_unittest_suite":
350 return
351
352 try:
353 f = utils.urlopenRemote(makeAbsoluteURL("/seffe/%s"%rdId),
354 data={"__nevow_form__": "adminOps", "submit": "Reload RD"},
355 creds=("gavoadmin", pw))
356 f.read()
357 except IOError:
358 # this is probably a refused connection; if the server doesn't run
359 # don't bother to report that.
360 pass
361 except Exception as ex:
362 utils.sendUIEvent("Info", "Could not reload %s RD (%s). This means"
363 " that the server may still use stale metadata. You may want"
364 " to reload %s manually (or restart the server)."%(rdId, ex, rdId))