-
Notifications
You must be signed in to change notification settings - Fork 157
/
builder.go
262 lines (233 loc) · 6.89 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
// Copyright 2022 The envd 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 builder
import (
"context"
"io"
"os"
"github.com/cockroachdb/errors"
"github.com/moby/buildkit/client"
"github.com/moby/buildkit/client/llb"
"github.com/sirupsen/logrus"
"golang.org/x/sync/errgroup"
"github.com/tensorchord/envd/pkg/buildkitd"
"github.com/tensorchord/envd/pkg/docker"
"github.com/tensorchord/envd/pkg/flag"
"github.com/tensorchord/envd/pkg/home"
"github.com/tensorchord/envd/pkg/lang/frontend/starlark"
"github.com/tensorchord/envd/pkg/lang/ir"
"github.com/tensorchord/envd/pkg/progress/progresswriter"
"github.com/tensorchord/envd/pkg/types"
"github.com/tensorchord/envd/pkg/util/fileutil"
)
type Builder interface {
Build(ctx context.Context, pub string) error
GPUEnabled() bool
NumGPUs() int
}
type generalBuilder struct {
manifestFilePath string
configFilePath string
progressMode string
tag string
buildContextDir string
outputType string
outputDest string
logger *logrus.Entry
starlark.Interpreter
buildkitd.Client
}
func New(ctx context.Context, configFilePath, manifestFilePath, buildContextDir, tag, output string, debug bool) (Builder, error) {
outputType, outputDest, err := parseOutput(output)
if err != nil {
return nil, errors.Wrap(err, "failed to parse output")
}
var mode string = "auto"
if debug {
mode = "plain"
}
b := &generalBuilder{
manifestFilePath: manifestFilePath,
configFilePath: configFilePath,
outputType: outputType,
outputDest: outputDest,
buildContextDir: buildContextDir,
// TODO(gaocegege): Support other mode?
progressMode: mode,
tag: tag,
logger: logrus.WithFields(logrus.Fields{
"tag": tag,
}),
}
cli, err := buildkitd.NewClient(ctx, "")
if err != nil {
return nil, errors.Wrap(err, "failed to create buildkit client")
}
b.Client = cli
b.Interpreter = starlark.NewInterpreter()
return b, nil
}
// GPUEnabled returns true if cuda is enabled.
func (b generalBuilder) GPUEnabled() bool {
return ir.GPUEnabled()
}
// NumGPUs returns the number of GPUs requested.
func (b generalBuilder) NumGPUs() int {
return ir.NumGPUs()
}
func (b generalBuilder) Build(ctx context.Context, pub string) error {
def, err := b.compile(ctx, pub)
if err != nil {
return errors.Wrap(err, "failed to compile")
}
pw, err := progresswriter.NewPrinter(ctx, os.Stdout, b.progressMode)
if err != nil {
return errors.Wrap(err, "failed to create progress writer")
}
if err = b.build(ctx, def, pw); err != nil {
return errors.Wrap(err, "failed to build")
}
return nil
}
func (b generalBuilder) interpret() error {
// Evaluate config first.
if _, err := b.ExecFile(b.configFilePath, ""); err != nil {
return errors.Wrap(err, "failed to exec starlark file")
}
if _, err := b.ExecFile(b.manifestFilePath, "build"); err != nil {
return errors.Wrap(err, "failed to exec starlark file")
}
return nil
}
func (b generalBuilder) compile(ctx context.Context, pub string) (*llb.Definition, error) {
if err := b.interpret(); err != nil {
return nil, errors.Wrap(err, "failed to interpret")
}
def, err := ir.Compile(ctx, fileutil.Base(b.buildContextDir), pub)
if err != nil {
return nil, errors.Wrap(err, "failed to compile build.envd")
}
b.logger.Debug("compiled build.envd")
return def, nil
}
func (b generalBuilder) labels(ctx context.Context) (string, error) {
labels, err := ir.Labels()
if err != nil {
return "", errors.Wrap(err, "failed to get labels")
}
labels[types.ImageLabelContext] = b.buildContextDir
data, err := ImageConfigStr(labels)
if err != nil {
return "", errors.Wrap(err, "failed to get image config")
}
return data, nil
}
func (b generalBuilder) build(ctx context.Context, def *llb.Definition, pw progresswriter.Writer) error {
labels, err := b.labels(ctx)
if err != nil {
return errors.Wrap(err, "failed to get labels")
}
// k := platforms.Format(platforms.DefaultSpec())
ctx, cancel := context.WithCancel(ctx)
defer cancel()
eg, ctx := errgroup.WithContext(ctx)
// Create a pipe to load the image into the docker host.
pipeR, pipeW := io.Pipe()
eg.Go(func() error {
defer pipeW.Close()
_, err := b.Solve(ctx, def, client.SolveOpt{
Exports: []client.ExportEntry{
{
Type: client.ExporterDocker,
Attrs: map[string]string{
"name": b.tag,
// Ref https://github.com/r2d4/mockerfile/blob/140c6a912bbfdae220febe59ab535ef0acba0e1f/pkg/build/build.go#L65
"containerimage.config": labels,
},
Output: func(map[string]string) (io.WriteCloser, error) {
return pipeW, nil
},
},
},
LocalDirs: map[string]string{
flag.FlagContextDir: b.buildContextDir,
flag.FlagCacheDir: home.GetManager().CacheDir(),
},
// TODO(gaocegege): Use llb.WithProxy to implement it.
FrontendAttrs: map[string]string{
"build-arg:HTTPS_PROXY": os.Getenv("HTTPS_PROXY"),
},
}, pw.Status())
if err != nil {
err = errors.Wrap(err, "failed to solve LLB")
b.logger.Error(err)
return err
}
b.logger.Debug("llb def is solved successfully")
return nil
})
// Watch the progress.
eg.Go(func() error {
// not using shared context to not disrupt display but let is finish reporting errors
<-pw.Done()
return pw.Err()
})
if b.outputDest != "" {
// Save the image to the output file.
eg.Go(func() error {
defer pipeR.Close()
f, err := os.Create(b.outputDest)
if err != nil {
return err
}
defer f.Close()
_, err = io.Copy(f, pipeR)
if err != nil {
return err
}
b.logger.Debug("export the image successfully")
return nil
})
}
if b.outputDest == "" {
// Load the image to docker host.
eg.Go(func() error {
defer pipeR.Close()
dockerClient, err := docker.NewClient(ctx)
if err != nil {
return errors.Wrap(err, "failed to new docker client")
}
b.logger.Debug("loading image to docker host")
if err := dockerClient.Load(ctx, pipeR, true); err != nil {
err = errors.Wrap(err, "failed to load docker image")
b.logger.Error(err)
return err
}
b.logger.Debug("loaded docker image successfully")
return nil
})
}
err = eg.Wait()
if err != nil {
if errors.Is(err, context.Canceled) {
b.logger.Debug("cancelling the error group")
// Close the pipe on cancels, otherwise the whole thing hangs.
pipeR.Close()
return errors.Wrap(err, "build cancelled")
} else {
return errors.Wrap(err, "failed to wait error group")
}
}
return nil
}