forked from ycahome/pp-manager
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathplugin.py
More file actions
3236 lines (2778 loc) · 133 KB
/
Copy pathplugin.py
File metadata and controls
3236 lines (2778 loc) · 133 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
# PyPluginStore - PyPluginStore
#
# Author: adrighem, 2018
#
# Since (2018-02-23): Initial Version
#
"""
<plugin key="PP-MANAGER" name="PyPluginStore" author="adrighem" version="2.14.0" externallink="https://forum.domoticz.com/viewtopic.php?t=44626"> <!-- x-release-please-version -->
<description>
<h2>PyPluginStore</h2><br/>
This plugin manages other Domoticz Python plugins.<br/><br/>
<b>Usage:</b><br/>
1. Add this hardware to Domoticz.<br/>
2. Navigate to <b>Custom</b> -> <b>pypluginstore</b> in the top menu to manage your plugins.
</description>
<params>
<param field="Mode4" label="Auto Update" width="175px">
<options>
<option label="All" value="All"/>
<option label="All (NotifyOnly)" value="AllNotify" default="true"/>
<option label="None" value="None"/>
</options>
</param>
<param field="Mode6" label="Debug" width="75px">
<options>
<option label="True" value="Debug"/>
<option label="False" value="Normal" default="true" />
</options>
</param>
</params>
</plugin>
"""
import base64
import html
import os
import platform
import re
import subprocess
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import json
import shutil
from datetime import datetime, timedelta
import Domoticz
API_PAYLOAD_MAX_LENGTH = 2000
def parameter_get(parameters, key, default):
try:
return parameters.get(key, default)
except AttributeError:
try:
return parameters[key]
except Exception:
return default
class HostRuntime:
platform_name = "generic"
def __init__(self, parameters):
self.parameters = parameters
self._git_ownership_reported = set()
self._git_ownership_repair_attempted = set()
def parameter(self, key, default):
return parameter_get(self.parameters, key, default)
def plugin_home_folder(self):
return os.path.abspath(self.parameter("HomeFolder", str(os.getcwd()) + os.sep))
def current_plugin_folder(self):
return os.path.basename(os.path.normpath(self.plugin_home_folder()))
def plugins_dir(self):
return os.path.abspath(os.path.join(self.plugin_home_folder(), ".."))
def domoticz_dir(self):
return os.path.abspath(os.path.join(self.plugin_home_folder(), "..", ".."))
def shared_deps_dir(self):
return os.path.join(self.plugin_home_folder(), ".shared_deps")
def templates_dir(self):
return os.path.join(self.domoticz_dir(), "www", "templates")
def images_dir(self):
return os.path.join(self.domoticz_dir(), "www", "images")
def ui_html_source(self):
return os.path.join(self.plugin_home_folder(), "pypluginstore.html")
def ui_html_destination(self):
return os.path.join(self.templates_dir(), "pypluginstore.html")
def ui_asset_source(self, asset_name):
return os.path.join(self.plugin_home_folder(), asset_name)
def ui_asset_destination(self, asset_name):
return os.path.join(self.images_dir(), asset_name)
def requirements_file(self, plugin_key):
return os.path.join(self.resolve_plugin_dir(plugin_key), "requirements.txt")
def pending_operations_file(self):
return os.path.join(self.plugin_home_folder(), "pending_operations.json")
def restart_log_file(self):
return os.path.join(self.plugin_home_folder(), "restart_domoticz.log")
def self_update_log_file(self):
return os.path.join(self.plugin_home_folder(), "self_update.log")
def append_restart_log(self, message):
timestamp = datetime.now().isoformat(timespec="seconds")
try:
with open(self.restart_log_file(), "a", encoding="utf-8") as restart_log:
restart_log.write("[{}] {}\n".format(timestamp, message))
return True
except Exception as e:
Domoticz.Error(f"Failed to write Domoticz restart log: {e}")
return False
def get_git_env(self):
env = os.environ.copy()
env["GIT_TERMINAL_PROMPT"] = "0"
return env
def git_result_output(self, result):
if result is None:
return ""
return "\n".join(
part.strip()
for part in (getattr(result, "stderr", ""), getattr(result, "stdout", ""))
if part and part.strip()
)
def is_git_dubious_ownership(self, result):
output = self.git_result_output(result).lower()
return "detected dubious ownership in repository" in output
def git_ownership_repair_message(self, cwd):
return (
"Git refused the plugin repository because file ownership does not match the Domoticz user. "
"Trying to fix ownership for " + str(cwd) + "."
)
def git_ownership_failure_message(self, cwd):
location = " for " + str(cwd) if cwd else ""
return (
"Git refused the plugin repository because file ownership does not match the Domoticz user. "
"PyPluginStore could not fix ownership" + location + "; fix the plugin folder ownership manually."
)
def format_command(self, command):
return " ".join(str(part) for part in command)
def command_available(self, command):
return shutil.which(command) is not None
def command_can_run(self, command, timeout=10):
try:
result = subprocess.run(
command,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=timeout
)
return result.returncode == 0
except Exception:
return False
def _run_git_once(self, command, cwd, timeout=15):
try:
return subprocess.run(
command,
cwd=cwd,
env=self.get_git_env(),
capture_output=True,
text=True,
timeout=timeout
)
except subprocess.TimeoutExpired:
Domoticz.Error("Git command timed out in " + str(cwd) + ": " + self.format_command(command))
except OSError as e:
Domoticz.Error("Git ErrorNo:" + str(e.errno))
Domoticz.Error("Git StrError:" + str(e.strerror))
except Exception as e:
Domoticz.Error("Git command failed in " + str(cwd) + ": " + str(e))
return None
def is_managed_plugin_repository(self, path):
repo_dir = os.path.realpath(os.path.abspath(path))
plugins_dir = os.path.realpath(self.plugins_dir())
try:
inside_plugins_dir = os.path.commonpath([repo_dir, plugins_dir]) == plugins_dir
except ValueError:
inside_plugins_dir = False
return repo_dir != plugins_dir and inside_plugins_dir and os.path.isdir(os.path.join(repo_dir, ".git"))
def chown_path(self, path, uid, gid):
stat_result = os.lstat(path)
target_gid = stat_result.st_gid if gid == -1 else gid
if stat_result.st_uid == uid and stat_result.st_gid == target_gid:
return
try:
os.chown(path, uid, gid, follow_symlinks=False)
except TypeError:
if not os.path.islink(path):
os.chown(path, uid, gid)
def repair_git_repository_ownership(self, cwd):
if not hasattr(os, "chown") or not hasattr(os, "geteuid"):
return False
repo_dir = os.path.realpath(os.path.abspath(cwd))
if not self.is_managed_plugin_repository(repo_dir):
return False
uid = os.geteuid()
gid = os.getegid() if hasattr(os, "getegid") else -1
try:
for root, dirs, files in os.walk(repo_dir, topdown=True, followlinks=False):
self.chown_path(root, uid, gid)
for name in dirs:
self.chown_path(os.path.join(root, name), uid, gid)
for name in files:
self.chown_path(os.path.join(root, name), uid, gid)
return True
except Exception as e:
Domoticz.Debug("Could not fix Git repository ownership for " + repo_dir + ": " + str(e))
return False
def handle_git_ownership_failure(self, result, command, cwd, timeout):
repo_dir = os.path.realpath(os.path.abspath(cwd))
if repo_dir not in self._git_ownership_reported:
Domoticz.Error(self.git_ownership_repair_message(repo_dir))
self._git_ownership_reported.add(repo_dir)
if repo_dir in self._git_ownership_repair_attempted:
return result
self._git_ownership_repair_attempted.add(repo_dir)
if not self.repair_git_repository_ownership(repo_dir):
Domoticz.Error(self.git_ownership_failure_message(repo_dir))
return result
Domoticz.Log("Fixed plugin repository ownership; retrying Git command.")
retry_result = self._run_git_once(command, cwd, timeout=timeout)
if retry_result is not None and self.is_git_dubious_ownership(retry_result):
Domoticz.Error(self.git_ownership_failure_message(repo_dir))
return retry_result
def run_git(self, command, cwd, timeout=15):
result = self._run_git_once(command, cwd, timeout=timeout)
if result is not None and result.returncode != 0 and self.is_git_dubious_ownership(result):
return self.handle_git_ownership_failure(result, command, cwd, timeout)
return result
def make_web_readable(self, path):
return None
def validate_plugin_key(self, plugin_key):
plugin_key = str(plugin_key or "").strip()
if not plugin_key or plugin_key in (".", ".."):
raise ValueError("Invalid plugin key")
if plugin_key.startswith(".") or "/" in plugin_key or "\\" in plugin_key:
raise ValueError("Invalid plugin key")
if os.path.basename(plugin_key) != plugin_key:
raise ValueError("Invalid plugin key")
return plugin_key
def is_path_inside(self, target_path, base_path):
target_path = os.path.normcase(os.path.abspath(target_path))
base_path = os.path.normcase(os.path.abspath(base_path))
try:
return os.path.commonpath([target_path, base_path]) == base_path
except ValueError:
return False
def resolve_plugin_dir(self, plugin_key):
plugin_key = self.validate_plugin_key(plugin_key)
plugin_dir = os.path.abspath(os.path.join(self.plugins_dir(), plugin_key))
if not self.is_path_inside(plugin_dir, self.plugins_dir()):
raise ValueError("Invalid plugin path")
return plugin_dir
def restart_command_groups(self):
return []
def detached_popen_kwargs(self):
return {}
def build_restart_helper(self, command_groups, log_file, startup_delay=2, command_delay=3):
helper = """
import datetime
import subprocess
import time
import traceback
command_groups = __COMMAND_GROUPS__
log_file = __LOG_FILE__
startup_delay = __STARTUP_DELAY__
command_delay = __COMMAND_DELAY__
failures = []
def write_log(message):
timestamp = datetime.datetime.now().isoformat(timespec="seconds")
try:
with open(log_file, "a", encoding="utf-8") as restart_log:
restart_log.write("[{}] {}\\n".format(timestamp, message))
except Exception:
pass
def classify_restart_failure(failed_attempts):
combined_output = "\\n".join(
[
"\\n".join(
[
str(failure.get("stdout", "")),
str(failure.get("stderr", "")),
str(failure.get("exception", "")),
]
)
for failure in failed_attempts
]
).lower()
sudo_password_markers = (
"a password is required",
"password is required",
"a terminal is required to read the password",
"wachtwoord is verplicht",
)
permission_markers = (
"access denied",
"permission denied",
"not authorized",
"interactive authentication required",
"authentication is required",
)
service_missing_markers = (
"unit domoticz.service not found",
"domoticz.service not found",
"unrecognized service",
)
command_missing_markers = (
"no such file or directory",
"command not found",
"not found",
)
if any(marker in combined_output for marker in sudo_password_markers):
return (
"Domoticz restart failed: sudo requires an interactive password. "
"Configure a narrowly scoped NOPASSWD sudoers rule for the exact Domoticz restart command, or restart Domoticz manually."
)
if any(marker in combined_output for marker in permission_markers):
return (
"Domoticz restart failed: the Domoticz OS user is not allowed to restart domoticz.service. "
"Grant only the required service-restart permission, or restart Domoticz manually."
)
if any(marker in combined_output for marker in service_missing_markers):
return (
"Domoticz restart failed: domoticz.service was not found. "
"Check the Domoticz service name and restart it manually."
)
if any(marker in combined_output for marker in command_missing_markers):
return (
"Domoticz restart failed: one or more restart commands were not available on this host. "
"Check the Domoticz service manager and restart it manually."
)
return "Domoticz restart failed: all configured restart commands failed. Review the command output above."
write_log("restart helper started")
if startup_delay:
time.sleep(startup_delay)
for group_index, command_group in enumerate(command_groups, start=1):
write_log("trying command group {}".format(group_index))
success = True
for index, command in enumerate(command_group):
write_log("running: {}".format(subprocess.list2cmdline(command)))
try:
result = subprocess.run(
command,
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
timeout=20
)
write_log("return code: {}".format(result.returncode))
if result.stdout:
write_log("stdout: {}".format(result.stdout.strip()))
if result.stderr:
write_log("stderr: {}".format(result.stderr.strip()))
if result.returncode != 0:
failures.append({
"command": subprocess.list2cmdline(command),
"returncode": result.returncode,
"stdout": result.stdout,
"stderr": result.stderr,
})
success = False
break
if index < len(command_group) - 1 and command_delay:
time.sleep(command_delay)
except Exception as e:
write_log("exception: {}".format(e))
write_log(traceback.format_exc().strip())
failures.append({
"command": subprocess.list2cmdline(command),
"exception": str(e),
})
success = False
break
if success:
write_log("restart command group completed")
break
else:
write_log("all restart command groups failed")
write_log("failure summary: {}".format(classify_restart_failure(failures)))
"""
return (
helper
.replace("__COMMAND_GROUPS__", repr(command_groups))
.replace("__LOG_FILE__", repr(log_file))
.replace("__STARTUP_DELAY__", repr(startup_delay))
.replace("__COMMAND_DELAY__", repr(command_delay))
)
def restart_domoticz(self):
command_groups = self.restart_command_groups()
if not command_groups:
return False, "Domoticz restart is not configured for this platform."
helper = self.build_restart_helper(command_groups, self.restart_log_file())
self.append_restart_log("restart requested")
self.append_restart_log("launching Python restart helper: " + str(sys.executable))
popen_kwargs = {
"stdin": subprocess.DEVNULL,
"stdout": subprocess.DEVNULL,
"stderr": subprocess.DEVNULL,
}
popen_kwargs.update(self.detached_popen_kwargs())
try:
subprocess.Popen([sys.executable, "-c", helper], **popen_kwargs)
return True, "Domoticz restart requested"
except Exception as e:
Domoticz.Error(f"Failed to schedule Domoticz restart: {e}")
return False, str(e)
def git_failure_message(self, result, fallback, cwd=""):
if result is None:
return fallback
if self.is_git_dubious_ownership(result):
return self.git_ownership_failure_message(cwd)
output = (result.stderr or result.stdout or "").strip()
return output or fallback
def require_git_success(self, plugin_dir, command, timeout=15, fallback=None):
result = self.run_git(command, plugin_dir, timeout=timeout)
if result is None:
return None, fallback or "Git command failed: " + self.format_command(command)
if result.returncode != 0:
return None, self.git_failure_message(
result,
fallback or "Git command failed: " + self.format_command(command),
plugin_dir,
)
return result, ""
def validate_self_update_candidate(self, plugin_dir, target_ref):
required_paths = ("plugin.py", "plugin_core.py", "pypluginstore.html", "registry.json")
for candidate_path in required_paths:
_, message = self.require_git_success(
plugin_dir,
["git", "cat-file", "-e", f"{target_ref}:{candidate_path}"],
fallback="Self update target is missing " + candidate_path + ".",
)
if message:
return False, message
for python_path in ("plugin.py", "plugin_core.py"):
result, message = self.require_git_success(
plugin_dir,
["git", "show", f"{target_ref}:{python_path}"],
fallback="Could not read " + python_path + " from self update target.",
)
if message:
return False, message
try:
compile(result.stdout, python_path, "exec")
except SyntaxError as e:
return False, "Self update target has invalid Python syntax in " + python_path + ": " + str(e)
return True, ""
def preflight_self_update(self, plugin_dir):
if not self.command_available("git"):
return False, "Git is not available, so PyPluginStore cannot self-update.", {}
if not os.path.isdir(os.path.join(plugin_dir, ".git")):
return False, "PyPluginStore is not installed as a git repository.", {}
result, message = self.require_git_success(
plugin_dir,
["git", "rev-parse", "--is-inside-work-tree"],
fallback="Could not verify the PyPluginStore git repository.",
)
if message:
return False, message, {}
if result.stdout.strip().lower() != "true":
return False, "PyPluginStore folder is not a git work tree.", {}
result, message = self.require_git_success(
plugin_dir,
["git", "rev-parse", "--show-toplevel"],
fallback="Could not verify the PyPluginStore git work tree root.",
)
if message:
return False, message, {}
repo_root = os.path.normcase(os.path.abspath(result.stdout.strip()))
expected_root = os.path.normcase(os.path.abspath(plugin_dir))
if repo_root != expected_root:
return False, "PyPluginStore self-update must run from the repository root.", {}
result, message = self.require_git_success(
plugin_dir,
["git", "status", "--porcelain", "--untracked-files=no"],
fallback="Could not check PyPluginStore working tree status.",
)
if message:
return False, message, {}
if result.stdout.strip():
return False, "PyPluginStore has local tracked file changes; self-update refused.", {}
result, message = self.require_git_success(
plugin_dir,
["git", "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"],
fallback="PyPluginStore branch has no upstream; self-update refused.",
)
if message:
return False, message, {}
upstream_ref = result.stdout.strip()
if not upstream_ref:
return False, "PyPluginStore branch has no upstream; self-update refused.", {}
_, message = self.require_git_success(
plugin_dir,
["git", "fetch", "--prune"],
timeout=60,
fallback="Could not fetch PyPluginStore updates from the upstream remote.",
)
if message:
return False, message, {}
_, message = self.require_git_success(
plugin_dir,
["git", "rev-parse", "--verify", upstream_ref],
fallback="Could not verify the PyPluginStore upstream revision.",
)
if message:
return False, message, {}
_, message = self.require_git_success(
plugin_dir,
["git", "merge-base", "--is-ancestor", "HEAD", upstream_ref],
fallback="PyPluginStore local branch has diverged from upstream; self-update refused.",
)
if message:
return False, message, {}
result, message = self.require_git_success(
plugin_dir,
["git", "rev-list", "--left-right", "--count", "HEAD..." + upstream_ref],
fallback="Could not compare PyPluginStore with upstream.",
)
if message:
return False, message, {}
try:
ahead, behind = [int(value) for value in result.stdout.split()[:2]]
except Exception:
return False, "Could not parse PyPluginStore upstream comparison.", {}
if ahead:
return False, "PyPluginStore has local commits; self-update refused.", {}
if behind == 0:
return True, "PyPluginStore is already up-to-date.", {"already_current": True, "upstream_ref": upstream_ref}
valid_candidate, message = self.validate_self_update_candidate(plugin_dir, upstream_ref)
if not valid_candidate:
return False, message, {}
return True, "Self update pre-flight checks passed.", {
"already_current": False,
"upstream_ref": upstream_ref,
}
def build_self_update_helper(self, plugin_dir, log_file, upstream_ref, startup_delay=1):
helper = """
import datetime
import os
import subprocess
import time
import traceback
plugin_dir = __PLUGIN_DIR__
log_file = __LOG_FILE__
upstream_ref = __UPSTREAM_REF__
startup_delay = __STARTUP_DELAY__
def write_log(message):
timestamp = datetime.datetime.now().isoformat(timespec="seconds")
try:
with open(log_file, "a", encoding="utf-8") as update_log:
update_log.write("[{}] {}\\n".format(timestamp, message))
except Exception:
pass
write_log("self update helper started")
if startup_delay:
time.sleep(startup_delay)
if not os.path.isdir(os.path.join(plugin_dir, ".git")):
write_log("not a git repository: {}".format(plugin_dir))
raise SystemExit(1)
env = os.environ.copy()
env["GIT_TERMINAL_PROMPT"] = "0"
def run_command(command, timeout):
write_log("running: {}".format(subprocess.list2cmdline(command)))
try:
result = subprocess.run(
command,
cwd=plugin_dir,
env=env,
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
timeout=timeout
)
write_log("return code: {}".format(result.returncode))
if result.stdout:
write_log("stdout: {}".format(result.stdout.strip()))
if result.stderr:
write_log("stderr: {}".format(result.stderr.strip()))
if result.returncode != 0:
write_log("self update failed")
raise SystemExit(result.returncode)
return result
except Exception as e:
write_log("exception: {}".format(e))
write_log(traceback.format_exc().strip())
raise
status = run_command(["git", "status", "--porcelain", "--untracked-files=no"], 15)
if status.stdout.strip():
write_log("tracked files changed after pre-flight; self update refused")
raise SystemExit(1)
run_command(["git", "fetch", "--prune"], 60)
run_command(["git", "merge", "--ff-only", upstream_ref], 120)
write_log("self update completed")
"""
return (
helper
.replace("__PLUGIN_DIR__", repr(plugin_dir))
.replace("__LOG_FILE__", repr(log_file))
.replace("__UPSTREAM_REF__", repr(upstream_ref))
.replace("__STARTUP_DELAY__", repr(startup_delay))
)
def schedule_self_update(self, plugin_dir):
preflight_success, preflight_message, preflight_plan = self.preflight_self_update(plugin_dir)
if not preflight_success or preflight_plan.get("already_current"):
return preflight_success, preflight_message
helper = self.build_self_update_helper(
plugin_dir,
self.self_update_log_file(),
preflight_plan["upstream_ref"],
)
popen_kwargs = {
"stdin": subprocess.DEVNULL,
"stdout": subprocess.DEVNULL,
"stderr": subprocess.DEVNULL,
}
popen_kwargs.update(self.detached_popen_kwargs())
try:
subprocess.Popen([sys.executable, "-c", helper], **popen_kwargs)
return True, "Self update started after pre-flight checks. Reload the Plugin Store after Domoticz finishes reloading the plugin."
except Exception as e:
Domoticz.Error(f"Failed to schedule PyPluginStore self update: {e}")
return False, str(e)
def dependency_install_command(self, requirements_file, target_dir):
if self.command_available("uv") and sys.executable:
return ["uv", "pip", "install", "--python", sys.executable, "-r", requirements_file, "--target", target_dir]
if sys.executable and self.command_can_run([sys.executable, "-m", "pip", "--version"]):
return [sys.executable, "-m", "pip", "install", "-r", requirements_file, "--target", target_dir]
for command in ("pip3", "pip"):
if self.command_available(command):
return [command, "install", "-r", requirements_file, "--target", target_dir]
return None
def install_requirements(self, requirements_file, target_dir, plugin_key):
if not os.path.isfile(requirements_file):
Domoticz.Log("No requirements.txt found for plugin: " + plugin_key)
return True, "No requirements.txt found"
Domoticz.Log("requirements.txt found for plugin: " + plugin_key)
os.makedirs(target_dir, exist_ok=True)
install_command = self.dependency_install_command(requirements_file, target_dir)
if not install_command:
Domoticz.Log("Neither 'uv' nor a working pip command found. Skipping automatic dependency installation.")
Domoticz.Log(f"Please install dependencies manually from {requirements_file} into {target_dir}")
return False, "No Python dependency installer found"
Domoticz.Log("Installing dependencies using: " + self.format_command(install_command))
try:
pr = subprocess.Popen(install_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
out, error = pr.communicate()
if pr.returncode == 0:
Domoticz.Log("Dependencies installed successfully: " + out.strip())
return True, ""
Domoticz.Error("Error installing dependencies: " + error.strip())
return False, error.strip()
except Exception as e:
Domoticz.Error("Error running installation command: " + str(e))
return False, str(e)
def is_locked_file_error(self, error):
return False
def is_locked_file_message(self, message):
return False
class LinuxHostRuntime(HostRuntime):
platform_name = "linux"
def get_git_env(self):
env = super().get_git_env()
env["LANG"] = "en_US.UTF-8"
env["LC_ALL"] = "en_US.UTF-8"
return env
def make_web_readable(self, path):
try:
os.chmod(path, 0o644)
except Exception as e:
Domoticz.Debug(f"Could not update file permissions for {path}: {e}")
def restart_command_groups(self):
return [
[["systemctl", "restart", "domoticz.service"]],
[["sudo", "-n", "systemctl", "restart", "domoticz.service"]],
[["service", "domoticz", "restart"]],
[["sudo", "-n", "service", "domoticz", "restart"]],
]
def detached_popen_kwargs(self):
return {"start_new_session": True}
class WindowsHostRuntime(HostRuntime):
platform_name = "windows"
def windows_restart_script_file(self):
return os.path.join(self.plugin_home_folder(), "restart_domoticz.ps1")
def windows_restart_command_file(self):
return os.path.join(self.plugin_home_folder(), "restart_domoticz.cmd")
def windows_restart_probe_file(self):
return os.path.join(self.plugin_home_folder(), "restart_domoticz_probe.ps1")
def windows_restart_task_name(self):
return r"\PyPluginStore-Domoticz-Restart"
def schtasks_executable(self):
system_root = os.environ.get("SystemRoot", r"C:\Windows")
candidate = os.path.join(system_root, "System32", "schtasks.exe")
if os.path.isfile(candidate):
return candidate
return "schtasks.exe"
def powershell_executable(self):
system_root = os.environ.get("SystemRoot", r"C:\Windows")
candidate = os.path.join(system_root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe")
if os.path.isfile(candidate):
return candidate
return "powershell.exe"
def powershell_quote(self, value):
return "'" + str(value).replace("'", "''") + "'"
def powershell_encoded_command(self, script):
return base64.b64encode(script.encode("utf-16le")).decode("ascii")
def probe_powershell_file_execution(self):
probe_file = self.windows_restart_probe_file()
try:
with open(probe_file, "w", encoding="utf-8", newline="\r\n") as probe_script:
probe_script.write("Write-Output 'PyPluginStore PowerShell file execution probe'\n")
result = subprocess.run(
[
self.powershell_executable(),
"-NoProfile",
"-ExecutionPolicy",
"Bypass",
"-File",
probe_file,
],
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
timeout=10,
)
self.append_restart_log("PowerShell .ps1 probe return code: " + str(result.returncode))
if result.stdout:
self.append_restart_log("PowerShell .ps1 probe stdout: " + result.stdout.strip())
if result.stderr:
self.append_restart_log("PowerShell .ps1 probe stderr: " + result.stderr.strip())
if result.returncode != 0:
self.append_restart_log("PowerShell .ps1 execution probe failed")
if "running scripts is disabled" in str(result.stderr).lower():
self.append_restart_log("PowerShell execution policy blocks .ps1 files")
return False
return True
except Exception as e:
self.append_restart_log("PowerShell .ps1 probe exception: " + str(e))
return False
def probe_powershell_encoded_command(self):
script = (
"$LogFile = {log_file}\n"
"$timestamp = (Get-Date).ToString(\"s\")\n"
"Add-Content -LiteralPath $LogFile -Value \"[$timestamp] PowerShell EncodedCommand probe succeeded\" -Encoding UTF8\n"
"Write-Output 'PyPluginStore PowerShell EncodedCommand probe'\n"
).format(log_file=self.powershell_quote(self.restart_log_file()))
try:
result = subprocess.run(
[
self.powershell_executable(),
"-NoProfile",
"-NonInteractive",
"-ExecutionPolicy",
"Bypass",
"-EncodedCommand",
self.powershell_encoded_command(script),
],
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
timeout=10,
)
self.append_restart_log("PowerShell EncodedCommand probe return code: " + str(result.returncode))
if result.stdout:
self.append_restart_log("PowerShell EncodedCommand probe stdout: " + result.stdout.strip())
if result.stderr:
self.append_restart_log("PowerShell EncodedCommand probe stderr: " + result.stderr.strip())
return result.returncode == 0
except Exception as e:
self.append_restart_log("PowerShell EncodedCommand probe exception: " + str(e))
return False
def build_windows_restart_script(self):
script = r"""
$ErrorActionPreference = "Continue"
$LogFile = __LOG_FILE__
$ServiceNames = @(__SERVICE_NAMES__)
function Write-RestartLog {
param([string]$Message)
try {
$timestamp = (Get-Date).ToString("s")
Add-Content -LiteralPath $LogFile -Value "[$timestamp] $Message" -Encoding UTF8
} catch {
}
}
function Write-CommandOutput {
param($Output)
if ($null -eq $Output) {
return
}
foreach ($line in $Output) {
Write-RestartLog ("output: " + [string]$line)
}
}
function Invoke-ExternalCommand {
param([string[]]$Command)
Write-RestartLog ("running: " + ($Command -join " "))
try {
$commandArgs = @()
if ($Command.Count -gt 1) {
$commandArgs = $Command[1..($Command.Count - 1)]
}
$output = & $Command[0] @commandArgs 2>&1
$exitCode = $LASTEXITCODE
Write-CommandOutput $output
Write-RestartLog ("return code: " + $exitCode)
return ($exitCode -eq 0)
} catch {
Write-RestartLog ("exception: " + $_.Exception.Message)
return $false
}
}
Write-RestartLog "restart helper started"
Start-Sleep -Seconds 2
foreach ($serviceName in $ServiceNames) {
Write-RestartLog ("running: Restart-Service -Name " + $serviceName + " -Force")
try {
$output = Restart-Service -Name $serviceName -Force -ErrorAction Stop 2>&1
Write-CommandOutput $output
Write-RestartLog ("Restart-Service completed for " + $serviceName)
exit 0
} catch {
Write-RestartLog ("exception: " + $_.Exception.Message)
}
}
foreach ($serviceName in $ServiceNames) {
$stopOk = Invoke-ExternalCommand @("sc.exe", "stop", $serviceName)
Start-Sleep -Seconds 3
$startOk = Invoke-ExternalCommand @("sc.exe", "start", $serviceName)
if ($stopOk -and $startOk) {
Write-RestartLog ("sc stop/start completed for " + $serviceName)
exit 0
}
}
Write-RestartLog "all restart command groups failed"
exit 1
"""
service_names = [self.powershell_quote("Domoticz"), self.powershell_quote("domoticz")]
return (
script
.replace("__LOG_FILE__", self.powershell_quote(self.restart_log_file()))
.replace("__SERVICE_NAMES__", ", ".join(service_names))
)
def build_windows_restart_command(self, script_file):
powershell_command = (
"$ErrorActionPreference = 'Stop'; "
"$LogFile = {log_file}; "
"function Write-RestartLog {{ "
"param([string]$Message) "
"try {{ "
"$timestamp = (Get-Date).ToString('s'); "
"Add-Content -LiteralPath $LogFile -Value ('[{{0}}] {{1}}' -f $timestamp, $Message) -Encoding UTF8 "
"}} catch {{}} "
"}}; "
"try {{ "
"Write-RestartLog 'scheduled task helper started'; "
"$script = [System.IO.File]::ReadAllText({script_file}); "
"Invoke-Expression $script; "
"exit $LASTEXITCODE "
"}} catch {{ "
"Write-RestartLog ('scheduled task helper exception: ' + $_.Exception.Message); "
"exit 1 "
"}}"
).format(
log_file=self.powershell_quote(self.restart_log_file()),
script_file=self.powershell_quote(script_file),
)
return '@echo off\r\n"{}" -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command "{}"\r\n'.format(
self.powershell_executable(),
powershell_command,
)
def run_schtasks(self, args, timeout=20):
command = [self.schtasks_executable()] + args
self.append_restart_log("running: " + subprocess.list2cmdline(command))
try: