Skip to content

Conversation

weibaohui
Copy link
Owner

No description provided.

添加缺失的API端点描述和响应格式说明
完善现有注释的详细描述信息
更新集群相关API的响应类型从amis.Response改为string
修改用户模型字段:移除created_by,添加disabled字段,更新two_fa_enabled描述
为SaveKubeConfig和RemoveKubeConfig接口添加Swagger注释,包括功能描述、认证方式和响应格式
为条件控制器和kubeconfig相关操作添加swagger注解,包括列表查询、创建/更新、删除、快速保存状态等接口
为系统配置和SSO配置相关接口添加Swagger注解,包括:
- 获取/更新系统配置
- SSO配置的增删改查及状态更新
同时更新swagger.yaml和swagger.json文档
添加两个巡检相关API端点:
1. 根据巡检计划ID获取巡检记录列表
2. 将巡检记录的AI总结推送到配置的Webhook接收器
Copy link
Contributor

coderabbitai bot commented Jul 20, 2025

Warning

Rate limit exceeded

@weibaohui has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 11 minutes and 50 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between ce28524 and 97d0d5b.

📒 Files selected for processing (3)
  • pkg/controller/storageclass/storage_class.go (2 hunks)
  • pkg/controller/sts/sts.go (8 hunks)
  • pkg/controller/svc/svc.go (1 hunks)
📝 Walkthrough

Summary by CodeRabbit

  • 新功能

    • 新增批量和单个操作的 API 端点,支持 Deployment、ReplicaSet、DaemonSet 等资源的批量重启、恢复、停止、扩缩容、回滚、历史查询等操作。
    • 新增端点支持管理 Toleration、NodeAffinity、PodAffinity、PodAntiAffinity 等调度策略。
    • 新增端点支持批量和单个节点的 Drain、Cordon、Uncordon 操作。
    • 新增端点支持 Pod 日志流式查看、下载、端口转发管理、文件操作、Xterm 终端等。
    • 新增端点支持集群 KubeConfig 管理、断开/重连集群、条件管理、系统配置、SSO、Webhook、Lua 脚本、MCP 服务器、用户与用户组、AI Chat、资源文档等。
    • 新增端点支持 IngressClass、GatewayClass、ConfigMap、ResourceQuota、LimitRange、命名空间等多种资源的选项获取与管理。
    • 新增 AI Chat 相关接口,支持 K8s 资源描述、事件分析、示例生成、错误解释等智能问答功能。
  • 文档

    • 全面完善和新增所有 API 的 Swagger/OpenAPI 文档,详细描述参数、响应、认证方式和路由,便于自动生成接口文档和前端集成。
  • 样式/重构

    • 统一和优化部分接口的参数解析、错误处理、变量声明风格。
    • 优化部分控制器代码结构,提升可读性和一致性。

本次更新极大丰富了 API 能力,提升了文档友好性和自动化集成体验。

"""

Walkthrough

本次更新主要为后端管理 API 增加了丰富的 Swagger 文档注释,涵盖集群管理、KubeConfig 管理、条件(Condition)配置、系统配置、单点登录(SSO)配置及巡检记录等模块。新增了若干集群管理相关接口(如扫描、断开、重连集群),并完善了相关路由注册和模型定义。未涉及核心业务逻辑变更,仅为接口文档和模型描述提供了详细注释与说明。

Changes

文件/路径 变更摘要
pkg/controller/admin/cluster/cluster.go 新增 Scan、Reconnect、Disconnect 方法及路由注册,完善接口文档注释
pkg/controller/admin/cluster/kubeconfig.go 为 KubeConfig 保存/删除方法添加 Swagger 注释
pkg/controller/admin/config/condition.go 为 ConditionController 所有公开方法添加 Swagger 注释
pkg/controller/admin/config/config.go 为配置获取/更新方法添加 Swagger 注释
pkg/controller/admin/config/sso.go 为 SSO 配置相关方法添加 Swagger 注释
pkg/controller/admin/inspection/record.go 为巡检记录列表与推送方法添加 Swagger 注释
pkg/controller/admin/inspection/schedule.go 为巡检计划相关方法添加 Swagger 注释
pkg/controller/admin/inspection/summary.go 为巡检汇总相关方法添加 Swagger 注释
pkg/controller/admin/inspection/webhooks.go 为巡检 Webhook 相关方法添加 Swagger 注释
pkg/controller/admin/inspection/scripts.go 为 Lua 脚本管理相关方法添加 Swagger 注释
pkg/controller/admin/mcp/mcp_server.go 更新 MCP 服务器相关方法的 Swagger 注释
pkg/controller/admin/mcp/mcp_tools.go 修改 MCP 工具快速保存状态方法的注释
pkg/controller/admin/user/user.go 新增用户选项列表及快速更新用户状态接口
pkg/controller/chat/chat.go 新增多个人工智能 Kubernetes 相关聊天接口
pkg/controller/chat/chat_history.go 为聊天历史和重置接口添加 Swagger 注释
pkg/controller/chat/chat_websocket.go 添加 GPTShell WebSocket 交互接口文档注释及代码微调
pkg/controller/cluster_status/status.go 为集群资源统计接口添加 Swagger 注释
pkg/controller/cm/cm.go 为 ConfigMap 导入、更新、创建接口添加 Swagger 注释
pkg/controller/cronjob/cronjob.go 为 CronJob 暂停、恢复及批量操作接口添加 Swagger 注释
pkg/controller/deploy/deploy.go 新增批量和单个 Deployment 管理接口及对应 Swagger 注释
pkg/controller/doc/doc.go 为文档查询接口添加 Swagger 注释
pkg/controller/ds/ds.go 为 DaemonSet 管理相关接口添加 Swagger 注释
pkg/controller/dynamic/container.go 为容器相关接口添加 Swagger 注释,优化部分代码结构及错误处理
pkg/controller/dynamic/crd_option.go 为 CRD 组和类型选项接口添加 Swagger 注释
pkg/controller/dynamic/crd_status.go 为 CRD 状态接口添加 Swagger 注释
pkg/controller/dynamic/dynamic.go 新增多种 Kubernetes 资源动态管理接口及对应 Swagger 注释
pkg/controller/dynamic/metadata.go 新增和完善资源标签、注解管理接口及 Swagger 注释,移除重复代码
pkg/controller/dynamic/toleration.go 新增容忍度(Toleration)增删改接口及 Swagger 注释,调整类型声明
swagger/docs.go
swagger/swagger.json
swagger/swagger.yaml
扩展/完善 Swagger API 文档,新增多个管理端 API 及模型定义

Sequence Diagram(s)

sequenceDiagram
    participant Admin as 管理端用户
    participant API as 管理 API
    participant ClusterSvc as 集群服务

    Admin->>API: POST /admin/cluster/scan
    API->>ClusterSvc: 扫描本地 kubeconfig
    ClusterSvc-->>API: 返回扫描结果
    API-->>Admin: 返回操作结果

    Admin->>API: POST /admin/cluster/{cluster}/disconnect
    API->>ClusterSvc: 解码 clusterId 并断开连接
    ClusterSvc-->>API: 返回断开结果
    API-->>Admin: 返回操作结果

    Admin->>API: POST /admin/cluster/{cluster}/reconnect
    API->>ClusterSvc: 解码 clusterId 并异步重连
    ClusterSvc-->>API: 返回重连结果
    API-->>Admin: 返回操作结果
Loading

Possibly related PRs

  • Route升级 #262: 涉及集群管理路由注册的重构,与本次新增集群管理接口的路由更新相关,但具体接口实现无重叠。

Poem

兔子敲键盘,接口文档忙,
Swagger 注释添光芒。
集群扫描与断连,
配置管理更周详。
代码无改动,文档焕新装,
API 世界更明亮!

(_/)
( •_•)
/ >🍃
"""

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch swagger

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.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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

🧹 Nitpick comments (14)
pkg/controller/admin/config/sso.go (4)

24-27: Swagger 返回类型与实际响应不一致

List 实际返回的是 total + items 的列表结构,而注释写成了 string。这会导致前端/生成的 OpenAPI schema 误解返回格式。请改为指向真实响应结构,例如:

-// @Success 200 {object} string
+// @Success 200 {object} amis.ListResponse "包含 total 与 items 字段"

40-43: Save 接口文档同样需修正返回体

Save 实际返回 {"id": <int>},建议在 Swagger 中声明具体字段,避免默认成未知字符串。

-// @Success 200 {object} string
+// @Success 200 {object} map[string]int "返回创建/更新后的主键 ID"

65-69: Delete 接口的返回描述不准确

当前注释仍为 string,但实现里调用 WriteJsonOK,返回的是统一 OK 结构体。保持一致性更易读。

-// @Success 200 {object} string
+// @Success 200 {object} amis.OKResponse

83-88: QuickSave 接口的 HTTP Method 与语义

快速切换启用状态属于部分更新,推荐使用 PATCH 或在注释里说明理由;此外 @Success 类型同样需修正,避免 Swagger 生成无用 schema。

pkg/controller/admin/config/config.go (2)

19-22: All 接口返回体注释应为系统配置结构

实际返回 models.Config,请在注释中指明:

-// @Success 200 {object} string
+// @Success 200 {object} models.Config

32-36: Update 接口成功响应应体现统一 OK 结构

目前实现 WriteJsonOK,建议 Swagger 使用统一结构体而非 string

pkg/controller/admin/inspection/record.go (1)

49-54: Push 接口返回体注释需与实现统一

返回的是标准 OK 结构,注释应更新;同时可添加错误场景描述,提升文档完整度。

pkg/controller/admin/cluster/kubeconfig.go (2)

15-19: SaveKubeConfig 的成功响应类型不明确

建议将 string 改为统一 OK 结构,或声明实际字段,便于前端生成类型。


83-87: RemoveKubeConfig 的返回类型同上,需要保持一致

SaveKubeConfig 一致,保持统一 OK 响应结构。

pkg/controller/admin/config/condition.go (4)

22-25: List 接口返回体应为列表结构而非 string

同样问题,建议改为 amis.ListResponse 或自定义响应体。


38-41: Save 接口文档需指明返回字段

返回 {"id": <int>},应体现在 Swagger,否则前端难以解析。


61-65: Delete 接口返回类型需统一

请将 string 改为统一 OK 结构,保持与实现一致。


79-84: QuickSave 路由命名与 HTTP Method 语义

快速启停状态属于部分更新,可考虑使用 PATCH;同时 @Success 描述需修正。

swagger/swagger.json (1)

1320-1374: 敏感字段直接暴露在模型定义中,需确认最小权限原则

models.User 定义中包含 password, salt, two_fa_secret 等高敏感字段。虽然仅管理员可调用相关接口,但在 Swagger 文档中公开这些字段会放大泄漏风险,也可能误导前端直接传输明文密码/密钥。建议:

  • 对外只暴露必要的可写字段(如 password 使用单独 DTO)。
  • 对只读字段设定 readOnly: true,避免出现在请求示例中。
  • 对绝不应返回的字段(salt、secret)从响应模型中移除或打 writeOnly: true

遵循最小暴露原则提高整体安全性。

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5c6c791 and 840724f.

📒 Files selected for processing (9)
  • pkg/controller/admin/cluster/cluster.go (3 hunks)
  • pkg/controller/admin/cluster/kubeconfig.go (2 hunks)
  • pkg/controller/admin/config/condition.go (4 hunks)
  • pkg/controller/admin/config/config.go (2 hunks)
  • pkg/controller/admin/config/sso.go (4 hunks)
  • pkg/controller/admin/inspection/record.go (2 hunks)
  • swagger/docs.go (5 hunks)
  • swagger/swagger.json (5 hunks)
  • swagger/swagger.yaml (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (12)
pkg/controller/admin/inspection/record.go (1)

23-30: 同一函数使用两条 @router 可能导致 swag 解析冲突

Swaggo 通常只解析第一条 @Router,第二条可能被忽略。若需声明多路由,请拆分为两个 handler 或验证生成结果。

pkg/controller/admin/cluster/cluster.go (4)

28-32: LGTM! Swagger 文档完善

为 FileOptionList 方法添加的 Swagger 注释清晰明了,准确描述了接口的功能和返回内容。


61-66: LGTM! Swagger 文档规范

扫描集群接口的 Swagger 注释完整,准确描述了扫描本地 Kubeconfig 文件的功能。


71-87: LGTM! 重连接口实现合理

重连集群接口的实现很好:

  • 正确处理 Base64 编码的集群 ID
  • 使用 goroutine 进行异步连接,避免阻塞请求
  • 提供了合适的用户反馈信息
  • Swagger 文档与实现保持一致

88-103: LGTM! 断开连接接口实现正确

断开集群连接接口的实现符合预期:

  • 与重连接口保持一致的参数处理方式
  • 正确的错误处理机制
  • 清晰的用户反馈信息
  • Swagger 文档准确描述了接口功能
swagger/docs.go (4)

170-282: LGTM! 集群管理接口文档完整

新增的集群管理相关接口文档结构良好:

  • 接口路径和参数定义清晰
  • 统一使用 BearerAuth 认证
  • 描述信息准确,便于理解各接口功能
  • 响应格式保持一致

520-616: LGTM! 条件管理接口文档规范

条件管理相关接口的文档化工作做得很好:

  • 包含完整的 CRUD 操作接口
  • 快速状态更新接口设计合理
  • 参数描述清晰明确
  • 与其他模块保持一致的文档风格

617-760: LGTM! 配置管理接口文档完善

系统配置和 SSO 配置管理接口文档质量很高:

  • 系统配置的获取和更新接口定义清晰
  • SSO 配置的 CRUD 操作文档完整
  • 正确引用了 models.Config 模型
  • 状态切换接口设计合理

1273-1391: LGTM! 模型定义完整且规范

模型定义的更新很好:

  • models.Config 模型涵盖了系统的各项配置参数
  • 字段描述清晰,包含中文说明便于理解
  • models.User 模型的 2FA 相关字段描述更加明确
  • GORM 时间戳字段有合适的注释说明
swagger/swagger.yaml (3)

2-46: LGTM! YAML 格式的配置模型定义规范

models.Config 模型在 YAML 格式中的定义很好:

  • 字段类型和描述信息完整
  • 中文描述便于理解各配置项的用途
  • YAML 格式规范,缩进正确
  • 涵盖了系统所需的各项配置参数

181-258: LGTM! 集群管理接口的 YAML 文档结构良好

集群管理相关接口在 YAML 格式中的文档化工作很好:

  • 接口路径和 HTTP 方法定义正确
  • 参数描述清晰,特别是 Base64 编码的集群 ID 说明
  • 安全认证要求一致
  • 响应描述恰当,与实际返回内容匹配

402-575: LGTM! 管理功能接口文档完整统一

新增的管理功能接口文档质量很高:

  • 条件管理、系统配置、SSO 配置、巡检记录等模块文档完整
  • 各模块都包含完整的 CRUD 操作接口
  • 状态切换接口设计合理,便于快速操作
  • 文档风格统一,描述信息清晰准确

Comment on lines +153 to +171
"/admin/cluster/kubeconfig/remove": {
"post": {
"security": [
{
"BearerAuth": []
}
],
"description": "从数据库中删除KubeConfig配置",
"summary": "删除KubeConfig",
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "string"
}
}
}
}
},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

删除 KubeConfig 接口缺少入参,无法指定目标记录

/admin/cluster/kubeconfig/remove 仅声明 POST 方法且无任何参数描述,运行时无法确定需要删除的 KubeConfig 记录(ID / 名称)。这会导致接口无法被正确调用,也与其他同类删除接口(均通过 path 参数或 body 批量删除)风格不一致。建议补充明确的参数定义,例如:

"parameters": [
+  {
+    "type": "integer",
+    "description": "KubeConfig 记录 ID,多个用逗号分隔",
+    "name": "ids",
+    "in": "path",
+    "required": true
+  }
]

或改为 body 方式批量删除并同步调整路径。

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In swagger/swagger.json between lines 153 and 171, the POST endpoint
/admin/cluster/kubeconfig/remove lacks parameter definitions to specify which
KubeConfig record to delete. To fix this, add a parameter section defining
either a path or body parameter that clearly identifies the target record(s) for
deletion, such as an ID or list of IDs, ensuring consistency with similar delete
endpoints. Alternatively, modify the endpoint to accept a request body for batch
deletion and update the path accordingly.

Comment on lines +172 to +190
"/admin/cluster/kubeconfig/save": {
"post": {
"security": [
{
"BearerAuth": []
}
],
"description": "保存KubeConfig配置到数据库",
"summary": "保存KubeConfig",
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "string"
}
}
}
}
},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

保存 KubeConfig 接口缺少请求体定义,无法描述必要字段

/admin/cluster/kubeconfig/save 作为创建 / 更新接口,应至少包含 kubeconfig 内容、名称等字段,但当前未声明任何 bodyformData 参数,Swagger UI 将无法正确生成示例请求。请补充 parameters 段,例如:

"parameters": [
+  {
+    "in": "body",
+    "name": "data",
+    "description": "KubeConfig 文件内容及元数据",
+    "required": true,
+    "schema": {
+      "type": "object",
+      "properties": {
+        "name": { "type": "string" },
+        "content": { "type": "string" }
+      }
+    }
+  }
]

同时考虑增加 consumes: ["application/json"] 以保持一致性。

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
"/admin/cluster/kubeconfig/save": {
"post": {
"security": [
{
"BearerAuth": []
}
],
"description": "保存KubeConfig配置到数据库",
"summary": "保存KubeConfig",
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "string"
}
}
}
}
},
"/admin/cluster/kubeconfig/save": {
"post": {
"security": [
{
"BearerAuth": []
}
],
+ "parameters": [
+ {
+ "in": "body",
+ "name": "data",
+ "description": "KubeConfig 文件内容及元数据",
+ "required": true,
+ "schema": {
+ "type": "object",
+ "properties": {
+ "name": { "type": "string" },
+ "content": { "type": "string" }
+ }
+ }
+ }
+ ],
"description": "保存KubeConfig配置到数据库",
"summary": "保存KubeConfig",
+ "consumes": [ "application/json" ],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "string"
}
}
}
}
},
🤖 Prompt for AI Agents
In swagger/swagger.json around lines 172 to 190, the POST endpoint
/admin/cluster/kubeconfig/save lacks a request body definition, so required
fields like kubeconfig content and name are not described. Add a parameters
section with an "in": "body" parameter that defines a schema including these
necessary fields. Also, add a "consumes": ["application/json"] property to
specify the content type for the request.

Comment on lines 744 to 760
"/admin/inspection/record/list": {
"get": {
"security": [
{
"BearerAuth": []
}
],
"description": "根据巡检计划ID获取对应的巡检记录列表",
"summary": "获取巡检记录列表",
"parameters": [
{
"type": "string",
"description": "巡检计划ID",
"name": "id",
"in": "path"
}
],
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

路径与参数不匹配导致规范无效

/admin/inspection/record/list 定义了 id 参数且 inpath,但路径本身并未包含 {id} 占位符,这会使 OpenAPI 校验失败,客户端代码生成也会报错。请根据实际需求二选一:

  1. 若按计划 ID 过滤:修改路径 "/admin/inspection/record/{id}/list" 并保留 path 参数。
  2. 若无需 ID:删除该参数或改为 in: "query"

务必保持路径与参数的一致性。

🤖 Prompt for AI Agents
In swagger/swagger.json around lines 744 to 760, the path
"/admin/inspection/record/list" declares a path parameter "id" but the path does
not include an "{id}" placeholder, causing OpenAPI validation errors. To fix
this, either change the path to include the "{id}" segment like
"/admin/inspection/record/{id}/list" if filtering by plan ID is intended, or
remove the "id" parameter or change its "in" value to "query" if no path
parameter is needed. Ensure the path and parameters are consistent.

- 新增获取巡检计划列表接口
- 新增删除巡检计划接口
- 新增更新巡检脚本代码接口
- 新增获取巡检事件列表接口
- 新增获取巡检脚本输出列表接口
- 新增保存巡检计划接口
- 新增快速更新巡检计划状态接口
- 新增启动巡检计划接口
- 新增获取巡检事件状态选项列表接口
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (4)
swagger/docs.go (1)

850-857: 与 YAML 文件存在相同的参数定义问题。

此处的 script_codes 参数定义与 swagger.yaml 中的问题一致,应该定义为对象类型而不是简单字符串。由于这是生成文件,需要在源码的 Swagger 注释中修正。

这个问题与 swagger.yaml 文件中 line 585-606 的问题相同。

swagger/swagger.json (3)

153-171: 接口缺少定位删除目标的参数

/admin/cluster/kubeconfig/remove 仍未声明任何 pathquerybody 参数来标识要删除的 KubeConfig 记录,调用方无法指定目标记录,Swagger 校验也会报 missing required parameters。请补充参数定义,示例(任选其一):

   "parameters": [
+    {
+      "name": "ids",
+      "in": "path",
+      "description": "KubeConfig 记录 ID,多个用逗号分隔",
+      "required": true,
+      "type": "string"
+    }
+  ],

或改为 body 方式批量删除。
与之前 review 建议一致,问题仍未修复。


172-190: 保存接口缺少请求体定义,Swagger 无法生成示例

/admin/cluster/kubeconfig/save 为新增 / 更新接口,应至少包含 KubeConfig 内容、名称等字段的 body 参数,但目前完全缺失,导致自动化客户端无法正确生成。建议:

   "consumes": ["application/json"],
   "parameters": [
+    {
+      "in": "body",
+      "name": "data",
+      "description": "KubeConfig 文件内容及元数据",
+      "required": true,
+      "schema": {
+        "type": "object",
+        "properties": {
+          "name":   { "type": "string" },
+          "content":{ "type": "string" }
+        },
+        "required": ["name","content"]
+      }
+    }
   ],

762-778: 路径与参数不匹配,OpenAPI 校验会失败

/admin/inspection/record/list 声明了 idin: "path",但路径并未包含 {id} 占位符。两种修正方式:

  1. 若按计划 ID 过滤:改为 "/admin/inspection/record/{id}/list"
  2. 若无需 ID:删除该参数或改为 in: "query"

此问题与之前 review 相同,依旧存在。

🧹 Nitpick comments (3)
pkg/controller/admin/inspection/schedule.go (1)

280-285: 建议完善请求体参数文档。

虽然代码中定义了 requestBody 结构体,但 Swagger 注释中的 @Param script_codes body string 可以更详细地描述请求体的结构。

考虑使用更具体的参数定义:

-// @Param script_codes body string true "脚本代码"
+// @Param script_codes body object true "脚本代码" schema({script_codes:string})
swagger/swagger.json (2)

210-265: Base64 集群 ID 类型说明建议补充格式

/admin/cluster/{cluster}/disconnectreconnect 已使用 string 类型,但最好在描述中说明格式示例(如 Y2x1c3RlcjE=),便于前端校验;亦可使用 pattern 字段约束 Base64。


1488-1550: 时间字段未指定 format: date-time

models.Configcreated_atupdated_at 字段声明为 string,缺少 format: date-time,Swagger UI 会按普通字符串展示。建议:

- "type": "string"
+ "type": "string",
+ "format": "date-time"

同理可应用到 models.Usermodels.UserGroup 的时间字段。

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 840724f and e0c2b27.

📒 Files selected for processing (4)
  • pkg/controller/admin/inspection/schedule.go (9 hunks)
  • swagger/docs.go (11 hunks)
  • swagger/swagger.json (11 hunks)
  • swagger/swagger.yaml (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Analyze (go)
🔇 Additional comments (8)
pkg/controller/admin/inspection/schedule.go (3)

38-41: Swagger 文档注释完整且格式正确。

所有的 Swagger 注释都遵循了一致的格式,包含了必要的安全认证、成功响应和路由定义。文档质量良好。


54-58: 参数定义准确。

路径参数 id 的定义正确,描述清晰明确,符合接口实际需求。


174-178: 批量删除接口文档完善。

参数描述准确说明了支持多个 ID 用逗号分隔的格式,便于 API 使用者理解。

swagger/swagger.yaml (3)

2-46: 新增的 models.Config 模型定义完整且结构合理。

模型包含了系统配置的各个方面,字段描述清晰,GORM 时间戳字段也有适当的说明。所有字段的类型定义都是正确的。


181-226: 集群断开/重连接口设计合理。

Base64 编码的集群 ID 参数设计得当,响应描述清楚地说明了异步执行的特性。接口文档完整准确。


526-542: 配置更新接口的参数定义正确。

使用 $ref: '#/definitions/models.Config' 引用新定义的配置模型,确保了类型安全和文档一致性。

swagger/docs.go (2)

1-3: 注意这是自动生成的文件。

文件头部明确标注这是由 swaggo/swag 工具自动生成的文件,不应该手动编辑。任何修改都应该在源代码的 Swagger 注释中进行。


1505-1568: models.Config 定义与 YAML 规范保持一致。

生成的模型定义正确反映了 YAML 文件中的规范,所有字段类型和描述都保持一致。

Comment on lines 952 to 968
"/admin/inspection/schedule/save": {
"post": {
"security": [
{
"BearerAuth": []
}
],
"summary": "更新指定集群用户角色的命名空间字段",
"summary": "保存巡检计划",
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "string"
}
}
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

保存巡检计划接口缺少请求体,无法描述必要字段

/admin/inspection/schedule/save 为复杂对象保存接口,仅返回 200,没有任何 body 参数定义。请补充 JSON 请求体 schema(如巡检周期、脚本等),并添加 "consumes": ["application/json"]

🤖 Prompt for AI Agents
In swagger/swagger.json around lines 952 to 968, the POST endpoint
/admin/inspection/schedule/save lacks a request body definition and the consumes
field. Add a "consumes": ["application/json"] property to specify the content
type, and define a JSON request body schema under the parameters section
describing the necessary fields like inspection cycle and scripts to properly
document the input data structure.

Comment on lines 585 to 606
/admin/inspection/schedule/id/{id}/update_script_code:
post:
parameters:
- description: 巡检计划ID
in: path
name: id
required: true
type: integer
- description: 脚本代码
in: body
name: script_codes
required: true
schema:
type: string
responses:
"200":
description: OK
schema:
type: string
security:
- BearerAuth: []
summary: 更新巡检脚本代码
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

脚本代码更新接口的请求体定义需要改进。

当前将 script_codes 定义为简单的 string 类型,但根据控制器代码,实际上需要的是包含 script_codes 字段的 JSON 对象。

建议修正请求体定义:

-        "schema": {
-          "type": "string"
-        }
+        "schema": {
+          "type": "object",
+          "properties": {
+            "script_codes": {
+              "type": "string",
+              "description": "脚本代码内容"
+            }
+          }
+        }

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In swagger/swagger.yaml around lines 585 to 606, the request body for the
update_script_code endpoint is incorrectly defined as a simple string named
script_codes. Instead, it should be a JSON object containing a script_codes
field. Modify the schema under the body parameter to define an object with a
property script_codes of type string, ensuring the request body matches the
expected structure in the controller.

为AdminLuaScriptController中的Lua脚本列表、保存、删除、选项列表和加载内置脚本接口添加Swagger注释,方便API文档生成
添加巡检计划执行情况统计接口,支持按时间范围和集群过滤
添加巡检记录AI总结生成接口
添加Lua脚本相关管理接口
完善删除、保存和快速更新接口的请求参数描述
为chat控制器中的各个API方法添加Swagger注释,包括参数说明和返回信息
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🔭 Outside diff range comments (1)
swagger/swagger.json (1)

89-105: /admin/ai/model/save 缺少请求体定义

创建 / 更新模型配置需要明确字段(名称、类型、地址等)。当前未声明任何 body 参数,Swagger UI 无法生成示例。

"consumes": [
+  "application/json"
],
"parameters": [
+  {
+    "in": "body",
+    "name": "data",
+    "description": "AI 模型配置",
+    "required": true,
+    "schema": {
+      "type": "object",
+      "properties": {
+        "name": { "type": "string" },
+        "endpoint": { "type": "string" },
+        "token": { "type": "string" }
+      },
+      "required": ["name", "endpoint"]
+    }
+  }
]
♻️ Duplicate comments (5)
swagger/swagger.yaml (1)

613-634: 脚本代码更新接口的请求体定义仍需修正

该接口的请求体定义存在与之前评审中相同的问题。当前将 script_codes 定义为简单的 string 类型,但根据控制器代码的实际需求,应该是包含 script_codes 字段的JSON对象。

请参考之前的评审建议修正请求体定义,确保Swagger文档与实际的控制器实现保持一致。

swagger/swagger.json (4)

153-171: /admin/cluster/kubeconfig/remove 仍缺少用于定位删除目标的参数

路径无 {id} 占位符,也未声明 body/formData,导致调用方无法指定要删除的记录。请补充参数定义或改为在路径中携带 ids


172-190: /admin/cluster/kubeconfig/save 缺少请求体定义

作为保存接口,至少应声明包含 kubeconfig 内容与元数据的 body 参数,并声明 consumes: ["application/json"]


762-778: 路径与参数不匹配

/admin/inspection/record/list 声明了 idin: path,但路径本身无 {id}。须二选一:

  1. 修改路径 .../record/{id}/list 并保留 path 参数;
  2. 将参数改为 query 或直接删除。

1025-1041: /admin/inspection/schedule/save 缺少请求体

保存巡检计划应包含周期、脚本等字段,请补充 body schema,并声明 consumes: ["application/json"]

🧹 Nitpick comments (1)
pkg/controller/admin/user/user.go (1)

257-283: 用户状态快速更新接口需要改进错误处理

该接口实现了用户状态的快速切换功能,但存在一些可以改进的地方:

  1. 布尔值转换逻辑过于简单,只检查 "true",其他所有值都视为 false
  2. 最后的错误处理调用了 amis.WriteJsonErrorOrOK(c, err),但实际上 err 永远不会是 nil(因为前面已经处理了错误情况)

建议改进实现:

func (a *AdminUserController) UserStatusQuickSave(c *gin.Context) {
	id := c.Param("id")
	disabled := c.Param("disabled")

	var entity models.User
	entity.ID = utils.ToUInt(id)

-	if disabled == "true" {
-		entity.Disabled = true
-	} else {
-		entity.Disabled = false
-	}
+	// 更严格的布尔值解析
+	switch strings.ToLower(disabled) {
+	case "true", "1", "yes":
+		entity.Disabled = true
+	case "false", "0", "no":
+		entity.Disabled = false
+	default:
+		amis.WriteJsonError(c, fmt.Errorf("无效的状态值: %s", disabled))
+		return
+	}
+	
	err := dao.DB().Model(&entity).Select("disabled").Updates(entity).Error

	if err != nil {
		amis.WriteJsonError(c, err)
		return
	}
-	amis.WriteJsonErrorOrOK(c, err)
+	amis.WriteJsonOK(c)
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e0c2b27 and fe8c415.

📒 Files selected for processing (9)
  • pkg/controller/admin/inspection/scripts.go (5 hunks)
  • pkg/controller/admin/inspection/summary.go (2 hunks)
  • pkg/controller/admin/inspection/webhooks.go (4 hunks)
  • pkg/controller/admin/mcp/mcp_server.go (3 hunks)
  • pkg/controller/admin/mcp/mcp_tools.go (1 hunks)
  • pkg/controller/admin/user/user.go (2 hunks)
  • swagger/docs.go (12 hunks)
  • swagger/swagger.json (12 hunks)
  • swagger/swagger.yaml (5 hunks)
✅ Files skipped from review due to trivial changes (4)
  • pkg/controller/admin/mcp/mcp_tools.go
  • pkg/controller/admin/mcp/mcp_server.go
  • pkg/controller/admin/inspection/summary.go
  • pkg/controller/admin/inspection/webhooks.go
🔇 Additional comments (5)
pkg/controller/admin/user/user.go (1)

178-208: 用户选项列表接口实现正确

该接口正确地获取了不同的用户名并格式化为下拉选项,错误处理得当,结果已排序。实现符合预期功能。

pkg/controller/admin/inspection/scripts.go (1)

25-139: Swagger文档注释添加完善

为所有Lua脚本管理接口添加了完整的Swagger文档注释,包括接口描述、安全认证要求和响应模式。这些文档注释将有助于API的自动化文档生成和客户端集成。

swagger/docs.go (1)

1-1876: Swagger文档自动生成文件已更新

该文件是由swaggo/swag工具自动生成的,包含了大量新增的管理API端点文档。新增内容涵盖:

  1. 集群管理接口(断开连接、重新连接、扫描、KubeConfig管理)
  2. 集群权限管理接口
  3. 条件管理接口
  4. 系统配置接口(包括SSO配置)
  5. 巡检相关接口(记录、计划、脚本、摘要、Webhook)
  6. 新的models.Config模型定义

由于这是自动生成的文件,建议确保源代码中的Swagger注释与生成的文档保持一致。

swagger/swagger.yaml (2)

2-46: 新增系统配置模型定义完善

新增的 models.Config 模型提供了完整的系统配置属性定义,包括AI功能开关、镜像拉取超时、JWT密钥、Shell镜像配置、模型参数等。字段描述清晰,类型定义准确。


181-814: 管理API端点文档显著扩展

新增了大量管理API端点的完整文档,涵盖:

  • 集群连接管理(断开/重连)
  • KubeConfig管理(保存/删除/扫描)
  • 条件管理(CRUD操作)
  • 系统配置管理(包括SSO)
  • 巡检功能(计划、记录、脚本、AI摘要)

所有端点都包含了适当的安全认证、参数描述和响应模式定义,大大提升了API的可文档化程度。

Comment on lines +1185 to +1201
"/admin/inspection/script/save": {
"post": {
"security": [
{
"BearerAuth": []
}
],
"summary": "保存Lua脚本",
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "string"
}
}
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

/admin/inspection/script/save 缺少脚本内容的请求体

保存 Lua 脚本至少应包含 namecode 字段,目前接口无任何参数定义,无法正确调用。

🤖 Prompt for AI Agents
In swagger/swagger.json around lines 1185 to 1201, the POST endpoint
/admin/inspection/script/save lacks a request body definition for the Lua script
content. To fix this, add a requestBody section specifying a JSON schema that
includes at least the required fields "name" and "code" so that the API
consumers know what parameters to send when calling this endpoint.

weibaohui added 12 commits July 20, 2025 20:54
为History、Reset和GPTShell方法添加Swagger注释,包括接口摘要、认证方式和路由信息
添加暂停/恢复滚动更新、扩缩容、版本回滚、获取事件和HPA信息等API接口
添加models.MCPServerConfig模型定义
新增Webhook接收器的增删改查API接口
完善MCP服务器和用户管理的API文档
新增AI聊天和K8s部署管理相关API
添加Swagger注释以完善API文档,包括单个和批量暂停/恢复CronJob的接口
添加Swagger API文档注释以描述/cluster/resource_count/cache_seconds/{cache}接口的功能和参数
为Import、Update和Create接口添加Swagger注释,明确API的参数、权限和返回信息
为Doc和Detail控制器方法添加Swagger注释,包括参数说明和响应定义
为DaemonSet控制器添加了Swagger文档注释,包括获取回滚历史、重启、批量重启、回滚到指定版本、批量停止和批量恢复等API接口的详细说明
将ShouldBindJSON的错误处理改为使用短变量声明err
将interface{}类型替换为any类型以提高代码可读性
为List、Add、Update和Delete接口添加Swagger注释文档,方便API文档生成
weibaohui added 12 commits July 20, 2025 22:04
为YAML控制器的UploadFile、Apply和Delete方法添加Swagger文档注释
将yamlRequest结构体移动到comm.go文件
修改DaemonSet相关接口路由,统一添加cluster参数
修复ShouldBindJSON错误处理变量重复声明问题
将文档相关接口路径修改为包含集群名称,以支持多集群环境下的文档查询
修改CronJob的暂停、恢复及批量操作接口,增加集群名称参数
统一路由前缀为/k8s/cluster/{cluster},以支持多集群场景
修改所有Deployment相关API接口,在路径中添加cluster参数以支持多集群操作
统一将错误变量赋值从`:=`改为`=`以保持一致性
避免重复声明err变量,提高代码简洁性
在ConfigMap的导入、更新和创建接口中增加集群名称路径参数,以支持多集群环境下的操作
为GatewayClassOptionList和ClusterResourceCount接口添加Swagger注释
更新ClusterResourceCount接口的路由路径以包含集群名称参数
为Helm Release控制器的各个API接口添加Swagger注解,包括接口说明、参数定义和响应格式
添加 swagger 注释以生成 API 文档,包括参数和响应信息
添加Swagger注释以描述K8sGPT相关接口的功能和参数
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🔭 Outside diff range comments (5)
pkg/controller/dynamic/pod_link.go (1)

458-476: 缺少 Swagger 文档注释

LinksPod 方法缺少 Swagger 文档注释,而文件中其他所有方法都有完整的 Swagger 注释。为保持一致性,应该添加相应的文档注释。

LinksPod 方法添加 Swagger 注释:

+// @Summary 获取Pod关联的Pod列表
+// @Security BearerAuth
+// @Param cluster query string true "集群名称"
+// @Param kind path string true "资源类型"
+// @Param group path string true "API组"
+// @Param version path string true "API版本"
+// @Param ns path string true "命名空间"
+// @Param name path string true "资源名称"
+// @Success 200 {object} string
+// @Router /k8s/cluster/{cluster}/{kind}/group/{group}/version/{version}/ns/{ns}/name/{name}/links/pod [get]
 func (pc *PodLinkController) LinksPod(c *gin.Context) {
pkg/controller/deploy/deploy.go (4)

64-80: 改进批量操作的错误处理机制

当前实现在批量操作中如果遇到错误会继续处理其他部署,但只返回最后遇到的错误,这可能会掩盖之前的错误信息。

建议收集所有错误信息:

-	for i := 0; i < len(req.Names); i++ {
-		name := req.Names[i]
-		ns := req.Namespaces[i]
-		x := kom.Cluster(selectedCluster).WithContext(ctx).Resource(&v1.Deployment{}).Namespace(ns).Name(name).
-			Ctl().Scaler().Stop()
-		if x != nil {
-			klog.V(6).Infof("批量停止 deploy 错误 %s/%s %v", ns, name, x)
-
-			err = x
-		}
-	}
-
-	if err != nil {
-		amis.WriteJsonError(c, err)
-		return
-	}
+	var errors []string
+	for i := 0; i < len(req.Names); i++ {
+		name := req.Names[i]
+		ns := req.Namespaces[i]
+		x := kom.Cluster(selectedCluster).WithContext(ctx).Resource(&v1.Deployment{}).Namespace(ns).Name(name).
+			Ctl().Scaler().Stop()
+		if x != nil {
+			klog.V(6).Infof("批量停止 deploy 错误 %s/%s %v", ns, name, x)
+			errors = append(errors, fmt.Sprintf("%s/%s: %v", ns, name, x))
+		}
+	}
+
+	if len(errors) > 0 {
+		amis.WriteJsonError(c, fmt.Errorf("批量操作失败: %s", strings.Join(errors, "; ")))
+		return
+	}

55-66: 添加数组长度验证防止运行时异常

批量操作假设 name_listns_list 数组长度相同,但没有进行验证。如果数组长度不匹配会导致运行时异常。

在所有批量操作中添加长度验证:

 	var req struct {
 		Names      []string `json:"name_list"`
 		Namespaces []string `json:"ns_list"`
 	}
 	if err = c.ShouldBindJSON(&req); err != nil {
 		amis.WriteJsonError(c, err)
 		return
 	}
+
+	if len(req.Names) != len(req.Namespaces) {
+		amis.WriteJsonError(c, fmt.Errorf("name_list 和 ns_list 长度必须相同"))
+		return
+	}

253-266: 改进版本比较的错误处理和可读性

当前实现没有处理找不到指定版本的情况,且忽略了 YAML 转换的错误。

 	var rsVersion *v1.ReplicaSet
 	for _, r := range rsList {
 		if r.ObjectMeta.Annotations != nil && r.ObjectMeta.Annotations[deployment.RevisionAnnotation] == revision {
 			rsVersion = r
 			break
 		}
 	}
+
+	if rsVersion == nil {
+		amis.WriteJsonError(c, fmt.Errorf("未找到版本 %s 的 ReplicaSet", revision))
+		return
+	}

-	current, _ := yaml.JSONToYAML([]byte(utils.ToJSON(rsVersion)))
-	latest, _ := yaml.JSONToYAML([]byte(utils.ToJSON(rsLatest)))
+	currentYAML, err := yaml.JSONToYAML([]byte(utils.ToJSON(rsVersion)))
+	if err != nil {
+		amis.WriteJsonError(c, fmt.Errorf("转换当前版本为 YAML 失败: %v", err))
+		return
+	}
+	latestYAML, err := yaml.JSONToYAML([]byte(utils.ToJSON(rsLatest)))
+	if err != nil {
+		amis.WriteJsonError(c, fmt.Errorf("转换最新版本为 YAML 失败: %v", err))
+		return
+	}
 	amis.WriteJsonData(c, gin.H{
-		"current": string(current),
-		"latest":  string(latest),
+		"current": string(currentYAML),
+		"latest":  string(latestYAML),
 	})

480-540: 简化请求结构并添加字段验证

当前的嵌套结构过于复杂,且缺少必要的字段验证。硬编码的标签值可能不适用于所有场景。

建议简化结构并添加验证:

 	var req struct {
-		Metadata struct {
-			Namespace   string            `json:"namespace"`
-			Name        string            `json:"name"`
-			Labels      map[string]string `json:"labels,omitempty"`
-			Annotations map[string]string `json:"annotations,omitempty"`
-		}
-		Spec struct {
-			Replicas int32 `json:"replicas"`
-			Template struct {
-				Spec struct {
-					Containers []struct {
-						Name            string            `json:"name"`
-						Image           string            `json:"image"`
-						ImagePullPolicy corev1.PullPolicy `json:"imagePullPolicy"`
-					} `json:"containers"`
-				} `json:"spec"`
-			} `json:"template"`
-		}
+		Namespace   string            `json:"namespace" binding:"required"`
+		Name        string            `json:"name" binding:"required"`
+		Labels      map[string]string `json:"labels,omitempty"`
+		Annotations map[string]string `json:"annotations,omitempty"`
+		Replicas    int32            `json:"replicas" binding:"min=1"`
+		Containers  []struct {
+			Name            string            `json:"name" binding:"required"`
+			Image           string            `json:"image" binding:"required"`
+			ImagePullPolicy corev1.PullPolicy `json:"imagePullPolicy"`
+		} `json:"containers" binding:"required,min=1"`
 	}

同时,避免硬编码版本标签:

-				Labels: map[string]string{
-					"app":     req.Metadata.Name,
-					"version": "v1",
-				},
+				Labels: map[string]string{
+					"app": req.Name,
+				},
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5eeb42f and 6c31885.

📒 Files selected for processing (17)
  • pkg/controller/cluster_status/status.go (1 hunks)
  • pkg/controller/cm/cm.go (5 hunks)
  • pkg/controller/cronjob/cronjob.go (4 hunks)
  • pkg/controller/deploy/deploy.go (17 hunks)
  • pkg/controller/doc/doc.go (2 hunks)
  • pkg/controller/ds/ds.go (9 hunks)
  • pkg/controller/dynamic/comm.go (1 hunks)
  • pkg/controller/dynamic/dynamic.go (17 hunks)
  • pkg/controller/dynamic/node_affinity.go (4 hunks)
  • pkg/controller/dynamic/pod_affinity.go (3 hunks)
  • pkg/controller/dynamic/pod_anti_affinity.go (3 hunks)
  • pkg/controller/dynamic/pod_link.go (10 hunks)
  • pkg/controller/dynamic/yaml.go (3 hunks)
  • pkg/controller/gatewayapi/gateway_class.go (1 hunks)
  • pkg/controller/helm/helm_release.go (8 hunks)
  • pkg/controller/ingressclass/ingress_class.go (2 hunks)
  • pkg/controller/k8sgpt/k8sgpt.go (4 hunks)
✅ Files skipped from review due to trivial changes (5)
  • pkg/controller/dynamic/comm.go
  • pkg/controller/gatewayapi/gateway_class.go
  • pkg/controller/dynamic/yaml.go
  • pkg/controller/helm/helm_release.go
  • pkg/controller/k8sgpt/k8sgpt.go
🚧 Files skipped from review as they are similar to previous changes (6)
  • pkg/controller/cluster_status/status.go
  • pkg/controller/cm/cm.go
  • pkg/controller/cronjob/cronjob.go
  • pkg/controller/ds/ds.go
  • pkg/controller/doc/doc.go
  • pkg/controller/dynamic/dynamic.go
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Analyze (go)
🔇 Additional comments (12)
pkg/controller/ingressclass/ingress_class.go (1)

19-78: API 设计良好,实现正确

两个新增的 API 端点实现都遵循了良好的实践:

  • 完整的错误处理
  • 正确的参数提取和验证
  • 适当的响应格式
  • 一致的命名约定

代码结构清晰,逻辑正确。

pkg/controller/dynamic/pod_link.go (1)

86-476: 代码结构良好,实现一致

所有的 Pod 链接端点都遵循了一致的实现模式:

  • 统一的参数提取
  • 标准的错误处理
  • 调用相应的服务方法
  • 使用 amis.WriteJsonList 返回结果

代码结构清晰,易于维护。

pkg/controller/dynamic/node_affinity.go (3)

182-182: 代码风格改进良好

err := c.ShouldBindJSON(&info) 的赋值简化是一个很好的风格改进,使代码更简洁一致。


392-392: 使用 Go 1.18+ 泛型是现代化的改进

将函数参数类型从 interface{} 更新为 any 是使用 Go 1.18+ 泛型的现代化改进,提高了代码的可读性。


34-163: Swagger 文档注释完整且一致

为所有的节点亲和性管理方法添加了完整的 Swagger 注释,包括:

  • 清晰的摘要描述
  • 安全认证要求
  • 详细的参数文档
  • 响应格式说明
  • 准确的路由路径

文档结构一致,有助于 API 使用者理解和使用这些端点。

pkg/controller/dynamic/pod_affinity.go (2)

37-140: Swagger 文档注释全面且规范

为所有 Pod 亲和性管理方法添加了全面的 Swagger 注释:

  • 描述清晰准确
  • 参数文档详细完整
  • 请求体和响应格式明确
  • 路由路径正确

文档质量高,便于 API 集成和使用。


159-159: 代码风格保持一致

与其他控制器保持一致的错误处理风格改进,代码更加简洁。

pkg/controller/dynamic/pod_anti_affinity.go (2)

28-134: Swagger 文档注释完整准确

为所有 Pod 反亲和性管理方法添加了完整的 Swagger 注释,文档结构与其他亲和性控制器保持一致,有助于维护 API 文档的统一性。


150-150: 代码风格改进一致

与其他控制器保持相同的错误处理风格改进,提升了代码的一致性。

pkg/controller/deploy/deploy.go (3)

40-46: Swagger 文档注释完善且准确

文档注释很好地描述了 API 端点的功能、参数和安全要求,与实际的处理器实现保持一致。


420-431: 事件查询逻辑实现正确

事件收集逻辑正确地从 Deployment、ReplicaSet 和 Pod 中获取相关事件,查询条件构建也是合理的。


22-37: 路由注册和处理器结构设计良好

所有处理器遵循一致的模式,包括上下文提取、集群选择和错误处理。Swagger 注释完整且一致,响应模式通过 amis 工具函数保持统一。

// @Param name path string true "资源名称"
// @Param body body podAffinity true "Pod反亲和性配置"
// @Success 200 {object} string
// @Router /k8s/cluster/{cluster}/{kind}/group/{group}/version/{version}/update_pod_anti_affinity/ns/{ns}/name/{name} [post]
func (ac *PodAntiAffinityController) UpdatePodAntiAffinity(c *gin.Context) {
processPodAffinity(c, "modify")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

函数调用错误

UpdatePodAntiAffinity 方法中,调用了 processPodAffinity(c, "modify"),但应该调用 processPodAntiAffinity(c, "modify")。这是一个复制粘贴错误。

修正函数调用:

 func (ac *PodAntiAffinityController) UpdatePodAntiAffinity(c *gin.Context) {
-	processPodAffinity(c, "modify")
+	processPodAntiAffinity(c, "modify")
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
processPodAffinity(c, "modify")
func (ac *PodAntiAffinityController) UpdatePodAntiAffinity(c *gin.Context) {
processPodAntiAffinity(c, "modify")
}
🤖 Prompt for AI Agents
In pkg/controller/dynamic/pod_anti_affinity.go at line 118, the function call
mistakenly uses processPodAffinity instead of processPodAntiAffinity. Replace
the call to processPodAffinity(c, "modify") with processPodAntiAffinity(c,
"modify") to correctly invoke the intended function.

Comment on lines +19 to +24
// @Summary 设置默认的 IngressClass
// @Security BearerAuth
// @Param cluster query string true "集群名称"
// @Param name path string true "IngressClass 名称"
// @Success 200 {object} string
// @Router /k8s/cluster/{cluster}/ingress_class/set_default/name/{name} [post]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Swagger 路由路径与注释不一致

Swagger 注释中的路由路径使用了 {cluster} 占位符,但实际的路由注册并未包含集群路径前缀。这可能会导致 API 文档与实际路由不匹配。

建议确保 Swagger 注释中的路由路径与实际注册的路由保持一致:

-// @Router /k8s/cluster/{cluster}/ingress_class/set_default/name/{name} [post]
+// @Router /ingress_class/set_default/name/{name} [post]
-// @Router /k8s/cluster/{cluster}/ingress_class/option_list [get]
+// @Router /ingress_class/option_list [get]

或者在路由注册时添加集群前缀。

🤖 Prompt for AI Agents
In pkg/controller/ingressclass/ingress_class.go around lines 19 to 24, the
Swagger route path includes a {cluster} placeholder that does not match the
actual registered route, causing documentation and routing inconsistencies. To
fix this, either update the Swagger annotation to remove the {cluster} segment
to match the real route or modify the route registration to include the cluster
prefix so both paths align correctly.

weibaohui added 11 commits July 20, 2025 22:36
为MetadataController和ActionController中的方法添加Swagger注解,包括接口摘要、安全认证、参数和响应格式等
添加Swagger注释以生成API文档,包括接口描述、参数和返回信息
为节点污点管理的所有接口添加Swagger注释,包括参数、认证和响应格式
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🔭 Outside diff range comments (4)
pkg/controller/rs/rs.go (3)

74-84: 批量操作的错误处理可能导致部分失败被掩盖

在批量重启逻辑中,如果某个 ReplicaSet 重启失败,错误会被覆盖而不是累积。这可能导致只报告最后一个错误,而掩盖了前面的失败。

建议改进错误处理逻辑:

+	var errors []string
	for i := 0; i < len(req.Names); i++ {
		name := req.Names[i]
		ns := req.Namespaces[i]

		x := kom.Cluster(selectedCluster).WithContext(ctx).Resource(&v1.ReplicaSet{}).Namespace(ns).Name(name).
			Ctl().Rollout().Restart()
		if x != nil {
			klog.V(6).Infof("批量重启 rs 错误 %s/%s %v", ns, name, x)
-			err = x
+			errors = append(errors, fmt.Sprintf("%s/%s: %v", ns, name, x))
		}
	}

-	if err != nil {
-		amis.WriteJsonError(c, err)
+	if len(errors) > 0 {
+		amis.WriteJsonError(c, fmt.Errorf("批量操作失败: %s", strings.Join(errors, "; ")))
		return
	}

117-127: 批量停止和恢复操作存在相同的错误处理问题

BatchStop 和 BatchRestore 方法中的错误处理逻辑与 BatchRestart 存在相同问题,建议应用相同的修复方案。

Also applies to: 160-170


210-212: Event 方法中的资源类型不匹配

在获取 Pod 列表时使用了错误的资源类型 &v1.Deployment{},应该使用 &v1.Pod{}

-	pods, err := kom.Cluster(selectedCluster).WithContext(ctx).Resource(&v1.Deployment{}).
+	pods, err := kom.Cluster(selectedCluster).WithContext(ctx).Resource(&v1.Pod{}).
		Namespace(ns).Name(name).
		Ctl().ReplicaSet().ManagedPods()
pkg/controller/pod/pod_forward.go (1)

220-244: 随机端口分配算法可能导致无限循环

在端口范围耗尽的情况下,getRandomPort 函数可能会陷入无限循环。

建议添加重试次数限制:

func getRandomPort() string {
+	maxRetries := 100
+	for retry := 0; retry < maxRetries; retry++ {
-	for {
		port := utils.RandInt(40000, 49999)
		portStr := fmt.Sprintf("%d", port)

		portForwardTableMutex.RLock()
		isUsed := false
		for _, portInfo := range portForwardTable {
			if portInfo.LocalPort == portStr {
				isUsed = true
				break
			}
		}
		portForwardTableMutex.RUnlock()

		if !isUsed {
			return portStr
		}
	}
+	// 如果所有重试都失败,返回错误或使用固定端口
+	return "0" // 让系统自动分配
}
🧹 Nitpick comments (1)
pkg/controller/pod/pod_forward.go (1)

148-152: 停止端口转发时可能出现阻塞

直接向 channel 发送信号可能会阻塞,如果接收方没有准备好接收。

建议使用非阻塞发送或关闭 channel:

	if pf, ok := portForwardTable[key]; ok {
-		pf.StopCh <- struct{}{}
+		close(pf.StopCh)
		pf.Status = "stopped"
		pf.LocalPort = ""
	}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6c31885 and ce28524.

📒 Files selected for processing (16)
  • pkg/controller/node/metadata.go (3 hunks)
  • pkg/controller/node/node.go (6 hunks)
  • pkg/controller/node/resource.go (2 hunks)
  • pkg/controller/node/taint.go (5 hunks)
  • pkg/controller/node/xterm.go (2 hunks)
  • pkg/controller/ns/limit_range.go (1 hunks)
  • pkg/controller/ns/ns.go (1 hunks)
  • pkg/controller/ns/resource_quota.go (1 hunks)
  • pkg/controller/pod/pod.go (2 hunks)
  • pkg/controller/pod/pod_file.go (6 hunks)
  • pkg/controller/pod/pod_forward.go (3 hunks)
  • pkg/controller/pod/pod_label.go (1 hunks)
  • pkg/controller/pod/pod_resource.go (2 hunks)
  • pkg/controller/pod/pod_xterm.go (1 hunks)
  • pkg/controller/rs/rs.go (6 hunks)
  • pkg/controller/sso/sso.go (4 hunks)
✅ Files skipped from review due to trivial changes (12)
  • pkg/controller/ns/limit_range.go
  • pkg/controller/ns/resource_quota.go
  • pkg/controller/ns/ns.go
  • pkg/controller/pod/pod_resource.go
  • pkg/controller/pod/pod_label.go
  • pkg/controller/pod/pod_xterm.go
  • pkg/controller/node/resource.go
  • pkg/controller/node/xterm.go
  • pkg/controller/node/node.go
  • pkg/controller/node/metadata.go
  • pkg/controller/sso/sso.go
  • pkg/controller/node/taint.go
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Analyze (go)
🔇 Additional comments (9)
pkg/controller/rs/rs.go (1)

268-269: 无需修改:HPAList 方法在 ReplicaSet 控制器中已正确实现

rg 查询结果显示,kom 库中各类控制器(StatefulSet、Deployment、ReplicaSet、CRD 等)都一致使用了 Ctl().Xxx().HPAList() 来列出与该资源关联的 HPA,说明该方法确实存在并用法正确,无需改为其它调用。

Likely an incorrect or invalid review comment.

pkg/controller/pod/pod_file.go (3)

46-51: Swagger 文档注释完整且格式正确

为 List 方法添加的 Swagger 注释格式正确,包含了必要的安全认证、参数说明和路由定义。


88-93: 所有方法的 Swagger 文档注释都已正确添加

各个文件操作方法的 Swagger 注释都遵循了一致的格式,包含了完整的 API 文档信息。

Also applies to: 147-152, 193-201, 246-256, 357-362


295-295: 文件名安全处理已实现

代码中使用 utils.SanitizeFileName 对上传的文件名进行安全处理,这是良好的安全实践。

pkg/controller/pod/pod.go (3)

24-32: 新增的日志流式传输和下载功能的 Swagger 文档完整

StreamLogs 和 DownloadLogs 方法的 Swagger 注释格式正确,清晰地描述了 API 功能和参数。

Also applies to: 78-86


57-60: Pod 数量验证逻辑合理

两个方法都正确验证了查询结果中 Pod 的数量,确保只操作单个 Pod,避免了潜在的歧义。

Also applies to: 110-113


121-121: 下载日志时正确禁用了跟随模式

在 DownloadLogs 方法中设置 logOpt.Follow = false 是正确的,因为下载操作不需要持续跟随日志输出。

pkg/controller/pod/pod_forward.go (2)

43-52: 端口转发功能的 Swagger 文档注释完整

三个端口转发方法的 Swagger 注释都包含了完整的参数说明和路由定义。

Also applies to: 125-133, 158-164


93-122: 端口转发启动逻辑中的并发安全性良好

使用 goroutine 启动端口转发,并在 mutex 保护下更新全局状态表,并发安全性处理得当。错误情况下也会正确更新状态。

@weibaohui weibaohui merged commit 370d09d into main Jul 20, 2025
6 checks passed
@weibaohui weibaohui deleted the swagger branch July 20, 2025 15:14
@coderabbitai coderabbitai bot mentioned this pull request Jul 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant