blob: beed3632128f599d3cb17afc288651fb02a1ce79 [file] [log] [blame]
Max Rasskazov26787df2015-06-05 14:47:27 +03001#-*- coding: utf-8 -*-
2
3import datetime
Max Rasskazov26787df2015-06-05 14:47:27 +03004
5import utils
6
7from rsync_remote import RsyncRemote
8from utils import singleton
9
10
11@singleton
12class TimeStamp(object):
Max Rasskazov83e10a52015-06-18 14:08:12 +030013 def __init__(self, now=None):
14 # now='2015-06-18-104259'
15 self.snapshot_stamp_format = r'%Y-%m-%d-%H%M%S'
16 self.snapshot_stamp_regexp = r'[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{6}'
17
18 if now is None:
19 self.now = datetime.datetime.utcnow()
20 else:
21 self.now = datetime.datetime.strptime(now,
22 self.snapshot_stamp_format)
23 self.snapshot_stamp = self.now.strftime(self.snapshot_stamp_format)
Max Rasskazov26787df2015-06-05 14:47:27 +030024
25 def __str__(self):
Max Rasskazov83e10a52015-06-18 14:08:12 +030026 return self.snapshot_stamp
Max Rasskazov26787df2015-06-05 14:47:27 +030027
Max Rasskazovd77a5e62015-06-19 17:47:30 +030028 def reinit(self, *args, **kwagrs):
29 self.__init__(*args, **kwagrs)
30
Max Rasskazov26787df2015-06-05 14:47:27 +030031
Max Rasskazov3e837582015-06-17 18:44:15 +030032class TRsync(RsyncRemote):
Max Rasskazov26787df2015-06-05 14:47:27 +030033 # retry and other function with mirror
34 # add all the needed directory functions here, like mkdir, ls, rm etc
35 # possible check that rsync url is exists
36 def __init__(self,
37 rsync_url,
Max Rasskazov01271622015-06-17 02:35:09 +030038 snapshot_dir='snapshots',
39 latest_successful_postfix='latest',
Max Rasskazov26787df2015-06-05 14:47:27 +030040 save_latest_days=14,
41 init_directory_structure=True,
Max Rasskazov83e10a52015-06-18 14:08:12 +030042 timestamp=None,
Max Rasskazov26787df2015-06-05 14:47:27 +030043 ):
Max Rasskazov3e837582015-06-17 18:44:15 +030044 super(TRsync, self).__init__(rsync_url)
45 self.logger = utils.logger.getChild('TRsync.' + rsync_url)
Max Rasskazov83e10a52015-06-18 14:08:12 +030046 self.timestamp = TimeStamp(timestamp)
Max Rasskazov26787df2015-06-05 14:47:27 +030047 self.logger.info('Using timestamp {}'.format(self.timestamp))
Max Rasskazov46cc0732015-06-05 19:23:24 +030048 self.snapshot_dir = self.url.a_dir(snapshot_dir)
Max Rasskazov26787df2015-06-05 14:47:27 +030049 self.latest_successful_postfix = latest_successful_postfix
50 self.save_latest_days = save_latest_days
51
Max Rasskazov26787df2015-06-05 14:47:27 +030052 if init_directory_structure is True:
53 self.init_directory_structure()
54
55 def init_directory_structure(self):
56 # TODO: self.rsyncRemote.mkdir
Max Rasskazov01271622015-06-17 02:35:09 +030057 if self.url.url_type != 'path':
58 server_root = RsyncRemote(self.url.root)
59 return server_root.mkdir(
60 self.url.a_dir(self.url.path, self.snapshot_dir)
61 )
Max Rasskazov26787df2015-06-05 14:47:27 +030062
Max Rasskazov501cea52015-06-29 18:11:25 +030063 def push(self, source, repo_name, symlinks=[], extra=None, save_diff=True):
Max Rasskazov46cc0732015-06-05 19:23:24 +030064 latest_path = self.url.a_file(
Max Rasskazov26787df2015-06-05 14:47:27 +030065 self.snapshot_dir,
Max Rasskazov46cc0732015-06-05 19:23:24 +030066 '{}-{}'.format(self.url.a_file(repo_name),
Max Rasskazov26787df2015-06-05 14:47:27 +030067 self.latest_successful_postfix)
68 )
Max Rasskazovdc8df002015-06-25 19:37:41 +030069
70 symlinks = list(symlinks)
71 symlinks.insert(0, latest_path)
72
Max Rasskazov46cc0732015-06-05 19:23:24 +030073 snapshot_name = self.url.a_file(
74 '{}-{}'.format(self.url.a_file(repo_name), self.timestamp)
Max Rasskazov26787df2015-06-05 14:47:27 +030075 )
Max Rasskazov46cc0732015-06-05 19:23:24 +030076 repo_path = self.url.a_file(self.snapshot_dir, snapshot_name)
Max Rasskazov26787df2015-06-05 14:47:27 +030077
Max Rasskazov854399e2015-06-05 16:35:17 +030078 extra = '--link-dest={}'.format(
Max Rasskazov46cc0732015-06-05 19:23:24 +030079 self.url.a_file(self.url.path, latest_path)
Max Rasskazov854399e2015-06-05 16:35:17 +030080 )
Max Rasskazovb1b50832015-06-18 11:24:53 +030081
Max Rasskazova5911852015-06-17 18:29:58 +030082 # TODO: retry on base class!!!!!!!!!!!!!!!
83 # TODO: locking - symlink dir-timestamp.lock -> dir-timestamp
Max Rasskazovb1b50832015-06-18 11:24:53 +030084 # TODO: split transaction run (push or pull), and
85 # commit/rollback functions. transaction must has possibility to
86 # rollback after commit for implementation of working with pool
87 # of servers. should be something like this:
88 # transactions = list()
89 # result = True
90 # for server in servers:
91 # transactions.append(server.push(source, repo_name))
92 # result = result and transactions[-1].success
93 # if result is True:
94 # for transaction in transactions:
95 # transaction.commit()
96 # result = result and transactions[-1].success
97 # if result is False:
98 # for transaction in transactions:
99 # transaction.rollback()
Max Rasskazova5911852015-06-17 18:29:58 +0300100 transaction = list()
101 try:
102 # start transaction
Max Rasskazov3e837582015-06-17 18:44:15 +0300103 result = super(TRsync, self).push(source, repo_path, extra)
Max Rasskazovdc8df002015-06-25 19:37:41 +0300104 transaction.append(lambda p=repo_path: self.rmdir(p))
Max Rasskazova5911852015-06-17 18:29:58 +0300105 self.logger.info('{}'.format(result))
106
Max Rasskazov501cea52015-06-29 18:11:25 +0300107 if save_diff is True:
108 diff_file = self.tmp.get_file(content='{}'.format(result))
109 diff_file_name = '{}.diff.txt'.format(repo_path)
110 super(TRsync, self).push(diff_file, diff_file_name, extra)
111 transaction.append(lambda f=diff_file_name: self.rmfile(f))
112 self.logger.debug('Diff file {} created.'
113 ''.format(diff_file_name))
114
Max Rasskazovdc8df002015-06-25 19:37:41 +0300115 for symlink in symlinks:
116 try:
117 tgt = [_[1] for _ in self.ls_symlinks(symlink)][0]
118 self.logger.info('Previous {} -> {}'.format(symlink, tgt))
119 undo = lambda l=symlink, t=tgt: self.symlink(l, t)
120 except:
121 undo = lambda l=symlink: self.rmfile(l)
122 # TODO: implement detection of target relative symlink
123 if symlink.startswith(self.snapshot_dir):
124 self.symlink(symlink, snapshot_name)
125 else:
126 self.symlink(symlink, repo_path)
127 transaction.append(undo)
Max Rasskazova5911852015-06-17 18:29:58 +0300128
Max Rasskazovad1518a2015-06-18 11:24:16 +0300129 except RuntimeError:
Max Rasskazovdc8df002015-06-25 19:37:41 +0300130 self.logger.error("Rollback transaction because some of sync"
131 "operation failed")
132 [_() for _ in reversed(transaction)]
133 raise
134
135 try:
Max Rasskazova5911852015-06-17 18:29:58 +0300136 # deleting of old snapshots ignored when assessing the transaction
137 # only warning
Max Rasskazovdc8df002015-06-25 19:37:41 +0300138 self._remove_old_snapshots(repo_name)
139 except RuntimeError:
140 self.logger.warn("Old snapshots are not deleted. Ignore. "
141 "May be next time.")
Max Rasskazova5911852015-06-17 18:29:58 +0300142
Max Rasskazov26787df2015-06-05 14:47:27 +0300143 return result
Max Rasskazov452138b2015-06-17 02:37:34 +0300144
145 def _remove_old_snapshots(self, repo_name, save_latest_days=None):
146 if save_latest_days is None:
147 save_latest_days = self.save_latest_days
148 if save_latest_days is None or save_latest_days is False:
149 # delete all snapshots
150 self.logger.info('Deletion all of the old snapshots '
151 '(save_latest_days == {})'
152 ''.format(save_latest_days))
153 save_latest_days = -1
154 elif save_latest_days == 0:
155 # skipping deletion
156 self.logger.info('Skip deletion of old snapshots '
157 '(save_latest_days == {})'
158 ''.format(save_latest_days))
159 return
160 else:
161 # delete snapshots older than
162 self.logger.info('Deletion all of the unlinked snapshots older '
163 'than {0} days (save_latest_days == {0})'
164 ''.format(save_latest_days))
165 warn_date = \
166 self.timestamp.now - datetime.timedelta(days=save_latest_days)
167 warn_date = datetime.datetime.combine(warn_date, datetime.time(0))
168 snapshots = self.ls_dirs(
169 self.url.a_dir(self.snapshot_dir),
170 pattern=r'^{}-{}$'.format(
171 repo_name,
Max Rasskazov83e10a52015-06-18 14:08:12 +0300172 self.timestamp.snapshot_stamp_regexp
Max Rasskazov452138b2015-06-17 02:37:34 +0300173 )
174 )
175 links = self.ls_symlinks(self.url.a_dir())
176 links += self.ls_symlinks(self.url.a_dir(self.snapshot_dir))
177 for s in snapshots:
178 s_date = datetime.datetime.strptime(
179 s,
180 '{}-{}'.format(repo_name,
Max Rasskazov83e10a52015-06-18 14:08:12 +0300181 self.timestamp.snapshot_stamp_format)
Max Rasskazov452138b2015-06-17 02:37:34 +0300182 )
183 s_date = datetime.datetime.combine(s_date, datetime.time(0))
184 s_path = self.url.a_dir(self.snapshot_dir, s)
185 if s_date < warn_date:
186 s_links = [_[0] for _ in links
187 if _[1] == s
188 or _[1].endswith('/{}'.format(s))
189 ]
190 if not s_links:
191 self.rmdir(s_path)
192 else:
193 self.logger.info('Skip deletion of "{}" because there are '
194 'symlinks found: {}'.format(s, s_links))
195 else:
196 self.logger.info('Skip deletion of "{}" because it newer than '
197 '{} days'.format(s, save_latest_days))