-
Notifications
You must be signed in to change notification settings - Fork 0
/
import.go
414 lines (365 loc) · 12.6 KB
/
import.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
package main
import (
"crypto/tls"
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"github.com/iver-wharf/wharf-api-client-go/v2/pkg/model/request"
"github.com/iver-wharf/wharf-api-client-go/v2/pkg/model/response"
"github.com/iver-wharf/wharf-api-client-go/v2/pkg/wharfapi"
"github.com/iver-wharf/wharf-core/pkg/ginutil"
"github.com/xanzy/go-gitlab"
)
type importModule struct {
config *Config
}
func (m importModule) register(r gin.IRouter) {
r.POST("/import/gitlab", m.runGitLabHandler)
}
// runGitLabHandler godoc
// @Summary Import projects from gitlab or refresh existing one
// @Accept json
// @Produce json
// @Param import body main.Import _ "import object"
// @Success 201 "Successfully imported"
// @Failure 400 {object} problem.Response "Bad request"
// @Failure 401 {object} problem.Response "Unauthorized or missing jwt token"
// @Failure 502 {object} problem.Response "Bad gateway"
// @Router /gitlab [post]
func (m importModule) runGitLabHandler(c *gin.Context) {
http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
i := Import{}
err := c.ShouldBindJSON(&i)
if err != nil {
ginutil.WriteInvalidBindError(c, err,
"One or more parameters failed to parse when reading the request body for GitHub projects import/refresh")
return
}
wharfClient := wharfapi.Client{
AuthHeader: c.GetHeader("Authorization"),
APIURL: m.config.API.URL,
}
importer, ok := newGitLabImporterWritesProblem(c, &wharfClient, &i)
if !ok {
return
}
var detail string
if i.ProjectID == 0 {
switch i.whatToImport() {
case importProject:
err = importer.importProject(i.Group, i.Project)
detail = fmt.Sprintf("Unable to import GitLab project %q", i.Project)
case importGroup:
err = importer.importGroup(i.Group)
detail = fmt.Sprintf("Unable to import GitLab group %q", i.Group)
case importAllGroups:
err = importer.importAll()
detail = "Unable to import GitLab groups"
default:
err = fmt.Errorf("invalid import data")
detail = fmt.Sprintf("You need to specify either group, group and project, or neither. "+
"Specifying only project is invalid. "+
"Group=%q, Project=%q", i.Group, i.Project)
ginutil.WriteInvalidParamError(c, err, "Group or Project", detail)
return
}
} else {
err = importer.refreshProject(i.TokenID, i.ProviderID, i.ProjectID)
detail = fmt.Sprintf("Unable to refresh GitLab project %q", i.Project)
}
if err != nil {
ginutil.WriteAPIClientWriteError(c, err, detail)
return
}
c.Status(http.StatusCreated)
}
type gitLabImporter struct {
gitLabClient gitLabFetcher
wharfClient wharfClientAPIFetcher
mapper mapper
}
func newGitLabImporterWritesProblem(c *gin.Context, wharfClient wharfClientAPIFetcher, importData *Import) (*gitLabImporter, bool) {
token, ok := obtainTokenWritesProblem(c, wharfClient, importData)
if !ok {
return nil, false
}
provider, ok := obtainProviderWritesProblem(c, wharfClient, token.TokenID, importData)
if !ok {
return nil, false
}
gitLabClient, ok := getGitLabClientWritesProblem(c, token.Token, provider.URL)
if !ok {
return nil, false
}
return &gitLabImporter{
wharfClient: wharfClient,
gitLabClient: gitLabClient,
mapper: mapper{token.TokenID, provider.ProviderID},
}, true
}
func obtainTokenWritesProblem(c *gin.Context, wharfClient wharfClientAPIFetcher, importData *Import) (response.Token, bool) {
if importData.TokenID != 0 {
token, err := wharfClient.GetToken(importData.TokenID)
if err != nil {
ginutil.WriteAPIClientReadError(c, err,
fmt.Sprintf(
"Unable to get token by ID %d. Likely because of a failed request or malformed response.",
importData.TokenID))
} else if token.TokenID == 0 {
err = fmt.Errorf("token with ID %d not found", importData.TokenID)
ginutil.WriteAPIClientReadError(c, err,
fmt.Sprintf("Token with ID %d not found.", importData.TokenID))
}
if err != nil {
return response.Token{}, false
}
return token, true
}
search := wharfapi.TokenSearch{
UserName: &importData.User,
}
tokens, err := wharfClient.GetTokenList(search)
if err != nil {
ginutil.WriteAPIClientReadError(c, err,
"Unable to get token from the API. This issue might be temporary. Please try again later.")
log.Error().WithError(err).Message("Unable to get token.")
return response.Token{}, false
}
token, ok := findTokenByTokenString(tokens.List, importData.Token)
if !ok {
token, err = wharfClient.CreateToken(request.Token{Token: importData.Token, UserName: importData.User})
if authErr, ok := err.(*wharfapi.AuthError); ok {
c.Header("WWW-Authenticate", authErr.Realm)
ginutil.WriteUnauthorizedError(c, authErr,
"You are not allowed to use this functionality. Please make sure your token is correct.")
return response.Token{}, false
}
if err != nil {
ginutil.WriteAPIClientWriteError(c, err,
"Unable to post token to the API. This issue might be temporary. Please try again later.")
log.Error().WithError(err).Message("Unable to post token.")
return response.Token{}, false
}
}
log.Debug().WithUint("tokenId", token.TokenID).Message("Successfully created token.")
return token, true
}
func findTokenByTokenString(tokens []response.Token, tokenStr string) (response.Token, bool) {
token, ok := response.Token{}, false
for _, t := range tokens {
if t.Token == tokenStr {
token = t
ok = true
break
}
}
return token, ok
}
func obtainProviderWritesProblem(c *gin.Context, wharfClient wharfClientAPIFetcher, tokenID uint, importData *Import) (response.Provider, bool) {
if importData.ProviderID != 0 {
provider, err := wharfClient.GetProvider(importData.ProviderID)
if err != nil || provider.ProviderID == 0 {
ginutil.WriteAPIClientReadError(c, err,
fmt.Sprintf("Unable to get provider by ID %d.", importData.ProjectID))
log.Error().WithError(err).Message("Unable to get provider.")
return response.Provider{}, false
}
return provider, true
}
providerName := ProviderName
search := wharfapi.ProviderSearch{
Name: &providerName,
URL: &importData.URL,
}
var provider response.Provider
providers, err := wharfClient.GetProviderList(search)
if authErr, ok := err.(*wharfapi.AuthError); ok {
c.Header("WWW-Authenticate", authErr.Realm)
ginutil.WriteUnauthorizedError(c, authErr,
"You are not allowed to use this functionality. Please make sure your token is correct.")
return response.Provider{}, false
}
if err != nil {
ginutil.WriteAPIClientWriteError(c, err,
"Unable to get provider from the API. This issue might be temporary. Please try again later.")
log.Error().WithError(err).Message("Unable to get provider.")
return response.Provider{}, false
}
provider, ok := findProviderByTokenID(providers.List, tokenID)
if !ok {
provider, err = wharfClient.CreateProvider(request.Provider{
Name: ProviderName,
URL: importData.URL,
TokenID: tokenID})
if err != nil {
ginutil.WriteAPIClientWriteError(c, err,
"Unable to post provider to the API. This issue might be temporary. Please try again later.")
log.Error().WithError(err).Message("Unable to create provider.")
return response.Provider{}, false
}
}
log.Debug().
WithString("provider", string(provider.Name)).
WithString("providerUrl", provider.URL).
Message("Provider from DB.")
return provider, true
}
func findProviderByTokenID(providers []response.Provider, tokenID uint) (response.Provider, bool) {
provider, ok := response.Provider{}, false
for _, p := range providers {
if p.TokenID == tokenID {
provider = p
ok = true
break
}
}
return provider, ok
}
func (importer *gitLabImporter) importProject(groupName string, projectName string) error {
gitLabProject, err := importer.gitLabClient.getProject(groupName, projectName)
if err != nil {
log.Error().WithError(err).Message("Failed to get project.")
return err
}
wharfProject, err := importer.postProject(*gitLabProject)
if err != nil {
log.Error().
WithError(err).
WithString("gitLabProject", gitLabProject.NameWithNamespace).
Message("Failed to create project.")
return err
}
err = importer.importBranches(wharfProject.ProjectID, gitLabProject.ID)
if err != nil {
log.Error().
WithString("gitLabProject", gitLabProject.NameWithNamespace).
WithStringf("wharfProject", "%s/%s", wharfProject.GroupName, wharfProject.Name).
Message("Unable to import branches.")
return err
}
return nil
}
func (importer *gitLabImporter) importGroup(groupName string) error {
return importPaginatedProjects(func(page int) ([]*gitlab.Project, gitLabPaging, error) {
return importer.gitLabClient.listProjectsFromGroup(groupName, page)
}, importer.importProjects)
}
func (importer *gitLabImporter) importAll() error {
return importPaginatedProjects(importer.gitLabClient.listProjects, importer.importProjects)
}
func (importer gitLabImporter) importProjects(projects []*gitlab.Project) string {
var errMessage string
for _, project := range projects {
wharfProject, err := importer.postProject(*project)
if err != nil {
log.Error().
WithError(err).
WithString("gitLabProject", project.NameWithNamespace).
Message("Failed to create project")
errMessage += fmt.Sprintf("proj: %v err: %+v \n", project, err)
continue
}
err = importer.importBranches(wharfProject.ProjectID, project.ID)
if err != nil {
log.Error().
WithString("gitLabProject", project.NameWithNamespace).
WithStringf("wharfProject", "%s/%s", wharfProject.GroupName, wharfProject.Name).
Message("Unable to import branches.")
errMessage += fmt.Sprintf("proj: %v err: %+v \n", wharfProject, err)
}
}
return errMessage
}
func (importer gitLabImporter) refreshProject(tokenID, providerID, projectID uint) error {
proj, err := importer.wharfClient.GetProject(projectID)
if err != nil {
log.Error().
WithUint("projectID", projectID).
Message("Unable to fetch project from Wharf database.")
return err
}
// TODO: Use remote project ID if available.
gitLabProject, err := importer.gitLabClient.getProject(proj.GroupName, proj.Name)
if err != nil {
log.Error().
WithStringf("wharfProject", "%s/%s", proj.GroupName, proj.Name).
Message("Unable to get project from GitLab.")
return err
}
buildDef, err := importer.gitLabClient.getBuildDefinitionIfExists(gitLabProject.ID, gitLabProject.DefaultBranch)
if err != nil {
return err
}
groupName := ""
if gitLabProject.Namespace != nil {
groupName = gitLabProject.Namespace.FullPath
}
_, err = importer.wharfClient.UpdateProject(projectID, request.ProjectUpdate{
Name: gitLabProject.Name,
BuildDefinition: buildDef,
Description: gitLabProject.Description,
AvatarURL: gitLabProject.AvatarURL,
GitURL: gitLabProject.SSHURLToRepo,
TokenID: tokenID,
ProviderID: providerID,
GroupName: groupName,
})
if err == nil {
importer.refreshBranches(projectID, gitLabProject.ID)
}
return err
}
func (importer gitLabImporter) postProject(gitLabProject gitlab.Project) (response.Project, error) {
buildDef, err := importer.gitLabClient.getBuildDefinitionIfExists(gitLabProject.ID, gitLabProject.DefaultBranch)
if err != nil {
return response.Project{}, err
}
wharfProject := importer.mapper.mapProjectToWharfEntity(gitLabProject, buildDef)
dbProject, err := importer.wharfClient.CreateProject(wharfProject)
if err != nil {
log.Error().WithError(err).Message("Unable to create project.")
return response.Project{}, err
}
return dbProject, nil
}
func (importer gitLabImporter) importBranches(wharfProjectID uint, gitLabProjectID int) error {
errMessage := ""
page := 0
for page >= 0 {
branches, paging, err := importer.gitLabClient.getBranches(gitLabProjectID, page)
if err != nil {
log.Error().WithError(err).Message("Failed to get branches.")
return err
}
for _, branch := range branches {
b := importer.mapper.mapBranchToWharfEntity(*branch)
_, err := importer.wharfClient.CreateProjectBranch(wharfProjectID, b)
if err != nil {
log.Error().WithError(err).Message("Failed to reset branches.")
errMessage += err.Error()
}
}
page = paging.next()
}
if errMessage != "" {
return fmt.Errorf(errMessage)
}
return nil
}
func (importer gitLabImporter) refreshBranches(wharfProjectID uint, gitLabProjectID int) error {
page := 0
var allBranches []request.Branch
for page >= 0 {
branches, paging, err := importer.gitLabClient.getBranches(gitLabProjectID, page)
if err != nil {
log.Error().WithError(err).Message("Failed to get branches.")
return err
}
for _, branch := range branches {
allBranches = append(allBranches, importer.mapper.mapBranchToWharfEntity(*branch))
}
page = paging.next()
}
_, err := importer.wharfClient.UpdateProjectBranchList(wharfProjectID, allBranches)
return err
}