diff options
| author | Andy Grover <agrover@redhat.com> | 2013-02-12 16:17:39 -0800 |
|---|---|---|
| committer | Andy Grover <agrover@redhat.com> | 2013-02-12 16:17:39 -0800 |
| commit | c7bc33ac0ad97a486f48170d8fc3e24269d0675b (patch) | |
| tree | ff34490a0a4a1564a6c568c56909b4e03fa50848 | |
| parent | df39c0a0392af3baccdc2fbf6173731f5ca7bcde (diff) | |
| download | targetcli-c7bc33ac0ad97a486f48170d8fc3e24269d0675b.tar.gz | |
Save N backups of config file
We save so much, they can get smooshed when something goes wrong but
you're just checking it out with targetcli. Save 10.
Only save backups when saving to default location.
Signed-off-by: Andy Grover <agrover@redhat.com>
| -rw-r--r-- | targetcli/ui_root.py | 32 |
1 files changed, 23 insertions, 9 deletions
diff --git a/targetcli/ui_root.py b/targetcli/ui_root.py index 2522a09..a183239 100644 --- a/targetcli/ui_root.py +++ b/targetcli/ui_root.py @@ -27,8 +27,11 @@ import json import shutil import os import stat +from glob import glob +from datetime import datetime default_save_file = "/etc/target/saveconfig.json" +kept_backups = 10 class UIRoot(UINode): ''' @@ -60,22 +63,33 @@ class UIRoot(UINode): savefile = os.path.expanduser(savefile) - backupfile = savefile + ".backup" - try: - shutil.move(savefile, backupfile) - self.shell.log.info("Existing file %s backed up to %s" % \ - (savefile, backupfile.split('/')[-1])) - except IOError: - pass - with open(savefile+".temp", "w+") as f: os.fchmod(f.fileno(), stat.S_IRUSR | stat.S_IWUSR) f.write(json.dumps(RTSRoot().dump(), sort_keys=True, indent=2)) f.write("\n") os.fsync(f.fileno()) - os.rename(savefile+".temp", savefile) + # Only save backups if saving to default location + if savefile == default_save_file: + backup_dir = os.path.dirname(savefile) + "/backup" + backup_name = "saveconfig-" + \ + datetime.now().strftime("%Y%m%d-%H:%M:%S") + ".json" + backupfile = backup_dir + "/" + backup_name + try: + shutil.move(savefile, backupfile) + except IOError: + pass + # Kill excess backups + backups = sorted(glob(os.path.dirname(savefile) + "/backup/*.json")) + files_to_unlink = list(reversed(backups))[kept_backups:] + for f in files_to_unlink: + os.unlink(f) + + self.shell.log.info("Last %d configs saved in %s." % \ + (kept_backups, backup_dir)) + + os.rename(savefile+".temp", savefile) self.shell.log.info("Configuration saved to %s" % savefile) def ui_command_restoreconfig(self, savefile=default_save_file, clear_existing=False): |
