-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgpu_server_tool.py
More file actions
1760 lines (1564 loc) · 76.8 KB
/
Copy pathgpu_server_tool.py
File metadata and controls
1760 lines (1564 loc) · 76.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import csv
import base64
import datetime as dt
import json
import queue
import shutil
import subprocess
import threading
import time
import tkinter as tk
import sys
from dataclasses import dataclass
from pathlib import Path
from tkinter import messagebox, ttk
try:
import paramiko
except ImportError: # pragma: no cover - handled at runtime in the UI
paramiko = None
APP_DIR = Path(sys.executable).resolve().parent if getattr(sys, "frozen", False) else Path(__file__).resolve().parent
RESOURCE_DIR = Path(getattr(sys, "_MEIPASS", APP_DIR))
SERVERS_FILE = APP_DIR / "servers.json"
SETTINGS_FILE = APP_DIR / "settings.json"
DEFAULT_IDENTITY_FILE = Path.home() / ".ssh" / "id_ed25519"
DEFAULT_SHARED_DIR = "/mnt/share/user"
DEFAULT_SOURCE_CONDA_ROOT = "/data/user/miniconda3"
DEFAULT_TARGET_CONDA_ROOT = "/data/user/miniconda3"
DEFAULT_QUEUE_RUNNER_DIR = "/mnt/share/user/gpu-queue-runner"
LOCAL_GPUQ_FILE = RESOURCE_DIR / "queue_runner" / "gpuq"
SSH_TIMEOUT_S = 8
TEXTS = {
"en": {
"gpu_tab": "GPU Monitor",
"conda_tab": "Conda Migration",
"queue_tab": "Queue Runner",
"free": "Free",
"online": "Online",
"busy": "Busy",
"auto": "Auto",
"every": "Every",
"idle": "Idle",
"refresh": "Refresh",
"manage_servers": "Manage Servers",
"not_refreshed": "Not refreshed yet",
"preparing": "Preparing to connect to servers",
"refreshing_gpu": "Refreshing GPU status...",
"connecting": "Connecting",
"connection_failed": "Connection failed",
"reading_gpu": "Reading nvidia-smi...",
"nvidia_smi_failed": "Unable to read nvidia-smi. Check SSH, network, or server state.",
"free_count": "Free",
"last_refresh": "Last refresh",
"idle_hint": "Green means idle. Red means busy or memory usage is above the threshold.",
"source_env": "Source Environment",
"source_env_hint": "Pack an existing environment to a shared directory",
"target_env": "Target Environment",
"target_env_hint": "Unpack into target miniconda envs directory",
"server": "Server",
"conda_root": "miniconda root",
"env_name": "Environment name",
"target_env_name": "Target env name",
"source_env_placeholder": "<source env>",
"source_server_placeholder": "<source server>",
"target_server_placeholder": "<target server>",
"shared_dir": "Source shared",
"target_shared": "Target shared",
"target_shared_hint": "Blank = same as source",
"overwrite": "Overwrite target env if it exists",
"start_migration": "Start Migration",
"preview": "Preview",
"current_state": "Current State",
"migration_log": "Migration Log",
"clear": "Clear",
"waiting": "Waiting",
"queue_server": "Server",
"queue_dir": "Remote gpuq dir",
"install_sync": "Install/Sync",
"add_job": "Add Job",
"name": "Name",
"cwd": "CWD",
"command": "Command",
"gpus": "GPUs",
"queue": "Queue",
"priority": "Priority",
"conda_env": "Conda env",
"add_to_queue": "Add to Queue",
"operations": "Operations",
"daemon_status": "Daemon Status",
"start_daemon": "Start Daemon",
"stop_daemon": "Stop Daemon",
"queue_list": "Queue List",
"daemon_logs": "Daemon Logs",
"job_id": "Job ID",
"show": "Show",
"logs": "Logs",
"retry": "Retry",
"cancel": "Cancel",
"queue_output": "Queue Runner Output",
"ready": "Ready",
"language": "Language",
"language_en": "English",
"language_zh": "Chinese",
"save": "Save",
"close": "Close",
},
"zh": {
"gpu_tab": "GPU 监控",
"conda_tab": "Conda 环境迁移",
"queue_tab": "任务队列",
"free": "空闲",
"online": "在线",
"busy": "占用",
"auto": "自动",
"every": "每",
"idle": "空闲阈值",
"refresh": "刷新",
"manage_servers": "管理服务器",
"not_refreshed": "尚未刷新",
"preparing": "正在准备连接服务器",
"refreshing_gpu": "正在刷新 GPU 状态...",
"connecting": "正在连接",
"connection_failed": "连接失败",
"reading_gpu": "正在读取 nvidia-smi...",
"nvidia_smi_failed": "无法读取 nvidia-smi,请检查 SSH、网络或服务器状态。",
"free_count": "空闲",
"last_refresh": "最后刷新",
"idle_hint": "绿色表示空闲,红色表示正在使用或显存超过阈值。",
"source_env": "源环境",
"source_env_hint": "将已有环境打包到共享目录",
"target_env": "目标环境",
"target_env_hint": "解压到目标 miniconda 的 envs 目录",
"server": "服务器",
"conda_root": "miniconda 根目录",
"env_name": "环境名",
"target_env_name": "目标环境名",
"source_env_placeholder": "<源环境名>",
"source_server_placeholder": "<源服务器>",
"target_server_placeholder": "<目标服务器>",
"shared_dir": "源共享目录",
"target_shared": "目标共享目录",
"target_shared_hint": "留空表示与源一致",
"overwrite": "目标环境已存在时覆盖",
"start_migration": "开始迁移",
"preview": "流程预览",
"current_state": "当前状态",
"migration_log": "迁移日志",
"clear": "清空",
"waiting": "等待中",
"queue_server": "服务器",
"queue_dir": "远端 gpuq 目录",
"install_sync": "安装/同步",
"add_job": "添加任务",
"name": "名称",
"cwd": "运行目录",
"command": "命令",
"gpus": "GPU",
"queue": "队列",
"priority": "优先级",
"conda_env": "Conda 环境",
"add_to_queue": "加入队列",
"operations": "操作",
"daemon_status": "守护状态",
"start_daemon": "启动守护",
"stop_daemon": "停止守护",
"queue_list": "队列列表",
"daemon_logs": "守护日志",
"job_id": "任务 ID",
"show": "查看",
"logs": "日志",
"retry": "重试",
"cancel": "取消",
"queue_output": "队列输出",
"ready": "就绪",
"language": "语言",
"language_en": "English",
"language_zh": "中文",
"save": "保存",
"close": "关闭",
},
}
BG = "#f5f7fb"
SURFACE = "#ffffff"
SURFACE_SOFT = "#eef3f8"
TEXT = "#17202a"
MUTED = "#607080"
BORDER = "#d7dee8"
GREEN = "#1f8a4c"
GREEN_BG = "#e8f6ef"
RED = "#bd3c2f"
RED_BG = "#fdecea"
AMBER = "#9a6500"
AMBER_BG = "#fff4d8"
BLUE = "#2868c7"
BLUE_BG = "#e8f0ff"
DARK = "#101923"
@dataclass(frozen=True)
class Server:
alias: str
hostname: str
user: str
port: int = 22
ssh_host: str = ""
password: str = ""
@property
def target(self) -> str:
return f"{self.user}@{self.hostname}"
@property
def display_target(self) -> str:
target = f"{self.user}@{self.hostname}:{self.port}"
if self.ssh_host:
return f"{self.ssh_host} -> {target}"
return target
@property
def label(self) -> str:
port = "" if self.port == 22 else f":{self.port}"
# return f"{self.alias} ({self.hostname}{port})"
return f"{self.alias}" # 只显示别名
@dataclass
class GpuInfo:
index: str
uuid: str
name: str
mem_total_mb: int
mem_used_mb: int
util_percent: int
temperature_c: int | None
def is_free(self, util_threshold: int, mem_threshold_mb: int) -> bool:
return self.util_percent <= util_threshold and self.mem_used_mb <= mem_threshold_mb
@property
def mem_percent(self) -> int:
if self.mem_total_mb <= 0:
return 0
return min(100, round(self.mem_used_mb * 100 / self.mem_total_mb))
@dataclass(frozen=True)
class GpuStaticInfo:
index: str
uuid: str
name: str
mem_total_mb: int
def load_servers() -> list[Server]:
if not SERVERS_FILE.exists():
example_file = APP_DIR / "servers.example.json"
if example_file.exists():
return [
Server(alias="example-gpu-01", hostname="192.168.1.101", user="your_user"),
]
raise FileNotFoundError(f"找不到服务器配置文件: {SERVERS_FILE}")
try:
data = json.loads(SERVERS_FILE.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
raise ValueError(
f"servers.json format error: {exc.msg} at line {exc.lineno}, column {exc.colno}.\n"
"Tip: do not leave a comma after the last server item."
) from exc
servers: list[Server] = []
for item in data:
servers.append(
Server(
alias=str(item["alias"]).strip(),
hostname=str(item["hostname"]).strip(),
user=str(item["user"]).strip(),
port=int(item.get("port", 22)),
ssh_host=str(item.get("ssh_host", "")).strip(),
password=str(item.get("password", "")),
)
)
return servers
def save_servers(servers: list[Server]) -> None:
data = [
{
"alias": server.alias,
"hostname": server.hostname,
"user": server.user,
**({"port": server.port} if server.port != 22 else {}),
**({"ssh_host": server.ssh_host} if server.ssh_host else {}),
**({"password": server.password} if server.password else {}),
}
for server in servers
]
tmp = SERVERS_FILE.with_suffix(".json.tmp")
tmp.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
tmp.replace(SERVERS_FILE)
def load_app_settings() -> dict[str, str]:
if not SETTINGS_FILE.exists():
return {"language": "en"}
try:
data = json.loads(SETTINGS_FILE.read_text(encoding="utf-8"))
except Exception:
return {"language": "en"}
language = str(data.get("language", "en"))
return {"language": language if language in TEXTS else "en"}
def save_app_settings(settings: dict[str, str]) -> None:
SETTINGS_FILE.write_text(json.dumps(settings, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
def ssh_binary() -> str:
path = shutil.which("ssh")
if not path:
raise RuntimeError("找不到 ssh。请在 Windows 中启用 OpenSSH Client。")
return path
def ssh_args(server: Server, timeout_s: int = SSH_TIMEOUT_S) -> list[str]:
if server.password:
raise RuntimeError("This server is configured for password login. Install/use paramiko for password-based commands.")
args = [
ssh_binary(),
"-o",
"BatchMode=yes",
"-o",
f"ConnectTimeout={timeout_s}",
]
if DEFAULT_IDENTITY_FILE.exists():
args.extend(["-i", str(DEFAULT_IDENTITY_FILE), "-o", "IdentitiesOnly=yes"])
if server.port != 22:
args.extend(["-p", str(server.port)])
args.append(server.target)
return args
def connect_ssh_client(server: Server):
if paramiko is None:
raise RuntimeError("paramiko is not installed")
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
kwargs = {
"hostname": server.hostname,
"username": server.user,
"port": server.port,
"timeout": SSH_TIMEOUT_S,
"banner_timeout": SSH_TIMEOUT_S,
"auth_timeout": SSH_TIMEOUT_S,
}
if server.password:
kwargs["password"] = server.password
kwargs["look_for_keys"] = False
kwargs["allow_agent"] = False
elif DEFAULT_IDENTITY_FILE.exists():
kwargs["key_filename"] = str(DEFAULT_IDENTITY_FILE)
kwargs["look_for_keys"] = False
kwargs["allow_agent"] = False
else:
kwargs["look_for_keys"] = True
kwargs["allow_agent"] = True
client.connect(**kwargs)
transport = client.get_transport()
if transport is not None:
transport.set_keepalive(20)
return client
def run_remote_script(server: Server, script: str, timeout_s: int = 120) -> subprocess.CompletedProcess[str]:
if paramiko is not None:
client = connect_ssh_client(server)
try:
command = "bash -s"
stdin, stdout, stderr = client.exec_command(command, timeout=None)
stdout.channel.settimeout(None)
stdin.write(script.replace("\r\n", "\n").replace("\r", "\n"))
stdin.channel.shutdown_write()
out = stdout.read().decode("utf-8", "replace")
err = stderr.read().decode("utf-8", "replace")
code = stdout.channel.recv_exit_status()
return subprocess.CompletedProcess(command, code, out, err)
finally:
client.close()
args = ssh_args(server, min(timeout_s, SSH_TIMEOUT_S)) + ["bash", "-s"]
script_bytes = script.replace("\r\n", "\n").replace("\r", "\n").encode("utf-8")
proc = subprocess.run(
args,
input=script_bytes,
capture_output=True,
timeout=timeout_s,
check=False,
)
return subprocess.CompletedProcess(
proc.args,
proc.returncode,
proc.stdout.decode("utf-8", "replace"),
proc.stderr.decode("utf-8", "replace"),
)
class PersistentSshPool:
def __init__(self) -> None:
self._clients: dict[str, object] = {}
self._locks: dict[str, threading.Lock] = {}
self._guard = threading.Lock()
def close_all(self) -> None:
with self._guard:
clients = list(self._clients.values())
self._clients.clear()
self._locks.clear()
for client in clients:
try:
client.close()
except Exception:
pass
def run(self, server: Server, command: str, timeout_s: int = 20) -> subprocess.CompletedProcess[str]:
if paramiko is None:
return run_remote_script(server, command, timeout_s=timeout_s)
lock = self._lock_for(server)
with lock:
client = self._client_for(server)
try:
return self._exec(client, command, timeout_s)
except Exception:
self._drop(server)
client = self._client_for(server)
return self._exec(client, command, timeout_s)
def _key(self, server: Server) -> str:
return server.alias
def _lock_for(self, server: Server) -> threading.Lock:
key = self._key(server)
with self._guard:
if key not in self._locks:
self._locks[key] = threading.Lock()
return self._locks[key]
def _client_for(self, server: Server):
key = self._key(server)
with self._guard:
client = self._clients.get(key)
if client is not None and self._is_alive(client):
return client
if paramiko is None:
raise RuntimeError("paramiko is not installed")
client = connect_ssh_client(server)
with self._guard:
self._clients[key] = client
return client
def _drop(self, server: Server) -> None:
key = self._key(server)
with self._guard:
client = self._clients.pop(key, None)
if client is not None:
try:
client.close()
except Exception:
pass
def _is_alive(self, client: object) -> bool:
try:
transport = client.get_transport()
return bool(transport and transport.is_active())
except Exception:
return False
def _exec(self, client: object, command: str, timeout_s: int) -> subprocess.CompletedProcess[str]:
stdin, stdout, stderr = client.exec_command(command, timeout=timeout_s)
try:
stdin.close()
except Exception:
pass
out = stdout.read().decode("utf-8", "replace")
err = stderr.read().decode("utf-8", "replace")
code = stdout.channel.recv_exit_status()
return subprocess.CompletedProcess(command, code, out, err)
def parse_int(value: str, default: int = 0) -> int:
try:
return int(str(value).strip())
except (TypeError, ValueError):
return default
def parse_gpu_csv(text: str) -> list[GpuInfo]:
rows = csv.reader(line for line in text.splitlines() if line.strip())
gpus: list[GpuInfo] = []
for row in rows:
if len(row) < 7:
continue
index, uuid, name, mem_total, mem_used, util, temp = [cell.strip() for cell in row[:7]]
temperature = None if temp in {"", "[Not Supported]", "N/A"} else parse_int(temp, 0)
gpus.append(
GpuInfo(
index=index,
uuid=uuid,
name=name,
mem_total_mb=parse_int(mem_total),
mem_used_mb=parse_int(mem_used),
util_percent=parse_int(util),
temperature_c=temperature,
)
)
return gpus
def parse_gpu_static_csv(text: str) -> dict[str, GpuStaticInfo]:
rows = csv.reader(line for line in text.splitlines() if line.strip())
items: dict[str, GpuStaticInfo] = {}
for row in rows:
if len(row) < 4:
continue
index, uuid, name, mem_total = [cell.strip() for cell in row[:4]]
items[index] = GpuStaticInfo(
index=index,
uuid=uuid,
name=name,
mem_total_mb=parse_int(mem_total),
)
return items
def parse_gpu_dynamic_csv(text: str, static_info: dict[str, GpuStaticInfo]) -> list[GpuInfo]:
rows = csv.reader(line for line in text.splitlines() if line.strip())
gpus: list[GpuInfo] = []
for row in rows:
if len(row) < 4:
continue
index, mem_used, util, temp = [cell.strip() for cell in row[:4]]
cached = static_info.get(index)
if cached is None:
continue
temperature = None if temp in {"", "[Not Supported]", "N/A"} else parse_int(temp, 0)
gpus.append(
GpuInfo(
index=index,
uuid=cached.uuid,
name=cached.name,
mem_total_mb=cached.mem_total_mb,
mem_used_mb=parse_int(mem_used),
util_percent=parse_int(util),
temperature_c=temperature,
)
)
return gpus
def query_gpus(
server: Server,
pool: PersistentSshPool | None = None,
static_info: dict[str, GpuStaticInfo] | None = None,
) -> tuple[list[GpuInfo], dict[str, GpuStaticInfo], str]:
dynamic_command = "nvidia-smi --query-gpu=index,memory.used,utilization.gpu,temperature.gpu --format=csv,noheader,nounits"
full_command = "nvidia-smi --query-gpu=index,uuid,name,memory.total,memory.used,utilization.gpu,temperature.gpu --format=csv,noheader,nounits"
if static_info:
proc = pool.run(server, dynamic_command, timeout_s=20) if pool else run_remote_script(server, dynamic_command, timeout_s=20)
if proc.returncode == 0:
gpus = parse_gpu_dynamic_csv(proc.stdout, static_info)
if gpus and len(gpus) == len(static_info):
return gpus, static_info, ""
proc = pool.run(server, full_command, timeout_s=20) if pool else run_remote_script(server, full_command, timeout_s=20)
if proc.returncode != 0:
err = (proc.stderr or proc.stdout).strip()
return [], static_info or {}, err or f"ssh exit code {proc.returncode}"
gpus = parse_gpu_csv(proc.stdout)
refreshed_static = {
gpu.index: GpuStaticInfo(
index=gpu.index,
uuid=gpu.uuid,
name=gpu.name,
mem_total_mb=gpu.mem_total_mb,
)
for gpu in gpus
}
return gpus, refreshed_static, ""
def shell_single_quote(value: str) -> str:
return "'" + value.replace("'", "'\"'\"'") + "'"
def pack_script(conda_root: str, env_name: str, shared_dir: str) -> str:
return f"""set -euo pipefail
CONDA_ROOT={shell_single_quote(conda_root)}
ENV_NAME={shell_single_quote(env_name)}
SHARED_DIR={shell_single_quote(shared_dir)}
PACK_DIR="$SHARED_DIR/conda-packs"
ENV_DIR="$CONDA_ROOT/envs/$ENV_NAME"
mkdir -p "$PACK_DIR"
if [ ! -x "$CONDA_ROOT/bin/conda" ]; then
echo "Cannot find conda executable: $CONDA_ROOT/bin/conda" >&2
exit 10
fi
if [ ! -d "$ENV_DIR" ]; then
echo "Cannot find conda env directory: $ENV_DIR" >&2
echo "Available envs under $CONDA_ROOT/envs:" >&2
ls -1 "$CONDA_ROOT/envs" >&2 || true
exit 13
fi
if [ -x "$CONDA_ROOT/bin/conda-pack" ]; then
PACK_CMD="$CONDA_ROOT/bin/conda-pack"
elif "$CONDA_ROOT/bin/python" -c "import conda_pack" >/dev/null 2>&1; then
PACK_CMD="$CONDA_ROOT/bin/python -m conda_pack"
else
echo "conda-pack is not installed in base. Installing it automatically..."
if "$CONDA_ROOT/bin/python" -m pip --version >/dev/null 2>&1; then
"$CONDA_ROOT/bin/python" -m pip install conda-pack || "$CONDA_ROOT/bin/python" -m pip install -i https://pypi.tuna.tsinghua.edu.cn/simple conda-pack
else
"$CONDA_ROOT/bin/conda" install -y -n base -c conda-forge conda-pack
fi
if [ -x "$CONDA_ROOT/bin/conda-pack" ]; then
PACK_CMD="$CONDA_ROOT/bin/conda-pack"
elif "$CONDA_ROOT/bin/python" -c "import conda_pack" >/dev/null 2>&1; then
PACK_CMD="$CONDA_ROOT/bin/python -m conda_pack"
else
echo "Failed to install conda-pack automatically. Install it manually in base and retry." >&2
exit 12
fi
fi
STAMP="$(date +%Y%m%d-%H%M%S)"
HOST="$(hostname -s 2>/dev/null || hostname)"
ARCHIVE="$PACK_DIR/${{ENV_NAME}}_${{HOST}}_${{STAMP}}.tar.gz"
echo "Packing $ENV_NAME to $ARCHIVE"
$PACK_CMD -p "$ENV_DIR" -o "$ARCHIVE" --force --ignore-missing-files --ignore-editable-packages
chmod a+r "$ARCHIVE" || true
echo "__ARCHIVE__=$ARCHIVE"
"""
def unpack_script(
conda_root: str,
target_env_name: str,
archive_path: str,
overwrite: bool,
source_shared_dir: str = "",
target_shared_dir: str = "",
) -> str:
overwrite_flag = "1" if overwrite else "0"
return f"""set -euo pipefail
CONDA_ROOT={shell_single_quote(conda_root)}
TARGET_ENV_NAME={shell_single_quote(target_env_name)}
ARCHIVE={shell_single_quote(archive_path)}
SOURCE_SHARED_DIR={shell_single_quote(source_shared_dir)}
TARGET_SHARED_DIR={shell_single_quote(target_shared_dir)}
OVERWRITE={overwrite_flag}
if [ -n "$SOURCE_SHARED_DIR" ] && [ -n "$TARGET_SHARED_DIR" ] && [ "$SOURCE_SHARED_DIR" != "$TARGET_SHARED_DIR" ]; then
case "$ARCHIVE" in
"$SOURCE_SHARED_DIR"/*)
ARCHIVE="$TARGET_SHARED_DIR/${{ARCHIVE#"$SOURCE_SHARED_DIR"/}}"
;;
esac
fi
DEST="$CONDA_ROOT/envs/$TARGET_ENV_NAME"
if [ ! -x "$CONDA_ROOT/bin/conda" ]; then
echo "Cannot find conda executable: $CONDA_ROOT/bin/conda" >&2
exit 20
fi
if [ ! -f "$ARCHIVE" ]; then
echo "Archive is not visible on target server: $ARCHIVE" >&2
exit 21
fi
if [ -e "$DEST" ]; then
if [ "$OVERWRITE" = "1" ]; then
rm -rf "$DEST"
else
echo "Target env already exists: $DEST" >&2
echo "Enable overwrite if you really want to replace it." >&2
exit 22
fi
fi
mkdir -p "$DEST"
echo "Unpacking $ARCHIVE to $DEST"
tar -xzf "$ARCHIVE" -C "$DEST"
if [ -x "$DEST/bin/conda-unpack" ]; then
PATH="$DEST/bin:$PATH" "$DEST/bin/conda-unpack"
else
echo "Warning: conda-unpack was not found. The env may still contain old absolute paths." >&2
fi
echo "__DEST__=$DEST"
"""
def gpuq_install_script(remote_dir: str, payload_b64: str) -> str:
return f"""set -euo pipefail
REMOTE_DIR={shell_single_quote(remote_dir)}
PAYLOAD={shell_single_quote(payload_b64)}
mkdir -p "$REMOTE_DIR"
printf '%s' "$PAYLOAD" | base64 -d > "$REMOTE_DIR/gpuq"
chmod +x "$REMOTE_DIR/gpuq"
cd "$REMOTE_DIR"
./gpuq init
./gpuq doctor
echo "__GPUQ_DIR__=$REMOTE_DIR"
"""
def gpuq_command_script(remote_dir: str, args: list[str]) -> str:
quoted_args = " ".join(shell_single_quote(arg) for arg in args)
return f"""set -euo pipefail
REMOTE_DIR={shell_single_quote(remote_dir)}
if [ ! -x "$REMOTE_DIR/gpuq" ]; then
echo "gpuq is not installed or executable at: $REMOTE_DIR/gpuq" >&2
exit 80
fi
cd "$REMOTE_DIR"
./gpuq {quoted_args}
"""
class ScrollFrame(tk.Frame):
def __init__(self, parent: tk.Widget) -> None:
super().__init__(parent, bg=BG)
self.canvas = tk.Canvas(self, bg=BG, highlightthickness=0)
self.scrollbar = ttk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
self.inner = tk.Frame(self.canvas, bg=BG)
self.window_id = self.canvas.create_window((0, 0), window=self.inner, anchor="nw")
self.canvas.configure(yscrollcommand=self.scrollbar.set)
self.canvas.grid(row=0, column=0, sticky="nsew")
self.scrollbar.grid(row=0, column=1, sticky="ns")
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
self.inner.bind("<Configure>", self._on_inner_configure)
self.canvas.bind("<Configure>", self._on_canvas_configure)
self.canvas.bind_all("<MouseWheel>", self._on_mousewheel)
def _on_inner_configure(self, _event: tk.Event) -> None:
self.canvas.configure(scrollregion=self.canvas.bbox("all"))
def _on_canvas_configure(self, event: tk.Event) -> None:
self.canvas.itemconfigure(self.window_id, width=event.width)
def _on_mousewheel(self, event: tk.Event) -> None:
if self.winfo_containing(event.x_root, event.y_root):
bbox = self.canvas.bbox("all")
if not bbox:
return
content_height = bbox[3] - bbox[1]
if content_height <= self.canvas.winfo_height():
self.canvas.yview_moveto(0)
return
self.canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
class ServerSettingsWindow(tk.Toplevel):
def __init__(self, app: "App", servers: list[Server]) -> None:
super().__init__(app)
self.app = app
self.title("Server Settings")
self.geometry("620x420")
self.minsize(600, 400)
self.configure(bg=BG)
self.servers = list(servers)
self.alias_var = tk.StringVar()
self.hostname_var = tk.StringVar()
self.port_var = tk.StringVar(value="22")
self.user_var = tk.StringVar(value="your_user")
self.password_var = tk.StringVar()
self.transient(app)
self._build()
self._refresh_list()
def _build(self) -> None:
body = tk.Frame(self, bg=BG, padx=12, pady=12)
body.pack(fill="both", expand=True)
body.grid_columnconfigure(0, weight=1)
body.grid_columnconfigure(1, weight=1)
body.grid_rowconfigure(1, weight=1)
tk.Label(body, text="Servers", bg=BG, fg=TEXT, font=("Segoe UI", 13, "bold")).grid(row=0, column=0, sticky="w")
tk.Label(body, text="Edit alias, host, and user for GPU polling.", bg=BG, fg=MUTED).grid(row=0, column=1, sticky="e")
list_frame = tk.Frame(body, bg=SURFACE, bd=1, relief="solid", padx=8, pady=8)
list_frame.grid(row=1, column=0, sticky="nsew", padx=(0, 8), pady=(10, 10))
list_frame.grid_rowconfigure(0, weight=1)
list_frame.grid_columnconfigure(0, weight=1)
self.listbox = tk.Listbox(list_frame, height=12, exportselection=False)
self.listbox.grid(row=0, column=0, sticky="nsew")
scrollbar = ttk.Scrollbar(list_frame, orient="vertical", command=self.listbox.yview)
scrollbar.grid(row=0, column=1, sticky="ns")
self.listbox.configure(yscrollcommand=scrollbar.set)
self.listbox.bind("<<ListboxSelect>>", self._on_select)
form = tk.Frame(body, bg=SURFACE, bd=1, relief="solid", padx=12, pady=12)
form.grid(row=1, column=1, sticky="nsew", pady=(10, 10))
form.grid_columnconfigure(1, weight=1)
tk.Label(form, text="Alias", bg=SURFACE, fg=MUTED).grid(row=0, column=0, sticky="w", pady=6)
ttk.Entry(form, textvariable=self.alias_var).grid(row=0, column=1, sticky="ew", pady=6)
tk.Label(form, text="Host/IP", bg=SURFACE, fg=MUTED).grid(row=1, column=0, sticky="w", pady=6)
ttk.Entry(form, textvariable=self.hostname_var).grid(row=1, column=1, sticky="ew", pady=6)
tk.Label(form, text="Port", bg=SURFACE, fg=MUTED).grid(row=2, column=0, sticky="w", pady=6)
ttk.Entry(form, textvariable=self.port_var).grid(row=2, column=1, sticky="ew", pady=6)
tk.Label(form, text="User", bg=SURFACE, fg=MUTED).grid(row=3, column=0, sticky="w", pady=6)
ttk.Entry(form, textvariable=self.user_var).grid(row=3, column=1, sticky="ew", pady=6)
tk.Label(form, text="Password", bg=SURFACE, fg=MUTED).grid(row=4, column=0, sticky="w", pady=6)
ttk.Entry(form, textvariable=self.password_var, show="*").grid(row=4, column=1, sticky="ew", pady=6)
tk.Label(form, text="Leave blank to use SSH key.", bg=SURFACE, fg=MUTED, font=("Segoe UI", 8)).grid(row=5, column=1, sticky="w")
actions = tk.Frame(form, bg=SURFACE)
actions.grid(row=6, column=0, columnspan=2, sticky="ew", pady=(12, 0))
ttk.Button(actions, text="Add", command=self._add).pack(side="left")
ttk.Button(actions, text="Update", command=self._update).pack(side="left", padx=6)
ttk.Button(actions, text="Delete", command=self._delete).pack(side="left")
ttk.Button(actions, text="Clear", command=self._clear).pack(side="left", padx=6)
bottom = tk.Frame(body, bg=BG)
bottom.grid(row=2, column=0, columnspan=2, sticky="ew")
ttk.Button(bottom, text="Cancel", command=self.destroy).pack(side="right")
ttk.Button(bottom, text="Save && Apply", command=self._save).pack(side="right", padx=8)
def _refresh_list(self) -> None:
self.listbox.delete(0, "end")
for server in self.servers:
auth = "password" if server.password else "key"
self.listbox.insert("end", f"{server.alias} {server.user}@{server.hostname}:{server.port} [{auth}]")
def _selected_index(self) -> int | None:
selection = self.listbox.curselection()
if not selection:
return None
return int(selection[0])
def _on_select(self, _event: tk.Event) -> None:
idx = self._selected_index()
if idx is None:
return
server = self.servers[idx]
self.alias_var.set(server.alias)
self.hostname_var.set(server.hostname)
self.port_var.set(str(server.port))
self.user_var.set(server.user)
self.password_var.set(server.password)
def _read_form(self) -> Server | None:
alias = self.alias_var.get().strip()
hostname = self.hostname_var.get().strip()
port_text = self.port_var.get().strip() or "22"
user = self.user_var.get().strip()
password = self.password_var.get()
if not alias or not hostname or not user:
messagebox.showerror("Missing Field", "Alias, host/IP, and user are required.", parent=self)
return None
if any(ch.isspace() for ch in alias):
messagebox.showerror("Invalid Alias", "Alias cannot contain whitespace.", parent=self)
return None
try:
port = int(port_text)
except ValueError:
messagebox.showerror("Invalid Port", "Port must be a number.", parent=self)
return None
if port < 1 or port > 65535:
messagebox.showerror("Invalid Port", "Port must be between 1 and 65535.", parent=self)
return None
return Server(alias=alias, hostname=hostname, port=port, user=user, password=password)
def _add(self) -> None:
server = self._read_form()
if server is None:
return
if any(existing.alias == server.alias for existing in self.servers):
messagebox.showerror("Duplicate Alias", "Alias already exists. Use Update instead.", parent=self)
return
self.servers.append(server)
self._refresh_list()
self.listbox.selection_clear(0, "end")
self.listbox.selection_set(len(self.servers) - 1)
def _update(self) -> None:
idx = self._selected_index()
if idx is None:
messagebox.showinfo("No Selection", "Select a server to update.", parent=self)
return
server = self._read_form()
if server is None:
return
if any(i != idx and existing.alias == server.alias for i, existing in enumerate(self.servers)):
messagebox.showerror("Duplicate Alias", "Alias already exists.", parent=self)
return
self.servers[idx] = server
self._refresh_list()
self.listbox.selection_set(idx)
def _delete(self) -> None:
idx = self._selected_index()
if idx is None:
messagebox.showinfo("No Selection", "Select a server to delete.", parent=self)
return
del self.servers[idx]
self._refresh_list()
self._clear()
def _clear(self) -> None:
self.alias_var.set("")
self.hostname_var.set("")
self.port_var.set("22")
self.user_var.set("your_user")
self.password_var.set("")
self.listbox.selection_clear(0, "end")
def _save(self) -> None:
if not self.servers:
messagebox.showerror("No Servers", "Add at least one server.", parent=self)
return
self.app.apply_server_settings(self.servers)
self.destroy()
class App(tk.Tk):
def __init__(self) -> None:
super().__init__()
self.title("GPU Server Control")
self.geometry("1260x820")
self.minsize(980, 620)
self.configure(bg=BG)
self.app_settings = load_app_settings()
self.language = self.app_settings.get("language", "en")
self.servers = load_servers()
self.server_by_label = {server.label: server for server in self.servers}
self.result_queue: queue.Queue[tuple[str, object]] = queue.Queue()
self.refresh_running = False
self.migration_running = False
self.auto_refresh = tk.BooleanVar(value=True)
self.refresh_interval_s = tk.IntVar(value=5)
self.util_threshold = tk.IntVar(value=5)
self.mem_threshold_mb = tk.IntVar(value=1000)
self.last_refresh_at = tk.StringVar(value=self.tr("not_refreshed"))
self.summary_free_var = tk.StringVar(value="-")
self.summary_online_var = tk.StringVar(value="-")
self.summary_busy_var = tk.StringVar(value="-")
self.summary_hint_var = tk.StringVar(value=self.tr("preparing"))
self.status_vars: dict[str, dict[str, tk.StringVar]] = {}
self.gpu_frames: dict[str, tk.Frame] = {}
self.count_labels: dict[str, tk.Label] = {}
self.gpu_widgets: dict[str, dict[str, dict[str, object]]] = {}
self.gpu_static_cache: dict[str, dict[str, GpuStaticInfo]] = {}
self.queue_running = False
self.ssh_pool = PersistentSshPool()
self.settings_window: tk.Toplevel | None = None
self._build_menu()
self._configure_style()
self._build_ui()
self.protocol("WM_DELETE_WINDOW", self._on_close)
self.after(200, self._poll_queue)
self.after(500, self.refresh_gpus)
self.after(1000, self._auto_refresh_tick)
def tr(self, key: str) -> str:
return TEXTS.get(self.language, TEXTS["en"]).get(key, TEXTS["en"].get(key, key))
def set_language(self, language: str) -> None:
if language not in TEXTS:
language = "en"
self.language = language
self.app_settings["language"] = language
save_app_settings(self.app_settings)
self._rebuild_tabs()
def _set_language_from_menu(self, language: str) -> None:
self.set_language(language)
def _build_menu(self) -> None:
menu = tk.Menu(self)
language_menu = tk.Menu(menu, tearoff=0)
language_menu.add_command(label=self.tr("language_en"), command=lambda: self._set_language_from_menu("en"))
language_menu.add_command(label=self.tr("language_zh"), command=lambda: self._set_language_from_menu("zh"))
menu.add_cascade(label=self.tr("language"), menu=language_menu)
self.config(menu=menu)
self.menu_bar = menu