logship.py
3.22 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
"""日志上云:所有 edge / dmsfetch 日志(已脱敏)进内存队列,后台线程按云端运行参数 log_ship_interval(默认 2 秒)
批量上传;上传失败写本地 outbox,恢复后补传。云端连不上时按指数退避(最长 60 秒)再试,
只在第一次失败和恢复时各记一行日志。
每行带一个设备内单调递增的序号 seq(毫秒时间戳 × 1000 + 计数),云端按 (设备, seq) 去重,补传重复也不会多。
"""
import collections
import datetime
import logging
import threading
import time
from .cloud import CloudError
log = logging.getLogger("edge")
_Q = collections.deque(maxlen=20000)
_lock = threading.Lock()
_last = [0]
current_task = {"id": None} # 正在执行的任务(写进每行日志)
def next_seq():
with _lock:
v = int(time.time() * 1000) * 1000
if v <= _last[0]:
v = _last[0] + 1
_last[0] = v
return v
class ShipHandler(logging.Handler):
def emit(self, record):
try:
msg = self.format(record)
except Exception: # noqa: BLE001
return
_Q.append({"seq": next_seq(), "ts": datetime.datetime.fromtimestamp(record.created).strftime("%Y-%m-%d %H:%M:%S"),
"level": record.levelname, "logger": record.name, "task_id": current_task["id"], "msg": msg[:8000]})
def drain(n=500):
out = []
while _Q and len(out) < n:
out.append(_Q.popleft())
return out
def pending():
return len(_Q)
class Shipper(threading.Thread):
def __init__(self, cc, outbox, interval=2.0, interval_fn=None):
super(Shipper, self).__init__(name="logship", daemon=True)
self.cc, self.outbox, self.interval = cc, outbox, interval
self.interval_fn = interval_fn
self._halt = threading.Event()
self.alive_at = time.time()
self.fails = 0
def stop(self):
self._halt.set()
def ship_once(self):
lines = drain()
if not lines:
return 0
try:
self.cc.logs(lines)
if self.fails:
log.info("云端已恢复,日志继续实时上传(断开期间的日志稍后补传)")
self.fails = 0
return len(lines)
except CloudError as e:
self.fails += 1
if e.retryable:
self.outbox.put("logs", "batch", {"lines": lines})
if self.fails == 1:
log.warning("云端暂时连不上(%s),日志先存本地,恢复后自动补传", e)
return 0
def _interval(self):
try:
base = max(1.0, float(self.interval_fn())) if self.interval_fn else self.interval
except Exception: # noqa: BLE001
base = self.interval
return min(60.0, base * (2 ** min(self.fails, 6))) if self.fails else base
def run(self):
while not self._halt.wait(self._interval()):
self.alive_at = time.time()
try:
while self.ship_once() == 500:
pass
if not self.fails:
self.outbox.flush(self.cc)
except Exception: # noqa: BLE001 日志线程自身不能挂
pass
self.ship_once()