-
Notifications
You must be signed in to change notification settings - Fork 1
/
common_git.go
288 lines (265 loc) · 8.45 KB
/
common_git.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
package cmd
import (
"fmt"
"io/ioutil"
"time"
"github.com/jenkins-x/jx/pkg/auth"
"github.com/jenkins-x/jx/pkg/gits"
"github.com/jenkins-x/jx/pkg/issues"
"github.com/jenkins-x/jx/pkg/kube"
"github.com/jenkins-x/jx/pkg/log"
"github.com/jenkins-x/jx/pkg/util"
"github.com/spf13/cobra"
gitcfg "gopkg.in/src-d/go-git.v4/config"
"k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// createGitProvider creates a git from the given directory
func (o *CommonOptions) createGitProvider(dir string) (*gits.GitRepositoryInfo, gits.GitProvider, issues.IssueProvider, error) {
gitDir, gitConfDir, err := gits.FindGitConfigDir(dir)
if err != nil {
return nil, nil, nil, err
}
if gitDir == "" || gitConfDir == "" {
log.Warnf("No git directory could be found from dir %s\n", dir)
return nil, nil, nil, nil
}
gitUrl, err := gits.DiscoverUpstreamGitURL(gitConfDir)
if err != nil {
return nil, nil, nil, err
}
gitInfo, err := gits.ParseGitURL(gitUrl)
if err != nil {
return nil, nil, nil, err
}
authConfigSvc, err := o.CreateGitAuthConfigService()
if err != nil {
return gitInfo, nil, nil, err
}
gitKind, err := o.GitServerKind(gitInfo)
gitProvider, err := gitInfo.CreateProvider(authConfigSvc, gitKind)
if err != nil {
return gitInfo, gitProvider, nil, err
}
tracker, err := o.createIssueProvider(dir)
if err != nil {
return gitInfo, gitProvider, tracker, err
}
return gitInfo, gitProvider, tracker, nil
}
func (o *CommonOptions) updatePipelineGitCredentialsSecret(server *auth.AuthServer, userAuth *auth.UserAuth) (string, error) {
client, curNs, err := o.KubeClient()
if err != nil {
return "", err
}
ns, _, err := kube.GetDevNamespace(client, curNs)
if err != nil {
return "", err
}
options := metav1.GetOptions{}
serverName := server.Name
name := kube.ToValidName(kube.SecretJenkinsPipelineGitCredentials + server.Kind + "-" + serverName)
secrets := client.CoreV1().Secrets(ns)
secret, err := secrets.Get(name, options)
create := false
operation := "update"
labels := map[string]string{
kube.LabelCredentialsType: kube.ValueCredentialTypeUsernamePassword,
kube.LabelCreatedBy: kube.ValueCreatedByJX,
kube.LabelKind: kube.ValueKindGit,
kube.LabelServiceKind: server.Kind,
}
annotations := map[string]string{
kube.AnnotationCredentialsDescription: fmt.Sprintf("API Token for acccessing %s git service inside pipelines", server.URL),
kube.AnnotationURL: server.URL,
kube.AnnotationName: serverName,
}
if err != nil {
// lets create a new secret
create = true
operation = "create"
secret = &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Annotations: annotations,
Labels: labels,
},
Data: map[string][]byte{},
}
} else {
secret.Annotations = kube.MergeMaps(secret.Annotations, annotations)
secret.Labels = kube.MergeMaps(secret.Labels, labels)
}
if userAuth.Username != "" {
secret.Data["username"] = []byte(userAuth.Username)
}
if userAuth.ApiToken != "" {
secret.Data["password"] = []byte(userAuth.ApiToken)
}
if create {
_, err = secrets.Create(secret)
} else {
_, err = secrets.Update(secret)
}
if err != nil {
return name, fmt.Errorf("Failed to %s secret %s due to %s", operation, secret.Name, err)
}
cm, err := client.CoreV1().ConfigMaps(ns).Get(kube.ConfigMapJenkinsX, metav1.GetOptions{})
if err != nil {
return name, fmt.Errorf("Could not load Jenkins ConfigMap: %s", err)
}
updated, err := kube.UpdateJenkinsGitServers(cm, server, userAuth, name)
if err != nil {
return name, err
}
if updated {
_, err = client.CoreV1().ConfigMaps(ns).Update(cm)
if err != nil {
return name, fmt.Errorf("Failed to update Jenkins ConfigMap: %s", err)
}
log.Infof("Updated the Jenkins ConfigMap %s\n", kube.ConfigMapJenkinsX)
// wait a little bit to give k8s chance to sync the ConfigMap to the file system
time.Sleep(time.Second * 2)
// lets ensure that the git server + credential is in the Jenkins server configuration
jenk, err := o.JenkinsClient()
if err != nil {
return name, err
}
// TODO reload does not seem to reload the plugin content
//err = jenk.Reload()
err = jenk.SafeRestart()
if err != nil {
log.Warnf("Failed to safe restart Jenkins after configuration change %s\n", err)
} else {
log.Infoln("Safe Restarted Jenkins server")
// Let's wait 5 minutes for Jenkins to come back up.
// This is kinda gross, but it's just polling Jenkins every second for 5 minutes.
timeout := time.Duration(5) * time.Minute
start := int64(time.Now().Nanosecond())
for int64(time.Now().Nanosecond())-start < timeout.Nanoseconds() {
_, err := jenk.GetJobs()
if err == nil {
break
}
log.Infoln("Jenkins returned an error. Waiting for it to recover...")
time.Sleep(1 * time.Second)
}
}
}
return name, nil
}
func (o *CommonOptions) ensureGitServiceCRD(server *auth.AuthServer) error {
kind := server.Kind
if kind == "" || kind == "github" || server.URL == "" {
return nil
}
apisClient, err := o.Factory.CreateApiExtensionsClient()
if err != nil {
return err
}
err = kube.RegisterGitServiceCRD(apisClient)
if err != nil {
return err
}
jxClient, devNs, err := o.JXClientAndDevNamespace()
if err != nil {
return err
}
return kube.EnsureGitServiceExistsForHost(jxClient, devNs, kind, server.Name, server.URL, o.Out)
}
func (o *CommonOptions) discoverGitURL(gitConf string) (string, error) {
if gitConf == "" {
return "", fmt.Errorf("No GitConfDir defined!")
}
cfg := gitcfg.NewConfig()
data, err := ioutil.ReadFile(gitConf)
if err != nil {
return "", fmt.Errorf("Failed to load %s due to %s", gitConf, err)
}
err = cfg.Unmarshal(data)
if err != nil {
return "", fmt.Errorf("Failed to unmarshal %s due to %s", gitConf, err)
}
remotes := cfg.Remotes
if len(remotes) == 0 {
return "", nil
}
url := gits.GetRemoteUrl(cfg, "origin")
if url == "" {
url = gits.GetRemoteUrl(cfg, "upstream")
if url == "" {
url, err = o.pickRemoteURL(cfg)
if err != nil {
return "", err
}
}
}
return url, nil
}
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 (o *CommonOptions) GitServerKind(gitInfo *gits.GitRepositoryInfo) (string, error) {
return o.GitServerHostURLKind(gitInfo.HostURL())
}
func (o *CommonOptions) GitServerHostURLKind(hostURL string) (string, error) {
jxClient, devNs, err := o.JXClientAndDevNamespace()
if err != nil {
return "", err
}
kubeClient, _, err := o.KubeClient()
if err != nil {
return "", err
}
apisClient, err := o.CreateApiExtensionsClient()
if err != nil {
return "", err
}
err = kube.RegisterGitServiceCRD(apisClient)
if err != nil {
return "", err
}
kind, err := kube.GetGitServiceKind(jxClient, kubeClient, devNs, hostURL)
if err != nil {
return kind, err
}
if kind == "" {
if o.BatchMode {
return "", fmt.Errorf("No git server kind could be found for URL %s\nPlease try specify it via: jx create git server someKind %s", hostURL, hostURL)
}
kind, err = util.PickName(gits.KindGits, fmt.Sprintf("Pick what kind of git server is: %s", hostURL))
if err != nil {
return "", err
}
if kind == "" {
return "", fmt.Errorf("No git kind chosen!")
}
}
return kind, nil
}
// 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.CreateGitAuthConfigService()
if err != nil {
return nil, err
}
gitKind, err := o.GitServerKind(gitInfo)
if err != nil {
return nil, err
}
return gitInfo.PickOrCreateProvider(authConfigSvc, message, o.BatchMode, gitKind)
}
// gitProviderForURL returns a GitProvider for the given git server URL
func (o *CommonOptions) gitProviderForGitServerURL(gitServiceUrl string, gitKind string) (gits.GitProvider, error) {
authConfigSvc, err := o.CreateGitAuthConfigService()
if err != nil {
return nil, err
}
return gits.CreateProviderForURL(authConfigSvc, gitKind, gitServiceUrl)
}