root/scripts/deejayd

Revision 1456:a950e246dfef, 9.4 kB (checked in by Alexandre Rossi <alexandre.rossi@…>, 6 months ago)

[i18n] also translate -h option help in deejayd script

darcs-hash:20090925132508-85ee7-dc92ee5065066cc3c51ffe90adcb9d73b54b3600.gz

committer: Alexandre Rossi <alexandre.rossi@…>

  • Property exe set to *
Line 
1#!/usr/bin/env python
2
3# Deejayd, a media player daemon
4# Copyright (C) 2007-2009 Mickael Royer <mickael.royer@gmail.com>
5#                         Alexandre Rossi <alexandre.rossi@gmail.com>
6#
7# This program is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License along
18# with this program; if not, write to the Free Software Foundation, Inc.,
19# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20
21"""
22This is the script used to launch deejayd
23"""
24
25import errno, random, sys, os, pwd, grp, traceback
26from optparse import OptionParser
27from deejayd.ui.config import DeejaydConfig
28
29
30INSTALL_BIN_DIR = os.path.dirname(__file__)
31binsuffix = os.path.basename(INSTALL_BIN_DIR)
32INSTALL_MODE = 'source'
33if binsuffix == 'bin':
34    # Deejayd is installed, and not in source tree
35    INSTALL_MODE = 'installed'
36    INSTALL_PREFIX = INSTALL_BIN_DIR[:-len(binsuffix)]
37
38# init translation
39######################################################
40import gettext
41from deejayd.ui.i18n import DeejaydTranslations
42if INSTALL_MODE == 'source':
43    LOCALES_PATH = os.path.join(INSTALL_BIN_DIR, '..', 'build', 'mo')
44else:
45    LOCALES_PATH = os.path.join(INSTALL_PREFIX, 'share', 'locale')
46try:
47    t = gettext.translation("deejayd", LOCALES_PATH, class_=DeejaydTranslations)
48except IOError:
49    t = DeejaydTranslations()
50t.install()
51
52############ Parse Option ############################
53######################################################
54usage = "usage: %prog [options]"
55parser = OptionParser(usage=usage)
56
57# List options
58parser.set_defaults(pidfile="deejayd.pid",kill = False,daemon = True)
59
60# The help option must be changed to comply with i18n.
61parser.get_option('-h').help = _("Show this help message and exit.")
62
63parser.add_option("-u","--uid",dest="uid",type="string",\
64    help=_("The uid to run as"))
65parser.add_option("-g","--gid",dest="gid",type="string",\
66    help=_("The gid to run as (the first one), and the supplementary gids separated by commas."))
67parser.add_option("-n","--nodaemon",action="store_false",dest="daemon",\
68    help=_("No daemonize deejayd"))
69parser.add_option("-l","--log-file",type="string",dest="logfile",\
70    metavar="FILE", help=_("Specify the log file"))
71parser.add_option("-w","--webui-log",type="string",dest="webui_logfile",\
72    metavar="FILE", help=_("Specify the log file for the webui"))
73parser.add_option("-p","--pid-file",type="string",dest="pidfile",\
74    metavar="FILE", help=_("Specify the log file"))
75parser.add_option("-c","--conf-file",type="string",dest="conffile",\
76    metavar="FILE", help=_("Specify a custom conf file"))
77parser.add_option("-k","--kill",action="store_true",dest="kill",\
78    help=_("Kill the actual deejayd process"))
79parser.add_option("-d", "--debug",
80                  action="store_true", dest="debug",
81                  help=_("Log more debug informations"))
82
83(options, args) = parser.parse_args()
84######################################################
85
86# add custom config parms
87if options.conffile:
88    if os.path.isfile(options.conffile):
89        DeejaydConfig.custom_conf = options.conffile
90    else:
91        sys.exit(_("The config file does not exist."))
92
93if options.debug:
94    DeejaydConfig().set('general', 'log', 'debug')
95
96
97######################################################
98
99def daemonize():
100    # See http://www.erlenstar.demon.co.uk/unix/faq_toc.html#TOC16
101    if os.fork():   # launch child and...
102        os._exit(0) # kill off parent
103    os.setsid()
104    if os.fork():   # launch child and...
105        os._exit(0) # kill off parent again.
106    os.umask(077)
107    null=os.open('/dev/null', os.O_RDWR)
108    for i in range(3):
109        try:
110            os.dup2(null, i)
111        except OSError, e:
112            if e.errno != errno.EBADF:
113                raise
114    os.close(null)
115
116
117def killDeejayd(pidfile):
118    if os.path.exists(pidfile):
119        try: pid = int(open(pidfile).read())
120        except ValueError:
121            sys.exit(_('Pidfile %s contains non-numeric value') % pidfile)
122        try:
123            os.kill(pid, 15)
124            removePID(pidfile)
125        except OSError, err:
126            sys.exit(\
127                _('Unable to stop deejayd : %s, are you sure it running ?')\
128                 % (err,))
129    else:
130        sys.exit(_('no PidFile found, are you sure deejayd running ?'))
131
132
133def removePID(pidfile):
134    try: os.unlink(pidfile)
135    except OSError, e:
136        if e.errno == errno.EACCES or e.errno == errno.EPERM:
137            sys.exit(_("Unable to remove pid file : %s") % (e,))
138
139
140def setEnv(options):
141    # Init random generator
142    random.seed()
143
144    if options.daemon:
145        daemonize()
146    # Store the pid
147    removePID(options.pidfile)
148    open(options.pidfile,'wb').write(str(os.getpid()))
149
150    if options.gid:
151        gids = options.gid.split(',')
152        ngids = []
153        for gid in gids:
154            try: ngid = int(gid)
155            except ValueError:
156                ngid = grp.getgrnam(gid)[2]
157            ngids.append(ngid)
158        try:
159            os.setgroups(ngids)
160            os.setgid(ngids[0])
161        except OSError:
162            sys.exit(_("Unable to change gid of the process"))
163    if options.uid:
164        try: uid = int(options.uid)
165        except ValueError:
166            uid = pwd.getpwnam(options.uid)[2]
167        try:
168            os.setuid(uid)
169        except OSError:
170            sys.exit(_("Unable to change uid of the process"))
171
172
173def startLog(options):
174    from twisted.python import log
175    import deejayd.ui.log
176
177    log_file_name = None
178    if options.logfile:
179        log_file_name = options.logfile
180    elif options.daemon:
181        log_file_name = 'deejayd.log'
182
183    if log_file_name:
184        flo = deejayd.ui.log.SignaledFileLogObserver(log_file_name)
185        log.startLoggingWithObserver(flo.emit)
186    else:
187        log.startLogging(sys.stdout)
188
189
190# Start
191if __name__ == "__main__":
192    if options.kill:
193        killDeejayd(options.pidfile)
194        sys.exit()
195
196    ###################
197    # install reactor
198    ##################
199    config = DeejaydConfig()
200    media_backend = config.get("general", "media_backend")
201    if media_backend == "gstreamer":
202        # Install glib2 reactor
203        from twisted.internet import glib2reactor
204        glib2reactor.install()
205
206    from twisted.internet import reactor
207    # use twisted loop for kaa
208    import kaa
209    kaa.main.select_notifier('twisted')
210    ###############################################################
211
212    setEnv(options)
213    startLog(options)
214
215    from twisted.internet.error import CannotListenError
216    from twisted.python import log
217
218    # start core
219    try:
220        from deejayd.core import DeejayDaemonCore
221        deejayd_core = DeejayDaemonCore(config)
222    except Exception, ex:
223        from deejayd.utils import str_encode
224        log.err(\
225            _("Unable to launch deejayd core, see traceback for more details"))
226        log.msg(str_encode(traceback.format_exc()))
227        sys.exit(1)
228
229    service = False
230    # net service
231    if config.getboolean("net","enabled"):
232        service = True
233        from deejayd.net.protocol import DeejaydFactory
234
235        factory = DeejaydFactory(deejayd_core)
236        port = config.getint("net", "port")
237        for bind_address in config.get_bind_addresses('net'):
238            try: reactor.listenTCP(port, factory, interface=bind_address)
239            except CannotListenError, err:
240                deejayd_core.close()
241                log.err(str(err))
242                sys.exit(1)
243
244    # webui service
245    if config.getboolean("webui","enabled"):
246        try:
247            from deejayd import webui
248        except ImportError:
249            log.err(_("Webui does not seem to be installed, disabling."))
250            config.set("webui", "enabled", False)
251        else:
252            service = True
253            htdocs_dir = None
254            if INSTALL_MODE == 'source':
255                htdocs_dir = os.path.abspath(os.path.join(INSTALL_BIN_DIR, '..',
256                                                          'data', 'htdocs'))
257            elif INSTALL_MODE == 'installed':
258                htdocs_dir = os.path.abspath(os.path.join(INSTALL_PREFIX,
259                                                          'share', 'deejayd',
260                                                          'htdocs'))
261            try:
262                site = webui.init(deejayd_core, config,
263                                  options.webui_logfile, htdocs_dir)
264            except webui.DeejaydWebError, err:
265                deejayd_core.close()
266                log.err(err)
267                sys.exit(1)
268
269            port = config.getint("webui","port")
270            for bind_address in config.get_bind_addresses('webui'):
271                try: reactor.listenTCP(port, site, interface=bind_address)
272                except CannotListenError, err:
273                    deejayd_core.close()
274                    log.err(str(err))
275                    sys.exit(1)
276
277    # launch reactor
278    if not service:
279        deejayd_core.close()
280        log.err(_("No service has been activated"))
281        sys.exit(1)
282    reactor.addSystemEventTrigger('after','shutdown',deejayd_core.close)
283    reactor.run()
284
285# vim: ts=4 sw=4 expandtab
Note: See TracBrowser for help on using the browser.