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
3992 lines (3449 loc) · 163 KB
/
Copy pathplugin.py
File metadata and controls
3992 lines (3449 loc) · 163 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.16.1" 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>
<param field="Mode7" label="Git Ownership Repair" width="175px">
<options>
<option label="Disabled" value="Disabled" default="true"/>
<option label="Enabled" value="Enabled"/>
</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, timezone
import Domoticz
API_PAYLOAD_MAX_LENGTH = 2000
SELF_UPDATE_STARTUP_DELAY_SECONDS = 5
DEFAULT_GIT_HOST = "github.com"
SUPPORTED_GIT_HOSTS = ("github.com", "gitlab.com", "codeberg.org")
REPOSITORY_PATH_STOP_PARTS = {
"-",
"blob",
"commits",
"issues",
"pulls",
"raw",
"releases",
"src",
"tree",
}
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_safe_directory_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 self_update_state_file(self):
return os.path.join(self.plugin_home_folder(), "self_update_state.json")
def git_index_lock_file(self, plugin_dir):
return os.path.join(plugin_dir, ".git", "index.lock")
def has_git_index_lock(self, plugin_dir):
return os.path.exists(self.git_index_lock_file(plugin_dir))
def git_index_lock_message(self, plugin_dir):
lock_file = self.git_index_lock_file(plugin_dir)
return (
"PyPluginStore git index lock exists at " + lock_file
+ "; stop any running git command, then remove the lock file if it is stale and retry self-update."
)
def utc_timestamp(self):
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def read_self_update_state(self):
default_state = {
"operation": "self_update",
"phase": "idle",
"message": "",
"log_file": self.self_update_log_file(),
}
state_file = self.self_update_state_file()
if not os.path.isfile(state_file):
return default_state
try:
with open(state_file, "r", encoding="utf-8") as f:
state = json.load(f)
if not isinstance(state, dict):
raise ValueError("state file does not contain a JSON object")
default_state.update(state)
default_state["operation"] = "self_update"
default_state["log_file"] = default_state.get("log_file") or self.self_update_log_file()
return default_state
except Exception as e:
default_state.update({
"phase": "stale_unknown",
"message": "Could not read self-update state: " + str(e),
})
return default_state
def write_json_atomic(self, path, data):
os.makedirs(os.path.dirname(path), exist_ok=True)
tmp_path = path + ".tmp"
with open(tmp_path, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, sort_keys=True)
f.write("\n")
os.replace(tmp_path, path)
def write_self_update_state(self, phase, message="", previous_state=None, **fields):
now = self.utc_timestamp()
state = dict(previous_state or {})
state.setdefault("created_at", now)
state.update({
"operation": "self_update",
"phase": phase,
"message": message,
"updated_at": now,
"log_file": self.self_update_log_file(),
})
for key, value in fields.items():
if value is not None:
state[key] = value
self.write_json_atomic(self.self_update_state_file(), state)
return state
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 username_for_uid(self, uid):
try:
import pwd
return pwd.getpwuid(uid).pw_name
except Exception:
return ""
def groupname_for_gid(self, gid):
try:
import grp
return grp.getgrgid(gid).gr_name
except Exception:
return ""
def format_owner(self, uid, gid):
user = self.username_for_uid(uid)
group = self.groupname_for_gid(gid)
numeric = str(uid) + ":" + str(gid)
if user and group:
return user + ":" + group + " (" + numeric + ")"
return numeric
def path_owner_description(self, path):
if not path:
return ""
try:
stat_result = os.stat(path)
return self.format_owner(stat_result.st_uid, stat_result.st_gid)
except Exception:
return ""
def process_owner_description(self):
if not hasattr(os, "geteuid"):
return ""
uid = os.geteuid()
gid = os.getegid() if hasattr(os, "getegid") else -1
return self.format_owner(uid, gid)
def git_ownership_guidance(self, cwd):
details = []
expected_owner = self.process_owner_description()
current_owner = self.path_owner_description(cwd)
if current_owner:
details.append("Current owner: " + current_owner + ".")
if expected_owner:
details.append("Expected owner: " + expected_owner + " (the Domoticz process user).")
return " ".join(details)
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_repair_enabled(self):
value = str(self.parameter("Mode7", "Disabled") or "").strip().lower()
return value in ("enabled", "true", "yes", "allow")
def git_ownership_failure_message(self, cwd):
location = " for " + str(cwd) if cwd else ""
guidance = self.git_ownership_guidance(cwd)
guidance = " " + guidance if guidance else ""
if not self.git_ownership_repair_enabled():
return (
"Git refused the plugin repository because file ownership does not match the Domoticz user. "
"PyPluginStore will not change file ownership automatically" + location + "; "
"fix the plugin folder ownership manually if Git still fails."
+ guidance
)
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."
+ guidance
)
def has_safe_directory_option(self, command):
return any(str(part).startswith("safe.directory=") for part in command)
def safe_git_command(self, command, cwd):
safe_command = list(command)
repo_dir = os.path.realpath(os.path.abspath(cwd))
if len(safe_command) > 0 and safe_command[0] == "git" and not self.has_safe_directory_option(safe_command):
safe_command.insert(1, "-c")
safe_command.insert(2, "safe.directory=" + repo_dir)
return safe_command
def should_use_safe_git_directory(self, command, cwd):
return (
len(command) > 0
and command[0] == "git"
and self.is_managed_plugin_repository(cwd)
)
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))
safe_command = self.safe_git_command(command, cwd)
if safe_command != list(command):
if repo_dir not in self._git_ownership_safe_directory_reported:
Domoticz.Log("Git refused the plugin repository due to file ownership; retrying with safe.directory bypass.")
self._git_ownership_safe_directory_reported.add(repo_dir)
retry_result = self._run_git_once(safe_command, cwd, timeout=timeout)
if retry_result is not None and not self.is_git_dubious_ownership(retry_result):
return retry_result
if repo_dir in self._git_ownership_repair_attempted:
return result
self._git_ownership_repair_attempted.add(repo_dir)
if not self.git_ownership_repair_enabled():
if repo_dir not in self._git_ownership_reported:
Domoticz.Error(self.git_ownership_failure_message(repo_dir))
self._git_ownership_reported.add(repo_dir)
return result
# Fallback to original chown repair if safe.directory fails
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 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):
actual_command = command
if self.should_use_safe_git_directory(command, cwd):
actual_command = self.safe_git_command(command, cwd)
result = self._run_git_once(actual_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, actual_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 log_git_result(self, label, result):
if not label or result is None:
return
if result.stdout:
Domoticz.Debug("Git " + label + " Response:" + result.stdout.strip())
if result.stderr and not self.is_git_dubious_ownership(result):
Domoticz.Debug("Git " + label + " Error:" + result.stderr.strip())
def require_git_success(self, plugin_dir, command, timeout=15, fallback=None, log_label=""):
result = self.run_git(command, plugin_dir, timeout=timeout)
self.log_git_result(log_label, result)
fallback = fallback or "Git command failed: " + self.format_command(command)
if result is None:
return result, fallback
if result.returncode != 0:
return result, self.git_failure_message(
result,
fallback,
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.", {}
if self.has_git_index_lock(plugin_dir):
return False, self.git_index_lock_message(plugin_dir), {}
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, {}
current_result, message = self.require_git_success(
plugin_dir,
["git", "rev-parse", "--verify", "HEAD"],
fallback="Could not verify the current PyPluginStore revision.",
)
if message:
return False, message, {}
current_commit = current_result.stdout.strip().splitlines()[0] if current_result.stdout.strip() else ""
target_result, 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, {}
target_commit = target_result.stdout.strip().splitlines()[0] if target_result.stdout.strip() else ""
_, 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,
"current_commit": current_commit,
"target_commit": target_commit,
}
valid_candidate, message = self.validate_self_update_candidate(plugin_dir, upstream_ref)
if not valid_candidate:
return False, message, {}
if self.has_git_index_lock(plugin_dir):
return False, self.git_index_lock_message(plugin_dir), {}
return True, "Self update pre-flight checks passed.", {
"already_current": False,
"upstream_ref": upstream_ref,
"current_commit": current_commit,
"target_commit": target_commit,
}
def build_self_update_helper(
self,
plugin_dir,
log_file,
upstream_ref,
state_file=None,
job_id="",
state_template=None,
startup_delay=SELF_UPDATE_STARTUP_DELAY_SECONDS,
):
state_file = state_file or self.self_update_state_file()
state_template = dict(state_template or {})
helper = """
import datetime
import json
import os
import subprocess
import time
import traceback
plugin_dir = __PLUGIN_DIR__
log_file = __LOG_FILE__
upstream_ref = __UPSTREAM_REF__
state_file = __STATE_FILE__
job_id = __JOB_ID__
state_template = __STATE_TEMPLATE__
startup_delay = __STARTUP_DELAY__
safe_directory = os.path.realpath(os.path.abspath(plugin_dir))
index_lock_file = os.path.join(plugin_dir, ".git", "index.lock")
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
def write_state(phase, message="", **extra):
timestamp = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
state = dict(state_template)
state.setdefault("created_at", timestamp)
state.update({
"operation": "self_update",
"phase": phase,
"message": message,
"updated_at": timestamp,
"log_file": log_file,
"job_id": job_id,
"upstream_ref": upstream_ref,
})
state.update(extra)
try:
os.makedirs(os.path.dirname(state_file), exist_ok=True)
tmp_state_file = state_file + ".tmp"
with open(tmp_state_file, "w", encoding="utf-8") as state_handle:
json.dump(state, state_handle, indent=2, sort_keys=True)
state_handle.write("\\n")
os.replace(tmp_state_file, state_file)
except Exception as e:
write_log("failed to write state: {}".format(e))
write_log("self update helper started")
write_state("running", "Self update helper is running.")
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))
write_state("failed", "PyPluginStore is not installed as a git repository.")
raise SystemExit(1)
env = os.environ.copy()
env["GIT_TERMINAL_PROMPT"] = "0"
def git_command(*args):
return ["git", "-c", "safe.directory=" + safe_directory] + list(args)
def git_index_lock_message():
return (
"PyPluginStore git index lock exists at {}; "
"stop any running git command, then remove the lock file if it is stale and retry self-update."
).format(index_lock_file)
def refuse_git_index_lock():
if os.path.exists(index_lock_file):
message = git_index_lock_message()
write_log(message)
write_state("failed", message)
raise SystemExit(1)
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")
write_state(
"failed",
"Self update command failed: {}".format(subprocess.list2cmdline(command)),
return_code=result.returncode
)
raise SystemExit(result.returncode)
return result
except Exception as e:
write_log("exception: {}".format(e))
write_log(traceback.format_exc().strip())
write_state("failed", "Self update helper exception: {}".format(e))
raise
refuse_git_index_lock()
status = run_command(git_command("status", "--porcelain", "--untracked-files=no"), 15)
if status.stdout.strip():
write_log("tracked files changed after pre-flight; self update refused")
write_state("failed", "Tracked files changed after pre-flight; self update refused.")
raise SystemExit(1)
run_command(git_command("fetch", "--prune"), 60)
refuse_git_index_lock()
run_command(git_command("merge", "--ff-only", upstream_ref), 120)
head = run_command(git_command("rev-parse", "--short", "HEAD"), 15).stdout.strip()
write_log("self update completed")
write_state(
"applied_needs_reload",
"Self update completed. Reload the Plugin Store after Domoticz finishes reloading the plugin.",
applied_commit=head
)
"""
return (
helper
.replace("__PLUGIN_DIR__", repr(plugin_dir))
.replace("__LOG_FILE__", repr(log_file))
.replace("__UPSTREAM_REF__", repr(upstream_ref))
.replace("__STATE_FILE__", repr(state_file))
.replace("__JOB_ID__", repr(job_id))
.replace("__STATE_TEMPLATE__", repr(state_template))
.replace("__STARTUP_DELAY__", repr(startup_delay))
)
def schedule_self_update(self, plugin_dir):
Domoticz.Log("Starting PyPluginStore self-update pre-flight.")
preflight_success, preflight_message, preflight_plan = self.preflight_self_update(plugin_dir)
if not preflight_success or preflight_plan.get("already_current"):
phase = "confirmed" if preflight_plan.get("already_current") else "preflight_failed"
state = self.write_self_update_state(
phase,
preflight_message,
job_id=self.utc_timestamp().replace("-", "").replace(":", ""),
upstream_ref=preflight_plan.get("upstream_ref", ""),
current_commit=preflight_plan.get("current_commit", ""),
target_commit=preflight_plan.get("target_commit", ""),
)
if preflight_success: