forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
224 lines (195 loc) · 6.9 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
package util
import (
"fmt"
"math/rand"
"os"
"path"
"path/filepath"
"time"
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"
restclient "k8s.io/client-go/rest"
kapi "k8s.io/kubernetes/pkg/api"
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"
configapi "github.com/openshift/origin/pkg/cmd/server/api"
cmdutil "github.com/openshift/origin/pkg/cmd/util"
"github.com/openshift/origin/pkg/cmd/util/tokencmd"
oauthapi "github.com/openshift/origin/pkg/oauth/apis/oauth"
oauthclient "github.com/openshift/origin/pkg/oauth/generated/internalclientset"
"github.com/openshift/origin/pkg/serviceaccounts"
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 GetClusterAdminKubeClient(adminKubeConfigFile string) (kclientset.Interface, error) {
c, _, err := configapi.GetInternalKubeClient(adminKubeConfigFile, nil)
if err != nil {
return nil, err
}
return c, nil
}
func GetClusterAdminClientConfig(adminKubeConfigFile string) (*restclient.Config, error) {
_, conf, err := configapi.GetInternalKubeClient(adminKubeConfigFile, nil)
if err != nil {
return nil, err
}
return 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(clientConfig *restclient.Config, username string) (kclientset.Interface, *restclient.Config, error) {
token, err := tokencmd.RequestToken(clientConfig, nil, username, "password")
if err != nil {
return nil, nil, err
}
userClientConfig := restclient.AnonymousClientConfig(clientConfig)
userClientConfig.BearerToken = token
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).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).OAuthAccessTokens().Create(token); err != nil {
return nil, nil, err
}
scopedConfig := restclient.AnonymousClientConfig(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 serviceaccounts.IsValidServiceAccountToken(sa, &secret) {
token = string(secret.Data[kapi.ServiceAccountTokenKey])
return true, nil
}
}
return false, nil
})
if err != nil {
return nil, nil, err
}
saClientConfig := restclient.AnonymousClientConfig(&clientConfig)
saClientConfig.BearerToken = token
kubeClientset, err := kclientset.NewForConfig(saClientConfig)
if err != nil {
return nil, nil, err
}
return kubeClientset, saClientConfig, nil
}
// WaitForResourceQuotaSync 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
}