This repository has been archived by the owner on May 22, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 158
/
main.go
234 lines (202 loc) · 5.03 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
package main
import (
"flag"
"fmt"
"io/ioutil"
"os"
"os/signal"
"strings"
"sync"
"syscall"
)
var (
buildVersion string
signals chan os.Signal
wg sync.WaitGroup
)
func shutdown(tempdir string) {
defer wg.Done()
<-signals
debugf("Removing tempdir %s\n", tempdir)
err := os.RemoveAll(tempdir)
if err != nil {
fatal(err)
}
}
func main() {
var from, input, output, tempdir, tag string
var keepTemp, version, last bool
flag.StringVar(&input, "i", "", "Read from a tar archive file, instead of STDIN")
flag.StringVar(&output, "o", "", "Write to a file, instead of STDOUT")
flag.StringVar(&tag, "t", "", "Repository name and tag for new image")
flag.StringVar(&from, "from", "", "Squash from layer ID (default: first FROM layer)")
flag.BoolVar(&last, "last", false, "Squash from last found layer ID (Inverts order for automatic root-layer selection")
flag.BoolVar(&keepTemp, "keepTemp", false, "Keep temp dir when done. (Useful for debugging)")
flag.BoolVar(&verbose, "verbose", false, "Enable verbose logging")
flag.BoolVar(&version, "v", false, "Print version information and quit")
flag.Usage = func() {
fmt.Printf("\nUsage: docker-squash [options]\n\n")
fmt.Printf("Squashes the layers of a tar archive on STDIN and streams it to STDOUT\n\n")
fmt.Printf("Options:\n")
flag.PrintDefaults()
}
flag.Parse()
if version {
fmt.Println(buildVersion)
return
}
var err error
tempdir, err = ioutil.TempDir("", "docker-squash")
if err != nil {
fatal(err)
}
if tag != "" && strings.Contains(tag, ":") {
parts := strings.Split(tag, ":")
if parts[0] == "" || parts[1] == "" {
fatalf("bad tag format: %s\n", tag)
}
}
signals = make(chan os.Signal, 1)
if !keepTemp {
wg.Add(1)
signal.Notify(signals, os.Interrupt, os.Kill, syscall.SIGTERM)
go shutdown(tempdir)
}
export, err := LoadExport(input, tempdir)
if err != nil {
fatal(err)
}
// Export may have multiple branches with the same parent.
// We can't handle that currently so abort.
for _, v := range export.Repositories {
commits := map[string]string{}
for tag, commit := range *v {
commits[commit] = tag
}
if len(commits) > 1 {
fatal("This image is a full repository export w/ multiple images in it. " +
"You need to generate the export from a specific image ID or tag.")
}
}
var start *ExportedImage
if last {
start = export.LastSquash()
// Can't find a previously squashed layer, use last FROM
if start == nil {
start = export.LastFrom()
}
} else {
start = export.FirstSquash()
// Can't find a previously squashed layer, use first FROM
if start == nil {
start = export.FirstFrom()
}
}
// Can't find a FROM, default to root
if start == nil {
start = export.Root()
}
if from != "" {
if from == "root" {
start = export.Root()
} else {
start, err = export.GetById(from)
if err != nil {
fatal(err)
}
}
}
if start == nil {
fatalf("no layer matching %s\n", from)
return
}
// extract each "layer.tar" to "layer" dir
err = export.ExtractLayers()
if err != nil {
fatal(err)
return
}
// insert a new layer after our squash point
newEntry, err := export.InsertLayer(start.LayerConfig.Id)
if err != nil {
fatal(err)
return
}
debugf("Inserted new layer %s after %s\n", newEntry.LayerConfig.Id[0:12],
newEntry.LayerConfig.Parent[0:12])
if verbose {
e := export.Root()
for {
if e == nil {
break
}
cmd := strings.Join(e.LayerConfig.ContainerConfig().Cmd, " ")
if len(cmd) > 60 {
cmd = cmd[:60]
}
if e.LayerConfig.Id == newEntry.LayerConfig.Id {
debugf(" -> %s %s\n", e.LayerConfig.Id[0:12], cmd)
} else {
debugf(" - %s %s\n", e.LayerConfig.Id[0:12], cmd)
}
e = export.ChildOf(e.LayerConfig.Id)
}
}
// squash all later layers into our new layer
err = export.SquashLayers(newEntry, newEntry)
if err != nil {
fatal(err)
return
}
debugf("Tarring up squashed layer %s\n", newEntry.LayerConfig.Id[:12])
// create a layer.tar from our squashed layer
err = newEntry.TarLayer()
if err != nil {
fatal(err)
}
debugf("Removing extracted layers\n")
// remove our expanded "layer" dirs
err = export.RemoveExtractedLayers()
if err != nil {
fatal(err)
}
if tag != "" {
tagPart := "latest"
repoPart := tag
parts := strings.Split(tag, ":")
if len(parts) > 1 {
repoPart = parts[0]
tagPart = parts[1]
}
tagInfo := TagInfo{}
layer := export.LastChild()
tagInfo[tagPart] = layer.LayerConfig.Id
export.Repositories[repoPart] = &tagInfo
debugf("Tagging %s as %s:%s\n", layer.LayerConfig.Id[0:12], repoPart, tagPart)
err := export.WriteRepositoriesJson()
if err != nil {
fatal(err)
}
}
ow := os.Stdout
if output != "" {
var err error
ow, err = os.Create(output)
if err != nil {
fatal(err)
}
debugf("Tarring new image to %s\n", output)
} else {
debugf("Tarring new image to STDOUT\n")
}
// bundle up the new image
err = export.TarLayers(ow)
if err != nil {
fatal(err)
}
debug("Done. New image created.")
// print our new history
export.PrintHistory()
signals <- os.Interrupt
wg.Wait()
}