Test Failed
Push — master ( 73a01d...ef36eb )
by Nicolas
04:43
created

issue3319   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 58
Duplicated Lines 46.55 %

Importance

Changes 0
Metric Value
eloc 34
dl 27
loc 58
rs 10
c 0
b 0
f 0
wmc 5

1 Function

Rating   Name   Duplication   Size   Complexity  
A exit_after() 27 27 3

1 Method

Rating   Name   Duplication   Size   Complexity  
A Issue3290.blocking_io_call() 0 6 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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