File: debtorrent-client.py

package info (click to toggle)
debtorrent 0.1.9
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 1,452 kB
  • ctags: 1,183
  • sloc: python: 13,526; sh: 274; makefile: 51
file content (117 lines) | stat: -rwxr-xr-x 3,835 bytes parent folder | download | duplicates (2)
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
#!/usr/bin/env python
#
# see LICENSE.txt for license information
#
# $Id: debtorrent-client.py 270 2007-08-19 07:33:13Z camrdale-guest $

"""A multiple downloader client daemon for debtorrent.

This script implements a client daemon for managing multiple 
debtorrent downloads.

@type logger: C{logging.Logger}
@var logger: the logger to send all log messages to for this module

"""

from DebTorrent import PSYCO
if PSYCO.psyco:
    try:
        import psyco
        assert psyco.__version__ >= 0x010100f0
        psyco.full()
    except:
        pass

from DebTorrent.launchmanycore import LaunchMany
from DebTorrent.download_bt1 import defaults, get_usage
from DebTorrent.parseargs import parseargs
from sys import argv, exit, version_info
import os, logging
from DebTorrent import version
from DebTorrent.ConfigDir import ConfigDir

assert version_info >= (2,3), 'Requires Python 2.3 or better'

logger = logging.getLogger()

def run(params):
    """Runs the downloader.
    
    The main function used to initialize the environment and create the controller.
    
    @type params: C{list} of C{strings}
    @param params: a list of the command-line arguments given to the script
    @rtype: C{boolean}
    @return: whether the server should be restarted
    
    """

    restart = False
    configdefaults = {}
    try:
        # Load the configuration data
        configdir = ConfigDir('debtorrent-client')
        defaultsToIgnore = ['configfile']
        configdir.setDefaults(defaults,defaultsToIgnore)
        configdefaults = configdir.loadConfig(params)
        defaults.append(('save_options',0,
         "whether to save the current options as the new default configuration " +
         "(only for debtorrent-client.py)"))
        config, args = parseargs(params, defaults, 0, 0, configdefaults)
        configdir.setCacheDir(config['cache_dir'])
        if config['log_dir']:
            outfilename = os.path.join(config['log_dir'], 'debtorrent-client.log')
        else:
            outfilename = os.path.join(configdir.cache_dir, 'debtorrent-client.log')
        
        # Create the root handler (removing any others)
        hdlr = logging.FileHandler(outfilename, 'a')
        hdlr.setFormatter(logging.Formatter('%(asctime)s %(threadName)s %(name)s %(levelname)s %(message)s'))
        for h in logging.root.handlers:
            logging.root.removeHandler(h)
        logging.root.addHandler(hdlr)
        logging.root.setLevel(config['log_level'])
        logger.info('Logging begins')
        
        # Continue
        if config['save_options']:
            configdir.saveConfig(config)
    except ValueError, e:
        logger.error('error: ' + str(e))
        logger.error("Usage: debtorrent-client.py <global options>")
        logger.error(get_usage(defaults, 80, configdefaults))
        logging.shutdown()
        exit(1)
    except IOError, e:
        logger.exception('error: ' + str(e))
        logging.shutdown()
        exit(2)
    except:
        logger.exception('unhandled exception')

    try:
        many_launcher = LaunchMany(config, configdir)
        restart = many_launcher.run()
    except:
        logger.exception('unhandled exception')

    logger.info('Shutting down')
    logging.shutdown()
    return restart

if __name__ == '__main__':
    if argv[1:2] == ['--version']:
        print version
        exit(0)
    elif argv[1:2] == ['--profile']:
        import profile, pstats
        p = profile.Profile()
        p.runcall(run, argv[2:])
        p.dump_stats('debtorrent-client.pstat')
        # pstats.Stats(p).strip_dirs().sort_stats('cumulative').print_stats()
        pstats.Stats(p).strip_dirs().sort_stats('time').print_stats()
    else:
        # Run the client in a loop, exiting when it says it shouldn't be restarted
        while run(argv[1:]):
            pass