-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathghx_server.py
More file actions
5031 lines (4212 loc) · 208 KB
/
ghx_server.py
File metadata and controls
5031 lines (4212 loc) · 208 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
GHX (GPU Health Expert) 统一服务 - 集成数据收集、节点状态查询和Job管理
整合了原gpu_collector_service和gpu_cli的功能
提供完整的GPU健康检查解决方案
"""
import sqlite3
from datetime import datetime, timedelta
from datetime import timezone
from functools import wraps
import json
import logging
import os
import subprocess
import time
import uuid
import glob
import queue
import threading
import yaml
from typing import Dict, Any, List, Optional
from flask import Flask, request, jsonify, Response
from flask_cors import CORS
# 添加kubernetes客户端导入
try:
from kubernetes import client, config, watch
from kubernetes.client.rest import ApiException
KUBERNETES_AVAILABLE = True
except ImportError:
KUBERNETES_AVAILABLE = False
print("Warning: kubernetes package not available, falling back to kubectl commands")
# 导入backend_rate_limit模块
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('/var/log/ghx_service.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
try:
from backend_rate_limit import (
get_rate_limit_decorator,
setup_rate_limit_error_handlers,
init_rate_limit,
get_rate_limit_stats,
log_rate_limit_event
)
logger.info("成功导入backend_rate_limit模块")
except ImportError:
logger.warning("无法导入backend_rate_limit模块,使用简单限流")
def get_rate_limit_decorator():
"""简单的限流装饰器"""
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
return f(*args, **kwargs)
return decorated_function
return decorator
def setup_rate_limit_error_handlers(app):
"""设置限流错误处理器"""
pass
def init_rate_limit(app, use_redis=False, use_flask_limiter=False):
"""初始化限流"""
return "simple"
def get_rate_limit_stats():
"""获取限流统计"""
return {}
def log_rate_limit_event(client_ip, action, result):
"""记录限流事件"""
logger.info(f"限流事件: {client_ip} - {action} - {result}")
# 创建Flask应用
app = Flask(__name__)
# ==================== CORS配置 ====================
def get_cors_origins():
"""获取CORS允许的源地址"""
# 默认的CORS地址(开发环境常用地址)
origins = [
"http://localhost:3000",
"http://localhost:31033",
"http://127.0.0.1:3000",
"http://127.0.0.1:31033"
]
# 从环境变量获取CORS_ORIGINS,支持多个地址用逗号分隔
cors_origins_env = os.getenv('CORS_ORIGINS', '')
if cors_origins_env:
# 如果设置了环境变量,在默认地址基础上添加环境变量中的地址
additional_origins = [origin.strip() for origin in cors_origins_env.split(',') if origin.strip()]
origins.extend(additional_origins)
# 去重并过滤空值
origins = list(set([origin for origin in origins if origin]))
logger.info(f"CORS允许的源地址: {origins}")
return origins
# 配置CORS
CORS(app,
origins=get_cors_origins(),
methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allow_headers=["Content-Type", "Authorization", "X-Requested-With"],
supports_credentials=True)
# ==================== 实时Job状态监听 ====================
# 存储所有SSE连接的客户端
sse_clients = set()
# 定时状态检查线程
status_check_thread = None
status_check_running = False
# 添加全局变量用于Informer机制
pod_cache = {} # 本地Pod缓存
last_resource_version = None # 资源版本控制
last_sync_time = 0 # 上次同步时间
sync_interval = 300 # 同步间隔(5分钟)
def notify_job_status_change(job_id: str, status: str, node_name: str = None):
"""通知所有SSE客户端Job状态变化"""
global sse_clients
message = {
"type": "job_status_change",
"job_id": job_id,
"status": status,
"node_name": node_name,
"timestamp": time.time()
}
logger.info(f"准备通知SSE客户端: {message}")
if not sse_clients:
logger.warning("没有SSE客户端连接,无法发送状态更新")
return
# 移除断开的连接
disconnected_clients = set()
for client in sse_clients:
try:
client.put(f"data: {json.dumps(message)}\n\n")
logger.debug(f"已发送状态更新到SSE客户端: {job_id} -> {status}")
except Exception as e:
logger.warning(f"发送状态更新到SSE客户端失败: {e}")
disconnected_clients.add(client)
# 清理断开的连接
sse_clients -= disconnected_clients
if disconnected_clients:
logger.info(f"清理了 {len(disconnected_clients)} 个断开的SSE连接")
logger.info(f"成功通知 {len(sse_clients) - len(disconnected_clients)} 个SSE客户端Job状态变化")
def notify_diagnostic_results_update():
"""通知SSE客户端诊断结果已更新"""
global sse_clients
message = {
"type": "diagnostic_results_updated",
"message": "诊断结果已更新,请刷新查看",
"timestamp": time.time()
}
logger.info("准备通知SSE客户端诊断结果已更新")
if not sse_clients:
logger.warning("没有SSE客户端连接,无法发送诊断结果更新通知")
return
# 移除断开的连接
disconnected_clients = set()
for client in sse_clients:
try:
client.put(f"data: {json.dumps(message)}\n\n")
logger.debug(f"已发送诊断结果更新通知到SSE客户端")
except Exception as e:
logger.warning(f"发送诊断结果更新通知到SSE客户端失败: {e}")
disconnected_clients.add(client)
# 清理断开的连接
sse_clients -= disconnected_clients
if disconnected_clients:
logger.info(f"清理了 {len(disconnected_clients)} 个断开的SSE连接")
logger.info(f"成功通知 {len(sse_clients) - len(disconnected_clients)} 个SSE客户端诊断结果已更新")
def get_kubernetes_job_status(job_id: str):
"""获取Kubernetes Job的实时状态"""
try:
# 首先查找所有匹配的Job(因为一个job_id可能对应多个节点的Job)
# 尝试多种标签选择器
job_found = False
jobs = []
# 策略1: 使用job-id标签
result = subprocess.run([
'kubectl', 'get', 'jobs', '-n', 'gpu-health-expert',
'-l', f'job-id={job_id}', '-o', 'json'
], capture_output=True, text=True, timeout=30)
if result.returncode == 0:
jobs_data = json.loads(result.stdout)
jobs = jobs_data.get('items', [])
if jobs:
logger.info(f"通过job-id标签找到 {len(jobs)} 个Job")
job_found = True
# 策略2: 如果策略1失败,尝试通过Job名称模式查找
if not job_found:
logger.info(f"通过job-id标签未找到Job,尝试通过名称模式查找: {job_id}")
result = subprocess.run([
'kubectl', 'get', 'jobs', '-n', 'gpu-health-expert',
'-o', 'json'
], capture_output=True, text=True, timeout=30)
if result.returncode == 0:
all_jobs_data = json.loads(result.stdout)
all_jobs = all_jobs_data.get('items', [])
# 查找名称包含job_id的Job
for job in all_jobs:
job_name = job.get('metadata', {}).get('name', '')
if job_id in job_name:
jobs.append(job)
logger.info(f"通过名称模式找到Job: {job_name}")
if jobs:
job_found = True
logger.info(f"通过名称模式找到 {len(jobs)} 个Job")
if not job_found:
logger.warning(f"未找到匹配的Job: job-id={job_id}")
return None
# 合并所有Job的状态
total_completions = 0
total_failed = 0
total_active = 0
all_pod_statuses = []
for job in jobs:
job_status = job.get('status', {})
total_completions += job_status.get('succeeded', 0)
total_failed += job_status.get('failed', 0)
total_active += job_status.get('active', 0)
# 获取每个Job的Pod状态
job_name = job.get('metadata', {}).get('name', '')
if job_name:
try:
pod_result = subprocess.run([
'kubectl', 'get', 'pods', '-n', 'gpu-health-expert',
'-l', f'job-name={job_name}', '-o', 'json'
], capture_output=True, text=True, timeout=30)
if pod_result.returncode == 0:
pods_data = json.loads(pod_result.stdout)
pods = pods_data.get('items', [])
for pod in pods:
pod_phase = pod.get('status', {}).get('phase', 'Unknown')
container_statuses = pod.get('status', {}).get('containerStatuses', [])
logger.info(f"Pod {pod.get('metadata', {}).get('name', 'unknown')} 状态分析:")
logger.info(f" - pod_phase: {pod_phase}")
logger.info(f" - container_statuses: {len(container_statuses)} 个容器")
# 首先检查容器状态,因为它更准确反映实际运行状态
if container_statuses:
container_status = container_statuses[0]
container_state = container_status.get('state', {})
logger.info(f" - container_state: {container_state}")
if container_state.get('running'):
all_pod_statuses.append('Running')
logger.info(f" - 检测到Running状态 (来自container_state)")
elif container_state.get('terminated'):
exit_code = container_state['terminated'].get('exitCode', 0)
if exit_code == 0:
all_pod_statuses.append('Completed')
logger.info(f" - 检测到Completed状态 (来自container_state)")
else:
reason = container_state['terminated'].get('reason', 'Error')
all_pod_statuses.append(f'Failed: {reason}')
logger.info(f" - 检测到Failed状态 (来自container_state): {reason}")
elif container_state.get('waiting'):
reason = container_state['waiting'].get('reason', 'Waiting')
all_pod_statuses.append(f'Waiting: {reason}')
logger.info(f" - 检测到Waiting状态 (来自container_state): {reason}")
else:
# 如果没有明确的容器状态,使用pod_phase
if pod_phase == 'Running':
all_pod_statuses.append('Running')
logger.info(f" - 检测到Running状态 (来自pod_phase)")
elif pod_phase == 'Completed':
all_pod_statuses.append('Completed')
logger.info(f" - 检测到Completed状态 (来自pod_phase)")
elif pod_phase == 'Failed':
all_pod_statuses.append('Failed')
logger.info(f" - 检测到Failed状态 (来自pod_phase)")
else:
all_pod_statuses.append(pod_phase)
logger.info(f" - 使用pod_phase: {pod_phase}")
else:
# 没有容器状态,使用pod_phase
if pod_phase == 'Running':
all_pod_statuses.append('Running')
logger.info(f" - 检测到Running状态 (来自pod_phase)")
elif pod_phase == 'Completed':
all_pod_statuses.append('Completed')
logger.info(f" - 检测到Completed状态 (来自pod_phase)")
elif pod_phase == 'Failed':
all_pod_statuses.append('Failed')
logger.info(f" - 检测到Failed状态 (来自pod_phase)")
elif pod_phase == 'Pending':
all_pod_statuses.append('Pending')
logger.info(f" - 检测到Pending状态 (来自pod_phase)")
else:
all_pod_statuses.append(pod_phase)
logger.info(f" - 使用pod_phase: {pod_phase}")
# 额外检查:如果pod_phase是Running但容器状态为空,可能是容器刚启动
if pod_phase == 'Running' and not container_statuses:
logger.info(f" - Pod状态为Running但容器状态为空,可能是容器刚启动")
all_pod_statuses.append('Running')
except Exception as e:
logger.warning(f"获取Pod状态失败: {e}")
# 确定整体状态
if total_failed > 0:
status = 'Failed'
elif total_completions > 0 and total_active == 0:
status = 'Completed'
elif total_active > 0:
status = 'Running'
else:
status = 'Pending'
# 确定Pod状态 - 优先使用Pod的实际状态
if not all_pod_statuses:
pod_status = 'Unknown'
else:
# 统计各种状态的数量
running_count = sum(1 for s in all_pod_statuses if 'Running' in s)
completed_count = sum(1 for s in all_pod_statuses if 'Completed' in s)
failed_count = sum(1 for s in all_pod_statuses if 'Failed' in s)
waiting_count = sum(1 for s in all_pod_statuses if 'Waiting' in s)
pending_count = sum(1 for s in all_pod_statuses if s == 'Pending')
logger.info(f"Pod状态统计: Running={running_count}, Completed={completed_count}, Failed={failed_count}, Waiting={waiting_count}, Pending={pending_count}")
if failed_count > 0:
pod_status = 'Failed'
elif completed_count > 0 and running_count == 0 and waiting_count == 0 and pending_count == 0:
pod_status = 'Completed'
elif running_count > 0:
pod_status = 'Running'
elif waiting_count > 0 or pending_count > 0:
pod_status = 'Pending' # 统一使用Pending状态
else:
pod_status = 'Unknown'
logger.info(f"Job {job_id} 最终状态: {status}, Pod状态: {pod_status}")
logger.info(f"Job统计: completions={total_completions}, failed={total_failed}, active={total_active}")
logger.info(f"Pod状态列表: {all_pod_statuses}")
return {
'pod_status': pod_status,
'job_status': status,
'total_completions': total_completions,
'total_failed': total_failed,
'total_active': total_active,
'all_pod_statuses': all_pod_statuses
}
except Exception as e:
logger.error(f"获取Kubernetes Job状态失败: {e}")
return None
def extract_job_id_from_pod_name(pod_name):
"""从Pod名称中提取job_id"""
try:
# Pod名称格式: ghx-manual-job-{job_id}-{node_name}-{random_suffix}
# 例如: ghx-manual-job-manual-1756721527-21039310-hd03-gpu2-0062-mdtlt
parts = pod_name.split('-')
if len(parts) >= 7: # ghx, manual, job, manual, timestamp, random_id, node_name, ...
# 提取job_id部分: manual-1756721527-21039310
job_id_parts = parts[3:6] # manual, timestamp, random_id
job_id = '-'.join(job_id_parts)
return job_id
return None
except Exception as e:
logger.warning(f"从Pod名称提取job_id失败: {pod_name}, 错误: {e}")
return None
def convert_kubectl_status_to_standard(kubectl_status, ready):
"""将kubectl状态转换为标准状态"""
status = kubectl_status.lower()
# 映射kubectl状态到标准状态
status_mapping = {
'pending': 'Pending',
'running': 'Running',
'succeeded': 'Completed',
'failed': 'Failed',
'unknown': 'Unknown',
'crashloopbackoff': 'Failed',
'error': 'Failed',
'completed': 'Completed'
}
# 检查ready状态
if ready and '/' in ready:
ready_parts = ready.split('/')
if len(ready_parts) == 2:
ready_count = int(ready_parts[0])
total_count = int(ready_parts[1])
# 如果所有容器都ready且状态是running,则认为是Running
if ready_count == total_count and status == 'running':
return 'Running'
# 如果部分ready且状态是running,则认为是Running(容器启动中)
elif ready_count > 0 and status == 'running':
return 'Running'
# 返回映射的状态,如果没有映射则返回原状态
return status_mapping.get(status, kubectl_status)
def get_job_from_db(job_id):
"""从数据库中获取Job信息"""
try:
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('SELECT * FROM diagnostic_jobs WHERE job_id = ?', (job_id,))
job = cursor.fetchone()
conn.close()
if job:
return {
'job_id': job[1], # job_id
'status': job[7], # status
'node_name': job[4], # selected_nodes (作为node_name)
'created_at': job[8], # created_at
'updated_at': job[9] # updated_at
}
return None
except Exception as e:
logger.warning(f"从数据库获取Job失败: {e}")
return None
def get_pod_cache_key(pod_name):
"""生成Pod缓存键"""
return pod_name
def update_pod_cache(pod_name, pod_data):
"""更新Pod缓存"""
global pod_cache
cache_key = get_pod_cache_key(pod_name)
pod_cache[cache_key] = {
'data': pod_data,
'timestamp': time.time(),
'resource_version': pod_data.metadata.resource_version if hasattr(pod_data.metadata, 'resource_version') else None
}
def get_pod_from_cache(pod_name):
"""从缓存获取Pod数据"""
global pod_cache
cache_key = get_pod_cache_key(pod_name)
return pod_cache.get(cache_key)
def sync_pod_cache_from_api():
"""从API同步Pod缓存(定期全量同步)"""
global last_sync_time, last_resource_version, pod_cache
try:
if not kubernetes_client:
logger.warning("Kubernetes客户端不可用,跳过缓存同步")
return
v1, batch_v1 = kubernetes_client
current_time = time.time()
# 检查是否需要同步
if current_time - last_sync_time < sync_interval:
return
logger.info("开始定期同步Pod缓存...")
# 获取所有相关Pod
pods = v1.list_namespaced_pod(
namespace='gpu-health-expert',
label_selector='app=ghx-manual,job-type=manual'
)
# 更新缓存
new_cache = {}
for pod in pods.items:
cache_key = get_pod_cache_key(pod.metadata.name)
new_cache[cache_key] = {
'data': pod,
'timestamp': current_time,
'resource_version': pod.metadata.resource_version if hasattr(pod.metadata, 'resource_version') else None
}
# 检查缓存变化
cache_changes = []
for pod_name, pod_info in new_cache.items():
old_pod_info = pod_cache.get(pod_name)
if not old_pod_info or old_pod_info['resource_version'] != pod_info['resource_version']:
cache_changes.append(pod_name)
# 更新全局缓存
pod_cache = new_cache
last_sync_time = current_time
if pods.metadata and hasattr(pods.metadata, 'resource_version'):
last_resource_version = pods.metadata.resource_version
logger.info(f"Pod缓存同步完成,共 {len(new_cache)} 个Pod,{len(cache_changes)} 个变化")
except Exception as e:
logger.error(f"同步Pod缓存失败: {e}")
def handle_pod_status_change(pod):
"""处理Pod状态变化(Informer风格)"""
try:
pod_name = pod.metadata.name
pod_status = pod.status.phase if pod.status else 'Unknown'
# 从Pod名称中提取job_id
job_id = extract_job_id_from_pod_name(pod_name)
if not job_id:
logger.debug(f"无法从Pod名称提取job_id: {pod_name}")
return
# 检查数据库中是否存在这个Job
db_job = get_job_from_db(job_id)
if not db_job:
logger.debug(f"数据库中不存在Job: {job_id}")
return
# 转换状态格式 - 将Pod状态转换为小写后传给转换函数
pod_status_standard = convert_kubectl_status_to_standard(pod_status.lower(), "1/1" if pod_status == "Running" else "0/1")
# 检查状态是否有变化 - 统一转换为小写进行比较
if pod_status_standard.lower() != db_job['status'].lower():
logger.info(f"🔄 Pod状态变化: {job_id} {db_job['status']} -> {pod_status_standard}")
# 更新数据库状态
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('''
UPDATE diagnostic_jobs
SET status = ?, updated_at = datetime('now', 'localtime')
WHERE job_id = ?
''', (pod_status_standard, job_id))
conn.commit()
conn.close()
# 通知SSE客户端
notify_job_status_change(job_id, pod_status_standard, db_job['node_name'] if 'node_name' in db_job.keys() else None)
# 如果Pod完成,处理结果收集
if pod_status_standard in ['Succeeded', 'Failed', 'Completed']:
handle_job_completion(job_id)
else:
logger.debug(f"Pod {pod_name} 状态无变化: {pod_status_standard}")
except Exception as e:
logger.warning(f"处理Pod状态变化失败: {e}")
def pod_status_callback(event):
"""Pod状态变化回调函数(Informer风格)"""
try:
event_type = event['type']
pod = event['object']
pod_name = pod.metadata.name
logger.info(f"🔄 收到Pod事件: {event_type} - {pod_name}")
# 更新本地缓存
update_pod_cache(pod_name, pod)
# 根据事件类型处理
if event_type == 'MODIFIED':
handle_pod_status_change(pod)
elif event_type == 'ADDED':
logger.info(f"新增Pod: {pod_name}")
handle_pod_status_change(pod)
elif event_type == 'DELETED':
logger.info(f"删除Pod: {pod_name}")
# 从缓存中移除
cache_key = get_pod_cache_key(pod_name)
if cache_key in pod_cache:
del pod_cache[cache_key]
except Exception as e:
logger.warning(f"处理Watch事件失败: {e}")
def start_kubernetes_watch_thread():
"""启动Kubernetes Watch线程(基于Informer机制优化)"""
global status_check_thread, status_check_running, last_resource_version
if status_check_running:
logger.info("状态检查线程已在运行中")
return
logger.info("正在启动Kubernetes Watch线程(Informer优化版)...")
status_check_running = True
def kubernetes_watch_worker():
"""Kubernetes Watch工作线程(Informer风格)"""
global last_resource_version
thread_id = threading.current_thread().ident
logger.info(f"Kubernetes Watch工作线程已启动 (线程ID: {thread_id})")
v1, batch_v1 = kubernetes_client
retry_count = 0
max_retries = 10 # 最大重试次数
# 初始化时进行全量同步
sync_pod_cache_from_api()
while status_check_running:
try:
# 定期同步缓存
sync_pod_cache_from_api()
# 构建Watch参数
watch_params = {
'namespace': 'gpu-health-expert',
'label_selector': 'app=ghx-manual,job-type=manual'
}
# 如果有资源版本,从该版本开始Watch
if last_resource_version:
watch_params['resource_version'] = last_resource_version
logger.info(f"从资源版本 {last_resource_version} 开始Watch")
# 创建Watch对象
from kubernetes import watch
w = watch.Watch()
# 开始Watch流
for event in w.stream(v1.list_namespaced_pod, **watch_params):
if not status_check_running:
logger.info("收到停止信号,终止Watch")
break
# 更新资源版本
if hasattr(event['object'].metadata, 'resource_version'):
last_resource_version = event['object'].metadata.resource_version
# 调用回调函数处理事件
pod_status_callback(event)
# Watch流结束(通常是网络问题或超时)
logger.info("Kubernetes Watch流结束,准备重新启动...")
w.stop()
# 短暂等待后重新启动Watch
if status_check_running:
logger.info("5秒后重新启动Watch...")
time.sleep(5)
except Exception as e:
retry_count += 1
logger.error(f"Kubernetes Watch异常 (重试 {retry_count}/{max_retries}): {e}")
if retry_count >= max_retries:
logger.error(f"Watch重试次数达到上限,回退到kubectl watch模式...")
start_kubectl_watch_thread()
break
# 指数退避:1秒, 2秒, 4秒, 8秒, 16秒...
wait_time = min(2 ** retry_count, 30) # 最大等待30秒
logger.info(f"{wait_time}秒后重试Watch...")
try:
w.stop()
except:
pass
time.sleep(wait_time)
continue # 继续循环,重试Watch
logger.info(f"Kubernetes Watch工作线程已退出 (线程ID: {thread_id})")
# 启动线程
status_check_thread = threading.Thread(target=kubernetes_watch_worker, daemon=True)
status_check_thread.start()
time.sleep(0.1)
if status_check_thread.is_alive():
logger.info(f"Kubernetes Watch线程已成功启动 (线程ID: {status_check_thread.ident})")
else:
logger.error("Kubernetes Watch线程启动失败")
status_check_running = False
def start_kubectl_watch_thread():
"""启动kubectl watch Pod监听线程"""
global status_check_thread, status_check_running
if status_check_running:
logger.info("状态检查线程已在运行中")
return
logger.info("正在启动kubectl watch Pod监听线程...")
status_check_running = True
def kubectl_watch_worker():
"""kubectl watch工作线程"""
thread_id = threading.current_thread().ident
logger.info(f"kubectl watch工作线程已启动 (线程ID: {thread_id})")
retry_count = 0
max_retries = 10 # 最大重试次数
while status_check_running:
try:
# 使用kubectl watch监听Pod变化
logger.info("开始使用kubectl watch监听gpu-health-expert命名空间的Pod变化...")
# 构建kubectl get --watch命令
cmd = [
'kubectl', 'get', 'pods', '-n', 'gpu-health-expert',
'-l', 'app=ghx-manual,job-type=manual',
'--no-headers', '--watch'
]
logger.info(f"执行kubectl watch命令: {' '.join(cmd)}")
# 启动kubectl watch进程
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
bufsize=1,
universal_newlines=True
)
logger.info(f"kubectl watch进程已启动 (PID: {process.pid})")
# 读取输出
for line in iter(process.stdout.readline, ''):
if not status_check_running:
logger.info("收到停止信号,终止kubectl watch")
break
if line.strip():
try:
# 解析kubectl watch输出
# 格式: NAME READY STATUS RESTARTS AGE
# 例如: ghx-manual-job-xxx-yyy-zzz 0/1 Pending 0 5s
parts = line.strip().split()
if len(parts) >= 4:
pod_name = parts[0]
ready = parts[1] # 例如: 0/1
status = parts[2] # 例如: Pending, Running, Completed, Failed
restarts = parts[3]
logger.info(f"🔄 kubectl watch检测到Pod变化: {pod_name} -> {status} (Ready: {ready}, Restarts: {restarts})")
# 从Pod名称中提取job_id
job_id = extract_job_id_from_pod_name(pod_name)
if not job_id:
logger.debug(f"无法从Pod名称提取job_id: {pod_name}")
continue
# 检查数据库中是否存在这个Job
db_job = get_job_from_db(job_id)
if not db_job:
logger.debug(f"数据库中不存在Job: {job_id}")
continue
# 转换状态格式 - 将kubectl状态转换为小写后传给转换函数
pod_status = convert_kubectl_status_to_standard(status.lower(), ready)
# 检查状态是否有变化 - 统一转换为小写进行比较
if pod_status.lower() != db_job['status'].lower():
logger.info(f"🔄 Pod状态变化: {job_id} {db_job['status']} -> {pod_status}")
# 更新数据库状态
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('''
UPDATE diagnostic_jobs
SET status = ?, updated_at = datetime('now', 'localtime')
WHERE job_id = ?
''', (pod_status, job_id))
conn.commit()
conn.close()
# 通知SSE客户端
notify_job_status_change(job_id, pod_status, db_job['node_name'] if 'node_name' in db_job.keys() else None)
# 如果Pod完成,处理结果收集
if pod_status in ['Succeeded', 'Failed', 'Completed']:
handle_job_completion(job_id)
else:
logger.debug(f"Pod {pod_name} 状态无变化: {pod_status}")
except Exception as e:
logger.warning(f"解析kubectl watch输出失败: {e}, 原始行: {line.strip()}")
continue
# 检查进程是否异常退出
if process.poll() is not None:
stderr_output = process.stderr.read()
if stderr_output:
logger.warning(f"kubectl watch进程异常退出: {stderr_output}")
else:
logger.info("kubectl watch进程正常退出")
# 清理进程
try:
process.terminate()
process.wait(timeout=5)
except subprocess.TimeoutExpired:
process.kill()
process.wait()
except Exception as e:
logger.warning(f"清理kubectl watch进程失败: {e}")
if not status_check_running:
break
# 等待一段时间后重新启动
logger.info("kubectl watch连接断开,5秒后重新启动...")
time.sleep(5)
except Exception as e:
retry_count += 1
logger.error(f"kubectl watch异常 (重试 {retry_count}/{max_retries}): {e}")
if retry_count >= max_retries:
logger.error(f"kubectl watch重试次数达到上限,回退到定时轮询模式...")
start_polling_status_check_thread()
break
# 指数退避:1秒, 2秒, 4秒, 8秒, 16秒...
wait_time = min(2 ** retry_count, 30) # 最大等待30秒
logger.info(f"{wait_time}秒后重试kubectl watch...")
time.sleep(wait_time)
logger.info(f"kubectl watch工作线程已退出 (线程ID: {thread_id})")
# 启动线程
status_check_thread = threading.Thread(target=kubectl_watch_worker, daemon=True)
status_check_thread.start()
time.sleep(0.1)
if status_check_thread.is_alive():
logger.info(f"kubectl watch线程已成功启动 (线程ID: {status_check_thread.ident})")
else:
logger.error("kubectl watch线程启动失败")
status_check_running = False
def start_status_check_thread():
"""启动状态检查线程(多方案备选)"""
global status_check_thread, status_check_running
if status_check_running:
logger.info("状态检查线程已在运行中")
return
# 添加调试信息
logger.info(f"kubernetes_client: {kubernetes_client}")
# 优先尝试Kubernetes客户端Watch
if kubernetes_client:
logger.info("正在启动Kubernetes Watch状态检查线程...")
start_kubernetes_watch_thread()
else:
logger.warning("Kubernetes客户端不可用,尝试使用kubectl watch...")
start_kubectl_watch_thread()
# 如果kubectl watch也失败,回退到轮询模式
if not status_check_running:
logger.warning("kubectl watch启动失败,回退到定时轮询模式")
start_polling_status_check_thread()
def start_polling_status_check_thread():
"""启动定时轮询状态检查线程(回退方案)"""
global status_check_thread, status_check_running
logger.info("正在启动定时轮询状态检查线程...")
status_check_running = True
def polling_status_check_worker():
"""定时轮询工作线程"""
thread_id = threading.current_thread().ident
logger.info(f"定时轮询工作线程已启动 (线程ID: {thread_id})")
while status_check_running:
try:
# 每10秒检查一次活跃Job的状态
time.sleep(10)
# 获取所有活跃Job
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('''
SELECT job_id, status FROM diagnostic_jobs
WHERE status IN ('pending', 'running', 'Pending', 'Running', 'unknown', 'Unknown')
OR status LIKE '%pending%' OR status LIKE '%running%'
OR status LIKE '%waiting%' OR status LIKE '%creating%'
OR status LIKE '%ContainerCreating%'
''')
active_jobs = cursor.fetchall()
conn.close()
if active_jobs:
logger.info(f"定时检查: 找到 {len(active_jobs)} 个活跃Job")
for job_id, current_status in active_jobs:
try:
# 获取最新的Kubernetes状态
k8s_status = get_kubernetes_job_status(job_id)
if k8s_status:
new_status = k8s_status['pod_status']
# 标准化状态比较
current_normalized = current_status.lower().strip()
new_normalized = new_status.lower().strip()
if current_normalized != new_normalized:
logger.info(f"🔄 状态变化: {job_id} {current_status} -> {new_status}")
# 通知前端状态变化
notify_job_status_change(job_id, new_status)
# 更新数据库中的状态
try:
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('''
UPDATE diagnostic_jobs
SET status = ?, updated_at = datetime('now', 'localtime')
WHERE job_id = ?
''', (new_status, job_id))
conn.commit()
conn.close()
except Exception as db_error:
logger.warning(f"❌ 更新数据库失败: {db_error}")
# 如果Job已完成,自动触发诊断结果入库
if new_status in ['Completed', 'Succeeded', 'Failed']:
handle_job_completion(job_id)
else:
# 如果无法获取Kubernetes状态,说明Job可能已被删除
new_status = 'unknown'
logger.warning(f"无法获取Job {job_id} 的Kubernetes状态,设为unknown")
# 通知前端状态变化
notify_job_status_change(job_id, new_status)
# 更新数据库中的状态
try:
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('''
UPDATE diagnostic_jobs
SET status = ?, updated_at = datetime('now', 'localtime')
WHERE job_id = ?
''', (new_status, job_id))
conn.commit()
conn.close()
except Exception as db_error:
logger.warning(f"❌ 更新数据库失败: {db_error}")
except Exception as e:
logger.warning(f"检查Job {job_id} 状态失败: {e}")
else:
logger.debug("没有活跃Job需要检查")
# 没有活跃Job时,减少检查频率
time.sleep(30) # 等待30秒再检查
continue
logger.info(f"定时状态检查完成,检查了 {len(active_jobs)} 个活跃Job")
except Exception as e:
logger.error(f"定时状态检查异常: {e}")