github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/caas/kubernetes/provider/dockerconfig.go (about)

     1  // Copyright 2018 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package provider
     5  
     6  import (
     7  	// Import shas that are used for docker image validation.
     8  	_ "crypto/sha256"
     9  	_ "crypto/sha512"
    10  	"encoding/json"
    11  
    12  	"github.com/docker/distribution/reference"
    13  	"github.com/juju/errors"
    14  
    15  	"github.com/juju/juju/caas"
    16  )
    17  
    18  // These Docker Config datatypes have been pulled from
    19  // "k8s.io/kubernetes/pkg/credentialprovider".
    20  // multiple k8s packages import the same package, we don't yet have the tooling
    21  // to flatten the deps.
    22  // The specific package in this case is golog.
    23  
    24  // DockerConfigJson represents ~/.docker/config.json file info.
    25  type DockerConfigJson struct {
    26  	Auths DockerConfig `json:"auths"`
    27  }
    28  
    29  // DockerConfig represents the config file used by the docker CLI.
    30  type DockerConfig map[string]DockerConfigEntry
    31  
    32  // DockerConfigEntry represents an Auth entry in the dockerconfigjson.
    33  type DockerConfigEntry struct {
    34  	Username string
    35  	Password string
    36  	Email    string
    37  }
    38  
    39  func createDockerConfigJSON(imageDetails *caas.ImageDetails) ([]byte, error) {
    40  	dockerEntry := DockerConfigEntry{
    41  		Username: imageDetails.Username,
    42  		Password: imageDetails.Password,
    43  	}
    44  	registryURL, err := extractRegistryURL(imageDetails.ImagePath)
    45  	if err != nil {
    46  		return nil, errors.Trace(err)
    47  	}
    48  
    49  	dockerConfig := DockerConfigJson{
    50  		Auths: map[string]DockerConfigEntry{
    51  			registryURL: dockerEntry,
    52  		},
    53  	}
    54  	return json.Marshal(dockerConfig)
    55  }
    56  
    57  // extractRegistryName returns the registry URL part of an images path
    58  func extractRegistryURL(imagePath string) (string, error) {
    59  	imageNamed, err := reference.ParseNormalizedNamed(imagePath)
    60  	if err != nil {
    61  		return "", errors.Annotate(err, "extracting registry from path")
    62  	}
    63  	return reference.Domain(imageNamed), nil
    64  }