File: ReplicaCountTransformer.go

package info (click to toggle)
golang-k8s-sigs-kustomize-api 0.19.0%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,732 kB
  • sloc: makefile: 206; sh: 67
file content (72 lines) | stat: -rw-r--r-- 1,912 bytes parent folder | download
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
// Copyright 2019 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0

//go:generate pluginator
package main

import (
	"fmt"

	"sigs.k8s.io/kustomize/api/filters/replicacount"
	"sigs.k8s.io/kustomize/api/resmap"
	"sigs.k8s.io/kustomize/api/types"
	"sigs.k8s.io/kustomize/kyaml/resid"
	"sigs.k8s.io/yaml"
)

// Find matching replicas declarations and replace the count.
// Eases the kustomization configuration of replica changes.
type plugin struct {
	Replica    types.Replica     `json:"replica,omitempty" yaml:"replica,omitempty"`
	FieldSpecs []types.FieldSpec `json:"fieldSpecs,omitempty" yaml:"fieldSpecs,omitempty"`
}

var KustomizePlugin plugin //nolint:gochecknoglobals

func (p *plugin) Config(
	_ *resmap.PluginHelpers, c []byte) (err error) {
	p.Replica = types.Replica{}
	p.FieldSpecs = nil
	return yaml.Unmarshal(c, p)
}

func (p *plugin) Transform(m resmap.ResMap) error {
	found := false
	for _, fs := range p.FieldSpecs {
		matcher := p.createMatcher(fs)
		resList := m.GetMatchingResourcesByAnyId(matcher)
		if len(resList) > 0 {
			found = true
			for _, r := range resList {
				// There are redundant checks in the filter
				// that we'll live with until resolution of
				// https://github.com/kubernetes-sigs/kustomize/issues/2506
				err := r.ApplyFilter(replicacount.Filter{
					Replica:   p.Replica,
					FieldSpec: fs,
				})
				if err != nil {
					return err
				}
			}
		}
	}

	if !found {
		gvks := make([]string, len(p.FieldSpecs))
		for i, replicaSpec := range p.FieldSpecs {
			gvks[i] = replicaSpec.Gvk.String()
		}
		return fmt.Errorf("resource with name %s does not match a config with the following GVK %v",
			p.Replica.Name, gvks)
	}

	return nil
}

// Match Replica.Name and FieldSpec
func (p *plugin) createMatcher(fs types.FieldSpec) resmap.IdMatcher {
	return func(r resid.ResId) bool {
		return r.Name == p.Replica.Name && r.Gvk.IsSelected(&fs.Gvk)
	}
}