kuma

Форк
0
/
kumactl.go 
228 строк · 5.6 Кб
1
package kumactl
2

3
import (
4
	"encoding/json"
5
	"net/url"
6
	"os"
7
	"strings"
8
	"time"
9

10
	"github.com/gruntwork-io/terratest/modules/logger"
11
	"github.com/gruntwork-io/terratest/modules/retry"
12
	"github.com/gruntwork-io/terratest/modules/shell"
13
	"github.com/gruntwork-io/terratest/modules/testing"
14
	"github.com/pkg/errors"
15

16
	core_model "github.com/kumahq/kuma/pkg/core/resources/model"
17
	"github.com/kumahq/kuma/pkg/core/resources/model/rest"
18
)
19

20
type KumactlOptions struct {
21
	t          testing.TestingT
22
	CPName     string
23
	Kumactl    string
24
	ConfigPath string
25
	Verbose    bool
26
	Env        map[string]string
27
	Retries    int
28
	Timeout    time.Duration
29
	ExtraArgs  []string
30
}
31

32
func NewKumactlOptions(
33
	t testing.TestingT,
34
	cpname string,
35
	command string,
36
	extraArgs []string,
37
	configPath string,
38
	verbose bool,
39
	retries int,
40
	timeout time.Duration,
41
) *KumactlOptions {
42
	return &KumactlOptions{
43
		t:          t,
44
		CPName:     cpname,
45
		Kumactl:    command,
46
		ExtraArgs:  extraArgs,
47
		ConfigPath: configPath,
48
		Verbose:    verbose,
49
		Retries:    retries,
50
		Timeout:    timeout,
51
		Env:        map[string]string{},
52
	}
53
}
54

55
func (k *KumactlOptions) RunKumactl(args ...string) error {
56
	out, err := k.RunKumactlAndGetOutput(args...)
57
	if err != nil {
58
		return errors.Wrapf(err, out)
59
	}
60
	return nil
61
}
62

63
func (k *KumactlOptions) RunKumactlAndGetOutput(args ...string) (string, error) {
64
	return k.RunKumactlAndGetOutputV(k.Verbose, args...)
65
}
66

67
func (k *KumactlOptions) RunKumactlAndGetOutputV(verbose bool, args ...string) (string, error) {
68
	cmdArgs := []string{}
69
	if len(k.ExtraArgs) > 0 {
70
		cmdArgs = append(cmdArgs, k.ExtraArgs...)
71
	}
72
	if k.ConfigPath != "" {
73
		cmdArgs = append(cmdArgs, "--config-file", k.ConfigPath)
74
	}
75

76
	cmdArgs = append(cmdArgs, args...)
77
	command := shell.Command{
78
		Command: k.Kumactl,
79
		Args:    cmdArgs,
80
		Env:     k.Env,
81
	}
82

83
	if !verbose {
84
		command.Logger = logger.Discard
85
	}
86

87
	return shell.RunCommandAndGetStdOutE(k.t, command)
88
}
89

90
func (k *KumactlOptions) KumactlVersion() (string, error) {
91
	return k.RunKumactlAndGetOutput("version")
92
}
93

94
func (k *KumactlOptions) KumactlDelete(kumatype, name, mesh string) error {
95
	return k.RunKumactl("delete", kumatype, name, "--mesh", mesh)
96
}
97

98
func (k *KumactlOptions) KumactlList(kumatype, mesh string) ([]string, error) {
99
	out, err := k.RunKumactlAndGetOutput("get", kumatype, "--mesh", mesh, "-o", "json")
100
	if err != nil {
101
		return nil, err
102
	}
103

104
	type item struct {
105
		Name string `json:"name"`
106
	}
107
	type resourceList struct {
108
		Items []item `json:"items"`
109
	}
110

111
	list := &resourceList{}
112
	if err := json.Unmarshal([]byte(out), list); err != nil {
113
		return nil, err
114
	}
115

116
	var items []string
117
	for _, item := range list.Items {
118
		items = append(items, item.Name)
119
	}
120
	return items, nil
121
}
122

123
func (k *KumactlOptions) KumactlApply(configPath string) error {
124
	return k.RunKumactl("apply", "-f", configPath)
125
}
126

127
func (k *KumactlOptions) KumactlApplyFromString(configData string) error {
128
	tmpfile, err := storeConfigToTempFile(k.t.Name(), configData)
129
	if err != nil {
130
		return err
131
	}
132

133
	defer os.Remove(tmpfile)
134

135
	return k.KumactlApply(tmpfile)
136
}
137

138
func storeConfigToTempFile(name string, configData string) (string, error) {
139
	escapedTestName := url.PathEscape(name)
140

141
	tmpfile, err := os.CreateTemp("", escapedTestName)
142
	if err != nil {
143
		return "", err
144
	}
145
	defer tmpfile.Close()
146

147
	_, err = tmpfile.WriteString(configData)
148

149
	return tmpfile.Name(), err
150
}
151

152
func (k *KumactlOptions) KumactlInstallCP(args ...string) (string, error) {
153
	cmd := []string{
154
		"install", "control-plane",
155
	}
156

157
	cmd = append(cmd, args...)
158

159
	return k.RunKumactlAndGetOutputV(
160
		false, // silence the log output of Install
161
		cmd...)
162
}
163

164
func (k *KumactlOptions) KumactlInstallObservability(namespace string, components []string) (string, error) {
165
	args := []string{"install", "observability", "--namespace", namespace}
166
	if len(components) != 0 {
167
		args = append(args, "--components", strings.Join(components, ","))
168
	}
169
	return k.RunKumactlAndGetOutput(args...)
170
}
171

172
func (k *KumactlOptions) KumactlConfigControlPlanesAdd(name, address, token string, headers []string) error {
173
	_, err := retry.DoWithRetryE(k.t, "kumactl config control-planes add", k.Retries, k.Timeout,
174
		func() (string, error) {
175
			args := []string{
176
				"config", "control-planes", "add",
177
				"--overwrite",
178
				"--name", name,
179
				"--address", address,
180
			}
181
			if len(headers) > 0 {
182
				args = append(args, "--headers", strings.Join(headers, ","))
183
			}
184
			if token != "" {
185
				args = append(args,
186
					"--auth-type", "tokens",
187
					"--auth-conf", "token="+token,
188
				)
189
			}
190
			err := k.RunKumactl(args...)
191
			if err != nil {
192
				return "Unable to register Kuma CP. Try again.", err
193
			}
194

195
			return "", nil
196
		})
197

198
	return err
199
}
200

201
func (k *KumactlOptions) KumactlConfigControlPlanesSwitch(name string) error {
202
	return k.RunKumactl("config", "control-planes", "switch", "--name", name)
203
}
204

205
// KumactlUpdateObject fetches an object and updates it after the update function is applied to it.
206
func (k *KumactlOptions) KumactlUpdateObject(
207
	typeName string,
208
	objectName string,
209
	update func(core_model.Resource) core_model.Resource,
210
) error {
211
	out, err := k.RunKumactlAndGetOutput("get", typeName, objectName, "-o", "yaml")
212
	if err != nil {
213
		return errors.Wrapf(err, "failed to get %q object %q", typeName, objectName)
214
	}
215

216
	resource, err := rest.YAML.UnmarshalCore([]byte(out))
217
	if err != nil {
218
		return errors.Wrapf(err, "failed to unmarshal %q object %q: %q", typeName, objectName, out)
219
	}
220

221
	updated := rest.From.Resource(update(resource))
222
	jsonRes, err := json.Marshal(updated)
223
	if err != nil {
224
		return errors.Wrapf(err, "failed to marshal JSON for %q object %q", typeName, objectName)
225
	}
226

227
	return k.KumactlApplyFromString(string(jsonRes))
228
}
229

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

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

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

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