csi_mounter_test.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  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 csi
  14. import (
  15. "context"
  16. "fmt"
  17. "math/rand"
  18. "os"
  19. "path"
  20. "path/filepath"
  21. "testing"
  22. "reflect"
  23. api "k8s.io/api/core/v1"
  24. storage "k8s.io/api/storage/v1"
  25. storagev1beta1 "k8s.io/api/storage/v1beta1"
  26. meta "k8s.io/apimachinery/pkg/apis/meta/v1"
  27. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  28. "k8s.io/apimachinery/pkg/types"
  29. utilfeature "k8s.io/apiserver/pkg/util/feature"
  30. fakeclient "k8s.io/client-go/kubernetes/fake"
  31. featuregatetesting "k8s.io/component-base/featuregate/testing"
  32. "k8s.io/kubernetes/pkg/features"
  33. "k8s.io/kubernetes/pkg/volume"
  34. fakecsi "k8s.io/kubernetes/pkg/volume/csi/fake"
  35. "k8s.io/kubernetes/pkg/volume/util"
  36. volumetypes "k8s.io/kubernetes/pkg/volume/util/types"
  37. )
  38. var (
  39. testDriver = "test-driver"
  40. testVol = "vol-123"
  41. testns = "test-ns"
  42. testPod = "test-pod"
  43. testPodUID = types.UID("test-pod")
  44. testAccount = "test-service-account"
  45. )
  46. func TestMounterGetPath(t *testing.T) {
  47. plug, tmpDir := newTestPlugin(t, nil)
  48. defer os.RemoveAll(tmpDir)
  49. // TODO (vladimirvivien) specName with slashes will not work
  50. testCases := []struct {
  51. name string
  52. specVolumeName string
  53. path string
  54. }{
  55. {
  56. name: "simple specName",
  57. specVolumeName: "spec-0",
  58. path: filepath.Join(tmpDir, fmt.Sprintf("pods/%s/volumes/kubernetes.io~csi/%s/%s", testPodUID, "spec-0", "/mount")),
  59. },
  60. {
  61. name: "specName with dots",
  62. specVolumeName: "test.spec.1",
  63. path: filepath.Join(tmpDir, fmt.Sprintf("pods/%s/volumes/kubernetes.io~csi/%s/%s", testPodUID, "test.spec.1", "/mount")),
  64. },
  65. }
  66. for _, tc := range testCases {
  67. t.Logf("test case: %s", tc.name)
  68. registerFakePlugin(testDriver, "endpoint", []string{"1.0.0"}, t)
  69. pv := makeTestPV(tc.specVolumeName, 10, testDriver, testVol)
  70. spec := volume.NewSpecFromPersistentVolume(pv, pv.Spec.PersistentVolumeSource.CSI.ReadOnly)
  71. mounter, err := plug.NewMounter(
  72. spec,
  73. &api.Pod{ObjectMeta: meta.ObjectMeta{UID: testPodUID, Namespace: testns}},
  74. volume.VolumeOptions{},
  75. )
  76. if err != nil {
  77. t.Fatalf("Failed to make a new Mounter: %v", err)
  78. }
  79. csiMounter := mounter.(*csiMountMgr)
  80. mountPath := csiMounter.GetPath()
  81. if tc.path != mountPath {
  82. t.Errorf("expecting path %s, got %s", tc.path, mountPath)
  83. }
  84. }
  85. }
  86. func MounterSetUpTests(t *testing.T, podInfoEnabled bool) {
  87. defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.CSIDriverRegistry, podInfoEnabled)()
  88. tests := []struct {
  89. name string
  90. driver string
  91. volumeContext map[string]string
  92. expectedVolumeContext map[string]string
  93. csiInlineVolume bool
  94. }{
  95. {
  96. name: "no pod info",
  97. driver: "no-info",
  98. volumeContext: nil,
  99. expectedVolumeContext: nil,
  100. },
  101. {
  102. name: "no CSIDriver -> no pod info",
  103. driver: "unknown-driver",
  104. volumeContext: nil,
  105. expectedVolumeContext: nil,
  106. },
  107. {
  108. name: "CSIDriver with PodInfoRequiredOnMount=nil -> no pod info",
  109. driver: "nil",
  110. volumeContext: nil,
  111. expectedVolumeContext: nil,
  112. },
  113. {
  114. name: "no pod info -> keep existing volumeContext",
  115. driver: "no-info",
  116. volumeContext: map[string]string{"foo": "bar"},
  117. expectedVolumeContext: map[string]string{"foo": "bar"},
  118. },
  119. {
  120. name: "add pod info",
  121. driver: "info",
  122. volumeContext: nil,
  123. expectedVolumeContext: map[string]string{"csi.storage.k8s.io/pod.uid": "test-pod", "csi.storage.k8s.io/serviceAccount.name": "test-service-account", "csi.storage.k8s.io/pod.name": "test-pod", "csi.storage.k8s.io/pod.namespace": "test-ns"},
  124. },
  125. {
  126. name: "add pod info -> keep existing volumeContext",
  127. driver: "info",
  128. volumeContext: map[string]string{"foo": "bar"},
  129. expectedVolumeContext: map[string]string{"foo": "bar", "csi.storage.k8s.io/pod.uid": "test-pod", "csi.storage.k8s.io/serviceAccount.name": "test-service-account", "csi.storage.k8s.io/pod.name": "test-pod", "csi.storage.k8s.io/pod.namespace": "test-ns"},
  130. },
  131. {
  132. name: "CSIInlineVolume pod info",
  133. driver: "info",
  134. volumeContext: nil,
  135. expectedVolumeContext: map[string]string{"csi.storage.k8s.io/pod.uid": "test-pod", "csi.storage.k8s.io/serviceAccount.name": "test-service-account", "csi.storage.k8s.io/pod.name": "test-pod", "csi.storage.k8s.io/pod.namespace": "test-ns", "csi.storage.k8s.io/ephemeral": "false"},
  136. csiInlineVolume: true,
  137. },
  138. }
  139. noPodMountInfo := false
  140. currentPodInfoMount := true
  141. for _, test := range tests {
  142. t.Run(test.name, func(t *testing.T) {
  143. // Modes must be set if (and only if) CSIInlineVolume is enabled.
  144. var modes []storagev1beta1.VolumeLifecycleMode
  145. defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.CSIInlineVolume, test.csiInlineVolume)()
  146. if test.csiInlineVolume {
  147. modes = append(modes, storagev1beta1.VolumeLifecyclePersistent)
  148. }
  149. fakeClient := fakeclient.NewSimpleClientset(
  150. getTestCSIDriver("no-info", &noPodMountInfo, nil, modes),
  151. getTestCSIDriver("info", &currentPodInfoMount, nil, modes),
  152. getTestCSIDriver("nil", nil, nil, modes),
  153. )
  154. plug, tmpDir := newTestPlugin(t, fakeClient)
  155. defer os.RemoveAll(tmpDir)
  156. registerFakePlugin(test.driver, "endpoint", []string{"1.0.0"}, t)
  157. pv := makeTestPV("test-pv", 10, test.driver, testVol)
  158. pv.Spec.CSI.VolumeAttributes = test.volumeContext
  159. pv.Spec.MountOptions = []string{"foo=bar", "baz=qux"}
  160. pvName := pv.GetName()
  161. mounter, err := plug.NewMounter(
  162. volume.NewSpecFromPersistentVolume(pv, pv.Spec.PersistentVolumeSource.CSI.ReadOnly),
  163. &api.Pod{
  164. ObjectMeta: meta.ObjectMeta{UID: testPodUID, Namespace: testns, Name: testPod},
  165. Spec: api.PodSpec{
  166. ServiceAccountName: testAccount,
  167. },
  168. },
  169. volume.VolumeOptions{},
  170. )
  171. if err != nil {
  172. t.Fatalf("failed to make a new Mounter: %v", err)
  173. }
  174. if mounter == nil {
  175. t.Fatal("failed to create CSI mounter")
  176. }
  177. csiMounter := mounter.(*csiMountMgr)
  178. csiMounter.csiClient = setupClient(t, true)
  179. attachID := getAttachmentName(csiMounter.volumeID, string(csiMounter.driverName), string(plug.host.GetNodeName()))
  180. attachment := &storage.VolumeAttachment{
  181. ObjectMeta: meta.ObjectMeta{
  182. Name: attachID,
  183. },
  184. Spec: storage.VolumeAttachmentSpec{
  185. NodeName: "test-node",
  186. Attacher: CSIPluginName,
  187. Source: storage.VolumeAttachmentSource{
  188. PersistentVolumeName: &pvName,
  189. },
  190. },
  191. Status: storage.VolumeAttachmentStatus{
  192. Attached: false,
  193. AttachError: nil,
  194. DetachError: nil,
  195. },
  196. }
  197. _, err = csiMounter.k8s.StorageV1().VolumeAttachments().Create(context.TODO(), attachment, metav1.CreateOptions{})
  198. if err != nil {
  199. t.Fatalf("failed to setup VolumeAttachment: %v", err)
  200. }
  201. // Mounter.SetUp()
  202. var mounterArgs volume.MounterArgs
  203. fsGroup := int64(2000)
  204. mounterArgs.FsGroup = &fsGroup
  205. if err := csiMounter.SetUp(mounterArgs); err != nil {
  206. t.Fatalf("mounter.Setup failed: %v", err)
  207. }
  208. //Test the default value of file system type is not overridden
  209. if len(csiMounter.spec.PersistentVolume.Spec.CSI.FSType) != 0 {
  210. t.Errorf("default value of file system type was overridden by type %s", csiMounter.spec.PersistentVolume.Spec.CSI.FSType)
  211. }
  212. mountPath := csiMounter.GetPath()
  213. if _, err := os.Stat(mountPath); err != nil {
  214. if os.IsNotExist(err) {
  215. t.Errorf("SetUp() failed, volume path not created: %s", mountPath)
  216. } else {
  217. t.Errorf("SetUp() failed: %v", err)
  218. }
  219. }
  220. // ensure call went all the way
  221. pubs := csiMounter.csiClient.(*fakeCsiDriverClient).nodeClient.GetNodePublishedVolumes()
  222. vol, ok := pubs[csiMounter.volumeID]
  223. if !ok {
  224. t.Error("csi server may not have received NodePublishVolume call")
  225. }
  226. if vol.Path != csiMounter.GetPath() {
  227. t.Errorf("csi server expected path %s, got %s", csiMounter.GetPath(), vol.Path)
  228. }
  229. if !reflect.DeepEqual(vol.MountFlags, pv.Spec.MountOptions) {
  230. t.Errorf("csi server expected mount options %v, got %v", pv.Spec.MountOptions, vol.MountFlags)
  231. }
  232. if podInfoEnabled {
  233. if !reflect.DeepEqual(vol.VolumeContext, test.expectedVolumeContext) {
  234. t.Errorf("csi server expected volumeContext %+v, got %+v", test.expectedVolumeContext, vol.VolumeContext)
  235. }
  236. } else {
  237. // CSIPodInfo feature is disabled, we expect no modifications to volumeContext.
  238. if !reflect.DeepEqual(vol.VolumeContext, test.volumeContext) {
  239. t.Errorf("csi server expected volumeContext %+v, got %+v", test.volumeContext, vol.VolumeContext)
  240. }
  241. }
  242. })
  243. }
  244. }
  245. func TestMounterSetUp(t *testing.T) {
  246. t.Run("WithCSIPodInfo", func(t *testing.T) {
  247. MounterSetUpTests(t, true)
  248. })
  249. t.Run("WithoutCSIPodInfo", func(t *testing.T) {
  250. MounterSetUpTests(t, false)
  251. })
  252. }
  253. func TestMounterSetUpSimple(t *testing.T) {
  254. fakeClient := fakeclient.NewSimpleClientset()
  255. plug, tmpDir := newTestPlugin(t, fakeClient)
  256. defer os.RemoveAll(tmpDir)
  257. testCases := []struct {
  258. name string
  259. podUID types.UID
  260. mode storagev1beta1.VolumeLifecycleMode
  261. fsType string
  262. options []string
  263. spec func(string, []string) *volume.Spec
  264. shouldFail bool
  265. }{
  266. {
  267. name: "setup with ephemeral source",
  268. podUID: types.UID(fmt.Sprintf("%08X", rand.Uint64())),
  269. mode: storagev1beta1.VolumeLifecycleEphemeral,
  270. fsType: "ext4",
  271. shouldFail: true,
  272. spec: func(fsType string, options []string) *volume.Spec {
  273. volSrc := makeTestVol("pv1", testDriver)
  274. volSrc.CSI.FSType = &fsType
  275. return volume.NewSpecFromVolume(volSrc)
  276. },
  277. },
  278. {
  279. name: "setup with persistent source",
  280. podUID: types.UID(fmt.Sprintf("%08X", rand.Uint64())),
  281. mode: storagev1beta1.VolumeLifecyclePersistent,
  282. fsType: "zfs",
  283. spec: func(fsType string, options []string) *volume.Spec {
  284. pvSrc := makeTestPV("pv1", 20, testDriver, "vol1")
  285. pvSrc.Spec.CSI.FSType = fsType
  286. pvSrc.Spec.MountOptions = options
  287. return volume.NewSpecFromPersistentVolume(pvSrc, false)
  288. },
  289. },
  290. {
  291. name: "setup with persistent source without unspecified fstype and options",
  292. podUID: types.UID(fmt.Sprintf("%08X", rand.Uint64())),
  293. mode: storagev1beta1.VolumeLifecyclePersistent,
  294. spec: func(fsType string, options []string) *volume.Spec {
  295. return volume.NewSpecFromPersistentVolume(makeTestPV("pv1", 20, testDriver, "vol2"), false)
  296. },
  297. },
  298. {
  299. name: "setup with missing spec",
  300. shouldFail: true,
  301. spec: func(fsType string, options []string) *volume.Spec { return nil },
  302. },
  303. }
  304. for _, tc := range testCases {
  305. registerFakePlugin(testDriver, "endpoint", []string{"1.0.0"}, t)
  306. t.Run(tc.name, func(t *testing.T) {
  307. mounter, err := plug.NewMounter(
  308. tc.spec(tc.fsType, tc.options),
  309. &api.Pod{ObjectMeta: meta.ObjectMeta{UID: tc.podUID, Namespace: testns}},
  310. volume.VolumeOptions{},
  311. )
  312. if tc.shouldFail && err != nil {
  313. t.Log(err)
  314. return
  315. }
  316. if !tc.shouldFail && err != nil {
  317. t.Fatal("unexpected error:", err)
  318. }
  319. if mounter == nil {
  320. t.Fatal("failed to create CSI mounter")
  321. }
  322. csiMounter := mounter.(*csiMountMgr)
  323. csiMounter.csiClient = setupClient(t, true)
  324. if csiMounter.volumeLifecycleMode != storagev1beta1.VolumeLifecyclePersistent {
  325. t.Fatal("unexpected volume mode: ", csiMounter.volumeLifecycleMode)
  326. }
  327. attachID := getAttachmentName(csiMounter.volumeID, string(csiMounter.driverName), string(plug.host.GetNodeName()))
  328. attachment := makeTestAttachment(attachID, "test-node", csiMounter.spec.Name())
  329. _, err = csiMounter.k8s.StorageV1().VolumeAttachments().Create(context.TODO(), attachment, metav1.CreateOptions{})
  330. if err != nil {
  331. t.Fatalf("failed to setup VolumeAttachment: %v", err)
  332. }
  333. // Mounter.SetUp()
  334. if err := csiMounter.SetUp(volume.MounterArgs{}); err != nil {
  335. t.Fatalf("mounter.Setup failed: %v", err)
  336. }
  337. // ensure call went all the way
  338. pubs := csiMounter.csiClient.(*fakeCsiDriverClient).nodeClient.GetNodePublishedVolumes()
  339. vol, ok := pubs[csiMounter.volumeID]
  340. if !ok {
  341. t.Error("csi server may not have received NodePublishVolume call")
  342. }
  343. if vol.VolumeHandle != csiMounter.volumeID {
  344. t.Error("volumeHandle not sent to CSI driver properly")
  345. }
  346. devicePath, err := makeDeviceMountPath(plug, csiMounter.spec)
  347. if err != nil {
  348. t.Fatal(err)
  349. }
  350. if vol.DeviceMountPath != devicePath {
  351. t.Errorf("DeviceMountPath not sent properly to CSI driver: %s, %s", vol.DeviceMountPath, devicePath)
  352. }
  353. if !reflect.DeepEqual(vol.MountFlags, csiMounter.spec.PersistentVolume.Spec.MountOptions) {
  354. t.Errorf("unexpected mount flags passed to driver: %+v", vol.MountFlags)
  355. }
  356. if vol.FSType != tc.fsType {
  357. t.Error("unexpected FSType sent to driver:", vol.FSType)
  358. }
  359. if vol.Path != csiMounter.GetPath() {
  360. t.Error("csi server may not have received NodePublishVolume call")
  361. }
  362. })
  363. }
  364. }
  365. func TestMounterSetupWithStatusTracking(t *testing.T) {
  366. fakeClient := fakeclient.NewSimpleClientset()
  367. plug, tmpDir := newTestPlugin(t, fakeClient)
  368. defer os.RemoveAll(tmpDir)
  369. nonFinalError := volumetypes.NewUncertainProgressError("non-final-error")
  370. transientError := volumetypes.NewTransientOperationFailure("transient-error")
  371. testCases := []struct {
  372. name string
  373. podUID types.UID
  374. spec func(string, []string) *volume.Spec
  375. shouldFail bool
  376. exitError error
  377. createAttachment bool
  378. }{
  379. {
  380. name: "setup with correct persistent volume source should result in finish exit status",
  381. podUID: types.UID(fmt.Sprintf("%08X", rand.Uint64())),
  382. spec: func(fsType string, options []string) *volume.Spec {
  383. pvSrc := makeTestPV("pv1", 20, testDriver, "vol1")
  384. pvSrc.Spec.CSI.FSType = fsType
  385. pvSrc.Spec.MountOptions = options
  386. return volume.NewSpecFromPersistentVolume(pvSrc, false)
  387. },
  388. createAttachment: true,
  389. },
  390. {
  391. name: "setup with missing attachment should result in nochange",
  392. podUID: types.UID(fmt.Sprintf("%08X", rand.Uint64())),
  393. spec: func(fsType string, options []string) *volume.Spec {
  394. return volume.NewSpecFromPersistentVolume(makeTestPV("pv3", 20, testDriver, "vol4"), false)
  395. },
  396. exitError: transientError,
  397. createAttachment: false,
  398. shouldFail: true,
  399. },
  400. {
  401. name: "setup with timeout errors on NodePublish",
  402. podUID: types.UID(fmt.Sprintf("%08X", rand.Uint64())),
  403. spec: func(fsType string, options []string) *volume.Spec {
  404. return volume.NewSpecFromPersistentVolume(makeTestPV("pv4", 20, testDriver, fakecsi.NodePublishTimeOut_VolumeID), false)
  405. },
  406. createAttachment: true,
  407. exitError: nonFinalError,
  408. shouldFail: true,
  409. },
  410. {
  411. name: "setup with missing secrets should result in nochange exit",
  412. podUID: types.UID(fmt.Sprintf("%08X", rand.Uint64())),
  413. spec: func(fsType string, options []string) *volume.Spec {
  414. pv := makeTestPV("pv5", 20, testDriver, "vol6")
  415. pv.Spec.PersistentVolumeSource.CSI.NodePublishSecretRef = &api.SecretReference{
  416. Name: "foo",
  417. Namespace: "default",
  418. }
  419. return volume.NewSpecFromPersistentVolume(pv, false)
  420. },
  421. exitError: transientError,
  422. createAttachment: true,
  423. shouldFail: true,
  424. },
  425. }
  426. for _, tc := range testCases {
  427. registerFakePlugin(testDriver, "endpoint", []string{"1.0.0"}, t)
  428. t.Run(tc.name, func(t *testing.T) {
  429. mounter, err := plug.NewMounter(
  430. tc.spec("ext4", []string{}),
  431. &api.Pod{ObjectMeta: meta.ObjectMeta{UID: tc.podUID, Namespace: testns}},
  432. volume.VolumeOptions{},
  433. )
  434. if mounter == nil {
  435. t.Fatal("failed to create CSI mounter")
  436. }
  437. csiMounter := mounter.(*csiMountMgr)
  438. csiMounter.csiClient = setupClient(t, true)
  439. if csiMounter.volumeLifecycleMode != storagev1beta1.VolumeLifecyclePersistent {
  440. t.Fatal("unexpected volume mode: ", csiMounter.volumeLifecycleMode)
  441. }
  442. if tc.createAttachment {
  443. attachID := getAttachmentName(csiMounter.volumeID, string(csiMounter.driverName), string(plug.host.GetNodeName()))
  444. attachment := makeTestAttachment(attachID, "test-node", csiMounter.spec.Name())
  445. _, err = csiMounter.k8s.StorageV1().VolumeAttachments().Create(context.TODO(), attachment, metav1.CreateOptions{})
  446. if err != nil {
  447. t.Fatalf("failed to setup VolumeAttachment: %v", err)
  448. }
  449. }
  450. err = csiMounter.SetUp(volume.MounterArgs{})
  451. if tc.exitError != nil && reflect.TypeOf(tc.exitError) != reflect.TypeOf(err) {
  452. t.Fatalf("expected exitError: %+v got: %+v", tc.exitError, err)
  453. }
  454. if tc.shouldFail && err == nil {
  455. t.Fatalf("expected failure but Setup succeeded")
  456. }
  457. if !tc.shouldFail && err != nil {
  458. t.Fatalf("expected success got mounter.Setup failed with: %v", err)
  459. }
  460. })
  461. }
  462. }
  463. func TestMounterSetUpWithInline(t *testing.T) {
  464. defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.CSIInlineVolume, true)()
  465. testCases := []struct {
  466. name string
  467. podUID types.UID
  468. mode storagev1beta1.VolumeLifecycleMode
  469. fsType string
  470. options []string
  471. spec func(string, []string) *volume.Spec
  472. shouldFail bool
  473. }{
  474. {
  475. name: "setup with vol source",
  476. podUID: types.UID(fmt.Sprintf("%08X", rand.Uint64())),
  477. mode: storagev1beta1.VolumeLifecycleEphemeral,
  478. fsType: "ext4",
  479. spec: func(fsType string, options []string) *volume.Spec {
  480. volSrc := makeTestVol("pv1", testDriver)
  481. volSrc.CSI.FSType = &fsType
  482. return volume.NewSpecFromVolume(volSrc)
  483. },
  484. },
  485. {
  486. name: "setup with persistent source",
  487. podUID: types.UID(fmt.Sprintf("%08X", rand.Uint64())),
  488. mode: storagev1beta1.VolumeLifecyclePersistent,
  489. fsType: "zfs",
  490. spec: func(fsType string, options []string) *volume.Spec {
  491. pvSrc := makeTestPV("pv1", 20, testDriver, "vol1")
  492. pvSrc.Spec.CSI.FSType = fsType
  493. pvSrc.Spec.MountOptions = options
  494. return volume.NewSpecFromPersistentVolume(pvSrc, false)
  495. },
  496. },
  497. {
  498. name: "setup with persistent source without unspecified fstype and options",
  499. podUID: types.UID(fmt.Sprintf("%08X", rand.Uint64())),
  500. mode: storagev1beta1.VolumeLifecyclePersistent,
  501. spec: func(fsType string, options []string) *volume.Spec {
  502. return volume.NewSpecFromPersistentVolume(makeTestPV("pv1", 20, testDriver, "vol2"), false)
  503. },
  504. },
  505. {
  506. name: "setup with missing spec",
  507. shouldFail: true,
  508. spec: func(fsType string, options []string) *volume.Spec { return nil },
  509. },
  510. }
  511. for _, tc := range testCases {
  512. // The fake driver currently supports all modes.
  513. volumeLifecycleModes := []storagev1beta1.VolumeLifecycleMode{
  514. storagev1beta1.VolumeLifecycleEphemeral,
  515. storagev1beta1.VolumeLifecyclePersistent,
  516. }
  517. driver := getTestCSIDriver(testDriver, nil, nil, volumeLifecycleModes)
  518. fakeClient := fakeclient.NewSimpleClientset(driver)
  519. plug, tmpDir := newTestPlugin(t, fakeClient)
  520. defer os.RemoveAll(tmpDir)
  521. registerFakePlugin(testDriver, "endpoint", []string{"1.0.0"}, t)
  522. t.Run(tc.name, func(t *testing.T) {
  523. mounter, err := plug.NewMounter(
  524. tc.spec(tc.fsType, tc.options),
  525. &api.Pod{ObjectMeta: meta.ObjectMeta{UID: tc.podUID, Namespace: testns}},
  526. volume.VolumeOptions{},
  527. )
  528. if tc.shouldFail && err != nil {
  529. t.Log(err)
  530. return
  531. }
  532. if !tc.shouldFail && err != nil {
  533. t.Fatal("unexpected error:", err)
  534. }
  535. if mounter == nil {
  536. t.Fatal("failed to create CSI mounter")
  537. }
  538. csiMounter := mounter.(*csiMountMgr)
  539. csiMounter.csiClient = setupClient(t, true)
  540. if csiMounter.volumeLifecycleMode != tc.mode {
  541. t.Fatal("unexpected volume mode: ", csiMounter.volumeLifecycleMode)
  542. }
  543. if csiMounter.volumeLifecycleMode == storagev1beta1.VolumeLifecycleEphemeral && csiMounter.volumeID != makeVolumeHandle(string(tc.podUID), csiMounter.specVolumeID) {
  544. t.Fatal("unexpected generated volumeHandle:", csiMounter.volumeID)
  545. }
  546. if csiMounter.volumeLifecycleMode == storagev1beta1.VolumeLifecyclePersistent {
  547. attachID := getAttachmentName(csiMounter.volumeID, string(csiMounter.driverName), string(plug.host.GetNodeName()))
  548. attachment := makeTestAttachment(attachID, "test-node", csiMounter.spec.Name())
  549. _, err = csiMounter.k8s.StorageV1().VolumeAttachments().Create(context.TODO(), attachment, metav1.CreateOptions{})
  550. if err != nil {
  551. t.Fatalf("failed to setup VolumeAttachment: %v", err)
  552. }
  553. }
  554. // Mounter.SetUp()
  555. if err := csiMounter.SetUp(volume.MounterArgs{}); err != nil {
  556. t.Fatalf("mounter.Setup failed: %v", err)
  557. }
  558. // ensure call went all the way
  559. pubs := csiMounter.csiClient.(*fakeCsiDriverClient).nodeClient.GetNodePublishedVolumes()
  560. vol, ok := pubs[csiMounter.volumeID]
  561. if !ok {
  562. t.Error("csi server may not have received NodePublishVolume call")
  563. }
  564. if vol.VolumeHandle != csiMounter.volumeID {
  565. t.Error("volumeHandle not sent to CSI driver properly")
  566. }
  567. // validate stagingTargetPath
  568. if tc.mode == storagev1beta1.VolumeLifecycleEphemeral && vol.DeviceMountPath != "" {
  569. t.Errorf("unexpected devicePathTarget sent to driver: %s", vol.DeviceMountPath)
  570. }
  571. if tc.mode == storagev1beta1.VolumeLifecyclePersistent {
  572. devicePath, err := makeDeviceMountPath(plug, csiMounter.spec)
  573. if err != nil {
  574. t.Fatal(err)
  575. }
  576. if vol.DeviceMountPath != devicePath {
  577. t.Errorf("DeviceMountPath not sent properly to CSI driver: %s, %s", vol.DeviceMountPath, devicePath)
  578. }
  579. if !reflect.DeepEqual(vol.MountFlags, csiMounter.spec.PersistentVolume.Spec.MountOptions) {
  580. t.Errorf("unexpected mount flags passed to driver: %+v", vol.MountFlags)
  581. }
  582. }
  583. if vol.FSType != tc.fsType {
  584. t.Error("unexpected FSType sent to driver:", vol.FSType)
  585. }
  586. if vol.Path != csiMounter.GetPath() {
  587. t.Error("csi server may not have received NodePublishVolume call")
  588. }
  589. })
  590. }
  591. }
  592. func TestMounterSetUpWithFSGroup(t *testing.T) {
  593. fakeClient := fakeclient.NewSimpleClientset()
  594. plug, tmpDir := newTestPlugin(t, fakeClient)
  595. defer os.RemoveAll(tmpDir)
  596. testCases := []struct {
  597. name string
  598. accessModes []api.PersistentVolumeAccessMode
  599. readOnly bool
  600. fsType string
  601. setFsGroup bool
  602. fsGroup int64
  603. }{
  604. {
  605. name: "default fstype, with no fsgroup (should not apply fsgroup)",
  606. accessModes: []api.PersistentVolumeAccessMode{
  607. api.ReadWriteOnce,
  608. },
  609. readOnly: false,
  610. fsType: "",
  611. },
  612. {
  613. name: "default fstype with fsgroup (should not apply fsgroup)",
  614. accessModes: []api.PersistentVolumeAccessMode{
  615. api.ReadWriteOnce,
  616. },
  617. readOnly: false,
  618. fsType: "",
  619. setFsGroup: true,
  620. fsGroup: 3000,
  621. },
  622. {
  623. name: "fstype, fsgroup, RWM, ROM provided (should not apply fsgroup)",
  624. accessModes: []api.PersistentVolumeAccessMode{
  625. api.ReadWriteMany,
  626. api.ReadOnlyMany,
  627. },
  628. fsType: "ext4",
  629. setFsGroup: true,
  630. fsGroup: 3000,
  631. },
  632. {
  633. name: "fstype, fsgroup, RWO, but readOnly (should not apply fsgroup)",
  634. accessModes: []api.PersistentVolumeAccessMode{
  635. api.ReadWriteOnce,
  636. },
  637. readOnly: true,
  638. fsType: "ext4",
  639. setFsGroup: true,
  640. fsGroup: 3000,
  641. },
  642. {
  643. name: "fstype, fsgroup, RWO provided (should apply fsgroup)",
  644. accessModes: []api.PersistentVolumeAccessMode{
  645. api.ReadWriteOnce,
  646. },
  647. fsType: "ext4",
  648. setFsGroup: true,
  649. fsGroup: 3000,
  650. },
  651. }
  652. for i, tc := range testCases {
  653. t.Logf("Running test %s", tc.name)
  654. volName := fmt.Sprintf("test-vol-%d", i)
  655. registerFakePlugin(testDriver, "endpoint", []string{"1.0.0"}, t)
  656. pv := makeTestPV("test-pv", 10, testDriver, volName)
  657. pv.Spec.AccessModes = tc.accessModes
  658. pvName := pv.GetName()
  659. spec := volume.NewSpecFromPersistentVolume(pv, tc.readOnly)
  660. if tc.fsType != "" {
  661. spec.PersistentVolume.Spec.CSI.FSType = tc.fsType
  662. }
  663. mounter, err := plug.NewMounter(
  664. spec,
  665. &api.Pod{ObjectMeta: meta.ObjectMeta{UID: testPodUID, Namespace: testns}},
  666. volume.VolumeOptions{},
  667. )
  668. if err != nil {
  669. t.Fatalf("Failed to make a new Mounter: %v", err)
  670. }
  671. if mounter == nil {
  672. t.Fatal("failed to create CSI mounter")
  673. }
  674. csiMounter := mounter.(*csiMountMgr)
  675. csiMounter.csiClient = setupClient(t, true)
  676. attachID := getAttachmentName(csiMounter.volumeID, string(csiMounter.driverName), string(plug.host.GetNodeName()))
  677. attachment := makeTestAttachment(attachID, "test-node", pvName)
  678. _, err = csiMounter.k8s.StorageV1().VolumeAttachments().Create(context.TODO(), attachment, metav1.CreateOptions{})
  679. if err != nil {
  680. t.Errorf("failed to setup VolumeAttachment: %v", err)
  681. continue
  682. }
  683. // Mounter.SetUp()
  684. var mounterArgs volume.MounterArgs
  685. var fsGroupPtr *int64
  686. if tc.setFsGroup {
  687. fsGroup := tc.fsGroup
  688. fsGroupPtr = &fsGroup
  689. }
  690. mounterArgs.FsGroup = fsGroupPtr
  691. if err := csiMounter.SetUp(mounterArgs); err != nil {
  692. t.Fatalf("mounter.Setup failed: %v", err)
  693. }
  694. //Test the default value of file system type is not overridden
  695. if len(csiMounter.spec.PersistentVolume.Spec.CSI.FSType) != len(tc.fsType) {
  696. t.Errorf("file system type was overridden by type %s", csiMounter.spec.PersistentVolume.Spec.CSI.FSType)
  697. }
  698. // ensure call went all the way
  699. pubs := csiMounter.csiClient.(*fakeCsiDriverClient).nodeClient.GetNodePublishedVolumes()
  700. if pubs[csiMounter.volumeID].Path != csiMounter.GetPath() {
  701. t.Error("csi server may not have received NodePublishVolume call")
  702. }
  703. }
  704. }
  705. func TestUnmounterTeardown(t *testing.T) {
  706. plug, tmpDir := newTestPlugin(t, nil)
  707. defer os.RemoveAll(tmpDir)
  708. registerFakePlugin(testDriver, "endpoint", []string{"1.0.0"}, t)
  709. pv := makeTestPV("test-pv", 10, testDriver, testVol)
  710. // save the data file prior to unmount
  711. dir := filepath.Join(getTargetPath(testPodUID, pv.ObjectMeta.Name, plug.host), "/mount")
  712. if err := os.MkdirAll(dir, 0755); err != nil && !os.IsNotExist(err) {
  713. t.Errorf("failed to create dir [%s]: %v", dir, err)
  714. }
  715. // do a fake local mount
  716. diskMounter := util.NewSafeFormatAndMountFromHost(plug.GetPluginName(), plug.host)
  717. if err := diskMounter.FormatAndMount("/fake/device", dir, "testfs", nil); err != nil {
  718. t.Errorf("failed to mount dir [%s]: %v", dir, err)
  719. }
  720. if err := saveVolumeData(
  721. path.Dir(dir),
  722. volDataFileName,
  723. map[string]string{
  724. volDataKey.specVolID: pv.ObjectMeta.Name,
  725. volDataKey.driverName: testDriver,
  726. volDataKey.volHandle: testVol,
  727. },
  728. ); err != nil {
  729. t.Fatalf("failed to save volume data: %v", err)
  730. }
  731. unmounter, err := plug.NewUnmounter(pv.ObjectMeta.Name, testPodUID)
  732. if err != nil {
  733. t.Fatalf("failed to make a new Unmounter: %v", err)
  734. }
  735. csiUnmounter := unmounter.(*csiMountMgr)
  736. csiUnmounter.csiClient = setupClient(t, true)
  737. err = csiUnmounter.TearDownAt(dir)
  738. if err != nil {
  739. t.Fatal(err)
  740. }
  741. // ensure csi client call
  742. pubs := csiUnmounter.csiClient.(*fakeCsiDriverClient).nodeClient.GetNodePublishedVolumes()
  743. if _, ok := pubs[csiUnmounter.volumeID]; ok {
  744. t.Error("csi server may not have received NodeUnpublishVolume call")
  745. }
  746. }