can't blindly decode() a pickle, need to store as bytes
[nodemanager.git] / tools.py
index 74705aa..0d8fe95 100644 (file)
--- a/tools.py
+++ b/tools.py
@@ -154,13 +154,14 @@ using <do_write> to write that file, and then renaming the temporary file.
     shutil.move(write_temp_file(do_write, **kw_args), filename)
 
 
-def write_temp_file(do_write, mode=None, uidgid=None):
+def write_temp_file(do_write, mode=None, uidgid=None, binary=False):
     fd, temporary_filename = tempfile.mkstemp()
     if mode:
         os.chmod(temporary_filename, mode)
     if uidgid:
         os.chown(temporary_filename, *uidgid)
-    f = os.fdopen(fd, 'w')
+    open_mode = 'wb' if binary else 'w'
+    f = os.fdopen(fd, open_mode)
     try:
         do_write(f)
     finally:
@@ -168,7 +169,8 @@ def write_temp_file(do_write, mode=None, uidgid=None):
     return temporary_filename
 
 
-def replace_file_with_string(target, new_contents, chmod=None, remove_if_empty=False):
+def replace_file_with_string(target, new_contents,
+                             chmod=None, remove_if_empty=False):
     """
 Replace a target file with a new contents
 checks for changes: does not do anything if previous state was already right
@@ -179,8 +181,8 @@ writes in a tmp file, which is then renamed (from sliverauth originally)
 returns True if a change occurred, or the file is deleted
     """
     try:
-        with open(target) as f:
-            current = f.read()
+        with open(target) as feed:
+            current = feed.read()
     except:
         current = ""
     if current == new_contents:
@@ -197,7 +199,7 @@ returns True if a change occurred, or the file is deleted
     # overwrite target file: create a temp in the same directory
     path = os.path.dirname(target) or '.'
     fd, name = tempfile.mkstemp('', 'repl', path)
-    os.write(fd, new_contents)
+    os.write(fd, new_contents.encode())
     os.close(fd)
     if os.path.exists(target):
         os.unlink(target)
@@ -461,7 +463,7 @@ def get_node_virt():
         virt = 'vs' if subprocess.call(['vserver', '--help']) == 0 else 'lxc'
     except:
         virt = 'lxc'
-    with file(virt_stamp, "w") as f:
+    with open(virt_stamp, "w") as f:
         f.write(virt)
     return virt