-
Notifications
You must be signed in to change notification settings - Fork 496
/
build.go
404 lines (340 loc) · 10.2 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
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
/*
Copyright 2020 The Kubernetes 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 build
import (
"errors"
"fmt"
"os"
"path"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"github.com/google/uuid"
"github.com/olekukonko/tablewriter"
"github.com/sirupsen/logrus"
"golang.org/x/net/context"
"google.golang.org/api/cloudbuild/v1"
"google.golang.org/api/option"
"k8s.io/release/pkg/release"
"sigs.k8s.io/release-sdk/gcli"
"sigs.k8s.io/release-sdk/object"
"sigs.k8s.io/release-utils/command"
"sigs.k8s.io/release-utils/tar"
"sigs.k8s.io/yaml"
)
const (
gcsSourceDir = "/source"
gcsLogsDir = "/logs"
DefaultCloudbuildFile = "cloudbuild.yaml"
)
// TODO: Pull some of these options in cmd/gcbuilder, so they don't have to be public.
type Options struct {
objStore object.Store
BuildDir string
ConfigDir string
CloudbuildFile string
LogDir string
ScratchBucket string
Project string
AllowDirty bool
NoSource bool
Async bool
DiskSize string
Variant string
EnvPassthrough string
}
// NewDefaultOptions returns a new default `*Options` instance.
func NewDefaultOptions() *Options {
return &Options{
objStore: object.NewGCS(),
Project: release.DefaultKubernetesStagingProject,
CloudbuildFile: DefaultCloudbuildFile,
}
}
func PrepareBuilds(o *Options) error {
if o.ConfigDir == "" {
return errors.New("expected a config directory to be provided")
}
if bazelWorkspace := os.Getenv("BUILD_WORKSPACE_DIRECTORY"); bazelWorkspace != "" {
if err := os.Chdir(bazelWorkspace); err != nil {
return fmt.Errorf("failed to chdir to bazel workspace (%s): %w", bazelWorkspace, err)
}
}
if o.BuildDir == "" {
o.BuildDir = o.ConfigDir
}
logrus.Infof("Build directory: %s", o.BuildDir)
// Canonicalize the config directory to be an absolute path.
// As we're about to cd into the build directory, we need a consistent way to reference the config files
// when the config directory is not the same as the build directory.
absConfigDir, absErr := filepath.Abs(o.ConfigDir)
if absErr != nil {
return fmt.Errorf("could not resolve absolute path for config directory: %w", absErr)
}
o.ConfigDir = absConfigDir
o.CloudbuildFile = path.Join(o.ConfigDir, o.CloudbuildFile)
configDirErr := o.ValidateConfigDir()
if configDirErr != nil {
return fmt.Errorf("could not validate config directory: %w", configDirErr)
}
logrus.Infof("Config directory: %s", o.ConfigDir)
logrus.Infof("Changing to build directory: %s", o.BuildDir)
if err := os.Chdir(o.BuildDir); err != nil {
return fmt.Errorf("failed to chdir to build directory (%s): %w", o.BuildDir, err)
}
return nil
}
func (o *Options) ValidateConfigDir() error {
configDir := o.ConfigDir
dirInfo, err := os.Stat(o.ConfigDir)
if os.IsNotExist(err) {
logrus.Infof("Config directory (%s) does not exist", configDir)
return err
}
if !dirInfo.IsDir() {
logrus.Infof("Config directory (%s) is not actually a directory", configDir)
return err
}
_, err = os.Stat(o.CloudbuildFile)
if os.IsNotExist(err) {
logrus.Infof("%s does not exist", o.CloudbuildFile)
return err
}
return nil
}
func (o *Options) uploadBuildDir(targetBucket string) (string, error) {
f, err := os.CreateTemp("", "")
if err != nil {
return "", fmt.Errorf("failed to create temp file: %w", err)
}
name := f.Name()
_ = f.Close()
defer os.Remove(name)
logrus.Infof("Creating source tarball at %s...", name)
if err := tar.Compress(name, ".", regexp.MustCompile(".git")); err != nil {
return "", fmt.Errorf("create tarball: %w", err)
}
u := uuid.New()
uploaded := fmt.Sprintf("%s/%s.tgz", targetBucket, u.String())
logrus.Infof("Uploading %s to %s...", name, uploaded)
if err := o.objStore.CopyToRemote(
name,
uploaded,
); err != nil {
return "", fmt.Errorf("upload files to GCS: %w", err)
}
return uploaded, nil
}
func getExtraSubs(o *Options) map[string]string {
envs := strings.Split(o.EnvPassthrough, ",")
subs := map[string]string{}
for _, e := range envs {
e = strings.TrimSpace(e)
if e != "" {
subs[e] = os.Getenv(e)
}
}
return subs
}
func RunSingleJob(o *Options, jobName, uploaded, version string, subs map[string]string) error {
s := make([]string, 0, len(subs)+1)
for k, v := range subs {
s = append(s, fmt.Sprintf("_%s=%s", k, v))
}
s = append(s, "_GIT_TAG="+version)
args := []string{
"builds", "submit",
"--verbosity", "info",
"--config", o.CloudbuildFile,
"--substitutions", strings.Join(s, ","),
}
if o.Project != "" {
args = append(args, "--project", o.Project)
}
if o.Async {
args = append(args, "--async")
}
if o.ScratchBucket != "" {
args = append(
args,
"--gcs-log-dir",
o.ScratchBucket+gcsLogsDir,
"--gcs-source-staging-dir",
o.ScratchBucket+gcsSourceDir,
)
}
if uploaded != "" {
args = append(args, uploaded)
} else {
if o.NoSource {
args = append(args, "--no-source")
} else {
args = append(args, ".")
}
}
if o.DiskSize != "" {
diskSizeInt, intErr := strconv.Atoi(o.DiskSize)
if intErr != nil {
return intErr
}
if diskSizeInt > 1000 {
return errors.New("selected disk size must be no greater than 1000 GB")
} else if diskSizeInt <= 0 {
return errors.New("selected disk size must be greater than 0 GB")
}
diskSizeArg := fmt.Sprintf("--disk-size=%s", o.DiskSize)
args = append(args, diskSizeArg)
}
cmd := command.New(gcli.GCloudExecutable, args...)
if o.LogDir != "" {
p := path.Join(o.LogDir, strings.ReplaceAll(jobName, "/", "-")+".log")
f, err := os.Create(p)
if err != nil {
return fmt.Errorf("couldn't create %s: %w", p, err)
}
defer f.Close()
cmd.AddWriter(f)
}
logrus.Infof("cloudbuild command to send to gcp: %s", cmd.String())
if err := cmd.RunSuccess(); err != nil {
return fmt.Errorf("error running %s: %w", cmd.String(), err)
}
return nil
}
type variants map[string]map[string]string
func getVariants(o *Options) (variants, error) {
content, err := os.ReadFile(path.Join(o.ConfigDir, "variants.yaml"))
if err != nil {
if !os.IsNotExist(err) {
return nil, fmt.Errorf("failed to load variants.yaml: %w", err)
}
if o.Variant != "" {
return nil, fmt.Errorf("no variants.yaml found, but a build variant (%q) was specified: %w", o.Variant, err)
}
return nil, nil
}
v := struct {
Variants variants `json:"variants"`
}{}
if err := yaml.UnmarshalStrict(content, &v); err != nil {
return nil, fmt.Errorf("failed to read variants.yaml: %w", err)
}
if o.Variant != "" {
va, ok := v.Variants[o.Variant]
if !ok {
return nil, fmt.Errorf("requested variant %q, which is not present in variants.yaml", o.Variant)
}
return variants{o.Variant: va}, nil
}
return v.Variants, nil
}
func RunBuildJobs(o *Options) []error {
var uploaded string
if o.ScratchBucket != "" {
if !o.NoSource {
var err error
uploaded, err = o.uploadBuildDir(o.ScratchBucket + gcsSourceDir)
if err != nil {
return []error{fmt.Errorf("failed to upload source: %w", err)}
}
}
} else {
logrus.Info("Skipping advance upload and relying on gcloud...")
}
logrus.Info("Running build jobs...")
repo := release.NewRepo()
err := repo.Open()
if err != nil {
return []error{err}
}
tag, err := repo.GetTag()
if err != nil {
return []error{err}
}
if !o.AllowDirty && strings.HasSuffix(tag, "-dirty") {
return []error{errors.New("the working copy is dirty")}
}
vs, err := getVariants(o)
if err != nil {
return []error{err}
}
if len(vs) == 0 {
logrus.Info("No variants.yaml, starting single build job...")
if err := RunSingleJob(o, "build", uploaded, tag, getExtraSubs(o)); err != nil {
return []error{err}
}
return nil
}
logrus.Infof("Found variants.yaml, starting %d build jobs...", len(vs))
w := sync.WaitGroup{}
w.Add(len(vs))
var jobErrors []error
extraSubs := getExtraSubs(o)
for k, v := range vs {
go func(job string, vc map[string]string) {
defer w.Done()
logrus.Infof("Starting job %q...", job)
if err := RunSingleJob(o, job, uploaded, tag, mergeMaps(extraSubs, vc)); err != nil {
logrus.Infof("Job %q failed: %v", job, err)
jobErrors = append(jobErrors, fmt.Errorf("job %q failed: %w", job, err))
} else {
logrus.Infof("Job %q completed", job)
}
}(k, v)
}
w.Wait()
return jobErrors
}
func mergeMaps(maps ...map[string]string) map[string]string {
out := map[string]string{}
for _, m := range maps {
for k, v := range m {
out[k] = v
}
}
return out
}
func ListJobs(project string, lastJobs int64) error {
ctx := context.Background()
opts := option.WithCredentialsFile("")
service, err := cloudbuild.NewService(ctx, opts)
if err != nil {
return fmt.Errorf("failed to fetching gcloud credentials... try running \"gcloud auth application-default login\": %w", err)
}
req, err := service.Projects.Builds.List(project).PageSize(lastJobs).Do()
if err != nil {
return fmt.Errorf("failed to listing the builds: %w", err)
}
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Start Time", "Finish Time", "Status", "Console Logs"})
for _, build := range req.Builds {
table.Append([]string{strings.TrimSpace(build.StartTime), strings.TrimSpace(build.FinishTime), strings.TrimSpace(build.Status), strings.TrimSpace(build.LogUrl)})
}
table.Render()
return nil
}
func GetJobsByTag(project, tagsFilter string) ([]*cloudbuild.Build, error) {
ctx := context.Background()
opts := option.WithCredentialsFile("")
service, err := cloudbuild.NewService(ctx, opts)
if err != nil {
return nil, fmt.Errorf("failed to fetching gcloud credentials... try running \"gcloud auth application-default login\": %w", err)
}
req, err := service.Projects.Builds.List(project).Filter(tagsFilter).PageSize(50).Do()
if err != nil {
return nil, fmt.Errorf("failed to listing the builds: %w", err)
}
return req.Builds, nil
}