saranwrap.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. import cPickle as Pickle
  2. import os
  3. import struct
  4. import sys
  5. from eventlet.processes import Process, DeadProcess
  6. from eventlet import pools
  7. import warnings
  8. warnings.warn("eventlet.saranwrap is deprecated due to underuse. If you love "
  9. "it, let us know by emailing eventletdev@lists.secondlife.com",
  10. DeprecationWarning, stacklevel=2)
  11. # debugging hooks
  12. _g_debug_mode = False
  13. if _g_debug_mode:
  14. import traceback
  15. import tempfile
  16. def pythonpath_sync():
  17. """
  18. apply the current ``sys.path`` to the environment variable ``PYTHONPATH``,
  19. so that child processes have the same paths as the caller does.
  20. """
  21. pypath = os.pathsep.join(sys.path)
  22. os.environ['PYTHONPATH'] = pypath
  23. def wrap(obj, dead_callback = None):
  24. """
  25. wrap in object in another process through a saranwrap proxy
  26. :param object: The object to wrap.
  27. :dead_callback: A callable to invoke if the process exits.
  28. """
  29. if type(obj).__name__ == 'module':
  30. return wrap_module(obj.__name__, dead_callback)
  31. pythonpath_sync()
  32. if _g_debug_mode:
  33. p = Process(sys.executable,
  34. ["-W", "ignore", __file__, '--child',
  35. '--logfile', os.path.join(tempfile.gettempdir(), 'saranwrap.log')],
  36. dead_callback)
  37. else:
  38. p = Process(sys.executable, ["-W", "ignore", __file__, '--child'], dead_callback)
  39. prox = Proxy(ChildProcess(p, p))
  40. prox.obj = obj
  41. return prox.obj
  42. def wrap_module(fqname, dead_callback = None):
  43. """
  44. wrap a module in another process through a saranwrap proxy
  45. :param fqname: The fully qualified name of the module.
  46. :param dead_callback: A callable to invoke if the process exits.
  47. """
  48. pythonpath_sync()
  49. global _g_debug_mode
  50. if _g_debug_mode:
  51. p = Process(sys.executable,
  52. ["-W", "ignore", __file__, '--module', fqname,
  53. '--logfile', os.path.join(tempfile.gettempdir(), 'saranwrap.log')],
  54. dead_callback)
  55. else:
  56. p = Process(sys.executable,
  57. ["-W", "ignore", __file__, '--module', fqname,], dead_callback)
  58. prox = Proxy(ChildProcess(p,p))
  59. return prox
  60. def status(proxy):
  61. """
  62. get the status from the server through a proxy
  63. :param proxy: a :class:`eventlet.saranwrap.Proxy` object connected to a
  64. server.
  65. """
  66. return proxy.__local_dict['_cp'].make_request(Request('status', {}))
  67. class BadResponse(Exception):
  68. """This exception is raised by an saranwrap client when it could
  69. parse but cannot understand the response from the server."""
  70. pass
  71. class BadRequest(Exception):
  72. """This exception is raised by a saranwrap server when it could parse
  73. but cannot understand the response from the server."""
  74. pass
  75. class UnrecoverableError(Exception):
  76. pass
  77. class Request(object):
  78. "A wrapper class for proxy requests to the server."
  79. def __init__(self, action, param):
  80. self._action = action
  81. self._param = param
  82. def __str__(self):
  83. return "Request `"+self._action+"` "+str(self._param)
  84. def __getitem__(self, name):
  85. return self._param[name]
  86. def get(self, name, default = None):
  87. try:
  88. return self[name]
  89. except KeyError:
  90. return default
  91. def action(self):
  92. return self._action
  93. def _read_lp_hunk(stream):
  94. len_bytes = stream.read(4)
  95. if len_bytes == '':
  96. raise EOFError("No more data to read from %s" % stream)
  97. length = struct.unpack('I', len_bytes)[0]
  98. body = stream.read(length)
  99. return body
  100. def _read_response(id, attribute, input, cp):
  101. """local helper method to read respones from the rpc server."""
  102. try:
  103. str = _read_lp_hunk(input)
  104. _prnt(repr(str))
  105. response = Pickle.loads(str)
  106. except (AttributeError, DeadProcess, Pickle.UnpicklingError), e:
  107. raise UnrecoverableError(e)
  108. _prnt("response: %s" % response)
  109. if response[0] == 'value':
  110. return response[1]
  111. elif response[0] == 'callable':
  112. return CallableProxy(id, attribute, cp)
  113. elif response[0] == 'object':
  114. return ObjectProxy(cp, response[1])
  115. elif response[0] == 'exception':
  116. exp = response[1]
  117. raise exp
  118. else:
  119. raise BadResponse(response[0])
  120. def _write_lp_hunk(stream, hunk):
  121. write_length = struct.pack('I', len(hunk))
  122. stream.write(write_length + hunk)
  123. if hasattr(stream, 'flush'):
  124. stream.flush()
  125. def _write_request(param, output):
  126. _prnt("request: %s" % param)
  127. str = Pickle.dumps(param)
  128. _write_lp_hunk(output, str)
  129. def _is_local(attribute):
  130. "Return ``True`` if the attribute should be handled locally"
  131. # return attribute in ('_in', '_out', '_id', '__getattribute__',
  132. # '__setattr__', '__dict__')
  133. # good enough for now. :)
  134. if '__local_dict' in attribute:
  135. return True
  136. return False
  137. def _prnt(message):
  138. global _g_debug_mode
  139. if _g_debug_mode:
  140. print message
  141. _g_logfile = None
  142. def _log(message):
  143. global _g_logfile
  144. if _g_logfile:
  145. _g_logfile.write(str(os.getpid()) + ' ' + message + '\n')
  146. _g_logfile.flush()
  147. def _unmunge_attr_name(name):
  148. """ Sometimes attribute names come in with classname prepended, not sure why.
  149. This function removes said classname, because we're huge hackers and we didn't
  150. find out what the true right thing to do is. *TODO: find out. """
  151. if(name.startswith('_Proxy')):
  152. name = name[len('_Proxy'):]
  153. if(name.startswith('_ObjectProxy')):
  154. name = name[len('_ObjectProxy'):]
  155. return name
  156. class ChildProcess(object):
  157. """
  158. This class wraps a remote python process, presumably available in an
  159. instance of a :class:`Server`.
  160. """
  161. def __init__(self, instr, outstr, dead_list = None):
  162. """
  163. :param instr: a file-like object which supports ``read()``.
  164. :param outstr: a file-like object which supports ``write()`` and
  165. ``flush()``.
  166. :param dead_list: a list of ids of remote objects that are dead
  167. """
  168. # default dead_list inside the function because all objects in method
  169. # argument lists are init-ed only once globally
  170. _prnt("ChildProcess::__init__")
  171. if dead_list is None:
  172. dead_list = set()
  173. self._dead_list = dead_list
  174. self._in = instr
  175. self._out = outstr
  176. self._lock = pools.TokenPool(max_size=1)
  177. def make_request(self, request, attribute=None):
  178. _id = request.get('id')
  179. t = self._lock.get()
  180. try:
  181. _write_request(request, self._out)
  182. retval = _read_response(_id, attribute, self._in, self)
  183. finally:
  184. self._lock.put(t)
  185. return retval
  186. def __del__(self):
  187. self._in.close()
  188. class Proxy(object):
  189. """
  190. This is the class you will typically use as a client to a child
  191. process.
  192. Simply instantiate one around a file-like interface and start calling
  193. methods on the thing that is exported. The ``dir()`` builtin is not
  194. supported, so you have to know what has been exported.
  195. """
  196. def __init__(self, cp):
  197. """
  198. :param cp: :class:`ChildProcess` instance that wraps the i/o to the
  199. child process.
  200. """
  201. #_prnt("Proxy::__init__")
  202. self.__local_dict = dict(
  203. _cp = cp,
  204. _id = None)
  205. def __getattribute__(self, attribute):
  206. #_prnt("Proxy::__getattr__: %s" % attribute)
  207. if _is_local(attribute):
  208. # call base class getattribute so we actually get the local variable
  209. attribute = _unmunge_attr_name(attribute)
  210. return super(Proxy, self).__getattribute__(attribute)
  211. elif attribute in ('__deepcopy__', '__copy__'):
  212. # redirect copy function calls to our own versions instead of
  213. # to the proxied object
  214. return super(Proxy, self).__getattribute__('__deepcopy__')
  215. else:
  216. my_cp = self.__local_dict['_cp']
  217. my_id = self.__local_dict['_id']
  218. _dead_list = my_cp._dead_list
  219. for dead_object in _dead_list.copy():
  220. request = Request('del', {'id':dead_object})
  221. my_cp.make_request(request)
  222. try:
  223. _dead_list.remove(dead_object)
  224. except KeyError:
  225. pass
  226. # Pass all public attributes across to find out if it is
  227. # callable or a simple attribute.
  228. request = Request('getattr', {'id':my_id, 'attribute':attribute})
  229. return my_cp.make_request(request, attribute=attribute)
  230. def __setattr__(self, attribute, value):
  231. #_prnt("Proxy::__setattr__: %s" % attribute)
  232. if _is_local(attribute):
  233. # It must be local to this actual object, so we have to apply
  234. # it to the dict in a roundabout way
  235. attribute = _unmunge_attr_name(attribute)
  236. super(Proxy, self).__getattribute__('__dict__')[attribute]=value
  237. else:
  238. my_cp = self.__local_dict['_cp']
  239. my_id = self.__local_dict['_id']
  240. # Pass the set attribute across
  241. request = Request('setattr',
  242. {'id':my_id, 'attribute':attribute, 'value':value})
  243. return my_cp.make_request(request, attribute=attribute)
  244. class ObjectProxy(Proxy):
  245. """
  246. This class wraps a remote object in the :class:`Server`
  247. This class will be created during normal operation, and users should
  248. not need to deal with this class directly.
  249. """
  250. def __init__(self, cp, _id):
  251. """
  252. :param cp: A :class:`ChildProcess` object that wraps the i/o of a child
  253. process.
  254. :param _id: an identifier for the remote object. humans do not provide
  255. this.
  256. """
  257. Proxy.__init__(self, cp)
  258. self.__local_dict['_id'] = _id
  259. #_prnt("ObjectProxy::__init__ %s" % _id)
  260. def __del__(self):
  261. my_id = self.__local_dict['_id']
  262. #_prnt("ObjectProxy::__del__ %s" % my_id)
  263. self.__local_dict['_cp']._dead_list.add(my_id)
  264. def __getitem__(self, key):
  265. my_cp = self.__local_dict['_cp']
  266. my_id = self.__local_dict['_id']
  267. request = Request('getitem', {'id':my_id, 'key':key})
  268. return my_cp.make_request(request, attribute=key)
  269. def __setitem__(self, key, value):
  270. my_cp = self.__local_dict['_cp']
  271. my_id = self.__local_dict['_id']
  272. request = Request('setitem', {'id':my_id, 'key':key, 'value':value})
  273. return my_cp.make_request(request, attribute=key)
  274. def __eq__(self, rhs):
  275. my_cp = self.__local_dict['_cp']
  276. my_id = self.__local_dict['_id']
  277. request = Request('eq', {'id':my_id, 'rhs':rhs.__local_dict['_id']})
  278. return my_cp.make_request(request)
  279. def __repr__(self):
  280. # apparently repr(obj) skips the whole getattribute thing and just calls __repr__
  281. # directly. Therefore we just pass it through the normal call pipeline, and
  282. # tack on a little header so that you can tell it's an object proxy.
  283. val = self.__repr__()
  284. return "saran:%s" % val
  285. def __str__(self):
  286. # see description for __repr__, because str(obj) works the same. We don't
  287. # tack anything on to the return value here because str values are used as data.
  288. return self.__str__()
  289. def __nonzero__(self):
  290. # bool(obj) is another method that skips __getattribute__.
  291. # There's no good way to just pass
  292. # the method on, so we use a special message.
  293. my_cp = self.__local_dict['_cp']
  294. my_id = self.__local_dict['_id']
  295. request = Request('nonzero', {'id':my_id})
  296. return my_cp.make_request(request)
  297. def __len__(self):
  298. # see description for __repr__, len(obj) is the same.
  299. return self.__len__()
  300. def __contains__(self, item):
  301. # another special name that is normally called without recours to __getattribute__
  302. return self.__contains__(item)
  303. def __deepcopy__(self, memo=None):
  304. """Copies the entire external object and returns its
  305. value. Will only work if the remote object is pickleable."""
  306. my_cp = self.__local_dict['_cp']
  307. my_id = self.__local_dict['_id']
  308. request = Request('copy', {'id':my_id})
  309. return my_cp.make_request(request)
  310. # since the remote object is being serialized whole anyway,
  311. # there's no semantic difference between copy and deepcopy
  312. __copy__ = __deepcopy__
  313. def proxied_type(self):
  314. """ Returns the type of the object in the child process.
  315. Calling type(obj) on a saranwrapped object will always return
  316. <class saranwrap.ObjectProxy>, so this is a way to get at the
  317. 'real' type value."""
  318. if type(self) is not ObjectProxy:
  319. return type(self)
  320. my_cp = self.__local_dict['_cp']
  321. my_id = self.__local_dict['_id']
  322. request = Request('type', {'id':my_id})
  323. return my_cp.make_request(request)
  324. def getpid(self):
  325. """ Returns the pid of the child process. The argument should be
  326. a saranwrapped object."""
  327. my_cp = self.__local_dict['_cp']
  328. return my_cp._in.getpid()
  329. class CallableProxy(object):
  330. """
  331. This class wraps a remote function in the :class:`Server`
  332. This class will be created by an :class:`Proxy` during normal operation,
  333. and users should not need to deal with this class directly.
  334. """
  335. def __init__(self, object_id, name, cp):
  336. #_prnt("CallableProxy::__init__: %s, %s" % (object_id, name))
  337. self._object_id = object_id
  338. self._name = name
  339. self._cp = cp
  340. def __call__(self, *args, **kwargs):
  341. #_prnt("CallableProxy::__call__: %s, %s" % (args, kwargs))
  342. # Pass the call across. We never build a callable without
  343. # having already checked if the method starts with '_' so we
  344. # can safely pass this one to the remote object.
  345. #_prnt("calling %s %s" % (self._object_id, self._name)
  346. request = Request('call', {'id':self._object_id,
  347. 'name':self._name,
  348. 'args':args, 'kwargs':kwargs})
  349. return self._cp.make_request(request, attribute=self._name)
  350. class Server(object):
  351. def __init__(self, input, output, export):
  352. """
  353. :param input: a file-like object which supports ``read()``.
  354. :param output: a file-like object which supports ``write()`` and
  355. ``flush()``.
  356. :param export: an object, function, or map which is exported to clients
  357. when the id is ``None``.
  358. """
  359. #_log("Server::__init__")
  360. self._in = input
  361. self._out = output
  362. self._export = export
  363. self._next_id = 1
  364. self._objects = {}
  365. def handle_status(self, obj, req):
  366. return {
  367. 'object_count':len(self._objects),
  368. 'next_id':self._next_id,
  369. 'pid':os.getpid()}
  370. def handle_getattr(self, obj, req):
  371. try:
  372. return getattr(obj, req['attribute'])
  373. except AttributeError, e:
  374. if hasattr(obj, "__getitem__"):
  375. return obj[req['attribute']]
  376. else:
  377. raise e
  378. #_log('getattr: %s' % str(response))
  379. def handle_setattr(self, obj, req):
  380. try:
  381. return setattr(obj, req['attribute'], req['value'])
  382. except AttributeError, e:
  383. if hasattr(obj, "__setitem__"):
  384. return obj.__setitem__(req['attribute'], req['value'])
  385. else:
  386. raise e
  387. def handle_getitem(self, obj, req):
  388. return obj[req['key']]
  389. def handle_setitem(self, obj, req):
  390. obj[req['key']] = req['value']
  391. return None # *TODO figure out what the actual return value
  392. # of __setitem__ should be
  393. def handle_eq(self, obj, req):
  394. #_log("__eq__ %s %s" % (obj, req))
  395. rhs = None
  396. try:
  397. rhs = self._objects[req['rhs']]
  398. except KeyError:
  399. return False
  400. return (obj == rhs)
  401. def handle_call(self, obj, req):
  402. #_log("calling %s " % (req['name']))
  403. try:
  404. fn = getattr(obj, req['name'])
  405. except AttributeError, e:
  406. if hasattr(obj, "__setitem__"):
  407. fn = obj[req['name']]
  408. else:
  409. raise e
  410. return fn(*req['args'],**req['kwargs'])
  411. def handle_del(self, obj, req):
  412. id = req['id']
  413. _log("del %s from %s" % (id, self._objects))
  414. # *TODO what does __del__ actually return?
  415. try:
  416. del self._objects[id]
  417. except KeyError:
  418. pass
  419. return None
  420. def handle_type(self, obj, req):
  421. return type(obj)
  422. def handle_nonzero(self, obj, req):
  423. return bool(obj)
  424. def handle_copy(self, obj, req):
  425. return obj
  426. def loop(self):
  427. """Loop forever and respond to all requests."""
  428. _log("Server::loop")
  429. while True:
  430. try:
  431. try:
  432. str_ = _read_lp_hunk(self._in)
  433. except EOFError:
  434. if _g_debug_mode:
  435. _log("Exiting normally")
  436. sys.exit(0)
  437. request = Pickle.loads(str_)
  438. _log("request: %s (%s)" % (request, self._objects))
  439. req = request
  440. id = None
  441. obj = None
  442. try:
  443. id = req['id']
  444. if id:
  445. id = int(id)
  446. obj = self._objects[id]
  447. #_log("id, object: %d %s" % (id, obj))
  448. except Exception, e:
  449. #_log("Exception %s" % str(e))
  450. pass
  451. if obj is None or id is None:
  452. id = None
  453. obj = self._export()
  454. #_log("found object %s" % str(obj))
  455. # Handle the request via a method with a special name on the server
  456. handler_name = 'handle_%s' % request.action()
  457. try:
  458. handler = getattr(self, handler_name)
  459. except AttributeError:
  460. raise BadRequest, request.action()
  461. response = handler(obj, request)
  462. # figure out what to do with the response, and respond
  463. # apprpriately.
  464. if request.action() in ['status', 'type', 'copy']:
  465. # have to handle these specially since we want to
  466. # pickle up the actual value and not return a proxy
  467. self.respond(['value', response])
  468. elif callable(response):
  469. #_log("callable %s" % response)
  470. self.respond(['callable'])
  471. elif self.is_value(response):
  472. self.respond(['value', response])
  473. else:
  474. self._objects[self._next_id] = response
  475. #_log("objects: %s" % str(self._objects))
  476. self.respond(['object', self._next_id])
  477. self._next_id += 1
  478. except (KeyboardInterrupt, SystemExit), e:
  479. raise e
  480. except Exception, e:
  481. self.write_exception(e)
  482. def is_value(self, value):
  483. """
  484. Test if *value* should be serialized as a simple dataset.
  485. :param value: The value to test.
  486. :return: Returns ``True`` if *value* is a simple serializeable set of
  487. data.
  488. """
  489. return type(value) in (str,unicode,int,float,long,bool,type(None))
  490. def respond(self, body):
  491. _log("responding with: %s" % body)
  492. #_log("objects: %s" % self._objects)
  493. s = Pickle.dumps(body)
  494. _log(repr(s))
  495. _write_lp_hunk(self._out, s)
  496. def write_exception(self, e):
  497. """Helper method to respond with an exception."""
  498. #_log("exception: %s" % sys.exc_info()[0])
  499. # TODO: serialize traceback using generalization of code from mulib.htmlexception
  500. global _g_debug_mode
  501. if _g_debug_mode:
  502. _log("traceback: %s" % traceback.format_tb(sys.exc_info()[2]))
  503. self.respond(['exception', e])
  504. # test function used for testing return of unpicklable exceptions
  505. def raise_an_unpicklable_error():
  506. class Unpicklable(Exception):
  507. pass
  508. raise Unpicklable()
  509. # test function used for testing return of picklable exceptions
  510. def raise_standard_error():
  511. raise FloatingPointError()
  512. # test function to make sure print doesn't break the wrapper
  513. def print_string(str):
  514. print str
  515. # test function to make sure printing on stdout doesn't break the
  516. # wrapper
  517. def err_string(str):
  518. print >>sys.stderr, str
  519. def named(name):
  520. """Return an object given its name.
  521. The name uses a module-like syntax, eg::
  522. os.path.join
  523. or::
  524. mulib.mu.Resource
  525. """
  526. toimport = name
  527. obj = None
  528. import_err_strings = []
  529. while toimport:
  530. try:
  531. obj = __import__(toimport)
  532. break
  533. except ImportError, err:
  534. # print 'Import error on %s: %s' % (toimport, err) # debugging spam
  535. import_err_strings.append(err.__str__())
  536. toimport = '.'.join(toimport.split('.')[:-1])
  537. if obj is None:
  538. raise ImportError(
  539. '%s could not be imported. Import errors: %r' % (name, import_err_strings))
  540. for seg in name.split('.')[1:]:
  541. try:
  542. obj = getattr(obj, seg)
  543. except AttributeError:
  544. dirobj = dir(obj)
  545. dirobj.sort()
  546. raise AttributeError(
  547. 'attribute %r missing from %r (%r) %r. Import errors: %r' % (
  548. seg, obj, dirobj, name, import_err_strings))
  549. return obj
  550. def main():
  551. import optparse
  552. parser = optparse.OptionParser(
  553. usage="usage: %prog [options]",
  554. description="Simple saranwrap.Server wrapper")
  555. parser.add_option(
  556. '-c', '--child', default=False, action='store_true',
  557. help='Wrap an object serialized via setattr.')
  558. parser.add_option(
  559. '-m', '--module', type='string', dest='module', default=None,
  560. help='a module to load and export.')
  561. parser.add_option(
  562. '-l', '--logfile', type='string', dest='logfile', default=None,
  563. help='file to log to.')
  564. options, args = parser.parse_args()
  565. global _g_logfile
  566. if options.logfile:
  567. _g_logfile = open(options.logfile, 'a')
  568. from eventlet import tpool
  569. base_obj = [None]
  570. if options.module:
  571. def get_module():
  572. if base_obj[0] is None:
  573. base_obj[0] = named(options.module)
  574. return base_obj[0]
  575. server = Server(tpool.Proxy(sys.stdin),
  576. tpool.Proxy(sys.stdout),
  577. get_module)
  578. elif options.child:
  579. def get_base():
  580. if base_obj[0] is None:
  581. base_obj[0] = {}
  582. return base_obj[0]
  583. server = Server(tpool.Proxy(sys.stdin),
  584. tpool.Proxy(sys.stdout),
  585. get_base)
  586. # *HACK: some modules may emit on stderr, which breaks everything.
  587. class NullSTDOut(object):
  588. def noop(*args):
  589. pass
  590. def log_write(self, message):
  591. self.message = getattr(self, 'message', '') + message
  592. if '\n' in message:
  593. _log(self.message.rstrip())
  594. self.message = ''
  595. write = noop
  596. read = noop
  597. flush = noop
  598. sys.stderr = NullSTDOut()
  599. sys.stdout = NullSTDOut()
  600. if _g_debug_mode:
  601. sys.stdout.write = sys.stdout.log_write
  602. sys.stderr.write = sys.stderr.log_write
  603. # Loop until EOF
  604. server.loop()
  605. if _g_logfile:
  606. _g_logfile.close()
  607. if __name__ == "__main__":
  608. main()