web_client_linkaja.py
7.58 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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
import sys
import os
import requests
from datetime import datetime
from time import (
sleep,
time,
)
from threading import Thread
from argparse import ArgumentParser
from pyramid_linkaja.responses import (
InquiryResponse,
PaymentResponse,
)
headers = {'content-type': 'application/x-www-form-urlencoded'}
threads = dict()
end_threads = list()
durations = dict()
csv_responses = dict()
server_info = dict()
default_url = 'http://localhost:7000/linkaja'
default_count = 1
default_merchant = 'ldmjakarta1'
default_terminal = 'Terminal Name'
default_pwd = 'ldmjkt1pass'
default_msisdn = '628111234567'
default_timeout = 35
help_url = 'default ' + default_url
help_count = f'default {default_count}'
help_amount = 'wajib saat --payment dan --reversal'
help_bill_ref = 'wajib saat payment dan reversal, '\
'diperoleh dari inquiry response'
help_trx_id = 'Nomor Transaksi Bank, '\
'opsional saat --payment, wajib saat --reversal'
help_merchant = 'default ' + default_merchant
help_timeout = f'default {default_timeout} detik'
ERRORS = [
'Connection refused',
]
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(
'--count', type=int, default=default_count, help=help_count)
parser.add_argument('--invoice-id', required=True)
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('--bill-ref', help=help_bill_ref)
parser.add_argument('--trx-id', help=help_trx_id)
parser.add_argument(
'--merchant', default=default_merchant, help=help_merchant)
parser.add_argument('--terminal', default=default_terminal)
parser.add_argument('--pwd', default=default_pwd)
parser.add_argument('--msisdn', default=default_msisdn)
parser.add_argument('--msg', default='')
parser.add_argument(
'--timeout', help=help_timeout, default=default_timeout, type=int)
return parser.parse_args(argv)
def send(thread_id, p):
url = server_info['url']
timeout = server_info['timeout']
log_info('Request: {}'.format(p))
start = time()
try:
resp = requests.post(url, data=p, headers=headers, timeout=timeout)
durations[thread_id] = time() - start
data = p['trx_type'] == '021' and InquiryResponse() or \
PaymentResponse()
if resp.status_code == 200:
data.from_raw(resp.text)
log_info('Response {}: {} -> {}'.format(
resp.status_code, [resp.text], data.values))
csv_responses[thread_id] = resp
except requests.exceptions.ConnectionError as e:
durations[thread_id] = time() - start
log_info('Response: {}'.format(e))
csv_responses[thread_id] = dict(fatal=e)
except requests.exceptions.ReadTimeout as e:
durations[thread_id] = time() - start
log_info('Response: {}'.format(e))
csv_responses[thread_id] = dict(fatal=e)
finally:
end_threads.append(thread_id)
def show_errors(errors):
if errors:
for err, count in errors.items():
log_info('{} {}'.format(err, count))
else:
log_info('Tidak ada yang gagal')
def nice_error(s):
for msg in ERRORS:
if s.find(msg) > -1:
return msg
return s
def show_durations():
tid_fastest = tid_slowest = None
total_duration = 0
messages = dict()
errors = dict()
for tid in durations:
duration = durations[tid]
resp = csv_responses.get(tid)
if resp:
err = None
if 'fatal' in resp:
err = msg = nice_error(str(resp['fatal']))
elif resp.status_code == 200:
messages[tid] = msg = resp.text.strip()
if tid_fastest:
if duration < durations[tid_fastest]:
tid_fastest = tid
else:
tid_fastest = tid
if tid_slowest:
if duration > durations[tid_slowest]:
tid_slowest = tid
else:
tid_slowest = tid
total_duration += duration
else:
err = msg = resp.text.split('\n')[0].strip()
else:
err = msg = 'KOSONG'
if err:
if err in errors:
errors[err] += 1
else:
errors[err] = 1
log_info('thread {} {} detik {}'.format(tid, duration, msg))
if tid_fastest != tid_slowest:
log_info('Tercepat {}'.format(messages[tid_fastest]))
log_info('Terlama {}'.format(messages[tid_slowest]))
log_info('Rerata {} detik / request'.format(
total_duration/len(durations)))
show_errors(errors)
class App:
def __init__(self, argv):
self.option = get_option(argv)
server_info['url'] = self.option.url
server_info['timeout'] = self.option.timeout
def create_thread(self, thread_id, data):
thread = Thread(target=send, args=[thread_id, data])
# Exit the server thread when the main thread terminates
thread.daemon = True
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 '022'
if self.option.reversal:
return '023'
return '021'
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.replace('_', '-')))
p[name] = value or default
p = dict(
merchant=self.option.merchant,
terminal=self.option.terminal,
pwd=self.option.pwd,
msisdn=self.option.msisdn,
acc_no=self.option.invoice_id,
trx_date=datetime.now().strftime('%Y%m%d%H%M%S'),
msg=self.option.msg)
p['trx_type'] = self.get_method()
if self.option.payment or self.option.reversal:
required('amount')
required('bill_ref')
if self.option.payment:
required('trx_id', datetime.now().strftime('%m%d%H%M%S'))
else:
required('trx_id')
return p
def run_transaction(self):
thread_id = 0
for i in range(self.option.count):
for invoice_id in self.get_invoice_ids():
thread_id += 1
data = self.get_transaction(invoice_id)
self.create_thread(thread_id, data)
def run(self):
self.run_transaction()
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()