-
Notifications
You must be signed in to change notification settings - Fork 136
/
builder_test.go
265 lines (229 loc) · 6.65 KB
/
builder_test.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
package oci
import (
"archive/tar"
"compress/gzip"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"runtime"
"sort"
"strings"
"sync"
"testing"
"github.com/google/go-cmp/cmp"
v1 "github.com/google/go-containerregistry/pkg/v1"
fn "knative.dev/func/pkg/functions"
. "knative.dev/func/pkg/testing"
)
var TestPlatforms = []fn.Platform{{OS: runtime.GOOS, Architecture: runtime.GOARCH}}
// TestBuilder_Build ensures that, when given a Go Function, an OCI-compliant
// directory structure is created on .Build in the expected path.
func TestBuilder_Build(t *testing.T) {
root, done := Mktemp(t)
defer done()
client := fn.New(fn.WithVerbose(true))
f, err := client.Init(fn.Function{Root: root, Runtime: "go"})
if err != nil {
t.Fatal(err)
}
builder := NewBuilder("", true)
if err := builder.Build(context.Background(), f, TestPlatforms); err != nil {
t.Fatal(err)
}
last := path(f.Root, fn.RunDataDir, "builds", "last", "oci")
validateOCI(last, t)
}
// TestBuilder_Concurrency
func TestBuilder_Concurrency(t *testing.T) {
root, done := Mktemp(t)
defer done()
client := fn.New()
// Initialize a new Go Function
f, err := client.Init(fn.Function{Root: root, Runtime: "go"})
if err != nil {
t.Fatal(err)
}
// Concurrency
//
// The first builder is setup to use a mock implementation of the
// builder function which will block until released after first notifying
// that it has been paused.
//
// When the test receives the message that the builder has been paused, it
// starts a second, concurrently executing builder to ensure there is a
// typed error returned indicating a build is in progress.
//
// When the second builder completes, having confirmed the error message
// received is as expected. It signals the first (blocked) builder that it
// can now continue.
// Thet test waits until the first builder notifies that it is done, and
// has therefore ran its tests as well.
var (
pausedCh = make(chan bool)
continueCh = make(chan bool)
wg sync.WaitGroup
)
// Build A
builder1 := NewBuilder("builder1", true)
builder1.buildFn = func(cfg *buildConfig, p v1.Platform) (d v1.Descriptor, l v1.Layer, err error) {
if isFirstBuild(cfg, p) {
pausedCh <- true // Notify of being paused
<-continueCh // Block until released
}
return
}
wg.Add(1)
go func() {
defer wg.Done()
if err := builder1.Build(context.Background(), f, TestPlatforms); err != nil {
t.Errorf("test build error: %v", err)
}
}()
// Wait until build 1 indicates it is paused
<-pausedCh
// Build B
builder2 := NewBuilder("builder2", true)
builder2.buildFn = func(config *buildConfig, platform v1.Platform) (v1.Descriptor, v1.Layer, error) {
return v1.Descriptor{}, nil, fmt.Errorf("the buildFn should not have been invoked")
}
wg.Add(1)
go func() {
defer wg.Done()
err = builder2.Build(context.Background(), f, TestPlatforms)
if !errors.As(err, &ErrBuildInProgress{}) {
t.Errorf("test build error: %v", err)
}
}()
// Release the blocking Build A and wait until complete.
continueCh <- true
wg.Wait()
}
func isFirstBuild(cfg *buildConfig, current v1.Platform) bool {
first := cfg.platforms[0]
return current.OS == first.OS &&
current.Architecture == first.Architecture &&
current.Variant == first.Variant
}
// ImageIndex represents the structure of an OCI Image Index.
type ImageIndex struct {
SchemaVersion int `json:"schemaVersion"`
Manifests []struct {
MediaType string `json:"mediaType"`
Size int64 `json:"size"`
Digest string `json:"digest"`
Platform struct {
Architecture string `json:"architecture"`
OS string `json:"os"`
} `json:"platform"`
} `json:"manifests"`
}
// validateOCI performs a cursory check that the given path exists and
// has the basics of an OCI compliant structure.
func validateOCI(path string, t *testing.T) {
if _, err := os.Stat(path); err != nil {
t.Fatalf("unable to stat output path. %v", path)
return
}
ociLayoutFile := filepath.Join(path, "oci-layout")
indexJSONFile := filepath.Join(path, "index.json")
blobsDir := filepath.Join(path, "blobs")
// Check if required files and directories exist
if _, err := os.Stat(ociLayoutFile); os.IsNotExist(err) {
t.Fatal("missing oci-layout file")
}
if _, err := os.Stat(indexJSONFile); os.IsNotExist(err) {
t.Fatal("missing index.json file")
}
if _, err := os.Stat(blobsDir); os.IsNotExist(err) {
t.Fatal("missing blobs directory")
}
// Load and validate index.json
indexJSONData, err := os.ReadFile(indexJSONFile)
if err != nil {
t.Fatalf("failed to read index.json: %v", err)
}
var imageIndex ImageIndex
err = json.Unmarshal(indexJSONData, &imageIndex)
if err != nil {
t.Fatalf("failed to parse index.json: %v", err)
}
if imageIndex.SchemaVersion != 2 {
t.Fatalf("invalid schema version, expected 2, got %d", imageIndex.SchemaVersion)
}
if len(imageIndex.Manifests) < 1 {
t.Fatal("fewer manifests")
}
digest := strings.TrimPrefix(imageIndex.Manifests[0].Digest, "sha256:")
manifestFile := filepath.Join(path, "blobs", "sha256", digest)
manifestFileData, err := os.ReadFile(manifestFile)
if err != nil {
t.Fatal(err)
}
mf := struct {
Layers []struct {
Digest string `json:"digest"`
} `json:"layers"`
}{}
err = json.Unmarshal(manifestFileData, &mf)
if err != nil {
t.Fatal(err)
}
type fileInfo struct {
Path string
Type fs.FileMode
Executable bool
}
var files []fileInfo
for _, layer := range mf.Layers {
func() {
digest = strings.TrimPrefix(layer.Digest, "sha256:")
f, err := os.Open(filepath.Join(path, "blobs", "sha256", digest))
if err != nil {
t.Fatal(err)
}
defer f.Close()
gr, err := gzip.NewReader(f)
if err != nil {
t.Fatal(err)
}
defer gr.Close()
tr := tar.NewReader(gr)
for {
hdr, err := tr.Next()
if err != nil {
if errors.Is(err, io.EOF) {
break
}
t.Fatal(err)
}
files = append(files, fileInfo{
Path: hdr.Name,
Type: hdr.FileInfo().Mode() & fs.ModeType,
Executable: (hdr.FileInfo().Mode()&0111 == 0111) && !hdr.FileInfo().IsDir(),
})
}
}()
}
sort.Slice(files, func(i, j int) bool {
return files[i].Path < files[j].Path
})
expectedFiles := []fileInfo{
{Path: "/etc/pki/tls/certs/ca-certificates.crt"},
{Path: "/etc/ssl/certs/ca-certificates.crt"},
{Path: "/func", Type: fs.ModeDir},
{Path: "/func/README.md"},
{Path: "/func/f", Executable: true},
{Path: "/func/func.yaml"},
{Path: "/func/go.mod"},
{Path: "/func/handle.go"},
{Path: "/func/handle_test.go"},
}
if diff := cmp.Diff(expectedFiles, files); diff != "" {
t.Error("files in oci differ from expectation (-want, +got):", diff)
}
}