]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/scripts/startstop_node.py
45b7fd11233753ebca334342f9c2ae1011625d64
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / scripts / startstop_node.py
1
2 import os, sys, signal, time
3 from allmydata.scripts.common import BasedirOptions
4 from twisted.scripts import twistd
5 from twisted.python import usage
6 from allmydata.util import fileutil
7 from allmydata.util.encodingutil import listdir_unicode, quote_local_unicode_path
8
9
10 class StartOptions(BasedirOptions):
11     subcommand_name = "start"
12
13     def parseArgs(self, basedir=None, *twistd_args):
14         # This can't handle e.g. 'tahoe start --nodaemon', since '--nodaemon'
15         # looks like an option to the tahoe subcommand, not to twistd.
16         # So you can either use 'tahoe start' or 'tahoe start NODEDIR --TWISTD-OPTIONS'.
17         # Note that 'tahoe --node-directory=NODEDIR start --TWISTD-OPTIONS' also
18         # isn't allowed, unfortunately.
19
20         BasedirOptions.parseArgs(self, basedir)
21         self.twistd_args = twistd_args
22
23     def getSynopsis(self):
24         return "Usage:  %s [global-opts] %s [options] [NODEDIR [twistd-options]]" % (self.command_name, self.subcommand_name)
25
26     def getUsage(self, width=None):
27         t = BasedirOptions.getUsage(self, width) + "\n"
28         twistd_options = str(MyTwistdConfig()).partition("\n")[2].partition("\n\n")[0]
29         t += twistd_options.replace("Options:", "twistd-options:", 1)
30         t += """
31
32 Note that if any twistd-options are used, NODEDIR must be specified explicitly
33 (not by default or using -C/--basedir or -d/--node-directory), and followed by
34 the twistd-options.
35 """
36         return t
37
38 class StopOptions(BasedirOptions):
39     def parseArgs(self, basedir=None):
40         BasedirOptions.parseArgs(self, basedir)
41
42     def getSynopsis(self):
43         return "Usage:  %s [global-opts] stop [options] [NODEDIR]" % (self.command_name,)
44
45 class RestartOptions(StartOptions):
46     subcommand_name = "restart"
47
48 class RunOptions(StartOptions):
49     subcommand_name = "run"
50
51
52 class MyTwistdConfig(twistd.ServerOptions):
53     subCommands = [("StartTahoeNode", None, usage.Options, "node")]
54
55 class StartTahoeNodePlugin:
56     tapname = "tahoenode"
57     def __init__(self, nodetype, basedir):
58         self.nodetype = nodetype
59         self.basedir = basedir
60     def makeService(self, so):
61         # delay this import as late as possible, to allow twistd's code to
62         # accept --reactor= selection. N.B.: this can't actually work until
63         # this file, and all the __init__.py files above it, also respect the
64         # prohibition on importing anything that transitively imports
65         # twisted.internet.reactor . That will take a lot of work.
66         if self.nodetype == "client":
67             from allmydata.client import Client
68             return Client(self.basedir)
69         if self.nodetype == "introducer":
70             from allmydata.introducer.server import IntroducerNode
71             return IntroducerNode(self.basedir)
72         if self.nodetype == "key-generator":
73             from allmydata.key_generator import KeyGeneratorService
74             return KeyGeneratorService(default_key_size=2048)
75         if self.nodetype == "stats-gatherer":
76             from allmydata.stats import StatsGathererService
77             return StatsGathererService(verbose=True)
78         raise ValueError("unknown nodetype %s" % self.nodetype)
79
80 def identify_node_type(basedir):
81     for fn in listdir_unicode(basedir):
82         if fn.endswith(u".tac"):
83             tac = str(fn)
84             break
85     else:
86         return None
87
88     for t in ("client", "introducer", "key-generator", "stats-gatherer"):
89         if t in tac:
90             return t
91     return None
92
93 def start(config, out=sys.stdout, err=sys.stderr):
94     basedir = config['basedir']
95     quoted_basedir = quote_local_unicode_path(basedir)
96     print >>out, "STARTING", quoted_basedir
97     if not os.path.isdir(basedir):
98         print >>err, "%s does not look like a directory at all" % quoted_basedir
99         return 1
100     nodetype = identify_node_type(basedir)
101     if not nodetype:
102         print >>err, "%s is not a recognizable node directory" % quoted_basedir
103         return 1
104     # Now prepare to turn into a twistd process. This os.chdir is the point
105     # of no return.
106     os.chdir(basedir)
107     twistd_args = []
108     if (nodetype in ("client", "introducer")
109         and "--nodaemon" not in config.twistd_args
110         and "--syslog" not in config.twistd_args
111         and "--logfile" not in config.twistd_args):
112         fileutil.make_dirs(os.path.join(basedir, u"logs"))
113         twistd_args.extend(["--logfile", os.path.join("logs", "twistd.log")])
114     twistd_args.extend(config.twistd_args)
115     twistd_args.append("StartTahoeNode") # point at our StartTahoeNodePlugin
116
117     twistd_config = MyTwistdConfig()
118     try:
119         twistd_config.parseOptions(twistd_args)
120     except usage.error, ue:
121         # these arguments were unsuitable for 'twistd'
122         print >>err, config
123         print >>err, "tahoe %s: usage error from twistd: %s\n" % (config.subcommand_name, ue)
124         return 1
125     twistd_config.loadedPlugins = {"StartTahoeNode": StartTahoeNodePlugin(nodetype, basedir)}
126
127     # On Unix-like platforms:
128     #   Unless --nodaemon was provided, the twistd.runApp() below spawns off a
129     #   child process, and the parent calls os._exit(0), so there's no way for
130     #   us to get control afterwards, even with 'except SystemExit'. If
131     #   application setup fails (e.g. ImportError), runApp() will raise an
132     #   exception.
133     #
134     #   So if we wanted to do anything with the running child, we'd have two
135     #   options:
136     #
137     #    * fork first, and have our child wait for the runApp() child to get
138     #      running. (note: just fork(). This is easier than fork+exec, since we
139     #      don't have to get PATH and PYTHONPATH set up, since we're not
140     #      starting a *different* process, just cloning a new instance of the
141     #      current process)
142     #    * or have the user run a separate command some time after this one
143     #      exits.
144     #
145     #   For Tahoe, we don't need to do anything with the child, so we can just
146     #   let it exit.
147     #
148     # On Windows:
149     #   twistd does not fork; it just runs in the current process whether or not
150     #   --nodaemon is specified. (As on Unix, --nodaemon does have the side effect
151     #   of causing us to log to stdout/stderr.)
152
153     if "--nodaemon" in twistd_args or sys.platform == "win32":
154         verb = "running"
155     else:
156         verb = "starting"
157
158     print >>out, "%s node in %s" % (verb, quoted_basedir)
159     twistd.runApp(twistd_config)
160     # we should only reach here if --nodaemon or equivalent was used
161     return 0
162
163 def stop(config, out=sys.stdout, err=sys.stderr):
164     basedir = config['basedir']
165     quoted_basedir = quote_local_unicode_path(basedir)
166     print >>out, "STOPPING", quoted_basedir
167     pidfile = os.path.join(basedir, u"twistd.pid")
168     if not os.path.exists(pidfile):
169         print >>err, "%s does not look like a running node directory (no twistd.pid)" % quoted_basedir
170         # we define rc=2 to mean "nothing is running, but it wasn't me who
171         # stopped it"
172         return 2
173     pid = open(pidfile, "r").read()
174     pid = int(pid)
175
176     # kill it hard (SIGKILL), delete the twistd.pid file, then wait for the
177     # process itself to go away. If it hasn't gone away after 20 seconds, warn
178     # the user but keep waiting until they give up.
179     try:
180         os.kill(pid, signal.SIGKILL)
181     except OSError, oserr:
182         if oserr.errno == 3:
183             print oserr.strerror
184             # the process didn't exist, so wipe the pid file
185             os.remove(pidfile)
186             return 2
187         else:
188             raise
189     try:
190         os.remove(pidfile)
191     except EnvironmentError:
192         pass
193     start = time.time()
194     time.sleep(0.1)
195     wait = 40
196     first_time = True
197     while True:
198         # poll once per second until we see the process is no longer running
199         try:
200             os.kill(pid, 0)
201         except OSError:
202             print >>out, "process %d is dead" % pid
203             return
204         wait -= 1
205         if wait < 0:
206             if first_time:
207                 print >>err, ("It looks like pid %d is still running "
208                               "after %d seconds" % (pid,
209                                                     (time.time() - start)))
210                 print >>err, "I will keep watching it until you interrupt me."
211                 wait = 10
212                 first_time = False
213             else:
214                 print >>err, "pid %d still running after %d seconds" % \
215                       (pid, (time.time() - start))
216                 wait = 10
217         time.sleep(1)
218     # we define rc=1 to mean "I think something is still running, sorry"
219     return 1
220
221 def restart(config, stdout, stderr):
222     rc = stop(config, stdout, stderr)
223     if rc == 2:
224         print >>stderr, "ignoring couldn't-stop"
225         rc = 0
226     if rc:
227         print >>stderr, "not restarting"
228         return rc
229     return start(config, stdout, stderr)
230
231 def run(config, stdout, stderr):
232     config.twistd_args = config.twistd_args + ("--nodaemon",)
233     # Previously we would do the equivalent of adding ("--logfile", "tahoesvc.log"),
234     # but that redirects stdout/stderr which is often unhelpful, and the user can
235     # add that option explicitly if they want.
236
237     return start(config, stdout, stderr)
238
239
240 subCommands = [
241     ["start", None, StartOptions, "Start a node (of any type)."],
242     ["stop", None, StopOptions, "Stop a node."],
243     ["restart", None, RestartOptions, "Restart a node."],
244     ["run", None, RunOptions, "Run a node synchronously."],
245 ]
246
247 dispatch = {
248     "start": start,
249     "stop": stop,
250     "restart": restart,
251     "run": run,
252     }