forked from moby/buildkit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hosts.go
69 lines (59 loc) · 1.46 KB
/
hosts.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
package oci
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"github.com/moby/buildkit/executor"
"github.com/moby/buildkit/identity"
)
const hostsContent = `
127.0.0.1 localhost buildkitsandbox
::1 localhost ip6-localhost ip6-loopback
`
func GetHostsFile(ctx context.Context, stateDir string, extraHosts []executor.HostIP) (string, func(), error) {
if len(extraHosts) == 0 {
_, err := g.Do(ctx, stateDir, func(ctx context.Context) (interface{}, error) {
_, _, err := makeHostsFile(stateDir, nil)
return nil, err
})
if err != nil {
return "", nil, err
}
return filepath.Join(stateDir, "hosts"), func() {}, nil
}
return makeHostsFile(stateDir, extraHosts)
}
func makeHostsFile(stateDir string, extraHosts []executor.HostIP) (string, func(), error) {
p := filepath.Join(stateDir, "hosts")
if len(extraHosts) != 0 {
p += "." + identity.NewID()
}
_, err := os.Stat(p)
if err == nil {
return "", func() {}, nil
}
if !os.IsNotExist(err) {
return "", nil, err
}
b := &bytes.Buffer{}
if _, err := b.Write([]byte(hostsContent)); err != nil {
return "", nil, err
}
for _, h := range extraHosts {
if _, err := b.Write([]byte(fmt.Sprintf("%s\t%s\n", h.IP.String(), h.Host))); err != nil {
return "", nil, err
}
}
if err := ioutil.WriteFile(p+".tmp", b.Bytes(), 0644); err != nil {
return "", nil, err
}
if err := os.Rename(p+".tmp", p); err != nil {
return "", nil, err
}
return p, func() {
os.RemoveAll(p)
}, nil
}