2017-12-11 02:18:18 +00:00
|
|
|
package oci
|
|
|
|
|
|
|
|
import (
|
2018-08-01 21:15:43 +00:00
|
|
|
"bytes"
|
2018-01-16 22:30:10 +00:00
|
|
|
"context"
|
2018-08-01 21:15:43 +00:00
|
|
|
"fmt"
|
2017-12-11 02:18:18 +00:00
|
|
|
"io/ioutil"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
2018-08-01 21:15:43 +00:00
|
|
|
|
|
|
|
"github.com/moby/buildkit/executor"
|
|
|
|
"github.com/moby/buildkit/identity"
|
2017-12-11 02:18:18 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const hostsContent = `
|
2018-10-03 00:25:33 +00:00
|
|
|
127.0.0.1 localhost buildkitsandbox
|
2017-12-11 02:18:18 +00:00
|
|
|
::1 localhost ip6-localhost ip6-loopback
|
|
|
|
`
|
|
|
|
|
2018-08-03 21:01:54 +00:00
|
|
|
func GetHostsFile(ctx context.Context, stateDir string, extraHosts []executor.HostIP) (string, func(), error) {
|
2018-08-01 21:15:43 +00:00
|
|
|
if len(extraHosts) == 0 {
|
|
|
|
_, err := g.Do(ctx, stateDir, func(ctx context.Context) (interface{}, error) {
|
2018-08-03 21:01:54 +00:00
|
|
|
_, _, err := makeHostsFile(stateDir, nil)
|
2018-08-01 21:15:43 +00:00
|
|
|
return nil, err
|
|
|
|
})
|
|
|
|
if err != nil {
|
2018-08-03 21:01:54 +00:00
|
|
|
return "", nil, err
|
2017-12-11 02:18:18 +00:00
|
|
|
}
|
2018-08-03 21:01:54 +00:00
|
|
|
return filepath.Join(stateDir, "hosts"), func() {}, nil
|
2018-08-01 21:15:43 +00:00
|
|
|
}
|
|
|
|
return makeHostsFile(stateDir, extraHosts)
|
|
|
|
}
|
|
|
|
|
2018-08-03 21:01:54 +00:00
|
|
|
func makeHostsFile(stateDir string, extraHosts []executor.HostIP) (string, func(), error) {
|
2018-08-01 21:15:43 +00:00
|
|
|
p := filepath.Join(stateDir, "hosts")
|
|
|
|
if len(extraHosts) != 0 {
|
|
|
|
p += "." + identity.NewID()
|
|
|
|
}
|
|
|
|
_, err := os.Stat(p)
|
|
|
|
if err == nil {
|
2018-08-03 21:01:54 +00:00
|
|
|
return "", func() {}, nil
|
2018-08-01 21:15:43 +00:00
|
|
|
}
|
|
|
|
if !os.IsNotExist(err) {
|
2018-08-03 21:01:54 +00:00
|
|
|
return "", nil, err
|
2018-08-01 21:15:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
b := &bytes.Buffer{}
|
|
|
|
|
|
|
|
if _, err := b.Write([]byte(hostsContent)); err != nil {
|
2018-08-03 21:01:54 +00:00
|
|
|
return "", nil, err
|
2018-08-01 21:15:43 +00:00
|
|
|
}
|
2017-12-11 02:18:18 +00:00
|
|
|
|
2018-08-01 21:15:43 +00:00
|
|
|
for _, h := range extraHosts {
|
|
|
|
if _, err := b.Write([]byte(fmt.Sprintf("%s\t%s\n", h.IP.String(), h.Host))); err != nil {
|
2018-08-03 21:01:54 +00:00
|
|
|
return "", nil, err
|
2017-12-11 02:18:18 +00:00
|
|
|
}
|
2018-08-01 21:15:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if err := ioutil.WriteFile(p+".tmp", b.Bytes(), 0644); err != nil {
|
2018-08-03 21:01:54 +00:00
|
|
|
return "", nil, err
|
2018-08-01 21:15:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if err := os.Rename(p+".tmp", p); err != nil {
|
2018-08-03 21:01:54 +00:00
|
|
|
return "", nil, err
|
2017-12-11 02:18:18 +00:00
|
|
|
}
|
2018-08-03 21:01:54 +00:00
|
|
|
return p, func() {
|
|
|
|
os.RemoveAll(p)
|
|
|
|
}, nil
|
2017-12-11 02:18:18 +00:00
|
|
|
}
|