-
Notifications
You must be signed in to change notification settings - Fork 130
调整集群切换ID编码方式 #443
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
调整集群切换ID编码方式 #443
Conversation
- 新增MD5Hex工具函数用于生成集群标识 - 引入ResolveClusterID方法统一解析多种集群标识格式 - 更新集群配置结构,将ClusterIDBase64字段替换为ClusterMD - 修改所有相关控制器,使用新的集群标识解析逻辑 - 保持对旧Base64编码的向后兼容性
- 后端集群解析服务移除旧的Base64兼容逻辑,仅支持MD5标识 - 前端URL路径和API调用中的cluster_id_base64替换为cluster_md - 集群选择中间件和插件路由使用新的集群标识解析方法 - 集群租约管理器将clusterID标签迁移至注解,使用MD5作为主标识 - 添加前端集群标识规范化函数,自动将集群ID转换为MD5 - 简化ESLint配置,移除max-warnings限制
更新前端页面配置文件和工具函数,将URL中的集群标识符从Base64编码改为MD5编码,确保集群标识符处理的一致性。修改涉及多个页面配置文件和工具函数,包括SelectedCluster过滤器和相关工具函数的重命名与重构。
📝 WalkthroughSummary by CodeRabbit发布说明
✏️ Tip: You can customize this high-level summary in your review settings. Walkthrough该 PR 将集群标识符编码方案从 Base64 切换为 MD5:新增 MD5 工具、在 ClusterService 中引入 ClusterMD 和 ResolveClusterID,后端控制器/中间件改为通过服务解析标识符,前端模板与工具函数替换为 MD5 规范,部分 Lease 元数据和 kubeconfig 命名也随之调整。 Changes
Sequence Diagram(s)sequenceDiagram
participant User as 用户 (浏览器)
participant UI as 前端 (页面/Amis)
participant Server as 后端 (HTTP 控制器)
participant Middleware as 中间件
participant ClusterSvc as ClusterService
participant Store as 集群配置存储
User->>UI: 点击包含 cluster_md 的链接/发起请求
UI->>Server: HTTP 请求 (/k/.../...)
Server->>Middleware: 请求进入
Middleware->>ClusterSvc: ResolveClusterID(cluster_md)
ClusterSvc->>Store: 查询 ClusterConfig via ClusterMD
Store-->>ClusterSvc: 返回 clusterID
ClusterSvc-->>Middleware: 返回 clusterID 或 错误
Middleware->>Server: 将 resolved clusterID 注入上下文
Server->>ClusterSvc: 调用具体服务操作(如 reconnect / run)
ClusterSvc-->>Server: 操作结果
Server-->>UI: 返回 HTTP 响应
UI-->>User: 更新界面/导航
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
pkg/plugins/modules/inspection/frontend/script.json (1)
1-339: 此目录下所有JSON配置文件与ui/public/pages/plugins/inspection/内容完全相同,需要同步维护。检查发现
pkg/plugins/modules/inspection/frontend/目录下的5个JSON文件(lua_doc.json、record.json、schedule.json、script.json、summary.json)均与ui/public/pages/plugins/inspection/中的对应文件内容完全相同。两个目录中的文件在同一次提交中更新,但不存在自动同步机制。建议:
- 明确说明两个目录的用途(如是否为嵌入式资源 vs UI静态资源)
- 建立自动同步或生成机制以避免两份副本不一致
- 如无必要,考虑删除其中一份副本并通过构建流程生成
🤖 Fix all issues with AI agents
In `@pkg/middleware/cluster.go`:
- Around line 68-80: The error messages contain stray numeric debug markers
("未指定集群1", "未找到集群2", "集群未连接3"); locate the responses around clusterIdentifier
checks and the ResolveClusterID call (references: variable clusterIdentifier,
service.ClusterService().ResolveClusterID) and remove the trailing digits so
messages read consistently (e.g. "未指定集群", "未找到集群", "集群未连接"); also update the
similar message referenced at the later location around line 107 to match the
cleaned wording to keep responses professional and consistent.
In `@pkg/plugins/modules/inspection/controller/summary.go`:
- Around line 60-67: The current block leaves `cluster` empty when
service.ClusterService().ResolveClusterID(clusterIdentifier) fails, which causes
unfiltered queries; update the handler so that if c.Param("cluster") is
non-empty and ResolveClusterID returns an error you return an HTTP error
response (e.g., 400/422) instead of silently continuing, and also raise the log
visibility by changing klog.V(6) to a more visible level such as klog.V(2)
(references: c.Param("cluster"), variable cluster,
service.ClusterService().ResolveClusterID, and the klog.V(...) call).
In `@pkg/service/clusters.go`:
- Around line 191-213: ResolveClusterID currently only checks ClusterMD; update
the function (ResolveClusterID) to also accept a direct cluster ID match
(compare clusterIdentifier to cc.ClusterID) and to try decoding URL-safe Base64
inputs (use base64.URLEncoding/RawURLEncoding.DecodeString) and compare the
decoded string against cc.ClusterID and cc.ClusterMD for compatibility,
returning cc.ClusterID on match; if you intentionally removed backward
compatibility instead, adjust the function comment to reflect that only
ClusterMD is supported. Ensure you still skip nil cc and empty cc.GetClusterID()
as in the existing clusterConfigs loop.
🧹 Nitpick comments (11)
ui/package.json (1)
6-6: lint 放宽后请确认 CI 仍会拦截告警。
如果仍希望“零告警/零无效 disable”,建议保留之前的严格参数。🛠️ 可选恢复严格 lint 参数
- "lint": "eslint . --ext ts,tsx" + "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0"pkg/comm/utils/base64.go (1)
49-53: MD5 仅适合非安全用途,建议确认威胁模型。
如果该值被用于鉴权边界或需要强抗碰撞,建议改用 SHA-256(注意输出长度变化)。🛠️ 可选:切换到 SHA-256(输出长度会变为 64 位十六进制)
-import ( - "crypto/md5" +import ( + "crypto/sha256" "encoding/base64" "encoding/hex" "strings" ) @@ func MD5Hex(s string) string { - sum := md5.Sum([]byte(s)) + sum := sha256.Sum256([]byte(s)) return hex.EncodeToString(sum[:]) }ui/.eslintrc.cjs (1)
1-18: 建议添加extends和plugins配置以获得更完整的 TypeScript 校验。当前配置仅设置了解析器,但没有启用任何推荐规则集。建议扩展配置以获得更好的代码质量检查:
♻️ 建议的配置改进
module.exports = { root: true, env: { browser: true, es2021: true, node: true, }, + extends: [ + "eslint:recommended", + "plugin:`@typescript-eslint/recommended`", + ], + plugins: ["@typescript-eslint"], parser: "@typescript-eslint/parser", parserOptions: { ecmaVersion: "latest", sourceType: "module", ecmaFeatures: { jsx: true, }, }, ignorePatterns: ["dist", "node_modules"], rules: {}, };pkg/controller/param/cluster.go (1)
88-88: 移除第 88 行冗余的GetClusterID()调用。在第 82 行的
Filter操作中,cluster.GetClusterID()已被调用,此时ClusterMD已经通过GetClusterID()内部的副作用被初始化(见 pkg/service/clusters.go:147)。第 88 行的调用重复了这个操作,且其返回值未被使用,可直接删除。♻️ 建议移除冗余调用
for _, cluster := range clusters { - cluster.GetClusterID() // InCluster AWS if !(cluster.IsInCluster || cluster.IsAWSEKS) && slice.ContainBy(configs, func(item *service.ClusterConfig) bool {pkg/plugins/modules/gllog/route/admin_api.go (1)
31-38: 错误处理与其他控制器不一致当
ResolveClusterID失败时,此处选择静默继续(使用空 cluster),而其他控制器(如cluster_permission.go、cluster.go)会返回错误给客户端。如果这是有意设计(允许在集群标识无效时列出所有日志),建议添加注释说明此行为。否则,考虑与其他端点保持一致的错误处理。
💡 建议添加注释说明意图
cluster := "" if clusterIdentifier != "" { if clusterID, err := service.ClusterService().ResolveClusterID(clusterIdentifier); err == nil { cluster = clusterID } else { + // 解析失败时继续执行,允许在无有效集群时列出全局日志 klog.V(6).Infof("解析cluster参数失败: cluster=%s, err=%v", clusterIdentifier, err) } }pkg/middleware/cluster.go (1)
69-79: 使用非标准 HTTP 状态码 512状态码 512 不是标准 HTTP 状态码。对于客户端错误(如未指定集群、集群不存在),通常应使用 4xx 系列状态码(如 400 Bad Request 或 404 Not Found)。
如果 512 是项目约定的自定义状态码,请忽略此建议。
pkg/plugins/modules/leader/lease/manager.go (1)
141-159: 重复的集群标识提取逻辑
AddFunc和DeleteFunc处理器中存在相同的集群标识提取逻辑(从 Annotations 获取,失败则从 Labels 解码)。建议提取为辅助函数以减少重复代码。♻️ 建议提取辅助函数
+// extractClusterID 从 Lease 中提取集群标识,优先从 Annotations 获取, +// 若不存在则尝试从 Labels["clusterID"] 解码(兼容旧版本)。 +func extractClusterID(l *coordinationv1.Lease) string { + if l.Annotations != nil { + if cid := l.Annotations["clusterID"]; cid != "" { + return cid + } + } + if cid := l.Labels["clusterID"]; cid != "" { + decoded, err := utils.UrlSafeBase64Decode(cid) + if err != nil { + klog.V(6).Infof("解码 Lease 标签 clusterID 失败:%v", err) + return "" + } + return decoded + } + return "" +}然后在
AddFunc和DeleteFunc中使用:AddFunc: func(obj any) { l := obj.(*coordinationv1.Lease) if !isLeaseValid(l, m.durationSec) { return } - clusterID := "" - if l.Annotations != nil { - clusterID = l.Annotations["clusterID"] - } - if clusterID == "" { - cid := l.Labels["clusterID"] - if cid != "" { - decoded, err := utils.UrlSafeBase64Decode(cid) - if err != nil { - klog.V(6).Infof("解码 Lease 标签 clusterID 失败:%v", err) - return - } - clusterID = decoded - } - } + clusterID := extractClusterID(l) if clusterID == "" { klog.V(6).Infof("未获取到 Lease 关联集群标识,跳过处理:%s", l.Name) return }Also applies to: 178-196
ui/src/utils/utils.ts (2)
85-90: MD5 检测逻辑可能存在边界情况使用
v.length === 32判断输入是否已经是 MD5 哈希是一种启发式方法。如果集群 ID 恰好为 32 个字符,将被错误地视为 MD5 而不进行哈希处理。虽然在实际场景中集群 ID(格式为
FileName/ContextName)不太可能恰好是 32 字符,但可以考虑添加更严格的校验(如检查是否仅包含十六进制字符)。💡 更严格的 MD5 检测
export function normalizeClusterIdentifier(input: string): string { const v = (input || '').trim() if (!v) return '' - if (v.length === 32) return v + // 检查是否为有效的 MD5 哈希(32位十六进制字符) + if (v.length === 32 && /^[a-f0-9]+$/i.test(v)) return v return CryptoJS.MD5(v).toString() }
1-2: 建议添加 crypto-js 类型定义使用
@ts-ignore抑制类型检查错误通常不是最佳实践。建议安装@types/crypto-js以获得正确的类型支持。#!/bin/bash # 检查项目中是否已有 crypto-js 类型定义 cat package.json 2>/dev/null | jq '.devDependencies["@types/crypto-js"] // .dependencies["@types/crypto-js"] // "not found"'pkg/plugins/modules/k8sgpt/frontend/analysis.json (1)
54-54: LGTM!API 端点更新正确。
注意:此文件与
ui/public/pages/plugins/k8sgpt/analysis.json内容高度相似。如果这不是有意为之(如嵌入式插件与公共 UI 分离),可考虑后续合并或抽取共享配置以减少维护成本。Also applies to: 70-70
ui/src/components/Sidebar/index.tsx (1)
81-85: 冗余的标识符规范化调用。根据
ui/src/utils/utils.ts中的实现,getCurrentClusterId()内部已经调用了normalizeClusterIdentifier(第 174 行),返回的clusterId已经是规范化后的 32 字符 MD5 值。因此第 83 行再次调用normalizeClusterIdentifier(clusterId)是冗余的。虽然由于
normalizeClusterIdentifier的幂等性(长度为 32 时直接返回),这不会导致功能问题,但可以简化代码。♻️ 建议简化
const loadJsonPage = (path: string) => { const clusterId = getCurrentClusterId(); if (clusterId) { - const normalized = normalizeClusterIdentifier(clusterId); const purePath = path.startsWith('/') ? path : `/${path}`; - navigate(`/k/${normalized}${purePath}`); + navigate(`/k/${clusterId}${purePath}`); } else { navigate(path); } };
移除集群中间件错误消息中多余的“1”、“2”、“3”数字后缀,使错误提示信息更清晰专业
- 将参数 `clusterIdentifier` 重命名为 `clusterIdMd5`,以更准确地反映其存储 MD5 值的实际用途。 - 移除函数注释中关于输入格式的过时说明,因当前逻辑仅处理 MD5 匹配。
调整集群切换ID编码方式