2014-08-07 14:43:06 +00:00
package registry
import (
"bytes"
"crypto/sha256"
2015-05-14 14:12:54 +00:00
"errors"
2015-05-16 01:35:04 +00:00
"sync"
2014-10-06 19:34:39 +00:00
// this is required for some certificates
2014-08-07 14:43:06 +00:00
_ "crypto/sha512"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/cookiejar"
"net/url"
"strconv"
"strings"
"time"
2015-03-26 22:22:04 +00:00
"github.com/Sirupsen/logrus"
2015-04-22 12:06:58 +00:00
"github.com/docker/docker/cliconfig"
2014-10-24 22:11:48 +00:00
"github.com/docker/docker/pkg/httputils"
2015-05-17 09:07:48 +00:00
"github.com/docker/docker/pkg/ioutils"
2015-04-08 02:29:29 +00:00
"github.com/docker/docker/pkg/stringid"
2014-08-07 14:43:06 +00:00
"github.com/docker/docker/pkg/tarsum"
)
2015-06-10 22:18:15 +00:00
var (
2015-07-21 19:40:36 +00:00
// ErrRepoNotFound is returned if the repository didn't exist on the
// remote side
2015-06-10 22:18:15 +00:00
ErrRepoNotFound = errors . New ( "Repository not found" )
)
2015-07-21 19:40:36 +00:00
// A Session is used to communicate with a V1 registry
2014-08-07 14:43:06 +00:00
type Session struct {
2014-08-26 23:21:04 +00:00
indexEndpoint * Endpoint
2015-05-14 14:12:54 +00:00
client * http . Client
// TODO(tiborvass): remove authConfig
authConfig * cliconfig . AuthConfig
2015-04-08 02:29:29 +00:00
id string
2014-08-07 14:43:06 +00:00
}
2015-05-16 01:35:04 +00:00
type authTransport struct {
http . RoundTripper
* cliconfig . AuthConfig
alwaysSetBasicAuth bool
token [ ] string
mu sync . Mutex // guards modReq
modReq map [ * http . Request ] * http . Request // original -> modified
}
// AuthTransport handles the auth layer when communicating with a v1 registry (private or official)
2015-05-14 14:12:54 +00:00
//
// For private v1 registries, set alwaysSetBasicAuth to true.
//
// For the official v1 registry, if there isn't already an Authorization header in the request,
// but there is an X-Docker-Token header set to true, then Basic Auth will be used to set the Authorization header.
// After sending the request with the provided base http.RoundTripper, if an X-Docker-Token header, representing
// a token, is present in the response, then it gets cached and sent in the Authorization header of all subsequent
// requests.
//
// If the server sends a token without the client having requested it, it is ignored.
//
// This RoundTripper also has a CancelRequest method important for correct timeout handling.
2015-05-16 01:35:04 +00:00
func AuthTransport ( base http . RoundTripper , authConfig * cliconfig . AuthConfig , alwaysSetBasicAuth bool ) http . RoundTripper {
if base == nil {
base = http . DefaultTransport
}
return & authTransport {
RoundTripper : base ,
AuthConfig : authConfig ,
alwaysSetBasicAuth : alwaysSetBasicAuth ,
modReq : make ( map [ * http . Request ] * http . Request ) ,
}
2015-05-14 14:12:54 +00:00
}
2014-08-07 14:43:06 +00:00
2015-05-17 09:07:48 +00:00
// cloneRequest returns a clone of the provided *http.Request.
// The clone is a shallow copy of the struct and its Header map.
func cloneRequest ( r * http . Request ) * http . Request {
// shallow copy of the struct
r2 := new ( http . Request )
* r2 = * r
// deep copy of the Header
r2 . Header = make ( http . Header , len ( r . Header ) )
for k , s := range r . Header {
r2 . Header [ k ] = append ( [ ] string ( nil ) , s ... )
}
return r2
}
2015-07-21 19:40:36 +00:00
// RoundTrip changes a HTTP request's headers to add the necessary
// authentication-related headers
2015-05-16 01:35:04 +00:00
func ( tr * authTransport ) RoundTrip ( orig * http . Request ) ( * http . Response , error ) {
2015-06-08 23:56:37 +00:00
// Authorization should not be set on 302 redirect for untrusted locations.
2015-07-21 19:40:36 +00:00
// This logic mirrors the behavior in addRequiredHeadersToRedirectedRequests.
2015-06-08 23:56:37 +00:00
// As the authorization logic is currently implemented in RoundTrip,
// a 302 redirect is detected by looking at the Referer header as go http package adds said header.
// This is safe as Docker doesn't set Referer in other scenarios.
if orig . Header . Get ( "Referer" ) != "" && ! trustedLocation ( orig ) {
return tr . RoundTripper . RoundTrip ( orig )
}
2015-02-12 18:23:22 +00:00
req := cloneRequest ( orig )
2015-05-16 01:35:04 +00:00
tr . mu . Lock ( )
tr . modReq [ orig ] = req
tr . mu . Unlock ( )
2015-05-14 14:12:54 +00:00
if tr . alwaysSetBasicAuth {
2015-07-16 16:38:44 +00:00
if tr . AuthConfig == nil {
return nil , errors . New ( "unexpected error: empty auth config" )
}
2015-05-14 14:12:54 +00:00
req . SetBasicAuth ( tr . Username , tr . Password )
return tr . RoundTripper . RoundTrip ( req )
2014-08-07 14:43:06 +00:00
}
2015-05-14 14:12:54 +00:00
// Don't override
if req . Header . Get ( "Authorization" ) == "" {
2015-07-16 16:38:44 +00:00
if req . Header . Get ( "X-Docker-Token" ) == "true" && tr . AuthConfig != nil && len ( tr . Username ) > 0 {
2015-05-14 14:12:54 +00:00
req . SetBasicAuth ( tr . Username , tr . Password )
2015-06-08 23:56:37 +00:00
} else if len ( tr . token ) > 0 {
2015-05-14 14:12:54 +00:00
req . Header . Set ( "Authorization" , "Token " + strings . Join ( tr . token , "," ) )
}
}
resp , err := tr . RoundTripper . RoundTrip ( req )
2014-08-07 14:43:06 +00:00
if err != nil {
2015-05-16 01:35:04 +00:00
delete ( tr . modReq , orig )
2014-08-07 14:43:06 +00:00
return nil , err
}
2015-05-21 20:53:22 +00:00
if len ( resp . Header [ "X-Docker-Token" ] ) > 0 {
2015-05-14 14:12:54 +00:00
tr . token = resp . Header [ "X-Docker-Token" ]
}
2015-05-17 09:07:48 +00:00
resp . Body = & ioutils . OnEOFReader {
2015-05-16 01:35:04 +00:00
Rc : resp . Body ,
2015-06-01 20:25:18 +00:00
Fn : func ( ) {
tr . mu . Lock ( )
delete ( tr . modReq , orig )
tr . mu . Unlock ( )
} ,
2015-05-16 01:35:04 +00:00
}
2015-05-14 14:12:54 +00:00
return resp , nil
}
2015-05-16 01:35:04 +00:00
// CancelRequest cancels an in-flight request by closing its connection.
func ( tr * authTransport ) CancelRequest ( req * http . Request ) {
type canceler interface {
CancelRequest ( * http . Request )
}
if cr , ok := tr . RoundTripper . ( canceler ) ; ok {
tr . mu . Lock ( )
modReq := tr . modReq [ req ]
delete ( tr . modReq , req )
tr . mu . Unlock ( )
cr . CancelRequest ( modReq )
}
}
2015-07-21 19:40:36 +00:00
// NewSession creates a new session
2015-05-14 14:12:54 +00:00
// TODO(tiborvass): remove authConfig param once registry client v2 is vendored
func NewSession ( client * http . Client , authConfig * cliconfig . AuthConfig , endpoint * Endpoint ) ( r * Session , err error ) {
r = & Session {
authConfig : authConfig ,
client : client ,
indexEndpoint : endpoint ,
2015-04-08 02:29:29 +00:00
id : stringid . GenerateRandomID ( ) ,
2015-05-14 14:12:54 +00:00
}
var alwaysSetBasicAuth bool
2014-08-07 14:43:06 +00:00
// If we're working with a standalone private registry over HTTPS, send Basic Auth headers
2015-05-14 14:12:54 +00:00
// alongside all our requests.
2015-07-21 19:40:36 +00:00
if endpoint . VersionString ( 1 ) != IndexServer && endpoint . URL . Scheme == "https" {
2015-05-14 14:12:54 +00:00
info , err := endpoint . Ping ( )
2014-08-07 14:43:06 +00:00
if err != nil {
return nil , err
}
2015-05-14 14:12:54 +00:00
if info . Standalone && authConfig != nil {
logrus . Debugf ( "Endpoint %s is eligible for private registry. Enabling decorator." , endpoint . String ( ) )
alwaysSetBasicAuth = true
2014-08-07 14:43:06 +00:00
}
}
2015-06-19 17:12:52 +00:00
// Annotate the transport unconditionally so that v2 can
// properly fallback on v1 when an image is not found.
client . Transport = AuthTransport ( client . Transport , authConfig , alwaysSetBasicAuth )
2014-08-07 14:43:06 +00:00
2015-05-14 14:12:54 +00:00
jar , err := cookiejar . New ( nil )
if err != nil {
return nil , errors . New ( "cookiejar.New is not supposed to return an error" )
}
client . Jar = jar
return r , nil
2014-08-07 14:43:06 +00:00
}
2015-04-08 02:29:29 +00:00
// ID returns this registry session's ID.
func ( r * Session ) ID ( ) string {
return r . id
}
2015-07-21 19:40:36 +00:00
// GetRemoteHistory retrieves the history of a given image from the registry.
// It returns a list of the parent's JSON files (including the requested image).
2015-05-14 14:12:54 +00:00
func ( r * Session ) GetRemoteHistory ( imgID , registry string ) ( [ ] string , error ) {
res , err := r . client . Get ( registry + "images/" + imgID + "/ancestry" )
2014-08-07 14:43:06 +00:00
if err != nil {
return nil , err
}
defer res . Body . Close ( )
if res . StatusCode != 200 {
if res . StatusCode == 401 {
return nil , errLoginRequired
}
2015-03-29 21:17:23 +00:00
return nil , httputils . NewHTTPRequestError ( fmt . Sprintf ( "Server error: %d trying to fetch remote history for %s" , res . StatusCode , imgID ) , res )
2014-08-07 14:43:06 +00:00
}
2015-05-14 14:12:54 +00:00
var history [ ] string
if err := json . NewDecoder ( res . Body ) . Decode ( & history ) ; err != nil {
return nil , fmt . Errorf ( "Error while reading the http response: %v" , err )
2014-08-07 14:43:06 +00:00
}
2015-05-14 14:12:54 +00:00
logrus . Debugf ( "Ancestry: %v" , history )
return history , nil
2014-08-07 14:43:06 +00:00
}
2015-07-21 19:40:36 +00:00
// LookupRemoteImage checks if an image exists in the registry
2015-05-14 14:12:54 +00:00
func ( r * Session ) LookupRemoteImage ( imgID , registry string ) error {
res , err := r . client . Get ( registry + "images/" + imgID + "/json" )
2014-08-07 14:43:06 +00:00
if err != nil {
2014-11-16 13:25:10 +00:00
return err
2014-08-07 14:43:06 +00:00
}
res . Body . Close ( )
2014-11-16 13:25:10 +00:00
if res . StatusCode != 200 {
2015-03-29 21:17:23 +00:00
return httputils . NewHTTPRequestError ( fmt . Sprintf ( "HTTP code %d" , res . StatusCode ) , res )
2014-11-16 13:25:10 +00:00
}
return nil
2014-08-07 14:43:06 +00:00
}
2015-07-21 19:40:36 +00:00
// GetRemoteImageJSON retrieves an image's JSON metadata from the registry.
2015-07-23 21:19:58 +00:00
func ( r * Session ) GetRemoteImageJSON ( imgID , registry string ) ( [ ] byte , int64 , error ) {
2015-05-14 14:12:54 +00:00
res , err := r . client . Get ( registry + "images/" + imgID + "/json" )
2014-08-07 14:43:06 +00:00
if err != nil {
return nil , - 1 , fmt . Errorf ( "Failed to download json: %s" , err )
}
defer res . Body . Close ( )
if res . StatusCode != 200 {
2015-03-29 21:17:23 +00:00
return nil , - 1 , httputils . NewHTTPRequestError ( fmt . Sprintf ( "HTTP code %d" , res . StatusCode ) , res )
2014-08-07 14:43:06 +00:00
}
// if the size header is not present, then set it to '-1'
2015-07-23 21:19:58 +00:00
imageSize := int64 ( - 1 )
2014-08-07 14:43:06 +00:00
if hdr := res . Header . Get ( "X-Docker-Size" ) ; hdr != "" {
2015-07-23 21:19:58 +00:00
imageSize , err = strconv . ParseInt ( hdr , 10 , 64 )
2014-08-07 14:43:06 +00:00
if err != nil {
return nil , - 1 , err
}
}
jsonString , err := ioutil . ReadAll ( res . Body )
if err != nil {
2015-05-14 14:12:54 +00:00
return nil , - 1 , fmt . Errorf ( "Failed to parse downloaded json: %v (%s)" , err , jsonString )
2014-08-07 14:43:06 +00:00
}
return jsonString , imageSize , nil
}
2015-07-21 19:40:36 +00:00
// GetRemoteImageLayer retrieves an image layer from the registry
2015-05-14 14:12:54 +00:00
func ( r * Session ) GetRemoteImageLayer ( imgID , registry string , imgSize int64 ) ( io . ReadCloser , error ) {
2014-08-07 14:43:06 +00:00
var (
2014-09-03 13:21:06 +00:00
retries = 5
statusCode = 0
res * http . Response
2015-05-14 14:12:54 +00:00
err error
2014-09-03 13:21:06 +00:00
imageURL = fmt . Sprintf ( "%simages/%s/layer" , registry , imgID )
2014-08-07 14:43:06 +00:00
)
2015-05-14 14:12:54 +00:00
req , err := http . NewRequest ( "GET" , imageURL , nil )
2014-08-07 14:43:06 +00:00
if err != nil {
2015-05-14 14:12:54 +00:00
return nil , fmt . Errorf ( "Error while getting from the server: %v" , err )
2014-08-07 14:43:06 +00:00
}
2015-02-12 18:23:22 +00:00
// TODO(tiborvass): why are we doing retries at this level?
2015-05-14 14:12:54 +00:00
// These retries should be generic to both v1 and v2
2014-08-07 14:43:06 +00:00
for i := 1 ; i <= retries ; i ++ {
2014-09-03 13:21:06 +00:00
statusCode = 0
2015-05-14 14:12:54 +00:00
res , err = r . client . Do ( req )
if err == nil {
break
}
logrus . Debugf ( "Error contacting registry %s: %v" , registry , err )
if res != nil {
if res . Body != nil {
res . Body . Close ( )
2014-08-07 14:43:06 +00:00
}
2015-05-14 14:12:54 +00:00
statusCode = res . StatusCode
}
if i == retries {
return nil , fmt . Errorf ( "Server error: Status %d while fetching image layer (%s)" ,
statusCode , imgID )
2014-08-07 14:43:06 +00:00
}
2015-05-14 14:12:54 +00:00
time . Sleep ( time . Duration ( i ) * 5 * time . Second )
2014-08-07 14:43:06 +00:00
}
if res . StatusCode != 200 {
res . Body . Close ( )
return nil , fmt . Errorf ( "Server error: Status %d while fetching image layer (%s)" ,
res . StatusCode , imgID )
}
if res . Header . Get ( "Accept-Ranges" ) == "bytes" && imgSize > 0 {
2015-03-26 22:22:04 +00:00
logrus . Debugf ( "server supports resume" )
2015-05-14 14:12:54 +00:00
return httputils . ResumableRequestReaderWithInitialResponse ( r . client , req , 5 , imgSize , res ) , nil
2014-08-07 14:43:06 +00:00
}
2015-03-26 22:22:04 +00:00
logrus . Debugf ( "server doesn't support resume" )
2014-08-07 14:43:06 +00:00
return res . Body , nil
}
2015-07-21 19:40:36 +00:00
// GetRemoteTag retrieves the tag named in the askedTag argument from the given
// repository. It queries each of the registries supplied in the registries
// argument, and returns data from the first one that answers the query
// successfully.
2015-06-10 22:18:15 +00:00
func ( r * Session ) GetRemoteTag ( registries [ ] string , repository string , askedTag string ) ( string , error ) {
if strings . Count ( repository , "/" ) == 0 {
2015-07-21 19:40:36 +00:00
// This will be removed once the registry supports auto-resolution on
2015-06-10 22:18:15 +00:00
// the "library" namespace
repository = "library/" + repository
}
for _ , host := range registries {
endpoint := fmt . Sprintf ( "%srepositories/%s/tags/%s" , host , repository , askedTag )
res , err := r . client . Get ( endpoint )
if err != nil {
return "" , err
}
logrus . Debugf ( "Got status code %d from %s" , res . StatusCode , endpoint )
defer res . Body . Close ( )
if res . StatusCode == 404 {
return "" , ErrRepoNotFound
}
if res . StatusCode != 200 {
continue
}
2015-07-21 19:40:36 +00:00
var tagID string
if err := json . NewDecoder ( res . Body ) . Decode ( & tagID ) ; err != nil {
2015-06-10 22:18:15 +00:00
return "" , err
}
2015-07-21 19:40:36 +00:00
return tagID , nil
2015-06-10 22:18:15 +00:00
}
return "" , fmt . Errorf ( "Could not reach any registry endpoint" )
}
2015-07-21 19:40:36 +00:00
// GetRemoteTags retrieves all tags from the given repository. It queries each
// of the registries supplied in the registries argument, and returns data from
// the first one that answers the query successfully. It returns a map with
// tag names as the keys and image IDs as the values.
2015-05-14 14:12:54 +00:00
func ( r * Session ) GetRemoteTags ( registries [ ] string , repository string ) ( map [ string ] string , error ) {
2014-08-07 14:43:06 +00:00
if strings . Count ( repository , "/" ) == 0 {
2015-07-21 19:40:36 +00:00
// This will be removed once the registry supports auto-resolution on
2014-08-07 14:43:06 +00:00
// the "library" namespace
repository = "library/" + repository
}
for _ , host := range registries {
endpoint := fmt . Sprintf ( "%srepositories/%s/tags" , host , repository )
2015-05-14 14:12:54 +00:00
res , err := r . client . Get ( endpoint )
2014-08-07 14:43:06 +00:00
if err != nil {
return nil , err
}
2015-03-26 22:22:04 +00:00
logrus . Debugf ( "Got status code %d from %s" , res . StatusCode , endpoint )
2014-08-07 14:43:06 +00:00
defer res . Body . Close ( )
2015-04-19 13:23:48 +00:00
if res . StatusCode == 404 {
2015-06-10 22:18:15 +00:00
return nil , ErrRepoNotFound
2015-04-19 21:36:58 +00:00
}
if res . StatusCode != 200 {
2015-04-19 13:23:48 +00:00
continue
2014-08-07 14:43:06 +00:00
}
result := make ( map [ string ] string )
2014-10-27 19:04:36 +00:00
if err := json . NewDecoder ( res . Body ) . Decode ( & result ) ; err != nil {
2014-08-07 14:43:06 +00:00
return nil , err
}
return result , nil
}
return nil , fmt . Errorf ( "Could not reach any registry endpoint" )
}
func buildEndpointsList ( headers [ ] string , indexEp string ) ( [ ] string , error ) {
var endpoints [ ] string
2014-10-06 19:34:39 +00:00
parsedURL , err := url . Parse ( indexEp )
2014-08-07 14:43:06 +00:00
if err != nil {
return nil , err
}
2014-10-06 19:34:39 +00:00
var urlScheme = parsedURL . Scheme
2015-07-21 19:40:36 +00:00
// The registry's URL scheme has to match the Index'
2014-08-07 14:43:06 +00:00
for _ , ep := range headers {
epList := strings . Split ( ep , "," )
for _ , epListElement := range epList {
endpoints = append (
endpoints ,
fmt . Sprintf ( "%s://%s/v1/" , urlScheme , strings . TrimSpace ( epListElement ) ) )
}
}
return endpoints , nil
}
2015-07-21 19:40:36 +00:00
// GetRepositoryData returns lists of images and endpoints for the repository
2014-08-07 14:43:06 +00:00
func ( r * Session ) GetRepositoryData ( remote string ) ( * RepositoryData , error ) {
2014-10-02 01:26:06 +00:00
repositoryTarget := fmt . Sprintf ( "%srepositories/%s/images" , r . indexEndpoint . VersionString ( 1 ) , remote )
2014-08-07 14:43:06 +00:00
2015-03-26 22:22:04 +00:00
logrus . Debugf ( "[registry] Calling GET %s" , repositoryTarget )
2014-08-07 14:43:06 +00:00
2015-05-14 14:12:54 +00:00
req , err := http . NewRequest ( "GET" , repositoryTarget , nil )
2014-08-07 14:43:06 +00:00
if err != nil {
return nil , err
}
2015-05-14 14:12:54 +00:00
// this will set basic auth in r.client.Transport and send cached X-Docker-Token headers for all subsequent requests
2014-08-07 14:43:06 +00:00
req . Header . Set ( "X-Docker-Token" , "true" )
2015-05-14 14:12:54 +00:00
res , err := r . client . Do ( req )
2014-08-07 14:43:06 +00:00
if err != nil {
2015-07-22 01:45:17 +00:00
// check if the error is because of i/o timeout
// and return a non-obtuse error message for users
// "Get https://index.docker.io/v1/repositories/library/busybox/images: i/o timeout"
// was a top search on the docker user forum
if strings . HasSuffix ( err . Error ( ) , "i/o timeout" ) {
return nil , fmt . Errorf ( "Network timed out while trying to connect to %s. You may want to check your internet connection or if you are behind a proxy." , repositoryTarget )
}
return nil , fmt . Errorf ( "Error while pulling image: %v" , err )
2014-08-07 14:43:06 +00:00
}
defer res . Body . Close ( )
if res . StatusCode == 401 {
return nil , errLoginRequired
}
// TODO: Right now we're ignoring checksums in the response body.
// In the future, we need to use them to check image validity.
2015-03-23 01:15:18 +00:00
if res . StatusCode == 404 {
2015-03-29 21:17:23 +00:00
return nil , httputils . NewHTTPRequestError ( fmt . Sprintf ( "HTTP code: %d" , res . StatusCode ) , res )
2015-03-23 01:15:18 +00:00
} else if res . StatusCode != 200 {
2015-03-14 08:31:35 +00:00
errBody , err := ioutil . ReadAll ( res . Body )
if err != nil {
2015-03-26 22:22:04 +00:00
logrus . Debugf ( "Error reading response body: %s" , err )
2015-03-14 08:31:35 +00:00
}
2015-03-29 21:17:23 +00:00
return nil , httputils . NewHTTPRequestError ( fmt . Sprintf ( "Error: Status %d trying to pull repository %s: %q" , res . StatusCode , remote , errBody ) , res )
2014-08-07 14:43:06 +00:00
}
var endpoints [ ] string
if res . Header . Get ( "X-Docker-Endpoints" ) != "" {
2014-10-02 01:26:06 +00:00
endpoints , err = buildEndpointsList ( res . Header [ "X-Docker-Endpoints" ] , r . indexEndpoint . VersionString ( 1 ) )
2014-08-07 14:43:06 +00:00
if err != nil {
return nil , err
}
} else {
// Assume the endpoint is on the same host
2014-08-26 23:21:04 +00:00
endpoints = append ( endpoints , fmt . Sprintf ( "%s://%s/v1/" , r . indexEndpoint . URL . Scheme , req . URL . Host ) )
2014-08-07 14:43:06 +00:00
}
remoteChecksums := [ ] * ImgData { }
2014-10-27 19:04:36 +00:00
if err := json . NewDecoder ( res . Body ) . Decode ( & remoteChecksums ) ; err != nil {
2014-08-07 14:43:06 +00:00
return nil , err
}
// Forge a better object from the retrieved data
2015-02-12 18:23:22 +00:00
imgsData := make ( map [ string ] * ImgData , len ( remoteChecksums ) )
2014-08-07 14:43:06 +00:00
for _ , elem := range remoteChecksums {
imgsData [ elem . ID ] = elem
}
return & RepositoryData {
ImgList : imgsData ,
Endpoints : endpoints ,
} , nil
}
2015-07-21 19:40:36 +00:00
// PushImageChecksumRegistry uploads checksums for an image
2015-05-14 14:12:54 +00:00
func ( r * Session ) PushImageChecksumRegistry ( imgData * ImgData , registry string ) error {
u := registry + "images/" + imgData . ID + "/checksum"
2014-08-07 14:43:06 +00:00
2015-05-14 14:12:54 +00:00
logrus . Debugf ( "[registry] Calling PUT %s" , u )
2014-08-07 14:43:06 +00:00
2015-05-14 14:12:54 +00:00
req , err := http . NewRequest ( "PUT" , u , nil )
2014-08-07 14:43:06 +00:00
if err != nil {
return err
}
req . Header . Set ( "X-Docker-Checksum" , imgData . Checksum )
req . Header . Set ( "X-Docker-Checksum-Payload" , imgData . ChecksumPayload )
2015-05-14 14:12:54 +00:00
res , err := r . client . Do ( req )
2014-08-07 14:43:06 +00:00
if err != nil {
2015-05-14 14:12:54 +00:00
return fmt . Errorf ( "Failed to upload metadata: %v" , err )
2014-08-07 14:43:06 +00:00
}
defer res . Body . Close ( )
if len ( res . Cookies ( ) ) > 0 {
2015-05-14 14:12:54 +00:00
r . client . Jar . SetCookies ( req . URL , res . Cookies ( ) )
2014-08-07 14:43:06 +00:00
}
if res . StatusCode != 200 {
errBody , err := ioutil . ReadAll ( res . Body )
if err != nil {
return fmt . Errorf ( "HTTP code %d while uploading metadata and error when trying to parse response body: %s" , res . StatusCode , err )
}
var jsonBody map [ string ] string
if err := json . Unmarshal ( errBody , & jsonBody ) ; err != nil {
errBody = [ ] byte ( err . Error ( ) )
} else if jsonBody [ "error" ] == "Image already exists" {
return ErrAlreadyExists
}
2015-03-16 22:32:47 +00:00
return fmt . Errorf ( "HTTP code %d while uploading metadata: %q" , res . StatusCode , errBody )
2014-08-07 14:43:06 +00:00
}
return nil
}
2015-07-21 19:40:36 +00:00
// PushImageJSONRegistry pushes JSON metadata for a local image to the registry
2015-05-14 14:12:54 +00:00
func ( r * Session ) PushImageJSONRegistry ( imgData * ImgData , jsonRaw [ ] byte , registry string ) error {
2014-08-07 14:43:06 +00:00
2015-05-14 14:12:54 +00:00
u := registry + "images/" + imgData . ID + "/json"
2014-08-07 14:43:06 +00:00
2015-05-14 14:12:54 +00:00
logrus . Debugf ( "[registry] Calling PUT %s" , u )
req , err := http . NewRequest ( "PUT" , u , bytes . NewReader ( jsonRaw ) )
2014-08-07 14:43:06 +00:00
if err != nil {
return err
}
req . Header . Add ( "Content-type" , "application/json" )
2015-05-14 14:12:54 +00:00
res , err := r . client . Do ( req )
2014-08-07 14:43:06 +00:00
if err != nil {
return fmt . Errorf ( "Failed to upload metadata: %s" , err )
}
defer res . Body . Close ( )
if res . StatusCode == 401 && strings . HasPrefix ( registry , "http://" ) {
2015-03-29 21:17:23 +00:00
return httputils . NewHTTPRequestError ( "HTTP code 401, Docker will not send auth headers over HTTP." , res )
2014-08-07 14:43:06 +00:00
}
if res . StatusCode != 200 {
errBody , err := ioutil . ReadAll ( res . Body )
if err != nil {
2015-03-29 21:17:23 +00:00
return httputils . NewHTTPRequestError ( fmt . Sprintf ( "HTTP code %d while uploading metadata and error when trying to parse response body: %s" , res . StatusCode , err ) , res )
2014-08-07 14:43:06 +00:00
}
var jsonBody map [ string ] string
if err := json . Unmarshal ( errBody , & jsonBody ) ; err != nil {
errBody = [ ] byte ( err . Error ( ) )
} else if jsonBody [ "error" ] == "Image already exists" {
return ErrAlreadyExists
}
2015-03-29 21:17:23 +00:00
return httputils . NewHTTPRequestError ( fmt . Sprintf ( "HTTP code %d while uploading metadata: %q" , res . StatusCode , errBody ) , res )
2014-08-07 14:43:06 +00:00
}
return nil
}
2015-07-21 19:40:36 +00:00
// PushImageLayerRegistry sends the checksum of an image layer to the registry
2015-05-14 14:12:54 +00:00
func ( r * Session ) PushImageLayerRegistry ( imgID string , layer io . Reader , registry string , jsonRaw [ ] byte ) ( checksum string , checksumPayload string , err error ) {
u := registry + "images/" + imgID + "/layer"
2014-08-07 14:43:06 +00:00
2015-05-14 14:12:54 +00:00
logrus . Debugf ( "[registry] Calling PUT %s" , u )
2014-08-07 14:43:06 +00:00
2014-08-21 20:12:52 +00:00
tarsumLayer , err := tarsum . NewTarSum ( layer , false , tarsum . Version0 )
if err != nil {
return "" , "" , err
}
2014-08-07 14:43:06 +00:00
h := sha256 . New ( )
h . Write ( jsonRaw )
h . Write ( [ ] byte { '\n' } )
checksumLayer := io . TeeReader ( tarsumLayer , h )
2015-05-14 14:12:54 +00:00
req , err := http . NewRequest ( "PUT" , u , checksumLayer )
2014-08-07 14:43:06 +00:00
if err != nil {
return "" , "" , err
}
req . Header . Add ( "Content-Type" , "application/octet-stream" )
req . ContentLength = - 1
req . TransferEncoding = [ ] string { "chunked" }
2015-05-14 14:12:54 +00:00
res , err := r . client . Do ( req )
2014-08-07 14:43:06 +00:00
if err != nil {
2015-05-14 14:12:54 +00:00
return "" , "" , fmt . Errorf ( "Failed to upload layer: %v" , err )
2014-08-07 14:43:06 +00:00
}
if rc , ok := layer . ( io . Closer ) ; ok {
if err := rc . Close ( ) ; err != nil {
return "" , "" , err
}
}
defer res . Body . Close ( )
if res . StatusCode != 200 {
errBody , err := ioutil . ReadAll ( res . Body )
if err != nil {
2015-03-29 21:17:23 +00:00
return "" , "" , httputils . NewHTTPRequestError ( fmt . Sprintf ( "HTTP code %d while uploading metadata and error when trying to parse response body: %s" , res . StatusCode , err ) , res )
2014-08-07 14:43:06 +00:00
}
2015-03-29 21:17:23 +00:00
return "" , "" , httputils . NewHTTPRequestError ( fmt . Sprintf ( "Received HTTP code %d while uploading layer: %q" , res . StatusCode , errBody ) , res )
2014-08-07 14:43:06 +00:00
}
checksumPayload = "sha256:" + hex . EncodeToString ( h . Sum ( nil ) )
return tarsumLayer . Sum ( jsonRaw ) , checksumPayload , nil
}
2015-07-21 19:40:36 +00:00
// PushRegistryTag pushes a tag on the registry.
2014-08-07 14:43:06 +00:00
// Remote has the format '<user>/<repo>
2015-05-14 14:12:54 +00:00
func ( r * Session ) PushRegistryTag ( remote , revision , tag , registry string ) error {
2014-08-07 14:43:06 +00:00
// "jsonify" the string
revision = "\"" + revision + "\""
path := fmt . Sprintf ( "repositories/%s/tags/%s" , remote , tag )
2015-05-14 14:12:54 +00:00
req , err := http . NewRequest ( "PUT" , registry + path , strings . NewReader ( revision ) )
2014-08-07 14:43:06 +00:00
if err != nil {
return err
}
req . Header . Add ( "Content-type" , "application/json" )
req . ContentLength = int64 ( len ( revision ) )
2015-05-14 14:12:54 +00:00
res , err := r . client . Do ( req )
2014-08-07 14:43:06 +00:00
if err != nil {
return err
}
res . Body . Close ( )
if res . StatusCode != 200 && res . StatusCode != 201 {
2015-03-29 21:17:23 +00:00
return httputils . NewHTTPRequestError ( fmt . Sprintf ( "Internal server error: %d trying to push tag %s on %s" , res . StatusCode , tag , remote ) , res )
2014-08-07 14:43:06 +00:00
}
return nil
}
2015-07-21 19:40:36 +00:00
// PushImageJSONIndex uploads an image list to the repository
2014-08-07 14:43:06 +00:00
func ( r * Session ) PushImageJSONIndex ( remote string , imgList [ ] * ImgData , validate bool , regs [ ] string ) ( * RepositoryData , error ) {
cleanImgList := [ ] * ImgData { }
if validate {
for _ , elem := range imgList {
if elem . Checksum != "" {
cleanImgList = append ( cleanImgList , elem )
}
}
} else {
cleanImgList = imgList
}
imgListJSON , err := json . Marshal ( cleanImgList )
if err != nil {
return nil , err
}
var suffix string
if validate {
suffix = "images"
}
2014-10-02 01:26:06 +00:00
u := fmt . Sprintf ( "%srepositories/%s/%s" , r . indexEndpoint . VersionString ( 1 ) , remote , suffix )
2015-03-26 22:22:04 +00:00
logrus . Debugf ( "[registry] PUT %s" , u )
logrus . Debugf ( "Image list pushed to index:\n%s" , imgListJSON )
2014-12-11 02:08:40 +00:00
headers := map [ string ] [ ] string {
2015-05-14 14:12:54 +00:00
"Content-type" : { "application/json" } ,
// this will set basic auth in r.client.Transport and send cached X-Docker-Token headers for all subsequent requests
2014-12-11 02:08:40 +00:00
"X-Docker-Token" : { "true" } ,
2014-08-07 14:43:06 +00:00
}
if validate {
2014-12-11 02:08:40 +00:00
headers [ "X-Docker-Endpoints" ] = regs
2014-08-07 14:43:06 +00:00
}
// Redirect if necessary
2014-12-11 02:08:40 +00:00
var res * http . Response
for {
if res , err = r . putImageRequest ( u , headers , imgListJSON ) ; err != nil {
2014-08-07 14:43:06 +00:00
return nil , err
}
2014-12-11 02:08:40 +00:00
if ! shouldRedirect ( res ) {
break
2014-08-07 14:43:06 +00:00
}
2014-12-11 02:08:40 +00:00
res . Body . Close ( )
u = res . Header . Get ( "Location" )
2015-03-26 22:22:04 +00:00
logrus . Debugf ( "Redirected to %s" , u )
2014-08-07 14:43:06 +00:00
}
2014-12-11 02:08:40 +00:00
defer res . Body . Close ( )
2014-08-07 14:43:06 +00:00
2015-01-12 19:56:01 +00:00
if res . StatusCode == 401 {
return nil , errLoginRequired
}
2014-08-07 14:43:06 +00:00
var tokens , endpoints [ ] string
if ! validate {
if res . StatusCode != 200 && res . StatusCode != 201 {
errBody , err := ioutil . ReadAll ( res . Body )
if err != nil {
2015-03-26 22:22:04 +00:00
logrus . Debugf ( "Error reading response body: %s" , err )
2014-08-07 14:43:06 +00:00
}
2015-03-29 21:17:23 +00:00
return nil , httputils . NewHTTPRequestError ( fmt . Sprintf ( "Error: Status %d trying to push repository %s: %q" , res . StatusCode , remote , errBody ) , res )
2014-08-07 14:43:06 +00:00
}
2015-04-19 13:23:48 +00:00
tokens = res . Header [ "X-Docker-Token" ]
logrus . Debugf ( "Auth token: %v" , tokens )
2014-08-07 14:43:06 +00:00
2015-04-19 13:23:48 +00:00
if res . Header . Get ( "X-Docker-Endpoints" ) == "" {
2014-08-07 14:43:06 +00:00
return nil , fmt . Errorf ( "Index response didn't contain any endpoints" )
}
2015-04-19 13:23:48 +00:00
endpoints , err = buildEndpointsList ( res . Header [ "X-Docker-Endpoints" ] , r . indexEndpoint . VersionString ( 1 ) )
if err != nil {
return nil , err
}
2015-05-14 14:12:54 +00:00
} else {
2014-08-07 14:43:06 +00:00
if res . StatusCode != 204 {
errBody , err := ioutil . ReadAll ( res . Body )
if err != nil {
2015-03-26 22:22:04 +00:00
logrus . Debugf ( "Error reading response body: %s" , err )
2014-08-07 14:43:06 +00:00
}
2015-03-29 21:17:23 +00:00
return nil , httputils . NewHTTPRequestError ( fmt . Sprintf ( "Error: Status %d trying to push checksums %s: %q" , res . StatusCode , remote , errBody ) , res )
2014-08-07 14:43:06 +00:00
}
}
return & RepositoryData {
Endpoints : endpoints ,
} , nil
}
2014-12-11 02:08:40 +00:00
func ( r * Session ) putImageRequest ( u string , headers map [ string ] [ ] string , body [ ] byte ) ( * http . Response , error ) {
2015-05-14 14:12:54 +00:00
req , err := http . NewRequest ( "PUT" , u , bytes . NewReader ( body ) )
2014-12-11 02:08:40 +00:00
if err != nil {
return nil , err
}
req . ContentLength = int64 ( len ( body ) )
for k , v := range headers {
req . Header [ k ] = v
}
2015-05-14 14:12:54 +00:00
response , err := r . client . Do ( req )
2014-12-11 02:08:40 +00:00
if err != nil {
return nil , err
}
return response , nil
}
func shouldRedirect ( response * http . Response ) bool {
return response . StatusCode >= 300 && response . StatusCode < 400
}
2015-07-21 19:40:36 +00:00
// SearchRepositories performs a search against the remote repository
2014-08-07 14:43:06 +00:00
func ( r * Session ) SearchRepositories ( term string ) ( * SearchResults , error ) {
2015-03-26 22:22:04 +00:00
logrus . Debugf ( "Index server: %s" , r . indexEndpoint )
2014-10-02 01:26:06 +00:00
u := r . indexEndpoint . VersionString ( 1 ) + "search?q=" + url . QueryEscape ( term )
2015-07-10 03:56:23 +00:00
req , err := http . NewRequest ( "GET" , u , nil )
if err != nil {
return nil , fmt . Errorf ( "Error while getting from the server: %v" , err )
}
// Have the AuthTransport send authentication, when logged in.
req . Header . Set ( "X-Docker-Token" , "true" )
res , err := r . client . Do ( req )
2014-08-07 14:43:06 +00:00
if err != nil {
return nil , err
}
defer res . Body . Close ( )
if res . StatusCode != 200 {
2015-03-29 21:17:23 +00:00
return nil , httputils . NewHTTPRequestError ( fmt . Sprintf ( "Unexpected status code %d" , res . StatusCode ) , res )
2014-08-07 14:43:06 +00:00
}
result := new ( SearchResults )
2015-04-26 16:50:25 +00:00
return result , json . NewDecoder ( res . Body ) . Decode ( result )
2014-08-07 14:43:06 +00:00
}
2015-07-21 19:40:36 +00:00
// GetAuthConfig returns the authentication settings for a session
2015-05-14 14:12:54 +00:00
// TODO(tiborvass): remove this once registry client v2 is vendored
2015-04-22 12:06:58 +00:00
func ( r * Session ) GetAuthConfig ( withPasswd bool ) * cliconfig . AuthConfig {
2014-08-07 14:43:06 +00:00
password := ""
if withPasswd {
password = r . authConfig . Password
}
2015-04-22 12:06:58 +00:00
return & cliconfig . AuthConfig {
2014-08-07 14:43:06 +00:00
Username : r . authConfig . Username ,
Password : password ,
Email : r . authConfig . Email ,
}
}