3 """Automated tests of the apt-dht functionality.
5 This script runs several automatic tests of some of the functionality in
8 @type tests: C{dictionary}
9 @var tests: all of the tests that can be run.
10 The keys are the test names (strings) which are used on the command-line
11 to identify the tests (can not be 'all' or 'help'). The values are tuples
12 with four elements: a description of the test (C{string}), the bootstrap
13 nodes to start (C{dictionary}), the downloaders to start (C{dictionary},
14 and the apt-get commands to run (C{list}).
16 The bootstrap nodes keys are integers, which must be in the range 1-9.
17 The values are the dictionary of string formatting values for creating
18 the apt-dht configuration file (see L{apt_dht_conf_template} below).
20 The downloaders keys are also integers in the range 1-99. The values are
21 the dictionary of string formatting values for creating the apt-dht
22 configuration file (see L{apt_dht_conf_template} below).
24 The apt-get commands' list elements are tuples with 2 elements: the
25 downloader to run the command on, and the list of command-line
26 arguments to specify to the apt-get program.
29 @var CWD: the working directory the script was run from
30 @type apt_conf_template: C{string}
31 @var apt_conf_template: the template to use for the apt.conf file
35 from time import sleep, time
36 import sys, os, signal
37 from traceback import print_exc
38 from os.path import exists
40 tests = {'1': ('Start a single bootstrap and downloader, test updating and downloading ' +
45 (1, ['install', 'aboot-base']),
46 (1, ['install', 'aap-doc']),
47 (1, ['install', 'ada-reference-manual']),
48 (1, ['install', 'aspectj-doc']),
49 (1, ['install', 'fop-doc']),
50 (1, ['install', 'jswat-doc']),
51 (1, ['install', 'asis-doc']),
52 (1, ['install', 'bison-doc']),
53 (1, ['install', 'crash-whitepaper']),
54 (1, ['install', 'doc-iana']),
57 '2': ('Start a single bootstrap and 2 downloaders to test downloading from a peer.',
63 (1, ['install', 'aboot-base']),
64 (2, ['install', 'aboot-base']),
65 (1, ['install', 'aap-doc']),
66 (1, ['install', 'ada-reference-manual']),
67 (1, ['install', 'fop-doc']),
68 (1, ['install', 'jswat-doc']),
69 (1, ['install', 'bison-doc']),
70 (1, ['install', 'crash-whitepaper']),
71 (2, ['install', 'aap-doc']),
72 (2, ['install', 'ada-reference-manual']),
73 (2, ['install', 'fop-doc']),
74 (2, ['install', 'jswat-doc']),
75 (2, ['install', 'bison-doc']),
76 (2, ['install', 'crash-whitepaper']),
79 '3': ('Start a single bootstrap and 6 downloaders, to test downloading' +
80 ' speeds from each other.',
89 (1, ['install', 'aboot-base']),
90 (1, ['install', 'ada-reference-manual']),
91 (1, ['install', 'fop-doc']),
92 (1, ['install', 'doc-iana']),
94 (2, ['install', 'aboot-base']),
95 (2, ['install', 'ada-reference-manual']),
96 (2, ['install', 'fop-doc']),
97 (2, ['install', 'doc-iana']),
99 (3, ['install', 'aboot-base']),
100 (3, ['install', 'ada-reference-manual']),
101 (3, ['install', 'fop-doc']),
102 (3, ['install', 'doc-iana']),
104 (4, ['install', 'aboot-base']),
105 (4, ['install', 'ada-reference-manual']),
106 (4, ['install', 'fop-doc']),
107 (4, ['install', 'doc-iana']),
109 (5, ['install', 'aboot-base']),
110 (5, ['install', 'ada-reference-manual']),
111 (5, ['install', 'fop-doc']),
112 (5, ['install', 'doc-iana']),
114 (6, ['install', 'aboot-base']),
115 (6, ['install', 'ada-reference-manual']),
116 (6, ['install', 'fop-doc']),
117 (6, ['install', 'doc-iana']),
120 '4': ('Start a single bootstrap and 1 downloader, requesting the same' +
121 ' packages multiple times to test caching.',
125 (1, ['install', 'aboot-base']),
126 (1, ['install', 'ada-reference-manual']),
127 (1, ['install', 'fop-doc']),
128 (1, ['install', 'doc-iana']),
130 (1, ['install', 'aboot-base']),
131 (1, ['install', 'ada-reference-manual']),
132 (1, ['install', 'fop-doc']),
133 (1, ['install', 'doc-iana']),
135 (1, ['install', 'aboot-base']),
136 (1, ['install', 'ada-reference-manual']),
137 (1, ['install', 'fop-doc']),
138 (1, ['install', 'doc-iana']),
141 '5': ('Start a single bootstrap and 6 downloaders, update all to test' +
142 ' that they can all see each other.',
144 {1: ([], {'suites': 'contrib non-free'}),
145 2: ([], {'suites': 'contrib non-free'}),
146 3: ([], {'suites': 'contrib non-free'}),
147 4: ([], {'suites': 'contrib non-free'}),
148 5: ([], {'suites': 'contrib non-free'}),
149 6: ([], {'suites': 'contrib non-free'})},
158 '6': ('Test caching with multiple apt-get updates.',
167 '7': ('Test pipelining of multiple simultaneous downloads.',
171 (1, ['install', 'aboot-base', 'aap-doc', 'ada-reference-manual',
172 'aspectj-doc', 'fop-doc', 'jswat-doc', 'asis-doc',
173 'bison-doc', 'crash-whitepaper', 'doc-iana',
174 'bash-doc', 'apt-howto-common', 'autotools-dev',
175 'aptitude-doc-en', 'armagetron-common', 'asr-manpages',
176 'atomix-data', 'alcovebook-sgml-doc', 'alamin-doc',
177 'aegis-doc', 'afbackup-common', 'airstrike-common',
181 '8': ('Test pipelining of multiple simultaneous downloads with many peers.',
190 (1, ['install', 'aboot-base', 'aap-doc', 'ada-reference-manual',
191 'aspectj-doc', 'fop-doc', 'jswat-doc', 'asis-doc',
192 'bison-doc', 'crash-whitepaper', 'doc-iana',
193 'bash-doc', 'apt-howto-common', 'autotools-dev',
194 'aptitude-doc-en', 'armagetron-common', 'asr-manpages',
195 'atomix-data', 'alcovebook-sgml-doc', 'alamin-doc',
196 'aegis-doc', 'afbackup-common', 'airstrike-common',
199 (2, ['install', 'aboot-base', 'aap-doc', 'ada-reference-manual',
200 'aspectj-doc', 'fop-doc', 'jswat-doc', 'asis-doc',
201 'bison-doc', 'crash-whitepaper', 'doc-iana',
202 'bash-doc', 'apt-howto-common', 'autotools-dev',
203 'aptitude-doc-en', 'armagetron-common', 'asr-manpages',
204 'atomix-data', 'alcovebook-sgml-doc', 'alamin-doc',
205 'aegis-doc', 'afbackup-common', 'airstrike-common',
208 (3, ['install', 'aboot-base', 'aap-doc', 'ada-reference-manual',
209 'aspectj-doc', 'fop-doc', 'jswat-doc', 'asis-doc',
210 'bison-doc', 'crash-whitepaper', 'doc-iana',
211 'bash-doc', 'apt-howto-common', 'autotools-dev',
212 'aptitude-doc-en', 'armagetron-common', 'asr-manpages',
213 'atomix-data', 'alcovebook-sgml-doc', 'alamin-doc',
214 'aegis-doc', 'afbackup-common', 'airstrike-common',
217 (4, ['install', 'aboot-base', 'aap-doc', 'ada-reference-manual',
218 'aspectj-doc', 'fop-doc', 'jswat-doc', 'asis-doc',
219 'bison-doc', 'crash-whitepaper', 'doc-iana',
220 'bash-doc', 'apt-howto-common', 'autotools-dev',
221 'aptitude-doc-en', 'armagetron-common', 'asr-manpages',
222 'atomix-data', 'alcovebook-sgml-doc', 'alamin-doc',
223 'aegis-doc', 'afbackup-common', 'airstrike-common',
226 (5, ['install', 'aboot-base', 'aap-doc', 'ada-reference-manual',
227 'aspectj-doc', 'fop-doc', 'jswat-doc', 'asis-doc',
228 'bison-doc', 'crash-whitepaper', 'doc-iana',
229 'bash-doc', 'apt-howto-common', 'autotools-dev',
230 'aptitude-doc-en', 'armagetron-common', 'asr-manpages',
231 'atomix-data', 'alcovebook-sgml-doc', 'alamin-doc',
232 'aegis-doc', 'afbackup-common', 'airstrike-common',
235 (6, ['install', 'aboot-base', 'aap-doc', 'ada-reference-manual',
236 'aspectj-doc', 'fop-doc', 'jswat-doc', 'asis-doc',
237 'bison-doc', 'crash-whitepaper', 'doc-iana',
238 'bash-doc', 'apt-howto-common', 'autotools-dev',
239 'aptitude-doc-en', 'armagetron-common', 'asr-manpages',
240 'atomix-data', 'alcovebook-sgml-doc', 'alamin-doc',
241 'aegis-doc', 'afbackup-common', 'airstrike-common',
247 assert 'all' not in tests
248 assert 'help' not in tests
251 apt_conf_template = """
253 // Location of the state dir
258 userstatus "status.user";
259 cdroms "cdroms.list";
262 // Location of the cache dir
263 Cache "var/cache/apt/" {
264 Archives "archives/";
265 srcpkgcache "srcpkgcache.bin";
266 pkgcache "pkgcache.bin";
271 SourceList "sources.list";
273 Preferences "preferences";
277 // Locations of binaries
279 methods "/usr/lib/apt/methods/";
282 dpkg "/usr/bin/dpkg --simulate";
283 dpkg-source "/usr/bin/dpkg-source";
284 dpkg-buildpackage "/usr/bin/dpkg-buildpackage";
285 apt-get "/usr/bin/apt-get";
286 apt-cache "/usr/bin/apt-cache";
290 /* Options you can set to see some debugging text They correspond to names
291 of classes in the source code */
294 pkgProblemResolver "false";
295 pkgDepCache::AutoInstall "false"; // what packages apt install to satify dependencies
297 pkgAcquire::Worker "false";
298 pkgAcquire::Auth "false";
300 pkgDPkgProgressReporting "false";
301 pkgOrderList "false";
304 pkgInitialize "false"; // This one will dump the configuration space
306 Acquire::Ftp "false"; // Show ftp command traffic
307 Acquire::Http "false"; // Show http command traffic
308 Acquire::Debtorrent "false"; // Show http command traffic
309 Acquire::gpgv "false"; // Show the gpgv traffic
310 aptcdrom "false"; // Show found package files
315 apt_dht_conf_template = """
318 # Port to listen on for all requests (TCP and UDP)
321 # Directory to store the downloaded files in
322 CACHE_DIR = %(CACHE_DIR)s
324 # Other directories containing packages to share with others
325 # WARNING: all files in these directories will be hashed and available
326 # for everybody to download
329 # User name to try and run as
332 # Whether it's OK to use an IP addres from a known local/private range
335 # Which DHT implementation to use.
336 # It must be possile to do "from <DHT>.DHT import DHT" to get a class that
337 # implements the IDHT interface.
338 DHT = apt_dht_Khashmir
340 # Whether to only run the DHT (for providing only a bootstrap node)
341 DHT-ONLY = %(DHT-ONLY)s
344 # bootstrap nodes to contact to join the DHT
345 BOOTSTRAP = %(BOOTSTRAP)s
347 # whether this node is a bootstrap node
348 BOOTSTRAP_NODE = %(BOOTSTRAP_NODE)s
350 # Kademlia "K" constant, this should be an even number
353 # SHA1 is 160 bits long
356 # checkpoint every this many seconds
357 CHECKPOINT_INTERVAL = 15m
359 # concurrent xmlrpc calls per find node/value request!
362 # how many hosts to post to
365 # how many times in a row a node can fail to respond before it's booted from the routing table
368 # never ping a node more often than this
369 MIN_PING_INTERVAL = 15m
371 # refresh buckets that haven't been touched in this long
372 BUCKET_STALENESS = 1h
374 # time before expirer starts running
375 KEINITIAL_DELAY = 15s
377 # time between expirer runs
380 # expire entries older than this
383 # whether to spew info about the requests/responses in the protocol
388 """Remove all the files and directories below a top-level one.
391 @param top: the top-level directory to start at
395 for root, dirs, files in os.walk(top, topdown=False):
397 os.remove(os.path.join(root, name))
399 os.rmdir(os.path.join(root, name))
402 """Join together a list of directories into a path string.
404 @type dir: C{list} of C{string}
405 @param dir: the path to join together
407 @return: the joined together path
413 joined = os.path.join(joined, i)
417 """Create all the directories to make a path.
419 @type dir: C{list} of C{string}
420 @param dir: the path to create
423 if not os.path.exists(join(dir)):
424 os.makedirs(join(dir))
427 """Create an empty file.
429 @type path: C{list} of C{string}
430 @param path: the path to create
434 f = open(join(path), 'w')
437 def start(cmd, args, work_dir = None):
438 """Fork and start a background process running.
441 @param cmd: the name of the command to run
442 @type args: C{list} of C{string}
443 @param args: the argument to pass to the command
444 @type work_dir: C{string}
445 @param work_dir: the directory to change to to execute the child process in
446 (optional, defaults to the current directory)
448 @return: the PID of the forked process
452 new_cmd = [cmd] + args
453 pid = os.spawnvp(os.P_NOWAIT, new_cmd[0], new_cmd)
457 """Stop a forked background process that is running.
460 @param pid: the PID of the process to stop
462 @return: the return status code from the child
466 # First try a keyboard interrupt
467 os.kill(pid, signal.SIGINT)
470 (r_pid, r_value) = os.waitpid(pid, os.WNOHANG)
474 # Try a keyboard interrupt again, just in case
475 os.kill(pid, signal.SIGINT)
478 (r_pid, r_value) = os.waitpid(pid, os.WNOHANG)
483 os.kill(pid, signal.SIGTERM)
486 (r_pid, r_value) = os.waitpid(pid, os.WNOHANG)
490 # Finally a kill, don't return until killed
491 os.kill(pid, signal.SIGKILL)
494 (r_pid, r_value) = os.waitpid(pid, os.WNOHANG)
498 def apt_get(num_down, cmd):
499 """Start an apt-get process in the background.
501 The default argument specified to the apt-get invocation are
502 'apt-get -d -q -c <conf_file>'. Any additional arguments (including
503 the apt-get action to use) should be specified.
505 @type num_down: C{int}
506 @param num_down: the number of the downloader to use
507 @type cmd: C{list} of C{string}
508 @param cmd: the arguments to pass to the apt-get process
510 @return: the PID of the background process
514 print '*************** apt-get (' + str(num_down) + ') ' + ' '.join(cmd) + ' ****************'
515 apt_conf = join([down_dir(num_down), 'etc', 'apt', 'apt.conf'])
516 dpkg_status = join([down_dir(num_down), 'var', 'lib', 'dpkg', 'status'])
517 args = ['-d', '-c', apt_conf, '-o', 'Dir::state::status='+dpkg_status] + cmd
518 pid = start('apt-get', args)
521 def bootstrap_address(num_boot):
522 """Determine the bootstrap address to use for a node.
524 @type num_boot: C{int}
525 @param num_boot: the number of the bootstrap node
527 @return: the bootstrap address to use
531 return 'localhost:1' + str(num_boot) + '969'
533 def down_dir(num_down):
534 """Determine the working directory to use for a downloader.
536 @type num_down: C{int}
537 @param num_down: the number of the downloader
539 @return: the downloader's directory
543 return os.path.join(CWD,'downloader' + str(num_down))
545 def boot_dir(num_boot):
546 """Determine the working directory to use for a bootstrap node.
548 @type num_boot: C{int}
549 @param num_boot: the number of the bootstrap node
551 @return: the bootstrap node's directory
555 return os.path.join(CWD,'bootstrap' + str(num_boot))
557 def start_downloader(bootstrap_addresses, num_down, options = {},
558 mirror = 'ftp.us.debian.org/debian',
559 suites = 'main contrib non-free', clean = True):
560 """Initialize a new downloader process.
562 The default arguments specified to the downloader invocation are
563 the configuration directory, apt port, minport, maxport and the
565 Any additional arguments needed should be specified by L{options}.
567 @type num_down: C{int}
568 @param num_down: the number of the downloader to use
569 @type options: C{dictionary}
570 @param options: the dictionary of string formatting values for creating
571 the apt-dht configuration file (see L{apt_dht_conf_template} above).
572 (optional, defaults to only using the default arguments)
573 @type mirror: C{string}
574 @param mirror: the Debian mirror to use
575 (optional, defaults to 'ftp.us.debian.org/debian')
576 @type suites: C{string}
577 @param suites: space separated list of suites to download
578 (optional, defaults to 'main contrib non-free')
579 @type clean: C{boolean}
580 @param clean: whether to remove any previous downloader files
581 (optional, defaults to removing them)
583 @return: the PID of the downloader process
587 assert num_down < 100
589 print '************************** Starting Downloader ' + str(num_down) + ' **************************'
591 downloader_dir = down_dir(num_down)
599 # Create the directory structure needed by apt
600 makedirs([downloader_dir, 'etc', 'apt', 'apt.conf.d'])
601 makedirs([downloader_dir, 'var', 'lib', 'apt', 'lists', 'partial'])
602 makedirs([downloader_dir, 'var', 'lib', 'dpkg'])
603 makedirs([downloader_dir, 'var', 'cache', 'apt', 'archives', 'partial'])
604 touch([downloader_dir, 'var', 'lib', 'apt', 'lists', 'lock'])
605 touch([downloader_dir, 'var', 'lib', 'dpkg', 'lock'])
606 touch([downloader_dir, 'var', 'lib', 'dpkg', 'status'])
607 touch([downloader_dir, 'var', 'cache', 'apt', 'archives', 'lock'])
609 # Create apt's config files
610 f = open(join([downloader_dir, 'etc', 'apt', 'sources.list']), 'w')
611 f.write('deb http://localhost:1%02d77/%s/ stable %s\n' % (num_down, mirror, suites))
614 f = open(join([downloader_dir, 'etc', 'apt', 'apt.conf']), 'w')
615 f.write('Dir "' + downloader_dir + '"')
616 f.write(apt_conf_template)
619 defaults = {'PORT': '1%02d77' % num_down,
620 'CACHE_DIR': downloader_dir,
622 'BOOTSTRAP': bootstrap_addresses,
623 'BOOTSTRAP_NODE': 'no'}
626 defaults[k] = options[k]
627 f = open(join([downloader_dir, 'apt-dht.conf']), 'w')
628 f.write(apt_dht_conf_template % defaults)
631 pid = start('python', [join([sys.path[0], 'apt-dht.py']),
632 '--config-file=' + join([downloader_dir, 'apt-dht.conf']),
633 '--log-file=' + join([downloader_dir, 'apt-dht.log']),],
637 def start_bootstrap(bootstrap_addresses, num_boot, options = [], clean = True):
638 """Initialize a new bootstrap node process.
640 The default arguments specified to the apt-dht invocation are
641 the state file and port to use. Any additional arguments needed
642 should be specified by L{options}.
644 @type num_boot: C{int}
645 @param num_boot: the number of the bootstrap node to use
646 @type options: C{list} of C{string}
647 @param options: the arguments to pass to the bootstrap node
648 (optional, defaults to only using the default arguments)
649 @type clean: C{boolean}
650 @param clean: whether to remove any previous bootstrap node files
651 (optional, defaults to removing them)
653 @return: the PID of the downloader process
659 print '************************** Starting Bootstrap ' + str(num_boot) + ' **************************'
661 bootstrap_dir = boot_dir(num_boot)
669 makedirs([bootstrap_dir])
671 defaults = {'PORT': '1%d969' % num_boot,
672 'CACHE_DIR': bootstrap_dir,
674 'BOOTSTRAP': bootstrap_addresses,
675 'BOOTSTRAP_NODE': 'yes'}
678 defaults[k] = options[k]
679 f = open(join([bootstrap_dir, 'apt-dht.conf']), 'w')
680 f.write(apt_dht_conf_template % defaults)
683 pid = start('python', [join([sys.path[0], 'apt-dht.py']),
684 '--config-file=' + join([bootstrap_dir, 'apt-dht.conf']),
685 '--log-file=' + join([bootstrap_dir, 'apt-dht.log']),],
690 def run_test(bootstraps, downloaders, apt_get_queue):
691 """Run a single test.
693 @type bootstraps: C{dictionary} of {C{int}: C{list} of C{string}}
694 @param bootstraps: the bootstrap nodes to start, keys are the bootstrap numbers and
695 values are the list of options to invoke the bootstrap node with
696 @type downloaders: C{dictionary} of {C{int}: (C{int}, C{list} of C{string})}
697 @param downloaders: the downloaders to start, keys are the downloader numbers and
698 values are the list of options to invoke the downloader with
699 @type apt_get_queue: C{list} of (C{int}, C{list} of C{string})
700 @param apt_get_queue: the apt-get downloader to use and commands to execute
701 @rtype: C{list} of (C{float}, C{int})
702 @return: the execution time and returned status code for each element of apt_get_queue
706 running_bootstraps = {}
707 running_downloaders = {}
712 boot_keys = bootstraps.keys()
714 bootstrap_addresses = bootstrap_address(boot_keys[0])
715 for i in xrange(1, len(boot_keys)):
716 bootstrap_addresses += '\n ' + bootstrap_address(boot_keys[i])
718 for k, v in bootstraps.items():
719 running_bootstraps[k] = start_bootstrap(bootstrap_addresses, k, v)
723 for k, v in downloaders.items():
724 running_downloaders[k] = start_downloader(bootstrap_addresses, k, v)
728 for (num_down, cmd) in apt_get_queue:
729 running_apt_get[num_down] = apt_get(num_down, cmd)
731 (pid, r_value) = os.waitpid(running_apt_get[num_down], 0)
732 elapsed = time() - start_time
733 del running_apt_get[num_down]
734 r_value = r_value / 256
735 apt_get_results.append((elapsed, r_value))
738 print '********** apt-get completed successfully in ' + str(elapsed) + ' sec. *****************'
740 print '********** apt-get finished with status ' + str(r_value) + ' in ' + str(elapsed) + ' sec. ************'
745 print '************************** Exception occurred **************************'
747 print '************************** will attempt to shut down *******************'
749 print '*********************** shutting down the apt-gets *******************'
750 for k, v in running_apt_get.items():
752 print 'apt-get', k, stop(v)
754 print '************************** Exception occurred **************************'
759 print '*********************** shutting down the downloaders *******************'
760 for k, v in running_downloaders.items():
762 print 'downloader', k, stop(v)
764 print '************************** Exception occurred **************************'
769 print '************************** shutting down the bootstraps *******************'
770 for k, v in running_bootstraps.items():
772 print 'bootstrap', k, stop(v)
774 print '************************** Exception occurred **************************'
777 print '************************** Test Results *******************'
779 for (num_down, cmd) in apt_get_queue:
781 s = str(num_down) + ': "apt-get ' + ' '.join(cmd) + '" '
782 if len(apt_get_results) > i:
783 (elapsed, r_value) = apt_get_results[i]
784 s += 'took ' + str(elapsed) + ' secs (' + str(r_value) + ')'
786 s += 'did not complete'
789 return apt_get_results
792 """Get the usage information to display to the user.
795 @return: the usage information to display
799 s = 'Usage: ' + sys.argv[0] + ' (all|<test>|help)\n\n'
800 s += ' all - run all the tests\n'
801 s += ' help - display this usage information\n'
802 s += ' <test> - run the <test> test (see list below for valid tests)\n\n'
807 s += 'test "' + str(k) + '" - ' + v[0] + '\n'
811 if __name__ == '__main__':
812 if len(sys.argv) != 2:
814 elif sys.argv[1] == 'all':
815 for k, v in tests.items():
816 run_test(v[1], v[2], v[3])
817 elif sys.argv[1] in tests:
818 v = tests[sys.argv[1]]
819 run_test(v[1], v[2], v[3])
820 elif sys.argv[1] == 'help':
823 print 'Unknown test to run:', sys.argv[1], '\n'