blob: 2e7a01501dd717f5a32df33247db16932f1407e6 [file] [log] [blame]
Max Rasskazov26787df2015-06-05 14:47:27 +03001#-*- coding: utf-8 -*-
2
3import datetime
Max Rasskazov69c29262015-07-16 19:22:16 +03004import os
Max Rasskazov26787df2015-06-05 14:47:27 +03005
6import utils
7
8from rsync_remote import RsyncRemote
9from utils import singleton
10
11
12@singleton
13class TimeStamp(object):
Max Rasskazov83e10a52015-06-18 14:08:12 +030014 def __init__(self, now=None):
15 # now='2015-06-18-104259'
16 self.snapshot_stamp_format = r'%Y-%m-%d-%H%M%S'
17 self.snapshot_stamp_regexp = r'[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{6}'
18
19 if now is None:
20 self.now = datetime.datetime.utcnow()
21 else:
22 self.now = datetime.datetime.strptime(now,
23 self.snapshot_stamp_format)
24 self.snapshot_stamp = self.now.strftime(self.snapshot_stamp_format)
Max Rasskazov26787df2015-06-05 14:47:27 +030025
26 def __str__(self):
Max Rasskazov83e10a52015-06-18 14:08:12 +030027 return self.snapshot_stamp
Max Rasskazov26787df2015-06-05 14:47:27 +030028
Max Rasskazovd77a5e62015-06-19 17:47:30 +030029 def reinit(self, *args, **kwagrs):
30 self.__init__(*args, **kwagrs)
31
Max Rasskazov26787df2015-06-05 14:47:27 +030032
Max Rasskazov3e837582015-06-17 18:44:15 +030033class TRsync(RsyncRemote):
Max Rasskazov6d7b5c82015-07-13 13:31:58 +030034 # TODO: possible check that rsync url is exists
Max Rasskazov26787df2015-06-05 14:47:27 +030035 def __init__(self,
36 rsync_url,
Max Rasskazov01271622015-06-17 02:35:09 +030037 snapshot_dir='snapshots',
38 latest_successful_postfix='latest',
Max Rasskazov26787df2015-06-05 14:47:27 +030039 save_latest_days=14,
40 init_directory_structure=True,
Max Rasskazov83e10a52015-06-18 14:08:12 +030041 timestamp=None,
Max Rasskazov26787df2015-06-05 14:47:27 +030042 ):
Max Rasskazov3e837582015-06-17 18:44:15 +030043 super(TRsync, self).__init__(rsync_url)
44 self.logger = utils.logger.getChild('TRsync.' + rsync_url)
Max Rasskazov83e10a52015-06-18 14:08:12 +030045 self.timestamp = TimeStamp(timestamp)
Max Rasskazov26787df2015-06-05 14:47:27 +030046 self.logger.info('Using timestamp {}'.format(self.timestamp))
Max Rasskazov46cc0732015-06-05 19:23:24 +030047 self.snapshot_dir = self.url.a_dir(snapshot_dir)
Max Rasskazov26787df2015-06-05 14:47:27 +030048 self.latest_successful_postfix = latest_successful_postfix
49 self.save_latest_days = save_latest_days
50
Max Rasskazov26787df2015-06-05 14:47:27 +030051 if init_directory_structure is True:
52 self.init_directory_structure()
53
54 def init_directory_structure(self):
Max Rasskazov01271622015-06-17 02:35:09 +030055 if self.url.url_type != 'path':
56 server_root = RsyncRemote(self.url.root)
57 return server_root.mkdir(
58 self.url.a_dir(self.url.path, self.snapshot_dir)
59 )
Max Rasskazov26787df2015-06-05 14:47:27 +030060
Max Rasskazov501cea52015-06-29 18:11:25 +030061 def push(self, source, repo_name, symlinks=[], extra=None, save_diff=True):
Max Rasskazov69c29262015-07-16 19:22:16 +030062 repo_basename = os.path.split(repo_name)[-1]
Max Rasskazov46cc0732015-06-05 19:23:24 +030063 latest_path = self.url.a_file(
Max Rasskazov26787df2015-06-05 14:47:27 +030064 self.snapshot_dir,
Max Rasskazov69c29262015-07-16 19:22:16 +030065 '{}-{}'.format(self.url.a_file(repo_basename),
Max Rasskazov26787df2015-06-05 14:47:27 +030066 self.latest_successful_postfix)
67 )
Max Rasskazovdc8df002015-06-25 19:37:41 +030068
69 symlinks = list(symlinks)
70 symlinks.insert(0, latest_path)
71
Max Rasskazov46cc0732015-06-05 19:23:24 +030072 snapshot_name = self.url.a_file(
Max Rasskazov69c29262015-07-16 19:22:16 +030073 '{}-{}'.format(self.url.a_file(repo_basename), self.timestamp)
Max Rasskazov26787df2015-06-05 14:47:27 +030074 )
Max Rasskazov46cc0732015-06-05 19:23:24 +030075 repo_path = self.url.a_file(self.snapshot_dir, snapshot_name)
Max Rasskazov26787df2015-06-05 14:47:27 +030076
Max Rasskazov854399e2015-06-05 16:35:17 +030077 extra = '--link-dest={}'.format(
Max Rasskazov46cc0732015-06-05 19:23:24 +030078 self.url.a_file(self.url.path, latest_path)
Max Rasskazov854399e2015-06-05 16:35:17 +030079 )
Max Rasskazovb1b50832015-06-18 11:24:53 +030080
Max Rasskazovb1b50832015-06-18 11:24:53 +030081 # TODO: split transaction run (push or pull), and
82 # commit/rollback functions. transaction must has possibility to
83 # rollback after commit for implementation of working with pool
84 # of servers. should be something like this:
85 # transactions = list()
86 # result = True
87 # for server in servers:
88 # transactions.append(server.push(source, repo_name))
89 # result = result and transactions[-1].success
90 # if result is True:
91 # for transaction in transactions:
92 # transaction.commit()
93 # result = result and transactions[-1].success
94 # if result is False:
95 # for transaction in transactions:
96 # transaction.rollback()
Max Rasskazova5911852015-06-17 18:29:58 +030097 transaction = list()
98 try:
99 # start transaction
Max Rasskazov3e837582015-06-17 18:44:15 +0300100 result = super(TRsync, self).push(source, repo_path, extra)
Max Rasskazovdc8df002015-06-25 19:37:41 +0300101 transaction.append(lambda p=repo_path: self.rmdir(p))
Max Rasskazova5911852015-06-17 18:29:58 +0300102 self.logger.info('{}'.format(result))
103
Max Rasskazov501cea52015-06-29 18:11:25 +0300104 if save_diff is True:
105 diff_file = self.tmp.get_file(content='{}'.format(result))
106 diff_file_name = '{}.diff.txt'.format(repo_path)
107 super(TRsync, self).push(diff_file, diff_file_name, extra)
108 transaction.append(lambda f=diff_file_name: self.rmfile(f))
109 self.logger.debug('Diff file {} created.'
110 ''.format(diff_file_name))
111
Max Rasskazovdc8df002015-06-25 19:37:41 +0300112 for symlink in symlinks:
113 try:
114 tgt = [_[1] for _ in self.ls_symlinks(symlink)][0]
115 self.logger.info('Previous {} -> {}'.format(symlink, tgt))
116 undo = lambda l=symlink, t=tgt: self.symlink(l, t)
117 except:
118 undo = lambda l=symlink: self.rmfile(l)
119 # TODO: implement detection of target relative symlink
120 if symlink.startswith(self.snapshot_dir):
121 self.symlink(symlink, snapshot_name)
122 else:
123 self.symlink(symlink, repo_path)
124 transaction.append(undo)
Max Rasskazova5911852015-06-17 18:29:58 +0300125
Max Rasskazovad1518a2015-06-18 11:24:16 +0300126 except RuntimeError:
Max Rasskazovdc8df002015-06-25 19:37:41 +0300127 self.logger.error("Rollback transaction because some of sync"
128 "operation failed")
129 [_() for _ in reversed(transaction)]
130 raise
131
132 try:
Max Rasskazova5911852015-06-17 18:29:58 +0300133 # deleting of old snapshots ignored when assessing the transaction
134 # only warning
Max Rasskazovdc8df002015-06-25 19:37:41 +0300135 self._remove_old_snapshots(repo_name)
136 except RuntimeError:
137 self.logger.warn("Old snapshots are not deleted. Ignore. "
138 "May be next time.")
Max Rasskazova5911852015-06-17 18:29:58 +0300139
Max Rasskazov26787df2015-06-05 14:47:27 +0300140 return result
Max Rasskazov452138b2015-06-17 02:37:34 +0300141
142 def _remove_old_snapshots(self, repo_name, save_latest_days=None):
143 if save_latest_days is None:
144 save_latest_days = self.save_latest_days
145 if save_latest_days is None or save_latest_days is False:
146 # delete all snapshots
147 self.logger.info('Deletion all of the old snapshots '
148 '(save_latest_days == {})'
149 ''.format(save_latest_days))
150 save_latest_days = -1
151 elif save_latest_days == 0:
152 # skipping deletion
153 self.logger.info('Skip deletion of old snapshots '
154 '(save_latest_days == {})'
155 ''.format(save_latest_days))
156 return
157 else:
158 # delete snapshots older than
159 self.logger.info('Deletion all of the unlinked snapshots older '
160 'than {0} days (save_latest_days == {0})'
161 ''.format(save_latest_days))
162 warn_date = \
163 self.timestamp.now - datetime.timedelta(days=save_latest_days)
164 warn_date = datetime.datetime.combine(warn_date, datetime.time(0))
165 snapshots = self.ls_dirs(
166 self.url.a_dir(self.snapshot_dir),
167 pattern=r'^{}-{}$'.format(
168 repo_name,
Max Rasskazov83e10a52015-06-18 14:08:12 +0300169 self.timestamp.snapshot_stamp_regexp
Max Rasskazov452138b2015-06-17 02:37:34 +0300170 )
171 )
172 links = self.ls_symlinks(self.url.a_dir())
173 links += self.ls_symlinks(self.url.a_dir(self.snapshot_dir))
174 for s in snapshots:
175 s_date = datetime.datetime.strptime(
176 s,
177 '{}-{}'.format(repo_name,
Max Rasskazov83e10a52015-06-18 14:08:12 +0300178 self.timestamp.snapshot_stamp_format)
Max Rasskazov452138b2015-06-17 02:37:34 +0300179 )
180 s_date = datetime.datetime.combine(s_date, datetime.time(0))
181 s_path = self.url.a_dir(self.snapshot_dir, s)
182 if s_date < warn_date:
183 s_links = [_[0] for _ in links
184 if _[1] == s
185 or _[1].endswith('/{}'.format(s))
186 ]
187 if not s_links:
188 self.rmdir(s_path)
Max Rasskazov052e9112015-06-29 18:43:15 +0300189 self.rmfile(s_path + '.target.txt')
190 self.rmfile(s_path + '.diff.txt')
Max Rasskazov452138b2015-06-17 02:37:34 +0300191 else:
192 self.logger.info('Skip deletion of "{}" because there are '
193 'symlinks found: {}'.format(s, s_links))
194 else:
195 self.logger.info('Skip deletion of "{}" because it newer than '
196 '{} days'.format(s, save_latest_days))