-
Notifications
You must be signed in to change notification settings - Fork 173
/
main.go
333 lines (270 loc) · 9.78 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
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
// Copyright 2016-2017 VMware, Inc. All Rights Reserved.
//
// 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 main
import (
"context"
"flag"
"fmt"
"io"
"os"
"path"
"runtime/debug"
"runtime/trace"
"strings"
"sync"
"time"
log "github.com/Sirupsen/logrus"
"github.com/docker/docker/pkg/streamformatter"
"github.com/docker/docker/reference"
"github.com/docker/docker/registry"
"github.com/go-openapi/runtime"
rc "github.com/go-openapi/runtime/client"
"github.com/pkg/profile"
"github.com/vmware/vic/lib/apiservers/engine/proxy"
apiclient "github.com/vmware/vic/lib/apiservers/portlayer/client"
vicarchive "github.com/vmware/vic/lib/archive"
"github.com/vmware/vic/lib/constants"
"github.com/vmware/vic/lib/imagec"
optrace "github.com/vmware/vic/pkg/trace"
"github.com/vmware/vic/pkg/version"
)
var (
imageCOptions = ImageCOptions{}
// https://raw.githubusercontent.com/docker/docker/master/distribution/pull_v2.go
sf = streamformatter.NewJSONStreamFormatter()
)
const (
PullImage = "pull"
PushImage = "push"
ListLayers = "listlayers"
Save = "save"
)
// ImageCOptions wraps the cli arguments
type ImageCOptions struct {
imageName string
options imagec.Options
logfile string
stdout bool
debug bool
profiling string
tracing bool
operation string
}
func init() {
flag.StringVar(&imageCOptions.imageName, "reference", "", "Name of the reference")
flag.StringVar(&imageCOptions.options.Destination, "destination", imagec.DefaultDestination, "Destination directory")
flag.StringVar(&imageCOptions.options.Host, "host", imagec.DefaultPortLayerHost, "Host that runs portlayer API (FQDN:port format)")
flag.StringVar(&imageCOptions.logfile, "logfile", imagec.DefaultLogfile, "Path of the imagec log file")
flag.StringVar(&imageCOptions.options.Username, "username", "", "Username")
flag.StringVar(&imageCOptions.options.Password, "password", "", "Password")
flag.DurationVar(&imageCOptions.options.Timeout, "timeout", imagec.DefaultHTTPTimeout, "HTTP timeout")
flag.BoolVar(&imageCOptions.stdout, "stdout", false, "Enable writing to stdout")
flag.BoolVar(&imageCOptions.debug, "debug", false, "Show debug logging")
flag.BoolVar(&imageCOptions.options.InsecureSkipVerify, "insecure-skip-verify", false, "Don't verify certificates when fetching images")
flag.BoolVar(&imageCOptions.options.InsecureAllowHTTP, "insecure-allow-http", false, "Uses unencrypted connections when fetching images")
flag.BoolVar(&imageCOptions.options.Standalone, "standalone", false, "Disable port-layer integration")
flag.StringVar(&imageCOptions.profiling, "profile.mode", "", "Enable profiling mode, one of [cpu, mem, block]")
flag.BoolVar(&imageCOptions.tracing, "tracing", false, "Enable runtime tracing")
flag.StringVar(&imageCOptions.operation, "operation", "pull", "Pull image/push image/listlayers/save image")
flag.StringVar(&imageCOptions.options.Registry, "registry", registry.DefaultV2Registry.Host, "Registry to pull/push images (default: registry-1.docker.io)")
flag.StringVar(&imageCOptions.options.ImageStore, "image-store", registry.DefaultV2Registry.Host, "portlayer image store name or url used to query image data")
flag.Parse()
var err error
if imageCOptions.options.Reference, err = reference.ParseNamed(imageCOptions.imageName); err != nil {
panic(err)
}
}
func main() {
defer func() {
if r := recover(); r != nil {
_, err := fmt.Fprintf(os.Stderr, string(sf.FormatError(fmt.Errorf("%s : %s", r, debug.Stack()))))
if err != nil {
//do this to pass security check
}
}
}()
if version.Show() {
_, err := fmt.Fprintf(os.Stdout, "%s\n", version.String())
if err != nil {
panic(err)
}
return
}
// Enable profiling if mode is set
switch imageCOptions.profiling {
case "cpu":
defer profile.Start(profile.CPUProfile, profile.ProfilePath("."), profile.Quiet).Stop()
case "mem":
defer profile.Start(profile.MemProfile, profile.ProfilePath("."), profile.Quiet).Stop()
case "block":
defer profile.Start(profile.BlockProfile, profile.ProfilePath("."), profile.Quiet).Stop()
default:
// do nothing
}
// Register our custom Error hook
log.AddHook(NewErrorHook(os.Stderr))
// Enable runtime tracing if tracing is true
if imageCOptions.tracing {
tracing, err := os.Create(time.Now().Format("2006-01-02T150405.pprof"))
if err != nil {
log.Fatalf("Failed to create tracing logfile: %s", err)
}
defer tracing.Close()
if err := trace.Start(tracing); err != nil {
log.Fatalf("Failed to start tracing: %s", err)
}
defer trace.Stop()
}
// Open the log file
// #nosec: Expect file permissions to be 0600 or less
f, err := os.OpenFile(imageCOptions.logfile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
log.Fatalf("Failed to open the logfile %s: %s", imageCOptions.logfile, err)
}
defer f.Close()
// Initiliaze logger with default TextFormatter
log.SetFormatter(&log.TextFormatter{DisableColors: true, FullTimestamp: true})
// Set the log level
if imageCOptions.debug {
log.SetLevel(log.DebugLevel)
}
// SetOutput to log file and/or stdout
log.SetOutput(f)
if imageCOptions.stdout {
log.SetOutput(io.MultiWriter(os.Stdout, f))
}
op := optrace.NewOperation(context.Background(), "imagec")
switch imageCOptions.operation {
case PullImage:
options := imageCOptions.options
options.Outstream = os.Stdout
ic := imagec.NewImageC(options, streamformatter.NewJSONStreamFormatter())
if err := ic.PullImage(op); err != nil {
log.Fatalf("Pulling image failed due to %s\n", err)
}
case PushImage:
log.Errorf("The operation '%s' is not implemented\n", PushImage)
case ListLayers:
options := imageCOptions.options
options.Outstream = os.Stdout
ic := imagec.NewImageC(options, streamformatter.NewJSONStreamFormatter())
if err := ic.ListLayers(op); err != nil {
log.Fatalf("Listing layers for image failed due to %s\n", err)
}
case Save:
options := imageCOptions.options
options.Outstream = os.Stdout
ap := archiveProxy(options.Host)
ic := imagec.NewImageC(options, streamformatter.NewJSONStreamFormatter())
if err := saveImage(op, ap, ic); err != nil {
log.Fatalf("Saving image %s failed due to %s\n", options.Reference.String(), err)
}
default:
log.Errorf("The operation '%s' is not valid\n", imageCOptions.operation)
}
}
func saveImage(op optrace.Operation, ap proxy.VicArchiveProxy, ic *imagec.ImageC) error {
log.Debugf("Save image %s", ic.Options.Reference)
err := ic.ListLayers(op)
if err != nil {
return err
}
layers, err := ic.LayersToDownload(op)
if err != nil {
return err
}
dest := imagec.DestinationDirectory(ic.Options)
var wg sync.WaitGroup
errChan := make(chan error, len(layers))
for i := len(layers) - 1; i >= 0; i-- {
if layers[i].ID == constants.ScratchLayerID {
continue
}
wg.Add(1)
go func(pid, cid string) {
defer wg.Done()
var err error
log.Debugf("parent id: %s, layer id: %s", pid, cid)
defer func() {
errChan <- err
}()
fileDir := path.Join(dest, cid)
err = os.MkdirAll(fileDir, 0755) /* #nosec */
if err != nil {
return
}
filePath := path.Join(fileDir, cid+".tar")
log.Debugf("save layer %s to file %s", cid, filePath)
err = writeArchiveFile(ap, ic.ImageStore, ic.ImageStore, cid, pid, filePath)
}(layers[i].Parent, layers[i].ID)
}
wg.Wait()
close(errChan)
var errs []string
for e := range errChan {
if e == nil {
continue
}
errs = append(errs, e.Error())
}
if len(errs) > 0 {
return fmt.Errorf("save image layers failed: %s", strings.Join(errs, ","))
}
return nil
}
func portlayerClient(portLayerAddr string) *apiclient.PortLayer {
t := rc.New(portLayerAddr, "/", []string{"http"})
t.Consumers["application/x-tar"] = runtime.ByteStreamConsumer()
t.Consumers["application/octet-stream"] = runtime.ByteStreamConsumer()
t.Producers["application/x-tar"] = runtime.ByteStreamProducer()
t.Producers["application/octet-stream"] = runtime.ByteStreamProducer()
client := apiclient.New(t, nil)
return client
}
func archiveProxy(portLayerAddr string) proxy.VicArchiveProxy {
plClient := portlayerClient(portLayerAddr)
archiveProxy := proxy.NewArchiveProxy(plClient)
return archiveProxy
}
func writeArchiveFile(archiveProxy proxy.VicArchiveProxy, store, ancestorStore, layerID, ancestorID, archivePath string) error {
var filterSpec vicarchive.FilterSpec
op := optrace.NewOperation(context.Background(), "export layer %s:%s", layerID, ancestorID)
//Initialize an archive stream from the portlayer for the layer
ar, err := archiveProxy.ArchiveExportReader(op, store, ancestorStore, layerID, ancestorID, true, filterSpec)
if err != nil || ar == nil {
return fmt.Errorf("Failed to get reader for layer %s", layerID)
}
log.Infof("Obtain archive reader for layer %s, parent %s", layerID, ancestorID)
// #nosec - there's nothing secret/sensitive about these image layer files
tarFile, err := os.OpenFile(archivePath, os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
msg := fmt.Sprintf("Failed to create tmp file: %s", err.Error())
log.Info(msg)
return fmt.Errorf(msg)
}
defer tarFile.Close()
_, err = io.Copy(tarFile, ar)
if err != nil {
msg := fmt.Sprintf("Failed to read from acrhive stream: %s", err.Error())
log.Info(msg)
return fmt.Errorf(msg)
}
ar.Close()
if err = tarFile.Sync(); err != nil {
msg := fmt.Sprintf("Failed to flush tar file: %s", err.Error())
log.Info(msg)
return fmt.Errorf(msg)
}
return nil
}