forked from jenkins-x/jx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
factory.go
452 lines (392 loc) · 12.6 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
package cmd
import (
"flag"
"fmt"
"io"
"net/url"
"os"
"path/filepath"
"github.com/heptio/sonobuoy/pkg/client"
"github.com/jenkins-x/jx/pkg/jenkins"
"github.com/jenkins-x/jx/pkg/kube"
"github.com/jenkins-x/jx/pkg/table"
"github.com/pkg/errors"
"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"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
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
_ "k8s.io/client-go/plugin/pkg/client/auth"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
const (
AddonAuthConfigFile = "addonAuth.yaml"
JenkinsAuthConfigFile = "jenkinsAuth.yaml"
IssuesAuthConfigFile = "issuesAuth.yaml"
ChatAuthConfigFile = "chatAuth.yaml"
GitAuthConfigFile = "gitAuth.yaml"
ChartmuseumAuthConfigFile = "chartmuseumAuth.yaml"
)
type Factory interface {
CreateJenkinsClient(kubeClient kubernetes.Interface, ns string) (*gojenkins.Jenkins, error)
GetJenkinsURL(kubeClient kubernetes.Interface, ns string) (string, error)
CreateAuthConfigService(fileName string) (auth.AuthConfigService, error)
CreateJenkinsAuthConfigService(kubernetes.Interface, string) (auth.AuthConfigService, error)
CreateChartmuseumAuthConfigService() (auth.AuthConfigService, error)
CreateIssueTrackerAuthConfigService(secrets *corev1.SecretList) (auth.AuthConfigService, error)
CreateChatAuthConfigService(secrets *corev1.SecretList) (auth.AuthConfigService, error)
CreateAddonAuthConfigService(secrets *corev1.SecretList) (auth.AuthConfigService, error)
CreateClient() (kubernetes.Interface, string, error)
CreateKubeConfig() (*rest.Config, error)
CreateJXClient() (versioned.Interface, string, error)
CreateApiExtensionsClient() (apiextensionsclientset.Interface, error)
CreateMetricsClient() (*metricsclient.Clientset, error)
CreateComplianceClient() (*client.SonobuoyClient, error)
CreateTable(out io.Writer) table.Table
SetBatch(batch bool)
ImpersonateUser(user string) Factory
IsInCluster() bool
IsInCDPIpeline() bool
AuthMergePipelineSecrets(config *auth.AuthConfig, secrets *corev1.SecretList, kind string, isCDPipeline bool) error
}
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(kubeClient kubernetes.Interface, ns string) (*gojenkins.Jenkins, error) {
svc, err := f.CreateJenkinsAuthConfigService(kubeClient, ns)
if err != nil {
return nil, err
}
url, err := f.GetJenkinsURL(kubeClient, ns)
if err != nil {
return nil, fmt.Errorf("%s. Try switching to the Development Tools environment via: jx env dev", err)
}
return jenkins.GetJenkinsClient(url, f.Batch, &svc)
}
func (f *factory) GetJenkinsURL(kubeClient kubernetes.Interface, ns string) (string, error) {
// lets find the kubernetes service
client, ns, err := f.CreateClient()
if err != nil {
return "", errors.Wrap(err, "failed to create the kube client")
}
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 "", errors.Wrapf(err, "failed to get the dev namespace from '%s' namespace")
}
if realNS != ns {
url, err = kube.FindServiceURL(client, realNS, kube.ServiceJenkins)
if err != nil {
return "", fmt.Errorf("%s in namespaces %s and %s", err, realNS, ns)
}
return url, nil
}
}
if err != nil {
return "", fmt.Errorf("%s in namespace %s", err, ns)
}
return url, err
}
func (f *factory) CreateJenkinsAuthConfigService(c kubernetes.Interface, ns string) (auth.AuthConfigService, error) {
authConfigSvc, err := f.CreateAuthConfigService(JenkinsAuthConfigFile)
if err != nil {
return authConfigSvc, err
}
config, err := authConfigSvc.LoadConfig()
if err != nil {
return authConfigSvc, err
}
if len(config.Servers) == 0 {
s, err := c.CoreV1().Secrets(ns).Get(kube.SecretJenkins, metav1.GetOptions{})
if err != nil {
return authConfigSvc, err
}
userAuth := auth.UserAuth{
Username: "admin",
ApiToken: string(s.Data[kube.JenkinsAdminApiToken]),
}
svc, err := c.CoreV1().Services(ns).Get(kube.ServiceJenkins, metav1.GetOptions{})
if err != nil {
return authConfigSvc, err
}
svcURL := kube.GetServiceURL(svc)
if svcURL == "" {
return authConfigSvc, fmt.Errorf("unable to find external URL annotation on service %s in namespace %s", svc.Name, ns)
}
u, err := url.Parse(svcURL)
if err != nil {
return authConfigSvc, err
}
if !userAuth.IsInvalid() {
config.Servers = []*auth.AuthServer{
{
Name: u.Host,
URL: svcURL,
Users: []*auth.UserAuth{&userAuth},
},
}
}
}
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) CreateAddonAuthConfigService(secrets *corev1.SecretList) (auth.AuthConfigService, error) {
authConfigSvc, err := f.CreateAuthConfigService(AddonAuthConfigFile)
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) error {
if config == nil || secrets == nil {
return nil
}
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)
}
}
}
}
}
}
}
}
return nil
}
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.Interface, 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.Interface, 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.Interface, 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
}
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) {
masterUrl := ""
kubeConfigEnv := os.Getenv("KUBECONFIG")
if kubeConfigEnv != "" {
pathList := filepath.SplitList(kubeConfigEnv)
return clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
&clientcmd.ClientConfigLoadingRules{Precedence: pathList},
&clientcmd.ConfigOverrides{ClusterInfo: clientcmdapi.Cluster{Server: masterUrl}}).ClientConfig()
}
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(masterUrl, *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") != ""
}
// function to tell if we are running incluster
func (f *factory) IsInCluster() bool {
_, err := rest.InClusterConfig()
if err != nil {
return false
}
return true
}
// CreateComplianceClient creates a new Sonobuoy compliance client
func (f *factory) CreateComplianceClient() (*client.SonobuoyClient, error) {
config, err := f.CreateKubeConfig()
if err != nil {
return nil, errors.Wrap(err, "compliance client failed to load the Kubernetes configuration")
}
return client.NewSonobuoyClient(config, nil)
}