1package testutilities
2
3import (
4	"context"
5	"os"
6	"testing"
7
8	"github.com/Microsoft/hcsshim/internal/uvm"
9)
10
11// CreateWCOWUVM creates a WCOW utility VM with all default options. Returns the
12// UtilityVM object; folder used as its scratch
13func CreateWCOWUVM(ctx context.Context, t *testing.T, id, image string) (*uvm.UtilityVM, []string, string) {
14	return CreateWCOWUVMFromOptsWithImage(ctx, t, uvm.NewDefaultOptionsWCOW(id, ""), image)
15
16}
17
18// CreateWCOWUVMFromOpts creates a WCOW utility VM with the passed opts.
19func CreateWCOWUVMFromOpts(ctx context.Context, t *testing.T, opts *uvm.OptionsWCOW) *uvm.UtilityVM {
20	if opts == nil || len(opts.LayerFolders) < 2 {
21		t.Fatalf("opts must bet set with LayerFolders")
22	}
23
24	uvm, err := uvm.CreateWCOW(ctx, opts)
25	if err != nil {
26		t.Fatal(err)
27	}
28	if err := uvm.Start(ctx); err != nil {
29		uvm.Close()
30		t.Fatal(err)
31	}
32	return uvm
33}
34
35// CreateWCOWUVMFromOptsWithImage creates a WCOW utility VM with the passed opts
36// builds the LayerFolders based on `image`. Returns the UtilityVM object;
37// folder used as its scratch
38func CreateWCOWUVMFromOptsWithImage(ctx context.Context, t *testing.T, opts *uvm.OptionsWCOW, image string) (*uvm.UtilityVM, []string, string) {
39	if opts == nil {
40		t.Fatal("opts must be set")
41	}
42
43	uvmLayers := LayerFolders(t, image)
44	scratchDir := CreateTempDir(t)
45	defer func() {
46		if t.Failed() {
47			os.RemoveAll(scratchDir)
48		}
49	}()
50
51	opts.LayerFolders = append(opts.LayerFolders, uvmLayers...)
52	opts.LayerFolders = append(opts.LayerFolders, scratchDir)
53
54	return CreateWCOWUVMFromOpts(ctx, t, opts), uvmLayers, scratchDir
55}
56
57// CreateLCOWUVM with all default options.
58func CreateLCOWUVM(ctx context.Context, t *testing.T, id string) *uvm.UtilityVM {
59	return CreateLCOWUVMFromOpts(ctx, t, uvm.NewDefaultOptionsLCOW(id, ""))
60}
61
62// CreateLCOWUVMFromOpts creates an LCOW utility VM with the specified options.
63func CreateLCOWUVMFromOpts(ctx context.Context, t *testing.T, opts *uvm.OptionsLCOW) *uvm.UtilityVM {
64	if opts == nil {
65		t.Fatal("opts must be set")
66	}
67
68	uvm, err := uvm.CreateLCOW(ctx, opts)
69	if err != nil {
70		t.Fatal(err)
71	}
72	if err := uvm.Start(ctx); err != nil {
73		uvm.Close()
74		t.Fatal(err)
75	}
76	return uvm
77}
78