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/watch.py ADDED
@@ -0,0 +1,669 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ import random
6
+ import sys
7
+ import tempfile
8
+ import time
9
+ from dataclasses import asdict, dataclass, field
10
+ from datetime import datetime, timezone
11
+ from pathlib import Path
12
+ from typing import Callable, Optional, Sequence
13
+
14
+ from cloudgpu.errors import (
15
+ AdapterError,
16
+ AuthFailedError,
17
+ AuthRequiredError,
18
+ )
19
+ from cloudgpu.models import GpuOffer, filter_offers
20
+ from cloudgpu.notify import AlertEvent, Notifier
21
+
22
+
23
+ def _default_warn(message: str) -> None:
24
+ print(message, file=sys.stderr)
25
+
26
+
27
+ @dataclass
28
+ class WatchState:
29
+ inventory: dict = field(default_factory=dict)
30
+ failures: dict = field(default_factory=dict)
31
+
32
+ @staticmethod
33
+ def inventory_key(
34
+ platform: str,
35
+ kind: str,
36
+ model: str,
37
+ region=None,
38
+ machine_id=None,
39
+ ) -> str:
40
+ if not region and not machine_id:
41
+ return f"{platform}|{kind}|{model}"
42
+ machine = (machine_id or "").replace("|", "%7C")
43
+ return (
44
+ f"{platform}|{kind}|{region or ''}|{model}|"
45
+ f"{machine}"
46
+ )
47
+
48
+ @staticmethod
49
+ def failure_key(platform: str, kind: str, scope=None) -> str:
50
+ if scope is None:
51
+ return f"{platform}|{kind}"
52
+ return f"{platform}|{kind}|{scope}"
53
+
54
+ @classmethod
55
+ def load(cls, path, warn=None) -> "WatchState":
56
+ warn = warn or _default_warn
57
+ path = Path(path)
58
+ if not path.exists():
59
+ return cls()
60
+ try:
61
+ payload = json.loads(path.read_text(encoding="utf-8"))
62
+ except (OSError, json.JSONDecodeError) as exc:
63
+ warn(f"状态文件损坏,按空状态继续: {exc}")
64
+ return cls()
65
+
66
+ if not isinstance(payload, dict):
67
+ warn("状态文件损坏,按空状态继续: 顶层不是对象")
68
+ return cls()
69
+
70
+ inventory = payload.get("inventory", {})
71
+ failures = payload.get("failures", {})
72
+ if not isinstance(inventory, dict) or not isinstance(failures, dict):
73
+ warn("状态文件损坏,按空状态继续: inventory/failures 类型非法")
74
+ return cls()
75
+
76
+ clean_inventory = {}
77
+ for key, value in inventory.items():
78
+ if not isinstance(key, str) or not isinstance(value, dict):
79
+ warn("状态文件损坏,按空状态继续: inventory 条目非法")
80
+ return cls()
81
+ free = value.get("free")
82
+ if isinstance(free, bool) or not isinstance(free, int) or free < 0:
83
+ warn("状态文件损坏,按空状态继续: free 非法")
84
+ return cls()
85
+ checked_at = value.get("checked_at", "")
86
+ if not isinstance(checked_at, str):
87
+ warn("状态文件损坏,按空状态继续: checked_at 非法")
88
+ return cls()
89
+ clean_inventory[key] = {"free": free, "checked_at": checked_at}
90
+
91
+ clean_failures = {}
92
+ for key, value in failures.items():
93
+ if not isinstance(key, str) or not isinstance(value, bool):
94
+ warn("状态文件损坏,按空状态继续: failures 条目非法")
95
+ return cls()
96
+ clean_failures[key] = value
97
+
98
+ return cls(clean_inventory, clean_failures)
99
+
100
+ def save(self, path) -> None:
101
+ path = Path(path)
102
+ path.parent.mkdir(parents=True, exist_ok=True)
103
+ payload = {
104
+ "version": 1,
105
+ "inventory": self.inventory,
106
+ "failures": self.failures,
107
+ }
108
+ descriptor, temporary = tempfile.mkstemp(
109
+ prefix=f"{path.name}.",
110
+ dir=str(path.parent),
111
+ text=True,
112
+ )
113
+ try:
114
+ with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
115
+ json.dump(payload, handle, ensure_ascii=False, sort_keys=True)
116
+ handle.flush()
117
+ os.fsync(handle.fileno())
118
+ os.chmod(temporary, 0o600)
119
+ os.replace(temporary, path)
120
+ except Exception:
121
+ try:
122
+ os.unlink(temporary)
123
+ except OSError:
124
+ pass
125
+ raise
126
+
127
+
128
+ def evaluate_success(
129
+ offers: Sequence[GpuOffer],
130
+ state: WatchState,
131
+ *,
132
+ platform: str,
133
+ kinds: Sequence[str],
134
+ gpu_patterns: Sequence[str],
135
+ min_free: int,
136
+ checked_at: str,
137
+ reset_prefixes: Sequence[str] = (),
138
+ failure_scope=None,
139
+ ) -> list[AlertEvent]:
140
+ events = []
141
+
142
+ for kind in kinds:
143
+ key = state.failure_key(platform, kind, failure_scope)
144
+ if state.failures.get(key):
145
+ state.failures[key] = False
146
+ events.append(
147
+ AlertEvent(
148
+ "recovery",
149
+ f"{platform} {kind} 监控恢复",
150
+ f"检查时间 {checked_at}",
151
+ )
152
+ )
153
+
154
+ current_keys = set()
155
+ for offer in offers:
156
+ if offer.platform != platform or offer.service_kind not in kinds:
157
+ continue
158
+ key = state.inventory_key(
159
+ platform,
160
+ offer.service_kind,
161
+ offer.gpu_model,
162
+ offer.region,
163
+ offer.machine_id,
164
+ )
165
+ current_keys.add(key)
166
+
167
+ previous = state.inventory.get(key, {}).get("free")
168
+ if isinstance(previous, bool) or not isinstance(previous, int):
169
+ previous = None
170
+
171
+ state.inventory[key] = {
172
+ "free": offer.free,
173
+ "checked_at": offer.checked_at or checked_at,
174
+ }
175
+
176
+ matches = bool(
177
+ filter_offers([offer], gpu_patterns, min_free=0)
178
+ )
179
+ if matches and offer.free >= min_free:
180
+ if previous is None or previous < min_free:
181
+ events.append(
182
+ AlertEvent(
183
+ "available",
184
+ _available_title(offer),
185
+ _available_body(offer, checked_at),
186
+ )
187
+ )
188
+
189
+ for key, value in list(state.inventory.items()):
190
+ parts = _inventory_parts(key)
191
+ if parts is None or not isinstance(value, dict):
192
+ continue
193
+ key_platform, key_kind, _region, _model, _machine = parts
194
+ if reset_prefixes and not any(
195
+ key.startswith(prefix) for prefix in reset_prefixes
196
+ ):
197
+ continue
198
+ if (
199
+ key_platform == platform
200
+ and key_kind in kinds
201
+ and key not in current_keys
202
+ ):
203
+ value["free"] = 0
204
+ value["checked_at"] = checked_at
205
+
206
+ return events
207
+
208
+
209
+ def evaluate_failure(
210
+ platform: str,
211
+ kind: str,
212
+ error: Exception,
213
+ state: WatchState,
214
+ checked_at: str,
215
+ credential_hint=None,
216
+ scope=None,
217
+ ) -> list[AlertEvent]:
218
+ key = state.failure_key(platform, kind, scope)
219
+ if state.failures.get(key):
220
+ return []
221
+ state.failures[key] = True
222
+ if isinstance(error, (AuthFailedError, AuthRequiredError)):
223
+ hint = credential_hint or _credential_hint(platform)
224
+ return [
225
+ AlertEvent(
226
+ "failure",
227
+ f"{platform} {kind} 凭据失效",
228
+ f"查询失败 {error}\n{hint}\n检查时间 {checked_at}",
229
+ )
230
+ ]
231
+ return [
232
+ AlertEvent(
233
+ "failure",
234
+ f"{platform} {kind} 监控失效",
235
+ f"查询失败 {error}\n检查时间 {checked_at}",
236
+ )
237
+ ]
238
+
239
+
240
+ def _credential_hint(platform: str, token_file=None) -> str:
241
+ if platform == "gpushare":
242
+ path = (
243
+ str(token_file)
244
+ if token_file
245
+ else "~/.cloudgpu/gpushare.token"
246
+ )
247
+ return (
248
+ f"gpu_share_token 可能已过期,请重新复制到 {path},"
249
+ "或更新 CLOUDGPU_GPUSHARE_TOKEN"
250
+ )
251
+ if platform == "autodl":
252
+ path = (
253
+ str(token_file)
254
+ if token_file
255
+ else "~/.cloudgpu/autodl.token"
256
+ )
257
+ return (
258
+ f"AutoDL token 可能已过期,请重新复制 Authorization 到 "
259
+ f"{path},或更新 CLOUDGPU_AUTODL_TOKEN"
260
+ )
261
+ if platform == "gongji":
262
+ path = (
263
+ str(token_file)
264
+ if token_file
265
+ else "~/.cloudgpu/gongji.token"
266
+ )
267
+ return (
268
+ f"共绩 token 可能已过期,请重新复制到 {path},"
269
+ "或更新 CLOUDGPU_GONGJI_TOKEN"
270
+ )
271
+ return "平台凭据可能已过期,请重新获取 token"
272
+
273
+
274
+ def _available_title(offer: GpuOffer) -> str:
275
+ parts = [offer.platform]
276
+ if offer.region:
277
+ parts.append(offer.region)
278
+ elif offer.service_kind:
279
+ parts.append(offer.service_kind)
280
+ if offer.service_kind == "machine" and offer.machine_id:
281
+ parts.append(offer.machine_id)
282
+ parts.append(offer.display_name)
283
+ parts.append("有卡")
284
+ return " ".join(parts)
285
+
286
+
287
+ def _available_body(offer: GpuOffer, checked_at: str) -> str:
288
+ memory = (
289
+ f"{offer.gpu_memory_gb}G"
290
+ if offer.gpu_memory_gb is not None
291
+ else "未知"
292
+ )
293
+ lines = [
294
+ f"空闲 {offer.free} 张",
295
+ f"显存 {memory}",
296
+ f"检查时间 {offer.checked_at or checked_at}",
297
+ ]
298
+ if offer.url:
299
+ lines.append(offer.url)
300
+ if offer.service_kind == "region":
301
+ lines.append("地区级空闲数,非同机卡数")
302
+ if offer.service_kind == "machine":
303
+ if offer.price_per_hour is not None:
304
+ lines.append(
305
+ f"价格 ¥{offer.price_per_hour:.2f}/时/卡"
306
+ )
307
+ extra = offer.extra or {}
308
+ if extra.get("highest_cuda_version"):
309
+ lines.append(f"CUDA {extra['highest_cuda_version']}")
310
+ if extra.get("cpu_name"):
311
+ lines.append(f"CPU {extra['cpu_name']}")
312
+ if offer.platform == "gpugeek":
313
+ lines.append("GPUGeek 云端为规格级空闲数,非同机卡数")
314
+ if offer.price_per_hour is not None:
315
+ lines.append(
316
+ f"价格 ¥{offer.price_per_hour:.2f}/时/卡"
317
+ )
318
+ extra = offer.extra or {}
319
+ if extra.get("cpu_name"):
320
+ lines.append(f"CPU {extra['cpu_name']}")
321
+ if offer.platform == "mornai":
322
+ lines.append("晨涧云仅提供全平台空闲计数,非同机卡数")
323
+ return "\n".join(lines)
324
+
325
+
326
+ def _inventory_parts(key: str):
327
+ parts = key.split("|")
328
+ if len(parts) == 3:
329
+ return parts[0], parts[1], None, parts[2], None
330
+ if len(parts) == 5:
331
+ return (
332
+ parts[0],
333
+ parts[1],
334
+ parts[2] or None,
335
+ parts[3],
336
+ parts[4] or None,
337
+ )
338
+ return None
339
+
340
+
341
+ @dataclass
342
+ class WatchOptions:
343
+ platform: str
344
+ kinds: tuple
345
+ gpu_patterns: tuple
346
+ min_free: int
347
+ interval: float
348
+ jitter: float
349
+ once: bool
350
+ quiet: bool
351
+ state_path: Path
352
+ json_output: bool = False
353
+ reset_prefixes: tuple = ()
354
+ credential_hint: str = ""
355
+
356
+
357
+ @dataclass
358
+ class WatchJob:
359
+ name: str
360
+ platform: str
361
+ kinds: tuple
362
+ gpu_patterns: tuple
363
+ min_free: int
364
+ fetch_offers: Callable
365
+ reset_prefixes: tuple = ()
366
+ credential_hint: str = ""
367
+ notifier: object = None
368
+
369
+
370
+ @dataclass
371
+ class SchedulerOptions:
372
+ interval: float
373
+ jitter: float
374
+ once: bool
375
+ quiet: bool
376
+ state_path: Path
377
+ json_output: bool = False
378
+
379
+
380
+ def run_watch(
381
+ adapter,
382
+ notifier: Notifier,
383
+ state: WatchState,
384
+ options: WatchOptions,
385
+ *,
386
+ fetch_offers=None,
387
+ sleeper=None,
388
+ clock=None,
389
+ random_func=None,
390
+ max_cycles=None,
391
+ stream=None,
392
+ ) -> int:
393
+ if options.interval < 5:
394
+ raise ValueError("interval 不能小于 5 秒")
395
+ if options.jitter < 0:
396
+ raise ValueError("jitter 不能为负数")
397
+ if options.min_free < 1:
398
+ raise ValueError("min_free 不能小于 1")
399
+
400
+ sleeper = sleeper or time.sleep
401
+ clock = clock or (lambda: datetime.now(timezone.utc))
402
+ random_func = random_func or random.uniform
403
+ output = stream or sys.stdout
404
+ fetch = fetch_offers or (
405
+ lambda kind: adapter.list_offers(kind=kind)
406
+ )
407
+ cycles = 0
408
+ auth_hints = set()
409
+
410
+ try:
411
+ while True:
412
+ cycles += 1
413
+ now = clock()
414
+ checked_at = _format_time(now)
415
+ events = []
416
+ offers = []
417
+ ok_kinds = []
418
+ failed_kinds = []
419
+
420
+ for kind in options.kinds:
421
+ try:
422
+ offers.extend(fetch(kind))
423
+ ok_kinds.append(kind)
424
+ except (AdapterError, ValueError) as exc:
425
+ failed_kinds.append(kind)
426
+ events.extend(
427
+ evaluate_failure(
428
+ options.platform,
429
+ kind,
430
+ exc,
431
+ state,
432
+ checked_at,
433
+ credential_hint=(
434
+ options.credential_hint or None
435
+ ),
436
+ )
437
+ )
438
+ if isinstance(
439
+ exc, (AuthFailedError, AuthRequiredError)
440
+ ) and kind not in auth_hints:
441
+ hint = (
442
+ options.credential_hint
443
+ or _credential_hint(options.platform)
444
+ )
445
+ print(f"提醒: {hint}", file=sys.stderr)
446
+ auth_hints.add(kind)
447
+
448
+ if ok_kinds:
449
+ events.extend(
450
+ evaluate_success(
451
+ offers,
452
+ state,
453
+ platform=options.platform,
454
+ kinds=tuple(ok_kinds),
455
+ gpu_patterns=options.gpu_patterns,
456
+ min_free=options.min_free,
457
+ checked_at=checked_at,
458
+ reset_prefixes=options.reset_prefixes,
459
+ )
460
+ )
461
+ for kind in ok_kinds:
462
+ auth_hints.discard(kind)
463
+
464
+ try:
465
+ state.save(options.state_path)
466
+ except OSError as exc:
467
+ print(f"状态保存失败: {exc}", file=sys.stderr)
468
+
469
+ for event in events:
470
+ try:
471
+ notifier.send(event)
472
+ except Exception as exc:
473
+ print(f"通知失败: {exc}", file=sys.stderr)
474
+
475
+ if not options.quiet:
476
+ matched = filter_offers(
477
+ offers,
478
+ options.gpu_patterns,
479
+ min_free=options.min_free,
480
+ )
481
+ line = (
482
+ f"[{now.strftime('%H:%M:%S')}] "
483
+ f"检查完成,有卡 {len(matched)} 个"
484
+ )
485
+ if failed_kinds:
486
+ line += f",失败 {','.join(failed_kinds)}"
487
+ print(line, file=output)
488
+
489
+ if options.once:
490
+ if options.json_output:
491
+ print(
492
+ json.dumps(
493
+ {
494
+ "kind": (
495
+ options.kinds[0]
496
+ if len(options.kinds) == 1
497
+ else "both"
498
+ ),
499
+ "events": [
500
+ asdict(event) for event in events
501
+ ],
502
+ "inventory": state.inventory,
503
+ "failures": state.failures,
504
+ },
505
+ ensure_ascii=False,
506
+ ),
507
+ file=output,
508
+ )
509
+ return 0 if ok_kinds else 3
510
+
511
+ if max_cycles is not None and cycles >= max_cycles:
512
+ return 0
513
+
514
+ sleeper(options.interval + random_func(0, options.jitter))
515
+ except KeyboardInterrupt:
516
+ return 0
517
+
518
+
519
+ def _format_time(value: datetime) -> str:
520
+ if value.tzinfo is None:
521
+ value = value.replace(tzinfo=timezone.utc)
522
+ return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
523
+
524
+
525
+ def run_watch_jobs(
526
+ jobs,
527
+ state: WatchState,
528
+ options: SchedulerOptions,
529
+ *,
530
+ sleeper=None,
531
+ clock=None,
532
+ random_func=None,
533
+ max_cycles=None,
534
+ stream=None,
535
+ ) -> int:
536
+ if options.interval < 5:
537
+ raise ValueError("interval 不能小于 5 秒")
538
+ if options.jitter < 0:
539
+ raise ValueError("jitter 不能为负数")
540
+
541
+ sleeper = sleeper or time.sleep
542
+ clock = clock or (lambda: datetime.now(timezone.utc))
543
+ random_func = random_func or random.uniform
544
+ output = stream or sys.stdout
545
+ auth_hints = set()
546
+ cycles = 0
547
+
548
+ try:
549
+ while True:
550
+ cycles += 1
551
+ now = clock()
552
+ checked_at = _format_time(now)
553
+ job_results = []
554
+ any_ok = False
555
+
556
+ for job in jobs:
557
+ offers = []
558
+ ok_kinds = []
559
+ failed_kinds = []
560
+ events = []
561
+
562
+ for kind in job.kinds:
563
+ try:
564
+ offers.extend(job.fetch_offers(kind))
565
+ ok_kinds.append(kind)
566
+ except (AdapterError, ValueError) as exc:
567
+ failed_kinds.append(kind)
568
+ events.extend(
569
+ evaluate_failure(
570
+ job.platform,
571
+ kind,
572
+ exc,
573
+ state,
574
+ checked_at,
575
+ credential_hint=(
576
+ job.credential_hint or None
577
+ ),
578
+ scope=job.name,
579
+ )
580
+ )
581
+ hint_key = (job.name, kind)
582
+ if isinstance(
583
+ exc, (AuthFailedError, AuthRequiredError)
584
+ ) and hint_key not in auth_hints:
585
+ hint = (
586
+ job.credential_hint
587
+ or _credential_hint(job.platform)
588
+ )
589
+ print(f"提醒: {hint}", file=sys.stderr)
590
+ auth_hints.add(hint_key)
591
+
592
+ if ok_kinds:
593
+ events.extend(
594
+ evaluate_success(
595
+ offers,
596
+ state,
597
+ platform=job.platform,
598
+ kinds=tuple(ok_kinds),
599
+ gpu_patterns=job.gpu_patterns,
600
+ min_free=job.min_free,
601
+ checked_at=checked_at,
602
+ reset_prefixes=job.reset_prefixes,
603
+ failure_scope=job.name,
604
+ )
605
+ )
606
+ for kind in ok_kinds:
607
+ auth_hints.discard((job.name, kind))
608
+ any_ok = True
609
+
610
+ for event in events:
611
+ if job.notifier is None:
612
+ continue
613
+ try:
614
+ job.notifier.send(event)
615
+ except Exception as exc:
616
+ print(
617
+ f"通知失败: {exc}", file=sys.stderr
618
+ )
619
+
620
+ matched = filter_offers(
621
+ offers,
622
+ job.gpu_patterns,
623
+ job.min_free,
624
+ )
625
+ job_results.append(
626
+ {
627
+ "name": job.name,
628
+ "platform": job.platform,
629
+ "events": [
630
+ asdict(event) for event in events
631
+ ],
632
+ "matched": len(matched),
633
+ }
634
+ )
635
+ if not options.quiet:
636
+ line = (
637
+ f"[{now.strftime('%H:%M:%S')}] {job.name} "
638
+ f"检查完成,有卡 {len(matched)} 个"
639
+ )
640
+ if failed_kinds:
641
+ line += f",失败 {','.join(failed_kinds)}"
642
+ print(line, file=output)
643
+
644
+ try:
645
+ state.save(options.state_path)
646
+ except OSError as exc:
647
+ print(f"状态保存失败: {exc}", file=sys.stderr)
648
+
649
+ if options.once:
650
+ if options.json_output:
651
+ print(
652
+ json.dumps(
653
+ {
654
+ "jobs": job_results,
655
+ "inventory": state.inventory,
656
+ "failures": state.failures,
657
+ },
658
+ ensure_ascii=False,
659
+ ),
660
+ file=output,
661
+ )
662
+ return 0 if any_ok else 3
663
+
664
+ if max_cycles is not None and cycles >= max_cycles:
665
+ return 0
666
+
667
+ sleeper(options.interval + random_func(0, options.jitter))
668
+ except KeyboardInterrupt:
669
+ return 0