Test Failed
Push — develop ( a41a67...f01008 )
by Nicolas
02:31
created

issue3319.Issue3290.blocking_io_call()   A

Complexity

Conditions 2

Size

Total Lines 6
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nop 2
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
####################################################################################
2
#
3
# Migration of the code issue3290.py to use multiprocessing with 'fork' start method
4
#
5
####################################################################################
6
7
import multiprocessing
8
import time
9
10
import psutil
11
12
# multiprocessing.set_start_method("fork")
13
ctx_mp_fork = multiprocessing.get_context('fork')
14
15
16 View Code Duplication
def exit_after(seconds, default=None):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
17
    """Exit the function if it takes more than 'second' seconds to complete.
18
    In this case, return the value of 'default' (default: None)."""
19
20
    def handler(q, func, args, kwargs):
21
        q.put(func(*args, **kwargs))
22
23
    def decorator(func):
24
        def wraps(*args, **kwargs):
25
            q = ctx_mp_fork.Queue()
26
            p = ctx_mp_fork.Process(target=handler, args=(q, func, args, kwargs))
27
            p.start()
28
            p.join(timeout=seconds)
29
            if not p.is_alive():
30
                return q.get()
31
32
            p.terminate()
33
            p.join(timeout=0.1)
34
            if p.is_alive():
35
                # Kill in case processes doesn't terminate
36
                # Happens with cases like broken NFS connections
37
                p.kill()
38
            return default
39
40
        return wraps
41
42
    return decorator
43
44
45
class Issue3290:
46
    @exit_after(1, default=None)
47
    def blocking_io_call(self, fs):
48
        try:
49
            return psutil.disk_usage(fs)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable psutil does not seem to be defined.
Loading history...
50
        except OSError:
51
            return None
52
53
54
issue = Issue3290()
55
while True:
56
    print(f"{time.time()} {issue.blocking_io_call('/home/nicolargo/tmp/hang')}")
57
    time.sleep(1)
58