helpers_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. /*
  2. Copyright 2015 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 container
  14. import (
  15. "reflect"
  16. "testing"
  17. "github.com/google/go-cmp/cmp"
  18. "github.com/stretchr/testify/assert"
  19. "k8s.io/api/core/v1"
  20. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  21. utilfeature "k8s.io/apiserver/pkg/util/feature"
  22. featuregatetesting "k8s.io/component-base/featuregate/testing"
  23. "k8s.io/kubernetes/pkg/features"
  24. )
  25. func TestEnvVarsToMap(t *testing.T) {
  26. vars := []EnvVar{
  27. {
  28. Name: "foo",
  29. Value: "bar",
  30. },
  31. {
  32. Name: "zoo",
  33. Value: "baz",
  34. },
  35. }
  36. varMap := EnvVarsToMap(vars)
  37. if e, a := len(vars), len(varMap); e != a {
  38. t.Errorf("Unexpected map length; expected: %d, got %d", e, a)
  39. }
  40. if a := varMap["foo"]; a != "bar" {
  41. t.Errorf("Unexpected value of key 'foo': %v", a)
  42. }
  43. if a := varMap["zoo"]; a != "baz" {
  44. t.Errorf("Unexpected value of key 'zoo': %v", a)
  45. }
  46. }
  47. func TestExpandCommandAndArgs(t *testing.T) {
  48. cases := []struct {
  49. name string
  50. container *v1.Container
  51. envs []EnvVar
  52. expectedCommand []string
  53. expectedArgs []string
  54. }{
  55. {
  56. name: "none",
  57. container: &v1.Container{},
  58. },
  59. {
  60. name: "command expanded",
  61. container: &v1.Container{
  62. Command: []string{"foo", "$(VAR_TEST)", "$(VAR_TEST2)"},
  63. },
  64. envs: []EnvVar{
  65. {
  66. Name: "VAR_TEST",
  67. Value: "zoo",
  68. },
  69. {
  70. Name: "VAR_TEST2",
  71. Value: "boo",
  72. },
  73. },
  74. expectedCommand: []string{"foo", "zoo", "boo"},
  75. },
  76. {
  77. name: "args expanded",
  78. container: &v1.Container{
  79. Args: []string{"zap", "$(VAR_TEST)", "$(VAR_TEST2)"},
  80. },
  81. envs: []EnvVar{
  82. {
  83. Name: "VAR_TEST",
  84. Value: "hap",
  85. },
  86. {
  87. Name: "VAR_TEST2",
  88. Value: "trap",
  89. },
  90. },
  91. expectedArgs: []string{"zap", "hap", "trap"},
  92. },
  93. {
  94. name: "both expanded",
  95. container: &v1.Container{
  96. Command: []string{"$(VAR_TEST2)--$(VAR_TEST)", "foo", "$(VAR_TEST3)"},
  97. Args: []string{"foo", "$(VAR_TEST)", "$(VAR_TEST2)"},
  98. },
  99. envs: []EnvVar{
  100. {
  101. Name: "VAR_TEST",
  102. Value: "zoo",
  103. },
  104. {
  105. Name: "VAR_TEST2",
  106. Value: "boo",
  107. },
  108. {
  109. Name: "VAR_TEST3",
  110. Value: "roo",
  111. },
  112. },
  113. expectedCommand: []string{"boo--zoo", "foo", "roo"},
  114. expectedArgs: []string{"foo", "zoo", "boo"},
  115. },
  116. }
  117. for _, tc := range cases {
  118. actualCommand, actualArgs := ExpandContainerCommandAndArgs(tc.container, tc.envs)
  119. if e, a := tc.expectedCommand, actualCommand; !reflect.DeepEqual(e, a) {
  120. t.Errorf("%v: unexpected command; expected %v, got %v", tc.name, e, a)
  121. }
  122. if e, a := tc.expectedArgs, actualArgs; !reflect.DeepEqual(e, a) {
  123. t.Errorf("%v: unexpected args; expected %v, got %v", tc.name, e, a)
  124. }
  125. }
  126. }
  127. func TestExpandVolumeMountsWithSubpath(t *testing.T) {
  128. cases := []struct {
  129. name string
  130. container *v1.Container
  131. envs []EnvVar
  132. expectedSubPath string
  133. expectedMountPath string
  134. expectedOk bool
  135. }{
  136. {
  137. name: "subpath with no expansion",
  138. container: &v1.Container{
  139. VolumeMounts: []v1.VolumeMount{{SubPathExpr: "foo"}},
  140. },
  141. expectedSubPath: "foo",
  142. expectedMountPath: "",
  143. expectedOk: true,
  144. },
  145. {
  146. name: "volumes with expanded subpath",
  147. container: &v1.Container{
  148. VolumeMounts: []v1.VolumeMount{{SubPathExpr: "foo/$(POD_NAME)"}},
  149. },
  150. envs: []EnvVar{
  151. {
  152. Name: "POD_NAME",
  153. Value: "bar",
  154. },
  155. },
  156. expectedSubPath: "foo/bar",
  157. expectedMountPath: "",
  158. expectedOk: true,
  159. },
  160. {
  161. name: "volumes expanded with empty subpath",
  162. container: &v1.Container{
  163. VolumeMounts: []v1.VolumeMount{{SubPathExpr: ""}},
  164. },
  165. envs: []EnvVar{
  166. {
  167. Name: "POD_NAME",
  168. Value: "bar",
  169. },
  170. },
  171. expectedSubPath: "",
  172. expectedMountPath: "",
  173. expectedOk: true,
  174. },
  175. {
  176. name: "volumes expanded with no envs subpath",
  177. container: &v1.Container{
  178. VolumeMounts: []v1.VolumeMount{{SubPathExpr: "/foo/$(POD_NAME)"}},
  179. },
  180. expectedSubPath: "/foo/$(POD_NAME)",
  181. expectedMountPath: "",
  182. expectedOk: false,
  183. },
  184. {
  185. name: "volumes expanded with leading environment variable",
  186. container: &v1.Container{
  187. VolumeMounts: []v1.VolumeMount{{SubPathExpr: "$(POD_NAME)/bar"}},
  188. },
  189. envs: []EnvVar{
  190. {
  191. Name: "POD_NAME",
  192. Value: "foo",
  193. },
  194. },
  195. expectedSubPath: "foo/bar",
  196. expectedMountPath: "",
  197. expectedOk: true,
  198. },
  199. {
  200. name: "volumes with volume and subpath",
  201. container: &v1.Container{
  202. VolumeMounts: []v1.VolumeMount{{MountPath: "/foo", SubPathExpr: "$(POD_NAME)/bar"}},
  203. },
  204. envs: []EnvVar{
  205. {
  206. Name: "POD_NAME",
  207. Value: "foo",
  208. },
  209. },
  210. expectedSubPath: "foo/bar",
  211. expectedMountPath: "/foo",
  212. expectedOk: true,
  213. },
  214. {
  215. name: "volumes with volume and no subpath",
  216. container: &v1.Container{
  217. VolumeMounts: []v1.VolumeMount{{MountPath: "/foo"}},
  218. },
  219. envs: []EnvVar{
  220. {
  221. Name: "POD_NAME",
  222. Value: "foo",
  223. },
  224. },
  225. expectedSubPath: "",
  226. expectedMountPath: "/foo",
  227. expectedOk: true,
  228. },
  229. {
  230. name: "subpaths with empty environment variable",
  231. container: &v1.Container{
  232. VolumeMounts: []v1.VolumeMount{{SubPathExpr: "foo/$(POD_NAME)/$(ANNOTATION)"}},
  233. },
  234. envs: []EnvVar{
  235. {
  236. Name: "ANNOTATION",
  237. Value: "",
  238. },
  239. },
  240. expectedSubPath: "foo/$(POD_NAME)/$(ANNOTATION)",
  241. expectedMountPath: "",
  242. expectedOk: false,
  243. },
  244. {
  245. name: "subpaths with missing env variables",
  246. container: &v1.Container{
  247. VolumeMounts: []v1.VolumeMount{{SubPathExpr: "foo/$(ODD_NAME)/$(POD_NAME)"}},
  248. },
  249. envs: []EnvVar{
  250. {
  251. Name: "ODD_NAME",
  252. Value: "bar",
  253. },
  254. },
  255. expectedSubPath: "foo/$(ODD_NAME)/$(POD_NAME)",
  256. expectedMountPath: "",
  257. expectedOk: false,
  258. },
  259. {
  260. name: "subpaths with empty expansion",
  261. container: &v1.Container{
  262. VolumeMounts: []v1.VolumeMount{{SubPathExpr: "$()"}},
  263. },
  264. expectedSubPath: "$()",
  265. expectedMountPath: "",
  266. expectedOk: false,
  267. },
  268. {
  269. name: "subpaths with nested expandable envs",
  270. container: &v1.Container{
  271. VolumeMounts: []v1.VolumeMount{{SubPathExpr: "$(POD_NAME$(ANNOTATION))"}},
  272. },
  273. envs: []EnvVar{
  274. {
  275. Name: "POD_NAME",
  276. Value: "foo",
  277. },
  278. {
  279. Name: "ANNOTATION",
  280. Value: "bar",
  281. },
  282. },
  283. expectedSubPath: "$(POD_NAME$(ANNOTATION))",
  284. expectedMountPath: "",
  285. expectedOk: false,
  286. },
  287. }
  288. for _, tc := range cases {
  289. actualSubPath, err := ExpandContainerVolumeMounts(tc.container.VolumeMounts[0], tc.envs)
  290. ok := err == nil
  291. if e, a := tc.expectedOk, ok; !reflect.DeepEqual(e, a) {
  292. t.Errorf("%v: unexpected validation failure of subpath; expected %v, got %v", tc.name, e, a)
  293. }
  294. if !ok {
  295. // if ExpandContainerVolumeMounts returns an error, we don't care what the actualSubPath value is
  296. continue
  297. }
  298. if e, a := tc.expectedSubPath, actualSubPath; !reflect.DeepEqual(e, a) {
  299. t.Errorf("%v: unexpected subpath; expected %v, got %v", tc.name, e, a)
  300. }
  301. if e, a := tc.expectedMountPath, tc.container.VolumeMounts[0].MountPath; !reflect.DeepEqual(e, a) {
  302. t.Errorf("%v: unexpected mountpath; expected %v, got %v", tc.name, e, a)
  303. }
  304. }
  305. }
  306. func TestGetContainerSpec(t *testing.T) {
  307. defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.EphemeralContainers, true)()
  308. for _, tc := range []struct {
  309. name string
  310. havePod *v1.Pod
  311. haveName string
  312. wantContainer *v1.Container
  313. }{
  314. {
  315. name: "regular container",
  316. havePod: &v1.Pod{
  317. Spec: v1.PodSpec{
  318. Containers: []v1.Container{
  319. {Name: "plain-ole-container"},
  320. },
  321. InitContainers: []v1.Container{
  322. {Name: "init-container"},
  323. },
  324. },
  325. },
  326. haveName: "plain-ole-container",
  327. wantContainer: &v1.Container{Name: "plain-ole-container"},
  328. },
  329. {
  330. name: "init container",
  331. havePod: &v1.Pod{
  332. Spec: v1.PodSpec{
  333. Containers: []v1.Container{
  334. {Name: "plain-ole-container"},
  335. },
  336. InitContainers: []v1.Container{
  337. {Name: "init-container"},
  338. },
  339. },
  340. },
  341. haveName: "init-container",
  342. wantContainer: &v1.Container{Name: "init-container"},
  343. },
  344. {
  345. name: "ephemeral container",
  346. havePod: &v1.Pod{
  347. Spec: v1.PodSpec{
  348. Containers: []v1.Container{
  349. {Name: "plain-ole-container"},
  350. },
  351. InitContainers: []v1.Container{
  352. {Name: "init-container"},
  353. },
  354. EphemeralContainers: []v1.EphemeralContainer{
  355. {EphemeralContainerCommon: v1.EphemeralContainerCommon{
  356. Name: "debug-container",
  357. }},
  358. },
  359. },
  360. },
  361. haveName: "debug-container",
  362. wantContainer: &v1.Container{Name: "debug-container"},
  363. },
  364. } {
  365. t.Run(tc.name, func(t *testing.T) {
  366. gotContainer := GetContainerSpec(tc.havePod, tc.haveName)
  367. if diff := cmp.Diff(tc.wantContainer, gotContainer); diff != "" {
  368. t.Fatalf("GetContainerSpec for %q returned diff (-want +got):%v", tc.name, diff)
  369. }
  370. })
  371. }
  372. }
  373. func TestShouldContainerBeRestarted(t *testing.T) {
  374. pod := &v1.Pod{
  375. ObjectMeta: metav1.ObjectMeta{
  376. UID: "12345678",
  377. Name: "foo",
  378. Namespace: "new",
  379. },
  380. Spec: v1.PodSpec{
  381. Containers: []v1.Container{
  382. {Name: "no-history"},
  383. {Name: "alive"},
  384. {Name: "succeed"},
  385. {Name: "failed"},
  386. {Name: "unknown"},
  387. },
  388. },
  389. }
  390. podStatus := &PodStatus{
  391. ID: pod.UID,
  392. Name: pod.Name,
  393. Namespace: pod.Namespace,
  394. ContainerStatuses: []*ContainerStatus{
  395. {
  396. Name: "alive",
  397. State: ContainerStateRunning,
  398. },
  399. {
  400. Name: "succeed",
  401. State: ContainerStateExited,
  402. ExitCode: 0,
  403. },
  404. {
  405. Name: "failed",
  406. State: ContainerStateExited,
  407. ExitCode: 1,
  408. },
  409. {
  410. Name: "alive",
  411. State: ContainerStateExited,
  412. ExitCode: 2,
  413. },
  414. {
  415. Name: "unknown",
  416. State: ContainerStateUnknown,
  417. },
  418. {
  419. Name: "failed",
  420. State: ContainerStateExited,
  421. ExitCode: 3,
  422. },
  423. },
  424. }
  425. policies := []v1.RestartPolicy{
  426. v1.RestartPolicyNever,
  427. v1.RestartPolicyOnFailure,
  428. v1.RestartPolicyAlways,
  429. }
  430. expected := map[string][]bool{
  431. "no-history": {true, true, true},
  432. "alive": {false, false, false},
  433. "succeed": {false, false, true},
  434. "failed": {false, true, true},
  435. "unknown": {true, true, true},
  436. }
  437. for _, c := range pod.Spec.Containers {
  438. for i, policy := range policies {
  439. pod.Spec.RestartPolicy = policy
  440. e := expected[c.Name][i]
  441. r := ShouldContainerBeRestarted(&c, pod, podStatus)
  442. if r != e {
  443. t.Errorf("Restart for container %q with restart policy %q expected %t, got %t",
  444. c.Name, policy, e, r)
  445. }
  446. }
  447. }
  448. }
  449. func TestHasPrivilegedContainer(t *testing.T) {
  450. newBoolPtr := func(b bool) *bool {
  451. return &b
  452. }
  453. tests := map[string]struct {
  454. securityContext *v1.SecurityContext
  455. expected bool
  456. }{
  457. "nil security context": {
  458. securityContext: nil,
  459. expected: false,
  460. },
  461. "nil privileged": {
  462. securityContext: &v1.SecurityContext{},
  463. expected: false,
  464. },
  465. "false privileged": {
  466. securityContext: &v1.SecurityContext{Privileged: newBoolPtr(false)},
  467. expected: false,
  468. },
  469. "true privileged": {
  470. securityContext: &v1.SecurityContext{Privileged: newBoolPtr(true)},
  471. expected: true,
  472. },
  473. }
  474. for k, v := range tests {
  475. pod := &v1.Pod{
  476. Spec: v1.PodSpec{
  477. Containers: []v1.Container{
  478. {SecurityContext: v.securityContext},
  479. },
  480. },
  481. }
  482. actual := HasPrivilegedContainer(pod)
  483. if actual != v.expected {
  484. t.Errorf("%s expected %t but got %t", k, v.expected, actual)
  485. }
  486. }
  487. // Test init containers as well.
  488. for k, v := range tests {
  489. pod := &v1.Pod{
  490. Spec: v1.PodSpec{
  491. InitContainers: []v1.Container{
  492. {SecurityContext: v.securityContext},
  493. },
  494. },
  495. }
  496. actual := HasPrivilegedContainer(pod)
  497. if actual != v.expected {
  498. t.Errorf("%s expected %t but got %t", k, v.expected, actual)
  499. }
  500. }
  501. }
  502. func TestMakePortMappings(t *testing.T) {
  503. port := func(name string, protocol v1.Protocol, containerPort, hostPort int32, ip string) v1.ContainerPort {
  504. return v1.ContainerPort{
  505. Name: name,
  506. Protocol: protocol,
  507. ContainerPort: containerPort,
  508. HostPort: hostPort,
  509. HostIP: ip,
  510. }
  511. }
  512. portMapping := func(name string, protocol v1.Protocol, containerPort, hostPort int, ip string) PortMapping {
  513. return PortMapping{
  514. Name: name,
  515. Protocol: protocol,
  516. ContainerPort: containerPort,
  517. HostPort: hostPort,
  518. HostIP: ip,
  519. }
  520. }
  521. tests := []struct {
  522. container *v1.Container
  523. expectedPortMappings []PortMapping
  524. }{
  525. {
  526. &v1.Container{
  527. Name: "fooContainer",
  528. Ports: []v1.ContainerPort{
  529. port("", v1.ProtocolTCP, 80, 8080, "127.0.0.1"),
  530. port("", v1.ProtocolTCP, 443, 4343, "192.168.0.1"),
  531. port("foo", v1.ProtocolUDP, 555, 5555, ""),
  532. // Duplicated, should be ignored.
  533. port("foo", v1.ProtocolUDP, 888, 8888, ""),
  534. // Duplicated, should be ignored.
  535. port("", v1.ProtocolTCP, 80, 8888, "127.0.0.1"),
  536. // Duplicated with different address family, shouldn't be ignored
  537. port("", v1.ProtocolTCP, 80, 8080, "::"),
  538. // No address family specified
  539. port("", v1.ProtocolTCP, 1234, 5678, ""),
  540. },
  541. },
  542. []PortMapping{
  543. portMapping("fooContainer-v4-TCP:80", v1.ProtocolTCP, 80, 8080, "127.0.0.1"),
  544. portMapping("fooContainer-v4-TCP:443", v1.ProtocolTCP, 443, 4343, "192.168.0.1"),
  545. portMapping("fooContainer-foo", v1.ProtocolUDP, 555, 5555, ""),
  546. portMapping("fooContainer-v6-TCP:80", v1.ProtocolTCP, 80, 8080, "::"),
  547. portMapping("fooContainer-any-TCP:1234", v1.ProtocolTCP, 1234, 5678, ""),
  548. },
  549. },
  550. }
  551. for i, tt := range tests {
  552. actual := MakePortMappings(tt.container)
  553. assert.Equal(t, tt.expectedPortMappings, actual, "[%d]", i)
  554. }
  555. }
  556. func TestHashContainer(t *testing.T) {
  557. testCases := []struct {
  558. name string
  559. image string
  560. args []string
  561. containerPort int32
  562. expectedHash uint64
  563. }{
  564. {
  565. name: "test_container",
  566. image: "foo/image:v1",
  567. args: []string{
  568. "/bin/sh",
  569. "-c",
  570. "echo abc",
  571. },
  572. containerPort: int32(8001),
  573. expectedHash: uint64(0x3c42280f),
  574. },
  575. }
  576. for _, tc := range testCases {
  577. container := v1.Container{
  578. Name: tc.name,
  579. Image: tc.image,
  580. Args: tc.args,
  581. Ports: []v1.ContainerPort{{ContainerPort: tc.containerPort}},
  582. }
  583. hashVal := HashContainer(&container)
  584. assert.Equal(t, tc.expectedHash, hashVal, "the hash value here should not be changed.")
  585. }
  586. }