github.com/taylorchu/nomad@v0.5.3-rc1.0.20170407200202-db11e7dd7b55/client/driver/raw_exec_unix_test.go (about)

     1  // +build !windows
     2  
     3  package driver
     4  
     5  import (
     6  	"io/ioutil"
     7  	"path/filepath"
     8  	"strings"
     9  	"syscall"
    10  	"testing"
    11  	"time"
    12  
    13  	"github.com/hashicorp/nomad/nomad/structs"
    14  	"github.com/hashicorp/nomad/testutil"
    15  )
    16  
    17  func TestRawExecDriver_Signal(t *testing.T) {
    18  	task := &structs.Task{
    19  		Name:   "signal",
    20  		Driver: "raw_exec",
    21  		Config: map[string]interface{}{
    22  			"command": "/bin/bash",
    23  			"args":    []string{"test.sh"},
    24  		},
    25  		LogConfig: &structs.LogConfig{
    26  			MaxFiles:      10,
    27  			MaxFileSizeMB: 10,
    28  		},
    29  		Resources:   basicResources,
    30  		KillTimeout: 10 * time.Second,
    31  	}
    32  
    33  	ctx := testDriverContexts(t, task)
    34  	defer ctx.AllocDir.Destroy()
    35  	d := NewRawExecDriver(ctx.DriverCtx)
    36  
    37  	testFile := filepath.Join(ctx.ExecCtx.TaskDir.Dir, "test.sh")
    38  	testData := []byte(`
    39  at_term() {
    40      echo 'Terminated.'
    41      exit 3
    42  }
    43  trap at_term USR1
    44  while true; do
    45      sleep 1
    46  done
    47  	`)
    48  	if err := ioutil.WriteFile(testFile, testData, 0777); err != nil {
    49  		t.Fatalf("Failed to write data: %v", err)
    50  	}
    51  
    52  	if _, err := d.Prestart(ctx.ExecCtx, task); err != nil {
    53  		t.Fatalf("prestart err: %v", err)
    54  	}
    55  	handle, err := d.Start(ctx.ExecCtx, task)
    56  	if err != nil {
    57  		t.Fatalf("err: %v", err)
    58  	}
    59  	if handle == nil {
    60  		t.Fatalf("missing handle")
    61  	}
    62  
    63  	go func() {
    64  		time.Sleep(100 * time.Millisecond)
    65  		err := handle.Signal(syscall.SIGUSR1)
    66  		if err != nil {
    67  			t.Fatalf("err: %v", err)
    68  		}
    69  	}()
    70  
    71  	// Task should terminate quickly
    72  	select {
    73  	case res := <-handle.WaitCh():
    74  		if res.Successful() {
    75  			t.Fatal("should err")
    76  		}
    77  	case <-time.After(time.Duration(testutil.TestMultiplier()*6) * time.Second):
    78  		t.Fatalf("timeout")
    79  	}
    80  
    81  	// Check the log file to see it exited because of the signal
    82  	outputFile := filepath.Join(ctx.ExecCtx.TaskDir.LogDir, "signal.stdout.0")
    83  	act, err := ioutil.ReadFile(outputFile)
    84  	if err != nil {
    85  		t.Fatalf("Couldn't read expected output: %v", err)
    86  	}
    87  
    88  	exp := "Terminated."
    89  	if strings.TrimSpace(string(act)) != exp {
    90  		t.Logf("Read from %v", outputFile)
    91  		t.Fatalf("Command outputted %v; want %v", act, exp)
    92  	}
    93  }