- backupdir = os.path.join(self.location, ".scripts", "backups")
- backup = str(self.version) + "-" + datetime.date.today().isoformat()
- outdir = os.path.join(backupdir, backup)
- if not os.path.exists(backupdir):
- os.mkdir(backupdir)
- if os.path.exists(outdir):
- util.safe_unlink(outdir)
- os.mkdir(outdir)
- self.application.backup(self, outdir, options)
+ # There are retarded amounts of race-safety in this function,
+ # because we do NOT want to claim to have made a backup, when
+ # actually something weird happened to it.
+ if not os.path.exists(self.backup_dir):
+ try:
+ os.mkdir(self.backup_dir)
+ except OSError as e:
+ if e.errno == errno.EEXIST:
+ pass
+ else:
+ raise
+ tmpdir = tempfile.mkdtemp() # actually will be kept around
+ try:
+ self.application.backup(self, tmpdir, options)
+ except app.BackupFailure:
+ # the backup is bogus, don't let it show up
+ shutil.rmtree(tmpdir)
+ raise
+ backup = None
+ with util.LockDirectory(os.path.join(self.backup_dir, "lock")):
+ while 1:
+ backup = str(self.version) + "-" + datetime.datetime.today().strftime("%Y-%m-%dT%H%M%S")
+ outdir = os.path.join(self.backup_dir, backup)
+ if os.path.exists(outdir):
+ logging.warning("Backup: A backup occurred in the last second. Trying again in a second...")
+ time.sleep(1)
+ continue
+ try:
+ shutil.move(tmpdir, outdir)
+ except:
+ # don't leave half-baked stuff lying around
+ try:
+ shutil.rmtree(outdir)
+ except OSError:
+ pass
+ raise
+ break