github.com/zoomfoo/nomad@v0.8.5-0.20180907175415-f28fd3a1a056/client/allocdir/task_dir_linux_test.go (about)

     1  package allocdir
     2  
     3  import (
     4  	"io/ioutil"
     5  	"os"
     6  	"path/filepath"
     7  	"testing"
     8  
     9  	"github.com/hashicorp/nomad/helper/testlog"
    10  	"golang.org/x/sys/unix"
    11  )
    12  
    13  // TestLinuxSpecialDirs ensures mounting /dev and /proc works.
    14  func TestLinuxSpecialDirs(t *testing.T) {
    15  	if unix.Geteuid() != 0 {
    16  		t.Skip("Must be run as root")
    17  	}
    18  
    19  	allocDir, err := ioutil.TempDir("", "nomadtest-specialdirs")
    20  	if err != nil {
    21  		t.Fatalf("unable to create tempdir for test: %v", err)
    22  	}
    23  	defer os.RemoveAll(allocDir)
    24  
    25  	td := newTaskDir(testlog.Logger(t), allocDir, "test")
    26  
    27  	// Despite the task dir not existing, unmountSpecialDirs should *not*
    28  	// return an error
    29  	if err := td.unmountSpecialDirs(); err != nil {
    30  		t.Fatalf("error removing nonexistent special dirs: %v", err)
    31  	}
    32  
    33  	// Mounting special dirs in a nonexistent task dir *should* return an
    34  	// error
    35  	if err := td.mountSpecialDirs(); err == nil {
    36  		t.Fatalf("expected mounting in a nonexistent task dir %q to fail", td.Dir)
    37  	}
    38  
    39  	// Create the task dir like TaskDir.Build would
    40  	if err := os.MkdirAll(td.Dir, 0777); err != nil {
    41  		t.Fatalf("error creating task dir %q: %v", td.Dir, err)
    42  	}
    43  
    44  	// Mounting special dirs should now work and contain files
    45  	if err := td.mountSpecialDirs(); err != nil {
    46  		t.Fatalf("error mounting special dirs in %q: %v", td.Dir, err)
    47  	}
    48  	if empty, err := pathEmpty(filepath.Join(td.Dir, "dev")); empty || err != nil {
    49  		t.Fatalf("expected dev to be populated but found: empty=%v error=%v", empty, err)
    50  	}
    51  	if empty, err := pathEmpty(filepath.Join(td.Dir, "proc")); empty || err != nil {
    52  		t.Fatalf("expected proc to be populated but found: empty=%v error=%v", empty, err)
    53  	}
    54  
    55  	// Remounting again should be fine
    56  	if err := td.mountSpecialDirs(); err != nil {
    57  		t.Fatalf("error remounting special dirs in %q: %v", td.Dir, err)
    58  	}
    59  
    60  	// Now unmount
    61  	if err := td.unmountSpecialDirs(); err != nil {
    62  		t.Fatalf("error unmounting special dirs in %q: %v", td.Dir, err)
    63  	}
    64  	if pathExists(filepath.Join(td.Dir, "dev")) {
    65  		t.Fatalf("dev was not removed from %q", td.Dir)
    66  	}
    67  	if pathExists(filepath.Join(td.Dir, "proc")) {
    68  		t.Fatalf("proc was not removed from %q", td.Dir)
    69  	}
    70  	if err := td.unmountSpecialDirs(); err != nil {
    71  		t.Fatalf("error re-unmounting special dirs in %q: %v", td.Dir, err)
    72  	}
    73  }