~nova-coresec/nova/bexar-translations

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

"""
Twisted daemon helpers, specifically to parse out gFlags from twisted flags,
manage pid files and support syslogging.
"""

import gflags
import os
import signal
import sys
import time
from twisted.scripts import twistd
from twisted.python import log
from twisted.python import reflect
from twisted.python import runtime
from twisted.python import usage

from nova import flags
from nova import log as logging


if runtime.platformType == "win32":
    from twisted.scripts._twistw import ServerOptions
else:
    from twisted.scripts._twistd_unix import ServerOptions


FLAGS = flags.FLAGS
flags.DEFINE_string('logdir', None, 'directory to keep log files in '
                                     '(will be prepended to $logfile)')


class TwistdServerOptions(ServerOptions):
    def parseArgs(self, *args):
        return


class FlagParser(object):
    # this is a required attribute for gflags
    syntactic_help = ''

    def __init__(self, parser):
        self.parser = parser

    def Parse(self, s):
        return self.parser(s)


def WrapTwistedOptions(wrapped):
    class TwistedOptionsToFlags(wrapped):
        subCommands = None

        def __init__(self):
            # NOTE(termie): _data exists because Twisted stuff expects
            #               to be able to set arbitrary things that are
            #               not actual flags
            self._data = {}
            self._flagHandlers = {}
            self._paramHandlers = {}

            # Absorb the twistd flags into our FLAGS
            self._absorbFlags()
            self._absorbParameters()
            self._absorbHandlers()

            super(TwistedOptionsToFlags, self).__init__()

        def _absorbFlags(self):
            twistd_flags = []
            reflect.accumulateClassList(self.__class__, 'optFlags',
                                        twistd_flags)
            for flag in twistd_flags:
                key = flag[0].replace('-', '_')
                if hasattr(FLAGS, key):
                    continue
                flags.DEFINE_boolean(key, None, str(flag[-1]))

        def _absorbParameters(self):
            twistd_params = []
            reflect.accumulateClassList(self.__class__, 'optParameters',
                                        twistd_params)
            for param in twistd_params:
                key = param[0].replace('-', '_')
                if hasattr(FLAGS, key):
                    continue
                if len(param) > 4:
                    flags.DEFINE(FlagParser(param[4]),
                                 key, param[2], str(param[3]),
                                 serializer=gflags.ArgumentSerializer())
                else:
                    flags.DEFINE_string(key, param[2], str(param[3]))

        def _absorbHandlers(self):
            twistd_handlers = {}
            reflect.addMethodNamesToDict(self.__class__, twistd_handlers,
                                         "opt_")

            # NOTE(termie): Much of the following is derived/copied from
            #               twisted.python.usage with the express purpose of
            #               providing compatibility
            for name in twistd_handlers.keys():
                method = getattr(self, 'opt_' + name)

                takesArg = not usage.flagFunction(method, name)
                doc = getattr(method, '__doc__', None)
                if not doc:
                    doc = 'undocumented'

                if not takesArg:
                    if name not in FLAGS:
                        flags.DEFINE_boolean(name, None, doc)
                    self._flagHandlers[name] = method
                else:
                    if name not in FLAGS:
                        flags.DEFINE_string(name, None, doc)
                    self._paramHandlers[name] = method

        def _doHandlers(self):
            for flag, handler in self._flagHandlers.iteritems():
                if self[flag]:
                    handler()
            for param, handler in self._paramHandlers.iteritems():
                if self[param] is not None:
                    handler(self[param])

        def __str__(self):
            return str(FLAGS)

        def parseOptions(self, options=None):
            if options is None:
                options = sys.argv
            else:
                options.insert(0, '')

            args = FLAGS(options)
            argv = args[1:]
            # ignore subcommands

            try:
                self.parseArgs(*argv)
            except TypeError:
                raise usage.UsageError(_("Wrong number of arguments."))

            self.postOptions()
            return args

        def parseArgs(self, *args):
            # TODO(termie): figure out a decent way of dealing with args
            #return
            super(TwistedOptionsToFlags, self).parseArgs(*args)

        def postOptions(self):
            self._doHandlers()

            super(TwistedOptionsToFlags, self).postOptions()

        def __getitem__(self, key):
            key = key.replace('-', '_')
            try:
                return getattr(FLAGS, key)
            except (AttributeError, KeyError):
                return self._data[key]

        def __setitem__(self, key, value):
            key = key.replace('-', '_')
            try:
                return setattr(FLAGS, key, value)
            except (AttributeError, KeyError):
                self._data[key] = value

        def get(self, key, default):
            key = key.replace('-', '_')
            try:
                return getattr(FLAGS, key)
            except (AttributeError, KeyError):
                self._data.get(key, default)

    return TwistedOptionsToFlags


def stop(pidfile):
    """
    Stop the daemon
    """
    # Get the pid from the pidfile
    try:
        pf = file(pidfile, 'r')
        pid = int(pf.read().strip())
        pf.close()
    except IOError:
        pid = None

    if not pid:
        message = _("pidfile %s does not exist. Daemon not running?\n")
        sys.stderr.write(message % pidfile)
        # Not an error in a restart
        return

    # Try killing the daemon process
    try:
        while 1:
            os.kill(pid, signal.SIGKILL)
            time.sleep(0.1)
    except OSError, err:
        err = str(err)
        if err.find(_("No such process")) > 0:
            if os.path.exists(pidfile):
                os.remove(pidfile)
        else:
            print str(err)
            sys.exit(1)


def serve(filename):
    logging.debug(_("Serving %s") % filename)
    name = os.path.basename(filename)
    OptionsClass = WrapTwistedOptions(TwistdServerOptions)
    options = OptionsClass()
    argv = options.parseOptions()
    FLAGS.python = filename
    FLAGS.no_save = True
    if not FLAGS.pidfile:
        FLAGS.pidfile = '%s.pid' % name
    elif FLAGS.pidfile.endswith('twistd.pid'):
        FLAGS.pidfile = FLAGS.pidfile.replace('twistd.pid', '%s.pid' % name)
    if not FLAGS.prefix:
        FLAGS.prefix = name
    elif FLAGS.prefix.endswith('twisted'):
        FLAGS.prefix = FLAGS.prefix.replace('twisted', name)

    action = 'start'
    if len(argv) > 1:
        action = argv.pop()

    if action == 'stop':
        stop(FLAGS.pidfile)
        sys.exit()
    elif action == 'restart':
        stop(FLAGS.pidfile)
    elif action == 'start':
        pass
    else:
        print 'usage: %s [options] [start|stop|restart]' % argv[0]
        sys.exit(1)

    logging.basicConfig()
    logging.debug(_("Full set of FLAGS:"))
    for flag in FLAGS:
        logging.debug("%s : %s" % (flag, FLAGS.get(flag, None)))

    logging.audit(_("Starting %s"), name)
    twistd.runApp(options)