def __init__(self, clone = None): GraphCategory.__init__(self, clone) if not clone: # fill in past bandwidth information controller = tor_controller() bw_entries, is_successful = controller.get_info('bw-event-cache', None), True if bw_entries: for entry in bw_entries.split(): entry_comp = entry.split(',') if len(entry_comp) != 2 or not entry_comp[0].isdigit() or not entry_comp[1].isdigit(): log.warn(msg('panel.graphing.bw_event_cache_malformed', response = bw_entries)) is_successful = False break self.primary.update(int(entry_comp[0])) self.secondary.update(int(entry_comp[1])) if is_successful: log.info(msg('panel.graphing.prepopulation_successful', duration = str_tools.time_label(len(bw_entries.split()), is_long = True))) read_total = controller.get_info('traffic/read', None) write_total = controller.get_info('traffic/written', None) start_time = system.start_time(controller.get_pid(None)) if read_total and write_total and start_time: self.primary.total = int(read_total) self.secondary.total = int(write_total) self.start_time = start_time
def _update(self): self._vals = Sampling.create(self._vals) if self._vals.fd_used and self._vals.fd_limit != -1: fd_percent = 100 * self._vals.fd_used / self._vals.fd_limit if fd_percent >= 90: log_msg = msg('panel.header.fd_used_at_ninety_percent', percentage=fd_percent) log.log_once('fd_used_at_ninety_percent', log.WARN, log_msg) log.DEDUPLICATION_MESSAGE_IDS.add('fd_used_at_sixty_percent') elif fd_percent >= 60: log_msg = msg('panel.header.fd_used_at_sixty_percent', percentage=fd_percent) log.log_once('fd_used_at_sixty_percent', log.NOTICE, log_msg) if self._vals.is_connected: if not self._reported_inactive and ( time.time() - self._vals.last_heartbeat) >= 10: self._reported_inactive = True log.notice('Relay unresponsive (last heartbeat: %s)' % time.ctime(self._vals.last_heartbeat)) elif self._reported_inactive and (time.time() - self._vals.last_heartbeat) < 10: self._reported_inactive = False log.notice('Relay resumed') self.redraw()
def parse(argv): """ Parses our arguments, providing a named tuple with their values. :param list argv: input arguments to be parsed :returns: a **named tuple** with our parsed arguments :raises: **ValueError** if we got an invalid argument """ args = dict(DEFAULT_ARGS) try: recognized_args, unrecognized_args = getopt.getopt(argv, OPT, OPT_EXPANDED) if unrecognized_args: error_msg = "aren't recognized arguments" if len(unrecognized_args) > 1 else "isn't a recognized argument" raise getopt.GetoptError("'%s' %s" % ("', '".join(unrecognized_args), error_msg)) except getopt.GetoptError as exc: raise ValueError(msg('usage.invalid_arguments', error = exc)) for opt, arg in recognized_args: if opt in ('-i', '--interface'): if ':' in arg: address, port = arg.split(':', 1) else: address, port = None, arg if address is not None: if not stem.util.connection.is_valid_ipv4_address(address): raise ValueError(msg('usage.not_a_valid_address', address_input = address)) args['control_address'] = address if not stem.util.connection.is_valid_port(port): raise ValueError(msg('usage.not_a_valid_port', port_input = port)) args['control_port'] = int(port) args['user_provided_port'] = True elif opt in ('-s', '--socket'): args['control_socket'] = arg args['user_provided_socket'] = True elif opt in ('-c', '--config'): args['config'] = arg elif opt in ('-d', '--debug'): args['debug_path'] = os.path.expanduser(arg) elif opt in ('-l', '--log'): args['logged_events'] = arg elif opt in ('-v', '--version'): args['print_version'] = True elif opt in ('-h', '--help'): args['print_help'] = True # translates our args dict into a named tuple Args = collections.namedtuple('Args', args.keys()) return Args(**args)
def conf_handler(key, value): if key == 'features.colorOverride': if value not in Color and value != 'None': raise ValueError( msg('usage.unable_to_set_color_override', color=value)) elif key == 'features.torrc.maxLineWrap': return max(1, value)
def get_help(): """ Provides our --help usage information. :returns: **str** with our usage information """ return msg( 'usage.help_output', address = DEFAULT_ARGS['control_address'], port = DEFAULT_ARGS['control_port'], socket = DEFAULT_ARGS['control_socket'], config_path = DEFAULT_ARGS['config'], events = DEFAULT_ARGS['logged_events'], event_flags = msg('misc.event_types'), )
def reset_listener(self, controller, event_type, _): """ Reloads and displays the torrc on tor reload (sighup) events. """ if event_type == State.RESET: try: self._torrc_location = expand_path(controller.get_info('config-file')) self._torrc_content = _read_torrc(self._torrc_location) except ControllerError as exc: self._torrc_load_error = msg('panel.torrc.unable_to_find_torrc', error = exc) self._torrc_location = None self._torrc_content = None except Exception as exc: exc_msg = exc.strerror if (hasattr(exc, 'strerror') and exc.strerror) else str(exc) self._torrc_load_error = msg('panel.torrc.unable_to_load_torrc', error = exc_msg) self._torrc_content = None
def _log(runlevel, message, **attr): """ Logs the given message, formatted with optional attributes. :param stem.util.log.Runlevel runlevel: runlevel at which to log the message :param str message: message handle to log :param dict attr: attributes to format the message with """ stem.util.log.log(runlevel, nyx.msg(message, **attr))
def reset_listener(self, controller, event_type, _): """ Reloads and displays the torrc on tor reload (sighup) events. """ if event_type == State.RESET: try: self._torrc_location = expand_path( controller.get_info('config-file')) self._torrc_content = _read_torrc(self._torrc_location) except ControllerError as exc: self._torrc_load_error = msg( 'panel.torrc.unable_to_find_torrc', error=exc) self._torrc_location = None self._torrc_content = None except Exception as exc: exc_msg = exc.strerror if (hasattr(exc, 'strerror') and exc.strerror) else str(exc) self._torrc_load_error = msg( 'panel.torrc.unable_to_load_torrc', error=exc_msg) self._torrc_content = None
def get_version(): """ Provides our --version information. :returns: **str** with our versioning information """ return msg( 'usage.version_output', version = nyx.__version__, date = nyx.__release_date__, )
def __init__(self, clone=None): GraphCategory.__init__(self, clone) if not clone: # fill in past bandwidth information controller = tor_controller() bw_entries, is_successful = controller.get_info( 'bw-event-cache', None), True if bw_entries: for entry in bw_entries.split(): entry_comp = entry.split(',') if len(entry_comp) != 2 or not entry_comp[0].isdigit( ) or not entry_comp[1].isdigit(): log.warn( msg('panel.graphing.bw_event_cache_malformed', response=bw_entries)) is_successful = False break self.primary.update(int(entry_comp[0])) self.secondary.update(int(entry_comp[1])) if is_successful: log.info( msg('panel.graphing.prepopulation_successful', duration=str_tools.time_label(len( bw_entries.split()), is_long=True))) read_total = controller.get_info('traffic/read', None) write_total = controller.get_info('traffic/written', None) start_time = system.start_time(controller.get_pid(None)) if read_total and write_total and start_time: self.primary.total = int(read_total) self.secondary.total = int(write_total) self.start_time = start_time
def reset_listener(self, controller, event_type, _): """ Reloads and displays the torrc on tor reload (sighup) events. """ if event_type == State.RESET: try: self._torrc_location = expand_path(controller.get_info('config-file')) contents = [] with open(self._torrc_location) as torrc_file: for line in torrc_file.readlines(): line = line.replace('\t', ' ').replace('\xc2', "'").rstrip() contents.append(filter(lambda char: char in string.printable, line)) self._torrc_content = contents except ControllerError as exc: self._torrc_load_error = msg('panel.torrc.unable_to_find_torrc', error = exc) self._torrc_location = None self._torrc_content = None except Exception as exc: self._torrc_load_error = msg('panel.torrc.unable_to_load_torrc', error = exc.strerror) self._torrc_content = None
def _update(self): self._vals = Sampling.create(self._vals) if self._vals.fd_used and self._vals.fd_limit != -1: fd_percent = 100 * self._vals.fd_used / self._vals.fd_limit if fd_percent >= 90: log_msg = msg('panel.header.fd_used_at_ninety_percent', percentage = fd_percent) log.log_once('fd_used_at_ninety_percent', log.WARN, log_msg) log.DEDUPLICATION_MESSAGE_IDS.add('fd_used_at_sixty_percent') elif fd_percent >= 60: log_msg = msg('panel.header.fd_used_at_sixty_percent', percentage = fd_percent) log.log_once('fd_used_at_sixty_percent', log.NOTICE, log_msg) if self._vals.is_connected: if not self._reported_inactive and (time.time() - self._vals.last_heartbeat) >= 10: self._reported_inactive = True log.notice('Relay unresponsive (last heartbeat: %s)' % time.ctime(self._vals.last_heartbeat)) elif self._reported_inactive and (time.time() - self._vals.last_heartbeat) < 10: self._reported_inactive = False log.notice('Relay resumed') self.redraw()
def get_help(): """ Provides our --help usage information. :returns: **str** with our usage information """ return msg( 'usage.help_output', address = DEFAULT_ARGS['control_address'], port = DEFAULT_ARGS['control_port'], socket = DEFAULT_ARGS['control_socket'], config_path = DEFAULT_ARGS['config'], )
def set_color_override(color = None): """ Overwrites all requests for color with the given color instead. :param nyx.curses.Color color: color to override all requests with, **None** if color requests shouldn't be overwritten :raises: **ValueError** if the color name is invalid """ nyx_config = stem.util.conf.get_config('nyx') if color is None: nyx_config.set('features.colorOverride', 'None') elif color in Color: nyx_config.set('features.colorOverride', color) else: raise ValueError(msg('usage.unable_to_set_color_override', color = color))
def set_color_override(color=None): """ Overwrites all requests for color with the given color instead. :param nyx.curses.Color color: color to override all requests with, **None** if color requests shouldn't be overwritten :raises: **ValueError** if the color name is invalid """ nyx_config = stem.util.conf.get_config('nyx') if color is None: nyx_config.set('features.colorOverride', 'None') elif color in Color: nyx_config.set('features.colorOverride', color) else: raise ValueError(msg('usage.unable_to_set_color_override', color=color))
def main(config): config.set('start_time', str(int(time.time()))) try: args = nyx.arguments.parse(sys.argv[1:]) config.set('startup.events', args.logged_events) except ValueError as exc: print(exc) sys.exit(1) if args.print_help: print(nyx.arguments.get_help()) sys.exit() elif args.print_version: print(nyx.arguments.get_version()) sys.exit() if args.debug_path is not None: try: _setup_debug_logging(args) print(msg('debug.saving_to_path', path = args.debug_path)) except IOError as exc: print(msg('debug.unable_to_write_file', path = args.debug_path, error = exc.strerror)) sys.exit(1) _load_user_nyxrc(args.config) control_port = (args.control_address, args.control_port) control_socket = args.control_socket # If the user explicitely specified an endpoint then just try to connect to # that. if args.user_provided_socket and not args.user_provided_port: control_port = None elif args.user_provided_port and not args.user_provided_socket: control_socket = None controller = init_controller( control_port = control_port, control_socket = control_socket, password_prompt = True, chroot_path = config.get('tor.chroot', ''), ) if controller is None: exit(1) _warn_if_root(controller) _warn_if_unable_to_get_pid(controller) _setup_freebsd_chroot(controller) _use_english_subcommands() _use_no_esc_delay() _use_unicode() _set_process_name() try: nyx.curses.start(nyx.controller.start_nyx, transparent_background = True, cursor = False) except UnboundLocalError as exc: if os.environ['TERM'] != 'xterm': print(msg('setup.unknown_term', term = os.environ['TERM'])) else: raise exc except KeyboardInterrupt: pass # skip printing a stack trace finally: nyx.curses.halt() _shutdown_daemons(controller)
def main(config): config.set('start_time', str(int(time.time()))) try: args = nyx.arguments.parse(sys.argv[1:]) config.set('startup.events', args.logged_events) except ValueError as exc: print(exc) sys.exit(1) if args.print_help: print(nyx.arguments.get_help()) sys.exit() elif args.print_version: print(nyx.arguments.get_version()) sys.exit() if args.debug_path is not None: try: _setup_debug_logging(args) print(msg('debug.saving_to_path', path = args.debug_path)) except IOError as exc: print(msg('debug.unable_to_write_file', path = args.debug_path, error = exc.strerror)) sys.exit(1) _load_user_nyxrc(args.config) control_port = (args.control_address, args.control_port) control_socket = args.control_socket # If the user explicitely specified an endpoint then just try to connect to # that. if args.user_provided_socket and not args.user_provided_port: control_port = None elif args.user_provided_port and not args.user_provided_socket: control_socket = None controller = init_controller( control_port = control_port, control_socket = control_socket, password_prompt = True, chroot_path = config.get('tor.chroot', ''), ) if controller is None: exit(1) _warn_if_root(controller) _warn_if_unable_to_get_pid(controller) _setup_freebsd_chroot(controller) _notify_of_unknown_events() _use_english_subcommands() _use_unicode() _set_process_name() _set_escdelay_to_zero() try: nyx.curses.start(nyx.controller.start_nyx, transparent_background = True, cursor = False) except UnboundLocalError as exc: if os.environ['TERM'] != 'xterm': print(msg('setup.unknown_term', term = os.environ['TERM'])) else: raise exc except KeyboardInterrupt: pass # skip printing a stack trace finally: nyx.panel.HALT_ACTIVITY = True _shutdown_daemons(controller)
def conf_handler(key, value): if key == 'features.colorOverride': if value not in Color and value != 'None': raise ValueError(msg('usage.unable_to_set_color_override', color = value)) elif key == 'features.torrc.maxLineWrap': return max(1, value)