[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

[tor-commits] [nyx/master] Move strings from config to source



commit de4600b6c00513321523c3bb5be3bfe2e88fabe9
Author: Damian Johnson <atagar@xxxxxxxxxxxxxx>
Date:   Wed Nov 30 18:58:21 2016 -0800

    Move strings from config to source
    
    String config files are great in a few situations...
    
      * Localizized applications.
      * Strings are repeatidly used multiple places.
      * Applications that have large bodies of text.
    
    We're none of these. Having strings in a config file makes finding code we want
    via grep more of a hassle, in addition to being more complicated. Lets keep
    things simple until we have a good reason to do otherwise.
---
 nyx/__init__.py          | 31 ++--------------
 nyx/arguments.py         | 36 ++++++++++++------
 nyx/curses.py            | 11 +++---
 nyx/log.py               | 59 ++++-------------------------
 nyx/panel/graph.py       |  6 +--
 nyx/panel/header.py      |  8 ++--
 nyx/panel/torrc.py       |  6 +--
 nyx/settings/strings.cfg | 97 ------------------------------------------------
 nyx/starter.py           | 43 ++++++++++++++-------
 nyx/tracker.py           | 47 ++++++++++-------------
 10 files changed, 98 insertions(+), 246 deletions(-)

diff --git a/nyx/__init__.py b/nyx/__init__.py
index f711cd0..b9624a7 100644
--- a/nyx/__init__.py
+++ b/nyx/__init__.py
@@ -14,7 +14,6 @@ Tor curses monitoring application.
   init_controller - initializes our connection to tor
   expand_path - expands path with respect to our chroot
   join - joins a series of strings up to a set length
-  msg - string from our configuration
 
   Interface - overall nyx interface
     |- get_page - page we're showing
@@ -85,7 +84,6 @@ CONFIG = stem.util.conf.config_dict('nyx', {
 NYX_INTERFACE = None
 TOR_CONTROLLER = None
 BASE_DIR = os.path.sep.join(__file__.split(os.path.sep)[:-1])
-TESTING = False
 
 # technically can change but we use this query a *lot* so needs to be cached
 
@@ -125,7 +123,7 @@ def draw_loop():
   interface = nyx_interface()
   next_key = None  # use this as the next user input
 
-  stem.util.log.info(msg('startup_time', start_time = time.time() - CONFIG['start_time']))
+  stem.util.log.info('nyx started (initialization took %0.1f seconds)' % (time.time() - CONFIG['start_time']))
 
   while not interface._quit:
     interface.redraw()
@@ -148,14 +146,14 @@ def draw_loop():
       nyx.menu.show_menu()
     elif key.match('q'):
       if CONFIG['confirm_quit']:
-        confirmation_key = show_message(msg('confirm_quit'), nyx.curses.BOLD, max_wait = 30)
+        confirmation_key = show_message('Are you sure (q again to confirm)?', nyx.curses.BOLD, max_wait = 30)
 
         if not confirmation_key.match('q'):
           continue
 
       break
     elif key.match('x'):
-      confirmation_key = show_message(msg('confirm_reload'), nyx.curses.BOLD, max_wait = 30)
+      confirmation_key = show_message("This will reset Tor's internal state. Are you sure (x again to confirm)?", nyx.curses.BOLD, max_wait = 30)
 
       if confirmation_key.match('x'):
         try:
@@ -302,29 +300,6 @@ def join(entries, joiner = ' ', size = None):
   return result
 
 
-@uses_settings
-def msg(message, config, **attr):
-  """
-  Provides the given message.
-
-  :param str message: message handle to log
-  :param dict attr: attributes to format the message with
-
-  :returns: **str** that was requested
-  """
-
-  try:
-    return config.get('msg.%s' % message).format(**attr)
-  except:
-    msg = 'BUG: We attempted to use an undefined string resource (%s)' % message
-
-    if TESTING:
-      raise ValueError(msg)
-
-    stem.util.log.notice(msg)
-    return ''
-
-
 class Interface(object):
   """
   Overall state of the nyx interface.
diff --git a/nyx/arguments.py b/nyx/arguments.py
index 09c0003..d26a6c5 100644
--- a/nyx/arguments.py
+++ b/nyx/arguments.py
@@ -14,8 +14,6 @@ import nyx.log
 
 import stem.util.connection
 
-from nyx import msg
-
 DEFAULT_ARGS = {
   'control_address': '127.0.0.1',
   'control_port': 9051,
@@ -41,6 +39,25 @@ OPT_EXPANDED = [
   'help',
 ]
 
+HELP_OUTPUT = """
+Usage nyx [OPTION]
+Terminal status monitor for Tor relays.
+
+  -i, --interface [ADDRESS:]PORT  change control interface from {address}:{port}
+  -s, --socket SOCKET_PATH        attach using unix domain socket if present,
+                                    SOCKET_PATH defaults to: {socket}
+  -c, --config CONFIG_PATH        loaded configuration options, CONFIG_PATH
+                                    defaults to: {config_path}
+  -d, --debug LOG_PATH            writes all nyx logs to the given location
+  -l, --log EVENTS                comma separated list of events to log
+  -v, --version                   provides version information
+  -h, --help                      presents this help
+
+Example:
+nyx -i 1643             attach to control port 1643
+nyx -l we -c /tmp/cfg   use this configuration file with 'WARN'/'ERR' events
+""".strip()
+
 
 def parse(argv):
   """
@@ -62,7 +79,7 @@ def parse(argv):
       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))
+    raise ValueError('%s (for usage provide --help)' % exc)
 
   for opt, arg in recognized_args:
     if opt in ('-i', '--interface'):
@@ -73,12 +90,12 @@ def parse(argv):
 
       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))
+          raise ValueError("'%s' isn't a valid IPv4 address" % 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))
+        raise ValueError("'%s' isn't a valid port number" % port)
 
       args['control_port'] = int(port)
       args['user_provided_port'] = True
@@ -109,8 +126,7 @@ def get_help():
   :returns: **str** with our usage information
   """
 
-  return msg(
-    'usage.help_output',
+  return HELP_OUTPUT.format(
     address = DEFAULT_ARGS['control_address'],
     port = DEFAULT_ARGS['control_port'],
     socket = DEFAULT_ARGS['control_socket'],
@@ -125,8 +141,4 @@ def get_version():
   :returns: **str** with our versioning information
   """
 
-  return msg(
-    'usage.version_output',
-    version = nyx.__version__,
-    date = nyx.__release_date__,
-  )
+  return 'nyx version %s (released %s)\n' % (nyx.__version__, nyx.__release_date__)
diff --git a/nyx/curses.py b/nyx/curses.py
index 4396ab4..feb1ef7 100644
--- a/nyx/curses.py
+++ b/nyx/curses.py
@@ -95,11 +95,10 @@ import threading
 
 import stem.util.conf
 import stem.util.enum
+import stem.util.log
 import stem.util.str_tools
 import stem.util.system
 
-from nyx import msg, log
-
 # Curses screen we've initialized and lock for interacting with it. Curses
 # isn't thread safe and concurrency bugs produce especially sinister glitches.
 
@@ -170,7 +169,7 @@ Dimensions = collections.namedtuple('Dimensions', ['width', 'height'])
 def conf_handler(key, value):
   if key == 'color_override':
     if value not in Color and value != 'None':
-      raise ValueError(msg('usage.unable_to_set_color_override', color = value))
+      raise ValueError('"%s" isn\'t a valid color' % value)
   elif key == 'max_line_wrap':
     return max(1, value)
 
@@ -625,7 +624,7 @@ def set_color_override(color = None):
   elif color in Color:
     nyx_config.set('color_override', color)
   else:
-    raise ValueError(msg('usage.unable_to_set_color_override', color = color))
+    raise ValueError('"%s" isn\'t a valid color' % color)
 
 
 def _color_attr():
@@ -648,10 +647,10 @@ def _color_attr():
         curses.init_pair(color_pair + 1, foreground_color, background_color)
         color_attr[color_name] = curses.color_pair(color_pair + 1)
 
-      log.info('setup.color_support_available')
+      stem.util.log.info('Terminal color support detected and enabled')
       COLOR_ATTR = color_attr
     else:
-      log.info('setup.color_support_unavailable')
+      stem.util.log.info('Terminal color support unavailable')
       COLOR_ATTR = DEFAULT_COLOR_ATTR
 
   return COLOR_ATTR
diff --git a/nyx/log.py b/nyx/log.py
index aa458a2..941de1c 100644
--- a/nyx/log.py
+++ b/nyx/log.py
@@ -7,13 +7,6 @@ runlevels.
 
 ::
 
-  trace - logs a message at the TRACE runlevel
-  debug - logs a message at the DEBUG runlevel
-  info - logs a message at the INFO runlevel
-  notice - logs a message at the NOTICE runlevel
-  warn - logs a message at the WARN runlevel
-  error - logs a message at the ERROR runlevel
-
   day_count - number of days since a given timestamp
   log_file_path - path of tor's log file if one is present on disk
   condense_runlevels - condensed displayable listing of log events
@@ -193,7 +186,7 @@ def listen_for_events(listener, events):
     try:
       controller.add_event_listener(listener, event_type)
     except stem.ProtocolError:
-      warn('panel.log.unsupported_event', event = event_type)
+      stem.util.log.warn("%s isn't an event tor supports" % event_type)
       tor_events.remove(event_type)
 
   return sorted(tor_events.union(nyx_events))
@@ -385,11 +378,9 @@ class LogFileOutput(object):
           os.makedirs(path_dir)
 
         self._file = open(path, 'a')
-        notice('panel.log.opening_log_file', version = nyx.__version__, path = path)
-      except IOError as exc:
-        error('msg.panel.log.unable_to_open_log_file', reason = exc.strerror)
-      except OSError as exc:
-        error('msg.panel.log.unable_to_open_log_file', reason = exc)
+        stem.util.log.notice('nyx %s opening log file (%s)' % (nyx.__version__, path))
+      except (IOError, OSError) as exc:
+        stem.util.log.error('Unable to write to log file: %s' % exc.strerror)
 
   def write(self, msg):
     if self._file:
@@ -397,7 +388,7 @@ class LogFileOutput(object):
         self._file.write(msg + '\n')
         self._file.flush()
       except IOError as exc:
-        error('msg.panel.log.unable_to_open_log_file', reason = exc.strerror)
+        stem.util.log.error('Unable to write to log file: %s' % exc.strerror)
         self._file = None
 
 
@@ -437,7 +428,7 @@ class LogFilters(object):
         if len(self._past_filters) > self._max_filters:
           self._past_filters.popitem(False)
       except re.error as exc:
-        notice('panel.log.bad_filter_regex', reason = exc, pattern = regex)
+        stem.util.log.notice('Invalid regular expression pattern (%s): %s' % (exc, regex))
 
   def selection(self):
     return self._selected
@@ -458,42 +449,6 @@ class LogFilters(object):
       return copy
 
 
-def trace(msg, **attr):
-  _log(stem.util.log.TRACE, msg, **attr)
-
-
-def debug(msg, **attr):
-  _log(stem.util.log.DEBUG, msg, **attr)
-
-
-def info(msg, **attr):
-  _log(stem.util.log.INFO, msg, **attr)
-
-
-def notice(msg, **attr):
-  _log(stem.util.log.NOTICE, msg, **attr)
-
-
-def warn(msg, **attr):
-  _log(stem.util.log.WARN, msg, **attr)
-
-
-def error(msg, **attr):
-  _log(stem.util.log.ERROR, msg, **attr)
-
-
-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 read_tor_log(path, read_limit = None):
   """
   Provides logging messages from a tor log file, from newest to oldest.
@@ -554,4 +509,4 @@ def read_tor_log(path, read_limit = None):
     if 'opening log file' in msg or 'opening new log file' in msg:
       break  # this entry marks the start of this tor instance
 
-  info('panel.log.read_from_log_file', count = count, path = path, read_limit = read_limit if read_limit else 'none', runtime = '%0.3f' % (time.time() - start_time))
+  stem.util.log.info("Read %s entries from tor's log file: %s (read limit: %s, runtime: %0.3f)" % (count, path, read_limit if read_limit else 'none', time.time() - start_time))
diff --git a/nyx/panel/graph.py b/nyx/panel/graph.py
index f8b507e..824db0c 100644
--- a/nyx/panel/graph.py
+++ b/nyx/panel/graph.py
@@ -23,7 +23,7 @@ import nyx.panel
 import nyx.popups
 import nyx.tracker
 
-from nyx import nyx_interface, tor_controller, msg, join, show_message
+from nyx import nyx_interface, tor_controller, join, show_message
 from nyx.curses import RED, GREEN, CYAN, BOLD, HIGHLIGHT
 from nyx.menu import MenuItem, Submenu, RadioMenuItem, RadioGroup
 from stem.control import EventType, Listener
@@ -278,7 +278,7 @@ class BandwidthStats(GraphCategory):
           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))
+            log.warn("Tor's 'GETINFO bw-event-cache' provided malformed output: %s" % bw_entries)
             is_successful = False
             break
 
@@ -286,7 +286,7 @@ class BandwidthStats(GraphCategory):
           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)))
+          log.info('Bandwidth graph has information for the last %s' % 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)
diff --git a/nyx/panel/header.py b/nyx/panel/header.py
index df4fb8d..63a4f86 100644
--- a/nyx/panel/header.py
+++ b/nyx/panel/header.py
@@ -22,7 +22,7 @@ import nyx.popups
 import nyx.tracker
 
 from stem.util import conf, log
-from nyx import nyx_interface, tor_controller, msg, input_prompt
+from nyx import nyx_interface, tor_controller, input_prompt
 
 from nyx.curses import RED, GREEN, YELLOW, CYAN, WHITE, BOLD, HIGHLIGHT
 
@@ -193,14 +193,14 @@ class HeaderPanel(nyx.panel.DaemonPanel):
     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
+      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_msg = "Tor's file descriptor usage is at %s%%. If you run out Tor will be unable to continue functioning." % 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_msg = "Tor's file descriptor usage is at %s%%." % fd_percent
         log.log_once('fd_used_at_sixty_percent', log.NOTICE, log_msg)
 
     if self._vals.is_connected:
diff --git a/nyx/panel/torrc.py b/nyx/panel/torrc.py
index b9e873b..46ce895 100644
--- a/nyx/panel/torrc.py
+++ b/nyx/panel/torrc.py
@@ -13,7 +13,7 @@ import nyx.curses
 
 from nyx.curses import RED, GREEN, YELLOW, CYAN, WHITE, BOLD, HIGHLIGHT
 from nyx.menu import MenuItem, Submenu
-from nyx import expand_path, msg, panel, tor_controller
+from nyx import expand_path, panel, tor_controller
 
 from stem import ControllerError
 from stem.control import State
@@ -62,12 +62,12 @@ class TorrcPanel(panel.Panel):
         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_load_error = 'Unable to determine our torrc location: %s' % 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_load_error = 'Unable to read our torrc: %s' % exc_msg
         self._torrc_content = None
 
   def key_handlers(self):
diff --git a/nyx/settings/strings.cfg b/nyx/settings/strings.cfg
deleted file mode 100644
index 0f24529..0000000
--- a/nyx/settings/strings.cfg
+++ /dev/null
@@ -1,97 +0,0 @@
-################################################################################
-#
-# User facing strings. These are sorted into the following namespaces...
-#
-#   * config    parsing or handling configuration options
-#   * debug     concerns the --debug argument
-#   * misc      anything that doesn't fit into a present namespace
-#   * panel     used after startup by our curses panels
-#   * setup     notificaitons or issues arising while starting nyx
-#   * tracker   related to tracking resource usage or connections
-#   * usage     usage information about starting and running nyx
-#
-################################################################################
-
-msg.wrap {text}
-
-msg.startup_time nyx started (initialization took {start_time} seconds)
-msg.confirm_quit Are you sure (q again to confirm)?
-msg.confirm_reload This will reset Tor's internal state. Are you sure (x again to confirm)?
-
-msg.config.unable_to_read_file Failed to load configuration (using defaults): "{error}"
-msg.config.nothing_loaded No nyxrc loaded, using defaults. You can customize nyx by placing a configuration file at {path} (see the nyxrc.sample for its options).
-
-msg.debug.saving_to_path Saving a debug log to {path}, please check it for sensitive information before sharing it.
-msg.debug.unable_to_write_file Unable to write to our debug log file ({path}): {error}
-
-msg.panel.header.fd_used_at_sixty_percent Tor's file descriptor usage is at {percentage}%.
-msg.panel.header.fd_used_at_ninety_percent Tor's file descriptor usage is at {percentage}%. If you run out Tor will be unable to continue functioning.
-msg.panel.graphing.prepopulation_successful Bandwidth graph has information for the last {duration}
-msg.panel.graphing.bw_event_cache_malformed Tor's 'GETINFO bw-event-cache' provided malformed output: {response}
-msg.panel.log.read_from_log_file Read {count} entries from tor's log file: {path} (read limit: {read_limit}, runtime: {runtime})
-msg.panel.log.unsupported_event {event} isn't an event tor spupports
-msg.panel.log.bad_filter_regex Invalid regular expression pattern ({reason}): {pattern}
-msg.panel.log.opening_log_file nyx {version} opening log file ({path})
-msg.panel.log.unable_to_open_log_file Unable to write to log file: {reason}
-msg.panel.torrc.unable_to_find_torrc Unable to determine our torrc location: {error}
-msg.panel.torrc.unable_to_load_torrc Unable to read our torrc: {error}
-
-msg.setup.nyx_is_running_as_root Nyx is currently running with root permissions. This isn't a good idea, nor should it be necessary.
-msg.setup.chroot_doesnt_exist The chroot path set in your config ({path}) doesn't exist.
-msg.setup.set_freebsd_chroot Adjusting paths to account for Tor running in a FreeBSD jail at: {path}
-msg.setup.tor_is_running_as_root Tor is currently running with root permissions. This isn't a good idea, nor should it be necessary. See the 'User UID' option on Tor's man page for an easy method of reducing its permissions after startup.
-msg.setup.unable_to_determine_pid Unable to determine Tor's pid. Some information, like its resource usage will be unavailable.
-msg.setup.color_support_available Terminal color support detected and enabled
-msg.setup.color_support_unavailable Terminal color support unavailable
-
-msg.tracker.available_resolvers Operating System: {os}, Connection Resolvers: {resolvers}
-msg.tracker.abort_getting_resources Failed three attempts to get process resource usage from {resolver}, {response} ({exc})
-msg.tracker.abort_getting_port_usage Failed three attempts to determine the process using active ports ({exc})
-msg.tracker.lookup_rate_increased connection lookup time increasing to {seconds} seconds per call
-msg.tracker.unable_to_get_port_usages Unable to query the processes using ports usage lsof ({exc})
-msg.tracker.unable_to_get_resources Unable to query process resource usage from {resolver} ({exc})
-msg.tracker.unable_to_use_all_resolvers We were unable to use any of your system's resolvers to get tor's connections. This is fine, but means that the connections page will be empty. This is usually permissions related so if you would like to fix this then run nyx with the same user as tor (ie, "sudo -u <tor user> nyx").
-msg.tracker.unable_to_use_resolver Unable to query connections with {old_resolver}, trying {new_resolver}
-
-msg.usage.invalid_arguments {error} (for usage provide --help)
-msg.usage.not_a_valid_address '{address_input}' isn't a valid IPv4 address
-msg.usage.not_a_valid_port '{port_input}' isn't a valid port number
-msg.usage.unable_to_set_color_override "{color}" isn't a valid color
-
-msg.debug.header
-|Nyx {nyx_version} Debug Dump
-|Stem Version: {stem_version}
-|Python Version: {python_version}
-|Platform: {system} ({platform})
-|--------------------------------------------------------------------------------
-|Nyx Configuration ({nyxrc_path}):
-|{nyxrc_content}
-|--------------------------------------------------------------------------------
-
-msg.setup.unknown_term
-|Unknown $TERM: ({term})
-|Either update your terminfo database or run nyx using "TERM=xterm nyx".
-|
-
-msg.usage.help_output
-|Usage nyx [OPTION]
-|Terminal status monitor for Tor relays.
-|
-|  -i, --interface [ADDRESS:]PORT  change control interface from {address}:{port}
-|  -s, --socket SOCKET_PATH        attach using unix domain socket if present,
-|                                    SOCKET_PATH defaults to: {socket}
-|  -c, --config CONFIG_PATH        loaded configuration options, CONFIG_PATH
-|                                    defaults to: {config_path}
-|  -d, --debug LOG_PATH            writes all nyx logs to the given location
-|  -l, --log EVENTS                comma separated list of events to log
-|  -v, --version                   provides version information
-|  -h, --help                      presents this help
-|
-|Example:
-|nyx -i 1643             attach to control port 1643
-|nyx -l we -c /tmp/cfg   use this configuration file with 'WARN'/'ERR' events
-
-msg.usage.version_output
-|nyx version {version} (released {date})
-|
-
diff --git a/nyx/starter.py b/nyx/starter.py
index ce23929..0538b0c 100644
--- a/nyx/starter.py
+++ b/nyx/starter.py
@@ -23,7 +23,23 @@ import stem
 import stem.util.log
 import stem.util.system
 
-from nyx import log, init_controller, msg, uses_settings, nyx_interface
+from nyx import log, init_controller, uses_settings, nyx_interface
+
+DEBUG_HEADER = """
+Nyx {nyx_version} Debug Dump
+Stem Version: {stem_version}
+Python Version: {python_version}
+Platform: {system} ({platform})
+--------------------------------------------------------------------------------
+Nyx Configuration ({nyxrc_path}):
+{nyxrc_content}
+--------------------------------------------------------------------------------
+""".strip()
+
+UNKNOWN_TERM = """\
+Unknown $TERM: (%s)
+Either update your terminfo database or run nyx using "TERM=xterm nyx".
+"""
 
 
 @uses_settings
@@ -47,9 +63,9 @@ def main(config):
   if args.debug_path is not None:
     try:
       _setup_debug_logging(args)
-      print(msg('debug.saving_to_path', path = args.debug_path))
+      print('Saving a debug log to %s, please check it for sensitive information before sharing it.' % args.debug_path)
     except IOError as exc:
-      print(msg('debug.unable_to_write_file', path = args.debug_path, error = exc.strerror))
+      print('Unable to write to our debug log file (%s): %s' % (args.debug_path, exc.strerror))
       sys.exit(1)
 
   _load_user_nyxrc(args.config)
@@ -88,7 +104,7 @@ def main(config):
     nyx.curses.start(nyx.draw_loop, acs_support = config.get('acs_support', True), transparent_background = True, cursor = False)
   except UnboundLocalError as exc:
     if os.environ['TERM'] != 'xterm':
-      print(msg('setup.unknown_term', term = os.environ['TERM']))
+      print(UNKNOWN_TERM % os.environ['TERM'])
     else:
       raise exc
   except KeyboardInterrupt:
@@ -128,8 +144,7 @@ def _setup_debug_logging(args):
     except IOError as exc:
       nyxrc_content = '[unable to read file: %s]' % exc.strerror
 
-  log.trace(
-    'debug.header',
+  stem.util.log.trace(DEBUG_HEADER.format(
     nyx_version = nyx.__version__,
     stem_version = stem.__version__,
     python_version = '.'.join(map(str, sys.version_info[:3])),
@@ -137,7 +152,7 @@ def _setup_debug_logging(args):
     platform = ' '.join(platform.dist()),
     nyxrc_path = args.config,
     nyxrc_content = nyxrc_content,
-  )
+  ))
 
 
 @uses_settings
@@ -156,14 +171,14 @@ def _load_user_nyxrc(path, config):
       chroot = config.get('tor_chroot', '').strip().rstrip(os.path.sep)
 
       if chroot and not os.path.exists(chroot):
-        log.notice('setup.chroot_doesnt_exist', path = chroot)
+        stem.util.log.notice("The chroot path set in your config (%s) doesn't exist." % chroot)
         config.set('tor_chroot', '')
       else:
         config.set('tor_chroot', chroot)  # use the normalized path
     except IOError as exc:
-      log.warn('config.unable_to_read_file', error = exc.strerror)
+      stem.util.log.warn('Failed to load configuration (using defaults): "%s"' % exc.strerror)
   else:
-    log.notice('config.nothing_loaded', path = path)
+    stem.util.log.notice('No nyxrc loaded, using defaults. You can customize nyx by placing a configuration file at %s (see the nyxrc.sample for its options).' % path)
 
 
 def _warn_if_root(controller):
@@ -172,9 +187,9 @@ def _warn_if_root(controller):
   """
 
   if controller.get_user(None) == 'root':
-    log.notice('setup.tor_is_running_as_root')
+    stem.util.log.notice("Tor is currently running with root permissions. This isn't a good idea, nor should it be necessary. See the 'User UID' option on Tor's man page for an easy method of reducing its permissions after startup.")
   elif os.getuid() == 0:
-    log.notice('setup.nyx_is_running_as_root')
+    stem.util.log.notice("Nyx is currently running with root permissions. This isn't a good idea, nor should it be necessary.")
 
 
 def _warn_if_unable_to_get_pid(controller):
@@ -186,7 +201,7 @@ def _warn_if_unable_to_get_pid(controller):
   try:
     controller.get_pid()
   except ValueError:
-    log.warn('setup.unable_to_determine_pid')
+    stem.util.log.warn("Unable to determine Tor's pid. Some information, like its resource usage will be unavailable.")
 
 
 @uses_settings
@@ -210,7 +225,7 @@ def _setup_freebsd_chroot(controller, config):
     jail_chroot = stem.util.system.bsd_jail_path(controller.get_pid(0))
 
     if jail_chroot and os.path.exists(jail_chroot):
-      log.info('setup.set_freebsd_chroot', path = jail_chroot)
+      stem.util.log.info('Adjusting paths to account for Tor running in a FreeBSD jail at: %s' % jail_chroot)
       config.set('tor_chroot', jail_chroot)
 
 
diff --git a/nyx/tracker.py b/nyx/tracker.py
index a42b357..da0ac13 100644
--- a/nyx/tracker.py
+++ b/nyx/tracker.py
@@ -56,8 +56,9 @@ import threading
 
 import stem.control
 import stem.descriptor.router_status_entry
+import stem.util.log
 
-from nyx import log, tor_controller
+from nyx import tor_controller
 from stem.util import conf, connection, enum, proc, str_tools, system
 
 CONFIG = conf.config_dict('nyx', {
@@ -66,6 +67,13 @@ CONFIG = conf.config_dict('nyx', {
   'port_usage_rate': 5,
 })
 
+UNABLE_TO_USE_ANY_RESOLVER_MSG = """
+We were unable to use any of your system's resolvers to get tor's connections.
+This is fine, but means that the connections page will be empty. This is
+usually permissions related so if you would like to fix this then run nyx with
+the same user as tor (ie, "sudo -u <tor user> nyx").
+""".strip()
+
 CONNECTION_TRACKER = None
 RESOURCE_TRACKER = None
 PORT_USAGE_TRACKER = None
@@ -508,7 +516,7 @@ class ConnectionTracker(Daemon):
     else:
       self._resolvers = [CustomResolver.INFERENCE]
 
-    log.info('tracker.available_resolvers', os = os.uname()[0], resolvers = ', '.join(self._resolvers))
+    stem.util.log.info('Operating System: %s, Connection Resolvers: %s' % (os.uname()[0], ', '.join(self._resolvers)))
 
   def _task(self, process_pid, process_name):
     if self._custom_resolver:
@@ -569,13 +577,13 @@ class ConnectionTracker(Daemon):
           min_rate += 1  # little extra padding so we don't frequently update this
           self.set_rate(min_rate)
           self._rate_too_low_count = 0
-          log.debug('tracker.lookup_rate_increased', seconds = "%0.1f" % min_rate)
+          stem.util.log.debug('connection lookup time increasing to %0.1f seconds per call' % min_rate)
       else:
         self._rate_too_low_count = 0
 
       return True
     except IOError as exc:
-      log.info('wrap', text = exc)
+      stem.util.log.info(str(exc))
 
       # Fail over to another resolver if we've repeatedly been unable to use
       # this one.
@@ -588,13 +596,9 @@ class ConnectionTracker(Daemon):
           self._failure_count = 0
 
           if self._resolvers:
-            log.notice(
-              'tracker.unable_to_use_resolver',
-              old_resolver = resolver,
-              new_resolver = self._resolvers[0],
-            )
+            stem.util.log.notice('Unable to query connections with %s, trying %s' % (resolver, self._resolvers[0]))
           else:
-            log.notice('tracker.unable_to_use_all_resolvers')
+            stem.util.log.notice(UNABLE_TO_USE_ANY_RESOLVER_MSG)
 
       return False
 
@@ -686,28 +690,17 @@ class ResourceTracker(Daemon):
           self._use_proc = False
           self._failure_count = 0
 
-          log.info(
-            'tracker.abort_getting_resources',
-            resolver = 'proc',
-            response = 'falling back to ps',
-            exc = exc,
-          )
+          stem.util.log.info('Failed three attempts to get process resource usage from proc, falling back to ps (%s)' % exc)
         else:
-          log.debug('tracker.unable_to_get_resources', resolver = 'proc', exc = exc)
+          stem.util.log.debug('Unable to query process resource usage from proc (%s)' % exc)
       else:
         if self._failure_count >= 3:
           # Give up on further attempts.
 
-          log.info(
-            'tracker.abort_getting_resources',
-            resolver = 'ps',
-            response = 'giving up on getting resource usage information',
-            exc = exc,
-          )
-
+          stem.util.log.info('Failed three attempts to get process resource usage from ps, giving up on getting resource usage information (%s)' % exc)
           self.stop()
         else:
-          log.debug('tracker.unable_to_get_resources', resolver = 'ps', exc = exc)
+          stem.util.log.debug('Unable to query process resource usage from ps (%s)' % exc)
 
       return False
 
@@ -799,10 +792,10 @@ class PortUsageTracker(Daemon):
       self._failure_count += 1
 
       if self._failure_count >= 3:
-        log.info('tracker.abort_getting_port_usage', exc = exc)
+        stem.util.log.info('Failed three attempts to determine the process using active ports (%s)' % exc)
         self.stop()
       else:
-        log.debug('tracker.unable_to_get_port_usages', exc = exc)
+        stem.util.log.debug('Unable to query the processes using ports usage lsof (%s)' % exc)
 
       return False
 



_______________________________________________
tor-commits mailing list
tor-commits@xxxxxxxxxxxxxxxxxxxx
https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits