-
Notifications
You must be signed in to change notification settings - Fork 1
/
factory.go
454 lines (391 loc) · 12.1 KB
/
factory.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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
package util
import (
"flag"
"fmt"
"io"
"os"
"path/filepath"
"github.com/jenkins-x/jx/pkg/jenkins"
"github.com/jenkins-x/jx/pkg/jx/cmd/table"
"github.com/jenkins-x/jx/pkg/kube"
"github.com/jenkins-x/golang-jenkins"
"github.com/jenkins-x/jx/pkg/auth"
"github.com/jenkins-x/jx/pkg/client/clientset/versioned"
"github.com/jenkins-x/jx/pkg/util"
corev1 "k8s.io/api/core/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
apiextensionsclientset "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
metricsclient "k8s.io/metrics/pkg/client/clientset_generated/clientset"
// this is so that we load the auth plugins so we can connect to, say, GCP
"github.com/jenkins-x/jx/pkg/gits"
_ "k8s.io/client-go/plugin/pkg/client/auth"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
const (
JenkinsAuthConfigFile = "jenkinsAuth.yaml"
IssuesAuthConfigFile = "issuesAuth.yaml"
ChatAuthConfigFile = "chat.yaml"
GitAuthConfigFile = "gitAuth.yaml"
ChartmuseumAuthConfigFile = "chartmuseumAuth.yaml"
)
type Factory interface {
CreateJenkinsClient() (*gojenkins.Jenkins, error)
GetJenkinsURL() (string, error)
CreateAuthConfigService(fileName string) (auth.AuthConfigService, error)
CreateGitAuthConfigService() (auth.AuthConfigService, error)
CreateJenkinsAuthConfigService() (auth.AuthConfigService, error)
CreateChartmuseumAuthConfigService() (auth.AuthConfigService, error)
CreateIssueTrackerAuthConfigService(secrets *corev1.SecretList) (auth.AuthConfigService, error)
CreateChatAuthConfigService(secrets *corev1.SecretList) (auth.AuthConfigService, error)
CreateClient() (*kubernetes.Clientset, string, error)
CreateJXClient() (*versioned.Clientset, string, error)
CreateApiExtensionsClient() (*apiextensionsclientset.Clientset, error)
CreateMetricsClient() (*metricsclient.Clientset, error)
CreateTable(out io.Writer) table.Table
SetBatch(batch bool)
LoadPipelineSecrets(kind string) (*corev1.SecretList, error)
ImpersonateUser(user string) Factory
}
type factory struct {
Batch bool
impersonateUser string
}
// NewFactory creates a factory with the default Kubernetes resources defined
// if optionalClientConfig is nil, then flags will be bound to a new clientcmd.ClientConfig.
// if optionalClientConfig is not nil, then this factory will make use of it.
func NewFactory() Factory {
return &factory{}
}
func (f *factory) SetBatch(batch bool) {
f.Batch = batch
}
// ImpersonateUser returns a new factory impersonating the given user
func (f *factory) ImpersonateUser(user string) Factory {
copy := *f
copy.impersonateUser = user
return ©
}
// CreateJenkinsClient creates a new jenkins client
func (f *factory) CreateJenkinsClient() (*gojenkins.Jenkins, error) {
svc, err := f.CreateJenkinsAuthConfigService()
if err != nil {
return nil, err
}
url, err := f.GetJenkinsURL()
if err != nil {
return nil, err
}
return jenkins.GetJenkinsClient(url, f.Batch, &svc)
}
func (f *factory) GetJenkinsURL() (string, error) {
// lets find the kubernetes service
client, ns, err := f.CreateClient()
if err != nil {
return "", err
}
url, err := kube.FindServiceURL(client, ns, kube.ServiceJenkins)
if err != nil {
// lets try the real environment
realNS, _, err := kube.GetDevNamespace(client, ns)
if err != nil {
return "", err
}
if realNS != ns {
url, err = kube.FindServiceURL(client, realNS, kube.ServiceJenkins)
if err != nil {
return "", err
}
} else {
return "", err
}
}
return url, err
}
func (f *factory) CreateJenkinsAuthConfigService() (auth.AuthConfigService, error) {
authConfigSvc, err := f.CreateAuthConfigService(JenkinsAuthConfigFile)
if err != nil {
return authConfigSvc, err
}
_, err = authConfigSvc.LoadConfig()
if err != nil {
return authConfigSvc, err
}
return authConfigSvc, err
}
func (f *factory) CreateChartmuseumAuthConfigService() (auth.AuthConfigService, error) {
authConfigSvc, err := f.CreateAuthConfigService(ChartmuseumAuthConfigFile)
if err != nil {
return authConfigSvc, err
}
_, err = authConfigSvc.LoadConfig()
if err != nil {
return authConfigSvc, err
}
return authConfigSvc, err
}
func (f *factory) CreateIssueTrackerAuthConfigService(secrets *corev1.SecretList) (auth.AuthConfigService, error) {
authConfigSvc, err := f.CreateAuthConfigService(IssuesAuthConfigFile)
if err != nil {
return authConfigSvc, err
}
if secrets != nil {
config, err := authConfigSvc.LoadConfig()
if err != nil {
return authConfigSvc, err
}
f.authMergePipelineSecrets(config, secrets, kube.ValueKindIssue, f.isInCDPIpeline())
}
return authConfigSvc, err
}
func (f *factory) CreateChatAuthConfigService(secrets *corev1.SecretList) (auth.AuthConfigService, error) {
authConfigSvc, err := f.CreateAuthConfigService(ChatAuthConfigFile)
if err != nil {
return authConfigSvc, err
}
if secrets != nil {
config, err := authConfigSvc.LoadConfig()
if err != nil {
return authConfigSvc, err
}
f.authMergePipelineSecrets(config, secrets, kube.ValueKindChat, f.isInCDPIpeline())
}
return authConfigSvc, err
}
func (f *factory) authMergePipelineSecrets(config *auth.AuthConfig, secrets *corev1.SecretList, kind string, isCDPipeline bool) {
if config == nil || secrets == nil {
return
}
for _, secret := range secrets.Items {
labels := secret.Labels
annotations := secret.Annotations
data := secret.Data
if labels != nil && labels[kube.LabelKind] == kind && annotations != nil {
u := annotations[kube.AnnotationURL]
name := annotations[kube.AnnotationName]
k := labels[kube.LabelServiceKind]
if u != "" {
server := config.GetOrCreateServer(u)
if server != nil {
// lets use the latest values from the credential
if k != "" {
server.Kind = k
}
if name != "" {
server.Name = name
}
if data != nil {
username := data[kube.SecretDataUsername]
pwd := data[kube.SecretDataPassword]
if len(username) > 0 && isCDPipeline {
userAuth := config.GetOrCreateUserAuth(u, string(username))
if userAuth != nil {
if len(pwd) > 0 {
userAuth.ApiToken = string(pwd)
}
}
}
}
}
}
}
}
}
func (f *factory) CreateGitAuthConfigService() (auth.AuthConfigService, error) {
secrets, err := f.LoadPipelineSecrets(kube.ValueKindGit)
if err != nil {
kubeConfig, _, configLoadErr := kube.LoadConfig()
if err != nil {
fmt.Printf("WARNING: Could not load config: %s", configLoadErr)
}
ns := kube.CurrentNamespace(kubeConfig)
if ns == "" {
fmt.Printf("WARNING: Could not get the current namespace")
}
fmt.Printf("WARNING: The current user cannot query secrets in the namespace %s: %s\n", ns, err)
}
fileName := GitAuthConfigFile
return f.createGitAuthConfigServiceFromSecrets(fileName, secrets, f.isInCDPIpeline())
}
func (f *factory) createGitAuthConfigServiceFromSecrets(fileName string, secrets *corev1.SecretList, isCDPipeline bool) (auth.AuthConfigService, error) {
authConfigSvc, err := f.CreateAuthConfigService(fileName)
if err != nil {
return authConfigSvc, err
}
config, err := authConfigSvc.LoadConfig()
if err != nil {
return authConfigSvc, err
}
if secrets != nil {
f.authMergePipelineSecrets(config, secrets, kube.ValueKindGit, isCDPipeline)
}
// lets add a default if there's none defined yet
if len(config.Servers) == 0 {
// if in cluster then there's no user configfile, so check for env vars first
userAuth := auth.CreateAuthUserFromEnvironment("GIT")
if !userAuth.IsInvalid() {
// if no config file is being used lets grab the git server from the current directory
server, err := gits.GetGitServer("")
if err != nil {
fmt.Printf("WARNING: unable to get remote git repo server, %v\n", err)
server = "https://github.com"
}
config.Servers = []*auth.AuthServer{
{
Name: "Git",
URL: server,
Users: []*auth.UserAuth{&userAuth},
},
}
}
}
if len(config.Servers) == 0 {
config.Servers = []*auth.AuthServer{
{
Name: "GitHub",
URL: "https://github.com",
Kind: gits.KindGitHub,
Users: []*auth.UserAuth{},
},
}
}
return authConfigSvc, nil
}
func (f *factory) LoadPipelineSecrets(kind string) (*corev1.SecretList, error) {
kubeClient, curNs, err := f.CreateClient()
if err != nil {
return nil, fmt.Errorf("Failed to create a kuberntees client %s", err)
}
ns, _, err := kube.GetDevNamespace(kubeClient, curNs)
if err != nil {
return nil, fmt.Errorf("Failed to get the development environment %s", err)
}
// TODO use kind as a label selector...
return kubeClient.CoreV1().Secrets(ns).List(metav1.ListOptions{})
}
func (f *factory) mergePipeineSecrets(config *auth.AuthConfig, secretList *corev1.SecretList) {
}
func (f *factory) CreateAuthConfigService(fileName string) (auth.AuthConfigService, error) {
svc := auth.AuthConfigService{}
dir, err := util.ConfigDir()
if err != nil {
return svc, err
}
svc.FileName = filepath.Join(dir, fileName)
return svc, nil
}
func (f *factory) CreateJXClient() (*versioned.Clientset, string, error) {
config, err := f.createKubeConfig()
if err != nil {
return nil, "", err
}
kubeConfig, _, err := kube.LoadConfig()
if err != nil {
return nil, "", err
}
ns := kube.CurrentNamespace(kubeConfig)
client, err := versioned.NewForConfig(config)
if err != nil {
return nil, ns, err
}
return client, ns, err
}
func (f *factory) CreateApiExtensionsClient() (*apiextensionsclientset.Clientset, error) {
config, err := f.createKubeConfig()
if err != nil {
return nil, err
}
return apiextensionsclientset.NewForConfig(config)
}
func (f *factory) CreateMetricsClient() (*metricsclient.Clientset, error) {
config, err := f.createKubeConfig()
if err != nil {
return nil, err
}
return metricsclient.NewForConfig(config)
}
func (f *factory) CreateClient() (*kubernetes.Clientset, string, error) {
cfg, err := f.createKubeConfig()
if err != nil {
return nil, "", err
}
client, err := kubernetes.NewForConfig(cfg)
if err != nil {
return nil, "", err
}
if client == nil {
return nil, "", fmt.Errorf("Failed to create Kubernetes Client!")
}
ns := ""
config, _, err := kube.LoadConfig()
if err != nil {
return client, ns, err
}
ns = kube.CurrentNamespace(config)
// TODO allow namsepace to be specified as a CLI argument!
return client, ns, nil
}
var kubeConfigCache *string
func createKubeConfig() *string {
var kubeconfig *string
if kubeConfigCache != nil {
return kubeConfigCache
}
kubeconfenv := os.Getenv("KUBECONFIG")
if kubeconfenv != "" {
kubeconfig = &kubeconfenv
} else {
if home := util.HomeDir(); home != "" {
kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
} else {
kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
}
}
kubeConfigCache = kubeconfig
return kubeconfig
}
func (f *factory) createKubeConfig() (*rest.Config, error) {
kubeconfig := createKubeConfig()
var config *rest.Config
var err error
if kubeconfig != nil {
exists, err := util.FileExists(*kubeconfig)
if err == nil && exists {
// use the current context in kubeconfig
config, err = clientcmd.BuildConfigFromFlags("", *kubeconfig)
if err != nil {
return nil, err
}
}
}
if config == nil {
config, err = rest.InClusterConfig()
if err != nil {
return nil, err
}
}
user := f.getImpersonateUser()
if config != nil && user != "" && config.Impersonate.UserName == "" {
config.Impersonate.UserName = user
}
return config, nil
}
func (f *factory) getImpersonateUser() string {
user := f.impersonateUser
if user == "" {
// this is really only used for testing really
user = os.Getenv("JX_IMPERSONATE_USER")
}
return user
}
func (f *factory) CreateTable(out io.Writer) table.Table {
return table.CreateTable(os.Stdout)
}
// isInCDPIpeline we should only load the git / issue tracker API tokens if the current pod
// is in a pipeline and running as the jenkins service account
func (f *factory) isInCDPIpeline() bool {
// TODO should we let RBAC decide if we can see the Secrets in the dev namespace?
// or we should test if we are in the cluster and get the current ServiceAccount name?
return os.Getenv("BUILD_NUMBER") != ""
}