From fb14c7da9873634525bee52925169b8ec0ada9dc Mon Sep 17 00:00:00 2001 From: weibaohui Date: Fri, 18 Oct 2024 23:04:01 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0context=E5=8F=82=E6=95=B0?= =?UTF-8?q?=E4=BB=A5=E6=94=AF=E6=8C=81=E5=8F=96=E6=B6=88=E6=93=8D=E4=BD=9C?= =?UTF-8?q?=E5=92=8C=E4=BC=A0=E9=80=92=E8=AF=B7=E6=B1=82=E7=89=B9=E5=AE=9A?= =?UTF-8?q?=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 在此更改中,将context.Context参数添加到多个函数中,以便于取消操作和传递请求特定值。主要修改包括: - 在ApplyYAML和DeleteYAML函数中添加context参数- 更新CRD相关函数以使用context参数 - 修改资源操作函数如CreateResource、UpdateResource和DeleteResource以支持context - 在控制器和处理器函数中传递context参数这些更改提高了系统的灵活性和响应能力,特别是在处理长时间运行的操作和需要传递用户特定信息的场景中。 --- internal/kubectl/apply.go | 21 ++++++------ internal/kubectl/callback.go | 21 ++++++------ internal/kubectl/client.go | 10 +----- internal/kubectl/configmap.go | 17 +++++----- internal/kubectl/deploy.go | 21 ++++++------ internal/kubectl/dynamic.go | 49 ++++++++++++++------------- internal/kubectl/dynamic_crd.go | 33 +++++++++--------- internal/kubectl/dynamic_gvr.go | 37 ++++++++++---------- internal/kubectl/image_pull_secret.go | 11 +++--- internal/kubectl/ingress.go | 17 +++++----- internal/kubectl/node.go | 9 ++--- internal/kubectl/ns.go | 17 +++++----- internal/kubectl/pod.go | 17 +++++----- internal/kubectl/pvc.go | 13 +++---- internal/kubectl/secret.go | 13 +++---- internal/kubectl/service_account.go | 21 ++++++------ internal/kubectl/statement.go | 3 -- internal/kubectl/svc.go | 17 +++++----- pkg/callback/cb.go | 7 ++-- pkg/controller/deploy/deploy.go | 6 ++-- pkg/controller/dynamic/dynamic.go | 46 +++++++++++++++---------- pkg/controller/ns/ns.go | 3 +- pkg/controller/pod/pod.go | 12 ++++--- 23 files changed, 223 insertions(+), 198 deletions(-) diff --git a/internal/kubectl/apply.go b/internal/kubectl/apply.go index c77c6dc..3a5927b 100644 --- a/internal/kubectl/apply.go +++ b/internal/kubectl/apply.go @@ -1,6 +1,7 @@ package kubectl import ( + "context" "fmt" "strings" @@ -10,7 +11,7 @@ import ( ) // ApplyYAML 解析并应用 YAML 字符串到 Kubernetes -func (k8s *Kubectl) ApplyYAML(yamlStr string) (result []string) { +func (k8s *Kubectl) ApplyYAML(ctx context.Context, yamlStr string) (result []string) { docs := splitYAML(yamlStr) for _, doc := range docs { @@ -34,11 +35,11 @@ func (k8s *Kubectl) ApplyYAML(yamlStr string) (result []string) { builtin := k8s.IsBuiltinResource(gvk.Kind) if !builtin { - crd, err := k8s.GetCRD(gvk.Kind, gvk.Group) + crd, err := k8s.GetCRD(ctx, gvk.Kind, gvk.Group) if err != nil { result = append(result, fmt.Sprintf("%v", err)) } else { - crdResult := k8s.ApplyCRD(crd, &obj) + crdResult := k8s.ApplyCRD(ctx, crd, &obj) result = append(result, crdResult) } continue @@ -54,11 +55,11 @@ func (k8s *Kubectl) ApplyYAML(yamlStr string) (result []string) { } // 使用 CreateOrUpdateResource 应用资源 - _, err := k8s.CreateResource(kind, ns, &obj) + _, err := k8s.CreateResource(ctx, kind, ns, &obj) if err != nil { if errors.IsAlreadyExists(err) { // 已经存在,更新 - existingResource, err := k8s.GetResource(kind, ns, obj.GetName()) + existingResource, err := k8s.GetResource(ctx, kind, ns, obj.GetName()) if err != nil { result = append(result, fmt.Sprintf("获取应用失败%v", err.Error())) continue @@ -67,7 +68,7 @@ func (k8s *Kubectl) ApplyYAML(yamlStr string) (result []string) { obj.SetResourceVersion(existingResource.GetResourceVersion()) } - _, err = k8s.UpdateResource(kind, ns, &obj) + _, err = k8s.UpdateResource(ctx, kind, ns, &obj) if err != nil { result = append(result, fmt.Sprintf("更新应用失败:%v", err.Error())) continue @@ -86,7 +87,7 @@ func (k8s *Kubectl) ApplyYAML(yamlStr string) (result []string) { return result } -func (k8s *Kubectl) DeleteYAML(yamlStr string) (result []string) { +func (k8s *Kubectl) DeleteYAML(ctx context.Context, yamlStr string) (result []string) { docs := splitYAML(yamlStr) for _, doc := range docs { @@ -112,12 +113,12 @@ func (k8s *Kubectl) DeleteYAML(yamlStr string) (result []string) { builtIn := k8s.IsBuiltinResource(gvk.Kind) if !builtIn { // CRD 类型资源 - crd, err := k8s.GetCRD(gvk.Kind, gvk.Group) + crd, err := k8s.GetCRD(ctx, gvk.Kind, gvk.Group) if err != nil { result = append(result, fmt.Sprintf("%v", err)) } else { // 确认为 CRD - crdResult := k8s.DeleteCRD(crd, &obj) + crdResult := k8s.DeleteCRD(ctx, crd, &obj) result = append(result, crdResult) } continue @@ -129,7 +130,7 @@ func (k8s *Kubectl) DeleteYAML(yamlStr string) (result []string) { ns = "default" // 默认命名空间 } - err := k8s.DeleteResource(gvk.Kind, ns, obj.GetName()) + err := k8s.DeleteResource(ctx, gvk.Kind, ns, obj.GetName()) if err != nil { result = append(result, fmt.Sprintf("%s/%s deleted error:%v", obj.GetKind(), obj.GetName(), err)) } else { diff --git a/internal/kubectl/callback.go b/internal/kubectl/callback.go index ab66f36..bdcb779 100644 --- a/internal/kubectl/callback.go +++ b/internal/kubectl/callback.go @@ -1,6 +1,7 @@ package kubectl import ( + "context" "fmt" "sort" @@ -26,7 +27,7 @@ type callbacks struct { type processor struct { kubectl *Kubectl - fns []func(*Kubectl) error + fns []func(context.Context, *Kubectl) error callbacks []*callback } type callback struct { @@ -35,7 +36,7 @@ type callback struct { after string remove bool replace bool - handler func(*Kubectl) error + handler func(context.Context, *Kubectl) error processor *processor } @@ -65,7 +66,7 @@ func (c *callback) Remove(name string) error { return c.processor.compile() } -func (c *callback) Replace(name string, fn func(*Kubectl) error) error { +func (c *callback) Replace(name string, fn func(context.Context, *Kubectl) error) error { klog.V(4).Infof("replacing callback `%s` \n", name) c.name = name c.handler = fn @@ -84,14 +85,14 @@ func (c *callback) After(name string) *callback { return c } -func (c *callback) Register(name string, fn func(*Kubectl) error) error { +func (c *callback) Register(name string, fn func(context.Context, *Kubectl) error) error { c.name = name c.handler = fn c.processor.callbacks = append(c.processor.callbacks, c) return c.processor.compile() } -func (p *processor) Get(name string) func(*Kubectl) error { +func (p *processor) Get(name string) func(context.Context, *Kubectl) error { for i := len(p.callbacks) - 1; i >= 0; i-- { if v := p.callbacks[i]; v.name == name && !v.remove { return v.handler @@ -104,13 +105,13 @@ func (p *processor) Remove(name string) error { return (&callback{processor: p}).Remove(name) } -func (p *processor) Replace(name string, fn func(*Kubectl) error) error { +func (p *processor) Replace(name string, fn func(context.Context, *Kubectl) error) error { return (&callback{processor: p}).Replace(name, fn) } -func (p *processor) Execute(k8s *Kubectl) error { +func (p *processor) Execute(ctx context.Context, k8s *Kubectl) error { for _, f := range p.fns { - err := f(k8s) + err := f(ctx, k8s) if err != nil { return err } @@ -126,7 +127,7 @@ func (p *processor) After(name string) *callback { return &callback{after: name, processor: p} } -func (p *processor) Register(name string, fn func(*Kubectl) error) error { +func (p *processor) Register(name string, fn func(context.Context, *Kubectl) error) error { return (&callback{processor: p}).Register(name, fn) } @@ -150,7 +151,7 @@ func (p *processor) compile() (err error) { } return } -func sortCallbacks(cs []*callback) (fns []func(*Kubectl) error, err error) { +func sortCallbacks(cs []*callback) (fns []func(context.Context, *Kubectl) error, err error) { var ( names, sorted []string sortCallback func(*callback) error diff --git a/internal/kubectl/client.go b/internal/kubectl/client.go index 0cb6c18..0de2765 100644 --- a/internal/kubectl/client.go +++ b/internal/kubectl/client.go @@ -1,7 +1,6 @@ package kubectl import ( - "context" "strings" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -79,9 +78,7 @@ func InitConnection(path string) { // 注册回调参数 kubectl.callbacks = initializeCallbacks(kubectl) - kubectl.Stmt = &Statement{ - Context: context.TODO(), - } + kubectl.Stmt = &Statement{} } func getKubeConfig(path string) (*rest.Config, error) { @@ -106,8 +103,3 @@ func getKubeConfig(path string) (*rest.Config, error) { func (k8s *Kubectl) Callback() *callbacks { return k8s.callbacks } - -func (k8s *Kubectl) WithContext(c context.Context) *Kubectl { - k8s.Stmt.Context = c - return kubectl -} diff --git a/internal/kubectl/configmap.go b/internal/kubectl/configmap.go index 9925a61..d019f78 100644 --- a/internal/kubectl/configmap.go +++ b/internal/kubectl/configmap.go @@ -1,14 +1,15 @@ package kubectl import ( + "context" "sort" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) -func (k8s *Kubectl) ListConfigMap(ns string) ([]v1.ConfigMap, error) { - list, err := k8s.client.CoreV1().ConfigMaps(ns).List(k8s.Stmt.Context, metav1.ListOptions{}) +func (k8s *Kubectl) ListConfigMap(ctx context.Context, ns string) ([]v1.ConfigMap, error) { + list, err := k8s.client.CoreV1().ConfigMaps(ns).List(ctx, metav1.ListOptions{}) if err == nil && list != nil && list.Items != nil && len(list.Items) > 0 { // 按创建时间倒序排序 Pods 列表 sort.Slice(list.Items, func(i, j int) bool { @@ -19,15 +20,15 @@ func (k8s *Kubectl) ListConfigMap(ns string) ([]v1.ConfigMap, error) { return nil, err } -func (k8s *Kubectl) GetConfigMap(ns, name string) (*v1.ConfigMap, error) { - ConfigMap, err := k8s.client.CoreV1().ConfigMaps(ns).Get(k8s.Stmt.Context, name, metav1.GetOptions{}) +func (k8s *Kubectl) GetConfigMap(ctx context.Context, ns, name string) (*v1.ConfigMap, error) { + ConfigMap, err := k8s.client.CoreV1().ConfigMaps(ns).Get(ctx, name, metav1.GetOptions{}) return ConfigMap, err } -func (k8s *Kubectl) RemoveConfigMap(ns, name string) error { - err := k8s.client.CoreV1().ConfigMaps(ns).Delete(k8s.Stmt.Context, name, metav1.DeleteOptions{}) +func (k8s *Kubectl) RemoveConfigMap(ctx context.Context, ns, name string) error { + err := k8s.client.CoreV1().ConfigMaps(ns).Delete(ctx, name, metav1.DeleteOptions{}) return err } -func (k8s *Kubectl) CreateConfigMap(cm *v1.ConfigMap) (*v1.ConfigMap, error) { - cm, err := k8s.client.CoreV1().ConfigMaps(cm.Namespace).Create(k8s.Stmt.Context, cm, metav1.CreateOptions{}) +func (k8s *Kubectl) CreateConfigMap(ctx context.Context, cm *v1.ConfigMap) (*v1.ConfigMap, error) { + cm, err := k8s.client.CoreV1().ConfigMaps(cm.Namespace).Create(ctx, cm, metav1.CreateOptions{}) return cm, err } diff --git a/internal/kubectl/deploy.go b/internal/kubectl/deploy.go index 177d5ab..d80b695 100644 --- a/internal/kubectl/deploy.go +++ b/internal/kubectl/deploy.go @@ -1,6 +1,7 @@ package kubectl import ( + "context" "strings" "time" @@ -8,18 +9,18 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) -func (k8s *Kubectl) GetDeploy(ns, name string) (*v1.Deployment, error) { - deployment, err := k8s.client.AppsV1().Deployments(ns).Get(k8s.Stmt.Context, name, metav1.GetOptions{}) +func (k8s *Kubectl) GetDeploy(ctx context.Context, ns, name string) (*v1.Deployment, error) { + deployment, err := k8s.client.AppsV1().Deployments(ns).Get(ctx, name, metav1.GetOptions{}) return deployment, err } -func (k8s *Kubectl) CreateDeploy(deploy *v1.Deployment) (*v1.Deployment, error) { - deployment, err := k8s.client.AppsV1().Deployments(deploy.Namespace).Create(k8s.Stmt.Context, deploy, metav1.CreateOptions{}) +func (k8s *Kubectl) CreateDeploy(ctx context.Context, deploy *v1.Deployment) (*v1.Deployment, error) { + deployment, err := k8s.client.AppsV1().Deployments(deploy.Namespace).Create(ctx, deploy, metav1.CreateOptions{}) return deployment, err } -func (k8s *Kubectl) RestartDeploy(ns string, name string) (*v1.Deployment, error) { - deployment, err := k8s.GetDeploy(ns, name) +func (k8s *Kubectl) RestartDeploy(ctx context.Context, ns string, name string) (*v1.Deployment, error) { + deployment, err := k8s.GetDeploy(ctx, ns, name) if err != nil { return nil, err } @@ -30,14 +31,14 @@ func (k8s *Kubectl) RestartDeploy(ns string, name string) (*v1.Deployment, error deployment.Spec.Template.Annotations["kubectl.kubernetes.io/restartedAt"] = time.Now().Format(time.RFC3339) // 更新 Deployment - updatedDeployment, err := k8s.client.AppsV1().Deployments(deployment.Namespace).Update(k8s.Stmt.Context, deployment, metav1.UpdateOptions{}) + updatedDeployment, err := k8s.client.AppsV1().Deployments(deployment.Namespace).Update(ctx, deployment, metav1.UpdateOptions{}) if err != nil { return nil, err } return updatedDeployment, nil } -func (k8s *Kubectl) UpdateDeployImageTag(ns string, name string, containerName string, tag string) (*v1.Deployment, error) { - deploy, err := k8s.GetDeploy(ns, name) +func (k8s *Kubectl) UpdateDeployImageTag(ctx context.Context, ns string, name string, containerName string, tag string) (*v1.Deployment, error) { + deploy, err := k8s.GetDeploy(ctx, ns, name) if err != nil { return nil, err } @@ -49,7 +50,7 @@ func (k8s *Kubectl) UpdateDeployImageTag(ns string, name string, containerName s c.Image = replaceImageTag(c.Image, tag) } } - deployment, err := k8s.client.AppsV1().Deployments(deploy.Namespace).Update(k8s.Stmt.Context, deploy, metav1.UpdateOptions{}) + deployment, err := k8s.client.AppsV1().Deployments(deploy.Namespace).Update(ctx, deploy, metav1.UpdateOptions{}) return deployment, err } diff --git a/internal/kubectl/dynamic.go b/internal/kubectl/dynamic.go index d698a44..e615ec0 100644 --- a/internal/kubectl/dynamic.go +++ b/internal/kubectl/dynamic.go @@ -1,6 +1,7 @@ package kubectl import ( + "context" "fmt" "sort" "strings" @@ -27,7 +28,7 @@ func WithFieldSelector(fieldSelector string) ListOption { } } -func (k8s *Kubectl) ListResources(kind string, ns string, opts ...ListOption) ([]unstructured.Unstructured, error) { +func (k8s *Kubectl) ListResources(ctx context.Context, kind string, ns string, opts ...ListOption) ([]unstructured.Unstructured, error) { gvr, namespaced := k8s.GetGVR(kind) if gvr.Empty() { return nil, fmt.Errorf("不支持的资源类型: %s", kind) @@ -46,16 +47,16 @@ func (k8s *Kubectl) ListResources(kind string, ns string, opts ...ListOption) ([ SetNamespaced(namespaced). SetType(Query). SetListOptions(&listOptions) - err = k8s.Callback().Query().Execute(k8s) + err = k8s.Callback().Query().Execute(ctx, k8s) if err != nil { return nil, err } var list *unstructured.UnstructuredList if namespaced { - list, err = k8s.dynamicClient.Resource(gvr).Namespace(ns).List(k8s.Stmt.Context, listOptions) + list, err = k8s.dynamicClient.Resource(gvr).Namespace(ns).List(ctx, listOptions) } else { - list, err = k8s.dynamicClient.Resource(gvr).List(k8s.Stmt.Context, listOptions) + list, err = k8s.dynamicClient.Resource(gvr).List(ctx, listOptions) } if err != nil { return nil, err @@ -69,7 +70,7 @@ func (k8s *Kubectl) ListResources(kind string, ns string, opts ...ListOption) ([ return sortByCreationTime(resources), nil } -func (k8s *Kubectl) GetResource(kind string, ns, name string) (*unstructured.Unstructured, error) { +func (k8s *Kubectl) GetResource(ctx context.Context, kind string, ns, name string) (*unstructured.Unstructured, error) { gvr, namespaced := k8s.GetGVR(kind) if gvr.Empty() { return nil, fmt.Errorf("不支持的资源类型: %s", kind) @@ -82,15 +83,15 @@ func (k8s *Kubectl) GetResource(kind string, ns, name string) (*unstructured.Uns SetKind(kind). SetNamespaced(namespaced). SetType(Query) - err = k8s.Callback().Query().Execute(k8s) + err = k8s.Callback().Query().Execute(ctx, k8s) if err != nil { return nil, err } if namespaced { - res, err = k8s.dynamicClient.Resource(gvr).Namespace(ns).Get(k8s.Stmt.Context, name, metav1.GetOptions{}) + res, err = k8s.dynamicClient.Resource(gvr).Namespace(ns).Get(ctx, name, metav1.GetOptions{}) } else { - res, err = k8s.dynamicClient.Resource(gvr).Get(k8s.Stmt.Context, name, metav1.GetOptions{}) + res, err = k8s.dynamicClient.Resource(gvr).Get(ctx, name, metav1.GetOptions{}) } if err != nil { return nil, err @@ -99,7 +100,7 @@ func (k8s *Kubectl) GetResource(kind string, ns, name string) (*unstructured.Uns removeManagedFields(res) return res, nil } -func (k8s *Kubectl) CreateResource(kind string, ns string, resource *unstructured.Unstructured) (*unstructured.Unstructured, error) { +func (k8s *Kubectl) CreateResource(ctx context.Context, kind string, ns string, resource *unstructured.Unstructured) (*unstructured.Unstructured, error) { gvr, namespaced := k8s.GetGVR(kind) if gvr.Empty() { return nil, fmt.Errorf("不支持的资源类型: %s", kind) @@ -112,14 +113,14 @@ func (k8s *Kubectl) CreateResource(kind string, ns string, resource *unstructure SetKind(kind). SetNamespaced(namespaced). SetType(Create) - err = k8s.Callback().Create().Execute(k8s) + err = k8s.Callback().Create().Execute(ctx, k8s) if err != nil { return nil, err } if namespaced { - createdResource, err = k8s.dynamicClient.Resource(gvr).Namespace(ns).Create(k8s.Stmt.Context, resource, metav1.CreateOptions{}) + createdResource, err = k8s.dynamicClient.Resource(gvr).Namespace(ns).Create(ctx, resource, metav1.CreateOptions{}) } else { - createdResource, err = k8s.dynamicClient.Resource(gvr).Create(k8s.Stmt.Context, resource, metav1.CreateOptions{}) + createdResource, err = k8s.dynamicClient.Resource(gvr).Create(ctx, resource, metav1.CreateOptions{}) } if err != nil { return nil, err @@ -129,7 +130,7 @@ func (k8s *Kubectl) CreateResource(kind string, ns string, resource *unstructure return createdResource, nil } -func (k8s *Kubectl) UpdateResource(kind string, ns string, resource *unstructured.Unstructured) (*unstructured.Unstructured, error) { +func (k8s *Kubectl) UpdateResource(ctx context.Context, kind string, ns string, resource *unstructured.Unstructured) (*unstructured.Unstructured, error) { gvr, namespaced := k8s.GetGVR(kind) if gvr.Empty() { return nil, fmt.Errorf("不支持的资源类型: %s", kind) @@ -142,14 +143,14 @@ func (k8s *Kubectl) UpdateResource(kind string, ns string, resource *unstructure SetKind(kind). SetNamespaced(namespaced). SetType(Update) - err = k8s.Callback().Update().Execute(k8s) + err = k8s.Callback().Update().Execute(ctx, k8s) if err != nil { return nil, err } if namespaced { - updatedResource, err = k8s.dynamicClient.Resource(gvr).Namespace(ns).Update(k8s.Stmt.Context, resource, metav1.UpdateOptions{}) + updatedResource, err = k8s.dynamicClient.Resource(gvr).Namespace(ns).Update(ctx, resource, metav1.UpdateOptions{}) } else { - updatedResource, err = k8s.dynamicClient.Resource(gvr).Update(k8s.Stmt.Context, resource, metav1.UpdateOptions{}) + updatedResource, err = k8s.dynamicClient.Resource(gvr).Update(ctx, resource, metav1.UpdateOptions{}) } if err != nil { @@ -159,7 +160,7 @@ func (k8s *Kubectl) UpdateResource(kind string, ns string, resource *unstructure return updatedResource, nil } -func (k8s *Kubectl) DeleteResource(kind string, ns, name string) error { +func (k8s *Kubectl) DeleteResource(ctx context.Context, kind string, ns, name string) error { gvr, namespaced := k8s.GetGVR(kind) if gvr.Empty() { return fmt.Errorf("不支持的资源类型: %s", kind) @@ -172,19 +173,19 @@ func (k8s *Kubectl) DeleteResource(kind string, ns, name string) error { SetKind(kind). SetNamespaced(namespaced). SetType(Delete) - err = k8s.Callback().Delete().Execute(k8s) + err = k8s.Callback().Delete().Execute(ctx, k8s) if err != nil { return err } if namespaced { - return k8s.dynamicClient.Resource(gvr).Namespace(ns).Delete(k8s.Stmt.Context, name, metav1.DeleteOptions{}) + return k8s.dynamicClient.Resource(gvr).Namespace(ns).Delete(ctx, name, metav1.DeleteOptions{}) } else { - return k8s.dynamicClient.Resource(gvr).Delete(k8s.Stmt.Context, name, metav1.DeleteOptions{}) + return k8s.dynamicClient.Resource(gvr).Delete(ctx, name, metav1.DeleteOptions{}) } } -func (k8s *Kubectl) PatchResource(kind string, ns, name string, patchType types.PatchType, patchData []byte) (*unstructured.Unstructured, error) { +func (k8s *Kubectl) PatchResource(ctx context.Context, kind string, ns, name string, patchType types.PatchType, patchData []byte) (*unstructured.Unstructured, error) { gvr, namespaced := k8s.GetGVR(kind) if gvr.Empty() { return nil, fmt.Errorf("不支持的资源类型: %s", kind) @@ -197,15 +198,15 @@ func (k8s *Kubectl) PatchResource(kind string, ns, name string, patchType types. SetKind(kind). SetNamespaced(namespaced). SetType(Patch) - err = k8s.Callback().Update().Execute(k8s) + err = k8s.Callback().Update().Execute(ctx, k8s) if err != nil { return nil, err } if namespaced { - obj, err = k8s.dynamicClient.Resource(gvr).Namespace(ns).Patch(k8s.Stmt.Context, name, patchType, patchData, metav1.PatchOptions{}) + obj, err = k8s.dynamicClient.Resource(gvr).Namespace(ns).Patch(ctx, name, patchType, patchData, metav1.PatchOptions{}) } else { - obj, err = k8s.dynamicClient.Resource(gvr).Patch(k8s.Stmt.Context, name, patchType, patchData, metav1.PatchOptions{}) + obj, err = k8s.dynamicClient.Resource(gvr).Patch(ctx, name, patchType, patchData, metav1.PatchOptions{}) } if err != nil { return nil, err diff --git a/internal/kubectl/dynamic_crd.go b/internal/kubectl/dynamic_crd.go index eddbfc0..615b806 100644 --- a/internal/kubectl/dynamic_crd.go +++ b/internal/kubectl/dynamic_crd.go @@ -1,13 +1,14 @@ package kubectl import ( + "context" "fmt" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime/schema" ) -func (k8s *Kubectl) FetchCRD(crd *unstructured.Unstructured, ns, name string) (*unstructured.Unstructured, error) { +func (k8s *Kubectl) FetchCRD(ctx context.Context, crd *unstructured.Unstructured, ns, name string) (*unstructured.Unstructured, error) { gvr := k8s.getGRVFromCRD(crd) // 检查CRD是否是Namespaced isNamespaced := crd.Object["spec"].(map[string]interface{})["scope"].(string) == "Namespaced" @@ -15,9 +16,9 @@ func (k8s *Kubectl) FetchCRD(crd *unstructured.Unstructured, ns, name string) (* if ns == "" && isNamespaced { ns = "default" // 默认命名空间 } - return k8s.GetResourceDynamic(gvr, isNamespaced, ns, name) + return k8s.GetResourceDynamic(ctx, gvr, isNamespaced, ns, name) } -func (k8s *Kubectl) RemoveCRD(crd *unstructured.Unstructured, ns, name string) error { +func (k8s *Kubectl) RemoveCRD(ctx context.Context, crd *unstructured.Unstructured, ns, name string) error { gvr := k8s.getGRVFromCRD(crd) // 检查CRD是否是Namespaced isNamespaced := crd.Object["spec"].(map[string]interface{})["scope"].(string) == "Namespaced" @@ -25,9 +26,9 @@ func (k8s *Kubectl) RemoveCRD(crd *unstructured.Unstructured, ns, name string) e if ns == "" && isNamespaced { ns = "default" // 默认命名空间 } - return k8s.RemoveResourceDynamic(gvr, isNamespaced, ns, name) + return k8s.RemoveResourceDynamic(ctx, gvr, isNamespaced, ns, name) } -func (k8s *Kubectl) UpdateCRD(crd *unstructured.Unstructured, res *unstructured.Unstructured) (*unstructured.Unstructured, error) { +func (k8s *Kubectl) UpdateCRD(ctx context.Context, crd *unstructured.Unstructured, res *unstructured.Unstructured) (*unstructured.Unstructured, error) { gvr := k8s.getGRVFromCRD(crd) // 检查CRD是否是Namespaced isNamespaced := crd.Object["spec"].(map[string]interface{})["scope"].(string) == "Namespaced" @@ -35,9 +36,9 @@ func (k8s *Kubectl) UpdateCRD(crd *unstructured.Unstructured, res *unstructured. if res.GetNamespace() == "" && isNamespaced { res.SetNamespace("default") // 默认命名空间 } - return k8s.UpdateResourceDynamic(gvr, isNamespaced, res) + return k8s.UpdateResourceDynamic(ctx, gvr, isNamespaced, res) } -func (k8s *Kubectl) ListCRD(crd *unstructured.Unstructured, ns string) ([]unstructured.Unstructured, error) { +func (k8s *Kubectl) ListCRD(ctx context.Context, crd *unstructured.Unstructured, ns string) ([]unstructured.Unstructured, error) { gvr := k8s.getGRVFromCRD(crd) // 检查CRD是否是Namespaced isNamespaced := crd.Object["spec"].(map[string]interface{})["scope"].(string) == "Namespaced" @@ -45,11 +46,11 @@ func (k8s *Kubectl) ListCRD(crd *unstructured.Unstructured, ns string) ([]unstru if ns == "" && isNamespaced { ns = "default" // 默认命名空间 } - return k8s.ListResourcesDynamic(gvr, isNamespaced, ns) + return k8s.ListResourcesDynamic(ctx, gvr, isNamespaced, ns) } -func (k8s *Kubectl) GetCRD(kind string, group string) (*unstructured.Unstructured, error) { - crdList, err := k8s.ListResources("CustomResourceDefinition", "") +func (k8s *Kubectl) GetCRD(ctx context.Context, kind string, group string) (*unstructured.Unstructured, error) { + crdList, err := k8s.ListResources(ctx, "CustomResourceDefinition", "") if err != nil { return nil, err } @@ -87,7 +88,7 @@ func (k8s *Kubectl) getGRVFromCRD(crd *unstructured.Unstructured) schema.GroupVe } return gvr } -func (k8s *Kubectl) DeleteCRD(crd *unstructured.Unstructured, obj *unstructured.Unstructured) (result string) { +func (k8s *Kubectl) DeleteCRD(ctx context.Context, crd *unstructured.Unstructured, obj *unstructured.Unstructured) (result string) { gvr := k8s.getGRVFromCRD(crd) // 检查CRD是否是Namespaced isNamespaced := crd.Object["spec"].(map[string]interface{})["scope"].(string) == "Namespaced" @@ -98,7 +99,7 @@ func (k8s *Kubectl) DeleteCRD(crd *unstructured.Unstructured, obj *unstructured. ns = "default" // 默认命名空间 obj.SetNamespace(ns) } - err := k8s.RemoveResourceDynamic(gvr, isNamespaced, ns, name) + err := k8s.RemoveResourceDynamic(ctx, gvr, isNamespaced, ns, name) if err != nil { result = fmt.Sprintf("%s/%s deleted error:%v", obj.GetKind(), obj.GetName(), err) } else { @@ -106,7 +107,7 @@ func (k8s *Kubectl) DeleteCRD(crd *unstructured.Unstructured, obj *unstructured. } return result } -func (k8s *Kubectl) ApplyCRD(crd *unstructured.Unstructured, obj *unstructured.Unstructured) (result string) { +func (k8s *Kubectl) ApplyCRD(ctx context.Context, crd *unstructured.Unstructured, obj *unstructured.Unstructured) (result string) { gvr := k8s.getGRVFromCRD(crd) // 检查CRD是否是Namespaced isNamespaced := crd.Object["spec"].(map[string]interface{})["scope"].(string) == "Namespaced" @@ -118,11 +119,11 @@ func (k8s *Kubectl) ApplyCRD(crd *unstructured.Unstructured, obj *unstructured.U ns = "default" // 默认命名空间 obj.SetNamespace(ns) } - exist, err := k8s.GetResourceDynamic(gvr, isNamespaced, ns, name) + exist, err := k8s.GetResourceDynamic(ctx, gvr, isNamespaced, ns, name) if err == nil && exist != nil && exist.GetName() != "" { // 已经存在资源,那么就更新 obj.SetResourceVersion(exist.GetResourceVersion()) - _, err := k8s.UpdateResourceDynamic(gvr, isNamespaced, obj) + _, err := k8s.UpdateResourceDynamic(ctx, gvr, isNamespaced, obj) if err != nil { result = fmt.Sprintf("更新CRD应用失败:%v", err.Error()) return result @@ -130,7 +131,7 @@ func (k8s *Kubectl) ApplyCRD(crd *unstructured.Unstructured, obj *unstructured.U result = fmt.Sprintf("%s/%s updated", kind, name) } else { // 不存在,那么就创建 - _, err := k8s.CreateResourceDynamic(gvr, isNamespaced, obj) + _, err := k8s.CreateResourceDynamic(ctx, gvr, isNamespaced, obj) if err != nil { result = fmt.Sprintf("创建CRD应用失败:%v %s/%s %v", err.Error(), gvr.GroupResource(), name, isNamespaced) return result diff --git a/internal/kubectl/dynamic_gvr.go b/internal/kubectl/dynamic_gvr.go index de7241a..20de3ac 100644 --- a/internal/kubectl/dynamic_gvr.go +++ b/internal/kubectl/dynamic_gvr.go @@ -1,6 +1,7 @@ package kubectl import ( + "context" "fmt" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -9,7 +10,7 @@ import ( "k8s.io/apimachinery/pkg/types" ) -func (k8s *Kubectl) ListResourcesDynamic(gvr schema.GroupVersionResource, isNamespaced bool, ns string, opts ...ListOption) ([]unstructured.Unstructured, error) { +func (k8s *Kubectl) ListResourcesDynamic(ctx context.Context, gvr schema.GroupVersionResource, isNamespaced bool, ns string, opts ...ListOption) ([]unstructured.Unstructured, error) { if gvr.Empty() { return nil, fmt.Errorf("GroupVersionResource is empty") } @@ -21,9 +22,9 @@ func (k8s *Kubectl) ListResourcesDynamic(gvr schema.GroupVersionResource, isName var list *unstructured.UnstructuredList var err error if isNamespaced { - list, err = k8s.dynamicClient.Resource(gvr).Namespace(ns).List(k8s.Stmt.Context, listOptions) + list, err = k8s.dynamicClient.Resource(gvr).Namespace(ns).List(ctx, listOptions) } else { - list, err = k8s.dynamicClient.Resource(gvr).List(k8s.Stmt.Context, listOptions) + list, err = k8s.dynamicClient.Resource(gvr).List(ctx, listOptions) } if err != nil { return nil, err @@ -37,16 +38,16 @@ func (k8s *Kubectl) ListResourcesDynamic(gvr schema.GroupVersionResource, isName return sortByCreationTime(resources), nil } -func (k8s *Kubectl) GetResourceDynamic(gvr schema.GroupVersionResource, isNamespaced bool, ns, name string) (*unstructured.Unstructured, error) { +func (k8s *Kubectl) GetResourceDynamic(ctx context.Context, gvr schema.GroupVersionResource, isNamespaced bool, ns, name string) (*unstructured.Unstructured, error) { if gvr.Empty() { return nil, fmt.Errorf("GroupVersionResource is empty") } var obj *unstructured.Unstructured var err error if isNamespaced { - obj, err = k8s.dynamicClient.Resource(gvr).Namespace(ns).Get(k8s.Stmt.Context, name, metav1.GetOptions{}) + obj, err = k8s.dynamicClient.Resource(gvr).Namespace(ns).Get(ctx, name, metav1.GetOptions{}) } else { - obj, err = k8s.dynamicClient.Resource(gvr).Get(k8s.Stmt.Context, name, metav1.GetOptions{}) + obj, err = k8s.dynamicClient.Resource(gvr).Get(ctx, name, metav1.GetOptions{}) } if err != nil { return nil, err @@ -55,16 +56,16 @@ func (k8s *Kubectl) GetResourceDynamic(gvr schema.GroupVersionResource, isNamesp removeManagedFields(obj) return obj, nil } -func (k8s *Kubectl) CreateResourceDynamic(gvr schema.GroupVersionResource, isNamespaced bool, resource *unstructured.Unstructured) (*unstructured.Unstructured, error) { +func (k8s *Kubectl) CreateResourceDynamic(ctx context.Context, gvr schema.GroupVersionResource, isNamespaced bool, resource *unstructured.Unstructured) (*unstructured.Unstructured, error) { if gvr.Empty() { return nil, fmt.Errorf("GroupVersionResource is empty") } var createdResource *unstructured.Unstructured var err error if isNamespaced { - createdResource, err = k8s.dynamicClient.Resource(gvr).Namespace(resource.GetNamespace()).Create(k8s.Stmt.Context, resource, metav1.CreateOptions{}) + createdResource, err = k8s.dynamicClient.Resource(gvr).Namespace(resource.GetNamespace()).Create(ctx, resource, metav1.CreateOptions{}) } else { - createdResource, err = k8s.dynamicClient.Resource(gvr).Create(k8s.Stmt.Context, resource, metav1.CreateOptions{}) + createdResource, err = k8s.dynamicClient.Resource(gvr).Create(ctx, resource, metav1.CreateOptions{}) } if err != nil { return nil, err @@ -74,27 +75,27 @@ func (k8s *Kubectl) CreateResourceDynamic(gvr schema.GroupVersionResource, isNam return createdResource, nil } -func (k8s *Kubectl) RemoveResourceDynamic(gvr schema.GroupVersionResource, isNamespaced bool, ns, name string) error { +func (k8s *Kubectl) RemoveResourceDynamic(ctx context.Context, gvr schema.GroupVersionResource, isNamespaced bool, ns, name string) error { if gvr.Empty() { return fmt.Errorf("GroupVersionResource is empty") } if isNamespaced { - return k8s.dynamicClient.Resource(gvr).Namespace(ns).Delete(k8s.Stmt.Context, name, metav1.DeleteOptions{}) + return k8s.dynamicClient.Resource(gvr).Namespace(ns).Delete(ctx, name, metav1.DeleteOptions{}) } else { - return k8s.dynamicClient.Resource(gvr).Delete(k8s.Stmt.Context, name, metav1.DeleteOptions{}) + return k8s.dynamicClient.Resource(gvr).Delete(ctx, name, metav1.DeleteOptions{}) } } -func (k8s *Kubectl) PatchResourceDynamic(gvr schema.GroupVersionResource, isNamespaced bool, ns, name string, patchType types.PatchType, patchData []byte) (*unstructured.Unstructured, error) { +func (k8s *Kubectl) PatchResourceDynamic(ctx context.Context, gvr schema.GroupVersionResource, isNamespaced bool, ns, name string, patchType types.PatchType, patchData []byte) (*unstructured.Unstructured, error) { if gvr.Empty() { return nil, fmt.Errorf("GroupVersionResource is empty") } var obj *unstructured.Unstructured var err error if isNamespaced { - obj, err = k8s.dynamicClient.Resource(gvr).Namespace(ns).Patch(k8s.Stmt.Context, name, patchType, patchData, metav1.PatchOptions{}) + obj, err = k8s.dynamicClient.Resource(gvr).Namespace(ns).Patch(ctx, name, patchType, patchData, metav1.PatchOptions{}) } else { - obj, err = k8s.dynamicClient.Resource(gvr).Patch(k8s.Stmt.Context, name, patchType, patchData, metav1.PatchOptions{}) + obj, err = k8s.dynamicClient.Resource(gvr).Patch(ctx, name, patchType, patchData, metav1.PatchOptions{}) } if err != nil { return nil, err @@ -103,17 +104,17 @@ func (k8s *Kubectl) PatchResourceDynamic(gvr schema.GroupVersionResource, isName removeManagedFields(obj) return obj, nil } -func (k8s *Kubectl) UpdateResourceDynamic(gvr schema.GroupVersionResource, isNamespaced bool, resource *unstructured.Unstructured) (*unstructured.Unstructured, error) { +func (k8s *Kubectl) UpdateResourceDynamic(ctx context.Context, gvr schema.GroupVersionResource, isNamespaced bool, resource *unstructured.Unstructured) (*unstructured.Unstructured, error) { if gvr.Empty() { return nil, fmt.Errorf("GroupVersionResource is empty") } var updatedResource *unstructured.Unstructured var err error if isNamespaced { - updatedResource, err = k8s.dynamicClient.Resource(gvr).Namespace(resource.GetNamespace()).Update(k8s.Stmt.Context, resource, metav1.UpdateOptions{}) + updatedResource, err = k8s.dynamicClient.Resource(gvr).Namespace(resource.GetNamespace()).Update(ctx, resource, metav1.UpdateOptions{}) } else { - updatedResource, err = k8s.dynamicClient.Resource(gvr).Update(k8s.Stmt.Context, resource, metav1.UpdateOptions{}) + updatedResource, err = k8s.dynamicClient.Resource(gvr).Update(ctx, resource, metav1.UpdateOptions{}) } if err != nil { diff --git a/internal/kubectl/image_pull_secret.go b/internal/kubectl/image_pull_secret.go index 914c0ba..02cbfdb 100644 --- a/internal/kubectl/image_pull_secret.go +++ b/internal/kubectl/image_pull_secret.go @@ -1,18 +1,19 @@ package kubectl import ( + "context" "strings" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) -func (k8s *Kubectl) CreateImagePullSecret(ns string, serviceAccount string, pullSecret string) error { +func (k8s *Kubectl) CreateImagePullSecret(ctx context.Context, ns string, serviceAccount string, pullSecret string) error { secretName := "pull-secret" // 先查查Secrets 有没有 - _, err := k8s.GetSecret(ns, secretName) + _, err := k8s.GetSecret(ctx, ns, secretName) if err != nil && strings.Contains(err.Error(), "not found") { secret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ @@ -25,14 +26,14 @@ func (k8s *Kubectl) CreateImagePullSecret(ns string, serviceAccount string, pull }, } // 创建 secret - _, err := k8s.CreateSecret(secret) + _, err := k8s.CreateSecret(ctx, secret) if err != nil { return err } } // 将 secret 绑定到 ServiceAccount - sa, err := k8s.GetServiceAccount(ns, serviceAccount) + sa, err := k8s.GetServiceAccount(ctx, ns, serviceAccount) if err != nil { return err } @@ -46,6 +47,6 @@ func (k8s *Kubectl) CreateImagePullSecret(ns string, serviceAccount string, pull // 绑定 imagePullSecret sa.ImagePullSecrets = append(sa.ImagePullSecrets, corev1.LocalObjectReference{Name: secretName}) - _, err = k8s.UpdateServiceAccount(sa) + _, err = k8s.UpdateServiceAccount(ctx, sa) return err } diff --git a/internal/kubectl/ingress.go b/internal/kubectl/ingress.go index 9531755..0013249 100644 --- a/internal/kubectl/ingress.go +++ b/internal/kubectl/ingress.go @@ -1,14 +1,15 @@ package kubectl import ( + "context" "sort" v1 "k8s.io/api/networking/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) -func (k8s *Kubectl) ListIngress(ns string) ([]v1.Ingress, error) { - list, err := k8s.client.NetworkingV1().Ingresses(ns).List(k8s.Stmt.Context, metav1.ListOptions{}) +func (k8s *Kubectl) ListIngress(ctx context.Context, ns string) ([]v1.Ingress, error) { + list, err := k8s.client.NetworkingV1().Ingresses(ns).List(ctx, metav1.ListOptions{}) if err == nil && list != nil && list.Items != nil && len(list.Items) > 0 { // 按创建时间倒序排序 Pods 列表 sort.Slice(list.Items, func(i, j int) bool { @@ -19,15 +20,15 @@ func (k8s *Kubectl) ListIngress(ns string) ([]v1.Ingress, error) { return nil, err } -func (k8s *Kubectl) GetIngress(ns, name string) (*v1.Ingress, error) { - Ingress, err := k8s.client.NetworkingV1().Ingresses(ns).Get(k8s.Stmt.Context, name, metav1.GetOptions{}) +func (k8s *Kubectl) GetIngress(ctx context.Context, ns, name string) (*v1.Ingress, error) { + Ingress, err := k8s.client.NetworkingV1().Ingresses(ns).Get(ctx, name, metav1.GetOptions{}) return Ingress, err } -func (k8s *Kubectl) RemoveIngress(ns, name string) error { - err := k8s.client.NetworkingV1().Ingresses(ns).Delete(k8s.Stmt.Context, name, metav1.DeleteOptions{}) +func (k8s *Kubectl) RemoveIngress(ctx context.Context, ns, name string) error { + err := k8s.client.NetworkingV1().Ingresses(ns).Delete(ctx, name, metav1.DeleteOptions{}) return err } -func (k8s *Kubectl) CreateIngress(Ingress *v1.Ingress) (*v1.Ingress, error) { - Ingress, err := k8s.client.NetworkingV1().Ingresses(Ingress.Namespace).Create(k8s.Stmt.Context, Ingress, metav1.CreateOptions{}) +func (k8s *Kubectl) CreateIngress(ctx context.Context, Ingress *v1.Ingress) (*v1.Ingress, error) { + Ingress, err := k8s.client.NetworkingV1().Ingresses(Ingress.Namespace).Create(ctx, Ingress, metav1.CreateOptions{}) return Ingress, err } diff --git a/internal/kubectl/node.go b/internal/kubectl/node.go index eb67e2c..fb72d0e 100644 --- a/internal/kubectl/node.go +++ b/internal/kubectl/node.go @@ -1,14 +1,15 @@ package kubectl import ( + "context" "sort" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) -func (k8s *Kubectl) ListNode() ([]v1.Node, error) { - list, err := k8s.client.CoreV1().Nodes().List(k8s.Stmt.Context, metav1.ListOptions{}) +func (k8s *Kubectl) ListNode(ctx context.Context) ([]v1.Node, error) { + list, err := k8s.client.CoreV1().Nodes().List(ctx, metav1.ListOptions{}) if err == nil && list != nil && list.Items != nil && len(list.Items) > 0 { sort.Slice(list.Items, func(i, j int) bool { return list.Items[i].CreationTimestamp.Time.After(list.Items[j].CreationTimestamp.Time) @@ -18,7 +19,7 @@ func (k8s *Kubectl) ListNode() ([]v1.Node, error) { return nil, err } -func (k8s *Kubectl) GetNode(name string) (*v1.Node, error) { - node, err := k8s.client.CoreV1().Nodes().Get(k8s.Stmt.Context, name, metav1.GetOptions{}) +func (k8s *Kubectl) GetNode(ctx context.Context, name string) (*v1.Node, error) { + node, err := k8s.client.CoreV1().Nodes().Get(ctx, name, metav1.GetOptions{}) return node, err } diff --git a/internal/kubectl/ns.go b/internal/kubectl/ns.go index 88afb08..86456f5 100644 --- a/internal/kubectl/ns.go +++ b/internal/kubectl/ns.go @@ -1,14 +1,15 @@ package kubectl import ( + "context" "sort" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) -func (k8s *Kubectl) ListNamespace() ([]v1.Namespace, error) { - list, err := k8s.client.CoreV1().Namespaces().List(k8s.Stmt.Context, metav1.ListOptions{}) +func (k8s *Kubectl) ListNamespace(ctx context.Context) ([]v1.Namespace, error) { + list, err := k8s.client.CoreV1().Namespaces().List(ctx, metav1.ListOptions{}) if err == nil && list != nil && list.Items != nil && len(list.Items) > 0 { // 按创建时间倒序排序 Pods 列表 sort.Slice(list.Items, func(i, j int) bool { @@ -19,16 +20,16 @@ func (k8s *Kubectl) ListNamespace() ([]v1.Namespace, error) { return nil, err } -func (k8s *Kubectl) GetNamespace(name string) (*v1.Namespace, error) { - Namespace, err := k8s.client.CoreV1().Namespaces().Get(k8s.Stmt.Context, name, metav1.GetOptions{}) +func (k8s *Kubectl) GetNamespace(ctx context.Context, name string) (*v1.Namespace, error) { + Namespace, err := k8s.client.CoreV1().Namespaces().Get(ctx, name, metav1.GetOptions{}) return Namespace, err } -func (k8s *Kubectl) RemoveNamespace(name string) error { - err := k8s.client.CoreV1().Namespaces().Delete(k8s.Stmt.Context, name, metav1.DeleteOptions{}) +func (k8s *Kubectl) RemoveNamespace(ctx context.Context, name string) error { + err := k8s.client.CoreV1().Namespaces().Delete(ctx, name, metav1.DeleteOptions{}) return err } -func (k8s *Kubectl) CreateNamespace(ns *v1.Namespace) (*v1.Namespace, error) { - ns, err := k8s.client.CoreV1().Namespaces().Create(k8s.Stmt.Context, ns, metav1.CreateOptions{}) +func (k8s *Kubectl) CreateNamespace(ctx context.Context, ns *v1.Namespace) (*v1.Namespace, error) { + ns, err := k8s.client.CoreV1().Namespaces().Create(ctx, ns, metav1.CreateOptions{}) return ns, err } diff --git a/internal/kubectl/pod.go b/internal/kubectl/pod.go index 30978f4..467e9c8 100644 --- a/internal/kubectl/pod.go +++ b/internal/kubectl/pod.go @@ -1,6 +1,7 @@ package kubectl import ( + "context" "io" "sort" @@ -8,8 +9,8 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) -func (k8s *Kubectl) ListPod(ns string) ([]v1.Pod, error) { - list, err := k8s.client.CoreV1().Pods(ns).List(k8s.Stmt.Context, metav1.ListOptions{}) +func (k8s *Kubectl) ListPod(ctx context.Context, ns string) ([]v1.Pod, error) { + list, err := k8s.client.CoreV1().Pods(ns).List(ctx, metav1.ListOptions{}) if err == nil && list != nil && list.Items != nil && len(list.Items) > 0 { // 按创建时间倒序排序 Pods 列表 sort.Slice(list.Items, func(i, j int) bool { @@ -20,12 +21,12 @@ func (k8s *Kubectl) ListPod(ns string) ([]v1.Pod, error) { return nil, err } -func (k8s *Kubectl) GetPod(ns, name string) (*v1.Pod, error) { - pod, err := k8s.client.CoreV1().Pods(ns).Get(k8s.Stmt.Context, name, metav1.GetOptions{}) +func (k8s *Kubectl) GetPod(ctx context.Context, ns, name string) (*v1.Pod, error) { + pod, err := k8s.client.CoreV1().Pods(ns).Get(ctx, name, metav1.GetOptions{}) return pod, err } -func (k8s *Kubectl) StreamPodLogs(ns, name string, logOptions *v1.PodLogOptions) (io.ReadCloser, error) { +func (k8s *Kubectl) StreamPodLogs(ctx context.Context, ns, name string, logOptions *v1.PodLogOptions) (io.ReadCloser, error) { // 检查logOptions // at most one of `sinceTime` or `sinceSeconds` may be specified @@ -41,14 +42,14 @@ func (k8s *Kubectl) StreamPodLogs(ns, name string, logOptions *v1.PodLogOptions) // 获取 Pod 日志 podLogs := k8s.client.CoreV1().Pods(ns).GetLogs(name, logOptions) - logStream, err := podLogs.Stream(k8s.Stmt.Context) + logStream, err := podLogs.Stream(ctx) return logStream, err } // ListPodByLabelSelector key1=value1,key2=value2 -func (k8s *Kubectl) ListPodByLabelSelector(ns, selector string) ([]v1.Pod, error) { - list, err := k8s.client.CoreV1().Pods(ns).List(k8s.Stmt.Context, metav1.ListOptions{LabelSelector: selector}) +func (k8s *Kubectl) ListPodByLabelSelector(ctx context.Context, ns, selector string) ([]v1.Pod, error) { + list, err := k8s.client.CoreV1().Pods(ns).List(ctx, metav1.ListOptions{LabelSelector: selector}) if err == nil && list != nil && list.Items != nil && len(list.Items) > 0 { sort.Slice(list.Items, func(i, j int) bool { return list.Items[i].CreationTimestamp.Time.After(list.Items[j].CreationTimestamp.Time) diff --git a/internal/kubectl/pvc.go b/internal/kubectl/pvc.go index eec6a7b..ea207aa 100644 --- a/internal/kubectl/pvc.go +++ b/internal/kubectl/pvc.go @@ -1,14 +1,15 @@ package kubectl import ( + "context" "sort" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) -func (k8s *Kubectl) ListPVC(ns string) ([]v1.PersistentVolumeClaim, error) { - list, err := k8s.client.CoreV1().PersistentVolumeClaims(ns).List(k8s.Stmt.Context, metav1.ListOptions{}) +func (k8s *Kubectl) ListPVC(ctx context.Context, ns string) ([]v1.PersistentVolumeClaim, error) { + list, err := k8s.client.CoreV1().PersistentVolumeClaims(ns).List(ctx, metav1.ListOptions{}) if err == nil && list != nil && list.Items != nil && len(list.Items) > 0 { // 按创建时间倒序排序 Pods 列表 sort.Slice(list.Items, func(i, j int) bool { @@ -19,12 +20,12 @@ func (k8s *Kubectl) ListPVC(ns string) ([]v1.PersistentVolumeClaim, error) { return nil, err } -func (k8s *Kubectl) GetPVC(ns, name string) (*v1.PersistentVolumeClaim, error) { - pvc, err := k8s.client.CoreV1().PersistentVolumeClaims(ns).Get(k8s.Stmt.Context, name, metav1.GetOptions{}) +func (k8s *Kubectl) GetPVC(ctx context.Context, ns, name string) (*v1.PersistentVolumeClaim, error) { + pvc, err := k8s.client.CoreV1().PersistentVolumeClaims(ns).Get(ctx, name, metav1.GetOptions{}) return pvc, err } -func (k8s *Kubectl) CreatePVC(pvc *v1.PersistentVolumeClaim) (*v1.PersistentVolumeClaim, error) { - pvc, err := k8s.client.CoreV1().PersistentVolumeClaims(pvc.Namespace).Create(k8s.Stmt.Context, pvc, metav1.CreateOptions{}) +func (k8s *Kubectl) CreatePVC(ctx context.Context, pvc *v1.PersistentVolumeClaim) (*v1.PersistentVolumeClaim, error) { + pvc, err := k8s.client.CoreV1().PersistentVolumeClaims(pvc.Namespace).Create(ctx, pvc, metav1.CreateOptions{}) return pvc, err } diff --git a/internal/kubectl/secret.go b/internal/kubectl/secret.go index 7c53e6f..87f626c 100644 --- a/internal/kubectl/secret.go +++ b/internal/kubectl/secret.go @@ -1,14 +1,15 @@ package kubectl import ( + "context" "sort" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) -func (k8s *Kubectl) ListSecret(ns string) ([]v1.Secret, error) { - list, err := k8s.client.CoreV1().Secrets(ns).List(k8s.Stmt.Context, metav1.ListOptions{}) +func (k8s *Kubectl) ListSecret(ctx context.Context, ns string) ([]v1.Secret, error) { + list, err := k8s.client.CoreV1().Secrets(ns).List(ctx, metav1.ListOptions{}) if err == nil && list != nil && list.Items != nil && len(list.Items) > 0 { // 按创建时间倒序排序 Pods 列表 sort.Slice(list.Items, func(i, j int) bool { @@ -19,11 +20,11 @@ func (k8s *Kubectl) ListSecret(ns string) ([]v1.Secret, error) { return nil, err } -func (k8s *Kubectl) GetSecret(ns, name string) (*v1.Secret, error) { - Secret, err := k8s.client.CoreV1().Secrets(ns).Get(k8s.Stmt.Context, name, metav1.GetOptions{}) +func (k8s *Kubectl) GetSecret(ctx context.Context, ns, name string) (*v1.Secret, error) { + Secret, err := k8s.client.CoreV1().Secrets(ns).Get(ctx, name, metav1.GetOptions{}) return Secret, err } -func (k8s *Kubectl) CreateSecret(secret *v1.Secret) (*v1.Secret, error) { - secret, err := k8s.client.CoreV1().Secrets(secret.Namespace).Create(k8s.Stmt.Context, secret, metav1.CreateOptions{}) +func (k8s *Kubectl) CreateSecret(ctx context.Context, secret *v1.Secret) (*v1.Secret, error) { + secret, err := k8s.client.CoreV1().Secrets(secret.Namespace).Create(ctx, secret, metav1.CreateOptions{}) return secret, err } diff --git a/internal/kubectl/service_account.go b/internal/kubectl/service_account.go index 350c988..6141335 100644 --- a/internal/kubectl/service_account.go +++ b/internal/kubectl/service_account.go @@ -1,14 +1,15 @@ package kubectl import ( + "context" "sort" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) -func (k8s *Kubectl) ListServiceAccount(ns string) ([]v1.ServiceAccount, error) { - list, err := k8s.client.CoreV1().ServiceAccounts(ns).List(k8s.Stmt.Context, metav1.ListOptions{}) +func (k8s *Kubectl) ListServiceAccount(ctx context.Context, ns string) ([]v1.ServiceAccount, error) { + list, err := k8s.client.CoreV1().ServiceAccounts(ns).List(ctx, metav1.ListOptions{}) if err == nil && list != nil && list.Items != nil && len(list.Items) > 0 { // 按创建时间倒序排序 Pods 列表 sort.Slice(list.Items, func(i, j int) bool { @@ -19,20 +20,20 @@ func (k8s *Kubectl) ListServiceAccount(ns string) ([]v1.ServiceAccount, error) { return nil, err } -func (k8s *Kubectl) GetServiceAccount(ns, name string) (*v1.ServiceAccount, error) { - ServiceAccount, err := k8s.client.CoreV1().ServiceAccounts(ns).Get(k8s.Stmt.Context, name, metav1.GetOptions{}) +func (k8s *Kubectl) GetServiceAccount(ctx context.Context, ns, name string) (*v1.ServiceAccount, error) { + ServiceAccount, err := k8s.client.CoreV1().ServiceAccounts(ns).Get(ctx, name, metav1.GetOptions{}) return ServiceAccount, err } -func (k8s *Kubectl) RemoveServiceAccount(ns, name string) error { - err := k8s.client.CoreV1().ServiceAccounts(ns).Delete(k8s.Stmt.Context, name, metav1.DeleteOptions{}) +func (k8s *Kubectl) RemoveServiceAccount(ctx context.Context, ns, name string) error { + err := k8s.client.CoreV1().ServiceAccounts(ns).Delete(ctx, name, metav1.DeleteOptions{}) return err } -func (k8s *Kubectl) CreateServiceAccount(sa *v1.ServiceAccount) (*v1.ServiceAccount, error) { - sa, err := k8s.client.CoreV1().ServiceAccounts(sa.Namespace).Create(k8s.Stmt.Context, sa, metav1.CreateOptions{}) +func (k8s *Kubectl) CreateServiceAccount(ctx context.Context, sa *v1.ServiceAccount) (*v1.ServiceAccount, error) { + sa, err := k8s.client.CoreV1().ServiceAccounts(sa.Namespace).Create(ctx, sa, metav1.CreateOptions{}) return sa, err } -func (k8s *Kubectl) UpdateServiceAccount(sa *v1.ServiceAccount) (*v1.ServiceAccount, error) { - sa, err := k8s.client.CoreV1().ServiceAccounts(sa.Namespace).Update(k8s.Stmt.Context, sa, metav1.UpdateOptions{}) +func (k8s *Kubectl) UpdateServiceAccount(ctx context.Context, sa *v1.ServiceAccount) (*v1.ServiceAccount, error) { + sa, err := k8s.client.CoreV1().ServiceAccounts(sa.Namespace).Update(ctx, sa, metav1.UpdateOptions{}) return sa, err } diff --git a/internal/kubectl/statement.go b/internal/kubectl/statement.go index ad529c5..49bc5ca 100644 --- a/internal/kubectl/statement.go +++ b/internal/kubectl/statement.go @@ -1,8 +1,6 @@ package kubectl import ( - "context" - "github.com/weibaohui/k8m/internal/utils" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" @@ -32,7 +30,6 @@ type Statement struct { ListOptions *metav1.ListOptions Type StatementType // list get create update remove Resource string - Context context.Context } func (s *Statement) SetNamespace(ns string) *Statement { diff --git a/internal/kubectl/svc.go b/internal/kubectl/svc.go index bc526a6..bf65a61 100644 --- a/internal/kubectl/svc.go +++ b/internal/kubectl/svc.go @@ -1,14 +1,15 @@ package kubectl import ( + "context" "sort" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) -func (k8s *Kubectl) ListService(ns string) ([]v1.Service, error) { - list, err := k8s.client.CoreV1().Services(ns).List(k8s.Stmt.Context, metav1.ListOptions{}) +func (k8s *Kubectl) ListService(ctx context.Context, ns string) ([]v1.Service, error) { + list, err := k8s.client.CoreV1().Services(ns).List(ctx, metav1.ListOptions{}) if err == nil && list != nil && list.Items != nil && len(list.Items) > 0 { // 按创建时间倒序排序 Pods 列表 sort.Slice(list.Items, func(i, j int) bool { @@ -19,15 +20,15 @@ func (k8s *Kubectl) ListService(ns string) ([]v1.Service, error) { return nil, err } -func (k8s *Kubectl) GetService(ns, name string) (*v1.Service, error) { - Service, err := k8s.client.CoreV1().Services(ns).Get(k8s.Stmt.Context, name, metav1.GetOptions{}) +func (k8s *Kubectl) GetService(ctx context.Context, ns, name string) (*v1.Service, error) { + Service, err := k8s.client.CoreV1().Services(ns).Get(ctx, name, metav1.GetOptions{}) return Service, err } -func (k8s *Kubectl) RemoveService(ns, name string) error { - err := k8s.client.CoreV1().Services(ns).Delete(k8s.Stmt.Context, name, metav1.DeleteOptions{}) +func (k8s *Kubectl) RemoveService(ctx context.Context, ns, name string) error { + err := k8s.client.CoreV1().Services(ns).Delete(ctx, name, metav1.DeleteOptions{}) return err } -func (k8s *Kubectl) CreateService(svc *v1.Service) (*v1.Service, error) { - svc, err := k8s.client.CoreV1().Services(svc.Namespace).Create(k8s.Stmt.Context, svc, metav1.CreateOptions{}) +func (k8s *Kubectl) CreateService(ctx context.Context, svc *v1.Service) (*v1.Service, error) { + svc, err := k8s.client.CoreV1().Services(svc.Namespace).Create(ctx, svc, metav1.CreateOptions{}) return svc, err } diff --git a/pkg/callback/cb.go b/pkg/callback/cb.go index 09eb449..bd85b20 100644 --- a/pkg/callback/cb.go +++ b/pkg/callback/cb.go @@ -1,6 +1,8 @@ package callback import ( + "context" + "github.com/weibaohui/k8m/internal/kubectl" "k8s.io/klog/v2" ) @@ -10,8 +12,9 @@ func RegisterCallback() { _ = queryCallback.Register("k8m:query", Query) } -func Query(k8s *kubectl.Kubectl) error { +func Query(ctx context.Context, k8s *kubectl.Kubectl) error { json := k8s.Stmt.String() - klog.V(2).Infof("k8s Query stmt json:\n%s\n", json) + u := ctx.Value("user") + klog.V(2).Infof("%s k8s Query stmt json:\n %s\n", u, json) return nil } diff --git a/pkg/controller/deploy/deploy.go b/pkg/controller/deploy/deploy.go index 924d469..9be9ee4 100644 --- a/pkg/controller/deploy/deploy.go +++ b/pkg/controller/deploy/deploy.go @@ -11,13 +11,15 @@ func UpdateImageTag(c *gin.Context) { var name = c.Param("name") var tag = c.Param("tag") var containerName = c.Param("container_name") - deploy, _ := kubectl.Init().UpdateDeployImageTag(ns, name, containerName, tag) + ctx := c.Request.Context() + deploy, _ := kubectl.Init().UpdateDeployImageTag(ctx, ns, name, containerName, tag) amis.WriteJsonData(c, deploy) } func Restart(c *gin.Context) { var ns = c.Param("ns") var name = c.Param("name") - deploy, _ := kubectl.Init().RestartDeploy(ns, name) + ctx := c.Request.Context() + deploy, _ := kubectl.Init().RestartDeploy(ctx, ns, name) amis.WriteJsonData(c, deploy) } diff --git a/pkg/controller/dynamic/dynamic.go b/pkg/controller/dynamic/dynamic.go index d3101b8..fcec2fc 100644 --- a/pkg/controller/dynamic/dynamic.go +++ b/pkg/controller/dynamic/dynamic.go @@ -14,16 +14,18 @@ func List(c *gin.Context) { ns := c.Param("ns") group := c.Param("group") kind := c.Param("kind") + ctx := context.WithValue(c, "user", "zhangsan") var list []unstructured.Unstructured var err error - builtIn := kubectl.Init().WithContext(context.TODO()).IsBuiltinResource(kind) + builtIn := kubectl.Init().IsBuiltinResource(kind) if builtIn { // 内置资源 - list, err = kubectl.Init().ListResources(kind, ns) + + list, err = kubectl.Init().ListResources(ctx, kind, ns) } else { // CRD 类型资源 - if crd, err := kubectl.Init().GetCRD(kind, group); err == nil { - list, err = kubectl.Init().ListCRD(crd, ns) + if crd, err := kubectl.Init().GetCRD(ctx, kind, group); err == nil { + list, err = kubectl.Init().ListCRD(ctx, crd, ns) } } @@ -34,21 +36,22 @@ func Fetch(c *gin.Context) { var name = c.Param("name") kind := c.Param("kind") group := c.Param("group") + ctx := c.Request.Context() var obj *unstructured.Unstructured var err error builtIn := kubectl.Init().IsBuiltinResource(kind) if !builtIn { // CRD 类型资源 - if crd, err := kubectl.Init().GetCRD(kind, group); err == nil { - obj, err = kubectl.Init().FetchCRD(crd, ns, name) + if crd, err := kubectl.Init().GetCRD(ctx, kind, group); err == nil { + obj, err = kubectl.Init().FetchCRD(ctx, crd, ns, name) if err != nil { amis.WriteJsonError(c, err) return } } } else { - obj, err = kubectl.Init().GetResource(kind, ns, name) + obj, err = kubectl.Init().GetResource(ctx, kind, ns, name) if err != nil { amis.WriteJsonError(c, err) return @@ -69,8 +72,9 @@ func Remove(c *gin.Context) { var name = c.Param("name") kind := c.Param("kind") group := c.Param("group") + ctx := c.Request.Context() - err := removeSingle(kind, group, ns, name) + err := removeSingle(ctx, kind, group, ns, name) if err != nil { amis.WriteJsonError(c, err) return @@ -78,19 +82,19 @@ func Remove(c *gin.Context) { amis.WriteJsonOK(c) } -func removeSingle(kind, group, ns, name string) error { +func removeSingle(ctx context.Context, kind, group, ns, name string) error { builtIn := kubectl.Init().IsBuiltinResource(kind) if !builtIn { // CRD 类型资源 - if crd, err := kubectl.Init().GetCRD(kind, group); err == nil { - err = kubectl.Init().RemoveCRD(crd, ns, name) + if crd, err := kubectl.Init().GetCRD(ctx, kind, group); err == nil { + err = kubectl.Init().RemoveCRD(ctx, crd, ns, name) if err != nil { return err } } } else { // 内置资源类型 - err := kubectl.Init().DeleteResource(kind, ns, name) + err := kubectl.Init().DeleteResource(ctx, kind, ns, name) if err != nil { return err } @@ -109,6 +113,7 @@ func BatchRemove(c *gin.Context) { var ns = c.Param("ns") kind := c.Param("kind") group := c.Param("group") + ctx := c.Request.Context() // 初始化结构体实例 var payload NamesPayload @@ -120,7 +125,7 @@ func BatchRemove(c *gin.Context) { } for _, name := range payload.Names { - _ = removeSingle(kind, group, ns, name) + _ = removeSingle(ctx, kind, group, ns, name) } amis.WriteJsonOK(c) } @@ -134,6 +139,7 @@ func Save(c *gin.Context) { var name = c.Param("name") kind := c.Param("kind") group := c.Param("group") + ctx := c.Request.Context() var req ApplyYAMLRequest if err := c.ShouldBindJSON(&req); err != nil { @@ -155,15 +161,15 @@ func Save(c *gin.Context) { builtIn := kubectl.Init().IsBuiltinResource(kind) if !builtIn { // CRD 类型资源 - if crd, err := kubectl.Init().GetCRD(kind, group); err == nil { - _, err = kubectl.Init().UpdateCRD(crd, &obj) + if crd, err := kubectl.Init().GetCRD(ctx, kind, group); err == nil { + _, err = kubectl.Init().UpdateCRD(ctx, crd, &obj) if err != nil { amis.WriteJsonError(c, err) return } } } else { - _, err := kubectl.Init().UpdateResource(kind, ns, &obj) + _, err := kubectl.Init().UpdateResource(ctx, kind, ns, &obj) if err != nil { amis.WriteJsonError(c, err) return @@ -176,13 +182,15 @@ func Save(c *gin.Context) { } func Apply(c *gin.Context) { + ctx := c.Request.Context() + var req ApplyYAMLRequest if err := c.ShouldBindJSON(&req); err != nil { amis.WriteJsonError(c, err) return } yamlStr := req.YAML - result := kubectl.Init().ApplyYAML(yamlStr) + result := kubectl.Init().ApplyYAML(ctx, yamlStr) amis.WriteJsonData(c, gin.H{ "result": result, }) @@ -190,13 +198,15 @@ func Apply(c *gin.Context) { } func Delete(c *gin.Context) { + ctx := c.Request.Context() + var req ApplyYAMLRequest if err := c.ShouldBindJSON(&req); err != nil { amis.WriteJsonError(c, err) return } yamlStr := req.YAML - result := kubectl.Init().DeleteYAML(yamlStr) + result := kubectl.Init().DeleteYAML(ctx, yamlStr) amis.WriteJsonData(c, gin.H{ "result": result, }) diff --git a/pkg/controller/ns/ns.go b/pkg/controller/ns/ns.go index a095fb0..0f9258c 100644 --- a/pkg/controller/ns/ns.go +++ b/pkg/controller/ns/ns.go @@ -7,7 +7,8 @@ import ( ) func OptionList(c *gin.Context) { - namespace, err := kubectl.Init().ListNamespace() + ctx := c.Request.Context() + namespace, err := kubectl.Init().ListNamespace(ctx) if err != nil { amis.WriteJsonError(c, err) } diff --git a/pkg/controller/pod/pod.go b/pkg/controller/pod/pod.go index 077f74a..30531c5 100644 --- a/pkg/controller/pod/pod.go +++ b/pkg/controller/pod/pod.go @@ -19,7 +19,9 @@ func StreamLogs(c *gin.Context) { StreamPodLogsBySelector(c, ns, containerName, kubectl.WithFieldSelector(selector)) } func StreamPodLogsBySelector(c *gin.Context, ns string, containerName string, opts ...kubectl.ListOption) { - pods, err := kubectl.Init().ListResources("Pod", ns, opts...) + ctx := c.Request.Context() + + pods, err := kubectl.Init().ListResources(ctx, "Pod", ns, opts...) if err != nil { amis.WriteJsonError(c, err) return @@ -35,7 +37,7 @@ func StreamPodLogsBySelector(c *gin.Context, ns string, containerName string, op amis.WriteJsonError(c, err) return } - stream, err := kubectl.Init().StreamPodLogs(ns, podName, logOpt) + stream, err := kubectl.Init().StreamPodLogs(ctx, ns, podName, logOpt) if err != nil { amis.WriteJsonError(c, err) @@ -52,7 +54,9 @@ func DownloadLogs(c *gin.Context) { DownloadPodLogsBySelector(c, ns, containerName, kubectl.WithFieldSelector(selector)) } func DownloadPodLogsBySelector(c *gin.Context, ns string, containerName string, opts ...kubectl.ListOption) { - pods, err := kubectl.Init().ListResources("Pod", ns, opts...) + ctx := c.Request.Context() + + pods, err := kubectl.Init().ListResources(ctx, "Pod", ns, opts...) if err != nil { amis.WriteJsonError(c, err) return @@ -70,7 +74,7 @@ func DownloadPodLogsBySelector(c *gin.Context, ns string, containerName string, } logOpt.Follow = false - stream, err := kubectl.Init().StreamPodLogs(ns, podName, logOpt) + stream, err := kubectl.Init().StreamPodLogs(ctx, ns, podName, logOpt) if err != nil { amis.WriteJsonError(c, err)