Debian Codegraph @

gavo/user/initdachs.py

raw
1 """
2 Initial setup for the file system hierarchy.
3
4 This module is supposed to create as much of the DaCHS file system environment
5 as possible. Take care to give sensible error messages -- much can go wrong
6 here, and it's nice if the user has a way to figure out what's wrong.
7 """
8
9 #c Copyright 2008-2025, the GAVO project <[email protected]>
10 #c
11 #c This program is free software, covered by the GNU GPL. See the
12 #c COPYING file in the source distribution.
13
14
15 import base64
16 import datetime
17 import os
18 import sys
19 import textwrap
20 import warnings
21
22 import psycopg2
23
24 # keep sqlsupport from initialisation before we've set up the profiles
25 os.environ["GAVO_INIT_RUNNING"] = "1"
26 from gavo import base
27 from gavo import utils
28 del os.environ["GAVO_INIT_RUNNING"]
29
30
31 def bailOut(msg, hint=None):
32 sys.stderr.write("*** Error: %s\n\n"%msg)
33 if hint is not None:
34 sys.stderr.write(textwrap.fill(hint)+"\n")
35 sys.exit(1)
36
37
38 def unindentString(s):
39 return "\n".join(s.strip() for s in s.split("\n"))+"\n"
40
41
42 def makeRoot():
43 rootDir = base.getConfig("rootDir")
44 if rootDir.is_dir():
45 return
46 try:
47 os.makedirs(rootDir)
48 except os.error:
49 bailOut("Cannot create root directory %s."%rootDir,
50 "This usually means that the current user has insufficient privileges"
51 " to write to the parent directory. To fix this, either have rootDir"
52 " somewhere you can write to (edit /etc/gavorc) or create the directory"
53 " as root and grant it to your user id.")
54
55
56 def makeDirVerbose(path, setGroupTo, makeWritable):
57 if not os.path.isdir(path):
58 try:
59 os.makedirs(path)
60 except os.error as err:
61 bailOut("Could not create directory %s (%s)"%(
62 path, err)) # add hints
63 except Exception as msg:
64 bailOut("Could not create directory %s (%s)"%(
65 path, msg))
66 if setGroupTo is not None:
67 stats = os.stat(path)
68 if stats.st_mode&0o060!=0o60 or stats.st_gid!=setGroupTo:
69 try:
70 os.chown(path, -1, setGroupTo)
71 if makeWritable:
72 os.chmod(path, stats.st_mode | 0o060)
73 except Exception as ex:
74 # don't fail hard because something is wrong here; there
75 # *are* configurations in which things may still work.
76 sys.stderr.write(f"Cannot set {path} to group ownership {setGroupTo},"
77 f" group writable.\n{ex}\n"
78 "This will probably be trouble later. Hence,"
79 " please fix it manually.\n")
80
81
82 _GAVO_WRITABLE_DIRS = set([
83 "stateDir",
84 "cacheDir",
85 "logDir",
86 "tempDir",
87 "uwsWD",])
88
89
90 def makeDirForConfig(configKey, gavoGrpId):
91 path = base.getConfig(configKey)
92 makeDirVerbose(path, gavoGrpId, configKey in _GAVO_WRITABLE_DIRS)
93
94
95 def makeDefaultMeta():
96 destPath = base.getConfig("configDir") / "defaultmeta.txt"
97 if os.path.exists(destPath):
98 return
99 rawData = unindentString(r"""publisher: Your organisation's name
100 contact.name: Fill Out
101 contact.address: Ordinary street address.
102 contact.email: [email protected]
103 contact.telephone: Delete this line if you don't want to give it
104 creator.name: Could be same as contact.name
105 creator.logo: \getConfig{web}{serverURL}/favicon.png
106
107 _noresultwarning: Your query did not match any data.
108
109 authority.creationDate: %s
110 authority.shortName: <13 chrs
111
112 site.description: This should be a relatively terse \
113 description of your data center. This will, for instance, turn \
114 up in the default root template.
115 """%(datetime.datetime.utcnow().isoformat().split(".")[0]))
116 with open(destPath, "w") as f:
117 f.write(rawData)
118
119 # load new new default meta
120 from gavo.base import meta
121 meta.makeFallbackMeta()
122
123
124 def makeMatplotlibCfg():
125 destPath = base.getConfig("configDir") / "matplotlibrc"
126 if destPath.exists():
127 return
128 with open(destPath, "w") as f:
129 f.write("backend: Agg\nsvg.fonttype: path\n")
130
131
132 def makeAstropyCfg():
133 """creates an astropy directory in configDir.
134
135 This should prevent astropy from trying to read from home once DaCHS
136 is properly up.
137 """
138 destPath = base.getConfig("configDir") / "astropy"
139 makeDirVerbose(destPath, base.getGroupId(), True)
140
141
142 def prepareWeb(groupId):
143 makeDirVerbose(base.getConfig("webDir") / "nv_static", groupId, False)
144 makeDirVerbose(base.getConfig("webDir") / "templates", groupId, False)
145
146
147 def _genPW():
148 """returns a random string that may be suitable as a database password.
149
150 The entropy of the generated passwords should be close to 160 bits, so
151 the passwords themselves would probably not be a major issue. Of course,
152 for DaCHS they are stored in the file system in clear text...
153 """
154 return utils.debytify(base64.b64encode(os.urandom(20)))
155
156
157 def makeProfiles(dsn, userPrefix=""):
158 """writes profiles with made-up passwords to DaCHS' config dir.
159
160 This will mess everything up when the users already exist. We
161 should probably provide an option to drop standard users.
162
163 userPrefix is mainly for the test infrastructure.
164 """
165 profilePath = base.getConfig("configDir")
166 dsnContent = ["database = %s"%(dsn.parsed["dbname"])]
167 if "host" in dsn.parsed:
168 dsnContent.append("host = %s"%dsn.parsed["host"])
169 else:
170 dsnContent.append("host = localhost")
171 if "port" in dsn.parsed:
172 dsnContent.append("port = %s"%dsn.parsed["port"])
173 else:
174 dsnContent.append("port = 5432")
175
176 for fName, content in [
177 ("dsn", "\n".join(dsnContent)+"\n"),
178 ("feed", "include dsn\nuser = %sgavoadmin\npassword = %s\n"%(
179 userPrefix, _genPW())),
180 ("trustedquery", "include dsn\nuser = %sgavo\npassword = %s\n"%(
181 userPrefix, _genPW())),
182 ("untrustedquery", "include dsn\nuser = %suntrusted\npassword = %s\n"%(
183 userPrefix, _genPW())),]:
184 destPath = profilePath / fName
185 if not destPath.exists():
186 with open(destPath, "w") as f:
187 f.write(content)
188
189
190 def createFSHierarchy(dsn, userPrefix=""):
191 """creates the directories required by DaCHS.
192
193 userPrefix is for use of the test infrastructure.
194 """
195 makeRoot()
196 grpId = base.getGroupId()
197 for configKey in ["configDir", "inputsDir", "cacheDir", "logDir",
198 "tempDir", "webDir", "stateDir"]:
199 makeDirForConfig(configKey, grpId)
200 makeDirVerbose(base.getConfig("inputsDir") / "__system", grpId, False)
201 makeDefaultMeta()
202 makeMatplotlibCfg()
203 makeAstropyCfg()
204 makeProfiles(dsn, userPrefix)
205 prepareWeb(grpId)
206
207
208 ###################### DB interface
209 # This doesn't use much of sqlsupport since the roles are just being
210 # created and some of the operations may not be available for non-supervisors.
211
212 class DSN(object):
213 """a psycopg-style DSN, both parsed and unparsed.
214 """
215 def __init__(self, dsn):
216 self.full = dsn
217 self._parse()
218 self._validate()
219
220 _knownKeys = set(["dbname", "user", "password", "host", "port", "sslmode"])
221
222 def _validate(self):
223 for key in self.parsed:
224 if key not in self._knownKeys:
225 sys.stderr.write("Unknown DSN key %s will get lost in profiles."%(
226 key))
227
228 def _parse(self):
229 if "=" in self.full:
230 self.parsed = utils.parseKVLine(self.full)
231 else:
232 self.parsed = {"dbname": self.full}
233 self.full = utils.makeKVLine(self.parsed)
234
235
236 def _execDB(conn, query, args={}):
237 """returns the result of running query with args through conn.
238
239 No transaction management is being done here.
240 """
241 cursor = conn.cursor()
242 cursor.execute(query, args)
243 return list(cursor)
244
245
246 def _roleExists(conn, roleName):
247 return _execDB(conn,
248 "SELECT rolname FROM pg_roles WHERE rolname=%(rolname)s",
249 {"rolname": roleName})
250
251
252 def _createRoleFromProfile(conn, profile, privileges):
253 cursor = conn.cursor()
254 try:
255 verb = "CREATE"
256 if _roleExists(conn, profile.user):
257 verb = "ALTER"
258 cursor.execute(
259 "%s ROLE %s PASSWORD %%(password)s %s LOGIN"%(
260 verb, profile.user, privileges), {
261 "password": profile.password,})
262 conn.commit()
263 except:
264 warnings.warn("Could not create role %s (see db server log)"%
265 profile.user)
266 conn.rollback()
267
268
269 def _createRoles(dsn):
270 """creates the roles for the DaCHS profiles admin, trustedquery
271 and untrustedquery.
272 """
273 from gavo.base import config
274
275 conn = psycopg2.connect(dsn.full)
276 for profileName, privileges in [
277 ("admin", "CREATEROLE"),
278 ("trustedquery", ""),
279 ("untrustedquery", "")]:
280 _createRoleFromProfile(conn,
281 config.getDBProfile(profileName),
282 privileges)
283
284 adminProfile = config.getDBProfile("admin")
285 cursor = conn.cursor()
286 cursor.execute("GRANT ALL ON DATABASE %s TO %s"%(dsn.parsed["dbname"],
287 adminProfile.user))
288 conn.commit()
289
290
291 def _getServerScriptPath(conn):
292 """returns the path where a local postgres server would store its
293 contrib scripts.
294
295 This is probably Debian specific. It's used by the the extension
296 script upload.
297 """
298 from gavo.base import sqlsupport
299 version = ".".join(str(n) for n in sqlsupport.getPgVersion())
300 name = "/usr/share/postgresql/%s/contrib"%version
301 if os.path.isdir(name):
302 return name
303 name = "/usr/share/postgresql/contrib"
304 # Try others here? Which?
305 return name
306
307
308 def _readDBScript(conn, scriptPath, sourceName, procName):
309 """tries to execute the sql script in scriptPath within conn.
310
311 sourceName is some user-targeted indicator what package the script
312 comes from, procName the name of a procedure left by the script
313 so we don't run the script again when it's already run.
314 """
315 if not os.path.exists(scriptPath):
316 warnings.warn("SQL script file for %s not found. There are many"
317 " reasons why that may be ok, but unless you know what you are"
318 " doing, you probably should install the corresponding postgres"
319 " extension."%scriptPath)
320 from gavo.rscdef import scripting
321
322 cursor = conn.cursor()
323 if _execDB(conn, "SELECT * FROM pg_proc WHERE proname=%(procName)s",
324 {"procName": procName}):
325 # script has already run
326 return
327
328 try:
329 for statement in scripting.getSQLScriptGrammar().parseString(
330 open(scriptPath).read()):
331 cursor.execute(statement)
332 except:
333 conn.rollback()
334 warnings.warn("SQL script file %s failed. Try running manually"
335 " using psql. While it hasn't run, the %s extension is not"
336 " available."%(scriptPath, sourceName))
337 else:
338 conn.commit()
339
340
341 def _loadPgExtension(conn, extName):
342 """tries to create the extension extName.
343
344 This is for new-style extensions (e.g., pgsphere starting from 1.1.1.7)
345 that don't have a load script any more.
346
347 It returns True if the extension was found (and has created it as a
348 side effect).
349 """
350 res = _execDB(conn, "SELECT default_version, installed_version"
351 " FROM pg_available_extensions"
352 " WHERE name=%(name)s", {"name": extName})
353 if not res:
354 # The extension is not available at all; let's hope we can limp on.
355 return False
356
357 if res[0][1] is not None:
358 # there is an installed version. Leave it as is for now
359 # (is it worth annoying the user with nagging for updates if
360 # there's a new version? Perhaps, but will they read it? So, for now:
361 return True
362
363 cursor = conn.cursor()
364 cursor.execute("CREATE EXTENSION "+extName)
365 cursor.close()
366 return True
367
368
369 def _doLocalSetup(dsn):
370 # When adding stuff here, fix docs/install.rstx, "Owner-only db setup"
371 from gavo.base import config
372 feedProfile = config.getDBProfile("feed")
373
374 conn = psycopg2.connect(dsn.full)
375 for statement in [
376 # gavoadmin/feed can create public functions and similar; perhaps
377 # we need to think again if we should put them somewhere else.
378 # cf. https://www.postgresql.org/docs/15/ddl-schemas.html#DDL-SCHEMAS-PATTERNS
379 f"GRANT ALL ON SCHEMA public TO {feedProfile.user}",
380 f"ALTER ROLE {feedProfile.user} CREATEROLE",
381 "CREATE OR REPLACE LANGUAGE plpgsql"]:
382 cursor = conn.cursor()
383 try:
384 cursor.execute(statement)
385 except psycopg2.DatabaseError as msg:
386 warnings.warn("SQL statement '%s' failed (%s); continuing."%(
387 statement, msg))
388 conn.rollback()
389 else:
390 conn.commit()
391
392
393 def _readDBScripts(dsn):
394 """loads definitions of pgsphere, q3c and similar into the DB.
395
396 This only works for local installations, and the script location
397 is more or less hardcoded (Debian and SuSE work, at least).
398 """
399 conn = psycopg2.connect(dsn.full)
400 scriptPath = _getServerScriptPath(conn)
401 for extScript, pkgName, procName, extName in [
402 ("pg_sphere.sql", "pgSphere", "spoint_in", "pg_sphere"),
403 ("q3c.sql", "q3c", "q3c_ang2ipix", "q3c")]:
404 # first try new-style extension, then fall back to running scripts
405 if not _loadPgExtension(conn, extName):
406 _readDBScript(conn,
407 os.path.join(scriptPath, extScript),
408 pkgName,
409 procName)
410 conn.commit()
411
412
413 def _importBasicResources():
414 from gavo import rsc
415 from gavo.rscdef import common
416 from gavo.user import importing
417
418 # see rscdef.common for info on the _BOOTSTRAPPING hack.
419 common._BOOTSTRAPPING = True
420 for rdId in ["//dc_tables", "//services", "//users",
421 "//uws", "//adql", "//tap", "//products",
422 "//datalink"]:
423 print(f"({rdId})", end=" ", flush=True)
424 base.ui.notifyInfo("Importing %s"%rdId)
425 importing.process(rsc.getParseOptions(), [rdId])
426 print()
427 common._BOOTSTRAPPING = False
428
429
430 def initDB(dsn):
431 """creates users and tables expected by DaCHS in the database described
432 by the DSN dsn.
433
434 Connecting with dsn must give you superuser privileges.
435 """
436 _createRoles(dsn)
437 _doLocalSetup(dsn)
438 _readDBScripts(dsn)
439
440 from gavo.base import sqlsupport
441 sqlsupport.initPsycopg()
442 _importBasicResources()
443
444
445 def parseCommandLine():
446 import argparse
447 parser = argparse.ArgumentParser(description="Create or update DaCHS'"
448 " file system and database environment.")
449 parser.add_argument("-d", "--dsn", help="DSN to use to connect to"
450 " the future DaCHS database. The DSN must let DaCHS connect"
451 " to the DB as an administrator. dbname, host, and port"
452 " get copied to the profile, if given. The DSN looks roughly like"
453 ' "host=foo.bar user=admin password=secret dbname=gavo".'
454 ' If you followed the'
455 " installation instructions, you don't need this option.",
456 action="store", type=str, dest="dsn", default="gavo")
457 parser.add_argument("--nodb", help="Inhibit initialization of the"
458 " database (you may want to use this when refreshing the file system"
459 " hierarchy)", action="store_false", dest="initDB")
460 parser.add_argument("--debug", help="Dump a traceback when init"
461 "fails", action="store_true", dest="showTB")
462
463 return parser.parse_args()
464
465
466 def main():
467 """initializes the DaCHS environment (where that's not already done).
468 """
469 # do all error handling here; you cannot rely on the rest of DaCHS
470 # when init hasn't run.
471 try:
472 opts = parseCommandLine()
473 dsn = DSN(opts.dsn)
474 createFSHierarchy(dsn)
475 if opts.initDB:
476 initDB(dsn)
477 except Exception as exc:
478 sys.stderr.write(f"*** DaCHS init failed: {exc}.\n")
479 if opts.showTB:
480 import traceback; traceback.print_exc()
481 else:
482 sys.stderr.write("Pass --debug for a traceback.\n")