-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
274 lines (260 loc) · 8 KB
/
main.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
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"log"
"os"
"path/filepath"
"strings"
"github.com/andrewbaxter/dinker/dinkerlib"
imagecopy "github.com/containers/image/v5/copy"
"github.com/containers/image/v5/manifest"
"github.com/containers/image/v5/oci/archive"
ocidir "github.com/containers/image/v5/oci/layout"
"github.com/containers/image/v5/signature"
"github.com/containers/image/v5/transports/alltransports"
"github.com/containers/image/v5/types"
)
type RegistryCreds struct {
User string `json:"user"`
Password string `json:"password"`
}
type ConfigDest struct {
Ref string `json:"ref"`
User string `json:"user"`
Password string `json:"password"`
Http bool `json:"http"`
Host string `json:"host"`
}
type Config struct {
From dinkerlib.AbsPath `json:"from"`
FromPull string `json:"from_pull"`
FromUser string `json:"from_user"`
FromPassword string `json:"from_password"`
FromHttp bool `json:"from_http"`
FromHost string `json:"from_host"`
Dests []ConfigDest `json:"dests"`
Architecture string `json:"arch"`
Os string `json:"os"`
Files []dinkerlib.BuildImageArgsFile `json:"files"`
AddEnv map[string]string `json:"add_env"`
ClearEnv bool `json:"clear_env"`
WorkingDir string `json:"working_dir"`
User string `json:"user"`
Entrypoint []string `json:"entrypoint"`
Cmd []string `json:"cmd"`
Ports []dinkerlib.BuildImageArgsPort `json:"ports"`
Labels map[string]string `json:"labels"`
StopSignal string `json:"stop_signal"`
}
func main0() error {
if len(os.Args) != 2 {
return fmt.Errorf("must have one argument: path to config json file")
}
var args0 []byte
if os.Args[1] == "-" {
var err error
args0, err = io.ReadAll(os.Stdin)
if err != nil {
return fmt.Errorf("error reading config from stdin: %w", err)
}
} else {
var err error
args0, err = os.ReadFile(os.Args[1])
if err != nil {
return fmt.Errorf("error reading config at %s: %w", os.Args[1], err)
}
}
var config Config
err := json.Unmarshal(args0, &config)
if err != nil {
return fmt.Errorf("error parsing config json at %s: %w", os.Args[1], err)
}
if config.From == "" && config.Os == "" && config.Architecture == "" {
return fmt.Errorf("missing FROM ref in config")
}
if len(config.Files) == 0 {
return fmt.Errorf("missing files to add in config")
}
if len(config.Dests) == 0 {
return fmt.Errorf("missing dests in config")
}
var policy *signature.Policy
if _, err := os.Stat("/etc/containers/policy.json"); !os.IsNotExist(err) {
var err error
policy, err = signature.DefaultPolicy(nil)
if err != nil {
return fmt.Errorf("error setting up docker registry client policy context signature: %w", err)
}
} else {
policyJson, _ := json.Marshal(map[string]any{
"default": []any{
map[string]any{
"type": "insecureAcceptAnything",
},
},
"transports": map[string]any{
"docker-daemon": map[string]any{
"": []any{
map[string]any{"type": "insecureAcceptAnything"},
},
},
},
})
policy, err = signature.NewPolicyFromBytes(policyJson)
if err != nil {
return fmt.Errorf("error setting up docker registry client policy context signature: %w", err)
}
}
policyContext, err := signature.NewPolicyContext(policy)
if err != nil {
return fmt.Errorf("error setting up docker registry client policy context: %w", err)
}
if config.From != "" && !config.From.Exists() {
if config.FromPull == "" {
return fmt.Errorf("no FROM image exists at %s, and no pull ref configured to pull from", config.From)
}
log.Printf("Pulling from image...")
sourceRef, err := alltransports.ParseImageName(config.FromPull)
if err != nil {
return fmt.Errorf("error parsing FROM pull ref %s: %w", config.FromPull, err)
}
destRef, err := archive.Transport.ParseReference(config.From.Raw())
if err != nil {
panic(err)
}
var noHttpVerify types.OptionalBool
if config.FromHttp {
noHttpVerify = types.OptionalBoolTrue
}
_, err = imagecopy.Image(
context.TODO(),
policyContext,
destRef,
sourceRef,
&imagecopy.Options{
SourceCtx: &types.SystemContext{
DockerInsecureSkipTLSVerify: noHttpVerify,
DockerDaemonHost: config.FromHost,
DockerDaemonInsecureSkipTLSVerify: config.FromHttp,
OCIInsecureSkipTLSVerify: config.FromHttp,
DockerAuthConfig: &types.DockerAuthConfig{
Username: config.FromUser,
Password: config.FromPassword,
},
},
},
)
if err != nil {
return fmt.Errorf("error pulling FROM image %s: %w", config.FromPull, err)
}
log.Printf("Pulling from image... done.")
}
if err := os.MkdirAll(os.TempDir(), 0o755); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("temp dir doesn't exist and couldn't create it, unable to write generated image: %w", err)
}
t, err := os.MkdirTemp("", ".dinker-image-*")
if err != nil {
return fmt.Errorf("unable to create temp file to write generated image to: %w", err)
}
t0, err := filepath.Abs(t)
if err != nil {
panic(err)
}
destDirPath := dinkerlib.AbsPath(t0)
defer func() {
if err := os.RemoveAll(destDirPath.Raw()); err != nil {
log.Printf("Error deleting temp image dir at %s: %s", destDirPath, err)
}
}()
log.Printf("Building image...")
hash, err := dinkerlib.BuildImage(dinkerlib.BuildImageArgs{
FromPath: config.From,
Architecture: config.Architecture,
Os: config.Os,
Files: config.Files,
ClearEnv: config.ClearEnv,
AddEnv: config.AddEnv,
WorkingDir: config.WorkingDir,
User: config.User,
Entrypoint: config.Entrypoint,
Cmd: config.Cmd,
Ports: config.Ports,
StopSignal: config.StopSignal,
Labels: config.Labels,
DestDirPath: destDirPath,
})
if err != nil {
return fmt.Errorf("error building image: %w", err)
}
log.Printf("Building image... done.")
sourceRef, err := ocidir.Transport.ParseReference(destDirPath.Raw())
if err != nil {
panic(err)
}
for i, dest := range config.Dests {
destString := dest.Ref
if destString == "" {
panic(fmt.Sprintf("Missing ref in dest %d", i))
}
for k, v := range map[string]string{
"hash": hash,
"short_hash": hash[:8],
} {
destString = strings.ReplaceAll(destString, fmt.Sprintf("{%s}", k), v)
}
destRef, err := alltransports.ParseImageName(destString)
if err != nil {
return fmt.Errorf("invalid dest image ref %s: %w", destString, err)
}
log.Printf("Pushing to %s...", destString)
var noHttpVerify types.OptionalBool
if dest.Http {
noHttpVerify = types.OptionalBoolTrue
}
destSysCtx := types.SystemContext{
DockerInsecureSkipTLSVerify: noHttpVerify,
DockerDaemonHost: dest.Host,
DockerDaemonInsecureSkipTLSVerify: dest.Http,
OCIInsecureSkipTLSVerify: dest.Http,
DockerAuthConfig: &types.DockerAuthConfig{
Username: dest.User,
Password: dest.Password,
},
}
destImg, err := destRef.NewImageDestination(context.TODO(), &destSysCtx)
if err != nil {
panic(err)
}
manifestFormat := ""
for _, format := range destImg.SupportedManifestMIMETypes() {
// Prefer docker manifest
if format == manifest.DockerV2Schema2MediaType {
manifestFormat = format
}
}
_, err = imagecopy.Image(
context.TODO(),
policyContext,
destRef,
sourceRef,
&imagecopy.Options{
ForceManifestMIMEType: manifestFormat,
DestinationCtx: &destSysCtx,
},
)
if err != nil {
return fmt.Errorf("error uploading image: %w", err)
}
log.Printf("Pushing to %s... done.", dest.Ref)
}
return nil
}
func main() {
err := main0()
if err != nil {
log.Fatalf("Exiting with fatal error: %s", err)
}
}