Forked mumble-django project from https://bitbucket.org/Svedrin/mumble-django
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

246 lines
8.0 KiB

  1. # -*- coding: utf-8 -*-
  2. """
  3. * Copyright (C) 2009, Michael "Svedrin" Ziegler <diese-addy@funzt-halt.net>
  4. *
  5. * Mumble-Django is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This package is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. """
  15. import os, subprocess, signal
  16. from select import select
  17. from os.path import join, exists
  18. from shutil import copyfile
  19. from django.conf import settings
  20. from utils import ObjectInfo
  21. def get_available_versions():
  22. """ Return murmur versions installed inside the LAB_DIR. """
  23. dirs = os.listdir( settings.TEST_MURMUR_LAB_DIR );
  24. dirs.sort();
  25. return dirs;
  26. def run_callback( version, callback, *args, **kwargs ):
  27. """ Initialize the database and run murmur, then call the callback.
  28. After the callback has returned, kill murmur.
  29. The callback will be passed the Popen object that wraps murmur,
  30. and any arguments that were passed to run_callback.
  31. If the callback raises an exception, murmur will still be properly
  32. shutdown and the exception will be reraised.
  33. The callback can either return an arbitrary value, or a tuple.
  34. If it returns a tuple, it must be of the form:
  35. ( <any> intended_return_value, <bool> call_update_dbase )
  36. That means: If the second value evaluates to True, update_dbase
  37. will be called; the first value will be returned by run_callback.
  38. If the callback returns anything other than a tuple, that value
  39. will be returned directly.
  40. So, If run_callback should return a tuple, you will need to return
  41. the tuple form mentioned above in the callback, and put your tuple
  42. into the first parameter.
  43. """
  44. murmur_root = join( settings.TEST_MURMUR_LAB_DIR, version );
  45. if not exists( murmur_root ):
  46. raise EnvironmentError( "This version could not be found: '%s' does not exist!" % murmur_root );
  47. init_dbase( version );
  48. process = run_murmur( version );
  49. try:
  50. result = callback( process, *args, **kwargs );
  51. if type(result) == tuple:
  52. if result[1]:
  53. update_dbase( version );
  54. return result[0];
  55. else:
  56. return result;
  57. finally:
  58. kill_murmur( process );
  59. def init_dbase( version ):
  60. """ Initialize Murmur's database by copying the one from FILES_DIR. """
  61. dbasefile = join( settings.TEST_MURMUR_FILES_DIR, "murmur-%s.db3" % version );
  62. if not exists( dbasefile ):
  63. raise EnvironmentError( "This version could not be found: '%s' does not exist!" % dbasefile );
  64. murmurfile = join( settings.TEST_MURMUR_LAB_DIR, version, "murmur.sqlite" );
  65. copyfile( dbasefile, murmurfile );
  66. def update_dbase( version ):
  67. """ Copy Murmur's database to FILES_DIR (the inverse of init_dbase). """
  68. murmurfile = join( settings.TEST_MURMUR_LAB_DIR, version, "murmur.sqlite" );
  69. if not exists( murmurfile ):
  70. raise EnvironmentError( "Murmur's database could not be found: '%s' does not exist!" % murmurfile );
  71. dbasefile = join( settings.TEST_MURMUR_FILES_DIR, "murmur-%s.db3" % version );
  72. copyfile( dbasefile, target );
  73. def run_murmur( version ):
  74. """ Run the given Murmur version as a subprocess.
  75. Either returns a Popen object or raises an EnvironmentError.
  76. """
  77. murmur_root = join( settings.TEST_MURMUR_LAB_DIR, version );
  78. if not exists( murmur_root ):
  79. raise EnvironmentError( "This version could not be found: '%s' does not exist!" % murmur_root );
  80. binary_candidates = ( 'murmur.64', 'murmur.x86', 'murmurd' );
  81. files = os.listdir( murmur_root );
  82. for binname in binary_candidates:
  83. if exists( join( murmur_root, binname ) ):
  84. process = subprocess.Popen(
  85. ( join( murmur_root, binname ), '-fg' ),
  86. stdin=None, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
  87. cwd=murmur_root
  88. );
  89. # Check capabilities by waiting for certain lines to show up.
  90. capa = ObjectInfo( has_dbus=False, has_ice=False, has_instance=False, has_users=False );
  91. def canRead( self, timeout=1 ):
  92. rdy_read, rdy_write, rdy_other = select( [self.stdout], [], [], timeout );
  93. return self.stdout in rdy_read;
  94. setattr(subprocess.Popen, 'canRead', canRead)
  95. while process.canRead(0.5):
  96. line = process.stdout.readline();
  97. #print "read line:", line
  98. if line == 'DBus registration succeeded\n':
  99. capa.has_dbus = True;
  100. elif line == 'MurmurIce: Endpoint "tcp -h 127.0.0.1 -p 6502" running\n':
  101. capa.has_ice = True;
  102. elif line == '1 => Server listening on 0.0.0.0:64738\n':
  103. capa.has_instance = True;
  104. elif "> Authenticated\n" in line:
  105. capa.has_users = True;
  106. process.capabilities = capa;
  107. return process;
  108. raise EnvironmentError( "Murmur binary not found. (Tried %s)" % unicode(binary_candidates) );
  109. def wait_for_user( process, timeout=1 ):
  110. """ Wait for a user to connect. This call will consume any output from murmur
  111. until a line indicating a user's attempt to connect has been found.
  112. The timeout parameter specifies how long (in seconds) to wait for input.
  113. It defaults to 1 second. If you set this to 0 it will return at the end
  114. of input (and thereby tell you if a player has already connected). If
  115. you set this to None, the call will block until a player has connected.
  116. Returns True if a user has connected before the timeout has been hit,
  117. False otherwise.
  118. """
  119. while process.canRead( timeout ):
  120. line = process.stdout.readline();
  121. if "> Authenticated\n" in line:
  122. process.capabilities.has_users = True;
  123. return True;
  124. return False;
  125. def kill_murmur( process ):
  126. """ Send a sigterm to the given process. """
  127. return os.kill( process.pid, signal.SIGTERM );
  128. class MumbleCommandWrapper_noargs( object ):
  129. """ Mixin used to run a standard Django command inside MurmurEnvUtils.
  130. To modify a standard Django command for MEU, you will need to create
  131. a new command and derive its Command class from the wrapper, and the
  132. Command class of the original command:
  133. from django.core.management.commands.shell import Command as ShellCommand
  134. from mumble.murmurenvutils import MumbleCommandWrapper
  135. class Command( MumbleCommandWrapper, ShellCommand ):
  136. pass
  137. That will run the original command, after the user has had the chance to
  138. select the version of Murmur to run.
  139. """
  140. def _choose_version( self ):
  141. print "Choose version:";
  142. vv = get_available_versions();
  143. for idx in range(len(vv)):
  144. print " #%d %s" % ( idx, vv[idx] );
  145. chosen = int( raw_input("#> ") );
  146. return vv[chosen];
  147. def handle_noargs( self, **options ):
  148. self.origOpts = options;
  149. run_callback( self._choose_version(), self.runOrig );
  150. def runOrig( self, proc ):
  151. super( MumbleCommandWrapper_noargs, self ).handle_noargs( **self.origOpts );
  152. class MumbleCommandWrapper( object ):
  153. """ Mixin used to run a standard Django command inside MurmurEnvUtils.
  154. To modify a standard Django command for MEU, you will need to create
  155. a new command and derive its Command class from the wrapper, and the
  156. Command class of the original command:
  157. from django.core.management.commands.shell import Command as ShellCommand
  158. from mumble.murmurenvutils import MumbleCommandWrapper
  159. class Command( MumbleCommandWrapper, ShellCommand ):
  160. pass
  161. That will run the original command, after the user has had the chance to
  162. select the version of Murmur to run.
  163. """
  164. def _choose_version( self ):
  165. print "Choose version:";
  166. vv = get_available_versions();
  167. for idx in range(len(vv)):
  168. print " #%d %s" % ( idx, vv[idx] );
  169. chosen = int( raw_input("#> ") );
  170. return vv[chosen];
  171. def handle( self, *args, **options ):
  172. self.origArgs = args;
  173. self.origOpts = options;
  174. run_callback( self._choose_version(), self.runOrig );
  175. def runOrig( self, proc ):
  176. super( MumbleCommandWrapper, self ).handle( *self.origArgs, **self.origOpts );