-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.go
269 lines (225 loc) · 5.98 KB
/
util.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
package attr
import (
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"runtime"
"strconv"
"strings"
)
func Quote(l []string) []string {
var quoted []string
for _, s := range l {
quoted = append(quoted, fmt.Sprintf("%q", s))
}
return quoted
}
func In(list []string, el string) bool {
return IndexOf(list, el) != -1
}
func IndexOf(list []string, el string) int {
for i, x := range list {
if el == x {
return i
}
}
return -1
}
const (
dockercfgFileName = ".dockercfg"
)
const (
defaultTag = "latest"
defaultIndexURL = "registry-1.docker.io"
)
func ParseDockerURL(arg string) *ParsedDockerURL {
if arg == "" {
return nil
}
taglessRemote, tag := parseRepositoryTag(arg)
if tag == "" {
tag = defaultTag
}
indexURL, imageName := SplitReposName(taglessRemote)
if indexURL == "" && !strings.Contains(imageName, "/") {
imageName = "library/" + imageName
}
if indexURL == "" {
indexURL = defaultIndexURL
}
return &ParsedDockerURL{
IndexURL: indexURL,
ImageName: imageName,
Tag: tag,
}
}
// splitReposName breaks a reposName into an index name and remote name
func SplitReposName(reposName string) (string, string) {
nameParts := strings.SplitN(reposName, "/", 2)
var indexName, remoteName string
if len(nameParts) == 1 || (!strings.Contains(nameParts[0], ".") &&
!strings.Contains(nameParts[0], ":") && nameParts[0] != "localhost") {
// This is a Docker Index repos (ex: samalba/hipache or ubuntu)
// The URL for the index is different depending on the version of the
// API used to fetch it, so it cannot be inferred here.
indexName = ""
remoteName = reposName
} else {
indexName = nameParts[0]
remoteName = nameParts[1]
}
return indexName, remoteName
}
// Get a repos name and returns the right reposName + tag
// The tag can be confusing because of a port in a repository name.
// Ex: localhost.localdomain:5000/samalba/hipache:latest
func parseRepositoryTag(repos string) (string, string) {
n := strings.LastIndex(repos, ":")
if n < 0 {
return repos, ""
}
if tag := repos[n+1:]; !strings.Contains(tag, "/") {
return repos[:n], tag
}
return repos, ""
}
func decodeDockerAuth(s string) (string, string, error) {
decoded, err := base64.StdEncoding.DecodeString(s)
if err != nil {
return "", "", err
}
parts := strings.SplitN(string(decoded), ":", 2)
if len(parts) != 2 {
return "", "", fmt.Errorf("invalid auth configuration file")
}
user := parts[0]
password := strings.Trim(parts[1], "\x00")
return user, password, nil
}
func getHomeDir() string {
if runtime.GOOS == "windows" {
return os.Getenv("USERPROFILE")
}
return os.Getenv("HOME")
}
// GetDockercfgAuth reads a ~/.dockercfg file and returns the username and password
// of the given docker index server.
func GetAuthInfo(indexServer string) (string, string, error) {
dockerCfgPath := path.Join(getHomeDir(), dockercfgFileName)
if _, err := os.Stat(dockerCfgPath); os.IsNotExist(err) {
return "", "", nil
}
j, err := ioutil.ReadFile(dockerCfgPath)
if err != nil {
return "", "", err
}
var dockerAuth map[string]DockerAuthConfig
if err := json.Unmarshal(j, &dockerAuth); err != nil {
return "", "", err
}
// the official auth uses the full address instead of the hostname
officialAddress := "https://" + indexServer + "/v1/"
if c, ok := dockerAuth[officialAddress]; ok {
return decodeDockerAuth(c.Auth)
}
// try the normal case
if c, ok := dockerAuth[indexServer]; ok {
return decodeDockerAuth(c.Auth)
}
return "", "", nil
}
func parseDockerUser(dockerUser string) (string, string) {
// if the docker user is empty assume root user and group
if dockerUser == "" {
return "0", "0"
}
dockerUserParts := strings.Split(dockerUser, ":")
// when only the user is given, the docker spec says that the default and
// supplementary groups of the user in /etc/passwd should be applied.
// Assume root group for now in this case.
if len(dockerUserParts) < 2 {
return dockerUserParts[0], "0"
}
return dockerUserParts[0], dockerUserParts[1]
}
func getExecCommand(entrypoint []string, cmd []string) Exec {
var command []string
if entrypoint == nil && cmd == nil {
return nil
}
command = append(entrypoint, cmd...)
// non-absolute paths are not allowed, fallback to "/bin/sh -c command"
if len(command) > 0 && !filepath.IsAbs(command[0]) {
command_prefix := []string{"/bin/sh", "-c"}
quoted_command := Quote(command)
command = append(command_prefix, strings.Join(quoted_command, " "))
}
return command
}
func getPorts(dockerExposedPorts map[string]struct{}, dockerPortSpecs []string) ([]Port, error) {
ports := []Port{}
for ep := range dockerExposedPorts {
aPort, err := parseDockerPort(ep)
if err != nil {
return nil, err
}
ports = append(ports, *aPort)
}
if dockerExposedPorts == nil && dockerPortSpecs != nil {
fmt.Println("warning: docker image uses deprecated PortSpecs field")
for _, ep := range dockerPortSpecs {
aPort, err := parseDockerPort(ep)
if err != nil {
return nil, err
}
ports = append(ports, *aPort)
}
}
return ports, nil
}
func parseDockerPort(dockerPort string) (*Port, error) {
var portString string
proto := "tcp"
sp := strings.Split(dockerPort, "/")
if len(sp) < 2 {
portString = dockerPort
} else {
proto = sp[1]
portString = sp[0]
}
port, err := strconv.ParseUint(portString, 10, 0)
if err != nil {
return nil, fmt.Errorf("error parsing port %q: %v", portString, err)
}
sn := strings.ToLower(dockerPort)
parsedPort := &Port{
Name: sn,
Protocol: proto,
Port: uint(port),
}
return parsedPort, nil
}
func convertVolumesToMPs(dockerVolumes map[string]struct{}) ([]MountPoint, error) {
mps := []MountPoint{}
dup := make(map[string]int)
for p := range dockerVolumes {
sn := filepath.Join("volume", p)
// check for duplicate names
if i, ok := dup[sn]; ok {
dup[sn] = i + 1
sn = fmt.Sprintf("%s-%d", sn, i)
} else {
dup[sn] = 1
}
mp := MountPoint{
Name: sn,
Path: p,
}
mps = append(mps, mp)
}
return mps, nil
}