9
|
1 # dev copy
|
|
2 import asyncio
|
|
3 import logging
|
0
|
4 import time
|
|
5 import traceback
|
9
|
6 from typing import Awaitable, Callable
|
|
7
|
|
8 from prometheus_client import Gauge, Summary
|
0
|
9
|
|
10 log = logging.getLogger()
|
|
11
|
|
12
|
9
|
13 # throw this away (when net_routes is rewritten)
|
0
|
14 def loop_forever_sync(func, sleep_period, up_metric):
|
|
15 first_run = True
|
|
16 while True:
|
|
17 try:
|
|
18 func(first_run)
|
|
19 up_metric.set(1)
|
|
20 first_run = False
|
|
21 except Exception as ex:
|
|
22 log.error(ex)
|
|
23 traceback.print_exc()
|
|
24 up_metric.set(0)
|
|
25 time.sleep(sleep_period)
|
|
26
|
|
27
|
9
|
28 async def loop_forever(
|
|
29 func: Callable[[bool], Awaitable[None]],
|
|
30 sleep_period: float,
|
|
31 up_metric: Gauge,
|
|
32 call_metric: Summary,
|
|
33 ):
|
0
|
34 """
|
|
35 sleep_period is the sleep time after however long func takes to run
|
|
36 """
|
9
|
37 @call_metric.time()
|
|
38 async def call_func(first_run):
|
|
39 if asyncio.iscoroutinefunction(func):
|
|
40 await func(first_run)
|
|
41 else:
|
|
42 func(first_run)
|
0
|
43
|
9
|
44 first_run = True
|
|
45 while True:
|
0
|
46 try:
|
9
|
47 await call_func(first_run)
|
0
|
48 up_metric.set(1)
|
|
49 first_run = False
|
|
50 except Exception as ex:
|
|
51 log.error(ex)
|
|
52 traceback.print_exc()
|
|
53 up_metric.set(0)
|
9
|
54 # todo: something that reveals error ratio
|
|
55 await asyncio.sleep(sleep_period)
|