Пример #1
0
    def __init__(self,
                 verbose=False,
                 log_dir=None,
                 console_log=False,
                 run_dir=None,
                 config_file=None,
                 test_dir=None):

        # Check if process exists
        exit_code = subprocess.call(['pgrep', 'razer-service'],
                                    stderr=subprocess.DEVNULL,
                                    stdout=subprocess.DEVNULL)

        if exit_code == 0:
            print("Daemon already exists. Please stop that one.",
                  file=sys.stderr)
            exit(-1)

        setproctitle.setproctitle('razer-service')

        # Expanding ~ as python doesnt do it by default, also creating dirs if needed
        if log_dir is not None:
            log_dir = os.path.expanduser(log_dir)
            os.makedirs(log_dir, mode=0o750, exist_ok=True)
        if run_dir is not None:
            run_dir = os.path.expanduser(run_dir)
            os.makedirs(run_dir, mode=0o750, exist_ok=True)
        if config_file is not None:
            config_file = os.path.expanduser(config_file)
            os.makedirs(os.path.dirname(config_file),
                        mode=0o750,
                        exist_ok=True)

        self._test_dir = test_dir
        self._data_dir = run_dir
        self._config_file = config_file
        self._config = configparser.ConfigParser()
        self.read_config(config_file)

        # Setup DBus to use gobject main loop
        dbus.mainloop.glib.threads_init()
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        DBusService.__init__(self, self.BUS_PATH, '/org/razer')

        self._init_signals()
        self._main_loop = GObject.MainLoop()

        # Listen for input events from udev
        self._udev_context = Context()
        udev_monitor = Monitor.from_netlink(self._udev_context)
        udev_monitor.filter_by(subsystem='input')
        self._udev_observer = MonitorObserver(udev_monitor,
                                              callback=self._udev_input_event,
                                              name='device-monitor')

        # Logging
        logging_level = logging.INFO
        if verbose or self._config.getboolean('General', 'verbose_logging'):
            logging_level = logging.DEBUG

        self.logger = logging.getLogger('razer')
        self.logger.setLevel(logging_level)
        formatter = logging.Formatter(
            '%(asctime)s | %(name)-30s | %(levelname)-8s | %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S')
        # Dont propagate to default logger
        self.logger.propagate = 0

        if console_log:
            console_logger = logging.StreamHandler()
            console_logger.setLevel(logging_level)
            console_logger.setFormatter(formatter)
            self.logger.addHandler(console_logger)

        if log_dir is not None:
            log_file = os.path.join(log_dir, 'razer.log')
            file_logger = logging.handlers.RotatingFileHandler(
                log_file, maxBytes=16777216, backupCount=10)  # 16MiB
            file_logger.setLevel(logging_level)
            file_logger.setFormatter(formatter)
            self.logger.addHandler(file_logger)

        self.logger.info("Initialising Daemon (v%s). Pid: %d", __version__,
                         os.getpid())

        # Setup screensaver thread
        self._screensaver_thread = ScreensaverThread(
            self,
            active=self._config.getboolean('Startup',
                                           'devices_off_on_screensaver'))
        self._screensaver_thread.start()

        self._razer_devices = DeviceCollection()
        self._load_devices(first_run=True)

        # Add DBus methods
        self.logger.info("Adding razer.devices.getDevices method to DBus")
        self.add_dbus_method('razer.devices',
                             'getDevices',
                             self.get_serial_list,
                             out_signature='as')
        self.logger.info(
            "Adding razer.devices.enableTurnOffOnScreensaver method to DBus")
        self.add_dbus_method('razer.devices', 'enableTurnOffOnScreensaver',
                             self.enable_turn_off_on_screensaver)
        self.logger.info(
            "Adding razer.devices.disableTurnOffOnScreensaver method to DBus")
        self.add_dbus_method('razer.devices', 'disableTurnOffOnScreensaver',
                             self.disable_turn_off_on_screensaver)
        self.logger.info("Adding razer.devices.syncEffects method to DBus")
        self.add_dbus_method('razer.devices',
                             'syncEffects',
                             self.sync_effects,
                             in_signature='b')
        self.logger.info("Adding razer.daemon.version method to DBus")
        self.add_dbus_method('razer.daemon',
                             'version',
                             self.version,
                             out_signature='s')
        self.logger.info("Adding razer.daemon.stop method to DBus")
        self.add_dbus_method('razer.daemon', 'stop', self.stop)

        # TODO remove
        self.sync_effects(
            self._config.getboolean('Startup', 'sync_effects_enabled'))
Пример #2
0
    def __init__(self,
                 verbose=False,
                 log_dir=None,
                 console_log=False,
                 run_dir=None,
                 config_file=None,
                 test_dir=None):

        # Check if process exists and is not running as current user
        proc = subprocess.Popen(['pgrep', 'razer-daemon'],
                                stderr=subprocess.DEVNULL,
                                stdout=subprocess.PIPE)
        stdout = proc.communicate()[0]

        # If 0 there are other services running
        if proc.returncode == 0:
            current_uid = str(os.getuid())

            # Loop through other running daemon's
            pids = stdout.decode().strip('\n').split('\n')
            for pid in pids:
                # Open status file in /proc to get uid
                with open('/proc/{0}/status'.format(pid), 'r') as status_file:
                    for line in status_file:
                        # Looking for
                        # Uid:	1000	1000	1000	1000
                        # If they match current pid, then we have a daemon running as this user
                        if line.startswith('Uid:') and line.strip(
                                '\n').split()[-1] == current_uid:
                            print(
                                "Daemon already exists. Please stop that one.",
                                file=sys.stderr)
                            sys.exit(-1)

        setproctitle.setproctitle('razer-daemon')

        # Expanding ~ as python doesnt do it by default, also creating dirs if needed
        if log_dir is not None:
            log_dir = os.path.expanduser(log_dir)
        if run_dir is not None:
            run_dir = os.path.expanduser(run_dir)
        if config_file is not None:
            config_file = os.path.expanduser(config_file)

        self._test_dir = test_dir
        self._run_dir = run_dir
        self._config_file = config_file
        self._config = configparser.ConfigParser()
        self.read_config(config_file)

        # Setup DBus to use gobject main loop
        dbus.mainloop.glib.threads_init()
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        DBusService.__init__(self, self.BUS_PATH, '/org/razer')

        self._init_signals()
        self._main_loop = GObject.MainLoop()

        # Listen for input events from udev
        self._udev_context = Context()
        udev_monitor = Monitor.from_netlink(self._udev_context)
        udev_monitor.filter_by(subsystem='hid')
        self._udev_observer = MonitorObserver(udev_monitor,
                                              callback=self._udev_input_event,
                                              name='device-monitor')

        # Logging
        logging_level = logging.INFO
        if verbose or self._config.getboolean('General', 'verbose_logging'):
            logging_level = logging.DEBUG

        self.logger = logging.getLogger('razer')
        self.logger.setLevel(logging_level)
        formatter = logging.Formatter(
            '%(asctime)s | %(name)-30s | %(levelname)-8s | %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S')
        # Dont propagate to default logger
        self.logger.propagate = 0

        if console_log:
            console_logger = logging.StreamHandler()
            console_logger.setLevel(logging_level)
            console_logger.setFormatter(formatter)
            self.logger.addHandler(console_logger)

        if log_dir is not None:
            log_file = os.path.join(log_dir, 'razer.log')
            file_logger = logging.handlers.RotatingFileHandler(
                log_file, maxBytes=16777216, backupCount=10)  # 16MiB
            file_logger.setLevel(logging_level)
            file_logger.setFormatter(formatter)
            self.logger.addHandler(file_logger)

        # Load Classes
        self._device_classes = razer_daemon.hardware.get_device_classes()

        self.logger.info("Initialising Daemon (v%s). Pid: %d", __version__,
                         os.getpid())

        # Check for plugdev group
        try:
            plugdev_group = grp.getgrnam('plugdev')

            if getpass.getuser() not in plugdev_group.gr_mem:
                self.logger.critical(
                    "User is not a member of the plugdev group")
                sys.exit(1)
        except KeyError:
            self.logger.warning(
                "Could not check if user is a member of the plugdev group. Continuing..."
            )

        self._screensaver_monitor = ScreensaverMonitor(self)
        self._screensaver_monitor.monitoring = self._config.getboolean(
            'Startup', 'devices_off_on_screensaver')

        self._razer_devices = DeviceCollection()
        self._load_devices(first_run=True)

        # Add DBus methods
        self.logger.info("Adding razer.devices.getDevices method to DBus")
        self.add_dbus_method('razer.devices',
                             'getDevices',
                             self.get_serial_list,
                             out_signature='as')
        self.logger.info("Adding razer.daemon.supportedDevices method to DBus")
        self.add_dbus_method('razer.daemon',
                             'supportedDevices',
                             self.supported_devices,
                             out_signature='s')
        self.logger.info(
            "Adding razer.devices.enableTurnOffOnScreensaver method to DBus")
        self.add_dbus_method('razer.devices',
                             'enableTurnOffOnScreensaver',
                             self.enable_turn_off_on_screensaver,
                             in_signature='b')
        self.logger.info("Adding razer.devices.syncEffects method to DBus")
        self.add_dbus_method('razer.devices',
                             'getOffOnScreensaver',
                             self.get_off_on_screensaver,
                             out_signature='b')
        self.logger.info("Adding razer.devices.syncEffects method to DBus")
        self.add_dbus_method('razer.devices',
                             'syncEffects',
                             self.sync_effects,
                             in_signature='b')
        self.logger.info("Adding razer.devices.syncEffects method to DBus")
        self.add_dbus_method('razer.devices',
                             'getSyncEffects',
                             self.get_sync_effects,
                             out_signature='b')
        self.logger.info("Adding razer.daemon.version method to DBus")
        self.add_dbus_method('razer.daemon',
                             'version',
                             self.version,
                             out_signature='s')
        self.logger.info("Adding razer.daemon.stop method to DBus")
        self.add_dbus_method('razer.daemon', 'stop', self.stop)

        # TODO remove
        self.sync_effects(
            self._config.getboolean('Startup', 'sync_effects_enabled'))