forked from jenkins-x/jx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.go
342 lines (313 loc) · 9.32 KB
/
common.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
package cmd
import (
"fmt"
"io"
"net/url"
"os/exec"
"strings"
"os"
"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/gits"
"github.com/jenkins-x/jx/pkg/jx/cmd/table"
cmdutil "github.com/jenkins-x/jx/pkg/jx/cmd/util"
"github.com/jenkins-x/jx/pkg/kube"
"github.com/jenkins-x/jx/pkg/util"
"github.com/spf13/cobra"
"k8s.io/client-go/kubernetes"
)
const (
optionServerName = "name"
optionServerURL = "url"
)
// CommonOptions contains common options and helper methods
type CommonOptions struct {
Factory cmdutil.Factory
Out io.Writer
Err io.Writer
Cmd *cobra.Command
Args []string
BatchMode bool
// common cached clients
kubeClient *kubernetes.Clientset
currentNamespace string
jxClient *versioned.Clientset
jenkinsClient *gojenkins.Jenkins
}
type ServerFlags struct {
ServerName string
ServerURL string
}
func (f *ServerFlags) IsEmpty() bool {
return f.ServerName == "" && f.ServerURL == ""
}
func addGitRepoOptionsArguments(cmd *cobra.Command, repositoryOptions *gits.GitRepositoryOptions) {
cmd.Flags().StringVarP(&repositoryOptions.ServerURL, "git-provider-url", "", "", "The git server URL to create new git repositories inside")
cmd.Flags().StringVarP(&repositoryOptions.Username, "git-username", "", "", "The git username to use for creating new git repositories")
cmd.Flags().StringVarP(&repositoryOptions.ApiToken, "git-api-token", "", "", "The git API token to use for creating new git repositories")
}
func (c *CommonOptions) CreateTable() table.Table {
return c.Factory.CreateTable(c.Out)
}
func (c *CommonOptions) Printf(format string, a ...interface{}) (n int, err error) {
return fmt.Fprintf(c.Out, format, a...)
}
func (o *CommonOptions) runCommandFromDir(dir, name string, args ...string) error {
e := exec.Command(name, args...)
if dir != "" {
e.Dir = dir
}
e.Stdout = o.Out
e.Stderr = o.Err
err := e.Run()
if err != nil {
o.Printf("Error: Command failed %s %s\n", name, strings.Join(args, " "))
}
return err
}
func (o *CommonOptions) runCommand(name string, args ...string) error {
e := exec.Command(name, args...)
e.Stdout = o.Out
e.Stderr = o.Err
err := e.Run()
if err != nil {
o.Printf("Error: Command failed %s %s\n", name, strings.Join(args, " "))
}
return err
}
func (o *CommonOptions) runCommandInteractive(interactive bool, name string, args ...string) error {
e := exec.Command(name, args...)
e.Stdout = o.Out
e.Stderr = o.Err
if interactive {
e.Stdin = os.Stdin
}
err := e.Run()
if err != nil {
o.Printf("Error: Command failed %s %s\n", name, strings.Join(args, " "))
}
return err
}
// getCommandOutput evaluates the given command and returns the trimmed output
func (o *CommonOptions) getCommandOutput(dir string, name string, args ...string) (string, error) {
e := exec.Command(name, args...)
if dir != "" {
e.Dir = dir
}
data, err := e.CombinedOutput()
text := string(data)
text = strings.TrimSpace(text)
return text, err
}
func (options *CommonOptions) addCommonFlags(cmd *cobra.Command) {
cmd.Flags().BoolVarP(&options.BatchMode, "batch-mode", "b", false, "In batch mode the command never prompts for user input")
options.Cmd = cmd
}
func (o *CommonOptions) KubeClient() (*kubernetes.Clientset, string, error) {
if o.kubeClient == nil {
kubeClient, currentNs, err := o.Factory.CreateClient()
if err != nil {
return nil, "", err
}
o.kubeClient = kubeClient
o.currentNamespace = currentNs
}
return o.kubeClient, o.currentNamespace, nil
}
func (o *CommonOptions) JXClient() (*versioned.Clientset, string, error) {
if o.jxClient == nil {
jxClient, ns, err := o.Factory.CreateJXClient()
if err != nil {
return nil, ns, err
}
o.jxClient = jxClient
if o.currentNamespace == "" {
o.currentNamespace = ns
}
}
return o.jxClient, o.currentNamespace, nil
}
func (o *CommonOptions) JenkinsClient() (*gojenkins.Jenkins, error) {
if o.jenkinsClient == nil {
jenkins, err := o.Factory.CreateJenkinsClient()
if err != nil {
return nil, err
}
o.jenkinsClient = jenkins
}
return o.jenkinsClient, nil
}
func (o *CommonOptions) TeamAndEnvironmentNames() (string, string, error) {
kubeClient, currentNs, err := o.KubeClient()
if err != nil {
return "", "", err
}
return kube.GetDevNamespace(kubeClient, currentNs)
}
// warnf generates a warning
func (o *CommonOptions) warnf(format string, a ...interface{}) {
o.Printf(util.ColorWarning("WARNING: "+format), a...)
}
// gitProviderForURL returns a GitProvider for the given git URL
func (o *CommonOptions) gitProviderForURL(gitURL string, message string) (gits.GitProvider, error) {
gitInfo, err := gits.ParseGitURL(gitURL)
if err != nil {
return nil, err
}
authConfigSvc, err := o.Factory.CreateGitAuthConfigService()
if err != nil {
return nil, err
}
return gitInfo.PickOrCreateProvider(authConfigSvc, message)
}
func (o *ServerFlags) addGitServerFlags(cmd *cobra.Command) {
cmd.Flags().StringVarP(&o.ServerName, optionServerName, "n", "", "The name of the git server to add a user")
cmd.Flags().StringVarP(&o.ServerName, optionServerURL, "u", "", "The URL of the git server to add a user")
}
// findGitServer finds the git server from the given flags or returns an error
func (o *CommonOptions) findGitServer(config *auth.AuthConfig, serverFlags *ServerFlags) (*auth.AuthServer, error) {
return o.findServer(config, serverFlags, "git server", "Try creating one via: jx create git server")
}
func (o *CommonOptions) findServer(config *auth.AuthConfig, serverFlags *ServerFlags, kind string, missingServerDescription string) (*auth.AuthServer, error) {
var server *auth.AuthServer
if serverFlags.ServerURL != "" {
server = config.GetServer(serverFlags.ServerURL)
if server == nil {
return nil, util.InvalidOption(optionServerURL, serverFlags.ServerURL, config.GetServerURLs())
}
}
if server == nil && serverFlags.ServerName != "" {
server = config.GetServerByName(serverFlags.ServerName)
if server == nil {
return nil, util.InvalidOption(optionServerName, serverFlags.ServerName, config.GetServerNames())
}
}
if server == nil {
name := config.CurrentServer
if name != "" && o.BatchMode {
server = config.GetServerByName(name)
if server == nil {
o.warnf("Current server %s no longer exists\n", name)
}
}
}
if server == nil && len(config.Servers) == 1 {
server = config.Servers[0]
}
if server == nil && len(config.Servers) > 1 {
if o.BatchMode {
return nil, fmt.Errorf("Multiple servers found. Please specify one via the %s option", optionServerName)
}
defaultServerName := ""
if config.CurrentServer != "" {
s := config.GetServer(config.CurrentServer)
if s != nil {
defaultServerName = s.Name
}
}
name, err := util.PickNameWithDefault(config.GetServerNames(), "Pick server to use: ", defaultServerName)
if err != nil {
return nil, err
}
server = config.GetServerByName(name)
if server == nil {
return nil, fmt.Errorf("Could not find the server for name %s", name)
}
}
if server == nil {
return nil, fmt.Errorf("Could not find a %s. %s", kind, missingServerDescription)
}
return server, nil
}
func (o *CommonOptions) findService(name string) (string, error) {
f := o.Factory
client, ns, err := f.CreateClient()
if err != nil {
return "", err
}
devNs, _, err := kube.GetDevNamespace(client, ns)
if err != nil {
return "", err
}
url, err := kube.FindServiceURL(client, ns, name)
if url == "" {
url, err = kube.FindServiceURL(client, devNs, name)
}
if url == "" {
names, err := kube.GetServiceNames(client, ns, name)
if err != nil {
return "", err
}
if len(names) > 1 {
name, err = util.PickName(names, "Pick service to open: ")
if err != nil {
return "", err
}
if name != "" {
url, err = kube.FindServiceURL(client, ns, name)
}
} else if len(names) == 1 {
// must have been a filter
url, err = kube.FindServiceURL(client, ns, names[0])
}
if url == "" {
return "", fmt.Errorf("Could not find URL for service %s in namespace %s", name, ns)
}
}
return url, nil
}
func (o *CommonOptions) registerLocalHelmRepo(repoName string) error {
if repoName == "" {
repoName = kube.LocalHelmRepoName
}
// TODO we should use the auth package to keep a list of server login/pwds
username := "admin"
password := "admin"
// lets check if we have a local helm repository
client, ns, err := o.Factory.CreateClient()
if err != nil {
return err
}
u, err := kube.FindServiceURL(client, ns, kube.ServiceChartMuseum)
if err != nil {
return err
}
u2, err := url.Parse(u)
if err != nil {
return err
}
if u2.User == nil {
u2.User = url.UserPassword(username, password)
}
helmUrl := u2.String()
// lets check if we already have the helm repo installed or if we need to add it or remove + add it
text, err := o.getCommandOutput("", "helm", "repo", "list")
if err != nil {
return err
}
lines := strings.Split(text, "\n")
remove := false
for _, line := range lines {
t := strings.TrimSpace(line)
if t != "" {
fields := strings.Fields(t)
if len(fields) > 1 {
if fields[0] == repoName {
if fields[1] == helmUrl {
return nil
} else {
remove = true
}
}
}
}
}
if remove {
err = o.runCommand("helm", "repo", "remove", repoName)
if err != nil {
return err
}
}
return o.runCommand("helm", "repo", "add", repoName, helmUrl)
}