File: test.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 (773 lines) | stat: -rwxr-xr-x 28,127 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
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
#!/usr/bin/env python
#
# see LICENSE.txt for license information
#
# $Id: test.py 381 2008-06-19 22:40:22Z camrdale-guest $

"""Automated tests of the DebTorrent functionality.

This script runs several automatic tests of some of the functionality in
the DebTorrent programs.

@type tests: C{dictionary}
@var tests: all of the tests that can be run.
    The keys are the test names (strings) which are used on the command-line
    to identify the tests (can not be 'all' or 'help'). The values are tuples
    with four elements: a description of the test (C{string}), the trackers
    to start (C{dictionary}), the downloaders to start (C{dictionary}, and
    the apt-get commands to run (C{list}).
    
    The trackers keys are integers, which must be in the range 1-9. The values
    are the list of command-line options (strings) to start the tracker with.
    
    The downloaders keys are also integers in the range 1-9. The values are
    tuples with 3 elements: the number of the tracker to connect to, the list
    of command-line options to start the downloader with, and any other
    keyword arguments to specify to the L{start_downloader} function.
    
    The apt-get commands' list elements are tuples with 2 elements: the
    downloader to run the command on, and the list of command-line
    arguments to specify to the apt-get program.
    
@type CWD: C{string}
@var CWD: the working directory the script was run from
@type apt_conf_template: C{string}
@var apt_conf_template: the template to use for the apt.conf file

"""

from time import sleep, time
from DebTorrent.BT1.track import track
from DebTorrent.__init__ import resetPeerIDs
import sys, os, signal
from traceback import print_exc
from os.path import exists

DebTorrentClient = __import__('debtorrent-client', globals(), locals(), [])

tests = {'1': ('Start a single tracker and downloader, test updating and downloading ' +
             'using the HTTPDownloader.',
             {1: []},
             {1: (1, [], {})},
             [(1, ['update']), 
              (1, ['install', 'aspectj-doc']),
              (1, ['install', 'fop-doc']),
              (1, ['install', 'asis-doc']),
              (1, ['install', 'bison-doc']),
              (1, ['install', 'crash-whitepaper']),
              (1, ['install', 'aboot-base']),
              (1, ['install', 'aap-doc']),
              (1, ['install', 'ada-reference-manual']),
              ]),

         '2': ('Start a single tracker and 2 downloaders, disable HTTP downloading' +
               ' on the second one to test downloading from a peer.',
               {1: []},
               {1: (1, [], {}),
                2: (1, ['--disable_http_downloader', '1'], {})},
               [(1, ['update']),
                (1, ['install', 'fop-doc']),
                (1, ['install', 'bison-doc']),
                (1, ['install', 'crash-whitepaper']),
                (1, ['install', 'aboot-base']),
                (1, ['install', 'aap-doc']),
                (1, ['install', 'ada-reference-manual']),
                (2, ['update']),
                (2, ['install', 'fop-doc']),
                (2, ['install', 'bison-doc']),
                (2, ['install', 'crash-whitepaper']),
                (2, ['install', 'aboot-base']),
                (2, ['install', 'aap-doc']),
                (2, ['install', 'ada-reference-manual']),
                ]),
                
         '3': ('Start a single tracker and 6 downloaders, to test downloading' +
               ' speeds from each other.',
               {1: []},
               {1: (1, [], {}),
                2: (1, [], {}),
                3: (1, [], {}),
                4: (1, [], {}),
                5: (1, [], {}),
                6: (1, [], {})},
               [(1, ['update']),
                (1, ['install', 'fop-doc']),
                (1, ['install', 'aboot-base']),
                (1, ['install', 'ada-reference-manual']),
                (2, ['update']),
                (2, ['install', 'fop-doc']),
                (2, ['install', 'aboot-base']),
                (2, ['install', 'ada-reference-manual']),
                (3, ['update']),
                (3, ['install', 'fop-doc']),
                (3, ['install', 'aboot-base']),
                (3, ['install', 'ada-reference-manual']),
                (4, ['update']),
                (4, ['install', 'fop-doc']),
                (4, ['install', 'aboot-base']),
                (4, ['install', 'ada-reference-manual']),
                (5, ['update']),
                (5, ['install', 'fop-doc']),
                (5, ['install', 'aboot-base']),
                (5, ['install', 'ada-reference-manual']),
                (6, ['update']),
                (6, ['install', 'fop-doc']),
                (6, ['install', 'aboot-base']),
                (6, ['install', 'ada-reference-manual']),
                ]),

         '4': ('Start a single tracker and 1 downloader, requesting the same' +
               ' packages multiple times to test caching.',
               {1: []},
               {1: (1, [], {})},
               [(1, ['update']),
                (1, ['install', 'fop-doc']),
                (1, ['install', 'aboot-base']),
                (1, ['install', 'ada-reference-manual']),
                (1, ['update']),
                (1, ['install', 'fop-doc']),
                (1, ['install', 'aboot-base']),
                (1, ['install', 'ada-reference-manual']),
                (1, ['update']),
                (1, ['install', 'fop-doc']),
                (1, ['install', 'aboot-base']),
                (1, ['install', 'ada-reference-manual']),
                ]),
                
         '5': ('Start a single tracker and 6 downloaders, update all to test' +
               ' that they can all see each other.',
               {1: []},
               {1: (1, [], {'suites': 'contrib non-free'}),
                2: (1, [], {'suites': 'contrib non-free', 'mirror': 'debian.mirror.iweb.ca/debian'}),
                3: (1, [], {'suites': 'contrib non-free', 'mirror': 'debian.sth.sze.hu'}),
                4: (1, [], {'suites': 'contrib non-free', 'mirror': 'ftp.monash.edu.au/pub/linux/debian'}),
                5: (1, [], {'suites': 'contrib non-free', 'mirror': 'mmc.igeofcu.unam.mx/debian'}),
                6: (1, [], {'suites': 'contrib non-free', 'mirror': 'debian.revolsys.fr/debian'})},
               [(1, ['update']),
                (2, ['update']),
                (3, ['update']),
                (4, ['update']),
                (5, ['update']),
                (6, ['update']),
                ]),

        '6': ('Test caching with multiple apt-get updates.',
             {1: []},
             {1: (1, [], {})},
             [(1, ['update']), 
              (1, ['update']),
              (1, ['update']),
              (1, ['update']),
              ]),

        '7': ('Test pipelining of multiple simultaneous downloads.',
             {1: []},
             {1: (1, [], {})},
             [(1, ['update']), 
              (1, ['install', 'aboot-base', 'aap-doc', 'ada-reference-manual',
                   'aspectj-doc', 'fop-doc', 'asis-doc',
                   'bison-doc', 'crash-whitepaper',
                   'bash-doc', 'apt-howto-common', 'autotools-dev',
                   'aptitude-doc-en', 'asr-manpages',
                   'atomix-data', 'alcovebook-sgml-doc',
                   'aegis-doc', 'afbackup-common', 'airstrike-common',
                   ]),
              ]),

        '8': ('Test pipelining of multiple simultaneous downloads with many peers.',
             {1: []},
             {1: (1, [], {}),
              2: (1, [], {}),
              3: (1, [], {}),
              4: (1, [], {}),
              5: (1, [], {}),
              6: (1, [], {})},
             [(1, ['update']), 
              (1, ['install', 'aboot-base', 'aap-doc', 'ada-reference-manual',
                   'aspectj-doc', 'fop-doc', 'asis-doc',
                   'bison-doc', 'crash-whitepaper',
                   'bash-doc', 'apt-howto-common', 'autotools-dev',
                   'aptitude-doc-en', 'asr-manpages',
                   'atomix-data', 'alcovebook-sgml-doc',
                   'aegis-doc', 'afbackup-common', 'airstrike-common',
                   ]),
              (2, ['update']), 
              (2, ['install', 'aboot-base', 'aap-doc', 'ada-reference-manual',
                   'aspectj-doc', 'fop-doc', 'asis-doc',
                   'bison-doc', 'crash-whitepaper',
                   'bash-doc', 'apt-howto-common', 'autotools-dev',
                   'aptitude-doc-en', 'asr-manpages',
                   'atomix-data', 'alcovebook-sgml-doc',
                   'aegis-doc', 'afbackup-common', 'airstrike-common',
                   ]),
              (3, ['update']), 
              (3, ['install', 'aboot-base', 'aap-doc', 'ada-reference-manual',
                   'aspectj-doc', 'fop-doc', 'asis-doc',
                   'bison-doc', 'crash-whitepaper',
                   'bash-doc', 'apt-howto-common', 'autotools-dev',
                   'aptitude-doc-en', 'asr-manpages',
                   'atomix-data', 'alcovebook-sgml-doc',
                   'aegis-doc', 'afbackup-common', 'airstrike-common',
                   ]),
              (4, ['update']), 
              (4, ['install', 'aboot-base', 'aap-doc', 'ada-reference-manual',
                   'aspectj-doc', 'fop-doc', 'asis-doc',
                   'bison-doc', 'crash-whitepaper',
                   'bash-doc', 'apt-howto-common', 'autotools-dev',
                   'aptitude-doc-en', 'asr-manpages',
                   'atomix-data', 'alcovebook-sgml-doc',
                   'aegis-doc', 'afbackup-common', 'airstrike-common',
                   ]),
              (5, ['update']), 
              (5, ['install', 'aboot-base', 'aap-doc', 'ada-reference-manual',
                   'aspectj-doc', 'fop-doc', 'asis-doc',
                   'bison-doc', 'crash-whitepaper',
                   'bash-doc', 'apt-howto-common', 'autotools-dev',
                   'aptitude-doc-en', 'asr-manpages',
                   'atomix-data', 'alcovebook-sgml-doc',
                   'aegis-doc', 'afbackup-common', 'airstrike-common',
                   ]),
              (6, ['update']), 
              (6, ['install', 'aboot-base', 'aap-doc', 'ada-reference-manual',
                   'aspectj-doc', 'fop-doc', 'asis-doc',
                   'bison-doc', 'crash-whitepaper',
                   'bash-doc', 'apt-howto-common', 'autotools-dev',
                   'aptitude-doc-en', 'asr-manpages',
                   'atomix-data', 'alcovebook-sgml-doc',
                   'aegis-doc', 'afbackup-common', 'airstrike-common',
                   ]),
              ]),

        '9': ('Run this test multiple times to test restarting the downloader.',
             {1: []},
             {1: (1, [], {'clean': False})},
             [(1, ['update']), 
              (1, ['install', 'aspectj-doc']),
              (1, ['install', 'fop-doc']),
              (1, ['install', 'asis-doc']),
              (1, ['install', 'bison-doc']),
              (1, ['install', 'crash-whitepaper']),
              (1, ['install', 'libhypre1.6.0c2']),
              (1, ['install', 'rar']),
              (1, ['install', 'aboot-base']),
              (1, ['install', 'aap-doc']),
              (1, ['install', 'ada-reference-manual']),
              (1, ['install', '2vcard']),
              (1, ['install', 'avahi-dbg']),
              (1, ['install', 'chasen-cannadic']),
              ]),

         }

assert 'all' not in tests
assert 'help' not in tests

CWD = os.getcwd()
apt_conf_template = """
{
  // Location of the state dir
  State "var/lib/apt/"
  {
     Lists "lists/";
     xstatus "xstatus";
     userstatus "status.user";
     cdroms "cdroms.list";
  };

  // Location of the cache dir
  Cache "var/cache/apt/" {
     Archives "archives/";
     srcpkgcache "srcpkgcache.bin";
     pkgcache "pkgcache.bin";
  };

  // Config files
  Etc "etc/apt/" {
     SourceList "sources.list";
     Main "apt.conf";
     Preferences "preferences";
     Parts "apt.conf.d/";
  };

  // Locations of binaries
  Bin {
     methods "/usr/lib/apt/methods/";
     gzip "/bin/gzip";
     gpg  "/usr/bin/gpgv";
     dpkg "/usr/bin/dpkg --simulate";
     dpkg-source "/usr/bin/dpkg-source";
     dpkg-buildpackage "/usr/bin/dpkg-buildpackage";
     apt-get "/usr/bin/apt-get";
     apt-cache "/usr/bin/apt-cache";
  };
};

// Options for the downloading routines
Acquire
{
  // DEBTORRENT method configuration
  debtorrent
  {
    // The timeout delay before the method will close the connection
    Timeout "300";
    // Don't keep copies of the downloaded files in apt's cache
    NoCache "false";
  };
};

/* Options you can set to see some debugging text They correspond to names
   of classes in the source code */
Debug
{
  pkgProblemResolver "false";
  pkgDepCache::AutoInstall "false"; // what packages apt install to satify dependencies
  pkgAcquire "false";
  pkgAcquire::Worker "false";
  pkgAcquire::Auth "false";
  pkgDPkgPM "false";
  pkgDPkgProgressReporting "false";
  pkgOrderList "false";
  BuildDeps "false";

  pkgInitialize "false";   // This one will dump the configuration space
  NoLocking "false";
  Acquire::Ftp "false";    // Show ftp command traffic
  Acquire::Http "false";   // Show http command traffic
  Acquire::Debtorrent "false";   // Show http command traffic
  Acquire::gpgv "false";   // Show the gpgv traffic
  aptcdrom "false";        // Show found package files
  IdentCdrom "false";

}
"""

def rmrf(top):
    """Remove all the files and directories below a top-level one.
    
    @type top: C{string}
    @param top: the top-level directory to start at
    
    """
    
    if exists(top):
        for root, dirs, files in os.walk(top, topdown=False):
            for name in files:
                os.remove(os.path.join(root, name))
            for name in dirs:
                os.rmdir(os.path.join(root, name))

def join(dir):
    """Join together a list of directories into a path string.
    
    @type dir: C{list} of C{string}
    @param dir: the path to join together
    @rtype: C{string}
    @return: the joined together path
    
    """
    
    joined = ''
    for i in dir:
        joined = os.path.join(joined, i)
    return joined

def makedirs(dir):
    """Create all the directories to make a path.
    
    @type dir: C{list} of C{string}
    @param dir: the path to create
    
    """
    
    if not exists(join(dir)):
        os.makedirs(join(dir))

def touch(path):
    """Create an empty file.
    
    @type path: C{list} of C{string}
    @param path: the path to create
    
    """

    if not exists(join(path)):
        f = open(join(path), 'w')
        f.close()

def start(func, args, work_dir = None):
    """Fork and start a background process running.
    
    @type func: C{method}
    @param func: the function to call in the child
    @type args: C{list} of C{string}
    @param args: the argument to pass to the function
    @type work_dir: C{string}
    @param work_dir: the directory to change to to execute the child process in
        (optional, defaults to the current directory)
    @rtype: C{int}
    @return: the PID of the forked child (only returned to the parent)
    
    """
    
    pid = os.fork()
    if pid != 0:
        return pid
    if work_dir:
        os.chdir(work_dir)
    func(args)
    os._exit(0)

def stop(pid):
    """Stop a forked background process that is running.
    
    @type pid: C{int}
    @param pid: the PID of the process to stop
    @rtype: C{int}
    @return: the return status code from the child
    
    """

    # First try a keyboard interrupt
    os.kill(pid, signal.SIGINT)
    for i in xrange(5):
        sleep(1)
        (r_pid, r_value) = os.waitpid(pid, os.WNOHANG)
        if r_pid:
            return r_value
    
    # Try a keyboard interrupt again, just in case
    os.kill(pid, signal.SIGINT)
    for i in xrange(5):
        sleep(1)
        (r_pid, r_value) = os.waitpid(pid, os.WNOHANG)
        if r_pid:
            return r_value

    # Try a terminate
    os.kill(pid, signal.SIGTERM)
    for i in xrange(5):
        sleep(1)
        (r_pid, r_value) = os.waitpid(pid, os.WNOHANG)
        if r_pid:
            return r_value

    # Finally a kill, don't return until killed
    os.kill(pid, signal.SIGKILL)
    while not r_pid:
        sleep(1)
        (r_pid, r_value) = os.waitpid(pid, os.WNOHANG)

    return r_value

def apt_get(num_down, cmd):
    """Start an apt-get process in the background.

    The default argument specified to the apt-get invocation are
    'apt-get -d -q -c <conf_file>'. Any additional arguments (including
    the apt-get action to use) should be specified.
    
    @type num_down: C{int}
    @param num_down: the number of the downloader to use
    @type cmd: C{list} of C{string}
    @param cmd: the arguments to pass to the apt-get process
    @rtype: C{int}
    @return: the PID of the background process
    
    """
    
    print '************************** apt-get (' + str(num_down) + ') ' + ' '.join(cmd) + ' **************************'
    apt_conf = join([down_dir(num_down), 'etc', 'apt', 'apt.conf'])
    dpkg_status = join([down_dir(num_down), 'var', 'lib', 'dpkg', 'status'])
    new_cmd = ['apt-get', '-d', '-c', apt_conf, '-o', 'Dir::state::status='+dpkg_status] + cmd
    pid = os.spawnvp(os.P_NOWAIT, new_cmd[0], new_cmd)
    return pid

def tracker_address(num_track):
    """Determine the announce address to use for a tracker.
    
    @type num_track: C{int}
    @param num_track: the number of the tracker
    @rtype: C{string}
    @return: the tracker address to use
    
    """
    
    return 'http://localhost:' + str(num_track) + '969/announce'

def down_dir(num_down):
    """Determine the working directory to use for a downloader.
    
    @type num_down: C{int}
    @param num_down: the number of the downloader
    @rtype: C{string}
    @return: the downloader's directory
    
    """
    
    return os.path.join(CWD,'downloader' + str(num_down))

def track_dir(num_track):
    """Determine the working directory to use for a tracker.
    
    @type num_track: C{int}
    @param num_track: the number of the tracker
    @rtype: C{string}
    @return: the tracker's directory
    
    """
    
    return os.path.join(CWD,'tracker' + str(num_track))

def start_downloader(num_down, options = [], mirror = 'ftp.us.debian.org/debian', 
                     suites = 'main contrib non-free', clean = True):
    """Initialize a new downloader process.

    The default arguments specified to the downloader invocation are
    the configuration directory, apt port, minport, maxport and the
    maximum upload rate. 
    Any additional arguments needed should be specified by L{options}.
    
    @type num_down: C{int}
    @param num_down: the number of the downloader to use
    @type options: C{list} of C{string}
    @param options: the arguments to pass to the downloader
        (optional, defaults to only using the default arguments)
    @type mirror: C{string}
    @param mirror: the Debian mirror to use
        (optional, defaults to 'ftp.us.debian.org/debian')
    @type suites: C{string}
    @param suites: space separated list of suites to download
        (optional, defaults to 'main contrib non-free')
    @type clean: C{boolean}
    @param clean: whether to remove any previous downloader files
        (optional, defaults to removing them)
    @rtype: C{int}
    @return: the PID of the downloader process
    
    """
    
    assert num_down < 10
    
    print '************************** Starting Downloader ' + str(num_down) + ' **************************'

    downloader_dir = down_dir(num_down)
    
    if clean:
        try:
            rmrf(downloader_dir)
        except:
            pass
    
    # Create the directory structure needed by apt
    makedirs([downloader_dir, 'etc', 'apt', 'apt.conf.d'])
    makedirs([downloader_dir, 'var', 'lib', 'apt', 'lists', 'partial'])
    makedirs([downloader_dir, 'var', 'lib', 'dpkg'])
    rmrf(join([downloader_dir, 'var', 'cache', 'apt', 'archives']))
    makedirs([downloader_dir, 'var', 'cache', 'apt', 'archives', 'partial'])
    touch([downloader_dir, 'var', 'lib', 'apt', 'lists', 'lock'])
    touch([downloader_dir, 'var', 'lib', 'dpkg', 'lock'])
    touch([downloader_dir, 'var', 'lib', 'dpkg', 'status'])
    touch([downloader_dir, 'var', 'cache', 'apt', 'archives', 'lock'])

    if not exists(join([downloader_dir, 'etc', 'apt', 'sources.list'])):
        # Create apt's config files
        f = open(join([downloader_dir, 'etc', 'apt', 'sources.list']), 'w')
        if exists('/usr/lib/apt/methods/newdebtorrent'):
            f.write('deb newdebtorrent://localhost:' + str(num_down) + '988/' + mirror + '/ unstable ' + suites + '\n')
        elif exists('/usr/lib/apt/methods/debtorrent'):
            f.write('deb debtorrent://localhost:' + str(num_down) + '988/' + mirror + '/ unstable ' + suites + '\n')
        else:
            f.write('deb http://localhost:' + str(num_down) + '988/' + mirror + '/ unstable ' + suites + '\n')
        f.close()

    if not exists(join([downloader_dir, 'etc', 'apt', 'apt.conf'])):
        f = open(join([downloader_dir, 'etc', 'apt', 'apt.conf']), 'w')
        f.write('Dir "' + downloader_dir + '"')
        f.write(apt_conf_template)
        f.close()

    # Reset the peer ID so it will be different
    resetPeerIDs()

    pid = start(DebTorrentClient.run, ['--cache_dir', downloader_dir,
                                       '--download_dir', downloader_dir,
                                       '--log_level', '10',
                                       '--security', '0',
                                       '--apt_port', str(num_down) + '988', 
                                       '--max_upload_rate', '100',
                                       '--minport', '1' + str(num_down) + '000', 
                                       '--maxport', '1' + str(num_down) + '999'] + options,
                downloader_dir)
    return pid

def start_tracker(num_track, options = [], clean = True):
    """Initialize a new tracker process.

    The default arguments specified to the tracker invocation are
    the state file and port to use. Any additional arguments needed 
    should be specified by L{options}.
    
    @type num_track: C{int}
    @param num_track: the number of the tracker to use
    @type options: C{list} of C{string}
    @param options: the arguments to pass to the tracker
        (optional, defaults to only using the default arguments)
    @type clean: C{boolean}
    @param clean: whether to remove any previous tracker files
        (optional, defaults to removing them)
    @rtype: C{int}
    @return: the PID of the downloader process
    
    """
    
    assert num_track < 10

    print '************************** Starting Tracker ' + str(num_track) + ' **************************'

    tracker_dir = track_dir(num_track)
    
    if clean:
        try:
            rmrf(tracker_dir)
        except:
            pass

    pid = start(track, ['--cache_dir', tracker_dir,
                        '--log_level', '10',
                        '--port', str(num_track) + '969'] + options)
    return pid

def run_test(trackers, downloaders, apt_get_queue):
    """Run a single test.
    
    @type trackers: C{dictionary} of {C{int}: C{list} of C{string}}
    @param trackers: the trackers to start, keys are the tracker numbers and
        values are the list of options to invoke the tracker with
    @type downloaders: C{dictionary} of {C{int}: (C{int}, C{list} of C{string})}
    @param downloaders: the downloaders to start, keys are the downloader numbers and
        values are the tracker to ascossiate with and the list of options to invoke 
        the downloader with
    @type apt_get_queue: C{list} of (C{int}, C{list} of C{string})
    @param apt_get_queue: the apt-get downloader to use and commands to execute
    @rtype: C{list} of (C{float}, C{int})
    @return: the execution time and returned status code for each element of apt_get_queue
    
    """
    
    running_trackers = {}
    running_downloaders = {}
    running_apt_get = {}
    apt_get_results = []

    try:
        for k, v in trackers.items():
            running_trackers[k] = start_tracker(k, v)
        
        sleep(5)
        
        for k, v in downloaders.items():
            opts = v[1] + ['--force_tracker', tracker_address(v[0])]
            running_downloaders[k] = start_downloader(k, opts, **v[2])
    
        sleep(10)
        
        for (num_down, cmd) in apt_get_queue:
            running_apt_get[num_down] = apt_get(num_down, cmd)
            start_time = time()
            (pid, r_value) = os.waitpid(running_apt_get[num_down], 0)
            elapsed = time() - start_time
            del running_apt_get[num_down]
            r_value = r_value / 256
            apt_get_results.append((elapsed, r_value))

            if r_value == 0:
                print '********************** apt-get completed successfully in ' +  str(elapsed) + ' sec. **************************'
            else:
                print '********************** apt-get finished with status ' + str(r_value) + ' in ' +  str(elapsed) + ' sec. **************************'
        
            sleep(5)
            if 'update' in cmd:
                sleep(25)
            
    except:
        print '************************** Exception occurred **************************'
        print_exc()
        print '************************** will attempt to shut down *******************'
        
    print '*********************** shutting down the apt-gets *******************'
    for k, v in running_apt_get.items():
        try:
            print 'apt-get', k, stop(v)
        except:
            print '************************** Exception occurred **************************'
            print_exc()

    sleep(5)

    print '*********************** shutting down the downloaders *******************'
    for k, v in running_downloaders.items():
        try:
            print 'downloader', k, stop(v)
        except:
            print '************************** Exception occurred **************************'
            print_exc()

    sleep(5)

    print '************************** shutting down the trackers *******************'
    for k, v in running_trackers.items():
        try:
            print 'tracker', k, stop(v)
        except:
            print '************************** Exception occurred **************************'
            print_exc()

    print '************************** Test Results *******************'
    i = -1
    for (num_down, cmd) in apt_get_queue:
        i += 1
        s = str(num_down) + ': "apt-get ' + ' '.join(cmd) + '" '
        if len(apt_get_results) > i:
            (elapsed, r_value) = apt_get_results[i]
            s += 'took ' + str(elapsed) + ' secs (' + str(r_value) + ')'
        else:
            s += 'did not complete'
        print s
    
    return apt_get_results

def get_usage():
    """Get the usage information to display to the user.
    
    @rtype: C{string}
    @return: the usage information to display
    
    """
    
    s = 'Usage: ' + sys.argv[0] + ' (all|<test>|help)\n\n'
    s += '  all    - run all the tests\n'
    s += '  help   - display this usage information\n'
    s += '  <test> - run the <test> test (see list below for valid tests)\n\n'
    
    t = tests.items()
    t.sort()
    for k, v in t:
        s += 'test "' + str(k) + '" - ' + v[0] + '\n'
    
    return s

if __name__ == '__main__':
    if len(sys.argv) != 2:
        print get_usage()
    elif sys.argv[1] == 'all':
        for k, v in tests.items():
            run_test(v[1], v[2], v[3])
    elif sys.argv[1] in tests:
        v = tests[sys.argv[1]]
        run_test(v[1], v[2], v[3])
    elif sys.argv[1] == 'help':
        print get_usage()
    else:
        print 'Unknown test to run:', sys.argv[1], '\n'
        print get_usage()