...
1
2
3
4 package builtins
5
6 import (
7 "fmt"
8
9 "sigs.k8s.io/kustomize/api/filters/replicacount"
10 "sigs.k8s.io/kustomize/api/resmap"
11 "sigs.k8s.io/kustomize/api/types"
12 "sigs.k8s.io/kustomize/kyaml/resid"
13 "sigs.k8s.io/yaml"
14 )
15
16
17
18 type ReplicaCountTransformerPlugin struct {
19 Replica types.Replica `json:"replica,omitempty" yaml:"replica,omitempty"`
20 FieldSpecs []types.FieldSpec `json:"fieldSpecs,omitempty" yaml:"fieldSpecs,omitempty"`
21 }
22
23 func (p *ReplicaCountTransformerPlugin) Config(
24 _ *resmap.PluginHelpers, c []byte) (err error) {
25 p.Replica = types.Replica{}
26 p.FieldSpecs = nil
27 return yaml.Unmarshal(c, p)
28 }
29
30 func (p *ReplicaCountTransformerPlugin) Transform(m resmap.ResMap) error {
31 found := false
32 for _, fs := range p.FieldSpecs {
33 matcher := p.createMatcher(fs)
34 resList := m.GetMatchingResourcesByAnyId(matcher)
35 if len(resList) > 0 {
36 found = true
37 for _, r := range resList {
38
39
40
41 err := r.ApplyFilter(replicacount.Filter{
42 Replica: p.Replica,
43 FieldSpec: fs,
44 })
45 if err != nil {
46 return err
47 }
48 }
49 }
50 }
51
52 if !found {
53 gvks := make([]string, len(p.FieldSpecs))
54 for i, replicaSpec := range p.FieldSpecs {
55 gvks[i] = replicaSpec.Gvk.String()
56 }
57 return fmt.Errorf("resource with name %s does not match a config with the following GVK %v",
58 p.Replica.Name, gvks)
59 }
60
61 return nil
62 }
63
64
65 func (p *ReplicaCountTransformerPlugin) createMatcher(fs types.FieldSpec) resmap.IdMatcher {
66 return func(r resid.ResId) bool {
67 return r.Name == p.Replica.Name && r.Gvk.IsSelected(&fs.Gvk)
68 }
69 }
70
71 func NewReplicaCountTransformerPlugin() resmap.TransformerPlugin {
72 return &ReplicaCountTransformerPlugin{}
73 }
74
View as plain text