-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchannel.py
More file actions
132 lines (115 loc) · 4.97 KB
/
Copy pathchannel.py
File metadata and controls
132 lines (115 loc) · 4.97 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
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
"""
Worker thread tying together source, regularizer, gap filling and sink for one
datapoint (dp_name/dp_location_code) pair.
"""
import logging
import math
import redis
import sched
import threading
import time
from typing import Optional
from .config import ChannelConfig
from .history import HistoryProvider
from .io import RedisStreamSink, RedisStreamSource
from .regularizer import TimeGridRegularizer
from .tools import Forecaster, Imputer
class Channel(threading.Thread):
"""
Runs `read -> regularize -> impute/forecast -> emit` on a wall-clock-aligned
schedule (`epoch + k * polling_interval`) via sched.scheduler. Each step
drains the Redis backlog with non-blocking reads, then polls the grid.
"""
def __init__(self, config: ChannelConfig, redis_pool: redis.ConnectionPool,
imputer: Imputer, forecaster: Forecaster,
history_provider: Optional[HistoryProvider],
stop_event: threading.Event):
"""
Initialize the channel.
Args:
config: The channel configuration object
redis_pool: The Redis connection pool object
imputer: The imputer to use object
forecaster: The forecaster to use object
history_provider: The optional TimescaleDB history provider object
stop_event: The event to signal when the channel should stop object
"""
super().__init__(name=f'channel-{config.name}', daemon=True)
self._config = config
self._stop_event = stop_event
self._logger = logging.getLogger(f'rdp-regularizer.{config.name}')
client = redis.Redis(connection_pool=redis_pool)
self._source = RedisStreamSource(client=client, stream=config.input_stream,
logger=self._logger)
self._regularizer = TimeGridRegularizer(config=config, imputer=imputer,
forecaster=forecaster,
history_provider=history_provider,
logger=self._logger)
self._sink = RedisStreamSink(client=client, config=config, logger=self._logger)
self._scheduler = sched.scheduler(time.time, self._stop_event.wait)
def run(self) -> None:
"""
Run the channel.
This method is called when the channel is started. It will:
- Log the channel start.
- Bootstrap the history if a history provider is configured.
- Schedule the first step.
- Run the scheduler.
- Log the channel stop.
"""
self._logger.info(f'Channel started: {self._config.input_stream} -> '
f'{self._config.output_stream} '
f'(polling {self._config.polling_interval}, lag {self._config.lag_time})')
# Bootstrap the history if a history provider is configured.
if not self._regularizer.bootstrap_history(
self._sink, self._source, self._stop_event
):
return
# Schedule the first step.
self._scheduler.enterabs(
self._next_polling_timestamp(),
1, self._scheduled_step
)
# Run the scheduler.
self._scheduler.run()
self._logger.info('Channel stopped')
def _step(self) -> None:
"""
Read samples from the source, add them to the regularizer, and emit the poll.
"""
# Read samples from the source.
for sample in self._source.read():
# Add the sample to the regularizer.
self._regularizer.add(sample)
# Emit the poll.
self._sink.emit(self._regularizer.poll())
def _scheduled_step(self) -> None:
"""
Scheduled step to read samples from the source, add them to the regularizer, and emit the poll.
"""
# Check if the channel should stop.
if self._stop_event.is_set():
return
# Try to read samples from the source, add them to the regularizer, and emit the poll.
try:
self._step()
except Exception as exc:
self._logger.exception(f'Unexpected error in channel step: {exc}')
self._logger.error(f'Try to resume in 5 seconds ...')
self._stop_event.wait(5)
# Schedule the next step.
if not self._stop_event.is_set():
self._scheduler.enterabs(
self._next_polling_timestamp(),
1, self._scheduled_step
)
def _next_polling_timestamp(self) -> float:
"""
Next wall-clock tick, aligned to `epoch + k * interval_s + offset_s`.
"""
# Get the current time, polling interval, and offset in seconds.
now = time.time()
interval_s = self._config.polling_interval.total_seconds()
offset_s = self._config.offset.total_seconds()
# Return the next wall-clock tick aligned to epoch.
return (math.floor(now / interval_s) + 1) * interval_s + offset_s