Statistiques
| Branche: | Tag: | Révision :

dockonsurf / modules / utilities.py @ 69d17e8b

Historique | Voir | Annoter | Télécharger (2,71 ko)

1
def tail(f, lines=20):
2
    total_lines_wanted = lines
3

    
4
    block_size = 1024
5
    f.seek(0, 2)
6
    block_end_byte = f.tell()
7
    lines_to_go = total_lines_wanted
8
    block_number = -1
9
    blocks = []
10
    while lines_to_go > 0 and block_end_byte > 0:
11
        if block_end_byte - block_size > 0:
12
            f.seek(block_number * block_size, 2)
13
            blocks.append(f.read(block_size))
14
        else:
15
            f.seek(0, 0)
16
            blocks.append(f.read(block_end_byte))
17
        lines_found = blocks[-1].count(b'\n')
18
        lines_to_go -= lines_found
19
        block_end_byte -= block_size
20
        block_number -= 1
21
    all_read_text = b''.join(reversed(blocks))
22
    return b'\n'.join(all_read_text.splitlines()[-total_lines_wanted:]).decode()
23

    
24

    
25
def check_bak(file_name):
26
    """Checks if a file already exists and backs it up if so.
27
    @param file_name: file to be checked if exists
28
    """
29
    import os
30
    new_name = file_name
31
    bak_num = 0
32
    while os.path.isdir(new_name) or os.path.isfile(new_name):
33
        bak_num += 1
34
        new_name = new_name.split(".bak")[0] + f".bak{bak_num}"
35
    if bak_num > 0:
36
        os.rename(file_name, new_name)
37
        logger.warning(f"'{file_name}' already present. Backed it up to "
38
                       f"{new_name}")
39

    
40

    
41
def try_command(command, expct_error_types: list, *args, **kwargs):
42
    """Try to run a command and record exceptions (expected and not) on a log.
43

44
    @param command: method or function, the command to be executed.
45
    @param expct_error_types: tuple of tuples, every inner tuple is supposed to
46
    contain an exception type (eg. ValueError, TypeError, etc.) to be caught and
47
    a message to print in the log and on the screen explaining the exception.
48
    Error types that are not allow to be called with a custom message as only
49
    error argument are not supported.
50
    The outer tuple encloses all couples of error types and their relative
51
    messages.
52
    *args and **kwargs: arguments and keyword-arguments of the command to be
53
    executed.
54
    When trying to run 'command' with its args and kwargs, if an exception
55
    present on the 'error_types' occurs, its relative error message is recorded
56
    on the log and a same type exception is raised with the custom message.
57
    """
58

    
59
    err = False
60
    try:
61
        return_val = command(*args, **kwargs)
62
    except Exception as e:
63
        for expct_err in expct_error_types:
64
            if isinstance(e, expct_err[0]):
65
                logger.error(expct_err[1])
66
                err = expct_err[0](expct_err[1])
67
                break
68
        else:
69
            logger.exception(unexp_error)
70
            err = e
71
    else:
72
        err = False
73
        return return_val
74
    finally:
75
        if isinstance(err, BaseException):
76
            raise err