-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkafkaflow.py
884 lines (793 loc) · 30 KB
/
kafkaflow.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
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
# vi: set ft=python sts=4 ts=4 sw=4 et:
import os
import json
import datetime
import random
import time
import gzip
import logging
import shutil
import subprocess
import multiprocessing
from configparser import ConfigParser
from logging.handlers import TimedRotatingFileHandler
import pymongo
from pymongo import UpdateOne, ReplaceOne
from urllib.parse import quote_plus
import bson
import oss2
from kafka import KafkaConsumer, KafkaProducer
from kafka.errors import KafkaError, KafkaTimeoutError
from weasyprint import HTML
# global var: root_dir
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
class TimedRotatingCompressedFileHandler(TimedRotatingFileHandler):
"""Extended version of TimedRotatingFileHandler that compress
logs on rollover.
"""
def __init__(self, filename='', when='W6', interval=1,
backup_count=50, encoding='utf-8'):
super(TimedRotatingCompressedFileHandler, self).__init__(
filename=filename,
when=when,
interval=int(interval),
backupCount=int(backup_count),
encoding=encoding,
)
def doRollover(self):
super(TimedRotatingCompressedFileHandler, self).doRollover()
log_dir = os.path.dirname(self.baseFilename)
to_compress = [
os.path.join(log_dir, f) for f in os.listdir(log_dir)
if f.startswith(
os.path.basename(os.path.splitext(self.baseFilename)[0])
) and not f.endswith(('.gz', '.json'))
]
for f in to_compress:
if os.path.exists(f):
with open(f, 'rb') as _old, gzip.open(f+'.gz', 'wb') as _new:
shutil.copyfileobj(_old, _new)
os.remove(f)
class KafkaReceiver(multiprocessing.Process):
"""Message Receiver for the Sundial-Report-Stream."""
def __init__(self, envs, fast_queue, queue, max_len):
"""Initialize kafka message receiver process."""
multiprocessing.Process.__init__(self)
self.consumer = KafkaConsumer(
envs.get('rec_topic'),
group_id = envs.get('rec_grp'),
#enable_auto_commit = True,
#auto_commit_interval_ms = 2,
#api_version = (0, 10),
sasl_mechanism = envs.get('sasl_mechanism'),
security_protocol = envs.get('security_protocol'),
sasl_plain_username = envs.get('user'),
sasl_plain_password = envs.get('pwd'),
bootstrap_servers = envs.get('bootstrap_servers').split(','),
auto_offset_reset = envs.get('auto_offset_rst'),
)
self.queue = queue
self.fast_queue = fast_queue
self.queue_max_size = max_len
def run(self):
"""Receive message and put it in the queue."""
msg_list = []
while True:
is_working = False
# retrive messages if there is less in cache
if len(msg_list) < self.queue_max_size:
try:
msg_pack = self.consumer.poll(
timeout_ms=500,
max_records = 2*self.queue_max_size - len(msg_list),
)
self.consumer.commit()
except:
print('Err while retrive kafka messages!')
else:
for tp, messages in msg_pack.items():
for msg in messages:
msg_list.append(msg.value.decode('utf-8').strip())
is_working = True
# append message into queue
if len(msg_list):
line = msg_list[0]
try:
_msg = json.loads(line)
assert _msg.get('version', None) is None
# XXX: avoid `priority` is None
if _msg.get('priority', None) is None:
_msg['priority'] = 'high'
if _msg.get('priority', 'high')=='low' and \
(not self.queue.full()):
self.queue.put(line)
msg_list.pop(0)
elif _msg.get('priority', 'high')=='high' and \
(not self.fast_queue.full()):
self.fast_queue.put(line)
msg_list.pop(0)
except:
print('Receive invalid message')
print(line)
msg_list.pop(0)
is_working = True
if not is_working:
time.sleep(1)
## read message
#for msg in self.consumer:
# line = msg.value.decode('utf-8').strip()
# #print(line)
# try:
# _msg = json.loads(line)
# assert _msg.get('version', None) is None
# if 'priority' in _msg and _msg['priority']=='low':
# self.queue.put(line)
# else:
# self.fast_queue.put(line)
# except:
# print('Receive invalid message')
# print(line)
def get_json_logger(log_level=logging.DEBUG):
"""Logger initialization."""
# init log dir
log_dir = os.path.join(ROOT_DIR, 'log')
if not os.path.exists(log_dir):
os.makedirs(log_dir, mode=0o755)
logger = logging.getLogger('logger')
logger.setLevel(log_level)
# set json format log file
handler = TimedRotatingCompressedFileHandler(
os.path.join(log_dir, 'log.json'),
when='W6',
interval=1,
backup_count=50,
encoding='utf-8',
)
# set log level
handler.setLevel(log_level)
# set json format
formatter = logging.Formatter(
'{"@timestamp":"%(asctime)s.%(msecs)03dZ","severity":"%(levelname)s","service":"jupyter-reporter",%(message)s}',
datefmt='%Y-%m-%dT%H:%M:%S',
)
formatter.converter = time.gmtime
handler.setFormatter(formatter)
logger.addHandler(handler)
return logger
def get_report_gallery(config_file='./report_gallery.config'):
"""Read report gallery config file."""
config = ConfigParser()
config.read(config_file)
return config
def conn2aliyun(envs):
"""Connect to aliyun."""
# aliyun oss auth
auth = oss2.Auth(envs.get('access_id'), envs.get('access_secret'))
# get oss bucket
bucket = oss2.Bucket(
auth,
envs.get('oss_endpoint_name'),
envs.get('oss_bucket_name'),
)
return bucket
def generate_report(msg, out_queue, cache_queue, bucket, base_url,
dummy_base_url):
"""Workflow for generating report."""
# local vars init
data_dict = msg['data']
user_id = data_dict['ticketID']
report_type = msg['reportType']
data_purpose = msg['dataObjective']
rec_ts = msg['receivedTime']
callback_flag = True
if 'callback' in msg:
if msg['callback']=='N':
callback_flag = False
msg.pop('callback')
# init return message
uploaded_msg = {
'id': user_id,
'report_type': report_type,
'status': 'ok',
'callback': callback_flag,
}
result_data = {
'dataType': 'results',
'reportType': report_type,
'dataObjective': data_purpose,
'receivedTime': msg['receivedTime'],
'user_id': data_dict['id'],
}
sel_keys = [
'ticketID',
'token',
'name',
'province',
'city',
'region',
'gender',
'school',
'grade',
'class',
'test_date',
]
for k in sel_keys:
result_data[k] = data_dict[k]
report_gallery = get_report_gallery(
os.path.join(ROOT_DIR, 'report_gallery.config')
)
if report_type not in report_gallery:
uploaded_msg['status'] = 'error'
uploaded_msg['args'] = ''
uploaded_msg['stderr'] = 'Not find report type %s'%(report_type)
#out_queue.put(json.dumps(uploaded_msg))
out_queue.put(uploaded_msg)
# add message to cache
msg['reportProcessStatus'] = 'ERR'
cache_queue.put(msg)
print('Error! Not find report type named %s'%(report_type))
return None
report_cfg = report_gallery[report_type]
# dir config
base_dir = report_cfg['base_dir']
# init user data dir
data_dir = os.path.join(base_dir, 'user_data')
if not os.path.exists(data_dir):
os.makedirs(data_dir, mode=0o755)
# init pdf dir
pdf_dir = os.path.join(base_dir, 'pdfs')
if not os.path.exists(pdf_dir):
os.makedirs(pdf_dir, mode=0o755)
# def img dir
img_dir = os.path.join(base_dir, 'imgs')
# save input data as json file
json_file = None
if isinstance(data_dict, dict):
json_file = os.path.join(base_dir, '%s_data.json'%(user_id))
with open(json_file, 'w') as jf:
jf.write(json.dumps(data_dict)+'\n')
# run ipynb file
ipynb_name = report_cfg['entry']
ipynb_file = os.path.join(base_dir, ipynb_name)
html_file = os.path.join(base_dir, 'raw_report_%s.html'%(user_id))
nbconvert_cmd = [
'jupyter-nbconvert',
'--ExecutePreprocessor.timeout=60',
'--execute',
'--to html',
'--template=' + os.path.join(base_dir,'templates','report_sample.tpl'),
ipynb_file,
'--output ' + html_file,
]
ret = subprocess.run(
' '.join(nbconvert_cmd),
shell = True,
env = dict(os.environ, USERID=user_id),
stdout = subprocess.PIPE,
stderr = subprocess.PIPE,
encoding = 'utf-8',
)
# user's image dir
user_img_dir = os.path.join(img_dir, user_id)
# check nbconvert output status
if not ret.returncode==0:
uploaded_msg['status'] = 'error'
uploaded_msg['args'] = ret.args
uploaded_msg['stderr'] = ret.stderr
#out_queue.put(json.dumps(uploaded_msg))
out_queue.put(uploaded_msg)
# add message to cache
msg['reportProcessStatus'] = 'ERR'
cache_queue.put(msg)
#print('Error in nbconvert stage!')
# clean img dir
if os.path.exists(user_img_dir):
shutil.rmtree(user_img_dir)
return None
# if we get computation results successfully, get the file path
result_file = os.path.join(base_dir, '%s_results.json'%(user_id))
try:
calc_data = json.load(open(result_file))
if len(calc_data):
uploaded_msg['reportData'] = {report_type: dict(calc_data)}
result_data['reportData'] = calc_data
else:
result_file = None
except:
result_file = None
# timestamp for further usage
ts = datetime.datetime.strftime(
datetime.datetime.now(),
'%Y%m%d%H%M%S',
)
# if the pdf file is needed
if data_purpose=='REPORT':
# convert html file to standard format
if eval(report_cfg['add_heading_number']):
heading_number_param = '--add_heading_number'
else:
heading_number_param = ''
if eval(report_cfg['include_foreword']):
foreword_param = '--include_foreword'
else:
foreword_param = ''
if eval(report_cfg['include_article_summary']):
article_summary_param = '--include_article_summary=' + \
report_cfg['include_article_summary']
else:
article_summary_param = ''
std_html_file = os.path.join(base_dir, 'std_report_%s.html'%(user_id))
trans2std_cmd = [
'trans2std',
'--in ' + html_file,
'--out_file ' + std_html_file,
'--toc_level ' + report_cfg['toc_level'],
heading_number_param,
foreword_param,
article_summary_param,
]
ret = subprocess.run(' '.join(trans2std_cmd), shell=True)
# check trans2std output status
if not ret.returncode==0:
uploaded_msg['status'] = 'error'
uploaded_msg['args'] = ret.args
uploaded_msg['stderr'] = ret.stderr
#out_queue.put(json.dumps(uploaded_msg))
out_queue.put(uploaded_msg)
# add message to cache
msg['reportProcessStatus'] = 'ERR'
cache_queue.put(msg)
#print('Error in trans2std stage!')
# clean
os.remove(html_file)
if os.path.exists(std_html_file):
os.remove(std_html_file)
if os.path.exists(user_img_dir):
shutil.rmtree(user_img_dir)
return None
# convert html to pdf
pdf_filename = 'report_%s_%s.pdf'%(user_id, ts)
pdf_file = os.path.join(pdf_dir, pdf_filename)
#weasyprint_cmd = ['weasyprint', std_html_file, pdf_file]
#ret = subprocess.run(' '.join(weasyprint_cmd), shell=True)
try:
HTML(std_html_file).write_pdf(pdf_file)
assert os.path.exists(pdf_file)
# check weasyprint output status
except:
#if not ret.returncode==0:
uploaded_msg['status'] = 'error'
#uploaded_msg['args'] = ret.args
#uploaded_msg['stderr'] = ret.stderr
uploaded_msg['args'] = ''
uploaded_msg['stderr'] = 'Err in weasyprint process'
out_queue.put(uploaded_msg)
#out_queue.put(json.dumps(uploaded_msg))
# add message to cache
msg['reportProcessStatus'] = 'ERR'
cache_queue.put(msg)
#print('Error in weasyprint stage!')
# clean
os.remove(html_file)
if os.path.exists(std_html_file):
os.remove(std_html_file)
if os.path.exists(user_img_dir):
shutil.rmtree(user_img_dir)
return None
# upload file
remote_file = os.path.join(report_cfg['oss_dir'], pdf_filename)
remote_url = upload_file(bucket, base_url, pdf_file, remote_file)
# clean
os.remove(html_file)
os.remove(std_html_file)
if os.path.exists(user_img_dir):
shutil.rmtree(user_img_dir)
if os.path.exists(pdf_file):
os.remove(pdf_file)
if remote_url:
uploaded_msg['status'] = 'ok'
dummy_remote_url = 'https://'+dummy_base_url+'/'+remote_file
uploaded_msg['urls'] = {report_type: dummy_remote_url}
#out_queue.put(json.dumps(uploaded_msg))
out_queue.put(uploaded_msg)
# add message to cache
result_data['report_url'] = dummy_remote_url
cache_queue.put(result_data)
cache_queue.put(msg)
else:
uploaded_msg['status'] = 'error'
uploaded_msg['args'] = 'Uploads to oss.'
uploaded_msg['stderr'] = 'Falied to upload pdf file.'
#out_queue.put(json.dumps(uploaded_msg))
out_queue.put(uploaded_msg)
msg['reportProcessStatus'] = 'ERR2OSS'
cache_queue.put(msg)
return None
elif data_purpose=='CALC':
# clean
os.remove(html_file)
if os.path.exists(user_img_dir):
shutil.rmtree(user_img_dir)
if result_file:
uploaded_msg['status'] = 'ok'
out_queue.put(uploaded_msg)
cache_queue.put(result_data)
cache_queue.put(msg)
else:
uploaded_msg['status'] = 'error'
uploaded_msg['args'] = 'Calculate attributes.'
uploaded_msg['stderr'] = 'No results file found'
out_queue.put(uploaded_msg)
msg['reportProcessStatus'] = 'ERR'
cache_queue.put(msg)
return None
# move raw data and result file
targ_file = os.path.join(data_dir, '%s_%s.json'%(user_id, rec_ts))
shutil.move(json_file, targ_file)
if result_file:
targ_file = os.path.join(data_dir, '%s_results_%s.json'%(user_id, rec_ts))
shutil.move(result_file, targ_file)
def upload_file(bucket, base_url, src_file, remote_file):
"""Upload files to aliyun oss.
Arguments:
bucket: oss bucket instance.
base_url: url of oss bucket.
"""
# kafka message of upload files successfully
uploaded_msg = {}
try:
rsp = bucket.put_object_from_file(
remote_file,
src_file,
)
# if upload successfully
# XXX: should check file content using etag field (md5)
if rsp.status==200:
return 'https://'+base_url+'/'+remote_file
else:
print('%s error while uploading file %s'%(rsp.status, src_file))
return None
except:
print('%s error while uploading file %s'%(rsp.status, src_file))
return None
def save_msgs(msg_list, db_config):
"""Save message."""
insert2db_err = False
err_list = []
if db_config.getboolean('msg2db'):
try:
# connect to db
uri = "mongodb://%s:%s@%s" % (
quote_plus(db_config.get('db_user')),
quote_plus(db_config.get('db_pwd')),
db_config.get('db_url'),
)
myclient = pymongo.MongoClient(
host=uri,
port=db_config.getint('db_port'),
)
# locate db and collection
db = myclient[db_config.get('db_name')]
msgs_col = db[db_config.get('raw_msg_collection')]
results_col = db[db_config.get('result_collection')]
# classify messages based on their destination and source
insert_msg_list = [
item for item in msg_list \
if (item['dataType']=='raw_msgs') and ('fromdb' not in item)
]
update_msg_list = [
item for item in msg_list \
if (item['dataType']=='raw_msgs') and ('db_id' in item) and \
(item['fromdb']==db_config.get('raw_msg_collection'))
]
result_list = [
item for item in msg_list if item['dataType']=='results'
]
# insert new messages
if len(insert_msg_list):
insert_list = [dict(item) for item in insert_msg_list]
for item in insert_list:
item['fromdb'] = db_config.get('raw_msg_collection')
item['receivedTimeFormatted'] = datetime.datetime.strptime(
item['receivedTime'],
'%Y%m%d%H%M%S',
)
item['receivedTime'] = int(item['receivedTime'])
item.pop('dataType')
ret = msgs_col.insert_many(insert_list)
if not (len(ret.inserted_ids)==len(insert_list)):
err_list.extend(insert_msg_list)
# update exist messages in db
if len(update_msg_list):
update_cmd = []
db_fields = ['dataObjective', 'reportProcessStatus', 'reportType']
for item in update_msg_list:
tmp = {}
for k in db_fields:
if k in item:
tmp[k] = item[k]
update_cmd.append(UpdateOne(
{'_id': bson.ObjectId(item['db_id'])},
{'$set': tmp},
))
ret = msgs_col.bulk_write(update_cmd)
if not ret.matched_count==len(update_msg_list):
err_list.extend(update_msg_list)
# update or insert new results
if len(result_list):
upsert_list = [dict(item) for item in result_list]
upsert_cmd = []
filter_fields = ['reportType', 'user_id', 'ticketID']
for item in upsert_list:
filter_query = {}
for k in filter_fields:
filter_query[k] = item[k]
item['receivedTimeFormatted'] = datetime.datetime.strptime(
item['receivedTime'],
'%Y%m%d%H%M%S',
)
item['receivedTime'] = int(item['receivedTime'])
item.pop('dataType')
upsert_cmd.append(ReplaceOne(
filter_query,
item,
upsert=True,
))
ret = results_col.bulk_write(upsert_cmd)
if not (ret.matched_count+ret.upserted_count)==len(upsert_list):
err_list.extend(result_list)
assert len(err_list)==0
except:
if len(err_list)==0:
err_list = msg_list
insert2db_err = True
else:
return 'msg2db_ok'
if (not db_config.getboolean('msg2db')) or insert2db_err:
if insert2db_err:
msg_list = err_list
try:
# init message dir
data_dir = os.path.join(ROOT_DIR, 'msg_pool')
if not os.path.exists(data_dir):
os.makedirs(data_dir, mode=0o755)
# save messages into file
msg_dt = datetime.datetime.strptime(
msg_list[0]['receivedTime'],
'%Y%m%d%H%M%S',
)
last_monday = msg_dt - datetime.timedelta(days=msg_dt.weekday())
data_file = os.path.join(
data_dir,
'msgs_%s-%02d-%02d.txt'%(
last_monday.year,
last_monday.month,
last_monday.day,
),
)
with open(data_file, 'a+') as f:
for msg in msg_list:
f.write(str(msg)+'\n')
except:
return 'msg2file_err'
else:
if insert2db_err:
return 'msg2db_err'
else:
return 'msg2file_ok'
def normalize_ret_dict(d):
"""Normalize return message."""
assert isinstance(d, dict)
for k in d:
if isinstance(d[k], dict):
normalize_ret_dict(d[k])
elif isinstance(d[k], int):
d[k] = str(d[k])
elif isinstance(d[k], float):
d[k] = str(d[k])
elif isinstance(d[k], list):
d[k] = '|'.join([str(ele) for ele in d[k]])
elif isinstance(d[k], tuple):
d[k] = '|'.join([str(ele) for ele in d[k]])
def queue_writer(q):
"""For test."""
for i in range(10):
time.sleep(random.random() * 10)
flag = random.randint(1, 51)
if flag>28:
msg = {
'reportType': 'mathDiagnosisK8_v1',
'data': '',
}
else:
msg = {
'reportType': 'mathDiagnosisK8_v1',
'data': {
'ticketID': '00'+str(i),
'var1': 1,
'var2': 2,
},
}
q.put(json.dumps(msg))
if __name__ == '__main__':
# read configs
envs = ConfigParser()
envs.read(os.path.join(ROOT_DIR, 'env.config'))
# create data queue for multiprocessing
data_manager = multiprocessing.Manager()
fast_in_queue = data_manager.Queue(envs.getint('general', 'in_queue_size'))
in_queue = data_manager.Queue(envs.getint('general', 'in_queue_size'))
out_queue = data_manager.Queue(envs.getint('general', 'out_queue_size'))
cache_queue = data_manager.Queue(envs.getint('general', 'cache_queue_size'))
kafka_sender = KafkaProducer(
sasl_mechanism = envs.get('kafka', 'sasl_mechanism'),
security_protocol = envs.get('kafka', 'security_protocol'),
sasl_plain_username = envs.get('kafka', 'user'),
sasl_plain_password = envs.get('kafka', 'pwd'),
bootstrap_servers = envs.get('kafka', 'bootstrap_servers').split(','),
value_serializer = lambda v: json.dumps(v).encode('utf-8'),
retries = 5,
)
#-- initialize kafka message receiver process
kafka_receiver = KafkaReceiver(
envs['kafka'],
fast_in_queue,
in_queue,
envs.getint('general', 'in_queue_size'),
)
kafka_receiver.start()
#XXX for test: Create a message writer
#multiprocessing.Process(target=queue_writer, args=(in_queue,)).start()
# connect to aliyun oss
bucket = conn2aliyun(envs['aliyun'])
base_url = '.'.join([
envs.get('aliyun', 'oss_bucket_name'),
envs.get('aliyun', 'oss_endpoint_name'),
])
dummy_base_url = envs.get('aliyun', 'dummy_oss_url')
# Create multiprocessing pool to process data
max_worker_num = envs.getint('general', 'mp_worker_num')
pool = multiprocessing.Pool(max_worker_num)
# logging
json_logger = get_json_logger()
# generate report
cache_max_time = envs.getint('general', 'cache_max_time')
last_time = time.time()
while True:
on_duty = False
# save messages to db or file
if (not cache_queue.empty()) and \
(cache_queue.full() or ((time.time()-last_time) > cache_max_time)):
msg_list = []
while not cache_queue.empty():
msg_list.append(cache_queue.get())
save_ret = save_msgs(msg_list, envs['mongodb'])
if save_ret=='msg2db_ok':
json_logger.info('"rest":"Save msgs to db successfully"')
elif save_ret=='msg2file_ok':
json_logger.info('"rest":"Save msgs to file successfully"')
elif save_ret=='msg2db_err':
json_logger.error('"rest":"Error while save msgs to db"')
elif save_ret=='msg2file_err':
json_logger.error('"rest":"Error while save msgs to file"')
last_time = time.time()
on_duty = True
# handle process results
if not out_queue.empty():
msg = out_queue.get()
callback_flag = msg.pop('callback')
if not callback_flag:
continue
#normalize_ret_dict(msg)
#print(msg)
if msg['status']=='ok':
try:
future = kafka_sender.send(
envs.get('kafka', 'send_topic'),
msg,
)
record_metadata = future.get(timeout=30)
assert future.succeeded()
except KafkaTimeoutError as kte:
json_logger.error(
'"rest":"Timeout while sending message - %s"'%(str(msg)),
exc_info=True,
)
except KafkaError as ke:
json_logger.error(
'"rest":"KafkaError while sending message - %s"'%(str(msg)),
exc_info=True,
)
except:
#print('Error!')
#print(msg)
json_logger.error(
'"rest":"Exception while sending message - %s"'%(str(msg)),
exc_info=True,
)
else:
json_logger.info(
'"rest":"Generate report successfully - %s"'%(str(msg)),
)
else:
#print(msg)
json_logger.error(
'"rest":"Error while printing","args":"%s"' %
(msg['args'].replace('\n', ';').replace('"', "'")),
)
print('*'*20)
print('Error while printing!\nArgs:')
print(msg['args'])
print('Err:')
print(msg['stderr'])
on_duty = True
# process new message
if (pool._taskqueue.qsize() <= (3*max_worker_num)) and \
(not in_queue.empty() or not fast_in_queue.empty()):
if not fast_in_queue.empty():
raw_msg = fast_in_queue.get()
else:
raw_msg = in_queue.get()
msg = json.loads(raw_msg)
if 'priority' in msg:
msg.pop('priority')
#print(msg)
# validate received data
if not msg['data']:
json_logger.info('"rest":"No data found in %s"'%(str(msg)))
#print('Not find data in message.')
continue
try:
msg['data'] = eval(msg['data'])
except:
json_logger.error('"rest":"Get invalid data - %s"'%(str(msg)))
continue
# get report type and the data objectives
if not msg['reportType']:
json_logger.info(
'"rest": "Get unrelated message - %s"'%(str(msg))
)
continue
if '|' in msg['reportType']:
report_type, data_purpose = msg['reportType'].split('|')
elif 'dataObjective' in msg:
report_type = msg['reportType']
data_purpose = msg['dataObjective']
else:
report_type = msg['reportType']
data_purpose = 'REPORT'
# if we get a test message
if report_type=='test':
json_logger.info('"rest":"Get test message - %s"'%(str(msg)))
continue
# normalize message structure
msg['reportType'] = report_type
msg['dataObjective'] = data_purpose
msg['reportProcessStatus'] = 'OK'
if 'receivedTime' not in msg:
ts = datetime.datetime.strftime(
datetime.datetime.now(),
'%Y%m%d%H%M%S',
)
msg['receivedTime'] = ts
# key `dataType` is used for choosing which collection the
# message should be saved
msg['dataType'] = 'raw_msgs'
# if the objective of the message is `store`
if data_purpose=='STORE':
cache_queue.put(msg)
continue
pool.apply_async(
generate_report,
(
msg,
out_queue,
cache_queue,
bucket,
base_url,
dummy_base_url,
),
)
on_duty = True
if not on_duty:
time.sleep(0.01)