docker_test.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package dockertools
  14. import (
  15. "encoding/json"
  16. "fmt"
  17. "hash/adler32"
  18. "math/rand"
  19. "path"
  20. "reflect"
  21. "sort"
  22. "strconv"
  23. "strings"
  24. "testing"
  25. "github.com/docker/docker/pkg/jsonmessage"
  26. dockertypes "github.com/docker/engine-api/types"
  27. dockernat "github.com/docker/go-connections/nat"
  28. cadvisorapi "github.com/google/cadvisor/info/v1"
  29. "github.com/stretchr/testify/assert"
  30. "k8s.io/kubernetes/pkg/api"
  31. "k8s.io/kubernetes/pkg/apis/componentconfig"
  32. "k8s.io/kubernetes/pkg/client/record"
  33. "k8s.io/kubernetes/pkg/credentialprovider"
  34. kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
  35. containertest "k8s.io/kubernetes/pkg/kubelet/container/testing"
  36. "k8s.io/kubernetes/pkg/kubelet/images"
  37. "k8s.io/kubernetes/pkg/kubelet/network"
  38. nettest "k8s.io/kubernetes/pkg/kubelet/network/testing"
  39. "k8s.io/kubernetes/pkg/types"
  40. hashutil "k8s.io/kubernetes/pkg/util/hash"
  41. )
  42. func verifyCalls(t *testing.T, fakeDocker *FakeDockerClient, calls []string) {
  43. assert.New(t).NoError(fakeDocker.AssertCalls(calls))
  44. }
  45. func verifyStringArrayEquals(t *testing.T, actual, expected []string) {
  46. invalid := len(actual) != len(expected)
  47. if !invalid {
  48. for ix, value := range actual {
  49. if expected[ix] != value {
  50. invalid = true
  51. }
  52. }
  53. }
  54. if invalid {
  55. t.Errorf("Expected: %#v, Actual: %#v", expected, actual)
  56. }
  57. }
  58. func findPodContainer(dockerContainers []*dockertypes.Container, podFullName string, uid types.UID, containerName string) (*dockertypes.Container, bool, uint64) {
  59. for _, dockerContainer := range dockerContainers {
  60. if len(dockerContainer.Names) == 0 {
  61. continue
  62. }
  63. dockerName, hash, err := ParseDockerName(dockerContainer.Names[0])
  64. if err != nil {
  65. continue
  66. }
  67. if dockerName.PodFullName == podFullName &&
  68. (uid == "" || dockerName.PodUID == uid) &&
  69. dockerName.ContainerName == containerName {
  70. return dockerContainer, true, hash
  71. }
  72. }
  73. return nil, false, 0
  74. }
  75. func TestGetContainerID(t *testing.T) {
  76. fakeDocker := NewFakeDockerClient()
  77. fakeDocker.SetFakeRunningContainers([]*FakeContainer{
  78. {
  79. ID: "foobar",
  80. Name: "/k8s_foo_qux_ns_1234_42",
  81. },
  82. {
  83. ID: "barbar",
  84. Name: "/k8s_bar_qux_ns_2565_42",
  85. },
  86. })
  87. dockerContainers, err := GetKubeletDockerContainers(fakeDocker, false)
  88. if err != nil {
  89. t.Errorf("Expected no error, Got %#v", err)
  90. }
  91. if len(dockerContainers) != 2 {
  92. t.Errorf("Expected %#v, Got %#v", fakeDocker.RunningContainerList, dockerContainers)
  93. }
  94. verifyCalls(t, fakeDocker, []string{"list"})
  95. dockerContainer, found, _ := findPodContainer(dockerContainers, "qux_ns", "", "foo")
  96. if dockerContainer == nil || !found {
  97. t.Errorf("Failed to find container %#v", dockerContainer)
  98. }
  99. fakeDocker.ClearCalls()
  100. dockerContainer, found, _ = findPodContainer(dockerContainers, "foobar", "", "foo")
  101. verifyCalls(t, fakeDocker, []string{})
  102. if dockerContainer != nil || found {
  103. t.Errorf("Should not have found container %#v", dockerContainer)
  104. }
  105. }
  106. func verifyPackUnpack(t *testing.T, podNamespace, podUID, podName, containerName string) {
  107. container := &api.Container{Name: containerName}
  108. hasher := adler32.New()
  109. hashutil.DeepHashObject(hasher, *container)
  110. computedHash := uint64(hasher.Sum32())
  111. podFullName := fmt.Sprintf("%s_%s", podName, podNamespace)
  112. _, name, _ := BuildDockerName(KubeletContainerName{podFullName, types.UID(podUID), container.Name}, container)
  113. returned, hash, err := ParseDockerName(name)
  114. if err != nil {
  115. t.Errorf("Failed to parse Docker container name %q: %v", name, err)
  116. }
  117. if podFullName != returned.PodFullName || podUID != string(returned.PodUID) || containerName != returned.ContainerName || computedHash != hash {
  118. t.Errorf("For (%s, %s, %s, %d), unpacked (%s, %s, %s, %d)", podFullName, podUID, containerName, computedHash, returned.PodFullName, returned.PodUID, returned.ContainerName, hash)
  119. }
  120. }
  121. func TestContainerNaming(t *testing.T) {
  122. podUID := "12345678"
  123. verifyPackUnpack(t, "file", podUID, "name", "container")
  124. verifyPackUnpack(t, "file", podUID, "name-with-dashes", "container")
  125. // UID is same as pod name
  126. verifyPackUnpack(t, "file", podUID, podUID, "container")
  127. // No Container name
  128. verifyPackUnpack(t, "other", podUID, "name", "")
  129. container := &api.Container{Name: "container"}
  130. podName := "foo"
  131. podNamespace := "test"
  132. name := fmt.Sprintf("k8s_%s_%s_%s_%s_42", container.Name, podName, podNamespace, podUID)
  133. podFullName := fmt.Sprintf("%s_%s", podName, podNamespace)
  134. returned, hash, err := ParseDockerName(name)
  135. if err != nil {
  136. t.Errorf("Failed to parse Docker container name %q: %v", name, err)
  137. }
  138. if returned.PodFullName != podFullName || string(returned.PodUID) != podUID || returned.ContainerName != container.Name || hash != 0 {
  139. t.Errorf("unexpected parse: %s %s %s %d", returned.PodFullName, returned.PodUID, returned.ContainerName, hash)
  140. }
  141. }
  142. func TestMatchImageTagOrSHA(t *testing.T) {
  143. for _, testCase := range []struct {
  144. Inspected dockertypes.ImageInspect
  145. Image string
  146. Output bool
  147. }{
  148. {
  149. Inspected: dockertypes.ImageInspect{RepoTags: []string{"ubuntu:latest"}},
  150. Image: "ubuntu",
  151. Output: true,
  152. },
  153. {
  154. Inspected: dockertypes.ImageInspect{RepoTags: []string{"ubuntu:14.04"}},
  155. Image: "ubuntu:latest",
  156. Output: false,
  157. },
  158. {
  159. Inspected: dockertypes.ImageInspect{RepoTags: []string{"colemickens/hyperkube-amd64:217.9beff63"}},
  160. Image: "colemickens/hyperkube-amd64:217.9beff63",
  161. Output: true,
  162. },
  163. {
  164. Inspected: dockertypes.ImageInspect{RepoTags: []string{"colemickens/hyperkube-amd64:217.9beff63"}},
  165. Image: "docker.io/colemickens/hyperkube-amd64:217.9beff63",
  166. Output: true,
  167. },
  168. {
  169. Inspected: dockertypes.ImageInspect{RepoTags: []string{"docker.io/kubernetes/pause:latest"}},
  170. Image: "kubernetes/pause:latest",
  171. Output: true,
  172. },
  173. {
  174. Inspected: dockertypes.ImageInspect{
  175. ID: "sha256:2208f7a29005d226d1ee33a63e33af1f47af6156c740d7d23c7948e8d282d53d",
  176. },
  177. Image: "myimage@sha256:2208f7a29005d226d1ee33a63e33af1f47af6156c740d7d23c7948e8d282d53d",
  178. Output: true,
  179. },
  180. {
  181. Inspected: dockertypes.ImageInspect{
  182. ID: "sha256:2208f7a29005d226d1ee33a63e33af1f47af6156c740d7d23c7948e8d282d53d",
  183. },
  184. Image: "myimage@sha256:2208f7a29005",
  185. Output: false,
  186. },
  187. {
  188. Inspected: dockertypes.ImageInspect{
  189. ID: "sha256:2208f7a29005d226d1ee33a63e33af1f47af6156c740d7d23c7948e8d282d53d",
  190. },
  191. Image: "myimage@sha256:2208",
  192. Output: false,
  193. },
  194. } {
  195. match := matchImageTagOrSHA(testCase.Inspected, testCase.Image)
  196. assert.Equal(t, testCase.Output, match, testCase.Image+" is not a match")
  197. }
  198. }
  199. func TestApplyDefaultImageTag(t *testing.T) {
  200. for _, testCase := range []struct {
  201. Input string
  202. Output string
  203. }{
  204. {Input: "root", Output: "root:latest"},
  205. {Input: "root:tag", Output: "root:tag"},
  206. {Input: "root@sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", Output: "root@sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"},
  207. } {
  208. image, err := applyDefaultImageTag(testCase.Input)
  209. if err != nil {
  210. t.Errorf("applyDefaultTag(%s) failed: %v", testCase.Input, err)
  211. } else if image != testCase.Output {
  212. t.Errorf("Expected image reference: %q, got %q", testCase.Output, image)
  213. }
  214. }
  215. }
  216. func TestPullWithNoSecrets(t *testing.T) {
  217. tests := []struct {
  218. imageName string
  219. expectedImage string
  220. }{
  221. {"ubuntu", "ubuntu:latest using {}"},
  222. {"ubuntu:2342", "ubuntu:2342 using {}"},
  223. {"ubuntu:latest", "ubuntu:latest using {}"},
  224. {"foo/bar:445566", "foo/bar:445566 using {}"},
  225. {"registry.example.com:5000/foobar", "registry.example.com:5000/foobar:latest using {}"},
  226. {"registry.example.com:5000/foobar:5342", "registry.example.com:5000/foobar:5342 using {}"},
  227. {"registry.example.com:5000/foobar:latest", "registry.example.com:5000/foobar:latest using {}"},
  228. }
  229. for _, test := range tests {
  230. fakeKeyring := &credentialprovider.FakeKeyring{}
  231. fakeClient := NewFakeDockerClient()
  232. dp := dockerPuller{
  233. client: fakeClient,
  234. keyring: fakeKeyring,
  235. }
  236. err := dp.Pull(test.imageName, []api.Secret{})
  237. if err != nil {
  238. t.Errorf("unexpected non-nil err: %s", err)
  239. continue
  240. }
  241. if e, a := 1, len(fakeClient.pulled); e != a {
  242. t.Errorf("%s: expected 1 pulled image, got %d: %v", test.imageName, a, fakeClient.pulled)
  243. continue
  244. }
  245. if e, a := test.expectedImage, fakeClient.pulled[0]; e != a {
  246. t.Errorf("%s: expected pull of %q, but got %q", test.imageName, e, a)
  247. }
  248. }
  249. }
  250. func TestPullWithJSONError(t *testing.T) {
  251. tests := map[string]struct {
  252. imageName string
  253. err error
  254. expectedError string
  255. }{
  256. "Json error": {
  257. "ubuntu",
  258. &jsonmessage.JSONError{Code: 50, Message: "Json error"},
  259. "Json error",
  260. },
  261. "Bad gateway": {
  262. "ubuntu",
  263. &jsonmessage.JSONError{Code: 502, Message: "<!doctype html>\n<html class=\"no-js\" lang=\"\">\n <head>\n </head>\n <body>\n <h1>Oops, there was an error!</h1>\n <p>We have been contacted of this error, feel free to check out <a href=\"http://status.docker.com/\">status.docker.com</a>\n to see if there is a bigger issue.</p>\n\n </body>\n</html>"},
  264. images.RegistryUnavailable.Error(),
  265. },
  266. }
  267. for i, test := range tests {
  268. fakeKeyring := &credentialprovider.FakeKeyring{}
  269. fakeClient := NewFakeDockerClient()
  270. fakeClient.InjectError("pull", test.err)
  271. puller := &dockerPuller{
  272. client: fakeClient,
  273. keyring: fakeKeyring,
  274. }
  275. err := puller.Pull(test.imageName, []api.Secret{})
  276. if err == nil || !strings.Contains(err.Error(), test.expectedError) {
  277. t.Errorf("%s: expect error %s, got : %s", i, test.expectedError, err)
  278. continue
  279. }
  280. }
  281. }
  282. func TestPullWithSecrets(t *testing.T) {
  283. // auth value is equivalent to: "username":"passed-user","password":"passed-password"
  284. dockerCfg := map[string]map[string]string{"index.docker.io/v1/": {"email": "passed-email", "auth": "cGFzc2VkLXVzZXI6cGFzc2VkLXBhc3N3b3Jk"}}
  285. dockercfgContent, err := json.Marshal(dockerCfg)
  286. if err != nil {
  287. t.Errorf("unexpected error: %v", err)
  288. }
  289. dockerConfigJson := map[string]map[string]map[string]string{"auths": dockerCfg}
  290. dockerConfigJsonContent, err := json.Marshal(dockerConfigJson)
  291. if err != nil {
  292. t.Errorf("unexpected error: %v", err)
  293. }
  294. tests := map[string]struct {
  295. imageName string
  296. passedSecrets []api.Secret
  297. builtInDockerConfig credentialprovider.DockerConfig
  298. expectedPulls []string
  299. }{
  300. "no matching secrets": {
  301. "ubuntu",
  302. []api.Secret{},
  303. credentialprovider.DockerConfig(map[string]credentialprovider.DockerConfigEntry{}),
  304. []string{"ubuntu:latest using {}"},
  305. },
  306. "default keyring secrets": {
  307. "ubuntu",
  308. []api.Secret{},
  309. credentialprovider.DockerConfig(map[string]credentialprovider.DockerConfigEntry{
  310. "index.docker.io/v1/": {Username: "built-in", Password: "password", Email: "email", Provider: nil},
  311. }),
  312. []string{`ubuntu:latest using {"username":"built-in","password":"password","email":"email"}`},
  313. },
  314. "default keyring secrets unused": {
  315. "ubuntu",
  316. []api.Secret{},
  317. credentialprovider.DockerConfig(map[string]credentialprovider.DockerConfigEntry{
  318. "extraneous": {Username: "built-in", Password: "password", Email: "email", Provider: nil},
  319. }),
  320. []string{`ubuntu:latest using {}`},
  321. },
  322. "builtin keyring secrets, but use passed": {
  323. "ubuntu",
  324. []api.Secret{{Type: api.SecretTypeDockercfg, Data: map[string][]byte{api.DockerConfigKey: dockercfgContent}}},
  325. credentialprovider.DockerConfig(map[string]credentialprovider.DockerConfigEntry{
  326. "index.docker.io/v1/": {Username: "built-in", Password: "password", Email: "email", Provider: nil},
  327. }),
  328. []string{`ubuntu:latest using {"username":"passed-user","password":"passed-password","email":"passed-email"}`},
  329. },
  330. "builtin keyring secrets, but use passed with new docker config": {
  331. "ubuntu",
  332. []api.Secret{{Type: api.SecretTypeDockerConfigJson, Data: map[string][]byte{api.DockerConfigJsonKey: dockerConfigJsonContent}}},
  333. credentialprovider.DockerConfig(map[string]credentialprovider.DockerConfigEntry{
  334. "index.docker.io/v1/": {Username: "built-in", Password: "password", Email: "email", Provider: nil},
  335. }),
  336. []string{`ubuntu:latest using {"username":"passed-user","password":"passed-password","email":"passed-email"}`},
  337. },
  338. }
  339. for i, test := range tests {
  340. builtInKeyRing := &credentialprovider.BasicDockerKeyring{}
  341. builtInKeyRing.Add(test.builtInDockerConfig)
  342. fakeClient := NewFakeDockerClient()
  343. dp := dockerPuller{
  344. client: fakeClient,
  345. keyring: builtInKeyRing,
  346. }
  347. err := dp.Pull(test.imageName, test.passedSecrets)
  348. if err != nil {
  349. t.Errorf("%s: unexpected non-nil err: %s", i, err)
  350. continue
  351. }
  352. if e, a := 1, len(fakeClient.pulled); e != a {
  353. t.Errorf("%s: expected 1 pulled image, got %d: %v", i, a, fakeClient.pulled)
  354. continue
  355. }
  356. if e, a := test.expectedPulls, fakeClient.pulled; !reflect.DeepEqual(e, a) {
  357. t.Errorf("%s: expected pull of %v, but got %v", i, e, a)
  358. }
  359. }
  360. }
  361. func TestDockerKeyringLookupFails(t *testing.T) {
  362. fakeKeyring := &credentialprovider.FakeKeyring{}
  363. fakeClient := NewFakeDockerClient()
  364. fakeClient.InjectError("pull", fmt.Errorf("test error"))
  365. dp := dockerPuller{
  366. client: fakeClient,
  367. keyring: fakeKeyring,
  368. }
  369. err := dp.Pull("host/repository/image:version", []api.Secret{})
  370. if err == nil {
  371. t.Errorf("unexpected non-error")
  372. }
  373. msg := "image pull failed for host/repository/image:version, this may be because there are no credentials on this request. details: (test error)"
  374. if err.Error() != msg {
  375. t.Errorf("expected: %s, saw: %s", msg, err.Error())
  376. }
  377. }
  378. func TestDockerKeyringLookup(t *testing.T) {
  379. ada := credentialprovider.LazyAuthConfiguration{
  380. AuthConfig: dockertypes.AuthConfig{
  381. Username: "ada",
  382. Password: "smash",
  383. Email: "ada@example.com",
  384. },
  385. }
  386. grace := credentialprovider.LazyAuthConfiguration{
  387. AuthConfig: dockertypes.AuthConfig{
  388. Username: "grace",
  389. Password: "squash",
  390. Email: "grace@example.com",
  391. },
  392. }
  393. dk := &credentialprovider.BasicDockerKeyring{}
  394. dk.Add(credentialprovider.DockerConfig{
  395. "bar.example.com/pong": credentialprovider.DockerConfigEntry{
  396. Username: grace.Username,
  397. Password: grace.Password,
  398. Email: grace.Email,
  399. },
  400. "bar.example.com": credentialprovider.DockerConfigEntry{
  401. Username: ada.Username,
  402. Password: ada.Password,
  403. Email: ada.Email,
  404. },
  405. })
  406. tests := []struct {
  407. image string
  408. match []credentialprovider.LazyAuthConfiguration
  409. ok bool
  410. }{
  411. // direct match
  412. {"bar.example.com", []credentialprovider.LazyAuthConfiguration{ada}, true},
  413. // direct match deeper than other possible matches
  414. {"bar.example.com/pong", []credentialprovider.LazyAuthConfiguration{grace, ada}, true},
  415. // no direct match, deeper path ignored
  416. {"bar.example.com/ping", []credentialprovider.LazyAuthConfiguration{ada}, true},
  417. // match first part of path token
  418. {"bar.example.com/pongz", []credentialprovider.LazyAuthConfiguration{grace, ada}, true},
  419. // match regardless of sub-path
  420. {"bar.example.com/pong/pang", []credentialprovider.LazyAuthConfiguration{grace, ada}, true},
  421. // no host match
  422. {"example.com", []credentialprovider.LazyAuthConfiguration{}, false},
  423. {"foo.example.com", []credentialprovider.LazyAuthConfiguration{}, false},
  424. }
  425. for i, tt := range tests {
  426. match, ok := dk.Lookup(tt.image)
  427. if tt.ok != ok {
  428. t.Errorf("case %d: expected ok=%t, got %t", i, tt.ok, ok)
  429. }
  430. if !reflect.DeepEqual(tt.match, match) {
  431. t.Errorf("case %d: expected match=%#v, got %#v", i, tt.match, match)
  432. }
  433. }
  434. }
  435. // This validates that dockercfg entries with a scheme and url path are properly matched
  436. // by images that only match the hostname.
  437. // NOTE: the above covers the case of a more specific match trumping just hostname.
  438. func TestIssue3797(t *testing.T) {
  439. rex := credentialprovider.LazyAuthConfiguration{
  440. AuthConfig: dockertypes.AuthConfig{
  441. Username: "rex",
  442. Password: "tiny arms",
  443. Email: "rex@example.com",
  444. },
  445. }
  446. dk := &credentialprovider.BasicDockerKeyring{}
  447. dk.Add(credentialprovider.DockerConfig{
  448. "https://quay.io/v1/": credentialprovider.DockerConfigEntry{
  449. Username: rex.Username,
  450. Password: rex.Password,
  451. Email: rex.Email,
  452. },
  453. })
  454. tests := []struct {
  455. image string
  456. match []credentialprovider.LazyAuthConfiguration
  457. ok bool
  458. }{
  459. // direct match
  460. {"quay.io", []credentialprovider.LazyAuthConfiguration{rex}, true},
  461. // partial matches
  462. {"quay.io/foo", []credentialprovider.LazyAuthConfiguration{rex}, true},
  463. {"quay.io/foo/bar", []credentialprovider.LazyAuthConfiguration{rex}, true},
  464. }
  465. for i, tt := range tests {
  466. match, ok := dk.Lookup(tt.image)
  467. if tt.ok != ok {
  468. t.Errorf("case %d: expected ok=%t, got %t", i, tt.ok, ok)
  469. }
  470. if !reflect.DeepEqual(tt.match, match) {
  471. t.Errorf("case %d: expected match=%#v, got %#v", i, tt.match, match)
  472. }
  473. }
  474. }
  475. type imageTrackingDockerClient struct {
  476. *FakeDockerClient
  477. imageName string
  478. }
  479. func (f *imageTrackingDockerClient) InspectImage(name string) (image *dockertypes.ImageInspect, err error) {
  480. image, err = f.FakeDockerClient.InspectImage(name)
  481. f.imageName = name
  482. return
  483. }
  484. func TestIsImagePresent(t *testing.T) {
  485. cl := &imageTrackingDockerClient{NewFakeDockerClient(), ""}
  486. puller := &dockerPuller{
  487. client: cl,
  488. }
  489. _, _ = puller.IsImagePresent("abc:123")
  490. if cl.imageName != "abc:123" {
  491. t.Errorf("expected inspection of image abc:123, instead inspected image %v", cl.imageName)
  492. }
  493. }
  494. type podsByID []*kubecontainer.Pod
  495. func (b podsByID) Len() int { return len(b) }
  496. func (b podsByID) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
  497. func (b podsByID) Less(i, j int) bool { return b[i].ID < b[j].ID }
  498. type containersByID []*kubecontainer.Container
  499. func (b containersByID) Len() int { return len(b) }
  500. func (b containersByID) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
  501. func (b containersByID) Less(i, j int) bool { return b[i].ID.ID < b[j].ID.ID }
  502. func TestFindContainersByPod(t *testing.T) {
  503. tests := []struct {
  504. runningContainerList []dockertypes.Container
  505. exitedContainerList []dockertypes.Container
  506. all bool
  507. expectedPods []*kubecontainer.Pod
  508. }{
  509. {
  510. []dockertypes.Container{
  511. {
  512. ID: "foobar",
  513. Names: []string{"/k8s_foobar.1234_qux_ns_1234_42"},
  514. },
  515. {
  516. ID: "barbar",
  517. Names: []string{"/k8s_barbar.1234_qux_ns_2343_42"},
  518. },
  519. {
  520. ID: "baz",
  521. Names: []string{"/k8s_baz.1234_qux_ns_1234_42"},
  522. },
  523. },
  524. []dockertypes.Container{
  525. {
  526. ID: "barfoo",
  527. Names: []string{"/k8s_barfoo.1234_qux_ns_1234_42"},
  528. },
  529. {
  530. ID: "bazbaz",
  531. Names: []string{"/k8s_bazbaz.1234_qux_ns_5678_42"},
  532. },
  533. },
  534. false,
  535. []*kubecontainer.Pod{
  536. {
  537. ID: "1234",
  538. Name: "qux",
  539. Namespace: "ns",
  540. Containers: []*kubecontainer.Container{
  541. {
  542. ID: kubecontainer.DockerID("foobar").ContainerID(),
  543. Name: "foobar",
  544. Hash: 0x1234,
  545. State: kubecontainer.ContainerStateUnknown,
  546. },
  547. {
  548. ID: kubecontainer.DockerID("baz").ContainerID(),
  549. Name: "baz",
  550. Hash: 0x1234,
  551. State: kubecontainer.ContainerStateUnknown,
  552. },
  553. },
  554. },
  555. {
  556. ID: "2343",
  557. Name: "qux",
  558. Namespace: "ns",
  559. Containers: []*kubecontainer.Container{
  560. {
  561. ID: kubecontainer.DockerID("barbar").ContainerID(),
  562. Name: "barbar",
  563. Hash: 0x1234,
  564. State: kubecontainer.ContainerStateUnknown,
  565. },
  566. },
  567. },
  568. },
  569. },
  570. {
  571. []dockertypes.Container{
  572. {
  573. ID: "foobar",
  574. Names: []string{"/k8s_foobar.1234_qux_ns_1234_42"},
  575. },
  576. {
  577. ID: "barbar",
  578. Names: []string{"/k8s_barbar.1234_qux_ns_2343_42"},
  579. },
  580. {
  581. ID: "baz",
  582. Names: []string{"/k8s_baz.1234_qux_ns_1234_42"},
  583. },
  584. },
  585. []dockertypes.Container{
  586. {
  587. ID: "barfoo",
  588. Names: []string{"/k8s_barfoo.1234_qux_ns_1234_42"},
  589. },
  590. {
  591. ID: "bazbaz",
  592. Names: []string{"/k8s_bazbaz.1234_qux_ns_5678_42"},
  593. },
  594. },
  595. true,
  596. []*kubecontainer.Pod{
  597. {
  598. ID: "1234",
  599. Name: "qux",
  600. Namespace: "ns",
  601. Containers: []*kubecontainer.Container{
  602. {
  603. ID: kubecontainer.DockerID("foobar").ContainerID(),
  604. Name: "foobar",
  605. Hash: 0x1234,
  606. State: kubecontainer.ContainerStateUnknown,
  607. },
  608. {
  609. ID: kubecontainer.DockerID("barfoo").ContainerID(),
  610. Name: "barfoo",
  611. Hash: 0x1234,
  612. State: kubecontainer.ContainerStateUnknown,
  613. },
  614. {
  615. ID: kubecontainer.DockerID("baz").ContainerID(),
  616. Name: "baz",
  617. Hash: 0x1234,
  618. State: kubecontainer.ContainerStateUnknown,
  619. },
  620. },
  621. },
  622. {
  623. ID: "2343",
  624. Name: "qux",
  625. Namespace: "ns",
  626. Containers: []*kubecontainer.Container{
  627. {
  628. ID: kubecontainer.DockerID("barbar").ContainerID(),
  629. Name: "barbar",
  630. Hash: 0x1234,
  631. State: kubecontainer.ContainerStateUnknown,
  632. },
  633. },
  634. },
  635. {
  636. ID: "5678",
  637. Name: "qux",
  638. Namespace: "ns",
  639. Containers: []*kubecontainer.Container{
  640. {
  641. ID: kubecontainer.DockerID("bazbaz").ContainerID(),
  642. Name: "bazbaz",
  643. Hash: 0x1234,
  644. State: kubecontainer.ContainerStateUnknown,
  645. },
  646. },
  647. },
  648. },
  649. },
  650. {
  651. []dockertypes.Container{},
  652. []dockertypes.Container{},
  653. true,
  654. nil,
  655. },
  656. }
  657. fakeClient := NewFakeDockerClient()
  658. np, _ := network.InitNetworkPlugin([]network.NetworkPlugin{}, "", nettest.NewFakeHost(nil), componentconfig.HairpinNone, "10.0.0.0/8", network.UseDefaultMTU)
  659. // image back-off is set to nil, this test should not pull images
  660. containerManager := NewFakeDockerManager(fakeClient, &record.FakeRecorder{}, nil, nil, &cadvisorapi.MachineInfo{}, "", 0, 0, "", &containertest.FakeOS{}, np, nil, nil, nil)
  661. for i, test := range tests {
  662. fakeClient.RunningContainerList = test.runningContainerList
  663. fakeClient.ExitedContainerList = test.exitedContainerList
  664. result, _ := containerManager.GetPods(test.all)
  665. for i := range result {
  666. sort.Sort(containersByID(result[i].Containers))
  667. }
  668. for i := range test.expectedPods {
  669. sort.Sort(containersByID(test.expectedPods[i].Containers))
  670. }
  671. sort.Sort(podsByID(result))
  672. sort.Sort(podsByID(test.expectedPods))
  673. if !reflect.DeepEqual(test.expectedPods, result) {
  674. t.Errorf("%d: expected: %#v, saw: %#v", i, test.expectedPods, result)
  675. }
  676. }
  677. }
  678. func TestMakePortsAndBindings(t *testing.T) {
  679. portMapping := func(container, host int, protocol api.Protocol, ip string) kubecontainer.PortMapping {
  680. return kubecontainer.PortMapping{
  681. ContainerPort: container,
  682. HostPort: host,
  683. Protocol: protocol,
  684. HostIP: ip,
  685. }
  686. }
  687. portBinding := func(port, ip string) dockernat.PortBinding {
  688. return dockernat.PortBinding{
  689. HostPort: port,
  690. HostIP: ip,
  691. }
  692. }
  693. ports := []kubecontainer.PortMapping{
  694. portMapping(80, 8080, "", "127.0.0.1"),
  695. portMapping(443, 443, "tcp", ""),
  696. portMapping(444, 444, "udp", ""),
  697. portMapping(445, 445, "foobar", ""),
  698. portMapping(443, 446, "tcp", ""),
  699. portMapping(443, 446, "udp", ""),
  700. }
  701. exposedPorts, bindings := makePortsAndBindings(ports)
  702. // Count the expected exposed ports and bindings
  703. expectedExposedPorts := map[string]struct{}{}
  704. for _, binding := range ports {
  705. dockerKey := strconv.Itoa(binding.ContainerPort) + "/" + string(binding.Protocol)
  706. expectedExposedPorts[dockerKey] = struct{}{}
  707. }
  708. // Should expose right ports in docker
  709. if len(expectedExposedPorts) != len(exposedPorts) {
  710. t.Errorf("Unexpected ports and bindings, %#v %#v %#v", ports, exposedPorts, bindings)
  711. }
  712. // Construct expected bindings
  713. expectPortBindings := map[string][]dockernat.PortBinding{
  714. "80/tcp": {
  715. portBinding("8080", "127.0.0.1"),
  716. },
  717. "443/tcp": {
  718. portBinding("443", ""),
  719. portBinding("446", ""),
  720. },
  721. "443/udp": {
  722. portBinding("446", ""),
  723. },
  724. "444/udp": {
  725. portBinding("444", ""),
  726. },
  727. "445/tcp": {
  728. portBinding("445", ""),
  729. },
  730. }
  731. // interate the bindings by dockerPort, and check its portBindings
  732. for dockerPort, portBindings := range bindings {
  733. switch dockerPort {
  734. case "80/tcp", "443/tcp", "443/udp", "444/udp", "445/tcp":
  735. if !reflect.DeepEqual(expectPortBindings[string(dockerPort)], portBindings) {
  736. t.Errorf("Unexpected portbindings for %#v, expected: %#v, but got: %#v",
  737. dockerPort, expectPortBindings[string(dockerPort)], portBindings)
  738. }
  739. default:
  740. t.Errorf("Unexpected docker port: %#v with portbindings: %#v", dockerPort, portBindings)
  741. }
  742. }
  743. }
  744. func TestMilliCPUToQuota(t *testing.T) {
  745. testCases := []struct {
  746. input int64
  747. quota int64
  748. period int64
  749. }{
  750. {
  751. input: int64(0),
  752. quota: int64(0),
  753. period: int64(0),
  754. },
  755. {
  756. input: int64(5),
  757. quota: int64(1000),
  758. period: int64(100000),
  759. },
  760. {
  761. input: int64(9),
  762. quota: int64(1000),
  763. period: int64(100000),
  764. },
  765. {
  766. input: int64(10),
  767. quota: int64(1000),
  768. period: int64(100000),
  769. },
  770. {
  771. input: int64(200),
  772. quota: int64(20000),
  773. period: int64(100000),
  774. },
  775. {
  776. input: int64(500),
  777. quota: int64(50000),
  778. period: int64(100000),
  779. },
  780. {
  781. input: int64(1000),
  782. quota: int64(100000),
  783. period: int64(100000),
  784. },
  785. {
  786. input: int64(1500),
  787. quota: int64(150000),
  788. period: int64(100000),
  789. },
  790. }
  791. for _, testCase := range testCases {
  792. quota, period := milliCPUToQuota(testCase.input)
  793. if quota != testCase.quota || period != testCase.period {
  794. t.Errorf("Input %v, expected quota %v period %v, but got quota %v period %v", testCase.input, testCase.quota, testCase.period, quota, period)
  795. }
  796. }
  797. }
  798. const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  799. func randStringBytes(n int) string {
  800. b := make([]byte, n)
  801. for i := range b {
  802. b[i] = letterBytes[rand.Intn(len(letterBytes))]
  803. }
  804. return string(b)
  805. }
  806. func TestLogSymLink(t *testing.T) {
  807. as := assert.New(t)
  808. containerLogsDir := "/foo/bar"
  809. podFullName := randStringBytes(128)
  810. containerName := randStringBytes(70)
  811. dockerId := randStringBytes(80)
  812. // The file name cannot exceed 255 characters. Since .log suffix is required, the prefix cannot exceed 251 characters.
  813. expectedPath := path.Join(containerLogsDir, fmt.Sprintf("%s_%s-%s", podFullName, containerName, dockerId)[:251]+".log")
  814. as.Equal(expectedPath, LogSymlink(containerLogsDir, podFullName, containerName, dockerId))
  815. }