[tor-commits] [nyx/master] Drop the Torrc class

atagar at torproject.org atagar at torproject.org
Sun Feb 14 02:55:49 UTC 2016


commit 7abb3c3cafee619fb9bad3f74f229521b6173608
Author: Damian Johnson <atagar at torproject.org>
Date:   Sun Jan 17 16:30:13 2016 -0800

    Drop the Torrc class
    
    Dropping the last usage of the class so we can finally remove it. Eventually
    plan is to axe the whole module but one bit at a time. ;)
---
 nyx/controller.py      |   9 +---
 nyx/torrc_panel.py     |  73 +++++++++-----------------
 nyx/util/tor_config.py | 137 -------------------------------------------------
 3 files changed, 25 insertions(+), 194 deletions(-)

diff --git a/nyx/controller.py b/nyx/controller.py
index 01f94ec..b520aa7 100644
--- a/nyx/controller.py
+++ b/nyx/controller.py
@@ -23,7 +23,7 @@ import stem
 
 from stem.control import State
 
-from nyx.util import panel, tor_config, tor_controller, ui_tools
+from nyx.util import panel, tor_controller, ui_tools
 
 from stem.util import conf, log, system
 
@@ -478,13 +478,6 @@ def conn_reset_listener(controller, event_type, _):
 
     if event_type == State.CLOSED:
       log.notice('Tor control port closed')
-    elif event_type in (State.INIT, State.RESET):
-      # Reload the torrc contents. If the torrc panel is present then it will
-      # do this instead since it wants to do validation and redraw _after_ the
-      # new contents are loaded.
-
-      if get_controller().get_panel('torrc') is None:
-        tor_config.get_torrc().load(True)
 
 
 def start_nyx(stdscr):
diff --git a/nyx/torrc_panel.py b/nyx/torrc_panel.py
index 0c70f37..f312553 100644
--- a/nyx/torrc_panel.py
+++ b/nyx/torrc_panel.py
@@ -11,7 +11,7 @@ import nyx.popups
 from nyx.util import expand_path, panel, tor_config, tor_controller, ui_tools
 
 from stem.control import State
-from stem.util import conf, str_tools
+from stem.util import conf, log, str_tools
 
 
 def conf_handler(key, value):
@@ -45,34 +45,31 @@ class TorrcPanel(panel.Panel):
     self._last_content_height = 1
     self._last_content_height_args = None
 
+    self.torrc_location = ''
+    self.torrc_content = None
+
     # listens for tor reload (sighup) events
 
     controller = tor_controller()
     controller.add_status_listener(self.reset_listener)
 
     if controller.is_alive():
-      self.reset_listener(None, State.INIT, None)
+      self.reset_listener(controller, State.RESET, None)
 
   def reset_listener(self, controller, event_type, _):
     """
     Reloads and displays the torrc on tor reload (sighup) events.
     """
 
-    if event_type == State.INIT:
-      # loads the torrc and provides warnings in case of validation errors
+    if event_type == State.RESET:
+      self.torrc_location = expand_path(controller.get_info('config-file', None))
 
       try:
-        loaded_torrc = tor_config.get_torrc()
-        loaded_torrc.load(True)
-        self.redraw(True)
-      except:
-        pass
-    elif event_type == State.RESET:
-      try:
-        tor_config.get_torrc().load(True)
-        self.redraw(True)
-      except:
-        pass
+        with open(self.torrc_location) as torrc_file:
+          self.torrc_content = torrc_file.readlines()
+      except IOError as exc:
+        log.log_once('torrc_load_failed', log.WARN, 'Unable to load torrc (%s)' % exc.strerror)
+        self.torrc_content = None
 
   def set_comments_visible(self, is_visible):
     """
@@ -98,23 +95,6 @@ class TorrcPanel(panel.Panel):
     self._last_content_height_args = None
     self.redraw(True)
 
-  def reload_torrc(self):
-    """
-    Reloads the torrc, displaying an indicator of success or failure.
-    """
-
-    try:
-      tor_config.get_torrc().load()
-      self._last_content_height_args = None
-      self.redraw(True)
-      result_msg = 'torrc reloaded'
-    except IOError:
-      result_msg = 'failed to reload torrc'
-
-    self._last_content_height_args = None
-    self.redraw(True)
-    nyx.popups.show_msg(result_msg, 1)
-
   def handle_key(self, key):
     with self._vals_lock:
       if key.is_scroll():
@@ -128,8 +108,6 @@ class TorrcPanel(panel.Panel):
         self.set_line_number_visible(not self.show_line_num)
       elif key.match('s'):
         self.set_comments_visible(self.strip_comments)
-      elif key.match('r'):
-        self.reload_torrc()
       else:
         return False
 
@@ -149,7 +127,6 @@ class TorrcPanel(panel.Panel):
       ('page down', 'scroll down a page', None),
       ('s', 'comment stripping', 'on' if self.strip_comments else 'off'),
       ('n', 'line numbering', 'on' if self.show_line_num else 'off'),
-      ('r', 'reload torrc', None),
       ('x', 'reset tor (issue sighup)', None),
     ]
 
@@ -167,22 +144,20 @@ class TorrcPanel(panel.Panel):
 
       self.scroll = max(0, min(self.scroll, self._last_content_height - height + 1))
 
-      rendered_contents, corrections, conf_location = None, {}, None
-
-      loaded_torrc = tor_config.get_torrc()
-      controller = tor_controller()
-
-      conf_location = expand_path(controller.get_info('config-file', None))
+      if self.torrc_content is None:
+        rendered_contents = ['### Unable to load the torrc ###']
+        corrections = {}
+      else:
+        rendered_contents = [ui_tools.get_printable(line.replace('\t', '   ')) for line in self.torrc_content]
 
-      with loaded_torrc.get_lock():
-        if not loaded_torrc.is_loaded():
-          rendered_contents = ['### Unable to load the torrc ###']
-        else:
-          rendered_contents = loaded_torrc.get_display_contents(self.strip_comments)
+        if self.strip_comments:
+          for i in range(len(rendered_contents)):
+            line = rendered_contents[i]
 
-          # constructs a mapping of line numbers to the issue on it
+            if line and '#' in line:
+              rendered_contents[i] = line[:line.find('#')].strip()
 
-          corrections = dict((line_number, (issue, msg)) for line_number, issue, msg in loaded_torrc.get_corrections())
+        corrections = dict((line_number, (issue, msg)) for line_number, issue, msg in tor_config.validate(self.torrc_content))
 
       # offset to make room for the line numbers
 
@@ -207,7 +182,7 @@ class TorrcPanel(panel.Panel):
       # draws the top label
 
       if self.is_title_visible():
-        location_label = ' (%s)' % conf_location if conf_location else ''
+        location_label = ' (%s)' % self.torrc_location
         self.addstr(0, 0, 'Tor Configuration File%s:' % (location_label), curses.A_STANDOUT)
 
       is_multiline = False  # true if we're in the middle of a multiline torrc entry
diff --git a/nyx/util/tor_config.py b/nyx/util/tor_config.py
index 1286a4a..7bc462b 100644
--- a/nyx/util/tor_config.py
+++ b/nyx/util/tor_config.py
@@ -335,140 +335,3 @@ def _strip_comments(contents):
     stripped_contents.append(line.strip())
 
   return stripped_contents
-
-
-class Torrc():
-  """
-  Wrapper for the torrc. All getters provide None if the contents are unloaded.
-  """
-
-  def __init__(self):
-    self.contents = None
-    self.config_location = None
-    self._vals_lock = threading.RLock()
-
-    # cached results for the current contents
-    self.displayable_contents = None
-    self.stripped_contents = None
-    self.corrections = None
-
-    # flag to indicate if we've given a load failure warning before
-    self.is_foad_fail_warned = False
-
-  def load(self, log_failure = False):
-    """
-    Loads or reloads the torrc contents, raising an IOError if there's a
-    problem.
-
-    Arguments:
-      log_failure - if the torrc fails to load and we've never provided a
-                   warning for this before then logs a warning
-    """
-
-    with self._vals_lock:
-      # clears contents and caches
-      self.contents, self.config_location = None, None
-      self.displayable_contents = None
-      self.stripped_contents = None
-      self.corrections = None
-
-      try:
-        self.config_location = get_config_location()
-        config_file = open(self.config_location, 'r')
-        self.contents = config_file.readlines()
-        config_file.close()
-      except IOError as exc:
-        if log_failure and not self.is_foad_fail_warned:
-          log.warn('Unable to load torrc (%s)' % exc.strerror)
-          self.is_foad_fail_warned = True
-
-        raise exc
-
-  def is_loaded(self):
-    """
-    Provides true if there's loaded contents, false otherwise.
-    """
-
-    return self.contents is not None
-
-  def get_config_location(self):
-    """
-    Provides the location of the loaded configuration contents. This may be
-    available, even if the torrc failed to be loaded.
-    """
-
-    return self.config_location
-
-  def get_contents(self):
-    """
-    Provides the contents of the configuration file.
-    """
-
-    with self._vals_lock:
-      return list(self.contents) if self.contents else None
-
-  def get_display_contents(self, strip = False):
-    """
-    Provides the contents of the configuration file, formatted in a rendering
-    frindly fashion:
-    - Tabs print as three spaces. Keeping them as tabs is problematic for
-      layouts since it's counted as a single character, but occupies several
-      cells.
-    - Strips control and unprintable characters.
-
-    Arguments:
-      strip - removes comments and extra whitespace if true
-    """
-
-    with self._vals_lock:
-      if not self.is_loaded():
-        return None
-      else:
-        if self.displayable_contents is None:
-          # restricts contents to displayable characters
-          self.displayable_contents = []
-
-          for line_number in range(len(self.contents)):
-            line_text = self.contents[line_number]
-            line_text = line_text.replace('\t', '   ')
-            line_text = ui_tools.get_printable(line_text)
-            self.displayable_contents.append(line_text)
-
-        if strip:
-          if self.stripped_contents is None:
-            self.stripped_contents = _strip_comments(self.displayable_contents)
-
-          return list(self.stripped_contents)
-        else:
-          return list(self.displayable_contents)
-
-  def get_corrections(self):
-    """
-    Performs validation on the loaded contents and provides back the
-    corrections. If validation is disabled then this won't provide any
-    results.
-    """
-
-    with self._vals_lock:
-      if not self.is_loaded():
-        return None
-      else:
-        tor_version = tor_controller().get_version(None)
-        skip_validation = not CONFIG['features.torrc.validate']
-        skip_validation |= (tor_version is None or not tor_version >= stem.version.Requirement.GETINFO_CONFIG_TEXT)
-
-        if skip_validation:
-          log.info('Skipping torrc validation (requires tor 0.2.2.7-alpha)')
-          return {}
-        else:
-          if self.corrections is None:
-            self.corrections = validate(self.contents)
-
-          return list(self.corrections)
-
-  def get_lock(self):
-    """
-    Provides the lock governing concurrent access to the contents.
-    """
-
-    return self._vals_lock





More information about the tor-commits mailing list