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.

245 lines
8.7 KiB

  1. # -*- coding: utf-8 -*-
  2. # kate: space-indent on; indent-width 4; replace-tabs on;
  3. """
  4. * Copyright © 2009-2010, Michael "Svedrin" Ziegler <diese-addy@funzt-halt.net>
  5. *
  6. * Mumble-Django is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This package is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. """
  16. import os, subprocess, signal
  17. from select import select
  18. from os.path import join, exists
  19. from shutil import copyfile
  20. from django.conf import settings
  21. from utils import ObjectInfo
  22. def get_available_versions():
  23. """ Return murmur versions installed inside the LAB_DIR. """
  24. dirs = os.listdir( settings.TEST_MURMUR_LAB_DIR )
  25. dirs.sort()
  26. return dirs
  27. def run_callback( version, callback, *args, **kwargs ):
  28. """ Initialize the database and run murmur, then call the callback.
  29. After the callback has returned, kill murmur.
  30. The callback will be passed the Popen object that wraps murmur,
  31. and any arguments that were passed to run_callback.
  32. If the callback raises an exception, murmur will still be properly
  33. shutdown and the exception will be reraised.
  34. The callback can either return an arbitrary value, or a tuple.
  35. If it returns a tuple, it must be of the form:
  36. ( <any> intended_return_value, <bool> call_update_dbase )
  37. That means: If the second value evaluates to True, update_dbase
  38. will be called; the first value will be returned by run_callback.
  39. If the callback returns anything other than a tuple, that value
  40. will be returned directly.
  41. So, If run_callback should return a tuple, you will need to return
  42. the tuple form mentioned above in the callback, and put your tuple
  43. into the first parameter.
  44. """
  45. murmur_root = join( settings.TEST_MURMUR_LAB_DIR, version )
  46. if not exists( murmur_root ):
  47. raise EnvironmentError( "This version could not be found: '%s' does not exist!" % murmur_root )
  48. init_dbase( version )
  49. process = run_murmur( version )
  50. try:
  51. result = callback( process, *args, **kwargs )
  52. if type(result) == tuple:
  53. if result[1]:
  54. update_dbase( version )
  55. return result[0]
  56. else:
  57. return result
  58. finally:
  59. kill_murmur( process )
  60. def init_dbase( version ):
  61. """ Initialize Murmur's database by copying the one from FILES_DIR. """
  62. dbasefile = join( settings.TEST_MURMUR_FILES_DIR, "murmur-%s.db3" % version )
  63. if not exists( dbasefile ):
  64. raise EnvironmentError( "This version could not be found: '%s' does not exist!" % dbasefile )
  65. murmurfile = join( settings.TEST_MURMUR_LAB_DIR, version, "murmur.sqlite" )
  66. copyfile( dbasefile, murmurfile )
  67. def update_dbase( version ):
  68. """ Copy Murmur's database to FILES_DIR (the inverse of init_dbase). """
  69. murmurfile = join( settings.TEST_MURMUR_LAB_DIR, version, "murmur.sqlite" )
  70. if not exists( murmurfile ):
  71. raise EnvironmentError( "Murmur's database could not be found: '%s' does not exist!" % murmurfile )
  72. dbasefile = join( settings.TEST_MURMUR_FILES_DIR, "murmur-%s.db3" % version )
  73. copyfile( murmurfile, dbasefile )
  74. def run_murmur( version ):
  75. """ Run the given Murmur version as a subprocess.
  76. Either returns a Popen object or raises an EnvironmentError.
  77. """
  78. murmur_root = join( settings.TEST_MURMUR_LAB_DIR, version )
  79. if not exists( murmur_root ):
  80. raise EnvironmentError( "This version could not be found: '%s' does not exist!" % murmur_root )
  81. binary_candidates = ( 'murmur.64', 'murmur.x86', 'murmurd' )
  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 )