forked from rkt/rkt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
docker2aci.go
297 lines (250 loc) · 9.64 KB
/
docker2aci.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
// Copyright 2015 CoreOS, Inc.
//
// 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 docker2aci implements a simple library for converting docker images to
// App Container Images (ACIs).
package docker2aci
import (
"archive/tar"
"compress/gzip"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
"github.com/coreos/rkt/Godeps/_workspace/src/github.com/appc/docker2aci/lib/backend/file"
"github.com/coreos/rkt/Godeps/_workspace/src/github.com/appc/docker2aci/lib/backend/repository"
"github.com/coreos/rkt/Godeps/_workspace/src/github.com/appc/docker2aci/lib/common"
"github.com/coreos/rkt/Godeps/_workspace/src/github.com/appc/docker2aci/lib/types"
"github.com/coreos/rkt/Godeps/_workspace/src/github.com/appc/docker2aci/lib/util"
"github.com/coreos/rkt/Godeps/_workspace/src/github.com/appc/docker2aci/tarball"
"github.com/coreos/rkt/Godeps/_workspace/src/github.com/appc/spec/pkg/acirenderer"
"github.com/coreos/rkt/Godeps/_workspace/src/github.com/appc/spec/schema"
appctypes "github.com/coreos/rkt/Godeps/_workspace/src/github.com/appc/spec/schema/types"
)
type Docker2ACIBackend interface {
GetImageInfo(dockerUrl string) ([]string, *types.ParsedDockerURL, error)
BuildACI(layerID string, dockerURL *types.ParsedDockerURL, outputDir string, curPWl []string, compress bool) (string, *schema.ImageManifest, error)
}
// Convert generates ACI images from docker registry URLs.
// It takes as input a dockerURL of the form:
//
// {docker registry URL}/{image name}:{tag}
//
// It then gets all the layers of the requested image and converts each of
// them to ACI.
// If the squash flag is true, it squashes all the layers in one file and
// places this file in outputDir; if it is false, it places every layer in its
// own ACI in outputDir.
// username and password can be passed if the image needs authentication.
// It returns the list of generated ACI paths.
func Convert(dockerURL string, squash bool, outputDir string, username string, password string) ([]string, error) {
repositoryBackend := repository.NewRepositoryBackend(username, password)
return convertReal(repositoryBackend, dockerURL, squash, outputDir)
}
// ConvertFile generates ACI images from a file generated with "docker save".
// If there are several images/tags in the file, a particular image can be
// chosen with the syntax:
//
// {docker registry URL}/{image name}:{tag}
//
// It takes as input the docker-generated file
//
// If the squash flag is true, it squashes all the layers in one file and
// places this file in outputDir; if it is false, it places every layer in its
// own ACI in outputDir.
// It returns the list of generated ACI paths.
func ConvertFile(dockerURL string, filePath string, squash bool, outputDir string) ([]string, error) {
f, err := os.Open(filePath)
if err != nil {
return nil, fmt.Errorf("error opening file: %v", err)
}
defer f.Close()
fileBackend := file.NewFileBackend(f)
return convertReal(fileBackend, dockerURL, squash, outputDir)
}
// GetIndexName returns the docker index server from a docker URL.
func GetIndexName(dockerURL string) string {
index, _ := common.SplitReposName(dockerURL)
return index
}
// GetDockercfgAuth reads a ~/.dockercfg file and returns the username and password
// of the given docker index server.
func GetDockercfgAuth(indexServer string) (string, string, error) {
return common.GetAuthInfo(indexServer)
}
func convertReal(backend Docker2ACIBackend, dockerURL string, squash bool, outputDir string) ([]string, error) {
util.Debug("Getting image info...")
ancestry, parsedDockerURL, err := backend.GetImageInfo(dockerURL)
if err != nil {
return nil, err
}
layersOutputDir := outputDir
if squash {
layersOutputDir, err = ioutil.TempDir("", "docker2aci-")
if err != nil {
return nil, fmt.Errorf("error creating dir: %v", err)
}
defer os.RemoveAll(layersOutputDir)
}
conversionStore := NewConversionStore()
var images acirenderer.Images
var aciLayerPaths []string
var curPwl []string
for i := len(ancestry) - 1; i >= 0; i-- {
layerID := ancestry[i]
// only compress individual layers if we're not squashing
aciPath, manifest, err := backend.BuildACI(layerID, parsedDockerURL, layersOutputDir, curPwl, !squash)
if err != nil {
return nil, fmt.Errorf("error building layer: %v", err)
}
key, err := conversionStore.WriteACI(aciPath)
if err != nil {
return nil, fmt.Errorf("error inserting in the conversion store: %v", err)
}
images = append(images, acirenderer.Image{Im: manifest, Key: key, Level: uint16(i)})
aciLayerPaths = append(aciLayerPaths, aciPath)
curPwl = manifest.PathWhitelist
}
// acirenderer expects images in order from upper to base layer
images = util.ReverseImages(images)
if squash {
squashedImagePath, err := SquashLayers(images, conversionStore, *parsedDockerURL, outputDir)
if err != nil {
return nil, fmt.Errorf("error squashing image: %v", err)
}
aciLayerPaths = []string{squashedImagePath}
}
return aciLayerPaths, nil
}
// SquashLayers receives a list of ACI layer file names ordered from base image
// to application image and squashes them into one ACI
func SquashLayers(images []acirenderer.Image, aciRegistry acirenderer.ACIRegistry, parsedDockerURL types.ParsedDockerURL, outputDir string) (string, error) {
util.Debug("Squashing layers...")
util.Debug("Rendering ACI...")
renderedACI, err := acirenderer.GetRenderedACIFromList(images, aciRegistry)
if err != nil {
return "", fmt.Errorf("error rendering squashed image: %v", err)
}
manifests, err := getManifests(renderedACI, aciRegistry)
if err != nil {
return "", fmt.Errorf("error getting manifests: %v", err)
}
squashedFilename := getSquashedFilename(parsedDockerURL)
squashedImagePath := path.Join(outputDir, squashedFilename)
squashedImageFile, err := os.Create(squashedImagePath)
if err != nil {
return "", err
}
defer squashedImageFile.Close()
util.Debug("Writing squashed ACI...")
if err := writeSquashedImage(squashedImageFile, renderedACI, aciRegistry, manifests); err != nil {
return "", fmt.Errorf("error writing squashed image: %v", err)
}
util.Debug("Validating squashed ACI...")
if err := common.ValidateACI(squashedImagePath); err != nil {
return "", fmt.Errorf("error validating image: %v", err)
}
util.Debug("ACI squashed!")
return squashedImagePath, nil
}
func getSquashedFilename(parsedDockerURL types.ParsedDockerURL) string {
squashedFilename := strings.Replace(parsedDockerURL.ImageName, "/", "-", -1)
if parsedDockerURL.Tag != "" {
squashedFilename += "-" + parsedDockerURL.Tag
}
squashedFilename += ".aci"
return squashedFilename
}
func getManifests(renderedACI acirenderer.RenderedACI, aciRegistry acirenderer.ACIRegistry) ([]schema.ImageManifest, error) {
var manifests []schema.ImageManifest
for _, aci := range renderedACI {
im, err := aciRegistry.GetImageManifest(aci.Key)
if err != nil {
return nil, err
}
manifests = append(manifests, *im)
}
return manifests, nil
}
func writeSquashedImage(outputFile *os.File, renderedACI acirenderer.RenderedACI, aciProvider acirenderer.ACIProvider, manifests []schema.ImageManifest) error {
gw := gzip.NewWriter(outputFile)
defer gw.Close()
outputWriter := tar.NewWriter(gw)
defer outputWriter.Close()
for _, aciFile := range renderedACI {
rs, err := aciProvider.ReadStream(aciFile.Key)
if err != nil {
return err
}
defer rs.Close()
squashWalker := func(t *tarball.TarFile) error {
cleanName := filepath.Clean(t.Name())
if _, ok := aciFile.FileMap[cleanName]; ok {
// we generate and add the squashed manifest later
if cleanName == "manifest" {
return nil
}
if err := outputWriter.WriteHeader(t.Header); err != nil {
return fmt.Errorf("error writing header: %v", err)
}
if _, err := io.Copy(outputWriter, t.TarStream); err != nil {
return fmt.Errorf("error copying file into the tar out: %v", err)
}
}
return nil
}
tr := tar.NewReader(rs)
if err := tarball.Walk(*tr, squashWalker); err != nil {
return err
}
}
if err := common.WriteRootfsDir(outputWriter); err != nil {
return err
}
finalManifest := mergeManifests(manifests)
if err := common.WriteManifest(outputWriter, finalManifest); err != nil {
return err
}
return nil
}
func mergeManifests(manifests []schema.ImageManifest) schema.ImageManifest {
// FIXME(iaguis) we take app layer's manifest as the final manifest for now
manifest := manifests[0]
manifest.Dependencies = nil
layerIndex := -1
for i, l := range manifest.Labels {
if l.Name.String() == "layer" {
layerIndex = i
}
}
if layerIndex != -1 {
manifest.Labels = append(manifest.Labels[:layerIndex], manifest.Labels[layerIndex+1:]...)
}
// this can't fail because the old name is legal
nameWithoutLayerID, _ := appctypes.NewACName(stripLayerID(manifest.Name.String()))
manifest.Name = *nameWithoutLayerID
// once the image is squashed, we don't need a pathWhitelist
manifest.PathWhitelist = nil
return manifest
}
// striplayerID strips the layer ID from an app name:
//
// myregistry.com/organization/app-name-85738f8f9a7f1b04b5329c590ebcb9e425925c6d0984089c43a022de4f19c281
// myregistry.com/organization/app-name
func stripLayerID(layerName string) string {
n := strings.LastIndex(layerName, "-")
return layerName[:n]
}