forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
292 lines (255 loc) · 9.08 KB
/
client.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
package util
import (
"encoding/base64"
"fmt"
"math/rand"
"os"
"path"
"path/filepath"
"time"
"github.com/pborman/uuid"
kerrs "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/kubernetes"
restclient "k8s.io/client-go/rest"
"k8s.io/client-go/util/flowcontrol"
kapi "k8s.io/kubernetes/pkg/apis/core"
kclientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"
kcoreclient "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion"
"k8s.io/kubernetes/pkg/quota"
sautil "k8s.io/kubernetes/pkg/serviceaccount"
configapi "github.com/openshift/origin/pkg/cmd/server/apis/config"
cmdutil "github.com/openshift/origin/pkg/cmd/util"
oauthapi "github.com/openshift/origin/pkg/oauth/apis/oauth"
oauthclient "github.com/openshift/origin/pkg/oauth/generated/internalclientset"
userapi "github.com/openshift/origin/pkg/user/apis/user"
userclient "github.com/openshift/origin/pkg/user/generated/internalclientset"
)
// GetBaseDir returns the base directory used for test.
func GetBaseDir() string {
return cmdutil.Env("BASETMPDIR", path.Join(os.TempDir(), "openshift-"+Namespace()))
}
func KubeConfigPath() string {
return filepath.Join(GetBaseDir(), "openshift.local.config", "master", "admin.kubeconfig")
}
func GetClusterAdminKubeInternalClient(adminKubeConfigFile string) (kclientset.Interface, error) {
clientConfig, err := GetClusterAdminClientConfig(adminKubeConfigFile)
if err != nil {
return nil, err
}
return kclientset.NewForConfig(clientConfig)
}
func GetClusterAdminKubeClient(adminKubeConfigFile string) (kubernetes.Interface, error) {
clientConfig, err := GetClusterAdminClientConfig(adminKubeConfigFile)
if err != nil {
return nil, err
}
return kubernetes.NewForConfig(clientConfig)
}
func GetClusterAdminClientConfig(adminKubeConfigFile string) (*restclient.Config, error) {
conf, err := configapi.GetClientConfig(adminKubeConfigFile, nil)
if err != nil {
return nil, err
}
return turnOffRateLimiting(conf), nil
}
// GetClusterAdminClientConfigOrDie returns a REST config for the cluster admin
// user or panic.
func GetClusterAdminClientConfigOrDie(adminKubeConfigFile string) *restclient.Config {
conf, err := GetClusterAdminClientConfig(adminKubeConfigFile)
if err != nil {
panic(err)
}
return conf
}
func GetClientForUser(clusterAdminConfig *restclient.Config, username string) (kclientset.Interface, *restclient.Config, error) {
userClient, err := userclient.NewForConfig(clusterAdminConfig)
if err != nil {
return nil, nil, err
}
user, err := userClient.User().Users().Get(username, metav1.GetOptions{})
if err != nil && !kerrs.IsNotFound(err) {
return nil, nil, err
}
if err != nil {
user = &userapi.User{
ObjectMeta: metav1.ObjectMeta{Name: username},
}
user, err = userClient.User().Users().Create(user)
if err != nil {
return nil, nil, err
}
}
oauthClient, err := oauthclient.NewForConfig(clusterAdminConfig)
if err != nil {
return nil, nil, err
}
oauthClientObj := &oauthapi.OAuthClient{
ObjectMeta: metav1.ObjectMeta{Name: "test-integration-client"},
}
if _, err := oauthClient.Oauth().OAuthClients().Create(oauthClientObj); err != nil && !kerrs.IsAlreadyExists(err) {
return nil, nil, err
}
randomToken := uuid.NewRandom()
accesstoken := base64.RawURLEncoding.EncodeToString([]byte(randomToken))
// make sure the token is long enough to pass validation
for i := len(accesstoken); i < 32; i++ {
accesstoken += "A"
}
token := &oauthapi.OAuthAccessToken{
ObjectMeta: metav1.ObjectMeta{Name: accesstoken},
ClientName: oauthClientObj.Name,
UserName: username,
UserUID: string(user.UID),
}
if _, err := oauthClient.Oauth().OAuthAccessTokens().Create(token); err != nil {
return nil, nil, err
}
userClientConfig := restclient.AnonymousClientConfig(turnOffRateLimiting(clusterAdminConfig))
userClientConfig.BearerToken = token.Name
kubeClientset, err := kclientset.NewForConfig(userClientConfig)
if err != nil {
return nil, nil, err
}
return kubeClientset, userClientConfig, nil
}
func GetScopedClientForUser(clusterAdminClientConfig *restclient.Config, username string, scopes []string) (kclientset.Interface, *restclient.Config, error) {
// make sure the user exists
if _, _, err := GetClientForUser(clusterAdminClientConfig, username); err != nil {
return nil, nil, err
}
user, err := userclient.NewForConfigOrDie(clusterAdminClientConfig).User().Users().Get(username, metav1.GetOptions{})
if err != nil {
return nil, nil, err
}
token := &oauthapi.OAuthAccessToken{
ObjectMeta: metav1.ObjectMeta{Name: fmt.Sprintf("%s-token-plus-some-padding-here-to-make-the-limit-%d", username, rand.Int())},
ClientName: "openshift-challenging-client",
ExpiresIn: 86400,
Scopes: scopes,
RedirectURI: "https://127.0.0.1:12000/oauth/token/implicit",
UserName: user.Name,
UserUID: string(user.UID),
}
if _, err := oauthclient.NewForConfigOrDie(clusterAdminClientConfig).Oauth().OAuthAccessTokens().Create(token); err != nil {
return nil, nil, err
}
scopedConfig := restclient.AnonymousClientConfig(turnOffRateLimiting(clusterAdminClientConfig))
scopedConfig.BearerToken = token.Name
kubeClient, err := kclientset.NewForConfig(scopedConfig)
if err != nil {
return nil, nil, err
}
return kubeClient, scopedConfig, nil
}
func GetClientForServiceAccount(adminClient kclientset.Interface, clientConfig restclient.Config, namespace, name string) (*kclientset.Clientset, *restclient.Config, error) {
_, err := adminClient.Core().Namespaces().Create(&kapi.Namespace{ObjectMeta: metav1.ObjectMeta{Name: namespace}})
if err != nil && !kerrs.IsAlreadyExists(err) {
return nil, nil, err
}
sa, err := adminClient.Core().ServiceAccounts(namespace).Create(&kapi.ServiceAccount{ObjectMeta: metav1.ObjectMeta{Name: name}})
if kerrs.IsAlreadyExists(err) {
sa, err = adminClient.Core().ServiceAccounts(namespace).Get(name, metav1.GetOptions{})
}
if err != nil {
return nil, nil, err
}
token := ""
err = wait.Poll(time.Second, 30*time.Second, func() (bool, error) {
selector := fields.OneTermEqualSelector(kapi.SecretTypeField, string(kapi.SecretTypeServiceAccountToken))
secrets, err := adminClient.Core().Secrets(namespace).List(metav1.ListOptions{FieldSelector: selector.String()})
if err != nil {
return false, err
}
for _, secret := range secrets.Items {
if sautil.InternalIsServiceAccountToken(&secret, sa) {
token = string(secret.Data[kapi.ServiceAccountTokenKey])
return true, nil
}
}
return false, nil
})
if err != nil {
return nil, nil, err
}
saClientConfig := restclient.AnonymousClientConfig(turnOffRateLimiting(&clientConfig))
saClientConfig.BearerToken = token
kubeClientset, err := kclientset.NewForConfig(saClientConfig)
if err != nil {
return nil, nil, err
}
return kubeClientset, saClientConfig, nil
}
// WaitForResourceQuotaLimitSync watches given resource quota until its hard limit is updated to match the desired
// spec or timeout occurs.
func WaitForResourceQuotaLimitSync(
client kcoreclient.ResourceQuotaInterface,
name string,
hardLimit kapi.ResourceList,
timeout time.Duration,
) error {
startTime := time.Now()
endTime := startTime.Add(timeout)
expectedResourceNames := quota.ResourceNames(hardLimit)
list, err := client.List(metav1.ListOptions{FieldSelector: fields.Set{"metadata.name": name}.AsSelector().String()})
if err != nil {
return err
}
for i := range list.Items {
used := quota.Mask(list.Items[i].Status.Hard, expectedResourceNames)
if isLimitSynced(used, hardLimit) {
return nil
}
}
rv := list.ResourceVersion
w, err := client.Watch(metav1.ListOptions{FieldSelector: fields.Set{"metadata.name": name}.AsSelector().String(), ResourceVersion: rv})
if err != nil {
return err
}
defer w.Stop()
for time.Now().Before(endTime) {
select {
case val, ok := <-w.ResultChan():
if !ok {
// reget and re-watch
continue
}
if rq, ok := val.Object.(*kapi.ResourceQuota); ok {
used := quota.Mask(rq.Status.Hard, expectedResourceNames)
if isLimitSynced(used, hardLimit) {
return nil
}
}
case <-time.After(endTime.Sub(time.Now())):
return wait.ErrWaitTimeout
}
}
return wait.ErrWaitTimeout
}
func isLimitSynced(received, expected kapi.ResourceList) bool {
resourceNames := quota.ResourceNames(expected)
masked := quota.Mask(received, resourceNames)
if len(masked) != len(expected) {
return false
}
if le, _ := quota.LessThanOrEqual(masked, expected); !le {
return false
}
if le, _ := quota.LessThanOrEqual(expected, masked); !le {
return false
}
return true
}
// turnOffRateLimiting reduces the chance that a flaky test can be written while using this package
func turnOffRateLimiting(config *restclient.Config) *restclient.Config {
configCopy := *config
configCopy.QPS = 10000
configCopy.Burst = 10000
configCopy.RateLimiter = flowcontrol.NewFakeAlwaysRateLimiter()
// We do not set a timeout because that will cause watches to fail
// Integration tests are already limited to 5 minutes
// configCopy.Timeout = time.Minute
return &configCopy
}