1- class Agent (object ):
1+ from abc import ABC , abstractmethod
2+
3+ from oshino .util import current_ts , timer
4+
5+
6+ class Agent (ABC ):
27
38 def __init__ (self , cfg ):
49 self ._data = cfg
10+ self ._last_run = current_ts ()
511
612 def on_start (self ):
713 pass
@@ -21,8 +27,60 @@ def get_logger(self):
2127 from logbook import Logger
2228 return Logger (self .__class__ .__name__ )
2329
30+ @abstractmethod
2431 async def process (self , event_fn ):
32+ """
33+ Each agent must implement this one to provide actual logic
34+ """
2535 pass
2636
2737 def is_valid (self ):
2838 return "name" in self ._data
39+
40+ async def pull_metrics (self , event_fn , loop = None ):
41+ """
42+ Method called by core.
43+ Should not be overwritten.
44+ """
45+ if self .lazy and not self .ready :
46+ return None
47+ logger = self .get_logger ()
48+
49+ ts = timer ()
50+ logger .trace ("Waiting for process event" )
51+ result = await self .process (event_fn )
52+ td = int (timer () - ts )
53+ logger .trace ("It took: {}ms" .format (td ))
54+ self ._last_run = current_ts ()
55+ return result
56+
57+ @property
58+ def lazy (self ):
59+ """
60+ Agents with flag `lazy` gives data when they want to,
61+ not when they are requested for.
62+ """
63+ return self ._data .get ("lazy" , False )
64+
65+ @property
66+ def ready (self ):
67+ """
68+ Function used when agent is `lazy`.
69+ It is being processed only when `ready` condition is satisfied
70+ """
71+ logger = self .get_logger ()
72+ now = current_ts ()
73+ logger .trace ("Current time: {0}" .format (now ))
74+ logger .trace ("Last Run: {0}" .format (self ._last_run ))
75+ delta = (now - self ._last_run )
76+ logger .trace ("Delta: {0}, Interval: {1}"
77+ .format (delta , self .interval * 1000 ))
78+ return delta > self .interval * 1000
79+
80+ @property
81+ def interval (self ):
82+ """
83+ By default, lazy agents expects to have some kind of time interval.
84+ `ready` output is calculated according to this interval.
85+ """
86+ return self ._data ["interval" ]
0 commit comments