-
Notifications
You must be signed in to change notification settings - Fork 239
/
labelreader.go
75 lines (61 loc) · 1.64 KB
/
labelreader.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
//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 . LabelReader
package containertools
import (
"encoding/json"
"fmt"
"github.com/sirupsen/logrus"
)
type LabelReader interface {
GetLabelsFromImage(string) (map[string]string, error)
}
type ImageLabelReader struct {
Logger *logrus.Entry
Cmd CommandRunner
}
func NewLabelReader(containerTool ContainerTool, logger *logrus.Entry) LabelReader {
cmd := NewCommandRunner(containerTool, logger)
return ImageLabelReader{
Logger: logger,
Cmd: cmd,
}
}
type DockerImageData struct {
Config DockerConfig `json:"Config"`
}
type DockerConfig struct {
Labels map[string]string `json:"Labels"`
}
type PodmanImageData struct {
Labels map[string]string `json:"Labels"`
}
// GetLabelsFromImage takes a container image path as input, pulls that image
// to the local environment and then inspects it for labels
func (r ImageLabelReader) GetLabelsFromImage(image string) (map[string]string, error) {
err := r.Cmd.Pull(image)
if err != nil {
return nil, err
}
r.Logger.Info("Getting label data from previous image")
imageData, err := r.Cmd.Inspect(image)
if err != nil {
return nil, err
}
// parse output of inspect to get labels
switch containerTool := r.Cmd.GetToolName(); containerTool {
case "docker":
var data []DockerImageData
err := json.Unmarshal(imageData, &data)
if err != nil {
return nil, err
}
return data[0].Config.Labels, nil
case "podman":
var data []PodmanImageData
err := json.Unmarshal(imageData, &data)
if err != nil {
return nil, err
}
return data[0].Labels, nil
}
return nil, fmt.Errorf("Unable to parse label data from container")
}