-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplugin.go
383 lines (332 loc) · 10.4 KB
/
plugin.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
// Package plasmactlmeta implements meta launchr plugin
package plasmactlmeta
import (
"context"
_ "embed"
"errors"
"fmt"
"log"
"net/http"
"sync"
"github.com/launchrctl/keyring"
"github.com/launchrctl/launchr"
"github.com/launchrctl/launchr/pkg/action"
)
//go:embed action.yaml
var actionYaml []byte
func init() {
launchr.RegisterPlugin(&Plugin{})
}
const (
tplAddCredentials = "execute '%s keyring:login --url=%s' to add credentials to keyring" //nolint:gosec
gitlabDomain = "https://projects.skilld.cloud"
repoDomain = "https://repositories.skilld.cloud"
internalRepoDomain = "http://repositories.interaction.svc.skilld:8081"
)
// Plugin is launchr plugin providing meta action.
type Plugin struct {
k keyring.Keyring
m action.Manager
app launchr.App
}
// PluginInfo implements launchr.Plugin interface.
func (p *Plugin) PluginInfo() launchr.PluginInfo {
return launchr.PluginInfo{
Weight: 1337,
}
}
// OnAppInit implements launchr.Plugin interface.
func (p *Plugin) OnAppInit(app launchr.App) error {
app.GetService(&p.k)
app.GetService(&p.m)
p.app = app
return nil
}
type metaOptions struct {
bin string
last bool
skipBump bool
ci bool
local bool
clean bool
debug bool
conflictsVerbosity bool
}
// DiscoverActions implements [launchr.ActionDiscoveryPlugin] interface.
func (p *Plugin) DiscoverActions(_ context.Context) ([]*action.Action, error) {
a := action.NewFromYAML("meta", actionYaml)
a.SetRuntime(action.NewFnRuntime(func(ctx context.Context, a *action.Action) error {
input := a.Input()
env := input.Arg("environment").(string)
tags := input.Arg("tags").(string)
v := launchr.Version()
options := metaOptions{
bin: v.Name,
last: input.Opt("last").(bool),
skipBump: input.Opt("skip-bump").(bool),
ci: input.Opt("ci").(bool),
local: input.Opt("local").(bool),
clean: input.Opt("clean").(bool),
debug: input.Opt("debug").(bool),
conflictsVerbosity: input.Opt("conflicts-verbosity").(bool),
}
return p.meta(ctx, env, tags, options)
}))
return []*action.Action{a}, nil
}
func (p *Plugin) meta(ctx context.Context, environment, tags string, options metaOptions) error {
if options.ci {
launchr.Term().Info().Println("--ci option is deprecated: builds are now done by default in CI")
}
launchr.Log().Info("arguments", "environment", environment, "tags", tags)
ansibleDebug := options.debug
if ansibleDebug {
launchr.Term().Info().Printfln("Ansible debug mode: %t", ansibleDebug)
}
var username string
var password string
// Commit unversioned changes if any
err := commitChangesIfAny()
if err != nil {
log.Fatalf("error: %v", err)
}
// Execute bump
if !options.skipBump {
err = p.executeAction(ctx, "bump", nil, action.InputParams{
"last": options.last,
})
if err != nil {
return fmt.Errorf("bump error: %w", err)
}
} else {
launchr.Term().Info().Println("--skip-bump option detected: Skipping bump execution")
}
launchr.Term().Printf("\n")
if options.local {
launchr.Term().Info().Println("Starting local build")
// Check if provided keyring pw is correct, since it will be used for multiple commands
// Check if publish command credentials are available in keyring and correct as stdin will not be available in goroutine
artifactsRepositoryDomain := repoDomain
var accessibilityCode int
if isURLAccessible(internalRepoDomain, &accessibilityCode) {
artifactsRepositoryDomain = internalRepoDomain
}
launchr.Term().Println("Checking keyring...")
keyringEntryName := "Artifacts repository"
err := validateCredentials(artifactsRepositoryDomain, options.bin, p.k, keyringEntryName)
if err != nil {
return err
}
// Commands executed sequentially
err = p.executeAction(ctx, "compose", nil, action.InputParams{
"skip-not-versioned": true,
"conflicts-verbosity": options.conflictsVerbosity,
"clean": options.clean,
})
if err != nil {
return fmt.Errorf("compose error: %w", err)
}
launchr.Term().Println()
err = p.executeAction(ctx, "bump", nil, action.InputParams{
"sync": true,
})
if err != nil {
return fmt.Errorf("sync error: %w", err)
}
// Commands executed in parallel
var packageErr error
var publishErr error
launchr.Term().Println()
wg := &sync.WaitGroup{}
wg.Add(1)
go func(wg *sync.WaitGroup) {
defer wg.Done()
packageErr = p.executeAction(ctx, "package", nil, nil)
if packageErr != nil {
return
}
publishErr = p.executeAction(ctx, "publish", nil, nil)
if publishErr != nil {
return
}
}(wg)
var deployErr error
wg.Add(1)
go func(wg *sync.WaitGroup) {
defer wg.Done()
deployErr = p.executeAction(ctx, "platform:deploy",
action.InputParams{
"environment": environment,
"tags": tags,
},
action.InputParams{
"debug": options.debug,
},
)
if deployErr != nil {
return
}
}(wg)
wg.Wait()
// Return all error messages, the first error code will be used as a result.
errJoin := errors.Join(packageErr, publishErr, deployErr)
if errJoin != nil {
return errJoin
}
} else {
launchr.Term().Info().Println("Starting CI build (now default behavior)")
// Push un-pushed commits if any
if err := pushBranchIfNotRemote(); err != nil {
return err
}
// Push un-pushed commits if any
if err := pushCommitsIfAny(); err != nil {
return err
}
launchr.Term().Info().Printfln("Getting %s credentials from keyring", gitlabDomain)
ci, save, err := getCredentials(gitlabDomain, username, password, p.k)
if err != nil {
return err
}
launchr.Term().Printfln("URL: %s", ci.URL)
launchr.Term().Printfln("Username: %s", ci.Username)
username = ci.Username
password = ci.Password
// Get OAuth token
accessToken, err := getOAuthToken(gitlabDomain, username, password)
if err != nil {
return fmt.Errorf("failed to get OAuth token: %w", err)
}
// Save gitlab credentials to keyring once we are sure that they are correct (after 1st successful api request)
if save {
err = p.k.Save()
launchr.Log().Debug("saving credentials to keyring", "url", gitlabDomain)
if err != nil {
launchr.Log().Error("error during saving keyring file", "error", err)
}
}
// Get branch name
branchName, err := getBranchName()
if err != nil {
return fmt.Errorf("failed to get branch name: %w", err)
}
// Get repo name
repoName, err := getRepoName()
if err != nil {
return fmt.Errorf("failed to get repo name: %w", err)
}
// Get project ID
projectID, err := getProjectID(gitlabDomain, username, password, accessToken, repoName)
if err != nil {
return fmt.Errorf("failed to get ID of project %q: %w", repoName, err)
}
// Trigger pipeline
pipelineID, err := triggerPipeline(gitlabDomain, username, password, accessToken, projectID, branchName, environment, tags, ansibleDebug)
if err != nil {
return fmt.Errorf("failed to trigger pipeline: %w", err)
}
// Get all jobs in the pipeline
jobs, err := getJobsInPipeline(gitlabDomain, username, password, accessToken, projectID, pipelineID)
if err != nil {
return fmt.Errorf("failed to retrieve jobs in pipeline: %w", err)
}
// Find the target job ID
var targetJobID int
for _, job := range jobs {
if job.Name == targetJobName {
targetJobID = job.ID
break
}
}
if targetJobID == 0 {
return fmt.Errorf("no %s job found in pipeline", targetJobName)
}
// Trigger the manual job
err = triggerManualJob(gitlabDomain, username, password, accessToken, projectID, targetJobID, pipelineID)
if err != nil {
return fmt.Errorf("failed to trigger manual job: %w", err)
}
}
return nil
}
func (p *Plugin) executeAction(ctx context.Context, id string, args action.InputParams, opts action.InputParams) error {
a, ok := p.m.Get(id)
if !ok {
return fmt.Errorf("action %q was not found", id)
}
err := a.SetInput(action.NewInput(a, args, opts, p.app.Streams()))
if err != nil {
return fmt.Errorf("failed to set input for action %q: %w", id, err)
}
err = a.Execute(ctx)
if err != nil {
return fmt.Errorf("error executing action %q: %w", id, err)
}
return nil
}
func validateCredentials(url, plasmaBinary string, k keyring.Keyring, keyringEntryName string) error {
if !k.Exists() {
launchr.Term().Error().Println("Keyring doesn't exist")
return fmt.Errorf(tplAddCredentials, plasmaBinary, url)
}
ci, err := k.GetForURL(url)
if len(ci.URL) != 0 && len(ci.Username) != 0 && len(ci.Password) != 0 {
launchr.Term().Success().Println("Keyring was unlocked successfully: %s credentials were found", keyringEntryName)
}
if err != nil {
if errors.Is(err, keyring.ErrEmptyPass) {
return err
} else if errors.Is(err, keyring.ErrNotFound) {
launchr.Term().Success().Println("Keyring was unlocked successfully: %s credentials were not found", keyringEntryName)
return fmt.Errorf(tplAddCredentials, plasmaBinary, url)
} else if !errors.Is(err, keyring.ErrNotFound) {
launchr.Log().Error("error", "error", err)
return errors.New("the keyring is malformed or wrong passphrase provided")
}
}
return nil
}
func getCredentials(url, username, password string, k keyring.Keyring) (keyring.CredentialsItem, bool, error) {
ci, err := k.GetForURL(url)
save := false
if err != nil {
if errors.Is(err, keyring.ErrEmptyPass) {
return ci, false, err
} else if !errors.Is(err, keyring.ErrNotFound) {
launchr.Log().Error("error", "error", err)
return ci, false, errors.New("the keyring is malformed or wrong passphrase provided")
}
ci = keyring.CredentialsItem{}
ci.URL = url
ci.Username = username
ci.Password = password
if ci.Username == "" || ci.Password == "" {
if ci.URL != "" {
launchr.Term().Info().Printfln("Please add login and password for URL - %s", ci.URL)
}
err = keyring.RequestCredentialsFromTty(&ci)
if err != nil {
return ci, false, err
}
}
err = k.AddItem(ci)
if err != nil {
return ci, false, err
}
save = true
}
return ci, save, nil
}
func isURLAccessible(url string, code *int) bool {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return false
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return false
}
defer resp.Body.Close()
*code = resp.StatusCode
return resp.StatusCode >= http.StatusOK && resp.StatusCode < http.StatusMultipleChoices
}