/
deploy.go
409 lines (340 loc) · 9.71 KB
/
deploy.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
package cmd
import (
"bufio"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strings"
"github.com/fatih/color"
"github.com/luizalabs/teresa/pkg/client"
"github.com/luizalabs/teresa/pkg/client/connection"
"github.com/luizalabs/teresa/pkg/client/tar"
"github.com/luizalabs/teresa/pkg/client/url"
dpb "github.com/luizalabs/teresa/pkg/protobuf/deploy"
"github.com/luizalabs/teresa/pkg/server/deploy"
"github.com/olekukonko/tablewriter"
"github.com/spf13/cobra"
context "golang.org/x/net/context"
"golang.org/x/sync/errgroup"
)
const (
rollBackWarning = `
WARNING: Teresa currently doesn't roll back nginx configurations or secrets.
In theses cases a new deploy might be a better option.
`
)
var deployCmd = &cobra.Command{
Use: "deploy",
Short: "Everything about deploys",
Long: `To deploy your application you must use the new "teresa deploy create ..."
To see the "deploy create" help, please enter either "teresa deploy create --help"
or just "teresa deploy create".`,
}
var deployCreateCmd = &cobra.Command{
Use: "create <app folder>",
Short: "Deploy an app",
Long: `Deploy an application.
To deploy an app you have to pass it's name and the path,
filename or url to the source code. You might want to describe
your deployments through --description, as that'll
eventually help on rollbacks.
eg.:
$ teresa deploy create . --app webapi --description "release 1.2 with new checkout"
$ teresa deploy create /my/path/webapi.tgz --app webapi --description "release 1.2 with new checkout"
$ teresa deploy create 'https://api.github.com/repos/owner/webapi/tarball/v1.0?access_token=xxx' --app webapi --description "release 1.0"
`,
Run: deployApp,
}
var deployListCmd = &cobra.Command{
Use: "list",
Short: "List app deploys",
Long: "Return all deploys from a given app.",
Example: " $ teresa deploy list --app myapp",
Run: deployList,
}
var deployRollbackCmd = &cobra.Command{
Use: "rollback",
Short: "rollback app to a given revision",
Long: "Rollback an application to a given revision.",
Example: " $ teresa deploy rollback myapp --revision 1",
Run: deployRollback,
}
func getCurrentClusterName() (string, error) {
cfg, err := client.ReadConfigFile(cfgFile)
if err != nil {
return "", err
}
if cfg.CurrentCluster == "" {
return "", client.ErrInvalidConfigFile
}
return cfg.CurrentCluster, nil
}
func getIgnorePatterns(source string) ([]string, error) {
fPath := filepath.Join(source, ".teresaignore")
if _, err := os.Stat(fPath); err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
file, err := os.Open(fPath)
if err != nil {
return nil, err
}
defer file.Close()
patterns := make([]string, 0)
scanner := bufio.NewScanner(file)
for scanner.Scan() {
if text := scanner.Text(); text != "" {
patterns = append(patterns, text)
}
}
if len(patterns) == 0 {
return nil, nil
}
return patterns, nil
}
func init() {
RootCmd.AddCommand(deployCmd)
deployCmd.AddCommand(deployCreateCmd)
deployCmd.AddCommand(deployListCmd)
deployCmd.AddCommand(deployRollbackCmd)
deployCreateCmd.Flags().String("app", "", "app name (required)")
deployCreateCmd.Flags().String("description", "", "deploy description (required)")
deployCreateCmd.Flags().Bool("no-input", false, "deploy app without warning")
deployListCmd.Flags().String("app", "", "app name (required)")
deployRollbackCmd.Flags().String("revision", "", "app revision (required)")
deployRollbackCmd.Flags().Bool("no-input", false, "rollback deploy without warning")
}
func deployApp(cmd *cobra.Command, args []string) {
if len(args) == 0 {
cmd.Usage()
return
}
appURL := args[0]
appName, err := cmd.Flags().GetString("app")
if err != nil || appName == "" {
client.PrintErrorAndExit("Invalid app parameter")
}
deployDescription, err := cmd.Flags().GetString("description")
if err != nil {
client.PrintErrorAndExit("Invalid description parameter")
}
noInput, err := cmd.Flags().GetBool("no-input")
if err != nil {
client.PrintErrorAndExit("Invalid no-input parameter")
}
currentClusterName := currentClusterNameOrExit()
fmt.Printf("Deploying app %s to the cluster %s...\n", color.CyanString(`"%s"`, appName), color.YellowString(`"%s"`, currentClusterName))
if !noInput {
readStdinYesOrExit()
}
path, cleanup := fetchApp(appURL)
if cleanup {
defer os.Remove(path)
}
dir, cleanup := extractApp(path)
if cleanup {
defer os.RemoveAll(dir)
}
ip, err := getIgnorePatterns(dir)
if err != nil {
client.PrintErrorAndExit("Error acessing .teresaignore file: %v", err)
}
fmt.Println("Generating tarball of:", appURL)
tarPath, err := tar.CreateTemp(dir, appName, ip)
if err != nil {
client.PrintErrorAndExit("Error generating tarball: %v", err)
}
defer os.Remove(tarPath)
conn, err := connection.New(cfgFile, currentClusterName)
if err != nil {
client.PrintErrorAndExit("Error connecting to server: %v", err)
}
defer conn.Close()
ctx := context.Background()
cli := dpb.NewDeployClient(conn)
stream, err := cli.Make(ctx)
if err != nil {
client.PrintErrorAndExit(client.GetErrorMsg(err))
}
info := &dpb.DeployRequest{Value: &dpb.DeployRequest_Info_{&dpb.DeployRequest_Info{
App: appName,
Description: deployDescription,
}}}
if err := stream.Send(info); err != nil {
client.PrintErrorAndExit("Error sending deploy information: %v", err)
}
g, _ := errgroup.WithContext(ctx)
g.Go(func() error { return sendAppTarball(tarPath, stream) })
g.Go(func() error { return streamServerMsgs(stream) })
if err := g.Wait(); err != nil {
client.PrintErrorAndExit(client.GetErrorMsg(err))
}
}
func fetchApp(appURL string) (string, bool) {
if url.Scheme(appURL) == "" {
return appURL, false
}
path, err := url.FetchToTemp(appURL)
if err != nil {
client.PrintErrorAndExit("Error downloading url: %v", err)
}
return path, true
}
func extractApp(path string) (string, bool) {
finfo, err := os.Stat(path)
if err != nil {
client.PrintErrorAndExit("Error accessing path: %v", err)
}
if finfo.IsDir() {
return path, false
}
dir, err := tar.ExtractToTemp(path)
if err != nil {
client.PrintErrorAndExit("Error extracting archive: %v", err)
}
return dir, true
}
func sendAppTarball(tarPath string, stream dpb.Deploy_MakeClient) error {
fmt.Println("Sending app tarbal...")
defer stream.CloseSend()
f, err := os.Open(tarPath)
if err != nil {
fmt.Fprintln(os.Stderr, "Error reading temp file:")
return err
}
defer f.Close()
r := bufio.NewReader(f)
for {
buf := make([]byte, 1024)
_, err := r.Read(buf)
if err != nil {
if err != io.EOF {
fmt.Fprintln(os.Stderr, "Error reading bytes of temp file:")
return err
}
break
}
bufMsg := &dpb.DeployRequest{Value: &dpb.DeployRequest_File_{&dpb.DeployRequest_File{
Chunk: buf,
}}}
if err := stream.Send(bufMsg); err != nil {
fmt.Fprintln(os.Stderr, "Error sending tarball chunk:")
return err
}
}
return nil
}
func streamServerMsgs(stream dpb.Deploy_MakeClient) error {
for {
msg, err := stream.Recv()
if err != nil {
if err == io.EOF {
break
}
return err
}
fmt.Print(msg.Text)
}
return nil
}
func deployList(cmd *cobra.Command, args []string) {
appName, err := cmd.Flags().GetString("app")
if err != nil || appName == "" {
client.PrintErrorAndExit("Invalid app parameter")
}
conn, err := connection.New(cfgFile, cfgCluster)
if err != nil {
client.PrintErrorAndExit("Error connecting to server: %v", err)
}
defer conn.Close()
cli := dpb.NewDeployClient(conn)
resp, err := cli.List(context.Background(), &dpb.ListRequest{AppName: appName})
if err != nil {
client.PrintErrorAndExit(client.GetErrorMsg(err))
}
if len(resp.Deploys) == 0 {
fmt.Println("App doesn't have any deploys")
return
}
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"REVISION", "CREATED AT", "DESCRIPTION"})
table.SetRowLine(true)
table.SetAlignment(tablewriter.ALIGN_LEFT)
table.SetRowSeparator("-")
table.SetAutoWrapText(false)
sort.Sort(sort.Reverse(deploy.ByRevision(resp.Deploys)))
for _, d := range resp.Deploys {
if d.Current {
d.Revision = fmt.Sprintf("%s (current)", d.Revision)
}
r := []string{
d.Revision,
d.CreatedAt,
d.Description,
}
table.Append(r)
}
table.Render()
}
func deployRollback(cmd *cobra.Command, args []string) {
if len(args) != 1 {
cmd.Usage()
return
}
appName := args[0]
revision, err := cmd.Flags().GetString("revision")
if err != nil || revision == "" {
client.PrintErrorAndExit("invalid revision parameter")
}
noInput, err := cmd.Flags().GetBool("no-input")
if err != nil {
client.PrintErrorAndExit("Invalid no-input parameter")
}
currentClusterName := currentClusterNameOrExit()
fmt.Printf(
"Rolling back app %s to revision %s on cluster %s...\n",
color.CyanString(`"%s"`, appName),
color.CyanString(`"%s"`, revision),
color.YellowString(`"%s"`, currentClusterName),
)
fmt.Println(color.YellowString(rollBackWarning))
if !noInput {
readStdinYesOrExit()
}
conn, err := connection.New(cfgFile, cfgCluster)
if err != nil {
client.PrintErrorAndExit("Error connecting to server: %v", err)
}
defer conn.Close()
req := &dpb.RollbackRequest{
AppName: appName,
Revision: revision,
}
cli := dpb.NewDeployClient(conn)
if _, err = cli.Rollback(context.Background(), req); err != nil {
client.PrintErrorAndExit(client.GetErrorMsg(err))
}
fmt.Println("rollback done")
}
func currentClusterNameOrExit() string {
name := cfgCluster
if name == "" {
var err error
name, err = getCurrentClusterName()
if err != nil {
client.PrintErrorAndExit("error reading config file: %v", err)
}
}
return name
}
func readStdinYesOrExit() {
fmt.Print("Are you sure? (yes/NO)? ")
s, _ := bufio.NewReader(os.Stdin).ReadString('\n')
if !strings.HasPrefix(strings.ToLower(s), "yes") {
os.Exit(0)
}
}