Debian Codegraph @

gavo/user/serve.py

raw
1 """
2 A wrapper script suitable for starting the server.
3 """
4
5 #c Copyright 2008-2025, the GAVO project <[email protected]>
6 #c
7 #c This program is free software, covered by the GNU GPL. See the
8 #c COPYING file in the source distribution.
9
10
11 import datetime
12 import grp
13 import os
14 import pwd
15 import resource
16 import signal
17 import subprocess
18 import sys
19 import time
20 import urllib.parse
21 import warnings
22
23 from twisted.internet import reactor
24 from twisted.internet import task
25 from twisted.internet import threads
26 from twisted.internet.error import CannotListenError
27 from twisted.python import log
28 from twisted.python import logfile
29 from twisted.web import resource as twresource
30
31 from gavo import base
32 from gavo import rscdesc #noflake: for cache registration
33 from gavo import registry
34 from gavo import utils
35 from gavo.base import config
36 from gavo.base import cron
37 from gavo.user import plainui
38 from gavo.utils import exposedFunction, makeCLIParser, Arg
39 from gavo.web import root
40
41
42 def onSystemd():
43 """returns true if it's likely that our init is a systemd.
44 """
45 return os.path.realpath("/sbin/init").endswith("systemd")
46
47
48 def setupServer(rootPage, runIntervalJobs=True):
49 """sets the process up for running a server.
50
51 This involves managing server resource limits, doing a notification,
52 and, in particular, starting up the scheduler.
53
54 runIntervalJobs can be set to False to suppress running jobs
55 that are probably maintenance jobs on a running instance and
56 which would be unwelcome on debug instances.
57 """
58 manageResourceLimits()
59 base.setGlobalMeta("upSince", utils.formatISODT(datetime.datetime.utcnow()))
60 base.ui.notifyWebServerUp()
61
62 if not runIntervalJobs:
63 # we don't want most periodic stuff to happen when in debug mode, since
64 # it usually will involve fetching or importing things, and it's at
65 # best going to be confusing. However, stuff that is supposed to
66 # run immediately at startup should run (e.g., cleaning up the TAP
67 # table). Define a cron.isCensored function to make that happen --
68 # note that this is too late to prevent the backup job from
69 # //services -- but that is a no-op unless configured.
70 def isCensored(job):
71 if isinstance(job, cron.TimedJob) or job.interval>=60:
72 return True
73 return False
74 cron.isCensored = isCensored
75
76 cron.registerScheduleFunction(_Scheduler.scheduleJob)
77
78
79 class _PIDManager(object):
80 """A manager for the PID of the server.
81
82 There's a single instance of this below.
83 """
84 def __init__(self):
85 self.path = base.getConfig("stateDir") / "web.pid"
86
87 def getPID(self):
88 """returns the PID of the currently running server, or None.
89 """
90 try:
91 with self.path.open() as f:
92 pidString = f.readline()
93 except IOError: # PID file does not exist (or we're beyond repair)
94 return None
95 try:
96 return int(pidString)
97 except ValueError: # junk in PID file -- no sense in keeping it
98 base.ui.notifyWarning("%s contained garbage, attempting to unlink"%
99 self.path)
100 self.clearPID()
101
102 def setPID(self):
103 """writes the current process' PID to the PID file.
104
105 Any existing content will be clobbered; thus, you could have
106 races here (and since both daemons would bind to the same socket,
107 only one would survive, possibly the wrong one). Let's just stipulate
108 people won't start two competing daemons.
109 """
110 try:
111 with self.path.open("w") as f:
112 f.write(str(os.getpid()))
113 except IOError: # Cannot write PID. This would suggest that much else
114 # is broken as well, so we bail out
115 base.ui.notifyError("Cannot write PID file %s. Assuming all is"
116 " broken, bailing out."%self.path)
117 sys.exit(1)
118
119 def clearPID(self):
120 """removes the PID file.
121 """
122 try:
123 self.path.unlink()
124 except os.error as ex:
125 if ex.errno==2: # ENOENT, we don't have to do anything
126 pass
127 else:
128 base.ui.notifyError("Cannot remove PID file %s (%s). This"
129 " probably means some other server owns it now."%(
130 self.file, str(ex)))
131
132
133 PIDManager = _PIDManager()
134
135
136 def _reloadConfig():
137 """should clear as many caches as we can get hold of.
138 """
139 base.caches.clearCaches()
140 from gavo.rscdef.common import getIvoidsForRDId
141 getIvoidsForRDId.cache_clear()
142
143 root.loadUserVanity(root.ArchiveService)
144 config.makeFallbackMeta(reload=True)
145 config.loadConfig()
146
147 base.ui.notifyInfo("Cleared caches on SIGHUP")
148
149
150 def manageResourceLimits():
151 """raises some resource limits to their hard limits.
152
153 This is, in particular, the number of open FDs, as DaCHS may need a
154 lot of those.
155 """
156 try:
157 configuredLimit = base.getConfig("web", "serverFDLimit")
158 resource.setrlimit(resource.RLIMIT_NOFILE,
159 (configuredLimit, configuredLimit))
160 _, hard = resource.getrlimit(resource.RLIMIT_CORE)
161 resource.setrlimit(resource.RLIMIT_CORE, (hard, hard))
162
163 # for an actual coredump in production systems (which setuid)
164 # you will usually also need
165 # echo 2 >/proc/sys/fs/suid_dumpable
166 # and this (needs python3-prctl installed):
167 # import prctl; prctl.set_dumpable(1)
168
169 except (ValueError, resource.error):
170 # it's perfectly legal to call this as an unprivileged user, so
171 # we won't complain here.
172 pass
173
174 hardLimit = resource.getrlimit(resource.RLIMIT_NOFILE)[-1]
175 resource.setrlimit(resource.RLIMIT_NOFILE, (hardLimit, hardLimit))
176 base.ui.notifyInfo("Current limits on file descriptors: %s"%
177 repr(resource.getrlimit(resource.RLIMIT_NOFILE)))
178
179
180 def _dropPrivileges():
181 uid = None
182 user = base.getConfig("web", "user")
183 if user and os.getuid()==0:
184 try:
185 uid = pwd.getpwnam(user)[2]
186 except KeyError:
187 base.ui.notifyError("Cannot change to user %s (not found)\n"%user)
188 sys.exit(1)
189 try:
190 try:
191 os.setgid(grp.getgrnam(base.getConfig("group"))[2])
192 except Exception as ex:
193 # don't fail because of setgid failure (should I rather?)
194 warnings.warn("Could not sgid to gavo group (%s)."%(str(ex)))
195 os.setuid(uid)
196 except os.error as ex:
197 base.ui.notifyError("Cannot change to user %s (%s)\n"%(
198 user, str(ex)))
199
200 try:
201 # see develNotes.rstx on the following thing
202 import prctl
203 prctl.set_dumpable(True)
204 except ImportError:
205 # no prctl, no dumps; that ought to be fine
206 pass
207
208
209 def daemonize(logFile, callable):
210 # We translate TERMs to INTs to ensure finally: code is executed
211 signal.signal(signal.SIGTERM,
212 lambda a,b: os.kill(os.getpid(), signal.SIGINT))
213 pid = os.fork()
214 if pid == 0:
215 os.setsid()
216 pid = os.fork()
217 if pid==0:
218 os.close(0)
219 os.close(1)
220 os.close(2)
221 os.dup(logFile.fileno())
222 os.dup(logFile.fileno())
223 os.dup(logFile.fileno())
224 callable()
225 else:
226 os._exit(0)
227 else:
228 os._exit(0)
229
230
231 def _configureTwistedLog(additionalLog=None):
232 """sets up the destination of the twisted web.log.
233
234 additionalLog can be a file to write to in addition to web.log. No
235 rotation will take place on that.
236
237 Note that dcErrors and dcInfos are set up in user.logui.
238 """
239 # create the file with the right permissions before passing it on
240 logFile = getLogFile("web.log")
241 logPath = logFile.name
242 logFile.close()
243
244 theLog = logfile.LogFile(
245 os.path.basename(logPath),
246 os.path.dirname(logPath))
247
248 log.startLogging(theLog, setStdout=False)
249 def rotator():
250 theLog.shouldRotate()
251 reactor.callLater(86400, rotator)
252 rotator()
253
254 if additionalLog is not None:
255 from twisted.logger import globalLogPublisher, textFileLogObserver
256 observer = textFileLogObserver(additionalLog)
257 globalLogPublisher.addObserver(observer)
258
259
260
261 def getLogFile(baseName):
262 """returns a log file group-writable by gavo.
263 """
264 fName = base.getConfig("logDir") / baseName
265 f = open(fName, "a")
266 try:
267 os.chmod(fName, 0o664)
268 os.chown(fName, -1, grp.getgrnam(base.getConfig("gavoGroup"))[2])
269 except (KeyError, os.error): # let someone else worry about it
270 pass
271 return f
272
273
274 def _preloadPublishedRDs():
275 """preloads all RDs with published services in them.
276
277 This is mainly a good idea in case of buggy code within the RDs which
278 in this way is executed halfway predictably.
279
280 Note that this function may take a significant amount of time and
281 should not be run within the event loop.
282 """
283 for rdId in registry.findPublishedRDs():
284 base.ui.notifyInfo("Preloading %s"%rdId)
285 try:
286 rscdesc.getRD(rdId)
287 except:
288 base.ui.notifyError("Broken RD preloaded: %s."%rdId)
289 base.ui.notifyInfo("Preloading published RDs finished.")
290
291
292 def _preloadRDs():
293 """accesses the RDs mentioned in [web]preloadRDs, and loads all
294 others it finds if [web]preloadAllRDs is True.
295
296 Errors while loading those are logged but are not fatal to the server.
297
298 This must be run from the reactor if preloadAllRDs is set, as it
299 uses deferreds.
300 """
301 for rdId in base.getConfig("web", "preloadRDs"):
302 base.ui.notifyInfo("Preloading %s"%rdId)
303 try:
304 base.caches.getRD(rdId)
305 except:
306 base.ui.notifyError("Broken RD preloaded: %s."%rdId)
307
308
309 class _Scheduler(object):
310 """An internal singleton (use as a class) housing a twisted base
311 scheduling function for base.cron.
312 """
313 lastDelayedCall = None
314
315 @classmethod
316 def scheduleJob(cls, wakeTime, job):
317 """puts job on the reactor's queue for execution in wakeTime seconds.
318 """
319 if cls.lastDelayedCall is not None and cls.lastDelayedCall.active():
320 cls.lastDelayedCall.cancel()
321
322 cls.lastDelayedCall = reactor.callLater(wakeTime, job)
323
324
325 def _loadCertificate(srcFile):
326 """A temporary stand-in for twisted.ssl.PrivateCertificate.load.
327
328 This is necessary because PrivateCertificate currently ignores intermediate
329 chains in there, and we need these for letsencrypt.
330
331 This is inspired by code by glyph.
332 """
333 from twisted.internet.ssl import Certificate, KeyPair, CertificateOptions
334 from OpenSSL.SSL import FILETYPE_PEM
335
336 # get certificates and keys from source files
337 certs, keys = [], []
338 with open(srcFile) as f:
339 for line in f:
340 if line.startswith("-----BEGIN"):
341 if 'CERTIFICATE' in line:
342 accum = certs
343 else:
344 accum = keys
345 accum.append([])
346 accum[-1].append(line)
347
348 keys = [KeyPair.load("".join(k), FILETYPE_PEM) for k in keys]
349 certs = [Certificate.loadPEM("".join(c)) for c in certs]
350
351 # now build the options from one key, a cert for it, and any number
352 # of other intermediate stuff
353 if len(keys)!=1:
354 raise base.ReportableError("Only one secret key expected in %s"%srcFile)
355 privateFingerprint = keys[0].keyHash()
356
357 # find cert for privateKey by fingerprint, stuff everything else
358 # into the chain.
359 chain, serverCert = [], None
360 for cert in certs:
361 if cert.getPublicKey().keyHash()==privateFingerprint:
362 serverCert = cert
363 else:
364 chain.append(cert)
365
366 if serverCert is None:
367 raise base.ReportableError("No certificate for secret key found in "
368 +srcFile)
369 return CertificateOptions(
370 certificate=serverCert.original,
371 privateKey=keys[0].original,
372 extraCertChain=[c.original for c in chain])
373
374
375 def _perhapsEnableSSL(factory, sslPort=443):
376 """lets the reactor listen to TLS requests, too, if there's a certificate
377 in the right place.
378
379 Actually, what we expect is a PEM that is a concatenation of a certificate
380 and a private key; that thing needs to be in $GAVO_ROOT/hazmat/bundle.pem
381
382 If anything goes wrong here, we're just emitting a diagnostic and don't
383 fail.
384 """
385 certPath = base.getConfig("rootDir") / "hazmat" / "bundle.pem"
386 if not os.path.isfile(certPath):
387 return
388
389 try:
390 reactor.listenSSL(
391 sslPort,
392 factory,
393 _loadCertificate(certPath),
394 interface=base.getConfig("web", "bindAddress"))
395 base.LISTENING_TO_HTTPS = True
396 except Exception as msg:
397 import traceback;traceback.print_exc()
398 log.err("Not turning on TLS because: "+str(msg))
399
400
401 def _startServer(managePID=True):
402 """runs a detached server, dropping privileges and all.
403 """
404 try:
405 reactor.listenTCP(
406 int(base.getConfig("web", "serverPort")),
407 root.site,
408 interface=base.getConfig("web", "bindAddress"))
409 _perhapsEnableSSL(root.site)
410 except CannotListenError:
411 raise base.ReportableError("Someone already listens on the"
412 " configured port %s."%base.getConfig("web", "serverPort"),
413 hint="This could mean that a DaCHS server is already running."
414 " You would have to manually kill it then since its PID file"
415 " got lost somehow. It's more likely that some"
416 " other server is already taking up this port; you may want to change"
417 " the [web] serverPort setting in that case.")
418 os.chdir(base.getConfig("stateDir"))
419 _dropPrivileges()
420 root.site.webLog = _configureTwistedLog()
421
422 if managePID:
423 PIDManager.setPID()
424 try:
425 setupServer(root)
426 signal.signal(signal.SIGHUP, lambda sig, stack:
427 reactor.callLater(0, _reloadConfig))
428 reactor.callLater(1, _preloadRDs)
429 if base.getConfig("web", "preloadpublishedrds"):
430 task.deferLater(reactor,
431 1, threads.deferToThread, _preloadPublishedRDs)
432 reactor.run()
433 finally:
434 if managePID:
435 PIDManager.clearPID()
436
437
438 @exposedFunction([
439 Arg("-f", "--foreground", help="Do not detach. This is a bit like"
440 " serve debug, but still changes user, activates logging, and does"
441 " not put DaCHS into debug mode. Use this in systemd units.",
442 action="store_true", dest="foreground"),],
443 help="start the server (and put it in the"
444 " background by default).",
445 )
446 def start(args):
447 if not getattr(args, "foreground", False):
448 if onSystemd():
449 raise base.ReportableError("Do not use dachs serve start on systemd"
450 " machines. Say ``systemctl start dachs`` instead.")
451
452 oldPID = PIDManager.getPID()
453 if oldPID is not None: # Server could already be running,.. .
454 if os.path.exists(f"/proc/{oldPID}"):
455 # ...if the PID is active, give up right away
456 sys.exit("It seems there's already a server (pid %s) running."
457 " Try 'dachs serve stop'."%(PIDManager.getPID()))
458 else:
459 warnings.warn(
460 "Unclean server shutdown suspected, trying to clean up...")
461 _stopServer()
462
463 # this is called here because we might still be root here and
464 # can raise our hard limits.
465 manageResourceLimits()
466 if getattr(args, "foreground", False):
467 _startServer(managePID=False)
468 else:
469 daemonize(
470 getLogFile("server.stderr"),
471 _startServer)
472
473
474 def _waitForServerExit(timeout=5):
475 """waits for server process to terminate.
476
477 It does so by polling the server pid file.
478 """
479 for i in range(int(timeout*10)):
480 lastPID = PIDManager.getPID()
481 if lastPID is None:
482 break
483 time.sleep(0.1)
484 else:
485 sys.exit("The server with pid %d refuses to die, probably because\n"
486 "pieces of it hang in the python kernel.\n\n"
487 "Try 'kill -KILL %s' to forcefully terminate it (this will break\n"
488 "connections).\n"%(lastPID, lastPID))
489
490
491 def _stopServer():
492 if onSystemd():
493 raise base.ReportableError("Do not use dachs serve stop on systemd"
494 " machines. Say ``systemctl stop dachs`` instead.")
495
496 pid = PIDManager.getPID()
497 if pid is None: # No server running, nothing to do
498 base.ui.notifyWarning("No running DaCHS server found."
499 " If you are trying to restart a DaCHS server on a systemd machine:"
500 " use `sudo systemctl restart dachs` instead.")
501 return
502
503 try:
504 os.kill(pid, signal.SIGTERM)
505 except os.error as ex:
506 if ex.errno==3: # no such process
507 PIDManager.clearPID()
508 base.ui.notifyWarning("Removed stale PID file.")
509 return
510 else:
511 raise
512 _waitForServerExit()
513
514
515 @exposedFunction(help="stop a running server.")
516 def stop(args):
517 _stopServer()
518
519
520 def waitForUnloadedServer(stopTimeout):
521 """delays while the service [web]serverURL appears to serve clients
522 or stopTimeout seconds are over.
523
524 This will also return fine if no server is running. If the service
525 keeps having clients after stopTimeout, a ReportableError is raised.
526 """
527 waitUntil = time.time()+stopTimeout
528 loadURL = base.getConfig("web", "serverURL")+"/clientcount"
529 while time.time()<waitUntil:
530 try:
531 content = utils.urlopenRemote(loadURL).read()
532 if int(content)==0:
533 return
534 except IOError:
535 # let's assume this means "server down" and try to reload it
536 return
537 time.sleep(1)
538
539 raise base.ReportableError("Timeout while waiting for all clients"
540 " to go away. Please restart manually.")
541
542
543 @exposedFunction([Arg("--if-unloaded-within", type=int,
544 dest="stopTimeout", default=None, metavar="SECS",
545 help="Wait SECS seconds until the server seems unloaded before"
546 " stopping it; give up if it doesn't seem to get unloaded.")],
547 help="restart the server")
548 def restart(args):
549 if args.stopTimeout:
550 waitForUnloadedServer(args.stopTimeout)
551 _stopServer()
552 start(args)
553
554
555 @exposedFunction(help="reload server configuration (incomplete)")
556 def reload(args):
557 if onSystemd():
558 raise base.ReportableError("dachs serve reload does"
559 " not work on systemd machines. Use"
560 " ``systemctl restart dachs`` instead.")
561
562 pid = PIDManager.getPID()
563 if pid is None:
564 raise base.ReportableError("No DaCHS server appears to be running."
565 " Thus, not reloading.")
566 os.kill(pid, signal.SIGHUP)
567
568
569 class ExitPage(twresource.Resource):
570 def render(self, request):
571 request.setHeader("content-type", "text/plain")
572 reactor.stop()
573 return b"exiting."
574
575
576 @exposedFunction(help="run a server and remain in the foreground, dumping"
577 " all kinds of stuff to the terminal")
578 def debug(args):
579 root.site.webLog = _configureTwistedLog(sys.stderr)
580 base.DEBUG = True
581 root.root.child_exit = ExitPage()
582 reactor.listenTCP(
583 int(base.getConfig("web", "serverPort")),
584 root.site,
585 interface=base.getConfig("web", "bindAddress"))
586 _perhapsEnableSSL(root.site, 40443)
587 # since we don't support non-443 https, really, fudge this to enable
588 # debugging
589 base.getHTTPSBase = lambda:"https://localhost:40443"
590 setupServer(root, runIntervalJobs=False)
591 reactor.run()
592
593
594 @exposedFunction([
595 Arg("rdIds", help="one or more rdIds", nargs="+"),
596 ], help="reload RDs listed in the server named by [web]serverURL.")
597 def expireRDs(args):
598 pw = base.getConfig("web", "adminpasswd")
599 if pw=='':
600 raise base.ReportableError("expireRDs needs [web]adminpasswd config item.")
601
602 for rdId in args.rdIds:
603 try:
604 f = utils.urlopenRemote(base.makeAbsoluteURL(
605 "/__system__/services/cacheclear?"
606 +urllib.parse.urlencode(
607 {"rdId":rdId, "__nevow_form__": "genForm", "submit": "Go"})),
608 creds=("gavoadmin", pw))
609 ignored = f.read() #noflake: don't care enough to check at this point.
610 except IOError:
611 raise base.ReportableError(
612 f"Failed to reload {rdId} -- have you set the admin password?")
613
614
615 @exposedFunction([], help="Create or renew a letsencrypt certificate"
616 " for hazmat/server.key using hazmat/account.key (this is for https"
617 " operation); you need to run this as a user that can read and write"
618 " hazmat (typically root).")
619 def updateCertificate(args):
620 from gavo.web import ifpages
621 acmeChallengeDir = ifpages.ACMEChallenge.acmeChallengeDir
622
623 os.chdir(base.getConfig("rootDir") / "hazmat")
624
625 # to make a CSR for the host names we're known as, first write an
626 # openssl cfg...
627 names = [urllib.parse.urlparse(config.get("web", "serverURL")).hostname
628 ]+base.getConfig("web", "alternateHostnames")
629 with open("dachs.conf", "wb") as f:
630 f.write(b"[req]\ndefault_bits=4096\n"
631 b"distinguished_name=req_distinguished_name\n")
632 f.write(b"[req_distinguished_name]\ncommonName=%s\n"%
633 names[0].encode("utf-8"))
634 f.write(b"[SAN]\nsubjectAltName=%s\n"%(b",".join(
635 b'DNS:'+s.encode("utf-8") for s in names)))
636
637 # ...and then let openssl write the CSR...
638 subprocess.check_call(["openssl", "req", "-new", "-sha256",
639 "-key", "server.key", "-subj", "/", "-reqexts", "SAN",
640 "-config", "dachs.conf", "-out", "dachs.csr"])
641
642 # I need to prepare a directory for the challenges
643 # first, and I'm creating a directory in a user-writable directory
644 # as (presumably) root. TODO: think hard if that's as bad an idea
645 # as it sounds. Anyway: we'll have to agree on that directory
646 # between the server and this updater, so it's a bit tricky.
647 try:
648 os.mkdir(acmeChallengeDir)
649 os.chmod(acmeChallengeDir, 0o755)
650 except os.error:
651 pass # let's hope the challenge dir is already in place
652
653 # The letsencrypt interaction is done by acme-tiny
654 cert = subprocess.check_output(["acme-tiny",
655 "--account-key", "./account.key", "--csr", "dachs.csr",
656 "--acme-dir", acmeChallengeDir])
657
658 if False:
659 # We used to have to obtain the intermediates manually.
660 # With acme-tiny >4.0 (i.e., at least bookworm, that should
661 # no longer be necessary, and it may indeed be harmful).
662 # I'll keep the code around for a bit anyway.
663 f = utils.urlopenRemote(
664 # This link needs to be updated now and then. If anyone knows a
665 # stable URI for "*the* itermediate certs for LE": tell me.
666 "https://letsencrypt.org/certs/lets-encrypt-r3.pem")
667 intermediate = f.read()
668 else:
669 intermediate = b""
670
671 with open("server.key", "rb") as f:
672 secretKey = f.read()
673
674 with open("bundle.pem", "wb") as f:
675 f.write(cert+b"\n")
676 f.write(intermediate+b"\n")
677 f.write(secretKey+b"\n")
678
679 subprocess.check_call(["dachs", "serve", "restart",
680 "--if-unloaded-within=300"])
681
682
683 def main():
684 plainui.SemiStingyPlainUI(base.ui)
685 base.IS_DACHS_SERVER = True
686 args = makeCLIParser(globals()).parse_args()
687 args.subAction(args)