utils.py 3.36 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
17
18
import os
import hashlib
import datetime
19
import threading
20
import watchdog.utils
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
21
22
import sys
import logging
23
import platform
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
24
25

logger = logging.getLogger(__name__)
26

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
27
28
from agkyra.syncer.common import OBJECT_DIRSEP

29
ENCODING = sys.getfilesystemencoding() or 'UTF-8'
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
30
PLATFORM = sys.platform
31
NODE = platform.node()
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
32

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
33
34
35
36
37
38
39
def iswin():
    return PLATFORM.startswith("win")


def islinux():
    return PLATFORM.startswith("linux")

40

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
41
42
43
44
def isosx():
    return PLATFORM.startswith("darwin")


Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
45
46
47
48
49
50
51
52
def to_local_sep(filename):
    return filename.replace(OBJECT_DIRSEP, os.path.sep)


def to_standard_sep(filename):
    return filename.replace(os.path.sep, OBJECT_DIRSEP)


53
def join_path(dirpath, filename):
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
54
55
56
57
58
59
60
    return os.path.join(dirpath, to_local_sep(filename))


def join_objname(prefix, filename):
    if prefix != "":
        prefix = prefix.rstrip(OBJECT_DIRSEP) + OBJECT_DIRSEP
    return prefix + filename
61
62


Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
63
64
65
66
67
68
69
70
def normalize_standard_suffix(path):
    return path.rstrip(OBJECT_DIRSEP) + OBJECT_DIRSEP


def normalize_local_suffix(path):
    return path.rstrip(os.path.sep) + os.path.sep


Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
def from_unicode(s):
    if type(s) is unicode:
        return s.encode(ENCODING)
    return s


def to_unicode(s):
    if type(s) is unicode:
        return s
    try:
        return unicode(s, ENCODING)
    except UnicodeDecodeError as e:
        logger.warning("Failed to decode %s" % s.__repr__())
        raise


87
def hash_string(s):
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
88
    s = from_unicode(s)
89
90
91
92
    return hashlib.sha256(s).hexdigest()


def time_stamp():
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
93
94
95
96
97
    return datetime.datetime.now()


def str_time_stamp():
    return time_stamp().isoformat().replace(':', '.')
98
99
100
101


def younger_than(tstamp, seconds):
    now = datetime.datetime.now()
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
102
    delta = now - tstamp
103
    return delta < datetime.timedelta(seconds=seconds)
104
105


106
107
def reg_name(settings, objname):
    if settings.case_insensitive:
108
109
110
111
        return objname.lower()
    return objname


112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
BaseStoppableThread = watchdog.utils.BaseThread


class StoppableThread(BaseStoppableThread):
    def run_body(self):
        raise NotImplementedError()

    def run(self):
        while True:
            if not self.should_keep_running():
                return
            self.run_body()


def start_daemon(threadClass):
    thread = threadClass()
    thread.daemon = True
    thread.start()
    return thread
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148


class ThreadSafeDict(object):
    def __init__(self, *args, **kwargs):
        self._DICT = {}
        self._LOCK = threading.Lock()

    def lock(self):
        class Lock(object):
            def __enter__(this):
                self._LOCK.acquire()
                return self._DICT

            def __exit__(this, exctype, value, traceback):
                self._LOCK.release()
                if value is not None:
                    raise value
        return Lock()