-
Notifications
You must be signed in to change notification settings - Fork 25
/
pve-mod-gui-sensors.sh
916 lines (850 loc) · 29.6 KB
/
pve-mod-gui-sensors.sh
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
#!/usr/bin/env bash
#
# This bash script installs a modification to the Proxmox Virtual Environment (PVE) web user interface (UI) to display sensors information.
#
################### Configuration #############
# Display configuration for HDD, NVME, CPU
# Set to 0 to disable line breaks
# Note: use these settings only if the displayed layout is broken
CPU_ITEMS_PER_ROW=0
NVME_ITEMS_PER_ROW=0
HDD_ITEMS_PER_ROW=0
# Known CPU sensor names. They can be full or partial but should ensure unambiguous identification.
# Should new ones be added, also update logic in configure() function.
KNOWN_CPU_SENSORS=("coretemp-isa-" "k10temp-pci-")
# This script's working directory
SCRIPT_CWD="$(dirname "$(readlink -f "$0")")"
# Files backup location
BACKUP_DIR="$SCRIPT_CWD/backup"
# File paths
PVE_MANAGER_LIB_JS_FILE="/usr/share/pve-manager/js/pvemanagerlib.js"
NODES_PM_FILE="/usr/share/perl5/PVE/API2/Nodes.pm"
# Debug location
DEBUG_SAVE_PATH="$SCRIPT_CWD"
DEBUG_SAVE_FILENAME="sensorsdata.json"
##################### DO NOT EDIT BELOW #######################
# Only to be used to debug on other systems. Save the "sensor -j" output into a json file.
# Information will be loaded for script configuration and presented in Proxmox.
DEBUG_REMOTE=false
DEBUG_JSON_FILE="/tmp/sensordata.json"
# Helper functions
function msg {
echo -e "\e[0m$1\e[0m"
}
#echo message in bold
function msgb {
echo -e "\e[1m$1\e[0m"
}
function info {
echo -e "\e[0;32m[info] $1\e[0m"
}
function warn {
echo -e "\e[0;93m[warning] $1\e[0m"
}
function err {
echo -e "\e[0;31m[error] $1\e[0m"
exit 1
}
function ask {
read -p $'\n\e[0;32m'"$1:"$'\e[0m'" " response
echo $response
}
# End of helper functions
# Function to display usage information
function usage {
msgb "\nUsage:\n$0 [install | uninstall | save-sensors-data]\n"
exit 1
}
# Define a function to install packages
function install_packages {
# Check if the 'sensors' command is available on the system
if (! command -v sensors &>/dev/null); then
# If the 'sensors' command is not available, prompt the user to install lm-sensors
local choiceInstallLmSensors=$(ask "lm-sensors is not installed. Would you like to install it? (y/n)")
case "$choiceInstallLmSensors" in
[yY])
# If the user chooses to install lm-sensors, update the package list and install the package
apt-get update
apt-get install lm-sensors
;;
[nN])
# If the user chooses not to install lm-sensors, exit the script with a zero status code
msg "Decided to not install lm-sensors. The mod cannot run without it. Exiting..."
exit 0
;;
*)
# If the user enters an invalid input, print an error message and exit the script with a non-zero status code
err "Invalid input. Exiting..."
;;
esac
fi
}
function configure {
SENSORS_DETECTED=false
local sensorsOutput
if [ $DEBUG_REMOTE = true ]; then
warn "Remote debugging is used. Sensor readings from dump file $DEBUG_JSON_FILE will be used."
sensorsOutput=$(cat $DEBUG_JSON_FILE)
else
sensorsOutput=$(sensors -j)
fi
if [ $? -ne 0 ]; then
err "Sensor output error.\n\nCommand output:\n${sensorsOutput}\n\nExiting...\n"
fi
# Check if CPU is part of known list for autoconfiguration
msg "\nDetecting support for CPU temperature sensors..."
for item in "${KNOWN_CPU_SENSORS[@]}"; do
if (echo "$sensorsOutput" | grep -q "$item"); then
CPU_ADDRESS_PREFIX=$item
fi
done
if [ -n "$CPU_ADDRESS_PREFIX" ]; then
msg "Detected sensors:\n$(echo "$sensorsOutput" | grep -o "\"${CPU_ADDRESS_PREFIX}[^\"]*\"" | sed 's/"//g')"
# Populate search criterias for known CPUs
if (echo "$sensorsOutput" | grep -q "coretemp-"); then
# Intel CPU
# Prompt user for which temperature to use
local choiceTempDisplayType=$(ask "Do you wish to display temperatures for all cores [C] or just an average temperature per CPU [a]? (C/a)")
case "$choiceTempDisplayType" in
# Set temperature search criteria
[cC] | "")
if (echo "$sensorsOutput" | grep -A 10 "coretemp-" | grep -q "Core "); then
CPU_ITEM_PREFIX="Core "
CPU_TEMP_CAPTION="Core"
info "Temperatures will be displayed for all cores."
fi
;;
[aA])
if (echo "$sensorsOutput" | grep -A 10 "coretemp-" | grep -q "Package id "); then
CPU_ITEM_PREFIX="Package id"
CPU_TEMP_CAPTION="Package"
info "An average temperature will be displayed per CPU."
fi
;;
*)
# If the user enters an invalid input, print an error message and exit the script with a non-zero status code
err "Invalid input. Exiting..."
;;
esac
elif (echo "$sensorsOutput" | grep -q "k10temp-"); then
# AMD CPU
# Find and set temperature search criteria
if (echo "$sensorsOutput" | grep -A 10 "$item" | grep -q "Tctl" && echo "$sensorsOutput" | grep -A 10 "$item" | grep -q "Tccd"); then
CPU_ADDRESS_PREFIX=$item
CPU_ITEM_PREFIX="Tccd"
CPU_TEMP_CAPTION="Temp"
elif (echo "$sensorsOutput" | grep -A 10 "$item" | grep -q -e "\"Tctl\""); then
CPU_ADDRESS_PREFIX=$item
CPU_ITEM_PREFIX="Tctl"
CPU_TEMP_CAPTION="Temp"
elif (echo "$sensorsOutput" | grep -A 10 "$item" | grep -q "\"temp1\""); then
CPU_ADDRESS_PREFIX=$item
CPU_ITEM_PREFIX="temp"
CPU_TEMP_CAPTION="Temp"
fi
fi
else
# If cpu is not known, ask the user for input
warn "Could not automatically detect the CPU temperature sensor. Please configure it manually."
# Ask user for CPU information
# Inform the user and prompt them to press any key to continue
read -rsp $'Sensor output will be presented. Press any key to continue...\n' -n1 key
# Print the output to the user
msg "Sensor output:\n${sensorsOutput}"
# Prompt the user for adapter name and item name
read -p "Enter the CPU sensor address prefix (e.g.: coretemp-isa- or k10temp-pci-): " CPU_ADDRESS_PREFIX
read -p "Enter the CPU sensor input prefix (e.g.: Core or Tc): " CPU_ITEM_PREFIX
read -p "Enter the CPU temperature caption (e.g.: Core or Temp): " CPU_TEMP_CAPTION
fi
if [[ -z "$CPU_ADDRESS_PREFIX" || -z "$CPU_ITEM_PREFIX" ]]; then
warn "The CPU configuration is not complete. Temperatures will not be available."
else
SENSORS_DETECTED=true
fi
# Check if HDD/SSD data is installed
msg "\nDetecting support for HDD/SDD temperature sensors..."
if (lsmod | grep -wq "drivetemp"); then
# Check if SDD/HDD data is available
if (echo "$sensorsOutput" | grep -q "drivetemp-scsi-"); then
msg "Detected sensors:\n$(echo "$sensorsOutput" | grep -o '"drivetemp-scsi[^"]*"' | sed 's/"//g')"
ENABLE_HDD_TEMP=true
SENSORS_DETECTED=true
else
warn "Kernel module \"drivetemp\" is not installed. HDD/SDD temperatures will not be available."
ENABLE_HDD_TEMP=false
fi
else
warn "No HDD/SSD temperature sensors found."
ENABLE_HDD_TEMP=false
fi
# Check if NVMe data is available
msg "\nDetecting support for NVMe temperature sensors..."
if (echo "$sensorsOutput" | grep -q "nvme-"); then
msg "Detected sensors:\n$(echo "$sensorsOutput" | grep -o '"nvme[^"]*"' | sed 's/"//g')"
ENABLE_NVME_TEMP=true
SENSORS_DETECTED=true
else
warn "No NVMe temperature sensors found."
ENABLE_NVME_TEMP=false
fi
# Look for fan speeds
msg "\nDetecting support for fan speed readings..."
if (echo "$sensorsOutput" | grep -q "fan[0-9]*_input"); then
msg "Detected fan speed sensors:\n$(echo $sensorsOutput | grep -Po '"[^"]*":\s*\{\s*"fan[0-9]*_input[^}]*' | sed -E 's/"([^"]*)":.*/\1/')"
ENABLE_FAN_SPEED=true
SENSORS_DETECTED=true
# Prompt user for display zero speed fans
local choiceDisplayZeroSpeedFans=$(ask "Do you wish to display fans reporting a speed of zero? If no, only active fans will be displayed. (Y/n)")
case "$choiceDisplayZeroSpeedFans" in
# Set temperature search criteria
[yY]|"")
DISPLAY_ZERO_SPEED_FANS=true
;;
[nN] )
DISPLAY_ZERO_SPEED_FANS=false
;;
*)
# If the user enters an invalid input, print an error message and exit the script with a non-zero status code
err "Invalid input. Exiting..."
;;
esac
else
warn "No fan speed sensors found."
ENABLE_FAN_SPEED=false
fi
if [ $SENSORS_DETECTED = true ]; then
local choiceTempUnit=$(ask "Do you wish to display temperatures in degrees Celsius [C] or Fahrenheit [f]? (C/f)")
case "$choiceTempUnit" in
[cC] | "")
TEMP_UNIT="C"
info "Temperatures will be presented in degrees Celsius."
;;
[fF])
TEMP_UNIT="F"
info "Temperatures will be presented in degrees Fahrenheit."
;;
*)
warn "Invalid unit selected. Temperatures will be displayed in degrees Celsius."
TEMP_UNIT="C"
;;
esac
fi
local choiceEnableSystemInfo=$(ask "Do you wish to enable system information? (Y/n)")
case "$choiceEnableSystemInfo" in
[yY] | "")
ENABLE_SYSTEM_INFO=true
info "System information will be displayed..."
;;
[nN])
ENABLE_SYSTEM_INFO=false
info "System information will NOT be displayed..."
;;
*)
warn "Invalid selection. System information will be displayed."
ENABLE_SYSTEM_INFO=true
;;
esac
echo # add a new line
}
# Function to install the modification
function install_mod {
msg "\nPreparing mod installation..."
# Provide sensor configuration
configure
# Create backup of original files
mkdir -p "$BACKUP_DIR"
local timestamp=$(date '+%Y-%m-%d_%H-%M-%S')
# Perform backup
if [[ -z $(cat $NODES_PM_FILE | grep -e "$res->{sensorsOutput}") ]] || [[ -z $(cat $NODES_PM_FILE | grep -e "$res->{systemInfo}") ]]; then
# Create backup of original file
cp "$NODES_PM_FILE" "$BACKUP_DIR/Nodes.pm.$timestamp"
msg "Backup of \"$NODES_PM_FILE\" saved to \"$BACKUP_DIR/Nodes.pm.$timestamp\"."
# Create backup of original file
cp "$PVE_MANAGER_LIB_JS_FILE" "$BACKUP_DIR/pvemanagerlib.js.$timestamp"
msg "Backup of \"$PVE_MANAGER_LIB_JS_FILE\" saved to \"$BACKUP_DIR/pvemanagerlib.js.$timestamp\"."
else
err "Mod is already installed. Uninstall existing before installing."
exit
fi
if [ $SENSORS_DETECTED = true ]; then
local sensorsCmd
if [ $DEBUG_REMOTE = true ]; then
sensorsCmd="cat \"$DEBUG_JSON_FILE\""
else
# WTF: sensors -f used for Fahrenheit breaks the fan speeds :|
#local sensorsCmd=$([[ "$TEMP_UNIT" = "F" ]] && echo "sensors -j -f" || echo "sensors -j")
sensorsCmd="sensors -j"
fi
sed -i '/my \$dinfo = df('\''\/'\'', 1);/i\'$'\t''$res->{sensorsOutput} = `'"$sensorsCmd"'`;\n\t# sanitize JSON output\n\t$res->{sensorsOutput} =~ s/ERROR:.+\\s(\\w+):\\s(.+)/\\"$1\\": 0.000,/g;\n\t$res->{sensorsOutput} =~ s/ERROR:.+\\s(\\w+)!/\\"$1\\": 0.000,/g;\n\t$res->{sensorsOutput} =~ s/,(.*[.\\n]*.+})/$1/g;\n' "$NODES_PM_FILE"
msg "Sensors' output added to \"$NODES_PM_FILE\"."
fi
if [ $ENABLE_SYSTEM_INFO = true ]; then
local systemInfoCmd=$(dmidecode -t 1 | awk -F': ' '/Manufacturer|Product Name|Serial Number/ {print $1": "$2}' | awk '{$1=$1};1' | sed 's/$/ |/' | paste -sd " " - | sed 's/ |$//')
sed -i "/my \$dinfo = df('\/', 1);/i\\\t\$res->{systemInfo} = \"$(echo "$systemInfoCmd")\";\n" "$NODES_PM_FILE"
msg "System information output added to \"$NODES_PM_FILE\"."
fi
# Add new item to the items array in PVE.node.StatusView
if [[ -z $(cat "$PVE_MANAGER_LIB_JS_FILE" | grep -e "itemId: 'thermal[[:alnum:]]*'") ]]; then
local tempHelperCtorParams=$([[ "$TEMP_UNIT" = "F" ]] && echo '{srcUnit: PVE.mod.TempHelper.CELSIUS, dstUnit: PVE.mod.TempHelper.FAHRENHEIT}' || echo '{srcUnit: PVE.mod.TempHelper.CELSIUS, dstUnit: PVE.mod.TempHelper.CELSIUS}')
# Expand space in StatusView
sed -i "/Ext.define('PVE\.node\.StatusView'/,/\},/ {
s/\(bodyPadding:\) '[^']*'/\1 '20 15 20 15'/
s/height: [0-9]\+/minHeight: 360,\n\tflex: 1,\n\tcollapsible: true,\n\ttitleCollapse: true/
s/\(tableAttrs:.*$\)/trAttrs: \{ valign: 'top' \},\n\t\1/
}" "$PVE_MANAGER_LIB_JS_FILE"
msg "Expanded space in \"$PVE_MANAGER_LIB_JS_FILE\"."
sed -i "/^Ext.define('PVE.node.StatusView'/i\
Ext.define('PVE.mod.TempHelper', {\n\
//singleton: true,\n\
\n\
requires: ['Ext.util.Format'],\n\
\n\
statics: {\n\
CELSIUS: 0,\n\
FAHRENHEIT: 1\n\
},\n\
\n\
srcUnit: null,\n\
dstUnit: null,\n\
\n\
isValidUnit: function (unit) {\n\
return (\n\
Ext.isNumber(unit) && (unit === this.self.CELSIUS || unit === this.self.FAHRENHEIT)\n\
);\n\
},\n\
\n\
constructor: function (config) {\n\
this.srcUnit = config && this.isValidUnit(config.srcUnit) ? config.srcUnit : this.self.CELSIUS;\n\
this.dstUnit = config && this.isValidUnit(config.dstUnit) ? config.dstUnit : this.self.CELSIUS;\n\
},\n\
\n\
toFahrenheit: function (tempCelsius) {\n\
return Ext.isNumber(tempCelsius)\n\
? tempCelsius * 9 / 5 + 32\n\
: NaN;\n\
},\n\
\n\
toCelsius: function (tempFahrenheit) {\n\
return Ext.isNumber(tempFahrenheit)\n\
? (tempFahrenheit - 32) * 5 / 9\n\
: NaN;\n\
},\n\
\n\
getTemp: function (value) {\n\
if (this.srcUnit !== this.dstUnit) {\n\
switch (this.srcUnit) {\n\
case this.self.CELSIUS:\n\
switch (this.dstUnit) {\n\
case this.self.FAHRENHEIT:\n\
return this.toFahrenheit(value);\n\
\n\
default:\n\
Ext.raise({\n\
msg:\n\
'Unsupported destination temperature unit: ' + this.dstUnit,\n\
});\n\
}\n\
case this.self.FAHRENHEIT:\n\
switch (this.dstUnit) {\n\
case this.self.CELSIUS:\n\
return this.toCelsius(value);\n\
\n\
default:\n\
Ext.raise({\n\
msg:\n\
'Unsupported destination temperature unit: ' + this.dstUnit,\n\
});\n\
}\n\
default:\n\
Ext.raise({\n\
msg: 'Unsupported source temperature unit: ' + this.srcUnit,\n\
});\n\
}\n\
} else {\n\
return value;\n\
}\n\
},\n\
\n\
getUnit: function(plainText) {\n\
switch (this.dstUnit) {\n\
case this.self.CELSIUS:\n\
return plainText !== true ? '\°C' : '\\\'C';\n\
\n\
case this.self.FAHRENHEIT:\n\\n\
return plainText !== true ? '\°F' : '\\\'F';\n\
\n\
default:\n\
Ext.raise({\n\
msg: 'Unsupported destination temperature unit: ' + this.srcUnit,\n\
});\n\
}\n\
},\n\
});\n" "$PVE_MANAGER_LIB_JS_FILE"
if [ $ENABLE_SYSTEM_INFO = true ]; then
sed -i "/^Ext.define('PVE.node.StatusView',/ {
:a;
/items:/!{N;ba;}
:b;
/cpus.*},/!{N;bb;}
a\
\\
{\n\
itemId: 'sysinfo',\n\
colspan: 2,\n\
printBar: false,\n\
title: gettext('System Information'),\n\
textField: 'systemInfo',\n\
renderer: function(value){\n\
return value;\n\
}\n\
},
}" "$PVE_MANAGER_LIB_JS_FILE"
fi
sed -i "/^Ext.define('PVE.node.StatusView',/ {
:a;
/items:/!{N;ba;}
:b;
/cpus.*},/!{N;bb;}
a\
\\
{\n\
itemId: 'thermalCpu',\n\
colspan: 2,\n\
printBar: false,\n\
title: gettext('CPU Thermal State'),\n\
iconCls: 'fa fa-fw fa-thermometer-half',\n\
textField: 'sensorsOutput',\n\
renderer: function(value){\n\
// sensors configuration\n\
const addressPrefix = \"$CPU_ADDRESS_PREFIX\";\n\
const cpuItemPrefix = \"$CPU_ITEM_PREFIX\";\n\
const cpuTempCaption = \"$CPU_TEMP_CAPTION\";\n\
const cpuTempHelper = Ext.create('PVE.mod.TempHelper', $tempHelperCtorParams);\n\
// display configuration\n\
const itemsPerRow = $CPU_ITEMS_PER_ROW;\n\
// ---\n\
let objValue;\n\
try {\n\
objValue = JSON.parse(value) || {};\n\
} catch(e) {\n\
objValue = {};\n\
}\n\
const cpuKeys = Object.keys(objValue).filter(item => String(item).startsWith(addressPrefix)).sort();\n\
const cpuCount = cpuKeys.length;\n\
let temps = [];\n\
cpuKeys.forEach((cpuKey, cpuIndex) => {\n\
let cpuTemps = [];\n\
const items = objValue[cpuKey];\n\
const itemKeys = Object.keys(items).filter(item => { return String(item).startsWith(cpuItemPrefix); });\n\
itemKeys.forEach((coreKey) => {\n\
try {\n\
let tempVal = NaN, tempMax = NaN, tempCrit = NaN;\n\
Object.keys(items[coreKey]).forEach((secondLevelKey) => {\n\
if (secondLevelKey.endsWith('_input')) {\n\
tempVal = cpuTempHelper.getTemp(parseFloat(items[coreKey][secondLevelKey]));\n\
} else if (secondLevelKey.endsWith('_max')) {\n\
tempMax = cpuTempHelper.getTemp(parseFloat(items[coreKey][secondLevelKey]));\n\
} else if (secondLevelKey.endsWith('_crit')) {\n\
tempCrit = cpuTempHelper.getTemp(parseFloat(items[coreKey][secondLevelKey]));\n\
}\n\
});\n\
if (!isNaN(tempVal)) {\n\
let tempStyle = '';\n\
if (!isNaN(tempMax) && tempVal >= tempMax) {\n\
tempStyle = 'color: #FFC300; font-weight: bold;';\n\
}\n\
if (!isNaN(tempCrit) && tempVal >= tempCrit) {\n\
tempStyle = 'color: red; font-weight: bold;';\n\
}\n\
let tempStr = '';\n\
let tempIndex = coreKey.match(/\\\S+\\\s*(\\\d+)/);\n\
if (tempIndex !== null && tempIndex.length > 1) {\n\
tempIndex = tempIndex[1];\n\
tempStr = \`\${cpuTempCaption} \${tempIndex}: <span style=\"\${tempStyle}\">\${Ext.util.Format.number(tempVal, '0.#')}\${cpuTempHelper.getUnit()}</span>\`;\n\
} else {\n\
tempStr = \`\${cpuTempCaption}: \${Ext.util.Format.number(tempVal, '0.#')}\${cpuTempHelper.getUnit()}\`;\n\
}\n\
cpuTemps.push(tempStr);\n\
}\n\
} catch (e) { /*_*/ }\n\
});\n\
if(cpuTemps.length > 0) {\n\
temps.push(cpuTemps);\n\
}\n\
});\n\
let result = '';\n\
temps.forEach((cpuTemps, cpuIndex) => {\n\
const strCoreTemps = cpuTemps.map((strTemp, index, arr) => { return strTemp + (index + 1 < arr.length ? (itemsPerRow > 0 && (index + 1) % itemsPerRow === 0 ? '<br>' : ' | ') : ''); })\n\
if(strCoreTemps.length > 0) {\n\
result += (cpuCount > 1 ? \`CPU \${cpuIndex+1}: \` : '') + strCoreTemps.join('') + (cpuIndex < cpuCount ? '<br>' : '');\n\
}\n\
});\n\
return '<div style=\"text-align: left; margin-left: 28px;\">' + (result.length > 0 ? result : 'N/A') + '</div>';\n\
}\n\
},
}" "$PVE_MANAGER_LIB_JS_FILE"
#
# NOTE: The following items will be added in reverse order
#
if [ $ENABLE_HDD_TEMP = true ]; then
sed -i "/^Ext.define('PVE.node.StatusView',/ {
:a;
/items:/!{N;ba;}
:b;
/'thermal.*},/!{N;bb;}
a\
\\
{\n\
itemId: 'thermalHdd',\n\
colspan: 2,\n\
printBar: false,\n\
title: gettext('HDD/SSD Thermal State'),\n\
iconCls: 'fa fa-fw fa-thermometer-half',\n\
textField: 'sensorsOutput',\n\
renderer: function(value) {\n\
// sensors configuration\n\
const addressPrefix = \"drivetemp-scsi-\";\n\
const sensorName = \"temp1\";\n\
const tempHelper = Ext.create('PVE.mod.TempHelper', $tempHelperCtorParams);\n\
// display configuration\n\
const itemsPerRow = ${HDD_ITEMS_PER_ROW};\n\
// ---\n\
let objValue;\n\
try {\n\
objValue = JSON.parse(value) || {};\n\
} catch(e) {\n\
objValue = {};\n\
}\n\
const drvKeys = Object.keys(objValue).filter(item => String(item).startsWith(addressPrefix)).sort();\n\
let temps = [];\n\
drvKeys.forEach((drvKey, index) => {\n\
try {\n\
let tempVal = NaN, tempMax = NaN, tempCrit = NaN;\n\
Object.keys(objValue[drvKey][sensorName]).forEach((secondLevelKey) => {\n\
if (secondLevelKey.endsWith('_input')) {\n\
tempVal = tempHelper.getTemp(parseFloat(objValue[drvKey][sensorName][secondLevelKey]));\n\
} else if (secondLevelKey.endsWith('_max')) {\n\
tempMax = tempHelper.getTemp(parseFloat(objValue[drvKey][sensorName][secondLevelKey]));\n\
} else if (secondLevelKey.endsWith('_crit')) {\n\
tempCrit = tempHelper.getTemp(parseFloat(objValue[drvKey][sensorName][secondLevelKey]));\n\
}\n\
});\n\
if (!isNaN(tempVal)) {\n\
let tempStyle = '';\n\
if (!isNaN(tempMax) && tempVal >= tempMax) {\n\
tempStyle = 'color: #FFC300; font-weight: bold;';\n\
}\n\
if (!isNaN(tempCrit) && tempVal >= tempCrit) {\n\
tempStyle = 'color: red; font-weight: bold;';\n\
}\n\
const tempStr = \`Drive \${index + 1}: <span style=\"\${tempStyle}\">\${Ext.util.Format.number(tempVal, '0.#')}\${tempHelper.getUnit()}</span>\`;\n\
temps.push(tempStr);\n\
}\n\
} catch(e) { /*_*/ }\n\
});\n\
const result = temps.map((strTemp, index, arr) => { return strTemp + (index + 1 < arr.length ? ((index + 1) % itemsPerRow === 0 ? '<br>' : ' | ') : ''); });\n\
return '<div style=\"text-align: left; margin-left: 28px;\">' + (result.length > 0 ? result.join('') : 'N/A') + '</div>';\n\
}\n\
},
}" "$PVE_MANAGER_LIB_JS_FILE"
fi
if [ $ENABLE_NVME_TEMP = true ]; then
sed -i "/^Ext.define('PVE.node.StatusView',/ {
:a;
/items:/!{N;ba;}
:b;
/'thermal.*},/!{N;bb;}
a\
\\
{\n\
itemId: 'thermalNvme',\n\
colspan: 2,\n\
printBar: false,\n\
title: gettext('NVMe Thermal State'),\n\
iconCls: 'fa fa-fw fa-thermometer-half',\n\
textField: 'sensorsOutput',\n\
renderer: function(value) {\n\
// sensors configuration\n\
const addressPrefix = \"nvme-pci-\";\n\
const sensorName = \"Composite\";\n\
const tempHelper = Ext.create('PVE.mod.TempHelper', $tempHelperCtorParams);\n\
// display configuration\n\
const itemsPerRow = ${NVME_ITEMS_PER_ROW};\n\
// ---\n\
let objValue;\n\
try {\n\
objValue = JSON.parse(value) || {};\n\
} catch(e) {\n\
objValue = {};\n\
}\n\
const nvmeKeys = Object.keys(objValue).filter(item => String(item).startsWith(addressPrefix)).sort();\n\
let temps = [];\n\
nvmeKeys.forEach((nvmeKey, index) => {\n\
try {\n\
let tempVal = NaN, tempMax = NaN, tempCrit = NaN;\n\
Object.keys(objValue[nvmeKey][sensorName]).forEach((secondLevelKey) => {\n\
if (secondLevelKey.endsWith('_input')) {\n\
tempVal = tempHelper.getTemp(parseFloat(objValue[nvmeKey][sensorName][secondLevelKey]));\n\
} else if (secondLevelKey.endsWith('_max')) {\n\
tempMax = tempHelper.getTemp(parseFloat(objValue[nvmeKey][sensorName][secondLevelKey]));\n\
} else if (secondLevelKey.endsWith('_crit')) {\n\
tempCrit = tempHelper.getTemp(parseFloat(objValue[nvmeKey][sensorName][secondLevelKey]));\n\
}\n\
});\n\
if (!isNaN(tempVal)) {\n\
let tempStyle = '';\n\
if (!isNaN(tempMax) && tempVal >= tempMax) {\n\
tempStyle = 'color: #FFC300; font-weight: bold;';\n\
}\n\
if (!isNaN(tempCrit) && tempVal >= tempCrit) {\n\
tempStyle = 'color: red; font-weight: bold;';\n\
}\n\
const tempStr = \`Drive \${index + 1}: <span style=\"\${tempStyle}\">\${Ext.util.Format.number(tempVal, '0.#')}\${tempHelper.getUnit()}</span>\`;\n\
temps.push(tempStr);\n\
}\n\
} catch(e) { /*_*/ }\n\
});\n\
const result = temps.map((strTemp, index, arr) => { return strTemp + (index + 1 < arr.length ? ((index + 1) % itemsPerRow === 0 ? '<br>' : ' | ') : ''); });\n\
return '<div style=\"text-align: left; margin-left: 28px;\">' + (result.length > 0 ? result.join('') : 'N/A') + '</div>';\n\
}\n\
},
}" "$PVE_MANAGER_LIB_JS_FILE"
fi
if [ $ENABLE_NVME_TEMP = true -o $ENABLE_HDD_TEMP = true ]; then
sed -i "/^Ext.define('PVE.node.StatusView',/ {
:a;
/items:/!{N;ba;}
:b;
/'thermal.*},/!{N;bb;}
a\
\\
{\n\
xtype: 'box',\n\
colspan: 2,\n\
html: gettext('Drive(s)'),\n\
},
}" "$PVE_MANAGER_LIB_JS_FILE"
fi
if [ $ENABLE_FAN_SPEED = true ]; then
# Add fan speeds display
sed -i "/^Ext.define('PVE.node.StatusView',/ {
:a;
/items:/!{N;ba;}
:b;
/'thermal.*},/!{N;bb;}
a\
\\
{\n\
xtype: 'box',\n\
colspan: 2,\n\
html: gettext('Cooling'),\n\
},\n\
{\n\
itemId: 'speedFan',\n\
colspan: 2,\n\
printBar: false,\n\
title: gettext('Fan Speed(s)'),\n\
iconCls: 'fa fa-fw fa-snowflake-o',\n\
textField: 'sensorsOutput',\n\
renderer: function(value) {\n\
// ---\n\
let objValue;\n\
try {\n\
objValue = JSON.parse(value) || {};\n\
} catch(e) {\n\
objValue = {};\n\
}\n\
\n\
// Recursive function to find fan keys and values\n\
function findFanKeys(obj, fanKeys, parentKey = null) {\n\
Object.keys(obj).forEach(key => {\n\
const value = obj[key];\n\
if (typeof value === 'object' && value !== null) {\n\
// If the value is an object, recursively call the function\n\
findFanKeys(value, fanKeys, key);\n\
} else if (/^fan[0-9]+(_input)?$/.test(key)) {\n\
if ($DISPLAY_ZERO_SPEED_FANS != true && value === 0) {\n\
// Skip this fan if DISPLAY_ZERO_SPEED_FANS is false and value is 0\n\
return;\n\
}\n\
// If the key matches the pattern, add the parent key and value to the fanKeys array\n\
fanKeys.push({ key: parentKey, value: value });\n\
}\n\
});\n\
}\n\
\n\
let speeds = [];\n\
// Loop through the parent keys\n\
Object.keys(objValue).forEach(parentKey => {\n\
const parentObj = objValue[parentKey];\n\
// Array to store fan keys and values\n\
const fanKeys = [];\n\
// Call the recursive function to find fan keys and values\n\
findFanKeys(parentObj, fanKeys);\n\
// Sort the fan keys\n\
fanKeys.sort();\n\
// Process each fan key and value\n\
fanKeys.forEach(({ key: fanKey, value: fanSpeed }) => {\n\
try {\n\
const fan = fanKey.charAt(0).toUpperCase() + fanKey.slice(1); // Capitalize the first letter of fanKey\n\
speeds.push(\`\${fan}: \${fanSpeed} RPM\`);\n\
} catch(e) {\n\
console.error(\`Error retrieving fan speed for \${fanKey} in \${parentKey}:\`, e); // Debug: Log specific error\n\
}\n\
});\n\
});\n\
return '<div style=\"text-align: left; margin-left: 28px;\">' + (speeds.length > 0 ? speeds.join(' | ') : 'N/A') + '</div>';\n\
}\n\
},
}" "$PVE_MANAGER_LIB_JS_FILE"
fi
# Add an empty line to separate modified items as a visual group
# NOTE: Check for the presence of items in the reverse order of display
local lastItemId=""
if [ $ENABLE_HDD_TEMP = true ]; then
lastItemId="thermalHdd"
elif [ $ENABLE_NVME_TEMP = true ]; then
lastItemId="thermalNvme"
elif [ $ENABLE_FAN_SPEED = true ]; then
lastItemId="speedFan"
else
lastItemId="thermalCpu"
fi
if [ -n "$lastItemId" ]; then
sed -i "/^Ext.define('PVE.node.StatusView',/ {
:a;
/^.*{.*'$lastItemId'.*},/!{N;ba;}
a\
\\
{\n\
xtype: 'box',\n\
colspan: 2,\n\
padding: '0 0 20 0',\n\
},
}" "$PVE_MANAGER_LIB_JS_FILE"
fi
# Move the node summary box into its own container
sed -i "/^\s*nodeStatus: nodeStatus,/ {
:a
/items: \[/ !{N;ba;}
a\
\\
{\n\
xtype: 'container',\n\
itemId: 'summarycontainer',\n\
layout: 'column',\n\
minWidth: 700,\n\
defaults: {\n\
minHeight: 350,\n\
padding: 5,\n\
columnWidth: 1,\n\
},\n\
items: [\n\
nodeStatus,\n\
]\n\
},
}" "$PVE_MANAGER_LIB_JS_FILE"
# Deactivate the original box instance
sed -i "/^\s*nodeStatus: nodeStatus,/ {
:a
/itemId: 'itemcontainer',/ !{N;ba;}
n;
:b
/nodeStatus,/ !{N;bb;}
s/nodeStatus/\/\/nodeStatus/
}" "$PVE_MANAGER_LIB_JS_FILE"
msg "Sensor display items added to the summary panel in \"$PVE_MANAGER_LIB_JS_FILE\"."
restart_proxy
msg "Installation completed."
info "Clear the browser cache to ensure all changes are visualized."
else
warn "Sensor display items already added to the summary panel in \"$PVE_MANAGER_LIB_JS_FILE\"."
fi
}
# Function to uninstall the modification
function uninstall_mod {
msg "\nRestoring modified files..."
# Find the latest Nodes.pm file using the find command
local latest_nodes_pm=$(find "$BACKUP_DIR" -name "Nodes.pm.*" -type f -printf '%T+ %p\n' 2>/dev/null | sort -r | head -n 1 | awk '{print $2}')
if [ -n "$latest_nodes_pm" ]; then
# Remove the latest Nodes.pm file
cp "$latest_nodes_pm" "$NODES_PM_FILE"
msg "Copied latest backup to $NODES_PM_FILE."
else
warn "No Nodes.pm files found."
fi
# Find the latest pvemanagerlib.js file using the find command
local latest_pvemanagerlibjs=$(find "$BACKUP_DIR" -name "pvemanagerlib.js.*" -type f -printf '%T+ %p\n' 2>/dev/null | sort -r | head -n 1 | awk '{print $2}')
if [ -n "$latest_pvemanagerlibjs" ]; then
# Remove the latest pvemanagerlib.js file
cp "$latest_pvemanagerlibjs" "$PVE_MANAGER_LIB_JS_FILE"
msg "Copied latest backup to \"$PVE_MANAGER_LIB_JS_FILE\"."
else
warn "No pvemanagerlib.js files found."
fi
if [ -n "$latest_nodes_pm" ] || [ -n "$latest_pvemanagerlibjs" ]; then
# At least one of the variables is not empty, restart the proxy
restart_proxy
fi
}
function restart_proxy {
# Restart pveproxy
msg "\nRestarting PVE proxy..."
systemctl restart pveproxy
}
function save_sensors_data {
# Check if DEBUG_SAVE_PATH exists and is writable
if [[ ! -d "$DEBUG_SAVE_PATH" || ! -w "$DEBUG_SAVE_PATH" ]]; then
err "Directory $DEBUG_SAVE_PATH does not exist or is not writable. No file could be saved."
return
fi
# Check if command exists
if (command -v sensors &>/dev/null); then
# Save sensors output
local filepath="${DEBUG_SAVE_PATH}/${DEBUG_SAVE_FILENAME}"
msg "Sensors data will be saved in $filepath"
# Prompt user for confirmation
local choiceContinue=$(ask "Do you wish to continue? (y/n)")
case "$choiceContinue" in
[yY])
sensors -j >"$filepath"
msgb "Sensors data saved in $filepath."
;;
*)
warn "Operation cancelled by user."
;;
esac
else
err "Sensors is not installed. No file could be saved."
fi
}
# Process the arguments using a while loop and a case statement
executed=0
while [[ $# -gt 0 ]]; do
case "$1" in
install)
executed=$(($executed + 1))
msgb "\nInstalling the Proxmox VE sensors display mod..."
install_packages
install_mod
echo # add a new line
;;
uninstall)
executed=$(($executed + 1))
msgb "\nUninstalling the Proxmox VE sensors display mod..."
uninstall_mod
echo # add a new line
;;
save-sensors-data)
executed=$(($executed + 1))
msgb "\nSaving current sensor readings in a file for debugging..."
save_sensors_data
echo # add a new line
;;
esac
shift
done
# If no arguments were provided or all arguments have been processed, print the usage message
if [[ $executed -eq 0 ]]; then
usage
fi