125 lines
4.7 KiB
Python
125 lines
4.7 KiB
Python
#!/usr/bin/env python3
|
|
"""Синтетический генератор нагрузки для наполнения дашборда lab6."""
|
|
import argparse, base64, json, random, threading, time, uuid
|
|
from collections import Counter
|
|
import requests
|
|
|
|
PNG = base64.b64decode(
|
|
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==')
|
|
|
|
LOCK = threading.Lock()
|
|
CODES = Counter()
|
|
TOTAL = 0
|
|
|
|
def add(code):
|
|
global TOTAL
|
|
with LOCK:
|
|
CODES[code] += 1
|
|
TOTAL += 1
|
|
|
|
def reporter(stop_evt, started):
|
|
while not stop_evt.is_set():
|
|
time.sleep(15)
|
|
with LOCK:
|
|
total, codes = TOTAL, dict(CODES)
|
|
dt = time.time() - started
|
|
rps = total / dt if dt > 0 else 0
|
|
print(f'[t={dt:6.1f}s] total={total:6d} rps={rps:6.2f} codes={codes}', flush=True)
|
|
|
|
def make_user(base, i):
|
|
uname = f'load{i}{uuid.uuid4().hex[:6]}'
|
|
r = requests.post(f'{base}/api/v1/users', json={
|
|
'username': uname, 'display_name': f'Load{i}',
|
|
'password': 'correcthorsebatterystaple'}, timeout=5)
|
|
if r.status_code not in (200, 201):
|
|
return None
|
|
uid = r.json()['id']
|
|
r = requests.post(f'{base}/api/v1/auth/sessions',
|
|
auth=(uname, 'correcthorsebatterystaple'), timeout=5)
|
|
if r.status_code not in (200, 201):
|
|
return None
|
|
token = r.json()['token']
|
|
r = requests.post(f'{base}/api/v1/chats',
|
|
json={'title': f'load-chat-{i}', 'member_ids': [uid]},
|
|
headers={'Authorization': f'Bearer {token}'}, timeout=5)
|
|
if r.status_code not in (200, 201):
|
|
return None
|
|
return token, r.json()['id']
|
|
|
|
def burst_uploads(base, ctx_list, n):
|
|
def one(k):
|
|
token, chat_id = ctx_list[k % len(ctx_list)]
|
|
r = requests.post(f'{base}/api/v1/chats/{chat_id}/attachments?filename=b{k}.png',
|
|
headers={'Authorization': f'Bearer {token}',
|
|
'Content-Type': 'image/png'},
|
|
data=PNG, timeout=10)
|
|
add(r.status_code)
|
|
threads = [threading.Thread(target=one, args=(k,)) for k in range(n)]
|
|
for t in threads: t.start()
|
|
for t in threads: t.join()
|
|
|
|
def worker_loop(base, ctx, deadline):
|
|
token, chat_id = ctx
|
|
h = {'Authorization': f'Bearer {token}'}
|
|
while time.time() < deadline:
|
|
op = random.random()
|
|
try:
|
|
if op < 0.4:
|
|
r = requests.post(f'{base}/api/v1/chats/{chat_id}/messages',
|
|
json={'text': f'msg {uuid.uuid4().hex[:6]}'},
|
|
headers={**h, 'Idempotency-Key': str(uuid.uuid4())}, timeout=5)
|
|
elif op < 0.6:
|
|
r = requests.post(f'{base}/api/v1/chats/{chat_id}/attachments?filename=l.png',
|
|
headers={**h, 'Content-Type': 'image/png'}, data=PNG, timeout=5)
|
|
elif op < 0.8:
|
|
r = requests.get(f'{base}/api/v1/chats/{chat_id}/messages', headers=h, timeout=5)
|
|
else:
|
|
r = requests.get(f'{base}/api/v1/users/me', headers=h, timeout=5)
|
|
add(r.status_code)
|
|
except Exception:
|
|
add(0)
|
|
time.sleep(random.uniform(0.1, 0.35))
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser()
|
|
ap.add_argument('--base-url', default='http://localhost:8080')
|
|
ap.add_argument('--duration', type=int, default=360)
|
|
ap.add_argument('--workers', type=int, default=8)
|
|
ap.add_argument('--burst', type=int, default=150)
|
|
args = ap.parse_args()
|
|
base = args.base_url.rstrip('/')
|
|
|
|
ctx_list = []
|
|
for i in range(args.workers):
|
|
ctx = make_user(base, i)
|
|
if ctx: ctx_list.append(ctx)
|
|
print(f'prepared {len(ctx_list)} users/chats', flush=True)
|
|
if not ctx_list:
|
|
raise SystemExit('cannot prepare users')
|
|
|
|
print(f'burst uploads: {args.burst}', flush=True)
|
|
burst_uploads(base, ctx_list, args.burst)
|
|
|
|
started = time.time()
|
|
deadline = started + args.duration
|
|
stop_evt = threading.Event()
|
|
rep = threading.Thread(target=reporter, args=(stop_evt, started), daemon=True)
|
|
rep.start()
|
|
|
|
threads = [threading.Thread(target=worker_loop, args=(base, c, deadline))
|
|
for c in ctx_list]
|
|
for t in threads: t.start()
|
|
for t in threads: t.join()
|
|
stop_evt.set()
|
|
|
|
with LOCK:
|
|
total, codes = TOTAL, dict(CODES)
|
|
err = sum(v for k, v in codes.items() if k >= 500 or k == 0)
|
|
summary = {'total': total, 'codes': codes,
|
|
'error_share': err / total if total else 0}
|
|
print('SUMMARY ' + json.dumps(summary), flush=True)
|
|
with open('evidence/loadgen_summary.json', 'w') as f:
|
|
json.dump(summary, f, indent=2)
|
|
|
|
if __name__ == '__main__':
|
|
main() |