Debian Codegraph @

gavo/base/config.py

raw
1 """
2 Definition of DC config options and their management including I/O.
3
4 Importing this reads the configuration, which influences almost everything
5 in DaCHS, including the way certain items are constructed. Hence, this
6 must be imported as early as humanly possible, in particular before
7 anything trying to talk to the database runs, because this is where
8 the database access profiles (well: the DSNs) are read.
9 """
10
11 #c Copyright 2008-2025, the GAVO project <[email protected]>
12 #c
13 #c This program is free software, covered by the GNU GPL. See the
14 #c COPYING file in the source distribution.
15
16
17 import functools
18 import io
19 import os
20 import re
21 import shlex
22 import sys
23 from configparser import NoOptionError
24
25 # You can't import base or anything from base here, as that would
26 # import sqlsupport, and sqlsupport needs config initialised to
27 # even come up.
28
29 from gavo import utils
30 from gavo.utils import fancyconfig
31 from gavo.utils.fancyconfig import (StringConfigItem, #noflake: exported names
32 EnumeratedConfigItem, IntConfigItem, PathConfigItem, ListConfigItem,
33 BooleanConfigItem, Section, DefaultSection, MagicSection,
34 PathRelativeConfigItem, ParseError, SetConfigItem, ExpandedPathConfigItem)
35
36 from gavo.utils.dachstypes import (Any, Callable, Dict, IO, List, NoReturn,
37 Optional, TextIO, Union, cast)
38
39 fancyconfig.BAD_CONFIG_ITEM_JUST_WARNS = True
40
41 defaultSettingsPath = "/etc/gavo.rc"
42
43
44 class RootRelativeConfigItem(PathRelativeConfigItem):
45 baseKey = "rootDir"
46 typedesc = "path relative to rootDir"
47
48
49 class WebRelativeConfigItem(PathRelativeConfigItem):
50 baseKey = "webDir"
51 typedesc = "path relative to webDir"
52
53
54 class RelativeURL(StringConfigItem):
55 """A configuration item that is interpreted relative to
56 the server's root URL.
57 """
58
59 _value = ""
60 typedesc = "URL fragment relative to the server's root"
61
62 def _getValue(self) -> str:
63 if (self._value.startswith("http://")
64 or self._value.startswith("https://")
65 or self._value.startswith("/")):
66 return self._value
67 if self.parent is not None:
68 return self.parent.get("web", "nevowRoot")+self._value
69 raise NotImplementedError("Unparented RelativeURL?")
70
71 def _setValue(self, val: str) -> None:
72 self._value = val
73
74 value = property(_getValue, _setValue)
75
76
77 class EatTrailingSlashesItem(StringConfigItem):
78 """is a config item that must not end with a slash. A trailing slash
79 on input is removed.
80 """
81
82 typedesc = "path fragment"
83
84 def _parse(self, val: str) -> str:
85 return StringConfigItem._parse(self, val).rstrip("/")
86
87
88 class EnsureTrailingSlashesItem(StringConfigItem):
89 """A config item that must end with a slash. If no slash is present
90 on input, it is added.
91 """
92
93 typedesc = "path fragment"
94
95 def _parse(self, val: str) -> str:
96 val = StringConfigItem._parse(self, val)
97 if val is not None and not val.endswith("/"):
98 val = val+"/"
99 return val
100
101
102 class AuthorityConfigItem(StringConfigItem):
103 """an IVOA Identifers-compatible authority.
104 """
105 def _parse(self, val: str) -> str:
106 val = StringConfigItem._parse(self, val)
107 authorityRE = "[a-zA-Z0-9][a-zA-Z0-9._~-]{2,}$"
108 if not re.match(authorityRE, val):
109 raise fancyconfig.BadConfigValue("[ivoa]authority must match %s"
110 " ('more than three normal characters')"%authorityRE)
111 return val
112
113
114 class Error(utils.Error):
115 pass
116
117 class ProfileParseError(Error):
118 pass
119
120
121 class DBProfile:
122 """A parsed form of the postgres connection string.
123 """
124 profileName = "anonymous"
125 name = None
126 host = ""
127 port = None
128 database = ""
129 user = ""
130 password = ""
131 sslmode = "allow" # or disable, allow, prefer, require, verify-*)")
132
133 def __init__(self, **kwargs: Any) -> None:
134 for k, v in kwargs.items():
135 setattr(self, k, v)
136
137 def getArgs(self) -> Dict[str, str]:
138 """returns a dictionary suitable as keyword arguments to psycopg2's
139 connect.
140 """
141 res = {}
142 for key in ["database", "user", "password", "host", "port", "sslmode"]:
143 if getattr(self, key):
144 res[key] = getattr(self, key)
145 if list(res.keys())==["sslmode"]:
146 raise utils.logOldExc(utils.StructureError("Insufficient information"
147 " to connect to the database in profile '%s'."%(
148 self.profileName)))
149 return res
150
151 @property
152 def roleName(self) -> str:
153 """returns the database role used by this profile.
154
155 This normally is user, but in the special case of the empty user,
156 we return the logged users' name.
157 """
158 if self.user:
159 return self.user
160 else:
161 try:
162 return os.getlogin()
163 except os.error:
164 raise utils.ReportableError("Profiles without user= are only"
165 " allowed when DaCHS is called interactively.")
166
167
168 _StateFunction = Callable[[str], Callable[[str], Callable]]
169
170 class ProfileParser:
171 r"""A parser for database access profiles.
172
173 The profiles are specified in simple text files that have a shell-like
174 syntax. Each line either contains an assignment (x=y) or is of the
175 form ``<command> <arg>*``. Recognized commands include:
176
177 - include f -- read instructions from file f, searched along profilePath
178
179 >>> p = ProfileParser()
180 >>> p.parse(None, "x", "host=foo.bar\n").host
181 'foo.bar'
182 >>> p.parse(None, "x", "") is not None
183 True
184 >>> p.parse(None, "x", "host=\n").host
185 ''
186 >>> p.parse(None, "x", "=bla\n")
187 Traceback (most recent call last):
188 gavo.base.config.ProfileParseError: "x", line 1: invalid identifier '='
189 >>> p.parse(None, "x", "host=bla")
190 Traceback (most recent call last):
191 gavo.base.config.ProfileParseError: "x", line 1: unexpected end of file (missing line feed?)
192 """
193 profileKeys = set(["host", "port", "database", "user", "password",
194 "sslmode"])
195
196 def __init__(self, sourcePath: List[str] = ["."]) -> None:
197 self.commands = {
198 "include": self._state_include,
199 }
200 self.sourcePath = sourcePath
201
202 def parse(self,
203 profileName: Optional[str],
204 sourceName: Optional[str],
205 stream: Optional[Union[str, IO]] = None) -> DBProfile:
206 """parses a profile input and returns a new DBProfile instance.
207
208 You can pass in a stream (a file open for reading or a string containing
209 profile material, but that's really mainly test instrumentation.
210 Usually, you will instead pass in sourceName, which is then searched
211 in the sourcePath.
212
213 stream, if an open file, will be closed by the function.
214
215 The parsing itself works by state function returning the next state
216 function; each state function is a Callable accepting a token and
217 returning a new state function.
218 """
219 self.tokenStack: List[str] = []
220 self.stateFun: _StateFunction = self._state_init
221 if stream is None:
222 if sourceName is None:
223 raise NotImplementedError(
224 "parse needs either a sourceName or a stream")
225 else:
226 sourceName = self._resolveSource(sourceName)
227 stream = open(sourceName)
228 elif isinstance(stream, str):
229 stream = io.StringIO(stream)
230
231 stream = cast(TextIO, stream)
232 self.parser = shlex.shlex(stream, sourceName, posix=True)
233 self.parser.whitespace = " \t\r"
234 self.profile = DBProfile(name=profileName)
235 while True:
236 tok = self.parser.get_token()
237 if not tok:
238 break
239 self._feed(tok)
240
241 if self.stateFun!=self._state_init:
242 self._raiseError("unexpected end of file (missing line feed?)")
243 if profileName:
244 self.profile.profileName = profileName
245
246 stream.close()
247 return self.profile
248
249 def _raiseError(self, msg: str) -> NoReturn:
250 # in bookworm, mypy gets error_leader's signature wrong.
251 # the type:ignore can probably be dropped later.
252 raise utils.logOldExc(
253 ProfileParseError(self.parser.error_leader()+msg)) # type:ignore
254
255 def _state_init(self, token: str) -> _StateFunction:
256 """the initial state of the parser: wait for a command or an assignement.
257 """
258 if token in self.commands:
259 return self.commands[token]
260 elif token=="\n":
261 return self._state_init
262
263 if not re.match(r"[A-Za-z][\w]+$", token):
264 self._raiseError("invalid identifier %s"%repr(token))
265 self.tokenStack.append(token)
266 return self._state_waitForEqual
267
268 def _resolveSource(self, fName: str) -> str:
269 """returns a path for a profile fragment in fName.
270
271 It resolves the name along sourcePath.
272 """
273 for dir in self.sourcePath:
274 fqName = os.path.join(dir, fName)
275 if os.path.exists(fqName):
276 return fqName
277 raise ProfileParseError("Requested db profile %s does not exist"%
278 repr(fName))
279
280 def _state_include(self, token: str) -> _StateFunction:
281 """the state in which the parser expects a profile fragment name.
282 """
283 if token=="\n":
284 fName = "".join(self.tokenStack)
285 self.tokenStack = []
286 fName = self._resolveSource(fName)
287 self.parser.push_source(open(fName), fName)
288 return self._state_init
289 else:
290 self.tokenStack.append(token)
291 return self._state_include
292
293 def _state_eol(self, token: str) -> _StateFunction:
294 """the state in which a statement has been successfully parsed.
295 """
296 if token!="\n":
297 self._raiseError("expected end of line")
298 return self._state_init
299
300 def _state_waitForEqual(self, token: str) -> _StateFunction:
301 """the state when the lvalue of an assingment has been parsed.
302 """
303 if token!="=":
304 self._raiseError("expected '='")
305 return self._state_rval
306
307 def _state_rval(self, token: str) -> _StateFunction:
308 """the state when an rvalue of an assignment is parsed.
309 """
310 if token=="\n":
311 key = self.tokenStack.pop(0)
312 val = "".join(self.tokenStack)
313 self.tokenStack = []
314 if not key in self.profileKeys:
315 self._raiseError("unknown setting %s"%repr(key))
316 setattr(self.profile, key, val)
317 return self._state_init
318 else:
319 self.tokenStack.append(token)
320 return self._state_rval
321
322 def _feed(self, token: str) -> None:
323 """processes token by driving the parser into the next state.
324 """
325 self.stateFun = self.stateFun(token)
326
327
328 class Configuration(fancyconfig.Configuration):
329 """A container for settings.
330
331 It is a fancyconfig.Configuration with the addition of making the
332 attributes shared at the class level to ward against multiple imports
333 (which may happen if config is imported in a weird way).
334
335 In addition, this class handles the access to database profiles.
336 """
337 __sharedState: Dict[str,Any] = {}
338
339 def __init__(self, *items: fancyconfig.Section):
340 self.__dict__ = self.__sharedState
341 fancyconfig.Configuration.__init__(self, *items)
342
343 def _getProfileParser(self) -> ProfileParser:
344 if not hasattr(self, "__profileParser"):
345 self.__profileParser = ProfileParser(
346 self.get("db", "profilePath"))
347 return self.__profileParser
348
349 @functools.cache
350 def getDBProfile(self, profileName: str) -> DBProfile:
351 # remains of retired profile name mapping infrastructure
352 if profileName=='admin':
353 profileName = 'feed'
354
355 try:
356 return self._getProfileParser().parse(profileName, profileName)
357 except utils.NoConfigItem:
358 raise ProfileParseError("Undefined DB profile: %s"%profileName)
359
360
361 _config = Configuration(
362 DefaultSection('Paths and other general settings.',
363 ExpandedPathConfigItem("rootDir", default="/var/gavo", description=
364 "Path to the root of the DC file (all other paths may be"
365 " relative to this"),
366 RootRelativeConfigItem("configDir", default="etc",
367 description="Path to the DC's non-ini configuration (e.g., DB profiles)"),
368 RootRelativeConfigItem("inputsDir", default="inputs",
369 description="Path to the DC's data holdings"),
370 RootRelativeConfigItem("cacheDir", default="cache",
371 description="Path to the DC's persistent scratch space"),
372 RootRelativeConfigItem("logDir", default="logs",
373 description="Path to the DC's logs (should be local)"),
374 RootRelativeConfigItem("tempDir", default="tmp",
375 description="Path to the DC's scratch space (should be local)"),
376 RootRelativeConfigItem("webDir", default="web",
377 description="Path to the DC's web related data (docs, css, js,"
378 " templates...)"),
379 RootRelativeConfigItem("stateDir", default="state",
380 description="Path to the DC's state information (last imported,...)"),
381 RootRelativeConfigItem("uwsWD", default="state/uwsjobs",
382 description="Directory to keep uws jobs in. This may need lots"
383 " of space if your users do large queries"),
384 EnumeratedConfigItem("logLevel", options=["info", "warning",
385 "debug", "error"], description="How much should be logged?"),
386 StringConfigItem("platform", description="Platform string (can be"
387 " empty if inputsDir is only accessed by identical machines)"),
388 StringConfigItem("gavoGroup", description="Name of the unix group that"
389 " administers the DC", default="gavo"),
390 StringConfigItem("defaultProfileName", description="Deprecated"
391 " and ignored.", default=""),
392 StringConfigItem("group", description="Name of the group that may write"
393 " into the log directory", default="gavo"),
394 PathConfigItem("xsdclasspath", description="Classpath necessary"
395 " to validate XSD using an xsdval java class. You want GAVO's"
396 " VO schemata collection for this. Deprecated, we're now using"
397 " libxml2 for validation.", default="None"),
398 StringConfigItem("sendmail", default="sendmail -t",
399 description="Command that reads a mail from stdin, taking the"
400 "recipient address from the mail header, and transfers the"
401 " mail (this is for sending mails to the administrator)."
402 " This command is processed by a shell (generally running as"
403 " the server user), so you can do tricks if necessary."),
404 StringConfigItem("maintainerAddress", default="",
405 description="An e-mail address to send reports and warnings to;"
406 " this could be the same as contact.email; in practice, it is"
407 " shown in more technical circumstances, so it's adviable"
408 " to have a narrower distribution here."),
409 SetConfigItem("future", default="",
410 description="A set of strings naming experimental features"
411 " to enable in the server. You only want to touch this"
412 " if you are working on proving proposed improvements."),
413 SetConfigItem("rdblacklist", default="",
414 description="File names of blacklisted RDs. These are matched"
415 " against the ends of file names, so be careful you do not"
416 " over-block; in general, you should use something like"
417 " '/resname/q.rd' or so. You can also blacklist RD ids"
418 " (which are compared literally). Separate multiple entries"
419 " by commas."),
420 ),
421
422 Section('web', 'Settings related to serving content to the web.',
423 StringConfigItem("serverURL", default="http://localhost:8080",
424 description="URL fragment used to qualify relative URLs where"
425 " necessary. Note that this must contain the port the server is"
426 " accessible under from the outside if that is not 80; nonstandard"
427 " ports are not supported for https. If you offer"
428 " both http and https, use your preferred protocol here."
429 " If you change this on an existing server, you *must* run"
430 " dachs pub ALL to update internal and external links."),
431 ListConfigItem("alternateHostnames", default="",
432 description="A comma-separated list of hostnames this server is"
433 " also known under. Only set this if you're running https."
434 " With this, you can handle a situation where your data"
435 " centre can be reached as both example.org and www.example.org."),
436 StringConfigItem("bindAddress", default="127.0.0.1", description=
437 "Interface to bind to"),
438 IntConfigItem("serverPort", default="8080",
439 description="Port to bind the http port of the server to; https,"
440 " if present at all, is always on 443."),
441 BooleanConfigItem("adaptProtocol", default="True",
442 description="Adapt internal absolute links to http/https by"
443 " request method used. You must switch this off if running"
444 " behind a reverse proxy."),
445 StringConfigItem("user", default="gavo", description="Run server as"
446 " this user."),
447 EnsureTrailingSlashesItem("nevowRoot", default="/",
448 description="Path fragment to the server's root for operation off the"
449 " server's root; this must end with a slash (setting this"
450 " will currently break essentially the entire web interface."
451 " If you must use it, contact the authors and we will fix things.)"),
452 StringConfigItem("realm", default="X-Unconfigured",
453 description="Authentication realm to be used (currently,"
454 " only one, server-wide, is supported)"),
455 WebRelativeConfigItem("templateDir", default="templates",
456 description="webDir-relative location of global nevow templates"),
457 StringConfigItem("adminpasswd", default="",
458 description="Password for online administration, leave empty to disable"),
459 StringConfigItem("sitename", "Unnamed data center",
460 "A short name for your site"),
461 IntConfigItem("sqlTimeout", "15",
462 "Default timeout for non-TAP database queries (which can in"
463 " general be overridden by users setting _TIMEOUT)."),
464 WebRelativeConfigItem("previewCache", "previewcache",
465 "Webdir-relative directory to store cached previews in"),
466 WebRelativeConfigItem("favicon", "None",
467 "Webdir-relative path to a favicon; this overrides the default of"
468 " a scaled version of the logo."),
469 BooleanConfigItem("enableTests", "False",
470 "Enable test pages (don't if you don't know why)"),
471 IntConfigItem("maxPreviewWidth", "300", "Ignored, only present"
472 " for backward compatibility"),
473 ListConfigItem("graphicMimes",
474 "image/fits,image/jpeg,application/x-votable+xml;content=datalink,"
475 "application/fits",
476 "Media types considered as graphics (for SIAP, mostly)"),
477 IntConfigItem("maxUploadSize",
478 "20000000",
479 "Maximal size of (mainly TAP) file uploads in async requests in bytes;"
480 " sync requests use maxSyncUploadSize."),
481 IntConfigItem("maxSyncUploadSize",
482 "500000",
483 "Maximal size of file uploads for synchronous TAP in bytes."),
484 ListConfigItem("preloadRDs", "", "RD ids to preload at the server"
485 " start. Load time of RDs listed here goes against startup time,"
486 " so only do this for RDs that have execute children"
487 " that should run regularly. For everything else consider"
488 " preloadPublishedRDs."),
489 BooleanConfigItem("preloadPublishedRDs", "False", "Preload"
490 " all RDs of services you've published. This is mainly helpful"
491 " when code in such RDs might, for instance, lock and such"
492 " failures don't suddenly occur in operation."),
493 BooleanConfigItem("jsSource", "False", "If True, Javascript"
494 " will not be minified on delivery (this is for debugging)"),
495 StringConfigItem("operatorCSS", "", "URL of an operator-specific"
496 " CSS. This is included as the last item and can therefore"
497 " override rules in the distributed CSS."),
498 StringConfigItem("corsOriginPat", "", "A regular expression"
499 " for URLs from which to authorise cross-origin requests."
500 " This is matched, i.e., the RE must account for the whole URL"
501 r" including the schema. Example: https?://example\.com/apps/.*."),
502 IntConfigItem("serverFDLimit", "4000",
503 "A hard limit of the number of file handles DaCHS should try to"
504 " set. This will only take effect if DaCHS is started as root."
505 " Otherwise, DaCHS will just adjust its soft limit to the"
506 " external limit irrespective of this setting."),
507 EnumeratedConfigItem("logFormat", "default", "Log format to use."
508 " Default doesn't log IPs, user agents, or referrers and"
509 " thus should be ok in terms of not processing personal data,"
510 " which in turn means you probably don't have to declare anything"
511 " in EU jurisdictions.", options=["default", "combined"]),
512 StringConfigItem("root", "__system__/services/root/fixed",
513 "The path of the the root page of the data center. The default"
514 " renders the root.html template. On single-service installations,"
515 " you could direct this to that single service, or you could"
516 " use the ADQL query form."),
517 BooleanConfigItem("ignore-uir-header", "False",
518 "Do not honour clients' upgrade-insecure-requests headers if"
519 " https is enabled. Outside of development or testing environments,"
520 " there is generally little reason to use this.")
521 ),
522
523 Section('adql', "(ignored, only left for backward compatibility)",
524 IntConfigItem("webDefaultLimit", "2000",
525 "(ignored, only present for backwards compatibility; use"
526 " [async]defaultMAXREC instead."),
527 ),
528
529 Section('async', "Settings concerning TAP, UWS, and friends",
530 IntConfigItem("defaultExecTimeSync", "60", "Timeout"
531 " for synchronous TAP/UWS jobs, in seconds."),
532 IntConfigItem("defaultExecTime", "3600", "Default timeout"
533 " for UWS jobs, in seconds"),
534 IntConfigItem("maxTAPRunning", "2", "Maximum number of"
535 " TAP jobs running at a time"),
536 IntConfigItem("maxUserUWSRunningDefault", "2", "Maximum number of"
537 " user UWS jobs running at a time"),
538 IntConfigItem("defaultLifetime", "172800", "Default"
539 " time to destruction for UWS jobs, in seconds"),
540 IntConfigItem("defaultMAXREC", "20000",
541 "Default match limit for ADQL queries via the UWS/TAP"),
542 IntConfigItem("hardMAXREC", "20000000",
543 "Hard match limit (i.e., users cannot raise MAXREC or TOP beyond that)"
544 " for ADQL queries via the UWS/TAP"),
545 StringConfigItem("csvDialect", "excel", "CSV dialect as defined"
546 " by the python csv module used when writing CSV files."),
547 IntConfigItem("maxSlowPollWait", "300", "Maximal time a UWS 1.1-WAIT"
548 " request will delay the response. This should be smaller than"
549 " what you have as timeout on outgoing connections."),
550 ),
551
552 Section('ui', "Settings concerning the local user interface",
553 ),
554
555 Section('db', 'Settings concerning database access.',
556 IntConfigItem("indexWorkMem",
557 "2000",
558 "Megabytes of memory to give to postgres while making indices."
559 " Set to roughly half your RAM when you have big tables."),
560 StringConfigItem("interface", "psycopg2", "Don't change"),
561 PathConfigItem("profilePath", "~/.gavo:$configDir",
562 "Path for locating DB profiles"),
563 StringConfigItem("msgEncoding", "utf-8", "Encoding of the"
564 " messages coming from the database"),
565 SetConfigItem("maintainers", "admin", "Name(s) of profiles"
566 " that should have full access to gavo imp-created tables by default"),
567 SetConfigItem("queryProfiles", "trustedquery", "Name(s) of profiles that"
568 " should be able to read gavo imp-created tables by default"),
569 SetConfigItem("adqlProfiles", "untrustedquery", "Name(s) of profiles that"
570 " get access to tables opened for ADQL"),
571 IntConfigItem("defaultLimit", "100", "Default match limit for DB queries"),
572 ListConfigItem("managedExtensions",
573 "pg_sphere",
574 "Name(s) of postgres extensions gavo upgrade -e should watch"),
575 BooleanConfigItem("dumpSystemTables",
576 "False",
577 "Dump the tables from //users and //system to"
578 " stateDir/system_tables once a day?"),
579 IntConfigItem("poolSize", "2",
580 "Number of connections in DaCHS' postgres connection pools."),
581 BooleanConfigItem("q3cPlannerHack",
582 "True",
583 "Disable seqscanning when running queries using q3c. This"
584 " used to unconditionally help in ancient times but may actually"
585 " hurt with newer postgreses."),
586 EnumeratedConfigItem("splitSpatialIndex", "pgsphere",
587 "Type of spatial index created for lat/lon pairs in TAP uploads"
588 " (and potentially later other things).",
589 options=["q3c", "pgsphere"])
590 ),
591
592 Section('ivoa', 'The interface to the Greater VO.',
593 AuthorityConfigItem("authority", "x-unregistred",
594 "The authority id for this DC; this has *no* leading ivo://"),
595 IntConfigItem("dalDefaultLimit", "10000",
596 "Default match limit on SCS/SSAP/SIAP queries"),
597 IntConfigItem("dalHardLimit", "1000000",
598 "Hard match limit on SCS/SSAP/SIAP queries (be careful: due to the"
599 " way these protocols work, the results cannot be streamed, and"
600 " the results have to be kept in memory; 1e7 rows requiring 1k"
601 " of memory each add up to 10 Gigs...)"),
602 IntConfigItem("oaipmhPageSize", "500",
603 "Default number of records per page in the OAI-PMH interface"),
604 EnumeratedConfigItem("votDefaultEncoding", "binary",
605 "Default 'encoding' for VOTables in many places (like the DAL"
606 " responses; this can be user-overridden using"
607 " the _TDENC local HTTP parameter.", options=["binary", "td"]),
608 EnumeratedConfigItem("sdmVersion", "1",
609 "Obsolete (SDM version 2 is shelved). Don't use.",
610 options=["1", "2"]),
611 EnumeratedConfigItem("VOSITableDetail",
612 "max",
613 "Default level of detail to return on the VOSI endpoint (change"
614 " to min when you have more than 100 or tables).",
615 options=["min", "max"]),
616 BooleanConfigItem("registerAlternative",
617 "False",
618 "Give access URLs for the alternative protocol (https when"
619 " serverURL is http and vice versa) as a mirrorURL? If you're"
620 " listening to HTTPS, this is probably a good idea."),
621 ListConfigItem("validOAISets",
622 "ivo_managed, vosi, local",
623 "Comma-separated list of OAI sets DaCHS should accept for publication."
624 " This must always include ivo_managed and vosi, and you will"
625 " want local if you run a web interface."),
626 IntConfigItem("userTableDays", "7",
627 "Number of days that user-uploaded TAP tables are kept before"
628 " garbage collection"),
629 BooleanConfigItem("materialiseObscore",
630 "False",
631 "Make ivoa.obscore a materialised view. This may help"
632 " if you have large, complex obscore contributions and"
633 " postgres chooses bad query planes for them (since 2.12.3)."),
634 ),
635 )
636
637 def loadConfig() -> None:
638 """reads the configuration from /etc/gavo.rc and ~/.gavorc.
639
640 This manipulates the global _config object.
641
642 Actually, you can override these locations in GAVOSETTINGS and GAVOCUSTOM.
643 But you'll confuse everyone if you do that in production, so only
644 do that if it *really* helps somewhere else (as perhaps in containers
645 when you want to everything writable in one place).
646
647 This also manipulates the environment such that libraries with
648 configuration files fetch them from our configDir.
649 """
650 try:
651 fancyconfig.readConfiguration(_config,
652 os.environ.get("GAVOSETTINGS", "/etc/gavo.rc"),
653 os.environ.get("GAVOCUSTOM",
654 os.path.join(os.environ.get("HOME", "/no_home"), ".gavorc")))
655 except fancyconfig.ConfigError as ex:
656 # This is usually not be protected by top-level exception catcher
657 sys.exit("Bad configuration item in %s. %s"%(
658 ex.fileName, str(ex)))
659
660 # also set XDG directories so astropy and friends look for their
661 # configuration in DaCHS' directories
662 os.environ["XDG_CONFIG_HOME"] = str(_config.get("configDir"))
663 os.environ["XDG_CACHE_HOME"] = str(_config.get("cacheDir"))
664 try:
665 from astropy.config import reload_config # type: ignore
666 reload_config("astropy")
667 except Exception:
668 # astropy panics here if it can't write to its home. But then
669 # the reload failure probably doesn't matter either, so let's
670 # just ignore it
671 pass
672
673 # also configure matplotlib to pull their configuration from
674 # DaCHS' configuration (rather than any random matplotlibrc people
675 # may have left).
676 os.environ["MATPLOTLIBRC"] = str(_config.get("configDir"))
677
678 loadConfig()
679
680
681 if "GAVO_INPUTSDIR" in os.environ:
682 _config.set("inputsDir", os.environ["GAVO_INPUTSDIR"])
683
684 get = _config.get
685 set = _config.set
686 getitem = _config.getitem
687
688 getDBProfile = _config.getDBProfile
689
690
691 def getRSTReference(underlineChar="-") -> str:
692 """returns a ReStructuredText reference of configuration items.
693
694 This will have one RST section per configuration section; to let
695 you adapt that to an embedding document, you can pass the character
696 to use for headline underlines in underlineChar.
697 """
698 return fancyconfig.makeTxtDocs(_config, underlineChar=underlineChar)
699
700
701 def main(): # pragma: no cover
702 try:
703 if len(sys.argv)==1:
704 print(getRSTReference)
705 sys.exit(0)
706 elif len(sys.argv)==2:
707 item = _config.getitem(sys.argv[1])
708 elif len(sys.argv)==3:
709 item = _config.getitem(sys.argv[1], sys.argv[2])
710 else:
711 sys.stderr.write("Usage: %s [<sect> <key> | <key>]\n")
712 sys.exit(1)
713 except NoOptionError:
714 print("")
715 sys.exit(2)
716 print(item.getAsString())
717
718
719 def _test(): # pragma: no cover
720 import doctest
721 doctest.testmod()
722
723
724 if __name__=="__main__": # pragma: no cover
725 _test()