cloudgpu 0.1.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.
cloudgpu/notify.py ADDED
@@ -0,0 +1,295 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ import re
6
+ import shutil
7
+ import subprocess
8
+ import sys
9
+ import urllib.error
10
+ import urllib.parse
11
+ import urllib.request
12
+ from dataclasses import dataclass
13
+ from typing import Callable, Mapping, Optional, Protocol, Sequence
14
+
15
+ HttpPost = Callable[[str, dict, bool], dict]
16
+
17
+
18
+ class NotifierError(RuntimeError):
19
+ """通知发送失败。"""
20
+
21
+
22
+ class NotifierConfigError(RuntimeError):
23
+ """通知渠道配置缺失或不可用。"""
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class AlertEvent:
28
+ kind: str
29
+ title: str
30
+ body: str
31
+
32
+
33
+ class Notifier(Protocol):
34
+ name: str
35
+
36
+ def send(self, event: AlertEvent) -> None:
37
+ ...
38
+
39
+
40
+ class TerminalNotifier:
41
+ name = "terminal"
42
+
43
+ def __init__(self, stream=None) -> None:
44
+ self._stream = stream or sys.stdout
45
+
46
+ def send(self, event: AlertEvent) -> None:
47
+ print(f"\a\n[{event.kind}] {event.title}\n{event.body}", file=self._stream)
48
+
49
+
50
+ class DesktopNotifier:
51
+ name = "desktop"
52
+
53
+ def __init__(self, runner=None, which=None) -> None:
54
+ self._which = which or shutil.which
55
+ self._runner = runner or _run_command
56
+ if self._which("notify-send"):
57
+ self._command = "notify-send"
58
+ elif self._which("osascript"):
59
+ self._command = "osascript"
60
+ else:
61
+ raise NotifierConfigError(
62
+ "桌面通知不可用,需要 notify-send 或 osascript"
63
+ )
64
+
65
+ def send(self, event: AlertEvent) -> None:
66
+ if self._command == "notify-send":
67
+ command = [
68
+ "notify-send",
69
+ "--app-name=cloudgpu",
70
+ "--urgency=critical",
71
+ event.title,
72
+ event.body,
73
+ ]
74
+ else:
75
+ script = (
76
+ f"display notification {json.dumps(event.body, ensure_ascii=False)} "
77
+ f"with title {json.dumps(event.title, ensure_ascii=False)}"
78
+ )
79
+ command = ["osascript", "-e", script]
80
+ self._runner(command)
81
+
82
+
83
+ class _WebhookNotifier:
84
+ name = ""
85
+ env_variable = ""
86
+ secret_label = ""
87
+
88
+ def __init__(self, secret: str, post: Optional[HttpPost] = None) -> None:
89
+ self._secret = secret
90
+ self._post = post or _http_post
91
+ self._last_response = None
92
+
93
+ def send(self, event: AlertEvent) -> None:
94
+ raise NotImplementedError
95
+
96
+
97
+ class ServerChanNotifier(_WebhookNotifier):
98
+ name = "serverchan"
99
+ env_variable = "CLOUDGPU_SERVERCHAN_KEY"
100
+ secret_label = "key"
101
+
102
+ def send(self, event: AlertEvent) -> None:
103
+ match = re.match(r"sctp(\d+)t", self._secret)
104
+ if match:
105
+ url = (
106
+ f"https://{match.group(1)}.push.ft07.com/send/"
107
+ f"{self._secret}.send"
108
+ )
109
+ else:
110
+ url = f"https://sctapi.ftqq.com/{self._secret}.send"
111
+ response = self._post(
112
+ url,
113
+ {"title": event.title, "desp": event.body},
114
+ True,
115
+ )
116
+ if response.get("code") != 0:
117
+ raise NotifierError(
118
+ f"Server酱推送失败 code={response.get('code')}"
119
+ )
120
+
121
+
122
+ class PushPlusNotifier(_WebhookNotifier):
123
+ name = "pushplus"
124
+ env_variable = "CLOUDGPU_PUSHPLUS_TOKEN"
125
+ secret_label = "token"
126
+
127
+ def send(self, event: AlertEvent) -> None:
128
+ response = self._post(
129
+ "https://www.pushplus.plus/send",
130
+ {
131
+ "token": self._secret,
132
+ "title": event.title,
133
+ "content": event.body,
134
+ "template": "txt",
135
+ },
136
+ False,
137
+ )
138
+ if response.get("code") != 200:
139
+ raise NotifierError(
140
+ f"PushPlus 推送失败 code={response.get('code')}"
141
+ )
142
+
143
+
144
+ class WxPusherNotifier(_WebhookNotifier):
145
+ name = "wxpusher"
146
+ env_variable = "CLOUDGPU_WXPUSHER_TOKEN"
147
+ secret_label = "spt"
148
+
149
+ def send(self, event: AlertEvent) -> None:
150
+ response = self._post(
151
+ "https://wxpusher.zjiecode.com/api/send/message/simple-push",
152
+ {
153
+ "spt": self._secret,
154
+ "summary": event.title,
155
+ "content": f"{event.title}\n{event.body}",
156
+ "contentType": 1,
157
+ },
158
+ False,
159
+ )
160
+ if not (response.get("code") == 1000 or response.get("success") is True):
161
+ raise NotifierError(
162
+ f"WxPusher 推送失败 code={response.get('code')}"
163
+ )
164
+
165
+
166
+ class WeComNotifier(_WebhookNotifier):
167
+ name = "wecom"
168
+ env_variable = "CLOUDGPU_WECOM_WEBHOOK"
169
+ secret_label = "webhook"
170
+
171
+ def send(self, event: AlertEvent) -> None:
172
+ url = self._secret
173
+ if not url.startswith("http"):
174
+ url = (
175
+ "https://qyapi.weixin.qq.com/cgi-bin/webhook/send"
176
+ f"?key={url}"
177
+ )
178
+ response = self._post(
179
+ url,
180
+ {
181
+ "msgtype": "text",
182
+ "text": {"content": f"{event.title}\n{event.body}"},
183
+ },
184
+ False,
185
+ )
186
+ if response.get("errcode") != 0:
187
+ raise NotifierError(
188
+ f"企业微信推送失败 errcode={response.get('errcode')}"
189
+ )
190
+
191
+
192
+ class CompositeNotifier:
193
+ name = "composite"
194
+
195
+ def __init__(self, notifiers: Sequence[Notifier], warn=None) -> None:
196
+ self._notifiers = list(notifiers)
197
+ self._warn = warn or (
198
+ lambda message: print(message, file=sys.stderr)
199
+ )
200
+
201
+ def send(self, event: AlertEvent) -> None:
202
+ for notifier in self._notifiers:
203
+ try:
204
+ notifier.send(event)
205
+ except Exception as exc:
206
+ self._warn(f"{notifier.name} 通知失败: {exc}")
207
+
208
+
209
+ CHANNEL_ENV = {
210
+ "serverchan": "CLOUDGPU_SERVERCHAN_KEY",
211
+ "pushplus": "CLOUDGPU_PUSHPLUS_TOKEN",
212
+ "wxpusher": "CLOUDGPU_WXPUSHER_TOKEN",
213
+ "wecom": "CLOUDGPU_WECOM_WEBHOOK",
214
+ }
215
+
216
+
217
+ def build_notifiers(
218
+ names: Sequence[str],
219
+ *,
220
+ env: Optional[Mapping[str, str]] = None,
221
+ post: Optional[HttpPost] = None,
222
+ runner=None,
223
+ which=None,
224
+ stream=None,
225
+ warn=None,
226
+ ) -> list[Notifier]:
227
+ resolved_env = os.environ if env is None else env
228
+ notifiers = []
229
+ for name in names:
230
+ if name == "terminal":
231
+ notifiers.append(TerminalNotifier(stream=stream))
232
+ elif name == "desktop":
233
+ notifiers.append(DesktopNotifier(runner=runner, which=which))
234
+ elif name in CHANNEL_ENV:
235
+ variable = CHANNEL_ENV[name]
236
+ secret = (resolved_env.get(variable) or "").strip()
237
+ if not secret:
238
+ raise NotifierConfigError(f"缺少环境变量 {variable}")
239
+ if name == "serverchan":
240
+ notifiers.append(ServerChanNotifier(secret, post=post))
241
+ elif name == "pushplus":
242
+ notifiers.append(PushPlusNotifier(secret, post=post))
243
+ elif name == "wxpusher":
244
+ notifiers.append(WxPusherNotifier(secret, post=post))
245
+ else:
246
+ notifiers.append(WeComNotifier(secret, post=post))
247
+ else:
248
+ raise NotifierConfigError(f"未知通知渠道: {name}")
249
+ return notifiers
250
+
251
+
252
+ def _run_command(command: Sequence[str]) -> None:
253
+ try:
254
+ subprocess.run(
255
+ command,
256
+ check=True,
257
+ timeout=10,
258
+ stdout=subprocess.DEVNULL,
259
+ stderr=subprocess.DEVNULL,
260
+ )
261
+ except (OSError, subprocess.SubprocessError) as exc:
262
+ raise NotifierError(f"桌面通知失败: {exc}") from exc
263
+
264
+
265
+ def _http_post(url: str, payload: dict, form: bool) -> dict:
266
+ if form:
267
+ body = urllib.parse.urlencode(payload).encode("utf-8")
268
+ content_type = "application/x-www-form-urlencoded"
269
+ else:
270
+ body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
271
+ content_type = "application/json"
272
+
273
+ try:
274
+ request = urllib.request.Request(
275
+ url,
276
+ data=body,
277
+ headers={"Content-Type": content_type},
278
+ method="POST",
279
+ )
280
+ with urllib.request.urlopen(request, timeout=10) as response:
281
+ raw = response.read()
282
+ except ValueError:
283
+ raise NotifierError("通知请求失败: URL 非法") from None
284
+ except (urllib.error.URLError, TimeoutError, OSError) as exc:
285
+ reason = getattr(exc, "reason", None) or type(exc).__name__
286
+ raise NotifierError(f"通知请求失败: {reason}") from None
287
+
288
+ try:
289
+ result = json.loads(raw.decode("utf-8"))
290
+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:
291
+ raise NotifierError(f"通知响应不是合法 JSON: {exc}") from exc
292
+
293
+ if not isinstance(result, dict):
294
+ raise NotifierError("通知响应格式异常: 顶层不是对象")
295
+ return result
cloudgpu/orders.py ADDED
@@ -0,0 +1,319 @@
1
+ from __future__ import annotations
2
+
3
+ import sqlite3
4
+ from datetime import datetime, timezone
5
+ from pathlib import Path
6
+
7
+ DEFAULT_DB = Path.home() / ".cloudgpu" / "orders.db"
8
+
9
+
10
+ class OrderConflictError(RuntimeError):
11
+ """存在未解决订单,不能创建新订单。"""
12
+
13
+ _SCHEMA = """
14
+ CREATE TABLE IF NOT EXISTS orders (
15
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
16
+ platform TEXT NOT NULL,
17
+ instance_name TEXT NOT NULL UNIQUE,
18
+ machine_id TEXT NOT NULL,
19
+ gpu_model TEXT NOT NULL,
20
+ gpu_count INTEGER NOT NULL,
21
+ image_id TEXT NOT NULL,
22
+ hourly_total REAL,
23
+ status TEXT NOT NULL,
24
+ instance_uuid TEXT,
25
+ error TEXT,
26
+ created_at TEXT NOT NULL,
27
+ updated_at TEXT NOT NULL,
28
+ response TEXT
29
+ )
30
+ """
31
+
32
+
33
+ def read_blocking_orders(path):
34
+ path = Path(path)
35
+ if not path.exists():
36
+ return []
37
+ conn = sqlite3.connect(
38
+ f"file:{path}?mode=ro", uri=True
39
+ )
40
+ try:
41
+ rows = conn.execute(
42
+ """
43
+ SELECT * FROM orders
44
+ WHERE status IN ('submitting', 'unknown')
45
+ ORDER BY id
46
+ """
47
+ ).fetchall()
48
+ except sqlite3.Error as exc:
49
+ raise ValueError(
50
+ f"读取订单台账失败: {exc}"
51
+ ) from None
52
+ finally:
53
+ conn.close()
54
+ return [dict(row) for row in rows]
55
+
56
+
57
+ class OrderStore:
58
+ def __init__(self, path=None, clock=None) -> None:
59
+ self.path = (
60
+ Path(path).expanduser() if path else DEFAULT_DB
61
+ )
62
+ self.path.parent.mkdir(parents=True, exist_ok=True)
63
+ self._clock = clock or (
64
+ lambda: datetime.now(timezone.utc)
65
+ )
66
+ self._init()
67
+
68
+ def _init(self) -> None:
69
+ with self._connect() as conn:
70
+ conn.execute(_SCHEMA)
71
+ try:
72
+ self.path.chmod(0o600)
73
+ except OSError:
74
+ pass
75
+
76
+ def _connect(self):
77
+ conn = sqlite3.connect(str(self.path))
78
+ conn.row_factory = sqlite3.Row
79
+ return conn
80
+
81
+ def _now(self) -> str:
82
+ value = self._clock()
83
+ if value.tzinfo is None:
84
+ value = value.replace(tzinfo=timezone.utc)
85
+ return value.astimezone(timezone.utc).strftime(
86
+ "%Y-%m-%dT%H:%M:%SZ"
87
+ )
88
+
89
+ def create_intent(
90
+ self,
91
+ *,
92
+ instance_name: str,
93
+ machine_id: str,
94
+ gpu_model: str,
95
+ gpu_count: int,
96
+ image_id: str,
97
+ hourly_total,
98
+ ) -> int:
99
+ now = self._now()
100
+ try:
101
+ with self._connect() as conn:
102
+ cursor = conn.execute(
103
+ """
104
+ INSERT INTO orders (
105
+ platform, instance_name, machine_id,
106
+ gpu_model, gpu_count, image_id,
107
+ hourly_total, status, created_at,
108
+ updated_at
109
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
110
+ """,
111
+ (
112
+ "autodl",
113
+ instance_name,
114
+ machine_id,
115
+ gpu_model,
116
+ gpu_count,
117
+ image_id,
118
+ hourly_total,
119
+ "submitting",
120
+ now,
121
+ now,
122
+ ),
123
+ )
124
+ return int(cursor.lastrowid)
125
+ except sqlite3.IntegrityError:
126
+ raise ValueError(
127
+ f"实例名已存在: {instance_name}"
128
+ ) from None
129
+
130
+ def create_intent_if_clear(
131
+ self,
132
+ *,
133
+ instance_name: str,
134
+ machine_id: str,
135
+ gpu_model: str,
136
+ gpu_count: int,
137
+ image_id: str,
138
+ hourly_total,
139
+ ) -> int:
140
+ now = self._now()
141
+ conn = self._connect()
142
+ try:
143
+ conn.execute("BEGIN IMMEDIATE")
144
+ blocking = conn.execute(
145
+ """
146
+ SELECT 1 FROM orders
147
+ WHERE status IN ('submitting', 'unknown')
148
+ LIMIT 1
149
+ """
150
+ ).fetchone()
151
+ if blocking is not None:
152
+ conn.rollback()
153
+ raise OrderConflictError(
154
+ "存在未解决的订单,请先对账"
155
+ )
156
+ cursor = conn.execute(
157
+ """
158
+ INSERT INTO orders (
159
+ platform, instance_name, machine_id,
160
+ gpu_model, gpu_count, image_id,
161
+ hourly_total, status, created_at,
162
+ updated_at
163
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
164
+ """,
165
+ (
166
+ "autodl",
167
+ instance_name,
168
+ machine_id,
169
+ gpu_model,
170
+ gpu_count,
171
+ image_id,
172
+ hourly_total,
173
+ "submitting",
174
+ now,
175
+ now,
176
+ ),
177
+ )
178
+ conn.commit()
179
+ return int(cursor.lastrowid)
180
+ except OrderConflictError:
181
+ raise
182
+ except sqlite3.IntegrityError:
183
+ conn.rollback()
184
+ raise ValueError(
185
+ f"实例名已存在: {instance_name}"
186
+ ) from None
187
+ except Exception:
188
+ conn.rollback()
189
+ raise
190
+ finally:
191
+ conn.close()
192
+
193
+ def mark_created(
194
+ self, order_id: int, instance_uuid: str
195
+ ) -> None:
196
+ if not isinstance(instance_uuid, str) or not instance_uuid:
197
+ raise ValueError("instance_uuid 不能为空")
198
+ self._transition(
199
+ order_id,
200
+ {"submitting", "unknown"},
201
+ "created",
202
+ instance_uuid=instance_uuid,
203
+ )
204
+
205
+ def mark_status(
206
+ self, order_id: int, status: str, error=None
207
+ ) -> None:
208
+ allowed = {
209
+ "submitting": {"sold_out", "rejected", "unknown"},
210
+ "unknown": {"not_created"},
211
+ }
212
+ row = self.get(order_id)
213
+ if row is None:
214
+ raise ValueError(f"订单不存在: {order_id}")
215
+ if status not in allowed.get(row["status"], set()):
216
+ raise ValueError(
217
+ f"订单 {order_id} 不能从 {row['status']} "
218
+ f"转为 {status}"
219
+ )
220
+ self._update(
221
+ order_id, status=status, error=error
222
+ )
223
+
224
+ def resolve_not_created(self, order_id: int) -> None:
225
+ row = self.get(order_id)
226
+ if row is None:
227
+ raise ValueError(f"订单不存在: {order_id}")
228
+ if row["status"] not in ("submitting", "unknown"):
229
+ raise ValueError(
230
+ f"订单 {order_id} 当前状态不可解决: "
231
+ f"{row['status']}"
232
+ )
233
+ self._update(
234
+ order_id,
235
+ status="not_created",
236
+ error=row["error"],
237
+ )
238
+
239
+ def blocking(self) -> list:
240
+ with self._connect() as conn:
241
+ rows = conn.execute(
242
+ """
243
+ SELECT * FROM orders
244
+ WHERE status IN ('submitting', 'unknown')
245
+ ORDER BY id
246
+ """
247
+ ).fetchall()
248
+ return [dict(row) for row in rows]
249
+
250
+ def all(self) -> list:
251
+ with self._connect() as conn:
252
+ rows = conn.execute(
253
+ "SELECT * FROM orders ORDER BY id"
254
+ ).fetchall()
255
+ return [dict(row) for row in rows]
256
+
257
+ def get(self, order_id: int):
258
+ with self._connect() as conn:
259
+ row = conn.execute(
260
+ "SELECT * FROM orders WHERE id = ?",
261
+ (order_id,),
262
+ ).fetchone()
263
+ return dict(row) if row is not None else None
264
+
265
+ def has_name(self, instance_name: str) -> bool:
266
+ with self._connect() as conn:
267
+ row = conn.execute(
268
+ "SELECT 1 FROM orders WHERE instance_name = ?",
269
+ (instance_name,),
270
+ ).fetchone()
271
+ return row is not None
272
+
273
+ def _transition(
274
+ self,
275
+ order_id: int,
276
+ from_statuses: set,
277
+ status: str,
278
+ *,
279
+ instance_uuid=None,
280
+ ) -> None:
281
+ row = self.get(order_id)
282
+ if row is None:
283
+ raise ValueError(f"订单不存在: {order_id}")
284
+ if row["status"] not in from_statuses:
285
+ raise ValueError(
286
+ f"订单 {order_id} 不能从 {row['status']} "
287
+ f"转为 {status}"
288
+ )
289
+ self._update(
290
+ order_id,
291
+ status=status,
292
+ instance_uuid=instance_uuid,
293
+ )
294
+
295
+ def _update(
296
+ self,
297
+ order_id: int,
298
+ *,
299
+ status: str,
300
+ error=None,
301
+ instance_uuid=None,
302
+ ) -> None:
303
+ with self._connect() as conn:
304
+ conn.execute(
305
+ """
306
+ UPDATE orders
307
+ SET status = ?, error = ?,
308
+ instance_uuid = COALESCE(?, instance_uuid),
309
+ updated_at = ?
310
+ WHERE id = ?
311
+ """,
312
+ (
313
+ status,
314
+ error,
315
+ instance_uuid,
316
+ self._now(),
317
+ order_id,
318
+ ),
319
+ )