Repository navigation
Expand file tree
/
Copy pathclass_USSensorManager.erl
More file actions
4630 lines (3201 loc) · 158 KB
/
Copy pathclass_USSensorManager.erl
File metadata and controls
4630 lines (3201 loc) · 158 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
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
% Copyright (C) 2021-2026 Olivier Boudeville
%
% This file belongs to the US-Main project, a part of the Universal Server
% framework.
%
% This program is free software: you can redistribute it and/or modify it under
% the terms of the GNU Affero General Public License as published by the Free
% Software Foundation, either version 3 of the License, or (at your option) any
% later version.
%
% This program is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
% FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
% details.
%
% You should have received a copy of the GNU Affero General Public License along
% with this program. If not, see <http://www.gnu.org/licenses/>.
%
% Author: Olivier Boudeville [olivier (dot) boudeville (at) esperide (dot) com]
% Creation date: Saturday, June 5, 2021.
-module(class_USSensorManager).
-moduledoc """
US server in charge of the **monitoring of the sensors available on a local
host** (notably the temperatures, chassis intrusion status and the operation of
fans), and of reporting any abnormal situation.
""".
-define( class_description, "US server in charge of the monitoring of the
sensors available on a local host (notably the temperatures and the operation of
fans), and of reporting any abnormal situation" ).
% Determines what are the direct mother classes of this class (if any):
-define( superclasses, [ class_USServer ] ).
% For settings regarding name registration:
-include("us_main_defines.hrl").
% Design notes:
%
% We rely here directly on the US infrastructure (as opposed to US-Web, which
% may run autonomously): the configuration file, scheduler, etc. of US-Common
% are used here.
% Two phases shall be considered:
% - an initial pass through all measurement points of all sensors, in order to
% initialise properly them, based on a per-category exhaustive filtering
% - regular update passes, just picking the enabled points, updating their
% status and possibly reporting any detected issue
% Implementation notes:
% Regarding sensors, refer to the Technical Manual of the Universal Server
% (http://us-main.esperide.org).
%
% Many sensors look like poorly-designed random generators.
%
% Initially we registered all sensors and points, even muted ones. It was overly
% complex and mostly useless. Now we drop muted ones, so unknown reported ones
% are just ignored (anyway the set of sensors never changes).
% This sensor manager is designed to be able to integrate to an OTP supervision
% tree thanks to a supervisor bridge, whose behaviour is directly defined in
% this module. See https://wooper.esperide.org/#otp-guidelines for further
% information.
%
-behaviour(supervisor_bridge).
% User API of the bridge:
-export([ start_link/0 ]).
% Callbacks of the supervisor_bridge behaviour:
-export([ init/1, terminate/2 ]).
-define( bridge_name, ?MODULE ).
% Entries in the US-configuration files for sensor monitoring:
-define( us_main_sensor_key, sensor_monitoring ).
% For measurement points known to report bogus values:
-define( us_main_muted_sensor_measurements, muted_measurements ).
% Designates all (measurement) points of a given sensor:
-define( us_main_all_points, all_points ).
% Note that map_hashtable instances are explicitly mentioned instead of tables,
% as this is the actual type returned by the json_utils module (as opposed to
% the 'table' WOOPER-native type).
% Section about JSON data being read.
%
% Types defined from here correspond to elements read from the JSON output of
% the 'sensors' tool.
% Canonical sensor order enforced here: temperature, fan, then chassis
% intrusion.
-doc "PID of a sensor manager.".
-type sensor_manager_pid() :: class_USServer:server_pid().
-doc "To designate values read from JSON keys.".
-type json_read_value() :: float().
-doc """
Table associating, to a measurement point (e.g. `<<"Core 0">>`), a table of the
corresponding attributes (that is a `point_attribute_map/0`).
""".
-type json_point_map() :: map_hashtable( measurement_point_name(),
point_attribute_map() ).
-doc "An entry of a json_point_map/0.".
-type json_point_entry() :: { measurement_point_name(), point_attribute_map() }.
-doc """
An entry corresponding to the top-level information read from JSON, in a
corresponding map.
""".
-type json_sensor_entry() :: { raw_sensor_id(), json_point_map() }.
-doc "Defined just for convenience.".
-type json_triple() :: { measurement_point_name(),
measurement_point_description(), point_attribute_map() }.
% Section about sensors.
-doc """
The reported type for a sensor, like "coretemp", "k10temp", "acpitz", "nvme",
"radeon", etc.; many exist as they correspond to different chips (e.g.
"nct6792") on motherboards.
""".
-type raw_sensor_type() :: ustring().
-doc "Atom-based version of a raw sensor type (e.g. `coretemp`).".
-type atom_sensor_type() :: atom().
-doc """
A higher-level (potentially less precise), clearer (US-assigned) category for a
sensor, deriving from a raw sensor type.
""".
-type sensor_category() ::
'cpu' % Also includes APU (e.g. Atom+Radeon)
| 'cpu_socket' % Often less reliable than 'cpu'.
| 'motherboard'
| 'chipset' % Like pch_skylake-virtual-*.
| 'ram'
| 'disk'
| 'battery'
| 'gpu'
| 'network' % Network interface, like the iwlwifi wireless adapter.
| 'bus' % Typically USB
| 'unknown'.
-doc "The reported hardware interface for a sensor.".
-type sensor_interface() ::
'isa' | 'acpi' | 'pci' | 'virtual' | 'unknown' | atom().
-doc """
For example "0a20", in `{nct6792, isa, "0a20"}`.
""".
-type user_sensor_number() :: ustring().
-doc """
Kept as a (binary) string (even if is an hexadecimal value), for clarity.
For example `<<"0a20">>`.
""".
-type sensor_number() :: bin_string().
-doc """
Full identifier of a sensor, directly as read from JSON; e.g.
`<<"coretemp-isa-0000">>`, `<<"nct6792-isa-0a20">>`, `<<"nvme-pci-0200">>`,
`<<"radeon-pci-0008">>`, etc.; structure is
`<<"RawSensorType-SensorInterface-SensorNumber">>`.
""".
-type raw_sensor_id() :: bin_string().
-doc """
Table registering all information regarding all local sensors; useful when
parsing a global (JSON) sensor report.
""".
-type sensor_table() :: table( raw_sensor_id(), sensor_info() ).
-doc """
Full internal identifier of a sensor, directly deriving from a raw one.
For example `{coretemp, isa, <<"0a20">>}`.
""".
-type sensor_id() ::
{ atom_sensor_type(), sensor_interface(), sensor_number() }.
% Section about measurement points.
-doc """
The (raw) name of a measurement point (e.g. '<<"temp1">>' or '<<"Core 0">>') of
a sensor (which may provide multiple points), as read from JSON.
""".
-type measurement_point_name() :: bin_string().
-doc """
A description of a measurement point that is more user-friendly than its raw
name.
""".
-type measurement_point_description() :: bin_string().
-doc """
The enable status of a measurement point. Those that report bogus values shall
be disabled.
""".
-type point_status() :: 'enabled' | 'disabled'.
-doc "The name of an attribute at a measurement point, as read from JSON.".
-type point_attribute() :: bin_string().
-doc """
The value associated to a read JSON key, e.g. a key that is an attribute at a
measurement point.
""".
-type point_value() :: json_read_value().
-doc """
Table associating, to an attribute (e.g. `<<"temp1_crit">>`) of a measurement
point, a value (e.g. 105.0).
""".
-type point_attribute_map() ::
map_hashtable( point_attribute(), point_value() ).
%-doc "An entry of a point_attribute_map/0.".
%-type point_attribute_entry() :: { point_attribute(), point_value() }.
-doc """
User specification of a sensor whose measurements may be muted.
For example `{nct6792, isa, "0a20"}`.
""".
-type user_muted_sensor_spec() ::
{ atom_sensor_type(), sensor_interface(), user_sensor_number() }.
-doc """
A measurement point specified in the configuration (e.g. "AUXTIN1").
""".
-type user_specified_point() :: ustring().
-doc """
User specification of measurement points to be muted for a given sensor (they
shall not be taken into account, typically because they are known to report
bogus values).
At least currently, this mostly applies to temperature sensors.
""".
-type user_muted_points() :: [ user_specified_point() ]
| 'all_points'. % of a given sensor
-doc """
A list expected to contain muted sensor measurement points, typically as read
from the sensor monitoring section of the US-Main configuration.
Expected to be specified in the form [user_muted_sensor_measurements()]:
```
UserMutedMeasurements = [
{ { nct6792, isa, "0a20" }, [ "AUXTIN1" ] },
{ { acpitz, acpi, "0" }, all_points } ].
```
""".
-type user_muted_sensor_points() :: list().
% Commented-out, as strangely considered as redefining the previous -doc
% attribute.
%
% -doc """
% User specification of sensor measurements to be muted.
% At least currently, this mostly applies to temperature sensors.
% Corresponds to the legit settings expected as
% class_USMainCentralServer:user_muted_sensor_points(); may be for example:
% ```
% [{nct6792, isa, "0a20"}, ["AUXTIN1"]},
% {acpitz, acpi, "0"}, all_points}].
% ```
% """.
-type user_muted_sensor_measurements() ::
% Previously was [{user_muted_sensor_spec(), user_muted_points()}], yet the
% user may have specified a sensor spec more than once, so:
table( user_muted_sensor_spec(), user_muted_points() ).
-doc """
Specification of measurement points (as binaries) to be muted for a given sensor
(they shall not be taken into account, typically because they are known to
report bogus values).
For example `[<<"AUXTIN1">>]` or all_points.
At least currently, this mostly applies to temperature sensors.
""".
-type muted_points() :: [ measurement_point_name() ]
| 'all_points'. % of a given sensor
-doc """
Specification of sensor measurements to be muted.
At least currently, this mostly applies to temperature sensors.
Corresponds to the legit settings expected as `user_muted_sensor_points/0`; may
be for example:
```
[{nct6792, isa, <<"0a20">>}, [<<"AUXTIN1">>]},
{acpitz, acpi, <<"0">>}, all_points}]
```.
""".
-type muted_sensor_measurements() :: [ { sensor_id(), muted_points() } ].
% Section about temperature sensors.
% Read from a sensor on your CPU: Core temperature.
%
% Read from sensors on the motherboard:
% - CPUTIN (CPU temperature index): CPU temperature
% - AUXTIN (auxiliary temperature index): power supply temperature sensor
% - SYSTIN (system temperature index): motherboard temperature
% Settings: HYST (hysteresis; this is the value at which you want an alarm to
% turn off. For example, if your alarm temperature is 80°C, set your HYST value
% to stop the alarm when the temperature falls to 75°C.)
-doc """
The description of a temperature (e.g. "alarm").
""".
-type temperature_description() :: ustring().
-doc """
The description of a temperature range (e.g. "bogus").
""".
-type range_description() :: ustring().
% By decreasing temperature:
-doc """
The temperature-related alert state of a measurement point. Allows to report
issues once, rather than repeatedly.
""".
-type temp_alert_state() :: 'critical_high'
| 'alarm_high'
| 'nominal'
| 'alarm_low'
| 'critical_low'.
% Stores information about the temperature measured by a given measurement point
% of a sensor.
%
-record( temperature_data, {
% The name of the attribute to read from the JSON table in order to
% determine the current temperature of the associated point:
%
% (e.g. <<"temp9_input">>)
%
input_attribute :: point_attribute(),
% The most user-friendly description of the associated measurement point:
description :: bin_string(),
% The enable status of the associated measurement point:
status = 'enabled' :: point_status(),
% The temperature-related alert state of this sensor:
alert_state = 'nominal' :: temp_alert_state(),
% The timestamp of the beginning of the current alert state:
alert_timestamp :: timestamp(),
% The current temperature reading:
current :: celsius(),
% The lowest temperature measured since start (hence an actual measurement,
% not a setting):
%
min_reached :: celsius(),
% The highest temperature measured since start (hence an actual measurement,
% not a setting):
%
max_reached :: celsius(),
% To compute the average temperature:
% The sum of all (vetted) temperatures measured since start:
avg_sum = 0.0 :: celsius(),
% The number of all (vetted) temperature measurements since start:
avg_count = 0 :: count(),
% We ensure that all thresholds are set, even if the sensor does not report
% corresponding values. We consider that thresholds shall be strictly
% exceeded in order to change severity.
%
% Of course following inequalities shall hold:
% crit_low < alarm_low < alarm_high < crit_high
%
% and under nominal conditions, the current measured temperature shall be in
% [alarm_low; alarm_high].
% The minimum allowed temperature, below which we consider that an alarm
% shall be raised (it is typically set higher than any crit_low):
%
% (not the most useful of indicators; generally is not reported, yet we set
% it to a sensible value in all cases)
%
alarm_low = undefined :: celsius(),
% The maximum allowed temperature, above which we consider that an alarm
% shall be raised (it is typically set lower than any crit_high):
%
alarm_high = undefined :: celsius(),
% The built-in critical low temperature (i.e. the temperature below which
% serious problems are bound to happen), as reported by the sensor (if any
% is defined):
%
% (not the most useful of indicators; generally is not reported, yet we set
% it to a sensible value in all cases)
%
crit_low = undefined :: celsius(),
% The built-in critical high temperature (i.e. the temperature above which
% serious problems are bound to happen), as reported by the sensor (if any
% is defined, otherwise it is estimated by ourselves):
%
crit_high = undefined :: celsius() } ).
-doc """
Stores information about the temperature measured by a given measurement point
of a sensor.
""".
-type temperature_data() :: #temperature_data{}.
% Section regarding fan sensors.
-doc "The detected type of a given fan.".
-type fan_type() :: 'fixed_speed' % Fans are rotating at a fixed speed,
% regardless of temperature
| 'pwm' % Pulse-Width modulation (controlled fan speed)
| 'unknown'.
-doc """
The (floating-point) number of pulses generated per revolution of the fan
(typically 2).
""".
-type fan_pulse() :: option( float() ).
-doc "The state condition of a given fan.".
-type fan_state() :: 'nominal'
| 'inactive' % If a fan is reported as non-operational
% (possibly not even existing)
| 'dysfunctional' % If a fan is reported as out of order
| 'insufficient_speed' % If a fan spins too slowly
| 'excessive_speed' % If a fan spins too fast
| 'unknown'.
-record( fan_data, {
% The name of the attribute to read from the JSON table in order to
% determine the current fan speed of the associated point:
%
% (e.g. <<"fan2_input">>)
%
input_attribute :: point_attribute(),
% The most user-friendly description of the associated measurement point:
description :: bin_string(),
% The enable status of the associated measurement point:
status = 'enabled' :: point_status(),
% The determined fan type:
type = 'unknown' :: fan_type(),
% Tells how many of pulses are generated per revolution of the fan:
pulses = 'undefined' :: option( fan_pulse() ),
% Tells whether this fan was ever detected as moving:
% (useless; see min_reached field)
%
%ever_spinned = 'false' :: boolean(),
% The determined state of this fan:
state = 'unknown' :: fan_state(),
% The timestamp of the last time this fan was detected as spinning:
last_spin_timestamp = undefined :: option( timestamp() ),
% The current fan speed (if any):
current :: option( rpm() ),
% The lowest fan speed (if any) measured since start:
min_reached :: option( rpm() ),
% The highest fan speed (if any) measured since start:
max_reached :: option( rpm() ),
% To compute the average fan speed:
% The sum of all (vetted) fan speeds measured since start:
avg_sum = 0.0 :: option( rpm() ),
% The number of all (vetted) fan measurements since start:
avg_count = 0 :: option( count() ),
% Tells, if defined, what is the speed threshold below which an alarm shall
% be raised regarding that fan (e.g. a fixed-speed fan that would halt for
% any reason).
%
alarm_low = undefined :: option( rpm() ),
% Tells, if defined, what is the speed threshold above which an alarm shall
% be raised regarding that fan (e.g. a PWM fan having to speed because of
% excessive heat).
%
alarm_high = undefined :: option( rpm() ),
% Tells whether the motherboard is to beep in case of (presumably) alarm:
beep_on_alarm = false :: boolean() } ).
-doc """
Stores information about the fan measured by a given measurement point of a
sensor.
""".
-type fan_data() :: #fan_data{}.
% Section regarding intrusion sensors.
-doc """
A status regarding the detection of a chassis intrusion: false if nothing
detected, true if an intrusion apparently happened.
""".
-type intrusion_detected_status() :: boolean().
-record( intrusion_data, {
% The name of the attribute to read from the JSON table in order to
% determine the current intrusion status of the associated point:
%
% (e.g. <<"intrusion0">>)
%
input_attribute :: point_attribute(),
% The most user-friendly description of the associated measurement point:
description :: bin_string(),
% The status of the associated measurement point:
status = 'enabled' :: point_status(),
% The current intrusion reading:
intrusion_reported :: intrusion_detected_status(),
% The timestamp of the beginning of the current intrusion status:
intrusion_timestamp :: timestamp(),
% Tells whether the motherboard is to beep in case of intrusion:
beep_on_intrusion = false :: boolean() } ).
-doc """
Stores information about any chassis intrusion detected by a given measurement
point of a sensor.
""".
-type intrusion_data() :: #intrusion_data{}.
% For a point P, intrusionP_alarm tells whether a chassis intrusion was detected
% (if equal to 1.0) or not (if equal to 0.0). Bogus values may be reported (we
% suppose that when this manager launches no intrusion already occurred), so
% only transitions from "normal" (an intrusion_detected_status of false) to
% "alarm" (an intrusion_detected_status of true) are scrutinised here.
-export_type([ user_muted_sensor_points/0,
user_muted_sensor_measurements/0,
raw_sensor_type/0, atom_sensor_type/0,
sensor_category/0, sensor_interface/0, sensor_number/0,
raw_sensor_id/0, sensor_id/0 ]).
-doc "The data that is associated to a measurement point.".
-type point_data() :: temperature_data() | intrusion_data().
-doc """
A table associating, for a given sensor, to each of its measurement points, its
data (e.g. regarding temperature, intrusion, etc.).
""".
-type points_data_table() :: table( measurement_point_name(), point_data() ).
% All information regarding a known sensor.
-record( sensor_info, {
% Duplicated here for convenience (often is an associated key):
raw_id :: raw_sensor_id(),
% Identifier of this sensor.
id :: sensor_id(),
% Higher-level category of this sensor:
category :: sensor_category(),
% All data (of all sorts; and if any, as the category of this sensor must be
% known in order to be interpreted) monitored by that sensor:
%
data :: option( points_data_table() ) } ).
-doc "All information regarding a known sensor.".
-type sensor_info() :: #sensor_info{}.
% Section for temperature defines.
% An initial temperature value below this threshold denotes a bogus measure,
% resulting in the corresponding measurement point to be disabled from start.
%
% We consider that, when this sensor manager starts, the local computer is
% running under norminal condition, and that thus any worryingly low or high
% reported temperature denotes a bogus sensor.
%
% So for example a sensor reporting 7°C at manager start-up is deemed bogus
% rather than being a real problem; afterwards this temperature means a problem
% (and not a bogus sensor).
%
-define( low_bogus_temperature_initial_threshold, 8.0 ).
% A temperature value below this threshold denotes a bogus measure, resulting in
% the corresponding measurement point to be disabled (at any time after
% initialisation):
%
-define( low_bogus_temperature_threshold, 5.0 ).
% A temperature value above this threshold denotes a bogus measure (e.g. 127°C),
% resulting in the corresponding measurement point to be disabled:
%
% We consider that, when this sensor manager starts, the local computer is
% running under norminal condition, and that thus any worryingly low or high
% reported temperature denotes a bogus sensor.
%
% So for example a sensor reporting 82°C at manager start-up is deemed bogus
% rather than being a real problem; afterwards this temperature means a problem
% (and not a bogus sensor).
%
-define( high_bogus_temperature_initial_threshold, 75.0 ).
% A temperature value above this threshold denotes a bogus measure (e.g. 127°C),
% resulting in the corresponding measurement point to be disabled (at any time
% after initialisation):
%
-define( high_bogus_temperature_threshold, 125.0 ).
% Should none be returned by a sensor (as celsius()):
-define( default_critical_high_temperature, 95.0 ).
% Should none be returned by a sensor (as celsius()):
-define( default_critical_low_temperature, 2.0 ).
% The class-specific attributes:
%
% (no more us_config_server_pid, scheduler_pid, comm_gateway_pid, etc. as, for
% an increased robustness, servers shall be resolved on the fly)
%
-define( class_attributes, [
{ sensor_exec_pair, system_utils:execution_pair(),
"to run the sensor tool conveniently" },
{ sensor_monitoring, boolean(),
"tells whether sensor monitoring is enabled" },
{ parser_state, parser_state(), "state of the JSON parser in use" },
{ sensor_table, sensor_table(),
"table registering all information regarding detected local sensors" },
{ task_id, task_id(),
"the scheduling identifier of the sensor-polling task" } ] ).
% Used by the trace_categorize/1 macro to use the right emitter:
-define( trace_emitter_categorization, "US.US-Main.HostSensors" ).
% Exported helpers:
-export([ get_licit_config_keys/0, manage_configuration/2,
intrusion_status_to_string/1 ]).
% Note: include order matters.
% Allows to define WOOPER base variables and methods for that class:
-include_lib("wooper/include/wooper.hrl").
% Allows to use macros for trace sending:
-include_lib("traces/include/class_TraceEmitter.hrl").
% User periodicity, hence in seconds:
% Nominal one:
-define( default_sensor_poll_periodicity, 30 ).
% For testing:
%-define( default_sensor_poll_periodicity, 5 ).
% Type shorthands:
-type count() :: basic_utils:count().
-type ustring() :: text_utils:ustring().
-type bin_string() :: text_utils:bin_string().
-type indentation_level() :: indentation_level().
-type file_path() :: file_utils:file_path().
-type string_json() :: json_utils:string_json().
-type decoded_json() :: json_utils:decoded_json().
-type parser_state() :: json_utils:parser_state().
-type celsius() :: unit_utils:celsius().
-type rpm() :: unit_utils:rpm().
-type timestamp() :: time_utils:timestamp().
-type map_hashtable( K, V ) :: map_hashtable:map_hashtable( K, V ).
% In state definition:
%-type scheduler_pid() :: class_USScheduler:scheduler_pid().
%-type task_id() :: class_USScheduler:task_id().
-type us_main_config_table() ::
class_USMainCentralServer:us_main_config_table().
% Implementation of the supervisor_bridge behaviour, for the intermediate
% process allowing to interface this sensor manager with an OTP supervision
% tree.
-doc """
Starts and links a supervision bridge for the sensor management.
Note: typically spawned as a supervised child of the US-Main root supervisor
(see `us_main_sup:init/1`), hence generally triggered by the application
initialisation.
""".
-spec start_link() -> term().
start_link() ->
% Apparently not displayed in a release context, yet executed:
trace_bridge:debug( "Starting the US-Main supervisor bridge for "
"the sensor management." ),
supervisor_bridge:start_link( { local, ?bridge_name },
_Module=?MODULE, _InitArgs=[] ).
-doc """
Callback to initialise this supervisor bridge, typically in answer to
`start_link/0` being executed.
""".
-spec init( list() ) -> { 'ok', pid(), State :: term() }
| 'ignore' | { 'error', Error :: term() }.
init( _Args=[] ) ->
trace_bridge:info_fmt( "Initialising the US-Main supervisor bridge ~w for "
"the sensor management.", [ self() ] ),
% Not specifically synchronous:
SensorManagerPid = ?MODULE:new_link(),
{ ok, SensorManagerPid, _InitialBridgeState=SensorManagerPid }.
-doc "Callback to terminate this supervisor bridge.".
-spec terminate( Reason :: 'shutdown' | term(), State :: term() ) -> void().
terminate( Reason, _BridgeState=SensorManagerPid )
when is_pid( SensorManagerPid ) ->
trace_bridge:info_fmt( "Terminating the US-Main supervisor bridge for "
"the sensor management (reason: ~w, sensor manager: ~w).",
[ Reason, SensorManagerPid ] ),
% Synchronicity needed, otherwise a potential race condition exists, leading
% this process to be killed by its OTP supervisor instead of being normally
% stopped:
%
wooper:delete_synchronously_instance( SensorManagerPid ),
trace_bridge:debug_fmt( "US-Main sensor manager ~w terminated.",
[ SensorManagerPid ] ).
% Actual implementation of the sensor manager.
-doc "Constructs a sensor manager, for the local host.".
-spec construct( wooper:state() ) -> wooper:state().
construct( State ) ->
ServerTraceName = text_utils:format( "Sensor manager for ~ts",
[ net_utils:localhost() ] ),
% First the direct mother classes, then this class-specific actions:
SrvState = class_USServer:construct( State,
?trace_categorize(ServerTraceName),
?us_main_sensor_server_registration_name,
?us_main_sensor_server_registration_scope ),
InitSensorState = case init_sensors( SrvState ) of
{ _SensorEnabled=true, InitState } ->
PollPeriod = ?default_sensor_poll_periodicity,
?send_info_fmt( InitState, "Performing a first, direct, relevant "
"sensor update before scheduling it periodically "
"(every ~B seconds).", [ PollPeriod ] ),
UpdatedSensorState = update_sensor_data( InitState ),
init_polling( PollPeriod, UpdatedSensorState );
{ _SensorEnabled=false, InitState } ->
?send_notice( InitState,
"No sensor enabled, no polling scheduled." ),
setAttribute( InitState, task_id, undefined )
end,
?send_notice_fmt( InitSensorState, "Constructed: ~ts",
[ to_string( InitSensorState ) ] ),
InitSensorState.
-doc """
Constructs a minimal sensor manager in order to test whether the sensor JSON
output stored in the specified file can be propertly interpreted.
Such a file is typically obtained thanks to `$ sensors --no-adapter -j >
my_sensor_output.txt`.
Useful to support sensors from third-party computers (transmitting such a file
just suffice to update this module accordingly). Applies only for testing.
""".
-spec construct( wooper:state(), file_path() ) -> wooper:state().
construct( State, SensorOutputFilePath ) ->
ServerTraceName = text_utils:format(
"Sensor manager for data from file ~ts", [ SensorOutputFilePath ] ),
% First the direct mother classes, then this class-specific actions:
SrvState = class_USServer:construct( State,
?trace_categorize(ServerTraceName),
?us_main_sensor_server_registration_name,
?us_main_sensor_server_registration_scope ),