Skip to content

Commit

Permalink
unify apk installed db for base layer
Browse files Browse the repository at this point in the history
Signed-off-by: Avi Deitcher <avi@deitcher.net>
  • Loading branch information
deitch committed Nov 30, 2022
1 parent bbd6231 commit 941d1ee
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 1 deletion.
78 changes: 78 additions & 0 deletions src/cmd/linuxkit/moby/apk_tarwriter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package moby

import (
"archive/tar"
"bytes"
)

// apkTarWriter apk-aware tar writer that consolidates installed database, so that
// it can be called multiple times and will do the union of all such databases,
// rather than overwriting the previous one.
const apkInstalledPath = "lib/apk/db/installed"

type apkTarWriter struct {
*tar.Writer
dbs [][]byte
current *bytes.Buffer
}

func newAPKTarWriter(w *tar.Writer) *apkTarWriter {
return &apkTarWriter{
Writer: w,
}
}

func (a *apkTarWriter) WriteHeader(hdr *tar.Header) error {
if a.current != nil {
a.dbs = append(a.dbs, a.current.Bytes())
a.current = nil
}
if hdr.Name == apkInstalledPath {
a.current = new(bytes.Buffer)
}
return a.Writer.WriteHeader(hdr)
}
func (a *apkTarWriter) Write(b []byte) (int, error) {
if a.current != nil {
a.current.Write(b)
}
return a.Writer.Write(b)
}

func (a *apkTarWriter) Close() error {
// before closing, write out the union of all the databases
if a.current != nil {
a.dbs = append(a.dbs, a.current.Bytes())
a.current = nil
}
if err := a.WriteAPKDB(); err != nil {
return err
}
return a.Writer.Close()
}

func (a *apkTarWriter) WriteAPKDB() error {
if len(a.dbs) > 1 {
// consolidate the databases
// calculate the size of the new database
var size int
for _, db := range a.dbs {
size += len(db)
size += 2 // 2 trailing newlines for each db
}
hdr := &tar.Header{
Name: apkInstalledPath,
Mode: 0o644,
Uid: 0,
Gid: 0,
Typeflag: tar.TypeReg,
Size: int64(size),
}
a.Writer.WriteHeader(hdr)
for _, db := range a.dbs {
a.Writer.Write(db)
a.Writer.Write([]byte{'\n', '\n'})
}
}
return nil
}
4 changes: 3 additions & 1 deletion src/cmd/linuxkit/moby/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,13 +168,15 @@ func Build(m Moby, w io.Writer, opts BuildOpts) error {
if len(m.Init) != 0 {
log.Infof("Add init containers:")
}
apkTar := newAPKTarWriter(iw)
for _, ii := range m.initRefs {
log.Infof("Process init image: %s", ii)
err := ImageTar(ii, "", iw, resolvconfSymlink, opts)
err := ImageTar(ii, "", apkTar, resolvconfSymlink, opts)
if err != nil {
return fmt.Errorf("Failed to build init tarball from %s: %v", ii, err)
}
}
apkTar.WriteAPKDB()

if len(m.Onboot) != 0 {
log.Infof("Add onboot containers:")
Expand Down

0 comments on commit 941d1ee

Please sign in to comment.