framework_test.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957
  1. /*
  2. Copyright 2016 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 persistentvolume
  14. import (
  15. "fmt"
  16. "reflect"
  17. "strings"
  18. "sync/atomic"
  19. "testing"
  20. "time"
  21. "k8s.io/klog"
  22. v1 "k8s.io/api/core/v1"
  23. storage "k8s.io/api/storage/v1"
  24. "k8s.io/apimachinery/pkg/api/resource"
  25. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  26. "k8s.io/apimachinery/pkg/types"
  27. "k8s.io/apimachinery/pkg/util/wait"
  28. "k8s.io/apimachinery/pkg/watch"
  29. "k8s.io/client-go/informers"
  30. clientset "k8s.io/client-go/kubernetes"
  31. "k8s.io/client-go/kubernetes/fake"
  32. corelisters "k8s.io/client-go/listers/core/v1"
  33. storagelisters "k8s.io/client-go/listers/storage/v1"
  34. "k8s.io/client-go/tools/cache"
  35. "k8s.io/client-go/tools/record"
  36. "k8s.io/kubernetes/pkg/controller"
  37. pvtesting "k8s.io/kubernetes/pkg/controller/volume/persistentvolume/testing"
  38. pvutil "k8s.io/kubernetes/pkg/controller/volume/persistentvolume/util"
  39. vol "k8s.io/kubernetes/pkg/volume"
  40. "k8s.io/kubernetes/pkg/volume/util/recyclerclient"
  41. )
  42. // This is a unit test framework for persistent volume controller.
  43. // It fills the controller with test claims/volumes and can simulate these
  44. // scenarios:
  45. // 1) Call syncClaim/syncVolume once.
  46. // 2) Call syncClaim/syncVolume several times (both simulating "claim/volume
  47. // modified" events and periodic sync), until the controller settles down and
  48. // does not modify anything.
  49. // 3) Simulate almost real API server/etcd and call add/update/delete
  50. // volume/claim.
  51. // In all these scenarios, when the test finishes, the framework can compare
  52. // resulting claims/volumes with list of expected claims/volumes and report
  53. // differences.
  54. // controllerTest contains a single controller test input.
  55. // Each test has initial set of volumes and claims that are filled into the
  56. // controller before the test starts. The test then contains a reference to
  57. // function to call as the actual test. Available functions are:
  58. // - testSyncClaim - calls syncClaim on the first claim in initialClaims.
  59. // - testSyncClaimError - calls syncClaim on the first claim in initialClaims
  60. // and expects an error to be returned.
  61. // - testSyncVolume - calls syncVolume on the first volume in initialVolumes.
  62. // - any custom function for specialized tests.
  63. // The test then contains list of volumes/claims that are expected at the end
  64. // of the test and list of generated events.
  65. type controllerTest struct {
  66. // Name of the test, for logging
  67. name string
  68. // Initial content of controller volume cache.
  69. initialVolumes []*v1.PersistentVolume
  70. // Expected content of controller volume cache at the end of the test.
  71. expectedVolumes []*v1.PersistentVolume
  72. // Initial content of controller claim cache.
  73. initialClaims []*v1.PersistentVolumeClaim
  74. // Expected content of controller claim cache at the end of the test.
  75. expectedClaims []*v1.PersistentVolumeClaim
  76. // Expected events - any event with prefix will pass, we don't check full
  77. // event message.
  78. expectedEvents []string
  79. // Errors to produce on matching action
  80. errors []pvtesting.ReactorError
  81. // Function to call as the test.
  82. test testCall
  83. }
  84. type testCall func(ctrl *PersistentVolumeController, reactor *pvtesting.VolumeReactor, test controllerTest) error
  85. const testNamespace = "default"
  86. const mockPluginName = "kubernetes.io/mock-volume"
  87. var novolumes []*v1.PersistentVolume
  88. var noclaims []*v1.PersistentVolumeClaim
  89. var noevents = []string{}
  90. var noerrors = []pvtesting.ReactorError{}
  91. type volumeReactor struct {
  92. *pvtesting.VolumeReactor
  93. ctrl *PersistentVolumeController
  94. }
  95. func newVolumeReactor(client *fake.Clientset, ctrl *PersistentVolumeController, fakeVolumeWatch, fakeClaimWatch *watch.FakeWatcher, errors []pvtesting.ReactorError) *volumeReactor {
  96. return &volumeReactor{
  97. pvtesting.NewVolumeReactor(client, fakeVolumeWatch, fakeClaimWatch, errors),
  98. ctrl,
  99. }
  100. }
  101. // waitForIdle waits until all tests, controllers and other goroutines do their
  102. // job and no new actions are registered for 10 milliseconds.
  103. func (r *volumeReactor) waitForIdle() {
  104. r.ctrl.runningOperations.WaitForCompletion()
  105. // Check every 10ms if the controller does something and stop if it's
  106. // idle.
  107. oldChanges := -1
  108. for {
  109. time.Sleep(10 * time.Millisecond)
  110. changes := r.GetChangeCount()
  111. if changes == oldChanges {
  112. // No changes for last 10ms -> controller must be idle.
  113. break
  114. }
  115. oldChanges = changes
  116. }
  117. }
  118. // waitTest waits until all tests, controllers and other goroutines do their
  119. // job and list of current volumes/claims is equal to list of expected
  120. // volumes/claims (with ~10 second timeout).
  121. func (r *volumeReactor) waitTest(test controllerTest) error {
  122. // start with 10 ms, multiply by 2 each step, 10 steps = 10.23 seconds
  123. backoff := wait.Backoff{
  124. Duration: 10 * time.Millisecond,
  125. Jitter: 0,
  126. Factor: 2,
  127. Steps: 10,
  128. }
  129. err := wait.ExponentialBackoff(backoff, func() (done bool, err error) {
  130. // Finish all operations that are in progress
  131. r.ctrl.runningOperations.WaitForCompletion()
  132. // Return 'true' if the reactor reached the expected state
  133. err1 := r.CheckClaims(test.expectedClaims)
  134. err2 := r.CheckVolumes(test.expectedVolumes)
  135. if err1 == nil && err2 == nil {
  136. return true, nil
  137. }
  138. return false, nil
  139. })
  140. return err
  141. }
  142. // checkEvents compares all expectedEvents with events generated during the test
  143. // and reports differences.
  144. func checkEvents(t *testing.T, expectedEvents []string, ctrl *PersistentVolumeController) error {
  145. var err error
  146. // Read recorded events - wait up to 1 minute to get all the expected ones
  147. // (just in case some goroutines are slower with writing)
  148. timer := time.NewTimer(time.Minute)
  149. defer timer.Stop()
  150. fakeRecorder := ctrl.eventRecorder.(*record.FakeRecorder)
  151. gotEvents := []string{}
  152. finished := false
  153. for len(gotEvents) < len(expectedEvents) && !finished {
  154. select {
  155. case event, ok := <-fakeRecorder.Events:
  156. if ok {
  157. klog.V(5).Infof("event recorder got event %s", event)
  158. gotEvents = append(gotEvents, event)
  159. } else {
  160. klog.V(5).Infof("event recorder finished")
  161. finished = true
  162. }
  163. case _, _ = <-timer.C:
  164. klog.V(5).Infof("event recorder timeout")
  165. finished = true
  166. }
  167. }
  168. // Evaluate the events
  169. for i, expected := range expectedEvents {
  170. if len(gotEvents) <= i {
  171. t.Errorf("Event %q not emitted", expected)
  172. err = fmt.Errorf("Events do not match")
  173. continue
  174. }
  175. received := gotEvents[i]
  176. if !strings.HasPrefix(received, expected) {
  177. t.Errorf("Unexpected event received, expected %q, got %q", expected, received)
  178. err = fmt.Errorf("Events do not match")
  179. }
  180. }
  181. for i := len(expectedEvents); i < len(gotEvents); i++ {
  182. t.Errorf("Unexpected event received: %q", gotEvents[i])
  183. err = fmt.Errorf("Events do not match")
  184. }
  185. return err
  186. }
  187. func alwaysReady() bool { return true }
  188. func newTestController(kubeClient clientset.Interface, informerFactory informers.SharedInformerFactory, enableDynamicProvisioning bool) (*PersistentVolumeController, error) {
  189. if informerFactory == nil {
  190. informerFactory = informers.NewSharedInformerFactory(kubeClient, controller.NoResyncPeriodFunc())
  191. }
  192. params := ControllerParameters{
  193. KubeClient: kubeClient,
  194. SyncPeriod: 5 * time.Second,
  195. VolumePlugins: []vol.VolumePlugin{},
  196. VolumeInformer: informerFactory.Core().V1().PersistentVolumes(),
  197. ClaimInformer: informerFactory.Core().V1().PersistentVolumeClaims(),
  198. ClassInformer: informerFactory.Storage().V1().StorageClasses(),
  199. PodInformer: informerFactory.Core().V1().Pods(),
  200. NodeInformer: informerFactory.Core().V1().Nodes(),
  201. EventRecorder: record.NewFakeRecorder(1000),
  202. EnableDynamicProvisioning: enableDynamicProvisioning,
  203. }
  204. ctrl, err := NewController(params)
  205. if err != nil {
  206. return nil, fmt.Errorf("failed to construct persistentvolume controller: %v", err)
  207. }
  208. ctrl.volumeListerSynced = alwaysReady
  209. ctrl.claimListerSynced = alwaysReady
  210. ctrl.classListerSynced = alwaysReady
  211. // Speed up the test
  212. ctrl.createProvisionedPVInterval = 5 * time.Millisecond
  213. return ctrl, nil
  214. }
  215. // newVolume returns a new volume with given attributes
  216. func newVolume(name, capacity, boundToClaimUID, boundToClaimName string, phase v1.PersistentVolumePhase, reclaimPolicy v1.PersistentVolumeReclaimPolicy, class string, annotations ...string) *v1.PersistentVolume {
  217. fs := v1.PersistentVolumeFilesystem
  218. volume := v1.PersistentVolume{
  219. ObjectMeta: metav1.ObjectMeta{
  220. Name: name,
  221. ResourceVersion: "1",
  222. },
  223. Spec: v1.PersistentVolumeSpec{
  224. Capacity: v1.ResourceList{
  225. v1.ResourceName(v1.ResourceStorage): resource.MustParse(capacity),
  226. },
  227. PersistentVolumeSource: v1.PersistentVolumeSource{
  228. GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{},
  229. },
  230. AccessModes: []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce, v1.ReadOnlyMany},
  231. PersistentVolumeReclaimPolicy: reclaimPolicy,
  232. StorageClassName: class,
  233. VolumeMode: &fs,
  234. },
  235. Status: v1.PersistentVolumeStatus{
  236. Phase: phase,
  237. },
  238. }
  239. if boundToClaimName != "" {
  240. volume.Spec.ClaimRef = &v1.ObjectReference{
  241. Kind: "PersistentVolumeClaim",
  242. APIVersion: "v1",
  243. UID: types.UID(boundToClaimUID),
  244. Namespace: testNamespace,
  245. Name: boundToClaimName,
  246. }
  247. }
  248. if len(annotations) > 0 {
  249. volume.Annotations = make(map[string]string)
  250. for _, a := range annotations {
  251. switch a {
  252. case pvutil.AnnDynamicallyProvisioned:
  253. volume.Annotations[a] = mockPluginName
  254. default:
  255. volume.Annotations[a] = "yes"
  256. }
  257. }
  258. }
  259. return &volume
  260. }
  261. // withLabels applies the given labels to the first volume in the array and
  262. // returns the array. Meant to be used to compose volumes specified inline in
  263. // a test.
  264. func withLabels(labels map[string]string, volumes []*v1.PersistentVolume) []*v1.PersistentVolume {
  265. volumes[0].Labels = labels
  266. return volumes
  267. }
  268. // withLabelSelector sets the label selector of the first claim in the array
  269. // to be MatchLabels of the given label set and returns the array. Meant
  270. // to be used to compose claims specified inline in a test.
  271. func withLabelSelector(labels map[string]string, claims []*v1.PersistentVolumeClaim) []*v1.PersistentVolumeClaim {
  272. claims[0].Spec.Selector = &metav1.LabelSelector{
  273. MatchLabels: labels,
  274. }
  275. return claims
  276. }
  277. // withVolumeVolumeMode applies the given VolumeMode to the first volume in the array and
  278. // returns the array. Meant to be used to compose volumes specified inline in
  279. // a test.
  280. func withVolumeVolumeMode(mode *v1.PersistentVolumeMode, volumes []*v1.PersistentVolume) []*v1.PersistentVolume {
  281. volumes[0].Spec.VolumeMode = mode
  282. return volumes
  283. }
  284. // withClaimVolumeMode applies the given VolumeMode to the first claim in the array and
  285. // returns the array. Meant to be used to compose volumes specified inline in
  286. // a test.
  287. func withClaimVolumeMode(mode *v1.PersistentVolumeMode, claims []*v1.PersistentVolumeClaim) []*v1.PersistentVolumeClaim {
  288. claims[0].Spec.VolumeMode = mode
  289. return claims
  290. }
  291. // withExpectedCapacity sets the claim.Spec.Capacity of the first claim in the
  292. // array to given value and returns the array. Meant to be used to compose
  293. // claims specified inline in a test.
  294. func withExpectedCapacity(capacity string, claims []*v1.PersistentVolumeClaim) []*v1.PersistentVolumeClaim {
  295. claims[0].Status.Capacity = v1.ResourceList{
  296. v1.ResourceName(v1.ResourceStorage): resource.MustParse(capacity),
  297. }
  298. return claims
  299. }
  300. // withMessage saves given message into volume.Status.Message of the first
  301. // volume in the array and returns the array. Meant to be used to compose
  302. // volumes specified inline in a test.
  303. func withMessage(message string, volumes []*v1.PersistentVolume) []*v1.PersistentVolume {
  304. volumes[0].Status.Message = message
  305. return volumes
  306. }
  307. // newVolumeArray returns array with a single volume that would be returned by
  308. // newVolume() with the same parameters.
  309. func newVolumeArray(name, capacity, boundToClaimUID, boundToClaimName string, phase v1.PersistentVolumePhase, reclaimPolicy v1.PersistentVolumeReclaimPolicy, class string, annotations ...string) []*v1.PersistentVolume {
  310. return []*v1.PersistentVolume{
  311. newVolume(name, capacity, boundToClaimUID, boundToClaimName, phase, reclaimPolicy, class, annotations...),
  312. }
  313. }
  314. // newClaim returns a new claim with given attributes
  315. func newClaim(name, claimUID, capacity, boundToVolume string, phase v1.PersistentVolumeClaimPhase, class *string, annotations ...string) *v1.PersistentVolumeClaim {
  316. fs := v1.PersistentVolumeFilesystem
  317. claim := v1.PersistentVolumeClaim{
  318. ObjectMeta: metav1.ObjectMeta{
  319. Name: name,
  320. Namespace: testNamespace,
  321. UID: types.UID(claimUID),
  322. ResourceVersion: "1",
  323. },
  324. Spec: v1.PersistentVolumeClaimSpec{
  325. AccessModes: []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce, v1.ReadOnlyMany},
  326. Resources: v1.ResourceRequirements{
  327. Requests: v1.ResourceList{
  328. v1.ResourceName(v1.ResourceStorage): resource.MustParse(capacity),
  329. },
  330. },
  331. VolumeName: boundToVolume,
  332. StorageClassName: class,
  333. VolumeMode: &fs,
  334. },
  335. Status: v1.PersistentVolumeClaimStatus{
  336. Phase: phase,
  337. },
  338. }
  339. // Make sure ref.GetReference(claim) works
  340. claim.ObjectMeta.SelfLink = "/api/v1/namespaces/" + testNamespace + "/persistentvolumeclaims/" + name
  341. if len(annotations) > 0 {
  342. claim.Annotations = make(map[string]string)
  343. for _, a := range annotations {
  344. switch a {
  345. case pvutil.AnnStorageProvisioner:
  346. claim.Annotations[a] = mockPluginName
  347. default:
  348. claim.Annotations[a] = "yes"
  349. }
  350. }
  351. }
  352. // Bound claims must have proper Status.
  353. if phase == v1.ClaimBound {
  354. claim.Status.AccessModes = claim.Spec.AccessModes
  355. // For most of the tests it's enough to copy claim's requested capacity,
  356. // individual tests can adjust it using withExpectedCapacity()
  357. claim.Status.Capacity = claim.Spec.Resources.Requests
  358. }
  359. return &claim
  360. }
  361. // newClaimArray returns array with a single claim that would be returned by
  362. // newClaim() with the same parameters.
  363. func newClaimArray(name, claimUID, capacity, boundToVolume string, phase v1.PersistentVolumeClaimPhase, class *string, annotations ...string) []*v1.PersistentVolumeClaim {
  364. return []*v1.PersistentVolumeClaim{
  365. newClaim(name, claimUID, capacity, boundToVolume, phase, class, annotations...),
  366. }
  367. }
  368. // claimWithAnnotation saves given annotation into given claims. Meant to be
  369. // used to compose claims specified inline in a test.
  370. // TODO(refactor): This helper function (and other helpers related to claim
  371. // arrays) could use some cleaning up (most assume an array size of one)-
  372. // replace with annotateClaim at all callsites. The tests require claimArrays
  373. // but mostly operate on single claims
  374. func claimWithAnnotation(name, value string, claims []*v1.PersistentVolumeClaim) []*v1.PersistentVolumeClaim {
  375. if claims[0].Annotations == nil {
  376. claims[0].Annotations = map[string]string{name: value}
  377. } else {
  378. claims[0].Annotations[name] = value
  379. }
  380. return claims
  381. }
  382. func annotateClaim(claim *v1.PersistentVolumeClaim, ann map[string]string) *v1.PersistentVolumeClaim {
  383. if claim.Annotations == nil {
  384. claim.Annotations = map[string]string{}
  385. }
  386. for key, val := range ann {
  387. claim.Annotations[key] = val
  388. }
  389. return claim
  390. }
  391. // volumeWithAnnotation saves given annotation into given volume.
  392. // Meant to be used to compose volume specified inline in a test.
  393. func volumeWithAnnotation(name, value string, volume *v1.PersistentVolume) *v1.PersistentVolume {
  394. if volume.Annotations == nil {
  395. volume.Annotations = map[string]string{name: value}
  396. } else {
  397. volume.Annotations[name] = value
  398. }
  399. return volume
  400. }
  401. // volumesWithAnnotation saves given annotation into given volumes.
  402. // Meant to be used to compose volumes specified inline in a test.
  403. func volumesWithAnnotation(name, value string, volumes []*v1.PersistentVolume) []*v1.PersistentVolume {
  404. for _, volume := range volumes {
  405. volumeWithAnnotation(name, value, volume)
  406. }
  407. return volumes
  408. }
  409. // claimWithAccessMode saves given access into given claims.
  410. // Meant to be used to compose claims specified inline in a test.
  411. func claimWithAccessMode(modes []v1.PersistentVolumeAccessMode, claims []*v1.PersistentVolumeClaim) []*v1.PersistentVolumeClaim {
  412. claims[0].Spec.AccessModes = modes
  413. return claims
  414. }
  415. func testSyncClaim(ctrl *PersistentVolumeController, reactor *pvtesting.VolumeReactor, test controllerTest) error {
  416. return ctrl.syncClaim(test.initialClaims[0])
  417. }
  418. func testSyncClaimError(ctrl *PersistentVolumeController, reactor *pvtesting.VolumeReactor, test controllerTest) error {
  419. err := ctrl.syncClaim(test.initialClaims[0])
  420. if err != nil {
  421. return nil
  422. }
  423. return fmt.Errorf("syncClaim succeeded when failure was expected")
  424. }
  425. func testSyncVolume(ctrl *PersistentVolumeController, reactor *pvtesting.VolumeReactor, test controllerTest) error {
  426. return ctrl.syncVolume(test.initialVolumes[0])
  427. }
  428. type operationType string
  429. const operationDelete = "Delete"
  430. const operationRecycle = "Recycle"
  431. var (
  432. classGold string = "gold"
  433. classSilver string = "silver"
  434. classCopper string = "copper"
  435. classEmpty string = ""
  436. classNonExisting string = "non-existing"
  437. classExternal string = "external"
  438. classExternalWait string = "external-wait"
  439. classUnknownInternal string = "unknown-internal"
  440. classUnsupportedMountOptions string = "unsupported-mountoptions"
  441. classLarge string = "large"
  442. classWait string = "wait"
  443. modeWait = storage.VolumeBindingWaitForFirstConsumer
  444. )
  445. // wrapTestWithPluginCalls returns a testCall that:
  446. // - configures controller with a volume plugin that implements recycler,
  447. // deleter and provisioner. The plugin returns provided errors when a volume
  448. // is deleted, recycled or provisioned.
  449. // - calls given testCall
  450. func wrapTestWithPluginCalls(expectedRecycleCalls, expectedDeleteCalls []error, expectedProvisionCalls []provisionCall, toWrap testCall) testCall {
  451. return func(ctrl *PersistentVolumeController, reactor *pvtesting.VolumeReactor, test controllerTest) error {
  452. plugin := &mockVolumePlugin{
  453. recycleCalls: expectedRecycleCalls,
  454. deleteCalls: expectedDeleteCalls,
  455. provisionCalls: expectedProvisionCalls,
  456. }
  457. ctrl.volumePluginMgr.InitPlugins([]vol.VolumePlugin{plugin}, nil /* prober */, ctrl)
  458. return toWrap(ctrl, reactor, test)
  459. }
  460. }
  461. // wrapTestWithReclaimCalls returns a testCall that:
  462. // - configures controller with recycler or deleter which will return provided
  463. // errors when a volume is deleted or recycled
  464. // - calls given testCall
  465. func wrapTestWithReclaimCalls(operation operationType, expectedOperationCalls []error, toWrap testCall) testCall {
  466. if operation == operationDelete {
  467. return wrapTestWithPluginCalls(nil, expectedOperationCalls, nil, toWrap)
  468. } else {
  469. return wrapTestWithPluginCalls(expectedOperationCalls, nil, nil, toWrap)
  470. }
  471. }
  472. // wrapTestWithProvisionCalls returns a testCall that:
  473. // - configures controller with a provisioner which will return provided errors
  474. // when a claim is provisioned
  475. // - calls given testCall
  476. func wrapTestWithProvisionCalls(expectedProvisionCalls []provisionCall, toWrap testCall) testCall {
  477. return wrapTestWithPluginCalls(nil, nil, expectedProvisionCalls, toWrap)
  478. }
  479. type fakeCSINameTranslator struct{}
  480. func (t fakeCSINameTranslator) GetCSINameFromInTreeName(pluginName string) (string, error) {
  481. return "vendor.com/MockCSIDriver", nil
  482. }
  483. type fakeCSIMigratedPluginManager struct{}
  484. func (t fakeCSIMigratedPluginManager) IsMigrationEnabledForPlugin(pluginName string) bool {
  485. return true
  486. }
  487. // wrapTestWithCSIMigrationProvisionCalls returns a testCall that:
  488. // - configures controller with a volume plugin that emulates CSI migration
  489. // - calls given testCall
  490. func wrapTestWithCSIMigrationProvisionCalls(toWrap testCall) testCall {
  491. plugin := &mockVolumePlugin{}
  492. return func(ctrl *PersistentVolumeController, reactor *pvtesting.VolumeReactor, test controllerTest) error {
  493. ctrl.volumePluginMgr.InitPlugins([]vol.VolumePlugin{plugin}, nil /* prober */, ctrl)
  494. ctrl.translator = fakeCSINameTranslator{}
  495. ctrl.csiMigratedPluginManager = fakeCSIMigratedPluginManager{}
  496. return toWrap(ctrl, reactor, test)
  497. }
  498. }
  499. // wrapTestWithInjectedOperation returns a testCall that:
  500. // - starts the controller and lets it run original testCall until
  501. // scheduleOperation() call. It blocks the controller there and calls the
  502. // injected function to simulate that something is happening when the
  503. // controller waits for the operation lock. Controller is then resumed and we
  504. // check how it behaves.
  505. func wrapTestWithInjectedOperation(toWrap testCall, injectBeforeOperation func(ctrl *PersistentVolumeController, reactor *pvtesting.VolumeReactor)) testCall {
  506. return func(ctrl *PersistentVolumeController, reactor *pvtesting.VolumeReactor, test controllerTest) error {
  507. // Inject a hook before async operation starts
  508. ctrl.preOperationHook = func(operationName string) {
  509. // Inside the hook, run the function to inject
  510. klog.V(4).Infof("reactor: scheduleOperation reached, injecting call")
  511. injectBeforeOperation(ctrl, reactor)
  512. }
  513. // Run the tested function (typically syncClaim/syncVolume) in a
  514. // separate goroutine.
  515. var testError error
  516. var testFinished int32
  517. go func() {
  518. testError = toWrap(ctrl, reactor, test)
  519. // Let the "main" test function know that syncVolume has finished.
  520. atomic.StoreInt32(&testFinished, 1)
  521. }()
  522. // Wait for the controller to finish the test function.
  523. for atomic.LoadInt32(&testFinished) == 0 {
  524. time.Sleep(time.Millisecond * 10)
  525. }
  526. return testError
  527. }
  528. }
  529. func evaluateTestResults(ctrl *PersistentVolumeController, reactor *pvtesting.VolumeReactor, test controllerTest, t *testing.T) {
  530. // Evaluate results
  531. if err := reactor.CheckClaims(test.expectedClaims); err != nil {
  532. t.Errorf("Test %q: %v", test.name, err)
  533. }
  534. if err := reactor.CheckVolumes(test.expectedVolumes); err != nil {
  535. t.Errorf("Test %q: %v", test.name, err)
  536. }
  537. if err := checkEvents(t, test.expectedEvents, ctrl); err != nil {
  538. t.Errorf("Test %q: %v", test.name, err)
  539. }
  540. }
  541. // Test single call to syncClaim and syncVolume methods.
  542. // For all tests:
  543. // 1. Fill in the controller with initial data
  544. // 2. Call the tested function (syncClaim/syncVolume) via
  545. // controllerTest.testCall *once*.
  546. // 3. Compare resulting volumes and claims with expected volumes and claims.
  547. func runSyncTests(t *testing.T, tests []controllerTest, storageClasses []*storage.StorageClass, pods []*v1.Pod) {
  548. for _, test := range tests {
  549. klog.V(4).Infof("starting test %q", test.name)
  550. // Initialize the controller
  551. client := &fake.Clientset{}
  552. ctrl, err := newTestController(client, nil, true)
  553. if err != nil {
  554. t.Fatalf("Test %q construct persistent volume failed: %v", test.name, err)
  555. }
  556. reactor := newVolumeReactor(client, ctrl, nil, nil, test.errors)
  557. for _, claim := range test.initialClaims {
  558. ctrl.claims.Add(claim)
  559. }
  560. for _, volume := range test.initialVolumes {
  561. ctrl.volumes.store.Add(volume)
  562. }
  563. reactor.AddClaims(test.initialClaims)
  564. reactor.AddVolumes(test.initialVolumes)
  565. // Inject classes into controller via a custom lister.
  566. indexer := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{})
  567. for _, class := range storageClasses {
  568. indexer.Add(class)
  569. }
  570. ctrl.classLister = storagelisters.NewStorageClassLister(indexer)
  571. podIndexer := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{})
  572. for _, pod := range pods {
  573. podIndexer.Add(pod)
  574. }
  575. ctrl.podLister = corelisters.NewPodLister(podIndexer)
  576. // Run the tested functions
  577. err = test.test(ctrl, reactor.VolumeReactor, test)
  578. if err != nil {
  579. t.Errorf("Test %q failed: %v", test.name, err)
  580. }
  581. // Wait for the target state
  582. err = reactor.waitTest(test)
  583. if err != nil {
  584. t.Errorf("Test %q failed: %v", test.name, err)
  585. }
  586. evaluateTestResults(ctrl, reactor.VolumeReactor, test, t)
  587. }
  588. }
  589. // Test multiple calls to syncClaim/syncVolume and periodic sync of all
  590. // volume/claims. For all tests, the test follows this pattern:
  591. // 0. Load the controller with initial data.
  592. // 1. Call controllerTest.testCall() once as in TestSync()
  593. // 2. For all volumes/claims changed by previous syncVolume/syncClaim calls,
  594. // call appropriate syncVolume/syncClaim (simulating "volume/claim changed"
  595. // events). Go to 2. if these calls change anything.
  596. // 3. When all changes are processed and no new changes were made, call
  597. // syncVolume/syncClaim on all volumes/claims (simulating "periodic sync").
  598. // 4. If some changes were done by step 3., go to 2. (simulation of
  599. // "volume/claim updated" events, eventually performing step 3. again)
  600. // 5. When 3. does not do any changes, finish the tests and compare final set
  601. // of volumes/claims with expected claims/volumes and report differences.
  602. // Some limit of calls in enforced to prevent endless loops.
  603. func runMultisyncTests(t *testing.T, tests []controllerTest, storageClasses []*storage.StorageClass, defaultStorageClass string) {
  604. for _, test := range tests {
  605. klog.V(4).Infof("starting multisync test %q", test.name)
  606. // Initialize the controller
  607. client := &fake.Clientset{}
  608. ctrl, err := newTestController(client, nil, true)
  609. if err != nil {
  610. t.Fatalf("Test %q construct persistent volume failed: %v", test.name, err)
  611. }
  612. // Inject classes into controller via a custom lister.
  613. indexer := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{})
  614. for _, class := range storageClasses {
  615. indexer.Add(class)
  616. }
  617. ctrl.classLister = storagelisters.NewStorageClassLister(indexer)
  618. reactor := newVolumeReactor(client, ctrl, nil, nil, test.errors)
  619. for _, claim := range test.initialClaims {
  620. ctrl.claims.Add(claim)
  621. }
  622. for _, volume := range test.initialVolumes {
  623. ctrl.volumes.store.Add(volume)
  624. }
  625. reactor.AddClaims(test.initialClaims)
  626. reactor.AddVolumes(test.initialVolumes)
  627. // Run the tested function
  628. err = test.test(ctrl, reactor.VolumeReactor, test)
  629. if err != nil {
  630. t.Errorf("Test %q failed: %v", test.name, err)
  631. }
  632. // Simulate any "changed" events and "periodical sync" until we reach a
  633. // stable state.
  634. firstSync := true
  635. counter := 0
  636. for {
  637. counter++
  638. klog.V(4).Infof("test %q: iteration %d", test.name, counter)
  639. if counter > 100 {
  640. t.Errorf("Test %q failed: too many iterations", test.name)
  641. break
  642. }
  643. // Wait for all goroutines to finish
  644. reactor.waitForIdle()
  645. obj := reactor.PopChange()
  646. if obj == nil {
  647. // Nothing was changed, should we exit?
  648. if firstSync || reactor.GetChangeCount() > 0 {
  649. // There were some changes after the last "periodic sync".
  650. // Simulate "periodic sync" of everything (until it produces
  651. // no changes).
  652. firstSync = false
  653. klog.V(4).Infof("test %q: simulating periodical sync of all claims and volumes", test.name)
  654. reactor.SyncAll()
  655. } else {
  656. // Last sync did not produce any updates, the test reached
  657. // stable state -> finish.
  658. break
  659. }
  660. }
  661. // waiting here cools down exponential backoff
  662. time.Sleep(600 * time.Millisecond)
  663. // There were some changes, process them
  664. switch obj.(type) {
  665. case *v1.PersistentVolumeClaim:
  666. claim := obj.(*v1.PersistentVolumeClaim)
  667. // Simulate "claim updated" event
  668. ctrl.claims.Update(claim)
  669. err = ctrl.syncClaim(claim)
  670. if err != nil {
  671. if err == pvtesting.ErrVersionConflict {
  672. // Ignore version errors
  673. klog.V(4).Infof("test intentionaly ignores version error.")
  674. } else {
  675. t.Errorf("Error calling syncClaim: %v", err)
  676. // Finish the loop on the first error
  677. break
  678. }
  679. }
  680. // Process generated changes
  681. continue
  682. case *v1.PersistentVolume:
  683. volume := obj.(*v1.PersistentVolume)
  684. // Simulate "volume updated" event
  685. ctrl.volumes.store.Update(volume)
  686. err = ctrl.syncVolume(volume)
  687. if err != nil {
  688. if err == pvtesting.ErrVersionConflict {
  689. // Ignore version errors
  690. klog.V(4).Infof("test intentionaly ignores version error.")
  691. } else {
  692. t.Errorf("Error calling syncVolume: %v", err)
  693. // Finish the loop on the first error
  694. break
  695. }
  696. }
  697. // Process generated changes
  698. continue
  699. }
  700. }
  701. evaluateTestResults(ctrl, reactor.VolumeReactor, test, t)
  702. klog.V(4).Infof("test %q finished after %d iterations", test.name, counter)
  703. }
  704. }
  705. // Dummy volume plugin for provisioning, deletion and recycling. It contains
  706. // lists of expected return values to simulate errors.
  707. type mockVolumePlugin struct {
  708. provisionCalls []provisionCall
  709. provisionCallCounter int
  710. deleteCalls []error
  711. deleteCallCounter int
  712. recycleCalls []error
  713. recycleCallCounter int
  714. provisionOptions vol.VolumeOptions
  715. }
  716. type provisionCall struct {
  717. expectedParameters map[string]string
  718. ret error
  719. }
  720. var _ vol.VolumePlugin = &mockVolumePlugin{}
  721. var _ vol.RecyclableVolumePlugin = &mockVolumePlugin{}
  722. var _ vol.DeletableVolumePlugin = &mockVolumePlugin{}
  723. var _ vol.ProvisionableVolumePlugin = &mockVolumePlugin{}
  724. func (plugin *mockVolumePlugin) Init(host vol.VolumeHost) error {
  725. return nil
  726. }
  727. func (plugin *mockVolumePlugin) GetPluginName() string {
  728. return mockPluginName
  729. }
  730. func (plugin *mockVolumePlugin) GetVolumeName(spec *vol.Spec) (string, error) {
  731. return spec.Name(), nil
  732. }
  733. func (plugin *mockVolumePlugin) CanSupport(spec *vol.Spec) bool {
  734. return true
  735. }
  736. func (plugin *mockVolumePlugin) RequiresRemount() bool {
  737. return false
  738. }
  739. func (plugin *mockVolumePlugin) SupportsMountOption() bool {
  740. return false
  741. }
  742. func (plugin *mockVolumePlugin) SupportsBulkVolumeVerification() bool {
  743. return false
  744. }
  745. func (plugin *mockVolumePlugin) ConstructVolumeSpec(volumeName, mountPath string) (*vol.Spec, error) {
  746. return nil, nil
  747. }
  748. func (plugin *mockVolumePlugin) NewMounter(spec *vol.Spec, podRef *v1.Pod, opts vol.VolumeOptions) (vol.Mounter, error) {
  749. return nil, fmt.Errorf("Mounter is not supported by this plugin")
  750. }
  751. func (plugin *mockVolumePlugin) NewUnmounter(name string, podUID types.UID) (vol.Unmounter, error) {
  752. return nil, fmt.Errorf("Unmounter is not supported by this plugin")
  753. }
  754. // Provisioner interfaces
  755. func (plugin *mockVolumePlugin) NewProvisioner(options vol.VolumeOptions) (vol.Provisioner, error) {
  756. if len(plugin.provisionCalls) > 0 {
  757. // mockVolumePlugin directly implements Provisioner interface
  758. klog.V(4).Infof("mock plugin NewProvisioner called, returning mock provisioner")
  759. plugin.provisionOptions = options
  760. return plugin, nil
  761. } else {
  762. return nil, fmt.Errorf("Mock plugin error: no provisionCalls configured")
  763. }
  764. }
  765. func (plugin *mockVolumePlugin) Provision(selectedNode *v1.Node, allowedTopologies []v1.TopologySelectorTerm) (*v1.PersistentVolume, error) {
  766. if len(plugin.provisionCalls) <= plugin.provisionCallCounter {
  767. return nil, fmt.Errorf("Mock plugin error: unexpected provisioner call %d", plugin.provisionCallCounter)
  768. }
  769. var pv *v1.PersistentVolume
  770. call := plugin.provisionCalls[plugin.provisionCallCounter]
  771. if !reflect.DeepEqual(call.expectedParameters, plugin.provisionOptions.Parameters) {
  772. klog.Errorf("invalid provisioner call, expected options: %+v, got: %+v", call.expectedParameters, plugin.provisionOptions.Parameters)
  773. return nil, fmt.Errorf("Mock plugin error: invalid provisioner call")
  774. }
  775. if call.ret == nil {
  776. // Create a fake PV with known GCE volume (to match expected volume)
  777. capacity := plugin.provisionOptions.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)]
  778. accessModes := plugin.provisionOptions.PVC.Spec.AccessModes
  779. pv = &v1.PersistentVolume{
  780. ObjectMeta: metav1.ObjectMeta{
  781. Name: plugin.provisionOptions.PVName,
  782. },
  783. Spec: v1.PersistentVolumeSpec{
  784. Capacity: v1.ResourceList{
  785. v1.ResourceName(v1.ResourceStorage): capacity,
  786. },
  787. AccessModes: accessModes,
  788. PersistentVolumeReclaimPolicy: plugin.provisionOptions.PersistentVolumeReclaimPolicy,
  789. PersistentVolumeSource: v1.PersistentVolumeSource{
  790. GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{},
  791. },
  792. },
  793. Status: v1.PersistentVolumeStatus{
  794. Phase: v1.VolumeAvailable,
  795. },
  796. }
  797. pv.Spec.VolumeMode = plugin.provisionOptions.PVC.Spec.VolumeMode
  798. }
  799. plugin.provisionCallCounter++
  800. klog.V(4).Infof("mock plugin Provision call nr. %d, returning %v: %v", plugin.provisionCallCounter, pv, call.ret)
  801. return pv, call.ret
  802. }
  803. // Deleter interfaces
  804. func (plugin *mockVolumePlugin) NewDeleter(spec *vol.Spec) (vol.Deleter, error) {
  805. if len(plugin.deleteCalls) > 0 {
  806. // mockVolumePlugin directly implements Deleter interface
  807. klog.V(4).Infof("mock plugin NewDeleter called, returning mock deleter")
  808. return plugin, nil
  809. } else {
  810. return nil, fmt.Errorf("Mock plugin error: no deleteCalls configured")
  811. }
  812. }
  813. func (plugin *mockVolumePlugin) Delete() error {
  814. if len(plugin.deleteCalls) <= plugin.deleteCallCounter {
  815. return fmt.Errorf("Mock plugin error: unexpected deleter call %d", plugin.deleteCallCounter)
  816. }
  817. ret := plugin.deleteCalls[plugin.deleteCallCounter]
  818. plugin.deleteCallCounter++
  819. klog.V(4).Infof("mock plugin Delete call nr. %d, returning %v", plugin.deleteCallCounter, ret)
  820. return ret
  821. }
  822. // Volume interfaces
  823. func (plugin *mockVolumePlugin) GetPath() string {
  824. return ""
  825. }
  826. func (plugin *mockVolumePlugin) GetMetrics() (*vol.Metrics, error) {
  827. return nil, nil
  828. }
  829. // Recycler interfaces
  830. func (plugin *mockVolumePlugin) Recycle(pvName string, spec *vol.Spec, eventRecorder recyclerclient.RecycleEventRecorder) error {
  831. if len(plugin.recycleCalls) == 0 {
  832. return fmt.Errorf("Mock plugin error: no recycleCalls configured")
  833. }
  834. if len(plugin.recycleCalls) <= plugin.recycleCallCounter {
  835. return fmt.Errorf("Mock plugin error: unexpected recycle call %d", plugin.recycleCallCounter)
  836. }
  837. ret := plugin.recycleCalls[plugin.recycleCallCounter]
  838. plugin.recycleCallCounter++
  839. klog.V(4).Infof("mock plugin Recycle call nr. %d, returning %v", plugin.recycleCallCounter, ret)
  840. return ret
  841. }