/
build.go
348 lines (295 loc) · 8.37 KB
/
build.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
package cmd
import (
"bufio"
"fmt"
"io"
"os"
"github.com/fatih/color"
"github.com/olekukonko/tablewriter"
"github.com/spf13/cobra"
context "golang.org/x/net/context"
"golang.org/x/sync/errgroup"
"github.com/luizalabs/teresa/pkg/client"
"github.com/luizalabs/teresa/pkg/client/connection"
"github.com/luizalabs/teresa/pkg/client/tar"
bpb "github.com/luizalabs/teresa/pkg/protobuf/build"
)
var buildCmd = &cobra.Command{
Use: "build",
Short: "Everything about build",
Long: `To build your application you must use the "teresa build create ..."
To see the "build create" help, please enter either "teresa build create --help"
or just "teresa build create".`,
}
var buildCreateCmd = &cobra.Command{
Use: "create <app folder>",
Short: "Create a build of an app",
Long: `Create a new build of an application.
The build create command follow almost the same rules of
deploy create command, you have to pass it's name, the path,
filename or url to the source code and a build name
(following the RFC-952), this name will help you
to promote a build to a new deploy.
`,
Example: " $ teresa build create . --app myapp --name v1-0-0-rc1",
Run: buildApp,
}
var buildListCmd = &cobra.Command{
Use: "list <app-name>",
Short: "List app builds",
Long: "Return all builds from a given app.",
Example: " $ teresa build list myapp",
Run: buildList,
}
var buildRunCmd = &cobra.Command{
Use: "run <app-name> <build-name>",
Short: "Run a build",
Long: "Run a previously created build in a single isolate pod",
Example: " $ teresa build run myapp v1-0-0-rc1",
Run: buildRun,
}
var buildDeleteCmd = &cobra.Command{
Use: "delete <app-name> <build-name>",
Short: "Delete a build",
Long: "Delete a previously created build",
Example: " $ teresa build delete myapp v1-0-0-rc1",
Run: buildDelete,
}
func buildApp(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")
}
buildName, err := cmd.Flags().GetString("name")
if err != nil {
client.PrintErrorAndExit("Invalid name parameter")
}
runApp, err := cmd.Flags().GetBool("run")
if err != nil {
client.PrintErrorAndExit("Invalid run parameter")
}
currentClusterName := cfgCluster
if currentClusterName == "" {
currentClusterName, err = getCurrentClusterName()
if err != nil {
client.PrintErrorAndExit("error reading config file: %v", err)
}
}
fmt.Printf(
"Creating build %s of app %s to the cluster %s...\n",
color.CyanString(`"%s"`, buildName),
color.CyanString(`"%s"`, appName),
color.YellowString(`"%s"`, currentClusterName),
)
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 accessing .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 := bpb.NewBuildClient(conn)
stream, err := cli.Make(ctx)
if err != nil {
client.PrintErrorAndExit(client.GetErrorMsg(err))
}
info := &bpb.BuildRequest{Value: &bpb.BuildRequest_Info_{&bpb.BuildRequest_Info{
App: appName,
Name: buildName,
Run: runApp,
}}}
if err := stream.Send(info); err != nil {
client.PrintErrorAndExit("Error sending build information: %v", err)
}
g, _ := errgroup.WithContext(ctx)
g.Go(func() error { return sendBuildTarball(tarPath, stream) })
g.Go(func() error { return streamServerBuildMsgs(stream) })
if err := g.Wait(); err != nil {
client.PrintErrorAndExit(client.GetErrorMsg(err))
}
}
func streamServerBuildMsgs(stream bpb.Build_MakeClient) error {
for {
msg, err := stream.Recv()
if err != nil {
if err == io.EOF {
break
}
return err
}
fmt.Print(msg.Text)
}
return nil
}
func sendBuildTarball(tarPath string, stream bpb.Build_MakeClient) error {
fmt.Println("Sending app tarball...")
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 := &bpb.BuildRequest{Value: &bpb.BuildRequest_File_{&bpb.BuildRequest_File{
Chunk: buf,
}}}
if err := stream.Send(bufMsg); err != nil {
fmt.Fprintln(os.Stderr, "Error sending tarball chunk:")
return err
}
}
return nil
}
func buildList(cmd *cobra.Command, args []string) {
if len(args) == 0 {
cmd.Usage()
return
}
appName := args[0]
conn, err := connection.New(cfgFile, cfgCluster)
if err != nil {
client.PrintErrorAndExit("Error connecting to server: %v", err)
}
defer conn.Close()
cli := bpb.NewBuildClient(conn)
resp, err := cli.List(context.Background(), &bpb.ListRequest{AppName: appName})
if err != nil {
client.PrintErrorAndExit(client.GetErrorMsg(err))
}
if len(resp.Builds) == 0 {
fmt.Println("App doesn't have any builds")
return
}
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"BUILD", "LAST MODIFIED"})
table.SetRowLine(true)
table.SetAlignment(tablewriter.ALIGN_LEFT)
table.SetRowSeparator("-")
table.SetAutoWrapText(false)
for _, b := range resp.Builds {
table.Append([]string{b.Name, b.LastModified})
}
table.Render()
}
func buildRun(cmd *cobra.Command, args []string) {
if len(args) != 2 {
cmd.Usage()
return
}
appName, buildName := args[0], args[1]
var err error
currentClusterName := cfgCluster
if currentClusterName == "" {
currentClusterName, err = getCurrentClusterName()
if err != nil {
client.PrintErrorAndExit("error reading config file: %v", err)
}
}
fmt.Printf(
"Running build %s of app %s in the cluster %s...\n",
color.CyanString(`"%s"`, buildName),
color.CyanString(`"%s"`, appName),
color.YellowString(`"%s"`, currentClusterName),
)
conn, err := connection.New(cfgFile, currentClusterName)
if err != nil {
client.PrintErrorAndExit("Error connecting to server: %v", err)
}
defer conn.Close()
ctx := context.Background()
cli := bpb.NewBuildClient(conn)
stream, err := cli.Run(ctx, &bpb.RunRequest{AppName: appName, Name: buildName})
if err != nil {
client.PrintErrorAndExit(client.GetErrorMsg(err))
}
for {
msg, err := stream.Recv()
if err != nil {
if err == io.EOF {
break
}
client.PrintErrorAndExit(client.GetErrorMsg(err))
}
fmt.Print(msg.Text)
}
}
func buildDelete(cmd *cobra.Command, args []string) {
if len(args) != 2 {
cmd.Usage()
return
}
appName, buildName := args[0], args[1]
var err error
currentClusterName := cfgCluster
if currentClusterName == "" {
currentClusterName, err = getCurrentClusterName()
if err != nil {
client.PrintErrorAndExit("error reading config file: %v", err)
}
}
inputMsg := fmt.Sprintf(
"Are you sure you want to delete the build %s of %s on %s? (yes/NO) ",
color.CyanString(`"%s"`, buildName),
color.CyanString(`"%s"`, appName),
color.YellowString(`"%s"`, currentClusterName),
)
s, _ := client.GetInput(inputMsg)
if s != "yes" {
fmt.Println("Delete process aborted!")
return
}
conn, err := connection.New(cfgFile, cfgCluster)
if err != nil {
client.PrintErrorAndExit("Error connecting to server: %v", err)
}
defer conn.Close()
cli := bpb.NewBuildClient(conn)
req := &bpb.DeleteRequest{AppName: appName, Name: buildName}
if _, err := cli.Delete(context.Background(), req); err != nil {
client.PrintErrorAndExit(client.GetErrorMsg(err))
}
fmt.Printf("Build %s deleted!\n", buildName)
}
func init() {
RootCmd.AddCommand(buildCmd)
buildCmd.AddCommand(buildCreateCmd)
buildCmd.AddCommand(buildListCmd)
buildCmd.AddCommand(buildRunCmd)
buildCmd.AddCommand(buildDeleteCmd)
buildCreateCmd.Flags().String("app", "", "app name (required)")
buildCreateCmd.Flags().String("name", "", "build name (required)")
buildCreateCmd.Flags().Bool("run", false, "run build in an isolate replica with a temporary service")
}