-
Notifications
You must be signed in to change notification settings - Fork 1
/
__init__.py
2660 lines (2104 loc) · 63.2 KB
/
__init__.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
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#-*-encoding=utf-8-*-
#db
import redis
import MySQLdb
import msgpack
#utils
import time
import sqlite3
import re
import traceback
import datetime
import subprocess
import hashlib
import json
import zlib
import binascii
#os libraries
import sys
import mmap
import struct
import socket
import select
import os
import io
import pdb
import ctypes
import signal
from importlib import import_module
from lxml import etree
from decimal import Decimal
#my package
from spider import async_http
from spider import simple_http
from spider import modules
from spider import configs
from spider import llkv
from spider.urlcrc import get_urlcrc
from spider import filepack2
from bug import tp_assert
from bug import tp_ensure
from bug import key_assert
__all__ = ["test", "async_http", "simple_http", "llkv", "filepack2", "modules"]
SPIDER_DIR = os.path.dirname(__file__)
CONNECTION_ERROR = redis.exceptions.ConnectionError
RESPONSE_ERROR = redis.exceptions.ResponseError
sys.path.append("/".join(os.path.dirname(__file__).split("/")[:-1]))
BIT_MASK_48 = 0xffffffffffff
BIT_MASK_63 = 0x7fffffffffffffffL
BIT_MASK_64 = 0xffffffffffffffff
LUA_LIST_POP_N = """
local key = KEYS[1]
local num = tonumber(KEYS[2])
local i = 1
local a = {}
while i <= num do
local k = redis.pcall("lpop", key)
if not k then
break
end
a[i] = k
i = i + 1
end
return a
"""
LUA_LIST_PUSH_N = """
local key = KEYS[1]
local i = 1
while 1 do
local v = KEYS[1+i]
if not v then
break
end
redis.pcall("rpush", key, v)
i = i + 1
end
return nil
"""
LUA_SET_PUSH_N = """
local key = KEYS[1]
local i = 1
while 1 do
local v = KEYS[1+i]
if not v then
break
end
redis.pcall("sadd", key, v)
i = i + 1
end
return nil
"""
LUA_SET_POP_N = """
local key = KEYS[1]
local num = tonumber(KEYS[2])
local i = 1
local a = {}
while i <= num do
local k = redis.pcall("spop", key)
if not k then
break
end
a[i] = k
i = i + 1
end
return a
"""
SCRIPTS = {
"list_pop_n": LUA_LIST_POP_N,
"list_push_n": LUA_LIST_PUSH_N,
"set_pop_n": LUA_SET_POP_N,
"set_push_n": LUA_SET_PUSH_N
}
SCRIPT_IDS = {}
"""
在redis上执行lua脚本
以最小化的成本批量操作
"""
def load_lua_scripts(node):
for x,v in SCRIPTS.items():
SCRIPT_IDS[x] = node.script_load(v)
"""
list_pop_n(redis, "mykey", 10)
"""
def list_pop_n(redis, key, n):
return redis.evalsha(SCRIPT_IDS["list_pop_n"], 2, key, n)
def list_push_n(redis, key, *args):
return redis.evalsha(SCRIPT_IDS["list_push_n"], len(args)+1, key, *args)
def set_pop_n(redis, key, n):
return redis.evalsha(SCRIPT_IDS["set_pop_n"], 2, key, n)
def set_push_n(redis, key, *args):
return redis.evalsha(SCRIPT_IDS["set_push_n"], len(args)+1, key, *args)
def profile_func(func, *args):
import cProfile, pstats, StringIO
pr = cProfile.Profile()
pr.enable()
time_a = time.time()
func(*args)
pr.disable()
s = StringIO.StringIO()
sortby = 'cumulative'
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
print s.getvalue()
def get_memsize():
items = open("/proc/%s/statm" % os.getpid()).read().split(" ")
size = int(items[0])
return size
def profile_mem(func, *args):
sizea = get_memsize()
func(*args)
sizeb = get_memsize()
print sizeb - sizea
CONFIG = {}
def jsonp_json(content):
a = content.find("(")
b = content.rfind(")")
if a < 0 or b < 0:
return
return json.loads(content[a+1:b])
def log_result(tp, result):
if tp =="hash":
b = []
for k,v in result.iteritems():
b.append("%s: %s" % (k, v))
log_with_time("\n".join(b))
else:
log_with_time("\n".join([repr(i) for i in result]))
def pack_result(tp, result):
b = []
pack = msgpack.packb
if tp == "hash":
for k,v in result.iteritems():
b.append((k, pack(v)))
else:
for r in result:
b.append(pack(r))
return b
def is_dst_overflow(node, dst):
limit = dst.get("limit")
if not limit:
return
qlen = 0
tp = dst["type"]
qname = dst["name"]
if tp == "list":
qlen = node.llen(qname)
elif tp =="set":
qlen = node.scard(qname)
elif tp == "hash":
qlen = node.hlen(qname)
if qlen and limit < qlen:
return True
def forward_one(node, result, dst):
b = []
tp = dst["type"]
if not tp:
return
if is_dst_overflow(node, dst):
log_with_time("dst overflow: %s" % dst["name"])
return
qname = dst["name"]
if dst.get("with_siteid"):
qname = "%s_%s" % (qname, CONFIG["site_id"])
if dst.get("log", True):
log_result(tp, result)
if dst.get("pack", True):
b = pack_result(tp, result)
else:
if tp == "hash":
b = result
if tp == "list":
list_push_n(node, qname, *b)
elif tp == "set":
set_push_n(node, qname, *b)
elif tp == "hash":
node.hmset(qname, dict(b))
elif tp == "kv":
for k, v in result.items():
node.set(k, v)
else:
log_with_time("unknown dst type")
return
def forward_dst(result, rule):
assert "dst" in rule or "multidst" in rule
if not result:
return
if "dst" in rule:
dst = rule["dst"]
node = get_node(dst.get("node"))
forward_one(node, result, dst)
return
for k,v in rule["multidst"].items():
if result.get(k):
node = get_node(v.get("node"))
forward_one(node, result[k], v)
else:
log_with_time("dst %s is empty" % k)
PRICE_STRIPED = set((u"¥", " ", "\t", "\n", "`"))
def fix_price(text):
ret = []
for i in text:
if i not in PRICE_STRIPED:
ret.append(i)
return "".join(ret)
sp_site = set((25, 1025, 2025, 3025, 31, 1031, 2031, 3031, 4031))
def format_price_item(item):
site_id = CONFIG["site_id"]
url, price, stock = item
tp_assert(str, url, price)
tp_assert(int, stock)
urlcrc = get_crc(url)
if not urlcrc:
return
try:
price = int(Decimal(price) * 100)
except:
traceback.print_exc()
return
stock = stock
if stock > 0 and price < 0:
log_with_time("bad price: %s" % str(item))
if price < 0:
stock = -1
price = -1
return site_id, urlcrc, price, stock
def format_price(result):
tp_assert(list, result)
ret = []
for i in result:
item = format_price_item(i)
if not item:
log_with_time("price format error: %s: %s" % (site_id, i))
continue
ret.append(item)
return ret
def get_crc(url):
site_id = CONFIG["site_id"]
if site_id in sp_site:
urlcrc = int(url)
else:
urlcrc = get_urlcrc(site_id, url)
return urlcrc
def format_promo(result):
site_id = CONFIG["site_id"]
ret = []
for crc, j in result:
ret.append(("%s-%s" % (crc, site_id), json.dumps(j)))
return ret
def format_style_group(main_url, urls):
site_id = CONFIG["site_id"]
main_crc = get_urlcrc(site_id, main_url)
crcs = []
for k in urls:
crcs.append(str(get_urlcrc(site_id, k)))
return main_crc, ",".join(crcs)
QUERY_METHODS = set(("get", "head", "delete", "trace", "option"))
UPLOAD_METHODS = set(("post", "delete"))
def get_header_by_role(get_def):
if get_def["type"] == "simple":
hdr = simple_http.default_header.copy()
elif get_def["type"] == "ajax":
hdr = simple_http.json_header.copy()
else:
log_with_time("unknown type: %s" % gt["type"])
return hdr
def get_source_items(rule, url):
get_def = rule["get"]
from_list = rule["from"]
from_filter = rule.get("from_filter")
old_url = url
if from_filter:
from_filter = load_func(from_filter)
url = from_filter(url)
do = getattr(simple_http, get_def["method"])
hdr = get_header_by_role(get_def)
if get_def["method"] in QUERY_METHODS:
res = do(url, query = get_def.get("query"), redirect=10)
elif get_def["method"] in UPLOAD_METHODS:
res = do(url, payload = get_def.get("payload"), redirect=10)
else:
log_with_time("unknown method: %s" % get_def["method"])
return
if res["status"] != 200:
log_with_time("get %s failed" % res)
return
parser = load_func(get_def["parser"])
result = parser(url, res, from_list[old_url])
if result and rule.get("price_range"):
urls = load_price_range(rule["price_range"])
result = replace_url_with_ranges(result, urls)
if result and rule.get("hotlimit"):
result = hotzone_filter(result, rule)
return result
def run_single(rule):
for url in rule["from"]:
items = get_source_items(rule, url)
forward_dst(items, rule)
def hotzone_filter(result, rule):
d = result
limit = rule.get("hotlimit")
result = []
for i in d:
result.append((i, limit))
return result
def run_single_repeat(rule):
repeat = rule.get("repeat", 0)
if not repeat:
run_single(rule)
log_with_time("%s done" % rule["name"])
return
while True:
run_single(rule)
log_with_time("sleeping")
sleep_with_counter(repeat)
def replace_url_with_ranges(result, urls):
tp_assert(list, result)
tp_assert(dict, urls)
filtered = []
for i in result:
if i in urls:
filtered.append(i)
result.extend(urls[i])
rset = set(result)
for i in filtered:
rset.remove(i)
return list(rset)
def load_price_range(name):
tp_assert(str, name)
if not name.startswith("/"):
subdir = "modules/%s/%s" % (CONFIG["site"], name)
name = os.path.join(os.path.dirname(__file__), subdir)
items = open(name).read().split("#")
urls = {}
for i in items:
if not i:
continue
lines = []
for j in i.split("\n"):
j = j.strip(" \r")
if not j:
continue
lines.append(j)
urls[lines[0]] = lines[1:]
return urls
def sleep_with_counter(n):
tp_assert(int, n)
for i in range(1, n+1):
log_with_time("sleeping, cnt, %s" % i)
time.sleep(1)
def load_func(path):
tp_assert(str, path)
import spider.modules
parts = path.split(".")
if getattr(spider.modules, path, ""):
return getattr(spider.modules, path)
ms = os.listdir(os.path.join(SPIDER_DIR, "modules"))
if len(parts) == 2 and parts[0] in ms:
module = import_module("spider.modules.%s" % parts[0])
else:
module = import_module(".".join(parts[:-1]))
return getattr(module, parts[-1])
def forward_result(task):
tp_assert(dict, task)
rule = CONFIG["rule"]
try:
result = task["to"](task, rule.get("rule"))
except:
traceback.print_exc()
exit(1)
if not result:
log_with_time("empty result: %s" % task["url"])
return
if result and ("dst" in rule or "multidst" in rule):
log_with_time("result of %s" % task["url"])
forward_dst(result, rule)
def forward_dp(task):
tp_assert(dict, task)
if "crc" not in task:
log_with_time("lost crc: %s" % task["url"])
return
status = task["res_status"]["status"]
if status != 200:
log_with_time("status: %s, %s" % (status, task["url"]))
return
CONFIG["fpack"].add(task["url"], task["text"], crc=task["crc"])
key = (CONFIG["site_id"] << 48) | ctypes.c_uint(task["crc"]).value
CONFIG["lc"].set(key, 0)
log_with_time(task["url"])
def get_name_by_xpath(text, expr):
tp_assert(str, text, expr)
tree = etree.HTML(text)
nodes = tree.xpath(expr)
if not nodes:
log_with_time("invalid xpath")
return
return str(nodes[0])
def forward_file(task):
tp_assert(dict, task)
fconfig = CONFIG["fconfig"]
ftype = fconfig.get("type", "url")
path = fconfig.get("path", "")
text = task["text"]
if ftype == "url":
name = task["url"]
elif ftype == "xpath":
expr = fconfig.get("xpath")
name = get_name_by_xpath(text, expr)
assert name
name += fconfig.get("suffix", ".tmp")
elif ftype == "hex":
name = hashlib.sha1(task["url"]).hexdigest()
if fconfig.get("compress"):
text = zlib.compress(text)
fname = os.path.join(path, name)
f = open(fname, "w+")
f.write(text)
f.close()
def forward_offshelf(task):
tp_assert(dict, task)
if "crc" not in task:
log_with_time("lost crc %s" % task["url"])
return
rule = CONFIG["rule"]
try:
result = CONFIG["to_parser"](task, rule.get("rule"))
except:
traceback.print_exc()
exit(1)
forward_dst(result, CONFIG["rule"])
def not200_abort(not200, task):
tp_assert(str, not200)
tp_assert(dict, task)
log_with_time("not200: %s, %s, %s" % (task["res_status"],
task["res_header"], task["url"]))
if not200 == "trace":
pdb.set_trace()
elif not200 == "retry":
log_with_time("retry: %s" % task["url"])
async_http.failed_tasks[task["random"]] = task
return True
elif not200 == "pass":
return False
return True
def batch_parser(task):
tp_assert(dict, task)
rule = CONFIG["rule"]
not200 = rule["get"].get("not200", "")
if task["res_status"]["status"] != 200 and not200_abort(not200, task):
return
qtype = rule.get("dst", {}).get("qtype", "redis")
if qtype == "redis":
forward_result(task)
elif qtype == "file":
forward_file(task)
elif qtype == "dp":
forward_dp(task)
elif qtype == "off":
forward_offshelf(task)
else:
log_with_time("unknown dst qtype: %s" % qtype)
exit(1)
def async_config(rule):
tp_assert(dict, rule)
args = rule["get"]["args"]
async_http.debug = args.get("debug")
for i in ("limit", "interval", "retry", "timeout"):
if i in args:
async_http.config[i] = args[i]
def split_list_iter(l, n):
le = len(l)
c = le / n
if le % n:
c += 1
for i in range(c):
yield l[i*n:(i+1)*n]
def apply_group_filter(items, model):
tp_assert(list, items)
tp_assert(dict, model)
loader = CONFIG["src_loader"]
flt = CONFIG["src_filter"]
items = [loader(item) for item in items]
tasks = []
for i in flt(items):
assert i is not None
for j in model:
if j not in i:
i[j] = model[j]
tasks.append(i)
return tasks
def apply_single_filter(items, model):
tp_assert(list, items)
tp_assert(dict, model)
tasks = []
loader = CONFIG["src_loader"]
flt = CONFIG["src_filter"]
for i in items:
unpacked = loader(i)
t = flt(unpacked)
assert i is not None
for i in model:
if i not in t:
t[i] = model[i]
tasks.append(t)
return tasks
def task_with_randua(rule):
tp_assert(dict, rule)
header = async_http.html_header.copy()
header["User-Agent"] = async_http.random_useragent()
return {
"method": rule["get"]["method"],
"to": CONFIG["to_parser"],
"parser": batch_parser,
"header": header
}
def task_simple(rule):
tp_assert(dict, rule)
return {
"method": rule["get"]["method"],
"to": CONFIG["to_parser"],
"parser": batch_parser,
"header": async_http.default_header.copy()
}
def get_source_from_redis(src, node):
tp_assert(dict, src)
tp_assert(redis.StrictRedis, node)
tp = src.get("type")
qname = src["name"]
batch = src.get("batch", 1)
if tp == "list":
items = list_pop_n(node, qname, batch)
elif tp == "set":
items = set_pop_n(node, qname, batch)
elif tp == "hash":
items = node.hgetall(qname)
else:
log_with_time("unknown src type")
exit(1)
return items
def get_source_from_file(src):
pass
def get_source(src, node):
tp_assert(dict, src)
tp_assert(redis.StrictRedis, node)
qtype = src.get("qtype", "redis")
if qtype == "redis":
return get_source_from_redis(src, node)
elif qtype == "file":
return get_source_from_file(src)
elif qtype == "loader":
return CONFIG["src_loader"](src, node)
elif qtype == "dp":
return get_source_from_dps(src, node)
else:
log_with_time("unknown qtype type")
exit(1)
def apply_filter(rule, items):
tp_assert(dict, rule)
tp_assert(list, items)
if not items:
return
ctp = rule["get"].get("client_type")
group = rule["src"].get("group")
md = task_simple(rule)
if ctp == "json":
md["header"] = async_http.json_header.copy()
elif ctp == "html":
md["header"] = async_http.html_header.copy()
redirect = rule["get"].get("redirect")
if redirect:
md["redirect"] = redirect
if group:
tasks = apply_group_filter(items, md)
else:
tasks = apply_single_filter(items, md)
return tasks
def dp_diff(lc, items):
tp_assert(llkv.Connection, lc)
tp_assert(list, items)
site_id = CONFIG["site_id"]
crcs = {}
for item in items:
li = len(item)
if li == 2:
url, title = item
crc = get_urlcrc(site_id, url)
elif li == 3:
url, crc, title = item
crc = int(crc)
else:
log_with_time("unknown dp format")
continue
key = get_llkv_key(site_id, crc)
crcs[key] = (crc, url)
d = lc.multi_get(crcs.keys())
ret = []
for k,v in d.items():
if v == None:
ret.append(crcs[k])
return ret
def get_dp_items(src):
tp_assert(dict, src)
dps_redis = get_node("dp_redis")
unpack = msgpack.unpackb
qname = src["name"]
b = []
for i in list_pop_n(dps_redis, qname, 1000):
item = unpack(i)
b.append(item)
return b
def get_dps_diffset(src):
tp_assert(dict, src)
diffset = []
atime = time.time()
while True:
if time.time() - atime > 60:
log_with_time("wait timeout, got: %s" % len(diffset))
break
b = get_dp_items(src)
if not b:
log_with_time("sleeping")
time.sleep(src.get("wait", 1))
continue
diffset.extend(dp_diff(CONFIG["lc"], b))
if len(diffset) >= 1000:
break
return diffset
def get_source_from_dps(src, node):
tp_assert(dict, src)
tp_assert(redis.StrictRedis, node)
diffset = get_dps_diffset(src)
tasks = []
for crc, url in diffset:
task = {
"url": url,
"crc": int(crc),
}
tasks.append(task)
return tasks
def setup_dp_env():
client = CONFIG["client"]
default_node = client["nodes"]["default"]
CONFIG["lc"] = llkv.Connection(**client["llkv_dp"])
CONFIG["last_flush_time"] = time.time()
CONFIG["fpack"] = filepack2.FilePack(db = default_node,
limit = 1000, site_id=CONFIG["site_id"],
datadir="/mnt/mfs")
CONFIG["to_parser"] = batch_parser
def setup_config(rule):
tp_assert(dict, rule)
if rule["get"].get("args"):
async_config(rule)
CONFIG["rule"] = rule
src = rule["src"]
if "filter" in src:
CONFIG["src_filter"] = load_func(src["filter"])
else:
CONFIG["src_filter"] = lambda x: x
qtype = src.get("qtype", "redis")
if qtype == "loader":
CONFIG["src_loader"] = load_func(src["loader"])
elif qtype == "redis":
CONFIG["src_loader"] = msgpack.unpackb
elif qtype == "dp":
CONFIG["src_loader"] = lambda x: x
setup_dp_env()
dst_parser = rule.get("get", {}).get("parser")
if dst_parser:
CONFIG["to_parser"] = load_func(dst_parser)
multidst = rule.get("multidst", {})
for v in multidst.values():
if v.get("qtype") == "file":
CONFIG["fconfig"] = dst
dst = rule.get("dst")
if dst and dst.get("qtype") == "file":
CONFIG["fconfig"] = dst
def flush_dp_files():
mlen = len(CONFIG["fpack"].meta)
if not mlen:
return
now = time.time()
if now - CONFIG["last_flush_time"] < 36000:
log_with_time("wait to flush...")
return
CONFIG["last_flush_time"] = now
log_with_time("flush %s files to disk" % mlen)
CONFIG["fpack"].flush()
time.sleep(5)
def get_node(node=None):
if not node:
return CONFIG["nodes"].get("default")
con = CONFIG["nodes"].get(node)
if not con:
return CONFIG["nodes"].get("default")
return con
def run_batch_do_wait(rule):
tp_assert(dict, rule)
wait = rule.get("wait", 1)
src = rule["src"]
qtype = src.get("qtype", "redis")
need_wait = False
if qtype == "redis":
if not wait:
log_with_time("%s done" % rule["name"])
exit(0)
else:
log_with_time('sleeping')
need_wait = True
elif qtype == "file" or qtype == "loader":
log_with_time("sleeping")
need_wait = True
elif qtype == "dp":
flush_dp_files()
need_wait = True
time.sleep(wait)
return need_wait
def run_batch(rule):
tp_assert(dict, rule)
setup_config(rule)
src = rule["src"]
node = get_node(src.get("node"))
while True:
items = get_source(src, node)
tasks = apply_filter(rule, items)
if not tasks and run_batch_do_wait(rule):
continue
async_http.repeat_tasks(tasks)
def run_worker_food(rule):
tp_assert(dict, rule)
if not rule.get("repeat", 0):
forward_dst(rule["food"], rule)
log_with_time("%s done" % rule["name"])
exit(0)
while True:
forward_dst(rule["food"], rule)
log_with_time("sleeping")
sleep_with_counter(rule.get("repeat"))
def now_is_in_period(period):
tp_assert(str, period)
h = datetime.datetime.now().hour
start,end = period.split("-")
start = int(start)
end = int(end)
if start < end and start < h < end:
return True
if start > end and (start < h < 24 or 0 <= h < end):
return True