PageRenderTime 49ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/pkg/volume/flexvolume/flexvolume_test.go

https://gitlab.com/CORP-RESELLER/kubernetes
Go | 417 lines | 374 code | 27 blank | 16 comment | 106 complexity | 55bc792db1e830f625ec1b501d5b2ceb MD5 | raw file
  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 flexvolume
  14. import (
  15. "bytes"
  16. "encoding/base64"
  17. "fmt"
  18. "os"
  19. "path"
  20. "testing"
  21. "text/template"
  22. "k8s.io/kubernetes/pkg/api"
  23. "k8s.io/kubernetes/pkg/types"
  24. "k8s.io/kubernetes/pkg/util/exec"
  25. "k8s.io/kubernetes/pkg/util/mount"
  26. utiltesting "k8s.io/kubernetes/pkg/util/testing"
  27. "k8s.io/kubernetes/pkg/volume"
  28. volumetest "k8s.io/kubernetes/pkg/volume/testing"
  29. )
  30. const execScriptTempl1 = `#!/bin/bash
  31. if [ "$1" == "init" -a $# -eq 1 ]; then
  32. echo -n '{
  33. "status": "Success"
  34. }'
  35. exit 0
  36. fi
  37. PATH=$2
  38. if [ "$1" == "attach" -a $# -eq 2 ]; then
  39. echo -n '{
  40. "device": "{{.DevicePath}}",
  41. "status": "Success"
  42. }'
  43. exit 0
  44. elif [ "$1" == "detach" -a $# -eq 2 ]; then
  45. echo -n '{
  46. "status": "Success"
  47. }'
  48. exit 0
  49. elif [ "$1" == "mount" -a $# -eq 4 ]; then
  50. echo -n '{
  51. "status": "Not supported"
  52. }'
  53. exit 0
  54. elif [ "$1" == "unmount" -a $# -eq 2 ]; then
  55. echo -n '{
  56. "status": "Not supported"
  57. }'
  58. exit 0
  59. fi
  60. echo -n '{
  61. "status": "Failure",
  62. "reason": "Invalid usage"
  63. }'
  64. exit 1
  65. # Direct the arguments to a file to be tested against later
  66. echo -n $@ &> {{.OutputFile}}
  67. `
  68. const execScriptTempl2 = `#!/bin/bash
  69. if [ "$1" == "init" -a $# -eq 1 ]; then
  70. echo -n '{
  71. "status": "Success"
  72. }'
  73. exit 0
  74. fi
  75. if [ "$1" == "attach" -a $# -eq 2 ]; then
  76. echo -n '{
  77. "status": "Not supported"
  78. }'
  79. exit 0
  80. elif [ "$1" == "detach" -a $# -eq 2 ]; then
  81. echo -n '{
  82. "status": "Not supported"
  83. }'
  84. exit 0
  85. elif [ "$1" == "mount" -a $# -eq 4 ]; then
  86. PATH=$2
  87. /bin/mkdir -p $PATH
  88. if [ $? -ne 0 ]; then
  89. echo -n '{
  90. "status": "Failure",
  91. "reason": "Failed to create $PATH"
  92. }'
  93. exit 1
  94. fi
  95. echo -n '{
  96. "status": "Success"
  97. }'
  98. exit 0
  99. elif [ "$1" == "unmount" -a $# -eq 2 ]; then
  100. PATH=$2
  101. /bin/rm -r $PATH
  102. if [ $? -ne 0 ]; then
  103. echo -n '{
  104. "status": "Failure",
  105. "reason": "Failed to cleanup $PATH"
  106. }'
  107. exit 1
  108. fi
  109. echo -n '{
  110. "status": "Success"
  111. }'
  112. exit 0
  113. fi
  114. echo -n '{
  115. "status": "Failure",
  116. "reason": "Invalid usage"
  117. }'
  118. exit 1
  119. # Direct the arguments to a file to be tested against later
  120. echo -n $@ &> {{.OutputFile}}
  121. `
  122. func installPluginUnderTest(t *testing.T, vendorName, plugName, tmpDir string, execScriptTempl string, execTemplateData *map[string]interface{}) {
  123. vendoredName := plugName
  124. if vendorName != "" {
  125. vendoredName = fmt.Sprintf("%s~%s", vendorName, plugName)
  126. }
  127. pluginDir := path.Join(tmpDir, vendoredName)
  128. err := os.MkdirAll(pluginDir, 0777)
  129. if err != nil {
  130. t.Errorf("Failed to create plugin: %v", err)
  131. }
  132. pluginExec := path.Join(pluginDir, plugName)
  133. f, err := os.Create(pluginExec)
  134. if err != nil {
  135. t.Errorf("Failed to install plugin")
  136. }
  137. err = f.Chmod(0777)
  138. if err != nil {
  139. t.Errorf("Failed to set exec perms on plugin")
  140. }
  141. if execTemplateData == nil {
  142. execTemplateData = &map[string]interface{}{
  143. "DevicePath": "/dev/sdx",
  144. "OutputFile": path.Join(pluginDir, plugName+".out"),
  145. }
  146. }
  147. tObj := template.Must(template.New("test").Parse(execScriptTempl))
  148. buf := &bytes.Buffer{}
  149. if err := tObj.Execute(buf, *execTemplateData); err != nil {
  150. t.Errorf("Error in executing script template - %v", err)
  151. }
  152. execScript := buf.String()
  153. _, err = f.WriteString(execScript)
  154. if err != nil {
  155. t.Errorf("Failed to write plugin exec")
  156. }
  157. f.Close()
  158. }
  159. func TestCanSupport(t *testing.T) {
  160. tmpDir, err := utiltesting.MkTmpdir("flexvolume_test")
  161. if err != nil {
  162. t.Fatalf("error creating temp dir: %v", err)
  163. }
  164. defer os.RemoveAll(tmpDir)
  165. plugMgr := volume.VolumePluginMgr{}
  166. installPluginUnderTest(t, "kubernetes.io", "fakeAttacher", tmpDir, execScriptTempl1, nil)
  167. plugMgr.InitPlugins(ProbeVolumePlugins(tmpDir), volumetest.NewFakeVolumeHost("fake", nil, nil, "" /* rootContext */))
  168. plugin, err := plugMgr.FindPluginByName("kubernetes.io/fakeAttacher")
  169. if err != nil {
  170. t.Errorf("Can't find the plugin by name")
  171. }
  172. if plugin.GetPluginName() != "kubernetes.io/fakeAttacher" {
  173. t.Errorf("Wrong name: %s", plugin.GetPluginName())
  174. }
  175. if !plugin.CanSupport(&volume.Spec{Volume: &api.Volume{VolumeSource: api.VolumeSource{FlexVolume: &api.FlexVolumeSource{Driver: "kubernetes.io/fakeAttacher"}}}}) {
  176. t.Errorf("Expected true")
  177. }
  178. if !plugin.CanSupport(&volume.Spec{PersistentVolume: &api.PersistentVolume{Spec: api.PersistentVolumeSpec{PersistentVolumeSource: api.PersistentVolumeSource{FlexVolume: &api.FlexVolumeSource{Driver: "kubernetes.io/fakeAttacher"}}}}}) {
  179. t.Errorf("Expected true")
  180. }
  181. if plugin.CanSupport(&volume.Spec{Volume: &api.Volume{VolumeSource: api.VolumeSource{}}}) {
  182. t.Errorf("Expected false")
  183. }
  184. }
  185. func TestGetAccessModes(t *testing.T) {
  186. tmpDir, err := utiltesting.MkTmpdir("flexvolume_test")
  187. if err != nil {
  188. t.Fatalf("error creating temp dir: %v", err)
  189. }
  190. defer os.RemoveAll(tmpDir)
  191. plugMgr := volume.VolumePluginMgr{}
  192. installPluginUnderTest(t, "kubernetes.io", "fakeAttacher", tmpDir, execScriptTempl1, nil)
  193. plugMgr.InitPlugins(ProbeVolumePlugins(tmpDir), volumetest.NewFakeVolumeHost(tmpDir, nil, nil, "" /* rootContext */))
  194. plugin, err := plugMgr.FindPersistentPluginByName("kubernetes.io/fakeAttacher")
  195. if err != nil {
  196. t.Fatalf("Can't find the plugin by name")
  197. }
  198. if !contains(plugin.GetAccessModes(), api.ReadWriteOnce) || !contains(plugin.GetAccessModes(), api.ReadOnlyMany) {
  199. t.Errorf("Expected two AccessModeTypes: %s and %s", api.ReadWriteOnce, api.ReadOnlyMany)
  200. }
  201. }
  202. func contains(modes []api.PersistentVolumeAccessMode, mode api.PersistentVolumeAccessMode) bool {
  203. for _, m := range modes {
  204. if m == mode {
  205. return true
  206. }
  207. }
  208. return false
  209. }
  210. func doTestPluginAttachDetach(t *testing.T, spec *volume.Spec, tmpDir string) {
  211. plugMgr := volume.VolumePluginMgr{}
  212. installPluginUnderTest(t, "kubernetes.io", "fakeAttacher", tmpDir, execScriptTempl1, nil)
  213. plugMgr.InitPlugins(ProbeVolumePlugins(tmpDir), volumetest.NewFakeVolumeHost(tmpDir, nil, nil, "" /* rootContext */))
  214. plugin, err := plugMgr.FindPluginByName("kubernetes.io/fakeAttacher")
  215. if err != nil {
  216. t.Errorf("Can't find the plugin by name")
  217. }
  218. fake := &mount.FakeMounter{}
  219. pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: types.UID("poduid")}}
  220. secretMap := make(map[string]string)
  221. secretMap["flexsecret"] = base64.StdEncoding.EncodeToString([]byte("foo"))
  222. mounter, err := plugin.(*flexVolumePlugin).newMounterInternal(spec, pod, &flexVolumeUtil{}, fake, exec.New(), secretMap)
  223. volumePath := mounter.GetPath()
  224. if err != nil {
  225. t.Errorf("Failed to make a new Mounter: %v", err)
  226. }
  227. if mounter == nil {
  228. t.Errorf("Got a nil Mounter")
  229. }
  230. path := mounter.GetPath()
  231. expectedPath := fmt.Sprintf("%s/pods/poduid/volumes/kubernetes.io~fakeAttacher/vol1", tmpDir)
  232. if path != expectedPath {
  233. t.Errorf("Unexpected path, expected %q, got: %q", expectedPath, path)
  234. }
  235. if err := mounter.SetUp(nil); err != nil {
  236. t.Errorf("Expected success, got: %v", err)
  237. }
  238. if _, err := os.Stat(volumePath); err != nil {
  239. if os.IsNotExist(err) {
  240. t.Errorf("SetUp() failed, volume path not created: %s", volumePath)
  241. } else {
  242. t.Errorf("SetUp() failed: %v", err)
  243. }
  244. }
  245. t.Logf("Setup successful")
  246. if mounter.(*flexVolumeMounter).readOnly {
  247. t.Errorf("The volume source should not be read-only and it is.")
  248. }
  249. if len(fake.Log) != 1 {
  250. t.Errorf("Mount was not called exactly one time. It was called %d times.", len(fake.Log))
  251. } else {
  252. if fake.Log[0].Action != mount.FakeActionMount {
  253. t.Errorf("Unexpected mounter action: %#v", fake.Log[0])
  254. }
  255. }
  256. fake.ResetLog()
  257. unmounter, err := plugin.(*flexVolumePlugin).newUnmounterInternal("vol1", types.UID("poduid"), &flexVolumeUtil{}, fake, exec.New())
  258. if err != nil {
  259. t.Errorf("Failed to make a new Unmounter: %v", err)
  260. }
  261. if unmounter == nil {
  262. t.Errorf("Got a nil Unmounter")
  263. }
  264. if err := unmounter.TearDown(); err != nil {
  265. t.Errorf("Expected success, got: %v", err)
  266. }
  267. if _, err := os.Stat(volumePath); err == nil {
  268. t.Errorf("TearDown() failed, volume path still exists: %s", volumePath)
  269. } else if !os.IsNotExist(err) {
  270. t.Errorf("SetUp() failed: %v", err)
  271. }
  272. if len(fake.Log) != 1 {
  273. t.Errorf("Unmount was not called exactly one time. It was called %d times.", len(fake.Log))
  274. } else {
  275. if fake.Log[0].Action != mount.FakeActionUnmount {
  276. t.Errorf("Unexpected mounter action: %#v", fake.Log[0])
  277. }
  278. }
  279. fake.ResetLog()
  280. }
  281. func doTestPluginMountUnmount(t *testing.T, spec *volume.Spec, tmpDir string) {
  282. tmpDir, err := utiltesting.MkTmpdir("flexvolume_test")
  283. if err != nil {
  284. t.Fatalf("error creating temp dir: %v", err)
  285. }
  286. defer os.RemoveAll(tmpDir)
  287. plugMgr := volume.VolumePluginMgr{}
  288. installPluginUnderTest(t, "kubernetes.io", "fakeMounter", tmpDir, execScriptTempl2, nil)
  289. plugMgr.InitPlugins(ProbeVolumePlugins(tmpDir), volumetest.NewFakeVolumeHost(tmpDir, nil, nil, "" /* rootContext */))
  290. plugin, err := plugMgr.FindPluginByName("kubernetes.io/fakeMounter")
  291. if err != nil {
  292. t.Errorf("Can't find the plugin by name")
  293. }
  294. fake := &mount.FakeMounter{}
  295. pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: types.UID("poduid")}}
  296. // Use nil secret to test for nil secret case.
  297. mounter, err := plugin.(*flexVolumePlugin).newMounterInternal(spec, pod, &flexVolumeUtil{}, fake, exec.New(), nil)
  298. volumePath := mounter.GetPath()
  299. if err != nil {
  300. t.Errorf("Failed to make a new Mounter: %v", err)
  301. }
  302. if mounter == nil {
  303. t.Errorf("Got a nil Mounter")
  304. }
  305. path := mounter.GetPath()
  306. expectedPath := fmt.Sprintf("%s/pods/poduid/volumes/kubernetes.io~fakeMounter/vol1", tmpDir)
  307. if path != expectedPath {
  308. t.Errorf("Unexpected path, expected %q, got: %q", expectedPath, path)
  309. }
  310. if err := mounter.SetUp(nil); err != nil {
  311. t.Errorf("Expected success, got: %v", err)
  312. }
  313. if _, err := os.Stat(volumePath); err != nil {
  314. if os.IsNotExist(err) {
  315. t.Errorf("SetUp() failed, volume path not created: %s", volumePath)
  316. } else {
  317. t.Errorf("SetUp() failed: %v", err)
  318. }
  319. }
  320. t.Logf("Setup successful")
  321. if mounter.(*flexVolumeMounter).readOnly {
  322. t.Errorf("The volume source should not be read-only and it is.")
  323. }
  324. unmounter, err := plugin.(*flexVolumePlugin).newUnmounterInternal("vol1", types.UID("poduid"), &flexVolumeUtil{}, fake, exec.New())
  325. if err != nil {
  326. t.Errorf("Failed to make a new Unmounter: %v", err)
  327. }
  328. if unmounter == nil {
  329. t.Errorf("Got a nil Unmounter")
  330. }
  331. if err := unmounter.TearDown(); err != nil {
  332. t.Errorf("Expected success, got: %v", err)
  333. }
  334. if _, err := os.Stat(volumePath); err == nil {
  335. t.Errorf("TearDown() failed, volume path still exists: %s", volumePath)
  336. } else if !os.IsNotExist(err) {
  337. t.Errorf("SetUp() failed: %v", err)
  338. }
  339. }
  340. func TestPluginVolumeAttacher(t *testing.T) {
  341. tmpDir, err := utiltesting.MkTmpdir("flexvolume_test")
  342. if err != nil {
  343. t.Fatalf("error creating temp dir: %v", err)
  344. }
  345. defer os.RemoveAll(tmpDir)
  346. vol := &api.Volume{
  347. Name: "vol1",
  348. VolumeSource: api.VolumeSource{FlexVolume: &api.FlexVolumeSource{Driver: "kubernetes.io/fakeAttacher", ReadOnly: false}},
  349. }
  350. doTestPluginAttachDetach(t, volume.NewSpecFromVolume(vol), tmpDir)
  351. }
  352. func TestPluginVolumeMounter(t *testing.T) {
  353. tmpDir, err := utiltesting.MkTmpdir("flexvolume_test")
  354. if err != nil {
  355. t.Fatalf("error creating temp dir: %v", err)
  356. }
  357. defer os.RemoveAll(tmpDir)
  358. vol := &api.Volume{
  359. Name: "vol1",
  360. VolumeSource: api.VolumeSource{FlexVolume: &api.FlexVolumeSource{Driver: "kubernetes.io/fakeMounter", ReadOnly: false}},
  361. }
  362. doTestPluginMountUnmount(t, volume.NewSpecFromVolume(vol), tmpDir)
  363. }
  364. func TestPluginPersistentVolume(t *testing.T) {
  365. tmpDir, err := utiltesting.MkTmpdir("flexvolume_test")
  366. if err != nil {
  367. t.Fatalf("error creating temp dir: %v", err)
  368. }
  369. defer os.RemoveAll(tmpDir)
  370. vol := &api.PersistentVolume{
  371. ObjectMeta: api.ObjectMeta{
  372. Name: "vol1",
  373. },
  374. Spec: api.PersistentVolumeSpec{
  375. PersistentVolumeSource: api.PersistentVolumeSource{
  376. FlexVolume: &api.FlexVolumeSource{Driver: "kubernetes.io/fakeAttacher", ReadOnly: false},
  377. },
  378. },
  379. }
  380. doTestPluginAttachDetach(t, volume.NewSpecFromPersistentVolume(vol, false), tmpDir)
  381. }