A lightweight mechanism to provide an *instant kickstart* to a Go web server instance upon changing any Go source files under the project directory (and its subdirectories).

syscall_unix_test.go 8.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. // Copyright 2013 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // +build darwin dragonfly freebsd linux netbsd openbsd solaris
  5. package unix_test
  6. import (
  7. "flag"
  8. "fmt"
  9. "io/ioutil"
  10. "net"
  11. "os"
  12. "os/exec"
  13. "path/filepath"
  14. "runtime"
  15. "testing"
  16. "time"
  17. "golang.org/x/sys/unix"
  18. )
  19. // Tests that below functions, structures and constants are consistent
  20. // on all Unix-like systems.
  21. func _() {
  22. // program scheduling priority functions and constants
  23. var (
  24. _ func(int, int, int) error = unix.Setpriority
  25. _ func(int, int) (int, error) = unix.Getpriority
  26. )
  27. const (
  28. _ int = unix.PRIO_USER
  29. _ int = unix.PRIO_PROCESS
  30. _ int = unix.PRIO_PGRP
  31. )
  32. // termios constants
  33. const (
  34. _ int = unix.TCIFLUSH
  35. _ int = unix.TCIOFLUSH
  36. _ int = unix.TCOFLUSH
  37. )
  38. // fcntl file locking structure and constants
  39. var (
  40. _ = unix.Flock_t{
  41. Type: int16(0),
  42. Whence: int16(0),
  43. Start: int64(0),
  44. Len: int64(0),
  45. Pid: int32(0),
  46. }
  47. )
  48. const (
  49. _ = unix.F_GETLK
  50. _ = unix.F_SETLK
  51. _ = unix.F_SETLKW
  52. )
  53. }
  54. // TestFcntlFlock tests whether the file locking structure matches
  55. // the calling convention of each kernel.
  56. func TestFcntlFlock(t *testing.T) {
  57. name := filepath.Join(os.TempDir(), "TestFcntlFlock")
  58. fd, err := unix.Open(name, unix.O_CREAT|unix.O_RDWR|unix.O_CLOEXEC, 0)
  59. if err != nil {
  60. t.Fatalf("Open failed: %v", err)
  61. }
  62. defer unix.Unlink(name)
  63. defer unix.Close(fd)
  64. flock := unix.Flock_t{
  65. Type: unix.F_RDLCK,
  66. Start: 0, Len: 0, Whence: 1,
  67. }
  68. if err := unix.FcntlFlock(uintptr(fd), unix.F_GETLK, &flock); err != nil {
  69. t.Fatalf("FcntlFlock failed: %v", err)
  70. }
  71. }
  72. // TestPassFD tests passing a file descriptor over a Unix socket.
  73. //
  74. // This test involved both a parent and child process. The parent
  75. // process is invoked as a normal test, with "go test", which then
  76. // runs the child process by running the current test binary with args
  77. // "-test.run=^TestPassFD$" and an environment variable used to signal
  78. // that the test should become the child process instead.
  79. func TestPassFD(t *testing.T) {
  80. if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" {
  81. passFDChild()
  82. return
  83. }
  84. tempDir, err := ioutil.TempDir("", "TestPassFD")
  85. if err != nil {
  86. t.Fatal(err)
  87. }
  88. defer os.RemoveAll(tempDir)
  89. fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_STREAM, 0)
  90. if err != nil {
  91. t.Fatalf("Socketpair: %v", err)
  92. }
  93. defer unix.Close(fds[0])
  94. defer unix.Close(fds[1])
  95. writeFile := os.NewFile(uintptr(fds[0]), "child-writes")
  96. readFile := os.NewFile(uintptr(fds[1]), "parent-reads")
  97. defer writeFile.Close()
  98. defer readFile.Close()
  99. cmd := exec.Command(os.Args[0], "-test.run=^TestPassFD$", "--", tempDir)
  100. cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"}
  101. if lp := os.Getenv("LD_LIBRARY_PATH"); lp != "" {
  102. cmd.Env = append(cmd.Env, "LD_LIBRARY_PATH="+lp)
  103. }
  104. cmd.ExtraFiles = []*os.File{writeFile}
  105. out, err := cmd.CombinedOutput()
  106. if len(out) > 0 || err != nil {
  107. t.Fatalf("child process: %q, %v", out, err)
  108. }
  109. c, err := net.FileConn(readFile)
  110. if err != nil {
  111. t.Fatalf("FileConn: %v", err)
  112. }
  113. defer c.Close()
  114. uc, ok := c.(*net.UnixConn)
  115. if !ok {
  116. t.Fatalf("unexpected FileConn type; expected UnixConn, got %T", c)
  117. }
  118. buf := make([]byte, 32) // expect 1 byte
  119. oob := make([]byte, 32) // expect 24 bytes
  120. closeUnix := time.AfterFunc(5*time.Second, func() {
  121. t.Logf("timeout reading from unix socket")
  122. uc.Close()
  123. })
  124. _, oobn, _, _, err := uc.ReadMsgUnix(buf, oob)
  125. closeUnix.Stop()
  126. scms, err := unix.ParseSocketControlMessage(oob[:oobn])
  127. if err != nil {
  128. t.Fatalf("ParseSocketControlMessage: %v", err)
  129. }
  130. if len(scms) != 1 {
  131. t.Fatalf("expected 1 SocketControlMessage; got scms = %#v", scms)
  132. }
  133. scm := scms[0]
  134. gotFds, err := unix.ParseUnixRights(&scm)
  135. if err != nil {
  136. t.Fatalf("unix.ParseUnixRights: %v", err)
  137. }
  138. if len(gotFds) != 1 {
  139. t.Fatalf("wanted 1 fd; got %#v", gotFds)
  140. }
  141. f := os.NewFile(uintptr(gotFds[0]), "fd-from-child")
  142. defer f.Close()
  143. got, err := ioutil.ReadAll(f)
  144. want := "Hello from child process!\n"
  145. if string(got) != want {
  146. t.Errorf("child process ReadAll: %q, %v; want %q", got, err, want)
  147. }
  148. }
  149. // passFDChild is the child process used by TestPassFD.
  150. func passFDChild() {
  151. defer os.Exit(0)
  152. // Look for our fd. It should be fd 3, but we work around an fd leak
  153. // bug here (http://golang.org/issue/2603) to let it be elsewhere.
  154. var uc *net.UnixConn
  155. for fd := uintptr(3); fd <= 10; fd++ {
  156. f := os.NewFile(fd, "unix-conn")
  157. var ok bool
  158. netc, _ := net.FileConn(f)
  159. uc, ok = netc.(*net.UnixConn)
  160. if ok {
  161. break
  162. }
  163. }
  164. if uc == nil {
  165. fmt.Println("failed to find unix fd")
  166. return
  167. }
  168. // Make a file f to send to our parent process on uc.
  169. // We make it in tempDir, which our parent will clean up.
  170. flag.Parse()
  171. tempDir := flag.Arg(0)
  172. f, err := ioutil.TempFile(tempDir, "")
  173. if err != nil {
  174. fmt.Printf("TempFile: %v", err)
  175. return
  176. }
  177. f.Write([]byte("Hello from child process!\n"))
  178. f.Seek(0, 0)
  179. rights := unix.UnixRights(int(f.Fd()))
  180. dummyByte := []byte("x")
  181. n, oobn, err := uc.WriteMsgUnix(dummyByte, rights, nil)
  182. if err != nil {
  183. fmt.Printf("WriteMsgUnix: %v", err)
  184. return
  185. }
  186. if n != 1 || oobn != len(rights) {
  187. fmt.Printf("WriteMsgUnix = %d, %d; want 1, %d", n, oobn, len(rights))
  188. return
  189. }
  190. }
  191. // TestUnixRightsRoundtrip tests that UnixRights, ParseSocketControlMessage,
  192. // and ParseUnixRights are able to successfully round-trip lists of file descriptors.
  193. func TestUnixRightsRoundtrip(t *testing.T) {
  194. testCases := [...][][]int{
  195. {{42}},
  196. {{1, 2}},
  197. {{3, 4, 5}},
  198. {{}},
  199. {{1, 2}, {3, 4, 5}, {}, {7}},
  200. }
  201. for _, testCase := range testCases {
  202. b := []byte{}
  203. var n int
  204. for _, fds := range testCase {
  205. // Last assignment to n wins
  206. n = len(b) + unix.CmsgLen(4*len(fds))
  207. b = append(b, unix.UnixRights(fds...)...)
  208. }
  209. // Truncate b
  210. b = b[:n]
  211. scms, err := unix.ParseSocketControlMessage(b)
  212. if err != nil {
  213. t.Fatalf("ParseSocketControlMessage: %v", err)
  214. }
  215. if len(scms) != len(testCase) {
  216. t.Fatalf("expected %v SocketControlMessage; got scms = %#v", len(testCase), scms)
  217. }
  218. for i, scm := range scms {
  219. gotFds, err := unix.ParseUnixRights(&scm)
  220. if err != nil {
  221. t.Fatalf("ParseUnixRights: %v", err)
  222. }
  223. wantFds := testCase[i]
  224. if len(gotFds) != len(wantFds) {
  225. t.Fatalf("expected %v fds, got %#v", len(wantFds), gotFds)
  226. }
  227. for j, fd := range gotFds {
  228. if fd != wantFds[j] {
  229. t.Fatalf("expected fd %v, got %v", wantFds[j], fd)
  230. }
  231. }
  232. }
  233. }
  234. }
  235. func TestRlimit(t *testing.T) {
  236. var rlimit, zero unix.Rlimit
  237. err := unix.Getrlimit(unix.RLIMIT_NOFILE, &rlimit)
  238. if err != nil {
  239. t.Fatalf("Getrlimit: save failed: %v", err)
  240. }
  241. if zero == rlimit {
  242. t.Fatalf("Getrlimit: save failed: got zero value %#v", rlimit)
  243. }
  244. set := rlimit
  245. set.Cur = set.Max - 1
  246. err = unix.Setrlimit(unix.RLIMIT_NOFILE, &set)
  247. if err != nil {
  248. t.Fatalf("Setrlimit: set failed: %#v %v", set, err)
  249. }
  250. var get unix.Rlimit
  251. err = unix.Getrlimit(unix.RLIMIT_NOFILE, &get)
  252. if err != nil {
  253. t.Fatalf("Getrlimit: get failed: %v", err)
  254. }
  255. set = rlimit
  256. set.Cur = set.Max - 1
  257. if set != get {
  258. // Seems like Darwin requires some privilege to
  259. // increase the soft limit of rlimit sandbox, though
  260. // Setrlimit never reports an error.
  261. switch runtime.GOOS {
  262. case "darwin":
  263. default:
  264. t.Fatalf("Rlimit: change failed: wanted %#v got %#v", set, get)
  265. }
  266. }
  267. err = unix.Setrlimit(unix.RLIMIT_NOFILE, &rlimit)
  268. if err != nil {
  269. t.Fatalf("Setrlimit: restore failed: %#v %v", rlimit, err)
  270. }
  271. }
  272. func TestSeekFailure(t *testing.T) {
  273. _, err := unix.Seek(-1, 0, 0)
  274. if err == nil {
  275. t.Fatalf("Seek(-1, 0, 0) did not fail")
  276. }
  277. str := err.Error() // used to crash on Linux
  278. t.Logf("Seek: %v", str)
  279. if str == "" {
  280. t.Fatalf("Seek(-1, 0, 0) return error with empty message")
  281. }
  282. }
  283. func TestDup(t *testing.T) {
  284. file, err := ioutil.TempFile("", "TestDup")
  285. if err != nil {
  286. t.Fatalf("Tempfile failed: %v", err)
  287. }
  288. defer os.Remove(file.Name())
  289. defer file.Close()
  290. f := int(file.Fd())
  291. newFd, err := unix.Dup(f)
  292. if err != nil {
  293. t.Fatalf("Dup: %v", err)
  294. }
  295. err = unix.Dup2(newFd, newFd+1)
  296. if err != nil {
  297. t.Fatalf("Dup2: %v", err)
  298. }
  299. b1 := []byte("Test123")
  300. b2 := make([]byte, 7)
  301. _, err = unix.Write(newFd+1, b1)
  302. if err != nil {
  303. t.Fatalf("Write to dup2 fd failed: %v", err)
  304. }
  305. _, err = unix.Seek(f, 0, 0)
  306. _, err = unix.Read(f, b2)
  307. if err != nil {
  308. t.Fatalf("Read back failed: %v", err)
  309. }
  310. if string(b1) != string(b2) {
  311. t.Errorf("Dup: stdout write not in file, expected %v, got %v", string(b1), string(b2))
  312. }
  313. }