-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
830 lines (675 loc) · 33.1 KB
/
Copy pathmain.py
File metadata and controls
830 lines (675 loc) · 33.1 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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
"""
main.py
Daily orchestration: read all sensors, log to Excel, send alerts, save run summary.
Runs at 08:00 via cron. Exit codes: 0=success, 1=partial failure, 2=system error, 3=unauthorized.
"""
import sys
import logging
from datetime import datetime
from pathlib import Path
import json
import traceback
import hashlib
import subprocess
import time
from typing import Dict, List, Tuple
from functools import wraps
from dotenv import load_dotenv
load_dotenv()
from src.sensor_factory import create_sensor
from src.excel_logger import ExcelLogger
from src.email_alerts import EmailAlerts
from src.access_control import AccessControl, check_execution_authorization
__version__ = "1.1.0"
def retry_on_permission_error(max_attempts=3, delay=5):
"""Retry decorator for operations that may fail due to Excel file locking."""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
last_exception = None
for attempt in range(max_attempts):
try:
return func(*args, **kwargs)
except PermissionError as e:
last_exception = e
if attempt < max_attempts - 1:
logging.warning(
f"Permission error (attempt {attempt + 1}/{max_attempts}): {e}. "
f"Retrying in {delay} seconds..."
)
time.sleep(delay)
else:
logging.error(f"Failed after {max_attempts} attempts")
raise
raise last_exception
return wrapper
return decorator
class TemperatureMonitor:
"""Coordinates sensor reading, Excel logging, and email alerting."""
def __init__(self, config_path: str = "config/settings.json"):
self.config_path = config_path
self.start_time = datetime.now()
self._setup_logging()
self.logger = logging.getLogger(__name__)
self.logger.info("=" * 70)
self.logger.info(f"TEMPERATURE MONITORING SYSTEM v{__version__}")
self.logger.info(f"Started: {self.start_time.isoformat()}")
self.logger.info("=" * 70)
self.run_summary = {
'total_sensors': 0,
'successful_readings': 0,
'failed_readings': 0,
'out_of_range': 0,
'sensors_offline': 0,
'excel_errors': 0,
'email_errors': 0,
'time_sync_ok': True
}
# Settings must load before time sync (environment detection depends on it)
self.settings = self._load_settings()
self.sensors_config = self._load_sensor_config()
self._verify_time_sync()
self._log_config_versions()
try:
self.logger.info("Initializing system components...")
self.sensor = create_sensor(config_path)
self.logger.info(f" Sensor interface: {type(self.sensor).__name__}")
self.email_alerts = EmailAlerts(config_path)
self.logger.info(f" Email alerts: Initialized")
# Pass the shared EmailAlerts instance to avoid duplicate SMTP connections
self.excel_logger = ExcelLogger(config_path, email_alerts=self.email_alerts)
self.logger.info(f" Excel logger: Initialized")
self.logger.info("All components initialized successfully")
except Exception as e:
self.logger.error(f"CRITICAL: Failed to initialize components: {e}", exc_info=True)
raise
def _setup_logging(self):
log_dir = Path("logs")
log_dir.mkdir(exist_ok=True)
log_file = log_dir / "temp_monitor.log"
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s | %(levelname)s | %(name)s | %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
handlers=[
logging.FileHandler(log_file),
logging.StreamHandler(sys.stdout)
],
force=True # overrides logging config from imported modules
)
def _verify_time_sync(self) -> bool:
"""Verify NTP sync; aborts in production if clock is unsynchronized."""
environment = self.settings.get('environment', 'development')
is_production = (environment == 'production')
try:
result = subprocess.run(['which', 'ntpstat'],
capture_output=True,
text=True)
if result.returncode != 0:
if is_production:
self.logger.critical("TIME SYNC FAILED: ntpstat not available in PRODUCTION mode")
self.logger.critical("ABORTING: Cannot verify timestamp accuracy")
self.run_summary['time_sync_ok'] = False
self.email_alerts.send_system_error_alert(
error_type="TIME_SYNC_FAILED",
error_message="System time synchronization check failed. NTP not configured.",
context={
'environment': environment,
'action': 'System aborted - manual temperature checks required',
'fix': 'Verify NTP service is installed and running'
}
)
raise SystemError(
"TIME SYNC FAILED: Cannot verify timestamp accuracy in production. "
"System aborted to prevent logging data with questionable timestamps. "
"Perform manual temperature checks until NTP is configured."
)
else:
self.logger.warning("TIME SYNC: ntpstat not available (development mode - OK)")
self.run_summary['time_sync_ok'] = False
return False
result = subprocess.run(['ntpstat'],
capture_output=True,
text=True,
timeout=5)
if result.returncode == 0:
self.logger.info("TIME SYNC: System clock synchronized to NTP")
self.run_summary['time_sync_ok'] = True
return True
else:
if is_production:
self.logger.critical("TIME SYNC FAILED: System clock not synchronized")
self.logger.critical(f"ntpstat output: {result.stdout}")
self.logger.critical("ABORTING: Cannot guarantee timestamp accuracy")
self.run_summary['time_sync_ok'] = False
self.email_alerts.send_system_error_alert(
error_type="TIME_SYNC_FAILED",
error_message="System time is not synchronized to NTP server.",
context={
'environment': environment,
'ntpstat_output': result.stdout,
'action': 'System aborted - manual temperature checks required',
'fix': 'Check NTP service: sudo systemctl status ntp'
}
)
raise SystemError(
"TIME SYNC FAILED: System clock not synchronized to NTP. "
"Cannot guarantee timestamp accuracy for FDA compliance. "
"Perform manual temperature checks until NTP sync is restored."
)
else:
self.logger.warning(f"TIME SYNC: Not synchronized (development mode - OK)")
self.logger.warning(f"ntpstat output: {result.stdout}")
self.run_summary['time_sync_ok'] = False
return False
except subprocess.TimeoutExpired:
self.logger.error("TIME SYNC: ntpstat command timed out")
self.run_summary['time_sync_ok'] = False
if is_production:
self.email_alerts.send_system_error_alert(
error_type="TIME_SYNC_TIMEOUT",
error_message="Time sync check timed out",
context={'environment': environment}
)
raise SystemError("TIME SYNC CHECK TIMED OUT")
return False
except Exception as e:
self.logger.error(f"TIME SYNC: Error checking time sync: {e}")
self.run_summary['time_sync_ok'] = False
if is_production:
self.email_alerts.send_system_error_alert(
error_type="TIME_SYNC_ERROR",
error_message=f"Error checking time sync: {str(e)}",
context={'environment': environment}
)
raise SystemError(f"TIME SYNC CHECK FAILED: {e}")
return False
def _calculate_checksum(self, filepath: Path) -> str:
"""Return SHA-256 checksum of a file."""
try:
with open(filepath, 'rb') as f:
return hashlib.sha256(f.read()).hexdigest()
except Exception as e:
return f"ERROR: {e}"
def _log_config_versions(self):
"""Verify config integrity and log current checksums."""
self._verify_config_integrity()
config_files = [
Path(self.config_path),
Path("config/sensors.json")
]
self.logger.info("Configuration versions:")
for config_file in config_files:
if config_file.exists():
checksum = self._calculate_checksum(config_file)
self.logger.info(f" {config_file}: SHA256={checksum}")
else:
self.logger.warning(f" {config_file}: NOT FOUND")
def _get_registry_path(self) -> Path:
return Path("config/checksum_registry.json")
def _load_checksum_registry(self) -> dict:
"""Load the checksum registry; returns empty dict on first run."""
registry_path = self._get_registry_path()
if not registry_path.exists():
self.logger.warning("Checksum registry not found - this appears to be first run")
return {}
try:
with open(registry_path, 'r') as f:
registry = json.load(f)
self.logger.debug(f"Loaded checksum registry: {len(registry)} files")
return registry
except Exception as e:
self.logger.error(f"Failed to load checksum registry: {e}")
return {}
def _save_checksum_registry(self, checksums: dict) -> None:
"""Save checksums to the registry file."""
registry_path = self._get_registry_path()
try:
registry_path.parent.mkdir(parents=True, exist_ok=True)
import getpass
import socket
try:
system_user = getpass.getuser()
except:
system_user = "UNKNOWN"
hostname = socket.gethostname()
registry_data = {
'checksums': checksums,
'last_updated': datetime.now().isoformat(),
'updated_by': system_user,
'hostname': hostname,
'environment': self.settings.get('environment', 'development')
}
with open(registry_path, 'w') as f:
json.dump(registry_data, f, indent=2)
self.logger.info(f"Checksum registry saved: {registry_path}")
except Exception as e:
self.logger.error(f"Failed to save checksum registry: {e}")
def _verify_config_integrity(self) -> bool:
"""Verify config checksums against registry; aborts in production on mismatch."""
environment = self.settings.get('environment', 'development')
is_production = (environment == 'production')
config_files = {
'settings.json': Path(self.config_path),
'sensors.json': Path("config/sensors.json")
}
current_checksums = {}
for name, filepath in config_files.items():
if filepath.exists():
current_checksums[name] = self._calculate_checksum(filepath)
else:
current_checksums[name] = None
registry = self._load_checksum_registry()
if not registry:
self.logger.warning("No checksum registry found - initializing")
self._save_checksum_registry(current_checksums)
self.logger.info("Checksum registry initialized")
return True
registry_checksums = registry.get('checksums', {})
mismatches = []
for name, current_checksum in current_checksums.items():
registry_checksum = registry_checksums.get(name)
if current_checksum != registry_checksum:
mismatches.append({
'file': name,
'expected': registry_checksum,
'actual': current_checksum
})
if mismatches:
self.logger.warning("Configuration file integrity check FAILED:")
for mismatch in mismatches:
self.logger.warning(
f" {mismatch['file']}: "
f"Expected {mismatch['expected']}, "
f"Got {mismatch['actual']}"
)
if is_production:
self.logger.critical("Configuration integrity check failed in production — aborting")
# Send alert (email_alerts may not be initialized yet since
# integrity check runs before component initialization)
try:
alerts = self.email_alerts if hasattr(self, 'email_alerts') else EmailAlerts(self.config_path)
alerts.send_system_error_alert(
error_type="CONFIG_INTEGRITY_FAILED",
error_message="Configuration files modified without authorization",
context={
'environment': environment,
'mismatches': mismatches,
'registry_updated': registry.get('last_updated'),
'action': 'System aborted - manual review required',
'fix': 'If changes are authorized, update registry via Change Control'
}
)
except Exception as email_err:
self.logger.error(f"Could not send integrity alert email: {email_err}")
raise SystemError(
"Configuration files have been modified without authorization. "
"If changes are authorized, update the checksum registry."
)
else:
self.logger.warning("Development mode - auto-updating checksum registry")
self._save_checksum_registry(current_checksums)
self.logger.info("Checksum registry updated with new values")
return True
else:
self.logger.info("Configuration integrity verified")
try:
access_ctrl = AccessControl(self.config_path)
for name in current_checksums.keys():
access_ctrl.log_config_access(name, 'INTEGRITY_CHECK', current_checksums[name])
except Exception as audit_err:
self.logger.warning(f"Could not log integrity check: {audit_err}")
return True
def _validate_sensor_config(self, sensor_id: str, config: dict, environment: str) -> None:
"""Validate sensor config dict; raises ValueError on any invalid field.
Modifies config in place to coerce temp_range and mock_base_temp to float.
"""
required_fields = ['unit_name', 'location', 'equipment_id', 'temp_range', 'unit_type']
for field in required_fields:
if field not in config:
raise ValueError(f"Sensor {sensor_id}: Missing required field '{field}'")
if not isinstance(config['unit_name'], str):
raise ValueError(
f"Sensor {sensor_id}: 'unit_name' must be a string, got {type(config['unit_name']).__name__}"
)
if not isinstance(config['location'], str):
raise ValueError(
f"Sensor {sensor_id}: 'location' must be a string, got {type(config['location']).__name__}"
)
if not isinstance(config['equipment_id'], str):
raise ValueError(
f"Sensor {sensor_id}: 'equipment_id' must be a string, got {type(config['equipment_id']).__name__}"
)
if not isinstance(config['unit_type'], str):
raise ValueError(
f"Sensor {sensor_id}: 'unit_type' must be a string, got {type(config['unit_type']).__name__}"
)
if not isinstance(config['temp_range'], list):
raise ValueError(
f"Sensor {sensor_id}: 'temp_range' must be a list, got {type(config['temp_range']).__name__}"
)
if len(config['temp_range']) != 2:
raise ValueError(
f"Sensor {sensor_id}: 'temp_range' must have exactly 2 values, got {len(config['temp_range'])}"
)
try:
min_temp = float(config['temp_range'][0])
max_temp = float(config['temp_range'][1])
config['temp_range'] = [min_temp, max_temp] # coerce to float in place
except (ValueError, TypeError) as e:
raise ValueError(
f"Sensor {sensor_id}: 'temp_range' values must be numeric. "
f"Got {config['temp_range']}: {e}"
)
if min_temp >= max_temp:
raise ValueError(
f"Sensor {sensor_id}: temp_range minimum ({min_temp}°C) must be LESS THAN "
f"maximum ({max_temp}°C). Your range appears to be reversed!"
)
# Practical bounds: absolute zero to boiling point covers all refrigeration equipment
if min_temp < -273.15 or min_temp > 100:
raise ValueError(
f"Sensor {sensor_id}: temp_range minimum ({min_temp}°C) is unrealistic. "
f"Must be between -273.15°C and 100°C"
)
if max_temp < -273.15 or max_temp > 100:
raise ValueError(
f"Sensor {sensor_id}: temp_range maximum ({max_temp}°C) is unrealistic. "
f"Must be between -273.15°C and 100°C"
)
valid_unit_types = ["Refrigerator", "Freezer", "Ultra Low Freezer", "Cold Room"]
if config['unit_type'] not in valid_unit_types:
raise ValueError(
f"Sensor {sensor_id}: 'unit_type' must be one of {valid_unit_types}, "
f"got '{config['unit_type']}'"
)
if environment == 'development':
if 'mock_base_temp' not in config:
raise ValueError(
f"Sensor {sensor_id}: 'mock_base_temp' is required in development mode"
)
try:
mock_temp = float(config['mock_base_temp'])
config['mock_base_temp'] = mock_temp # coerce to float in place
except (ValueError, TypeError) as e:
raise ValueError(
f"Sensor {sensor_id}: 'mock_base_temp' must be numeric, "
f"got {config['mock_base_temp']}: {e}"
)
self.logger.debug(f"Sensor {sensor_id} configuration validated successfully")
def _load_settings(self) -> dict:
"""Load and return settings.json."""
try:
with open(self.config_path, 'r') as f:
settings = json.load(f)
self.logger.info(f"Settings loaded from: {self.config_path}")
try:
access_ctrl = AccessControl(self.config_path)
checksum = self._calculate_checksum(Path(self.config_path))
access_ctrl.log_config_access(self.config_path, 'READ', checksum)
except Exception as audit_err:
self.logger.warning(f"Could not log config access: {audit_err}")
return settings
except Exception as e:
self.logger.error(f"Failed to load settings: {e}")
raise
def _load_sensor_config(self) -> dict:
"""Load and validate sensors.json; aborts if any sensor config is invalid."""
try:
config_file = Path("config/sensors.json")
with open(config_file, 'r') as f:
sensors = json.load(f)
try:
access_ctrl = AccessControl(self.config_path)
checksum = self._calculate_checksum(config_file)
access_ctrl.log_config_access(str(config_file), 'READ', checksum)
except Exception as audit_err:
self.logger.warning(f"Could not log config access: {audit_err}")
environment = self.settings.get('environment', 'development')
self.logger.info(f"Validating configuration for {len(sensors)} sensors...")
for sensor_id, config in sensors.items():
self._validate_sensor_config(sensor_id, config, environment)
self.logger.info(f"All {len(sensors)} sensor configurations validated successfully")
return sensors
except ValueError as e:
self.logger.error(f"CONFIGURATION VALIDATION FAILED: {e}")
self.logger.error("Fix sensors.json and restart the system")
raise
except Exception as e:
self.logger.error(f"Failed to load sensor config: {e}")
raise
@retry_on_permission_error(max_attempts=3, delay=5)
def _log_to_excel_with_retry(self, sensor_id: str, temperature: float,
sensor_config: dict, sensor_data: dict) -> dict:
return self.excel_logger.log_temperature(
sensor_id=sensor_id,
temperature=temperature,
sensor_config=sensor_config,
sensor_data=sensor_data
)
def check_sensor(self, sensor_id: str, sensor_config: dict) -> Tuple[bool, dict]:
"""Read one sensor, log to Excel, send alert if out of range."""
self.logger.info(f"Checking sensor: {sensor_id} ({sensor_config['unit_name']})")
try:
sensor_data = self.sensor.get_sensor_data(sensor_id)
if sensor_data is None:
# Sensor offline or not responding
self.logger.error(f"Sensor offline: {sensor_id}")
self.run_summary['sensors_offline'] += 1
self.run_summary['failed_readings'] += 1
try:
self.email_alerts.send_sensor_offline_alert(
sensor_id=sensor_id,
equipment_id=sensor_config['equipment_id'],
location=sensor_config['location'],
unit_name=sensor_config['unit_name']
)
except Exception as email_error:
self.logger.error(f"Failed to send offline alert: {email_error}")
self.run_summary['email_errors'] += 1
return False, {
'sensor_id': sensor_id,
'status': 'offline',
'error': 'No data available'
}
temperature = sensor_data['temperature']
battery = sensor_data.get('battery_level', 'N/A')
online = sensor_data.get('online', True)
min_temp, max_temp = sensor_config['temp_range']
in_range = min_temp <= temperature <= max_temp
self.logger.info(
f" Temperature: {temperature:.1f}°C "
f"(range: {min_temp}-{max_temp}°C) "
f"[{'IN RANGE' if in_range else 'OUT OF RANGE'}]"
)
self.logger.info(f" Battery: {battery}%, Online: {online}")
if not in_range:
self.run_summary['out_of_range'] += 1
try:
log_result = self._log_to_excel_with_retry(
sensor_id=sensor_id,
temperature=temperature,
sensor_config=sensor_config,
sensor_data=sensor_data
)
self.logger.info(f" Logged to Excel: {log_result['message']}")
self.run_summary['successful_readings'] += 1
# Temperature alert email is sent inside excel_logger.log_temperature
return True, {
'sensor_id': sensor_id,
'status': 'success',
'temperature': temperature,
'in_range': in_range,
'battery': battery,
'log_result': log_result
}
except Exception as excel_error:
self.logger.error(f" Excel logging failed: {excel_error}", exc_info=True)
self.run_summary['excel_errors'] += 1
self.run_summary['failed_readings'] += 1
# Send system error alert
try:
self.email_alerts.send_system_error_alert(
error_type="EXCEL_WRITE_FAILED",
error_message=f"Failed to log temperature for {sensor_id}",
context={
'sensor_id': sensor_id,
'temperature': temperature,
'error': str(excel_error)
}
)
except Exception as email_error:
self.logger.error(f"Failed to send error alert: {email_error}")
self.run_summary['email_errors'] += 1
return False, {
'sensor_id': sensor_id,
'status': 'excel_error',
'temperature': temperature,
'error': str(excel_error)
}
except Exception as e:
self.logger.error(f"Unexpected error checking {sensor_id}: {e}", exc_info=True)
self.run_summary['failed_readings'] += 1
return False, {
'sensor_id': sensor_id,
'status': 'error',
'error': str(e)
}
def run(self) -> dict:
"""Check all sensors and return a run summary dict."""
self.logger.info("\nStarting sensor checks...")
self.logger.info("-" * 70)
# Sorted order is required for deterministic audit records.
sensor_ids = sorted(self.sensors_config.keys())
self.run_summary['total_sensors'] = len(sensor_ids)
self.logger.info(f"Total sensors to check: {len(sensor_ids)}")
results = []
for idx, sensor_id in enumerate(sensor_ids, 1):
self.logger.info(f"\n[{idx}/{len(sensor_ids)}] Processing {sensor_id}...")
sensor_config = self.sensors_config[sensor_id]
success, result = self.check_sensor(sensor_id, sensor_config)
results.append(result)
end_time = datetime.now()
result = {
'start_time': self.start_time.isoformat(),
'end_time': end_time.isoformat(),
'duration_seconds': (end_time - self.start_time).total_seconds(),
'script_version': __version__,
'summary': self.run_summary,
'results': results
}
self._generate_summary(result)
self._save_summary_to_json(result)
return result
def _generate_summary(self, result: dict):
"""Log execution summary to the operational log."""
self.logger.info("\n" + "=" * 70)
self.logger.info("EXECUTION SUMMARY")
self.logger.info("=" * 70)
self.logger.info(f"Start Time: {self.start_time.strftime('%Y-%m-%d %H:%M:%S')}")
self.logger.info(f"End Time: {result['end_time'][:19].replace('T', ' ')}")
self.logger.info(f"Duration: {result['duration_seconds']:.1f} seconds")
self.logger.info(f"Script Version: {result['script_version']}")
self.logger.info("-" * 70)
self.logger.info(f"Total Sensors: {self.run_summary['total_sensors']}")
self.logger.info(f"Successful Readings: {self.run_summary['successful_readings']}")
self.logger.info(f"Failed Readings: {self.run_summary['failed_readings']}")
self.logger.info(f"Out of Range: {self.run_summary['out_of_range']}")
self.logger.info(f"Sensors Offline: {self.run_summary['sensors_offline']}")
self.logger.info(f"Excel Errors: {self.run_summary['excel_errors']}")
self.logger.info(f"Email Errors: {self.run_summary['email_errors']}")
self.logger.info(f"Time Sync OK: {self.run_summary['time_sync_ok']}")
self.logger.info("=" * 70)
if self.run_summary['failed_readings'] == 0:
self.logger.info("STATUS: ALL CHECKS COMPLETED SUCCESSFULLY")
elif self.run_summary['successful_readings'] > 0:
self.logger.warning("STATUS: PARTIAL SUCCESS - Some sensors failed")
else:
self.logger.error("STATUS: COMPLETE FAILURE - All sensors failed")
self.logger.info("=" * 70)
def _save_summary_to_json(self, result: dict):
"""Save run summary to JSON for trend analysis and inspection queries."""
try:
summary_dir = Path("logs/summaries")
summary_dir.mkdir(parents=True, exist_ok=True)
timestamp = self.start_time.strftime("%Y%m%d_%H%M%S")
summary_file = summary_dir / f"summary_{timestamp}.json"
def convert_paths(obj):
"""Recursively convert Path objects to strings for JSON serialization."""
if isinstance(obj, Path):
return str(obj)
elif isinstance(obj, dict):
return {k: convert_paths(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [convert_paths(item) for item in obj]
else:
return obj
json_safe_result = convert_paths(result)
with open(summary_file, 'w') as f:
json.dump(json_safe_result, f, indent=2)
self.logger.info(f"Run summary saved to: {summary_file}")
except Exception as e:
self.logger.error(f"Failed to save JSON summary: {e}")
def main():
"""Entry point called by cron at 08:00 AM."""
access_control = None
auth_result = None
start_time = datetime.now()
try:
logging.info("=" * 70)
logging.info("ACCESS CONTROL CHECK")
logging.info("=" * 70)
auth_result = check_execution_authorization()
access_control = AccessControl()
logging.info(f"User: {auth_result['user']}")
logging.info(f"Groups: {', '.join(auth_result['groups']) if auth_result['groups'] else 'none detected'}")
logging.info(f"Authorization: {auth_result['reason']}")
logging.info(f"Environment: {auth_result['environment']}")
logging.info("=" * 70)
monitor = TemperatureMonitor()
result = monitor.run()
duration = (datetime.now() - start_time).total_seconds()
summary = result['summary']
total = summary['total_sensors']
success = summary['successful_readings']
if summary['failed_readings'] == 0:
status = 'SUCCESS'
exit_code = 0
elif summary['successful_readings'] > 0:
status = 'PARTIAL_FAILURE'
exit_code = 1
else:
status = 'FAILURE'
exit_code = 2
if access_control and auth_result:
access_control.log_execution_end(
user=auth_result['user'],
duration_seconds=duration,
status=status,
sensors_checked=f"{success}/{total}"
)
sys.exit(exit_code)
except SystemExit as e:
raise
except Exception as e:
logging.error("CRITICAL SYSTEM FAILURE", exc_info=True)
if access_control and auth_result:
duration = (datetime.now() - start_time).total_seconds()
access_control.log_execution_end(
user=auth_result['user'],
duration_seconds=duration,
status='SYSTEM_ERROR',
sensors_checked='0/0'
)
try:
alerts = EmailAlerts()
alerts.send_system_error_alert(
error_type="SYSTEM_INITIALIZATION_FAILED",
error_message=str(e),
context={'traceback': traceback.format_exc()}
)
except:
pass
sys.exit(2)
if __name__ == "__main__":
main()