-
Notifications
You must be signed in to change notification settings - Fork 4
/
builder.go
279 lines (224 loc) · 6.59 KB
/
builder.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
package aws
import (
"fmt"
"io"
"io/ioutil"
"os"
"strings"
"time"
log "github.com/Sirupsen/logrus"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/codebuild"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
pb "github.com/dinesh/datacol/api/models"
sched "github.com/dinesh/datacol/cloud/kube"
"github.com/ejholmes/cloudwatch"
)
func (a *AwsCloud) ecrRepository(n string) string {
return fmt.Sprintf("%s-%s-repo", a.DeploymentName, n)
}
func (a *AwsCloud) codebuildProjectName(n string) string {
return fmt.Sprintf("%s-%s-code-builder", a.DeploymentName, n)
}
func (a *AwsCloud) dynamoBuilds() string {
return fmt.Sprintf("%s-builds", a.DeploymentName)
}
func (a *AwsCloud) codeBuildBucket() string {
return a.SettingBucket
}
func (g *AwsCloud) GetRunningPods(app string) (string, error) {
ns := g.DeploymentName
c := g.kubeClient()
return sched.RunningPods(ns, app, c)
}
func (a *AwsCloud) BuildGet(app, id string) (*pb.Build, error) {
req := &dynamodb.GetItemInput{
ConsistentRead: aws.Bool(true),
Key: map[string]*dynamodb.AttributeValue{
"id": {S: aws.String(id)},
},
TableName: aws.String(a.dynamoBuilds()),
}
res, err := a.dynamodb().GetItem(req)
if err != nil {
return nil, err
}
if res.Item == nil {
return nil, fmt.Errorf("no build found by id: %s", id)
}
build := a.buildFromItem(res.Item)
if build.Status == "IN_PROGRESS" {
rb, err := a.fetchRemoteBuild(build.RemoteId)
if err != nil {
return nil, err
}
status := rb.BuildStatus
if status != nil && *status != build.Status {
build.Status = *status
a.buildSave(build)
}
}
return build, nil
}
func (a *AwsCloud) BuildDelete(app, id string) error {
return nil
}
func (a *AwsCloud) BuildList(app string, limit int) (pb.Builds, error) {
return nil, nil
}
func (a *AwsCloud) BuildImport(app, gzipPath string) (*pb.Build, error) {
log.Debugf("converting gzip to zip of %s", gzipPath)
zipPath, err := convertGzipToZip(app, gzipPath)
if err != nil {
return nil, fmt.Errorf("converting gzip to zip archive. err: %v", err)
}
defer os.RemoveAll(zipPath)
reader, err := os.Open(zipPath)
if err != nil {
return nil, fmt.Errorf("reading tempfile err: %v", err)
}
defer reader.Close()
log.Debugf("Uploading to s3 from %s", zipPath)
uploader := s3manager.NewUploaderWithClient(a.s3())
if _, err = uploader.Upload(&s3manager.UploadInput{
Body: reader,
Bucket: aws.String(a.codeBuildBucket()),
Key: aws.String(app + "/source.zip"),
}, func(u *s3manager.Uploader) {
u.PartSize = 64 * 1024 * 1024 // 64MB per part
}); err != nil {
return nil, fmt.Errorf("uploading source to s3 err: %v", err)
}
log.Debug("OK \n")
build := &pb.Build{
App: app,
Id: generateId("B", 5),
Status: pb.StatusCreated,
CreatedAt: timestampNow(),
}
if err := a.buildSave(build); err != nil {
return nil, fmt.Errorf("saving to dynamodb err: %v", err)
}
return build, a.startBuild(build, &pb.CreateBuildOptions{})
}
func (a *AwsCloud) BuildCreate(app string, req *pb.CreateBuildOptions) (*pb.Build, error) {
build := &pb.Build{
App: app,
Id: generateId("B", 5),
Status: pb.StatusCreated,
CreatedAt: timestampNow(),
}
if err := a.buildSave(build); err != nil {
return nil, fmt.Errorf("saving to dynamodb err: %v", err)
}
return build, a.startBuild(build, req)
}
func (a *AwsCloud) BuildLogs(app, id string, index int) (int, []string, error) {
rb, err := a.fetchRemoteBuild(id)
if err != nil {
return 0, nil, err
}
return a.buildLogs(a.s3(), rb.Logs.GroupName, rb.Logs.StreamName, id, index)
}
func (a *AwsCloud) BuildLogsStream(id string) (io.Reader, error) {
fmt.Print("waiting for cloudwatch logstream (1s)")
var rb *codebuild.Build
for {
b, err := a.fetchRemoteBuild(id)
if err != nil {
return nil, fmt.Errorf("fetching build err: %v", err)
}
rb = b
if rb.Logs != nil && rb.Logs.StreamName != nil {
break
}
fmt.Print(".")
time.Sleep(1 * time.Second)
}
fmt.Print(" OK\n")
log.Debugf("Will start streaming from stream: %s", *rb.Logs.StreamName)
return cloudwatch.NewGroup(*rb.Logs.GroupName, a.cloudwatchlogs()).Open(*rb.Logs.StreamName)
}
func (a *AwsCloud) buildFromItem(item map[string]*dynamodb.AttributeValue) *pb.Build {
return &pb.Build{
Id: coalesce(item["id"], ""),
App: coalesce(item["app"], ""),
Status: coalesce(item["status"], ""),
RemoteId: coalesce(item["remote_id"], ""),
}
}
func (a *AwsCloud) buildSave(b *pb.Build) error {
req := &dynamodb.PutItemInput{
Item: map[string]*dynamodb.AttributeValue{
"id": {S: aws.String(b.Id)},
"app": {S: aws.String(b.App)},
},
TableName: aws.String(a.dynamoBuilds()),
}
if b.Status != "" {
req.Item["status"] = &dynamodb.AttributeValue{S: aws.String(b.Status)}
}
if b.RemoteId != "" {
req.Item["remote_id"] = &dynamodb.AttributeValue{S: aws.String(b.RemoteId)}
}
_, err := a.dynamodb().PutItem(req)
return err
}
func (a *AwsCloud) fetchRemoteBuild(id string) (*codebuild.Build, error) {
out, err := a.codebuild().BatchGetBuilds(&codebuild.BatchGetBuildsInput{
Ids: []*string{aws.String(id)},
})
if err != nil {
return nil, fmt.Errorf("fetching cloud builds err: %v", err)
}
for _, b := range out.Builds {
if b.Id != nil && *b.Id == id {
return b, nil
}
}
return nil, fmt.Errorf("no build found by id: %s", id)
}
func (a *AwsCloud) buildLogs(svc *s3.S3, bucket, key *string, bid string, index int) (int, []string, error) {
out, err := svc.GetObject(&s3.GetObjectInput{Bucket: bucket, Key: key})
if err != nil {
return 0, nil, err
}
defer out.Body.Close()
lines := []string{}
body, err := ioutil.ReadAll(out.Body)
if err != nil {
return index, lines, err
}
parts := strings.Split(string(body), "\n")
for _, line := range parts[index:] {
if len(line) > 0 && line != "\n" {
lines = append(lines, line)
}
}
return len(parts) - 1, lines, nil
}
func (a *AwsCloud) startBuild(build *pb.Build, req *pb.CreateBuildOptions) error {
log.Infof("Starting the build ...")
ret, err := a.codebuild().StartBuild(&codebuild.StartBuildInput{
ProjectName: aws.String(a.codebuildProjectName(build.App)),
SourceVersion: aws.String(req.Version),
EnvironmentVariablesOverride: []*codebuild.EnvironmentVariable{
{
Name: aws.String("APP"),
Value: aws.String(build.App),
}, {
Name: aws.String("IMAGE_TAG"),
Value: aws.String(build.Id),
},
},
})
if err != nil {
return err
}
build.RemoteId = *ret.Build.Id
build.Status = *ret.Build.BuildStatus
log.Debugf("Persisting build: %+v", build)
return a.buildSave(build)
}