launcher.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. import os, sys
  2. import logging
  3. import logging.config
  4. from ..monitor import pure as mmp
  5. from ..monitor.exceptions import FailedToObtainLocale, FailedToSetLocale
  6. from ..monitor.log import get_logger, setup_logging
  7. from std_err_override import LogWriter
  8. from ..saas.thread import InstanceThread, user, apc, getsig
  9. from ..monitor.log import Loggable
  10. from ..monitor.exceptions import CouldNotCreateIndexFile
  11. from ..monitor.toucher import ToucherThread
  12. from ..monitor.airtime import AirtimeNotifier, AirtimeMessageReceiver
  13. from ..monitor.watchersyncer import WatchSyncer
  14. from ..monitor.eventdrainer import EventDrainer
  15. from ..monitor.manager import Manager
  16. from ..monitor.syncdb import AirtimeDB
  17. from airtimeinstance import AirtimeInstance
  18. class MM2(InstanceThread, Loggable):
  19. def index_create(self, index_create_attempt=False):
  20. config = user().mm_config
  21. if not index_create_attempt:
  22. if not os.path.exists(config['media-monitor']['index_path']):
  23. self.logger.info("Attempting to create index file:...")
  24. try:
  25. with open(config['media-monitor']['index_path'], 'w') as f: f.write(" ")
  26. except Exception as e:
  27. self.logger.info("Failed to create index file with exception: %s" \
  28. % str(e))
  29. else:
  30. self.logger.info("Created index file, reloading configuration:")
  31. self.index_create(index_create_attempt=True)
  32. else:
  33. self.logger.info("Already tried to create index. Will not try again ")
  34. if not os.path.exists(config['media-monitor']['index_path']):
  35. raise CouldNotCreateIndexFile(config['media-monitor']['index_path'])
  36. def run(self):
  37. self.index_create()
  38. manager = Manager()
  39. apiclient = apc()
  40. config = user().mm_config
  41. WatchSyncer(signal=getsig('watch'),
  42. chunking_number=config['media-monitor']['chunking_number'],
  43. timeout=config['media-monitor']['request_max_wait'])
  44. airtime_receiver = AirtimeMessageReceiver(config,manager)
  45. airtime_notifier = AirtimeNotifier(config, airtime_receiver)
  46. adb = AirtimeDB(apiclient)
  47. store = {
  48. u'stor' : adb.storage_path(),
  49. u'watched_dirs' : adb.list_watched(),
  50. }
  51. self.logger.info("initializing mm with directories: %s" % str(store))
  52. self.logger.info(
  53. "Initing with the following airtime response:%s" % str(store))
  54. airtime_receiver.change_storage({ 'directory':store[u'stor'] })
  55. for watch_dir in store[u'watched_dirs']:
  56. if not os.path.exists(watch_dir):
  57. # Create the watch_directory here
  58. try: os.makedirs(watch_dir)
  59. except Exception:
  60. self.logger.error("Could not create watch directory: '%s' \
  61. (given from the database)." % watch_dir)
  62. if os.path.exists(watch_dir):
  63. airtime_receiver.new_watch({ 'directory':watch_dir }, restart=True)
  64. else: self.logger.info("Failed to add watch on %s" % str(watch_dir))
  65. EventDrainer(airtime_notifier,
  66. interval=float(config['media-monitor']['rmq_event_wait']))
  67. # Launch the toucher that updates the last time when the script was
  68. # ran every n seconds.
  69. # TODO : verify that this does not interfere with bootstrapping because the
  70. # toucher thread might update the last_ran variable too fast
  71. ToucherThread(path=user().touch_file_path(),
  72. interval=int(config['media-monitor']['touch_interval']))
  73. success = False
  74. while not success:
  75. try:
  76. apiclient.register_component('media-monitor')
  77. success = True
  78. except Exception, e:
  79. self.logger.error(str(e))
  80. import time
  81. time.sleep(10)
  82. manager.loop()
  83. def launch_instance(name, root, global_cfg):
  84. cfg = {
  85. 'api_client' : global_cfg,
  86. 'media_monitor' : global_cfg,
  87. }
  88. ai = AirtimeInstance(name, root, cfg)
  89. MM2(ai).start()
  90. def setup_global(log):
  91. """ setup unicode and other stuff """
  92. log.info("Attempting to set the locale...")
  93. try: mmp.configure_locale(mmp.get_system_locale())
  94. except FailedToSetLocale as e:
  95. log.info("Failed to set the locale...")
  96. sys.exit(1)
  97. except FailedToObtainLocale as e:
  98. log.info("Failed to obtain the locale form the default path: \
  99. '/etc/default/locale'")
  100. sys.exit(1)
  101. except Exception as e:
  102. log.info("Failed to set the locale for unknown reason. \
  103. Logging exception.")
  104. log.info(str(e))
  105. def setup_logger(log_config, logpath):
  106. logging.config.fileConfig(log_config)
  107. #need to wait for Python 2.7 for this..
  108. #logging.captureWarnings(True)
  109. logger = logging.getLogger()
  110. LogWriter.override_std_err(logger)
  111. logfile = unicode(logpath)
  112. setup_logging(logfile)
  113. log = get_logger()
  114. return log