kuma

Форк
0
/
k8s_resource.go 
191 строка · 5.2 Кб
1
package cmd
2

3
import (
4
	"os"
5
	"path/filepath"
6
	"text/template"
7

8
	"github.com/spf13/cobra"
9

10
	"github.com/kumahq/kuma/tools/policy-gen/generator/pkg/parse"
11
	"github.com/kumahq/kuma/tools/policy-gen/generator/pkg/save"
12
)
13

14
func newK8sResource(rootArgs *args) *cobra.Command {
15
	cmd := &cobra.Command{
16
		Use:   "k8s-resource",
17
		Short: "Generate a k8s model resource for the policy",
18
		Long:  "Generate a k8s model resource for the policy.",
19
		RunE: func(cmd *cobra.Command, _ []string) error {
20
			policyName := filepath.Base(rootArgs.pluginDir)
21
			policyPath := filepath.Join(rootArgs.pluginDir, "api", rootArgs.version, policyName+".go")
22
			if _, err := os.Stat(policyPath); err != nil {
23
				return err
24
			}
25

26
			pconfig, err := parse.Policy(policyPath)
27
			if err != nil {
28
				return err
29
			}
30

31
			pconfig.GoModule = rootArgs.goModule
32

33
			k8sPath := filepath.Join(rootArgs.pluginDir, "k8s", rootArgs.version)
34
			if err := os.MkdirAll(k8sPath, 0o755); err != nil {
35
				return err
36
			}
37

38
			k8sTypesPath := filepath.Join(k8sPath, "zz_generated.types.go")
39
			if err := save.GoTemplate(customResourceTemplate, pconfig, k8sTypesPath); err != nil {
40
				return err
41
			}
42

43
			gvInfoPath := filepath.Join(k8sPath, "groupversion_info.go")
44
			if err := save.GoTemplate(groupVersionInfoTemplate, pconfig, gvInfoPath); err != nil {
45
				return err
46
			}
47

48
			return nil
49
		},
50
	}
51

52
	return cmd
53
}
54

55
// customResourceTemplate for creating a Kubernetes CRD to wrap a Kuma resource.
56
var customResourceTemplate = template.Must(template.New("custom-resource").Parse(`
57
// Generated by tools/policy-gen
58
// Run "make generate" to update this file.
59

60
{{ $tk := "` + "`" + `" }}
61

62
// nolint:whitespace
63
package {{.Package}}
64

65
import (
66
	"fmt"
67

68
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
69

70
	core_model "github.com/kumahq/kuma/pkg/core/resources/model"
71
	policy "{{.GoModule}}/pkg/plugins/policies/{{.NameLower}}/api/{{.Package}}"
72
	"github.com/kumahq/kuma/pkg/plugins/resources/k8s/native/pkg/model"
73
	{{- if not .SkipRegistration }}
74
	"github.com/kumahq/kuma/pkg/plugins/resources/k8s/native/pkg/registry"
75
	{{- end }}
76
	"github.com/kumahq/kuma/pkg/plugins/runtime/k8s/metadata"
77
)
78

79
// +kubebuilder:object:root=true
80
// +kubebuilder:resource:categories=kuma,scope=Namespaced
81
// +kubebuilder:printcolumn:name="TargetRef Kind",type="string",JSONPath=".spec.targetRef.kind"
82
// +kubebuilder:printcolumn:name="TargetRef Name",type="string",JSONPath=".spec.targetRef.name"
83
type {{.Name}} struct {
84
	metav1.TypeMeta   {{ $tk }}json:",inline"{{ $tk }}
85
	metav1.ObjectMeta {{ $tk }}json:"metadata,omitempty"{{ $tk }}
86

87
	// Spec is the specification of the Kuma {{ .Name }} resource.
88
    // +kubebuilder:validation:Optional
89
	Spec   *policy.{{.Name}} {{ $tk }}json:"spec,omitempty"{{ $tk }}
90
}
91

92
// +kubebuilder:object:root=true
93
// +kubebuilder:resource:scope=Namespaced
94
type {{.Name}}List struct {
95
	metav1.TypeMeta {{ $tk }}json:",inline"{{ $tk }}
96
	metav1.ListMeta {{ $tk }}json:"metadata,omitempty"{{ $tk }}
97
	Items           []{{.Name}} {{ $tk }}json:"items"{{ $tk }}
98
}
99

100
func (cb *{{.Name}}) GetObjectMeta() *metav1.ObjectMeta {
101
	return &cb.ObjectMeta
102
}
103

104
func (cb *{{.Name}}) SetObjectMeta(m *metav1.ObjectMeta) {
105
	cb.ObjectMeta = *m
106
}
107

108
func (cb *{{.Name}}) GetMesh() string {
109
	if mesh, ok := cb.ObjectMeta.Labels[metadata.KumaMeshLabel]; ok {
110
		return mesh
111
	} else {
112
		return core_model.DefaultMesh
113
	}
114
}
115

116
func (cb *{{.Name}}) SetMesh(mesh string) {
117
	if cb.ObjectMeta.Labels == nil {
118
		cb.ObjectMeta.Labels = map[string]string{}
119
	}
120
	cb.ObjectMeta.Labels[metadata.KumaMeshLabel] = mesh
121
}
122

123
func (cb *{{.Name}}) GetSpec() (core_model.ResourceSpec, error) {
124
	return cb.Spec, nil
125
}
126

127
func (cb *{{.Name}}) SetSpec(spec core_model.ResourceSpec) {
128
	if spec == nil {
129
		cb.Spec = nil
130
		return
131
	}
132

133
	if _, ok := spec.(*policy.{{.Name}}); !ok {
134
		panic(fmt.Sprintf("unexpected protobuf message type %T", spec))
135
	}
136

137
	cb.Spec = spec.(*policy.{{.Name}})
138
}
139

140
func (cb *{{.Name}}) Scope() model.Scope {
141
	return model.ScopeNamespace
142
}
143

144
func (l *{{.Name}}List) GetItems() []model.KubernetesObject {
145
	result := make([]model.KubernetesObject, len(l.Items))
146
	for i := range l.Items {
147
		result[i] = &l.Items[i]
148
	}
149
	return result
150
}
151

152
{{if not .SkipRegistration}}
153
func init() {
154
	SchemeBuilder.Register(&{{.Name}}{}, &{{.Name}}List{})
155
	registry.RegisterObjectType(&policy.{{.Name}}{}, &{{.Name}}{
156
		TypeMeta: metav1.TypeMeta{
157
			APIVersion: GroupVersion.String(),
158
			Kind:       "{{.Name}}",
159
		},
160
	})
161
	registry.RegisterListType(&policy.{{.Name}}{}, &{{.Name}}List{
162
		TypeMeta: metav1.TypeMeta{
163
			APIVersion: GroupVersion.String(),
164
			Kind:       "{{.Name}}List",
165
		},
166
	})
167
}
168
{{- end }} {{/* .SkipRegistration */}}
169
`))
170

171
var groupVersionInfoTemplate = template.Must(template.New("groupversion-info").Parse(`
172
// Package {{.Package}} contains API Schema definitions for the mesh {{.Package}} API group
173
// +groupName=kuma.io
174
package {{.Package}}
175

176
import (
177
	"k8s.io/apimachinery/pkg/runtime/schema"
178
	"sigs.k8s.io/controller-runtime/pkg/scheme"
179
)
180

181
var (
182
	// GroupVersion is group version used to register these objects
183
	GroupVersion = schema.GroupVersion{Group: "kuma.io", Version: "{{.Package}}"}
184

185
	// SchemeBuilder is used to add go types to the GroupVersionKind scheme
186
	SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion}
187

188
	// AddToScheme adds the types in this group-version to the given scheme.
189
	AddToScheme = SchemeBuilder.AddToScheme
190
)
191
`))
192

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.