blob: 88e5b20e40463a055c954d84977aadf986684097 [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:
Max Rasskazova5911852015-06-17 18:29:58 +0300105 old_latest_path_symlink_target = \
106 [_[1] for _ in self.ls_symlinks(latest_path)][0]
107 self.logger.info('Previous {} -> {}'
108 ''.format(latest_path,
109 old_latest_path_symlink_target))
110 status = 'updated'
111 except:
112 status = 'created'
113 self.symlink(latest_path, snapshot_name)
114 transaction.append('symlink_latest_path_{}'.format(status))
115
116 self._remove_old_snapshots(repo_name)
117 transaction.append('old_snapshots_deleted')
118
Max Rasskazovad1518a2015-06-18 11:24:16 +0300119 except RuntimeError:
Max Rasskazova5911852015-06-17 18:29:58 +0300120 # deleting of old snapshots ignored when assessing the transaction
121 # only warning
122 if 'old_snapshots_deleted' not in transaction:
123 self.logger.warn("Old snapshots are not deleted. Ignore. "
124 "May be next time.")
125 transaction.append('old_snapshots_deleted')
126
127 if len(transaction) < 4:
128 # rollback transaction if some of sync operations failed
129
130 if 'symlink_latest_path_updated' in transaction:
131 self.logger.info('Restoring symlink {} -> {}'
132 ''.format(latest_path,
133 old_latest_path_symlink_target))
134 self.symlink(latest_path, old_latest_path_symlink_target)
135 elif 'symlink_latest_path_created' in transaction:
136 self.logger.info('Deleting symlink {}'.format(latest_path))
137 self.rmfile(latest_path)
138
Max Rasskazova5911852015-06-17 18:29:58 +0300139 if 'repo_dir_created' in transaction:
140 self.logger.info('Removing snapshot {}'.format(repo_path))
141 self.rmdir(repo_path)
142 raise
143
Max Rasskazov26787df2015-06-05 14:47:27 +0300144 return result
Max Rasskazov452138b2015-06-17 02:37:34 +0300145
146 def _remove_old_snapshots(self, repo_name, save_latest_days=None):
147 if save_latest_days is None:
148 save_latest_days = self.save_latest_days
149 if save_latest_days is None or save_latest_days is False:
150 # delete all snapshots
151 self.logger.info('Deletion all of the old snapshots '
152 '(save_latest_days == {})'
153 ''.format(save_latest_days))
154 save_latest_days = -1
155 elif save_latest_days == 0:
156 # skipping deletion
157 self.logger.info('Skip deletion of old snapshots '
158 '(save_latest_days == {})'
159 ''.format(save_latest_days))
160 return
161 else:
162 # delete snapshots older than
163 self.logger.info('Deletion all of the unlinked snapshots older '
164 'than {0} days (save_latest_days == {0})'
165 ''.format(save_latest_days))
166 warn_date = \
167 self.timestamp.now - datetime.timedelta(days=save_latest_days)
168 warn_date = datetime.datetime.combine(warn_date, datetime.time(0))
169 snapshots = self.ls_dirs(
170 self.url.a_dir(self.snapshot_dir),
171 pattern=r'^{}-{}$'.format(
172 repo_name,
Max Rasskazov83e10a52015-06-18 14:08:12 +0300173 self.timestamp.snapshot_stamp_regexp
Max Rasskazov452138b2015-06-17 02:37:34 +0300174 )
175 )
176 links = self.ls_symlinks(self.url.a_dir())
177 links += self.ls_symlinks(self.url.a_dir(self.snapshot_dir))
178 for s in snapshots:
179 s_date = datetime.datetime.strptime(
180 s,
181 '{}-{}'.format(repo_name,
Max Rasskazov83e10a52015-06-18 14:08:12 +0300182 self.timestamp.snapshot_stamp_format)
Max Rasskazov452138b2015-06-17 02:37:34 +0300183 )
184 s_date = datetime.datetime.combine(s_date, datetime.time(0))
185 s_path = self.url.a_dir(self.snapshot_dir, s)
186 if s_date < warn_date:
187 s_links = [_[0] for _ in links
188 if _[1] == s
189 or _[1].endswith('/{}'.format(s))
190 ]
191 if not s_links:
192 self.rmdir(s_path)
193 else:
194 self.logger.info('Skip deletion of "{}" because there are '
195 'symlinks found: {}'.format(s, s_links))
196 else:
197 self.logger.info('Skip deletion of "{}" because it newer than '
198 '{} days'.format(s, save_latest_days))