openrvdas.logger.writers.cached_data_writer
1#!/usr/bin/env python3 2 3import asyncio 4import json 5import logging 6import queue 7import ssl 8import threading 9import time 10 11from typing import Union 12try: 13 import websockets 14 WEBSOCKETS_INSTALLED = True 15except ImportError: 16 WEBSOCKETS_INSTALLED = False 17 18from logger.writers.writer import Writer # noqa: E402 19from logger.utils.das_record import DASRecord # noqa: E402 20 21 22class CachedDataWriter(Writer): 23 def __init__(self, data_server, start_server=False, back_seconds=480, 24 cleanup_interval=6, update_interval=1, 25 max_backup=60 * 60 * 24, use_wss=False, check_cert=False, **kwargs): 26 """Feed passed records to a CachedDataServer via a websocket. Expects 27 records in DASRecord or dict formats. 28 ``` 29 data_server [host:]port on which to look for data server 30 31 back_seconds Number of seconds of back data to hold in cache 32 33 cleanup_interval Remove old data every N seconds 34 35 update_interval Serve updates to websocket clients every N seconds 36 37 max_backup If the writer isn't able to connect to the data server, 38 it will locally cache records until it can. To avoid 39 unbounded memory usage, if max_backup is nonzero, it will 40 cache at most max_backup records before dropping the 41 oldest records. By default, cache one day's worth of 42 records at 1 Hz (86,400 records). If max_backup is zero, 43 cache size is unbounded. 44 45 use_wss - If True, use secure websockets 46 47 check_cert - If True and use_wss is True, check the server's TLS certificate 48 for validity; if a str, use as local filepath location of .pem 49 file to check against. 50 51 ``` 52 """ 53 if not WEBSOCKETS_INSTALLED: 54 raise ImportError('CachedDataWriter requires Python "websockets" module; ' 55 'please run "pip install websockets"') 56 57 super().__init__(**kwargs) # processes 'quiet' and type hints 58 59 host_port = data_server.split(':') 60 if len(host_port) == 1: 61 self.data_server = 'localhost:' + data_server # they gave us '8766' 62 elif not len(host_port[0]): 63 self.data_server = 'localhost' + data_server # they gave us ':8766' 64 else: 65 self.data_server = data_server # they gave us 'host:8766' 66 67 self.websocket = None 68 self.back_seconds = back_seconds 69 self.cleanup_interval = cleanup_interval 70 self.use_wss = use_wss 71 self.check_cert = check_cert 72 self.event_loop = asyncio.new_event_loop() 73 74 # Records are queued by write() - called from arbitrary threads - 75 # and drained by the sender thread, so this must be a thread-safe 76 # queue.Queue, NOT an asyncio.Queue (which is only safe within a 77 # single event loop). 78 self.send_queue = queue.Queue(maxsize=max_backup) 79 80 # Set by close() to tell the sender thread to finish up. 81 self.quit_flag = False 82 83 # Start the thread that will asynchronously pull stuff from the 84 # queue and send to the websocket. Also will, if we've got our oue 85 # data server, run cleanup from time to time. 86 self.cached_data_writer_thread = threading.Thread( 87 name='cached_data_writer_thread', 88 target=self._cached_data_writer_loop, daemon=True) 89 self.cached_data_writer_thread.start() 90 91 ############################ 92 def _cached_data_writer_loop(self): 93 """Use an inner async function to pull stuff from the queue and send 94 to the websocket. Also, if we've got our oue data server, run 95 cleanup from time to time. 96 """ 97 98 ############################ 99 async def _async_send_records_loop(self): 100 """Inner async function that actually does websocket writes 101 and cleanups. 102 """ 103 while not self.quit_flag: 104 logging.debug('CachedDataWriter trying to connect to ' 105 + self.data_server) 106 try: 107 if self.use_wss: 108 # If check_cert is a str, take it as the location of the 109 # .pem file we'll check for validity. Otherwise, if not 110 # False, take as a bool to verify by own means. 111 ws_data_server = 'wss://' + self.data_server 112 ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS) 113 if self.check_cert: 114 if isinstance(self.check_cert, str): 115 ssl_context.load_verify_locations(self.check_cert) 116 else: 117 ssl_context.verify_mode = ssl.CERT_REQUIRED 118 else: 119 ssl_context.verify_mode = ssl.CERT_NONE 120 121 else: # not using wss 122 ws_data_server = 'ws://' + self.data_server 123 ssl_context = None 124 125 logging.debug(f'CachedDataWriter connecting to {ws_data_server}') 126 async with websockets.connect(ws_data_server, ssl=ssl_context) as ws: 127 logging.debug(f'Connected to data server {ws_data_server}') 128 while True: 129 try: 130 record = self.send_queue.get_nowait() 131 logging.debug('sending record: %s', record) 132 record = {'type': 'publish', 'data': record} 133 await ws.send(json.dumps(record)) 134 response = await ws.recv() 135 logging.debug('received response: %s', response) 136 except queue.Empty: 137 if self.quit_flag: 138 return 139 await asyncio.sleep(.2) 140 141 except BrokenPipeError: 142 pass 143 except AttributeError as e: 144 logging.warning('CachedDataWriter websocket loop error: %s', e) 145 await asyncio.sleep(0.1) 146 except websockets.exceptions.ConnectionClosed: 147 logging.warning('CachedDataWriter lost websocket connection to ' 148 'data server; trying to reconnect.') 149 await asyncio.sleep(0.2) 150 151 except websockets.exceptions.InvalidStatusCode: 152 logging.warning('CachedDataWriter InvalidStatusCode connecting to ' 153 'data server; trying to reconnect.') 154 await asyncio.sleep(0.2) 155 156 # If the websocket connection failed 157 except OSError as e: 158 logging.warning('CachedDataWriter websocket connection to %s ' 159 'failed; sleeping before trying again: %s', 160 self.data_server, str(e)) 161 await asyncio.sleep(5) 162 163 # Now call the async process in its own event loop 164 self.event_loop.run_until_complete(_async_send_records_loop(self)) 165 self.event_loop.close() 166 167 ############################ 168 def close(self, timeout=5): 169 """Give the sender thread a bounded amount of time to deliver any 170 queued records, then tell it to quit. Without this, anything still 171 queued when the process exits is silently dropped (the sender is a 172 daemon thread). 173 """ 174 end_time = time.time() + timeout 175 while not self.send_queue.empty() and time.time() < end_time: 176 time.sleep(0.1) 177 178 undelivered = self.send_queue.qsize() 179 if undelivered: 180 logging.warning('CachedDataWriter closing with %d records ' 181 'undelivered', undelivered) 182 self.quit_flag = True 183 184 ############################ 185 def write(self, record: Union[DASRecord, dict]): 186 """Write out record. Expects passed records to be in one of three 187 formats: 188 189 1) DASRecord 190 191 2) a list of DASRecords 192 193 3) a dict encoding optionally a source data_id and timestamp and a 194 mandatory 'fields' key of field_name: value pairs. This is the format 195 emitted by default by ParseTransform: 196 197 { 198 'data_id': ..., 199 'timestamp': ..., 200 'fields': { 201 field_name: value, # use default timestamp of 'now' 202 field_name: value, 203 ... 204 } 205 } 206 207 A twist on format (3) THAT WE'RE PROBABLY GOING TO PHASE OUT IN 208 FAVOR OF (2) is that the values may either be a singleton (int, 209 float, string, etc) or a list. If the value is a singleton, it is 210 taken at face value. If it is a list, it is assumed to be a list 211 of (value, timestamp) tuples, in which case the top-level 212 timestamp, if any, is ignored. 213 214 { 215 'data_id': ..., 216 'timestamp': ..., 217 'fields': { 218 field_name: [(timestamp, value), (timestamp, value),...], 219 field_name: [(timestamp, value), (timestamp, value),...], 220 ... 221 } 222 } 223 224 """ 225 # See if it's something we can process, and if not, try digesting 226 if not self.can_process_record(record): # inherited from BaseModule() 227 self.digest_record(record) # inherited from BaseModule() 228 return 229 230 # Convert to a dict - inefficient, I know... 231 if isinstance(record, DASRecord): 232 record = json.loads(record.as_json()) 233 if isinstance(record, dict): 234 # If our local queue is full, throw away the oldest entries 235 while self.send_queue.full(): 236 try: 237 logging.debug('CachedDataWriter queue full - dropping oldest...') 238 self.send_queue.get_nowait() 239 except queue.Empty: 240 # Another thread emptied it in the meantime; that's fine 241 break 242 243 # Enqueue our latest record for send 244 try: 245 self.send_queue.put_nowait(record) 246 except queue.Full: 247 logging.warning('CachedDataWriter unable to write: write queue full') 248 else: 249 if not self.quiet: 250 logging.warning('CachedDataWriter got non-dict/DASRecord object of ' 251 'type %s: %s', type(record), str(record))
23class CachedDataWriter(Writer): 24 def __init__(self, data_server, start_server=False, back_seconds=480, 25 cleanup_interval=6, update_interval=1, 26 max_backup=60 * 60 * 24, use_wss=False, check_cert=False, **kwargs): 27 """Feed passed records to a CachedDataServer via a websocket. Expects 28 records in DASRecord or dict formats. 29 ``` 30 data_server [host:]port on which to look for data server 31 32 back_seconds Number of seconds of back data to hold in cache 33 34 cleanup_interval Remove old data every N seconds 35 36 update_interval Serve updates to websocket clients every N seconds 37 38 max_backup If the writer isn't able to connect to the data server, 39 it will locally cache records until it can. To avoid 40 unbounded memory usage, if max_backup is nonzero, it will 41 cache at most max_backup records before dropping the 42 oldest records. By default, cache one day's worth of 43 records at 1 Hz (86,400 records). If max_backup is zero, 44 cache size is unbounded. 45 46 use_wss - If True, use secure websockets 47 48 check_cert - If True and use_wss is True, check the server's TLS certificate 49 for validity; if a str, use as local filepath location of .pem 50 file to check against. 51 52 ``` 53 """ 54 if not WEBSOCKETS_INSTALLED: 55 raise ImportError('CachedDataWriter requires Python "websockets" module; ' 56 'please run "pip install websockets"') 57 58 super().__init__(**kwargs) # processes 'quiet' and type hints 59 60 host_port = data_server.split(':') 61 if len(host_port) == 1: 62 self.data_server = 'localhost:' + data_server # they gave us '8766' 63 elif not len(host_port[0]): 64 self.data_server = 'localhost' + data_server # they gave us ':8766' 65 else: 66 self.data_server = data_server # they gave us 'host:8766' 67 68 self.websocket = None 69 self.back_seconds = back_seconds 70 self.cleanup_interval = cleanup_interval 71 self.use_wss = use_wss 72 self.check_cert = check_cert 73 self.event_loop = asyncio.new_event_loop() 74 75 # Records are queued by write() - called from arbitrary threads - 76 # and drained by the sender thread, so this must be a thread-safe 77 # queue.Queue, NOT an asyncio.Queue (which is only safe within a 78 # single event loop). 79 self.send_queue = queue.Queue(maxsize=max_backup) 80 81 # Set by close() to tell the sender thread to finish up. 82 self.quit_flag = False 83 84 # Start the thread that will asynchronously pull stuff from the 85 # queue and send to the websocket. Also will, if we've got our oue 86 # data server, run cleanup from time to time. 87 self.cached_data_writer_thread = threading.Thread( 88 name='cached_data_writer_thread', 89 target=self._cached_data_writer_loop, daemon=True) 90 self.cached_data_writer_thread.start() 91 92 ############################ 93 def _cached_data_writer_loop(self): 94 """Use an inner async function to pull stuff from the queue and send 95 to the websocket. Also, if we've got our oue data server, run 96 cleanup from time to time. 97 """ 98 99 ############################ 100 async def _async_send_records_loop(self): 101 """Inner async function that actually does websocket writes 102 and cleanups. 103 """ 104 while not self.quit_flag: 105 logging.debug('CachedDataWriter trying to connect to ' 106 + self.data_server) 107 try: 108 if self.use_wss: 109 # If check_cert is a str, take it as the location of the 110 # .pem file we'll check for validity. Otherwise, if not 111 # False, take as a bool to verify by own means. 112 ws_data_server = 'wss://' + self.data_server 113 ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS) 114 if self.check_cert: 115 if isinstance(self.check_cert, str): 116 ssl_context.load_verify_locations(self.check_cert) 117 else: 118 ssl_context.verify_mode = ssl.CERT_REQUIRED 119 else: 120 ssl_context.verify_mode = ssl.CERT_NONE 121 122 else: # not using wss 123 ws_data_server = 'ws://' + self.data_server 124 ssl_context = None 125 126 logging.debug(f'CachedDataWriter connecting to {ws_data_server}') 127 async with websockets.connect(ws_data_server, ssl=ssl_context) as ws: 128 logging.debug(f'Connected to data server {ws_data_server}') 129 while True: 130 try: 131 record = self.send_queue.get_nowait() 132 logging.debug('sending record: %s', record) 133 record = {'type': 'publish', 'data': record} 134 await ws.send(json.dumps(record)) 135 response = await ws.recv() 136 logging.debug('received response: %s', response) 137 except queue.Empty: 138 if self.quit_flag: 139 return 140 await asyncio.sleep(.2) 141 142 except BrokenPipeError: 143 pass 144 except AttributeError as e: 145 logging.warning('CachedDataWriter websocket loop error: %s', e) 146 await asyncio.sleep(0.1) 147 except websockets.exceptions.ConnectionClosed: 148 logging.warning('CachedDataWriter lost websocket connection to ' 149 'data server; trying to reconnect.') 150 await asyncio.sleep(0.2) 151 152 except websockets.exceptions.InvalidStatusCode: 153 logging.warning('CachedDataWriter InvalidStatusCode connecting to ' 154 'data server; trying to reconnect.') 155 await asyncio.sleep(0.2) 156 157 # If the websocket connection failed 158 except OSError as e: 159 logging.warning('CachedDataWriter websocket connection to %s ' 160 'failed; sleeping before trying again: %s', 161 self.data_server, str(e)) 162 await asyncio.sleep(5) 163 164 # Now call the async process in its own event loop 165 self.event_loop.run_until_complete(_async_send_records_loop(self)) 166 self.event_loop.close() 167 168 ############################ 169 def close(self, timeout=5): 170 """Give the sender thread a bounded amount of time to deliver any 171 queued records, then tell it to quit. Without this, anything still 172 queued when the process exits is silently dropped (the sender is a 173 daemon thread). 174 """ 175 end_time = time.time() + timeout 176 while not self.send_queue.empty() and time.time() < end_time: 177 time.sleep(0.1) 178 179 undelivered = self.send_queue.qsize() 180 if undelivered: 181 logging.warning('CachedDataWriter closing with %d records ' 182 'undelivered', undelivered) 183 self.quit_flag = True 184 185 ############################ 186 def write(self, record: Union[DASRecord, dict]): 187 """Write out record. Expects passed records to be in one of three 188 formats: 189 190 1) DASRecord 191 192 2) a list of DASRecords 193 194 3) a dict encoding optionally a source data_id and timestamp and a 195 mandatory 'fields' key of field_name: value pairs. This is the format 196 emitted by default by ParseTransform: 197 198 { 199 'data_id': ..., 200 'timestamp': ..., 201 'fields': { 202 field_name: value, # use default timestamp of 'now' 203 field_name: value, 204 ... 205 } 206 } 207 208 A twist on format (3) THAT WE'RE PROBABLY GOING TO PHASE OUT IN 209 FAVOR OF (2) is that the values may either be a singleton (int, 210 float, string, etc) or a list. If the value is a singleton, it is 211 taken at face value. If it is a list, it is assumed to be a list 212 of (value, timestamp) tuples, in which case the top-level 213 timestamp, if any, is ignored. 214 215 { 216 'data_id': ..., 217 'timestamp': ..., 218 'fields': { 219 field_name: [(timestamp, value), (timestamp, value),...], 220 field_name: [(timestamp, value), (timestamp, value),...], 221 ... 222 } 223 } 224 225 """ 226 # See if it's something we can process, and if not, try digesting 227 if not self.can_process_record(record): # inherited from BaseModule() 228 self.digest_record(record) # inherited from BaseModule() 229 return 230 231 # Convert to a dict - inefficient, I know... 232 if isinstance(record, DASRecord): 233 record = json.loads(record.as_json()) 234 if isinstance(record, dict): 235 # If our local queue is full, throw away the oldest entries 236 while self.send_queue.full(): 237 try: 238 logging.debug('CachedDataWriter queue full - dropping oldest...') 239 self.send_queue.get_nowait() 240 except queue.Empty: 241 # Another thread emptied it in the meantime; that's fine 242 break 243 244 # Enqueue our latest record for send 245 try: 246 self.send_queue.put_nowait(record) 247 except queue.Full: 248 logging.warning('CachedDataWriter unable to write: write queue full') 249 else: 250 if not self.quiet: 251 logging.warning('CachedDataWriter got non-dict/DASRecord object of ' 252 'type %s: %s', type(record), str(record))
Base class Writer about which we know nothing else. By default the input format is Unknown unless overridden.
Passes arguments quiet, encoding and encoding_errors up to BaseModule
24 def __init__(self, data_server, start_server=False, back_seconds=480, 25 cleanup_interval=6, update_interval=1, 26 max_backup=60 * 60 * 24, use_wss=False, check_cert=False, **kwargs): 27 """Feed passed records to a CachedDataServer via a websocket. Expects 28 records in DASRecord or dict formats. 29 ``` 30 data_server [host:]port on which to look for data server 31 32 back_seconds Number of seconds of back data to hold in cache 33 34 cleanup_interval Remove old data every N seconds 35 36 update_interval Serve updates to websocket clients every N seconds 37 38 max_backup If the writer isn't able to connect to the data server, 39 it will locally cache records until it can. To avoid 40 unbounded memory usage, if max_backup is nonzero, it will 41 cache at most max_backup records before dropping the 42 oldest records. By default, cache one day's worth of 43 records at 1 Hz (86,400 records). If max_backup is zero, 44 cache size is unbounded. 45 46 use_wss - If True, use secure websockets 47 48 check_cert - If True and use_wss is True, check the server's TLS certificate 49 for validity; if a str, use as local filepath location of .pem 50 file to check against. 51 52 ``` 53 """ 54 if not WEBSOCKETS_INSTALLED: 55 raise ImportError('CachedDataWriter requires Python "websockets" module; ' 56 'please run "pip install websockets"') 57 58 super().__init__(**kwargs) # processes 'quiet' and type hints 59 60 host_port = data_server.split(':') 61 if len(host_port) == 1: 62 self.data_server = 'localhost:' + data_server # they gave us '8766' 63 elif not len(host_port[0]): 64 self.data_server = 'localhost' + data_server # they gave us ':8766' 65 else: 66 self.data_server = data_server # they gave us 'host:8766' 67 68 self.websocket = None 69 self.back_seconds = back_seconds 70 self.cleanup_interval = cleanup_interval 71 self.use_wss = use_wss 72 self.check_cert = check_cert 73 self.event_loop = asyncio.new_event_loop() 74 75 # Records are queued by write() - called from arbitrary threads - 76 # and drained by the sender thread, so this must be a thread-safe 77 # queue.Queue, NOT an asyncio.Queue (which is only safe within a 78 # single event loop). 79 self.send_queue = queue.Queue(maxsize=max_backup) 80 81 # Set by close() to tell the sender thread to finish up. 82 self.quit_flag = False 83 84 # Start the thread that will asynchronously pull stuff from the 85 # queue and send to the websocket. Also will, if we've got our oue 86 # data server, run cleanup from time to time. 87 self.cached_data_writer_thread = threading.Thread( 88 name='cached_data_writer_thread', 89 target=self._cached_data_writer_loop, daemon=True) 90 self.cached_data_writer_thread.start()
Feed passed records to a CachedDataServer via a websocket. Expects records in DASRecord or dict formats.
data_server [host:]port on which to look for data server
back_seconds Number of seconds of back data to hold in cache
cleanup_interval Remove old data every N seconds
update_interval Serve updates to websocket clients every N seconds
max_backup If the writer isn't able to connect to the data server,
it will locally cache records until it can. To avoid
unbounded memory usage, if max_backup is nonzero, it will
cache at most max_backup records before dropping the
oldest records. By default, cache one day's worth of
records at 1 Hz (86,400 records). If max_backup is zero,
cache size is unbounded.
use_wss - If True, use secure websockets
check_cert - If True and use_wss is True, check the server's TLS certificate
for validity; if a str, use as local filepath location of .pem
file to check against.
169 def close(self, timeout=5): 170 """Give the sender thread a bounded amount of time to deliver any 171 queued records, then tell it to quit. Without this, anything still 172 queued when the process exits is silently dropped (the sender is a 173 daemon thread). 174 """ 175 end_time = time.time() + timeout 176 while not self.send_queue.empty() and time.time() < end_time: 177 time.sleep(0.1) 178 179 undelivered = self.send_queue.qsize() 180 if undelivered: 181 logging.warning('CachedDataWriter closing with %d records ' 182 'undelivered', undelivered) 183 self.quit_flag = True
Give the sender thread a bounded amount of time to deliver any queued records, then tell it to quit. Without this, anything still queued when the process exits is silently dropped (the sender is a daemon thread).
186 def write(self, record: Union[DASRecord, dict]): 187 """Write out record. Expects passed records to be in one of three 188 formats: 189 190 1) DASRecord 191 192 2) a list of DASRecords 193 194 3) a dict encoding optionally a source data_id and timestamp and a 195 mandatory 'fields' key of field_name: value pairs. This is the format 196 emitted by default by ParseTransform: 197 198 { 199 'data_id': ..., 200 'timestamp': ..., 201 'fields': { 202 field_name: value, # use default timestamp of 'now' 203 field_name: value, 204 ... 205 } 206 } 207 208 A twist on format (3) THAT WE'RE PROBABLY GOING TO PHASE OUT IN 209 FAVOR OF (2) is that the values may either be a singleton (int, 210 float, string, etc) or a list. If the value is a singleton, it is 211 taken at face value. If it is a list, it is assumed to be a list 212 of (value, timestamp) tuples, in which case the top-level 213 timestamp, if any, is ignored. 214 215 { 216 'data_id': ..., 217 'timestamp': ..., 218 'fields': { 219 field_name: [(timestamp, value), (timestamp, value),...], 220 field_name: [(timestamp, value), (timestamp, value),...], 221 ... 222 } 223 } 224 225 """ 226 # See if it's something we can process, and if not, try digesting 227 if not self.can_process_record(record): # inherited from BaseModule() 228 self.digest_record(record) # inherited from BaseModule() 229 return 230 231 # Convert to a dict - inefficient, I know... 232 if isinstance(record, DASRecord): 233 record = json.loads(record.as_json()) 234 if isinstance(record, dict): 235 # If our local queue is full, throw away the oldest entries 236 while self.send_queue.full(): 237 try: 238 logging.debug('CachedDataWriter queue full - dropping oldest...') 239 self.send_queue.get_nowait() 240 except queue.Empty: 241 # Another thread emptied it in the meantime; that's fine 242 break 243 244 # Enqueue our latest record for send 245 try: 246 self.send_queue.put_nowait(record) 247 except queue.Full: 248 logging.warning('CachedDataWriter unable to write: write queue full') 249 else: 250 if not self.quiet: 251 logging.warning('CachedDataWriter got non-dict/DASRecord object of ' 252 'type %s: %s', type(record), str(record))
Write out record. Expects passed records to be in one of three formats:
1) DASRecord
2) a list of DASRecords
3) a dict encoding optionally a source data_id and timestamp and a mandatory 'fields' key of field_name: value pairs. This is the format emitted by default by ParseTransform:
{ 'data_id': ..., 'timestamp': ..., 'fields': { field_name: value, # use default timestamp of 'now' field_name: value, ... } }
A twist on format (3) THAT WE'RE PROBABLY GOING TO PHASE OUT IN FAVOR OF (2) is that the values may either be a singleton (int, float, string, etc) or a list. If the value is a singleton, it is taken at face value. If it is a list, it is assumed to be a list of (value, timestamp) tuples, in which case the top-level timestamp, if any, is ignored.
{ 'data_id': ..., 'timestamp': ..., 'fields': { field_name: [(timestamp, value), (timestamp, value),...], field_name: [(timestamp, value), (timestamp, value),...], ... } }