github.com/emate/nomad@v0.8.2-wo-binpacking/client/driver/driver_test.go (about)

     1  package driver
     2  
     3  import (
     4  	"io"
     5  	"io/ioutil"
     6  	"log"
     7  	"math/rand"
     8  	"os"
     9  	"path/filepath"
    10  	"reflect"
    11  	"testing"
    12  	"time"
    13  
    14  	"github.com/hashicorp/nomad/client/allocdir"
    15  	"github.com/hashicorp/nomad/client/config"
    16  	"github.com/hashicorp/nomad/client/driver/env"
    17  	"github.com/hashicorp/nomad/helper/testtask"
    18  	"github.com/hashicorp/nomad/helper/uuid"
    19  	"github.com/hashicorp/nomad/nomad/mock"
    20  	"github.com/hashicorp/nomad/nomad/structs"
    21  )
    22  
    23  var basicResources = &structs.Resources{
    24  	CPU:      250,
    25  	MemoryMB: 256,
    26  	DiskMB:   20,
    27  }
    28  
    29  func init() {
    30  	rand.Seed(49875)
    31  }
    32  
    33  func TestMain(m *testing.M) {
    34  	if !testtask.Run() {
    35  		os.Exit(m.Run())
    36  	}
    37  }
    38  
    39  // copyFile moves an existing file to the destination
    40  func copyFile(src, dst string, t *testing.T) {
    41  	in, err := os.Open(src)
    42  	if err != nil {
    43  		t.Fatalf("copying %v -> %v failed: %v", src, dst, err)
    44  	}
    45  	defer in.Close()
    46  	out, err := os.Create(dst)
    47  	if err != nil {
    48  		t.Fatalf("copying %v -> %v failed: %v", src, dst, err)
    49  	}
    50  	defer func() {
    51  		if err := out.Close(); err != nil {
    52  			t.Fatalf("copying %v -> %v failed: %v", src, dst, err)
    53  		}
    54  	}()
    55  	if _, err = io.Copy(out, in); err != nil {
    56  		t.Fatalf("copying %v -> %v failed: %v", src, dst, err)
    57  	}
    58  	if err := out.Sync(); err != nil {
    59  		t.Fatalf("copying %v -> %v failed: %v", src, dst, err)
    60  	}
    61  }
    62  
    63  func testLogger() *log.Logger {
    64  	return log.New(os.Stderr, "", log.LstdFlags)
    65  }
    66  
    67  func testConfig(t *testing.T) *config.Config {
    68  	conf := config.DefaultConfig()
    69  
    70  	// Evaluate the symlinks so that the temp directory resolves correctly on
    71  	// Mac OS.
    72  	d1, err := ioutil.TempDir("", "TestStateDir")
    73  	if err != nil {
    74  		t.Fatal(err)
    75  	}
    76  	d2, err := ioutil.TempDir("", "TestAllocDir")
    77  	if err != nil {
    78  		t.Fatal(err)
    79  	}
    80  
    81  	p1, err := filepath.EvalSymlinks(d1)
    82  	if err != nil {
    83  		t.Fatal(err)
    84  	}
    85  	p2, err := filepath.EvalSymlinks(d2)
    86  	if err != nil {
    87  		t.Fatal(err)
    88  	}
    89  
    90  	// Give the directories access to everyone
    91  	if err := os.Chmod(p1, 0777); err != nil {
    92  		t.Fatal(err)
    93  	}
    94  	if err := os.Chmod(p2, 0777); err != nil {
    95  		t.Fatal(err)
    96  	}
    97  
    98  	conf.StateDir = p1
    99  	conf.AllocDir = p2
   100  	conf.MaxKillTimeout = 10 * time.Second
   101  	conf.Region = "global"
   102  	conf.Node = mock.Node()
   103  	return conf
   104  }
   105  
   106  type testContext struct {
   107  	AllocDir   *allocdir.AllocDir
   108  	DriverCtx  *DriverContext
   109  	ExecCtx    *ExecContext
   110  	EnvBuilder *env.Builder
   111  }
   112  
   113  // testDriverContext sets up an alloc dir, task dir, DriverContext, and ExecContext.
   114  //
   115  // It is up to the caller to call AllocDir.Destroy to cleanup.
   116  func testDriverContexts(t *testing.T, task *structs.Task) *testContext {
   117  	cfg := testConfig(t)
   118  	cfg.Node = mock.Node()
   119  	allocDir := allocdir.NewAllocDir(testLogger(), filepath.Join(cfg.AllocDir, uuid.Generate()))
   120  	if err := allocDir.Build(); err != nil {
   121  		t.Fatalf("AllocDir.Build() failed: %v", err)
   122  	}
   123  	alloc := mock.Alloc()
   124  
   125  	// Build a temp driver so we can call FSIsolation and build the task dir
   126  	tmpdrv, err := NewDriver(task.Driver, NewEmptyDriverContext())
   127  	if err != nil {
   128  		allocDir.Destroy()
   129  		t.Fatalf("NewDriver(%q, nil) failed: %v", task.Driver, err)
   130  		return nil
   131  	}
   132  
   133  	// Build the task dir
   134  	td := allocDir.NewTaskDir(task.Name)
   135  	if err := td.Build(false, config.DefaultChrootEnv, tmpdrv.FSIsolation()); err != nil {
   136  		allocDir.Destroy()
   137  		t.Fatalf("TaskDir.Build(%#v, %q) failed: %v", config.DefaultChrootEnv, tmpdrv.FSIsolation(), err)
   138  		return nil
   139  	}
   140  	eb := env.NewBuilder(cfg.Node, alloc, task, cfg.Region)
   141  	SetEnvvars(eb, tmpdrv.FSIsolation(), td, cfg)
   142  	execCtx := NewExecContext(td, eb.Build())
   143  
   144  	logger := testLogger()
   145  	emitter := func(m string, args ...interface{}) {
   146  		logger.Printf("[EVENT] "+m, args...)
   147  	}
   148  	driverCtx := NewDriverContext(alloc.Job.Name, alloc.TaskGroup, task.Name, alloc.ID, cfg, cfg.Node, logger, emitter)
   149  
   150  	return &testContext{allocDir, driverCtx, execCtx, eb}
   151  }
   152  
   153  // setupTaskEnv creates a test env for GetTaskEnv testing. Returns task dir,
   154  // expected env, and actual env.
   155  func setupTaskEnv(t *testing.T, driver string) (*allocdir.TaskDir, map[string]string, map[string]string) {
   156  	task := &structs.Task{
   157  		Name:   "Foo",
   158  		Driver: driver,
   159  		Env: map[string]string{
   160  			"HELLO": "world",
   161  			"lorem": "ipsum",
   162  		},
   163  		Resources: &structs.Resources{
   164  			CPU:      1000,
   165  			MemoryMB: 500,
   166  			Networks: []*structs.NetworkResource{
   167  				{
   168  					IP:            "1.2.3.4",
   169  					ReservedPorts: []structs.Port{{Label: "one", Value: 80}, {Label: "two", Value: 443}},
   170  					DynamicPorts:  []structs.Port{{Label: "admin", Value: 8081}, {Label: "web", Value: 8086}},
   171  				},
   172  			},
   173  		},
   174  		Meta: map[string]string{
   175  			"chocolate":  "cake",
   176  			"strawberry": "icecream",
   177  		},
   178  	}
   179  
   180  	alloc := mock.Alloc()
   181  	alloc.Job.TaskGroups[0].Tasks[0] = task
   182  	alloc.Name = "Bar"
   183  	alloc.TaskResources["web"].Networks[0].DynamicPorts[0].Value = 2000
   184  	conf := testConfig(t)
   185  	allocDir := allocdir.NewAllocDir(testLogger(), filepath.Join(conf.AllocDir, alloc.ID))
   186  	taskDir := allocDir.NewTaskDir(task.Name)
   187  	eb := env.NewBuilder(conf.Node, alloc, task, conf.Region)
   188  	tmpDriver, err := NewDriver(driver, NewEmptyDriverContext())
   189  	if err != nil {
   190  		t.Fatalf("unable to create driver %q: %v", driver, err)
   191  	}
   192  	SetEnvvars(eb, tmpDriver.FSIsolation(), taskDir, conf)
   193  	exp := map[string]string{
   194  		"NOMAD_CPU_LIMIT":               "1000",
   195  		"NOMAD_MEMORY_LIMIT":            "500",
   196  		"NOMAD_ADDR_one":                "1.2.3.4:80",
   197  		"NOMAD_IP_one":                  "1.2.3.4",
   198  		"NOMAD_PORT_one":                "80",
   199  		"NOMAD_HOST_PORT_one":           "80",
   200  		"NOMAD_ADDR_two":                "1.2.3.4:443",
   201  		"NOMAD_IP_two":                  "1.2.3.4",
   202  		"NOMAD_PORT_two":                "443",
   203  		"NOMAD_HOST_PORT_two":           "443",
   204  		"NOMAD_ADDR_admin":              "1.2.3.4:8081",
   205  		"NOMAD_ADDR_web_admin":          "192.168.0.100:5000",
   206  		"NOMAD_ADDR_web_http":           "192.168.0.100:2000",
   207  		"NOMAD_IP_web_admin":            "192.168.0.100",
   208  		"NOMAD_IP_web_http":             "192.168.0.100",
   209  		"NOMAD_PORT_web_http":           "2000",
   210  		"NOMAD_PORT_web_admin":          "5000",
   211  		"NOMAD_IP_admin":                "1.2.3.4",
   212  		"NOMAD_PORT_admin":              "8081",
   213  		"NOMAD_HOST_PORT_admin":         "8081",
   214  		"NOMAD_ADDR_web":                "1.2.3.4:8086",
   215  		"NOMAD_IP_web":                  "1.2.3.4",
   216  		"NOMAD_PORT_web":                "8086",
   217  		"NOMAD_HOST_PORT_web":           "8086",
   218  		"NOMAD_META_CHOCOLATE":          "cake",
   219  		"NOMAD_META_STRAWBERRY":         "icecream",
   220  		"NOMAD_META_ELB_CHECK_INTERVAL": "30s",
   221  		"NOMAD_META_ELB_CHECK_TYPE":     "http",
   222  		"NOMAD_META_ELB_CHECK_MIN":      "3",
   223  		"NOMAD_META_OWNER":              "armon",
   224  		"NOMAD_META_chocolate":          "cake",
   225  		"NOMAD_META_strawberry":         "icecream",
   226  		"NOMAD_META_elb_check_interval": "30s",
   227  		"NOMAD_META_elb_check_type":     "http",
   228  		"NOMAD_META_elb_check_min":      "3",
   229  		"NOMAD_META_owner":              "armon",
   230  		"HELLO":                         "world",
   231  		"lorem":                         "ipsum",
   232  		"NOMAD_ALLOC_ID":                alloc.ID,
   233  		"NOMAD_ALLOC_INDEX":             "0",
   234  		"NOMAD_ALLOC_NAME":              alloc.Name,
   235  		"NOMAD_TASK_NAME":               task.Name,
   236  		"NOMAD_GROUP_NAME":              alloc.TaskGroup,
   237  		"NOMAD_JOB_NAME":                alloc.Job.Name,
   238  		"NOMAD_DC":                      "dc1",
   239  		"NOMAD_REGION":                  "global",
   240  	}
   241  
   242  	act := eb.Build().Map()
   243  	return taskDir, exp, act
   244  }
   245  
   246  func TestDriver_GetTaskEnv_None(t *testing.T) {
   247  	t.Parallel()
   248  	taskDir, exp, act := setupTaskEnv(t, "raw_exec")
   249  
   250  	// raw_exec should use host alloc dir path
   251  	exp[env.AllocDir] = taskDir.SharedAllocDir
   252  	exp[env.TaskLocalDir] = taskDir.LocalDir
   253  	exp[env.SecretsDir] = taskDir.SecretsDir
   254  
   255  	// Since host env vars are included only ensure expected env vars are present
   256  	for expk, expv := range exp {
   257  		v, ok := act[expk]
   258  		if !ok {
   259  			t.Errorf("%q not found in task env", expk)
   260  			continue
   261  		}
   262  		if v != expv {
   263  			t.Errorf("Expected %s=%q but found %q", expk, expv, v)
   264  		}
   265  	}
   266  
   267  	// Make sure common host env vars are included.
   268  	for _, envvar := range [...]string{"PATH", "HOME", "USER"} {
   269  		if exp := os.Getenv(envvar); act[envvar] != exp {
   270  			t.Errorf("Expected envvar %s=%q  !=  %q", envvar, exp, act[envvar])
   271  		}
   272  	}
   273  }
   274  
   275  func TestDriver_GetTaskEnv_Chroot(t *testing.T) {
   276  	t.Parallel()
   277  	_, exp, act := setupTaskEnv(t, "exec")
   278  
   279  	exp[env.AllocDir] = allocdir.SharedAllocContainerPath
   280  	exp[env.TaskLocalDir] = allocdir.TaskLocalContainerPath
   281  	exp[env.SecretsDir] = allocdir.TaskSecretsContainerPath
   282  
   283  	// Since host env vars are included only ensure expected env vars are present
   284  	for expk, expv := range exp {
   285  		v, ok := act[expk]
   286  		if !ok {
   287  			t.Errorf("%q not found in task env", expk)
   288  			continue
   289  		}
   290  		if v != expv {
   291  			t.Errorf("Expected %s=%q but found %q", expk, expv, v)
   292  		}
   293  	}
   294  
   295  	// Make sure common host env vars are included.
   296  	for _, envvar := range [...]string{"PATH", "HOME", "USER"} {
   297  		if exp := os.Getenv(envvar); act[envvar] != exp {
   298  			t.Errorf("Expected envvar %s=%q  !=  %q", envvar, exp, act[envvar])
   299  		}
   300  	}
   301  }
   302  
   303  // TestDriver_TaskEnv_Image ensures host environment variables are not set
   304  // for image based drivers. See #2211
   305  func TestDriver_TaskEnv_Image(t *testing.T) {
   306  	t.Parallel()
   307  	_, exp, act := setupTaskEnv(t, "docker")
   308  
   309  	exp[env.AllocDir] = allocdir.SharedAllocContainerPath
   310  	exp[env.TaskLocalDir] = allocdir.TaskLocalContainerPath
   311  	exp[env.SecretsDir] = allocdir.TaskSecretsContainerPath
   312  
   313  	// Since host env vars are excluded expected and actual maps should be equal
   314  	for expk, expv := range exp {
   315  		v, ok := act[expk]
   316  		delete(act, expk)
   317  		if !ok {
   318  			t.Errorf("Env var %s missing. Expected %s=%q", expk, expk, expv)
   319  			continue
   320  		}
   321  		if v != expv {
   322  			t.Errorf("Env var %s=%q -- Expected %q", expk, v, expk)
   323  		}
   324  	}
   325  	// Any remaining env vars are unexpected
   326  	for actk, actv := range act {
   327  		t.Errorf("Env var %s=%q is unexpected", actk, actv)
   328  	}
   329  }
   330  
   331  func TestMapMergeStrStr(t *testing.T) {
   332  	t.Parallel()
   333  	a := map[string]string{
   334  		"cake":   "chocolate",
   335  		"cookie": "caramel",
   336  	}
   337  
   338  	b := map[string]string{
   339  		"cake": "strawberry",
   340  		"pie":  "apple",
   341  	}
   342  
   343  	c := mapMergeStrStr(a, b)
   344  
   345  	d := map[string]string{
   346  		"cake":   "strawberry",
   347  		"cookie": "caramel",
   348  		"pie":    "apple",
   349  	}
   350  
   351  	if !reflect.DeepEqual(c, d) {
   352  		t.Errorf("\nExpected\n%+v\nGot\n%+v\n", d, c)
   353  	}
   354  }
   355  
   356  func TestCreatedResources_AddMerge(t *testing.T) {
   357  	t.Parallel()
   358  	res1 := NewCreatedResources()
   359  	res1.Add("k1", "v1")
   360  	res1.Add("k1", "v2")
   361  	res1.Add("k1", "v1")
   362  	res1.Add("k2", "v1")
   363  
   364  	expected := map[string][]string{
   365  		"k1": {"v1", "v2"},
   366  		"k2": {"v1"},
   367  	}
   368  	if !reflect.DeepEqual(expected, res1.Resources) {
   369  		t.Fatalf("1.  %#v != expected %#v", res1.Resources, expected)
   370  	}
   371  
   372  	// Make sure merging nil works
   373  	var res2 *CreatedResources
   374  	res1.Merge(res2)
   375  	if !reflect.DeepEqual(expected, res1.Resources) {
   376  		t.Fatalf("2.  %#v != expected %#v", res1.Resources, expected)
   377  	}
   378  
   379  	// Make sure a normal merge works
   380  	res2 = NewCreatedResources()
   381  	res2.Add("k1", "v3")
   382  	res2.Add("k2", "v1")
   383  	res2.Add("k3", "v3")
   384  	res1.Merge(res2)
   385  
   386  	expected = map[string][]string{
   387  		"k1": {"v1", "v2", "v3"},
   388  		"k2": {"v1"},
   389  		"k3": {"v3"},
   390  	}
   391  	if !reflect.DeepEqual(expected, res1.Resources) {
   392  		t.Fatalf("3.  %#v != expected %#v", res1.Resources, expected)
   393  	}
   394  }
   395  
   396  func TestCreatedResources_CopyRemove(t *testing.T) {
   397  	t.Parallel()
   398  	res1 := NewCreatedResources()
   399  	res1.Add("k1", "v1")
   400  	res1.Add("k1", "v2")
   401  	res1.Add("k1", "v3")
   402  	res1.Add("k2", "v1")
   403  
   404  	// Assert Copy creates a deep copy
   405  	res2 := res1.Copy()
   406  
   407  	if !reflect.DeepEqual(res1, res2) {
   408  		t.Fatalf("%#v != %#v", res1, res2)
   409  	}
   410  
   411  	// Assert removing v1 from k1 returns true and updates Resources slice
   412  	if removed := res2.Remove("k1", "v1"); !removed {
   413  		t.Fatalf("expected v1 to be removed: %#v", res2)
   414  	}
   415  
   416  	if expected := []string{"v2", "v3"}; !reflect.DeepEqual(expected, res2.Resources["k1"]) {
   417  		t.Fatalf("unexpected list for k1: %#v", res2.Resources["k1"])
   418  	}
   419  
   420  	// Assert removing the only value from a key removes the key
   421  	if removed := res2.Remove("k2", "v1"); !removed {
   422  		t.Fatalf("expected v1 to be removed from k2: %#v", res2.Resources)
   423  	}
   424  
   425  	if _, found := res2.Resources["k2"]; found {
   426  		t.Fatalf("k2 should have been removed from Resources: %#v", res2.Resources)
   427  	}
   428  
   429  	// Make sure res1 wasn't updated
   430  	if reflect.DeepEqual(res1, res2) {
   431  		t.Fatalf("res1 should not equal res2: #%v", res1)
   432  	}
   433  }