Sonui 的手账

No. 018 Date Topic 云原生 Tags KubeSphere · Kubernetes · ArgoCD · Go

KubeSphere 扩展组件开发笔记

前段时间参加了云原生 Meetup 杭州站活动,正好在这次活动上了解到了 KubeSphere 正在开展扩展组件开发训练营,于是报名了这个活动,记录下学习过程。

0x00 说明

资料来源:

0x01 开发环境搭建

开发需要一个 ks 集群,可以使用 KubeSphere 官方提供的 ks-dev 环境,也可以自己搭建一个 ks 集群。

使用 ks-dev 环境

https://kubesphere.cloud/ 可以在这里注册一个账号,然后在控制台创建一个 ks 集群。

官方每个月会赠送 10h 的免费使用时间,可以用来开发测试。

本地安装

Node 使用 nvm 安装

wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc
nvm install 18
terminal

安装 yarn

npm install --global yarn
terminal

安装 helm

这里官方提供了文件和脚本两种安装方式,因为是专门为了开发扩展组件开的环境所以为了省事直接脚本安装

https://helm.sh/docs/intro/install/

curl https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash
terminal

安装 kubectl

curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
sudo chmod +x kubectl 
sudo mv kubectl /usr/local/bin
terminal

安装完成以后去 ks 面板下载 kubeconfig 文件放到 ~/.kube/config 目录下

安装 ksbuilder

wget https://github.com/kubesphere/ksbuilder/releases/download/v0.3.13/ksbuilder_0.3.13_linux_amd64.tar.gz
tar -zxf ksbuilder_0.3.13_linux_amd64.tar.gz
sudo mv ksbuilder /usr/local/bin
terminal

检查安装版本

sonui@server:~$ ksbuilder --version
ksbuilder version 0.3.13
sonui@server:~$ node --version
v18.20.2
sonui@server:~$ yarn --version
1.22.22
sonui@server:~$ helm version
version.BuildInfo{Version:"v3.14.4", GitCommit:"81c902a123462fd4052bc5e9aa9c513c4c8fc142", GitTreeState:"clean", GoVersion:"go1.21.9"}
sonui@server:~$ kubectl version
Client Version: v1.30.0
Kustomize Version: v5.0.4-0.20230601165947-6ce0bf390ce3
sonui@server:~$ kubectl get node
NAME   STATUS   ROLES                         AGE   VERSION
ks     Ready    control-plane,master,worker   15d   v1.23.10
sonui@server:~$ kubectl -n kubesphere-system get po
NAME                                     READY   STATUS    RESTARTS        AGE
ks-apiserver-754d47ffcc-fx5fz            1/1     Running   2 (6d21h ago)   15d
ks-console-54958f4674-8s225              1/1     Running   2 (6d21h ago)   15d
ks-controller-manager-59d55bc77b-vgnl7   1/1     Running   2 (6d21h ago)   15d
terminal

编写 ks-apiserver 反向代理

参考官方示例

https://raw.githubusercontent.com/kubesphere/extension-samples/master/extensions-backend/weave-scope/weave-scope-reverse-proxy.yaml

修改为 argocd

apiVersion: extensions.kubesphere.io/v1alpha1
kind: ReverseProxy
metadata:
  name: argocd-scope
spec:
  matcher:
    method: '*'
    path: /proxy/argocd.works/*
  upstream:
    url: http://argocd-server.argocd.svc/proxy/argocd.works/
    # url: http://192.168.2.128:8080/proxy/argocd.works/ # 后面调试用到的
  directives:
    authProxy: true
    headerUp:
    - '-Authorization'
status:
  state: Available
yaml

其中 upstream.url 为 argocd 的服务地址

http://[service name].[namespace].svc

部署 ArgoCD

部署 ArgoCD 时需要修改下部署参数

首先创建一个 kustomization.yaml 文件

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: argocd
resources:
- github.com/argoproj/argo-cd/manifests/cluster-install?ref=v2.10.0 # 使用稳定版本

# 配置patches来修改argocd-server的配置
patches:
- path: argocd-server-config-patch.yaml
  target:
    kind: ConfigMap
    name: argocd-cmd-params-cm
yaml

argocd-server-config-patch.yaml:

apiVersion: v1
kind: ConfigMap
metadata:
  name: argocd-cmd-params-cm
  namespace: argocd
data:
  # 设置UI Base Path
  server.basehref: "/proxy/argocd.works/"  # 注意结尾的斜杠
  server.insecure: "true"      # 禁用 TLS
  server.rootpath: "/proxy/argocd.works"
yaml

basehref 配置说明

ArgoCD 返回页面中 base href 已指向 /proxy/argocd.works/

If the Argo CD UI is available under a non-root path (e.g. /argo-cd instead of /) then the UI path should be configured in the API server. To configure the UI path add the –basehref flag into the argocd-server deployment command https://argo-cd.readthedocs.io/en/stable/operator-manual/ingress/#ui-base-path

然后执行 kubectl apply -k . 重新部署 ArgoCD

如果这个配置没有生效可以执行 kubectl rollout restart deployment argocd-server -n argocd 重启下服务使更改生效

设置前端反向代理

插件设置下 webpack.config.js,如果不设置的话在浏览器中访问 ArgoCD 面板会提示 404 错误

ks-console/configs/webpack.config.js

const { merge } = require('webpack-merge');
const baseConfig = require('@ks-console/bootstrap/webpack/webpack.dev.conf');

const webpackDevConfig = merge(baseConfig, {
  devServer: {
    proxy: {
      '/proxy': {
        target: 'http://192.168.2.128:30880', // 修改为目标 ks-apiserver 的地址
        onProxyReq: (proxyReq, req, res) => {
            const username = 'admin'        // 请求代理时的用户凭证
            const password = '<你的密码>'
            const auth = Buffer.from(`${username}:${password}`).toString("base64");
            proxyReq.setHeader('Authorization', `Basic ${auth}`);
          },
      },
    },
  },
});

module.exports = webpackDevConfig;
js

username 和 password 填 KubeSphere 控制台的登录账号;新集群的默认账号和密码见 KubeSphere 官方文档,登录后记得改掉默认密码。

设置好以后需要重启下 yarn dev 使更改生效

0x02 调试

全部完成后访问控制面板可以看到弹出 ArgoCD 登录界面

KubeSphere 控制台中嵌入的 ArgoCD 登录界面

按照文档说明尝试登录出现进入面板后又回到登录界面的问题,F12 查看有接口返回 401 错误,猜测可能是传递给 ArgoCD 服务的这两个请求没有认证信息

开发者工具中 clusters 接口返回 401 Unauthorized

根据官方调试教程本地起了一个 ArgoCD 服务,然后修改 ReverseProxy 的 upstream.url 为本地 ArgoCD 服务地址

对官方文档中的 vscode 调试配置做了下修改

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Debug ArgoCD Server",
            "type": "go",
            "request": "launch",
            "mode": "auto",
            "program": "${workspaceFolder}/argo-cd/cmd/main.go",
            "env": {
                "ARGOCD_BINARY_NAME": "argocd-server",
                "CGO_ENABLED": "0",
                "KUBECONFIG": "/home/sonui/.kube/config",
            },
            "envFile": [
                "${workspaceFolder}/.envrc.remote",
            ],
            "args": [
                "--insecure",
                "--rootpath",
                "/proxy/argocd.works/",
                "--basehref",
                "/proxy/argocd.works/"
            ]
        }
    ]
}
jsonc

在 https://github.com/argoproj/argo-cd/blob/a7637cd106f615119930439d963ec0a9618b404d/server/server.go#L1037 添加请求头打印

    gwMuxOpts := runtime.WithMarshalerOption(runtime.MIMEWildcard, new(grpc_util.JSONMarshaler))
    gwCookieOpts := runtime.WithForwardResponseOption(a.translateGrpcCookieHeader)
    gwmux := runtime.NewServeMux(gwMuxOpts, gwCookieOpts)

    var handler http.Handler = gwmux
    if a.EnableGZip {
        handler = compressHandler(handler)
    }
    if len(a.ContentTypes) > 0 {
        handler = enforceContentTypes(handler, a.ContentTypes)
    } else {
        log.WithField(common.SecurityField, common.SecurityHigh).Warnf("Content-Type enforcement is disabled, which may make your API vulnerable to CSRF attacks")
    }

    logMiddleware := func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            // 打印基本请求信息
            log.WithFields(log.Fields{
                "method":     r.Method,
                "url":        r.URL.String(),
                "headers":    r.Header,
                "remoteAddr": r.RemoteAddr,
                "host":       r.Host,
                "requestURI": r.RequestURI,
            }).Info("Incoming HTTP request")

            next.ServeHTTP(w, r)
        })
    }
    handler = logMiddleware(handler)
    mux.Handle("/api/", handler)
go

发起请求

浏览器开发者工具中带有 argocd.token Cookie 的请求头

可以在浏览器开发者工具中看到请求头中有 Cookie 信息,而 ArgoCD 打印的日志没有

ArgoCD 打印的请求日志中没有 Cookie

如果在上面的日志代码中手动写死一个 Cookie 信息再请求能看到接口返回正常,确定是反向代理的问题,待联系 ks 技术问问,这里先写死继续后续开发

刷新页面提示 open dist/app/index.html: file does not exist 错误,添加下启动配置

进入 ArgoCD 代码目录下的 ui 目录,执行 build 命令生成 dist 目录,拷贝出来绝对地址填入下面的位置

          "args": [
                // ... 其它配置
                "--staticassets",
                "/path/to/argo-cd"
          ]
jsonc

重启 ArgoCD 服务,刷新浏览器页面可以看到正常进入 ArgoCD 面板

在 KubeSphere 中正常进入的 ArgoCD 应用面板

待解决 Cookie 问题后再对接 OAuth 认证

OAuth 对接文档

留言

正在翻留言……

写点什么

留言审核通过后公开。邮箱选填,只用来区分同名的人,不会公开。 存了什么、怎么删除

这本手账属于

Sonui

三牌楼的猫咪贴纸

三牌楼的猫咪贴纸墙:把街坊拍到的猫做成贴纸,贴在一块公共画布上。

© 2019–2026 Sonui 文章采用 CC BY-NC-SA 4.0 隐私说明 开源许可

运维与网络 ,共 5 篇

已解决

给 SL3000 刷 ImmortalWrt

保留原厂引导,用配置备份导入公钥拿到 SSH,只写 NOR 的 firmware 分区,再把 eMMC 挂成 extroot。

#OpenWrt#ImmortalWrt#路由器 2026.10.26
已解决

Docker 容器映射端口访问限制

在 DOCKER-USER 链中添加 iptables 规则,只允许指定网段访问容器映射端口。

#Docker#Linux#网络 2024.12.03
已解决

PVE 修改节点主机名

修改 Proxmox VE 节点主机名需要改的文件、节点目录迁移和存储配置检查。

#PVE#Linux 2024.04.12

WireGuard Use Notes

用 wg-easy 搭建 WireGuard,把家庭、公司和外出设备组进同一个虚拟网段。

#WireGuard#异地组网#网络 2024.02.13
已解决

Linux 报错 Certificate verification failed: The certificate is NOT trusted.

apt 使用 https 源报证书不受信任,先临时换 http 源安装 ca-certificates 再改回。

#Linux#安全 2021.03.11

后端 ,共 5 篇

HTTP 幂等机制支持

借助请求头唯一标识与 Redis,在 Kratos 中间件里为非幂等接口实现幂等。

#HTTP#后端#幂等 2024.04.25

Redis Reading Notes

Redis 源码阅读笔记,从 SDS 动态字符串的结构与内存布局讲起。

#Redis#源码阅读#C/C++ 2023.07.08

Fitness function-driven development(适应度函数驱动开发)翻译

ThoughtWorks 文章《Fitness function-driven development》的翻译开篇,目前只译了开头两句。

Apache Answer Plugin 开发笔记

为 Apache Answer 开发飞书通知插件的设计思路、配置项与插件创建要点。

#Apache Answer#Go#飞书 2024.08.03

一些收藏的文章

收藏的 Kubernetes 与后端文章链接,涵盖 Go Kratos、HTTP/3 和 REST API 设计。

云原生 ,共 3 篇

k8s 集群安装

用 kubeadm 和 containerd 在三台 Ubuntu 上搭建集群,记录安装过程与关闭 swap 的坑。

#Kubernetes#Linux#containerd 2024.05.09

KubeSphere 扩展组件开发笔记

参加 KubeSphere 扩展组件训练营,把 ArgoCD 接入 KubeSphere 的环境搭建与调试记录。

#KubeSphere#Kubernetes#ArgoCD 2024.04.12

The hater’s guide to Kubernetes

摘录 Paul Butler 的文章开头:Kubernetes 常被视为小团队过度设计的标志。

早年笔记 ,共 4 篇

C/C++ 二叉树

用 C/C++ 实现二叉树的创建、带深度的遍历输出与查找,并记下查找二叉树的特性。

#C/C++#数据结构 2020.11.19

Python 转换金额数字大写为数字小写

用 Python 把中文大写金额转换成小写数字,全程用整数运算来避开浮点误差。

VS Code C/C++ 环境配置

在 Windows 上安装 MinGW-W64 和 VS Code,配置环境变量与插件,跑通第一个 C/C++ 程序。

#VS Code#C/C++#MinGW 2021.09.09

easySQLite 使用笔记

补充 easySQLite 文档没写清的用法:中文路径下打开数据库失败的处理,以及读取字段值和主键。

#SQLite#C/C++#easySQLite 2019.02.09

Go ,共 3 篇

Go 中的 context

通过取消与超时示例,介绍 Go 中 context 的用法和传值注意事项。

#Go#context 2023.01.30

使用 Golang 开发腾讯云函数

记录用 Go 开发腾讯云函数时遇到的编译、启动、GLIBC 与部署缓存问题。

#Go#Serverless#腾讯云 2022.04.29

Golang 库 Redis 对 data 类型的支持

调试跟踪 go-redis 的 HSet 调用链,弄清它能序列化哪些数据类型。

#Go#Redis#源码阅读 2024.04.26

Web ,共 5 篇

Web 开发的安全之旅

青训营 Web 安全笔记,梳理 XSS、CSRF、注入、DoS 与中间人攻击的原理及防御手段。

#安全#前端#HTTP 2022.08.01

深入 CSS

字节青训营 CSS 进阶笔记,梳理特异度、继承、盒模型、常规流、BFC/IFC 与浮动定位。

#CSS#前端 2022.07.26

理解 CSS

字节青训营 CSS 入门笔记,涵盖引入方式、选择器、伪类、组合、颜色与字体样式。

#CSS#前端 2022.07.25

Hydro 二开笔记 前端篇

Hydro 评测系统二开前端篇的第一步:搭开发环境,安装 Node、MongoDB,拉取源码并用 pm2 启动。

#Hydro#前端#MongoDB 2022.04.03

如何设置 CORS

梳理跨域触发条件与预检机制,给出 CORS 各响应头的安全配置建议和中间件示例。

#CORS#HTTP#安全 2024.11.19

AI ,共 1 篇

已解决

通过 Cloudflare AI Gateway 使用 LLM

详细介绍如何通过 Cloudflare AI Gateway 使用 LLM,包括资源准备、配置方法和使用示例,帮助开发者快速集成 Cloudflare 的 AI 服务。

#AI#LLM#Cloudflare 2025.10.08

友链

交换友链

在任意笔记下留言,或到 GitHub 找我。写上你的名称、地址和一句话介绍就好。

我的名片:

名称
三牌楼猫咪贴纸
地址
https://meow.attack825.party
简介
三牌楼的猫咪贴纸
头像
https://meow.attack825.party/stickers/people-dog.webp

100%