-
Notifications
You must be signed in to change notification settings - Fork 13
/
dlgrab.go
217 lines (193 loc) · 5.24 KB
/
dlgrab.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
package main
import (
"fmt"
flag "github.com/getgauge/mflag"
"github.com/fsouza/go-dockerclient"
"io/ioutil"
"net"
"net/http"
"os"
"os/signal"
"path/filepath"
"sync"
"syscall"
"time"
)
var layerLock sync.Mutex
var layerId string = ""
var logger = &Logger{}
var (
GITCOMMIT string
)
func main() {
var outDir string
var doDebug bool
var doHelp bool
var doTagRemove bool
var regFormat bool
helpFd := os.Stderr
flag.Usage = func() {
fmt.Fprintf(helpFd, "Usage for %s [flags...] LAYER\n", os.Args[0])
fmt.Fprintf(helpFd, " LAYER: layer id to export, or image name to export top layer of\n")
flag.PrintDefaults()
fmt.Fprintf(helpFd, "\n")
fmt.Fprintf(helpFd, " The DOCKER_HOST environment variable overrides the default location to find the docker daemon\n")
}
flag.BoolVar(&doHelp, []string{"h", "-help"}, false, "Print this help text")
flag.StringVar(&outDir, []string{"o", "-outdir"}, ".", "Directory to write layer to")
flag.BoolVar(&doTagRemove, []string{"-clean"}, false, "Remove the temporary tag after use\nWARNING: can trigger layer deletion if run on a layer with no children or other references")
flag.BoolVar(&doDebug, []string{"-debug"}, false, "Set log level to debug")
flag.BoolVar(®Format, []string{"-registry-format"}, false, "Output in the format a registry would use, rather than for an image export")
flag.Parse()
if len(flag.Args()) != 1 {
flag.Usage()
os.Exit(2)
}
imgId := flag.Arg(0)
if len(imgId) == 0 {
flag.Usage()
os.Exit(2)
}
if doHelp {
helpFd = os.Stdout
flag.Usage()
return
}
logger.Level = INFO
if doDebug {
logger.Level = DEBUG
}
logger.Debug("DLGrab version %s", GITCOMMIT)
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, os.Kill, os.Signal(syscall.SIGTERM))
go func() {
sig := <-c
logger.Debug("Received signal '%v', exiting\n", sig)
os.Exit(1)
}()
endpoint := os.Getenv("DOCKER_HOST")
if endpoint == "" {
endpoint = "unix:///var/run/docker.sock"
}
client, err := docker.NewClient(endpoint)
if err != nil {
logger.Error("%s", err.Error())
os.Exit(1)
}
layerLock.Lock()
imgJson, err := client.InspectImage(imgId)
if err != nil {
logger.Error("%s", err.Error())
os.Exit(1)
}
layerId = imgJson.ID
if layerId != imgId {
logger.Info("Full layer id found: %s", layerId)
}
layerLock.Unlock()
logger.Info("Layer folder will be dumped into %s", outDir)
layerLock.Lock()
layerOutDir := filepath.Join(outDir, layerId)
layerLock.Unlock()
err = os.Mkdir(layerOutDir, 0755)
if err != nil {
logger.Error("%s", err.Error())
os.Exit(1)
}
if !regFormat {
ioutil.WriteFile(filepath.Join(layerOutDir, "VERSION"), []byte("1.0"), 0644)
}
logger.Debug("Attempting to probe for available port")
laddr := net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 0}
sock, err := net.ListenTCP("tcp", &laddr)
if err != nil {
logger.Error("%s", err.Error())
os.Exit(1)
}
listenOn := fmt.Sprintf("127.0.0.1:%d", sock.Addr().(*net.TCPAddr).Port)
sock.Close()
logger.Debug("Starting shim registry on %s", listenOn)
go (func() {
if err := http.ListenAndServe(listenOn, NewHandler(outDir, regFormat)); err != nil {
logger.Error("%s", err.Error())
os.Exit(1)
}
})()
sleeps := []int{1, 5, 10, 100, 200, 500, 1000, 2000}
pingUrl := "http://" + listenOn + "/v1/_ping"
apiIsUp := false
logger.Debug("Waiting for shim registry to start by checking %s", pingUrl)
for _, ms := range sleeps {
logger.Debug("Sleeping %d ms before ping", ms)
time.Sleep(time.Duration(ms) * time.Millisecond)
resp, err := http.Get(pingUrl)
if err == nil {
resp.Body.Close()
apiIsUp = true
break
}
}
if !apiIsUp {
logger.Error("Shim registry took too long to come up")
os.Exit(1)
}
logger.Debug("Shim Registry Started")
err = dockerMain(client, listenOn, doTagRemove)
if err != nil {
logger.Error("%s", err)
os.Exit(1)
}
logger.Info("Export complete")
}
func dockerMain(client *docker.Client, regUrl string, removeTag bool) (err error) {
imgNiceName := "dlgrab_tmp"
imgName := regUrl + "/" + "dlgrab_push_staging_tmp"
imgTag := "latest"
logger.Debug("Tagging image into temporary repo")
tagOpts := docker.TagImageOptions{
Repo: imgName,
Tag: imgTag,
Force: true,
}
layerLock.Lock()
err = client.TagImage(layerId, tagOpts)
layerLock.Unlock()
if err != nil {
return
}
tagOpts.Repo = imgNiceName
layerLock.Lock()
err = client.TagImage(layerId, tagOpts)
layerLock.Unlock()
if err != nil {
return
}
logger.Debug("Pushing image")
pushOpts := docker.PushImageOptions{
Registry: "",
Name: imgName,
Tag: imgTag,
}
err = client.PushImage(pushOpts, docker.AuthConfiguration{})
if err != nil {
return
}
// Unfortunately even with no-prune docker will remove a layer if the
// tag we've removed is the only one left. As such, we do a dance to
// have *two* symbolic tags on the image so we can leave one that looks
// slightly more aesthetically pleasing in place.
removeOpts := docker.RemoveImageOptions{Force: false, NoPrune: true}
logger.Debug("Removing ugly temporary image tag")
err = client.RemoveImageExtended(imgName, removeOpts)
if err != nil {
return
}
if removeTag {
logger.Debug("Removing nice temporary image tag")
err = client.RemoveImageExtended(imgNiceName, removeOpts)
if err != nil {
return
}
}
return nil
}