示例#1
0
    def start(self):
        """ This method overrides Daemon.start in order to read the credentials
        when attempting to start a session. """

        # we need to read the credentials here, so that we won't attempt access
        # stdin and/or stdout after having daemonized..
        self.__usr, self.__pwd = credentials.get_credentials()
        Daemon.start(self)
示例#2
0
    def stop(self):
        """ This method overrides Daemon.stop in order to disconnect the session
        when stopping the daemon. """

        client = Client()
        client.disconnect()

        Daemon.stop(self)
示例#3
0
 def __init__(self):
     Daemon.__init__(
         self,
         get_embedded_filename(mail_config),
         secret_key,
         installation_path,
         directory,
         catcher)
示例#4
0
 def __init__(self):
     self.start_time = time.time()
     self.max_life = 86400  # 24 hours in seconds
     self.last_run = 0
     Daemon.__init__(
         self,
         get_embedded_filename(mail_config),
         secret_key,
         installation_path,
         directory,
         catcher)
     self.file_cleaner = FileCleaner('/etc/hosts', get_notifier())
示例#5
0
 def __init__(self):
     super(DaemonMonitor, self).__init__()
     self._lock = threading.Lock()
     self._daemon = Daemon(
         "torrest", os.path.join(kodi.ADDON_PATH, "resources", "bin", get_platform_arch()),
         android_extra_dirs=(xbmc.translatePath("special://xbmcbin"),),
         dest_dir=os.path.join(kodi.ADDON_DATA, "bin"),
         pid_file=os.path.join(kodi.ADDON_DATA, ".pid"),
         root=run_as_root())
     self._daemon.ensure_exec_permissions()
     self._daemon.kill_leftover_process()
     self._port = self._enabled = None
     self._settings_path = os.path.join(kodi.ADDON_DATA, self.settings_name)
     self._log_path = os.path.join(kodi.ADDON_DATA, self.log_name)
     self._settings_spec = [s for s in kodi.get_all_settings_spec() if s["id"].startswith(
         self._settings_prefix + self._settings_separator)]
     self.onSettingsChanged()
示例#6
0
    def test_xmppmotedaemon_run(self):
        """ Test the run method of the XMPPMoteDaemon, using Mox in order to
        verify proper connection procedure. """

        mock_update_handler = self.mox.CreateMockAnything()

        self.mox.StubOutWithMock(StatusProvider, "__init__")
        self.mox.StubOutWithMock(StatusProvider, "start")
        self.mox.StubOutWithMock(Client, "__init__")
        self.mox.StubOutWithMock(Client, "connect")
        self.mox.StubOutWithMock(Client, "loop")
        self.mox.StubOutWithMock(Client, "disconnect")

        self.mox.StubOutWithMock(Daemon, "start")

        self.mox.StubOutWithMock(xmppmoted.XMPPMoteDaemon,
                                 "_XMPPMoteDaemon__parse_config_file")
        self.mox.StubOutWithMock(xmppmoted.XMPPMoteDaemon,
                                 "_XMPPMoteDaemon__get_pidfile")
        self.mox.StubOutWithMock(credentials, "get_credentials")

        self.mox.StubOutWithMock(updates, "get_update_handler")

        xmppmoted.XMPPMoteDaemon._XMPPMoteDaemon__parse_config_file()
        xmppmoted.XMPPMoteDaemon._XMPPMoteDaemon__get_pidfile().AndReturn(None)

        Daemon.start(mox.IgnoreArg())

        credentials.get_credentials().AndReturn((self.__usr, self.__pwd))

        StatusProvider.__init__()
        StatusProvider.start()

        updates.get_update_handler().AndReturn(mock_update_handler)
        mock_update_handler.start()

        Client.__init__(JID(self.__usr), self.__pwd)

        Client.connect()
        Client.loop(1)
        Client.disconnect()
        self.mox.ReplayAll()

        daemon = xmppmoted.XMPPMoteDaemon()
        daemon.start()
        daemon.run()
示例#7
0
 def __init__(self):
     super(DaemonMonitor, self).__init__()
     self._lock = threading.Lock()
     self._daemon = Daemon(
         "torrest",
         os.path.join(kodi.ADDON_PATH, "resources", "bin",
                      get_platform_arch()),
         extra_dirs=(xbmc.translatePath("special://xbmcbin"), ))
     self._daemon.ensure_exec_permissions()
     self._port = self._enabled = None
     self._settings_path = os.path.join(kodi.ADDON_DATA, "settings.json")
     self._log_path = os.path.join(kodi.ADDON_DATA, "torrest.log")
     self._settings_spec = [
         s for s in kodi.get_all_settings_spec()
         if s["id"].startswith(self._settings_prefix +
                               self._settings_separator)
     ]
     self.onSettingsChanged()
示例#8
0
    def test_parse_config_file(self):
        """ Test parsing the configuration, when it exists. """

        mock_file = self.mox.CreateMockAnything()
        mock_file.name = "xmppmoterc"

        self.mox.StubOutWithMock(__builtin__, "open")
        self.mox.StubOutWithMock(ConfigurationParser, "parse")
        self.mox.StubOutWithMock(xmppmoted.XMPPMoteDaemon,
                                 "_XMPPMoteDaemon__get_pidfile")
        self.mox.StubOutWithMock(Daemon, "__init__")

        config = ConfigurationParser()
        open("xmppmoterc", "a+").AndReturn(mock_file)
        config.parse(mock_file)
        xmppmoted.XMPPMoteDaemon._XMPPMoteDaemon__get_pidfile().AndReturn(None)
        Daemon.__init__(mox.IgnoreArg(), None)

        self.mox.ReplayAll()
    
        daemon = xmppmoted.XMPPMoteDaemon()
示例#9
0
def daemon_mode(config_path):
    try:
        twit = Daemon(config_path, log=False)
        twit.spawn_watchers()
        twit.spawn_tweet_thread()
        twit.spawn_retweet_thread()
        interface = CursesInterface(twit)
        interface.run()
        while active_count() > 0:
            try:
                sleep(1)
            except Exception as e:
                twit.log_handler.emit(e, rec_type='error')
                sleep(1)
    except KeyboardInterrupt:
        exit()
示例#10
0
class DaemonMonitor(xbmc.Monitor):
    _settings_prefix = "s"
    _settings_separator = ":"
    _settings_get_uri = "settings/get"
    _settings_set_uri = "settings/set"

    def __init__(self):
        super(DaemonMonitor, self).__init__()
        self._lock = threading.Lock()
        self._daemon = Daemon(
            "torrest",
            os.path.join(kodi.ADDON_PATH, "resources", "bin",
                         get_platform_arch()),
            extra_dirs=(xbmc.translatePath("special://xbmcbin"), ))
        self._daemon.ensure_exec_permissions()
        self._port = self._enabled = None
        self._settings_path = os.path.join(kodi.ADDON_DATA, "settings.json")
        self._log_path = os.path.join(kodi.ADDON_DATA, "torrest.log")
        self._settings_spec = [
            s for s in kodi.get_all_settings_spec()
            if s["id"].startswith(self._settings_prefix +
                                  self._settings_separator)
        ]
        self.onSettingsChanged()

    def _start(self):
        self._daemon.start("-port",
                           str(self._port),
                           "-settings",
                           self._settings_path,
                           level=logging.INFO,
                           path=self._log_path)

    def _stop(self):
        self._daemon.stop()

    def _request(self, method, url, **kwargs):
        return requests.request(
            method, "http://127.0.0.1:{}/{}".format(self._port, url), **kwargs)

    def _wait(self, timeout=-1, notification=False):
        start = time.time()
        while not 0 < timeout < time.time() - start:
            try:
                self._request("get", "")
                if notification:
                    kodi.notification(kodi.translate(30104))
                return
            except requests.exceptions.ConnectionError:
                if self.waitForAbort(0.5):
                    raise AbortRequestedError("Abort requested")
        raise DaemonTimeoutError("Timeout reached")

    def _get_kodi_settings(self):
        s = kodi.generate_dict_settings(
            self._settings_spec,
            separator=self._settings_separator)[self._settings_prefix]
        s["download_path"] = xbmc.translatePath(s["download_path"])
        s["torrents_path"] = os.path.join(s["download_path"], "Torrents")
        return s

    def _get_daemon_settings(self):
        r = self._request("get", self._settings_get_uri)
        if r.status_code != 200:
            logging.error("Failed getting daemon settings with code %d: %s",
                          r.status_code, r.text)
            return None
        return r.json()

    def _update_kodi_settings(self):
        daemon_settings = self._get_daemon_settings()
        if daemon_settings is None:
            return False
        kodi.set_settings_dict(daemon_settings,
                               prefix=self._settings_prefix,
                               separator=self._settings_separator)
        return True

    def _update_daemon_settings(self):
        daemon_settings = self._get_daemon_settings()
        if daemon_settings is None:
            return False

        kodi_settings = self._get_kodi_settings()
        if daemon_settings != kodi_settings:
            logging.debug("Need to update daemon settings")
            r = self._request("post",
                              self._settings_set_uri,
                              json=kodi_settings)
            if r.status_code != 200:
                xbmcgui.Dialog().ok(kodi.translate(30102), r.json()["error"])
                return False

        return True

    def onSettingsChanged(self):
        with self._lock:
            port_changed = enabled_changed = False

            port = get_port()
            if port != self._port:
                self._port = port
                port_changed = True

            enabled = service_enabled()
            if enabled != self._enabled:
                self._enabled = enabled
                enabled_changed = True

            if self._enabled:
                if port_changed and not enabled_changed:
                    self._stop()
                if port_changed or enabled_changed:
                    self._start()
                    self._wait(timeout=get_daemon_timeout(), notification=True)
                self._update_daemon_settings()
            elif enabled_changed:
                self._stop()

    def handle_crashes(self, max_crashes=5, max_consecutive_crash_time=20):
        crash_count = 0
        last_crash = 0

        while not self.waitForAbort(1):
            # Initial check to avoid using the lock most of the time
            if self._daemon.daemon_poll() is None:
                continue

            with self._lock:
                if self._enabled and self._daemon.daemon_poll() is not None:
                    logging.info("Deamon crashed")
                    kodi.notification(kodi.translate(30105))
                    self._stop()

                    crash_time = time.time()
                    time_between_crashes = crash_time - last_crash
                    if 0 < max_consecutive_crash_time < time_between_crashes:
                        crash_count = 1
                    else:
                        crash_count += 1

                    if last_crash > 0:
                        logging.info("%s seconds passed since last crash",
                                     time_between_crashes)
                    last_crash = crash_time

                    if crash_count <= max_crashes:
                        logging.info("Re-starting daemon - %s/%s", crash_count,
                                     max_crashes)
                        self._start()
                        self._wait(timeout=get_daemon_timeout(),
                                   notification=True)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self._stop()
        return exc_type is AbortRequestedError
示例#11
0
 def __init__(self, pidfile, stdout='/dev/null', stderr='/dev/null', stdin='/dev/null', cwd='/'):
     Daemon.__init__(self, pidfile, stdout, stderr, stdin)
     self.cwd=cwd
示例#12
0
def main(command):

    modulePath = os.path.join(os.getenv('FLASKEIKON'), 'app')
    processFile = os.path.realpath(os.path.join(modulePath, 'start.py'))
    pidName = modulePath.split('\\')[-1]

    try:
        if command == 'start':
            if os.path.isfile(Daemon.pidPath(pidName)) == True:
                print('Process is already running.')
            else:
                Daemon.start(processFile, pidName)

        elif command == 'stop':
            if os.path.isfile(Daemon.pidPath(pidName)) == True:
                Daemon.stop(pidName)
            else:
                print('There is no process before.')

        elif command == 'restart':
            Daemon.stop(pidName)
            Daemon.start(processFile, pidName)

        elif command == 'status':
            pid = Daemon.status(pidName)
            print(pid)

    except Exception as err:
        print(err)
        return -1

    return 0
示例#13
0
    def __init__(self):
        self.__usr = self.__pwd =  None

        self.__parse_config_file()

        Daemon.__init__(self, self.__get_pidfile())
示例#14
0
 def __init__(self, cfg):
     self._cfg = cfg
     Daemon.__init__(self, self._cfg['pid_path'])
     self._logger = get_logger('snoopy-collector')