File: hosts.go

package info (click to toggle)
singularity-container 4.1.5%2Bds4-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 43,876 kB
  • sloc: asm: 14,840; sh: 3,190; ansic: 1,751; awk: 414; makefile: 413; python: 99
file content (86 lines) | stat: -rw-r--r-- 2,179 bytes parent folder | download | duplicates (3)
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
package oci

import (
	"bytes"
	"context"
	"fmt"
	"os"
	"path/filepath"

	"github.com/docker/docker/pkg/idtools"
	"github.com/moby/buildkit/executor"
	"github.com/moby/buildkit/identity"
	"github.com/pkg/errors"
)

const defaultHostname = "buildkitsandbox"

func GetHostsFile(ctx context.Context, stateDir string, extraHosts []executor.HostIP, idmap *idtools.IdentityMapping, hostname string) (string, func(), error) {
	if len(extraHosts) != 0 || hostname != defaultHostname {
		return makeHostsFile(stateDir, extraHosts, idmap, hostname)
	}

	_, err := g.Do(ctx, stateDir, func(ctx context.Context) (struct{}, error) {
		_, _, err := makeHostsFile(stateDir, nil, idmap, hostname)
		return struct{}{}, err
	})
	if err != nil {
		return "", nil, err
	}
	return filepath.Join(stateDir, "hosts"), func() {}, nil
}

func makeHostsFile(stateDir string, extraHosts []executor.HostIP, idmap *idtools.IdentityMapping, hostname string) (string, func(), error) {
	p := filepath.Join(stateDir, "hosts")
	if len(extraHosts) != 0 || hostname != defaultHostname {
		p += "." + identity.NewID()
	}
	_, err := os.Stat(p)
	if err == nil {
		return "", func() {}, nil
	}
	if !errors.Is(err, os.ErrNotExist) {
		return "", nil, err
	}

	b := &bytes.Buffer{}
	if _, err := b.Write([]byte(initHostsFile(hostname))); 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
		}
	}

	tmpPath := p + ".tmp"
	if err := os.WriteFile(tmpPath, b.Bytes(), 0644); err != nil {
		return "", nil, err
	}

	if idmap != nil {
		root := idmap.RootPair()
		if err := os.Chown(tmpPath, root.UID, root.GID); err != nil {
			return "", nil, err
		}
	}

	if err := os.Rename(tmpPath, p); err != nil {
		return "", nil, err
	}
	return p, func() {
		os.RemoveAll(p)
	}, nil
}

func initHostsFile(hostname string) string {
	var hosts string
	if hostname != "" {
		hosts = fmt.Sprintf("127.0.0.1	localhost %s", hostname)
	} else {
		hosts = fmt.Sprintf("127.0.0.1	localhost %s", defaultHostname)
	}
	hosts = fmt.Sprintf("%s\n::1	localhost ip6-localhost ip6-loopback\n", hosts)
	return hosts
}