blob: 5ee5b2eddb6d0fd27e0d92c9ca284861fd2ab1ac [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
63 def push(self, source, repo_name, 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 Rasskazov46cc0732015-06-05 19:23:24 +030069 snapshot_name = self.url.a_file(
70 '{}-{}'.format(self.url.a_file(repo_name), self.timestamp)
Max Rasskazov26787df2015-06-05 14:47:27 +030071 )
Max Rasskazov46cc0732015-06-05 19:23:24 +030072 repo_path = self.url.a_file(self.snapshot_dir, snapshot_name)
Max Rasskazov26787df2015-06-05 14:47:27 +030073
Max Rasskazov854399e2015-06-05 16:35:17 +030074 extra = '--link-dest={}'.format(
Max Rasskazov46cc0732015-06-05 19:23:24 +030075 self.url.a_file(self.url.path, latest_path)
Max Rasskazov854399e2015-06-05 16:35:17 +030076 )
Max Rasskazovb1b50832015-06-18 11:24:53 +030077
Max Rasskazova5911852015-06-17 18:29:58 +030078 # TODO: retry on base class!!!!!!!!!!!!!!!
79 # TODO: locking - symlink dir-timestamp.lock -> dir-timestamp
Max Rasskazovb1b50832015-06-18 11:24:53 +030080 # TODO: write status file with symlink info
81 # 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 Rasskazova5911852015-06-17 18:29:58 +0300101 transaction.append('repo_dir_created')
102 self.logger.info('{}'.format(result))
103
104 try:
105 old_repo_name_symlink_target = \
106 [_[1] for _ in self.ls_symlinks(repo_name)][0]
107 self.logger.info('Previous {} -> {}'
108 ''.format(repo_name,
109 old_repo_name_symlink_target))
110 status = 'updated'
111 except:
112 status = 'created'
113 self.symlink(repo_name, repo_path)
114 transaction.append('symlink_repo_name_{}'.format(status))
115
116 try:
117 old_latest_path_symlink_target = \
118 [_[1] for _ in self.ls_symlinks(latest_path)][0]
119 self.logger.info('Previous {} -> {}'
120 ''.format(latest_path,
121 old_latest_path_symlink_target))
122 status = 'updated'
123 except:
124 status = 'created'
125 self.symlink(latest_path, snapshot_name)
126 transaction.append('symlink_latest_path_{}'.format(status))
127
128 self._remove_old_snapshots(repo_name)
129 transaction.append('old_snapshots_deleted')
130
Max Rasskazovad1518a2015-06-18 11:24:16 +0300131 except RuntimeError:
Max Rasskazova5911852015-06-17 18:29:58 +0300132 # deleting of old snapshots ignored when assessing the transaction
133 # only warning
134 if 'old_snapshots_deleted' not in transaction:
135 self.logger.warn("Old snapshots are not deleted. Ignore. "
136 "May be next time.")
137 transaction.append('old_snapshots_deleted')
138
139 if len(transaction) < 4:
140 # rollback transaction if some of sync operations failed
141
142 if 'symlink_latest_path_updated' in transaction:
143 self.logger.info('Restoring symlink {} -> {}'
144 ''.format(latest_path,
145 old_latest_path_symlink_target))
146 self.symlink(latest_path, old_latest_path_symlink_target)
147 elif 'symlink_latest_path_created' in transaction:
148 self.logger.info('Deleting symlink {}'.format(latest_path))
149 self.rmfile(latest_path)
150
151 if 'symlink_repo_name_updated' in transaction:
152 self.logger.info('Restoring symlink {} -> {}'
153 ''.format(repo_name,
154 old_repo_name_symlink_target))
155 self.symlink(repo_name, old_repo_name_symlink_target)
156 elif 'symlink_repo_name_created' in transaction:
157 self.logger.info('Deleting symlink {}'.format(repo_name))
158 self.rmfile(repo_name)
159
160 if 'repo_dir_created' in transaction:
161 self.logger.info('Removing snapshot {}'.format(repo_path))
162 self.rmdir(repo_path)
163 raise
164
Max Rasskazov26787df2015-06-05 14:47:27 +0300165 return result
Max Rasskazov452138b2015-06-17 02:37:34 +0300166
167 def _remove_old_snapshots(self, repo_name, save_latest_days=None):
168 if save_latest_days is None:
169 save_latest_days = self.save_latest_days
170 if save_latest_days is None or save_latest_days is False:
171 # delete all snapshots
172 self.logger.info('Deletion all of the old snapshots '
173 '(save_latest_days == {})'
174 ''.format(save_latest_days))
175 save_latest_days = -1
176 elif save_latest_days == 0:
177 # skipping deletion
178 self.logger.info('Skip deletion of old snapshots '
179 '(save_latest_days == {})'
180 ''.format(save_latest_days))
181 return
182 else:
183 # delete snapshots older than
184 self.logger.info('Deletion all of the unlinked snapshots older '
185 'than {0} days (save_latest_days == {0})'
186 ''.format(save_latest_days))
187 warn_date = \
188 self.timestamp.now - datetime.timedelta(days=save_latest_days)
189 warn_date = datetime.datetime.combine(warn_date, datetime.time(0))
190 snapshots = self.ls_dirs(
191 self.url.a_dir(self.snapshot_dir),
192 pattern=r'^{}-{}$'.format(
193 repo_name,
Max Rasskazov83e10a52015-06-18 14:08:12 +0300194 self.timestamp.snapshot_stamp_regexp
Max Rasskazov452138b2015-06-17 02:37:34 +0300195 )
196 )
197 links = self.ls_symlinks(self.url.a_dir())
198 links += self.ls_symlinks(self.url.a_dir(self.snapshot_dir))
199 for s in snapshots:
200 s_date = datetime.datetime.strptime(
201 s,
202 '{}-{}'.format(repo_name,
Max Rasskazov83e10a52015-06-18 14:08:12 +0300203 self.timestamp.snapshot_stamp_format)
Max Rasskazov452138b2015-06-17 02:37:34 +0300204 )
205 s_date = datetime.datetime.combine(s_date, datetime.time(0))
206 s_path = self.url.a_dir(self.snapshot_dir, s)
207 if s_date < warn_date:
208 s_links = [_[0] for _ in links
209 if _[1] == s
210 or _[1].endswith('/{}'.format(s))
211 ]
212 if not s_links:
213 self.rmdir(s_path)
214 else:
215 self.logger.info('Skip deletion of "{}" because there are '
216 'symlinks found: {}'.format(s, s_links))
217 else:
218 self.logger.info('Skip deletion of "{}" because it newer than '
219 '{} days'.format(s, save_latest_days))