forked from juju/juju
-
Notifications
You must be signed in to change notification settings - Fork 0
/
docker.go
91 lines (74 loc) · 2.05 KB
/
docker.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// Copyright 2019 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package docker
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/juju/errors"
"github.com/juju/loggo"
"github.com/juju/version"
"github.com/juju/juju/tools"
)
const (
baseRegistryURL = "https://registry.hub.docker.com/v1/repositories"
)
type imageInfo struct {
version version.Number
}
func (info imageInfo) AgentVersion() version.Number {
return info.version
}
var logger = loggo.GetLogger("juju.docker")
// ListOperatorImages queries the standard docker registry and
// returns the version tags for images matching imagePath.
// The results are used when upgrading Juju to see what's available.
func ListOperatorImages(imagePath string) (tools.Versions, error) {
tagsURL := fmt.Sprintf("%s/%s/tags", baseRegistryURL, imagePath)
logger.Debugf("operater image tags URL: %v", tagsURL)
data, err := HttpGet(tagsURL, 30*time.Second)
if err != nil {
return nil, errors.Trace(err)
}
type info struct {
Tag string `json:"name"`
}
var tagInfo []info
err = json.Unmarshal(data, &tagInfo)
if err != nil {
return nil, errors.Trace(err)
}
var images tools.Versions
for _, t := range tagInfo {
v, err := version.Parse(t.Tag)
if err != nil {
logger.Debugf("ignoring unexpected image tag %q", t.Tag)
continue
}
images = append(images, imageInfo{v})
}
return images, nil
}
// Override for testing.
var HttpGet = doHttpGet
func doHttpGet(url string, timeout time.Duration) ([]byte, error) {
request, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, errors.Trace(err)
}
ctx, cancelFunc := context.WithTimeout(context.Background(), timeout)
defer cancelFunc()
request = request.WithContext(ctx)
response, err := http.DefaultClient.Do(request)
if err != nil {
return nil, errors.Trace(err)
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return nil, errors.Errorf("invalid response code from registry: %v", response.StatusCode)
}
return ioutil.ReadAll(response.Body)
}