utils_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. package utils
  2. import (
  3. "bytes"
  4. "errors"
  5. "io"
  6. "io/ioutil"
  7. "strings"
  8. "testing"
  9. )
  10. func TestBufReader(t *testing.T) {
  11. reader, writer := io.Pipe()
  12. bufreader := NewBufReader(reader)
  13. // Write everything down to a Pipe
  14. // Usually, a pipe should block but because of the buffered reader,
  15. // the writes will go through
  16. done := make(chan bool)
  17. go func() {
  18. writer.Write([]byte("hello world"))
  19. writer.Close()
  20. done <- true
  21. }()
  22. // Drain the reader *after* everything has been written, just to verify
  23. // it is indeed buffering
  24. <-done
  25. output, err := ioutil.ReadAll(bufreader)
  26. if err != nil {
  27. t.Fatal(err)
  28. }
  29. if !bytes.Equal(output, []byte("hello world")) {
  30. t.Error(string(output))
  31. }
  32. }
  33. type dummyWriter struct {
  34. buffer bytes.Buffer
  35. failOnWrite bool
  36. }
  37. func (dw *dummyWriter) Write(p []byte) (n int, err error) {
  38. if dw.failOnWrite {
  39. return 0, errors.New("Fake fail")
  40. }
  41. return dw.buffer.Write(p)
  42. }
  43. func (dw *dummyWriter) String() string {
  44. return dw.buffer.String()
  45. }
  46. func (dw *dummyWriter) Close() error {
  47. return nil
  48. }
  49. func TestWriteBroadcaster(t *testing.T) {
  50. writer := NewWriteBroadcaster()
  51. // Test 1: Both bufferA and bufferB should contain "foo"
  52. bufferA := &dummyWriter{}
  53. writer.AddWriter(bufferA, "")
  54. bufferB := &dummyWriter{}
  55. writer.AddWriter(bufferB, "")
  56. writer.Write([]byte("foo"))
  57. if bufferA.String() != "foo" {
  58. t.Errorf("Buffer contains %v", bufferA.String())
  59. }
  60. if bufferB.String() != "foo" {
  61. t.Errorf("Buffer contains %v", bufferB.String())
  62. }
  63. // Test2: bufferA and bufferB should contain "foobar",
  64. // while bufferC should only contain "bar"
  65. bufferC := &dummyWriter{}
  66. writer.AddWriter(bufferC, "")
  67. writer.Write([]byte("bar"))
  68. if bufferA.String() != "foobar" {
  69. t.Errorf("Buffer contains %v", bufferA.String())
  70. }
  71. if bufferB.String() != "foobar" {
  72. t.Errorf("Buffer contains %v", bufferB.String())
  73. }
  74. if bufferC.String() != "bar" {
  75. t.Errorf("Buffer contains %v", bufferC.String())
  76. }
  77. // Test3: Test eviction on failure
  78. bufferA.failOnWrite = true
  79. writer.Write([]byte("fail"))
  80. if bufferA.String() != "foobar" {
  81. t.Errorf("Buffer contains %v", bufferA.String())
  82. }
  83. if bufferC.String() != "barfail" {
  84. t.Errorf("Buffer contains %v", bufferC.String())
  85. }
  86. // Even though we reset the flag, no more writes should go in there
  87. bufferA.failOnWrite = false
  88. writer.Write([]byte("test"))
  89. if bufferA.String() != "foobar" {
  90. t.Errorf("Buffer contains %v", bufferA.String())
  91. }
  92. if bufferC.String() != "barfailtest" {
  93. t.Errorf("Buffer contains %v", bufferC.String())
  94. }
  95. writer.CloseWriters()
  96. }
  97. type devNullCloser int
  98. func (d devNullCloser) Close() error {
  99. return nil
  100. }
  101. func (d devNullCloser) Write(buf []byte) (int, error) {
  102. return len(buf), nil
  103. }
  104. // This test checks for races. It is only useful when run with the race detector.
  105. func TestRaceWriteBroadcaster(t *testing.T) {
  106. writer := NewWriteBroadcaster()
  107. c := make(chan bool)
  108. go func() {
  109. writer.AddWriter(devNullCloser(0), "")
  110. c <- true
  111. }()
  112. writer.Write([]byte("hello"))
  113. <-c
  114. }
  115. // Test the behavior of TruncIndex, an index for querying IDs from a non-conflicting prefix.
  116. func TestTruncIndex(t *testing.T) {
  117. index := NewTruncIndex()
  118. // Get on an empty index
  119. if _, err := index.Get("foobar"); err == nil {
  120. t.Fatal("Get on an empty index should return an error")
  121. }
  122. // Spaces should be illegal in an id
  123. if err := index.Add("I have a space"); err == nil {
  124. t.Fatalf("Adding an id with ' ' should return an error")
  125. }
  126. id := "99b36c2c326ccc11e726eee6ee78a0baf166ef96"
  127. // Add an id
  128. if err := index.Add(id); err != nil {
  129. t.Fatal(err)
  130. }
  131. // Get a non-existing id
  132. assertIndexGet(t, index, "abracadabra", "", true)
  133. // Get the exact id
  134. assertIndexGet(t, index, id, id, false)
  135. // The first letter should match
  136. assertIndexGet(t, index, id[:1], id, false)
  137. // The first half should match
  138. assertIndexGet(t, index, id[:len(id)/2], id, false)
  139. // The second half should NOT match
  140. assertIndexGet(t, index, id[len(id)/2:], "", true)
  141. id2 := id[:6] + "blabla"
  142. // Add an id
  143. if err := index.Add(id2); err != nil {
  144. t.Fatal(err)
  145. }
  146. // Both exact IDs should work
  147. assertIndexGet(t, index, id, id, false)
  148. assertIndexGet(t, index, id2, id2, false)
  149. // 6 characters or less should conflict
  150. assertIndexGet(t, index, id[:6], "", true)
  151. assertIndexGet(t, index, id[:4], "", true)
  152. assertIndexGet(t, index, id[:1], "", true)
  153. // 7 characters should NOT conflict
  154. assertIndexGet(t, index, id[:7], id, false)
  155. assertIndexGet(t, index, id2[:7], id2, false)
  156. // Deleting a non-existing id should return an error
  157. if err := index.Delete("non-existing"); err == nil {
  158. t.Fatalf("Deleting a non-existing id should return an error")
  159. }
  160. // Deleting id2 should remove conflicts
  161. if err := index.Delete(id2); err != nil {
  162. t.Fatal(err)
  163. }
  164. // id2 should no longer work
  165. assertIndexGet(t, index, id2, "", true)
  166. assertIndexGet(t, index, id2[:7], "", true)
  167. assertIndexGet(t, index, id2[:11], "", true)
  168. // conflicts between id and id2 should be gone
  169. assertIndexGet(t, index, id[:6], id, false)
  170. assertIndexGet(t, index, id[:4], id, false)
  171. assertIndexGet(t, index, id[:1], id, false)
  172. // non-conflicting substrings should still not conflict
  173. assertIndexGet(t, index, id[:7], id, false)
  174. assertIndexGet(t, index, id[:15], id, false)
  175. assertIndexGet(t, index, id, id, false)
  176. }
  177. func assertIndexGet(t *testing.T, index *TruncIndex, input, expectedResult string, expectError bool) {
  178. if result, err := index.Get(input); err != nil && !expectError {
  179. t.Fatalf("Unexpected error getting '%s': %s", input, err)
  180. } else if err == nil && expectError {
  181. t.Fatalf("Getting '%s' should return an error", input)
  182. } else if result != expectedResult {
  183. t.Fatalf("Getting '%s' returned '%s' instead of '%s'", input, result, expectedResult)
  184. }
  185. }
  186. func assertKernelVersion(t *testing.T, a, b *KernelVersionInfo, result int) {
  187. if r := CompareKernelVersion(a, b); r != result {
  188. t.Fatalf("Unexpected kernel version comparison result. Found %d, expected %d", r, result)
  189. }
  190. }
  191. func TestCompareKernelVersion(t *testing.T) {
  192. assertKernelVersion(t,
  193. &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0},
  194. &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0},
  195. 0)
  196. assertKernelVersion(t,
  197. &KernelVersionInfo{Kernel: 2, Major: 6, Minor: 0},
  198. &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0},
  199. -1)
  200. assertKernelVersion(t,
  201. &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0},
  202. &KernelVersionInfo{Kernel: 2, Major: 6, Minor: 0},
  203. 1)
  204. assertKernelVersion(t,
  205. &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0},
  206. &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0},
  207. 0)
  208. assertKernelVersion(t,
  209. &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 5},
  210. &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0},
  211. 1)
  212. assertKernelVersion(t,
  213. &KernelVersionInfo{Kernel: 3, Major: 0, Minor: 20},
  214. &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0},
  215. -1)
  216. }
  217. func TestHumanSize(t *testing.T) {
  218. size := strings.Trim(HumanSize(1000), " \t")
  219. expect := "1 kB"
  220. if size != expect {
  221. t.Errorf("1000 -> expected '%s', got '%s'", expect, size)
  222. }
  223. size = strings.Trim(HumanSize(1024), " \t")
  224. expect = "1.024 kB"
  225. if size != expect {
  226. t.Errorf("1024 -> expected '%s', got '%s'", expect, size)
  227. }
  228. }
  229. func TestRAMInBytes(t *testing.T) {
  230. assertRAMInBytes(t, "32", false, 32)
  231. assertRAMInBytes(t, "32b", false, 32)
  232. assertRAMInBytes(t, "32B", false, 32)
  233. assertRAMInBytes(t, "32k", false, 32*1024)
  234. assertRAMInBytes(t, "32K", false, 32*1024)
  235. assertRAMInBytes(t, "32kb", false, 32*1024)
  236. assertRAMInBytes(t, "32Kb", false, 32*1024)
  237. assertRAMInBytes(t, "32Mb", false, 32*1024*1024)
  238. assertRAMInBytes(t, "32Gb", false, 32*1024*1024*1024)
  239. assertRAMInBytes(t, "", true, -1)
  240. assertRAMInBytes(t, "hello", true, -1)
  241. assertRAMInBytes(t, "-32", true, -1)
  242. assertRAMInBytes(t, " 32 ", true, -1)
  243. assertRAMInBytes(t, "32 mb", true, -1)
  244. assertRAMInBytes(t, "32m b", true, -1)
  245. assertRAMInBytes(t, "32bm", true, -1)
  246. }
  247. func assertRAMInBytes(t *testing.T, size string, expectError bool, expectedBytes int64) {
  248. actualBytes, err := RAMInBytes(size)
  249. if (err != nil) && !expectError {
  250. t.Errorf("Unexpected error parsing '%s': %s", size, err)
  251. }
  252. if (err == nil) && expectError {
  253. t.Errorf("Expected to get an error parsing '%s', but got none (bytes=%d)", size, actualBytes)
  254. }
  255. if actualBytes != expectedBytes {
  256. t.Errorf("Expected '%s' to parse as %d bytes, got %d", size, expectedBytes, actualBytes)
  257. }
  258. }
  259. func TestParseHost(t *testing.T) {
  260. var (
  261. defaultHttpHost = "127.0.0.1"
  262. defaultHttpPort = 4243
  263. defaultUnix = "/var/run/docker.sock"
  264. )
  265. if addr, err := ParseHost(defaultHttpHost, defaultHttpPort, defaultUnix, "0.0.0.0"); err != nil || addr != "tcp://0.0.0.0:4243" {
  266. t.Errorf("0.0.0.0 -> expected tcp://0.0.0.0:4243, got %s", addr)
  267. }
  268. if addr, err := ParseHost(defaultHttpHost, defaultHttpPort, defaultUnix, "0.0.0.1:5555"); err != nil || addr != "tcp://0.0.0.1:5555" {
  269. t.Errorf("0.0.0.1:5555 -> expected tcp://0.0.0.1:5555, got %s", addr)
  270. }
  271. if addr, err := ParseHost(defaultHttpHost, defaultHttpPort, defaultUnix, ":6666"); err != nil || addr != "tcp://127.0.0.1:6666" {
  272. t.Errorf(":6666 -> expected tcp://127.0.0.1:6666, got %s", addr)
  273. }
  274. if addr, err := ParseHost(defaultHttpHost, defaultHttpPort, defaultUnix, "tcp://:7777"); err != nil || addr != "tcp://127.0.0.1:7777" {
  275. t.Errorf("tcp://:7777 -> expected tcp://127.0.0.1:7777, got %s", addr)
  276. }
  277. if addr, err := ParseHost(defaultHttpHost, defaultHttpPort, defaultUnix, ""); err != nil || addr != "unix:///var/run/docker.sock" {
  278. t.Errorf("empty argument -> expected unix:///var/run/docker.sock, got %s", addr)
  279. }
  280. if addr, err := ParseHost(defaultHttpHost, defaultHttpPort, defaultUnix, "unix:///var/run/docker.sock"); err != nil || addr != "unix:///var/run/docker.sock" {
  281. t.Errorf("unix:///var/run/docker.sock -> expected unix:///var/run/docker.sock, got %s", addr)
  282. }
  283. if addr, err := ParseHost(defaultHttpHost, defaultHttpPort, defaultUnix, "unix://"); err != nil || addr != "unix:///var/run/docker.sock" {
  284. t.Errorf("unix:///var/run/docker.sock -> expected unix:///var/run/docker.sock, got %s", addr)
  285. }
  286. if addr, err := ParseHost(defaultHttpHost, defaultHttpPort, defaultUnix, "udp://127.0.0.1"); err == nil {
  287. t.Errorf("udp protocol address expected error return, but err == nil. Got %s", addr)
  288. }
  289. if addr, err := ParseHost(defaultHttpHost, defaultHttpPort, defaultUnix, "udp://127.0.0.1:4243"); err == nil {
  290. t.Errorf("udp protocol address expected error return, but err == nil. Got %s", addr)
  291. }
  292. }
  293. func TestParseRepositoryTag(t *testing.T) {
  294. if repo, tag := ParseRepositoryTag("root"); repo != "root" || tag != "" {
  295. t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "root", "", repo, tag)
  296. }
  297. if repo, tag := ParseRepositoryTag("root:tag"); repo != "root" || tag != "tag" {
  298. t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "root", "tag", repo, tag)
  299. }
  300. if repo, tag := ParseRepositoryTag("user/repo"); repo != "user/repo" || tag != "" {
  301. t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "user/repo", "", repo, tag)
  302. }
  303. if repo, tag := ParseRepositoryTag("user/repo:tag"); repo != "user/repo" || tag != "tag" {
  304. t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "user/repo", "tag", repo, tag)
  305. }
  306. if repo, tag := ParseRepositoryTag("url:5000/repo"); repo != "url:5000/repo" || tag != "" {
  307. t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "url:5000/repo", "", repo, tag)
  308. }
  309. if repo, tag := ParseRepositoryTag("url:5000/repo:tag"); repo != "url:5000/repo" || tag != "tag" {
  310. t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "url:5000/repo", "tag", repo, tag)
  311. }
  312. }
  313. func TestGetResolvConf(t *testing.T) {
  314. resolvConfUtils, err := GetResolvConf()
  315. if err != nil {
  316. t.Fatal(err)
  317. }
  318. resolvConfSystem, err := ioutil.ReadFile("/etc/resolv.conf")
  319. if err != nil {
  320. t.Fatal(err)
  321. }
  322. if string(resolvConfUtils) != string(resolvConfSystem) {
  323. t.Fatalf("/etc/resolv.conf and GetResolvConf have different content.")
  324. }
  325. }
  326. func TestCheckLocalDns(t *testing.T) {
  327. for resolv, result := range map[string]bool{`# Dynamic
  328. nameserver 10.0.2.3
  329. search dotcloud.net`: false,
  330. `# Dynamic
  331. #nameserver 127.0.0.1
  332. nameserver 10.0.2.3
  333. search dotcloud.net`: false,
  334. `# Dynamic
  335. nameserver 10.0.2.3 #not used 127.0.1.1
  336. search dotcloud.net`: false,
  337. `# Dynamic
  338. #nameserver 10.0.2.3
  339. #search dotcloud.net`: true,
  340. `# Dynamic
  341. nameserver 127.0.0.1
  342. search dotcloud.net`: true,
  343. `# Dynamic
  344. nameserver 127.0.1.1
  345. search dotcloud.net`: true,
  346. `# Dynamic
  347. `: true,
  348. ``: true,
  349. } {
  350. if CheckLocalDns([]byte(resolv)) != result {
  351. t.Fatalf("Wrong local dns detection: {%s} should be %v", resolv, result)
  352. }
  353. }
  354. }
  355. func assertParseRelease(t *testing.T, release string, b *KernelVersionInfo, result int) {
  356. var (
  357. a *KernelVersionInfo
  358. )
  359. a, _ = ParseRelease(release)
  360. if r := CompareKernelVersion(a, b); r != result {
  361. t.Fatalf("Unexpected kernel version comparison result. Found %d, expected %d", r, result)
  362. }
  363. }
  364. func TestParseRelease(t *testing.T) {
  365. assertParseRelease(t, "3.8.0", &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, 0)
  366. assertParseRelease(t, "3.4.54.longterm-1", &KernelVersionInfo{Kernel: 3, Major: 4, Minor: 54}, 0)
  367. assertParseRelease(t, "3.4.54.longterm-1", &KernelVersionInfo{Kernel: 3, Major: 4, Minor: 54}, 0)
  368. assertParseRelease(t, "3.8.0-19-generic", &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, 0)
  369. assertParseRelease(t, "3.12.8tag", &KernelVersionInfo{Kernel: 3, Major: 12, Minor: 8}, 0)
  370. }
  371. func TestParsePortMapping(t *testing.T) {
  372. data, err := PartParser("ip:public:private", "192.168.1.1:80:8080")
  373. if err != nil {
  374. t.Fatal(err)
  375. }
  376. if len(data) != 3 {
  377. t.FailNow()
  378. }
  379. if data["ip"] != "192.168.1.1" {
  380. t.Fail()
  381. }
  382. if data["public"] != "80" {
  383. t.Fail()
  384. }
  385. if data["private"] != "8080" {
  386. t.Fail()
  387. }
  388. }
  389. func TestGetNameserversAsCIDR(t *testing.T) {
  390. for resolv, result := range map[string][]string{`
  391. nameserver 1.2.3.4
  392. nameserver 40.3.200.10
  393. search example.com`: {"1.2.3.4/32", "40.3.200.10/32"},
  394. `search example.com`: {},
  395. `nameserver 1.2.3.4
  396. search example.com
  397. nameserver 4.30.20.100`: {"1.2.3.4/32", "4.30.20.100/32"},
  398. ``: {},
  399. ` nameserver 1.2.3.4 `: {"1.2.3.4/32"},
  400. `search example.com
  401. nameserver 1.2.3.4
  402. #nameserver 4.3.2.1`: {"1.2.3.4/32"},
  403. `search example.com
  404. nameserver 1.2.3.4 # not 4.3.2.1`: {"1.2.3.4/32"},
  405. } {
  406. test := GetNameserversAsCIDR([]byte(resolv))
  407. if !StrSlicesEqual(test, result) {
  408. t.Fatalf("Wrong nameserver string {%s} should be %v. Input: %s", test, result, resolv)
  409. }
  410. }
  411. }
  412. func StrSlicesEqual(a, b []string) bool {
  413. if len(a) != len(b) {
  414. return false
  415. }
  416. for i, v := range a {
  417. if v != b[i] {
  418. return false
  419. }
  420. }
  421. return true
  422. }