|
| 1 | +import datetime as dt |
| 2 | +import logging |
| 3 | +import time as tm |
| 4 | + |
| 5 | +from apscheduler.executors.pool import ThreadPoolExecutor |
| 6 | +from apscheduler.schedulers.asyncio import AsyncIOScheduler |
| 7 | + |
| 8 | +from data_agent.exceptions import HistoryHarvesterJobAlreadyExists |
| 9 | +from data_agent.msg_packer import encode_dataframe |
| 10 | + |
| 11 | +log = logging.getLogger(__name__) |
| 12 | + |
| 13 | + |
| 14 | +class HistoryHarvester: |
| 15 | + def __init__(self, connection_manager, broker): |
| 16 | + self.connection_manager = connection_manager |
| 17 | + self.broker = broker |
| 18 | + |
| 19 | + self._thread_pool_executor = ThreadPoolExecutor(max_workers=20) |
| 20 | + self._scheduler = AsyncIOScheduler(thread_pool=self._thread_pool_executor) |
| 21 | + self._scheduler.start() |
| 22 | + |
| 23 | + async def _delivery_job_func( |
| 24 | + self, |
| 25 | + job_id, |
| 26 | + conn, |
| 27 | + tags, |
| 28 | + first_timestamp, |
| 29 | + last_timestamp, |
| 30 | + time_frequency, |
| 31 | + batch_size, |
| 32 | + iteration, |
| 33 | + ): |
| 34 | + try: |
| 35 | + start_time = tm.time() |
| 36 | + |
| 37 | + next_period_end = min(last_timestamp, first_timestamp + batch_size) |
| 38 | + |
| 39 | + df = conn.read_tag_values_period( |
| 40 | + tags=tags, |
| 41 | + first_timestamp=first_timestamp, |
| 42 | + last_timestamp=next_period_end, |
| 43 | + time_frequency=time_frequency, |
| 44 | + ) |
| 45 | + |
| 46 | + read_time = tm.time() - start_time |
| 47 | + |
| 48 | + if df.empty: |
| 49 | + log.warning( |
| 50 | + f"No data read for job '{job_id}' for period {first_timestamp} - {next_period_end}" |
| 51 | + ) |
| 52 | + |
| 53 | + else: # Publish data |
| 54 | + headers = { |
| 55 | + "data_category": "historical", |
| 56 | + "connection": conn.name, |
| 57 | + "job_id": job_id, |
| 58 | + "batch_num": iteration, |
| 59 | + } |
| 60 | + |
| 61 | + payload = encode_dataframe(df) |
| 62 | + |
| 63 | + log.debug( |
| 64 | + f"(#{iteration}): Job {job_id}: " |
| 65 | + f"Data publish: read time={read_time:.2f}s), {len(df)} samples, " |
| 66 | + f"period: {first_timestamp} - {next_period_end}" |
| 67 | + ) |
| 68 | + self.broker.publish_data(payload, headers=headers) |
| 69 | + |
| 70 | + if next_period_end < last_timestamp: |
| 71 | + # Reschedule next run |
| 72 | + self._scheduler.add_job( |
| 73 | + func=self._delivery_job_func, |
| 74 | + trigger="date", |
| 75 | + # next_run_time=dt.datetime.now(), |
| 76 | + coalesce=True, # Always run once |
| 77 | + id=job_id, |
| 78 | + max_instances=2, |
| 79 | + replace_existing=True, |
| 80 | + args=[ |
| 81 | + job_id, |
| 82 | + conn, |
| 83 | + tags, |
| 84 | + next_period_end, |
| 85 | + last_timestamp, |
| 86 | + time_frequency, |
| 87 | + batch_size, |
| 88 | + iteration + 1, |
| 89 | + ], |
| 90 | + ) |
| 91 | + |
| 92 | + except Exception as e: |
| 93 | + log.exception(f'Exception in history harvester job "{job_id}" - {e}') |
| 94 | + |
| 95 | + def create_delivery_job( |
| 96 | + self, |
| 97 | + job_id: str, |
| 98 | + conn_name: str, |
| 99 | + tags: list, |
| 100 | + first_timestamp: dt.datetime, |
| 101 | + last_timestamp: dt.datetime, |
| 102 | + time_frequency: dt.timedelta, |
| 103 | + batch_size: dt.timedelta = None, |
| 104 | + progress_callback=None, |
| 105 | + ): |
| 106 | + # order tags alphabetically |
| 107 | + tags.sort() |
| 108 | + |
| 109 | + existing_job = self._scheduler.get_job(job_id) |
| 110 | + if existing_job: |
| 111 | + raise HistoryHarvesterJobAlreadyExists( |
| 112 | + f"History loader Job {job_id} already exists." |
| 113 | + ) |
| 114 | + |
| 115 | + conn = self.connection_manager.connection(conn_name, check_enabled=False) |
| 116 | + |
| 117 | + self._scheduler.add_job( |
| 118 | + func=self._delivery_job_func, |
| 119 | + trigger="date", |
| 120 | + # next_run_time=dt.datetime.now(), |
| 121 | + coalesce=True, # Always run once |
| 122 | + id=job_id, |
| 123 | + max_instances=2, |
| 124 | + replace_existing=True, |
| 125 | + args=[ |
| 126 | + job_id, |
| 127 | + conn, |
| 128 | + tags, |
| 129 | + first_timestamp, |
| 130 | + last_timestamp, |
| 131 | + time_frequency, |
| 132 | + batch_size, |
| 133 | + 0, |
| 134 | + ], |
| 135 | + ) |
0 commit comments