From 835787be94ce668b788ed47e6c1e8c0358dcf932 Mon Sep 17 00:00:00 2001 From: Simone Gotti Date: Mon, 23 Mar 2015 15:08:46 +0100 Subject: [PATCH] rkt: move download code from cas remote to rkt fetch. As the download code is not really related to the cas remote, this patch factors it out from cas to rkt fetch. It doesn't change the existing code but just moves it (with the minimum needed changes) leaving additional refactoring for future patches. It's now rkt fetch that should get the remote, choose if the images needs to be downloaded, verify the signature and write it to the cas blob store and then update the remote. As a side effect it avoids the stdout printing done by cas.Remote.Download (remains the printing done by docker2aci) This will also help avoiding tricky things and code duplication for future etag and cache-control handling. See #319. --- cas/cas_test.go | 88 ----------------------- cas/remote.go | 175 +------------------------------------------- rkt/fetch.go | 179 +++++++++++++++++++++++++++++++++++++++++++++- rkt/fetch_test.go | 90 +++++++++++++++++++++++ 4 files changed, 267 insertions(+), 265 deletions(-) diff --git a/cas/cas_test.go b/cas/cas_test.go index 2ffed69..8e7eeb2 100644 --- a/cas/cas_test.go +++ b/cas/cas_test.go @@ -15,13 +15,10 @@ package cas import ( - "archive/tar" "bytes" "database/sql" "encoding/hex" "io/ioutil" - "net/http" - "net/http/httptest" "os" "testing" "time" @@ -51,91 +48,6 @@ func TestBlobStore(t *testing.T) { ds.Dump(false) } -func TestDownloading(t *testing.T) { - dir, err := ioutil.TempDir("", tstprefix) - if err != nil { - t.Fatalf("error creating tempdir: %v", err) - } - defer os.RemoveAll(dir) - - imj := `{ - "acKind": "ImageManifest", - "acVersion": "0.4.0", - "name": "example.com/test01" - }` - - entries := []*aci.ACIEntry{ - // An empty file - { - Contents: "hello", - Header: &tar.Header{ - Name: "rootfs/file01.txt", - Size: 5, - }, - }, - } - - aci, err := aci.NewACI(dir, imj, entries) - if err != nil { - t.Fatalf("error creating test tar: %v", err) - } - - // Rewind the ACI - if _, err := aci.Seek(0, 0); err != nil { - t.Fatalf("unexpected error: %v", err) - } - body, err := ioutil.ReadAll(aci) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Write(body) - })) - defer ts.Close() - - tests := []struct { - ACIURL string - SigURL string - body []byte - hit bool - }{ - // The Blob entry isn't used - {ts.URL, "", body, false}, - {ts.URL, "", body, true}, - } - - ds, err := NewStore(dir) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - - for _, tt := range tests { - _, ok, err := ds.GetRemote(tt.ACIURL) - if err != nil { - t.Fatalf("unexpected err: %v", err) - } - if tt.hit == false && ok { - panic("expected miss got a hit") - } - if tt.hit == true && !ok { - panic("expected a hit got a miss") - } - rem := NewRemote(tt.ACIURL, tt.SigURL) - _, aciFile, err := rem.Download(*ds, nil) - if err != nil { - t.Fatalf("error downloading aci: %v", err) - } - defer os.Remove(aciFile.Name()) - - _, err = rem.Store(*ds, aciFile, false) - if err != nil { - panic(err) - } - } - - ds.Dump(false) -} - func TestResolveKey(t *testing.T) { dir, err := ioutil.TempDir("", tstprefix) if err != nil { diff --git a/cas/remote.go b/cas/remote.go index af5f557..0dee92c 100644 --- a/cas/remote.go +++ b/cas/remote.go @@ -17,25 +17,7 @@ // key-value blob store: https://github.com/peterbourgon/diskv package cas -import ( - "database/sql" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "os" - "strings" - "time" - - "github.com/coreos/rocket/pkg/keystore" - - "github.com/coreos/rocket/Godeps/_workspace/src/github.com/appc/docker2aci/lib" - "github.com/coreos/rocket/Godeps/_workspace/src/github.com/appc/spec/aci" - - "github.com/coreos/rocket/Godeps/_workspace/src/github.com/mitchellh/ioprogress" - "github.com/coreos/rocket/Godeps/_workspace/src/golang.org/x/crypto/openpgp" -) +import "database/sql" func NewRemote(aciurl, sigurl string) *Remote { r := &Remote{ @@ -53,161 +35,6 @@ type Remote struct { BlobKey string } -// Download downloads and verifies the remote ACI. -// If Keystore is nil signature verification will be skipped. -// Download returns the signer, an *os.File representing the ACI, and an error if any. -// err will be nil if the ACI downloads successfully and the ACI is verified. -func (r Remote) Download(ds Store, ks *keystore.Keystore) (*openpgp.Entity, *os.File, error) { - var entity *openpgp.Entity - u, err := url.Parse(r.ACIURL) - if err != nil { - return nil, nil, fmt.Errorf("error parsing ACI url: %v", err) - } - if u.Scheme == "docker" { - registryURL := strings.TrimPrefix(r.ACIURL, "docker://") - - tmpDir, err := ds.tmpDir() - if err != nil { - return nil, nil, fmt.Errorf("error creating temporary dir for docker to ACI conversion: %v", err) - } - - acis, err := docker2aci.Convert(registryURL, true, tmpDir) - if err != nil { - return nil, nil, fmt.Errorf("error converting docker image to ACI: %v", err) - } - - aciFile, err := os.Open(acis[0]) - if err != nil { - return nil, nil, fmt.Errorf("error opening squashed ACI file: %v", err) - } - - return nil, aciFile, nil - } - - var sigTempFile *os.File - if ks != nil { - fmt.Printf("Downloading signature from %v\n", r.SigURL) - sigTempFile, err = downloadSignatureFile(r.SigURL) - if err != nil { - return nil, nil, fmt.Errorf("error downloading the signature file: %v", err) - } - defer sigTempFile.Close() - defer os.Remove(sigTempFile.Name()) - } - - acif, err := downloadACI(ds, r.ACIURL) - if err != nil { - return nil, acif, fmt.Errorf("error downloading the aci image: %v", err) - } - - if ks != nil { - manifest, err := aci.ManifestFromImage(acif) - if err != nil { - return nil, acif, err - } - - if _, err := acif.Seek(0, 0); err != nil { - return nil, acif, err - } - if _, err := sigTempFile.Seek(0, 0); err != nil { - return nil, acif, err - } - if entity, err = ks.CheckSignature(manifest.Name.String(), acif, sigTempFile); err != nil { - return nil, acif, err - } - } - - if _, err := acif.Seek(0, 0); err != nil { - return nil, acif, err - } - return entity, acif, nil -} - -// TODO: add locking -// Store stores the ACI represented by r in the target data store. -func (r Remote) Store(ds Store, aci io.Reader, latest bool) (*Remote, error) { - key, err := ds.WriteACI(aci, latest) - if err != nil { - return nil, err - } - r.BlobKey = key - err = ds.WriteRemote(&r) - if err != nil { - return nil, err - } - return &r, nil -} - -// downloadACI gets the aci specified at aciurl -func downloadACI(ds Store, aciurl string) (*os.File, error) { - return downloadHTTP(aciurl, "ACI", ds.tmpFile) -} - -// downloadSignatureFile gets the signature specified at sigurl -func downloadSignatureFile(sigurl string) (*os.File, error) { - getTemp := func() (*os.File, error) { - return ioutil.TempFile("", "") - } - - return downloadHTTP(sigurl, "signature", getTemp) -} - -// downloadHTTP retrieves url, creating a temp file using getTempFile -// file:// http:// and https:// urls supported -func downloadHTTP(url, label string, getTempFile func() (*os.File, error)) (*os.File, error) { - tmp, err := getTempFile() - if err != nil { - return nil, fmt.Errorf("error downloading %s: %v", label, err) - } - defer func() { - if err != nil { - os.Remove(tmp.Name()) - tmp.Close() - } - }() - - res, err := http.Get(url) - if err != nil { - return nil, err - } - defer res.Body.Close() - - prefix := "Downloading " + label - fmtBytesSize := 18 - barSize := int64(80 - len(prefix) - fmtBytesSize) - bar := ioprogress.DrawTextFormatBar(barSize) - fmtfunc := func(progress, total int64) string { - return fmt.Sprintf( - "%s: %s %s", - prefix, - bar(progress, total), - ioprogress.DrawTextFormatBytes(progress, total), - ) - } - - reader := &ioprogress.Reader{ - Reader: res.Body, - Size: res.ContentLength, - DrawFunc: ioprogress.DrawTerminalf(os.Stdout, fmtfunc), - DrawInterval: time.Second, - } - - // TODO(jonboulle): handle http more robustly (redirects?) - if res.StatusCode != http.StatusOK { - return nil, fmt.Errorf("bad HTTP status code: %d", res.StatusCode) - } - - if _, err := io.Copy(tmp, reader); err != nil { - return nil, fmt.Errorf("error copying %s: %v", label, err) - } - - if err := tmp.Sync(); err != nil { - return nil, fmt.Errorf("error writing %s: %v", label, err) - } - - return tmp, nil -} - // GetRemote tries to retrieve a remote with the given aciURL. found will be // false if remote doesn't exist. func GetRemote(tx *sql.Tx, aciURL string) (remote *Remote, found bool, err error) { diff --git a/rkt/fetch.go b/rkt/fetch.go index cab917a..77d64d0 100644 --- a/rkt/fetch.go +++ b/rkt/fetch.go @@ -16,21 +16,32 @@ package main import ( "fmt" + "io" + "io/ioutil" + "net/http" "net/url" "os" + "path/filepath" "runtime" "strings" + "time" "github.com/coreos/rocket/cas" "github.com/coreos/rocket/pkg/keystore" + "github.com/coreos/rocket/Godeps/_workspace/src/github.com/appc/docker2aci/lib" + "github.com/coreos/rocket/Godeps/_workspace/src/github.com/appc/spec/aci" "github.com/coreos/rocket/Godeps/_workspace/src/github.com/appc/spec/discovery" "github.com/coreos/rocket/Godeps/_workspace/src/github.com/appc/spec/schema/types" + "github.com/coreos/rocket/Godeps/_workspace/src/github.com/mitchellh/ioprogress" + "github.com/coreos/rocket/Godeps/_workspace/src/golang.org/x/crypto/openpgp" ) const ( defaultOS = runtime.GOOS defaultArch = runtime.GOARCH + + defaultPathPerm os.FileMode = 0777 ) var ( @@ -129,8 +140,7 @@ func downloadImage(aciURL string, ascURL string, scheme string, ds *cas.Store, k return "", err } if !ok { - rem = cas.NewRemote(aciURL, ascURL) - entity, aciFile, err := rem.Download(*ds, ks) + entity, aciFile, err := download(aciURL, ascURL, ds, ks) if err != nil { return "", err } @@ -142,14 +152,161 @@ func downloadImage(aciURL string, ascURL string, scheme string, ds *cas.Store, k stdout(" %s", v.Name) } } - rem, err = rem.Store(*ds, aciFile, latest) + key, err := ds.WriteACI(aciFile, latest) if err != nil { return "", err } + rem = cas.NewRemote(aciURL, ascURL) + rem.BlobKey = key + err = ds.WriteRemote(rem) + if err != nil { + return "", err + } + } return rem.BlobKey, nil } +// download downloads and verifies the remote ACI. +// If Keystore is nil signature verification will be skipped. +// Download returns the signer, an *os.File representing the ACI, and an error if any. +// err will be nil if the ACI downloads successfully and the ACI is verified. +func download(aciURL string, ascURL string, ds *cas.Store, ks *keystore.Keystore) (*openpgp.Entity, *os.File, error) { + var entity *openpgp.Entity + u, err := url.Parse(aciURL) + if err != nil { + return nil, nil, fmt.Errorf("error parsing ACI url: %v", err) + } + if u.Scheme == "docker" { + registryURL := strings.TrimPrefix(aciURL, "docker://") + + tmpDir, err := tmpDir() + if err != nil { + return nil, nil, fmt.Errorf("error creating temporary dir for docker to ACI conversion: %v", err) + } + + acis, err := docker2aci.Convert(registryURL, true, tmpDir) + if err != nil { + return nil, nil, fmt.Errorf("error converting docker image to ACI: %v", err) + } + + aciFile, err := os.Open(acis[0]) + if err != nil { + return nil, nil, fmt.Errorf("error opening squashed ACI file: %v", err) + } + + return nil, aciFile, nil + } + + var sigTempFile *os.File + if ks != nil { + stdout("Downloading signature from %v\n", ascURL) + sigTempFile, err = downloadSignatureFile(ascURL) + if err != nil { + return nil, nil, fmt.Errorf("error downloading the signature file: %v", err) + } + defer sigTempFile.Close() + defer os.Remove(sigTempFile.Name()) + } + + acif, err := downloadACI(ds, aciURL) + if err != nil { + return nil, acif, fmt.Errorf("error downloading the aci image: %v", err) + } + + if ks != nil { + manifest, err := aci.ManifestFromImage(acif) + if err != nil { + return nil, acif, err + } + + if _, err := acif.Seek(0, 0); err != nil { + return nil, acif, err + } + if _, err := sigTempFile.Seek(0, 0); err != nil { + return nil, acif, err + } + if entity, err = ks.CheckSignature(manifest.Name.String(), acif, sigTempFile); err != nil { + return nil, acif, err + } + } + + if _, err := acif.Seek(0, 0); err != nil { + return nil, acif, err + } + return entity, acif, nil +} + +// downloadACI gets the aci specified at aciurl +func downloadACI(ds *cas.Store, aciurl string) (*os.File, error) { + return downloadHTTP(aciurl, "ACI", tmpFile) +} + +// downloadSignatureFile gets the signature specified at sigurl +func downloadSignatureFile(sigurl string) (*os.File, error) { + getTemp := func() (*os.File, error) { + return ioutil.TempFile("", "") + } + + return downloadHTTP(sigurl, "signature", getTemp) +} + +// downloadHTTP retrieves url, creating a temp file using getTempFile +// file:// http:// and https:// urls supported +func downloadHTTP(url, label string, getTempFile func() (*os.File, error)) (*os.File, error) { + tmp, err := getTempFile() + if err != nil { + return nil, fmt.Errorf("error downloading %s: %v", label, err) + } + defer func() { + if err != nil { + os.Remove(tmp.Name()) + tmp.Close() + } + }() + + res, err := http.Get(url) + if err != nil { + return nil, err + } + defer res.Body.Close() + + prefix := "Downloading " + label + fmtBytesSize := 18 + barSize := int64(80 - len(prefix) - fmtBytesSize) + bar := ioprogress.DrawTextFormatBar(barSize) + fmtfunc := func(progress, total int64) string { + return fmt.Sprintf( + "%s: %s %s", + prefix, + bar(progress, total), + ioprogress.DrawTextFormatBytes(progress, total), + ) + } + + reader := &ioprogress.Reader{ + Reader: res.Body, + Size: res.ContentLength, + DrawFunc: ioprogress.DrawTerminalf(os.Stdout, fmtfunc), + DrawInterval: time.Second, + } + + // TODO(jonboulle): handle http more robustly (redirects?) + if res.StatusCode != http.StatusOK { + return nil, fmt.Errorf("bad HTTP status code: %d", res.StatusCode) + } + + if _, err := io.Copy(tmp, reader); err != nil { + return nil, fmt.Errorf("error copying %s: %v", label, err) + } + + if err := tmp.Sync(); err != nil { + return nil, fmt.Errorf("error writing %s: %v", label, err) + } + + return tmp, nil +} + func validateURL(s string) error { u, err := url.Parse(s) if err != nil { @@ -186,3 +343,19 @@ func newDiscoveryApp(img string) *discovery.App { } return app } + +func tmpFile() (*os.File, error) { + dir, err := tmpDir() + if err != nil { + return nil, err + } + return ioutil.TempFile(dir, "") +} + +func tmpDir() (string, error) { + dir := filepath.Join(globalFlags.Dir, "tmp") + if err := os.MkdirAll(dir, defaultPathPerm); err != nil { + return "", err + } + return dir, nil +} diff --git a/rkt/fetch_test.go b/rkt/fetch_test.go index 449e7d8..9bd412f 100644 --- a/rkt/fetch_test.go +++ b/rkt/fetch_test.go @@ -15,6 +15,7 @@ package main import ( + "archive/tar" "bytes" "fmt" "io" @@ -113,6 +114,95 @@ func TestNewDiscoveryApp(t *testing.T) { } } +func TestDownloading(t *testing.T) { + dir, err := ioutil.TempDir("", "download-image") + if err != nil { + t.Fatalf("error creating tempdir: %v", err) + } + defer os.RemoveAll(dir) + + imj := `{ + "acKind": "ImageManifest", + "acVersion": "0.4.0", + "name": "example.com/test01" + }` + + entries := []*aci.ACIEntry{ + // An empty file + { + Contents: "hello", + Header: &tar.Header{ + Name: "rootfs/file01.txt", + Size: 5, + }, + }, + } + + aci, err := aci.NewACI(dir, imj, entries) + if err != nil { + t.Fatalf("error creating test tar: %v", err) + } + + // Rewind the ACI + if _, err := aci.Seek(0, 0); err != nil { + t.Fatalf("unexpected error: %v", err) + } + body, err := ioutil.ReadAll(aci) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Write(body) + })) + defer ts.Close() + + tests := []struct { + ACIURL string + SigURL string + body []byte + hit bool + }{ + {ts.URL, "", body, false}, + {ts.URL, "", body, true}, + } + + ds, err := cas.NewStore(dir) + if err != nil { + t.Fatalf("unexpected error %v", err) + } + + for _, tt := range tests { + _, ok, err := ds.GetRemote(tt.ACIURL) + if err != nil { + t.Fatalf("unexpected err: %v", err) + } + if tt.hit == false && ok { + t.Fatalf("expected miss got a hit") + } + if tt.hit == true && !ok { + t.Fatalf("expected a hit got a miss") + } + _, aciFile, err := download(tt.ACIURL, tt.SigURL, ds, nil) + if err != nil { + t.Fatalf("error downloading aci: %v", err) + } + defer os.Remove(aciFile.Name()) + + key, err := ds.WriteACI(aciFile, false) + if err != nil { + t.Fatalf("unexpected err: %v", err) + } + rem := cas.NewRemote(tt.ACIURL, tt.SigURL) + rem.BlobKey = key + err = ds.WriteRemote(rem) + if err != nil { + t.Fatalf("unexpected err: %v", err) + } + } + + ds.Dump(false) +} + func TestFetchImage(t *testing.T) { dir, err := ioutil.TempDir("", "fetch-image") if err != nil {