-
Notifications
You must be signed in to change notification settings - Fork 141
/
quickstart.go
446 lines (365 loc) · 10.9 KB
/
quickstart.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
// Copyright 2024 The PipeCD Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package quickstart
import (
"bytes"
"context"
"errors"
"fmt"
"html/template"
"os"
"os/exec"
"path"
"runtime"
"strings"
"sync"
"time"
"github.com/manifoldco/promptui"
"github.com/spf13/cobra"
"github.com/pipe-cd/pipecd/pkg/backoff"
"github.com/pipe-cd/pipecd/pkg/cli"
"github.com/pipe-cd/pipecd/pkg/version"
)
const (
defaultHelmVersion = "3.8.2"
helmControlPlaneReleaseName = "pipecd"
helmPipedReleaseName = "piped"
helmChartControlPlaneRepoName = "oci://ghcr.io/pipe-cd/chart/pipecd"
helmChartPipedRepoName = "oci://ghcr.io/pipe-cd/chart/piped"
helmQuickstartValueRemotePath = "https://raw.githubusercontent.com/pipe-cd/pipecd/%s/quickstart/control-plane-values.yaml"
pipecdDefaultNamespace = "pipecd"
controlPlaneLocalhost = "http://localhost:8080/settings/piped?project=quickstart"
pipedIDLabel = "ID"
pipedKeyLabel = "Key"
pipedGitRemoteRepo = "GitRemoteRepo"
deploymentReadyRetryTime = 3
deploymentReadyRetryDuration = time.Minute
)
type command struct {
version string
toolsDir string
namespace string
uninstall bool
}
func NewCommand() *cobra.Command {
home, err := os.UserHomeDir()
if err != nil {
panic(fmt.Sprintf("failed to detect the current user's home directory: %v", err))
}
defaultToolsDir := path.Join(home, ".pipectl", "tools")
if err = os.MkdirAll(defaultToolsDir, 0755); err != nil {
panic(fmt.Sprintf("failed to prepare tools dir: %v", err))
}
c := &command{
version: version.Get().Version,
toolsDir: defaultToolsDir,
namespace: pipecdDefaultNamespace,
}
cmd := &cobra.Command{
Use: "quickstart",
Short: "Quick prepare PipeCD control plane in quickstart mode.",
Long: "Quick prepare PipeCD control plane in quickstart mode.\nTo install PipeCD control plane for real-life usage, please read the docs: https://pipecd.dev/docs/installation/install-controlplane",
RunE: cli.WithContext(c.run),
}
cmd.Flags().StringVar(&c.version, "version", c.version, "The Control Plane version. Default is the version of pipectl.")
cmd.Flags().StringVar(&c.toolsDir, "tools-dir", c.toolsDir, "The path to directory where to install tools such as helm.")
cmd.Flags().StringVar(&c.namespace, "namespace", c.namespace, "The Kubernetes cluster namespace where to install Control Plane.")
cmd.Flags().BoolVar(&c.uninstall, "uninstall", c.uninstall, "Uninstall the quickstart mode installed PipeCD control plane.")
return cmd
}
func (c *command) run(ctx context.Context, input cli.Input) error {
helm, err := c.getHelm(ctx)
if err != nil {
return fmt.Errorf("failed to prepare required tools (helm) for installation: %v", err)
}
if c.uninstall {
return c.uninstallAll(ctx, helm, input)
}
if err = c.installControlPlane(ctx, helm, input); err != nil {
input.Logger.Error("Failed to install PipeCD control plane!!")
return err
}
var wg sync.WaitGroup
if err = c.exposeService(ctx, &wg); err != nil {
input.Logger.Error("Failed to expose PipeCD control plane service!!")
return err
}
if err = c.installPiped(ctx, helm, input); err != nil {
input.Logger.Error("Failed to install piped!!")
return err
}
input.Logger.Info("\nPipeCD console is ready at http://localhost:8080/")
// Wait until users hit SIG_KILL.
wg.Wait()
return nil
}
func (c *command) installControlPlane(ctx context.Context, helm string, input cli.Input) error {
input.Logger.Info("Installing the controlplane in quickstart mode...")
args := []string{
"upgrade",
"--install",
helmControlPlaneReleaseName,
helmChartControlPlaneRepoName,
"--version",
c.version,
"--namespace",
c.namespace,
"--create-namespace",
"--values",
fmt.Sprintf(helmQuickstartValueRemotePath, c.version),
"--set",
fmt.Sprintf("mysql.image=%s", selectMySQLImage()),
}
var stderr, stdout bytes.Buffer
cmd := exec.CommandContext(ctx, helm, args...)
cmd.Stderr = &stderr
cmd.Stdout = &stdout
if err := cmd.Run(); err != nil {
return fmt.Errorf("%w: %s", err, stderr.String())
}
input.Logger.Info(stdout.String())
input.Logger.Info("Intalled the controlplane successfully!")
return nil
}
func (c *command) installPiped(ctx context.Context, helm string, input cli.Input) error {
input.Logger.Info("\nInstalling the piped for quickstart...")
input.Logger.Info("\nOpenning PipeCD control plane at http://localhost:8080/\nPlease login using the following account:\n- Username: hello-pipecd\n- Password: hello-pipecd\nFor more information refer to https://pipecd.dev/docs/quickstart/\n")
if err := openbrowser(controlPlaneLocalhost); err != nil {
return fmt.Errorf("failed to open PipeCD control plane: %w", err)
}
input.Logger.Info("Fill up your registered Piped information:")
pipedID := getPromptInput(pipedIDLabel)
pipedKey := getPromptInput(pipedKeyLabel)
sourceRepo := getPromptInput(pipedGitRemoteRepo)
args := []string{
"upgrade",
"--install",
helmPipedReleaseName,
helmChartPipedRepoName,
"--version",
c.version,
"--namespace",
c.namespace,
"--set",
"quickstart.enabled=true",
"--set",
fmt.Sprintf("quickstart.pipedId=%s", pipedID),
"--set",
fmt.Sprintf("secret.data.piped-key=%s", pipedKey),
"--set",
fmt.Sprintf("quickstart.gitRepoRemote=%s", sourceRepo),
}
var stderr, stdout bytes.Buffer
cmd := exec.CommandContext(ctx, helm, args...)
cmd.Stderr = &stderr
cmd.Stdout = &stdout
if err := cmd.Run(); err != nil {
return fmt.Errorf("%w: %s", err, stderr.String())
}
input.Logger.Info(stdout.String())
input.Logger.Info("Intalled the piped successfully!")
return nil
}
func (c *command) exposeService(ctx context.Context, wg *sync.WaitGroup) error {
kubectl, err := c.getKubectl()
if err != nil {
return fmt.Errorf("failed to prepare required tool (kubectl) for installation: %v", err)
}
// Wait the control plane service to be ready.
args := []string{
"rollout",
"status",
"deploy/pipecd-server",
"-n",
c.namespace,
}
var stdout bytes.Buffer
cmd := exec.CommandContext(ctx, kubectl, args...)
cmd.Stdout = &stdout
retry := backoff.NewRetry(deploymentReadyRetryTime, backoff.NewConstant(deploymentReadyRetryDuration))
var serverIsReady bool
for retry.WaitNext(ctx) {
cmd.Run()
if strings.Contains(stdout.String(), "successfully rolled out") {
serverIsReady = true
break
}
}
if !serverIsReady {
return fmt.Errorf("failed while waiting for server to be ready")
}
// Expose the PipeCD control plane to localhost:8080.
args = []string{
"port-forward",
"svc/pipecd",
"8080",
"-n",
c.namespace,
}
var stderr bytes.Buffer
cmd = exec.CommandContext(ctx, kubectl, args...)
cmd.Stderr = &stderr
wg.Add(1)
go func() {
cmd.Run()
defer wg.Done()
}()
return nil
}
func getPromptInput(label string) string {
validate := func(input string) error {
switch label {
case pipedIDLabel:
if len(input) != 36 {
return fmt.Errorf("invalid ID")
}
case pipedKeyLabel:
if len(input) != 50 {
return fmt.Errorf("invalid Key")
}
default:
if len(input) == 0 {
return fmt.Errorf("missing value: %s", label)
}
}
return nil
}
prompt := promptui.Prompt{
Label: label,
Validate: validate,
}
result, err := prompt.Run()
if err != nil {
return ""
}
return result
}
func openbrowser(url string) error {
var err error
switch runtime.GOOS {
case "linux":
err = exec.Command("xdg-open", url).Start()
case "darwin":
err = exec.Command("open", url).Start()
default:
err = fmt.Errorf("unsupported platform: %s", runtime.GOOS)
}
return err
}
func selectMySQLImage() string {
var mysqlImage string
switch runtime.GOARCH {
case "amd64":
mysqlImage = "mysql"
case "arm64":
mysqlImage = "arm64v8/mysql"
default:
mysqlImage = "mysql"
}
return mysqlImage
}
func (c *command) uninstallAll(ctx context.Context, helm string, input cli.Input) error {
input.Logger.Info("Uninstalling PipeCD components...")
var stderr, stdout bytes.Buffer
// Uninstall PipeCD control plane.
args := []string{
"uninstall",
helmControlPlaneReleaseName,
"--namespace",
c.namespace,
}
cmd := exec.CommandContext(ctx, helm, args...)
cmd.Stderr = &stderr
cmd.Stdout = &stdout
if err := cmd.Run(); err != nil {
return fmt.Errorf("%w: %s", err, stderr.String())
}
// Uninstall Piped.
args = []string{
"uninstall",
helmPipedReleaseName,
"--namespace",
c.namespace,
}
cmd = exec.CommandContext(ctx, helm, args...)
cmd.Stderr = &stderr
cmd.Stdout = &stdout
if err := cmd.Run(); err != nil {
return fmt.Errorf("%w: %s", err, stderr.String())
}
input.Logger.Info(stdout.String())
input.Logger.Info("Uninstalled the PipeCD components successfully!")
return nil
}
func (c *command) getKubectl() (string, error) {
binName := "kubectl"
fi, err := os.Stat(path.Join(c.toolsDir, binName))
if err != nil && !os.IsNotExist(err) {
return "", err
}
if fi != nil {
return path.Join(c.toolsDir, binName), nil
}
epath, err := exec.LookPath(binName)
if err != nil && !errors.Is(err, exec.ErrNotFound) {
return "", err
}
if epath != "" {
return epath, nil
}
return "", fmt.Errorf("%s not found", binName)
}
// getHelm finds and returns helm executable binary in the following priority:
// 1. pre-installed in command specified toolsDir (default is $HOME/.pipectl/tools)
// 2. $PATH
// 3. install new helm to command specified toolsDir
func (c *command) getHelm(ctx context.Context) (string, error) {
binName := "helm"
fi, err := os.Stat(path.Join(c.toolsDir, binName))
if err != nil && !os.IsNotExist(err) {
return "", err
}
// If the Helm executable binary exists in tools dir, use it.
if fi != nil {
return path.Join(c.toolsDir, binName), nil
}
// If the Helm executable binary exists in $PATH, use it.
epath, err := exec.LookPath(binName)
if err != nil && !errors.Is(err, exec.ErrNotFound) {
return "", err
}
if epath != "" {
return epath, nil
}
// Install helm to command toolsDir.
helmInstallScriptTmpl := template.Must(template.New("helm").Parse(helmInstallScript))
var (
buf bytes.Buffer
data = map[string]interface{}{
"Version": defaultHelmVersion,
"BinDir": c.toolsDir,
}
)
if err := helmInstallScriptTmpl.Execute(&buf, data); err != nil {
return "", fmt.Errorf("failed to install helm %s (%v)", defaultHelmVersion, err)
}
var (
script = buf.String()
cmd = exec.CommandContext(ctx, "/bin/sh", "-c", script)
)
if _, err := cmd.CombinedOutput(); err != nil {
return "", fmt.Errorf("failed to install helm %s (%v)", defaultHelmVersion, err)
}
return path.Join(c.toolsDir, binName), nil
}