utils_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. /*
  2. Copyright 2017 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 staticpod
  14. import (
  15. "io/ioutil"
  16. "os"
  17. "path/filepath"
  18. "reflect"
  19. "sort"
  20. "strconv"
  21. "testing"
  22. "k8s.io/api/core/v1"
  23. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  24. kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
  25. testutil "k8s.io/kubernetes/cmd/kubeadm/test"
  26. )
  27. func TestComponentResources(t *testing.T) {
  28. a := ComponentResources("250m")
  29. if a.Requests == nil {
  30. t.Errorf(
  31. "failed componentResources, return value was nil",
  32. )
  33. }
  34. }
  35. func TestGetAPIServerProbeAddress(t *testing.T) {
  36. tests := []struct {
  37. desc string
  38. endpoint *kubeadmapi.APIEndpoint
  39. expected string
  40. }{
  41. {
  42. desc: "nil endpoint returns 127.0.0.1",
  43. expected: "127.0.0.1",
  44. },
  45. {
  46. desc: "empty AdvertiseAddress endpoint returns 127.0.0.1",
  47. endpoint: &kubeadmapi.APIEndpoint{},
  48. expected: "127.0.0.1",
  49. },
  50. {
  51. desc: "filled in AdvertiseAddress endpoint returns it",
  52. endpoint: &kubeadmapi.APIEndpoint{
  53. AdvertiseAddress: "10.10.10.10",
  54. },
  55. expected: "10.10.10.10",
  56. },
  57. }
  58. for _, test := range tests {
  59. t.Run(test.desc, func(t *testing.T) {
  60. actual := GetAPIServerProbeAddress(test.endpoint)
  61. if actual != test.expected {
  62. t.Errorf("Unexpected result from GetAPIServerProbeAddress:\n\texpected: %s\n\tactual: %s", test.expected, actual)
  63. }
  64. })
  65. }
  66. }
  67. func TestGetControllerManagerProbeAddress(t *testing.T) {
  68. tests := []struct {
  69. desc string
  70. cfg *kubeadmapi.ClusterConfiguration
  71. expected string
  72. }{
  73. {
  74. desc: "no controller manager extra args leads to 127.0.0.1 being used",
  75. cfg: &kubeadmapi.ClusterConfiguration{
  76. ControllerManager: kubeadmapi.ControlPlaneComponent{
  77. ExtraArgs: map[string]string{},
  78. },
  79. },
  80. expected: "127.0.0.1",
  81. },
  82. {
  83. desc: "setting controller manager extra address arg to something acknowledges it",
  84. cfg: &kubeadmapi.ClusterConfiguration{
  85. ControllerManager: kubeadmapi.ControlPlaneComponent{
  86. ExtraArgs: map[string]string{
  87. kubeControllerManagerAddressArg: "10.10.10.10",
  88. },
  89. },
  90. },
  91. expected: "10.10.10.10",
  92. },
  93. }
  94. for _, test := range tests {
  95. t.Run(test.desc, func(t *testing.T) {
  96. actual := GetControllerManagerProbeAddress(test.cfg)
  97. if actual != test.expected {
  98. t.Errorf("Unexpected result from GetControllerManagerProbeAddress:\n\texpected: %s\n\tactual: %s", test.expected, actual)
  99. }
  100. })
  101. }
  102. }
  103. func TestEtcdProbe(t *testing.T) {
  104. var tests = []struct {
  105. name string
  106. cfg *kubeadmapi.Etcd
  107. port int
  108. certsDir string
  109. cacert string
  110. cert string
  111. key string
  112. expected string
  113. }{
  114. {
  115. name: "valid etcd probe using listen-client-urls IPv4 addresses",
  116. cfg: &kubeadmapi.Etcd{
  117. Local: &kubeadmapi.LocalEtcd{
  118. ExtraArgs: map[string]string{
  119. "listen-client-urls": "http://1.2.3.4:2379,http://4.3.2.1:2379"},
  120. },
  121. },
  122. port: 1,
  123. certsDir: "secretsA",
  124. cacert: "ca1",
  125. cert: "cert1",
  126. key: "key1",
  127. expected: "ETCDCTL_API=3 etcdctl --endpoints=https://[1.2.3.4]:1 --cacert=secretsA/ca1 --cert=secretsA/cert1 --key=secretsA/key1 get foo",
  128. },
  129. {
  130. name: "valid etcd probe using listen-client-urls unspecified IPv6 address",
  131. cfg: &kubeadmapi.Etcd{
  132. Local: &kubeadmapi.LocalEtcd{
  133. ExtraArgs: map[string]string{
  134. "listen-client-urls": "http://[0:0:0:0:0:0:0:0]:2379"},
  135. },
  136. },
  137. port: 1,
  138. certsDir: "secretsB",
  139. cacert: "ca2",
  140. cert: "cert2",
  141. key: "key2",
  142. expected: "ETCDCTL_API=3 etcdctl --endpoints=https://[::1]:1 --cacert=secretsB/ca2 --cert=secretsB/cert2 --key=secretsB/key2 get foo",
  143. },
  144. {
  145. name: "valid etcd probe using listen-client-urls unspecified IPv6 address 2",
  146. cfg: &kubeadmapi.Etcd{
  147. Local: &kubeadmapi.LocalEtcd{
  148. ExtraArgs: map[string]string{
  149. "listen-client-urls": "http://[::0:0]:2379"},
  150. },
  151. },
  152. port: 1,
  153. certsDir: "secretsB",
  154. cacert: "ca2",
  155. cert: "cert2",
  156. key: "key2",
  157. expected: "ETCDCTL_API=3 etcdctl --endpoints=https://[::1]:1 --cacert=secretsB/ca2 --cert=secretsB/cert2 --key=secretsB/key2 get foo",
  158. },
  159. {
  160. name: "valid etcd probe using listen-client-urls unspecified IPv6 address 3",
  161. cfg: &kubeadmapi.Etcd{
  162. Local: &kubeadmapi.LocalEtcd{
  163. ExtraArgs: map[string]string{
  164. "listen-client-urls": "http://[::]:2379"},
  165. },
  166. },
  167. port: 1,
  168. certsDir: "secretsB",
  169. cacert: "ca2",
  170. cert: "cert2",
  171. key: "key2",
  172. expected: "ETCDCTL_API=3 etcdctl --endpoints=https://[::1]:1 --cacert=secretsB/ca2 --cert=secretsB/cert2 --key=secretsB/key2 get foo",
  173. },
  174. {
  175. name: "valid etcd probe using listen-client-urls unspecified IPv4 address",
  176. cfg: &kubeadmapi.Etcd{
  177. Local: &kubeadmapi.LocalEtcd{
  178. ExtraArgs: map[string]string{
  179. "listen-client-urls": "http://1.2.3.4:2379,http://4.3.2.1:2379"},
  180. },
  181. },
  182. port: 1,
  183. certsDir: "secretsA",
  184. cacert: "ca1",
  185. cert: "cert1",
  186. key: "key1",
  187. expected: "ETCDCTL_API=3 etcdctl --endpoints=https://[1.2.3.4]:1 --cacert=secretsA/ca1 --cert=secretsA/cert1 --key=secretsA/key1 get foo",
  188. },
  189. {
  190. name: "valid etcd probe using listen-client-urls IPv6 addresses",
  191. cfg: &kubeadmapi.Etcd{
  192. Local: &kubeadmapi.LocalEtcd{
  193. ExtraArgs: map[string]string{
  194. "listen-client-urls": "http://[2001:db8::1]:2379,http://[2001:db8::2]:2379"},
  195. },
  196. },
  197. port: 1,
  198. certsDir: "secretsB",
  199. cacert: "ca2",
  200. cert: "cert2",
  201. key: "key2",
  202. expected: "ETCDCTL_API=3 etcdctl --endpoints=https://[2001:db8::1]:1 --cacert=secretsB/ca2 --cert=secretsB/cert2 --key=secretsB/key2 get foo",
  203. },
  204. {
  205. name: "valid IPv4 etcd probe using hostname for listen-client-urls",
  206. cfg: &kubeadmapi.Etcd{
  207. Local: &kubeadmapi.LocalEtcd{
  208. ExtraArgs: map[string]string{
  209. "listen-client-urls": "http://localhost:2379"},
  210. },
  211. },
  212. port: 1,
  213. certsDir: "secretsC",
  214. cacert: "ca3",
  215. cert: "cert3",
  216. key: "key3",
  217. expected: "ETCDCTL_API=3 etcdctl --endpoints=https://[127.0.0.1]:1 --cacert=secretsC/ca3 --cert=secretsC/cert3 --key=secretsC/key3 get foo",
  218. },
  219. }
  220. for _, rt := range tests {
  221. t.Run(rt.name, func(t *testing.T) {
  222. actual := EtcdProbe(rt.cfg, rt.port, rt.certsDir, rt.cacert, rt.cert, rt.key)
  223. if actual.Handler.Exec.Command[2] != rt.expected {
  224. t.Errorf("%s test case failed:\n\texpected: %s\n\t actual: %s",
  225. rt.name, rt.expected,
  226. actual.Handler.Exec.Command[2])
  227. }
  228. })
  229. }
  230. }
  231. func TestComponentPod(t *testing.T) {
  232. var tests = []struct {
  233. name string
  234. expected v1.Pod
  235. }{
  236. {
  237. name: "foo",
  238. expected: v1.Pod{
  239. TypeMeta: metav1.TypeMeta{
  240. APIVersion: "v1",
  241. Kind: "Pod",
  242. },
  243. ObjectMeta: metav1.ObjectMeta{
  244. Name: "foo",
  245. Namespace: "kube-system",
  246. Labels: map[string]string{"component": "foo", "tier": "control-plane"},
  247. },
  248. Spec: v1.PodSpec{
  249. Containers: []v1.Container{
  250. {
  251. Name: "foo",
  252. },
  253. },
  254. PriorityClassName: "system-cluster-critical",
  255. HostNetwork: true,
  256. Volumes: []v1.Volume{},
  257. },
  258. },
  259. },
  260. }
  261. for _, rt := range tests {
  262. t.Run(rt.name, func(t *testing.T) {
  263. c := v1.Container{Name: rt.name}
  264. actual := ComponentPod(c, map[string]v1.Volume{})
  265. if !reflect.DeepEqual(rt.expected, actual) {
  266. t.Errorf(
  267. "failed componentPod:\n\texpected: %v\n\t actual: %v",
  268. rt.expected,
  269. actual,
  270. )
  271. }
  272. })
  273. }
  274. }
  275. func TestNewVolume(t *testing.T) {
  276. hostPathDirectoryOrCreate := v1.HostPathDirectoryOrCreate
  277. var tests = []struct {
  278. name string
  279. path string
  280. expected v1.Volume
  281. pathType *v1.HostPathType
  282. }{
  283. {
  284. name: "foo",
  285. path: "/etc/foo",
  286. expected: v1.Volume{
  287. Name: "foo",
  288. VolumeSource: v1.VolumeSource{
  289. HostPath: &v1.HostPathVolumeSource{
  290. Path: "/etc/foo",
  291. Type: &hostPathDirectoryOrCreate,
  292. },
  293. },
  294. },
  295. pathType: &hostPathDirectoryOrCreate,
  296. },
  297. }
  298. for _, rt := range tests {
  299. t.Run(rt.name, func(t *testing.T) {
  300. actual := NewVolume(rt.name, rt.path, rt.pathType)
  301. if !reflect.DeepEqual(actual, rt.expected) {
  302. t.Errorf(
  303. "failed newVolume:\n\texpected: %v\n\t actual: %v",
  304. rt.expected,
  305. actual,
  306. )
  307. }
  308. })
  309. }
  310. }
  311. func TestNewVolumeMount(t *testing.T) {
  312. var tests = []struct {
  313. name string
  314. path string
  315. ro bool
  316. expected v1.VolumeMount
  317. }{
  318. {
  319. name: "foo",
  320. path: "/etc/foo",
  321. ro: false,
  322. expected: v1.VolumeMount{
  323. Name: "foo",
  324. MountPath: "/etc/foo",
  325. ReadOnly: false,
  326. },
  327. },
  328. {
  329. name: "bar",
  330. path: "/etc/foo/bar",
  331. ro: true,
  332. expected: v1.VolumeMount{
  333. Name: "bar",
  334. MountPath: "/etc/foo/bar",
  335. ReadOnly: true,
  336. },
  337. },
  338. }
  339. for _, rt := range tests {
  340. t.Run(rt.name, func(t *testing.T) {
  341. actual := NewVolumeMount(rt.name, rt.path, rt.ro)
  342. if !reflect.DeepEqual(actual, rt.expected) {
  343. t.Errorf(
  344. "failed newVolumeMount:\n\texpected: %v\n\t actual: %v",
  345. rt.expected,
  346. actual,
  347. )
  348. }
  349. })
  350. }
  351. }
  352. func TestVolumeMapToSlice(t *testing.T) {
  353. testVolumes := map[string]v1.Volume{
  354. "foo": {
  355. Name: "foo",
  356. },
  357. "bar": {
  358. Name: "bar",
  359. },
  360. }
  361. volumeSlice := VolumeMapToSlice(testVolumes)
  362. if len(volumeSlice) != 2 {
  363. t.Errorf("Expected slice length of 1, got %d", len(volumeSlice))
  364. }
  365. if volumeSlice[0].Name != "bar" {
  366. t.Errorf("Expected first volume name \"bar\", got %s", volumeSlice[0].Name)
  367. }
  368. if volumeSlice[1].Name != "foo" {
  369. t.Errorf("Expected second volume name \"foo\", got %s", volumeSlice[1].Name)
  370. }
  371. }
  372. func TestVolumeMountMapToSlice(t *testing.T) {
  373. testVolumeMounts := map[string]v1.VolumeMount{
  374. "foo": {
  375. Name: "foo",
  376. },
  377. "bar": {
  378. Name: "bar",
  379. },
  380. }
  381. volumeMountSlice := VolumeMountMapToSlice(testVolumeMounts)
  382. if len(volumeMountSlice) != 2 {
  383. t.Errorf("Expected slice length of 1, got %d", len(volumeMountSlice))
  384. }
  385. if volumeMountSlice[0].Name != "bar" {
  386. t.Errorf("Expected first volume mount name \"bar\", got %s", volumeMountSlice[0].Name)
  387. }
  388. if volumeMountSlice[1].Name != "foo" {
  389. t.Errorf("Expected second volume name \"foo\", got %s", volumeMountSlice[1].Name)
  390. }
  391. }
  392. func TestGetExtraParameters(t *testing.T) {
  393. var tests = []struct {
  394. name string
  395. overrides map[string]string
  396. defaults map[string]string
  397. expected []string
  398. }{
  399. {
  400. name: "with admission-control default NamespaceLifecycle",
  401. overrides: map[string]string{
  402. "admission-control": "NamespaceLifecycle,LimitRanger",
  403. },
  404. defaults: map[string]string{
  405. "admission-control": "NamespaceLifecycle",
  406. "insecure-bind-address": "127.0.0.1",
  407. "allow-privileged": "true",
  408. },
  409. expected: []string{
  410. "--admission-control=NamespaceLifecycle,LimitRanger",
  411. "--insecure-bind-address=127.0.0.1",
  412. "--allow-privileged=true",
  413. },
  414. },
  415. {
  416. name: "without admission-control default",
  417. overrides: map[string]string{
  418. "admission-control": "NamespaceLifecycle,LimitRanger",
  419. },
  420. defaults: map[string]string{
  421. "insecure-bind-address": "127.0.0.1",
  422. "allow-privileged": "true",
  423. },
  424. expected: []string{
  425. "--admission-control=NamespaceLifecycle,LimitRanger",
  426. "--insecure-bind-address=127.0.0.1",
  427. "--allow-privileged=true",
  428. },
  429. },
  430. }
  431. for _, rt := range tests {
  432. t.Run(rt.name, func(t *testing.T) {
  433. actual := GetExtraParameters(rt.overrides, rt.defaults)
  434. sort.Strings(actual)
  435. sort.Strings(rt.expected)
  436. if !reflect.DeepEqual(actual, rt.expected) {
  437. t.Errorf("failed getExtraParameters:\nexpected:\n%v\nsaw:\n%v", rt.expected, actual)
  438. }
  439. })
  440. }
  441. }
  442. const (
  443. validPod = `
  444. apiVersion: v1
  445. kind: Pod
  446. metadata:
  447. labels:
  448. component: etcd
  449. tier: control-plane
  450. name: etcd
  451. namespace: kube-system
  452. spec:
  453. containers:
  454. - image: gcr.io/google_containers/etcd-amd64:3.1.11
  455. status: {}
  456. `
  457. invalidPod = `---{ broken yaml @@@`
  458. )
  459. func TestReadStaticPodFromDisk(t *testing.T) {
  460. tests := []struct {
  461. description string
  462. podYaml string
  463. expectErr bool
  464. writeManifest bool
  465. }{
  466. {
  467. description: "valid pod is marshaled",
  468. podYaml: validPod,
  469. writeManifest: true,
  470. expectErr: false,
  471. },
  472. {
  473. description: "invalid pod fails to unmarshal",
  474. podYaml: invalidPod,
  475. writeManifest: true,
  476. expectErr: true,
  477. },
  478. {
  479. description: "non-existent file returns error",
  480. podYaml: ``,
  481. writeManifest: false,
  482. expectErr: true,
  483. },
  484. }
  485. for _, rt := range tests {
  486. t.Run(rt.description, func(t *testing.T) {
  487. tmpdir := testutil.SetupTempDir(t)
  488. defer os.RemoveAll(tmpdir)
  489. manifestPath := filepath.Join(tmpdir, "pod.yaml")
  490. if rt.writeManifest {
  491. err := ioutil.WriteFile(manifestPath, []byte(rt.podYaml), 0644)
  492. if err != nil {
  493. t.Fatalf("Failed to write pod manifest\n%s\n\tfatal error: %v", rt.description, err)
  494. }
  495. }
  496. _, actualErr := ReadStaticPodFromDisk(manifestPath)
  497. if (actualErr != nil) != rt.expectErr {
  498. t.Errorf(
  499. "ReadStaticPodFromDisk failed\n%s\n\texpected error: %t\n\tgot: %t\n\tactual error: %v",
  500. rt.description,
  501. rt.expectErr,
  502. (actualErr != nil),
  503. actualErr,
  504. )
  505. }
  506. })
  507. }
  508. }
  509. func TestManifestFilesAreEqual(t *testing.T) {
  510. var tests = []struct {
  511. description string
  512. podYamls []string
  513. expectedResult bool
  514. expectErr bool
  515. }{
  516. {
  517. description: "manifests are equal",
  518. podYamls: []string{validPod, validPod},
  519. expectedResult: true,
  520. expectErr: false,
  521. },
  522. {
  523. description: "manifests are not equal",
  524. podYamls: []string{validPod, validPod + "\n"},
  525. expectedResult: false,
  526. expectErr: false,
  527. },
  528. {
  529. description: "first manifest doesn't exist",
  530. podYamls: []string{validPod, ""},
  531. expectedResult: false,
  532. expectErr: true,
  533. },
  534. {
  535. description: "second manifest doesn't exist",
  536. podYamls: []string{"", validPod},
  537. expectedResult: false,
  538. expectErr: true,
  539. },
  540. }
  541. for _, rt := range tests {
  542. t.Run(rt.description, func(t *testing.T) {
  543. tmpdir := testutil.SetupTempDir(t)
  544. defer os.RemoveAll(tmpdir)
  545. // write 2 manifests
  546. for i := 0; i < 2; i++ {
  547. if rt.podYamls[i] != "" {
  548. manifestPath := filepath.Join(tmpdir, strconv.Itoa(i)+".yaml")
  549. err := ioutil.WriteFile(manifestPath, []byte(rt.podYamls[i]), 0644)
  550. if err != nil {
  551. t.Fatalf("Failed to write manifest file\n%s\n\tfatal error: %v", rt.description, err)
  552. }
  553. }
  554. }
  555. // compare them
  556. result, actualErr := ManifestFilesAreEqual(filepath.Join(tmpdir, "0.yaml"), filepath.Join(tmpdir, "1.yaml"))
  557. if result != rt.expectedResult {
  558. t.Errorf(
  559. "ManifestFilesAreEqual failed\n%s\nexpected result: %t\nactual result: %t",
  560. rt.description,
  561. rt.expectedResult,
  562. result,
  563. )
  564. }
  565. if (actualErr != nil) != rt.expectErr {
  566. t.Errorf(
  567. "ManifestFilesAreEqual failed\n%s\n\texpected error: %t\n\tgot: %t\n\tactual error: %v",
  568. rt.description,
  569. rt.expectErr,
  570. (actualErr != nil),
  571. actualErr,
  572. )
  573. }
  574. })
  575. }
  576. }