naming.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. """
  2. Name Server and helper functions.
  3. Pyro - Python Remote Objects. Copyright by Irmen de Jong (irmen@razorvine.net).
  4. """
  5. from __future__ import print_function
  6. import warnings
  7. import re
  8. import logging
  9. import socket
  10. import sys
  11. import os
  12. import time
  13. import threading
  14. from Pyro4.errors import NamingError, PyroError, ProtocolError
  15. from Pyro4 import core, socketutil, constants
  16. from Pyro4.configuration import config
  17. from Pyro4.core import _locateNS as locateNS, _resolve as resolve # API compatibility with older versions
  18. __all__ = ["locateNS", "resolve", "type_meta", "startNSloop", "startNS"]
  19. if sys.version_info >= (3, 0):
  20. basestring = str
  21. log = logging.getLogger("Pyro4.naming")
  22. class MemoryStorage(dict):
  23. """
  24. Storage implementation that is just an in-memory dict.
  25. (because it inherits from dict it is automatically a collections.MutableMapping)
  26. Stopping the nameserver will make the server instantly forget about everything.
  27. """
  28. def __init__(self, **kwargs):
  29. super(MemoryStorage, self).__init__(**kwargs)
  30. def __setitem__(self, key, value):
  31. uri, metadata = value
  32. super(MemoryStorage, self).__setitem__(key, (uri, metadata or frozenset()))
  33. def optimized_prefix_list(self, prefix, return_metadata=False):
  34. return None
  35. def optimized_regex_list(self, regex, return_metadata=False):
  36. return None
  37. def optimized_metadata_search(self, metadata_all=None, metadata_any=None, return_metadata=False):
  38. return None
  39. def everything(self, return_metadata=False):
  40. if return_metadata:
  41. return self.copy()
  42. return {name: uri for name, (uri, metadata) in self.items()}
  43. def remove_items(self, items):
  44. for item in items:
  45. try:
  46. del self[item]
  47. except KeyError:
  48. pass
  49. def close(self):
  50. pass
  51. @core.expose
  52. class NameServer(object):
  53. """
  54. Pyro name server. Provides a simple flat name space to map logical object names to Pyro URIs.
  55. Default storage is done in an in-memory dictionary. You can provide custom storage types.
  56. """
  57. def __init__(self, storageProvider=None):
  58. self.storage = storageProvider
  59. if storageProvider is None:
  60. self.storage = MemoryStorage()
  61. log.debug("using volatile in-memory dict storage")
  62. self.lock = threading.RLock()
  63. def count(self):
  64. """Returns the number of name registrations."""
  65. return len(self.storage)
  66. def lookup(self, name, return_metadata=False):
  67. """
  68. Lookup the given name, returns an URI if found.
  69. Returns tuple (uri, metadata) if return_metadata is True.
  70. """
  71. try:
  72. uri, metadata = self.storage[name]
  73. uri = core.URI(uri)
  74. if return_metadata:
  75. metadata = list(metadata) if metadata else []
  76. return uri, metadata
  77. return uri
  78. except KeyError:
  79. raise NamingError("unknown name: " + name)
  80. def register(self, name, uri, safe=False, metadata=None):
  81. """Register a name with an URI. If safe is true, name cannot be registered twice.
  82. The uri can be a string or an URI object. Metadata must be None, or a collection of strings."""
  83. if isinstance(uri, core.URI):
  84. uri = uri.asString()
  85. elif not isinstance(uri, basestring):
  86. raise TypeError("only URIs or strings can be registered")
  87. else:
  88. core.URI(uri) # check if uri is valid
  89. if not isinstance(name, basestring):
  90. raise TypeError("name must be a str")
  91. if isinstance(metadata, basestring):
  92. raise TypeError("metadata should not be a str, but another iterable (set, list, etc)")
  93. metadata and iter(metadata) # validate that metadata is iterable
  94. with self.lock:
  95. if safe and name in self.storage:
  96. raise NamingError("name already registered: " + name)
  97. if metadata:
  98. metadata = set(metadata)
  99. self.storage[name] = uri, metadata
  100. def set_metadata(self, name, metadata):
  101. """update the metadata for an existing registration"""
  102. if not isinstance(name, basestring):
  103. raise TypeError("name must be a str")
  104. if isinstance(metadata, basestring):
  105. raise TypeError("metadata should not be a str, but another iterable (set, list, etc)")
  106. metadata and iter(metadata) # validate that metadata is iterable
  107. with self.lock:
  108. try:
  109. uri, old_meta = self.storage[name]
  110. if metadata:
  111. metadata = set(metadata)
  112. self.storage[name] = uri, metadata
  113. except KeyError:
  114. raise NamingError("unknown name: " + name)
  115. def remove(self, name=None, prefix=None, regex=None):
  116. """Remove a registration. returns the number of items removed."""
  117. if name and name in self.storage and name != constants.NAMESERVER_NAME:
  118. with self.lock:
  119. del self.storage[name]
  120. return 1
  121. if prefix:
  122. items = list(self.list(prefix=prefix).keys())
  123. if constants.NAMESERVER_NAME in items:
  124. items.remove(constants.NAMESERVER_NAME)
  125. self.storage.remove_items(items)
  126. return len(items)
  127. if regex:
  128. items = list(self.list(regex=regex).keys())
  129. if constants.NAMESERVER_NAME in items:
  130. items.remove(constants.NAMESERVER_NAME)
  131. self.storage.remove_items(items)
  132. return len(items)
  133. return 0
  134. # noinspection PyNoneFunctionAssignment
  135. def list(self, prefix=None, regex=None, metadata_all=None, metadata_any=None, return_metadata=False):
  136. """Retrieve the registered items as a dictionary name-to-URI. The URIs
  137. in the resulting dict are strings, not URI objects.
  138. You can filter by prefix or by regex or by metadata subset (separately)"""
  139. def fix_set(result):
  140. # for python 2 compatibility we cannot send sets to the default (serpent) serializer.
  141. # that's why we will convert them to lists here.
  142. if return_metadata:
  143. fixed = {}
  144. for name, data in result.items():
  145. fixed[name] = (data[0], list(data[1]))
  146. return fixed
  147. return result
  148. if sum(1 for x in [prefix, regex, metadata_all, metadata_any] if x is not None) > 1:
  149. raise ValueError("you can only filter on one thing at a time")
  150. with self.lock:
  151. if prefix:
  152. result = self.storage.optimized_prefix_list(prefix, return_metadata)
  153. if result is not None:
  154. return fix_set(result)
  155. result = {}
  156. for name in self.storage:
  157. if name.startswith(prefix):
  158. result[name] = self.storage[name] if return_metadata else self.storage[name][0]
  159. return fix_set(result)
  160. elif regex:
  161. result = self.storage.optimized_regex_list(regex, return_metadata)
  162. if result is not None:
  163. return fix_set(result)
  164. result = {}
  165. try:
  166. regex = re.compile(regex)
  167. except re.error as x:
  168. raise NamingError("invalid regex: " + str(x))
  169. else:
  170. for name in self.storage:
  171. if regex.match(name):
  172. result[name] = self.storage[name] if return_metadata else self.storage[name][0]
  173. return fix_set(result)
  174. elif metadata_all:
  175. # return the entries which have all of the given metadata as (a subset of) their metadata
  176. if isinstance(metadata_all, basestring):
  177. raise TypeError("metadata_all should not be a str, but another iterable (set, list, etc)")
  178. metadata_all and iter(metadata_all) # validate that metadata is iterable
  179. result = self.storage.optimized_metadata_search(metadata_all=metadata_all, return_metadata=return_metadata)
  180. if result is not None:
  181. return fix_set(result)
  182. metadata_all = frozenset(metadata_all)
  183. result = {}
  184. for name, (uri, meta) in self.storage.everything(return_metadata=True).items():
  185. if metadata_all.issubset(meta):
  186. result[name] = (uri, meta) if return_metadata else uri
  187. return fix_set(result)
  188. elif metadata_any:
  189. # return the entries which have any of the given metadata as part of their metadata
  190. if isinstance(metadata_any, basestring):
  191. raise TypeError("metadata_any should not be a str, but another iterable (set, list, etc)")
  192. metadata_any and iter(metadata_any) # validate that metadata is iterable
  193. result = self.storage.optimized_metadata_search(metadata_any=metadata_any, return_metadata=return_metadata)
  194. if result is not None:
  195. return fix_set(result)
  196. metadata_any = frozenset(metadata_any)
  197. result = {}
  198. for name, (uri, meta) in self.storage.everything(return_metadata=True).items():
  199. if metadata_any & meta:
  200. result[name] = (uri, meta) if return_metadata else uri
  201. return fix_set(result)
  202. else:
  203. # just return (a copy of) everything
  204. return fix_set(self.storage.everything(return_metadata))
  205. def ping(self):
  206. """A simple test method to check if the name server is running correctly."""
  207. pass
  208. class NameServerDaemon(core.Daemon):
  209. """Daemon that contains the Name Server."""
  210. def __init__(self, host=None, port=None, unixsocket=None, nathost=None, natport=None, storage=None):
  211. if host is None:
  212. host = config.HOST
  213. if port is None:
  214. port = config.NS_PORT
  215. if nathost is None:
  216. nathost = config.NATHOST
  217. if natport is None:
  218. natport = config.NATPORT or None
  219. storage = storage or "memory"
  220. if storage == "memory":
  221. log.debug("using volatile in-memory dict storage")
  222. self.nameserver = NameServer(MemoryStorage())
  223. elif storage.startswith("dbm:") and len(storage) > 4:
  224. dbmfile = storage[4:]
  225. log.debug("using persistent dbm storage in file %s", dbmfile)
  226. from Pyro4.naming_storage import DbmStorage
  227. self.nameserver = NameServer(DbmStorage(dbmfile))
  228. warning = "Warning: the DbmStorage doesn't support metadata."
  229. log.warning(warning)
  230. print(warning)
  231. elif storage.startswith("sql:") and len(storage) > 4:
  232. sqlfile = storage[4:]
  233. log.debug("using persistent sql storage in file %s", sqlfile)
  234. from Pyro4.naming_storage import SqlStorage
  235. self.nameserver = NameServer(SqlStorage(sqlfile))
  236. else:
  237. raise ValueError("invalid storage type '%s'" % storage)
  238. existing_count = self.nameserver.count()
  239. if existing_count > 0:
  240. log.debug("number of existing entries in storage: %d", existing_count)
  241. super(NameServerDaemon, self).__init__(host, port, unixsocket, nathost=nathost, natport=natport)
  242. self.register(self.nameserver, constants.NAMESERVER_NAME)
  243. metadata = {"class:Pyro4.naming.NameServer"}
  244. self.nameserver.register(constants.NAMESERVER_NAME, self.uriFor(self.nameserver), metadata=metadata)
  245. if config.NS_AUTOCLEAN > 0:
  246. if not AutoCleaner.override_autoclean_min and config.NS_AUTOCLEAN < AutoCleaner.min_autoclean_value:
  247. raise ValueError("NS_AUTOCLEAN cannot be smaller than " + str(AutoCleaner.min_autoclean_value))
  248. log.debug("autoclean enabled")
  249. self.cleaner_thread = AutoCleaner(self.nameserver)
  250. self.cleaner_thread.start()
  251. else:
  252. log.debug("autoclean not enabled")
  253. self.cleaner_thread = None
  254. log.info("nameserver daemon created")
  255. def close(self):
  256. super(NameServerDaemon, self).close()
  257. if self.nameserver is not None:
  258. self.nameserver.storage.close()
  259. self.nameserver = None
  260. if self.cleaner_thread:
  261. self.cleaner_thread.stop = True
  262. self.cleaner_thread.join()
  263. self.cleaner_thread = None
  264. def __enter__(self):
  265. if not self.nameserver:
  266. raise PyroError("cannot reuse this object")
  267. return self
  268. def __exit__(self, exc_type, exc_value, traceback):
  269. if self.nameserver is not None:
  270. self.nameserver.storage.close()
  271. self.nameserver = None
  272. if self.cleaner_thread:
  273. self.cleaner_thread.stop = True
  274. self.cleaner_thread.join()
  275. self.cleaner_thread = None
  276. return super(NameServerDaemon, self).__exit__(exc_type, exc_value, traceback)
  277. def handleRequest(self, conn):
  278. try:
  279. return super(NameServerDaemon, self).handleRequest(conn)
  280. except ProtocolError as x:
  281. # Notify the user that a protocol error occurred.
  282. # This is useful for instance when a wrong serializer is used, it helps
  283. # a lot to immediately see what is going wrong.
  284. warnings.warn("Pyro protocol error occurred: " + str(x))
  285. raise
  286. class AutoCleaner(threading.Thread):
  287. """
  288. Takes care of checking every registration in the name server.
  289. If it cannot be contacted anymore, it will be removed after ~20 seconds.
  290. """
  291. min_autoclean_value = 3
  292. max_unreachable_time = 20.0
  293. loop_delay = 2.0
  294. override_autoclean_min = False # only for unit test purposes
  295. def __init__(self, nameserver):
  296. assert config.NS_AUTOCLEAN > 0
  297. if not self.override_autoclean_min and config.NS_AUTOCLEAN < self.min_autoclean_value:
  298. raise ValueError("NS_AUTOCLEAN cannot be smaller than " + str(self.min_autoclean_value))
  299. super(AutoCleaner, self).__init__()
  300. self.nameserver = nameserver
  301. self.stop = False
  302. self.daemon = True
  303. self.last_cleaned = time.time()
  304. self.unreachable = {} # name->since when
  305. def run(self):
  306. while not self.stop:
  307. time.sleep(self.loop_delay)
  308. time_since_last_autoclean = time.time() - self.last_cleaned
  309. if time_since_last_autoclean < config.NS_AUTOCLEAN:
  310. continue
  311. for name, uri in self.nameserver.list().items():
  312. if name in (constants.DAEMON_NAME, constants.NAMESERVER_NAME):
  313. continue
  314. try:
  315. uri_obj = core.URI(uri)
  316. timeout = config.COMMTIMEOUT or 5
  317. sock = socketutil.createSocket(connect=(uri_obj.host, uri_obj.port), timeout=timeout)
  318. sock.close()
  319. # if we get here, the listed server is still answering on its port
  320. if name in self.unreachable:
  321. del self.unreachable[name]
  322. except socket.error:
  323. if name not in self.unreachable:
  324. self.unreachable[name] = time.time()
  325. if time.time() - self.unreachable[name] >= self.max_unreachable_time:
  326. log.info("autoclean: unregistering %s; cannot connect uri %s for %d sec", name, uri, self.max_unreachable_time)
  327. self.nameserver.remove(name)
  328. del self.unreachable[name]
  329. continue
  330. self.last_cleaned = time.time()
  331. if self.unreachable:
  332. log.debug("autoclean: %d/%d names currently unreachable", len(self.unreachable), self.nameserver.count())
  333. class BroadcastServer(object):
  334. class TransportServerAdapter(object):
  335. # this adapter is used to be able to pass the BroadcastServer to Daemon.combine() to integrate the event loops.
  336. def __init__(self, bcserver):
  337. self.sockets = [bcserver]
  338. def events(self, eventobjects):
  339. for bc in eventobjects:
  340. bc.processRequest()
  341. def __init__(self, nsUri, bchost=None, bcport=None, ipv6=False):
  342. self.transportServer = self.TransportServerAdapter(self)
  343. self.nsUri = nsUri
  344. if bcport is None:
  345. bcport = config.NS_BCPORT
  346. if bchost is None:
  347. bchost = config.NS_BCHOST
  348. if ":" in nsUri.host or ipv6: # match nameserver's ip version
  349. bchost = bchost or "::"
  350. self.sock = socketutil.createBroadcastSocket((bchost, bcport, 0, 0), reuseaddr=config.SOCK_REUSE, timeout=2.0)
  351. else:
  352. self.sock = socketutil.createBroadcastSocket((bchost, bcport), reuseaddr=config.SOCK_REUSE, timeout=2.0)
  353. self._sockaddr = self.sock.getsockname()
  354. bchost = bchost or self._sockaddr[0]
  355. bcport = bcport or self._sockaddr[1]
  356. if ":" in bchost: # ipv6
  357. self.locationStr = "[%s]:%d" % (bchost, bcport)
  358. else:
  359. self.locationStr = "%s:%d" % (bchost, bcport)
  360. log.info("ns broadcast server created on %s - %s", self.locationStr, socketutil.family_str(self.sock))
  361. self.running = True
  362. def close(self):
  363. log.debug("ns broadcast server closing")
  364. self.running = False
  365. try:
  366. self.sock.shutdown(socket.SHUT_RDWR)
  367. except (OSError, socket.error):
  368. pass
  369. self.sock.close()
  370. def getPort(self):
  371. return self.sock.getsockname()[1]
  372. def fileno(self):
  373. return self.sock.fileno()
  374. def runInThread(self):
  375. """Run the broadcast server loop in its own thread."""
  376. thread = threading.Thread(target=self.__requestLoop)
  377. thread.setDaemon(True)
  378. thread.start()
  379. log.debug("broadcast server loop running in own thread")
  380. return thread
  381. def __requestLoop(self):
  382. while self.running:
  383. self.processRequest()
  384. log.debug("broadcast server loop terminating")
  385. def processRequest(self):
  386. try:
  387. data, addr = self.sock.recvfrom(100)
  388. if data == b"GET_NSURI":
  389. responsedata = core.URI(self.nsUri)
  390. if responsedata.host == "0.0.0.0":
  391. # replace INADDR_ANY address by the interface IP address that connects to the requesting client
  392. try:
  393. interface_ip = socketutil.getInterfaceAddress(addr[0])
  394. responsedata.host = interface_ip
  395. except socket.error:
  396. pass
  397. log.debug("responding to broadcast request from %s: interface %s", addr[0], responsedata.host)
  398. responsedata = str(responsedata).encode("iso-8859-1")
  399. self.sock.sendto(responsedata, 0, addr)
  400. except socket.error:
  401. pass
  402. except SystemError:
  403. if sys.platform == "cli" and not self.running:
  404. # ironpython throws these systemerrors when shutting down... we can ignore them.
  405. pass
  406. else:
  407. raise
  408. def __enter__(self):
  409. return self
  410. def __exit__(self, exc_type, exc_value, traceback):
  411. self.close()
  412. def startNSloop(host=None, port=None, enableBroadcast=True, bchost=None, bcport=None,
  413. unixsocket=None, nathost=None, natport=None, storage=None, hmac=None):
  414. """utility function that starts a new Name server and enters its requestloop."""
  415. daemon = NameServerDaemon(host, port, unixsocket, nathost=nathost, natport=natport, storage=storage)
  416. daemon._pyroHmacKey = hmac
  417. nsUri = daemon.uriFor(daemon.nameserver)
  418. internalUri = daemon.uriFor(daemon.nameserver, nat=False)
  419. bcserver = None
  420. if unixsocket:
  421. hostip = "Unix domain socket"
  422. else:
  423. hostip = daemon.sock.getsockname()[0]
  424. if daemon.sock.family == socket.AF_INET6: # ipv6 doesn't have broadcast. We should probably use multicast instead...
  425. print("Not starting broadcast server for IPv6.")
  426. log.info("Not starting NS broadcast server because NS is using IPv6")
  427. enableBroadcast = False
  428. elif hostip.startswith("127.") or hostip == "::1":
  429. print("Not starting broadcast server for localhost.")
  430. log.info("Not starting NS broadcast server because NS is bound to localhost")
  431. enableBroadcast = False
  432. if enableBroadcast:
  433. # Make sure to pass the internal uri to the broadcast responder.
  434. # It is almost always useless to let it return the external uri,
  435. # because external systems won't be able to talk to this thing anyway.
  436. bcserver = BroadcastServer(internalUri, bchost, bcport, ipv6=daemon.sock.family == socket.AF_INET6)
  437. print("Broadcast server running on %s" % bcserver.locationStr)
  438. bcserver.runInThread()
  439. existing = daemon.nameserver.count()
  440. if existing > 1: # don't count our own nameserver registration
  441. print("Persistent store contains %d existing registrations." % existing)
  442. print("NS running on %s (%s)" % (daemon.locationStr, hostip))
  443. if not hmac:
  444. print("Warning: HMAC key not set. Anyone can connect to this server!")
  445. if daemon.natLocationStr:
  446. print("internal URI = %s" % internalUri)
  447. print("external URI = %s" % nsUri)
  448. else:
  449. print("URI = %s" % nsUri)
  450. try:
  451. daemon.requestLoop()
  452. finally:
  453. daemon.close()
  454. if bcserver is not None:
  455. bcserver.close()
  456. print("NS shut down.")
  457. def startNS(host=None, port=None, enableBroadcast=True, bchost=None, bcport=None,
  458. unixsocket=None, nathost=None, natport=None, storage=None, hmac=None):
  459. """utility fuction to quickly get a Name server daemon to be used in your own event loops.
  460. Returns (nameserverUri, nameserverDaemon, broadcastServer)."""
  461. daemon = NameServerDaemon(host, port, unixsocket, nathost=nathost, natport=natport, storage=storage)
  462. daemon._pyroHmacKey = hmac
  463. bcserver = None
  464. nsUri = daemon.uriFor(daemon.nameserver)
  465. if not unixsocket:
  466. hostip = daemon.sock.getsockname()[0]
  467. if hostip.startswith("127."):
  468. # not starting broadcast server for localhost.
  469. enableBroadcast = False
  470. if enableBroadcast:
  471. internalUri = daemon.uriFor(daemon.nameserver, nat=False)
  472. bcserver = BroadcastServer(internalUri, bchost, bcport, ipv6=daemon.sock.family == socket.AF_INET6)
  473. return nsUri, daemon, bcserver
  474. def type_meta(class_or_object, prefix="class:"):
  475. """extracts type metadata from the given class or object, can be used as Name server metadata."""
  476. if hasattr(class_or_object, "__mro__"):
  477. return {prefix + c.__module__ + "." + c.__name__
  478. for c in class_or_object.__mro__ if c.__module__ not in ("builtins", "__builtin__")}
  479. if hasattr(class_or_object, "__class__"):
  480. return type_meta(class_or_object.__class__)
  481. return frozenset()
  482. def main(args=None):
  483. from optparse import OptionParser
  484. parser = OptionParser()
  485. parser.add_option("-n", "--host", dest="host", help="hostname to bind server on")
  486. parser.add_option("-p", "--port", dest="port", type="int", help="port to bind server on (0=random)")
  487. parser.add_option("-u", "--unixsocket", help="Unix domain socket name to bind server on")
  488. parser.add_option("-s", "--storage", help="Storage system to use (memory, dbm:file, sql:file)", default="memory")
  489. parser.add_option("", "--bchost", dest="bchost", help="hostname to bind broadcast server on (default is \"\")")
  490. parser.add_option("", "--bcport", dest="bcport", type="int",
  491. help="port to bind broadcast server on (0=random)")
  492. parser.add_option("", "--nathost", dest="nathost", help="external hostname in case of NAT")
  493. parser.add_option("", "--natport", dest="natport", type="int", help="external port in case of NAT")
  494. parser.add_option("-x", "--nobc", dest="enablebc", action="store_false", default=True,
  495. help="don't start a broadcast server")
  496. parser.add_option("-k", "--key", help="the HMAC key to use (deprecated)")
  497. options, args = parser.parse_args(args)
  498. if options.key:
  499. warnings.warn("using -k to supply HMAC key on the command line is a security problem "
  500. "and is deprecated since Pyro 4.72. See the documentation for an alternative.")
  501. if "PYRO_HMAC_KEY" in os.environ:
  502. if options.key:
  503. raise SystemExit("error: don't use -k and PYRO_HMAC_KEY at the same time")
  504. options.key = os.environ["PYRO_HMAC_KEY"]
  505. startNSloop(options.host, options.port, enableBroadcast=options.enablebc,
  506. bchost=options.bchost, bcport=options.bcport, unixsocket=options.unixsocket,
  507. nathost=options.nathost, natport=options.natport, storage=options.storage,
  508. hmac=options.key)
  509. if __name__ == "__main__":
  510. main()