Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
127 changes: 97 additions & 30 deletions pkg/dockerregistry/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ import (
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"path"
"strings"

"github.com/fsouza/go-dockerclient"
Expand Down Expand Up @@ -32,29 +35,73 @@ type Connection interface {

// NewClient returns a client object which allows public access to
// a Docker registry.
// TODO: accept a docker auth config
func NewClient() Client {
return &client{
connections: make(map[string]connection),
connections: make(map[string]*connection),
}
}

// client implements the Client interface
type client struct {
connections map[string]connection
connections map[string]*connection
}

// Connect accepts the name of a registry in the common form Docker provides and will
// create a connection to the registry. Callers may provide a host, a host:port, or
// a fully qualified URL. When not providing a URL, the default scheme will be "https"
func (c *client) Connect(name string) (Connection, error) {
if len(name) == 0 {
name = "index.docker.io"
target, err := normalizeRegistryName(name)
if err != nil {
return nil, err
}
if conn, ok := c.connections[name]; ok {
prefix := target.String()
if conn, ok := c.connections[prefix]; ok {
return conn, nil
}
conn := newConnection(name)
c.connections[name] = conn
conn := newConnection(*target)
c.connections[prefix] = conn
return conn, nil
}

func normalizeRegistryName(name string) (*url.URL, error) {
prefix := name
if len(prefix) == 0 {
prefix = "index.docker.io"
}
hadPrefix := false
switch {
case strings.HasPrefix(prefix, "http://"), strings.HasPrefix(prefix, "https://"):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if !regexp.MatchString("^https??://",prefix) {
prefix="https://"+prefix
}
http://play.golang.org/p/UQ5oMQSnkr

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No regex when a switch can do it better.

On Apr 19, 2015, at 12:36 AM, Ben Parees [email protected] wrote:

In pkg/dockerregistry/client.go:

return conn, nil

}

+func normalizeRegistryName(name string) (*url.URL, error) {

—
Reply to this email directly or view it on GitHub.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i don't know that i agree with the definition of "better" here, but even if you don't want a regex (for performance or readability concerns? i comment would handle the latter), I would also say that:
if !a && !b {
prepend
}

would be better than this switch as it's currently written, since what you've currently written is semantically:

if a || b {
// do nothing
} else {
prepend()
}
which seems like an ineloquent (and needlessy verbose) expression.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Regex are bad because no one understands regex, avoid using them in general for anything that can be more clearly defined otherwise. Performance is important but clarity is more so.

Go generally prefers switch over multiple conditionals, but a simple Boolean as you mentioned is simpler - I'll make that change.

The coding style I think we should be trying for is when someone familiar with go looks at this code 2 years hence, would they mistake the intent or the correctness of the code. Verbosity can be bad, succinctness can be bad.

On Apr 19, 2015, at 12:42 PM, Ben Parees [email protected] wrote:

In pkg/dockerregistry/client.go:

return conn, nil

}

+func normalizeRegistryName(name string) (*url.URL, error) {

  • prefix := name
  • if len(prefix) == 0 {
  •   prefix = "index.docker.io"
    
  • }
  • switch {
  • case strings.HasPrefix(prefix, "http://"), strings.HasPrefix(prefix, "https://"):
    i don't know that i agree with the definition of "better" here, but even if you don't a regex (for performance or readability concerns? i comment would handle the latter), I would also say that:
    if !a && !b {
    prepend
    }

would be better than this switch as it's currently written, since what you've currently written is semantically:

if a || b {
// do nothing
} else {
prepend()
}
which seems like an ineloquent (and needlessy verbose) expression.

—
Reply to this email directly or view it on GitHub.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure you can ever create an ImageStream with spec.dockerImageRepository set to http://... or https://....

$ cat v1-ncdc-busybox.json
{
  "apiVersion": "v1beta1",
  "kind": "ImageStream",
  "metadata": {
    "name": "v1ncdcbusybox"
  },
  "spec": {
    "dockerImageRepository": "http://localhost:5100/ncdc/busybox"
  }
}

$ osc create -f v1-ncdc-busybox.json
Error: ImageStream "v1ncdcbusybox" is invalid: spec.dockerImageRepository: invalid value 'http://localhost:5100/ncdc/busybox': the docker pull spec "http://localhost:5100/ncdc/busybox" must be two or three segments separated by slashes

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

----- Original Message -----

return conn, nil

}

+func normalizeRegistryName(name string) (*url.URL, error) {

  • prefix := name
  • if len(prefix) == 0 {
  •   prefix = "index.docker.io"
    
  • }
  • hadPrefix := false
  • switch {
  • case strings.HasPrefix(prefix, "http://"), strings.HasPrefix(prefix,
    "https://"):

I'm not sure you can ever create an ImageStream with
spec.dockerImageRepository set to http://... or https://....

This doesn't have to be used by image streams. DockerImageReference guards against those prefixes.

$ cat v1-ncdc-busybox.json
{
  "apiVersion": "v1beta1",
  "kind": "ImageStream",
  "metadata": {
    "name": "v1ncdcbusybox"
  },
  "spec": {
    "dockerImageRepository": "http://localhost:5100/ncdc/busybox"
  }
}

$ osc create -f v1-ncdc-busybox.json
Error: ImageStream "v1ncdcbusybox" is invalid: spec.dockerImageRepository:
invalid value 'http://localhost:5100/ncdc/busybox': the docker pull spec
"http://localhost:5100/ncdc/busybox" must be two or three segments separated
by slashes

Because I reverted that change.

hadPrefix = true
default:
prefix = "https://" + prefix
}

target, err := url.Parse(prefix)
if err != nil {
return nil, fmt.Errorf("the registry name cannot be made into a valid url: %v", err)
}

if host, port, err := net.SplitHostPort(target.Host); err == nil {
if host == "docker.io" {
host = "index.docker.io"
}
if hadPrefix {
switch {
case port == "443" && target.Scheme == "https":
target.Host = host
case port == "80" && target.Scheme == "http":
target.Host = host
}
}
} else {
if target.Host == "docker.io" {
target.Host = "index.docker.io"
}
}
return target, nil
}

func convertConnectionError(registry string, err error) error {
switch {
case strings.Contains(err.Error(), "connection refused"):
Expand All @@ -66,26 +113,26 @@ func convertConnectionError(registry string, err error) error {

type connection struct {
client *http.Client
host string
url url.URL
cached map[string]*repository
}

func newConnection(name string) connection {
return connection{
host: name,
func newConnection(url url.URL) *connection {
return &connection{
url: url,
client: http.DefaultClient,
cached: make(map[string]*repository),
}
}

type repository struct {
name string
endpoint string
endpoint url.URL
token string
}

// ImageTags returns the tags for the named Docker image repository.
func (c connection) ImageTags(namespace, name string) (map[string]string, error) {
func (c *connection) ImageTags(namespace, name string) (map[string]string, error) {
if len(namespace) == 0 {
namespace = "library"
}
Expand All @@ -102,7 +149,7 @@ func (c connection) ImageTags(namespace, name string) (map[string]string, error)
}

// ImageByID returns the specified image within the named Docker image repository
func (c connection) ImageByID(namespace, name, imageID string) (*docker.Image, error) {
func (c *connection) ImageByID(namespace, name, imageID string) (*docker.Image, error) {
if len(namespace) == 0 {
namespace = "library"
}
Expand All @@ -119,7 +166,7 @@ func (c connection) ImageByID(namespace, name, imageID string) (*docker.Image, e
}

// ImageByTag returns the specified image within the named Docker image repository
func (c connection) ImageByTag(namespace, name, tag string) (*docker.Image, error) {
func (c *connection) ImageByTag(namespace, name, tag string) (*docker.Image, error) {
if len(namespace) == 0 {
namespace = "library"
}
Expand All @@ -144,7 +191,7 @@ func (c connection) ImageByTag(namespace, name, tag string) (*docker.Image, erro
return c.getImage(repo, imageID, tag)
}

func (c connection) getCachedRepository(name string) (*repository, error) {
func (c *connection) getCachedRepository(name string) (*repository, error) {
if cached, ok := c.cached[name]; ok {
return cached, nil
}
Expand All @@ -156,39 +203,55 @@ func (c connection) getCachedRepository(name string) (*repository, error) {
return repo, nil
}

func (c connection) getRepository(name string) (*repository, error) {
glog.V(4).Infof("Getting repository %s from %s", name, c.host)
req, err := http.NewRequest("GET", fmt.Sprintf("https://%s/v1/repositories/%s/images", c.host, name), nil)
func (c *connection) getRepository(name string) (*repository, error) {
glog.V(4).Infof("Getting repository %s from %s", name, c.url)
base := c.url
base.Path = path.Join(base.Path, fmt.Sprintf("/v1/repositories/%s/images", name))
req, err := http.NewRequest("GET", base.String(), nil)
if err != nil {
return nil, fmt.Errorf("error creating request: %v", err)
}
req.Header.Add("X-Docker-Token", "true")
resp, err := c.client.Do(req)
if err != nil {
return nil, convertConnectionError(c.host, fmt.Errorf("error getting X-Docker-Token from index.docker.io: %v", err))
// if we tried https and were rejected, try http
if c.url.Scheme == "https" {
glog.V(4).Infof("Failed to get https, trying http: %v", err)
c.url.Scheme = "http"
return c.getRepository(name)
}
return nil, convertConnectionError(c.url.String(), fmt.Errorf("error getting X-Docker-Token from %s: %v", name, err))
}

// if we were redirected, update the base urls
c.url.Scheme = resp.Request.URL.Scheme
c.url.Host = resp.Request.URL.Host

switch code := resp.StatusCode; {
case code == http.StatusNotFound:
return nil, errRepositoryNotFound{name}
case code >= 300 || resp.StatusCode < 200:
return nil, fmt.Errorf("error retrieving repository: server returned %d", resp.StatusCode)
}
// TODO: select a random endpoint
return &repository{
name: name,
endpoint: resp.Header.Get("X-Docker-Endpoints"),
endpoint: url.URL{Scheme: c.url.Scheme, Host: resp.Header.Get("X-Docker-Endpoints")},
token: resp.Header.Get("X-Docker-Token"),
}, nil
}

func (c connection) getTags(repo *repository) (map[string]string, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("https://%s/v1/repositories/%s/tags", repo.endpoint, repo.name), nil)
func (c *connection) getTags(repo *repository) (map[string]string, error) {
endpoint := repo.endpoint
endpoint.Path = path.Join(endpoint.Path, fmt.Sprintf("/v1/repositories/%s/tags", repo.name))
req, err := http.NewRequest("GET", endpoint.String(), nil)
if err != nil {
return nil, fmt.Errorf("error creating request: %v", err)
}
req.Header.Add("Authorization", "Token "+repo.token)
resp, err := c.client.Do(req)
if err != nil {
return nil, convertConnectionError(c.host, fmt.Errorf("error getting image tags for %s: %v", repo.name, err))
return nil, convertConnectionError(c.url.String(), fmt.Errorf("error getting image tags for %s: %v", repo.name, err))
}
switch code := resp.StatusCode; {
case code == http.StatusNotFound:
Expand All @@ -203,15 +266,17 @@ func (c connection) getTags(repo *repository) (map[string]string, error) {
return tags, nil
}

func (c connection) getTag(repo *repository, tag, userTag string) (string, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("https://%s/v1/repositories/%s/tags/%s", repo.endpoint, repo.name, tag), nil)
func (c *connection) getTag(repo *repository, tag, userTag string) (string, error) {
endpoint := repo.endpoint
endpoint.Path = path.Join(endpoint.Path, fmt.Sprintf("/v1/repositories/%s/tags/%s", repo.name, tag))
req, err := http.NewRequest("GET", endpoint.String(), nil)
if err != nil {
return "", fmt.Errorf("error creating request: %v", err)
}
req.Header.Add("Authorization", "Token "+repo.token)
resp, err := c.client.Do(req)
if err != nil {
return "", convertConnectionError(c.host, fmt.Errorf("error getting image id for %s:%s: %v", repo.name, tag, err))
return "", convertConnectionError(c.url.String(), fmt.Errorf("error getting image id for %s:%s: %v", repo.name, tag, err))
}
switch code := resp.StatusCode; {
case code == http.StatusNotFound:
Expand All @@ -226,15 +291,17 @@ func (c connection) getTag(repo *repository, tag, userTag string) (string, error
return imageID, nil
}

func (c connection) getImage(repo *repository, image, userTag string) (*docker.Image, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("https://%s/v1/images/%s/json", repo.endpoint, image), nil)
func (c *connection) getImage(repo *repository, image, userTag string) (*docker.Image, error) {
endpoint := repo.endpoint
endpoint.Path = path.Join(endpoint.Path, fmt.Sprintf("/v1/images/%s/json", image))
req, err := http.NewRequest("GET", endpoint.String(), nil)
if err != nil {
return nil, fmt.Errorf("error creating request: %v", err)
}
req.Header.Add("Authorization", "Token "+repo.token)
resp, err := c.client.Do(req)
if err != nil {
return nil, convertConnectionError(c.host, fmt.Errorf("error getting json for image %q: %v", image, err))
return nil, convertConnectionError(c.url.String(), fmt.Errorf("error getting json for image %q: %v", image, err))
}
switch code := resp.StatusCode; {
case code == http.StatusNotFound:
Expand Down
98 changes: 98 additions & 0 deletions pkg/dockerregistry/client_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
package dockerregistry

import (
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"strings"
"testing"
)

func TestConnect(t *testing.T) {
c := NewClient()
conn, err := c.Connect("docker.io")
if err != nil {
t.Fatal(err)
}
for _, s := range []string{"index.docker.io", "https://docker.io", "https://index.docker.io"} {
otherConn, err := c.Connect(s)
if err != nil {
t.Errorf("%s: can't connect: ", s, err)
continue
}
if !reflect.DeepEqual(otherConn, conn) {
t.Errorf("%s: did not reuse connection: %#v %#v", s, conn, otherConn)
}
}

otherConn, err := c.Connect("index.docker.io:443")
if err != nil || reflect.DeepEqual(otherConn, conn) {
t.Errorf("should not have reused index.docker.io:443: %v", err)
}

if _, err := c.Connect("http://ba%3/"); err == nil {
t.Error("Unexpected non-error")
}
}

func TestHTTPFallback(t *testing.T) {
called := make(chan struct{}, 2)
var uri *url.URL
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
called <- struct{}{}
if strings.HasSuffix(r.URL.Path, "/tags") {
w.WriteHeader(http.StatusNotFound)
return
}
w.Header().Set("X-Docker-Endpoints", uri.Host)
w.WriteHeader(http.StatusOK)
}))
uri, _ = url.Parse(server.URL)
conn, err := NewClient().Connect(uri.Host)
if err != nil {
t.Fatal(err)
}
if _, err := conn.ImageTags("foo", "bar"); !IsRepositoryNotFound(err) {
t.Error(err)
}
<-called
<-called
}

func TestRegistryNotFound(t *testing.T) {
conn, err := NewClient().Connect("localhost:65000")
if err != nil {
t.Fatal(err)
}
if _, err := conn.ImageByID("foo", "bar", "baz"); !IsRegistryNotFound(err) {
t.Error(err)
}
}

func TestImage(t *testing.T) {
conn, err := NewClient().Connect("")
if err != nil {
t.Fatal(err)
}

if _, err := conn.ImageByTag("openshift", "origin-not-found", "latest"); !IsRepositoryNotFound(err) {
t.Errorf("unexpected error: %v", err)
}

image, err := conn.ImageByTag("openshift", "origin", "latest")
if err != nil {
t.Fatal(err)
}
if len(image.ContainerConfig.Entrypoint) == 0 {
t.Errorf("unexpected image: %#v", image)
}

other, err := conn.ImageByID("openshift", "origin", image.ID)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(other.ContainerConfig.Entrypoint, image.ContainerConfig.Entrypoint) {
t.Errorf("unexpected image: %#v", other)
}
}
12 changes: 12 additions & 0 deletions pkg/image/api/helper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,10 +88,22 @@ func TestParseDockerImageReference(t *testing.T) {
Name: "baz",
ID: "sha256:3c87c572822935df60f0f5d3665bd376841a7fcfeb806b5f212de6a00e9a7b25",
},
{
From: "https://bar:5000/foo/baz",
Err: true,
},
{
From: "http://bar:5000/foo/baz@sha256:3c87c572822935df60f0f5d3665bd376841a7fcfeb806b5f212de6a00e9a7b25",
Err: true,
},
{
From: "bar/foo/baz/biz",
Err: true,
},
{
From: "ftp://baz/baz/biz",
Err: true,
},
{
From: "",
Err: true,
Expand Down