@@ -97,14 +97,18 @@ fn default_data_dir() -> Option<String> {
9797/// 生成客户端实例 ID
9898///
9999/// # 规则
100- /// - 添加 `node-` 前缀以明确标识节点实例
101- /// - 使用主机名作为实例标识(物理机为实际主机名,容器为容器 ID )
100+ /// - 物理机:使用 `node-{hostname}` 前缀(如 `node-server-01`)
101+ /// - Docker 容器:使用 `container-{hostname}` 前缀(如 `container-636b25ce7983` )
102102/// - 如果主机名为空或获取失败,使用 `node-unknown`
103103/// - 保证每台服务器有唯一的实例 ID
104104///
105+ /// # 检测逻辑
106+ /// - 如果存在 `/.dockerenv` 文件或 `/run/.containerenv` 文件,判定为容器环境
107+ /// - 否则判定为物理机/虚拟机环境
108+ ///
105109/// # 示例
106- /// - 物理机: `node-prod- server-01`
107- /// - Docker: `node -636b25ce7983`
110+ /// - 物理机: `node-server-01`
111+ /// - Docker: `container -636b25ce7983`
108112/// - Fallback: `node-unknown`
109113pub fn generate_client_instance_id ( ) -> String {
110114 let host = hostname:: get ( )
@@ -113,7 +117,13 @@ pub fn generate_client_instance_id() -> String {
113117 . filter ( |h| !h. is_empty ( ) )
114118 . unwrap_or_else ( || "unknown" . to_string ( ) ) ;
115119
116- format ! ( "node-{}" , host)
120+ // 检测是否在容器环境中
121+ let is_container = std:: path:: Path :: new ( "/.dockerenv" ) . exists ( )
122+ || std:: path:: Path :: new ( "/run/.containerenv" ) . exists ( ) ;
123+
124+ let prefix = if is_container { "container" } else { "node" } ;
125+
126+ format ! ( "{}-{}" , prefix, host)
117127}
118128
119129impl NodeTokenConfig {
@@ -430,16 +440,27 @@ max_concurrent_tasks = 4
430440 // 测试自动生成实例 ID
431441 let instance_id = generate_client_instance_id ( ) ;
432442
433- // 应该以 "node-" 前缀开头
434- assert ! ( instance_id. starts_with( "node-" ) ) ;
443+ // 应该以 "node-" 或 "container-" 前缀开头
444+ assert ! (
445+ instance_id. starts_with( "node-" ) || instance_id. starts_with( "container-" ) ,
446+ "Instance ID should start with 'node-' or 'container-', got: {}" ,
447+ instance_id
448+ ) ;
435449
436- // 应该不为空(至少有 "node-" 前缀 )
450+ // 应该不为空(至少有前缀 )
437451 assert ! ( instance_id. len( ) > 5 ) ;
438452
439453 // 不应该包含空格
440454 assert ! ( !instance_id. contains( char :: is_whitespace) ) ;
441455
442- // 应该是 "node-unknown" 或 "node-{hostname}"
443- assert ! ( instance_id == "node-unknown" || instance_id. len( ) > 5 ) ;
456+ // 验证格式正确性
457+ let parts: Vec < & str > = instance_id. splitn ( 2 , '-' ) . collect ( ) ;
458+ assert_eq ! ( parts. len( ) , 2 , "Should have exactly one hyphen" ) ;
459+ assert ! (
460+ parts[ 0 ] == "node" || parts[ 0 ] == "container" ,
461+ "Prefix should be 'node' or 'container', got: {}" ,
462+ parts[ 0 ]
463+ ) ;
464+ assert ! ( !parts[ 1 ] . is_empty( ) , "Host part should not be empty" ) ;
444465 }
445466}
0 commit comments