github.com/cvmfs/docker-graphdriver@v0.0.0-20181206110523-155ec6df0521/docker2cvmfs/lib/manifest.go (about)

     1  package lib
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"io/ioutil"
     7  	"net/http"
     8  	"strings"
     9  )
    10  
    11  func createImageUrl(dockerRegistryUrl, image string) (string, error) {
    12  	i := strings.Split(image, ":")
    13  	if len(i) < 2 {
    14  		return "", fmt.Errorf("No tag provide for the input reference \"%s\" reference, please provide one.", image)
    15  	}
    16  	tag := i[1]
    17  	ref := i[0]
    18  
    19  	arr := []string{dockerRegistryUrl, ref, "manifests", tag}
    20  	return strings.Join(arr, "/"), nil
    21  }
    22  
    23  func getManifest(dockerRegistryUrl, image string) (Manifest, error) {
    24  	var manifest Manifest
    25  	imageUrl, err := createImageUrl(dockerRegistryUrl, image)
    26  	if err != nil {
    27  		return manifest, err
    28  	}
    29  
    30  	resp, _ := http.Get(imageUrl)
    31  
    32  	if resp.StatusCode == http.StatusUnauthorized && token == "" {
    33  		authHeader := resp.Header["Www-Authenticate"][0]
    34  		token = getToken(getAuthParams(authHeader))
    35  	}
    36  
    37  	req, _ := http.NewRequest("GET", imageUrl, nil)
    38  	req.Header.Add("Authorization", "Bearer "+token)
    39  	req.Header.Add("Accept", "application/vnd.docker.distribution.manifest.v2+json")
    40  
    41  	var client http.Client
    42  	resp, err = client.Do(req)
    43  	if err != nil {
    44  		return manifest, err
    45  	}
    46  
    47  	body, err := ioutil.ReadAll(resp.Body)
    48  	resp.Body.Close()
    49  	if err != nil {
    50  		return manifest, err
    51  	}
    52  
    53  	if resp.StatusCode >= 400 || resp.StatusCode < 200 {
    54  		return manifest, fmt.Errorf("Impossible to get the manifest, got error status code from the registry: %d \nErrorBody: %s", resp.StatusCode, string(body))
    55  	}
    56  
    57  	json.Unmarshal(body, &manifest)
    58  
    59  	return manifest, nil
    60  }
    61  
    62  func GetManifest(dockerRegistryUrl, image string) (Manifest, error) {
    63  	manifest, err := getManifest(dockerRegistryUrl, image)
    64  	return manifest, err
    65  }