web_client.py
6.48 KB
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
import sys
import os
import requests
import json
from datetime import datetime
from time import (
sleep,
time,
)
from threading import Thread
from argparse import ArgumentParser
headers = {'content-type': 'application/json'}
threads = dict()
end_threads = list()
durations = dict()
json_responses = dict()
server_info = dict()
default_url = 'http://localhost:7000/rpc'
default_host = 'pemda'
default_count = 1
help_url = 'default ' + default_url
help_host = 'default ' + default_host
help_count = 'default {}'.format(default_count)
help_invoice_id = 'wajib saat --payment dan --reversal'
help_amount = 'wajib saat --payment dan --reversal'
help_ntb = 'opsional saat --payment, wajib saat --reversal'
help_stan = 'opsional saat --payment, wajib saat --reversal'
help_bit = 'bit tambahan, contoh: --bit=42:TOKOPEDIA'
help_conf = 'konfigurasi tambahan, contoh untuk multi: --conf=pajak:bphtb'
def error(s):
print('ERROR: {}'.format(s))
sys.exit()
def log_info(s):
t = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
t = t[:-3]
msg = '{} {}'.format(t, s)
print(msg)
def get_option(argv):
parser = ArgumentParser()
parser.add_argument('--url', default=default_url, help=help_url)
parser.add_argument('--host', default=default_host, help=help_host)
parser.add_argument(
'--count', type=int, default=default_count, help=help_count)
parser.add_argument('--invoice-id', help=help_invoice_id)
parser.add_argument('--payment', action='store_true')
parser.add_argument('--reversal', action='store_true')
parser.add_argument('--amount', type=int, help=help_amount)
parser.add_argument('--ntb', help=help_ntb)
parser.add_argument('--stan', help=help_stan)
parser.add_argument('--bit', help=help_bit)
parser.add_argument('--conf', help=help_conf)
return parser.parse_args(argv)
def send(p):
url = server_info['url']
key = p['id']
log_info('Request: {}'.format(p))
start = time()
try:
resp = requests.post(url, data=json.dumps(p), headers=headers)
durations[key] = time() - start
json_resp = resp.json()
log_info('Response: {}'.format(json_resp))
json_responses[key] = json_resp
finally:
end_threads.append(key)
def show_durations():
key_fastest = None
key_slowest = None
total_duration = 0
messages = dict()
for key in durations:
duration = durations[key]
resp = json_responses[key]
if 'error' in resp:
break
result = resp['result']
if result['code'] == 0:
stan = result['data']['11']
else:
stan = '-'
msg = 'thread {} stan {} {} detik'.format(key, stan, duration)
log_info(msg)
messages[key] = msg
if key_fastest:
if duration < durations[key_fastest]:
key_fastest = key
else:
key_fastest = key
if key_slowest:
if duration > durations[key_slowest]:
key_slowest = key
else:
key_slowest = key
total_duration += duration
log_info('Tercepat {}'.format(messages[key_fastest]))
log_info('Terlama {}'.format(messages[key_slowest]))
log_info('Rerata {} detik / request'.format(total_duration/len(durations)))
class App:
def __init__(self, argv):
self.option = get_option(argv)
server_info['url'] = self.option.url
def create_thread(self, data):
thread = Thread(target=send, args=[data])
# Exit the server thread when the main thread terminates
thread.daemon = True
thread_id = data['id']
threads[thread_id] = thread
thread.start()
def get_invoice_ids(self):
if not os.path.exists(self.option.invoice_id):
return [self.option.invoice_id]
r = []
with open(self.option.invoice_id) as f:
for line in f.readlines():
invoice_id = line.rstrip()
r += [invoice_id]
return r
def get_method(self):
if self.option.payment:
return 'payment'
if self.option.reversal:
return 'reversal'
return 'inquiry'
def get_transaction(self, invoice_id):
def required(name, default=None):
value = getattr(self.option, name)
if not value and not default:
error('--{} harus diisi'.format(name))
p[name] = value or default
p = dict(host=self.option.host, invoice_id=invoice_id)
if self.option.payment or self.option.reversal:
required('amount')
if self.option.method == 'payment':
required('ntb', datetime.now().strftime('%m%d%H%m%s'))
required('stan', datetime.now().strftime('%H%M%S'))
else:
required('ntb')
required('stan')
if self.option.bit:
bits = dict()
for t in self.option.bit.split(','):
bit, value = t.split(':')
bits[bit] = value
p['bits'] = bits
if self.option.conf:
conf = dict()
for t in self.option.conf.split(','):
key, val = t.split(':')
conf[key] = val
p['conf'] = conf
return p
def run_transaction(self):
method = self.get_method()
thread_id = 0
for i in range(self.option.count):
for invoice_id in self.get_invoice_ids():
thread_id += 1
p = self.get_transaction(invoice_id)
data = dict(
id=thread_id, method=method, params=[p],
jsonrpc='2.0')
self.create_thread(data)
def run_echo(self):
for thread_id in range(1, self.option.count+1):
p = dict(host=self.option.host, id=thread_id)
data = dict(id=thread_id, method='echo', params=[p], jsonrpc='2.0')
self.create_thread(dict(data))
def run(self):
p = dict(host=self.option.host)
if self.option.invoice_id:
self.run_transaction()
else:
self.run_echo()
while threads:
if not end_threads:
continue
i = end_threads[0]
if i in threads:
thread = threads[i]
thread.join()
del threads[i]
index = end_threads.index(i)
del end_threads[index]
show_durations()
def main(argv=sys.argv[1:]):
app = App(argv)
app.run()