podman

Форк
0
228 строк · 6.5 Кб
1
package buildah
2

3
import (
4
	"errors"
5
	"fmt"
6
	"io"
7
	"os"
8
	"path/filepath"
9
	"sync"
10

11
	"github.com/containers/buildah/copier"
12
	"github.com/containers/image/v5/docker/reference"
13
	"github.com/containers/image/v5/pkg/sysregistriesv2"
14
	"github.com/containers/image/v5/types"
15
	"github.com/containers/storage"
16
	"github.com/containers/storage/pkg/idtools"
17
	"github.com/containers/storage/pkg/reexec"
18
	v1 "github.com/opencontainers/image-spec/specs-go/v1"
19
	rspec "github.com/opencontainers/runtime-spec/specs-go"
20
	"github.com/opencontainers/selinux/go-selinux/label"
21
	"github.com/sirupsen/logrus"
22
)
23

24
// InitReexec is a wrapper for reexec.Init().  It should be called at
25
// the start of main(), and if it returns true, main() should return
26
// immediately.
27
func InitReexec() bool {
28
	return reexec.Init()
29
}
30

31
func copyStringStringMap(m map[string]string) map[string]string {
32
	n := map[string]string{}
33
	for k, v := range m {
34
		n[k] = v
35
	}
36
	return n
37
}
38

39
func copyStringSlice(s []string) []string {
40
	t := make([]string, len(s))
41
	copy(t, s)
42
	return t
43
}
44

45
func copyHistory(history []v1.History) []v1.History {
46
	if len(history) == 0 {
47
		return nil
48
	}
49
	h := make([]v1.History, 0, len(history))
50
	for _, entry := range history {
51
		created := entry.Created
52
		if created != nil {
53
			timestamp := *created
54
			created = &timestamp
55
		}
56
		h = append(h, v1.History{
57
			Created:    created,
58
			CreatedBy:  entry.CreatedBy,
59
			Author:     entry.Author,
60
			Comment:    entry.Comment,
61
			EmptyLayer: entry.EmptyLayer,
62
		})
63
	}
64
	return h
65
}
66

67
func convertStorageIDMaps(UIDMap, GIDMap []idtools.IDMap) ([]rspec.LinuxIDMapping, []rspec.LinuxIDMapping) {
68
	uidmap := make([]rspec.LinuxIDMapping, 0, len(UIDMap))
69
	gidmap := make([]rspec.LinuxIDMapping, 0, len(GIDMap))
70
	for _, m := range UIDMap {
71
		uidmap = append(uidmap, rspec.LinuxIDMapping{
72
			HostID:      uint32(m.HostID),
73
			ContainerID: uint32(m.ContainerID),
74
			Size:        uint32(m.Size),
75
		})
76
	}
77
	for _, m := range GIDMap {
78
		gidmap = append(gidmap, rspec.LinuxIDMapping{
79
			HostID:      uint32(m.HostID),
80
			ContainerID: uint32(m.ContainerID),
81
			Size:        uint32(m.Size),
82
		})
83
	}
84
	return uidmap, gidmap
85
}
86

87
func convertRuntimeIDMaps(UIDMap, GIDMap []rspec.LinuxIDMapping) ([]idtools.IDMap, []idtools.IDMap) {
88
	uidmap := make([]idtools.IDMap, 0, len(UIDMap))
89
	gidmap := make([]idtools.IDMap, 0, len(GIDMap))
90
	for _, m := range UIDMap {
91
		uidmap = append(uidmap, idtools.IDMap{
92
			HostID:      int(m.HostID),
93
			ContainerID: int(m.ContainerID),
94
			Size:        int(m.Size),
95
		})
96
	}
97
	for _, m := range GIDMap {
98
		gidmap = append(gidmap, idtools.IDMap{
99
			HostID:      int(m.HostID),
100
			ContainerID: int(m.ContainerID),
101
			Size:        int(m.Size),
102
		})
103
	}
104
	return uidmap, gidmap
105
}
106

107
// isRegistryBlocked checks if the named registry is marked as blocked
108
func isRegistryBlocked(registry string, sc *types.SystemContext) (bool, error) {
109
	reginfo, err := sysregistriesv2.FindRegistry(sc, registry)
110
	if err != nil {
111
		return false, fmt.Errorf("unable to parse the registries configuration (%s): %w", sysregistriesv2.ConfigPath(sc), err)
112
	}
113
	if reginfo != nil {
114
		if reginfo.Blocked {
115
			logrus.Debugf("registry %q is marked as blocked in registries configuration %q", registry, sysregistriesv2.ConfigPath(sc))
116
		} else {
117
			logrus.Debugf("registry %q is not marked as blocked in registries configuration %q", registry, sysregistriesv2.ConfigPath(sc))
118
		}
119
		return reginfo.Blocked, nil
120
	}
121
	logrus.Debugf("registry %q is not listed in registries configuration %q, assuming it's not blocked", registry, sysregistriesv2.ConfigPath(sc))
122
	return false, nil
123
}
124

125
// isReferenceSomething checks if the registry part of a reference is insecure or blocked
126
func isReferenceSomething(ref types.ImageReference, sc *types.SystemContext, what func(string, *types.SystemContext) (bool, error)) (bool, error) {
127
	if ref != nil {
128
		if named := ref.DockerReference(); named != nil {
129
			if domain := reference.Domain(named); domain != "" {
130
				return what(domain, sc)
131
			}
132
		}
133
	}
134
	return false, nil
135
}
136

137
// isReferenceBlocked checks if the registry part of a reference is blocked
138
func isReferenceBlocked(ref types.ImageReference, sc *types.SystemContext) (bool, error) {
139
	if ref != nil && ref.Transport() != nil {
140
		switch ref.Transport().Name() {
141
		case "docker":
142
			return isReferenceSomething(ref, sc, isRegistryBlocked)
143
		}
144
	}
145
	return false, nil
146
}
147

148
// ReserveSELinuxLabels reads containers storage and reserves SELinux contexts
149
// which are already being used by buildah containers.
150
func ReserveSELinuxLabels(store storage.Store, id string) error {
151
	if selinuxGetEnabled() {
152
		containers, err := store.Containers()
153
		if err != nil {
154
			return fmt.Errorf("getting list of containers: %w", err)
155
		}
156

157
		for _, c := range containers {
158
			if id == c.ID {
159
				continue
160
			} else {
161
				b, err := OpenBuilder(store, c.ID)
162
				if err != nil {
163
					if errors.Is(err, os.ErrNotExist) {
164
						// Ignore not exist errors since containers probably created by other tool
165
						// TODO, we need to read other containers json data to reserve their SELinux labels
166
						continue
167
					}
168
					return err
169
				}
170
				// Prevent different containers from using same MCS label
171
				if err := label.ReserveLabel(b.ProcessLabel); err != nil {
172
					return fmt.Errorf("reserving SELinux label %q: %w", b.ProcessLabel, err)
173
				}
174
			}
175
		}
176
	}
177
	return nil
178
}
179

180
// IsContainer identifies if the specified container id is a buildah container
181
// in the specified store.
182
func IsContainer(id string, store storage.Store) (bool, error) {
183
	cdir, err := store.ContainerDirectory(id)
184
	if err != nil {
185
		return false, err
186
	}
187
	// Assuming that if the stateFile exists, that this is a Buildah
188
	// container.
189
	if _, err = os.Stat(filepath.Join(cdir, stateFile)); err != nil {
190
		if errors.Is(err, os.ErrNotExist) {
191
			return false, nil
192
		}
193
		return false, err
194
	}
195
	return true, nil
196
}
197

198
// Copy content from the directory "src" to the directory "dest", ensuring that
199
// content from outside of "root" (which is a parent of "src" or "src" itself)
200
// isn't read.
201
func extractWithTar(root, src, dest string) error {
202
	var getErr, putErr error
203
	var wg sync.WaitGroup
204

205
	pipeReader, pipeWriter := io.Pipe()
206

207
	wg.Add(1)
208
	go func() {
209
		getErr = copier.Get(root, src, copier.GetOptions{}, []string{"."}, pipeWriter)
210
		pipeWriter.Close()
211
		wg.Done()
212
	}()
213
	wg.Add(1)
214
	go func() {
215
		putErr = copier.Put(dest, dest, copier.PutOptions{}, pipeReader)
216
		pipeReader.Close()
217
		wg.Done()
218
	}()
219
	wg.Wait()
220

221
	if getErr != nil {
222
		return fmt.Errorf("reading %q: %w", src, getErr)
223
	}
224
	if putErr != nil {
225
		return fmt.Errorf("copying contents of %q to %q: %w", src, dest, putErr)
226
	}
227
	return nil
228
}
229

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.