blob: 6498d4483078c2d31d422c2f65301daf34ea37cb [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 Rasskazovdc8df002015-06-25 19:37:41 +030063 def push(self, source, repo_name, symlinks=[], extra=None):
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 Rasskazovdc8df002015-06-25 19:37:41 +0300107 for symlink in symlinks:
108 try:
109 tgt = [_[1] for _ in self.ls_symlinks(symlink)][0]
110 self.logger.info('Previous {} -> {}'.format(symlink, tgt))
111 undo = lambda l=symlink, t=tgt: self.symlink(l, t)
112 except:
113 undo = lambda l=symlink: self.rmfile(l)
114 # TODO: implement detection of target relative symlink
115 if symlink.startswith(self.snapshot_dir):
116 self.symlink(symlink, snapshot_name)
117 else:
118 self.symlink(symlink, repo_path)
119 transaction.append(undo)
Max Rasskazova5911852015-06-17 18:29:58 +0300120
Max Rasskazovad1518a2015-06-18 11:24:16 +0300121 except RuntimeError:
Max Rasskazovdc8df002015-06-25 19:37:41 +0300122 self.logger.error("Rollback transaction because some of sync"
123 "operation failed")
124 [_() for _ in reversed(transaction)]
125 raise
126
127 try:
Max Rasskazova5911852015-06-17 18:29:58 +0300128 # deleting of old snapshots ignored when assessing the transaction
129 # only warning
Max Rasskazovdc8df002015-06-25 19:37:41 +0300130 self._remove_old_snapshots(repo_name)
131 except RuntimeError:
132 self.logger.warn("Old snapshots are not deleted. Ignore. "
133 "May be next time.")
Max Rasskazova5911852015-06-17 18:29:58 +0300134
Max Rasskazov26787df2015-06-05 14:47:27 +0300135 return result
Max Rasskazov452138b2015-06-17 02:37:34 +0300136
137 def _remove_old_snapshots(self, repo_name, save_latest_days=None):
138 if save_latest_days is None:
139 save_latest_days = self.save_latest_days
140 if save_latest_days is None or save_latest_days is False:
141 # delete all snapshots
142 self.logger.info('Deletion all of the old snapshots '
143 '(save_latest_days == {})'
144 ''.format(save_latest_days))
145 save_latest_days = -1
146 elif save_latest_days == 0:
147 # skipping deletion
148 self.logger.info('Skip deletion of old snapshots '
149 '(save_latest_days == {})'
150 ''.format(save_latest_days))
151 return
152 else:
153 # delete snapshots older than
154 self.logger.info('Deletion all of the unlinked snapshots older '
155 'than {0} days (save_latest_days == {0})'
156 ''.format(save_latest_days))
157 warn_date = \
158 self.timestamp.now - datetime.timedelta(days=save_latest_days)
159 warn_date = datetime.datetime.combine(warn_date, datetime.time(0))
160 snapshots = self.ls_dirs(
161 self.url.a_dir(self.snapshot_dir),
162 pattern=r'^{}-{}$'.format(
163 repo_name,
Max Rasskazov83e10a52015-06-18 14:08:12 +0300164 self.timestamp.snapshot_stamp_regexp
Max Rasskazov452138b2015-06-17 02:37:34 +0300165 )
166 )
167 links = self.ls_symlinks(self.url.a_dir())
168 links += self.ls_symlinks(self.url.a_dir(self.snapshot_dir))
169 for s in snapshots:
170 s_date = datetime.datetime.strptime(
171 s,
172 '{}-{}'.format(repo_name,
Max Rasskazov83e10a52015-06-18 14:08:12 +0300173 self.timestamp.snapshot_stamp_format)
Max Rasskazov452138b2015-06-17 02:37:34 +0300174 )
175 s_date = datetime.datetime.combine(s_date, datetime.time(0))
176 s_path = self.url.a_dir(self.snapshot_dir, s)
177 if s_date < warn_date:
178 s_links = [_[0] for _ in links
179 if _[1] == s
180 or _[1].endswith('/{}'.format(s))
181 ]
182 if not s_links:
183 self.rmdir(s_path)
184 else:
185 self.logger.info('Skip deletion of "{}" because there are '
186 'symlinks found: {}'.format(s, s_links))
187 else:
188 self.logger.info('Skip deletion of "{}" because it newer than '
189 '{} days'.format(s, save_latest_days))