| 1 |
// Copyright 2019 The Kubernetes Authors. |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
//go:generate pluginator |
| 5 |
package main |
| 6 |
|
| 7 |
import ( |
| 8 |
"fmt" |
| 9 |
|
| 10 |
"sigs.k8s.io/kustomize/api/filters/replicacount" |
| 11 |
"sigs.k8s.io/kustomize/api/resmap" |
| 12 |
"sigs.k8s.io/kustomize/api/types" |
| 13 |
"sigs.k8s.io/kustomize/kyaml/resid" |
| 14 |
"sigs.k8s.io/yaml" |
| 15 |
) |
| 16 |
|
| 17 |
// Find matching replicas declarations and replace the count. |
| 18 |
// Eases the kustomization configuration of replica changes. |
| 19 |
type plugin struct { |
| 20 |
Replica types.Replica `json:"replica,omitempty" yaml:"replica,omitempty"` |
| 21 |
FieldSpecs []types.FieldSpec `json:"fieldSpecs,omitempty" yaml:"fieldSpecs,omitempty"` |
| 22 |
} |
| 23 |
|
| 24 |
var KustomizePlugin plugin //nolint:gochecknoglobals |
| 25 |
|
| 26 |
func (p *plugin) Config( |
| 27 |
_ *resmap.PluginHelpers, c []byte) (err error) { |
| 28 |
p.Replica = types.Replica{} |
| 29 |
p.FieldSpecs = nil |
| 30 |
return yaml.Unmarshal(c, p) |
| 31 |
} |
| 32 |
|
| 33 |
func (p *plugin) Transform(m resmap.ResMap) error { |
| 34 |
found := false |
| 35 |
for _, fs := range p.FieldSpecs { |
| 36 |
matcher := p.createMatcher(fs) |
| 37 |
resList := m.GetMatchingResourcesByAnyId(matcher) |
| 38 |
if len(resList) > 0 { |
| 39 |
found = true |
| 40 |
for _, r := range resList { |
| 41 |
// There are redundant checks in the filter |
| 42 |
// that we'll live with until resolution of |
| 43 |
// https://github.com/kubernetes-sigs/kustomize/issues/2506 |
| 44 |
err := r.ApplyFilter(replicacount.Filter{ |
| 45 |
Replica: p.Replica, |
| 46 |
FieldSpec: fs, |
| 47 |
}) |
| 48 |
if err != nil { |
| 49 |
return err |
| 50 |
} |
| 51 |
} |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
if !found { |
| 56 |
gvks := make([]string, len(p.FieldSpecs)) |
| 57 |
for i, replicaSpec := range p.FieldSpecs { |
| 58 |
gvks[i] = replicaSpec.Gvk.String() |
| 59 |
} |
| 60 |
return fmt.Errorf("resource with name %s does not match a config with the following GVK %v", |
| 61 |
p.Replica.Name, gvks) |
| 62 |
} |
| 63 |
|
| 64 |
return nil |
| 65 |
} |
| 66 |
|
| 67 |
// Match Replica.Name and FieldSpec |
| 68 |
func (p *plugin) createMatcher(fs types.FieldSpec) resmap.IdMatcher { |
| 69 |
return func(r resid.ResId) bool { |
| 70 |
return r.Name == p.Replica.Name && r.Gvk.IsSelected(&fs.Gvk) |
| 71 |
} |
| 72 |
} |