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.
@@ -0,0 +1,179 @@
1
+ """共绩 RSA-SHA256 签名,纯标准库实现。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import hashlib
7
+ from pathlib import Path
8
+ from typing import Optional
9
+
10
+ from cloudgpu.errors import AuthRequiredError
11
+
12
+ try:
13
+ from cryptography.hazmat.primitives import hashes, serialization
14
+ from cryptography.hazmat.primitives.asymmetric import padding
15
+
16
+ _HAS_CRYPTOGRAPHY = True
17
+ except ImportError:
18
+ _HAS_CRYPTOGRAPHY = False
19
+
20
+
21
+ def _pem_decode(pem_text: str) -> bytes:
22
+ lines = [
23
+ line
24
+ for line in pem_text.strip().splitlines()
25
+ if line and not line.startswith("-----")
26
+ ]
27
+ return base64.b64decode("".join(lines))
28
+
29
+
30
+ def _read_tlv(data: bytes, offset: int):
31
+ tag = data[offset]
32
+ first = data[offset + 1]
33
+ if first & 0x80 == 0:
34
+ length = first
35
+ pos = offset + 2
36
+ else:
37
+ num_bytes = first & 0x7F
38
+ length = int.from_bytes(
39
+ data[offset + 2 : offset + 2 + num_bytes], "big"
40
+ )
41
+ pos = offset + 2 + num_bytes
42
+ return tag, data[pos : pos + length], pos + length
43
+
44
+
45
+ def _pkcs1_sequence(der: bytes) -> Optional[bytes]:
46
+ oid_marker = bytes.fromhex("06092A864886F70D010101")
47
+ idx = der.find(oid_marker)
48
+ if idx >= 0:
49
+ rest = der[idx + len(oid_marker) :]
50
+ if rest[:2] == b"\x05\x00":
51
+ rest = rest[2:]
52
+ if rest[0:1] == b"\x04":
53
+ _, pkcs1_der, _ = _read_tlv(rest, 0)
54
+ if pkcs1_der[0:1] == b"\x30":
55
+ _, value, _ = _read_tlv(pkcs1_der, 0)
56
+ return value
57
+ if der[0:1] == b"\x30":
58
+ _, value, _ = _read_tlv(der, 0)
59
+ return value
60
+ return None
61
+
62
+
63
+ def _parse_private_der(der: bytes):
64
+ seq = _pkcs1_sequence(der)
65
+ if seq is None:
66
+ raise ValueError("无法解析私钥 DER 结构")
67
+ pos = 0
68
+ _, _version, pos = _read_tlv(seq, pos)
69
+ _, n_bytes, pos = _read_tlv(seq, pos)
70
+ _, e_bytes, pos = _read_tlv(seq, pos)
71
+ _, d_bytes, pos = _read_tlv(seq, pos)
72
+ return (
73
+ int.from_bytes(n_bytes, "big"),
74
+ int.from_bytes(e_bytes, "big"),
75
+ int.from_bytes(d_bytes, "big"),
76
+ )
77
+
78
+
79
+ class _PureRSAPrivateKey:
80
+ def __init__(self, n: int, e: int, d: int) -> None:
81
+ self.n = n
82
+ self.e = e
83
+ self.d = d
84
+ self.key_size_bytes = (n.bit_length() + 7) // 8
85
+
86
+ def sign(self, data: bytes, padding_obj, hash_obj) -> bytes:
87
+ digest = hashlib.sha256(data).digest()
88
+ digest_info = (
89
+ bytes.fromhex("3031300d060960864801650304020105000420")
90
+ + digest
91
+ )
92
+ ps_len = self.key_size_bytes - len(digest_info) - 3
93
+ if ps_len < 8:
94
+ raise ValueError("RSA 密钥过短")
95
+ em = b"\x00\x01" + b"\xff" * ps_len + b"\x00" + digest_info
96
+ signature = pow(
97
+ int.from_bytes(em, "big"), self.d, self.n
98
+ )
99
+ return signature.to_bytes(self.key_size_bytes, "big")
100
+
101
+
102
+ def load_private_key(path) -> object:
103
+ path = Path(path).expanduser()
104
+ try:
105
+ key_data = path.read_bytes()
106
+ except OSError as exc:
107
+ raise AuthRequiredError(
108
+ f"读取共绩私钥失败: {path}: {exc}"
109
+ ) from None
110
+ if _HAS_CRYPTOGRAPHY:
111
+ try:
112
+ return serialization.load_pem_private_key(
113
+ key_data, password=None
114
+ )
115
+ except Exception as exc:
116
+ raise AuthRequiredError(
117
+ f"解析共绩私钥失败: {path}: {exc}"
118
+ ) from None
119
+ try:
120
+ pem_text = key_data.decode("utf-8")
121
+ der = _pem_decode(pem_text)
122
+ n, e, d = _parse_private_der(der)
123
+ return _PureRSAPrivateKey(n, e, d)
124
+ except Exception as exc:
125
+ raise AuthRequiredError(
126
+ f"解析共绩私钥失败: {path}: {exc}"
127
+ ) from None
128
+
129
+
130
+ def sign_request(
131
+ path: str,
132
+ version: str,
133
+ timestamp: int,
134
+ token: str,
135
+ body: str,
136
+ private_key,
137
+ ) -> str:
138
+ sign_str = (
139
+ f"{path}\n{version}\n{timestamp}\n{token}\n{body}"
140
+ )
141
+ if _HAS_CRYPTOGRAPHY and not isinstance(
142
+ private_key, _PureRSAPrivateKey
143
+ ):
144
+ signature = private_key.sign(
145
+ sign_str.encode("utf-8"),
146
+ padding.PKCS1v15(),
147
+ hashes.SHA256(),
148
+ )
149
+ else:
150
+ signature = private_key.sign(
151
+ sign_str.encode("utf-8"), None, None
152
+ )
153
+ return base64.b64encode(signature).decode("utf-8")
154
+
155
+
156
+ def build_headers(
157
+ path: str,
158
+ token: str,
159
+ version: str,
160
+ timestamp: int,
161
+ body: str = "{}",
162
+ private_key=None,
163
+ ) -> dict:
164
+ headers = {
165
+ "token": token,
166
+ "timestamp": str(timestamp),
167
+ "version": version,
168
+ "Content-Type": "application/json",
169
+ }
170
+ if private_key is not None:
171
+ headers["sign_str"] = sign_request(
172
+ path=path,
173
+ version=version,
174
+ timestamp=timestamp,
175
+ token=token,
176
+ body=body,
177
+ private_key=private_key,
178
+ )
179
+ return headers
@@ -0,0 +1,314 @@
1
+ from __future__ import annotations
2
+
3
+ import secrets
4
+ from dataclasses import dataclass
5
+ from datetime import datetime, timezone
6
+
7
+ from cloudgpu.errors import (
8
+ AdapterError,
9
+ AuthFailedError,
10
+ TaskNotFoundError,
11
+ TaskRejectedError,
12
+ TaskUncertainError,
13
+ )
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class DeployPlan:
18
+ task_name: str
19
+ image: str
20
+ ports: tuple
21
+ offer: object
22
+ mark: str
23
+ resource: dict
24
+ hourly_total: float
25
+ ttl_seconds: object
26
+ gpu_model: str
27
+ count: int
28
+ region: object
29
+
30
+
31
+ class DeployBlockedError(RuntimeError):
32
+ """存在未解决的共绩任务,不能创建新任务。"""
33
+
34
+
35
+ class NoResourceError(RuntimeError):
36
+ """没有满足条件的资源。"""
37
+
38
+
39
+ def prepare_deploy(
40
+ adapter,
41
+ pending,
42
+ *,
43
+ gpu_model,
44
+ count,
45
+ image,
46
+ ports,
47
+ region=None,
48
+ max_hourly=None,
49
+ ttl_seconds=None,
50
+ name_prefix="cloudgpu",
51
+ clock=None,
52
+ ):
53
+ if not isinstance(gpu_model, str) or not gpu_model:
54
+ raise ValueError("gpu_model 不能为空")
55
+ if (
56
+ isinstance(count, bool)
57
+ or not isinstance(count, int)
58
+ or count < 1
59
+ ):
60
+ raise ValueError("count 必须是 >=1 的整数")
61
+ if not isinstance(image, str) or not image:
62
+ raise ValueError("image 不能为空")
63
+ port_list = tuple(int(port) for port in ports)
64
+ if not port_list or any(
65
+ port <= 0 or port > 65535 for port in port_list
66
+ ):
67
+ raise ValueError("ports 非法")
68
+ if ttl_seconds is not None and ttl_seconds <= 0:
69
+ raise ValueError("ttl_seconds 必须大于 0")
70
+ if max_hourly is not None and max_hourly <= 0:
71
+ raise ValueError("max_hourly 必须大于 0")
72
+
73
+ if pending.blocking():
74
+ raise DeployBlockedError(
75
+ "存在未解决的共绩任务,请先运行 "
76
+ "gongji tasks --reconcile"
77
+ )
78
+
79
+ offers = adapter.list_resources(
80
+ gpu_model=gpu_model,
81
+ region=region,
82
+ min_free=1,
83
+ )
84
+ for candidate in offers[:5]:
85
+ price = candidate.price_per_hour
86
+ if price is None:
87
+ continue
88
+ mark_info = (candidate.extra or {}).get("mark")
89
+ if not isinstance(mark_info, dict):
90
+ continue
91
+ mark = mark_info.get("mark")
92
+ resource = mark_info.get("resource")
93
+ if (
94
+ not isinstance(mark, str)
95
+ or not mark
96
+ or not isinstance(resource, dict)
97
+ ):
98
+ continue
99
+ resource_count = _resource_gpu_count(resource)
100
+ if resource_count is None or resource_count != count:
101
+ continue
102
+ hourly_total = price * resource_count
103
+ if (
104
+ max_hourly is not None
105
+ and hourly_total > max_hourly
106
+ ):
107
+ continue
108
+ name = _unique_name(pending, name_prefix, clock)
109
+ return DeployPlan(
110
+ task_name=name,
111
+ image=image,
112
+ ports=port_list,
113
+ offer=candidate,
114
+ mark=mark,
115
+ resource=dict(resource),
116
+ hourly_total=hourly_total,
117
+ ttl_seconds=ttl_seconds,
118
+ gpu_model=gpu_model,
119
+ count=count,
120
+ region=region,
121
+ )
122
+ raise NoResourceError(
123
+ "没有满足库存、价格和 mark 条件的共绩资源"
124
+ )
125
+
126
+
127
+ def execute_deploy(
128
+ adapter, pending, ttl, plan, *, max_hourly, clock=None
129
+ ):
130
+ if max_hourly is None or max_hourly <= 0:
131
+ raise ValueError("--execute 必须提供 --max-hourly")
132
+ if pending.blocking():
133
+ raise DeployBlockedError(
134
+ "存在未解决的共绩任务,请先运行 "
135
+ "gongji tasks --reconcile"
136
+ )
137
+
138
+ offers = adapter.list_resources(
139
+ gpu_model=plan.gpu_model,
140
+ region=plan.region,
141
+ min_free=1,
142
+ )
143
+ offer = next(
144
+ (
145
+ item
146
+ for item in offers
147
+ if _mark_id(item) == plan.mark
148
+ ),
149
+ None,
150
+ )
151
+ if offer is None:
152
+ raise NoResourceError(
153
+ "提交前复核失败: mark 已无可用资源"
154
+ )
155
+ if (
156
+ offer.price_per_hour is None
157
+ or offer.price_per_hour * plan.count > max_hourly
158
+ ):
159
+ raise NoResourceError(
160
+ "提交前复核失败: 报价超过 --max-hourly"
161
+ )
162
+ hourly_total = offer.price_per_hour * plan.count
163
+
164
+ pending.add_submitting(
165
+ name=plan.task_name,
166
+ image=plan.image,
167
+ mark=plan.mark,
168
+ resource=plan.resource,
169
+ ttl_seconds=plan.ttl_seconds,
170
+ )
171
+ try:
172
+ task_id = adapter.create_task(
173
+ task_name=plan.task_name,
174
+ image=plan.image,
175
+ ports=list(plan.ports),
176
+ mark=plan.mark,
177
+ resource=plan.resource,
178
+ )
179
+ except TaskRejectedError as exc:
180
+ pending.mark_rejected(plan.task_name, str(exc))
181
+ raise
182
+ except AuthFailedError as exc:
183
+ pending.mark_rejected(plan.task_name, str(exc))
184
+ raise
185
+ except TaskUncertainError as exc:
186
+ pending.mark_unknown(plan.task_name, str(exc))
187
+ raise
188
+
189
+ pending.mark_created(plan.task_name, task_id)
190
+ if plan.ttl_seconds:
191
+ ttl.register(
192
+ task_id,
193
+ plan.ttl_seconds,
194
+ plan.task_name,
195
+ )
196
+ return {
197
+ "task_id": task_id,
198
+ "task_name": plan.task_name,
199
+ "status": "created",
200
+ "hourly_total": hourly_total,
201
+ }
202
+
203
+
204
+ def reconcile_pending(adapter, pending, ttl) -> list:
205
+ tasks = None
206
+ for entry in pending.blocking():
207
+ if tasks is None:
208
+ tasks = adapter.list_tasks()
209
+ match = next(
210
+ (
211
+ row
212
+ for row in tasks
213
+ if row.get("task_name") == entry["name"]
214
+ ),
215
+ None,
216
+ )
217
+ if match is None:
218
+ continue
219
+ task_id = match.get("task_id")
220
+ if not isinstance(task_id, int) or task_id <= 0:
221
+ continue
222
+ pending.mark_created(entry["name"], task_id)
223
+ if entry.get("ttl_seconds"):
224
+ ttl.register(
225
+ task_id,
226
+ entry["ttl_seconds"],
227
+ entry["name"],
228
+ )
229
+ return pending.all()
230
+
231
+
232
+ def sweep_ttl(adapter, ttl, *, execute=False) -> dict:
233
+ rows = [
234
+ row
235
+ for row in ttl.list_expiring()
236
+ if row.get("expired")
237
+ and row.get("auto_release", True)
238
+ ]
239
+ stats = {
240
+ "expired": len(rows),
241
+ "stopped": 0,
242
+ "ended": 0,
243
+ "failed": 0,
244
+ "items": rows,
245
+ }
246
+ if not execute:
247
+ return stats
248
+
249
+ for row in rows:
250
+ task_id = row["task_id"]
251
+ try:
252
+ detail = adapter.task_detail(task_id)
253
+ status = detail.get("status", "")
254
+ if status in ("End", "Other"):
255
+ ttl.unregister(task_id)
256
+ stats["ended"] += 1
257
+ continue
258
+ adapter.stop_task(task_id)
259
+ ttl.unregister(task_id)
260
+ stats["stopped"] += 1
261
+ except TaskNotFoundError:
262
+ ttl.unregister(task_id)
263
+ stats["ended"] += 1
264
+ except Exception:
265
+ stats["failed"] += 1
266
+ return stats
267
+
268
+
269
+ def lazy_sweep(adapter, ttl):
270
+ try:
271
+ rows = ttl.list_expiring()
272
+ if any(
273
+ row.get("expired")
274
+ and row.get("auto_release", True)
275
+ for row in rows
276
+ ):
277
+ return sweep_ttl(adapter, ttl, execute=True)
278
+ except Exception:
279
+ return None
280
+ return None
281
+
282
+
283
+ def _mark_id(offer):
284
+ mark_info = (offer.extra or {}).get("mark")
285
+ if not isinstance(mark_info, dict):
286
+ return None
287
+ return mark_info.get("mark")
288
+
289
+
290
+ def _resource_gpu_count(resource):
291
+ value = resource.get("gpu_count")
292
+ if (
293
+ isinstance(value, bool)
294
+ or not isinstance(value, int)
295
+ or value <= 0
296
+ ):
297
+ return None
298
+ return value
299
+
300
+
301
+ def _unique_name(pending, prefix: str, clock) -> str:
302
+ now = clock() if clock is not None else datetime.now(
303
+ timezone.utc
304
+ )
305
+ if now.tzinfo is None:
306
+ now = now.replace(tzinfo=timezone.utc)
307
+ stamp = now.astimezone(timezone.utc).strftime(
308
+ "%Y%m%d%H%M%S"
309
+ )
310
+ for _ in range(50):
311
+ name = f"{prefix}-{stamp}-{secrets.token_hex(2)}"
312
+ if not pending.has_name(name):
313
+ return name
314
+ raise RuntimeError("无法生成唯一共绩任务名")