/
processor_manifest.go
377 lines (335 loc) · 10.4 KB
/
processor_manifest.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
// Copyright 2022 The kubegems.io Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package application
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"sort"
"strings"
"github.com/go-git/go-billy/v5"
"github.com/go-git/go-billy/v5/helper/chroot"
"github.com/go-git/go-billy/v5/util"
"github.com/opentracing/opentracing-go"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/utils/pointer"
"kubegems.io/kubegems/pkg/log"
"kubegems.io/kubegems/pkg/utils/git"
"sigs.k8s.io/kustomize/api/types"
"sigs.k8s.io/yaml"
)
const (
ReadmeFilename = "readme.md"
MetaFilename = ".meta"
)
type ManifestProcessor struct {
GitProvider git.Provider
}
func NewManifestProcessor(GitProvider *git.SimpleLocalProvider) (*ManifestProcessor, error) {
return &ManifestProcessor{GitProvider: GitProvider}, nil
}
func (p *ManifestProcessor) ContentFunc(ctx context.Context, ref PathRef, fun RepositoryFileSystemFunc) error {
return p.Func(ctx, ref,
FsFunc(fun),
)
}
func (h *ManifestProcessor) UpdateContentFunc(ctx context.Context, ref PathRef, fun RepositoryFileSystemFunc, commitmsg string) error {
return h.Func(ctx, ref,
Pull(), // git remote update 一次
FsFunc(fun),
UpdateKustomizeCommit(commitmsg),
)
}
func (h *ManifestProcessor) StoreFunc(ctx context.Context, ref PathRef, fun func(ctx context.Context, store GitStore) error) error {
return h.ContentFunc(ctx, ref, FSStoreFunc(fun))
}
func (h *ManifestProcessor) StoreUpdateFunc(ctx context.Context, ref PathRef, fun func(ctx context.Context, store GitStore) error, commitmsg string) error {
return h.UpdateContentFunc(ctx, ref, FSStoreFunc(fun), commitmsg)
}
func (h *ManifestProcessor) Create(ctx context.Context, ref PathRef, manifest Manifest) error {
updatefunc := func(_ context.Context, fs billy.Filesystem) error {
// init sample data
// 初始化文件必须在kustomize前
if err := initSampleManifest(fs, manifest.Name, manifest.Kind); err != nil {
return err
}
// init readme
if err := util.WriteFile(fs, ReadmeFilename, []byte(manifest.Description), os.ModePerm); err != nil {
return err
}
// init creation meta
if err := setManifestMeta(fs, manifestmeta{Creator: AuthorFromContext(ctx).Name, CreateAt: metav1.Now()}); err != nil {
return err
}
return nil
}
if ref.Name == "" {
ref.Name = manifest.Name
}
if err := h.UpdateContentFunc(ctx, ref, updatefunc, "init"); err != nil {
return err
}
return nil
}
func initSampleManifest(fs billy.Filesystem, name, kind string) error {
var sample interface{}
labels := map[string]string{
LabelApplication: name,
"app": name, // kubernetes app
}
podTemplate := corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: labels,
},
Spec: corev1.PodSpec{
Containers: []corev1.Container{
{
Name: name,
Image: "docker.io/library/hello-world:latest",
},
},
},
}
selector := &metav1.LabelSelector{
MatchLabels: labels,
}
metadata := metav1.ObjectMeta{Name: name}
switch kind {
case "Deployment":
sample = &appsv1.Deployment{
TypeMeta: metav1.TypeMeta{
APIVersion: appsv1.SchemeGroupVersion.String(),
Kind: "Deployment",
},
ObjectMeta: metadata,
Spec: appsv1.DeploymentSpec{Replicas: pointer.Int32(1), Selector: selector, Template: podTemplate},
}
case "DaemonSet":
sample = &appsv1.DaemonSet{
TypeMeta: metav1.TypeMeta{
APIVersion: appsv1.SchemeGroupVersion.String(),
Kind: "DaemonSet",
},
ObjectMeta: metadata,
Spec: appsv1.DaemonSetSpec{Selector: selector, Template: podTemplate},
}
case "StatefulSet":
sample = &appsv1.StatefulSet{
TypeMeta: metav1.TypeMeta{
APIVersion: appsv1.SchemeGroupVersion.String(),
Kind: "StatefulSet",
},
ObjectMeta: metadata,
Spec: appsv1.StatefulSetSpec{Replicas: pointer.Int32(1), Selector: selector, Template: podTemplate},
}
}
bts, err := yaml.Marshal(sample)
if err != nil {
return err
}
return util.WriteFile(fs, strings.ToLower(kind)+".yaml", bts, os.ModePerm)
}
func (h *ManifestProcessor) Get(ctx context.Context, ref PathRef) (*Manifest, error) {
manifest := &Manifest{Name: ref.Name, Ref: ref}
h.ContentFunc(ctx, ref, func(ctx context.Context, fs billy.Filesystem) error {
return DecodeManifest(ctx, fs, manifest, ManifestListOptions{WithImages: true})
})
return manifest, nil
}
type ManifestListOption func(*ManifestListOptions)
func WithImages() ManifestListOption {
return func(o *ManifestListOptions) {
o.WithImages = true
}
}
func (h *ManifestProcessor) List(ctx context.Context, ref PathRef, options ...ManifestListOption) ([]Manifest, error) {
opts := &ManifestListOptions{}
for _, o := range options {
o(opts)
}
span, ctx := opentracing.StartSpanFromContext(ctx, "list manifests")
defer span.Finish()
if ref.Name != "" {
return nil, fmt.Errorf("name must be empty")
}
manifestList := []Manifest{}
contentfunc := func(_ context.Context, fs billy.Filesystem) error {
ForManifestFsFunc(fs, func(name string, ifs billy.Filesystem) {
// in app
manifest := Manifest{
Name: name,
Ref: PathRef{Tenant: ref.Tenant, Project: ref.Project, Env: ref.Env, Name: name},
}
_ = DecodeManifest(ctx, ifs, &manifest, *opts)
manifestList = append(manifestList, manifest)
})
return nil
}
if err := h.Func(ctx, ref,
FsFunc(contentfunc),
func(ctx context.Context, repository Repository) error {
// 一次性填充创建时间
decodeCreationTimestamp(ctx, repository, manifestList)
return nil
},
); err != nil {
return nil, err
}
sort.Slice(manifestList, func(i, j int) bool {
return manifestList[i].CreateAt.After(manifestList[j].CreateAt.Time)
})
return manifestList, nil
}
func (h *ManifestProcessor) Update(ctx context.Context, ref PathRef, manifest Manifest) error {
updatefunc := func(_ context.Context, fs billy.Filesystem) error {
// update readme
return util.WriteFile(fs, ReadmeFilename, []byte(manifest.Description), os.ModePerm)
}
return h.UpdateContentFunc(ctx, ref, updatefunc, "update description")
}
func (h *ManifestProcessor) Remove(ctx context.Context, ref PathRef) error {
updatefunc := func(_ context.Context, fs billy.Filesystem) error {
_ = util.RemoveAll(fs, ".")
return nil
}
return h.UpdateContentFunc(ctx, ref, updatefunc, "remove")
}
func ForManifestFsFunc(fs billy.Filesystem, fun func(string, billy.Filesystem)) {
fis, err := fs.ReadDir(".")
if err != nil {
return
}
for _, fi := range fis {
if !fi.IsDir() {
continue
}
// 空文件夹跳过
if infos, _ := fs.ReadDir(fi.Name()); len(infos) == 0 {
continue
}
name := fi.Name()
fun(name, chroot.New(fs, name))
}
}
type ManifestListOptions struct {
WithImages bool // 解析资源中的镜像 和 istioVersion 更准确的kind等
}
var detectKinds = []string{
"deployment",
"statefulset",
"daemonset",
"cronjob",
"job",
}
type manifestmeta struct {
Creator string `json:"creator"`
CreateAt metav1.Time `json:"createAt"`
}
// 从应用编排根目录获取编排详情
func DecodeManifest(ctx context.Context, fs billy.Filesystem, manifest *Manifest, options ManifestListOptions) error {
if manifest.Name == "" {
return errors.New("name cannot be empty")
}
// description
desccontent, _ := util.ReadFile(fs, ReadmeFilename)
manifest.Description = string(desccontent)
// creation
manifestmeta := &manifestmeta{}
creationcontent, _ := util.ReadFile(fs, MetaFilename)
_ = json.Unmarshal(creationcontent, manifestmeta)
if !manifestmeta.CreateAt.IsZero() {
manifest.CreateAt = manifestmeta.CreateAt
manifest.Creator = manifestmeta.Creator
}
// kustomization
kustomization := &types.Kustomization{}
kustomizationcontent, _ := util.ReadFile(fs, KustimizationFilename)
_ = yaml.Unmarshal(kustomizationcontent, kustomization)
manifest.Annotations = kustomization.CommonAnnotations
manifest.Labels = kustomization.CommonLabels
// images version kind
if options.WithImages {
images := []string{}
istioVersion := ""
workload, _ := ParseMainWorkload(ctx, NewGitFsStore(fs))
ObjectPodTemplateFunc(workload, func(template *corev1.PodTemplateSpec) {
for _, c := range template.Spec.Containers {
if v, ok := template.Labels[LabelIstioVersion]; ok {
istioVersion = v
}
images = append(images, c.Image)
}
})
// update
manifest.Images = images
manifest.IstioVersion = istioVersion
if workload != nil {
manifest.Kind = workload.GetObjectKind().GroupVersionKind().Kind
}
} else {
// kind
for _, res := range kustomization.Resources {
for _, kind := range detectKinds {
// 因为约定,文件名中一般包含 deployment statefulset 等字样,如果存在这些则可以直接判断
if strings.Contains(res, kind) {
manifest.Kind = kind
break
}
}
}
}
return nil
}
// 该方法仅作为备用方式
func decodeCreationTimestamp(ctx context.Context, repo Repository, manifests []Manifest) {
fs, err := repo.FS(ctx)
if err != nil {
return
}
update := false
// 是否存在 没有创建时间的
for i, manifest := range manifests {
if manifest.CreateAt.IsZero() {
meta := manifestmeta{}
// 直到路径下的最晚提交,作为创建时间
// 这种方式的开销太大
repo.repo.HistoryFunc(ctx, manifest.Name, func(_ context.Context, commit git.Commit) error {
meta.CreateAt = metav1.NewTime(commit.Author.When)
meta.Creator = commit.Author.Name
return nil
})
// set meta
update = true
manifests[i].CreateAt = meta.CreateAt
manifests[i].Creator = meta.Creator
setManifestMeta(chroot.New(fs, manifest.Name), meta)
}
}
if update {
// 后台更新
log.FromContextOrDiscard(ctx).Info("init creation meta", "repo", repo.repo.CloneURL())
go Commit("init meta")(ctx, repo)
}
}
func setManifestMeta(fs billy.Filesystem, meta manifestmeta) error {
content, err := json.Marshal(meta)
if err != nil {
return err
}
return util.WriteFile(fs, MetaFilename, content, os.ModePerm)
}