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