/
framework.go
324 lines (284 loc) · 11.1 KB
/
framework.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
/*
Copyright 2018 The Kubernetes 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 framework
import (
"fmt"
"io/fs"
"regexp"
"sync"
"time"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/klog/v2"
"k8s.io/perf-tests/clusterloader2/pkg/config"
"k8s.io/perf-tests/clusterloader2/pkg/errors"
"k8s.io/perf-tests/clusterloader2/pkg/framework/client"
frconfig "k8s.io/perf-tests/clusterloader2/pkg/framework/config"
"k8s.io/client-go/discovery"
restclient "k8s.io/client-go/rest"
// ensure auth plugins are loaded
_ "k8s.io/client-go/plugin/pkg/client/auth"
)
var namespaceID = regexp.MustCompile(`^test-[a-z0-9]+-[0-9]+$`)
// Framework allows for interacting with Kubernetes cluster via
// official Kubernetes client.
type Framework struct {
automanagedNamespacePrefix string
mux sync.Mutex
// automanagedNamespaces stores values as infromation if should the namespace be deleted
automanagedNamespaces map[string]bool
clientSets *MultiClientSet
dynamicClients *MultiDynamicClient
clusterConfig *config.ClusterConfig
restClientConfig *restclient.Config
discoveryClient *discovery.DiscoveryClient
}
// NewFramework creates new framework based on given clusterConfig.
func NewFramework(clusterConfig *config.ClusterConfig, clientsNumber int) (*Framework, error) {
return newFramework(clusterConfig, clientsNumber, clusterConfig.KubeConfigPath)
}
// NewRootFramework creates framework for the root cluster.
// For clusters other than kubemark there is no difference between NewRootFramework and NewFramework.
func NewRootFramework(clusterConfig *config.ClusterConfig, clientsNumber int) (*Framework, error) {
kubeConfigPath := clusterConfig.KubeConfigPath
if override := clusterConfig.Provider.GetConfig().RootFrameworkKubeConfigOverride(); override != "" {
kubeConfigPath = override
}
return newFramework(clusterConfig, clientsNumber, kubeConfigPath)
}
func newFramework(clusterConfig *config.ClusterConfig, clientsNumber int, kubeConfigPath string) (*Framework, error) {
klog.Infof("Creating framework with %d clients and %q kubeconfig.", clientsNumber, kubeConfigPath)
var err error
f := Framework{
automanagedNamespaces: map[string]bool{},
clusterConfig: clusterConfig,
}
if f.clientSets, err = NewMultiClientSet(kubeConfigPath, clientsNumber); err != nil {
return nil, fmt.Errorf("multi client set creation error: %v", err)
}
if f.dynamicClients, err = NewMultiDynamicClient(kubeConfigPath, clientsNumber); err != nil {
return nil, fmt.Errorf("multi dynamic client creation error: %v", err)
}
if f.restClientConfig, err = frconfig.GetConfig(kubeConfigPath); err != nil {
return nil, fmt.Errorf("rest client creation error: %v", err)
}
if f.discoveryClient, err = discovery.NewDiscoveryClientForConfig(f.restClientConfig); err != nil {
return nil, fmt.Errorf("discovery client creation error: %v", err)
}
return &f, nil
}
// GetAutomanagedNamespacePrefix returns automanaged namespace prefix.
func (f *Framework) GetAutomanagedNamespacePrefix() string {
return f.automanagedNamespacePrefix
}
// SetAutomanagedNamespacePrefix sets automanaged namespace prefix.
func (f *Framework) SetAutomanagedNamespacePrefix(nsName string) {
f.automanagedNamespacePrefix = nsName
}
// GetClientSets returns clientSet clients.
func (f *Framework) GetClientSets() *MultiClientSet {
return f.clientSets
}
// GetDynamicClients returns dynamic clients.
func (f *Framework) GetDynamicClients() *MultiDynamicClient {
return f.dynamicClients
}
func (f *Framework) GetRestClient() *restclient.Config {
return f.restClientConfig
}
// GetClusterConfig returns cluster config.
func (f *Framework) GetClusterConfig() *config.ClusterConfig {
return f.clusterConfig
}
func (f *Framework) GetDiscoveryClient() *discovery.DiscoveryClient {
return f.discoveryClient
}
// CreateAutomanagedNamespaces creates automanged namespaces.
func (f *Framework) CreateAutomanagedNamespaces(namespaceCount int, allowExistingNamespaces bool, deleteAutomanagedNamespaces bool) error {
f.mux.Lock()
defer f.mux.Unlock()
// get all pre-created namespaces and store in a hash set
namespacesList, err := client.ListNamespaces(f.clientSets.GetClient())
if err != nil {
return err
}
existingNamespaceSet := make(map[string]bool)
for _, ns := range namespacesList {
existingNamespaceSet[ns.Name] = true
}
for i := 1; i <= namespaceCount; i++ {
name := fmt.Sprintf("%v-%d", f.automanagedNamespacePrefix, i)
if _, created := existingNamespaceSet[name]; !created {
if err := client.CreateNamespace(f.clientSets.GetClient(), name); err != nil {
return err
}
} else {
if !allowExistingNamespaces {
return fmt.Errorf("automanaged namespace %s already created", name)
}
}
f.automanagedNamespaces[name] = deleteAutomanagedNamespaces
}
return nil
}
// ListAutomanagedNamespaces returns all existing automanged namespace names.
func (f *Framework) ListAutomanagedNamespaces() ([]string, []string, error) {
var automanagedNamespacesCurrentPrefixList, staleNamespaces []string
namespacesList, err := client.ListNamespaces(f.clientSets.GetClient())
if err != nil {
return automanagedNamespacesCurrentPrefixList, staleNamespaces, err
}
for _, namespace := range namespacesList {
matched, err := f.isAutomanagedNamespaceCurrentPrefix(namespace.Name)
if err != nil {
return automanagedNamespacesCurrentPrefixList, staleNamespaces, err
}
if matched {
automanagedNamespacesCurrentPrefixList = append(automanagedNamespacesCurrentPrefixList, namespace.Name)
} else {
// check further whether the namespace is a automanaged namespace created in previous test execution.
// this could happen when the execution is aborted abornamlly, and the resource is not able to be
// clean up.
matched := f.isStaleAutomanagedNamespace(namespace.Name)
if matched {
staleNamespaces = append(staleNamespaces, namespace.Name)
}
}
}
return automanagedNamespacesCurrentPrefixList, staleNamespaces, nil
}
func (f *Framework) deleteNamespace(namespace string, timeout time.Duration) error {
clientSet := f.clientSets.GetClient()
if err := client.DeleteNamespace(clientSet, namespace); err != nil {
return err
}
if err := client.WaitForDeleteNamespace(clientSet, namespace, timeout); err != nil {
return err
}
f.removeAutomanagedNamespace(namespace)
return nil
}
// DeleteAutomanagedNamespaces deletes all automanged namespaces.
func (f *Framework) DeleteAutomanagedNamespaces(timeout time.Duration) *errors.ErrorList {
var wg wait.Group
errList := errors.NewErrorList()
for namespace, shouldBeDeleted := range f.getAutomanagedNamespaces() {
namespace := namespace
if shouldBeDeleted {
wg.Start(func() {
if err := f.deleteNamespace(namespace, timeout); err != nil {
errList.Append(err)
return
}
})
}
}
wg.Wait()
return errList
}
func (f *Framework) removeAutomanagedNamespace(namespace string) {
f.mux.Lock()
defer f.mux.Unlock()
delete(f.automanagedNamespaces, namespace)
}
func (f *Framework) getAutomanagedNamespaces() map[string]bool {
f.mux.Lock()
defer f.mux.Unlock()
m := map[string]bool{}
for k, v := range f.automanagedNamespaces {
m[k] = v
}
return m
}
// DeleteNamespaces deletes the list of namespaces.
func (f *Framework) DeleteNamespaces(namespaces []string, timeout time.Duration) *errors.ErrorList {
var wg wait.Group
errList := errors.NewErrorList()
for _, namespace := range namespaces {
namespace := namespace
wg.Start(func() {
if err := f.deleteNamespace(namespace, timeout); err != nil {
errList.Append(err)
return
}
})
}
wg.Wait()
return errList
}
// CreateObject creates object base on given object description.
func (f *Framework) CreateObject(namespace string, name string, obj *unstructured.Unstructured, options ...*client.APICallOptions) error {
return client.CreateObject(f.dynamicClients.GetClient(), namespace, name, obj, options...)
}
// PatchObject updates object (using patch) with given name using given object description.
func (f *Framework) PatchObject(namespace string, name string, obj *unstructured.Unstructured, options ...*client.APICallOptions) error {
return client.PatchObject(f.dynamicClients.GetClient(), namespace, name, obj)
}
// DeleteObject deletes object with given name and group-version-kind.
func (f *Framework) DeleteObject(gvk schema.GroupVersionKind, namespace string, name string, options ...*client.APICallOptions) error {
return client.DeleteObject(f.dynamicClients.GetClient(), gvk, namespace, name)
}
// GetObject retrieves object with given name and group-version-kind.
func (f *Framework) GetObject(gvk schema.GroupVersionKind, namespace string, name string, options ...*client.APICallOptions) (*unstructured.Unstructured, error) {
return client.GetObject(f.dynamicClients.GetClient(), gvk, namespace, name)
}
// ApplyTemplatedManifests finds and applies all manifest template files matching the provided
// manifestGlob pattern. It substitutes the template placeholders using the templateMapping map.
func (f *Framework) ApplyTemplatedManifests(fsys fs.FS, manifestGlob string, templateMapping map[string]interface{}, options ...*client.APICallOptions) error {
// TODO(mm4tt): Consider using the out-of-the-box "kubectl create -f".
klog.Infof("Applying templates for %q", manifestGlob)
templateProvider := config.NewTemplateProvider(fsys)
manifests, err := fs.Glob(fsys, manifestGlob)
if err != nil {
return err
}
if manifests == nil {
klog.Warningf("There is no matching file for pattern %v.\n", manifestGlob)
}
for _, manifest := range manifests {
klog.V(1).Infof("Applying %s\n", manifest)
obj, err := templateProvider.TemplateToObject(manifest, templateMapping)
if err != nil {
if err == config.ErrorEmptyFile {
klog.Warningf("Skipping empty manifest %s", manifest)
continue
}
return fmt.Errorf("TemplateToObject error: %+v", err)
}
objList := []unstructured.Unstructured{*obj}
if obj.IsList() {
list, err := obj.ToList()
if err != nil {
return err
}
objList = list.Items
}
for _, item := range objList {
if err := f.CreateObject(item.GetNamespace(), item.GetName(), &item, options...); err != nil {
return fmt.Errorf("error while applying (%s): %v", manifest, err)
}
}
}
return nil
}
func (f *Framework) isAutomanagedNamespaceCurrentPrefix(name string) (bool, error) {
return regexp.MatchString(f.automanagedNamespacePrefix+"-[1-9][0-9]*", name)
}
func (f *Framework) isStaleAutomanagedNamespace(name string) bool {
if namespaceID.MatchString(name) {
_, isFromThisExecution := f.getAutomanagedNamespaces()[name]
return !isFromThisExecution
}
return false
}