-
Notifications
You must be signed in to change notification settings - Fork 479
/
resources.go
67 lines (58 loc) · 1.63 KB
/
resources.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
package k8s
import (
"context"
"fmt"
"io"
"os"
"time"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// ResourceSet deploys a set of temporary objects to a k8s test cluster and
// deletes them when Stop is called.
type ResourceSet struct {
log log.Logger
kubeClient client.Client
objects []client.Object
}
// NewResourceSet returns a new resource set.
func NewResourceSet(l log.Logger, cluster *Cluster) *ResourceSet {
return &ResourceSet{
log: l,
kubeClient: cluster.Client(),
}
}
// Add will read from r and deploy the resources into the cluster.
func (rs *ResourceSet) Add(ctx context.Context, r io.Reader) error {
readObjects, err := ReadObjects(r, rs.kubeClient)
if err != nil {
return fmt.Errorf("error reading fixture: %w", err)
}
err = CreateObjects(ctx, rs.kubeClient, readObjects...)
if err != nil {
return err
}
rs.objects = append(rs.objects, readObjects...)
return nil
}
// AddFile will open filename and deploy it into the cluster.
func (rs *ResourceSet) AddFile(ctx context.Context, filename string) error {
f, err := os.Open(filename)
if err != nil {
return fmt.Errorf("failed to open %q: %w", filename, err)
}
defer f.Close()
return rs.Add(ctx, f)
}
// Stop removes deployed resources from the cluster.
func (rs *ResourceSet) Stop() {
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
for _, obj := range rs.objects {
err := rs.kubeClient.Delete(ctx, obj)
if err != nil {
level.Error(rs.log).Log("msg", "failed to delete object", "obj", client.ObjectKeyFromObject(obj), "err", err)
}
}
}