1
0
Fork 0
mirror of https://github.com/moby/moby.git synced 2022-11-09 12:21:53 -05:00

Update push and pull to registry 2.1 specification

Signed-off-by: Derek McGowan <derek@mcgstyle.net>
This commit is contained in:
Derek McGowan 2014-12-16 16:57:37 -08:00
parent dbb4b03bfc
commit 0336b0cdaa
6 changed files with 281 additions and 313 deletions

View file

@ -2,6 +2,7 @@ package graph
import ( import (
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
@ -24,82 +25,12 @@ func (s *TagStore) CmdManifest(job *engine.Job) engine.Status {
} }
// Resolve the Repository name from fqn to endpoint + name // Resolve the Repository name from fqn to endpoint + name
_, remoteName, err := registry.ResolveRepositoryName(name) repoInfo, err := registry.ParseRepositoryInfo(name)
if err != nil { if err != nil {
return job.Error(err) return job.Error(err)
} }
manifest := &registry.ManifestData{ manifestBytes, err := s.newManifest(name, repoInfo.RemoteName, tag)
Name: remoteName,
Tag: tag,
SchemaVersion: 1,
}
localRepo, exists := s.Repositories[name]
if !exists {
return job.Errorf("Repo does not exist: %s", name)
}
layerId, exists := localRepo[tag]
if !exists {
return job.Errorf("Tag does not exist for %s: %s", name, tag)
}
layersSeen := make(map[string]bool)
layer, err := s.graph.Get(layerId)
if err != nil {
return job.Error(err)
}
if layer.Config == nil {
return job.Errorf("Missing layer configuration")
}
manifest.Architecture = layer.Architecture
manifest.FSLayers = make([]*registry.FSLayer, 0, 4)
manifest.History = make([]*registry.ManifestHistory, 0, 4)
var metadata runconfig.Config
metadata = *layer.Config
for ; layer != nil; layer, err = layer.GetParent() {
if err != nil {
return job.Error(err)
}
if layersSeen[layer.ID] {
break
}
if layer.Config != nil && metadata.Image != layer.ID {
err = runconfig.Merge(&metadata, layer.Config)
if err != nil {
return job.Error(err)
}
}
archive, err := layer.TarLayer()
if err != nil {
return job.Error(err)
}
tarSum, err := tarsum.NewTarSum(archive, true, tarsum.VersionDev)
if err != nil {
return job.Error(err)
}
if _, err := io.Copy(ioutil.Discard, tarSum); err != nil {
return job.Error(err)
}
tarId := tarSum.Sum(nil)
// Save tarsum to image json
manifest.FSLayers = append(manifest.FSLayers, &registry.FSLayer{BlobSum: tarId})
layersSeen[layer.ID] = true
jsonData, err := ioutil.ReadFile(path.Join(s.graph.Root, layer.ID, "json"))
if err != nil {
return job.Error(fmt.Errorf("Cannot retrieve the path for {%s}: %s", layer.ID, err))
}
manifest.History = append(manifest.History, &registry.ManifestHistory{V1Compatibility: string(jsonData)})
}
manifestBytes, err := json.MarshalIndent(manifest, "", " ")
if err != nil { if err != nil {
return job.Error(err) return job.Error(err)
} }
@ -111,3 +42,82 @@ func (s *TagStore) CmdManifest(job *engine.Job) engine.Status {
return engine.StatusOK return engine.StatusOK
} }
func (s *TagStore) newManifest(localName, remoteName, tag string) ([]byte, error) {
manifest := &registry.ManifestData{
Name: remoteName,
Tag: tag,
SchemaVersion: 1,
}
localRepo, exists := s.Repositories[localName]
if !exists {
return nil, fmt.Errorf("Repo does not exist: %s", localName)
}
layerId, exists := localRepo[tag]
if !exists {
return nil, fmt.Errorf("Tag does not exist for %s: %s", localName, tag)
}
layersSeen := make(map[string]bool)
layer, err := s.graph.Get(layerId)
if err != nil {
return nil, err
}
if layer.Config == nil {
return nil, errors.New("Missing layer configuration")
}
manifest.Architecture = layer.Architecture
manifest.FSLayers = make([]*registry.FSLayer, 0, 4)
manifest.History = make([]*registry.ManifestHistory, 0, 4)
var metadata runconfig.Config
metadata = *layer.Config
for ; layer != nil; layer, err = layer.GetParent() {
if err != nil {
return nil, err
}
if layersSeen[layer.ID] {
break
}
if layer.Config != nil && metadata.Image != layer.ID {
err = runconfig.Merge(&metadata, layer.Config)
if err != nil {
return nil, err
}
}
archive, err := layer.TarLayer()
if err != nil {
return nil, err
}
tarSum, err := tarsum.NewTarSum(archive, true, tarsum.Version1)
if err != nil {
return nil, err
}
if _, err := io.Copy(ioutil.Discard, tarSum); err != nil {
return nil, err
}
tarId := tarSum.Sum(nil)
// Save tarsum to image json
manifest.FSLayers = append(manifest.FSLayers, &registry.FSLayer{BlobSum: tarId})
layersSeen[layer.ID] = true
jsonData, err := ioutil.ReadFile(path.Join(s.graph.Root, layer.ID, "json"))
if err != nil {
return nil, fmt.Errorf("Cannot retrieve the path for {%s}: %s", layer.ID, err)
}
manifest.History = append(manifest.History, &registry.ManifestHistory{V1Compatibility: string(jsonData)})
}
manifestBytes, err := json.MarshalIndent(manifest, "", " ")
if err != nil {
return nil, err
}
return manifestBytes, nil
}

View file

@ -133,7 +133,12 @@ func (s *TagStore) CmdPull(job *engine.Job) engine.Status {
return job.Errorf("error updating trust base graph: %s", err) return job.Errorf("error updating trust base graph: %s", err)
} }
if err := s.pullV2Repository(job.Eng, r, job.Stdout, repoInfo, tag, sf, job.GetenvBool("parallel")); err == nil { auth, err := r.GetV2Authorization(repoInfo.RemoteName, true)
if err != nil {
return job.Errorf("error getting authorization: %s", err)
}
if err := s.pullV2Repository(job.Eng, r, job.Stdout, repoInfo, tag, sf, job.GetenvBool("parallel"), auth); err == nil {
if err = job.Eng.Job("log", "pull", logName, "").Run(); err != nil { if err = job.Eng.Job("log", "pull", logName, "").Run(); err != nil {
log.Errorf("Error logging event 'pull' for %s: %s", logName, err) log.Errorf("Error logging event 'pull' for %s: %s", logName, err)
} }
@ -423,23 +428,23 @@ type downloadInfo struct {
err chan error err chan error
} }
func (s *TagStore) pullV2Repository(eng *engine.Engine, r *registry.Session, out io.Writer, repoInfo *registry.RepositoryInfo, tag string, sf *utils.StreamFormatter, parallel bool) error { func (s *TagStore) pullV2Repository(eng *engine.Engine, r *registry.Session, out io.Writer, repoInfo *registry.RepositoryInfo, tag string, sf *utils.StreamFormatter, parallel bool, auth *registry.RequestAuthorization) error {
var layersDownloaded bool var layersDownloaded bool
if tag == "" { if tag == "" {
log.Debugf("Pulling tag list from V2 registry for %s", repoInfo.CanonicalName) log.Debugf("Pulling tag list from V2 registry for %s", repoInfo.CanonicalName)
tags, err := r.GetV2RemoteTags(repoInfo.RemoteName, nil) tags, err := r.GetV2RemoteTags(repoInfo.RemoteName, auth)
if err != nil { if err != nil {
return err return err
} }
for _, t := range tags { for _, t := range tags {
if downloaded, err := s.pullV2Tag(eng, r, out, repoInfo, t, sf, parallel); err != nil { if downloaded, err := s.pullV2Tag(eng, r, out, repoInfo, t, sf, parallel, auth); err != nil {
return err return err
} else if downloaded { } else if downloaded {
layersDownloaded = true layersDownloaded = true
} }
} }
} else { } else {
if downloaded, err := s.pullV2Tag(eng, r, out, repoInfo, tag, sf, parallel); err != nil { if downloaded, err := s.pullV2Tag(eng, r, out, repoInfo, tag, sf, parallel, auth); err != nil {
return err return err
} else if downloaded { } else if downloaded {
layersDownloaded = true layersDownloaded = true
@ -454,9 +459,9 @@ func (s *TagStore) pullV2Repository(eng *engine.Engine, r *registry.Session, out
return nil return nil
} }
func (s *TagStore) pullV2Tag(eng *engine.Engine, r *registry.Session, out io.Writer, repoInfo *registry.RepositoryInfo, tag string, sf *utils.StreamFormatter, parallel bool) (bool, error) { func (s *TagStore) pullV2Tag(eng *engine.Engine, r *registry.Session, out io.Writer, repoInfo *registry.RepositoryInfo, tag string, sf *utils.StreamFormatter, parallel bool, auth *registry.RequestAuthorization) (bool, error) {
log.Debugf("Pulling tag from V2 registry: %q", tag) log.Debugf("Pulling tag from V2 registry: %q", tag)
manifestBytes, err := r.GetV2ImageManifest(repoInfo.RemoteName, tag, nil) manifestBytes, err := r.GetV2ImageManifest(repoInfo.RemoteName, tag, auth)
if err != nil { if err != nil {
return false, err return false, err
} }
@ -525,7 +530,7 @@ func (s *TagStore) pullV2Tag(eng *engine.Engine, r *registry.Session, out io.Wri
return err return err
} }
r, l, err := r.GetV2ImageBlobReader(repoInfo.RemoteName, sumType, checksum, nil) r, l, err := r.GetV2ImageBlobReader(repoInfo.RemoteName, sumType, checksum, auth)
if err != nil { if err != nil {
return err return err
} }

View file

@ -290,26 +290,24 @@ func (s *TagStore) CmdPush(job *engine.Job) engine.Status {
return job.Error(err2) return job.Error(err2)
} }
var isOfficial bool
if endpoint.String() == registry.IndexServerAddress() {
isOfficial = isOfficialName(remoteName)
if isOfficial && strings.IndexRune(remoteName, '/') == -1 {
remoteName = "library/" + remoteName
}
}
if len(tag) == 0 { if len(tag) == 0 {
tag = DEFAULTTAG tag = DEFAULTTAG
} }
if isOfficial || endpoint.Version == registry.APIVersion2 {
if repoInfo.Official || endpoint.Version == registry.APIVersion2 {
j := job.Eng.Job("trust_update_base") j := job.Eng.Job("trust_update_base")
if err = j.Run(); err != nil { if err = j.Run(); err != nil {
return job.Errorf("error updating trust base graph: %s", err) return job.Errorf("error updating trust base graph: %s", err)
} }
repoData, err := r.PushImageJSONIndex(remoteName, []*registry.ImgData{}, false, nil) // Get authentication type
auth, err := r.GetV2Authorization(repoInfo.RemoteName, false)
if err != nil { if err != nil {
return job.Error(err) return job.Errorf("error getting authorization: %s", err)
}
if len(manifestBytes) == 0 {
// TODO Create manifest and sign
} }
// try via manifest // try via manifest
@ -359,13 +357,13 @@ func (s *TagStore) CmdPush(job *engine.Job) engine.Status {
} }
// Call mount blob // Call mount blob
exists, err := r.PostV2ImageMountBlob(remoteName, sumParts[0], manifestSum, repoData.Tokens) exists, err := r.PostV2ImageMountBlob(repoInfo.RemoteName, sumParts[0], manifestSum, auth)
if err != nil { if err != nil {
job.Stdout.Write(sf.FormatProgress(utils.TruncateID(img.ID), "Image push failed", nil)) job.Stdout.Write(sf.FormatProgress(utils.TruncateID(img.ID), "Image push failed", nil))
return job.Error(err) return job.Error(err)
} }
if !exists { if !exists {
_, err = r.PutV2ImageBlob(remoteName, sumParts[0], manifestSum, utils.ProgressReader(arch, int(img.Size), job.Stdout, sf, false, utils.TruncateID(img.ID), "Pushing"), repoData.Tokens) err = r.PutV2ImageBlob(repoInfo.RemoteName, sumParts[0], manifestSum, utils.ProgressReader(arch, int(img.Size), job.Stdout, sf, false, utils.TruncateID(img.ID), "Pushing"), auth)
if err != nil { if err != nil {
job.Stdout.Write(sf.FormatProgress(utils.TruncateID(img.ID), "Image push failed", nil)) job.Stdout.Write(sf.FormatProgress(utils.TruncateID(img.ID), "Image push failed", nil))
return job.Error(err) return job.Error(err)
@ -377,35 +375,36 @@ func (s *TagStore) CmdPush(job *engine.Job) engine.Status {
} }
// push the manifest // push the manifest
err = r.PutV2ImageManifest(remoteName, tag, bytes.NewReader([]byte(manifestBytes)), repoData.Tokens) err = r.PutV2ImageManifest(repoInfo.RemoteName, tag, bytes.NewReader([]byte(manifestBytes)), auth)
if err != nil { if err != nil {
return job.Error(err) return job.Error(err)
} }
// done, no fallback to V1 // done, no fallback to V1
return engine.StatusOK return engine.StatusOK
} } else {
if err != nil { if err != nil {
reposLen := 1 reposLen := 1
if tag == "" { if tag == "" {
reposLen = len(s.Repositories[repoInfo.LocalName]) reposLen = len(s.Repositories[repoInfo.LocalName])
}
job.Stdout.Write(sf.FormatStatus("", "The push refers to a repository [%s] (len: %d)", repoInfo.CanonicalName, reposLen))
// If it fails, try to get the repository
if localRepo, exists := s.Repositories[repoInfo.LocalName]; exists {
if err := s.pushRepository(r, job.Stdout, repoInfo, localRepo, tag, sf); err != nil {
return job.Error(err)
} }
return engine.StatusOK job.Stdout.Write(sf.FormatStatus("", "The push refers to a repository [%s] (len: %d)", repoInfo.CanonicalName, reposLen))
// If it fails, try to get the repository
if localRepo, exists := s.Repositories[repoInfo.LocalName]; exists {
if err := s.pushRepository(r, job.Stdout, repoInfo, localRepo, tag, sf); err != nil {
return job.Error(err)
}
return engine.StatusOK
}
return job.Error(err)
} }
return job.Error(err)
}
var token []string var token []string
job.Stdout.Write(sf.FormatStatus("", "The push refers to an image: [%s]", repoInfo.CanonicalName)) job.Stdout.Write(sf.FormatStatus("", "The push refers to an image: [%s]", repoInfo.CanonicalName))
if _, err := s.pushImage(r, job.Stdout, img.ID, endpoint.String(), token, sf); err != nil { if _, err := s.pushImage(r, job.Stdout, img.ID, endpoint.String(), token, sf); err != nil {
return job.Error(err) return job.Error(err)
}
return engine.StatusOK
} }
return engine.StatusOK
} }

View file

@ -37,6 +37,59 @@ type ConfigFile struct {
rootPath string rootPath string
} }
type RequestAuthorization struct {
Token string
Username string
Password string
}
func NewRequestAuthorization(authConfig *AuthConfig, registryEndpoint *Endpoint, resource, scope string, actions []string) (*RequestAuthorization, error) {
var auth RequestAuthorization
client := &http.Client{
Transport: &http.Transport{
DisableKeepAlives: true,
Proxy: http.ProxyFromEnvironment,
},
CheckRedirect: AddRequiredHeadersToRedirectedRequests,
}
factory := HTTPRequestFactory(nil)
for _, challenge := range registryEndpoint.AuthChallenges {
log.Debugf("Using %q auth challenge with params %s for %s", challenge.Scheme, challenge.Parameters, authConfig.Username)
switch strings.ToLower(challenge.Scheme) {
case "basic":
auth.Username = authConfig.Username
auth.Password = authConfig.Password
case "bearer":
params := map[string]string{}
for k, v := range challenge.Parameters {
params[k] = v
}
params["scope"] = fmt.Sprintf("%s:%s:%s", resource, scope, strings.Join(actions, ","))
token, err := getToken(authConfig.Username, authConfig.Password, params, registryEndpoint, client, factory)
if err != nil {
return nil, err
}
auth.Token = token
default:
log.Infof("Unsupported auth scheme: %q", challenge.Scheme)
}
}
return &auth, nil
}
func (auth *RequestAuthorization) Authorize(req *http.Request) {
if auth.Token != "" {
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", auth.Token))
} else if auth.Username != "" && auth.Password != "" {
req.SetBasicAuth(auth.Username, auth.Password)
}
}
// create a base64 encoded auth string to store in config // create a base64 encoded auth string to store in config
func encodeAuth(authConfig *AuthConfig) string { func encodeAuth(authConfig *AuthConfig) string {
authStr := authConfig.Username + ":" + authConfig.Password authStr := authConfig.Username + ":" + authConfig.Password

View file

@ -9,100 +9,34 @@ import (
"strconv" "strconv"
log "github.com/Sirupsen/logrus" log "github.com/Sirupsen/logrus"
"github.com/docker/docker/registry/v2"
"github.com/docker/docker/utils" "github.com/docker/docker/utils"
"github.com/gorilla/mux"
) )
func newV2RegistryRouter() *mux.Router { var registryURLBuilder *v2.URLBuilder
router := mux.NewRouter()
v2Router := router.PathPrefix("/v2/").Subrouter() func init() {
// Version Info
v2Router.Path("/version").Name("version")
// Image Manifests
v2Router.Path("/manifest/{imagename:[a-z0-9-._/]+}/{tagname:[a-zA-Z0-9-._]+}").Name("manifests")
// List Image Tags
v2Router.Path("/tags/{imagename:[a-z0-9-._/]+}").Name("tags")
// Download a blob
v2Router.Path("/blob/{imagename:[a-z0-9-._/]+}/{sumtype:[a-z0-9._+-]+}/{sum:[a-fA-F0-9]{4,}}").Name("downloadBlob")
// Upload a blob
v2Router.Path("/blob/{imagename:[a-z0-9-._/]+}/{sumtype:[a-z0-9._+-]+}").Name("uploadBlob")
// Mounting a blob in an image
v2Router.Path("/blob/{imagename:[a-z0-9-._/]+}/{sumtype:[a-z0-9._+-]+}/{sum:[a-fA-F0-9]{4,}}").Name("mountBlob")
return router
}
// APIVersion2 /v2/
var v2HTTPRoutes = newV2RegistryRouter()
func getV2URL(e *Endpoint, routeName string, vars map[string]string) (*url.URL, error) {
route := v2HTTPRoutes.Get(routeName)
if route == nil {
return nil, fmt.Errorf("unknown regisry v2 route name: %q", routeName)
}
varReplace := make([]string, 0, len(vars)*2)
for key, val := range vars {
varReplace = append(varReplace, key, val)
}
routePath, err := route.URLPath(varReplace...)
if err != nil {
return nil, fmt.Errorf("unable to make registry route %q with vars %v: %s", routeName, vars, err)
}
u, err := url.Parse(REGISTRYSERVER) u, err := url.Parse(REGISTRYSERVER)
if err != nil { if err != nil {
return nil, fmt.Errorf("invalid registry url: %s", err) panic(fmt.Errorf("invalid registry url: %s", err))
} }
registryURLBuilder = v2.NewURLBuilder(u)
return &url.URL{
Scheme: u.Scheme,
Host: u.Host,
Path: routePath.Path,
}, nil
} }
// V2 Provenance POC func getV2Builder(e *Endpoint) *v2.URLBuilder {
return registryURLBuilder
}
func (r *Session) GetV2Version(token []string) (*RegistryInfo, error) { // GetV2Authorization gets the authorization needed to the given image
routeURL, err := getV2URL(r.indexEndpoint, "version", nil) // If readonly access is requested, then only the authorization may
if err != nil { // only be used for Get operations.
return nil, err func (r *Session) GetV2Authorization(imageName string, readOnly bool) (*RequestAuthorization, error) {
scopes := []string{"pull"}
if !readOnly {
scopes = append(scopes, "push")
} }
method := "GET" return NewRequestAuthorization(r.GetAuthConfig(true), r.indexEndpoint, "repository", imageName, scopes)
log.Debugf("[registry] Calling %q %s", method, routeURL.String())
req, err := r.reqFactory.NewRequest(method, routeURL.String(), nil)
if err != nil {
return nil, err
}
setTokenAuth(req, token)
res, _, err := r.doRequest(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != 200 {
return nil, utils.NewHTTPRequestError(fmt.Sprintf("Server error: %d fetching Version", res.StatusCode), res)
}
decoder := json.NewDecoder(res.Body)
versionInfo := new(RegistryInfo)
err = decoder.Decode(versionInfo)
if err != nil {
return nil, fmt.Errorf("unable to decode GetV2Version JSON response: %s", err)
}
return versionInfo, nil
} }
// //
@ -112,25 +46,20 @@ func (r *Session) GetV2Version(token []string) (*RegistryInfo, error) {
// 1.c) if anything else, err // 1.c) if anything else, err
// 2) PUT the created/signed manifest // 2) PUT the created/signed manifest
// //
func (r *Session) GetV2ImageManifest(imageName, tagName string, token []string) ([]byte, error) { func (r *Session) GetV2ImageManifest(imageName, tagName string, auth *RequestAuthorization) ([]byte, error) {
vars := map[string]string{ routeURL, err := getV2Builder(r.indexEndpoint).BuildManifestURL(imageName, tagName)
"imagename": imageName,
"tagname": tagName,
}
routeURL, err := getV2URL(r.indexEndpoint, "manifests", vars)
if err != nil { if err != nil {
return nil, err return nil, err
} }
method := "GET" method := "GET"
log.Debugf("[registry] Calling %q %s", method, routeURL.String()) log.Debugf("[registry] Calling %q %s", method, routeURL)
req, err := r.reqFactory.NewRequest(method, routeURL.String(), nil) req, err := r.reqFactory.NewRequest(method, routeURL, nil)
if err != nil { if err != nil {
return nil, err return nil, err
} }
setTokenAuth(req, token) auth.Authorize(req)
res, _, err := r.doRequest(req) res, _, err := r.doRequest(req)
if err != nil { if err != nil {
return nil, err return nil, err
@ -155,26 +84,20 @@ func (r *Session) GetV2ImageManifest(imageName, tagName string, token []string)
// - Succeeded to mount for this image scope // - Succeeded to mount for this image scope
// - Failed with no error (So continue to Push the Blob) // - Failed with no error (So continue to Push the Blob)
// - Failed with error // - Failed with error
func (r *Session) PostV2ImageMountBlob(imageName, sumType, sum string, token []string) (bool, error) { func (r *Session) PostV2ImageMountBlob(imageName, sumType, sum string, auth *RequestAuthorization) (bool, error) {
vars := map[string]string{ routeURL, err := getV2Builder(r.indexEndpoint).BuildBlobURL(imageName, sumType+":"+sum)
"imagename": imageName,
"sumtype": sumType,
"sum": sum,
}
routeURL, err := getV2URL(r.indexEndpoint, "mountBlob", vars)
if err != nil { if err != nil {
return false, err return false, err
} }
method := "POST" method := "HEAD"
log.Debugf("[registry] Calling %q %s", method, routeURL.String()) log.Debugf("[registry] Calling %q %s", method, routeURL)
req, err := r.reqFactory.NewRequest(method, routeURL.String(), nil) req, err := r.reqFactory.NewRequest(method, routeURL, nil)
if err != nil { if err != nil {
return false, err return false, err
} }
setTokenAuth(req, token) auth.Authorize(req)
res, _, err := r.doRequest(req) res, _, err := r.doRequest(req)
if err != nil { if err != nil {
return false, err return false, err
@ -191,25 +114,19 @@ func (r *Session) PostV2ImageMountBlob(imageName, sumType, sum string, token []s
return false, fmt.Errorf("Failed to mount %q - %s:%s : %d", imageName, sumType, sum, res.StatusCode) return false, fmt.Errorf("Failed to mount %q - %s:%s : %d", imageName, sumType, sum, res.StatusCode)
} }
func (r *Session) GetV2ImageBlob(imageName, sumType, sum string, blobWrtr io.Writer, token []string) error { func (r *Session) GetV2ImageBlob(imageName, sumType, sum string, blobWrtr io.Writer, auth *RequestAuthorization) error {
vars := map[string]string{ routeURL, err := getV2Builder(r.indexEndpoint).BuildBlobURL(imageName, sumType+":"+sum)
"imagename": imageName,
"sumtype": sumType,
"sum": sum,
}
routeURL, err := getV2URL(r.indexEndpoint, "downloadBlob", vars)
if err != nil { if err != nil {
return err return err
} }
method := "GET" method := "GET"
log.Debugf("[registry] Calling %q %s", method, routeURL.String()) log.Debugf("[registry] Calling %q %s", method, routeURL)
req, err := r.reqFactory.NewRequest(method, routeURL.String(), nil) req, err := r.reqFactory.NewRequest(method, routeURL, nil)
if err != nil { if err != nil {
return err return err
} }
setTokenAuth(req, token) auth.Authorize(req)
res, _, err := r.doRequest(req) res, _, err := r.doRequest(req)
if err != nil { if err != nil {
return err return err
@ -226,25 +143,19 @@ func (r *Session) GetV2ImageBlob(imageName, sumType, sum string, blobWrtr io.Wri
return err return err
} }
func (r *Session) GetV2ImageBlobReader(imageName, sumType, sum string, token []string) (io.ReadCloser, int64, error) { func (r *Session) GetV2ImageBlobReader(imageName, sumType, sum string, auth *RequestAuthorization) (io.ReadCloser, int64, error) {
vars := map[string]string{ routeURL, err := getV2Builder(r.indexEndpoint).BuildBlobURL(imageName, sumType+":"+sum)
"imagename": imageName,
"sumtype": sumType,
"sum": sum,
}
routeURL, err := getV2URL(r.indexEndpoint, "downloadBlob", vars)
if err != nil { if err != nil {
return nil, 0, err return nil, 0, err
} }
method := "GET" method := "GET"
log.Debugf("[registry] Calling %q %s", method, routeURL.String()) log.Debugf("[registry] Calling %q %s", method, routeURL)
req, err := r.reqFactory.NewRequest(method, routeURL.String(), nil) req, err := r.reqFactory.NewRequest(method, routeURL, nil)
if err != nil { if err != nil {
return nil, 0, err return nil, 0, err
} }
setTokenAuth(req, token) auth.Authorize(req)
res, _, err := r.doRequest(req) res, _, err := r.doRequest(req)
if err != nil { if err != nil {
return nil, 0, err return nil, 0, err
@ -267,85 +178,76 @@ func (r *Session) GetV2ImageBlobReader(imageName, sumType, sum string, token []s
// Push the image to the server for storage. // Push the image to the server for storage.
// 'layer' is an uncompressed reader of the blob to be pushed. // 'layer' is an uncompressed reader of the blob to be pushed.
// The server will generate it's own checksum calculation. // The server will generate it's own checksum calculation.
func (r *Session) PutV2ImageBlob(imageName, sumType, sumStr string, blobRdr io.Reader, token []string) (serverChecksum string, err error) { func (r *Session) PutV2ImageBlob(imageName, sumType, sumStr string, blobRdr io.Reader, auth *RequestAuthorization) error {
vars := map[string]string{ routeURL, err := getV2Builder(r.indexEndpoint).BuildBlobUploadURL(imageName)
"imagename": imageName, if err != nil {
"sumtype": sumType, return err
} }
routeURL, err := getV2URL(r.indexEndpoint, "uploadBlob", vars) log.Debugf("[registry] Calling %q %s", "POST", routeURL)
req, err := r.reqFactory.NewRequest("POST", routeURL, nil)
if err != nil { if err != nil {
return "", err return err
} }
method := "PUT" auth.Authorize(req)
log.Debugf("[registry] Calling %q %s", method, routeURL.String())
req, err := r.reqFactory.NewRequest(method, routeURL.String(), blobRdr)
if err != nil {
return "", err
}
setTokenAuth(req, token)
req.Header.Set("X-Tarsum", sumStr)
res, _, err := r.doRequest(req) res, _, err := r.doRequest(req)
if err != nil { if err != nil {
return "", err return err
}
location := res.Header.Get("Location")
method := "PUT"
log.Debugf("[registry] Calling %q %s", method, location)
req, err = r.reqFactory.NewRequest(method, location, blobRdr)
if err != nil {
return err
}
queryParams := url.Values{}
queryParams.Add("digest", sumType+":"+sumStr)
req.URL.RawQuery = queryParams.Encode()
auth.Authorize(req)
res, _, err = r.doRequest(req)
if err != nil {
return err
} }
defer res.Body.Close() defer res.Body.Close()
if res.StatusCode != 201 {
if res.StatusCode == 401 {
return "", errLoginRequired
}
return "", utils.NewHTTPRequestError(fmt.Sprintf("Server error: %d trying to push %s blob", res.StatusCode, imageName), res)
}
type sumReturn struct {
Checksum string `json:"checksum"`
}
decoder := json.NewDecoder(res.Body)
var sumInfo sumReturn
err = decoder.Decode(&sumInfo)
if err != nil {
return "", fmt.Errorf("unable to decode PutV2ImageBlob JSON response: %s", err)
}
if sumInfo.Checksum != sumStr {
return "", fmt.Errorf("failed checksum comparison. serverChecksum: %q, localChecksum: %q", sumInfo.Checksum, sumStr)
}
// XXX this is a json struct from the registry, with its checksum
return sumInfo.Checksum, nil
}
// Finally Push the (signed) manifest of the blobs we've just pushed
func (r *Session) PutV2ImageManifest(imageName, tagName string, manifestRdr io.Reader, token []string) error {
vars := map[string]string{
"imagename": imageName,
"tagname": tagName,
}
routeURL, err := getV2URL(r.indexEndpoint, "manifests", vars)
if err != nil {
return err
}
method := "PUT"
log.Debugf("[registry] Calling %q %s", method, routeURL.String())
req, err := r.reqFactory.NewRequest(method, routeURL.String(), manifestRdr)
if err != nil {
return err
}
setTokenAuth(req, token)
res, _, err := r.doRequest(req)
if err != nil {
return err
}
res.Body.Close()
if res.StatusCode != 201 { if res.StatusCode != 201 {
if res.StatusCode == 401 { if res.StatusCode == 401 {
return errLoginRequired return errLoginRequired
} }
return utils.NewHTTPRequestError(fmt.Sprintf("Server error: %d trying to push %s blob", res.StatusCode, imageName), res)
}
return nil
}
// Finally Push the (signed) manifest of the blobs we've just pushed
func (r *Session) PutV2ImageManifest(imageName, tagName string, manifestRdr io.Reader, auth *RequestAuthorization) error {
routeURL, err := getV2Builder(r.indexEndpoint).BuildManifestURL(imageName, tagName)
if err != nil {
return err
}
method := "PUT"
log.Debugf("[registry] Calling %q %s", method, routeURL)
req, err := r.reqFactory.NewRequest(method, routeURL, manifestRdr)
if err != nil {
return err
}
auth.Authorize(req)
res, _, err := r.doRequest(req)
if err != nil {
return err
}
b, _ := ioutil.ReadAll(res.Body)
res.Body.Close()
if res.StatusCode != 200 {
if res.StatusCode == 401 {
return errLoginRequired
}
log.Debugf("Unexpected response from server: %q %#v", b, res.Header)
return utils.NewHTTPRequestError(fmt.Sprintf("Server error: %d trying to push %s:%s manifest", res.StatusCode, imageName, tagName), res) return utils.NewHTTPRequestError(fmt.Sprintf("Server error: %d trying to push %s:%s manifest", res.StatusCode, imageName, tagName), res)
} }
@ -353,24 +255,20 @@ func (r *Session) PutV2ImageManifest(imageName, tagName string, manifestRdr io.R
} }
// Given a repository name, returns a json array of string tags // Given a repository name, returns a json array of string tags
func (r *Session) GetV2RemoteTags(imageName string, token []string) ([]string, error) { func (r *Session) GetV2RemoteTags(imageName string, auth *RequestAuthorization) ([]string, error) {
vars := map[string]string{ routeURL, err := getV2Builder(r.indexEndpoint).BuildTagsURL(imageName)
"imagename": imageName,
}
routeURL, err := getV2URL(r.indexEndpoint, "tags", vars)
if err != nil { if err != nil {
return nil, err return nil, err
} }
method := "GET" method := "GET"
log.Debugf("[registry] Calling %q %s", method, routeURL.String()) log.Debugf("[registry] Calling %q %s", method, routeURL)
req, err := r.reqFactory.NewRequest(method, routeURL.String(), nil) req, err := r.reqFactory.NewRequest(method, routeURL, nil)
if err != nil { if err != nil {
return nil, err return nil, err
} }
setTokenAuth(req, token) auth.Authorize(req)
res, _, err := r.doRequest(req) res, _, err := r.doRequest(req)
if err != nil { if err != nil {
return nil, err return nil, err

View file

@ -50,6 +50,9 @@ func (p *JSONProgress) String() string {
} }
total := units.HumanSize(float64(p.Total)) total := units.HumanSize(float64(p.Total))
percentage := int(float64(p.Current)/float64(p.Total)*100) / 2 percentage := int(float64(p.Current)/float64(p.Total)*100) / 2
if percentage > 50 {
percentage = 50
}
if width > 110 { if width > 110 {
// this number can't be negetive gh#7136 // this number can't be negetive gh#7136
numSpaces := 0 numSpaces := 0