From 8badce286f9e50384b68e0f5e77e314fd48363db Mon Sep 17 00:00:00 2001 From: Alexander Bokovoy Date: Wed, 12 Oct 2011 16:42:09 +0300 Subject: [PATCH] Refactor backup_and_replace_hostname() into a flexible config modification tool backup_and_replace_hostname() was doing three things: 1. Given config file in 'key=value' style, replace value for a specified key (HOSTNAME) 2. Backup original file and install a replacement 3. Restore original security context after editing We have several more places where parts of the functionality are needed, thus making two tools in ipapython.ipautil: 1. config_replace_variables(filepath, replacevars=dict(), appendvars=dict()) Replaces or appends values to specified keys, adding new key=value pairs if key was absent 2. backup_config_and_replace_variables(fstore, filepath, replacevars=dict(), appendvars=dict()) Backups config file and calls config_replace_variables() A caller must handle security context after using these two tools. In addition, as before, there is ipapython.services.backup_and_replace_hostname() that uses these common tools and restores security context after editing. The code will be used extensively for systemd integration for Fedora 16. Fixes: https://fedorahosted.org/freeipa/ticket/1871 --- ipapython/ipautil.py | 90 ++++++++++++++++++++++++++++++++++++ ipapython/platform/redhat.py | 47 +++---------------- 2 files changed, 97 insertions(+), 40 deletions(-) diff --git a/ipapython/ipautil.py b/ipapython/ipautil.py index 6e037926c..232869802 100644 --- a/ipapython/ipautil.py +++ b/ipapython/ipautil.py @@ -1185,3 +1185,93 @@ def get_ipa_basedn(conn): return None +def config_replace_variables(filepath, replacevars=dict(), appendvars=dict()): + """ + Take a key=value based configuration file, and write new version + with certain values replaced or appended + + All (key,value) pairs from replacevars and appendvars that were not found + in the configuration file, will be added there. + + It is responsibility of a caller to ensure that replacevars and + appendvars do not overlap. + + It is responsibility of a caller to back up file. + + returns dictionary of affected keys and their previous values + + One have to run restore_context(filepath) afterwards or + security context of the file will not be correct after modification + """ + pattern = re.compile(''' +(^ + \s* + (?P