~0x44/nova/bug838466

1 by Jesse Andrews
initial commit
1
# vim: tabstop=4 shiftwidth=4 softtabstop=4
114 by Devin Carlen
Updated licenses
2
3
# Copyright 2010 United States Government as represented by the
3.1.9 by Vishvananda Ishaya
Removed trailing whitespace from header
4
# Administrator of the National Aeronautics and Space Administration.
114 by Devin Carlen
Updated licenses
5
# All Rights Reserved.
6
#
7
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
8
#    not use this file except in compliance with the License. You may obtain
9
#    a copy of the License at
10
#
11
#         http://www.apache.org/licenses/LICENSE-2.0
12
#
1 by Jesse Andrews
initial commit
13
#    Unless required by applicable law or agreed to in writing, software
114 by Devin Carlen
Updated licenses
14
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16
#    License for the specific language governing permissions and limitations
17
#    under the License.
1 by Jesse Andrews
initial commit
18
19
"""
237.1.91 by Vishvananda Ishaya
reverting accidental search/replace change to server.py
20
Base functionality for nova daemons - gradually being replaced with twistd.py.
1 by Jesse Andrews
initial commit
21
"""
22
237.1.91 by Vishvananda Ishaya
reverting accidental search/replace change to server.py
23
import daemon
24
from daemon import pidlockfile
1 by Jesse Andrews
initial commit
25
import logging
26
import logging.handlers
27
import os
28
import signal
29
import sys
30
import time
31
32
from nova import flags
33
34
35
FLAGS = flags.FLAGS
237.1.91 by Vishvananda Ishaya
reverting accidental search/replace change to server.py
36
flags.DEFINE_bool('daemonize', False, 'daemonize this process')
37
# NOTE(termie): right now I am defaulting to using syslog when we daemonize
1 by Jesse Andrews
initial commit
38
#               it may be better to do something else -shrug-
39
# NOTE(Devin): I think we should let each process have its own log file
40
#              and put it in /var/logs/nova/(appname).log
41
#              This makes debugging much easier and cuts down on sys log
42
#              clutter.
237.1.91 by Vishvananda Ishaya
reverting accidental search/replace change to server.py
43
flags.DEFINE_bool('use_syslog', True, 'output to syslog when daemonizing')
1 by Jesse Andrews
initial commit
44
flags.DEFINE_string('logfile', None, 'log file to output to')
45
flags.DEFINE_string('pidfile', None, 'pid file to output to')
46
flags.DEFINE_string('working_directory', './', 'working directory...')
242.2.1 by Soren Hansen
Use the argument handler specified by twistd, if any.
47
flags.DEFINE_integer('uid', os.getuid(), 'uid under which to run')
48
flags.DEFINE_integer('gid', os.getgid(), 'gid under which to run')
1 by Jesse Andrews
initial commit
49
50
51
def stop(pidfile):
52
    """
237.1.91 by Vishvananda Ishaya
reverting accidental search/replace change to server.py
53
    Stop the daemon
1 by Jesse Andrews
initial commit
54
    """
55
    # Get the pid from the pidfile
56
    try:
212.1.2 by jaypipes at gmail
pylint fixes for nova/server.py
57
        pid = int(open(pidfile,'r').read().strip())
1 by Jesse Andrews
initial commit
58
    except IOError:
237.1.91 by Vishvananda Ishaya
reverting accidental search/replace change to server.py
59
        message = "pidfile %s does not exist. Daemon not running?\n"
1 by Jesse Andrews
initial commit
60
        sys.stderr.write(message % pidfile)
61
        return # not an error in a restart
62
237.1.91 by Vishvananda Ishaya
reverting accidental search/replace change to server.py
63
    # Try killing the daemon process
1 by Jesse Andrews
initial commit
64
    try:
65
        while 1:
66
            os.kill(pid, signal.SIGTERM)
67
            time.sleep(0.1)
68
    except OSError, err:
69
        err = str(err)
70
        if err.find("No such process") > 0:
71
            if os.path.exists(pidfile):
72
                os.remove(pidfile)
73
        else:
74
            print str(err)
75
            sys.exit(1)
76
77
78
def serve(name, main):
212.1.2 by jaypipes at gmail
pylint fixes for nova/server.py
79
    """Controller for server"""
1 by Jesse Andrews
initial commit
80
    argv = FLAGS(sys.argv)
81
82
    if not FLAGS.pidfile:
83
        FLAGS.pidfile = '%s.pid' % name
84
212.1.2 by jaypipes at gmail
pylint fixes for nova/server.py
85
    logging.debug("Full set of FLAGS: \n\n\n")
1 by Jesse Andrews
initial commit
86
    for flag in FLAGS:
212.1.2 by jaypipes at gmail
pylint fixes for nova/server.py
87
        logging.debug("%s : %s", flag, FLAGS.get(flag, None))
1 by Jesse Andrews
initial commit
88
89
    action = 'start'
90
    if len(argv) > 1:
91
        action = argv.pop()
92
93
    if action == 'stop':
94
        stop(FLAGS.pidfile)
95
        sys.exit()
96
    elif action == 'restart':
97
        stop(FLAGS.pidfile)
98
    elif action == 'start':
99
        pass
100
    else:
101
        print 'usage: %s [options] [start|stop|restart]' % argv[0]
102
        sys.exit(1)
237.1.91 by Vishvananda Ishaya
reverting accidental search/replace change to server.py
103
    daemonize(argv, name, main)
104
105
106
def daemonize(args, name, main):
107
    """Does the work of daemonizing the process"""
1 by Jesse Andrews
initial commit
108
    logging.getLogger('amqplib').setLevel(logging.WARN)
237.1.91 by Vishvananda Ishaya
reverting accidental search/replace change to server.py
109
    if FLAGS.daemonize:
1 by Jesse Andrews
initial commit
110
        logger = logging.getLogger()
111
        formatter = logging.Formatter(
112
                name + '(%(name)s): %(levelname)s %(message)s')
113
        if FLAGS.use_syslog and not FLAGS.logfile:
114
            syslog = logging.handlers.SysLogHandler(address='/dev/log')
115
            syslog.setFormatter(formatter)
116
            logger.addHandler(syslog)
117
        else:
118
            if not FLAGS.logfile:
119
                FLAGS.logfile = '%s.log' % name
212.1.2 by jaypipes at gmail
pylint fixes for nova/server.py
120
            logfile = logging.FileHandler(FLAGS.logfile)
1 by Jesse Andrews
initial commit
121
            logfile.setFormatter(formatter)
122
            logger.addHandler(logfile)
123
        stdin, stdout, stderr = None, None, None
124
    else:
125
        stdin, stdout, stderr = sys.stdin, sys.stdout, sys.stderr
126
127
    if FLAGS.verbose:
128
        logging.getLogger().setLevel(logging.DEBUG)
129
    else:
130
        logging.getLogger().setLevel(logging.WARNING)
131
237.1.91 by Vishvananda Ishaya
reverting accidental search/replace change to server.py
132
    with daemon.DaemonContext(
133
            detach_process=FLAGS.daemonize,
1 by Jesse Andrews
initial commit
134
            working_directory=FLAGS.working_directory,
135
            pidfile=pidlockfile.TimeoutPIDLockFile(FLAGS.pidfile,
136
                                                   acquire_timeout=1,
137
                                                   threaded=False),
138
            stdin=stdin,
139
            stdout=stdout,
242.2.1 by Soren Hansen
Use the argument handler specified by twistd, if any.
140
            stderr=stderr,
141
            uid=FLAGS.uid,
142
            gid=FLAGS.gid
1 by Jesse Andrews
initial commit
143
            ):
212.1.2 by jaypipes at gmail
pylint fixes for nova/server.py
144
        main(args)