framework_test.go 33 KB

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