From 103a8233b1056082c2522e8283ddbe3bfbdf8370 Mon Sep 17 00:00:00 2001 From: Ben Swartzlander Date: Tue, 10 Oct 2017 17:23:31 -0400 Subject: [PATCH] Add utils methods to write files Add utils methods for writing local and remote files. Change-Id: I8f74909e9e4842668f41fc74452fbcb8e3350b59 --- etc/manila/rootwrap.d/share.filters | 3 +++ manila/utils.py | 26 ++++++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/etc/manila/rootwrap.d/share.filters b/etc/manila/rootwrap.d/share.filters index bbe8f30a57..416b466bc0 100644 --- a/etc/manila/rootwrap.d/share.filters +++ b/etc/manila/rootwrap.d/share.filters @@ -179,3 +179,6 @@ lvconvert: CommandFilter, lvconvert, root # manila/data/utils.py: 'sha256sum', '%s' sha256sum: CommandFilter, sha256sum, root + +# manila/utils.py: 'tee', '%s' +tee: CommandFilter, tee, root diff --git a/manila/utils.py b/manila/utils.py index 2cf94fc22f..de84c7ee5d 100644 --- a/manila/utils.py +++ b/manila/utils.py @@ -682,3 +682,29 @@ def if_notifications_enabled(function): return function(*args, **kwargs) return DO_NOTHING return wrapped + + +def write_local_file(filename, contents, as_root=False): + tmp_filename = "%s.tmp" % filename + if as_root: + execute('tee', tmp_filename, run_as_root=True, process_input=contents) + execute('mv', '-f', tmp_filename, filename, run_as_root=True) + else: + with open(tmp_filename, 'w') as f: + f.write(contents) + os.rename(tmp_filename, filename) + + +def write_remote_file(ssh, filename, contents, as_root=False): + tmp_filename = "%s.tmp" % filename + if as_root: + cmd = 'sudo tee "%s" > /dev/null' % tmp_filename + cmd2 = 'sudo mv -f "%s" "%s"' % (tmp_filename, filename) + else: + cmd = 'cat > "%s"' % tmp_filename + cmd2 = 'mv -f "%s" "%s"' % (tmp_filename, filename) + stdin, __, __ = ssh.exec_command(cmd) + stdin.write(contents) + stdin.close() + stdin.channel.shutdown_write() + ssh.exec_command(cmd2)