Debian Codegraph @

cylc/flow/daemonize.py

raw
1 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
2 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 """Turn a cylc scheduler into a Unix daemon."""
18
19 import atexit
20 import json
21 import os
22 import sys
23 from time import sleep, time
24
25 from cylc.flow.pathutil import get_workflow_run_scheduler_log_path
26
27 WORKFLOW_INFO_TMPL = (
28 "%(workflow)s: %(host)s PID=%(pid)s\n"
29 )
30
31 _TIMEOUT = 300.0 # 5 minutes
32
33
34 def daemonize(schd):
35 """Turn a cylc scheduler into a Unix daemon.
36
37 Do the UNIX double-fork magic, see Stevens' "Advanced Programming in the
38 UNIX Environment" for details (ISBN 0201563177)
39
40 ATTRIBUTION: base on a public domain code recipe by Jurgen Hermann:
41 http://code.activestate.com/recipes/66012-fork-a-daemon-process-on-unix/
42
43 """
44 logfname = get_workflow_run_scheduler_log_path(schd.workflow)
45 try:
46 old_log_mtime = os.stat(logfname).st_mtime
47 except OSError:
48 old_log_mtime = None
49 # fork 1
50 try:
51 pid = os.fork()
52 if pid > 0:
53 # Poll for workflow log to be populated
54 workflow_pid = None
55 workflow_url = None
56 pub_url = None
57 timeout = time() + _TIMEOUT
58 while time() <= timeout and (
59 workflow_pid is None or
60 workflow_url is None or
61 pub_url is None):
62 sleep(0.1)
63 try:
64 # First INFO line of workflow log should contain
65 # start up message, URL and PID. Format is:
66 # LOG-PREFIX Workflow schd program: url=URL, pid=PID
67 # Otherwise, something is wrong, print the workflow log
68 # and exit with an error.
69 log_stat = os.stat(logfname)
70 if (log_stat.st_mtime == old_log_mtime or
71 log_stat.st_size == 0):
72 continue
73 with open(logfname, 'r') as logfile:
74 for line in logfile:
75 if schd.START_MESSAGE_PREFIX in line:
76 workflow_url, workflow_pid = (
77 item.rsplit("=", 1)[-1]
78 for item in line.rsplit()[-2:])
79 if schd.START_PUB_MESSAGE_PREFIX in line:
80 pub_url = line.rsplit("=", 1)[-1].rstrip()
81 if workflow_url and pub_url:
82 break
83 elif ' ERROR -' in line or ' CRITICAL -' in line:
84 # ERROR and CRITICAL before workflow starts
85 try:
86 with open(logfname, 'r') as logfile2:
87 sys.stderr.write(logfile2.read())
88 sys.exit(1)
89 except IOError:
90 sys.exit("Workflow schd program exited")
91 except (OSError, ValueError):
92 pass
93 if workflow_pid is None or workflow_url is None:
94 sys.exit("Workflow not started after %ds" % _TIMEOUT)
95 # Print workflow information
96 info = {
97 "workflow": schd.workflow,
98 "host": schd.host,
99 "url": workflow_url,
100 "pub_url": pub_url,
101 "pid": workflow_pid
102 }
103 if schd.options.format == 'json':
104 sys.stdout.write(json.dumps(info, indent=4))
105 else:
106 sys.stdout.write(WORKFLOW_INFO_TMPL % info)
107 # exit parent 1
108 sys.exit(0)
109 except OSError as exc:
110 sys.exit("fork #1 failed: %d (%s)\n" % (exc.errno, exc.strerror))
111
112 # decouple from parent environment
113 os.chdir("/")
114 os.setsid()
115 os.umask(0)
116
117 # fork 2
118 try:
119 pid = os.fork()
120 if pid > 0:
121 # exit parent 2
122 sys.exit(0)
123 except OSError as exc:
124 sys.exit("fork #2 failed: %d (%s)\n" % (exc.errno, exc.strerror))
125
126 # reset umask, octal
127 os.umask(0o22)
128
129 # Redirect /dev/null to stdin.
130 # Note that simply reassigning the sys streams is not sufficient
131 # if we import modules that write to stdin and stdout from C
132 # code - evidently the subprocess module is in this category!
133 dvnl = open(os.devnull, 'r') # noqa: SIM115 (keep devnull open until exit)
134 os.dup2(dvnl.fileno(), sys.stdin.fileno())
135 atexit.register(dvnl.close)