-
Notifications
You must be signed in to change notification settings - Fork 357
/
Copy pathexport.go
211 lines (187 loc) · 6.37 KB
/
export.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
package export
import (
"context"
"time"
"github.com/cockroachdb/errors"
"github.com/google/go-containerregistry/pkg/authn"
"github.com/google/go-containerregistry/pkg/name"
v1 "github.com/google/go-containerregistry/pkg/v1"
"github.com/google/go-containerregistry/pkg/v1/daemon"
"github.com/google/go-containerregistry/pkg/v1/empty"
"github.com/google/go-containerregistry/pkg/v1/remote"
"github.com/rs/zerolog"
"encr.dev/cli/daemon/apps"
"encr.dev/internal/env"
"encr.dev/pkg/builder"
"encr.dev/pkg/builder/builderimpl"
"encr.dev/pkg/cueutil"
"encr.dev/pkg/dockerbuild"
"encr.dev/pkg/fns"
"encr.dev/pkg/option"
"encr.dev/pkg/vcs"
daemonpb "encr.dev/proto/encore/daemon"
)
// Docker exports the app as a docker image.
func Docker(ctx context.Context, app *apps.Instance, req *daemonpb.ExportRequest, log zerolog.Logger) (success bool, err error) {
params := req.GetDocker()
if params == nil {
return false, errors.Newf("unsupported format: %T", req.Format)
}
expSet, err := app.Experiments(req.Environ)
if err != nil {
return false, errors.Wrap(err, "get experimental features")
}
vcsRevision := vcs.GetRevision(app.Root())
buildInfo := builder.BuildInfo{
BuildTags: []string{"timetzdata"},
CgoEnabled: req.CgoEnabled,
StaticLink: true,
DebugMode: builder.DebugModeDisabled,
Environ: req.Environ,
GOOS: req.Goos,
GOARCH: req.Goarch,
KeepOutput: false,
Revision: vcsRevision.Revision,
UncommittedChanges: vcsRevision.Uncommitted,
}
bld := builderimpl.Resolve(app.Lang(), expSet)
defer fns.CloseIgnore(bld)
parse, err := bld.Parse(ctx, builder.ParseParams{
Build: buildInfo,
App: app,
Experiments: expSet,
WorkingDir: ".",
ParseTests: false,
})
if err != nil {
return false, err
}
if err := app.CacheMetadata(parse.Meta); err != nil {
log.Info().Err(err).Msg("failed to cache metadata")
return false, errors.Wrap(err, "cache metadata")
}
// Validate the service configs.
_, err = bld.ServiceConfigs(ctx, builder.ServiceConfigsParams{
Parse: parse,
CueMeta: &cueutil.Meta{
// Dummy data to satisfy config validation.
APIBaseURL: "http://localhost:0",
EnvName: "encore-eject",
EnvType: cueutil.EnvType_Development,
CloudType: cueutil.CloudType_Local,
},
})
if err != nil {
return false, err
}
log.Info().Msgf("compiling Encore application for %s/%s", req.Goos, req.Goarch)
result, err := bld.Compile(ctx, builder.CompileParams{
Build: buildInfo,
App: app,
Parse: parse,
OpTracker: nil, // TODO
Experiments: expSet,
WorkingDir: ".",
})
if err != nil {
log.Info().Err(err).Msg("compilation failed")
return false, errors.Wrap(err, "compilation failed")
}
spec, err := dockerbuild.Describe(dockerbuild.DescribeConfig{
Meta: parse.Meta,
Compile: result,
BundleSource: option.Option[dockerbuild.BundleSourceSpec]{},
DockerBaseImage: option.AsOptional(params.BaseImageTag),
Runtimes: dockerbuild.HostPath(env.EncoreRuntimesPath()),
})
if err != nil {
return false, errors.Wrap(err, "describe docker image")
}
var baseImgOverride option.Option[v1.Image]
if params.BaseImageTag != "" {
baseImg, err := resolveBaseImage(ctx, log, params)
if err != nil {
return false, errors.Wrap(err, "resolve base image")
}
baseImgOverride = option.Some(baseImg)
}
img, err := dockerbuild.BuildImage(ctx, spec, dockerbuild.ImageBuildConfig{
BuildTime: time.Now(),
BaseImageOverride: baseImgOverride,
AddCACerts: option.Some[dockerbuild.ImagePath](""),
// Not supported yet:
SupervisorPath: option.None[dockerbuild.HostPath](),
})
if err != nil {
return false, errors.Wrap(err, "build docker image")
}
if params.LocalDaemonTag != "" {
tag, err := name.NewTag(params.LocalDaemonTag, name.WeakValidation)
if err != nil {
log.Error().Err(err).Msg("invalid image tag")
return false, nil
}
log.Info().Msg("saving image to local docker daemon")
_, err = daemon.Write(tag, img, daemon.WithUnbufferedOpener())
if err != nil {
log.Error().Err(err).Msg("unable to save docker image")
return false, nil
}
log.Info().Msg("successfully saved local docker image")
}
if params.PushDestinationTag != "" {
tag, err := name.NewTag(params.PushDestinationTag, name.WeakValidation)
if err != nil {
log.Error().Err(err).Msg("invalid image tag")
return false, nil
}
log.Info().Msg("pushing image to docker registry")
if err := pushDockerImage(ctx, log, img, tag); err != nil {
log.Error().Err(err).Msg("unable to push docker image")
return false, nil
}
}
return true, nil
}
func resolveBaseImage(ctx context.Context, log zerolog.Logger, p *daemonpb.DockerExportParams) (v1.Image, error) {
baseImgTag := p.BaseImageTag
if baseImgTag == "" || baseImgTag == "scratch" {
return empty.Image, nil
}
// Try to get it from the daemon if it exists.
log.Info().Msgf("resolving base image %s", baseImgTag)
baseImgRef, err := name.ParseReference(baseImgTag)
if err != nil {
return nil, errors.Wrap(err, "parse base image")
}
img, err := daemon.Image(baseImgRef)
if err != nil {
log.Info().Msg("could not get image from local daemon, fetching it remotely")
keychain := authn.DefaultKeychain
img, err = remote.Image(baseImgRef, remote.WithAuthFromKeychain(keychain), remote.WithContext(ctx))
if err != nil {
return nil, errors.Wrap(err, "unable to fetch image")
}
// If the user requested to push the image locally, save the remote image locally as well.
if p.LocalDaemonTag != "" {
if tag, err := name.NewTag(baseImgTag, name.WeakValidation); err == nil {
log.Info().Msgf("saving remote image %s to local docker daemon", baseImgTag)
if _, err = daemon.Write(tag, img); err != nil {
log.Warn().Err(err).Msg("unable to save remote image to local docker daemon, skipping")
} else {
log.Info().Msgf("saved remote image to local docker daemon")
}
}
}
}
return img, nil
}
func pushDockerImage(ctx context.Context, log zerolog.Logger, img v1.Image, destination name.Tag) error {
log.Info().Msg("pushing docker image to container registry")
keychain := authn.DefaultKeychain
if err := remote.Write(destination, img, remote.WithAuthFromKeychain(keychain), remote.WithContext(ctx)); err != nil {
return errors.WithStack(err)
}
log.Info().Msg("successfully pushed docker image")
return nil
}