setup.py 11.4 KB
Newer Older
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Copyright (C) 2015 GRNET S.A.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

16
import os
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
17
import sys
18
19
import threading
import logging
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
20
import ctypes
21
import stat
22

23
24
from functools import wraps

25
from agkyra.syncer.utils import join_path, ThreadSafeDict
26
from agkyra.syncer.database import TransactedConnection
27
from agkyra.syncer.messaging import Messager
28
from agkyra.syncer import utils, common, database
29

30
from kamaki.clients import ClientError, KamakiSSLError
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

from kamaki.clients.astakos import AstakosClient
from kamaki.clients.pithos import PithosClient
from kamaki.clients.utils import https

logger = logging.getLogger(__name__)


DEFAULT_CACHE_NAME = '.agkyra_cache'
DEFAULT_CACHE_HIDE_NAME = 'hidden'
DEFAULT_CACHE_STAGE_NAME = 'staged'
DEFAULT_CACHE_FETCH_NAME = 'fetched'
GLOBAL_SETTINGS_NAME = '.agkyra'
DEFAULT_DBNAME = "syncer.db"
DEFAULT_ACTION_MAX_WAIT = 10
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
46
47
DEFAULT_PITHOS_LIST_INTERVAL = 5
DEFAULT_CONNECTION_RETRY_LIMIT = 3
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
48
INSTANCES_NAME = 'instances'
49
DEFAULT_MAX_ALIVE_SYNC_THREADS = 25
50
51
52

thread_local_data = threading.local()

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
53
54
55
56
57
58
59
60
61
62
63
if getattr(sys, 'frozen', False):
    # we are running in a |PyInstaller| bundle
    BASEDIR = sys._MEIPASS
    ISFROZEN = True
else:
    # we are running in a normal Python environment
    CURDIR = os.path.dirname(os.path.realpath(__file__))
    BASEDIR = os.path.dirname(CURDIR)
    ISFROZEN = False

RESOURCES = os.path.join(BASEDIR, 'resources')
64

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
65
66
67
68
69
def get_instance(elems):
    data = "".join(elems)
    return utils.hash_string(data)


70
71
def ssl_fall_back(method):
    """Catch an SSL error while executing a method, patch kamaki and retry"""
72
    @wraps(method)
73
74
75
76
77
78
79
    def wrap(self, *args, **kwargs):
        try:
            return method(self, *args, **kwargs)
        except KamakiSSLError as ssle:
            logger.debug('Kamaki SSL failed %s' % ssle)
            logger.info(
                'Kamaki SSL failed, fall back to certifi (mozilla certs)')
80
            https.patch_with_certs(os.path.join(RESOURCES, 'cacert.pem'))
81
82
83
84
            return method(self, *args, **kwargs)
    return wrap


Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
85
86
87
88
89
90
91
92
93
94
def check_encoding():
    platform = utils.PLATFORM
    encoding = utils.ENCODING
    if platform.startswith("linux"):
        if not encoding.lower() in ['utf-8', 'utf8']:
            raise Exception(
                "Cannot operate with encoding %s. Please use UTF-8."
                % encoding)


Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
95
96
97
98
def win_hide_file(path):
    ctypes.windll.kernel32.SetFileAttributesW(path, 2)


99
class SyncerSettings():
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
100
    def __init__(self, auth_url, auth_token, container, local_root_path,
101
                 *args, **kwargs):
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
102
103
104
105
106
        check_encoding()
        auth_url = utils.to_unicode(auth_url)
        auth_token = utils.to_unicode(auth_token)
        container = utils.to_unicode(container)
        local_root_path = utils.to_unicode(local_root_path)
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
107
        self.auth_url = utils.normalize_standard_suffix(auth_url)
108
        self.auth_token = auth_token
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
109
        self.container = utils.normalize_standard_suffix(container)
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
110
111
112
113

        self.ignore_ssl = kwargs.get("ignore_ssl", False)
        if self.ignore_ssl:
            https.patch_ignore_ssl()
114
115
116
        elif kwargs.get('ca_certs', None):
            https.patch_with_certs(kwargs['ca_certs'])

117
118
119
        self.endpoint = self._get_pithos_client(
            auth_url, auth_token, container)

120
121
        container_exists = self.check_container_exists(container)

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
122
        home_dir = utils.to_unicode(os.path.expanduser('~'))
123
        default_settings_path = join_path(home_dir, GLOBAL_SETTINGS_NAME)
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
124
125
        self.settings_path = utils.to_unicode(
            kwargs.get("agkyra_path", default_settings_path))
126
        self.create_dir(self.settings_path, mode=stat.S_IRWXU)
127

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
128
129
130
131
        self.instances_path = join_path(self.settings_path, INSTANCES_NAME)
        self.create_dir(self.instances_path)

        self.local_root_path = utils.normalize_local_suffix(local_root_path)
132
        local_root_path_exists = os.path.isdir(self.local_root_path)
133

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
134
135
        self.cache_name = utils.to_unicode(
            kwargs.get("cache_name", DEFAULT_CACHE_NAME))
136
137
        self.cache_path = join_path(self.local_root_path, self.cache_name)

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
138
139
        self.cache_hide_name = utils.to_unicode(
            kwargs.get("cache_hide_name", DEFAULT_CACHE_HIDE_NAME))
140
141
        self.cache_hide_path = join_path(self.cache_path, self.cache_hide_name)

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
142
143
        self.cache_stage_name = utils.to_unicode(
            kwargs.get("cache_stage_name", DEFAULT_CACHE_STAGE_NAME))
144
145
146
        self.cache_stage_path = join_path(self.cache_path,
                                          self.cache_stage_name)

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
147
148
        self.cache_fetch_name = utils.to_unicode(
            kwargs.get("cache_fetch_name", DEFAULT_CACHE_FETCH_NAME))
149
150
        self.cache_fetch_path = join_path(self.cache_path,
                                          self.cache_fetch_name)
151
152
153
154
155
156
157
158
159
160

        self.user_id = self.endpoint.account
        self.instance = get_instance(
            [self.auth_url, self.user_id,
             self.container, self.local_root_path])
        self.instance_path = join_path(self.instances_path, self.instance)
        self.create_dir(self.instance_path)

        self.dbname = utils.to_unicode(kwargs.get("dbname", DEFAULT_DBNAME))
        self.full_dbname = join_path(self.instance_path, self.dbname)
161
162
163
        self.syncer_dbtuple = common.DBTuple(
            dbtype=database.SyncerDB,
            dbname=self.full_dbname)
164
165
166

        db_existed = os.path.isfile(self.full_dbname)
        if not db_existed:
167
            database.initialize(self.syncer_dbtuple)
168

169
        self.mtime_lag = 0
170
        self.case_insensitive = False
171

172
173
174
175
176
177
178
179
180
        if not db_existed:
            self.set_localfs_enabled(True)
            self.create_local_dirs()
            self.set_pithos_enabled(True)
            if not container_exists:
                self.mk_container(container)
        else:
            if not local_root_path_exists:
                self.set_localfs_enabled(False)
181
182
            else:
                self.create_local_dirs()
183
184
            if not container_exists:
                self.set_pithos_enabled(False)
185

186
        self.heartbeat = ThreadSafeDict()
187
188
        self.action_max_wait = kwargs.get("action_max_wait",
                                          DEFAULT_ACTION_MAX_WAIT)
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
189
190
191
192
193
194
        self.pithos_list_interval = kwargs.get("pithos_list_interval",
                                               DEFAULT_PITHOS_LIST_INTERVAL)

        self.connection_retry_limit = kwargs.get(
            "connection_retry_limit", DEFAULT_CONNECTION_RETRY_LIMIT)
        self.endpoint.CONNECTION_RETRY_LIMIT = self.connection_retry_limit
195
196
        self.max_alive_sync_threads = kwargs.get(
            "max_alive_sync_threads", DEFAULT_MAX_ALIVE_SYNC_THREADS)
197
        self.messager = Messager()
198

199
200
201
    def create_local_dirs(self):
        self.create_dir(self.local_root_path)
        self.create_dir(self.cache_path)
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
202
203
        if utils.iswin():
            win_hide_file(self.cache_path)
204
205
206
        self.create_dir(self.cache_hide_path)
        self.create_dir(self.cache_stage_path)
        self.create_dir(self.cache_fetch_path)
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
207
        self.set_mtime_lag()
208
        self.set_case_insensitive()
209
210
211
212
213
214
215
216

    def determine_mtime_lag(self):
        st = os.stat(self.cache_path)
        mtime = st.st_mtime
        if mtime.is_integer():
            return 1.1
        return 0

217
    def set_mtime_lag(self):
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
218
        lag = self.determine_mtime_lag()
219
        logger.info("Setting mtime_lag = %s" % lag)
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
220
        self.mtime_lag = lag
221

222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
    def determine_fs_case_insensitive(self):
        path = self.cache_hide_path
        altered = path.upper() if not path.isupper() else path.lower()
        try:
            os.stat(altered)
            return True
        except OSError:
            return False

    def set_case_insensitive(self):
        case_insensitive = self.determine_fs_case_insensitive()
        case = "in" if case_insensitive else ""
        logger.info("Filesystem is case-%ssensitive" % case)
        self.case_insensitive = case_insensitive

237
    def create_dir(self, path, mode=0777):
238
239
240
241
242
        if os.path.exists(path):
            if os.path.isdir(path):
                return
            raise Exception("Cannot create dir '%s'; file exists" % path)
        logger.warning("Creating dir: '%s'" % path)
243
        os.makedirs(path, mode=mode)
244
245
        return path

246
    @ssl_fall_back
247
248
249
250
251
252
253
254
255
256
257
258
259
    def _get_pithos_client(self, auth_url, token, container):
        try:
            astakos = AstakosClient(auth_url, token)
        except ClientError:
            logger.error("Failed to authenticate user token")
            raise
        try:
            PITHOS_URL = astakos.get_endpoint_url(PithosClient.service_type)
        except ClientError:
            logger.error("Failed to get endpoints for Pithos")
            raise
        try:
            account = astakos.user_info['id']
260
            return PithosClient(PITHOS_URL, token, account, container)
261
262
263
        except ClientError:
            logger.error("Failed to initialize Pithos client")
            raise
264
265

    def check_container_exists(self, container):
266
        try:
267
268
            self.endpoint.get_container_info(container)
            return True
269
270
        except ClientError as e:
            if e.status == 404:
271
                return False
272
273
274
            else:
                raise

275
276
277
278
279
280
281
282
283
    def mk_container(self, container):
        try:
            self.endpoint.create_container(container)
            logger.warning("Creating container '%s'" % container)
        except ClientError:
            logger.error("Failed to create container '%s'" % container)
            raise

    def set_localfs_enabled(self, enabled):
284
285
        with TransactedConnection(self.syncer_dbtuple) as db:
            self._set_localfs_enabled(db, enabled)
286
287
288
289
290

    def _set_localfs_enabled(self, db, enabled):
        db.set_config("localfs_enabled", enabled)

    def set_pithos_enabled(self, enabled):
291
292
        with TransactedConnection(self.syncer_dbtuple) as db:
            self._set_pithos_enabled(db, enabled)
293
294
295
296
297

    def _set_pithos_enabled(self, db, enabled):
        db.set_config("pithos_enabled", enabled)

    def localfs_is_enabled(self):
298
299
        with TransactedConnection(self.syncer_dbtuple) as db:
            return self._localfs_is_enabled(db)
300
301
302
303
304

    def _localfs_is_enabled(self, db):
        return db.get_config("localfs_enabled")

    def pithos_is_enabled(self):
305
306
        with TransactedConnection(self.syncer_dbtuple) as db:
            return self._pithos_is_enabled(db)
307
308
309
310
311
312
313
314

    def _pithos_is_enabled(self, db):
        return db.get_config("pithos_enabled")

    def _sync_is_enabled(self, db):
        return self._localfs_is_enabled(db) and self._pithos_is_enabled(db)

    def purge_db_archives_and_enable(self):
315
316
317
318
        with TransactedConnection(self.syncer_dbtuple) as db:
            self._purge_db_archives_and_enable(db)

    def _purge_db_archives_and_enable(self, db):
319
320
321
322
323
324
325
        db.purge_archives()
        if not self._localfs_is_enabled(db):
            self.create_local_dirs()
            self._set_localfs_enabled(db, True)
        if not self._pithos_is_enabled(db):
            self._set_pithos_enabled(db, True)
            self.mk_container(self.container)