forked from jgyates/genmon
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenloader.py
More file actions
1506 lines (1329 loc) · 58.6 KB
/
Copy pathgenloader.py
File metadata and controls
1506 lines (1329 loc) · 58.6 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
# -------------------------------------------------------------------------------
# FILE: genloader.py
# PURPOSE: app for loading specific moduels for genmon
#
# AUTHOR: Jason G Yates
# DATE: 12-Sept-2018
#
# MODIFICATIONS:
# -------------------------------------------------------------------------------
import getopt
import os
import subprocess
import sys
import time
from shutil import copyfile, move
from subprocess import PIPE, Popen
try:
from genmonlib.myconfig import MyConfig
from genmonlib.mylog import SetupLogger
from genmonlib.mysupport import MySupport
from genmonlib.program_defaults import ProgramDefaults
except Exception as e1:
print(
"\n\nThis program requires the modules located in the genmonlib directory in the github repository.\n"
)
print(
"Please see the project documentation at https://github.com/jgyates/genmon.\n"
)
print("Error: " + str(e1))
sys.exit(2)
# ------------ Loader class -----------------------------------------------------
class Loader(MySupport):
def __init__(
self,
start=False,
stop=False,
hardstop=False,
loglocation=ProgramDefaults.LogPath,
log=None,
localinit=False,
ConfigFilePath=ProgramDefaults.ConfPath,
):
self.Start = start
self.Stop = stop
self.HardStop = hardstop
self.PipChecked = False
self.AptUpdated = False
self.NewInstall = False
self.Upgrade = False
self.version = None
self.ConfigFilePath = ConfigFilePath
self.ConfigFileName = "genloader.conf"
# log errors in this module to a file
if localinit == True:
self.configfile = self.ConfigFileName
else:
self.configfile = os.path.join(self.ConfigFilePath, self.ConfigFileName)
self.ModulePath = os.path.dirname(os.path.realpath(__file__))
self.ConfPath = os.path.join(
os.path.dirname(os.path.realpath(__file__)), "conf"
)
self.bSystemIsNotLinux = False
if not "linux" in sys.platform:
self.bSystemIsNotLinux = True
self.bSysetmIsWindows = False
if "win" in sys.platform:
self.bSysetmIsWindows = True
# log errors in this module to a file
if log == None:
self.log = SetupLogger(
"genloader", os.path.join(loglocation, "genloader.log")
)
else:
self.log = log
self.console = SetupLogger("genloader_console", log_file="", stream=True)
try:
if sys.version_info < (3, 9):
self.LogError(f"ERROR: Python version 3.9 or higher required.")
if sys.version_info[0] < 3:
self.pipProgram = "pip2"
else:
self.pipProgram = "pip3"
self.CachedConfig = {}
if not os.path.isdir(self.ConfigFilePath):
try:
os.mkdir(self.ConfigFilePath)
except Exception as e1:
self.LogInfo(
"Error creating target config directory: " + str(e1),
LogLine=True,
)
# check to see if genloader.conf is present, if not copy it from genmon directory
if not os.path.isfile(self.configfile):
self.LogInfo(
"Warning: unable to find config file: "
+ self.configfile
+ " Copying file to "
+ self.ConfigFilePath
+ " directory."
)
if not self.CopyConfFile():
sys.exit(2)
self.config = MyConfig(
filename=self.configfile, section="genmon", log=self.log
)
if not self.GetConfig():
self.CopyConfFile()
self.LogInfo("Error validating config. Retrying..")
self.config = MyConfig(
filename=self.configfile, section="genmon", log=self.log
)
if not self.GetConfig():
self.LogInfo("Error reading config file, 2nd attempt (1), Exiting")
sys.exit(2)
if not self.ValidateConfig():
self.CopyConfFile()
self.LogInfo("Error validating config. Retrying..")
self.config = MyConfig(
filename=self.configfile, section="genmon", log=self.log
)
if not self.GetConfig():
self.LogInfo("Error reading config file, 2nd attempt (2), Exiting")
sys.exit(2)
if not self.ValidateConfig():
self.LogInfo("Error validating config file, Exiting")
sys.exit(2)
if self.Start:
if not self.CheckSystem():
self.LogInfo("Error check system readiness. Exiting")
sys.exit(2)
self.LoadOrder = self.GetLoadOrder()
if self.Stop:
self.StopModules()
time.sleep(2)
self.Maintenance()
if self.Start:
self.StartModules()
except Exception as e1:
self.LogErrorLine("Error in init: " + str(e1))
# ---------------------------------------------------------------------------
def CopyConfFile(self):
if os.path.isfile(os.path.join(self.ConfPath, self.ConfigFileName)):
copyfile(os.path.join(self.ConfPath, self.ConfigFileName), self.configfile)
return True
else:
self.LogInfo("Unable to find config file.")
return False
sys.exit(2)
# ---------------------------------------------------------------------------
def IsModuleEnabled(self, ModuleList):
try:
if ModuleList == None or not len(ModuleList):
return True
for Module in ModuleList:
if Module in self.CachedConfig and self.CachedConfig[Module]["enable"]:
return True
return False
except Exception as e1:
self.LogInfo("Error in IsModuleEnabled: " + str(e1), LogLine=True)
return False
# ---------------------------------------------------------------------------
def IsConfigOptionEnabled(self, ConfigFile, Section, Option, default=False):
try:
ConfigPath = os.path.join(self.ConfigFilePath, ConfigFile)
if not os.path.isfile(ConfigPath):
ConfigPath = os.path.join(self.ConfPath, ConfigFile)
if not os.path.isfile(ConfigPath):
return default
config = MyConfig(filename=ConfigPath, section=Section, log=self.log)
return config.ReadValue(Option, return_type=bool, default=default)
except Exception as e1:
self.LogInfo("Error in IsConfigOptionEnabled: " + str(e1), LogLine=True)
return default
# ---------------------------------------------------------------------------
def LibraryDependency(
self,
ImportName,
InstallName=None,
Version=None,
LinuxOnly=False,
MinPython=None,
):
# ImportName is the module name used by importlib. InstallName is the
# package name used by pip, which can differ (e.g. serial -> pyserial).
return {
"import": ImportName,
"install": InstallName if InstallName != None else ImportName,
"version": Version,
"linuxonly": LinuxOnly,
"minpython": MinPython,
}
# ---------------------------------------------------------------------------
def GetDependencyRegistry(self):
# Dependency groups:
# base - always required for normal genmon/genserv startup
# addons - required only when at least one listed add-on is enabled
# features - required only when a config option is enabled; a feature
# may also list modules when both an add-on and an option
# must be enabled before installing the dependency.
#
# Keep optional or unusually large packages out of base. For example,
# fluids is only needed by genmopeka, and zeroconf is only needed when
# genhalink mDNS discovery is enabled.
#
# we will not use the check for configparser as this look like it is in backports on 2.7
# and our myconfig modules uses the default so this generates an error that is not warranted
# ['configparser','configparser',None], # reading config files
return {
"base": [
self.LibraryDependency("flask"), # Web server
self.LibraryDependency("serial", "pyserial"), # Serial
self.LibraryDependency("crcmod"), # Modbus CRC
self.LibraryDependency("pyowm"), # Open Weather API
self.LibraryDependency("pytz"), # Time zone support
self.LibraryDependency("pyotp", Version="2.3.0"), # 2FA support
self.LibraryDependency("psutil"), # process utilities
self.LibraryDependency("OpenSSL", "pyopenssl"), # SSL
self.LibraryDependency("ldap3"), # LDAP
],
"addons": [
{
"modules": ["gensnmp"],
"dependencies": [
self.LibraryDependency("pysnmp", Version="7.1.21"),
self.LibraryDependency("pyasn1", Version="0.6.1")
],
},
{
"modules": ["gentankdiy"],
"dependencies": [
self.LibraryDependency("smbus", LinuxOnly=True),
],
},
{
"modules": ["genpushover"],
"dependencies": [
self.LibraryDependency("chump"),
],
},
{
"modules": ["gensms"],
"dependencies": [
self.LibraryDependency("twilio"),
],
},
{
"modules": ["genmqtt", "genmqttin", "genhomeassistant"],
"dependencies": [
self.LibraryDependency(
"paho.mqtt.client", "paho-mqtt", Version="1.6.1"
),
],
},
{
"modules": ["gencthat"],
"dependencies": [
self.LibraryDependency("spidev", LinuxOnly=True),
],
},
{
"modules": ["genhalink"],
"dependencies": [
self.LibraryDependency("aiohttp"),
],
},
{
"modules": ["gensms_voip"],
"dependencies": [
self.LibraryDependency("voipms", Version="0.2.5"),
],
},
{
"modules": ["genmopeka"],
"dependencies": [
self.LibraryDependency("fluids", MinPython=(3, 6)),
],
},
{
"modules": ["genotodata"],
"dependencies": [
self.LibraryDependency("bleak"),
],
},
{
"modules": ["genhubitat"],
"dependencies": [
self.LibraryDependency("aiohttp"),
],
},
],
"features": [
{
# zeroconf is optional within genhalink. Do not install it
# unless the add-on is enabled and mDNS discovery is on.
"modules": ["genhalink"],
"config": {
"file": "genhalink.conf",
"section": "genhalink",
"option": "zeroconf_enabled",
"default": True,
},
"dependencies": [
self.LibraryDependency("zeroconf"),
],
},
{
# zeroconf is optional within genhubitat. Do not install it
# unless the add-on is enabled and mDNS discovery is on.
"modules": ["genhubitat"],
"config": {
"file": "genhubitat.conf",
"section": "genhubitat",
"option": "zeroconf_enabled",
"default": True,
},
"dependencies": [
self.LibraryDependency("zeroconf"),
],
},
{
# webauthn is used for passkeys, which are only available
# when MFA is enabled.
"config": {
"file": "genmon.conf",
"section": "GenMon",
"option": "usemfa",
"default": False,
},
"dependencies": [
self.LibraryDependency("webauthn", Version="2.7.0"),
],
},
],
}
# ---------------------------------------------------------------------------
def GetModuleList(self):
ModuleList = []
Seen = set()
DependencyRegistry = self.GetDependencyRegistry()
try:
# Start with the unconditional core dependencies.
for Module in DependencyRegistry["base"]:
ModuleList.append(Module)
# Add dependencies for enabled add-ons only. This keeps disabled
# add-ons from triggering pip installs during every genloader start.
for AddOn in DependencyRegistry["addons"]:
if not self.IsModuleEnabled(AddOn["modules"]):
continue
for Module in AddOn["dependencies"]:
Module = Module.copy()
Module["modules"] = AddOn["modules"]
ModuleList.append(Module)
# Add dependencies for enabled feature flags. Some features also
# have an add-on owner, so both gates must pass before inclusion.
for Feature in DependencyRegistry["features"]:
if "modules" in Feature:
if not self.IsModuleEnabled(Feature["modules"]):
continue
if not self.IsConfigOptionEnabled(
Feature["config"]["file"],
Feature["config"]["section"],
Feature["config"]["option"],
default=Feature["config"].get("default", False),
):
continue
for Module in Feature["dependencies"]:
Module = Module.copy()
if "modules" in Feature:
Module["modules"] = Feature["modules"]
Module["config"] = Feature["config"]
ModuleList.append(Module)
# A package can be required through more than one path. Check it
# once so shared dependencies do not produce duplicate log/install
# attempts.
DedupedList = []
for Module in ModuleList:
Key = (Module["import"], Module["install"], Module["version"])
if Key in Seen:
continue
Seen.add(Key)
DedupedList.append(Module)
return DedupedList
except Exception as e1:
self.LogInfo("Error in GetModuleList: " + str(e1), LogLine=True)
return ModuleList
# ---------------------------------------------------------------------------
def ShouldCheckLibrary(self, Module):
try:
# Final platform/version/config guard before importing or installing.
# GetModuleList already filters add-ons and features, but keeping
# this here preserves one validation path for any direct callers.
if "linuxonly" in Module and self.bSystemIsNotLinux and Module["linuxonly"]:
return False
if "minpython" in Module and Module["minpython"] != None:
if sys.version_info < Module["minpython"]:
return False
if not self.IsModuleEnabled(Module.get("modules", None)):
return False
if "config" in Module:
Config = Module["config"]
return self.IsConfigOptionEnabled(
Config["file"],
Config["section"],
Config["option"],
default=Config.get("default", False),
)
return True
except Exception as e1:
self.LogInfo("Error in ShouldCheckLibrary: " + str(e1), LogLine=True)
return True
# ---------------------------------------------------------------------------
def CheckSystem(self):
# this function checks the system to see if the required libraries are
# installed. If they are not then an attempt is made to install them.
ModuleList = self.GetModuleList()
try:
ErrorOccured = False
for Module in ModuleList:
if not self.ShouldCheckLibrary(Module):
continue
if not self.LibraryIsInstalled(Module["import"], Module["version"]):
self.LogInfo(
"Warning: required library "
+ Module["install"]
+ " not installed. Attempting to install...."
)
if not self.bSystemIsNotLinux:
self.CheckToolsNeeded()
if not self.InstallLibrary(Module["install"], version=Module["version"]):
self.LogInfo("Error: unable to install library " + Module["install"])
ErrorOccured = True
if Module["import"] == "ldap3":
# This will correct and issue with the ldap3 modbule not being recogonized in LibrayIsInstalled
self.InstallLibrary("pyasn1", version="0.6.1", update=True)
return not ErrorOccured
except Exception as e1:
self.LogInfo("Error in CheckSystem: " + str(e1), LogLine=True)
return False
# ---------------------------------------------------------------------------
def ExecuteCommandList(self, execute_list, env=None):
try:
process = Popen(execute_list, stdout=PIPE, stderr=PIPE, env=env)
output, _error = process.communicate()
if _error:
self.LogInfo("Error in ExecuteCommandList : " + str(_error))
return False
rc = process.returncode
return True
except:
return False
# ---------------------------------------------------------------------------
# check for other tools that are needed by pip libaries
def CheckToolsNeeded(self):
try:
command_list = ["cmake", "--version"]
if not self.ExecuteCommandList(command_list):
if not self.AptUpdated:
command_list = ["sudo", "apt-get", "-yqq", "--allow-releaseinfo-change","update"]
if not self.ExecuteCommandList(command_list):
self.LogInfo("Error: Unable to run apt-get update. Retrying...")
command_list = ["sudo", "apt-get", "-yqq", "update"]
if not self.ExecuteCommandList(command_list):
self.LogInfo("Error: Unable to run apt-get update. ")
self.AptUpdated = True
self.LogInfo("Installing cmake...")
command_list = [
"sudo",
"DEBIAN_FRONTEND=noninteractive",
"apt-get",
"-yqq",
"install",
"cmake",
]
if not self.ExecuteCommandList(command_list):
self.LogInfo("Error: Unable to install cmake.")
return True
except Exception as e1:
self.LogInfo("Error in CheckToolsNeeded: " + str(e1), LogLine=True)
return False
# ---------------------------------------------------------------------------
def CheckBaseSoftware(self):
try:
if self.PipChecked:
return True
command_list = [sys.executable, "-m", "pip", "-V"]
#command_list = [self.pipProgram, "-V"]
if not self.ExecuteCommandList(command_list):
self.InstallBaseSoftware()
self.PipChecked = True
return True
except Exception as e1:
self.LogInfo("Error in CheckBaseSoftware: " + str(e1), LogLine=True)
self.InstallBaseSoftware()
return False
# ---------------------------------------------------------------------------
def InstallBaseSoftware(self):
try:
if sys.version_info[0] < 3:
pipInstallProgram = "python-pip"
else:
pipInstallProgram = "python3-pip"
self.LogInfo("Installing " + pipInstallProgram)
if not self.AptUpdated:
command_list = ["sudo", "apt-get", "-yqq", "--allow-releaseinfo-change", "update"]
if not self.ExecuteCommandList(command_list):
self.LogInfo("Error: Unable to run apt-get update. Retrying..")
command_list = ["sudo", "apt-get", "-yqq", "update"]
if not self.ExecuteCommandList(command_list):
self.LogInfo("Error: Unable to run apt-get update. Retrying..")
self.AptUpdated = True
command_list = ["sudo", "apt-get", "-yqq", "install", pipInstallProgram]
if not self.ExecuteCommandList(command_list):
self.LogInfo("Error: Unable to install " + pipInstallProgram)
return True
except Exception as e1:
self.LogInfo("Error in InstallBaseSoftware: " + str(e1), LogLine=True)
return False
# ---------------------------------------------------------------------------
@staticmethod
def OneTimeMaint(ConfigFilePath, log):
FileList = {
"feedback.json": os.path.dirname(os.path.realpath(__file__)) + "/",
"outage.txt": os.path.dirname(os.path.realpath(__file__)) + "/",
"kwlog.txt": os.path.dirname(os.path.realpath(__file__)) + "/",
"maintlog.json": os.path.dirname(os.path.realpath(__file__)) + "/",
"Feedback_dat": os.path.dirname(os.path.realpath(__file__)) + "/genmonlib/",
"Message_dat": os.path.dirname(os.path.realpath(__file__)) + "/genmonlib/",
"genmon.conf": "/etc/",
"genserv.conf": "/etc/",
"gengpio.conf": "/etc/",
"gengpioin.conf": "/etc/",
"genlog.conf": "/etc/",
"gensms.conf": "/etc/",
"gensms_modem.conf": "/etc/",
"genpushover.conf": "/etc/",
"gensyslog.conf": "/etc/",
"genmqtt.conf": "/etc/",
"genmqttin.conf": "/etc/",
"genslack.conf": "/etc/",
"gencallmebot.conf": "/etc/",
"genexercise.conf": "/etc/",
"genemail2sms.conf": "/etc/",
"genloader.conf": "/etc/",
"mymail.conf": "/etc/",
"mymodem.conf": "/etc/",
}
try:
# Check to see if we have done this already by checking files in the genmon source directory
if (
not os.path.isfile(
os.path.dirname(os.path.realpath(__file__))
+ "/genmonlib/Message_dat"
)
and not os.path.isfile(
os.path.dirname(os.path.realpath(__file__)) + "/maintlog.json"
)
and not os.path.isfile(
os.path.dirname(os.path.realpath(__file__)) + "/outage.txt"
)
and not os.path.isfile(
os.path.dirname(os.path.realpath(__file__)) + "/kwlog.txt"
)
and not os.path.isfile("/etc/genmon.conf")
):
return False
# validate target directory
if not os.path.isdir(ConfigFilePath):
try:
os.mkdir(ConfigFilePath)
if not os.access(ConfigFilePath + File, os.R_OK):
pass
except Exception as e1:
log.error(
"Error validating target directory: " + str(e1), LogLine=True
)
# move files
for File, Path in FileList.items():
try:
SourceFile = Path + File
if os.path.isfile(SourceFile):
log.error("Moving " + SourceFile + " to " + ConfigFilePath)
if not MySupport.CopyFile(
SourceFile, ConfigFilePath + File, move=True, log=log
):
log.error("Error: using alternate move method")
move(SourceFile, ConfigFilePath + File)
if not os.access(ConfigFilePath + File, os.R_OK):
pass
except Exception as e1:
log.error("Error moving " + SourceFile)
except Exception as e1:
log.error("Error moving files: " + str(e1), LogLine=True)
return True
# ---------------------------------------------------------------------------
def FixPyOWMMaintIssues(self):
try:
# check version of pyowm
import pyowm
if sys.version_info[0] < 3:
required_version = "2.9.0"
else:
required_version = "2.10.0"
if not self.LibraryIsInstalled("pyowm"):
self.LogError("Error in FixPyOWMMaintIssues: pyowm not installed")
return False
installed_version = self.GetLibararyVersion("pyowm")
if installed_version == None:
self.LogError("Error in FixPyOWMMaintIssues: pyowm version not found")
return None
if self.VersionTuple(installed_version) <= self.VersionTuple(
required_version
):
return True
self.LogInfo(
"Found wrong version of pyowm, uninstalling and installing the correct version."
)
self.InstallLibrary("pyowm", uninstall=True)
self.InstallLibrary("pyowm", version=required_version)
return True
except Exception as e1:
self.LogErrorLine("Error in FixPyOWMMaintIssues: " + str(e1))
return False
# ---------------------------------------------------------------------------
def GetLibararyVersion(self, libraryname, importonly=False):
try:
try:
import importlib
my_module = importlib.import_module(libraryname)
return my_module.__version__
except:
if importonly:
return None
# if we get here then the libarary does not support a __version__ attribute
# lets use pip to get the version
try:
# This will check if pip is installed
if "linux" in sys.platform:
self.CheckBaseSoftware()
install_list = [sys.executable, "-m", "pip", "freeze", libraryname]
process = Popen(install_list, stdout=PIPE, stderr=PIPE)
output, _error = process.communicate()
if _error:
self.LogInfo(
"Error in GetLibararyVersion using pip : "
+ libraryname
+ ": "
+ str(_error)
)
rc = process.returncode
# process output of pip freeze
lines = output.splitlines()
for line in lines:
line = line.decode("utf-8")
line = line.strip()
if line.startswith(libraryname):
items = line.split("==")
if len(items) <= 2:
return items[1]
return None
except Exception as e1:
self.LogInfo(
"Error getting version of module: "
+ libraryname
+ ": "
+ str(e1),
LogLine=True,
)
return None
except Exception as e1:
self.LogErrorLine("Error in GetLibararyVersion: " + str(e1))
return None
# ---------------------------------------------------------------------------
def LibraryIsInstalled(self, libraryname, version = None):
try:
import importlib
my_module = importlib.import_module(libraryname)
if version != None:
try:
version_installed = tuple(int(x) for x in my_module.__version__.split('.'))
except Exception as e1:
# probably no version exported in this library
self.LogErrorLine(f"Error in LibraryIsInstalled, failure getting version: {libraryname}, version: {version}")
return True
version_needed = tuple(int(x) for x in version.split('.'))
if version_installed < version_needed:
self.LogError(f"Need update on {libraryname} from {version_installed} to {version_needed}")
return False
return True
except Exception as e1:
return False
# ---------------------------------------------------------------------------
def InstallLibrary(self, libraryname, update=False, version=None, uninstall=False):
try:
if version != None and uninstall == False:
libraryname = libraryname + "==" + version
# This will check if pip is installed
if "linux" in sys.platform:
self.CheckBaseSoftware()
if update:
install_list = [sys.executable, "-m", "pip", "install", libraryname, "-U"]
elif uninstall:
install_list = [sys.executable, "-m", "pip", "uninstall", "-y", libraryname]
else:
install_list = [sys.executable, "-m", "pip", "install", libraryname]
process = Popen(install_list, stdout=PIPE, stderr=PIPE)
output, _error = process.communicate()
if _error:
self.LogInfo(
"Error in InstallLibrary using pip : "
+ str(install_list)
+ ": "
+ str(_error)
)
rc = process.returncode
return True
except Exception as e1:
self.LogInfo(
"Error installing module: "
+ str(install_list)
+ ": "
+ str(e1),
LogLine=True,
)
return False
# ---------------------------------------------------------------------------
def ValidateConfig(self):
ErrorOccured = False
if not len(self.CachedConfig):
self.LogInfo("Error: Empty configruation found.")
return False
for Module, Settiings in self.CachedConfig.items():
try:
if self.CachedConfig[Module]["enable"]:
modulepath = self.GetModulePath(
self.ModulePath, self.CachedConfig[Module]["module"]
)
if modulepath == None:
self.LogInfo(
"Enable to find file " + self.CachedConfig[Module]["module"]
)
ErrorOccured = True
# validate config file and if it is not there then copy it.
if not self.CachedConfig[Module]["conffile"] == None and len(
self.CachedConfig[Module]["conffile"]
):
ConfFileList = self.CachedConfig[Module]["conffile"].split(",")
for ConfigFile in ConfFileList:
ConfigFile = ConfigFile.strip()
if not os.path.isfile(
os.path.join(self.ConfigFilePath, ConfigFile)
):
if os.path.isfile(os.path.join(self.ConfPath, ConfigFile)):
self.LogInfo(
"Copying "
+ ConfigFile
+ " to "
+ self.ConfigFilePath
)
copyfile(
os.path.join(self.ConfPath, ConfigFile),
os.path.join(self.ConfigFilePath, ConfigFile),
)
else:
self.LogInfo(
"Enable to find config file "
+ os.path.join(self.ConfPath, ConfigFile)
)
ErrorOccured = True
except Exception as e1:
self.LogInfo(
"Error validating config for " + Module + " : " + str(e1),
LogLine=True,
)
return False
try:
if not self.CachedConfig["genmon"]["enable"]:
self.LogError("Warning: Genmon is not enabled, assume corrupt file.")
ErrorOccured = True
if not self.CachedConfig["genserv"]["enable"]:
self.LogError("Warning: Genserv is not enabled")
except Exception as e1:
self.LogErrorLine(
"Error in ValidateConfig, possible corrupt file. " + str(e1)
)
ErrorOccured = True
return not ErrorOccured
# ---------------------------------------------------------------------------
def AddEntry(self, section=None, module=None, conffile="", args="", priority="2"):
try:
if section == None or module == None:
return
self.config.WriteSection(section)
self.config.WriteValue("module", module, section=section)
self.config.WriteValue("enable", "False", section=section)
self.config.WriteValue("hardstop", "False", section=section)
self.config.WriteValue("conffile", conffile, section=section)
self.config.WriteValue("args", args, section=section)
self.config.WriteValue("priority", priority, section=section)
except Exception as e1:
self.LogInfo("Error in AddEntry: " + str(e1), LogLine=True)
return
# ---------------------------------------------------------------------------
def UpdateIfNeeded(self):
try:
self.config.SetSection("gengpioin")
if not self.config.HasOption("conffile"):
self.config.WriteValue(
"conffile", "gengpioin.conf", section="gengpioin"
)
self.LogError("Updated entry gengpioin.conf")
else:
defValue = self.config.ReadValue("conffile", default="")
if not len(defValue):
self.config.WriteValue(
"conffile", "gengpioin.conf", section="gengpioin"
)
self.LogError("Updated entry gengpioin.conf")
self.config.SetSection("gengpio")
if not self.config.HasOption("conffile"):
self.config.WriteValue("conffile", "gengpio.conf", section="gengpio")
self.LogError("Updated entry gengpio.conf")
else:
defValue = self.config.ReadValue("conffile", default="")
if not len(defValue):
self.config.WriteValue(
"conffile", "gengpio.conf", section="gengpio"
)
self.LogError("Updated entry gengpio.conf")
# check version info
self.config.SetSection("genloader")
self.version = self.config.ReadValue("version", default="0.0.0")
if self.version == "0.0.0" or not len(self.version):
self.version = "0.0.0"
self.NewInstall = True
if self.VersionTuple(self.version) < self.VersionTuple(
ProgramDefaults.GENMON_VERSION
):
self.Upgrade = True
if self.NewInstall or self.Upgrade:
self.config.WriteValue(
"version", ProgramDefaults.GENMON_VERSION, section="genloader"
)
if self.NewInstall:
pass
#self.LogInfo("Running one time maintenance check")
#self.FixPyOWMMaintIssues()
# TODO other version checks can be added here
self.version = ProgramDefaults.GENMON_VERSION
except Exception as e1:
self.LogInfo("Error in UpdateIfNeeded: " + str(e1), LogLine=True)
# ---------------------------------------------------------------------------
# Misc maint to perform when genmon is stopped
def Maintenance(self):
# rename templogs folder to sensordata
self.OldSensorLogPath = os.path.join(ConfigFilePath, "templogs")
if os.path.isdir(self.OldSensorLogPath):
self.NewSensorLogPath = os.path.join(ConfigFilePath, "sensordata")
os.rename(self.OldSensorLogPath, self.NewSensorLogPath)
try:
from pathlib import Path
directory = Path(self.NewSensorLogPath)
# 2. Use wildcard to find files and rename them in a loop
old_prefix = "templog"
new_prefix = "sensor"
for file_path in directory.glob(f"{old_prefix}*"):
if file_path.is_file():
new_name = file_path.name.removeprefix(old_prefix)
new_file_path = file_path.with_name(f"{new_prefix}{new_name}")
# Rename the file
file_path.rename(new_file_path)
self.LogError(f"Renamed: {file_path.name} -> {new_file_path.name}")
except Exception as e1:
self.LogError("Error renaming sensor data files: " + str(e1))
# ---------------------------------------------------------------------------
def GetConfig(self):
try:
Sections = self.config.GetSections()