openrvdas.server.state_journal
An append-only journal of the logger manager's state changes: which cruise definition is loaded, which mode is active, which config each logger is running, and when loggers start, stop, crash and recover. See issue #670.
Each change is one line in a daily file named
{"data_id": "logger_manager", "message_type": "mode_changed",
"timestamp": 1792677791.204, "fields": {"event": "mode_changed",
"time": "2026-10-22T14:03:11.204Z", "from": "no_write", "to": "write"}}
Each line is plain JSON, so the journal can be read with jq or grep. It can also be read back - and followed as it grows - by a LogfileReader, which returns each line as a DASRecord, so a logger can send the journal to any writer: InfluxDB, the CachedDataServer, a UDP port, or Sealog by way of ToSealogTransform and SealogWriter. For example:
readers:
class: LogfileReader
kwargs:
filebase: /var/log/openrvdas/logger_manager_journal
tail: true # follow the journal as it grows
refresh_file_spec: true # and move on to each new day's file
Writing is deliberately low-impact: the file is opened only when there is something to record, and a failure to write (an unwritable directory, say) is logged once and otherwise ignored, so the journal can never get in the way of managing loggers.
1#!/usr/bin/env python3 2"""An append-only journal of the logger manager's state changes: which 3cruise definition is loaded, which mode is active, which config each logger 4is running, and when loggers start, stop, crash and recover. See issue #670. 5 6Each change is one line in a daily file named <filebase>-YYYY-MM-DD (the 7date in UTC), the same naming LogfileWriter uses. Each line is a DASRecord 8in JSON, whose message_type is the kind of event and whose fields describe 9it: 10 11 {"data_id": "logger_manager", "message_type": "mode_changed", 12 "timestamp": 1792677791.204, "fields": {"event": "mode_changed", 13 "time": "2026-10-22T14:03:11.204Z", "from": "no_write", "to": "write"}} 14 15Each line is plain JSON, so the journal can be read with jq or grep. It can 16also be read back - and followed as it grows - by a LogfileReader, which 17returns each line as a DASRecord, so a logger can send the journal to any 18writer: InfluxDB, the CachedDataServer, a UDP port, or Sealog by way of 19ToSealogTransform and SealogWriter. For example: 20 21 readers: 22 class: LogfileReader 23 kwargs: 24 filebase: /var/log/openrvdas/logger_manager_journal 25 tail: true # follow the journal as it grows 26 refresh_file_spec: true # and move on to each new day's file 27 28Writing is deliberately low-impact: the file is opened only when there is 29something to record, and a failure to write (an unwritable directory, say) 30is logged once and otherwise ignored, so the journal can never get in the 31way of managing loggers. 32""" 33import datetime 34import hashlib 35import json 36import logging 37import os 38import threading 39 40from logger.utils.das_record import DASRecord # noqa: E402 41 42DATA_ID = 'logger_manager' 43 44 45def config_hash(config): 46 """sha256 identifying a logger config's exact contents. Computed from 47 canonical JSON, so the same config gives the same hash wherever it is 48 computed - e.g. from a config snapshot's expanded_config.yaml.""" 49 canonical = json.dumps(config, sort_keys=True, separators=(',', ':'), default=str) 50 return hashlib.sha256(canonical.encode('utf-8')).hexdigest() 51 52 53class StateJournal: 54 def __init__(self, filebase=None): 55 """ 56 filebase - path prefix for the journal's daily files, e.g. 57 /var/log/openrvdas/logger_manager_journal. If None or 58 empty, record() does nothing. 59 """ 60 self.filebase = filebase or None 61 self.lock = threading.Lock() 62 self.warned = False 63 64 if self.filebase: 65 directory = os.path.dirname(os.path.abspath(self.filebase)) 66 if not os.path.isdir(directory) or not os.access(directory, os.W_OK): 67 self._warn(f'directory {directory} does not exist or is not writable') 68 69 def filename(self, when): 70 """The day's file, named as LogfileWriter would name it, so that a 71 LogfileReader given the same filebase finds it.""" 72 return f'{self.filebase}-{when.strftime("%Y-%m-%d")}' 73 74 def record(self, event, **fields): 75 """Append one event to the journal. Never raises.""" 76 if not self.filebase: 77 return 78 now = datetime.datetime.now(datetime.timezone.utc) 79 time_str = now.strftime('%Y-%m-%dT%H:%M:%S.') + f'{now.microsecond // 1000:03d}Z' 80 try: 81 # Make the fields plain JSON values (e.g. a datetime becomes a 82 # string), so that the record reads back exactly as written. 83 fields = json.loads(json.dumps( 84 {'event': event, 'time': time_str, **fields}, default=str)) 85 line = DASRecord(data_id=DATA_ID, message_type=event, 86 timestamp=now.timestamp(), fields=fields).as_json() 87 with self.lock: 88 with open(self.filename(now), 'a') as f: 89 f.write(line + '\n') 90 except Exception as e: # noqa: BLE001 - must never stop the logger manager 91 self._warn(e) 92 93 def _warn(self, problem): 94 """Complain once, rather than on every event.""" 95 if not self.warned: 96 self.warned = True 97 logging.warning('State journal %s: cannot write (%s); state changes ' 98 'will not be recorded.', self.filebase, problem)
46def config_hash(config): 47 """sha256 identifying a logger config's exact contents. Computed from 48 canonical JSON, so the same config gives the same hash wherever it is 49 computed - e.g. from a config snapshot's expanded_config.yaml.""" 50 canonical = json.dumps(config, sort_keys=True, separators=(',', ':'), default=str) 51 return hashlib.sha256(canonical.encode('utf-8')).hexdigest()
sha256 identifying a logger config's exact contents. Computed from canonical JSON, so the same config gives the same hash wherever it is computed - e.g. from a config snapshot's expanded_config.yaml.
54class StateJournal: 55 def __init__(self, filebase=None): 56 """ 57 filebase - path prefix for the journal's daily files, e.g. 58 /var/log/openrvdas/logger_manager_journal. If None or 59 empty, record() does nothing. 60 """ 61 self.filebase = filebase or None 62 self.lock = threading.Lock() 63 self.warned = False 64 65 if self.filebase: 66 directory = os.path.dirname(os.path.abspath(self.filebase)) 67 if not os.path.isdir(directory) or not os.access(directory, os.W_OK): 68 self._warn(f'directory {directory} does not exist or is not writable') 69 70 def filename(self, when): 71 """The day's file, named as LogfileWriter would name it, so that a 72 LogfileReader given the same filebase finds it.""" 73 return f'{self.filebase}-{when.strftime("%Y-%m-%d")}' 74 75 def record(self, event, **fields): 76 """Append one event to the journal. Never raises.""" 77 if not self.filebase: 78 return 79 now = datetime.datetime.now(datetime.timezone.utc) 80 time_str = now.strftime('%Y-%m-%dT%H:%M:%S.') + f'{now.microsecond // 1000:03d}Z' 81 try: 82 # Make the fields plain JSON values (e.g. a datetime becomes a 83 # string), so that the record reads back exactly as written. 84 fields = json.loads(json.dumps( 85 {'event': event, 'time': time_str, **fields}, default=str)) 86 line = DASRecord(data_id=DATA_ID, message_type=event, 87 timestamp=now.timestamp(), fields=fields).as_json() 88 with self.lock: 89 with open(self.filename(now), 'a') as f: 90 f.write(line + '\n') 91 except Exception as e: # noqa: BLE001 - must never stop the logger manager 92 self._warn(e) 93 94 def _warn(self, problem): 95 """Complain once, rather than on every event.""" 96 if not self.warned: 97 self.warned = True 98 logging.warning('State journal %s: cannot write (%s); state changes ' 99 'will not be recorded.', self.filebase, problem)
55 def __init__(self, filebase=None): 56 """ 57 filebase - path prefix for the journal's daily files, e.g. 58 /var/log/openrvdas/logger_manager_journal. If None or 59 empty, record() does nothing. 60 """ 61 self.filebase = filebase or None 62 self.lock = threading.Lock() 63 self.warned = False 64 65 if self.filebase: 66 directory = os.path.dirname(os.path.abspath(self.filebase)) 67 if not os.path.isdir(directory) or not os.access(directory, os.W_OK): 68 self._warn(f'directory {directory} does not exist or is not writable')
filebase - path prefix for the journal's daily files, e.g. /var/log/openrvdas/logger_manager_journal. If None or empty, record() does nothing.
70 def filename(self, when): 71 """The day's file, named as LogfileWriter would name it, so that a 72 LogfileReader given the same filebase finds it.""" 73 return f'{self.filebase}-{when.strftime("%Y-%m-%d")}'
The day's file, named as LogfileWriter would name it, so that a LogfileReader given the same filebase finds it.
75 def record(self, event, **fields): 76 """Append one event to the journal. Never raises.""" 77 if not self.filebase: 78 return 79 now = datetime.datetime.now(datetime.timezone.utc) 80 time_str = now.strftime('%Y-%m-%dT%H:%M:%S.') + f'{now.microsecond // 1000:03d}Z' 81 try: 82 # Make the fields plain JSON values (e.g. a datetime becomes a 83 # string), so that the record reads back exactly as written. 84 fields = json.loads(json.dumps( 85 {'event': event, 'time': time_str, **fields}, default=str)) 86 line = DASRecord(data_id=DATA_ID, message_type=event, 87 timestamp=now.timestamp(), fields=fields).as_json() 88 with self.lock: 89 with open(self.filename(now), 'a') as f: 90 f.write(line + '\n') 91 except Exception as e: # noqa: BLE001 - must never stop the logger manager 92 self._warn(e)
Append one event to the journal. Never raises.