-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcommon_tools.py
56 lines (46 loc) · 1.32 KB
/
common_tools.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
51
52
53
54
55
56
from config import *
import hashlib
import sys
def getHash(file, block_count=0):
"""
Returns a sha256 hash for the specified file.
Eventually sent to server to check for restarts.
"""
hash = hashlib.sha256()
i = 0
with open(file, "r") as file:
while True:
data = file.read(CHUNK_SIZE)
if not data or (block_count != 0 and i >= block_count):
file.close()
return hash.hexdigest()
i += 1
hash.update(data)
def fail(msg):
"""
Simple fail function that prints and logs the error message and then exits.
"""
logger.error(msg)
sys.stderr.write(msg)
sys.exit(1)
# from: http://stackoverflow.com/questions/2281850/timeout-function-if-it-takes-too-long-to-finish
from functools import wraps
import errno
import os
import signal
class TimeoutError(Exception):
pass
def timeout(seconds=10, error_message=os.strerror(errno.ETIME)):
def decorator(func):
def _handle_timeout(signum, frame):
raise TimeoutError(error_message)
def wrapper(*args, **kwargs):
signal.signal(signal.SIGALRM, _handle_timeout)
signal.alarm(seconds)
try:
result = func(*args, **kwargs)
finally:
signal.alarm(0)
return result
return wraps(func)(wrapper)
return decorator