0

我正在编写一个监听环境自定义资源的 Kubernetes 控制器。

pkg/apis/environment/v1alpha1/types.go有以下内容:

package v1alpha1

import (
    meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// +genclient
// +genclient:noStatus
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

// Environment describes an Environment resource
type Environment struct {
    meta_v1.TypeMeta   `json:",inline"`
    meta_v1.ObjectMeta `json:"metadata,omitempty"`
    Spec               EnvironmentSpec `json:"spec"`
}

// EnvironmentSpec contains the specs for an Environment resource
type EnvironmentSpec struct {
    Services []Service `json:"services"`
}

// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

// EnvironmentList is a list of Environment resources
type EnvironmentList struct {
    meta_v1.TypeMeta `json:",inline"`
    meta_v1.ListMeta `json:"metadata"`

    Items []Environment `json:"items"`
}

// Service describes a Service in the Environment Custom Resource
type Service struct {
    Code       string `json:"code"`
    Parameters struct {
        Foo map[string]string `json:"foo"`
        Bar int               `json:"bar"`
    } `json:"parameters"`
}

运行 k8s.io/code-generator/generate-groups.sh 脚本后,我得到了一个错误的pkg/apis/environment/v1alpha1/zz_generated.deepcopy.go文件。问题来自这个生成的方法:

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Service) DeepCopyInto(out *Service) {
    *out = *in
    in.Parameters.DeepCopyInto(&out.Parameters)
    return
}

尝试构建或运行此代码会给我以下错误

pkg/apis/environment/v1alpha1/zz_generated.deepcopy.go:113:15: in.Parameters.DeepCopyInto undefined (type struct { Foo map[string]string "json:\"foo\""; Bar int "json:\"bar\"" } has no field or method DeepCopyInto)

只要我在Parameters结构中包含的匿名结构中包含MapSlice ,就会遇到此错误。

解决方法

解决方法是创建一个包含映射的命名类型。例如,我像这样重构了Service结构:

// Service describes a Service in the Environment Custom Resource
type Service struct {
    Code       string `json:"code"`
    Parameters FooBar `json:"parameters"`
}

type FooBar struct {
    Foo map[string]string `json:"foo"`
    Bar int               `json:"bar"`
}

生成的func (in *Service) DeepCopyInto(out *Service)并没有改变,但创建了以下 2 个新方法:

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *FooBar) DeepCopyInto(out *FooBar) {
    *out = *in
    if in.Foo != nil {
        in, out := &in.Foo, &out.Foo
        *out = make(map[string]string, len(*in))
        for key, val := range *in {
            (*out)[key] = val
        }
    }
    return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new FooBar.
func (in *FooBar) DeepCopy() *FooBar {
    if in == nil {
        return nil
    }
    out := new(FooBar)
    in.DeepCopyInto(out)
    return out
}

现在,我在构建和运行代码时没有任何问题。

这种解决方法很痛苦,因为我真正的Service结构比这个例子大得多。

有没有办法通过代码生成器在匿名 func 中使用地图和切片?

4

0 回答 0