file_linux_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. // +build linux
  2. /*
  3. Copyright 2016 The Kubernetes Authors.
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. */
  14. package config
  15. import (
  16. "fmt"
  17. "io"
  18. "os"
  19. "path/filepath"
  20. "sync"
  21. "testing"
  22. "time"
  23. "k8s.io/api/core/v1"
  24. apiequality "k8s.io/apimachinery/pkg/api/equality"
  25. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  26. "k8s.io/apimachinery/pkg/runtime"
  27. "k8s.io/apimachinery/pkg/types"
  28. "k8s.io/apimachinery/pkg/util/wait"
  29. clientscheme "k8s.io/client-go/kubernetes/scheme"
  30. api "k8s.io/kubernetes/pkg/apis/core"
  31. k8s_api_v1 "k8s.io/kubernetes/pkg/apis/core/v1"
  32. "k8s.io/kubernetes/pkg/apis/core/validation"
  33. kubetypes "k8s.io/kubernetes/pkg/kubelet/types"
  34. "k8s.io/kubernetes/pkg/securitycontext"
  35. )
  36. func TestExtractFromNonExistentFile(t *testing.T) {
  37. ch := make(chan interface{}, 1)
  38. lw := newSourceFile("/some/fake/file", "localhost", time.Millisecond, ch)
  39. err := lw.doWatch()
  40. if err == nil {
  41. t.Errorf("Expected error")
  42. }
  43. }
  44. func TestUpdateOnNonExistentFile(t *testing.T) {
  45. ch := make(chan interface{})
  46. NewSourceFile("random_non_existent_path", "localhost", time.Millisecond, ch)
  47. select {
  48. case got := <-ch:
  49. update := got.(kubetypes.PodUpdate)
  50. expected := CreatePodUpdate(kubetypes.SET, kubetypes.FileSource)
  51. if !apiequality.Semantic.DeepDerivative(expected, update) {
  52. t.Fatalf("expected %#v, Got %#v", expected, update)
  53. }
  54. case <-time.After(wait.ForeverTestTimeout):
  55. t.Fatalf("expected update, timeout instead")
  56. }
  57. }
  58. func TestReadPodsFromFileExistAlready(t *testing.T) {
  59. hostname := types.NodeName("random-test-hostname")
  60. var testCases = getTestCases(hostname)
  61. for _, testCase := range testCases {
  62. func() {
  63. dirName, err := mkTempDir("file-test")
  64. if err != nil {
  65. t.Fatalf("unable to create temp dir: %v", err)
  66. }
  67. defer os.RemoveAll(dirName)
  68. file := testCase.writeToFile(dirName, "test_pod_manifest", t)
  69. ch := make(chan interface{})
  70. NewSourceFile(file, hostname, time.Millisecond, ch)
  71. select {
  72. case got := <-ch:
  73. update := got.(kubetypes.PodUpdate)
  74. for _, pod := range update.Pods {
  75. // TODO: remove the conversion when validation is performed on versioned objects.
  76. internalPod := &api.Pod{}
  77. if err := k8s_api_v1.Convert_v1_Pod_To_core_Pod(pod, internalPod, nil); err != nil {
  78. t.Fatalf("%s: Cannot convert pod %#v, %#v", testCase.desc, pod, err)
  79. }
  80. if errs := validation.ValidatePod(internalPod); len(errs) > 0 {
  81. t.Fatalf("%s: Invalid pod %#v, %#v", testCase.desc, internalPod, errs)
  82. }
  83. }
  84. if !apiequality.Semantic.DeepEqual(testCase.expected, update) {
  85. t.Fatalf("%s: Expected %#v, Got %#v", testCase.desc, testCase.expected, update)
  86. }
  87. case <-time.After(wait.ForeverTestTimeout):
  88. t.Fatalf("%s: Expected update, timeout instead", testCase.desc)
  89. }
  90. }()
  91. }
  92. }
  93. var (
  94. testCases = []struct {
  95. watchDir bool
  96. symlink bool
  97. }{
  98. {true, true},
  99. {true, false},
  100. {false, true},
  101. {false, false},
  102. }
  103. )
  104. func TestWatchFileAdded(t *testing.T) {
  105. for _, testCase := range testCases {
  106. watchFileAdded(testCase.watchDir, testCase.symlink, t)
  107. }
  108. }
  109. func TestWatchFileChanged(t *testing.T) {
  110. for _, testCase := range testCases {
  111. watchFileChanged(testCase.watchDir, testCase.symlink, t)
  112. }
  113. }
  114. type testCase struct {
  115. lock *sync.Mutex
  116. desc string
  117. pod runtime.Object
  118. expected kubetypes.PodUpdate
  119. }
  120. func getTestCases(hostname types.NodeName) []*testCase {
  121. grace := int64(30)
  122. enableServiceLinks := v1.DefaultEnableServiceLinks
  123. return []*testCase{
  124. {
  125. lock: &sync.Mutex{},
  126. desc: "Simple pod",
  127. pod: &v1.Pod{
  128. TypeMeta: metav1.TypeMeta{
  129. Kind: "Pod",
  130. APIVersion: "",
  131. },
  132. ObjectMeta: metav1.ObjectMeta{
  133. Name: "test",
  134. UID: "12345",
  135. Namespace: "mynamespace",
  136. },
  137. Spec: v1.PodSpec{
  138. Containers: []v1.Container{{Name: "image", Image: "test/image", SecurityContext: securitycontext.ValidSecurityContextWithContainerDefaults()}},
  139. SecurityContext: &v1.PodSecurityContext{},
  140. SchedulerName: api.DefaultSchedulerName,
  141. },
  142. Status: v1.PodStatus{
  143. Phase: v1.PodPending,
  144. },
  145. },
  146. expected: CreatePodUpdate(kubetypes.SET, kubetypes.FileSource, &v1.Pod{
  147. ObjectMeta: metav1.ObjectMeta{
  148. Name: "test-" + string(hostname),
  149. UID: "12345",
  150. Namespace: "mynamespace",
  151. Annotations: map[string]string{kubetypes.ConfigHashAnnotationKey: "12345"},
  152. SelfLink: getSelfLink("test-"+string(hostname), "mynamespace"),
  153. },
  154. Spec: v1.PodSpec{
  155. NodeName: string(hostname),
  156. RestartPolicy: v1.RestartPolicyAlways,
  157. DNSPolicy: v1.DNSClusterFirst,
  158. TerminationGracePeriodSeconds: &grace,
  159. Tolerations: []v1.Toleration{{
  160. Operator: "Exists",
  161. Effect: "NoExecute",
  162. }},
  163. Containers: []v1.Container{{
  164. Name: "image",
  165. Image: "test/image",
  166. TerminationMessagePath: "/dev/termination-log",
  167. ImagePullPolicy: "Always",
  168. SecurityContext: securitycontext.ValidSecurityContextWithContainerDefaults(),
  169. TerminationMessagePolicy: v1.TerminationMessageReadFile,
  170. }},
  171. SecurityContext: &v1.PodSecurityContext{},
  172. SchedulerName: api.DefaultSchedulerName,
  173. EnableServiceLinks: &enableServiceLinks,
  174. },
  175. Status: v1.PodStatus{
  176. Phase: v1.PodPending,
  177. },
  178. }),
  179. },
  180. }
  181. }
  182. func (tc *testCase) writeToFile(dir, name string, t *testing.T) string {
  183. fileContents, err := runtime.Encode(clientscheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), tc.pod)
  184. if err != nil {
  185. t.Fatalf("%s: error in encoding the pod: %v", tc.desc, err)
  186. }
  187. fileName := filepath.Join(dir, name)
  188. if err := writeFile(fileName, []byte(fileContents)); err != nil {
  189. t.Fatalf("unable to write test file %#v", err)
  190. }
  191. return fileName
  192. }
  193. func createSymbolicLink(link, target, name string, t *testing.T) string {
  194. linkName := filepath.Join(link, name)
  195. linkedFile := filepath.Join(target, name)
  196. err := os.Symlink(linkedFile, linkName)
  197. if err != nil {
  198. t.Fatalf("unexpected error when create symbolic link: %v", err)
  199. }
  200. return linkName
  201. }
  202. func watchFileAdded(watchDir bool, symlink bool, t *testing.T) {
  203. hostname := types.NodeName("random-test-hostname")
  204. var testCases = getTestCases(hostname)
  205. fileNamePre := "test_pod_manifest"
  206. for index, testCase := range testCases {
  207. func() {
  208. dirName, err := mkTempDir("dir-test")
  209. if err != nil {
  210. t.Fatalf("unable to create temp dir: %v", err)
  211. }
  212. defer removeAll(dirName, t)
  213. fileName := fmt.Sprintf("%s_%d", fileNamePre, index)
  214. var linkedDirName string
  215. if symlink {
  216. linkedDirName, err = mkTempDir("linked-dir-test")
  217. if err != nil {
  218. t.Fatalf("unable to create temp dir for linked files: %v", err)
  219. }
  220. defer removeAll(linkedDirName, t)
  221. createSymbolicLink(dirName, linkedDirName, fileName, t)
  222. }
  223. ch := make(chan interface{})
  224. if watchDir {
  225. NewSourceFile(dirName, hostname, 100*time.Millisecond, ch)
  226. } else {
  227. NewSourceFile(filepath.Join(dirName, fileName), hostname, 100*time.Millisecond, ch)
  228. }
  229. expectEmptyUpdate(t, ch)
  230. addFile := func() {
  231. // Add a file
  232. if symlink {
  233. testCase.writeToFile(linkedDirName, fileName, t)
  234. return
  235. }
  236. testCase.writeToFile(dirName, fileName, t)
  237. }
  238. go addFile()
  239. // For !watchDir: expect an update by SourceFile.reloadConfig().
  240. // For watchDir: expect at least one update from CREATE & MODIFY inotify event.
  241. // Shouldn't expect two updates from CREATE & MODIFY because CREATE doesn't guarantee file written.
  242. // In that case no update will be sent from CREATE event.
  243. expectUpdate(t, ch, testCase)
  244. }()
  245. }
  246. }
  247. func watchFileChanged(watchDir bool, symlink bool, t *testing.T) {
  248. hostname := types.NodeName("random-test-hostname")
  249. var testCases = getTestCases(hostname)
  250. fileNamePre := "test_pod_manifest"
  251. for index, testCase := range testCases {
  252. func() {
  253. dirName, err := mkTempDir("dir-test")
  254. fileName := fmt.Sprintf("%s_%d", fileNamePre, index)
  255. if err != nil {
  256. t.Fatalf("unable to create temp dir: %v", err)
  257. }
  258. defer removeAll(dirName, t)
  259. var linkedDirName string
  260. if symlink {
  261. linkedDirName, err = mkTempDir("linked-dir-test")
  262. if err != nil {
  263. t.Fatalf("unable to create temp dir for linked files: %v", err)
  264. }
  265. defer removeAll(linkedDirName, t)
  266. createSymbolicLink(dirName, linkedDirName, fileName, t)
  267. }
  268. var file string
  269. ch := make(chan interface{})
  270. func() {
  271. testCase.lock.Lock()
  272. defer testCase.lock.Unlock()
  273. if symlink {
  274. file = testCase.writeToFile(linkedDirName, fileName, t)
  275. return
  276. }
  277. file = testCase.writeToFile(dirName, fileName, t)
  278. }()
  279. if watchDir {
  280. NewSourceFile(dirName, hostname, 100*time.Millisecond, ch)
  281. } else {
  282. NewSourceFile(file, hostname, 100*time.Millisecond, ch)
  283. }
  284. // expect an update by SourceFile.resetStoreFromPath()
  285. expectUpdate(t, ch, testCase)
  286. changeFile := func() {
  287. // Edit the file content
  288. testCase.lock.Lock()
  289. defer testCase.lock.Unlock()
  290. pod := testCase.pod.(*v1.Pod)
  291. pod.Spec.Containers[0].Name = "image2"
  292. testCase.expected.Pods[0].Spec.Containers[0].Name = "image2"
  293. if symlink {
  294. file = testCase.writeToFile(linkedDirName, fileName, t)
  295. return
  296. }
  297. file = testCase.writeToFile(dirName, fileName, t)
  298. }
  299. go changeFile()
  300. // expect an update by MODIFY inotify event
  301. expectUpdate(t, ch, testCase)
  302. if watchDir {
  303. go changeFileName(dirName, fileName, fileName+"_ch", t)
  304. // expect an update by MOVED_FROM inotify event cause changing file name
  305. expectEmptyUpdate(t, ch)
  306. // expect an update by MOVED_TO inotify event cause changing file name
  307. expectUpdate(t, ch, testCase)
  308. }
  309. }()
  310. }
  311. }
  312. func expectUpdate(t *testing.T, ch chan interface{}, testCase *testCase) {
  313. timer := time.After(5 * time.Second)
  314. for {
  315. select {
  316. case got := <-ch:
  317. update := got.(kubetypes.PodUpdate)
  318. if len(update.Pods) == 0 {
  319. // filter out the empty updates from reading a non-existing path
  320. continue
  321. }
  322. for _, pod := range update.Pods {
  323. // TODO: remove the conversion when validation is performed on versioned objects.
  324. internalPod := &api.Pod{}
  325. if err := k8s_api_v1.Convert_v1_Pod_To_core_Pod(pod, internalPod, nil); err != nil {
  326. t.Fatalf("%s: Cannot convert pod %#v, %#v", testCase.desc, pod, err)
  327. }
  328. if errs := validation.ValidatePod(internalPod); len(errs) > 0 {
  329. t.Fatalf("%s: Invalid pod %#v, %#v", testCase.desc, internalPod, errs)
  330. }
  331. }
  332. testCase.lock.Lock()
  333. defer testCase.lock.Unlock()
  334. if !apiequality.Semantic.DeepEqual(testCase.expected, update) {
  335. t.Fatalf("%s: Expected: %#v, Got: %#v", testCase.desc, testCase.expected, update)
  336. }
  337. return
  338. case <-timer:
  339. t.Fatalf("%s: Expected update, timeout instead", testCase.desc)
  340. }
  341. }
  342. }
  343. func expectEmptyUpdate(t *testing.T, ch chan interface{}) {
  344. timer := time.After(5 * time.Second)
  345. for {
  346. select {
  347. case got := <-ch:
  348. update := got.(kubetypes.PodUpdate)
  349. if len(update.Pods) != 0 {
  350. t.Fatalf("expected empty update, got %#v", update)
  351. }
  352. return
  353. case <-timer:
  354. t.Fatalf("expected empty update, timeout instead")
  355. }
  356. }
  357. }
  358. func writeFile(filename string, data []byte) error {
  359. f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE, 0666)
  360. if err != nil {
  361. return err
  362. }
  363. n, err := f.Write(data)
  364. if err == nil && n < len(data) {
  365. err = io.ErrShortWrite
  366. }
  367. if err1 := f.Close(); err == nil {
  368. err = err1
  369. }
  370. return err
  371. }
  372. func changeFileName(dir, from, to string, t *testing.T) {
  373. fromPath := filepath.Join(dir, from)
  374. toPath := filepath.Join(dir, to)
  375. if err := os.Rename(fromPath, toPath); err != nil {
  376. t.Errorf("Fail to change file name: %s", err)
  377. }
  378. }