sinapsis_cli 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.
- sinapsis_cli/__init__.py +13 -0
- sinapsis_cli/commands/__init__.py +0 -0
- sinapsis_cli/commands/cloud/__init__.py +0 -0
- sinapsis_cli/commands/cloud/_agent_selection.py +112 -0
- sinapsis_cli/commands/cloud/_secrets_render.py +15 -0
- sinapsis_cli/commands/cloud/_webhook_render.py +19 -0
- sinapsis_cli/commands/cloud/agents.py +137 -0
- sinapsis_cli/commands/cloud/api_keys.py +155 -0
- sinapsis_cli/commands/cloud/files.py +135 -0
- sinapsis_cli/commands/cloud/jobs.py +532 -0
- sinapsis_cli/commands/cloud/packages.py +164 -0
- sinapsis_cli/commands/cloud/schedules.py +392 -0
- sinapsis_cli/commands/cloud/secrets.py +96 -0
- sinapsis_cli/commands/cloud/templates.py +95 -0
- sinapsis_cli/commands/cloud/webhooks.py +156 -0
- sinapsis_cli/commands/common/__init__.py +0 -0
- sinapsis_cli/commands/common/auth.py +219 -0
- sinapsis_cli/commands/common/profiles.py +156 -0
- sinapsis_cli/commands/common/telemetry.py +150 -0
- sinapsis_cli/commands/local_api/__init__.py +0 -0
- sinapsis_cli/commands/local_api/jobs.py +284 -0
- sinapsis_cli/commands/local_venv/__init__.py +0 -0
- sinapsis_cli/commands/local_venv/_templates_render.py +56 -0
- sinapsis_cli/commands/local_venv/jobs.py +76 -0
- sinapsis_cli/commands/local_venv/templates.py +47 -0
- sinapsis_cli/composition.py +215 -0
- sinapsis_cli/config.py +446 -0
- sinapsis_cli/execution.py +77 -0
- sinapsis_cli/main.py +185 -0
- sinapsis_cli/main_multi.py +152 -0
- sinapsis_cli/shared/__init__.py +3 -0
- sinapsis_cli/shared/jobs.py +134 -0
- sinapsis_cli/shared/terminal.py +8 -0
- sinapsis_cli/shared/writer.py +427 -0
- sinapsis_cli/state.py +310 -0
- sinapsis_cli/telemetry/__init__.py +7 -0
- sinapsis_cli/telemetry/collector.py +84 -0
- sinapsis_cli/telemetry/core.py +331 -0
- sinapsis_cli/telemetry/scheduler.py +234 -0
- sinapsis_cli/telemetry/transport.py +150 -0
- sinapsis_cli-1.0.0.dist-info/METADATA +386 -0
- sinapsis_cli-1.0.0.dist-info/RECORD +46 -0
- sinapsis_cli-1.0.0.dist-info/WHEEL +4 -0
- sinapsis_cli-1.0.0.dist-info/entry_points.txt +5 -0
- sinapsis_cli-1.0.0.dist-info/licenses/LICENSE-APACHE +202 -0
- sinapsis_cli-1.0.0.dist-info/licenses/LICENSE-MIT +21 -0
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
"""Consent, safe telemetry events, and bounded local history for Sinapsis CLI.
|
|
2
|
+
|
|
3
|
+
This module intentionally has no HTTP client or telemetry ingestion URL. Collection
|
|
4
|
+
is disabled by default. Never pass command arguments or job payloads into events.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import re
|
|
10
|
+
import sqlite3
|
|
11
|
+
import sys
|
|
12
|
+
import time
|
|
13
|
+
from datetime import UTC, datetime
|
|
14
|
+
from importlib import metadata
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any
|
|
17
|
+
from uuid import uuid4
|
|
18
|
+
|
|
19
|
+
from platformdirs import user_config_path, user_state_path
|
|
20
|
+
|
|
21
|
+
SCHEMA_VERSION = 1
|
|
22
|
+
MAX_EVENTS = 200
|
|
23
|
+
MAX_PENDING = 10_000
|
|
24
|
+
RETENTION_DAYS = 30
|
|
25
|
+
INVENTORY_INTERVAL_SECONDS = 24 * 60 * 60
|
|
26
|
+
|
|
27
|
+
# Only these literal, fixed command names may enter a command telemetry payload.
|
|
28
|
+
# Never use unrecognized positional arguments, even if they look harmless.
|
|
29
|
+
_ALLOWED_COMMANDS: dict[str, frozenset[str]] = {
|
|
30
|
+
"jobs": frozenset({"run", "status", "result", "stream", "cancel", "history", "clear", "list", "refresh"}),
|
|
31
|
+
"templates": frozenset({"list", "show", "inspect", "search", "run", "info"}),
|
|
32
|
+
"agents": frozenset({"list", "show", "run", "create", "register", "delete", "versions"}),
|
|
33
|
+
"files": frozenset({"list", "upload", "download", "delete", "search"}),
|
|
34
|
+
"api-keys": frozenset({"list", "create", "revoke", "permissions"}),
|
|
35
|
+
"webhooks": frozenset({"list", "create", "delete", "update"}),
|
|
36
|
+
"schedules": frozenset({"list", "create", "show", "delete", "pause", "resume", "history"}),
|
|
37
|
+
"profiles": frozenset({"list", "create", "show", "delete", "default"}),
|
|
38
|
+
"secrets": frozenset({"list", "create", "delete", "set"}),
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
_FIELD_DESCRIPTIONS: dict[str, str] = {
|
|
42
|
+
"schema_version": "Event schema version (integer).",
|
|
43
|
+
"event_id": "Random per-event UUID; not a persistent user/device identifier.",
|
|
44
|
+
"timestamp": "UTC time when the event was collected.",
|
|
45
|
+
"event_type": "One of cli.command or environment.inventory.",
|
|
46
|
+
"source": "cli only (or a separate local-api container journal).",
|
|
47
|
+
"backend": "Execution backend category, never API URL/profile name.",
|
|
48
|
+
"command": "Whitelisted command category, not flags or argument values.",
|
|
49
|
+
"outcome": "success or error; no error messages or stack traces.",
|
|
50
|
+
"duration_ms": "Rounded CLI command duration, capped at 24 hours.",
|
|
51
|
+
"python": "Python major.minor version only.",
|
|
52
|
+
"cli_version": "Installed Sinapsis CLI distribution version if available.",
|
|
53
|
+
"environment": "cli-runtime or local-venv; never the environment path.",
|
|
54
|
+
"distributions": "Installed sinapsis* distribution names and versions only.",
|
|
55
|
+
"distribution_count": "Number of matching installed distributions before truncation.",
|
|
56
|
+
"truncated": "Whether the inventory was truncated to the first 100 distributions.",
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def data_fields() -> dict[str, str]:
|
|
61
|
+
"""Return descriptions of every field that may be collected."""
|
|
62
|
+
return dict(_FIELD_DESCRIPTIONS)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def config_dir() -> Path:
|
|
66
|
+
"""Return the user-level directory for telemetry consent."""
|
|
67
|
+
override = os.environ.get("SINAPSIS_TELEMETRY_CONFIG_DIR")
|
|
68
|
+
return Path(override).expanduser() if override else user_config_path("sinapsis")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def state_dir() -> Path:
|
|
72
|
+
"""Return the user-level directory holding private telemetry event history."""
|
|
73
|
+
override = os.environ.get("SINAPSIS_TELEMETRY_STATE_DIR")
|
|
74
|
+
return Path(override).expanduser() if override else user_state_path("sinapsis")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _consent_path() -> Path:
|
|
78
|
+
return config_dir() / "telemetry.json"
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _db_path() -> Path:
|
|
82
|
+
return state_dir() / "telemetry.sqlite3"
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def stored_consent() -> bool:
|
|
86
|
+
"""Read opt-in state; missing, invalid, or inaccessible files mean disabled."""
|
|
87
|
+
try:
|
|
88
|
+
content = json.loads(_consent_path().read_text(encoding="utf-8"))
|
|
89
|
+
except (OSError, ValueError):
|
|
90
|
+
return False
|
|
91
|
+
return isinstance(content, dict) and content.get("enabled") is True
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def set_consent(enabled: bool) -> None:
|
|
95
|
+
"""Atomically persist an opt-in/out choice to user-only configuration."""
|
|
96
|
+
folder = config_dir()
|
|
97
|
+
folder.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
98
|
+
target = _consent_path()
|
|
99
|
+
tmp = folder / f".telemetry-{uuid4().hex}.tmp"
|
|
100
|
+
try:
|
|
101
|
+
fd = os.open(tmp, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
|
|
102
|
+
with os.fdopen(fd, "w", encoding="utf-8") as stream:
|
|
103
|
+
json.dump({"enabled": enabled, "schema_version": SCHEMA_VERSION}, stream)
|
|
104
|
+
stream.write("\n")
|
|
105
|
+
os.replace(tmp, target)
|
|
106
|
+
if os.name == "posix":
|
|
107
|
+
target.chmod(0o600)
|
|
108
|
+
finally:
|
|
109
|
+
tmp.unlink(missing_ok=True)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def override_state() -> str | None:
|
|
113
|
+
"""Return the operator's environment override, if explicitly present."""
|
|
114
|
+
return os.environ.get("SINAPSIS_TELEMETRY")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def collection_enabled() -> bool:
|
|
118
|
+
"""Determine effective consent; invalid overrides fail closed."""
|
|
119
|
+
override = override_state()
|
|
120
|
+
if override is not None:
|
|
121
|
+
return override.strip() == "1"
|
|
122
|
+
return stored_consent()
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _connect(*, create: bool = False) -> sqlite3.Connection | None:
|
|
126
|
+
"""Connect to the local journal without creating files on read-only commands."""
|
|
127
|
+
path = _db_path()
|
|
128
|
+
if not path.exists() and not create:
|
|
129
|
+
return None
|
|
130
|
+
if create:
|
|
131
|
+
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
132
|
+
connection = sqlite3.connect(path, timeout=0.1)
|
|
133
|
+
if create:
|
|
134
|
+
if os.name == "posix":
|
|
135
|
+
path.chmod(0o600)
|
|
136
|
+
connection.execute(
|
|
137
|
+
"CREATE TABLE IF NOT EXISTS events ("
|
|
138
|
+
"event_id TEXT PRIMARY KEY, timestamp TEXT NOT NULL, "
|
|
139
|
+
"event_type TEXT NOT NULL, payload TEXT NOT NULL, sent_at TEXT)"
|
|
140
|
+
)
|
|
141
|
+
connection.execute("CREATE INDEX IF NOT EXISTS events_time ON events(timestamp)")
|
|
142
|
+
connection.commit()
|
|
143
|
+
return connection
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def new_event(event_type: str, **fields: Any) -> dict[str, Any]:
|
|
147
|
+
"""Construct a typed, closed-schema event without user or device identifiers."""
|
|
148
|
+
if event_type not in {"cli.command", "environment.inventory"}:
|
|
149
|
+
raise ValueError("Unsupported telemetry event")
|
|
150
|
+
extras = set(fields) - set(_FIELD_DESCRIPTIONS)
|
|
151
|
+
if extras:
|
|
152
|
+
raise ValueError("Unknown telemetry fields")
|
|
153
|
+
return {
|
|
154
|
+
"schema_version": SCHEMA_VERSION,
|
|
155
|
+
"event_id": str(uuid4()),
|
|
156
|
+
"timestamp": datetime.now(UTC).isoformat(timespec="seconds"),
|
|
157
|
+
"event_type": event_type,
|
|
158
|
+
"source": "cli",
|
|
159
|
+
**fields,
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def append_event(event: dict[str, Any]) -> bool:
|
|
164
|
+
"""Store an event only with effective consent; never send it over the network."""
|
|
165
|
+
if not collection_enabled():
|
|
166
|
+
return False
|
|
167
|
+
if event.get("event_type") not in {"cli.command", "environment.inventory"}:
|
|
168
|
+
return False
|
|
169
|
+
if set(event) - set(_FIELD_DESCRIPTIONS):
|
|
170
|
+
return False
|
|
171
|
+
try:
|
|
172
|
+
connection = _connect(create=True)
|
|
173
|
+
assert connection is not None
|
|
174
|
+
with connection:
|
|
175
|
+
pending = connection.execute("SELECT COUNT(*) FROM events WHERE sent_at IS NULL").fetchone()[0]
|
|
176
|
+
if pending >= MAX_PENDING:
|
|
177
|
+
return False # Bounded disk: report backlog; never delete unsent events.
|
|
178
|
+
connection.execute(
|
|
179
|
+
"INSERT INTO events (event_id, timestamp, event_type, payload) VALUES (?, ?, ?, ?)",
|
|
180
|
+
(event["event_id"], event["timestamp"], event["event_type"], json.dumps(event, sort_keys=True)),
|
|
181
|
+
)
|
|
182
|
+
# Only acknowledged history is subject to retention. Pending events
|
|
183
|
+
# MUST survive retries, outages and CLI restarts without silent loss.
|
|
184
|
+
expiry = datetime.fromtimestamp(time.time() - RETENTION_DAYS * 86400, UTC).isoformat()
|
|
185
|
+
connection.execute("DELETE FROM events WHERE sent_at IS NOT NULL AND timestamp < ?", (expiry,))
|
|
186
|
+
connection.execute(
|
|
187
|
+
"DELETE FROM events WHERE event_id IN ("
|
|
188
|
+
"SELECT event_id FROM events WHERE sent_at IS NOT NULL ORDER BY timestamp DESC, rowid DESC LIMIT -1 OFFSET ?) ",
|
|
189
|
+
(MAX_EVENTS,),
|
|
190
|
+
)
|
|
191
|
+
connection.close()
|
|
192
|
+
return True
|
|
193
|
+
except (OSError, sqlite3.Error, KeyError, TypeError, ValueError):
|
|
194
|
+
# Telemetry must never break an ordinary Sinapsis operation.
|
|
195
|
+
return False
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def recent_events(limit: int = 10) -> list[dict[str, Any]]:
|
|
199
|
+
"""Read bounded local event history, newest first, without any side effects."""
|
|
200
|
+
try:
|
|
201
|
+
connection = _connect()
|
|
202
|
+
if connection is None:
|
|
203
|
+
return []
|
|
204
|
+
with connection:
|
|
205
|
+
rows = connection.execute(
|
|
206
|
+
"SELECT payload FROM events ORDER BY timestamp DESC, rowid DESC LIMIT ?",
|
|
207
|
+
(max(1, min(limit, MAX_EVENTS)),),
|
|
208
|
+
).fetchall()
|
|
209
|
+
connection.close()
|
|
210
|
+
return [json.loads(row[0]) for row in rows]
|
|
211
|
+
except (OSError, sqlite3.Error, ValueError):
|
|
212
|
+
return []
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def clear_events() -> int:
|
|
216
|
+
"""Permanently delete the local telemetry journal; leave consent unchanged."""
|
|
217
|
+
try:
|
|
218
|
+
connection = _connect()
|
|
219
|
+
if connection is None:
|
|
220
|
+
return 0
|
|
221
|
+
with connection:
|
|
222
|
+
count = connection.execute("SELECT COUNT(*) FROM events").fetchone()[0]
|
|
223
|
+
connection.execute("DELETE FROM events")
|
|
224
|
+
connection.close()
|
|
225
|
+
return int(count)
|
|
226
|
+
except (OSError, sqlite3.Error):
|
|
227
|
+
return 0
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _cli_version() -> str:
|
|
231
|
+
try:
|
|
232
|
+
return metadata.version("sinapsis-cli")
|
|
233
|
+
except metadata.PackageNotFoundError:
|
|
234
|
+
return "unknown"
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def safe_command(arguments: list[str]) -> str | None:
|
|
238
|
+
"""Classify only known fixed commands; NEVER return user-provided values."""
|
|
239
|
+
tokens = [token for token in arguments if not token.startswith("-")]
|
|
240
|
+
if not tokens:
|
|
241
|
+
return None
|
|
242
|
+
if tokens[0] == "config":
|
|
243
|
+
return None # Consent and information queries are deliberately excluded.
|
|
244
|
+
if tokens[0] == "configure":
|
|
245
|
+
return "configure"
|
|
246
|
+
commands = _ALLOWED_COMMANDS.get(tokens[0])
|
|
247
|
+
if commands is None:
|
|
248
|
+
return "other"
|
|
249
|
+
if len(tokens) < 2 or tokens[1] not in commands:
|
|
250
|
+
return f"{tokens[0]}.other"
|
|
251
|
+
return f"{tokens[0]}.{tokens[1]}"
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def record_cli_invocation(arguments: list[str], *, backend: str, outcome: str, duration_ms: int) -> None:
|
|
255
|
+
"""Record the command category, not command-line arguments or exception text."""
|
|
256
|
+
if not collection_enabled():
|
|
257
|
+
return
|
|
258
|
+
command = safe_command(arguments)
|
|
259
|
+
if command is None:
|
|
260
|
+
return
|
|
261
|
+
append_event(
|
|
262
|
+
new_event(
|
|
263
|
+
"cli.command",
|
|
264
|
+
backend=backend if backend in {"cloud", "local-api", "local-venv"} else "other",
|
|
265
|
+
command=command,
|
|
266
|
+
outcome="success" if outcome == "success" else "error",
|
|
267
|
+
duration_ms=max(0, min(round(duration_ms / 100) * 100, 86400000)),
|
|
268
|
+
python=f"{sys.version_info.major}.{sys.version_info.minor}",
|
|
269
|
+
cli_version=_cli_version(),
|
|
270
|
+
)
|
|
271
|
+
)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _distribution_paths(venv: Path | None) -> list[str] | None:
|
|
275
|
+
"""Select site-packages directories using filesystem metadata; do not execute Python."""
|
|
276
|
+
if venv is None:
|
|
277
|
+
return None # importlib.metadata uses the running Python environment.
|
|
278
|
+
if not (venv / "pyvenv.cfg").is_file():
|
|
279
|
+
return []
|
|
280
|
+
candidates = [venv / "Lib" / "site-packages", *sorted((venv / "lib").glob("python*/site-packages"))]
|
|
281
|
+
return [str(path) for path in candidates if path.is_dir()]
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def inventory_snapshot(*, venv: Path | None = None) -> dict[str, Any]:
|
|
285
|
+
"""Scan only installed Sinapsis distributions in the selected environment.
|
|
286
|
+
|
|
287
|
+
The scan uses installed wheel metadata, not imports or subprocesses, and
|
|
288
|
+
never collects installed non-Sinapsis packages or the environment path.
|
|
289
|
+
"""
|
|
290
|
+
paths = _distribution_paths(venv)
|
|
291
|
+
distributions: dict[str, str] = {}
|
|
292
|
+
if paths != []:
|
|
293
|
+
installed = metadata.distributions() if paths is None else metadata.distributions(path=paths)
|
|
294
|
+
for distribution in installed:
|
|
295
|
+
name = distribution.metadata.get("Name", "")
|
|
296
|
+
normalized = re.sub(r"[-_.]+", "-", name).lower()
|
|
297
|
+
if normalized == "sinapsis" or normalized.startswith("sinapsis-"):
|
|
298
|
+
distributions[normalized[:120]] = str(distribution.version)[:64]
|
|
299
|
+
names = sorted(distributions)
|
|
300
|
+
return {
|
|
301
|
+
"environment": "local-venv" if venv is not None else "cli-runtime",
|
|
302
|
+
"distributions": [{"name": name, "version": distributions[name]} for name in names[:100]],
|
|
303
|
+
"distribution_count": len(names),
|
|
304
|
+
"truncated": len(names) > 100,
|
|
305
|
+
"python": f"{sys.version_info.major}.{sys.version_info.minor}",
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def record_inventory_if_due(*, venv: Path | None = None, force: bool = False) -> bool:
|
|
310
|
+
"""Collect a privacy-scoped package inventory at most once per 24h/source."""
|
|
311
|
+
if not collection_enabled():
|
|
312
|
+
return False
|
|
313
|
+
source = "local-venv" if venv is not None else "cli-runtime"
|
|
314
|
+
if not force:
|
|
315
|
+
try:
|
|
316
|
+
connection = _connect()
|
|
317
|
+
if connection is not None:
|
|
318
|
+
row = connection.execute(
|
|
319
|
+
"SELECT timestamp FROM events WHERE event_type = ? AND "
|
|
320
|
+
"json_extract(payload, '$.environment') = ? ORDER BY timestamp DESC LIMIT 1",
|
|
321
|
+
("environment.inventory", source),
|
|
322
|
+
).fetchone()
|
|
323
|
+
connection.close()
|
|
324
|
+
if row and (datetime.now(UTC) - datetime.fromisoformat(row[0])).total_seconds() < INVENTORY_INTERVAL_SECONDS:
|
|
325
|
+
return False
|
|
326
|
+
except (OSError, sqlite3.Error, ValueError):
|
|
327
|
+
pass
|
|
328
|
+
try:
|
|
329
|
+
return append_event(new_event("environment.inventory", **inventory_snapshot(venv=venv)))
|
|
330
|
+
except (OSError, ValueError):
|
|
331
|
+
return False
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
"""User-level hourly telemetry delivery using native OS schedulers.
|
|
2
|
+
|
|
3
|
+
No constantly running daemon and no network I/O in the foreground CLI.
|
|
4
|
+
The scheduled process reads the consent file before *every* delivery.
|
|
5
|
+
On Linux the preferred backend is systemd --user; cron is a fallback.
|
|
6
|
+
macOS uses launchd and Windows uses Task Scheduler (schtasks.exe).
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import plistlib
|
|
13
|
+
import shlex
|
|
14
|
+
import shutil
|
|
15
|
+
import subprocess
|
|
16
|
+
import sys
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
from sinapsis_cli.telemetry.core import collection_enabled, config_dir, override_state, record_inventory_if_due
|
|
21
|
+
from sinapsis_cli.telemetry.transport import publish_pending
|
|
22
|
+
|
|
23
|
+
INTERVAL_SECONDS = 3600
|
|
24
|
+
SERVICE_NAME = 'sinapsis-telemetry'
|
|
25
|
+
LAUNCHD_LABEL = 'tech.sinapsis.telemetry'
|
|
26
|
+
TASK_NAME = 'SinapsisTelemetry'
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _state_file() -> Path:
|
|
30
|
+
return config_dir() / 'telemetry-scheduler.json'
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _run(args: list[str], *, stdin: str | None = None) -> subprocess.CompletedProcess[str]:
|
|
34
|
+
"""Run a platform scheduler command without a shell or interactive prompt."""
|
|
35
|
+
return subprocess.run(args, input=stdin, capture_output=True, text=True, timeout=8, check=False)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _scheduler_cmd() -> list[str]:
|
|
39
|
+
return [str(Path(sys.executable).resolve()), '-m', 'sinapsis_cli.telemetry.scheduler', 'run-once']
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _run_script() -> Path:
|
|
43
|
+
"""Create a locked-down shell wrapper for systemd or cron."""
|
|
44
|
+
path = config_dir() / 'telemetry-publish.sh'
|
|
45
|
+
cmd = ' '.join(shlex.quote(part) for part in _scheduler_cmd())
|
|
46
|
+
path.write_text('#!/bin/sh\nexec ' + cmd + '\n', encoding='utf-8')
|
|
47
|
+
if os.name == 'posix':
|
|
48
|
+
path.chmod(0o700)
|
|
49
|
+
return path
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _systemd_available() -> bool:
|
|
53
|
+
if not shutil.which('systemctl') or not os.environ.get('XDG_RUNTIME_DIR'):
|
|
54
|
+
return False
|
|
55
|
+
try:
|
|
56
|
+
return _run(['systemctl', '--user', 'show-environment']).returncode == 0
|
|
57
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
58
|
+
return False
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _install_systemd() -> dict[str, str]:
|
|
62
|
+
location = Path.home() / '.config' / 'systemd' / 'user'
|
|
63
|
+
location.mkdir(parents=True, exist_ok=True)
|
|
64
|
+
script = _run_script()
|
|
65
|
+
service = location / f'{SERVICE_NAME}.service'
|
|
66
|
+
timer = location / f'{SERVICE_NAME}.timer'
|
|
67
|
+
service.write_text('[Unit]\nDescription=Opt-in Sinapsis telemetry publisher\n'
|
|
68
|
+
'[Service]\nType=oneshot\nExecStart=' + str(script) + '\n', encoding='utf-8')
|
|
69
|
+
timer.write_text('[Unit]\nDescription=Publish opt-in Sinapsis telemetry hourly\n'
|
|
70
|
+
'[Timer]\nOnBootSec=1h\nOnUnitActiveSec=1h\nPersistent=true\n'
|
|
71
|
+
f'Unit={SERVICE_NAME}.service\n'
|
|
72
|
+
'[Install]\nWantedBy=timers.target\n', encoding='utf-8')
|
|
73
|
+
for argv in (['systemctl', '--user', 'daemon-reload'],
|
|
74
|
+
['systemctl', '--user', 'enable', '--now', f'{SERVICE_NAME}.timer']):
|
|
75
|
+
result = _run(argv)
|
|
76
|
+
if result.returncode:
|
|
77
|
+
raise RuntimeError('systemd user timer installation failed: ' + result.stderr.strip()[:160])
|
|
78
|
+
return {'provider': 'systemd', 'resource': str(timer)}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _cron_lines() -> list[str]:
|
|
82
|
+
result = _run(['crontab', '-l'])
|
|
83
|
+
if result.returncode and 'no crontab' not in result.stderr.lower():
|
|
84
|
+
raise RuntimeError('Cannot read user crontab: ' + result.stderr.strip()[:160])
|
|
85
|
+
return result.stdout.splitlines() if result.returncode == 0 else []
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _install_cron() -> dict[str, str]:
|
|
89
|
+
if not shutil.which('crontab'):
|
|
90
|
+
raise RuntimeError('Neither systemd user timers nor crontab are available')
|
|
91
|
+
script = _run_script()
|
|
92
|
+
marker = '# sinapsis-telemetry managed: do not edit this line'
|
|
93
|
+
lines = [line for line in _cron_lines() if marker not in line]
|
|
94
|
+
lines.append('0 * * * * ' + shlex.quote(str(script)) + ' ' + marker)
|
|
95
|
+
result = _run(['crontab', '-'], stdin='\n'.join(lines) + '\n')
|
|
96
|
+
if result.returncode:
|
|
97
|
+
raise RuntimeError('Cron installation failed: ' + result.stderr.strip()[:160])
|
|
98
|
+
return {'provider': 'cron', 'resource': marker}
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _install_launchd() -> dict[str, str]:
|
|
102
|
+
path = Path.home() / 'Library' / 'LaunchAgents' / f'{LAUNCHD_LABEL}.plist'
|
|
103
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
104
|
+
data: dict[str, Any] = {
|
|
105
|
+
'Label': LAUNCHD_LABEL,
|
|
106
|
+
'ProgramArguments': _scheduler_cmd(),
|
|
107
|
+
'StartInterval': INTERVAL_SECONDS,
|
|
108
|
+
'RunAtLoad': False,
|
|
109
|
+
'ProcessType': 'Background',
|
|
110
|
+
}
|
|
111
|
+
path.write_bytes(plistlib.dumps(data))
|
|
112
|
+
path.chmod(0o600)
|
|
113
|
+
domain = f'gui/{os.getuid()}'
|
|
114
|
+
_run(['launchctl', 'bootout', f'{domain}/{LAUNCHD_LABEL}'])
|
|
115
|
+
result = _run(['launchctl', 'bootstrap', domain, str(path)])
|
|
116
|
+
if result.returncode:
|
|
117
|
+
raise RuntimeError('launchd installation failed: ' + result.stderr.strip()[:160])
|
|
118
|
+
return {'provider': 'launchd', 'resource': str(path)}
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _install_windows() -> dict[str, str]:
|
|
122
|
+
# schtasks accepts a single /TR command line; use Windows quoting rules.
|
|
123
|
+
command_line = subprocess.list2cmdline(_scheduler_cmd())
|
|
124
|
+
result = _run(['schtasks', '/Create', '/F', '/SC', 'HOURLY', '/MO', '1',
|
|
125
|
+
'/TN', TASK_NAME, '/TR', command_line])
|
|
126
|
+
if result.returncode:
|
|
127
|
+
raise RuntimeError('Task Scheduler registration failed: ' + result.stderr.strip()[:160])
|
|
128
|
+
return {'provider': 'windows-task', 'resource': TASK_NAME}
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def install_scheduler() -> None:
|
|
132
|
+
"""Install the hourly user-level sender; fail rather than pretending it works."""
|
|
133
|
+
if override_state() == '0':
|
|
134
|
+
raise RuntimeError('SINAPSIS_TELEMETRY=0 explicitly disables telemetry in this shell')
|
|
135
|
+
config_dir().mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
136
|
+
if os.name == 'nt':
|
|
137
|
+
state = _install_windows()
|
|
138
|
+
elif sys.platform == 'darwin':
|
|
139
|
+
state = _install_launchd()
|
|
140
|
+
elif sys.platform.startswith('linux'):
|
|
141
|
+
state = _install_systemd() if _systemd_available() else _install_cron()
|
|
142
|
+
else:
|
|
143
|
+
raise RuntimeError(f'Unsupported scheduler operating system: {sys.platform}')
|
|
144
|
+
path = _state_file()
|
|
145
|
+
tmp = path.with_name(path.name + '.tmp')
|
|
146
|
+
try:
|
|
147
|
+
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
148
|
+
with os.fdopen(fd, 'w', encoding='utf-8') as stream:
|
|
149
|
+
json.dump(state, stream)
|
|
150
|
+
os.replace(tmp, path)
|
|
151
|
+
finally:
|
|
152
|
+
tmp.unlink(missing_ok=True)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def remove_scheduler() -> None:
|
|
156
|
+
"""Remove a previously registered scheduler without changing local event history."""
|
|
157
|
+
path = _state_file()
|
|
158
|
+
if not path.exists():
|
|
159
|
+
return
|
|
160
|
+
state = json.loads(path.read_text(encoding='utf-8'))
|
|
161
|
+
provider = state.get('provider')
|
|
162
|
+
if provider == 'systemd':
|
|
163
|
+
result = _run(['systemctl', '--user', 'disable', '--now', f'{SERVICE_NAME}.timer'])
|
|
164
|
+
if result.returncode:
|
|
165
|
+
raise RuntimeError('Could not disable systemd timer: ' + result.stderr.strip()[:160])
|
|
166
|
+
folder = Path.home() / '.config' / 'systemd' / 'user'
|
|
167
|
+
(folder / f'{SERVICE_NAME}.timer').unlink(missing_ok=True)
|
|
168
|
+
(folder / f'{SERVICE_NAME}.service').unlink(missing_ok=True)
|
|
169
|
+
_run(['systemctl', '--user', 'daemon-reload'])
|
|
170
|
+
elif provider == 'cron':
|
|
171
|
+
lines = [line for line in _cron_lines() if state.get('resource', '') not in line]
|
|
172
|
+
result = _run(['crontab', '-'], stdin='\n'.join(lines) + '\n')
|
|
173
|
+
if result.returncode:
|
|
174
|
+
raise RuntimeError('Could not remove cron entry: ' + result.stderr.strip()[:160])
|
|
175
|
+
elif provider == 'launchd':
|
|
176
|
+
_run(['launchctl', 'bootout', f'gui/{os.getuid()}/{LAUNCHD_LABEL}'])
|
|
177
|
+
Path(state['resource']).unlink(missing_ok=True)
|
|
178
|
+
elif provider == 'windows-task':
|
|
179
|
+
result = _run(['schtasks', '/Delete', '/F', '/TN', TASK_NAME])
|
|
180
|
+
if result.returncode:
|
|
181
|
+
raise RuntimeError('Could not remove scheduled task: ' + result.stderr.strip()[:160])
|
|
182
|
+
else:
|
|
183
|
+
raise RuntimeError('Unrecognized scheduler provider; refusing blind removal')
|
|
184
|
+
path.unlink(missing_ok=True)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def scheduler_status() -> dict[str, str]:
|
|
188
|
+
"""Check the operating system, not just a local consent Boolean."""
|
|
189
|
+
try:
|
|
190
|
+
state = json.loads(_state_file().read_text(encoding='utf-8'))
|
|
191
|
+
except (OSError, ValueError):
|
|
192
|
+
return {'status': 'not installed', 'provider': 'none'}
|
|
193
|
+
provider = state.get('provider', 'unknown')
|
|
194
|
+
try:
|
|
195
|
+
if provider == 'systemd':
|
|
196
|
+
active = _run(['systemctl', '--user', 'is-enabled', f'{SERVICE_NAME}.timer']).returncode == 0
|
|
197
|
+
elif provider == 'cron':
|
|
198
|
+
active = any(state.get('resource') in line for line in _cron_lines())
|
|
199
|
+
elif provider == 'launchd':
|
|
200
|
+
active = _run(['launchctl', 'print', f'gui/{os.getuid()}/{LAUNCHD_LABEL}']).returncode == 0
|
|
201
|
+
elif provider == 'windows-task':
|
|
202
|
+
active = _run(['schtasks', '/Query', '/TN', TASK_NAME]).returncode == 0
|
|
203
|
+
else:
|
|
204
|
+
active = False
|
|
205
|
+
except (OSError, subprocess.TimeoutExpired, RuntimeError):
|
|
206
|
+
active = False
|
|
207
|
+
return {'status': 'active' if active else 'missing/disabled', 'provider': str(provider)}
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def run_once() -> int:
|
|
211
|
+
"""Refresh due inventory and publish stored batches without an interactive CLI."""
|
|
212
|
+
if not collection_enabled():
|
|
213
|
+
return 0
|
|
214
|
+
record_inventory_if_due()
|
|
215
|
+
total = 0
|
|
216
|
+
for _ in range(25): # Bounded scheduled execution, maximum 1,000 events.
|
|
217
|
+
sent = publish_pending()
|
|
218
|
+
total += sent
|
|
219
|
+
if sent == 0:
|
|
220
|
+
break
|
|
221
|
+
return total
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def main() -> int:
|
|
225
|
+
"""Entry point called only by OS schedulers."""
|
|
226
|
+
if sys.argv[1:] != ['run-once']:
|
|
227
|
+
print('Usage: python -m sinapsis_cli.telemetry.scheduler run-once', file=sys.stderr)
|
|
228
|
+
return 2
|
|
229
|
+
run_once()
|
|
230
|
+
return 0
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
if __name__ == '__main__':
|
|
234
|
+
raise SystemExit(main())
|