Browse Source

registry: minor improvements and cleanup

- registry: newIndexInfo(): minor refactor
- registry: loadAllowNondistributableArtifacts() minor refactor
  initialise the slices with a length.
- registry: defaultService.Search(): minor refactor
  Perform all manipulation earlier, so that it's not needed to scroll up
  to learn what's done.
- various other minor cleanups

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
Sebastiaan van Stijn 3 years ago
parent
commit
9cb0aa4c91
4 changed files with 20 additions and 36 deletions
  1. 5 12
      registry/auth.go
  2. 5 6
      registry/config.go
  3. 4 9
      registry/endpoint_v1.go
  4. 6 9
      registry/service.go

+ 5 - 12
registry/auth.go

@@ -15,10 +15,8 @@ import (
 	"github.com/sirupsen/logrus"
 )
 
-const (
-	// AuthClientID is used the ClientID used for the token server
-	AuthClientID = "docker"
-)
+// AuthClientID is used the ClientID used for the token server
+const AuthClientID = "docker"
 
 type loginCredentialStore struct {
 	authConfig *types.AuthConfig
@@ -109,8 +107,7 @@ func loginV2(authConfig *types.AuthConfig, endpoint APIEndpoint, userAgent strin
 	}
 
 	// TODO(dmcgowan): Attempt to further interpret result, status code and error code string
-	err = errors.Errorf("login attempt to %s failed with status: %d %s", endpointStr, resp.StatusCode, http.StatusText(resp.StatusCode))
-	return "", "", err
+	return "", "", errors.Errorf("login attempt to %s failed with status: %d %s", endpointStr, resp.StatusCode, http.StatusText(resp.StatusCode))
 }
 
 func v2AuthHTTPClient(endpoint *url.URL, authTransport http.RoundTripper, modifiers []transport.RequestModifier, creds auth.CredentialStore, scopes []auth.Scope) (*http.Client, error) {
@@ -129,10 +126,9 @@ func v2AuthHTTPClient(endpoint *url.URL, authTransport http.RoundTripper, modifi
 	tokenHandler := auth.NewTokenHandlerWithOptions(tokenHandlerOptions)
 	basicHandler := auth.NewBasicHandler(creds)
 	modifiers = append(modifiers, auth.NewAuthorizer(challengeManager, tokenHandler, basicHandler))
-	tr := transport.NewTransport(authTransport, modifiers...)
 
 	return &http.Client{
-		Transport: tr,
+		Transport: transport.NewTransport(authTransport, modifiers...),
 		Timeout:   15 * time.Second,
 	}, nil
 }
@@ -146,10 +142,7 @@ func ConvertToHostname(url string) string {
 	} else if strings.HasPrefix(url, "https://") {
 		stripped = strings.TrimPrefix(url, "https://")
 	}
-
-	nameParts := strings.SplitN(stripped, "/", 2)
-
-	return nameParts[0]
+	return strings.SplitN(stripped, "/", 2)[0]
 }
 
 // ResolveAuthConfig matches an auth configuration to a server address or a URL

+ 5 - 6
registry/config.go

@@ -110,12 +110,12 @@ func (config *serviceConfig) loadAllowNondistributableArtifacts(registries []str
 		}
 	}
 
-	config.AllowNondistributableArtifactsCIDRs = make([]*(registry.NetIPNet), 0)
+	config.AllowNondistributableArtifactsCIDRs = make([]*registry.NetIPNet, 0, len(cidrs))
 	for _, c := range cidrs {
 		config.AllowNondistributableArtifactsCIDRs = append(config.AllowNondistributableArtifactsCIDRs, c)
 	}
 
-	config.AllowNondistributableArtifactsHostnames = make([]string, 0)
+	config.AllowNondistributableArtifactsHostnames = make([]string, 0, len(hostnames))
 	for h := range hostnames {
 		config.AllowNondistributableArtifactsHostnames = append(config.AllowNondistributableArtifactsHostnames, h)
 	}
@@ -378,13 +378,12 @@ func newIndexInfo(config *serviceConfig, indexName string) (*registry.IndexInfo,
 	}
 
 	// Construct a non-configured index info.
-	index := &registry.IndexInfo{
+	return &registry.IndexInfo{
 		Name:     indexName,
 		Mirrors:  make([]string, 0),
+		Secure:   isSecureIndex(config, indexName),
 		Official: false,
-	}
-	index.Secure = isSecureIndex(config, indexName)
-	return index, nil
+	}, nil
 }
 
 // GetAuthConfigKey special-cases using the full index address of the official

+ 4 - 9
registry/endpoint_v1.go

@@ -67,7 +67,7 @@ func validateEndpoint(endpoint *v1Endpoint) error {
 		}
 
 		// If registry is insecure and HTTPS failed, fallback to HTTP.
-		logrus.Debugf("Error from registry %q marked as insecure: %v. Insecurely falling back to HTTP", endpoint, err)
+		logrus.WithError(err).Debugf("error from registry %q marked as insecure - insecurely falling back to HTTP", endpoint)
 		endpoint.URL.Scheme = "http"
 
 		var err2 error
@@ -84,14 +84,9 @@ func validateEndpoint(endpoint *v1Endpoint) error {
 // trimV1Address trims the version off the address and returns the
 // trimmed address or an error if there is a non-V1 version.
 func trimV1Address(address string) (string, error) {
-	var (
-		chunks        []string
-		apiVersionStr string
-	)
-
 	address = strings.TrimSuffix(address, "/")
-	chunks = strings.Split(address, "/")
-	apiVersionStr = chunks[len(chunks)-1]
+	chunks := strings.Split(address, "/")
+	apiVersionStr := chunks[len(chunks)-1]
 	if apiVersionStr == "v1" {
 		return strings.Join(chunks[:len(chunks)-1], "/"), nil
 	}
@@ -168,7 +163,7 @@ func (e *v1Endpoint) ping() (v1PingResult, error) {
 		Standalone: true,
 	}
 	if err := json.Unmarshal(jsonString, &info); err != nil {
-		logrus.Debugf("Error unmarshaling the _ping v1PingResult: %s", err)
+		logrus.WithError(err).Debug("error unmarshaling _ping response")
 		// don't stop here. Just assume sane defaults
 	}
 	if hdr := resp.Header.Get("X-Docker-Registry-Version"); hdr != "" {

+ 6 - 9
registry/service.go

@@ -174,8 +174,11 @@ func (s *defaultService) Search(ctx context.Context, term string, limit int, aut
 	if err != nil {
 		return nil, err
 	}
+	if index.Official {
+		// If pull "library/foo", it's stored locally under "foo"
+		remoteName = strings.TrimPrefix(remoteName, "library/")
+	}
 
-	// *TODO: Search multiple indexes.
 	endpoint, err := newV1Endpoint(index, userAgent, headers)
 	if err != nil {
 		return nil, err
@@ -195,7 +198,7 @@ func (s *defaultService) Search(ctx context.Context, term string, limit int, aut
 		v2Client, err := v2AuthHTTPClient(endpoint.URL, endpoint.client.Transport, modifiers, creds, scopes)
 		if err != nil {
 			if fErr, ok := err.(fallbackError); ok {
-				logrus.Errorf("Cannot use identity token for search, v2 auth not supported: %v", fErr.err)
+				logrus.WithError(fErr.err).Error("cannot use identity token for search, v2 auth not supported")
 			} else {
 				return nil, err
 			}
@@ -217,13 +220,7 @@ func (s *defaultService) Search(ctx context.Context, term string, limit int, aut
 		}
 	}
 
-	r := newSession(client, endpoint)
-
-	if index.Official {
-		// If pull "library/foo", it's stored locally under "foo"
-		remoteName = strings.TrimPrefix(remoteName, "library/")
-	}
-	return r.searchRepositories(remoteName, limit)
+	return newSession(client, endpoint).searchRepositories(remoteName, limit)
 }
 
 // ResolveRepository splits a repository name into its components