util.py 14.5 KB
Newer Older
thiolliere's avatar
thiolliere committed
1
import os
rgaudin's avatar
rgaudin committed
2
import re
3
import zipfile
thiolliere's avatar
thiolliere committed
4
import threading
thiolliere's avatar
thiolliere committed
5
import signal
rgaudin's avatar
rgaudin committed
6
import sys
7
import base64
8
import string
rgaudin's avatar
rgaudin committed
9
import hashlib
10
import tempfile
rgaudin's avatar
rgaudin committed
11
import ctypes
thiolliere's avatar
util    
thiolliere committed
12
import platform
rgaudin's avatar
rgaudin committed
13
14
import datetime
import collections
15

16
import pytz
17
from path import Path
rgaudin's avatar
rgaudin committed
18
19
import humanfriendly

20
21
import data

rgaudin's avatar
rgaudin committed
22
23
24
ONE_MiB = 2 ** 20
ONE_GiB = 2 ** 30
ONE_GB = int(1e9)
25
EXFAT_FORBIDDEN_CHARS = ['/', '\\', ':', '*', '?', '"', '<', '>', '|']
rgaudin's avatar
rgaudin committed
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50


STAGES = collections.OrderedDict([
    ('master', "Retrieve Master Image"),
    ('download', "Download contents"),
    ('setup', "Image configuration (virtualized)"),
    ('copy', "Copy contents onto image"),
    ('move', "Post-process contents (virtualized)"),
    ('write', "SD-card creation"),
])


class ProgressHelper(object):
    ''' progression manager for the logger

        must be inherited by the logger (CLILogger or Logger)

        two kinds of progresses:
            - stages (1-6) are main high-level stages
            - steps are individual tasks

        progress percentage is kept by stage (0 to 1).
        total percentage is calculated using current stage and its progress'''

    def __init__(self):
51
52
53
        self.reset()

    def reset(self):
rgaudin's avatar
rgaudin committed
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
        self.stage_id = 'init'  # id of current stage
        self.stage_progress = None  # percentage of current stage progress
        self.will_write = False  # wether the process will run write stage

        self.started_on = datetime.datetime.now()  # when the process started
        self.ended_on = None  # when it ended
        self.durations = {}  # records timedeltas for every ran stages

    def start(self, will_write):
        ''' record logger start.
            will_write informs about whether stage 6 will take place '''
        self.started_on = datetime.datetime.now()
        self.will_write = will_write

    def stop(self):
        self.ended_on = datetime.datetime.now()

    def clean_up_stage(self):
72
73
        started_on = getattr(self, 'stage_started_on', self.started_on) \
            or datetime.datetime.now()
rgaudin's avatar
rgaudin committed
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
        ended_on = datetime.datetime.now()
        self.durations[self.stage_id] = (started_on, ended_on,
                                         ended_on - started_on)
        self.stage_started_on = None
        self.stage_progress = None
        self.tasks = None

    def stage(self, stage_id):
        ''' change the current stage. expects a string ID '''
        self.clean_up_stage()  # record duration of previous stage

        self.stage_id = stage_id
        self.stage_started_on = datetime.datetime.now()
        self.update()

89
    def progress(self, numerator, denominator=1):
rgaudin's avatar
rgaudin committed
90
        ''' record progress for the current stage '''
91
92
93
94
95
96
97
98
99
100
        if numerator is not None:
            try:
                percentage = numerator / denominator
                assert percentage >= 0 and percentage <= 1
            except AssertionError:
                percentage = None
            except ZeroDivisionError:
                percentage = 1
        else:
            percentage = None
rgaudin's avatar
rgaudin committed
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
        self.stage_progress = percentage
        self.update()

    def ansible(self, line):
        ''' reads logger output while in ansible

            detects the ansible --tasks-list call to build its list of tasks
            detects ansible's task calling to set progress accordingly '''

        # display output anyway
        self.std(line)

        if self.stage_id not in ['setup', 'move']:
            return

        # detect number of task for ansiblecube phase
        if self.tasks is None and line.startswith("### TASKS ###"):
            try:
                self.tasks = [
                    re.search(r'^\s{6}(.*)\tTAGS\:.*$', l).groups()[0]
                    for l in line.split("^")[5:]]
            except Exception as exp:
                print(str(exp))
                pass

        # detect tasks being executed
        # TODO: we currently record the task as complete while it just started
        if self.tasks is not None:
            # detect current task
            if line.startswith("TASK ["):
                try:
                    task = re.search(r'^TASK \[(.*)\] \*+$', line).groups()[0]
                except Exception:
                    return
                else:
                    self.step(task)
                    try:
                        task_index = self.tasks.index(task)
                    except ValueError:
                        pass
                    else:
                        self.progress(task_index / len(self.tasks))

    @property
    def stage_name(self):
        return self.get_stage_name(self.stage_id)

    @property
    def nb_of_stages(self):
        n = len(STAGES)
        return n if self.will_write else n - 1
152

rgaudin's avatar
rgaudin committed
153
154
155
    @property
    def stage_number(self):
        return self.get_stage_number(self.stage_id)
156

rgaudin's avatar
rgaudin committed
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
    @property
    def stage_numbers(self):
        return "{c}/{t}".format(c=self.stage_number, t=self.nb_of_stages)

    def get_stage_string(self, stage_id):
        return "[{c}/{t}] {n}".format(c=self.get_stage_number(stage_id),
                                      t=self.nb_of_stages,
                                      n=self.get_stage_name(stage_id))

    @classmethod
    def get_stage_number(cls, stage_id):
        try:
            return list(STAGES.keys()).index(stage_id) + 1
        except Exception:
            return 0

    @classmethod
    def get_stage_name(cls, stage_id):
        return STAGES.get(stage_id, "Preparations")

    def get_overall_progress(self):
        ''' total progression based on current stage and its progress '''
        if not self.stage_number:
            return 0
        span = 1 / self.nb_of_stages
        lbound = span * (self.stage_number - 1)
        if self.stage_progress is None:
            return lbound
        current_progress = self.stage_progress * span
        return lbound + current_progress

    def complete(self):
        ''' mark the logger as complete (successful) '''
        self.clean_up_stage()
        self.stop()

    def failed(self):
        ''' mark the logger as complete (failure) '''
        self.clean_up_stage()
        self.stop()

    def update(self):
        ''' update UI according to new stage/step/progress '''
        raise NotImplementedError()

    def summary(self):
        ''' textual summary of each stage's durations '''

        # make sure we have an end datetime
        if self.ended_on is None:
            self.stop()

        self.std("*** DURATIONS SUMMARY ***")
        for stage_id in STAGES.keys():
            data = self.durations.get(stage_id)
            if data is None:
                continue
            self.std("{stage}: {duration} ({start} to {end})"
                     .format(stage=self.get_stage_string(stage_id),
                             duration=humanfriendly.format_timespan(
                                 data[2].total_seconds()),
                             start=data[0].strftime('%c'),
                             end=data[1].strftime('%c')))
        duration = self.ended_on - self.started_on
        self.std("TOTAL: {duration} ({start} to {end})"
                 .format(duration=humanfriendly.format_timespan(
                         duration.total_seconds()),
                         start=self.started_on.strftime('%c'),
                         end=self.ended_on.strftime('%c')))
thiolliere's avatar
util    
thiolliere committed
226

227
def get_free_space_in_dir(dirname):
thiolliere's avatar
util    
thiolliere committed
228
229
230
231
232
233
234
235
    """Return folder/drive free space."""
    if platform.system() == 'Windows':
        free_bytes = ctypes.c_ulonglong(0)
        ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(dirname), None, None, ctypes.pointer(free_bytes))
        return free_bytes.value
    else:
        st = os.statvfs(dirname)
        return st.f_bavail * st.f_frsize
thiolliere's avatar
thiolliere committed
236

thiolliere's avatar
thiolliere committed
237
# Thread safe class to register pid to cancel in case of abort
thiolliere's avatar
thiolliere committed
238
239
class CancelEvent:
    def __init__(self):
thiolliere's avatar
thiolliere committed
240
241
        self._lock = threading.Lock()
        self._pids = []
rgaudin's avatar
rgaudin committed
242
243
244
        self.thread = None
        self.callback = None
        self.callback_args = None
thiolliere's avatar
thiolliere committed
245
246
247
248

    def lock(self):
        return _CancelEventRegister(self._lock, self._pids)

249
    def register_thread(self, thread):
rgaudin's avatar
rgaudin committed
250
251
252
253
254
255
256
        self.thread = thread

    def unregister_thread(self):
        self.thread = None
        self.callback = None
        self.callback_args = None

thiolliere's avatar
thiolliere committed
257
    def cancel(self):
rgaudin's avatar
rgaudin committed
258
        if self.thread is not None:
259
260
            self.thread.stop()
            self.thread.join(timeout=5)  # allow proper release of handles
rgaudin's avatar
rgaudin committed
261
262
            self.unregister_thread()

thiolliere's avatar
thiolliere committed
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
        self._lock.acquire()
        for pid in self._pids:
            os.kill(pid, signal.SIGTERM)

class _CancelEventRegister:
    def __init__(self, lock, pids):
        self._lock = lock
        self._pids = pids

    def __enter__(self):
        self._lock.acquire()
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self._lock.release()

    def register(self, pid):
        if self._pids.count(pid) == 0:
            self._pids.append(pid)

    def unregister(self, pid):
        self._pids.remove(pid)
thiolliere's avatar
thiolliere committed
285

rgaudin's avatar
rgaudin committed
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
def human_readable_size(size, binary=True):
    if isinstance(size, (int, float)):
        num_bytes = size
    else:
        try:
            num_bytes = humanfriendly.parse_size(size)
        except Exception:
            return "NaN"
    is_neg = num_bytes < 0
    if is_neg:
        num_bytes = abs(num_bytes)
    output = humanfriendly.format_size(num_bytes, binary=binary)
    if is_neg:
        return "- {}".format(output)
    return output
thiolliere's avatar
thiolliere committed
301

thiolliere's avatar
thiolliere committed
302
303
304
305
306
307
class ReportHook():
    def __init__(self, writter):
        self._current_size = 0
        self.width = 60
        self._last_line = None
        self._writter = writter
rgaudin's avatar
rgaudin committed
308
        self.reporthook(0, 0, 100)  # display empty bar as we start
thiolliere's avatar
thiolliere committed
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327

    def reporthook(self, chunk, chunk_size, total_size):
        if chunk != 0:
            self._current_size += chunk_size

        avail_dots = self.width-2
        if total_size == -1:
            line = "unknown size"
        elif self._current_size >= total_size:
            line = "[" + "."*avail_dots + "] 100%\n"
        else:
            ratio = min(float(self._current_size) / total_size, 1.)
            shaded_dots = min(int( ratio * avail_dots), avail_dots)
            percent = min(int(ratio*100), 100)
            line = "[" + "."*shaded_dots + " "*(avail_dots-shaded_dots) + "] " + str(percent) + "%\r"

        if line != self._last_line:
            self._last_line = line
            self._writter(line)
328

rgaudin's avatar
rgaudin committed
329
330
331
332
333
334
335
336
337
338
class CLILogger(ProgressHelper):
    def __init__(self):
        super(CLILogger, self).__init__()

    def step(self, step):
        self.p("--> {}".format(step), color="34")

    def err(self, err):
        self.p(err, color="31")

rgaudin's avatar
rgaudin committed
339
340
341
    def succ(self, succ):
        self.p(succ, color="32")

rgaudin's avatar
rgaudin committed
342
343
344
345
346
347
348
349
350
351
352
353
354
    def raw_std(self, std):
        sys.stdout.write(std)

    def std(self, std, end=None):
        self.p(std, end=end, flush=True)

    def p(self, text, color=None, end=None, flush=False):
        if color is not None and sys.platform != 32:
            text = "\033[00;{col}m{text}\033[00m".format(col=color, text=text)
        print(text, end=end, flush=flush)

    def complete(self):
        super(CLILogger, self).complete()
rgaudin's avatar
rgaudin committed
355
        self.succ("Installation succeded.")
rgaudin's avatar
rgaudin committed
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382

    def failed(self, error="?"):
        super(CLILogger, self).failed()
        self.err("Installation failed: {}".format(error))

    def update(self):
        self.p("[STAGE {nums}: {name} - {pc:.0f}%]"
               .format(nums=self.stage_numbers,
                       name=self.stage_name,
                       pc=self.get_overall_progress() * 100),
               color="35")

def get_checksum(fpath, func=hashlib.sha256):
    h = func()
    with open(fpath, "rb") as f:
        for chunk in iter(lambda: f.read(ONE_MiB * 8), b""):
            h.update(chunk)
    return h.hexdigest()

def get_cache(build_folder):
    fpath = os.path.join(build_folder, "cache")
    os.makedirs(fpath, exist_ok=True)
    return fpath

def get_temp_folder(in_path):
    os.makedirs(in_path, exist_ok=True)
    return tempfile.mkdtemp(dir=in_path)
383
384

def relpathto(dest):
385
    ''' relative path to an absolute one '''
386
387
388
    if dest is None:
        return None
    return str(Path(dest).relpath())
389
390
391
392
393
394
395
396
397
398
399
400

def b64encode(fpath):
    ''' base64 string of a binary file '''
    with open(fpath, "rb") as fp:
        return base64.b64encode(fp.read()).decode('utf-8')

def b64decode(fname, data, to):
    ''' write back a binary file from its fname and base64 string '''
    fpath = os.path.join(to, fname)
    with open(fpath, 'wb') as fp:
        fp.write(base64.b64decode(data))
    return fpath
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425


def exfat_fnames_filter(fname):
    ''' whether supplied fname is valid exfat fname or not '''
    # TODO: check for chars U+0000 to U+001F
    return sum([1 for x in EXFAT_FORBIDDEN_CHARS if x in fname]) == 0


def ensure_zip_exfat_compatible(fpath):
    ''' wether supplied ZIP archive at fpath contains exfat-OK file names

        boolean, [erroneous, file, names]'''
    bad_fnames = []
    try:
        with zipfile.ZipFile(fpath, 'r') as zipf:
            # loop over all file names in the ZIP
            for path in zipf.namelist():
                # loop over all parts (folder, subfolder(s), fname)
                for part in Path(path).splitall():
                    if not exfat_fnames_filter(part) \
                            and part not in bad_fnames:
                        bad_fnames.append(part)
    except Exception as exp:
        return False, [str(exp)]
    return len(bad_fnames) == 0, bad_fnames
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453


def check_user_inputs(project_name, language, timezone,
                      admin_login, admin_pwd, wifi_pwd=None):

    allowed_chars = set(string.ascii_uppercase + string.ascii_lowercase
                        + string.digits + '-' + ' ')
    valid_project_name = len(project_name) >= 1 \
        and len(project_name) <= 64 \
        and set(project_name) <= allowed_chars

    valid_language = language in dict(data.ideascube_languages).keys()

    valid_timezone = timezone in pytz.common_timezones

    valid_wifi_pwd = len(wifi_pwd) <= 31 \
        and set(wifi_pwd) <= set(string.ascii_uppercase
                                 + string.ascii_lowercase + string.digits
                                 + '-' + '_') \
        if wifi_pwd is not None else True

    valid_admin_login = len(admin_login) <= 31 \
        and set(admin_login) <= set(string.ascii_uppercase
                                    + string.ascii_lowercase
                                    + string.digits + '-' + '_')
    valid_admin_pwd = len(admin_pwd) <= 31 \
        and set(admin_pwd) <= set(string.ascii_uppercase
                                  + string.ascii_lowercase
454
                                  + string.digits + '-' + '_')
455
456
457

    return valid_project_name, valid_language, valid_timezone, \
        valid_wifi_pwd, valid_admin_login, valid_admin_pwd