-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
232 lines (186 loc) · 5.37 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
package main
import (
"archive/tar"
"bytes"
"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/mutate"
"github.com/google/go-containerregistry/pkg/v1/remote"
"github.com/google/go-containerregistry/pkg/v1/tarball"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"fmt"
"github.com/alexflint/go-arg"
"github.com/pkg/errors"
)
type params struct {
Target string `arg:"-t,required" help:"destination image GCR-URL"`
BaseImage string `arg:"-b,required" help:"base image GCR-URL"`
Files []string `arg:"-f,separate" help:"Specify a file to add"`
Env []string `arg:"-e,separate" help:"Environment Variables"`
Cmd string `arg:"-c" help:"Command to run when starting the container"`
}
func main() {
if err := run(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %s", err.Error())
os.Exit(1)
}
}
func run() error {
p := ¶ms{}
arg.MustParse(p)
fmt.Println("Checking base image...")
baseImage, _, err := getImage(p.BaseImage)
if err != nil {
return err
}
fmt.Println("Building new image...")
finalImage, err := buildNewImage(p.Files, p.Env, p.Cmd, baseImage)
if err != nil {
return err
}
fmt.Println("Pushing...")
if err := pushImage(finalImage, p.Target); err != nil {
return err
}
fmt.Println("Done.")
return nil
}
func buildNewImage(files, env []string, cmd string, baseImage v1.Image) (v1.Image, error) {
image, err := applyConfig(baseImage, env, cmd)
if err != nil {
return nil, errors.Wrap(err, "applying config")
}
image, err = addNewLayerFromFiles(image, files)
if err != nil {
return nil, errors.Wrap(err, "adding layer")
}
return image, nil
}
func applyConfig(image v1.Image, env []string, cmd string) (v1.Image, error) {
imageConfig, err := image.ConfigFile()
if err != nil {
return nil, errors.Wrap(err, "creating config file")
}
imageConfig.Config.Env = env
imageConfig.Config.Cmd = []string{cmd}
newImage, err := mutate.Config(image, imageConfig.Config)
if err != nil {
return nil, errors.Wrap(err, "applying new config")
}
newImage, err = mutate.CreatedAt(newImage, v1.Time{Time: time.Now()})
if err != nil {
return nil, errors.Wrap(err, "setting created-at timestamp")
}
return newImage, nil
}
func addNewLayerFromFiles(image v1.Image, files []string) (v1.Image, error) {
// the .tar file from the passed files will be our new layer
bb := bytes.Buffer{}
if err := createTarFile(files, &bb); err != nil {
return nil, errors.Wrap(err, "creating tar archive")
}
// wrapper for LayerFromOpener
opener := func() (io.ReadCloser, error) {
return ioutil.NopCloser(bytes.NewReader(bb.Bytes())), nil
}
// create new layer from our .tar
l, err := tarball.LayerFromOpener(opener)
if err != nil {
return nil, errors.Wrap(err, "creating layer")
}
image, err = mutate.AppendLayers(image, l)
if err != nil {
return nil, errors.Wrap(err, "appending Layer")
}
return image, nil
}
func pushImage(image v1.Image, destURL string) error {
destRef, err := name.ParseReference(destURL, name.WeakValidation)
if err != nil {
return errors.Wrapf(err, "parsing destination URL (%s)", destURL)
}
pushAuth, err := authn.DefaultKeychain.Resolve(destRef.Context().Registry)
if err != nil {
return errors.Wrapf(err, "authenticating target (%s)", destURL)
}
return remote.Write(destRef, image, remote.WithAuth(pushAuth), remote.WithTransport(http.DefaultTransport))
}
func getImage(sourceURL string) (v1.Image, name.Repository, error) {
ref, err := parseImageURL(sourceURL)
if err != nil {
return nil, name.Repository{}, errors.Wrap(err, "parsing source URL")
}
auth, err := authn.DefaultKeychain.Resolve(ref.Context().Registry)
if err != nil {
return nil, name.Repository{}, errors.Wrap(err, "authenticating")
}
img, err := remote.Image(ref, remote.WithAuth(auth), remote.WithTransport(http.DefaultTransport))
if err != nil {
return nil, name.Repository{}, errors.Wrap(err, "fetching")
}
return img, ref.Context(), nil
}
func parseImageURL(url string) (name.Reference, error) {
ref, err := name.ParseReference(url, name.WeakValidation)
if err != nil {
return nil, errors.Wrapf(err, "parsing url (%s)", url)
}
return ref, nil
}
// from https://github.com/verybluebot/tarinator-go/blob/master/tarinator.go
func createTarFile(paths []string, writer io.Writer) error {
tw := tar.NewWriter(writer)
defer tw.Close()
for _, i := range paths {
if err := tarwalk(i, tw); err != nil {
return err
}
}
return nil
}
func tarwalk(source string, tw *tar.Writer) error {
info, err := os.Stat(source)
if err != nil {
return err
}
var baseDir string
if info.IsDir() {
baseDir = filepath.Base(source)
}
return filepath.Walk(source,
func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
header, err := tar.FileInfoHeader(info, info.Name())
if err != nil {
return err
}
if baseDir != "" {
header.Name = filepath.ToSlash(filepath.Join(baseDir, strings.TrimPrefix(path, source)))
}
if err := tw.WriteHeader(header); err != nil {
return err
}
if info.IsDir() {
return nil
}
if !info.Mode().IsRegular() {
return nil
}
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
_, err = io.Copy(tw, file)
return err
})
}