forked from quay/claircore
-
Notifications
You must be signed in to change notification settings - Fork 0
/
containerapi.go
83 lines (76 loc) · 1.88 KB
/
containerapi.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
package containerapi
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"path"
"strings"
"github.com/quay/zlog"
)
type ContainerImages struct {
Images []ContainerImage `json:"data"`
}
type ContainerImage struct {
CPEs []string `json:"cpe_ids"`
ParsedData ParsedData `json:"parsed_data"`
}
type ParsedData struct {
Architecture string `json:"architecture"`
Labels []Label `json:"labels"`
}
type Label struct {
Name string `json:"name"`
Value string `json:"value"`
}
// ContainerAPI gets container metadata from Red Hat's API.
type ContainerAPI struct {
Client *http.Client
Root *url.URL
}
// GetCPEs fetches CPE information for given build from Red Hat Container API.
func (c *ContainerAPI) GetCPEs(ctx context.Context, nvr, arch string) ([]string, error) {
uri, err := c.Root.Parse(path.Join("v1/images/nvr/", nvr))
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, uri.String(), nil)
if err != nil {
return nil, err
}
zlog.Debug(ctx).
Str("uri", uri.String()).
Msg("making container API request")
res, err := c.Client.Do(req)
if res != nil {
defer res.Body.Close()
}
if err != nil {
return nil, err
}
if res.StatusCode != http.StatusOK {
var b strings.Builder
if _, err := io.Copy(&b, res.Body); err != nil {
zlog.Warn(ctx).Err(err).Msg("additional error while reading response")
} else {
zlog.Warn(ctx).Str("response", b.String()).Msg("received error response")
}
return nil, fmt.Errorf("rhel: unexpected response: %d %s", res.StatusCode, res.Status)
}
var ci ContainerImages
if err := json.NewDecoder(res.Body).Decode(&ci); err != nil {
return nil, err
}
for _, image := range ci.Images {
for _, label := range image.ParsedData.Labels {
if label.Name == "architecture" {
if label.Value == arch {
return image.CPEs, nil
}
}
}
}
return nil, nil
}