-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerator.py
131 lines (103 loc) · 3.39 KB
/
generator.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
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
import argparse
import multiprocessing
import threading
import time
import os
from functools import wraps
from urllib.request import urlopen
import numpy
import sys
import yaml
from scipy.stats import truncnorm
max_per_second = 0
url = None
normal_distribution = None
max_execution_time = 1
def get_truncated_normal(mean=0.0, sd=1, low=0, upp=10):
return truncnorm(
(low - mean) / sd, (upp - mean) / sd, loc=mean, scale=sd)
def rate_limited():
"""
Decorator that make functions not be called faster than
set mode to 'kill' to just ignore requests that are faster than the
rate.
set delay_first_call to True to delay the first call as well
"""
lock = threading.Lock()
def decorate(func):
last_time_called = [0.0]
@wraps(func)
def rate_limited_function(*vargs, **kwargs):
def run_func():
nonlocal last_time_called
ret = func(*vargs, **kwargs)
last_time_called[0] = time.perf_counter()
lock.release()
return ret
lock.acquire()
nonlocal last_time_called
global max_per_second
min_interval = 1.0 / float(max_per_second)
elapsed = time.perf_counter() - last_time_called[0]
left_to_wait = min_interval - elapsed
# Allows the first call to not have to wait
if not last_time_called[0] or elapsed > min_interval:
return run_func()
elif left_to_wait > 0: # Kill
lock.release()
return
return rate_limited_function
return decorate
def get_rand_cps_int(slots=1):
x1 = get_truncated_normal(mean=normal_distribution["mean"], sd=normal_distribution["standard_deviation"],
low=normal_distribution["lower_limit"], upp=normal_distribution["upper_limit"])
return numpy.round(x1.rvs(slots))
@rate_limited()
def do_request():
global url
urlopen(url, timeout=1)
return
class HttpWorker(threading.Thread):
_end = False
def stop(self):
self._end = True
def run(self):
while not self._end:
do_request()
def main():
global max_per_second, max_execution_time
max_per_second = get_rand_cps_int()[0]
print("Limited ", max_per_second)
thread_number = multiprocessing.cpu_count() * 2
threads = list()
for i in range(thread_number):
print("Starting thread ", i)
t = HttpWorker()
threads.append(t)
t.start()
cps_norm = get_rand_cps_int(max_execution_time)
for cps in cps_norm:
time.sleep(1)
max_per_second = cps
print("Limited ", max_per_second)
time.sleep(1)
for t in threads:
print("Stoping thread")
t.stop()
def load_config(cnf_name):
global url, max_execution_time, normal_distribution
config = yaml.safe_load(open(cnf_name).read())
url = config["url"]
max_execution_time = config["max_execution_time"]
normal_distribution = config["normal_distribution"]
if __name__ == "__main__":
argp = argparse.ArgumentParser()
argp.add_argument("-c", "--config", dest='config_file', default='config.yml', type=str)
args = argp.parse_args()
config_file = args.config_file
if os.path.isfile(config_file):
load_config(config_file)
else:
print("No such config file.")
sys.exit(-1)
main()