github.com/opencontainers/runtime-tools@v0.9.0/validation/prestart_fail/prestart_fail.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"path/filepath"
     7  
     8  	tap "github.com/mndrix/tap-go"
     9  	rspec "github.com/opencontainers/runtime-spec/specs-go"
    10  	"github.com/opencontainers/runtime-tools/specerror"
    11  	"github.com/opencontainers/runtime-tools/validation/util"
    12  	uuid "github.com/satori/go.uuid"
    13  )
    14  
    15  func main() {
    16  	t := tap.New()
    17  	t.Header(0)
    18  
    19  	bundleDir, err := util.PrepareBundle()
    20  	if err != nil {
    21  		return
    22  	}
    23  	defer os.RemoveAll(bundleDir)
    24  
    25  	g, err := util.GetDefaultGenerator()
    26  	if err != nil {
    27  		util.Fatal(err)
    28  	}
    29  	prestart := rspec.Hook{
    30  		Path: filepath.Join(bundleDir, g.Spec().Root.Path, "/bin/false"),
    31  		Args: []string{"false"},
    32  	}
    33  	g.AddPreStartHook(prestart)
    34  	g.SetProcessArgs([]string{"sh", "-c", fmt.Sprintf("touch %s", "/output")})
    35  	containerID := uuid.NewV4().String()
    36  
    37  	config := util.LifecycleConfig{
    38  		Config:    g,
    39  		BundleDir: bundleDir,
    40  		Actions:   util.LifecycleActionCreate | util.LifecycleActionStart,
    41  		PreCreate: func(r *util.Runtime) error {
    42  			r.SetID(containerID)
    43  			return nil
    44  		},
    45  	}
    46  
    47  	runErr := util.RuntimeLifecycleValidate(config)
    48  	_, outputErr := os.Stat(filepath.Join(bundleDir, g.Spec().Root.Path, "output"))
    49  
    50  	// query the state
    51  	r, _ := util.NewRuntime(util.RuntimeCommand, "")
    52  	r.SetID(containerID)
    53  	_, stateErr := r.State()
    54  	if stateErr != nil {
    55  		// In case a container is created, delete it
    56  		r.Delete()
    57  	}
    58  
    59  	// if runErr is nil, it means the runtime does not generate an error
    60  	// if outputErr is nil, it means the runtime calls the Process anyway
    61  	// if stateErr is nil, it means it does not continue lifecycle at step 9
    62  	if runErr == nil || outputErr == nil || stateErr == nil {
    63  		err = specerror.NewError(specerror.PrestartHookFailGenError, fmt.Errorf("if any prestart hook fails, the runtime MUST generate an error, stop the container, and continue the lifecycle at step 9"), rspec.Version)
    64  		diagnostic := map[string]string{
    65  			"error": err.Error(),
    66  		}
    67  		t.YAML(diagnostic)
    68  	}
    69  
    70  	t.AutoPlan()
    71  }