From 2d4eb20d89892dd56f389ecdcc47e5d6f00bebf3 Mon Sep 17 00:00:00 2001 From: sp16743 Date: Wed, 2 Dec 2026 12:44:52 +0530 Subject: [PATCH 1/5] Automation for Snapshot to Volume and Template --- test/integration/plugins/ontap/README.md | 26 +- test/integration/plugins/ontap/TEST_CASES.md | 203 ++- .../plugins/ontap/helpers/snapshot_base.py | 1450 +++++++++++++++++ .../template/test_snapshot_to_template.py | 769 +++++++++ .../iscsi/volume/test_snapshot_to_volume.py | 897 ++++++++++ .../nfs3/instance/test_vm_volume_attach.py | 1184 +------------- .../template/test_snapshot_to_template.py | 769 +++++++++ .../nfs3/volume/test_snapshot_to_volume.py | 826 ++++++++++ .../plugins/ontap/ontap_test_base.py | 64 +- 9 files changed, 5000 insertions(+), 1188 deletions(-) create mode 100644 test/integration/plugins/ontap/helpers/snapshot_base.py create mode 100644 test/integration/plugins/ontap/iscsi/template/test_snapshot_to_template.py create mode 100644 test/integration/plugins/ontap/iscsi/volume/test_snapshot_to_volume.py create mode 100644 test/integration/plugins/ontap/nfs3/template/test_snapshot_to_template.py create mode 100644 test/integration/plugins/ontap/nfs3/volume/test_snapshot_to_volume.py diff --git a/test/integration/plugins/ontap/README.md b/test/integration/plugins/ontap/README.md index 6a40a1402c2e..78eabf1128fc 100644 --- a/test/integration/plugins/ontap/README.md +++ b/test/integration/plugins/ontap/README.md @@ -46,7 +46,7 @@ test/integration/plugins/ontap/ ├── guest_ssh.py # Guest SSH (paramiko) for the VM workflow suites ├── setup_env.sh # venv: Marvin plus requirements.txt ├── requirements.txt # setuptools, pyvmomi, paramiko pins -├── TEST_CASES.md # Full test case reference table (151 tests) +├── TEST_CASES.md # Full test case reference table (214 tests) ├── README.md # This file │ ├── nfs3/ @@ -55,10 +55,12 @@ test/integration/plugins/ontap/ │ │ ├── test_pool_with_volumes.py # Same lifecycle with a CS volume present │ │ └── test_zone_scoped_pool.py # Zone-scoped pool (attachZone) │ ├── volume/ -│ │ └── test_volume_lifecycle.py # Volume create/delete/negative-delete +│ │ ├── test_volume_lifecycle.py # Volume create/delete/negative-delete +│ │ └── test_snapshot_to_volume.py # Create volumes from snapshots of a running VM, attach, rejects │ ├── instance/ -│ │ └── test_vm_volume_attach.py # Pool + volume + VM + resize, snapshots, attach/detach + template cache +│ │ └── test_vm_volume_attach.py # Pool + volume + VM + resize, volume/VM snapshots, attach/detach + template cache │ └── template/ +│ ├── test_snapshot_to_template.py # Create templates from snapshots, deploy VMs from them │ └── test_template_cache_negative.py # Template-cache boundary cases │ └── iscsi/ @@ -67,10 +69,12 @@ test/integration/plugins/ontap/ │ ├── test_pool_with_volumes.py # Same lifecycle with a LUN-backed volume │ └── test_zone_scoped_pool.py # Zone-scoped iSCSI pool ├── volume/ - │ └── test_volume_lifecycle.py # LUN create/delete/negative-delete + │ ├── test_volume_lifecycle.py # LUN create/delete/negative-delete + create volume from snapshot + │ └── test_snapshot_to_volume.py # Create volumes from snapshots of a running VM, attach, rejects ├── instance/ - │ └── test_vm_volume_attach.py # Pool + LUN + VM + resize, snapshots, LUN-map lifecycle + template cache + │ └── test_vm_volume_attach.py # Pool + LUN + VM + resize, volume/VM snapshots, LUN-map lifecycle + template cache └── template/ + ├── test_snapshot_to_template.py # Create templates from snapshots, deploy VMs from them └── test_template_cache_negative.py # Template-cache boundary cases ``` @@ -140,7 +144,7 @@ The script is safe to re-run. It creates `test/integration/plugins/ontap/.venv` #### Paramiko (guest SSH) -`nfs3/instance/test_vm_volume_attach.py` and `iscsi/instance/test_vm_volume_attach.py` log into the guest through `guest_ssh.py`. The lab template is CentOS 5.5, and its sshd only offers SHA-1 key exchange (`diffie-hellman-group14-sha1`) and `ssh-rsa` host keys. Paramiko 4.x removed SHA-1, so those logins fail unless the venv has Paramiko 3.x. +The VM suites (`*/instance/test_vm_volume_attach.py`, `*/volume/test_snapshot_to_volume.py` and `*/template/test_snapshot_to_template.py`) log into the guest through `guest_ssh.py`. The lab template is CentOS 5.5, and its sshd only offers SHA-1 key exchange (`diffie-hellman-group14-sha1`) and `ssh-rsa` host keys. Paramiko 4.x removed SHA-1, so those logins fail unless the venv has Paramiko 3.x. `setup_env.sh` installs the pin from `requirements.txt`: @@ -382,13 +386,17 @@ another ONTAP pool is present. | NFS3 Pool with Volumes | `nfs3/pool/test_pool_with_volumes.py` | 12 | Lifecycle with a live volume, deletion with a pre-deleted FlexVol or export policy, and host cases for an inactive libvirt pool, a read-only NFS mount, and a deleted mount point | | NFS3 Zone-Scoped Pool | `nfs3/pool/test_zone_scoped_pool.py` | 5 | Zone-scoped pool create, grow and shrink with CloudStack/ONTAP/KVM verification, disable, enable, and delete | | NFS3 Volume Lifecycle | `nfs3/volume/test_volume_lifecycle.py` | 5 | Volume is metadata-only; FlexVol unchanged on delete | -| NFS3 VM + Volume Attach | `nfs3/instance/test_vm_volume_attach.py` | 29 | Full VM lifecycle with stopped-VM qcow2 grow, guest SSH, volume and VM snapshots; ROOT on tagged pool seeds/reuses template cache, which survives VM delete | +| NFS3 VM + Volume Attach | `nfs3/instance/test_vm_volume_attach.py` | 22 | Full VM lifecycle with stopped-VM qcow2 grow, guest SSH and VM snapshots; ROOT on tagged pool seeds/reuses template cache, which survives VM delete | +| NFS3 Snapshot to Volume | `nfs3/volume/test_snapshot_to_volume.py` | 22 | Own VM setup, then volume snapshot and revert (VM-A and VM-B), volumes created from ROOT and DATA snapshots: attach, move between VMs, independence from the source, rejects (offering, missing snapshot, disabled or second pool, missing metadata), delete-during-create | +| NFS3 Snapshot to Template | `nfs3/template/test_snapshot_to_template.py` | 16 | Own setup (pool, data volume, VM) then templates created from ROOT and DATA snapshots: deploy from them, expunged source, attributes, rejects | | NFS3 Template Cache Negative | `nfs3/template/test_template_cache_negative.py` | 3 | Tag mismatch; undersized pool; out-of-band cache delete | | iSCSI Pool Lifecycle | `iscsi/pool/test_pool_lifecycle.py` | 21 | Create rejects for aggregate space, invalid capacitybytes, and a duplicate FlexVol name; grow to 300 TiB, reject grow past 300 TiB, safe shrink, disable, resize while disabled, enable, maintenance, grow and shrink in maintenance, delete + igroups, then re-create with a volume (LUN), reject shrink below used capacity, deploy a VM and attach the volume, cleanup, plus empty-pool deletion with a pre-deleted FlexVol or igroups | | iSCSI Pool with Volumes | `iscsi/pool/test_pool_with_volumes.py` | 13 | Lifecycle with a live LUN, deletion with a pre-deleted FlexVol or igroups, maintenance with pre-deleted LUN maps, and host cases for a logged-out iSCSI session, an existing session during volume delete, and a replaced by-path symlink | | iSCSI Zone-Scoped Pool | `iscsi/pool/test_zone_scoped_pool.py` | 5 | Zone-scoped pool create, grow and shrink with CloudStack/ONTAP verification, disable, enable, and delete | | iSCSI Volume Lifecycle | `iscsi/volume/test_volume_lifecycle.py` | 5 | LUN created per CS volume; LUN removed on delete | -| iSCSI VM + Volume Attach | `iscsi/instance/test_vm_volume_attach.py` | 29 | Full VM lifecycle; stopped-VM LUN grow, LUN-map checks, guest SSH, volume and VM snapshots; ROOT on tagged pool seeds/reuses `cs_tmpl_*` LUN cache | +| iSCSI VM + Volume Attach | `iscsi/instance/test_vm_volume_attach.py` | 22 | Full VM lifecycle; stopped-VM LUN grow, LUN-map checks, guest SSH and VM snapshots; ROOT on tagged pool seeds/reuses `cs_tmpl_*` LUN cache | +| iSCSI Snapshot to Volume | `iscsi/volume/test_snapshot_to_volume.py` | 23 | Own VM setup, then volume snapshot and revert (VM-A and VM-B), volumes created from ROOT and DATA snapshots: attach, move between VMs, independence from the source, rejects (offering, missing snapshot, disabled or second pool, missing metadata, duplicate name), delete-during-create | +| iSCSI Snapshot to Template | `iscsi/template/test_snapshot_to_template.py` | 16 | Own setup (pool, data volume, VM) then templates created from ROOT and DATA snapshots: deploy from them, expunged source, attributes, rejects | | iSCSI Template Cache Negative | `iscsi/template/test_template_cache_negative.py` | 3 | Tag mismatch; undersized pool; out-of-band cache delete | For the goal, dependencies, and exact success criteria of every individual test, see [TEST_CASES.md](TEST_CASES.md). @@ -405,7 +413,7 @@ For the goal, dependencies, and exact success criteria of every individual test, | `Lost connection to MySQL` | MySQL not accepting remote connections | Enable remote MySQL access (see Prerequisites §3) | | `sh: python: command not found` (repeated) | Marvin internal call — harmless on macOS | Ignore; Marvin Init still succeeds | | Pool state never reaches `Maintenance` | KVM agent not responding | Check `cloudstack-agent` on KVM host; verify host is connected in CloudStack UI | -| iSCSI `test_24` error 530 | KVM guest does not ACK SCSI hot-unplug | Detach of the data LUN from a running VM; see TEST_CASES.md Suite 10 `test_24_detach_volume_from_vm` | +| iSCSI `test_17` error 530 | KVM guest does not ACK SCSI hot-unplug | Detach of the data LUN from a running VM; see TEST_CASES.md Suite 10 `test_17_detach_volume_from_vm` | | ONTAP REST `401 Unauthorized` | Wrong credentials in `ontap.cfg` | Verify `username`/`password` under `ontap` section | | `ISCSI protocol is not enabled on SVM` / many pool tests EXCEPTION then FAIL | SVM iSCSI service off or no `data_iscsi` LIF | Enable iSCSI on the SVM and assign `default-data-iscsi` (or `default-data-blocks`) to at least one data LIF; `run_tests.sh` now fails this check before Marvin starts | | `No ready KVM user template available` | Template still downloading | Re-run `setup_zone` (step 12 waits for template readiness); or wait in CloudStack UI | diff --git a/test/integration/plugins/ontap/TEST_CASES.md b/test/integration/plugins/ontap/TEST_CASES.md index 4145e3c5eb79..1fe600eb394a 100644 --- a/test/integration/plugins/ontap/TEST_CASES.md +++ b/test/integration/plugins/ontap/TEST_CASES.md @@ -19,7 +19,7 @@ # ONTAP Integration Test Cases -Complete reference for all 151 test cases across 12 test suites. +Complete reference for all 214 test cases across 16 test suites. Each suite is sequential — tests must run in numbered order; each step builds on state created by the previous step. --- @@ -133,7 +133,7 @@ Each suite is sequential — tests must run in numbered order; each step builds **File:** `nfs3/instance/test_vm_volume_attach.py` **Class:** `TestOntapVMVolumeAttach` **Tag:** `vm_volume_workflow` -**Total:** 29 tests | **Scope:** end-to-end — NFS3 pool, data volume resize, running VM (ROOT on the ONTAP pool via a tagged compute offering), primary template cache seed / reuse / survive VM delete, attach/detach, guest SSH, volume snapshots, and VM snapshots. Guest login uses `guest_ssh.py` (paramiko) against the CentOS 5.5 template. +**Total:** 22 tests | **Scope:** end-to-end — NFS3 pool, data volume resize, running VM (ROOT on the ONTAP pool via a tagged compute offering), primary template cache seed / reuse / survive VM delete, attach/detach, guest SSH and VM snapshots. Volume snapshot, revert and create-volume-from-snapshot cases run in the snapshot-to-volume suite; create-template-from-snapshot cases run in the snapshot-to-template suite. Guest login uses `guest_ssh.py` (paramiko) against the CentOS 5.5 template. | # | Test method | Goal | Depends on | CloudStack success criteria | ONTAP success criteria | Type | | --- | ------------- | ------ | ------------ | ----------------------------- | ------------------------ | ------ | @@ -148,27 +148,80 @@ Each suite is sequential — tests must run in numbered order; each step builds | 07 | `test_07_shrink_rejected` | Attempt to shrink the grown qcow2 volume with `shrinkok=true` | test_06 | Resize is rejected; grown size remains unchanged | qcow2 virtual size remains unchanged | negative | | 08 | `test_08_start_vm_volume_accessible` | Start the stopped VM | test_07 | `vm.state == "Running"`; KVM data-disk capacity equals target | FlexVol still `online` | positive | | 09 | `test_09_open_ssh_and_write_root_data_files` | Port-forward SSH to the guest and write ROOT and DATA marker files | test_08 (`vm`, `volume`, guest network) | ROOT and DATA both on the ONTAP pool; DATA still attached; SSH login succeeds; both markers read back | FlexVol still `online` | positive | -| 10 | `test_10_root_volume_snapshot_create` | VS-01: snapshot the ROOT volume of the running VM | test_09 | Snapshot `BackedUp`; VM stays `Running` | One new FlexVol snapshot | positive | -| 11 | `test_11_data_volume_snapshot_create` | VS-03: snapshot the attached DATA volume (kept for test_14) | test_10 | Snapshot `BackedUp`; VM stays `Running` | One new FlexVol snapshot, kept until test_14 | positive | -| 12 | `test_12_volume_revert_running_vm_rejected` | VS-19: revert a volume snapshot while the VM is Running | test_11 | Revert is rejected | FlexVol unchanged | negative | -| 13 | `test_13_root_volume_revert` | VS-11: write A, snapshot ROOT, write B, stop, revert, start | test_12 | After revert and start, ROOT marker is A | New FlexVol snapshot for the snapshot; revert snapshot removed in tearDown | positive | -| 14 | `test_14_data_volume_revert` | Snapshot DATA again, revert to the test_11 snapshot then to this one, then delete both while the VM is running | test_11, test_13 | Older revert restores the test_11 DATA marker and the later snapshot stays listed; later revert restores its marker; both snapshots are then gone and the VM stays `Running` | Both FlexVol snapshots remain through the older revert, then both are removed | positive | -| 15 | `test_15_vm_snapshot_create_running` | VMS-01: VM snapshot of the running VM (kept for test_17) | test_14 | VM snapshot `Ready`; VM stays `Running` | One new FlexVol snapshot | positive | -| 16 | `test_16_vm_snapshot_create_stopped` | VMS-03: stop, VM snapshot, start (kept for test_17) | test_15 | VM snapshot `Ready` | One new FlexVol snapshot | positive | -| 17 | `test_17_vm_snapshot_s1_running_s2_stopped_revert` | VMS-09: revert to the test_15 snapshot, then to the test_16 snapshot, then delete both while the VM is running | test_15, test_16 | Each revert finishes; guest file matches that snapshot; both VM snapshots are then gone and the VM stays `Running` | FlexVol snapshots survive the reverts, then both are removed | positive | -| 18 | `test_18_vm_snapshot_duplicate_requests` | VMS-53: two VM snapshot requests for the same VM at once | test_17 | Both snapshots `Ready` (a rejected request is retried) | Two new FlexVol snapshots | positive | -| 19 | `test_19_deploy_second_vm` | Deploy VM-B whose ROOT disk is on the same ONTAP pool | test_18 | VM-B `Running`; ROOT `storageid` = pool | ROOT file present on the shared FlexVol | positive | -| 20 | `test_20_volume_revert_leaves_other_vm_untouched` | VS-28: revert VM-A's ROOT | test_19 | VM-A's ROOT marker is restored; VM-B's file is unchanged | FlexVol stays `online` | positive | -| 21 | `test_21_concurrent_vm_snapshots_two_vms` | VMS-54: VM snapshots of both VMs at the same time | test_20 | Both VM snapshots `Ready` | Two new FlexVol snapshots | positive | -| 22 | `test_22_concurrent_volume_snapshot_and_revert` | Volume snapshot of VM-A's ROOT while VM-B's ROOT reverts | test_21 | Snapshot `BackedUp` and revert both finish (retried on error 530) | New FlexVol snapshot for the volume snapshot | positive | -| 23 | `test_23_concurrent_vm_snapshot_and_revert` | VM snapshot of VM-A while VM-B reverts to its VM snapshot | test_22 | Both operations finish; VM-A snapshot `Ready` | New FlexVol snapshot for VM-A | positive | -| 24 | `test_24_detach_volume_from_vm` | Hot-detach the ONTAP volume from the running VM (TDS Detach NFS3) | test_23 (`vm`, `volume`) | `volume.virtualmachineid` cleared; `volume.state == "Ready"` | FlexVol still `online`; data file **still present** (NFS3: file persists until `deleteVolume`, not on detach) | positive | -| 25 | `test_25_grow_detached_volume` | Grow the detached, materialized data volume | test_24 | API and DB size equal target | qcow2 virtual size equals target | positive | -| 26 | `test_26_destroy_vm_with_vm_snapshot` | VMS-38: expunge VM-B while it still has a VM snapshot | test_19 (VM-B) | VM-B no longer listed | VM-B's FlexVol snapshot removed | positive | -| 27 | `test_27_destroy_vm_and_cleanup` | Destroy VM (expunge), delete volume, enter maintenance, force-delete pool | test_25, test_26 | VM no longer listed; spool_ref still Ready after VM expunge; volume no longer listed; pool no longer listed | Cache file present after VM expunge; FlexVol deleted; export policy deleted | cleanup | +| 10 | `test_10_vm_snapshot_create_running` | VMS-01: VM snapshot of the running VM (kept for test_12) | test_09 | VM snapshot `Ready`; VM stays `Running` | One new FlexVol snapshot | positive | +| 11 | `test_11_vm_snapshot_create_stopped` | VMS-03: stop, VM snapshot, start (kept for test_12) | test_10 | VM snapshot `Ready` | One new FlexVol snapshot | positive | +| 12 | `test_12_vm_snapshot_s1_running_s2_stopped_revert` | VMS-09: revert to the test_10 snapshot, then to the test_11 snapshot, then delete both while the VM is running | test_10, test_11 | Each revert finishes; guest file matches that snapshot; both VM snapshots are then gone and the VM stays `Running` | FlexVol snapshots survive the reverts, then both are removed | positive | +| 13 | `test_13_vm_snapshot_duplicate_requests` | VMS-53: two VM snapshot requests for the same VM at once | test_12 | Both snapshots `Ready` (a rejected request is retried) | Two new FlexVol snapshots | positive | +| 14 | `test_14_deploy_second_vm` | Deploy VM-B whose ROOT disk is on the same ONTAP pool | test_13 | VM-B `Running`; ROOT `storageid` = pool | ROOT file present on the shared FlexVol | positive | +| 15 | `test_15_concurrent_vm_snapshots_two_vms` | VMS-54: VM snapshots of both VMs at the same time | test_14 | Both VM snapshots `Ready` | Two new FlexVol snapshots | positive | +| 16 | `test_16_concurrent_vm_snapshot_and_revert` | VM snapshot of VM-A while VM-B reverts to its VM snapshot | test_15 | Both operations finish; VM-A snapshot `Ready` | New FlexVol snapshot for VM-A | positive | +| 17 | `test_17_detach_volume_from_vm` | Hot-detach the ONTAP volume from the running VM (TDS Detach NFS3) | test_16 (`vm`, `volume`) | `volume.virtualmachineid` cleared; `volume.state == "Ready"` | FlexVol still `online`; data file **still present** (NFS3: file persists until `deleteVolume`, not on detach) | positive | +| 18 | `test_18_grow_detached_volume` | Grow the detached, materialized data volume | test_17 | API and DB size equal target | qcow2 virtual size equals target | positive | +| 19 | `test_19_destroy_vm_with_vm_snapshot` | VMS-38: expunge VM-B while it still has a VM snapshot | test_14 (VM-B) | VM-B no longer listed | VM-B's FlexVol snapshot removed | positive | +| 20 | `test_20_destroy_vm_and_cleanup` | Destroy VM (expunge), delete volume, enter maintenance, force-delete pool | test_18, test_19 | VM no longer listed; spool_ref still Ready after VM expunge; volume no longer listed; pool no longer listed | Cache file present after VM expunge; FlexVol deleted; export policy deleted | cleanup | --- +## Suite 5a — NFS3 Snapshot to Volume + +**File:** `nfs3/volume/test_snapshot_to_volume.py` +**Class:** `TestOntapNfs3SnapshotToVolume` +**Tag:** `nfs3_snapshot_to_volume` +**Total:** 22 tests | **Scope:** create volumes from ROOT and DATA volume snapshots of a running VM, attach them to VMs and check them in CloudStack and ONTAP. Moved out of the VM suite because the full VM suite takes a long time; setup (01–06) and cleanup reuse the same steps. Run this suite in full. + +| # | Test method | Goal | Depends on | CloudStack success criteria | ONTAP success criteria | Type | +| --- | ------------- | ------ | ------------ | ----------------------------- | ------------------------ | ------ | +| 01 | `test_01_create_nfs3_pool` | Create the NFS3 primary storage pool on ONTAP | setUpClass | `pool.state == "Up"` | FlexVol `online` | positive | +| 02 | `test_02_prepare_vm_with_data_volume` | Create the data volume, deploy VM-A, attach the volume, open SSH and write ROOT and DATA files | test_01 (`pool`) | Volume Ready and attached; VM-A Running; both markers read back | FlexVol online; source files present | positive | +| 03 | `test_03_deploy_second_vm` | Deploy a second VM on the same pool | test_05 | VM-B `Running`; ROOT on the pool | ROOT file present on the shared FlexVol | positive | +| 04 | `test_04_create_volume_from_root_snapshot` | Create a volume from a ROOT snapshot of the running VM | setup tests 01–03 (`vm`) | Volume `Ready` on the test pool; type `DATADISK`; `volumes.format` is `QCOW2` | Clone file (named after the volume UUID) exists in the FlexVol; removed after the clone is deleted | positive | +| 05 | `test_05_create_volume_from_data_snapshot` | Create a volume from a DATA snapshot, attach it to the running VM and read the snapshot-time marker | setup tests 01–03 (`vm`, `volume`) | Clone `Ready`; marker is the snapshot-time token, not the one written after the snapshot; clone detaches and is deleted | Clone has its own file; file removed after the delete | positive | +| 06 | `test_03_detach_and_reattach_clone_on_second_vm` | Write to a clone on VM-A, detach it, attach it to VM-B and read it back | setup tests 01–03 (`vm2`) | Write reads back on VM-A; same data reads on VM-B | Clone file stays in the FlexVol while detached; removed after the delete | positive | +| 07 | `test_04_clone_is_independent_of_source` | Write to a clone, then to its source, and check each keeps its own data | setup tests 01–03 (`vm`, `volume`) | Clone holds the snapshot-time token; a write to the clone leaves the source marker unchanged; a write to the source leaves the clone marker unchanged | Clone file removed after the delete | positive | +| 08 | `test_05_reject_clone_from_vm_snapshot` | Pass a VM snapshot ID to `createVolume` | setup tests 01–03 (`vm`) | Request is rejected naming `snapshotid` (does not exist); no volume record is left behind; the VM snapshot stays `Ready` | No file is added to the FlexVol | negative | +| 09 | `test_06_reject_smaller_offering_for_root_snapshot` | Create a volume from a ROOT snapshot with a disk offering smaller than the ROOT disk | setup tests 01–03 (`vm`) | Request is rejected with `Invalid size for volume creation`; no volume record is left behind | No file is added to the FlexVol | negative | +| 10 | `test_07_reject_attach_of_attached_clone_to_second_vm` | Attach a clone to VM-A, then attach it to VM-B without detaching | setup tests 01–03 (`vm`, `vm2`) | Second attach is rejected because the volume is already attached (`Please specify a volume that is not attached to any VM`); clone still references VM-A; VM-A still reads its marker; VM-B sees no new disk | Clone file stays in the FlexVol and no file is added (NFS3 has no per-volume access map) | negative | +| 11 | `test_08_delete_snapshot_during_create` | Submit `createVolume` from a DATA snapshot without waiting, then delete the snapshot while the create is in flight | setup tests 01–03 (`vm`, `volume`) | Outcome is deterministic: if the create succeeds, the clone is `Ready` as `QCOW2` and is cleaned up; if it fails, no volume record is left behind. The snapshot is gone from CloudStack and ONTAP either way; the VM stays `Running` | Exactly one new file for the clone when it succeeds; no file added when it fails; FlexVol file set returns to baseline | positive or negative (race) | +| 12 | `test_09_create_volume_keeps_offering_and_size` | `createVolume(snapshotid)` with no disk offering; the clone takes the source's offering and size | setup tests 01–03 (`vm`, `volume`) | Clone Ready as DATADISK on the pool, QCOW2; same offering and size as the source; no `cloneOfSnapshot` detail | One new file for the clone; source file unchanged | positive | +| 13 | `test_10_reject_disk_offering_with_snapshot` | Pass both `snapshotid` and `diskofferingid` | setup tests 01–03 (`vm`) | Rejected with `Disk Offering ID cannot be passed`; no volume record left | No file added to the FlexVol | negative | +| 14 | `test_11_create_volumes_concurrently_from_snapshot` | Three `createVolume(snapshotid)` requests at the same moment | setup tests 01–03 (`vm`) | All Ready as distinct DATADISK volumes on the pool | Exactly three new files, one per volume | positive | +| 15 | `test_12_create_volume_after_source_deleted` | Snapshot a second data volume, delete it, then clone from the kept snapshot | setup tests 01–03 (`pool`) | Clone Ready as QCOW2 on the pool | Source file removed when the source is deleted; clone has its own file | positive | +| 16 | `test_13_create_volume_from_snapshot_of_clone` | Snapshot a clone, then create a volume from that snapshot | setup tests 01–03 (`vm`, `volume`) | Snapshot of the clone `BackedUp`; new volume Ready as QCOW2 | Own FlexVol snapshot; new volume has its own file | positive | +| 17 | `test_14_reject_create_when_ontap_snapshot_missing` | Delete a snapshot's FlexVol snapshot on ONTAP, then `createVolume` from the CloudStack snapshot | setup tests 01–03 (`vm`) | Request fails; no usable volume record | No file added to the FlexVol | negative | +| 18 | `test_15_reject_create_on_disabled_pool` | Disable the pool; create is rejected; enable it again; the same snapshot then gives a clone | setup tests 01–03 (`vm`) | Rejected while Disabled; clone Ready once the pool is `Up` | No file added while Disabled | negative then positive | +| 19 | `test_16_reject_nonexistent_snapshot` | `createVolume` with a random snapshot UUID | setup tests 01–03 | Rejected as an unknown `snapshotid`; no volume record left | No file added | negative | +| 20 | `test_17_reject_create_on_different_pool` | Create a second pool and disable the suite pool so only the second can be chosen | setup tests 01–03 (`vm`, `volume`) | Rejected; suite pool re-enabled and second pool removed | No file added to either pool's FlexVol | negative | +| 21 | `test_18_reject_create_with_missing_snapshot_metadata` | Delete each required `snapshot_details` row in turn, attempt the create, restore the row | setup tests 01–03 (`vm`) | Each attempt rejected; with all rows restored a clone is created | No file added while a row is missing | negative then positive | +| 22 | `test_19_destroy_vm_and_cleanup` | Destroy the VMs, delete the data volume and the pool | test_21 | VMs and volume no longer listed; pool no longer listed | FlexVol deleted; export policy deleted | cleanup | + +--- +## Suite 5b — NFS3 Snapshot to Template + +**File:** `nfs3/template/test_snapshot_to_template.py` +**Class:** `TestOntapNfs3SnapshotToTemplate` +**Tag:** `nfs3_snapshot_to_template` +**Total:** 16 tests | **Scope:** create templates from ROOT and DATA volume snapshots, deploy VMs from them and check the results in CloudStack and ONTAP. Moved out of the VM suite because the full VM suite takes a long time; setup (01–05) and cleanup reuse the same steps. Run this suite in full. + +| # | Test method | Goal | Depends on | CloudStack success criteria | ONTAP success criteria | Type | +| --- | ------------- | ------ | ------------ | ----------------------------- | ------------------------ | ------ | +| 01 | `test_01_create_nfs3_pool` | Create the NFS3 primary storage pool on ONTAP | setUpClass | `pool.state == "Up"` | FlexVol `online` | positive | +| 02 | `test_02_create_ontap_data_volume` | Create a CloudStack data volume on the ONTAP pool | test_01 (`pool`) | Volume listed in `listVolumes` | FlexVol still `online` | positive | +| 03 | `test_03_deploy_vm` | Deploy a VM whose ROOT disk is on the ONTAP pool | test_02 (`pool`, `volume`) | `vm.state == "Running"`; ROOT on the pool | Template cache seeded | positive | +| 04 | `test_04_attach_volume_to_vm` | Attach the data volume to the running VM | test_03 (`vm`, `volume`) | `volume.virtualmachineid == vm.id` | Data volume present on the pool | positive | +| 05 | `test_05_open_ssh_and_write_root_data_files` | Open an SSH port forward; write ROOT and DATA marker files | test_04 | SSH login succeeds; both markers read back | FlexVol still `online` | positive | +| 06 | `test_06_create_template_from_root_snapshot` | Snapshot the running VM root disk, create a template, deploy a VM from it | setup tests 01–05 (`vm`) | Template is Ready; deployed VM has the file; suite VM stays Running; snapshot stays BackedUp | FlexVol snapshot remains; FlexVol files unchanged by the template create | positive | +| 07 | `test_07_template_from_older_root_snapshot` | Two ROOT snapshots taken in order; template from the older one | setup tests 01–05 (`vm`) | Deployed VM has the older file and not the newer one | Both FlexVol snapshots remain | positive | +| 08 | `test_08_two_templates_from_two_snapshots` | Two createTemplate calls at the same time, one per snapshot | setup tests 01–05 (`vm`) | Both templates Ready and distinct; both snapshots BackedUp | Both FlexVol snapshots remain; FlexVol files unchanged | positive | +| 09 | `test_09_delete_template_keeps_snapshot` | Delete the template | setup tests 01–05 (`vm`) | Template gone; snapshot BackedUp | FlexVol snapshot remains | positive | +| 10 | `test_10_delete_snapshot_keeps_template` | Delete the source snapshot after the template is Ready | setup tests 01–05 (`vm`) | Template still Ready and deploys with the file | FlexVol snapshot removed; template unaffected | positive | +| 11 | `test_11_template_stores_attributes` | Create with password-enabled and dynamically-scalable set | setup tests 01–05 (`vm`) | Template stores both flags and the suite OS type | Snapshot remains | positive | +| 12 | `test_12_template_after_vm_expunged` | Snapshot a VM, expunge it, then create the template | setup tests 01–05 (`vm`) | Template Ready; deploys with the file | Snapshot remains | positive | +| 13 | `test_13_data_snapshot_template_unbootable` | Template from a DATA snapshot; deploy from it | setup tests 01–05 (`vm`, `volume`) | Deploy succeeds and the VM reaches Running; on the KVM host libvirt reports it running and its root disk read counter stays flat and under 8 MiB (no OS loaded); SSH is unreachable | Snapshot remains | negative | +| 14 | `test_14_reject_missing_template_fields` | createTemplate with an empty name, then with no OS type | setup tests 01–05 (`vm`) | Both calls rejected; no template created | FlexVol files unchanged; snapshot remains | negative | +| 15 | `test_15_reject_second_template_same_snapshot` | Two createTemplate calls for one snapshot at the same time | setup tests 01–05 (`vm`) | One succeeds and is Ready; the other is rejected with a concurrent or duplicate-state error; the loser is not Ready, no template stays in Creating, the account gains exactly one template, the snapshot returns to BackedUp | Snapshot remains; FlexVol files unchanged | negative | +| 16 | `test_16_destroy_vm_and_cleanup` | Destroy the VM, delete the data volume and the pool | test_15 | VM and volume no longer listed; pool no longer listed | FlexVol deleted; export policy deleted | cleanup | + +--- ## Suite 6 — iSCSI Pool Lifecycle **File:** `iscsi/pool/test_pool_lifecycle.py` @@ -266,7 +319,7 @@ Each suite is sequential — tests must run in numbered order; each step builds **File:** `iscsi/instance/test_vm_volume_attach.py` **Class:** `TestOntapVMVolumeAttachISCSI` **Tag:** `iscsi_vm_workflow` -**Total:** 29 tests | **Scope:** end-to-end — iSCSI pool, data volume resize (LUN), running VM (ROOT on the ONTAP pool via a tagged compute offering), `cs_tmpl_` LUN cache seed / reuse / survive VM delete, attach/stop/start/detach, guest SSH, volume snapshots, and VM snapshots. LUN-map checks are limited to the data volume's LUN. Guest login uses `guest_ssh.py` (paramiko) against the CentOS 5.5 template. +**Total:** 22 tests | **Scope:** end-to-end — iSCSI pool, data volume resize (LUN), running VM (ROOT on the ONTAP pool via a tagged compute offering), `cs_tmpl_` LUN cache seed / reuse / survive VM delete, attach/stop/start/detach, guest SSH and VM snapshots. Volume snapshot, revert and create-volume-from-snapshot cases run in the snapshot-to-volume suite; create-template-from-snapshot cases run in the snapshot-to-template suite. LUN-map checks are limited to the data volume's LUN. Guest login uses `guest_ssh.py` (paramiko) against the CentOS 5.5 template. | # | Test method | Goal | Depends on | CloudStack success criteria | ONTAP success criteria | Type | | --- | ------------- | ------ | ------------ | ----------------------------- | ------------------------ | ------ | @@ -281,29 +334,83 @@ Each suite is sequential — tests must run in numbered order; each step builds | 07 | `test_07_shrink_rejected` | Attempt to shrink the grown LUN with `shrinkok=true` | test_06 | Resize is rejected; grown size remains unchanged | LUN `space.size` remains unchanged | negative | | 08 | `test_08_start_vm_lun_remapped` | Start VM — LUN-maps must be re-created (TDS VM Start iSCSI) | test_07 | `vm.state == "Running"` | ≥1 LUN-map re-created | positive | | 09 | `test_09_open_ssh_and_write_root_data_files` | Port-forward SSH to the guest and write ROOT and DATA marker files | test_08 (`vm`, `volume`, guest network) | ROOT and DATA both on the ONTAP pool; DATA still attached; SSH login succeeds; both markers read back | Data LUN still mapped | positive | -| 10 | `test_10_root_volume_snapshot_create` | VS-01: snapshot the ROOT volume of the running VM | test_09 | Snapshot `BackedUp`; VM stays `Running` | One new FlexVol snapshot | positive | -| 11 | `test_11_data_volume_snapshot_create` | VS-03: snapshot the attached DATA volume (kept for test_14) | test_10 | Snapshot `BackedUp`; VM stays `Running` | One new FlexVol snapshot, kept until test_14 | positive | -| 12 | `test_12_volume_revert_running_vm_rejected` | VS-20: revert a volume snapshot while the VM is Running | test_11 | Revert is rejected | FlexVol unchanged | negative | -| 13 | `test_13_root_volume_revert` | VS-12: write A, snapshot ROOT, write B, stop, revert, start | test_12 | After revert and start, ROOT marker is A | New FlexVol snapshot for the snapshot; revert snapshot removed in tearDown | positive | -| 14 | `test_14_data_volume_revert` | Snapshot DATA again, revert to the test_11 snapshot then to this one, then delete both while the VM is running | test_11, test_13 | Older revert restores the test_11 DATA marker and the later snapshot stays listed; later revert restores its marker; both snapshots are then gone and the VM stays `Running` | Both FlexVol snapshots remain through the older revert, then both are removed | positive | -| 15 | `test_15_vm_snapshot_create_running` | VM snapshot of the running VM, ROOT + DATA LUNs (kept for test_17) | test_14 | VM snapshot `Ready`; VM stays `Running` | One new FlexVol snapshot | positive | -| 16 | `test_16_vm_snapshot_create_stopped` | Stop, VM snapshot, start (kept for test_17) | test_15 | VM snapshot `Ready` | One new FlexVol snapshot | positive | -| 17 | `test_17_vm_snapshot_s1_running_s2_stopped_revert` | VMS-09: revert to the test_15 snapshot, then to the test_16 snapshot, then delete both while the VM is running | test_15, test_16 | Each revert finishes; guest file matches that snapshot; both VM snapshots are then gone and the VM stays `Running` | FlexVol snapshots survive the reverts, then both are removed | positive | -| 18 | `test_18_vm_snapshot_duplicate_requests` | VMS-53: two VM snapshot requests for the same VM at once | test_17 | Both snapshots `Ready` (a rejected request is retried) | Two new FlexVol snapshots | positive | -| 19 | `test_19_deploy_second_vm` | Deploy VM-B whose ROOT LUN is on the same ONTAP pool | test_18 | VM-B `Running`; ROOT on pool | One more non-cache LUN; `cs_tmpl_*` still one | positive | -| 20 | `test_20_volume_revert_leaves_other_vm_untouched` | VS-28: revert VM-A's ROOT | test_19 | VM-A's ROOT marker is restored; VM-B's file is unchanged | FlexVol stays `online`; both ROOT LUNs remain | positive | -| 21 | `test_21_concurrent_vm_snapshots_two_vms` | VMS-55: VM snapshots of both VMs at the same time | test_20 | Both VM snapshots `Ready` | Two new FlexVol snapshots | positive | -| 22 | `test_22_concurrent_volume_snapshot_and_revert` | Volume snapshot of VM-A's ROOT while VM-B's ROOT reverts | test_21 | Snapshot `BackedUp` and revert both finish (retried on error 530) | New FlexVol snapshot for the volume snapshot | positive | -| 23 | `test_23_concurrent_vm_snapshot_and_revert` | VM snapshot of VM-A while VM-B reverts to its VM snapshot | test_22 | Both operations finish; VM-A snapshot `Ready` | New FlexVol snapshot for VM-A | positive | -| 24 | `test_24_detach_volume_from_vm` | Hot-detach the iSCSI volume from the running VM (TDS Detach iSCSI) | test_23 (`vm`, `volume`) | `volume.virtualmachineid` cleared | 0 LUN-maps for the data LUN; LUN still in FlexVol | positive ⚠️ | -| 25 | `test_25_grow_detached_volume` | Grow the detached, materialized data volume | test_24 | API and DB size equal target | LUN `space.size` equals target | positive | -| 26 | `test_26_destroy_vm_with_vm_snapshot` | Expunge VM-B while it still has a VM snapshot | test_19 (VM-B) | VM-B no longer listed | VM-B ROOT LUN gone; `cs_tmpl_*` still present | positive | -| 27 | `test_27_destroy_vm_and_cleanup` | Destroy VM (expunge), delete volume, enter maintenance, delete pool | test_25, test_26 | VM gone; spool_ref still Ready after VM expunge; volume gone; pool gone | `cs_tmpl_*` present after VM expunge; FlexVol deleted; all LUNs and igroups deleted | cleanup | - -> ⚠️ **test_24 known status:** iSCSI hot-detach from a running VM relies on the KVM guest acknowledging the SCSI device removal. On this environment the guest does not acknowledge in time, causing CloudStack error 530. This is a KVM-host-level or guest-template limitation, not a test code defect. +| 10 | `test_10_vm_snapshot_create_running` | VM snapshot of the running VM, ROOT + DATA LUNs (kept for test_12) | test_09 | VM snapshot `Ready`; VM stays `Running` | One new FlexVol snapshot | positive | +| 11 | `test_11_vm_snapshot_create_stopped` | Stop, VM snapshot, start (kept for test_12) | test_10 | VM snapshot `Ready` | One new FlexVol snapshot | positive | +| 12 | `test_12_vm_snapshot_s1_running_s2_stopped_revert` | VMS-09: revert to the test_10 snapshot, then to the test_11 snapshot, then delete both while the VM is running | test_10, test_11 | Each revert finishes; guest file matches that snapshot; both VM snapshots are then gone and the VM stays `Running` | FlexVol snapshots survive the reverts, then both are removed | positive | +| 13 | `test_13_vm_snapshot_duplicate_requests` | VMS-53: two VM snapshot requests for the same VM at once | test_12 | Both snapshots `Ready` (a rejected request is retried) | Two new FlexVol snapshots | positive | +| 14 | `test_14_deploy_second_vm` | Deploy VM-B whose ROOT LUN is on the same ONTAP pool | test_13 | VM-B `Running`; ROOT on pool | One more non-cache LUN; `cs_tmpl_*` still one | positive | +| 15 | `test_15_concurrent_vm_snapshots_two_vms` | VMS-55: VM snapshots of both VMs at the same time | test_14 | Both VM snapshots `Ready` | Two new FlexVol snapshots | positive | +| 16 | `test_16_concurrent_vm_snapshot_and_revert` | VM snapshot of VM-A while VM-B reverts to its VM snapshot | test_15 | Both operations finish; VM-A snapshot `Ready` | New FlexVol snapshot for VM-A | positive | +| 17 | `test_17_detach_volume_from_vm` | Hot-detach the iSCSI volume from the running VM (TDS Detach iSCSI) | test_16 (`vm`, `volume`) | `volume.virtualmachineid` cleared | 0 LUN-maps for the data LUN; LUN still in FlexVol | positive ⚠️ | +| 18 | `test_18_grow_detached_volume` | Grow the detached, materialized data volume | test_17 | API and DB size equal target | LUN `space.size` equals target | positive | +| 19 | `test_19_destroy_vm_with_vm_snapshot` | Expunge VM-B while it still has a VM snapshot | test_14 (VM-B) | VM-B no longer listed | VM-B ROOT LUN gone; `cs_tmpl_*` still present | positive | +| 20 | `test_20_destroy_vm_and_cleanup` | Destroy VM (expunge), delete volume, enter maintenance, delete pool | test_18, test_19 | VM gone; spool_ref still Ready after VM expunge; volume gone; pool gone | `cs_tmpl_*` present after VM expunge; FlexVol deleted; all LUNs and igroups deleted | cleanup | + +> ⚠️ **test_17 known status:** iSCSI hot-detach from a running VM relies on the KVM guest acknowledging the SCSI device removal. On this environment the guest does not acknowledge in time, causing CloudStack error 530. This is a KVM-host-level or guest-template limitation, not a test code defect. --- +## Suite 10a — iSCSI Snapshot to Volume + +**File:** `iscsi/volume/test_snapshot_to_volume.py` +**Class:** `TestOntapIscsiSnapshotToVolume` +**Tag:** `iscsi_snapshot_to_volume` +**Total:** 23 tests | **Scope:** create volumes from ROOT and DATA volume snapshots of a running VM, attach them to VMs and check them in CloudStack and ONTAP. Moved out of the VM suite because the full VM suite takes a long time; setup (01–06) and cleanup reuse the same steps. Run this suite in full. + +| # | Test method | Goal | Depends on | CloudStack success criteria | ONTAP success criteria | Type | +| --- | ------------- | ------ | ------------ | ----------------------------- | ------------------------ | ------ | +| 01 | `test_01_create_iscsi_pool` | Create the iSCSI primary storage pool on ONTAP | setUpClass | `pool.state == "Up"` | FlexVol `online` | positive | +| 02 | `test_02_prepare_vm_with_data_volume` | Create the data volume, deploy VM-A, attach the volume, open SSH and write ROOT and DATA files | test_01 (`pool`) | Volume Ready and attached; VM-A Running; both markers read back | FlexVol online; ROOT and DATA LUNs present and mapped | positive | +| 03 | `test_03_deploy_second_vm` | Deploy a second VM on the same pool | test_05 | VM-B `Running`; ROOT on the pool | ROOT file present on the shared FlexVol | positive | +| 04 | `test_04_create_volume_from_root_snapshot` | Create a volume from a ROOT snapshot of the running VM | setup tests 01–03 (`vm`) | Volume `Ready` on the test pool; type `DATADISK`; `volumes.format` is `RAW` | Clone LUN exists in the FlexVol; removed after the clone is deleted | positive | +| 05 | `test_05_create_volume_from_data_snapshot` | Create a volume from a DATA snapshot, attach it to the running VM and read the snapshot-time marker | setup tests 01–03 (`vm`, `volume`) | Clone `Ready`; marker is the snapshot-time token, not the one written after the snapshot; clone detaches and is deleted | Clone has its own LUN; LUN removed after the delete | positive | +| 06 | `test_03_detach_and_reattach_clone_on_second_vm` | Write to a clone on VM-A, detach it, attach it to VM-B and read it back | setup tests 01–03 (`vm2`) | Write reads back on VM-A; same data reads on VM-B | Clone LUN stays in the FlexVol while detached; removed after the delete | positive | +| 07 | `test_04_clone_is_independent_of_source` | Write to a clone, then to its source, and check each keeps its own data | setup tests 01–03 (`vm`, `volume`) | Clone holds the snapshot-time token; a write to the clone leaves the source marker unchanged; a write to the source leaves the clone marker unchanged | Clone LUN removed after the delete | positive | +| 08 | `test_05_reject_clone_from_vm_snapshot` | Pass a VM snapshot ID to `createVolume` | setup tests 01–03 (`vm`) | Request is rejected; no volume record is left behind; the VM snapshot stays `Ready` | FlexVol gains and loses no LUN | negative | +| 09 | `test_06_reject_smaller_offering_for_root_snapshot` | Create a volume from a ROOT snapshot with a disk offering smaller than the ROOT disk | setup tests 01–03 (`vm`) | Request is rejected; no volume record is left behind | FlexVol gains and loses no LUN | negative | +| 10 | `test_07_reject_attach_of_attached_clone_to_second_vm` | Attach a clone to VM-A, then attach it to VM-B without detaching | setup tests 01–03 (`vm`, `vm2`) | Second attach is rejected because the volume is already attached (`Please specify a volume that is not attached to any VM`); clone still references VM-A; VM-A still reads its marker; VM-B sees no new disk | Clone LUN maps unchanged: VM-A's map remains, none added for VM-B | negative | +| 11 | `test_08_delete_snapshot_during_create` | Submit `createVolume` from a DATA snapshot without waiting, then delete the snapshot while the create is in flight | setup tests 01–03 (`vm`, `volume`) | Outcome is deterministic: if the create succeeds, the clone is `Ready` as `RAW` and is cleaned up; if it fails, no volume record is left behind. The snapshot is gone from CloudStack and ONTAP either way; the VM stays `Running` | Exactly one new LUN for the clone when it succeeds; no LUN added when it fails; FlexVol LUN set returns to baseline | positive or negative (race) | +| 12 | `test_09_create_volume_keeps_offering_and_size` | `createVolume(snapshotid)` with no disk offering; the clone takes the source's offering and size | setup tests 01–03 (`vm`, `volume`) | Clone Ready as DATADISK on the pool, RAW; same offering and size as the source; no `cloneOfSnapshot` detail | One new LUN for the clone; source LUN unchanged | positive | +| 13 | `test_10_reject_disk_offering_with_snapshot` | Pass both `snapshotid` and `diskofferingid` | setup tests 01–03 (`vm`) | Rejected with `Disk Offering ID cannot be passed`; no volume record left | No LUN added to the FlexVol | negative | +| 14 | `test_11_create_volumes_concurrently_from_snapshot` | Three `createVolume(snapshotid)` requests at the same moment | setup tests 01–03 (`vm`) | All Ready as distinct DATADISK volumes on the pool | Exactly three new LUNs, one per volume | positive | +| 15 | `test_12_create_volume_after_source_deleted` | Snapshot a second data volume, delete it, then clone from the kept snapshot | setup tests 01–03 (`pool`) | Clone Ready as RAW on the pool | Source LUN removed when the source is deleted; clone has its own LUN | positive | +| 16 | `test_13_create_volume_from_snapshot_of_clone` | Snapshot a clone, then create a volume from that snapshot | setup tests 01–03 (`vm`, `volume`) | Snapshot of the clone `BackedUp`; new volume Ready as RAW | Own FlexVol snapshot; new volume has its own LUN | positive | +| 17 | `test_14_reject_create_when_ontap_snapshot_missing` | Delete a snapshot's FlexVol snapshot on ONTAP, then `createVolume` from the CloudStack snapshot | setup tests 01–03 (`vm`) | Request fails; no usable volume record | No LUN added to the FlexVol | negative | +| 18 | `test_15_reject_create_on_disabled_pool` | Disable the pool; create is rejected; enable it again; the same snapshot then gives a clone | setup tests 01–03 (`vm`) | Rejected while Disabled; clone Ready once the pool is `Up` | No LUN added while Disabled | negative then positive | +| 19 | `test_16_reject_nonexistent_snapshot` | `createVolume` with a random snapshot UUID | setup tests 01–03 | Rejected as an unknown `snapshotid`; no volume record left | No LUN added | negative | +| 20 | `test_17_reject_create_on_different_pool` | Create a second pool and disable the suite pool so only the second can be chosen | setup tests 01–03 (`vm`, `volume`) | Rejected; suite pool re-enabled and second pool removed | No LUN added to either pool's FlexVol | negative | +| 21 | `test_18_reject_create_with_missing_snapshot_metadata` | Delete each required `snapshot_details` row in turn, attempt the create, restore the row | setup tests 01–03 (`vm`) | Each attempt rejected; with all rows restored a clone is created | No LUN added while a row is missing | negative then positive | +| 22 | `test_19_reject_duplicate_volume_name_from_snapshot` | Create two volumes from one snapshot with the same volume name (the LUN name is built from it) | setup tests 01–03 (`vm`, `volume`) | First volume `Ready`; second create rejected or ends in a failed state; first volume stays `Ready` | One new LUN for the first volume; the failed create adds or removes no LUN | negative | +| 23 | `test_20_destroy_vm_and_cleanup` | Destroy the VMs, delete the data volume and the pool | test_22 | VMs and volume no longer listed; pool no longer listed | FlexVol and LUNs deleted | cleanup | + +--- +## Suite 10b — iSCSI Snapshot to Template + +**File:** `iscsi/template/test_snapshot_to_template.py` +**Class:** `TestOntapIscsiSnapshotToTemplate` +**Tag:** `iscsi_snapshot_to_template` +**Total:** 16 tests | **Scope:** create templates from ROOT and DATA volume snapshots, deploy VMs from them and check the results in CloudStack and ONTAP. Moved out of the VM suite because the full VM suite takes a long time; setup (01–05) and cleanup reuse the same steps. Run this suite in full. + +| # | Test method | Goal | Depends on | CloudStack success criteria | ONTAP success criteria | Type | +| --- | ------------- | ------ | ------------ | ----------------------------- | ------------------------ | ------ | +| 01 | `test_01_create_iscsi_pool` | Create the iSCSI primary storage pool on ONTAP | setUpClass | `pool.state == "Up"` | FlexVol `online` | positive | +| 02 | `test_02_create_ontap_data_volume` | Create a CloudStack data volume on the ONTAP pool | test_01 (`pool`) | Volume listed in `listVolumes` | FlexVol still `online` | positive | +| 03 | `test_03_deploy_vm` | Deploy a VM whose ROOT disk is on the ONTAP pool | test_02 (`pool`, `volume`) | `vm.state == "Running"`; ROOT on the pool | `cs_tmpl_*` cache LUN seeded | positive | +| 04 | `test_04_attach_volume_to_vm` | Attach the data volume to the running VM | test_03 (`vm`, `volume`) | `volume.virtualmachineid == vm.id` | LUN-map created for the data volume | positive | +| 05 | `test_05_open_ssh_and_write_root_data_files` | Open an SSH port forward; write ROOT and DATA marker files | test_04 | SSH login succeeds; both markers read back | FlexVol still `online` | positive | +| 06 | `test_06_create_template_from_root_snapshot` | Snapshot the running VM root disk, create a template, deploy a VM from it | setup tests 01–05 (`vm`) | Template is Ready; deployed VM has the file; suite VM stays Running; snapshot stays BackedUp | FlexVol snapshot remains; FlexVol LUN set unchanged by the template create | positive | +| 07 | `test_07_template_from_older_root_snapshot` | Two ROOT snapshots taken in order; template from the older one | setup tests 01–05 (`vm`) | Deployed VM has the older file and not the newer one | Both FlexVol snapshots remain | positive | +| 08 | `test_08_two_templates_from_two_snapshots` | Two createTemplate calls at the same time, one per snapshot | setup tests 01–05 (`vm`) | Both templates Ready and distinct; both snapshots BackedUp | Both FlexVol snapshots remain; FlexVol LUN set unchanged | positive | +| 09 | `test_09_delete_template_keeps_snapshot` | Delete the template | setup tests 01–05 (`vm`) | Template gone; snapshot BackedUp | FlexVol snapshot remains | positive | +| 10 | `test_10_delete_snapshot_keeps_template` | Delete the source snapshot after the template is Ready | setup tests 01–05 (`vm`) | Template still Ready and deploys with the file | FlexVol snapshot removed; template unaffected | positive | +| 11 | `test_11_template_stores_attributes` | Create with password-enabled and dynamically-scalable set | setup tests 01–05 (`vm`) | Template stores both flags and the suite OS type | Snapshot remains | positive | +| 12 | `test_12_template_after_vm_expunged` | Snapshot a VM, expunge it, then create the template | setup tests 01–05 (`vm`) | Template Ready; deploys with the file | Snapshot remains | positive | +| 13 | `test_13_data_snapshot_template_unbootable` | Template from a DATA snapshot; deploy from it | setup tests 01–05 (`vm`, `volume`) | Deploy succeeds and the VM reaches Running; on the KVM host libvirt reports it running and its root disk read counter stays flat and under 8 MiB (no OS loaded); SSH is unreachable | Snapshot remains | negative | +| 14 | `test_14_reject_missing_template_fields` | createTemplate with an empty name, then with no OS type | setup tests 01–05 (`vm`) | Both calls rejected; no template created | FlexVol LUN set unchanged; snapshot remains | negative | +| 15 | `test_15_reject_second_template_same_snapshot` | Two createTemplate calls for one snapshot at the same time | setup tests 01–05 (`vm`) | One succeeds and is Ready; the other is rejected with a concurrent or duplicate-state error; the loser is not Ready, no template stays in Creating, the account gains exactly one template, the snapshot returns to BackedUp | Snapshot remains; FlexVol LUN set unchanged | negative | +| 16 | `test_16_destroy_vm_and_cleanup` | Destroy the VM, delete the data volume and the pool | test_15 | VM and volume no longer listed; pool no longer listed | FlexVol and LUNs deleted | cleanup | + +--- ## Suite 11 — NFS3 Template Cache Negative / Boundary **File:** `nfs3/template/test_template_cache_negative.py` @@ -341,13 +448,17 @@ Each suite is sequential — tests must run in numbered order; each step builds | NFS3 Pool Lifecycle | NFS3 | Cluster | 21 | ✅ | | NFS3 Pool with Volumes | NFS3 | Cluster | 12 | ✅ | | NFS3 Zone-Scoped Pool | NFS3 | Zone | 5 | ✅ | -| NFS3 Volume Lifecycle | NFS3 | Cluster | 5 | ✅ | -| NFS3 VM + Volume Attach | NFS3 | Cluster | 29 | ⏳ resize and snapshot cases pending lab validation | +| NFS3 Volume Lifecycle | NFS3 | Cluster | 5 | Original pure volume lifecycle suite | +| NFS3 VM + Volume Attach | NFS3 | Cluster | 22 | ⏳ resize and snapshot cases pending lab validation | +| NFS3 Snapshot to Volume | NFS3 | Cluster | 22 | 🆕 includes 10 cases moved from the volume lifecycle suite; not yet lab-run | +| NFS3 Snapshot to Template | NFS3 | Cluster | 16 | 🆕 split out of the VM suite; not yet lab-run | | NFS3 Template Cache Negative | NFS3 | Cluster | 3 | 🆕 | | iSCSI Pool Lifecycle | iSCSI | Cluster | 21 | ✅ | | iSCSI Pool with Volumes | iSCSI | Cluster | 13 | ✅ | | iSCSI Zone-Scoped Pool | iSCSI | Zone | 5 | ✅ | -| iSCSI Volume Lifecycle | iSCSI | Cluster | 5 | ✅ | -| iSCSI VM + Volume Attach | iSCSI | Cluster | 29 | ⏳ resize and snapshot cases pending lab validation; detach limitation | +| iSCSI Volume Lifecycle | iSCSI | Cluster | 5 | Original pure volume lifecycle suite | +| iSCSI VM + Volume Attach | iSCSI | Cluster | 22 | ⏳ resize and snapshot cases pending lab validation; detach limitation | +| iSCSI Snapshot to Volume | iSCSI | Cluster | 23 | 🆕 includes 11 cases moved from the volume lifecycle suite; not yet lab-run | +| iSCSI Snapshot to Template | iSCSI | Cluster | 16 | 🆕 split out of the VM suite; not yet lab-run | | iSCSI Template Cache Negative | iSCSI | Cluster | 3 | 🆕 | -| **Total** | | | **151** | **Resize and snapshot cases pending lab validation** | +| **Total** | | | **214** | **Resize and snapshot cases pending lab validation; snapshot-to-volume and snapshot-to-template suites not yet lab-run** | diff --git a/test/integration/plugins/ontap/helpers/snapshot_base.py b/test/integration/plugins/ontap/helpers/snapshot_base.py new file mode 100644 index 000000000000..bfea34ba5d1e --- /dev/null +++ b/test/integration/plugins/ontap/helpers/snapshot_base.py @@ -0,0 +1,1450 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +""" +Shared base for the ONTAP VM snapshot suites, for NFS3 and iSCSI. + +Holds the class setup (account, offerings, guest network, ONTAP client), the +helpers the suites share, and the steps every suite starts with: pool, data +volume, VM, attach, guest SSH, second VM and cleanup. It has no tests of its +own. Each suite subclasses OntapSnapshotBase, sets PROTOCOL to "NFS3" or "ISCSI", +and calls the steps from its own test_NN methods: + + /instance/test_vm_volume_attach.py + VM lifecycle, resize, volume and VM snapshots, reverts + /volume/test_snapshot_to_volume.py + create volumes from snapshots and attach them + /template/test_snapshot_to_template.py + create templates from snapshots and deploy from them +""" + +import base64 +import logging +import random +import re +import time +import unittest + +from marvin.cloudstackAPI import ( + attachVolume as attachVolumeAPI, + createNetwork as createNetworkAPI, + createStoragePool as createStoragePoolAPI, + createVolume as createVolumeAPI, + deleteNetwork as deleteNetworkAPI, + deleteVolume as deleteVolumeAPI, + deployVirtualMachine as deployVirtualMachineAPI, + destroyVolume as destroyVolumeAPI, + destroyVirtualMachine as destroyVirtualMachineAPI, + detachVolume as detachVolumeAPI, + enableStorageMaintenance, + listNetworkOfferings as listNetworkOfferingsAPI, + listNetworks as listNetworksAPI, + listVolumes as listVolumesAPI, + queryAsyncJobResult, + stopVirtualMachine as stopVirtualMachineAPI, + updateStoragePool as updateStoragePoolAPI, +) +from marvin.lib.base import ( + Account, + DiskOffering, + ServiceOffering, + Snapshot, + StoragePool, + VmSnapshot, +) +from marvin.codes import JOB_INPROGRESS +from marvin.lib.common import list_storage_pools + +from guest_ssh import GuestSsh, guest_credentials, new_token, open_ssh_port +from ontap_test_base import ( + OntapRestClient, + OntapTestBase, + _is_rejected, + _list_vms_cmd, + _list_vols_cmd, + _wait_for_vm_state, + get_datacenter_config, +) +from helpers import template_cache_util as tcu +from helpers.template_cache_base import ( + find_ready_kvm_template, + tagged_compute_offering_data, + template_cache_capacity_bytes, +) + + +logger = logging.getLogger("OntapSnapshotBase") + + +# What differs between the protocols: ontap.cfg key, labels, pool URL scheme and +# the names of the resources the suites create. +_PROTOCOLS = { + "NFS3": { + "label": "NFS3", + "cfg_key": "nfs3", + "pool_url": "nfs://%s/ontap", + "prefix": "OntapVMVol", + "email": "ontap-vm-vol@test.com", + "lastname": "VMVol", + "user": "ontap_vm_vol", + }, + "ISCSI": { + "label": "iSCSI", + "cfg_key": "iscsi", + "pool_url": "iscsi://%s/ontap", + "prefix": "OntapISCSIVM", + "email": "ontap-iscsi-vm@test.com", + "lastname": "iSCSI-VM", + "user": "ontap_iscsi_vm", + }, +} + + +# --------------------------------------------------------------------------- +# Test data +# --------------------------------------------------------------------------- + +class TestData: + account = "account" + ontap = "ontap" + primaryStorage = "primaryStorage" + provider = "provider" + scope = "scope" + tags = "tags" + + DETAIL_USERNAME = "username" + DETAIL_PASSWORD = "password" + DETAIL_SVM_NAME = "svmName" + DETAIL_PROTOCOL = "protocol" + DETAIL_STORAGE_IP = "storageIP" + + ONTAP_MIN_VOLUME_SIZE = 1677721600 + # Used when ontap.cfg has neither templateCacheCapacitybytes nor capacitybytes. + DEFAULT_POOL_SIZE = 50 * 1024 ** 3 + + def __init__(self, storage_ip, svm_name, username, password, + protocol="NFS3", scope="CLUSTER", provider="NetApp ONTAP", + tags=None, capacitybytes=None): + protocol = protocol.upper() + names = _PROTOCOLS[protocol] + if tags is None: + tags = "ontap-" + names["cfg_key"] + if not capacitybytes: + capacitybytes = TestData.DEFAULT_POOL_SIZE + encoded_password = base64.b64encode(password.encode()).decode() + self.testdata = { + TestData.ontap: { + TestData.DETAIL_STORAGE_IP: storage_ip, + TestData.DETAIL_SVM_NAME: svm_name, + TestData.DETAIL_USERNAME: username, + TestData.DETAIL_PASSWORD: password, + }, + TestData.account: { + "email": names["email"], + "firstname": "ONTAP", + "lastname": names["lastname"], + "username": "%s_%d" % (names["user"], random.randint(0, 9999)), + "password": "password", + }, + TestData.primaryStorage: { + "name": "%s_%d" % (names["prefix"], random.randint(0, 9999)), + TestData.scope: scope, + TestData.provider: provider, + TestData.tags: tags, + "capacitybytes": capacitybytes, + "managed": True, + "details": { + TestData.DETAIL_USERNAME: username, + TestData.DETAIL_PASSWORD: encoded_password, + TestData.DETAIL_SVM_NAME: svm_name, + TestData.DETAIL_PROTOCOL: protocol, + TestData.DETAIL_STORAGE_IP: storage_ip, + }, + }, + } + + +# Volume states that mean a create did not leave a usable volume behind. +FAILED_VOLUME_STATES = ("Error", "Destroy", "Destroyed", "Expunging", "Expunged") + +# Where the guest mounts a clone's disk, and the marker file it holds. +CLONE_MOUNT = "/mnt/clone" +CLONE_MARKER = CLONE_MOUNT + "/ontap-marker" + +# Keys read by OntapPrimaryDatastoreDriver.cloneCloudStackVolumeFromSnapshot +# (OntapStorageConstants: ONTAP_SNAP_NAME, VOLUME_PATH, PRIMARY_POOL_ID, PROTOCOL). +REQUIRED_SNAPSHOT_DETAILS = ("ontap_snap_name", "volume_path", + "primary_pool_id", "protocol") + + +def _guest_disk_names(guest): + """Names of the block disks the guest sees, such as vda or vdc.""" + out = guest.run("ls /sys/block", check=False) + return {name for name in out.split() if re.match(r"^(vd|sd)[a-z]+$", name)} + + +class OntapSnapshotBase(OntapTestBase): + """ + Shared setup, helpers and setup steps for the NFS3 and iSCSI VM snapshot suites. + + Holds no tests of its own. A suite subclasses it, sets PROTOCOL to "NFS3" + or "ISCSI", and adds its own tests. + """ + + # ---- extra shared state beyond OntapTestBase ----------------------- + vm = None # running VirtualMachine + vm2 = None # second VM (template-cache reuse, concurrent cases) + vm2_baseline_luns = None # iSCSI: non-cache LUN count before the second VM + template_id = None # KVM template ID discovered at setup + template_db_id = None # numeric vm_template.id (template_spool_ref key) + pool_db_id = None # numeric storage_pool.id (template_spool_ref key) + service_offering_id = None + network_id = None # None for Basic zones + _created_network_id = None # network created by this suite for Advanced zones + initial_volume_size = None + target_volume_size = None + volume_path = None # NFS3: data file name in the FlexVol + vm_ssh = None # (public_ip, public_port) forwarded to vm:22 + vm2_ssh = None + vm_snap_running = None # VM suite step 10 snapshot, reused by step 12 + vm_snap_stopped = None # VM suite step 11 snapshot, reused by step 12 + token_s1 = None + token_s2 = None + kept_ontap_snaps = None + pool_tags = None # storage tag shared by the pool and the disk offering + guest_user = "root" + guest_password = "password" + + @classmethod + def setUpClass(cls): + super(OntapSnapshotBase, cls).setUpClass() + testclient = super(OntapSnapshotBase, cls).getClsTestClient() + + cls.apiClient = testclient.getApiClient() + cls.dbConnection = testclient.getDbConnection() + cls._all_volume_snapshot_ids = set() + config = get_datacenter_config(testclient, cls) + + names = _PROTOCOLS[cls.PROTOCOL.upper()] + ontap_cfg = config.get("ontap", {}) + pool_cfg = config.get("storagePool", {}) + storage_ip = ontap_cfg.get("storageIP", "") + svm_name = ontap_cfg.get("svmName", "") + username = ontap_cfg.get("username", "") + password = ontap_cfg.get("password", "") + proto_cfg = pool_cfg.get("protocols", {}).get(names["cfg_key"], {}) + if not proto_cfg.get("enabled", True): + raise unittest.SkipTest( + "%s tests disabled in ontap.cfg " + "(set protocols.%s.enabled=true to enable)" + % (names["label"], names["cfg_key"]) + ) + scope = pool_cfg.get("storagePoolScope", "CLUSTER") + provider = pool_cfg.get("storagePoolProvider", "NetApp ONTAP") + # Give this suite's primary pool and offerings a unique shared tag. + # This prevents another active ONTAP pool of the same protocol from + # being selected for ROOT or DATA volume placement. + base_tag = (proto_cfg.get("storagePoolTags") + or "ontap-%s" % names["cfg_key"]) + class_name = cls.__name__.lower() + if "snapshottovolume" in class_name: + purpose = "snapshot-volume" + elif "snapshottotemplate" in class_name: + purpose = "snapshot-template" + else: + purpose = "vm-volume" + tags = "%s-%s-%d" % ( + base_tag, purpose, random.randint(100000, 999999)) + capacitybytes = template_cache_capacity_bytes(pool_cfg) + + cls.testdata = TestData( + storage_ip, svm_name, username, password, + protocol=cls.PROTOCOL.upper(), scope=scope, provider=provider, + tags=tags, capacitybytes=capacitybytes, + ).testdata + cls.ontap = OntapRestClient(storage_ip, username, password) + cls.svm_name = svm_name + cls._vol_name_prefix = names["prefix"] + + cls._setup_cloudstack_resources(config, cls.testdata[TestData.account]) + + # Snapshots and templates take the owner of the VM's volumes, so this suite + # runs as the admin account, the owner the UI shows. _setup_cloudstack_resources + # created the test account and put it in cls._cleanup, so it is still deleted. + cls.test_account = cls.account + cls.account = cls._admin_account() + + cls.guest_user, cls.guest_password = guest_credentials(config) + + # Discover a suitable user KVM template in the zone (must be fully + # downloaded; system-type templates are excluded as they cannot be + # deployed as user VMs). + template = find_ready_kvm_template(cls.apiClient, cls.zone.id) + if template is not None: + cls.template_id = template.id + cls.template_db_id = tcu.get_db_id( + cls.dbConnection, "vm_template", cls.template_id + ) + else: + logger.warning( + "No ready user KVM template found in zone '%s'. " + "Tests that deploy VMs will be skipped until a template " + "finishes downloading." % cls.zone.name + ) + cls.template_id = None + + service_offering = ServiceOffering.create( + cls.apiClient, + tagged_compute_offering_data( + tags, "Ontap%sVMSO" % cls.PROTOCOL.upper()) + ) + cls._cleanup.append(service_offering) + cls.service_offering_id = service_offering.id + + # The data volume and every clone made from its snapshots use this disk + # offering. A DATA snapshot clone cannot take an offering of its own, so + # it inherits this one. Without storage tags the allocator can place the + # clone on a plain NFS pool, which ONTAP cannot clone from. Tag it with + # the pool tag so only the ONTAP pool matches. + disk_offering = DiskOffering.create( + cls.apiClient, + { + "name": "Ontap%sVMDO_%d" % ( + cls.PROTOCOL.upper(), random.randint(0, 99999)), + "displaytext": "ONTAP %s VM test disk offering (pool tag)" + % names["label"], + "disksize": 2, + "storagetype": "shared", + "tags": tags, + }, + ) + cls._cleanup.append(disk_offering) + cls.disk_offering_id = disk_offering.id + cls.pool_tags = tags + + # Detect zone type; resolve network ID for Advanced zones + cls.network_id = None + zone_type = getattr(cls.zone, "networktype", "Basic") + if zone_type.lower() == "advanced": + # Find a network already accessible to the test account + net_cmd = listNetworksAPI.listNetworksCmd() + net_cmd.zoneid = cls.zone.id + net_cmd.account = cls.account.name + net_cmd.domainid = cls.domain.id + nets = cls.apiClient.listNetworks(net_cmd) or [] + if nets: + cls.network_id = nets[0].id + else: + # Create an Isolated guest network for the test account + no_cmd = listNetworkOfferingsAPI.listNetworkOfferingsCmd() + no_cmd.state = "Enabled" + no_cmd.guestiptype = "Isolated" + no_cmd.specifyvlan = "false" + no_offerings = cls.apiClient.listNetworkOfferings(no_cmd) or [] + snat_offering = next( + (o for o in no_offerings + if "SourceNat" in o.name and "Vpc" not in o.name + and "NSX" not in o.name and "Netris" not in o.name), + no_offerings[0] if no_offerings else None + ) + if snat_offering: + cn_cmd = createNetworkAPI.createNetworkCmd() + cn_cmd.zoneid = cls.zone.id + cn_cmd.networkofferingid = snat_offering.id + cn_cmd.name = "ontap-%s-vm-net-%d" % ( + names["cfg_key"], random.randint(0, 9999)) + cn_cmd.displaytext = "ONTAP %s VM test network" % names["label"] + cn_cmd.account = cls.account.name + cn_cmd.domainid = cls.domain.id + net = cls.apiClient.createNetwork(cn_cmd) + cls.network_id = net.id + cls._created_network_id = net.id + + @classmethod + def tearDownClass(cls): + """Destroy the VMs first, then delegate pool/volume cleanup to super.""" + cls._delete_kept_vm_snapshots() + for vm in (cls.vm2, cls.vm): + if vm is None: + continue + try: + cls._stop_and_expunge_vm(vm.id) + except Exception as e: + logger.warning("tearDownClass: could not stop/destroy VM %s: " + "%s" % (vm.id, e)) + try: + dest_cmd = destroyVirtualMachineAPI.destroyVirtualMachineCmd() + dest_cmd.id = vm.id + dest_cmd.expunge = True + cls.apiClient.destroyVirtualMachine(dest_cmd) + except Exception as de: + logger.warning("tearDownClass: could not destroy VM %s: " + "%s" % (vm.id, de)) + cls.vm2 = None + cls.vm = None + + cls._force_expunge_suite_volumes() + for snap_id in list(cls._all_volume_snapshot_ids): + try: + Snapshot({"id": snap_id}).delete(cls.apiClient) + cls._all_volume_snapshot_ids.discard(snap_id) + except Exception as exc: + logger.warning("tearDownClass: could not delete volume snapshot " + "%s after volume expunge: %s" % (snap_id, exc)) + + # Delete the guest network created for this account in Advanced zones. + if cls._created_network_id is not None: + try: + dn_cmd = deleteNetworkAPI.deleteNetworkCmd() + dn_cmd.id = cls._created_network_id + cls.apiClient.deleteNetwork(dn_cmd) + cls._created_network_id = None + except Exception as e: + logger.warning( + "tearDownClass: could not delete network %s: %s" + % (cls._created_network_id, e)) + + super(OntapSnapshotBase, cls).tearDownClass() + + @classmethod + def _force_expunge_suite_volumes(cls): + """Permanently remove every volume record created by this suite.""" + cmd = listVolumesAPI.listVolumesCmd() + cmd.listall = True + cmd.account = cls.account.name + cmd.domainid = cls.domain.id + try: + volumes = cls.apiClient.listVolumes(cmd) or [] + except Exception as exc: + logger.warning("tearDownClass: could not list suite volumes: %s" % exc) + return + for volume in volumes: + if not getattr(volume, "name", "").startswith(cls._vol_name_prefix): + continue + try: + destroy = destroyVolumeAPI.destroyVolumeCmd() + destroy.id = volume.id + destroy.expunge = True + cls.apiClient.destroyVolume(destroy) + except Exception as exc: + logger.warning("tearDownClass: could not expunge volume %s " + "(%s): %s" % (volume.id, volume.name, exc)) + + @classmethod + def _stop_and_expunge_vm(cls, vm_id): + """Force-stop the VM if needed, then destroy it with expunge.""" + vms = cls.apiClient.listVirtualMachines(_list_vms_cmd(vm_id)) + current_state = vms[0].state if vms else "unknown" + if current_state.lower() not in ("stopped", "destroyed", + "expunging", "error"): + stop_cmd = stopVirtualMachineAPI.stopVirtualMachineCmd() + stop_cmd.id = vm_id + stop_cmd.forced = True + cls.apiClient.stopVirtualMachine(stop_cmd) + _wait_for_vm_state(cls.apiClient, vm_id, "Stopped", timeout=120) + dest_cmd = destroyVirtualMachineAPI.destroyVirtualMachineCmd() + dest_cmd.id = vm_id + dest_cmd.expunge = True + cls.apiClient.destroyVirtualMachine(dest_cmd) + + def _create_pool(self): + ps = self.testdata[TestData.primaryStorage] + storage_ip = self.testdata[TestData.ontap][TestData.DETAIL_STORAGE_IP] + names = _PROTOCOLS[self.PROTOCOL.upper()] + pool_name = "%s_%d" % (names["prefix"], random.randint(0, 99999)) + + cmd = createStoragePoolAPI.createStoragePoolCmd() + cmd.name = pool_name + cmd.url = names["pool_url"] % storage_ip + cmd.zoneid = self.zone.id + cmd.clusterid = self.cluster.id + cmd.podid = self.cluster.podid + cmd.scope = ps[TestData.scope] + cmd.provider = ps[TestData.provider] + pool_tags = ps[TestData.tags] + if self.__class__.pool is not None: + pool_tags = "%s-pool-%d" % ( + pool_tags, random.randint(100000, 999999)) + cmd.tags = pool_tags + cmd.capacitybytes = ps["capacitybytes"] + cmd.hypervisor = "KVM" + cmd.managed = True + + count = 1 + for key, value in ps["details"].items(): + setattr(cmd, "details[{}].{}".format(count, key), value) + count += 1 + + response = self.apiClient.createStoragePool(cmd) + return StoragePool(response.__dict__) + + def _volume_state(self, vol_id): + """Return the current CloudStack state string for a volume.""" + cmd = listVolumesAPI.listVolumesCmd() + cmd.id = vol_id + vols = self.apiClient.listVolumes(cmd) + return vols[0].state if vols else "unknown" + + def setUp(self): + super(OntapSnapshotBase, self).setUp() + self._volume_snapshot_ids = [] + self._vm_snapshot_ids = [] + self._extra_volume_ids = [] + self._created_ontap_snaps = set() + + def tearDown(self): + """ + Delete the snapshots and extra volumes a step created, then check + their FlexVol snapshots are gone from ONTAP. + """ + for snap_id in self._vm_snapshot_ids: + try: + VmSnapshot.deleteVMSnapshot(self.apiClient, snap_id) + except Exception as exc: + logger.warning("tearDown: VM snapshot %s: %s" % (snap_id, exc)) + self._delete_failed_vm_snapshots() + for snap_id in self._volume_snapshot_ids: + try: + Snapshot({"id": snap_id}).delete(self.apiClient) + except Exception as exc: + logger.warning("tearDown: volume snapshot %s: %s" % (snap_id, exc)) + for vol_id in self._extra_volume_ids: + try: + cmd = deleteVolumeAPI.deleteVolumeCmd() + cmd.id = vol_id + self.apiClient.deleteVolume(cmd) + except Exception as exc: + logger.warning("tearDown: volume %s: %s" % (vol_id, exc)) + if self._created_ontap_snaps and not self._wait_ontap_snaps_gone( + self._created_ontap_snaps, fail=False): + logger.warning("tearDown: FlexVol snapshots still present: %s" + % sorted(self._created_ontap_snaps)) + super(OntapSnapshotBase, self).tearDown() + + @classmethod + def _destroy_second_vm(cls): + if cls.vm2 is None: + return + try: + cmd = destroyVirtualMachineAPI.destroyVirtualMachineCmd() + cmd.id = cls.vm2.id + cmd.expunge = True + cls.apiClient.destroyVirtualMachine(cmd) + except Exception as exc: + logger.warning("Could not destroy second VM %s: %s" % (cls.vm2.id, exc)) + cls.vm2 = None + cls.vm2_ssh = None + + @classmethod + def _delete_kept_vm_snapshots(cls): + """Delete the VM suite step 10/11 snapshots when step 12 did not take them over.""" + for snap in (cls.vm_snap_running, cls.vm_snap_stopped): + if snap is None: + continue + try: + VmSnapshot.deleteVMSnapshot(cls.apiClient, snap.id) + except Exception as exc: + logger.warning("tearDownClass: VM snapshot %s: %s" % (snap.id, exc)) + cls.vm_snap_running = None + cls.vm_snap_stopped = None + cls.token_s1 = None + cls.token_s2 = None + cls.kept_ontap_snaps = set() + + def _require_snapshot_vm(self, ssh=True): + if self.__class__.vm is None: + self.skipTest("VM not deployed — test_03 was skipped (no ready template)") + if ssh and self.__class__.vm_ssh is None: + self.skipTest("Guest SSH not set up — the SSH step must pass first") + self._start_vm(self.__class__.vm.id) + return self.__class__.vm + + def _require_second_vm(self): + self._require_snapshot_vm() + if self.__class__.vm2 is None or self.__class__.vm2_ssh is None: + self.skipTest("Second VM not deployed — the second VM step must pass first") + self._start_vm(self.__class__.vm2.id) + return self.__class__.vm2 + + def _vm_state(self, vm_id): + vms = self.apiClient.listVirtualMachines(_list_vms_cmd(vm_id)) + return vms[0].state if vms else None + + def _stop_vm(self, vm_id): + if (self._vm_state(vm_id) or "").lower() == "stopped": + return + cmd = stopVirtualMachineAPI.stopVirtualMachineCmd() + cmd.id = vm_id + cmd.forced = True + self.apiClient.stopVirtualMachine(cmd) + self._poll_vm_state(vm_id, "Stopped", timeout=600) + + def _guest(self, which="vm"): + host, port = getattr(self.__class__, "%s_ssh" % which) + return GuestSsh(host, port, self.guest_user, self.guest_password) + + def _write_marker(self, token, which="vm", disks=("ROOT",)): + with self._guest(which) as guest: + if "ROOT" in disks: + guest.write_root_marker(token) + if "DATA" in disks: + guest.write_data_marker(token) + + def _assert_marker(self, token, which="vm", disk="ROOT", msg=""): + with self._guest(which) as guest: + found = guest.read_data_marker() if disk == "DATA" else guest.read_root_marker() + self.assertEqual(found, token, "%s: %s marker on %s is %r, expected %r" + % (msg, disk, which, found, token)) + + def _ontap_snap_names(self): + return {s.get("name") for s in self.ontap.list_snapshots(self.__class__.pool.name)} + + def _assert_new_ontap_snaps(self, before, snaps, kind, msg): + """Return the FlexVol snapshot created for each CloudStack snapshot. + + A volume snapshot is stored as ``..._cs`` and a VM snapshot as + ``..._vm``. ONTAP snapshots from its own schedule, such as + ``hourly.*`` or ``Anti_ransomware_*``, are ignored. + """ + new = self._ontap_snap_names() - before + prefix = "cs" if kind == "volume" else "vm" + table = "snapshots" if kind == "volume" else "vm_snapshots" + matched = set() + missing = [] + for snap in snaps: + db_id = tcu.get_db_id(self.dbConnection, table, snap.id) + suffix = "_%s%s" % (prefix, db_id) + hits = sorted(name for name in new if name.endswith(suffix)) + if len(hits) != 1: + missing.append("%s (suffix %s, matches %s)" % (snap.id, suffix, hits)) + else: + matched.add(hits[0]) + self.assertFalse( + missing, + "%s: FlexVol snapshot missing for %s; new FlexVol snapshots: %s" + % (msg, missing, sorted(new))) + ignored = new - matched + if ignored: + logger.info("%s: ignoring FlexVol snapshots not created by this step: %s", + msg, sorted(ignored)) + self._created_ontap_snaps |= matched + return matched + + def _assert_ontap_snaps_present(self, names, msg): + missing = set(names) - self._ontap_snap_names() + self.assertFalse(missing, "%s: FlexVol snapshots missing: %s" % (msg, sorted(missing))) + + def _wait_ontap_snaps_gone(self, names, timeout=180, fail=True): + names = set(names) + deadline = time.time() + timeout + left = names + while time.time() < deadline: + left = names & self._ontap_snap_names() + if not left: + return True + time.sleep(5) + if fail: + self.fail("FlexVol snapshots %s still present after %ds" % (sorted(left), timeout)) + return False + + @classmethod + def _admin_account(cls): + """The CloudStack 'admin' account, used as the owner for this suite.""" + listed = Account.list(cls.apiClient, name="admin", listall=True) or [] + assert listed, "No account named 'admin' on this CloudStack" + return listed[0] + + def _take_volume_snapshot(self, volume_id): + snap = Snapshot.create(self.apiClient, volume_id, + account=self.account.name, domainid=self.domain.id) + self._volume_snapshot_ids.append(snap.id) + self.__class__._all_volume_snapshot_ids.add(snap.id) + deadline = time.time() + 600 + state = getattr(snap, "state", None) + while time.time() < deadline: + listed = Snapshot.list( + self.apiClient, id=snap.id, listall=True) or [] + if listed: + snap = listed[0] + state = getattr(snap, "state", None) + if state == "BackedUp": + return snap + if state in ("Error", "Destroyed"): + break + time.sleep(5) + self.fail("Volume snapshot %s did not reach BackedUp (last state %s)" + % (snap.id, state)) + + def _take_vm_snapshot(self, vm_id): + snap = VmSnapshot.create(self.apiClient, vm_id, snapshotmemory="false", + name="ontap_%d" % random.randint(0, 999999)) + self._vm_snapshot_ids.append(snap.id) + self.assertEqual(snap.state, "Ready", + "VM snapshot %s is %s, expected Ready" % (snap.id, snap.state)) + return snap + + def _vm_snapshots_of(self, vm_id): + return VmSnapshot.list(self.apiClient, virtualmachineid=vm_id, listall=True) or [] + + def _delete_failed_vm_snapshots(self): + """Delete VM snapshots left in Error by a rejected create. + + A rejected createVMSnapshot (ONTAP refusing while a revert's clones + exist) leaves its record behind with no id the test ever saw. Any + Instance Snapshot, even in Error, blocks detach, resize and destroy. + """ + for vm in (self.__class__.vm, self.__class__.vm2): + if vm is None: + continue + try: + stale = [s for s in self._vm_snapshots_of(vm.id) + if (getattr(s, "state", "") or "").lower() == "error"] + except Exception as exc: + logger.warning("tearDown: could not list VM snapshots of %s: %s" + % (vm.id, exc)) + continue + for snap in stale: + try: + VmSnapshot.deleteVMSnapshot(self.apiClient, snap.id) + except Exception as exc: + logger.warning("tearDown: failed VM snapshot %s: %s" + % (snap.id, exc)) + + def _volume_snapshot_listed(self, snap_id): + listed = Snapshot.list(self.apiClient, id=snap_id, listall=True) or [] + return any(getattr(item, "id", None) == snap_id for item in listed) + + def _wait_until_gone(self, still_there, msg, timeout=180): + deadline = time.time() + timeout + while time.time() < deadline and still_there(): + time.sleep(5) + self.assertFalse(still_there(), msg) + + def _require_data_attached(self, vm): + """The attach step attaches the DATA volume and nothing detaches it until the detach step; the clone and template steps need it.""" + cmd = listVolumesAPI.listVolumesCmd() + cmd.id = self.__class__.volume.id + vols = self.apiClient.listVolumes(cmd) or [] + self.assertTrue(vols and getattr(vols[0], "virtualmachineid", None) == vm.id, + "DATA volume must be attached to the VM before this step") + + def _pool_files(self): + """Names of the files in the pool's FlexVol.""" + return set(self.ontap.list_files_in_volume(self.__class__.pool.name)) + + def _wait_async_job(self, job_id, timeout=600, interval=2): + """Poll queryAsyncJobResult until job_id leaves JOB_INPROGRESS; return the result.""" + deadline = time.time() + timeout + cmd = queryAsyncJobResult.queryAsyncJobResultCmd() + cmd.jobid = job_id + while time.time() < deadline: + res = self.apiClient.queryAsyncJobResult(cmd) + if getattr(res, "jobstatus", JOB_INPROGRESS) != JOB_INPROGRESS: + return res + time.sleep(interval) + self.fail("Async job %s did not finish within %ds" % (job_id, timeout)) + + def _delete_volume_snapshot_with_retry(self, snap_id, attempts=6, pause=15): + """Ask CloudStack to delete a volume snapshot, retrying while it refuses.""" + for attempt in range(1, attempts + 1): + try: + Snapshot({"id": snap_id}).delete(self.apiClient) + return + except Exception as exc: + if attempt == attempts: + raise + logger.warning("delete of volume snapshot %s refused, retry %d/%d: %s", + snap_id, attempt, attempts, exc) + time.sleep(pause) + + def _poll_volume_field(self, vol_id, field, target, timeout=120, + interval=5): + """Poll a volume field until it matches target; return the volume.""" + deadline = time.time() + timeout + while time.time() < deadline: + cmd = listVolumesAPI.listVolumesCmd() + cmd.id = vol_id + cmd.listall = True + vols = self.apiClient.listVolumes(cmd) + if vols: + val = getattr(vols[0], field, None) + if val == target: + return vols[0] + time.sleep(interval) + return None + + def _data_lun_name(self, volume=None): + """ + Full ONTAP path of the LUN backing the CloudStack data volume. + + UnifiedSANStrategy names the LUN after the CloudStack volume with + hyphens replaced by underscores, inside the pool's FlexVol. + """ + volume = volume or self.__class__.volume + if volume is None or self.__class__.pool is None: + return None + return "/vol/%s/%s" % (self.__class__.pool.name, + volume.name.replace("-", "_")) + + def _lun_maps(self, volume=None): + """ + Return LUN-maps belonging to the data volume's LUN only. + + The same FlexVol also holds the VM's ROOT LUN whenever the allocator + places the root disk on this pool, so the unfiltered map list is not a + measure of the data volume's accessibility. + """ + lun_name = self._data_lun_name(volume) + if lun_name is None: + return [] + return [m for m in self.ontap.list_lun_maps_for_volume( + self.svm_name, self.__class__.pool.name) + if m.get("lun", {}).get("name") == lun_name] + + def _data_luns(self, volume=None): + """Return LUN records for the data volume's LUN only.""" + lun_name = self._data_lun_name(volume) + if lun_name is None: + return [] + return [lun for lun in self.ontap.list_luns_with_clone( + self.svm_name, self.__class__.pool.name) + if lun.get("name") == lun_name] + + def _data_lun_size(self): + """Return the ONTAP data LUN size in bytes.""" + lun_name = self._data_lun_name() + lun = self.ontap.get_lun(self.svm_name, lun_name) + self.assertIsNotNone( + lun, "ONTAP LUN '%s' was not found" % lun_name) + size = int(lun.get("space", {}).get("size", 0)) + self.assertGreater( + size, 0, "ONTAP LUN '%s' did not report space.size" % lun_name) + return size + + def _pool_lun_uuids(self): + return {r["uuid"] for r in + self.ontap.list_luns_in_volume(self.svm_name, self.__class__.pool.name)} + + def _delete_guest_network_in_test(self): + """Delete the guest network setUpClass created for Advanced zones. + + Doing this inside the test (not only in tearDownClass) makes the full + sequence self-contained when every test passes. The management server + may briefly drop the connection after the heavy teardown above, so + deleteNetwork is retried up to 3 times with 15 s gaps. + """ + net_id = self.__class__._created_network_id + if net_id is None: + return + dn_cmd = deleteNetworkAPI.deleteNetworkCmd() + dn_cmd.id = net_id + last_net_exc = None + for attempt in range(3): + try: + self.apiClient.deleteNetwork(dn_cmd) + last_net_exc = None + break + except Exception as exc: + last_net_exc = exc + if attempt < 2: + time.sleep(15) + if last_net_exc is not None: + raise last_net_exc + self.__class__._created_network_id = None + self.__class__.network_id = None + + # CloudStack: guest network must be gone + net_cmd = listNetworksAPI.listNetworksCmd() + net_cmd.id = net_id + net_cmd.listall = True + remaining_nets = self.apiClient.listNetworks(net_cmd) or [] + self.assertFalse( + remaining_nets, + "Guest network %s still listed in CloudStack after deletion" + % net_id + ) + + # ---- snapshot-to-volume helpers shared by the NFS3 and iSCSI suites ---- + + def _request_clone(self, snapshot_id, disk_offering_id=None, name=None): + """Submit createVolume(snapshotid) and return the response without waiting.""" + cmd = createVolumeAPI.createVolumeCmd() + cmd.name = name or "%s_clone_%d" % (self._vol_name_prefix, random.randint(0, 999999)) + cmd.zoneid = self.zone.id + cmd.account = self.account.name + cmd.domainid = self.domain.id + cmd.snapshotid = snapshot_id + if disk_offering_id: + cmd.diskofferingid = disk_offering_id + return self.apiClient.createVolume(cmd) + + def _create_clone(self, snapshot_id, name=None): + """createVolume(snapshotid) with no disk offering; waits for Ready and returns the volume.""" + response = self._request_clone(snapshot_id, name=name) + self._extra_volume_ids.append(response.id) + clone = self._poll_volume_field(response.id, "state", "Ready", timeout=600) + self.assertIsNotNone( + clone, "Volume %s from snapshot %s did not reach Ready" % (response.id, snapshot_id)) + return clone + + def _wait_clone_object_gone(self, clone): + """Wait until the clone's ONTAP object (a file or a LUN) is removed.""" + self._wait_until_gone(lambda: self._clone_object_exists(clone), + "ONTAP object for clone %s still present after the clone was deleted" + % clone.id) + + def _attempt_clone(self, snapshot_id, timeout=600, name=None): + """Request a clone without failing the caller. Returns (rejected, volume). + + Any volume the API returns is tracked for cleanup, whatever its outcome. + """ + try: + response = self._request_clone(snapshot_id, name=name) + except Exception as exc: + logger.info("createVolume from snapshot %s rejected: %s" % (snapshot_id, exc)) + return True, None + self._extra_volume_ids.append(response.id) + deadline = time.time() + timeout + while time.time() < deadline: + vols = self.apiClient.listVolumes(_list_vols_cmd(response.id)) or [] + state = getattr(vols[0], "state", None) if vols else None + if state is None: + return True, None + if state == "Ready": + return False, vols[0] + if state in FAILED_VOLUME_STATES: + return True, vols[0] + time.sleep(10) + self.fail("Volume %s from snapshot %s did not finish in %ds" + % (response.id, snapshot_id, timeout)) + + def _expect_clone_rejected(self, snapshot_id, disk_offering_id=None, pools=None): + """createVolume(snapshotid) must fail and leave nothing behind. + + Checks that no usable CloudStack volume record is added and that the + ONTAP objects on each pool in ``pools`` (default: the suite pool) are + unchanged. Returns the error text. + """ + pools = pools or [self.__class__.pool] + volumes_before = self._account_volume_ids() + objects_before = {p.name: self._pool_objects_of(p) for p in pools} + try: + response = self._request_clone(snapshot_id, disk_offering_id=disk_offering_id) + except Exception as exc: + message = str(exc) + else: + self._extra_volume_ids.append(response.id) + self.fail("createVolume from snapshot %s was accepted (volume %s)" + % (snapshot_id, response.id)) + self.assertEqual(self._account_volume_ids(), volumes_before, + "A CloudStack volume record was left behind") + for p in pools: + after = self._pool_objects_of(p) + added = after - objects_before[p.name] + removed = objects_before[p.name] - after + self.assertFalse(added or removed, + "ONTAP objects on FlexVol '%s' changed: added %s, removed %s" + % (p.name, sorted(added), sorted(removed))) + return message + + def _cs_volume(self, vol_id): + vols = self.apiClient.listVolumes(_list_vols_cmd(vol_id)) or [] + return vols[0] if vols else None + + def _take_volume_snapshot_when_accepted(self, volume_id, attempts=6, pause=15): + """_take_volume_snapshot, retried while ONTAP refuses it because clones back a snapshot.""" + for attempt in range(1, attempts + 1): + try: + return self._take_volume_snapshot(volume_id) + except Exception as exc: + if attempt == attempts or not _is_rejected(exc): + raise + logger.warning("volume snapshot of %s refused, retry %d/%d: %s", + volume_id, attempt, attempts, exc) + time.sleep(pause) + + def _finish_volume_snapshot(self, snap_id): + """Delete a volume snapshot from CloudStack and wait until it is no longer listed.""" + if self._volume_snapshot_listed(snap_id): + try: + self._delete_volume_snapshot_with_retry(snap_id) + except Exception as exc: + logger.warning( + "Could not delete volume snapshot %s after retries; " + "leaving it registered for teardown: %s", snap_id, exc) + return + self._wait_until_gone(lambda: self._volume_snapshot_listed(snap_id), + "Volume snapshot %s still listed after delete" % snap_id) + if snap_id in self._volume_snapshot_ids: + self._volume_snapshot_ids.remove(snap_id) + self.__class__._all_volume_snapshot_ids.discard(snap_id) + + def _set_pool_enabled(self, pool_id, enabled): + upd = updateStoragePoolAPI.updateStoragePoolCmd() + upd.id = pool_id + upd.enabled = enabled + self.apiClient.updateStoragePool(upd) + self._poll_pool_state(pool_id, "Up" if enabled else "Disabled", timeout=120) + + def _remove_pool(self, pool): + """Maintenance, then force-delete, for a pool created inside a test.""" + maint = enableStorageMaintenance.enableStorageMaintenanceCmd() + maint.id = pool.id + self.apiClient.enableStorageMaintenance(maint) + self._poll_pool_state(pool.id, "Maintenance", timeout=120) + self._delete_pool(pool.id, forced=True) + + def _db_volume_format(self, volume_uuid): + rows = self.__class__.dbConnection.execute( + "SELECT format FROM volumes WHERE uuid = %s AND removed IS NULL", + params=(volume_uuid,)) + return rows[0][0] if rows else None + + def _attach_clone(self, clone, vm_id, which): + """Attach the clone to a VM and return the guest disk name that appears.""" + with self._guest(which) as guest: + before = _guest_disk_names(guest) + cmd = attachVolumeAPI.attachVolumeCmd() + cmd.id = clone.id + cmd.virtualmachineid = vm_id + self.apiClient.attachVolume(cmd) + attached = self._poll_volume_field(clone.id, "virtualmachineid", vm_id, timeout=120) + self.assertIsNotNone(attached, "Clone %s was not attached to VM %s" % (clone.id, vm_id)) + deadline = time.time() + 180 + while True: + with self._guest(which) as guest: + new = _guest_disk_names(guest) - before + if len(new) == 1: + return new.pop() + if time.time() >= deadline: + self.fail("Guest %s saw disks %s after attaching clone %s, expected one new disk" + % (which, sorted(new), clone.id)) + time.sleep(10) + + def _clone_marker(self, which, dev, write=None): + """Mount the clone's disk in the guest, optionally write the marker, read it back, unmount.""" + with self._guest(which) as guest: + guest.run("mkdir -p %s && mount /dev/%s %s" % (CLONE_MOUNT, dev, CLONE_MOUNT)) + try: + if write is not None: + guest.run("echo '%s' > %s && sync" % (write, CLONE_MARKER)) + return guest.run("cat %s 2>/dev/null; true" % CLONE_MARKER).strip() + finally: + guest.run("sync; umount %s 2>/dev/null; true" % CLONE_MOUNT, check=False) + + def _detach_clone(self, clone): + cmd = detachVolumeAPI.detachVolumeCmd() + cmd.id = clone.id + self.apiClient.detachVolume(cmd) + cleared = self._poll_volume_field(clone.id, "virtualmachineid", None, timeout=120) + self.assertIsNotNone(cleared, "Clone %s still attached after detach" % clone.id) + + def _remove_clone(self, clone): + """Detach and delete a clone. Errors are logged, not raised, so this is safe in a finally block.""" + try: + cmd = listVolumesAPI.listVolumesCmd() + cmd.id = clone.id + vols = self.apiClient.listVolumes(cmd) or [] + if vols and getattr(vols[0], "virtualmachineid", None): + self._detach_clone(clone) + except Exception as exc: + logger.warning("clone %s: detach failed: %s" % (clone.id, exc)) + try: + cmd = deleteVolumeAPI.deleteVolumeCmd() + cmd.id = clone.id + self.apiClient.deleteVolume(cmd) + if clone.id in self._extra_volume_ids: + self._extra_volume_ids.remove(clone.id) + except Exception as exc: + logger.warning("clone %s: delete failed: %s" % (clone.id, exc)) + + def _take_vm_snapshot_when_accepted(self, vm_id, attempts=6, pause=15): + """_take_vm_snapshot, retried while ONTAP refuses it because clones back a snapshot.""" + for attempt in range(1, attempts + 1): + try: + return self._take_vm_snapshot(vm_id) + except Exception as exc: + if attempt == attempts or not _is_rejected(exc): + raise + logger.warning("VM snapshot of %s refused, retry %d/%d: %s", + vm_id, attempt, attempts, exc) + self._delete_failed_vm_snapshots() + time.sleep(pause) + + def _account_volume_ids(self): + """IDs of the account's volumes, ignoring records in a failed or destroyed state.""" + cmd = listVolumesAPI.listVolumesCmd() + cmd.account = self.account.name + cmd.domainid = self.domain.id + cmd.listall = True + return {v.id for v in (self.apiClient.listVolumes(cmd) or []) + if getattr(v, "state", None) not in FAILED_VOLUME_STATES} + + # ---- steps shared by every suite ----------------------------------- + + def step_01_create_pool(self): + """Body of test_01: create the ONTAP primary storage pool.""" + pool = self._create_pool() + self.__class__.pool = pool + self.__class__.pool_db_id = tcu.get_db_id( + self.dbConnection, "storage_pool", pool.id + ) + + self.assertEqual( + pool.state, "Up", + "Pool state should be 'Up', got '%s'" % pool.state + ) + if self._is_iscsi(): + self.assertEqual( + pool.type, "OntapiSCSI", + "Pool type should be 'OntapiSCSI', got '%s'" % pool.type + ) + + ontap_vol = self.ontap.get_volume(pool.name) + self.assertIsNotNone( + ontap_vol, + "ONTAP FlexVol not created for pool '%s'" % pool.name + ) + self.assertEqual( + ontap_vol.get("state"), "online", + "ONTAP FlexVol should be 'online', got '%s'" + % ontap_vol.get("state") + ) + + def step_02_create_ontap_data_volume(self): + """Body of test_02: create a CloudStack data volume on the ONTAP pool.""" + self.assertIsNotNone(self.__class__.pool, + "Pool absent — test_01 must pass first") + + pool = self.__class__.pool + vol = self._create_volume(pool.id) + self.__class__.volume = vol + self.assertIsNotNone(vol, "createVolume returned None") + + if self._is_iscsi(): + # The LUN is created with the volume; grow it while detached. + luns = self._data_luns() + self.assertTrue( + len(luns) > 0, + "Expected the data volume's LUN '%s' in ONTAP FlexVol '%s' " + "after volume creation, found none" + % (self._data_lun_name(), pool.name) + ) + + volume = self._poll_volume_size(vol.id, int(vol.size)) + detached_target = ( + (int(volume.size) // (1024 ** 3)) + 1 + ) * (1024 ** 3) + self._resize_volume(vol.id, detached_target // (1024 ** 3)) + self._poll_volume_size(vol.id, detached_target) + self.assertEqual( + self._get_db_volume_size(vol.id), detached_target, + "DB size does not match detached iSCSI grow target") + self.assertEqual( + self._data_lun_size(), detached_target, + "ONTAP LUN size does not match detached grow target") + else: + vol_state = self._volume_state(vol.id) + self.assertIn( + vol_state.lower(), ("allocated", "ready"), + "Volume should be 'Allocated' or 'Ready', got '%s'" % vol_state + ) + + ontap_vol = self.ontap.get_volume(pool.name) + self.assertIsNotNone( + ontap_vol, + "ONTAP FlexVol disappeared after data volume creation" + ) + self.assertEqual( + ontap_vol.get("state"), "online", + "ONTAP FlexVol should still be 'online' after volume creation" + ) + + def step_03_deploy_vm(self): + """Body of test_03: deploy a VM whose ROOT disk is on the ONTAP pool.""" + self.assertIsNotNone(self.__class__.pool, + "Pool absent — test_01 must pass first") + if self.__class__.template_id is None: + self.skipTest( + "No ready user KVM template available — " + "waiting for template download to complete" + ) + self.assertIsNotNone(self.__class__.service_offering_id, + "No service offering available — check setup") + + cmd = deployVirtualMachineAPI.deployVirtualMachineCmd() + cmd.zoneid = self.zone.id + cmd.templateid = self.__class__.template_id + cmd.serviceofferingid = self.__class__.service_offering_id + cmd.account = self.account.name + cmd.domainid = self.domain.id + if self.__class__.network_id: + cmd.networkids = self.__class__.network_id + + vm = self._deploy_vm(cmd) + self.assertIsNotNone(vm, "deployVirtualMachine returned None") + self.__class__.vm = vm + + vm_obj = self._poll_vm_state(vm.id, "Running") + self.assertEqual( + vm_obj.state, "Running", + "VM should be 'Running', got '%s'" % vm_obj.state + ) + + pool = self.__class__.pool + self._assert_root_on_pool(vm.id, pool) + spool = self._wait_for_ready_spool_ref(self.__class__.pool_db_id) + self._assert_cache_on_ontap(pool, spool) + + if self._is_iscsi(): + # Data volume LUN-map must not exist yet (volume not yet attached) + lun_maps = self._lun_maps() + self.assertEqual( + len(lun_maps), 0, + "Expected 0 data-volume LUN-maps before volume attach, " + "found %d: %s" % (len(lun_maps), lun_maps) + ) + + def step_04_attach_volume_to_vm(self): + """Body of test_04: attach the data volume to the running VM.""" + if self.__class__.vm is None: + self.skipTest("VM not deployed — test_03 was skipped (no ready template)") + self.assertIsNotNone(self.__class__.volume, + "Volume absent — test_02 must pass first") + + vm = self.__class__.vm + vol = self.__class__.volume + pool = self.__class__.pool + + cmd = attachVolumeAPI.attachVolumeCmd() + cmd.id = vol.id + cmd.virtualmachineid = vm.id + attached = self.apiClient.attachVolume(cmd) + self.assertIsNotNone(attached, "attachVolume returned None") + + # On ONTAP shared storage CloudStack does not move the volume to + # 'In Use'; attachment shows as virtualmachineid on the volume record. + result = self._poll_volume_field( + vol.id, "virtualmachineid", vm.id, timeout=120) + self.assertIsNotNone( + result, + "Volume %s was not attached to VM %s after attachVolume" + % (vol.id, vm.id) + ) + + # VM must still be Running + vm_obj = self._poll_vm_state(vm.id, "Running", timeout=30) + self.assertEqual(vm_obj.state, "Running", + "VM should still be 'Running' after volume attach") + + initial_size = int(result.size) + self.__class__.initial_volume_size = initial_size + self.__class__.target_volume_size = ( + (initial_size // (1024 ** 3)) + 1 + ) * (1024 ** 3) + + if self._is_iscsi(): + # ONTAP: at least one LUN-map must exist for the data volume's LUN + lun_maps = self._lun_maps() + self.assertGreater( + len(lun_maps), 0, + "Expected ≥1 LUN-map after volume attach, found 0 — " + "LUN is not accessible to the VM's host" + ) + self.assertEqual( + self._data_lun_size(), initial_size, + "Initial ONTAP LUN size should match the CloudStack volume size") + return + + # ONTAP FlexVol must remain online + ontap_vol = self.ontap.get_volume(pool.name) + self.assertIsNotNone(ontap_vol, "ONTAP FlexVol not found after attach") + self.assertEqual( + ontap_vol.get("state"), "online", + "ONTAP FlexVol should be 'online' after attach" + ) + + # ONTAP: NFS3 uses lazy file creation — the volume data file is + # materialised on the FlexVol only when CloudStack calls createAsync + # during attachVolume. Verify that the file now exists. + files = self.ontap.list_files_in_volume(pool.name) + vol_file = next((f for f in files if vol.id in f), None) + self.assertIsNotNone( + vol_file, + "No data file matching volume UUID '%s' found in FlexVol '%s' " + "after attach; files present: %s" % (vol.id, pool.name, files) + ) + self.__class__.volume_path = vol_file + + backend_size = self._get_qcow2_virtual_size(pool.id, vol_file) + self.assertEqual( + backend_size, initial_size, + "Initial qcow2 virtual size should match the CloudStack volume size" + ) + + def step_09_open_ssh_and_write_root_data_files(self): + """Body of the SSH setup test.""" + vm = self._require_snapshot_vm(ssh=False) + if not self.__class__.network_id: + self.skipTest("Snapshot steps need an Advanced zone guest network for SSH") + pool_id = self.__class__.pool.id + root = self._root_volume_for_vm(vm.id) + self.assertEqual(getattr(root, "storageid", None), pool_id, + "ROOT volume is on '%s', not the ONTAP test pool" + % getattr(root, "storage", None)) + vols = self.apiClient.listVolumes(_list_vols_cmd(self.__class__.volume.id)) or [] + self.assertTrue(vols and getattr(vols[0], "virtualmachineid", None) == vm.id, + "DATA volume must be attached before the snapshot steps") + + host, port, _ = open_ssh_port(self.apiClient, vm.id, self.__class__.network_id) + self.__class__.vm_ssh = (host, port) + token = new_token("ssh-access-test") + self._write_marker(token, disks=("ROOT", "DATA")) + self._assert_marker(token, disk="ROOT", msg="guest access") + self._assert_marker(token, disk="DATA", msg="guest access") + + def step_19_deploy_second_vm(self): + """Body of the second-VM test: deploy a second VM on the pool.""" + self._require_snapshot_vm() + cmd = deployVirtualMachineAPI.deployVirtualMachineCmd() + cmd.zoneid = self.zone.id + cmd.templateid = self.__class__.template_id + cmd.serviceofferingid = self.__class__.service_offering_id + cmd.account = self.account.name + cmd.domainid = self.domain.id + cmd.networkids = self.__class__.network_id + vm2 = self.apiClient.deployVirtualMachine(cmd) + self.__class__.vm2 = vm2 + self._poll_vm_state(vm2.id, "Running", timeout=900) + root = self._root_volume_for_vm(vm2.id) + self.assertEqual(getattr(root, "storageid", None), self.__class__.pool.id, + "Second VM ROOT is not on the ONTAP test pool") + host, port, _ = open_ssh_port(self.apiClient, vm2.id, self.__class__.network_id) + self.__class__.vm2_ssh = (host, port) + token = new_token("second-vm-ssh-access-test") + self._write_marker(token, which="vm2") + self._assert_marker(token, which="vm2", msg="second VM access") + + def step_27_destroy_vm_and_cleanup(self): + """Body of the last test: destroy the VMs, delete the volume and the pool.""" + if not self._is_iscsi(): + self.assertIsNotNone(self.__class__.pool, + "Pool absent — test_01 must pass first") + + self._destroy_second_vm() + vm = self.__class__.vm + vol = self.__class__.volume + pool = self.__class__.pool + + if vm is not None: + self._stop_and_expunge_vm(vm.id) + self.__class__.vm = None + + if pool is not None: + spool = self._assert_single_ready_spool_ref( + self.__class__.pool_db_id) + self._assert_cache_on_ontap(pool, spool) + + if pool is not None: + pool_name = pool.name + + if vol is not None: + del_cmd = deleteVolumeAPI.deleteVolumeCmd() + del_cmd.id = vol.id + self.apiClient.deleteVolume(del_cmd) + self.__class__.volume = None + + if self._is_iscsi(): + # ONTAP: LUN must be removed after volume deletion + luns = self._data_luns(vol) + self.assertEqual( + len(luns), 0, + "Expected the data volume's LUN to be gone from FlexVol " + "'%s' after volume delete, found %d" + % (pool_name, len(luns)) + ) + else: + # ONTAP: the volume data file must be removed from the + # FlexVol after deleteVolume. + files = self.ontap.list_files_in_volume(pool_name) + vol_file = next((f for f in files if vol.id in f), None) + self.assertIsNone( + vol_file, + "Volume data file for '%s' should be gone from FlexVol " + "'%s' after deleteVolume; files still present: %s" + % (vol.id, pool_name, files) + ) + + # Enter maintenance, then force-delete the pool. forced=True: the + # template cache (template_spool_ref) is still on the pool; it is + # only reclaimed by storage GC or pool deletion. + maint_cmd = enableStorageMaintenance.enableStorageMaintenanceCmd() + maint_cmd.id = pool.id + self.apiClient.enableStorageMaintenance(maint_cmd) + self._poll_pool_state(pool.id, "Maintenance", timeout=120) + + self._delete_pool(pool.id, forced=True) + self.__class__.pool = None + + # CloudStack: pool must be gone + try: + remaining = list_storage_pools(self.apiClient, id=pool.id) + except Exception: + remaining = None + self.assertFalse( + remaining, + "Pool '%s' still listed in CloudStack after deletion" + % pool_name + ) + + # ONTAP: FlexVol must be deleted + ontap_vol = self.ontap.get_volume(pool_name) + self.assertIsNone( + ontap_vol, + "ONTAP FlexVol '%s' still exists after pool deletion" + % pool_name + ) + + if self._is_iscsi(): + # ONTAP: per-host igroups must be deleted by the pool force-delete + for host in self.cluster_hosts: + iqn = getattr(host, "storageurl", None) + if not iqn or not iqn.startswith("iqn."): + continue + short = host.name.split(".")[0] + igroup_name = "cs_%s_%s" % ( + self.svm_name, + re.sub(r"[^a-zA-Z0-9_-]", "_", short), + ) + igroup = self.ontap.get_igroup(self.svm_name, igroup_name) + self.assertIsNone( + igroup, + "ONTAP igroup '%s' still exists after pool deletion" + % igroup_name + ) + else: + # ONTAP: export policy must be removed + ep_name = "cs-%s-%s" % (self.svm_name, pool_name) + ep = self.ontap.get_export_policy(ep_name) + self.assertIsNone( + ep, + "ONTAP export policy '%s' still exists after pool deletion" + % ep_name + ) + + if self._is_iscsi(): + self._delete_guest_network_in_test() diff --git a/test/integration/plugins/ontap/iscsi/template/test_snapshot_to_template.py b/test/integration/plugins/ontap/iscsi/template/test_snapshot_to_template.py new file mode 100644 index 000000000000..862b4b809cf5 --- /dev/null +++ b/test/integration/plugins/ontap/iscsi/template/test_snapshot_to_template.py @@ -0,0 +1,769 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +""" +Snapshot-to-template integration tests for ONTAP iSCSI primary storage (Marvin). + +Create templates from ROOT and DATA volume snapshots of a running VM, deploy VMs +from them, and check the snapshots and templates in CloudStack and in ONTAP. + +Tests are numbered test_01 ... test_16 and must run in that order. Each step +builds on the shared state established by the previous step. + +Workflow: + 01 Create the iSCSI primary storage pool on ONTAP + 02 Create a CloudStack data volume on the ONTAP pool + 03 Deploy a VM whose ROOT disk is on the ONTAP pool + 04 Attach the ONTAP data volume to the running VM + 05 Open an SSH port forward to the VM; write ROOT and DATA files + 06 Create a template from the running VM's root snapshot and deploy from it + 07 Template from an older root snapshot has file A and not file B + 08 Create templates from two root snapshots at the same time + 09 Delete the template; the snapshot stays BackedUp + 10 Delete the snapshot after the template exists; the template still deploys + 11 Template stores password-enabled, dynamically-scalable, and the OS type + 12 Create the template after its source VM is expunged + 13 Template from the DATA snapshot does not boot; the KVM host shows no OS loaded + 14 Reject createTemplate with an empty name or no OS type + 15 One of two creates from the same snapshot succeeds; the other is rejected, + leaves no template, and the snapshot stays BackedUp + 16 Destroy the VMs, delete the data volume and the pool + +Setup and cleanup steps are shared with the VM suite; see helpers/snapshot_base.py. + +Guest login for the CentOS 5.5 template comes from ontap.cfg +(cloudstack.templateUsername / templatePassword); see guest_ssh.py. + +Running: + bash test/integration/plugins/ontap/run_tests.sh iscsi_snapshot_to_template + +Note: Tests share class-level state (sequential). Always run the full suite. +""" + +import logging +import random +import re +import shlex +import time +from contextlib import contextmanager + +from nose.plugins.attrib import attr + +from marvin.cloudstackAPI import ( + createTemplate as createTemplateAPI, + deleteTemplate as deleteTemplateAPI, + deployVirtualMachine as deployVirtualMachineAPI, + listImageStores as listImageStoresAPI, + listTemplates as listTemplatesAPI, + listVolumes as listVolumesAPI, +) +from marvin.lib.base import Snapshot +from marvin.codes import JOB_SUCCEEDED + +from guest_ssh import GuestSsh, close_ssh_port, new_token, open_ssh_port + +from helpers.snapshot_base import OntapSnapshotBase +from ontap_test_base import _list_vms_cmd + + +logger = logging.getLogger("TestOntapIscsiSnapshotToTemplate") + +TAG = "iscsi_snapshot_to_template" + + +# --------------------------------------------------------------------------- +# Sequential workflow test class +# --------------------------------------------------------------------------- + +TEMPLATE_FILE_A = "/root/ontap-file-a" +TEMPLATE_FILE_B = "/root/ontap-file-b" + + +def _enabled(value): + return str(value).lower() in ("true", "1") + + +def _template_in_progress(status): + """True when a template status means it is still being created or copied.""" + status = (status or "").lower() + if not status or any(word in status for word in ("complete", "error", "fail")): + return False + return any(word in status for word in ("creat", "progress", "download", "install", "%")) + + +# A guest with no bootable device reads only the BIOS boot-sector probe from its root disk. +NO_BOOT_MAX_READ_BYTES = 8 * 1024 * 1024 + + +# Expected text when CloudStack refuses a second createTemplate for a snapshot that +# is already being used. The exact wording is logged by test_19. +CONCURRENT_REJECTION = re.compile( + r"(not in\s+\w*\s*state|backedup|already|in progress|in use|being (used|processed)" + r"|busy|concurrent|locked|another|NoTransitionException|Unable to transition" + r"|from Copying|duplicate)", re.IGNORECASE) + + +class TestOntapIscsiSnapshotToTemplate(OntapSnapshotBase): + """ + Create templates from snapshots on the ONTAP iSCSI pool and deploy VMs from them. + + All tests are sequential; state is carried on class attributes. + """ + + PROTOCOL = "ISCSI" + + def setUp(self): + super(TestOntapIscsiSnapshotToTemplate, self).setUp() + self._template_ids = [] + self._extra_vm_ids = [] + self._extra_ssh_rules = [] + + def tearDown(self): + """Expunge the extra VMs and delete the templates, then run the base cleanup.""" + try: + self._cleanup_template_case() + finally: + super(TestOntapIscsiSnapshotToTemplate, self).tearDown() + + # ------------------------------------------------------------------ + # Steps 06-19 - Create a template from a volume snapshot, then deploy + # from it. Each step removes the templates, extra VMs and snapshots it + # created. + # ------------------------------------------------------------------ + + def _cleanup_template_case(self): + """Expunge the extra VMs, close the SSH rules, then delete the templates. + + A template cannot be deleted while a VM deployed from it still exists, so + the VMs go first. + """ + for vm_id in list(self._extra_vm_ids): + try: + self._stop_and_expunge_vm(vm_id) + except Exception as exc: + logger.warning("tearDown: VM %s: %s" % (vm_id, exc)) + self._extra_vm_ids = [] + for rule_id in list(self._extra_ssh_rules): + try: + close_ssh_port(self.apiClient, rule_id) + except Exception as exc: + logger.warning("tearDown: SSH rule %s: %s" % (rule_id, exc)) + self._extra_ssh_rules = [] + leftovers = [] + for template_id in list(self._template_ids): + try: + self._delete_template_with_retry(template_id) + except Exception as exc: + logger.warning("tearDown: template %s not deleted: %s" % (template_id, exc)) + leftovers.append(template_id) + self._template_ids = [] + self.assertFalse(leftovers, "Templates left behind by this test: %s" % leftovers) + + def _tpl_name(self, label): + return "snap-tpl-%s-%d" % (label, random.randint(0, 999999)) + + def _require_image_store(self): + cmd = listImageStoresAPI.listImageStoresCmd() + cmd.zoneid = self.zone.id + if not (self.apiClient.listImageStores(cmd) or []): + self.skipTest("Zone has no image store; createTemplate needs secondary storage") + + def _ostype_id(self): + cmd = listTemplatesAPI.listTemplatesCmd() + cmd.id = self.__class__.template_id + cmd.templatefilter = "executable" + cmd.zoneid = self.zone.id + listed = self.apiClient.listTemplates(cmd) or [] + ostype = getattr(listed[0], "ostypeid", None) if listed else None + self.assertTrue(ostype, "Suite template has no OS type") + return ostype + + def _template_record(self, template_id): + cmd = listTemplatesAPI.listTemplatesCmd() + cmd.id = template_id + cmd.templatefilter = "self" + cmd.zoneid = self.zone.id + cmd.account = self.account.name + cmd.domainid = self.domain.id + cmd.listall = True + try: + return self.apiClient.listTemplates(cmd) or [] + except Exception as exc: + # A create that CloudStack rejects is rolled back, and its id no + # longer exists. That is "no record", not an error. + if "entity does not exist" in str(exc): + return [] + raise + + def _wait_template_ready(self, template_id, timeout=1800): + deadline = time.time() + timeout + last = None + while time.time() < deadline: + listed = self._template_record(template_id) + if listed: + last = listed[0] + status = getattr(last, "status", None) or "" + if _enabled(getattr(last, "isready", False)) and status == "Download Complete": + return last + if "error" in status.lower() or status.lower().startswith("failed"): + self.fail("Template %s entered status %s" % (template_id, status)) + time.sleep(10) + self.fail("Template %s did not become Ready (last status %s)" + % (template_id, getattr(last, "status", None))) + + def _delete_template(self, template_id): + cmd = deleteTemplateAPI.deleteTemplateCmd() + cmd.id = template_id + cmd.zoneid = self.zone.id + self.apiClient.deleteTemplate(cmd) + if template_id in self._template_ids: + self._template_ids.remove(template_id) + + def _delete_template_with_retry(self, template_id, timeout=300): + """deleteTemplate, retried while CloudStack still rejects it (e.g. Not Ready).""" + deadline = time.time() + timeout + while True: + if not self._template_record(template_id): + if template_id in self._template_ids: + self._template_ids.remove(template_id) + return + try: + self._delete_template(template_id) + return + except Exception as exc: + if time.time() >= deadline: + raise + logger.info("deleteTemplate %s not accepted yet (%s); retrying" % (template_id, exc)) + time.sleep(10) + + def _wait_template_gone(self, template_id): + deadline = time.time() + 300 + while time.time() < deadline: + if not self._template_record(template_id): + return + time.sleep(5) + self.fail("Template %s is still listed after delete" % template_id) + + def _submit_template(self, snap_id, name, wait=True, ostype=True, **flags): + """createTemplate from a snapshot. wait=False returns the job id at once.""" + cmd = createTemplateAPI.createTemplateCmd() + cmd.name = name + cmd.displaytext = name + if ostype: + cmd.ostypeid = self._ostype_id() + cmd.snapshotid = snap_id + cmd.zoneid = self.zone.id + cmd.account = self.account.name + cmd.domainid = self.domain.id + cmd.ispublic = False + cmd.passwordenabled = flags.get("passwordenabled", False) + cmd.isdynamicallyscalable = flags.get("isdynamicallyscalable", False) + if not wait: + cmd.isAsync = "false" + response = self.apiClient.createTemplate(cmd) + template_id = getattr(response, "id", None) + if template_id: + self._template_ids.append(template_id) + return response + + def _create_ready_template(self, snap, ontap_names, name, suite_running=True, **flags): + """createTemplate from a snapshot, then check Ready, the snapshot and primary storage.""" + before = self._pool_lun_uuids() + response = self._submit_template(snap.id, name, **flags) + ready = self._wait_template_ready(response.id) + self.assertEqual(self._pool_lun_uuids(), before, + "Primary storage changed while creating template %s" % response.id) + self._assert_snapshot_kept(snap, ontap_names) + if suite_running: + self.assertEqual(self._vm_state(self.__class__.vm.id), "Running", + "Suite VM is not Running after template creation") + return ready + + def _assert_snapshot_kept(self, snap, ontap_names): + listed = Snapshot.list(self.apiClient, id=snap.id, listall=True) or [] + self.assertTrue(listed, "Snapshot %s is no longer listed" % snap.id) + self.assertEqual(listed[0].state, "BackedUp", + "Snapshot %s is %s, expected BackedUp" % (snap.id, listed[0].state)) + self._assert_ontap_snaps_present(ontap_names, "source snapshot") + + def _snapshot_volume(self, volume_id, label): + before = self._ontap_snap_names() + snap = self._take_volume_snapshot(volume_id) + names = self._assert_new_ontap_snaps(before, [snap], "volume", label) + return snap, names + + def _snapshot_root(self, vm, label): + return self._snapshot_volume(self._root_volume_for_vm(vm.id).id, label) + + def _deploy_cmd(self, template_id): + cmd = deployVirtualMachineAPI.deployVirtualMachineCmd() + cmd.zoneid = self.zone.id + cmd.templateid = template_id + cmd.serviceofferingid = self.__class__.service_offering_id + cmd.account = self.account.name + cmd.domainid = self.domain.id + if self.__class__.network_id: + cmd.networkids = self.__class__.network_id + return cmd + + def _deploy_from_template(self, template_id): + """Deploy a VM from a template and check its ROOT volume is on the pool.""" + vm = self._deploy_vm(self._deploy_cmd(template_id)) + self._extra_vm_ids.append(vm.id) + self._poll_vm_state(vm.id, "Running", timeout=900) + root = self._root_volume_for_vm(vm.id) + self.assertEqual(str(root.storageid), str(self.__class__.pool.id), + "VM %s root is not on the ONTAP pool" % vm.id) + return vm + + def _deploy_data_template(self, template_id): + """Deploy from a data-disk template. The VM must reach Running or the test fails.""" + try: + vm = self._deploy_vm(self._deploy_cmd(template_id)) + except Exception as exc: + self.fail("Deploy from the data-disk template failed (%s); expected the VM to " + "start and then fail to boot" % exc) + self._extra_vm_ids.append(vm.id) + self._poll_vm_state(vm.id, "Running", timeout=300) + return vm + + def _expunge_tracked(self, vm_id): + self._stop_and_expunge_vm(vm_id) + if vm_id in self._extra_vm_ids: + self._extra_vm_ids.remove(vm_id) + + def _data_disks(self, vm_id): + cmd = listVolumesAPI.listVolumesCmd() + cmd.virtualmachineid = vm_id + cmd.type = "DATADISK" + cmd.listall = True + return self.apiClient.listVolumes(cmd) or [] + + def _account_templates(self): + cmd = listTemplatesAPI.listTemplatesCmd() + cmd.templatefilter = "self" + cmd.zoneid = self.zone.id + cmd.account = self.account.name + cmd.domainid = self.domain.id + cmd.listall = True + return self.apiClient.listTemplates(cmd) or [] + + def _account_template_ids(self): + return {t.id for t in self._account_templates()} + + def _assert_no_template_in_progress(self, timeout=120): + """Fail if a template of the account stays in a creating or copying status.""" + deadline = time.time() + timeout + stuck = [] + while time.time() < deadline: + stuck = [(t.id, getattr(t, "status", None)) for t in self._account_templates() + if _template_in_progress(getattr(t, "status", None))] + if not stuck: + return + time.sleep(5) + self.fail("Templates still in progress after %ds: %s" % (timeout, stuck)) + + def _wait_snapshot_backed_up(self, snap_id, timeout=120): + deadline = time.time() + timeout + state = None + while time.time() < deadline: + listed = Snapshot.list(self.apiClient, id=snap_id, listall=True) or [] + state = listed[0].state if listed else None + if state == "BackedUp": + return + time.sleep(5) + self.fail("Snapshot %s is %s after the concurrent creates, expected BackedUp" + % (snap_id, state)) + + def _job_error_text(self, job): + result = getattr(job, "jobresult", None) + text = getattr(result, "errortext", None) + if text is None and isinstance(result, dict): + text = result.get("errortext") + return str(text if text is not None else result) + + def _vm_host_and_instance(self, vm_id): + """KVM host IP and libvirt domain name of a running VM.""" + vms = self.apiClient.listVirtualMachines(_list_vms_cmd(vm_id)) or [] + self.assertTrue(vms, "VM %s is not listed" % vm_id) + host_id = getattr(vms[0], "hostid", None) + instance = getattr(vms[0], "instancename", None) + self.assertTrue(host_id and instance, "VM %s has no host or instance name" % vm_id) + host_ip = next((h.ipaddress for h in (self.cluster_hosts or []) if h.id == host_id), None) + self.assertTrue(host_ip, "No cluster host with id %s for VM %s" % (host_id, vm_id)) + return host_ip, instance + + def _vm_root_read_bytes(self, host_ip, instance): + """Bytes the guest has read from its first (root) disk, from libvirt.""" + vm_arg = shlex.quote(str(instance)) + out = self._kvm_run( + host_ip, + "target=$(virsh domblklist {vm} --details | " + "awk '$2 == \"disk\" {{ print $3; exit }}'); " + "test -n \"$target\" && virsh domblkstat {vm} \"$target\" | " + "awk '$2 == \"rd_bytes\" {{ print $3; exit }}'".format(vm=vm_arg)) + text = "\n".join(out).strip() + self.assertTrue(text.isdigit(), + "Could not read rd_bytes for %s on %s, got %r" % (instance, host_ip, text)) + return int(text) + + def _assert_vm_has_no_bootable_disk(self, vm_id, settle=90, interval=30): + """Show on the KVM host that the guest never loaded an OS from its root disk. + + libvirt must report the domain running, so a host, network or capacity + failure cannot pass. The root disk read counter must then stay flat + and below NO_BOOT_MAX_READ_BYTES: a booting OS keeps reading, while a + guest with no bootable device only probes the boot sector. + """ + host_ip, instance = self._vm_host_and_instance(vm_id) + state = " ".join(self._kvm_run( + host_ip, "virsh domstate %s" % shlex.quote(str(instance)))).strip().lower() + self.assertEqual(state, "running", + "libvirt reports %s as %r on %s, expected running" % (instance, state, host_ip)) + time.sleep(settle) + first = self._vm_root_read_bytes(host_ip, instance) + time.sleep(interval) + second = self._vm_root_read_bytes(host_ip, instance) + logger.info("test_14: root disk reads of %s on %s: %d then %d bytes", + instance, host_ip, first, second) + self.assertEqual(second, first, + "Root disk reads of %s are still growing (%d -> %d bytes): " + "an OS is loading from it" % (instance, first, second)) + self.assertLessEqual( + second, NO_BOOT_MAX_READ_BYTES, + "Guest read %d bytes from its root disk; a guest with no bootable device " + "reads at most %d" % (second, NO_BOOT_MAX_READ_BYTES)) + return second + + @contextmanager + def _guest_of(self, vm_id, connect_timeout=600): + """SSH to any VM as the template user. The suite VM reuses its port forward.""" + cls = self.__class__ + if cls.vm is not None and vm_id == cls.vm.id and cls.vm_ssh: + host, port = cls.vm_ssh + rule = None + else: + host, port, rule = open_ssh_port(self.apiClient, vm_id, cls.network_id) + self._extra_ssh_rules.append(rule) + try: + with GuestSsh(host, port, self.guest_user, self.guest_password, + connect_timeout=connect_timeout) as guest: + yield guest + finally: + if rule is not None: + if rule in self._extra_ssh_rules: + self._extra_ssh_rules.remove(rule) + try: + close_ssh_port(self.apiClient, rule) + except Exception as exc: + logger.warning("could not close SSH rule %s: %s" % (rule, exc)) + + def _write_file(self, vm_id, path, token): + with self._guest_of(vm_id) as guest: + guest.run("echo '%s' > %s && sync" % (token, path)) + + def _read_file(self, vm_id, path, connect_timeout=600): + with self._guest_of(vm_id, connect_timeout=connect_timeout) as guest: + return guest.run("cat %s 2>/dev/null; true" % path).strip() + + def _write_data_disk_marker(self, vm_id, token): + with self._guest_of(vm_id) as guest: + guest.write_data_marker(token) + + @attr(tags=[TAG], required_hardware=True) + def test_01_create_iscsi_pool(self): + """Create the iSCSI primary storage pool on ONTAP.""" + self.step_01_create_pool() + + @attr(tags=[TAG], required_hardware=True) + def test_02_create_ontap_data_volume(self): + """Create a CloudStack data volume on the ONTAP pool.""" + self.step_02_create_ontap_data_volume() + + @attr(tags=[TAG], required_hardware=True) + def test_03_deploy_vm(self): + """Deploy a VM whose ROOT disk is on the ONTAP pool.""" + self.step_03_deploy_vm() + + @attr(tags=[TAG], required_hardware=True) + def test_04_attach_volume_to_vm(self): + """Attach the data volume to the running VM.""" + self.step_04_attach_volume_to_vm() + + @attr(tags=[TAG], required_hardware=True) + def test_05_open_ssh_and_write_root_data_files(self): + """Open an SSH port forward and write files to the ROOT and DATA disks.""" + self.step_09_open_ssh_and_write_root_data_files() + + @attr(tags=[TAG], required_hardware=True) + def test_06_create_template_from_root_snapshot(self): + """ + Snapshot the running VM's ROOT disk, create a template from the snapshot, + and deploy a VM from the template. The deployed VM must have the file + written before the snapshot. + """ + vm = self._require_snapshot_vm() + self._require_image_store() + token = new_token("root-template") + self._write_file(vm.id, TEMPLATE_FILE_A, token) + snap, names = self._snapshot_root(vm, "root snapshot for template") + template = self._create_ready_template(snap, names, self._tpl_name("root")) + found = self._read_file(self._deploy_from_template(template.id).id, TEMPLATE_FILE_A) + self.assertEqual(found, token, "Deployed VM has %r, expected %r" % (found, token)) + + @attr(tags=[TAG], required_hardware=True) + def test_07_template_from_older_root_snapshot(self): + """ + Take two ROOT snapshots, one after the other. The template made from the + older snapshot must have the older file and not the newer one. + """ + vm = self._require_snapshot_vm() + self._require_image_store() + token_a = new_token("older-a") + token_b = new_token("older-b") + self._write_file(vm.id, TEMPLATE_FILE_A, token_a) + snap, names = self._snapshot_root(vm, "older root snapshot") + self._write_file(vm.id, TEMPLATE_FILE_B, token_b) + self._snapshot_root(vm, "newer root snapshot") + template = self._create_ready_template(snap, names, self._tpl_name("older")) + deployed = self._deploy_from_template(template.id) + self.assertEqual(self._read_file(deployed.id, TEMPLATE_FILE_A), token_a) + self.assertNotEqual(self._read_file(deployed.id, TEMPLATE_FILE_B), token_b, + "Template from the older snapshot contains the later file") + + @attr(tags=[TAG], required_hardware=True) + def test_08_two_templates_from_two_snapshots(self): + """ + Submit two createTemplate calls without waiting, one per ROOT snapshot. + Both templates must reach Ready and both snapshots must stay BackedUp. + """ + vm = self._require_snapshot_vm() + self._require_image_store() + snap_a, names_a = self._snapshot_root(vm, "first of two snapshots") + snap_b, names_b = self._snapshot_root(vm, "second of two snapshots") + before = self._pool_lun_uuids() + first = self._submit_template(snap_a.id, self._tpl_name("two-a"), wait=False) + second = self._submit_template(snap_b.id, self._tpl_name("two-b"), wait=False) + job_a = self._wait_async_job(first.jobid) + job_b = self._wait_async_job(second.jobid) + self.assertEqual(job_a.jobstatus, JOB_SUCCEEDED, + "Template from the first snapshot failed: %s" % job_a) + self.assertEqual(job_b.jobstatus, JOB_SUCCEEDED, + "Template from the second snapshot failed: %s" % job_b) + ready_a = self._wait_template_ready(first.id) + ready_b = self._wait_template_ready(second.id) + self.assertNotEqual(ready_a.id, ready_b.id, "Both templates have the same ID") + self._assert_snapshot_kept(snap_a, names_a) + self._assert_snapshot_kept(snap_b, names_b) + self.assertEqual(self._pool_lun_uuids(), before, + "Primary storage changed while creating the two templates") + + @attr(tags=[TAG], required_hardware=True) + def test_09_delete_template_keeps_snapshot(self): + """ + Delete a ready template. The template is gone and its source snapshot is + still BackedUp in CloudStack and on ONTAP. + """ + vm = self._require_snapshot_vm() + self._require_image_store() + snap, names = self._snapshot_root(vm, "root snapshot for template delete") + template = self._create_ready_template(snap, names, self._tpl_name("delete-me")) + self._delete_template(template.id) + self._wait_template_gone(template.id) + self._assert_snapshot_kept(snap, names) + + @attr(tags=[TAG], required_hardware=True) + def test_10_delete_snapshot_keeps_template(self): + """ + Delete the source snapshot after its template is Ready. The template stays + Ready and still deploys with the file written before the snapshot. + """ + vm = self._require_snapshot_vm() + self._require_image_store() + token = new_token("snapshot-deleted") + self._write_file(vm.id, TEMPLATE_FILE_A, token) + snap, names = self._snapshot_root(vm, "snapshot deleted after template") + template = self._create_ready_template(snap, names, self._tpl_name("keeps-template")) + self._delete_volume_snapshot_with_retry(snap.id) + self._wait_until_gone( + lambda: self._volume_snapshot_listed(snap.id), + "Snapshot %s still listed after delete" % snap.id) + if snap.id in self._volume_snapshot_ids: + self._volume_snapshot_ids.remove(snap.id) + self._created_ontap_snaps -= set(names) + self._wait_ontap_snaps_gone(names) + ready = self._wait_template_ready(template.id) + self.assertTrue(_enabled(getattr(ready, "isready", False))) + found = self._read_file(self._deploy_from_template(template.id).id, TEMPLATE_FILE_A) + self.assertEqual(found, token) + + @attr(tags=[TAG], required_hardware=True) + def test_11_template_stores_attributes(self): + """ + Create a template with password-enabled and dynamically-scalable set. The + template must store both flags and the suite template's OS type. + """ + vm = self._require_snapshot_vm() + self._require_image_store() + snap, names = self._snapshot_root(vm, "root snapshot for attributes") + template = self._create_ready_template( + snap, names, self._tpl_name("attrs"), + passwordenabled=True, isdynamicallyscalable=True) + self.assertTrue(_enabled(getattr(template, "passwordenabled", False)), + "Template did not store passwordenabled") + self.assertTrue(_enabled(getattr(template, "isdynamicallyscalable", False)), + "Template did not store isdynamicallyscalable") + self.assertEqual(getattr(template, "ostypeid", None), self._ostype_id(), + "Template OS type is not the suite template's OS type") + + @attr(tags=[TAG], required_hardware=True) + def test_12_template_after_vm_expunged(self): + """ + Snapshot the ROOT disk of a second VM, expunge that VM, then create the + template from the snapshot. The template must deploy with the file. + """ + self._require_snapshot_vm() + self._require_image_store() + source = self._deploy_from_template(self.__class__.template_id) + token = new_token("vm-gone") + self._write_file(source.id, TEMPLATE_FILE_A, token) + snap, names = self._snapshot_root(source, "snapshot of VM that will be expunged") + self._expunge_tracked(source.id) + template = self._create_ready_template( + snap, names, self._tpl_name("after-expunge"), suite_running=True) + found = self._read_file(self._deploy_from_template(template.id).id, TEMPLATE_FILE_A) + self.assertEqual(found, token) + + @attr(tags=[TAG], required_hardware=True) + def test_13_data_snapshot_template_unbootable(self): + """ + Create a template from a DATA volume snapshot and deploy a VM from it. + The deployment must succeed and the VM must reach Running, so a network, + host or capacity failure fails the test. The KVM host must then show the + guest never loaded an OS: libvirt reports the domain running and its + root disk read counter stays flat and tiny, which is the BIOS probing + for a bootable device. SSH being unreachable is checked as well. + """ + vm = self._require_snapshot_vm() + self._require_data_attached(vm) + self._require_image_store() + self.assertTrue( + self.kvm_hosts_ssh_creds, + "No KVM host SSH credentials are configured for the host-side no-boot check") + snap, names = self._snapshot_volume(self.__class__.volume.id, + "data snapshot for template") + template = self._create_ready_template(snap, names, self._tpl_name("data-disk")) + deployed = self._deploy_data_template(template.id) + self._assert_vm_has_no_bootable_disk(deployed.id) + try: + self._read_file(deployed.id, TEMPLATE_FILE_A, connect_timeout=60) + except Exception as exc: + logger.info("test_13: SSH to the VM from the data-disk template failed " + "as expected: %s" % exc) + else: + self.fail("VM deployed from a data-disk snapshot template accepted SSH") + + @attr(tags=[TAG], required_hardware=True) + def test_14_reject_missing_template_fields(self): + """ + Call createTemplate once with an empty name and once with no OS type. Both + calls must be rejected and no template may be created. + """ + vm = self._require_snapshot_vm() + self._require_image_store() + snap, names = self._snapshot_root(vm, "snapshot for rejected template") + before = self._pool_lun_uuids() + for label, name, ostype in (("empty name", "", True), + ("no OS type", self._tpl_name("no-os"), False)): + try: + response = self._submit_template(snap.id, name, ostype=ostype) + except Exception as exc: + logger.info("test_14: %s rejected: %s" % (label, exc)) + continue + self.fail("createTemplate with %s was accepted (template %s)" + % (label, getattr(response, "id", None))) + self.assertEqual(self._pool_lun_uuids(), before, + "A rejected createTemplate changed primary storage") + self._assert_snapshot_kept(snap, names) + + @attr(tags=[TAG], required_hardware=True) + def test_15_reject_second_template_same_snapshot(self): + """ + Submit two createTemplate calls for one snapshot without waiting. Exactly + one must succeed and reach Ready. The other must be rejected with a + concurrent or duplicate-state error, either when it is submitted or as a + failed job. The losing template must not be Ready, no template may stay + in Creating, the account must gain exactly the winning template, and the + snapshot must return to BackedUp. + """ + vm = self._require_snapshot_vm() + self._require_image_store() + snap, names = self._snapshot_root(vm, "snapshot for two template creates") + before_ids = self._account_template_ids() + before_primary = self._pool_lun_uuids() + + calls = [] + for label in ("race-a", "race-b"): + try: + response = self._submit_template(snap.id, self._tpl_name(label), wait=False) + except Exception as exc: + calls.append({"label": label, "response": None, "error": str(exc)}) + continue + calls.append({"label": label, "response": response, "error": None}) + for call in calls: + if call["response"] is None: + continue + job = self._wait_async_job(call["response"].jobid) + if job.jobstatus != JOB_SUCCEEDED: + call["error"] = self._job_error_text(job) + + outcome = [(c["label"], c["error"]) for c in calls] + logger.info("test_15: outcomes (label, error): %s", outcome) + winners = [c for c in calls if c["error"] is None] + losers = [c for c in calls if c["error"] is not None] + self.assertEqual(len(winners), 1, + "Expected one template create to succeed, outcomes: %s" % outcome) + self.assertEqual(len(losers), 1, + "Expected one template create to be rejected, outcomes: %s" % outcome) + winner, loser = winners[0], losers[0] + self.assertTrue( + CONCURRENT_REJECTION.search(loser["error"]), + "The losing create was not rejected for the concurrent or duplicate state: %s" + % loser["error"]) + + self._wait_template_ready(winner["response"].id) + loser_id = getattr(loser["response"], "id", None) if loser["response"] else None + if loser_id: + for record in self._template_record(loser_id): + self.assertFalse( + _enabled(getattr(record, "isready", False)), + "Losing template %s is Ready" % loser_id) + self._assert_no_template_in_progress() + added = self._account_template_ids() - before_ids + self.assertEqual( + added, {winner["response"].id}, + "Expected the account to gain only the winning template %s, gained %s" + % (winner["response"].id, sorted(added))) + self._wait_snapshot_backed_up(snap.id) + self._assert_snapshot_kept(snap, names) + self.assertEqual(self._pool_lun_uuids(), before_primary, + "Primary storage changed after the two template creates") + + @attr(tags=[TAG], required_hardware=True) + def test_16_destroy_vm_and_cleanup(self): + """Destroy the VMs, delete the data volume and the pool.""" + self.step_27_destroy_vm_and_cleanup() diff --git a/test/integration/plugins/ontap/iscsi/volume/test_snapshot_to_volume.py b/test/integration/plugins/ontap/iscsi/volume/test_snapshot_to_volume.py new file mode 100644 index 000000000000..b5e934f95666 --- /dev/null +++ b/test/integration/plugins/ontap/iscsi/volume/test_snapshot_to_volume.py @@ -0,0 +1,897 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +""" +Snapshot-to-volume integration tests for ONTAP iSCSI primary storage (Marvin). + +Create volumes from ROOT and DATA volume snapshots of a running VM, attach them to +VMs, and check each new volume in CloudStack and in ONTAP. + +Tests are numbered test_01 ... test_23 and must run in that order. Each step +builds on the shared state established by the previous step. + +Workflow: + 01 Create the iSCSI primary storage pool on ONTAP + 02 Create and attach the data volume, deploy VM-A, and write ROOT and DATA files + 03 Deploy VM-B on the same pool + 04 Create a DATADISK (RAW) volume from a ROOT snapshot of VM-A + 05 Create a volume from a DATA snapshot; attach it and verify its marker + 06 Move a clone from VM-A to VM-B and verify its data + 07 Verify a clone is independent of its source + 08 Reject createVolume from a VM snapshot ID + 09 Reject a ROOT-snapshot clone with a smaller offering + 10 Reject attaching one clone to two VMs + 11 Delete a DATA snapshot while createVolume is in flight; no orphaned LUN + 12 Create a DATA-snapshot volume with the source offering and size + 13 Reject createVolume from a DATA snapshot with a disk offering + 14 Create three volumes concurrently from one snapshot + 15 Create a volume after its source volume is deleted + 16 Create a volume from a snapshot of a clone + 17 Reject createVolume when its FlexVol snapshot is missing + 18 Reject createVolume while the pool is Disabled; succeed once Up + 19 Reject createVolume with a nonexistent snapshot ID + 20 Reject createVolume when only another pool is available + 21 Reject createVolume when required snapshot metadata is missing + 22 Reject a second volume with the same name from one snapshot + 23 Destroy both VMs, delete the data volume and the pool +Setup and cleanup steps are shared with the VM suite; see helpers/snapshot_base.py. + +Guest login for the CentOS 5.5 template comes from ontap.cfg +(cloudstack.templateUsername / templatePassword); see guest_ssh.py. + +Running: + bash test/integration/plugins/ontap/run_tests.sh iscsi_snapshot_to_volume + +Note: Tests share class-level state (sequential). Always run the full suite. +""" + +import logging +import random +import uuid +from concurrent.futures import ThreadPoolExecutor + +from nose.plugins.attrib import attr + +from marvin.cloudstackAPI import ( + attachVolume as attachVolumeAPI, + createVolume as createVolumeAPI, + deleteVolume as deleteVolumeAPI, + listVolumes as listVolumesAPI, +) +from marvin.lib.base import DiskOffering, Snapshot +from marvin.codes import JOB_SUCCEEDED + +from guest_ssh import new_token + +from helpers.snapshot_base import ( + REQUIRED_SNAPSHOT_DETAILS, + FAILED_VOLUME_STATES, + OntapSnapshotBase, + _guest_disk_names, +) +from ontap_test_base import _list_vols_cmd + + +logger = logging.getLogger("TestOntapIscsiSnapshotToVolume") + +TAG = "iscsi_snapshot_to_volume" + + +class TestOntapIscsiSnapshotToVolume(OntapSnapshotBase): + """ + Create volumes from snapshots on the ONTAP iSCSI pool and attach them to VMs. + + All tests are sequential; state is carried on class attributes. + """ + + PROTOCOL = "ISCSI" + + def _pool_objects_of(self, pool): + """UUIDs of the LUNs in the pool's FlexVol.""" + return {r["uuid"] for r in + self.ontap.list_luns_in_volume(self.svm_name, pool.name)} + + def _clone_object_exists(self, clone): + """The clone's LUN is named after the CloudStack volume, inside the pool's FlexVol.""" + return self._lun_exists(self._data_lun_name(clone)) + + def _assert_clone_lun(self, lun, snapshot_id, source_lun_name, label): + """The LUN is an ONTAP clone made from the snapshot's source LUN. + + ONTAP's LUN GET reports only ``clone.created_as_clone``, not the source + path, so the source is checked on the CloudStack side: the snapshot's + ``volume_path`` detail is the LUN the driver passes to ONTAP as the clone + source. + """ + clone = lun.get("clone") or {} + self.assertTrue(clone.get("created_as_clone") is True, + "[%s] LUN is not reported as an ONTAP clone: %s" % (label, lun)) + rows = self.__class__.dbConnection.execute( + "SELECT d.value FROM snapshot_details d " + "JOIN snapshots s ON s.id = d.snapshot_id " + "WHERE s.uuid = %s AND d.name = 'volume_path'", params=(snapshot_id,)) + self.assertTrue(rows, "[%s] snapshot %s has no volume_path detail" % (label, snapshot_id)) + self.assertEqual(rows[0][0].rsplit("/", 1)[-1], source_lun_name.rsplit("/", 1)[-1], + "[%s] snapshot volume_path %r is not the source LUN %r" + % (label, rows[0][0], source_lun_name)) + + def _lun_exists(self, lun_path): + return self.ontap.get_lun(self.svm_name, lun_path) is not None + + def _wait_clone_lun_gone(self, clone): + lun_path = self._data_lun_name(clone) + self._wait_until_gone(lambda: self._lun_exists(lun_path), + "Clone LUN %s still present after the clone was deleted" % lun_path) + + def _clone_lun_maps(self, clone): + """The clone LUN's maps as sorted (igroup name, LUN id) pairs.""" + return sorted((m.get("igroup", {}).get("name"), m.get("logical_unit_number")) + for m in self._lun_maps(clone)) + + @attr(tags=[TAG], required_hardware=True) + def test_01_create_iscsi_pool(self): + """Create the iSCSI primary storage pool on ONTAP.""" + self.step_01_create_pool() + + @attr(tags=[TAG], required_hardware=True) + def test_02_prepare_vm_with_data_volume(self): + """Create the data volume, deploy the VM, attach it, and write ROOT and DATA files.""" + self.step_02_create_ontap_data_volume() + self.step_03_deploy_vm() + self.step_04_attach_volume_to_vm() + self.step_09_open_ssh_and_write_root_data_files() + + @attr(tags=[TAG], required_hardware=True) + def test_03_deploy_second_vm(self): + """Deploy a second VM on the same ONTAP pool.""" + self.step_19_deploy_second_vm() + + @attr(tags=[TAG], required_hardware=True) + def test_04_create_volume_from_root_snapshot(self): + """ + Create a volume from a ROOT volume snapshot of the running VM. + Verifies: + - the new volume reaches Ready on the ONTAP test pool + - CloudStack records it as DATADISK (not ROOT) with format RAW + - ONTAP has a LUN for it inside the pool's FlexVol + """ + vm = self._require_snapshot_vm() + before = self._ontap_snap_names() + snap = self._take_volume_snapshot(self._root_volume_for_vm(vm.id).id) + self._assert_new_ontap_snaps(before, [snap], "volume", "ROOT snapshot for clone") + + clone = self._create_clone(snap.id) + try: + self.assertEqual(getattr(clone, "type", None), "DATADISK", + "Clone of a ROOT snapshot is %r, expected DATADISK" + % getattr(clone, "type", None)) + self.assertEqual(getattr(clone, "storageid", None), self.__class__.pool.id, + "Clone of a ROOT snapshot is not on the ONTAP test pool") + self.assertEqual(self._db_volume_format(clone.id), "RAW", + "Clone of a ROOT snapshot is not RAW in the volumes table") + self.assertTrue(self._lun_exists(self._data_lun_name(clone)), + "ONTAP LUN for the clone of a ROOT snapshot is missing") + finally: + self._remove_clone(clone) + self._wait_clone_lun_gone(clone) + + @attr(tags=[TAG], required_hardware=True) + def test_05_create_volume_from_data_snapshot(self): + """ + Create a volume from a DATA volume snapshot, attach it to the running VM + and read the snapshot-time marker from it. + Verifies: + - the clone reaches Ready and has its own LUN in ONTAP + - the clone holds the token written before the snapshot, not the one + written after it + - the clone detaches and is deleted, and its LUN is removed + """ + vm = self._require_snapshot_vm() + self._require_data_attached(vm) + token_snap = new_token("clone-snapshot-time") + token_after = new_token("clone-after-snapshot") + self._write_marker(token_snap, disks=("DATA",)) + before = self._ontap_snap_names() + snap = self._take_volume_snapshot(self.__class__.volume.id) + self._assert_new_ontap_snaps(before, [snap], "volume", "DATA snapshot for clone") + self._write_marker(token_after, disks=("DATA",)) + + clone = self._create_clone(snap.id) + try: + self.assertTrue(self._lun_exists(self._data_lun_name(clone)), + "ONTAP LUN for the data clone is missing") + dev = self._attach_clone(clone, vm.id, "vm") + found = self._clone_marker("vm", dev) + self.assertEqual( + found, token_snap, + "Clone marker is %r, expected snapshot-time %r (post-snapshot token was %r)" + % (found, token_snap, token_after)) + self._detach_clone(clone) + finally: + self._remove_clone(clone) + self._wait_clone_lun_gone(clone) + + @attr(tags=[TAG], required_hardware=True) + def test_06_detach_and_reattach_clone_on_second_vm(self): + """ + Write to a clone attached to VM-A, detach it, attach it to VM-B and read + the data back. + Verifies: + - the write made on VM-A is read back on VM-A + - the clone's LUN stays in ONTAP while the clone is detached + - the same data is read on VM-B after the reattach + """ + vm = self._require_snapshot_vm() + vm2 = self._require_second_vm() + self._require_data_attached(vm) + before = self._ontap_snap_names() + snap = self._take_volume_snapshot(self.__class__.volume.id) + self._assert_new_ontap_snaps(before, [snap], "volume", "DATA snapshot for reattach") + + token = new_token("clone-written-on-vm-a") + clone = self._create_clone(snap.id) + lun_path = self._data_lun_name(clone) + try: + dev = self._attach_clone(clone, vm.id, "vm") + found = self._clone_marker("vm", dev, write=token) + self.assertEqual(found, token, "Write on VM-A read back as %r, expected %r" + % (found, token)) + self._detach_clone(clone) + self.assertTrue(self._lun_exists(lun_path), + "Clone LUN disappeared while the clone was detached") + dev2 = self._attach_clone(clone, vm2.id, "vm2") + found = self._clone_marker("vm2", dev2) + self.assertEqual(found, token, "Data read on VM-B is %r, expected %r" + % (found, token)) + finally: + self._remove_clone(clone) + self._wait_clone_lun_gone(clone) + + @attr(tags=[TAG], required_hardware=True) + def test_07_clone_is_independent_of_source(self): + """ + Write to a clone, then to its source, and check each side keeps its own data. + Verifies: + - the clone holds the snapshot-time token, not the one written after it + - a write to the clone does not change the source DATA marker + - a write to the source does not change the clone marker + """ + vm = self._require_snapshot_vm() + self._require_data_attached(vm) + token_snap = new_token("independence-snapshot") + token_src = new_token("independence-source-after") + token_clone = new_token("independence-clone-write") + token_src_final = new_token("independence-source-final") + self._write_marker(token_snap, disks=("DATA",)) + before = self._ontap_snap_names() + snap = self._take_volume_snapshot(self.__class__.volume.id) + self._assert_new_ontap_snaps(before, [snap], "volume", "DATA snapshot for independence") + self._write_marker(token_src, disks=("DATA",)) + + clone = self._create_clone(snap.id) + try: + dev = self._attach_clone(clone, vm.id, "vm") + found = self._clone_marker("vm", dev) + self.assertEqual(found, token_snap, + "Clone marker is %r, expected snapshot-time %r" + % (found, token_snap)) + self._clone_marker("vm", dev, write=token_clone) + self._assert_marker(token_src, disk="DATA", msg="after write to the clone") + self._write_marker(token_src_final, disks=("DATA",)) + found = self._clone_marker("vm", dev) + self.assertEqual(found, token_clone, + "Clone marker changed after a source write: %r, expected %r" + % (found, token_clone)) + self._detach_clone(clone) + finally: + self._remove_clone(clone) + self._wait_clone_lun_gone(clone) + + @attr(tags=[TAG], required_hardware=True) + def test_08_reject_clone_from_vm_snapshot(self): + """ + Pass a VM snapshot ID to createVolume. + Verifies: + - the request is rejected + - no volume record is left behind and the FlexVol gains no LUN + - the VM snapshot is still Ready + """ + vm = self._require_snapshot_vm() + before = self._ontap_snap_names() + vm_snap = self._take_vm_snapshot_when_accepted(vm.id) + self._assert_new_ontap_snaps(before, [vm_snap], "vm", + "VM snapshot for rejected clone") + + message = self._expect_clone_rejected(vm_snap.id) + logger.info("test_08: createVolume from a VM snapshot rejected: %s" % message) + # CloudStack looks the ID up as a volume snapshot and does not find it. + # The error must name snapshotid, so a storage-side failure cannot pass here. + self.assertIn("snapshotid", message.lower(), + "Rejection does not name snapshotid: %s" % message) + self.assertIn("does not exist", message.lower(), + "Rejection is not an unknown-snapshot error: %s" % message) + + listed = [s for s in self._vm_snapshots_of(vm.id) if s.id == vm_snap.id] + self.assertTrue(listed and listed[0].state == "Ready", + "VM snapshot %s is not Ready after the rejected create" % vm_snap.id) + + @attr(tags=[TAG], required_hardware=True) + def test_09_reject_smaller_offering_for_root_snapshot(self): + """ + Create a volume from a ROOT snapshot with a disk offering smaller than + the ROOT disk. + Verifies: + - the request is rejected + - no volume record is left behind and the FlexVol gains no LUN + """ + vm = self._require_snapshot_vm() + root = self._root_volume_for_vm(vm.id) + offering_gib = (int(root.size) - 1) // (1024 ** 3) + if offering_gib < 1: + self.skipTest("ROOT disk is %d bytes; no smaller offering of at least 1 GiB exists" + % int(root.size)) + before = self._ontap_snap_names() + snap = self._take_volume_snapshot(root.id) + self._assert_new_ontap_snaps(before, [snap], "volume", + "ROOT snapshot for rejected clone") + + small = DiskOffering.create( + self.apiClient, + { + "name": "OntapISCSIVMSmallDO_%d" % random.randint(0, 99999), + "displaytext": "Disk offering smaller than the ROOT disk", + "disksize": offering_gib, + "storagetype": "shared", + "tags": self.__class__.pool_tags, + }, + ) + try: + message = self._expect_clone_rejected(snap.id, disk_offering_id=small.id) + logger.info("test_09: %d GiB offering for a %d byte ROOT snapshot rejected: %s" + % (offering_gib, int(root.size), message)) + self.assertIn("Invalid size for volume creation", message, + "Rejection is not the size check: %s" % message) + finally: + try: + small.delete(self.apiClient) + except Exception as exc: + logger.warning("test_09: could not delete disk offering %s: %s" + % (small.id, exc)) + + @attr(tags=[TAG], required_hardware=True) + def test_10_reject_attach_of_attached_clone_to_second_vm(self): + """ + Attach a clone to VM-A, then try to attach it to VM-B without detaching. + Verifies: + - the second attach is rejected as already attached + - the clone still references VM-A + - VM-A still reads the clone marker + - the clone LUN's maps are unchanged: VM-A's map remains and none is added for VM-B + - VM-B sees no new disk + """ + vm = self._require_snapshot_vm() + vm2 = self._require_second_vm() + self._require_data_attached(vm) + before = self._ontap_snap_names() + snap = self._take_volume_snapshot(self.__class__.volume.id) + self._assert_new_ontap_snaps(before, [snap], "volume", "DATA snapshot for double attach") + + token = new_token("clone-attached-to-vm-a") + clone = self._create_clone(snap.id) + try: + dev = self._attach_clone(clone, vm.id, "vm") + found = self._clone_marker("vm", dev, write=token) + self.assertEqual(found, token, "Write on VM-A read back as %r, expected %r" + % (found, token)) + maps_before = self._clone_lun_maps(clone) + self.assertTrue(maps_before, "Clone LUN has no map while attached to VM-A") + with self._guest("vm2") as guest: + vm2_disks_before = _guest_disk_names(guest) + + cmd = attachVolumeAPI.attachVolumeCmd() + cmd.id = clone.id + cmd.virtualmachineid = vm2.id + try: + self.apiClient.attachVolume(cmd) + except Exception as exc: + message = str(exc) + else: + self.fail("attachVolume of clone %s to VM-B was accepted while attached to VM-A" + % clone.id) + logger.info("test_10: second attach rejected: %s" % message) + # The admin attach path says "not attached to any VM"; the user path says "already attached". + lowered = message.lower() + self.assertTrue("not attached to any vm" in lowered or "already attached" in lowered, + "Rejection is not the attached-volume check: %s" % message) + + cmd = listVolumesAPI.listVolumesCmd() + cmd.id = clone.id + cmd.listall = True + listed = self.apiClient.listVolumes(cmd) or [] + self.assertTrue(listed, "Clone %s is no longer listed" % clone.id) + self.assertEqual(getattr(listed[0], "virtualmachineid", None), vm.id, + "Clone no longer references VM-A after the rejected attach") + self.assertEqual(self._clone_lun_maps(clone), maps_before, + "Clone LUN maps changed after the rejected attach") + with self._guest("vm2") as guest: + self.assertEqual(_guest_disk_names(guest), vm2_disks_before, + "VM-B gained a disk after the rejected attach") + found = self._clone_marker("vm", dev) + self.assertEqual(found, token, "VM-A reads %r after the rejected attach, expected %r" + % (found, token)) + self._detach_clone(clone) + finally: + self._remove_clone(clone) + self._wait_clone_lun_gone(clone) + + @attr(tags=[TAG], required_hardware=True) + def test_11_delete_snapshot_during_create(self): + """ + Submit createVolume(snapshotid) without waiting for it, then delete the + DATA snapshot while the create is still in progress. + Verifies a deterministic outcome with no orphaned LUN: + - if createVolume succeeds: the volume is Ready as RAW and exactly + one new LUN for it appears in the FlexVol; the clone and the + snapshot are then removed in this step + - if createVolume fails: no usable volume record is left behind, no + LUN is added to the FlexVol, and the snapshot is removed from both + CloudStack and ONTAP + - the VM stays Running and the FlexVol LUN set returns to its baseline + """ + vm = self._require_snapshot_vm() + self._require_data_attached(vm) + before = self._ontap_snap_names() + snap = self._take_volume_snapshot(self.__class__.volume.id) + ontap_names = self._assert_new_ontap_snaps(before, [snap], "volume", + "DATA snapshot for delete race") + + luns_before = self._pool_lun_uuids() + volumes_before = self._account_volume_ids() + + create_cmd = createVolumeAPI.createVolumeCmd() + create_cmd.isAsync = "false" + create_cmd.name = "%s_race_%d" % (self._vol_name_prefix, random.randint(0, 999999)) + create_cmd.zoneid = self.zone.id + create_cmd.account = self.account.name + create_cmd.domainid = self.domain.id + create_cmd.snapshotid = snap.id + submitted = self.apiClient.createVolume(create_cmd) + self._extra_volume_ids.append(submitted.id) + + delete_rejected = False + delete_err = None + try: + Snapshot({"id": snap.id}).delete(self.apiClient) + except Exception as exc: + delete_rejected = True + delete_err = exc + logger.info("test_11: deleteSnapshot during in-flight create refused: %s" % exc) + + job = self._wait_async_job(submitted.jobid) + create_succeeded = (job.jobstatus == JOB_SUCCEEDED) + logger.info("test_11: race finished (create_succeeded=%s, delete_rejected=%s)", + create_succeeded, delete_rejected) + self.assertFalse( + (not create_succeeded) and delete_rejected, + "Both createVolume (jobstatus=%s) and deleteSnapshot (%s) failed" + % (job.jobstatus, delete_err)) + + if create_succeeded: + clone = self._poll_volume_field(submitted.id, "state", "Ready", timeout=600) + self.assertIsNotNone( + clone, "Completed createVolume left volume %s not Ready" % submitted.id) + self.assertEqual(self._db_volume_format(clone.id), "RAW", + "Race clone is not RAW in the volumes table") + self.assertEqual(self._account_volume_ids() - volumes_before, {clone.id}, + "Account volume set does not match the single created clone") + new_luns = self._pool_lun_uuids() - luns_before + self.assertEqual( + len(new_luns), 1, + "Expected 1 new LUN for the clone, found %d (orphaned or missing LUN)" + % len(new_luns)) + self.assertTrue(self._lun_exists(self._data_lun_name(clone)), + "The new LUN is not the clone's LUN %s" + % self._data_lun_name(clone)) + self._remove_clone(clone) + self._wait_clone_lun_gone(clone) + else: + vols = self.apiClient.listVolumes(_list_vols_cmd(submitted.id)) or [] + state = getattr(vols[0], "state", None) if vols else None + self.assertTrue(state is None or state in FAILED_VOLUME_STATES, + "Failed createVolume left volume %s in state %s" + % (submitted.id, state)) + self.assertEqual(self._account_volume_ids(), volumes_before, + "Failed createVolume left a usable volume record behind") + self.assertEqual(self._pool_lun_uuids(), luns_before, + "Failed createVolume left a LUN in the FlexVol") + if submitted.id in self._extra_volume_ids: + self._extra_volume_ids.remove(submitted.id) + + # Remove the snapshot. The delete may already have been accepted during + # the race, so only retry it while CloudStack still lists it. + if self._volume_snapshot_listed(snap.id): + self._delete_volume_snapshot_with_retry(snap.id) + self._wait_until_gone( + lambda: self._volume_snapshot_listed(snap.id), + "Volume snapshot %s still listed after the race" % snap.id) + if snap.id in self._volume_snapshot_ids: + self._volume_snapshot_ids.remove(snap.id) + self._created_ontap_snaps -= ontap_names + self._wait_ontap_snaps_gone(ontap_names) + + self.assertEqual(self._pool_lun_uuids(), luns_before, + "FlexVol LUN set after test_11 differs from baseline") + self.assertEqual(self._vm_state(vm.id), "Running", + "VM is not Running after the delete race") + + @attr(tags=[TAG], required_hardware=True) + def test_12_create_volume_keeps_offering_and_size(self): + """ + createVolume(snapshotid) with no disk offering; the clone takes the source's. + Verifies: + - the clone is Ready as DATADISK and RAW on the ONTAP test pool + - the clone has the source disk offering and size + - no cloneOfSnapshot volume detail is left on the clone + - ONTAP: the clone's LUN is an ONTAP clone of the source LUN, with the + same size; the source LUN UUID is unchanged + """ + src = self._cs_volume(self.__class__.volume.id) + src_luns = self._data_luns(self.__class__.volume) + self.assertEqual(len(src_luns), 1, + "Expected one LUN for the source volume, found %d" % len(src_luns)) + src_uuid = src_luns[0]["uuid"] + snap = self._take_volume_snapshot_when_accepted(self.__class__.volume.id) + clone = self._create_clone(snap.id) + try: + cloned = self._cs_volume(clone.id) + self.assertIsNotNone(cloned, "Clone not listed in CloudStack") + self.assertEqual(getattr(cloned, "type", None), "DATADISK", + "Clone type is %r, expected DATADISK" % getattr(cloned, "type", None)) + self.assertEqual(getattr(cloned, "storageid", None), self.__class__.pool.id, + "Clone is not on the ONTAP test pool") + self.assertEqual(cloned.diskofferingid, src.diskofferingid, + "Clone disk offering %s, expected source offering %s" + % (cloned.diskofferingid, src.diskofferingid)) + self.assertEqual(int(cloned.size), int(src.size), + "Clone size %s, expected %s" % (cloned.size, src.size)) + self.assertEqual(self._db_volume_format(clone.id), "RAW", + "Clone is not RAW in the volumes table") + + rows = self.__class__.dbConnection.execute( + "SELECT id FROM volumes WHERE uuid = %s", params=(clone.id,)) + self.assertTrue(rows, "No volumes row for uuid %s" % clone.id) + leftover = self.__class__.dbConnection.execute( + "SELECT id FROM volume_details WHERE volume_id = %s AND name = %s", + params=(rows[0][0], "cloneOfSnapshot")) + self.assertFalse(leftover, "cloneOfSnapshot detail was left on the clone volume") + + clone_luns = self._data_luns(clone) + self.assertEqual(len(clone_luns), 1, + "Expected one LUN for the clone, found %d" % len(clone_luns)) + self._assert_clone_lun(clone_luns[0], snap.id, + self._data_lun_name(self.__class__.volume), "test_12 clone") + src_size = (src_luns[0].get("space") or {}).get("size") + clone_size = (clone_luns[0].get("space") or {}).get("size") + self.assertIsNotNone(src_size, "ONTAP did not report the source LUN size") + self.assertEqual(int(clone_size), int(src_size), + "Clone LUN size %s, expected source LUN size %s" + % (clone_size, src_size)) + self.assertEqual({r["uuid"] for r in self._data_luns(self.__class__.volume)}, + {src_uuid}, "Source LUN changed after the clone was made") + finally: + self._remove_clone(clone) + self._wait_clone_object_gone(clone) + self._finish_volume_snapshot(snap.id) + + @attr(tags=[TAG], required_hardware=True) + def test_13_reject_disk_offering_with_snapshot(self): + """ + Pass both snapshotid and diskofferingid to createVolume. CloudStack only + allows a disk offering with a ROOT volume snapshot; this snapshot is of a + DATA volume. + Verifies: + - the request is rejected with the ROOT-only message + - no volume record is left behind and no LUN is added to the FlexVol + """ + snap = self._take_volume_snapshot_when_accepted(self.__class__.volume.id) + message = self._expect_clone_rejected( + snap.id, disk_offering_id=self.__class__.disk_offering_id) + self.assertIn("Disk Offering ID cannot be passed", message, + "Rejection is not the ROOT-only disk offering rule: %s" % message) + self._finish_volume_snapshot(snap.id) + + @attr(tags=[TAG], required_hardware=True) + def test_14_create_volumes_concurrently_from_snapshot(self): + """ + Submit three createVolume(snapshotid) requests at the same moment. + Verifies: + - every request ends Ready as a DATADISK on the pool, and the three are distinct + - exactly three new LUNs appear, one per volume, each an ONTAP clone of + the source LUN (no orphans) + """ + snap = self._take_volume_snapshot_when_accepted(self.__class__.volume.id) + before = self._pool_objects_of(self.__class__.pool) + with ThreadPoolExecutor(max_workers=3) as executor: + futures = [executor.submit(self._attempt_clone, snap.id) for _ in range(3)] + results = [f.result() for f in futures] + for rejected, _ in results: + self.assertFalse(rejected, "A concurrent createVolume from snapshot failed") + volumes = [vol for _, vol in results] + for vol in volumes: + self.assertEqual(getattr(vol, "type", None), "DATADISK", + "Concurrent clone %s is not DATADISK" % vol.id) + self.assertEqual(getattr(vol, "storageid", None), self.__class__.pool.id, + "Concurrent clone %s is not on the ONTAP test pool" % vol.id) + self.assertEqual(len({v.id for v in volumes}), 3, + "Concurrent createVolume returned duplicate volumes") + + new = self._pool_objects_of(self.__class__.pool) - before + self.assertEqual(len(new), 3, + "Expected 3 new LUNs, found %d (orphans or missing clones)" + % len(new)) + source_lun = self._data_lun_name(self.__class__.volume) + for vol in volumes: + luns = self._data_luns(vol) + self.assertEqual(len(luns), 1, + "Volume %s has %d LUNs, expected 1" % (vol.id, len(luns))) + self.assertIn(luns[0]["uuid"], new, "Volume %s LUN is not a new LUN" % vol.id) + self._assert_clone_lun(luns[0], snap.id, source_lun, + "test_14 volume %s" % vol.id) + for vol in volumes: + self._remove_clone(vol) + for vol in volumes: + self._wait_clone_object_gone(vol) + self._finish_volume_snapshot(snap.id) + + @attr(tags=[TAG], required_hardware=True) + def test_15_create_volume_after_source_deleted(self): + """ + Snapshot a second data volume, delete that volume, then create a volume + from the kept snapshot. + Verifies: + - the deleted volume's LUN is removed from the FlexVol + - the new clone is Ready as RAW on the pool and has its own LUN + """ + pool = self.__class__.pool + src2 = self._create_volume(pool.id) + self._extra_volume_ids.append(src2.id) + src2 = self._poll_volume_field(src2.id, "state", "Ready", timeout=600) + self.assertIsNotNone(src2, "Second source volume did not reach Ready") + self.assertTrue(self._clone_object_exists(src2), + "LUN for the second source volume is missing") + snap2 = self._take_volume_snapshot_when_accepted(src2.id) + + cmd = deleteVolumeAPI.deleteVolumeCmd() + cmd.id = src2.id + self.apiClient.deleteVolume(cmd) + self._extra_volume_ids.remove(src2.id) + self._wait_clone_object_gone(src2) + + clone = self._create_clone(snap2.id) + try: + self.assertEqual(self._db_volume_format(clone.id), "RAW", + "Clone is not RAW in the volumes table") + self.assertTrue(self._clone_object_exists(clone), + "ONTAP LUN for the clone is missing") + finally: + self._remove_clone(clone) + self._wait_clone_object_gone(clone) + self._finish_volume_snapshot(snap2.id) + + @attr(tags=[TAG], required_hardware=True) + def test_16_create_volume_from_snapshot_of_clone(self): + """ + Snapshot a clone of the DATA snapshot, then create a volume from that snapshot. + Verifies: + - the snapshot of the clone reaches BackedUp + - the new volume is Ready as RAW on the pool and has its own LUN + """ + snap = self._take_volume_snapshot_when_accepted(self.__class__.volume.id) + clone = self._create_clone(snap.id) + clone_snap = self._take_volume_snapshot_when_accepted(clone.id) + self.assertEqual(clone_snap.state, "BackedUp", + "Snapshot of the clone is %s, expected BackedUp" % clone_snap.state) + + new = self._create_clone(clone_snap.id) + try: + self.assertEqual(self._db_volume_format(new.id), "RAW", + "New volume is not RAW in the volumes table") + self.assertTrue(self._clone_object_exists(new), + "ONTAP LUN for the volume from the clone's snapshot is missing") + finally: + self._remove_clone(new) + self._wait_clone_object_gone(new) + self._finish_volume_snapshot(clone_snap.id) + self._remove_clone(clone) + self._wait_clone_object_gone(clone) + self._finish_volume_snapshot(snap.id) + + @attr(tags=[TAG], required_hardware=True) + def test_17_reject_create_when_ontap_snapshot_missing(self): + """ + CloudStack lists a snapshot as BackedUp, but its FlexVol snapshot was + deleted directly on ONTAP. + Verifies: + - createVolume(snapshotid) fails + - no volume record is left behind and no LUN is added to the FlexVol + """ + before = self._ontap_snap_names() + snap = self._take_volume_snapshot_when_accepted(self.__class__.volume.id) + new = self._ontap_snap_names() - before + self.assertEqual(len(new), 1, "Expected one new FlexVol snapshot, found %s" % sorted(new)) + ontap_name = new.pop() + + self.assertTrue(self.ontap.delete_snapshot(self.__class__.pool.name, ontap_name), + "FlexVol snapshot %s not found to delete" % ontap_name) + self._wait_until_gone(lambda: ontap_name in self._ontap_snap_names(), + "FlexVol snapshot %s still present" % ontap_name) + + message = self._expect_clone_rejected(snap.id) + logger.info("test_17: create from a snapshot missing on ONTAP rejected: %s" % message) + + @attr(tags=[TAG], required_hardware=True) + def test_18_reject_create_on_disabled_pool(self): + """ + Disable the pool; createVolume from the snapshot is rejected. Enable the + pool again; the same snapshot now gives a Ready clone. + Verifies: + - no LUN is added to the FlexVol while the pool is Disabled + - after the pool is Up again, the clone is Ready as RAW with its own LUN + """ + pool = self.__class__.pool + snap = self._take_volume_snapshot_when_accepted(self.__class__.volume.id) + + self._set_pool_enabled(pool.id, False) + try: + self._expect_clone_rejected(snap.id) + finally: + self._set_pool_enabled(pool.id, True) + + clone = self._create_clone(snap.id) + try: + self.assertEqual(self._db_volume_format(clone.id), "RAW", + "Clone is not RAW in the volumes table") + self.assertTrue(self._clone_object_exists(clone), + "ONTAP LUN for the clone is missing") + finally: + self._remove_clone(clone) + self._wait_clone_object_gone(clone) + self._finish_volume_snapshot(snap.id) + + @attr(tags=[TAG], required_hardware=True) + def test_19_reject_nonexistent_snapshot(self): + """ + createVolume with a random snapshot UUID. + Verifies: + - the request is rejected as an unknown snapshotid + - no volume record is left behind and no LUN is added to the FlexVol + """ + message = self._expect_clone_rejected(str(uuid.uuid4())) + logger.info("test_19: createVolume from an unknown snapshot rejected: %s" % message) + self.assertIn("snapshotid", message.lower(), + "Rejection does not name snapshotid: %s" % message) + self.assertIn("does not exist", message.lower(), + "Rejection is not an unknown-snapshot error: %s" % message) + + @attr(tags=[TAG], required_hardware=True) + def test_20_reject_create_on_different_pool(self): + """ + Create a second iSCSI pool and disable the suite pool, so the second pool + is the only one the allocator can choose. createVolume ignores storageid + when snapshotid is given. The suite pool is enabled again and the second + pool removed at the end of the test. + Verifies: + - the request is rejected, because a snapshot can only be cloned on the + pool that holds it + - no usable volume record and no LUN in either pool's FlexVol + """ + pool_a = self.__class__.pool + snap = self._take_volume_snapshot_when_accepted(self.__class__.volume.id) + pool_b = self._create_pool() + try: + self._poll_pool_state(pool_b.id, "Up", timeout=120) + try: + self._set_pool_enabled(pool_a.id, False) + message = self._expect_clone_rejected(snap.id, pools=[pool_a, pool_b]) + logger.info("test_20: create on the other pool rejected: %s" % message) + finally: + self._set_pool_enabled(pool_a.id, True) + finally: + self._remove_pool(pool_b) + self._finish_volume_snapshot(snap.id) + + @attr(tags=[TAG], required_hardware=True) + def test_21_reject_create_with_missing_snapshot_metadata(self): + """ + For each snapshot_details row the clone needs: delete it, attempt the + create, then restore it. With every row restored, creation succeeds, so + each failure came from the missing row. The error text is not checked. + This test edits the management database directly; if the run dies between + a delete and its restore, the snapshot stays unusable. + Verifies: + - each attempt is rejected with no usable volume record and no LUN + - with every row restored, a volume is created from the snapshot + """ + snap = self._take_volume_snapshot_when_accepted(self.__class__.volume.id) + db = self.__class__.dbConnection + rows = db.execute("SELECT id FROM snapshots WHERE uuid = %s", params=(snap.id,)) + self.assertTrue(rows, "No snapshots row for uuid %s" % snap.id) + snap_db_id = rows[0][0] + + for key in REQUIRED_SNAPSHOT_DETAILS: + found = db.execute( + "SELECT id, value FROM snapshot_details WHERE snapshot_id = %s AND name = %s", + params=(snap_db_id, key)) + self.assertTrue(found, "snapshot_details '%s' missing before the test" % key) + detail_id, value = found[0][0], found[0][1] + + db.execute("DELETE FROM snapshot_details WHERE id = %s", params=(detail_id,)) + try: + message = self._expect_clone_rejected(snap.id) + logger.info("test_21: create without '%s' rejected: %s" % (key, message)) + finally: + db.execute( + "INSERT INTO snapshot_details (snapshot_id, name, value) " + "VALUES (%s, %s, %s)", params=(snap_db_id, key, value)) + + clone = self._create_clone(snap.id) + try: + self.assertTrue(self._clone_object_exists(clone), + "ONTAP LUN for the clone is missing after the metadata was restored") + finally: + self._remove_clone(clone) + self._wait_clone_object_gone(clone) + self._finish_volume_snapshot(snap.id) + + @attr(tags=[TAG], required_hardware=True) + def test_22_reject_duplicate_volume_name_from_snapshot(self): + """ + Create two volumes from one snapshot with the same volume name. The LUN + name is built from the volume name, so the second LUN would collide with + the first on ONTAP. + Verifies: + - the first volume is Ready and adds one new LUN + - the second create is rejected or ends in a failed state + - the failed create adds or removes no LUN, and the first volume stays Ready + """ + pool = self.__class__.pool + snap = self._take_volume_snapshot_when_accepted(self.__class__.volume.id) + name = "%s_dup_%d" % (self._vol_name_prefix, random.randint(0, 999999)) + + before = self._pool_objects_of(pool) + first = self._create_clone(snap.id, name=name) + self.assertEqual(len(self._pool_objects_of(pool) - before), 1, + "The first clone did not add exactly one LUN") + luns_before = self._pool_objects_of(pool) + + rejected, vol = self._attempt_clone(snap.id, name=name) + self.assertTrue(rejected, + "A second volume with the same name was created (%s)" + % (vol.id if vol else None)) + self.assertEqual(self._pool_objects_of(pool), luns_before, + "The failed duplicate create added or removed a LUN") + self.assertIsNotNone(self._poll_volume_field(first.id, "state", "Ready", timeout=120), + "The first volume is no longer Ready") + + self._remove_clone(first) + self._wait_clone_object_gone(first) + self._finish_volume_snapshot(snap.id) + + @attr(tags=[TAG], required_hardware=True) + def test_23_destroy_vm_and_cleanup(self): + """Destroy the VMs, delete the data volume and the pool.""" + self.step_27_destroy_vm_and_cleanup() diff --git a/test/integration/plugins/ontap/nfs3/instance/test_vm_volume_attach.py b/test/integration/plugins/ontap/nfs3/instance/test_vm_volume_attach.py index c3b7e36a7316..08d5f75db504 100644 --- a/test/integration/plugins/ontap/nfs3/instance/test_vm_volume_attach.py +++ b/test/integration/plugins/ontap/nfs3/instance/test_vm_volume_attach.py @@ -19,7 +19,7 @@ Sequential workflow integration tests for NetApp ONTAP data volume lifecycle with a running virtual machine. -Tests are numbered test_01 ... test_27, plus test_03a and test_03b, and must +Tests are numbered test_01 ... test_20, plus test_03a and test_03b, and must run in that order. Each step builds on the shared state established by the previous step. @@ -41,34 +41,24 @@ 07 Verify shrinking the volume is rejected without changing its size 08 Start the VM — VM Running; volume still attached; FlexVol online 09 Open an SSH port forward to the VM; write ROOT and DATA files - 10 Snapshot the ROOT volume of the running VM - 11 Snapshot the DATA volume of the running VM (kept for step 14) - 12 Revert a volume snapshot while the VM is Running — rejected - 13 ROOT volume revert: write before-snapshot, snapshot, write - after-snapshot, revert, file is back to before-snapshot - 14 DATA: snapshot again, revert to the step-11 snapshot then to this - one, then delete both while the VM is still running - 15 Write before-s1; VM snapshot of the running VM (kept for step 17) - 16 Write before-s2, stop, VM snapshot (kept for step 17) - 17 Revert to the step-15 snapshot, then to the step-16 snapshot, then + 10 Write before-s1; VM snapshot of the running VM (kept for step 12) + 11 Write before-s2, stop, VM snapshot (kept for step 12) + 12 Revert to the step-10 snapshot, then to the step-11 snapshot, then delete both while the VM is still running - 18 Two VM snapshot requests for the same VM at once — both succeed - 19 Deploy a second VM whose ROOT disk is on the same pool - 20 Revert VM-A's ROOT; VM-B's file is unchanged - 21 VM snapshots of both VMs at the same time - 22 Volume snapshot of VM-A while VM-B's ROOT reverts - 23 VM snapshot of VM-A while VM-B reverts to its VM snapshot - 24 Detach the ONTAP data volume from the VM - 25 Grow the detached data volume - 26 Expunge the second VM while it still has a VM snapshot - 27 Destroy VM (cache still survives); delete ONTAP volume; enter + 13 Two VM snapshot requests for the same VM at once — both succeed + 14 Deploy a second VM whose ROOT disk is on the same pool + 15 VM snapshots of both VMs at the same time + 16 VM snapshot of VM-A while VM-B reverts to its VM snapshot + 17 Detach the ONTAP data volume from the VM + 18 Grow the detached data volume + 19 Expunge the second VM while it still has a VM snapshot + 20 Destroy VM (cache still survives); delete ONTAP volume; enter maintenance; force-delete pool Snapshot steps only create and verify; tearDown deletes every snapshot the -step created and waits for its FlexVol snapshot to go. Step 11 keeps its -DATA snapshot so step 14 can revert to it and then delete both DATA -snapshots while the VM is running. Steps 15 and 16 keep their VM snapshots -so step 17 can revert to them and then delete both while the VM is running. +step created and waits for its FlexVol snapshot to go. Steps 10 and 11 keep +their VM snapshots so step 12 can revert to them and then delete both while +the VM is running. Guest login for the CentOS 5.5 template comes from ontap.cfg (cloudstack.templateUsername / templatePassword); see guest_ssh.py. @@ -87,115 +77,35 @@ Note: Tests share class-level state (sequential). Always run the full suite. """ -import base64 import logging import random import threading import time -import unittest from nose.plugins.attrib import attr from marvin.cloudstackAPI import ( - attachVolume as attachVolumeAPI, - createNetwork as createNetworkAPI, - createStoragePool as createStoragePoolAPI, - deleteNetwork as deleteNetworkAPI, - deleteVolume as deleteVolumeAPI, deployVirtualMachine as deployVirtualMachineAPI, destroyVirtualMachine as destroyVirtualMachineAPI, detachVolume as detachVolumeAPI, - enableStorageMaintenance, - listNetworkOfferings as listNetworkOfferingsAPI, - listNetworks as listNetworksAPI, - listVirtualMachines as listVirtualMachinesAPI, listVolumes as listVolumesAPI, stopVirtualMachine as stopVirtualMachineAPI, - updateStoragePool as updateStoragePoolAPI, ) -from marvin.lib.base import ServiceOffering, Snapshot, StoragePool, VmSnapshot, Volume -from marvin.lib.common import list_storage_pools +from marvin.lib.base import VmSnapshot -from guest_ssh import GuestSsh, guest_credentials, new_token, open_ssh_port -from ontap_test_base import OntapRestClient, OntapTestBase, _parse_pool_details, get_datacenter_config +from guest_ssh import new_token from helpers import template_cache_util as tcu -from helpers.template_cache_base import ( - find_ready_kvm_template, - tagged_compute_offering_data, - template_cache_capacity_bytes, - template_cache_tags, -) + +from helpers.snapshot_base import OntapSnapshotBase +from ontap_test_base import _is_rejected, _list_vols_cmd + logger = logging.getLogger("TestOntapVMVolumeAttach") TAG = "vm_volume_workflow" -# --------------------------------------------------------------------------- -# Test data -# --------------------------------------------------------------------------- - -class TestData: - account = "account" - ontap = "ontap" - primaryStorage = "primaryStorage" - provider = "provider" - scope = "scope" - tags = "tags" - - DETAIL_USERNAME = "username" - DETAIL_PASSWORD = "password" - DETAIL_SVM_NAME = "svmName" - DETAIL_PROTOCOL = "protocol" - DETAIL_STORAGE_IP = "storageIP" - - ONTAP_MIN_VOLUME_SIZE = 1677721600 - # Used when ontap.cfg has neither templateCacheCapacitybytes nor capacitybytes. - DEFAULT_POOL_SIZE = 50 * 1024 ** 3 - - def __init__(self, storage_ip, svm_name, username, password, - protocol="NFS3", scope="CLUSTER", provider="NetApp ONTAP", - tags="ontap-nfs3", capacitybytes=None): - if not capacitybytes: - capacitybytes = TestData.DEFAULT_POOL_SIZE - encoded_password = base64.b64encode(password.encode()).decode() - self.testdata = { - TestData.ontap: { - TestData.DETAIL_STORAGE_IP: storage_ip, - TestData.DETAIL_SVM_NAME: svm_name, - TestData.DETAIL_USERNAME: username, - TestData.DETAIL_PASSWORD: password, - }, - TestData.account: { - "email": "ontap-vm-vol@test.com", - "firstname": "ONTAP", - "lastname": "VMVol", - "username": "ontap_vm_vol_%d" % random.randint(0, 9999), - "password": "password", - }, - TestData.primaryStorage: { - "name": "OntapVMVol_%d" % random.randint(0, 9999), - TestData.scope: scope, - TestData.provider: provider, - TestData.tags: tags, - "capacitybytes": capacitybytes, - "managed": True, - "details": { - TestData.DETAIL_USERNAME: username, - TestData.DETAIL_PASSWORD: encoded_password, - TestData.DETAIL_SVM_NAME: svm_name, - TestData.DETAIL_PROTOCOL: protocol, - TestData.DETAIL_STORAGE_IP: storage_ip, - }, - }, - } - - -# --------------------------------------------------------------------------- -# Sequential workflow test class -# --------------------------------------------------------------------------- - -class TestOntapVMVolumeAttach(OntapTestBase): +class TestOntapVMVolumeAttach(OntapSnapshotBase): """ Tests ONTAP data volume lifecycle with a running CloudStack VM whose ROOT volume is on the ONTAP pool (primary template cache). @@ -205,351 +115,6 @@ class TestOntapVMVolumeAttach(OntapTestBase): PROTOCOL = "NFS3" - # ---- extra shared state beyond OntapTestBase ----------------------- - vm = None # running VirtualMachine - vm2 = None # second VM used only to verify template-cache reuse - template_id = None # KVM template ID discovered at setup - template_db_id = None # numeric vm_template.id (template_spool_ref key) - pool_db_id = None # numeric storage_pool.id (template_spool_ref key) - service_offering_id = None - network_id = None # None for Basic zones - _created_network_id = None # network created by this suite for Advanced zones - initial_volume_size = None - target_volume_size = None - volume_path = None - vm_ssh = None # (public_ip, public_port) forwarded to vm:22 - vm2_ssh = None - vm_snap_running = None # step 15 snapshot, reused by step 17 - vm_snap_stopped = None # step 16 snapshot, reused by step 17 - token_s1 = None - token_s2 = None - kept_ontap_snaps = None - data_snap_older = None # step 11 DATA snapshot, reused by step 14 - data_token_older = None - kept_data_ontap_snaps = None - guest_user = "root" - guest_password = "password" - - _vol_name_prefix = "OntapVMVol" - - # ---- setup --------------------------------------------------------- - - @classmethod - def setUpClass(cls): - super(TestOntapVMVolumeAttach, cls).setUpClass() - testclient = super( - TestOntapVMVolumeAttach, cls - ).getClsTestClient() - - cls.apiClient = testclient.getApiClient() - cls.dbConnection = testclient.getDbConnection() - config = get_datacenter_config(testclient, cls) - - ontap_cfg = config.get("ontap", {}) - pool_cfg = config.get("storagePool", {}) - storage_ip = ontap_cfg.get("storageIP", "") - svm_name = ontap_cfg.get("svmName", "") - username = ontap_cfg.get("username", "") - password = ontap_cfg.get("password", "") - nfs3_cfg = pool_cfg.get("protocols", {}).get("nfs3", {}) - if not nfs3_cfg.get("enabled", True): - raise unittest.SkipTest( - "NFS3 tests disabled in ontap.cfg " - "(set protocols.nfs3.enabled=true to enable)" - ) - protocol = "NFS3" - scope = pool_cfg.get("storagePoolScope", "CLUSTER") - provider = pool_cfg.get("storagePoolProvider", "NetApp ONTAP") - # Dedicated tag shared by the pool and the compute offering so the - # VM's ROOT volume is placed on this ONTAP pool (template cache path). - tags = template_cache_tags(nfs3_cfg, "nfs3") - capacitybytes = template_cache_capacity_bytes(pool_cfg) - - cls.testdata = TestData( - storage_ip, svm_name, username, password, - protocol=protocol, scope=scope, provider=provider, - tags=tags, capacitybytes=capacitybytes, - ).testdata - cls.ontap = OntapRestClient(storage_ip, username, password) - cls.svm_name = svm_name - - cls._setup_cloudstack_resources(config, cls.testdata[TestData.account]) - - cls.guest_user, cls.guest_password = guest_credentials(config) - - # Discover a suitable user KVM template in the zone (must be fully - # downloaded; system-type templates are excluded as they cannot be - # deployed as user VMs). - template = find_ready_kvm_template(cls.apiClient, cls.zone.id) - if template is not None: - cls.template_id = template.id - cls.template_db_id = tcu.get_db_id( - cls.dbConnection, "vm_template", cls.template_id - ) - else: - logger.warning( - "No ready user KVM template found in zone '%s'. " - "Tests that deploy VMs will be skipped until a template " - "finishes downloading." % cls.zone.name - ) - cls.template_id = None - - service_offering = ServiceOffering.create( - cls.apiClient, tagged_compute_offering_data(tags, "OntapNFS3VMSO") - ) - cls._cleanup.append(service_offering) - cls.service_offering_id = service_offering.id - - # Detect zone type; resolve network ID for Advanced zones - cls.network_id = None - zone_type = getattr(cls.zone, "networktype", "Basic") - if zone_type.lower() == "advanced": - # Find a network already accessible to the test account - net_cmd = listNetworksAPI.listNetworksCmd() - net_cmd.zoneid = cls.zone.id - net_cmd.account = cls.account.name - net_cmd.domainid = cls.domain.id - nets = cls.apiClient.listNetworks(net_cmd) or [] - if nets: - cls.network_id = nets[0].id - else: - # Create an Isolated guest network for the test account - no_cmd = listNetworkOfferingsAPI.listNetworkOfferingsCmd() - no_cmd.state = "Enabled" - no_cmd.guestiptype = "Isolated" - no_cmd.specifyvlan = "false" - no_offerings = cls.apiClient.listNetworkOfferings(no_cmd) or [] - snat_offering = next( - (o for o in no_offerings - if "SourceNat" in o.name and "Vpc" not in o.name - and "NSX" not in o.name and "Netris" not in o.name), - no_offerings[0] if no_offerings else None - ) - if snat_offering: - cn_cmd = createNetworkAPI.createNetworkCmd() - cn_cmd.zoneid = cls.zone.id - cn_cmd.networkofferingid = snat_offering.id - cn_cmd.name = "ontap-nfs3-vm-net-%d" % random.randint( - 0, 9999) - cn_cmd.displaytext = "ONTAP NFS3 VM test network" - cn_cmd.account = cls.account.name - cn_cmd.domainid = cls.domain.id - net = cls.apiClient.createNetwork(cn_cmd) - cls.network_id = net.id - cls._created_network_id = net.id - - @classmethod - def tearDownClass(cls): - """Destroy the VMs first, then delegate pool/volume cleanup to super.""" - cls._delete_kept_data_snapshot() - cls._delete_kept_vm_snapshots() - for vm in (cls.vm2, cls.vm): - if vm is None: - continue - try: - cls._stop_and_expunge_vm(vm.id) - except Exception as e: - logger.warning("tearDownClass: could not stop/destroy VM %s: " - "%s" % (vm.id, e)) - try: - dest_cmd = destroyVirtualMachineAPI.destroyVirtualMachineCmd() - dest_cmd.id = vm.id - dest_cmd.expunge = True - cls.apiClient.destroyVirtualMachine(dest_cmd) - except Exception as de: - logger.warning("tearDownClass: could not destroy VM %s: " - "%s" % (vm.id, de)) - cls.vm2 = None - cls.vm = None - - # Delete the guest network created for this account in Advanced zones. - if cls._created_network_id is not None: - try: - dn_cmd = deleteNetworkAPI.deleteNetworkCmd() - dn_cmd.id = cls._created_network_id - cls.apiClient.deleteNetwork(dn_cmd) - cls._created_network_id = None - except Exception as e: - logger.warning( - "tearDownClass: could not delete network %s: %s" - % (cls._created_network_id, e)) - - super(TestOntapVMVolumeAttach, cls).tearDownClass() - - @classmethod - def _stop_and_expunge_vm(cls, vm_id): - """Force-stop the VM if needed, then destroy it with expunge.""" - vms = cls.apiClient.listVirtualMachines(_list_vms_cmd(vm_id)) - current_state = vms[0].state if vms else "unknown" - if current_state.lower() not in ("stopped", "destroyed", - "expunging", "error"): - stop_cmd = stopVirtualMachineAPI.stopVirtualMachineCmd() - stop_cmd.id = vm_id - stop_cmd.forced = True - cls.apiClient.stopVirtualMachine(stop_cmd) - _wait_for_vm_state(cls.apiClient, vm_id, "Stopped", timeout=120) - dest_cmd = destroyVirtualMachineAPI.destroyVirtualMachineCmd() - dest_cmd.id = vm_id - dest_cmd.expunge = True - cls.apiClient.destroyVirtualMachine(dest_cmd) - - # ---- pool creation helper ----------------------------------------- - - def _create_pool(self): - ps = self.testdata[TestData.primaryStorage] - storage_ip = self.testdata[TestData.ontap][TestData.DETAIL_STORAGE_IP] - pool_name = "OntapVMVol_%d" % random.randint(0, 99999) - - cmd = createStoragePoolAPI.createStoragePoolCmd() - cmd.name = pool_name - cmd.url = "nfs://%s/ontap" % storage_ip - cmd.zoneid = self.zone.id - cmd.clusterid = self.cluster.id - cmd.podid = self.cluster.podid - cmd.scope = ps[TestData.scope] - cmd.provider = ps[TestData.provider] - cmd.tags = ps[TestData.tags] - cmd.capacitybytes = ps["capacitybytes"] - cmd.hypervisor = "KVM" - cmd.managed = True - - count = 1 - for key, value in ps["details"].items(): - setattr(cmd, "details[{}].{}".format(count, key), value) - count += 1 - - response = self.apiClient.createStoragePool(cmd) - return StoragePool(response.__dict__) - - # ---- VM state helpers ---------------------------------------------- - - def _volume_state(self, vol_id): - """Return the current CloudStack state string for a volume.""" - cmd = listVolumesAPI.listVolumesCmd() - cmd.id = vol_id - vols = self.apiClient.listVolumes(cmd) - return vols[0].state if vols else "unknown" - - # ---- snapshot step helpers (steps 09-23) --------------------------- - - def setUp(self): - super(TestOntapVMVolumeAttach, self).setUp() - self._volume_snapshot_ids = [] - self._vm_snapshot_ids = [] - self._extra_volume_ids = [] - self._created_ontap_snaps = set() - - def tearDown(self): - """ - Delete the snapshots and extra volumes a step created, then check - their FlexVol snapshots are gone from ONTAP. - """ - for snap_id in self._vm_snapshot_ids: - try: - VmSnapshot.deleteVMSnapshot(self.apiClient, snap_id) - except Exception as exc: - logger.warning("tearDown: VM snapshot %s: %s" % (snap_id, exc)) - self._delete_failed_vm_snapshots() - for snap_id in self._volume_snapshot_ids: - try: - Snapshot({"id": snap_id}).delete(self.apiClient) - except Exception as exc: - logger.warning("tearDown: volume snapshot %s: %s" % (snap_id, exc)) - for vol_id in self._extra_volume_ids: - try: - cmd = deleteVolumeAPI.deleteVolumeCmd() - cmd.id = vol_id - self.apiClient.deleteVolume(cmd) - except Exception as exc: - logger.warning("tearDown: volume %s: %s" % (vol_id, exc)) - if self._created_ontap_snaps and not self._wait_ontap_snaps_gone( - self._created_ontap_snaps, fail=False): - logger.warning("tearDown: FlexVol snapshots still present: %s" - % sorted(self._created_ontap_snaps)) - super(TestOntapVMVolumeAttach, self).tearDown() - - @classmethod - def _destroy_second_vm(cls): - if cls.vm2 is None: - return - try: - cmd = destroyVirtualMachineAPI.destroyVirtualMachineCmd() - cmd.id = cls.vm2.id - cmd.expunge = True - cls.apiClient.destroyVirtualMachine(cmd) - except Exception as exc: - logger.warning("Could not destroy second VM %s: %s" % (cls.vm2.id, exc)) - cls.vm2 = None - cls.vm2_ssh = None - - @classmethod - def _delete_kept_vm_snapshots(cls): - """Delete the step 15/16 snapshots when step 17 did not take them over.""" - for snap in (cls.vm_snap_running, cls.vm_snap_stopped): - if snap is None: - continue - try: - VmSnapshot.deleteVMSnapshot(cls.apiClient, snap.id) - except Exception as exc: - logger.warning("tearDownClass: VM snapshot %s: %s" % (snap.id, exc)) - cls.vm_snap_running = None - cls.vm_snap_stopped = None - cls.token_s1 = None - cls.token_s2 = None - cls.kept_ontap_snaps = set() - - @classmethod - def _delete_kept_data_snapshot(cls): - """Delete the step 11 DATA snapshot when step 14 did not take it over.""" - snap = cls.data_snap_older - if snap is None: - return - try: - Snapshot({"id": snap.id}).delete(cls.apiClient) - except Exception as exc: - logger.warning("tearDownClass: volume snapshot %s: %s" % (snap.id, exc)) - cls.data_snap_older = None - cls.data_token_older = None - cls.kept_data_ontap_snaps = set() - - def _keep_data_snapshot(self, snap, ontap_names, token): - """Leave the step 11 DATA snapshot in place for step 14.""" - if snap.id in self._volume_snapshot_ids: - self._volume_snapshot_ids.remove(snap.id) - names = set(ontap_names) - self._created_ontap_snaps -= names - self.__class__.data_snap_older = snap - self.__class__.data_token_older = token - self.__class__.kept_data_ontap_snaps = names - - def _adopt_kept_data_snapshot(self): - """Hand the step 11 DATA snapshot to step 14.""" - snap = self.__class__.data_snap_older - token = self.__class__.data_token_older - if snap is None or not token: - self.skipTest("DATA snapshot from test_11 is required") - ontap_names = set(self.__class__.kept_data_ontap_snaps or []) - self._volume_snapshot_ids.append(snap.id) - self._created_ontap_snaps |= ontap_names - self.__class__.data_snap_older = None - self.__class__.data_token_older = None - self.__class__.kept_data_ontap_snaps = set() - return snap, token, ontap_names - - def _delete_volume_snapshot_while_running(self, vm, snap, ontap_names, token): - """Delete a volume snapshot while its VM is still running.""" - Snapshot({"id": snap.id}).delete(self.apiClient) - if snap.id in self._volume_snapshot_ids: - self._volume_snapshot_ids.remove(snap.id) - names = set(ontap_names) - self._created_ontap_snaps -= names - self._wait_until_gone( - lambda: self._volume_snapshot_listed(snap.id), - "Volume snapshot %s still listed after delete" % snap.id) - self._wait_ontap_snaps_gone(names) - self.assertEqual(self._vm_state(vm.id), "Running") - self._assert_marker(token, disk="DATA", msg="after volume snapshot delete") - def _delete_vm_snapshot_while_running(self, vm, snap, ontap_names, token): """Delete a VM snapshot while that VM is still running.""" VmSnapshot.deleteVMSnapshot(self.apiClient, snap.id) @@ -572,7 +137,7 @@ def _ontap_names_for_snap(self, names, snap, kind): return {name for name in names if str(name).endswith(suffix)} def _keep_vm_snapshot(self, snap, ontap_names, which): - """Leave this VM snapshot in place for step 17.""" + """Leave this VM snapshot in place for step 12.""" if snap.id in self._vm_snapshot_ids: self._vm_snapshot_ids.remove(snap.id) names = set(ontap_names) @@ -585,13 +150,13 @@ def _keep_vm_snapshot(self, snap, ontap_names, which): setattr(self.__class__, which, snap) def _adopt_kept_vm_snapshots(self): - """Hand the step 15 and 16 snapshots to this step's tearDown.""" + """Hand the step 10 and 11 snapshots to this step's tearDown.""" s1 = self.__class__.vm_snap_running s2 = self.__class__.vm_snap_stopped token_a = self.__class__.token_s1 token_b = self.__class__.token_s2 if s1 is None or s2 is None or not token_a or not token_b: - self.skipTest("VM snapshots from test_15 and test_16 are required") + self.skipTest("VM snapshots from test_10 and test_11 are required") ontap_names = set(self.__class__.kept_ontap_snaps or []) self._vm_snapshot_ids.extend([s1.id, s2.id]) self._created_ontap_snaps |= ontap_names @@ -602,184 +167,6 @@ def _adopt_kept_vm_snapshots(self): self.__class__.kept_ontap_snaps = set() return s1, s2, token_a, token_b, ontap_names - def _require_snapshot_vm(self, ssh=True): - if self.__class__.vm is None: - self.skipTest("VM not deployed — test_03 was skipped (no ready template)") - if ssh and self.__class__.vm_ssh is None: - self.skipTest("Guest SSH not set up — test_09 must pass first") - self._start_vm(self.__class__.vm.id) - return self.__class__.vm - - def _require_second_vm(self): - self._require_snapshot_vm() - if self.__class__.vm2 is None or self.__class__.vm2_ssh is None: - self.skipTest("Second VM not deployed — test_19 must pass first") - self._start_vm(self.__class__.vm2.id) - return self.__class__.vm2 - - def _vm_state(self, vm_id): - vms = self.apiClient.listVirtualMachines(_list_vms_cmd(vm_id)) - return vms[0].state if vms else None - - def _stop_vm(self, vm_id): - if (self._vm_state(vm_id) or "").lower() == "stopped": - return - cmd = stopVirtualMachineAPI.stopVirtualMachineCmd() - cmd.id = vm_id - cmd.forced = True - self.apiClient.stopVirtualMachine(cmd) - self._poll_vm_state(vm_id, "Stopped", timeout=600) - - def _root_volume(self, vm_id): - cmd = listVolumesAPI.listVolumesCmd() - cmd.virtualmachineid = vm_id - cmd.type = "ROOT" - cmd.listall = True - vols = self.apiClient.listVolumes(cmd) or [] - self.assertTrue(vols, "No ROOT volume found for VM %s" % vm_id) - return vols[0] - - def _guest(self, which="vm"): - host, port = getattr(self.__class__, "%s_ssh" % which) - return GuestSsh(host, port, self.guest_user, self.guest_password) - - def _write_marker(self, token, which="vm", disks=("ROOT",)): - with self._guest(which) as guest: - if "ROOT" in disks: - guest.write_root_marker(token) - if "DATA" in disks: - guest.write_data_marker(token) - - def _assert_marker(self, token, which="vm", disk="ROOT", msg=""): - with self._guest(which) as guest: - found = guest.read_data_marker() if disk == "DATA" else guest.read_root_marker() - self.assertEqual(found, token, "%s: %s marker on %s is %r, expected %r" - % (msg, disk, which, found, token)) - - def _ontap_snap_names(self): - return {s.get("name") for s in self.ontap.list_snapshots(self.__class__.pool.name)} - - def _assert_new_ontap_snaps(self, before, snaps, kind, msg): - """Return the FlexVol snapshot created for each CloudStack snapshot. - - A volume snapshot is stored as ``..._cs`` and a VM snapshot as - ``..._vm``. ONTAP snapshots from its own schedule, such as - ``hourly.*`` or ``Anti_ransomware_*``, are ignored. - """ - new = self._ontap_snap_names() - before - prefix = "cs" if kind == "volume" else "vm" - table = "snapshots" if kind == "volume" else "vm_snapshots" - matched = set() - missing = [] - for snap in snaps: - db_id = tcu.get_db_id(self.dbConnection, table, snap.id) - suffix = "_%s%s" % (prefix, db_id) - hits = sorted(name for name in new if name.endswith(suffix)) - if len(hits) != 1: - missing.append("%s (suffix %s, matches %s)" % (snap.id, suffix, hits)) - else: - matched.add(hits[0]) - self.assertFalse( - missing, - "%s: FlexVol snapshot missing for %s; new FlexVol snapshots: %s" - % (msg, missing, sorted(new))) - ignored = new - matched - if ignored: - logger.info("%s: ignoring FlexVol snapshots not created by this step: %s", - msg, sorted(ignored)) - self._created_ontap_snaps |= matched - return matched - - def _assert_ontap_snaps_present(self, names, msg): - missing = set(names) - self._ontap_snap_names() - self.assertFalse(missing, "%s: FlexVol snapshots missing: %s" % (msg, sorted(missing))) - - def _wait_ontap_snaps_gone(self, names, timeout=180, fail=True): - names = set(names) - deadline = time.time() + timeout - left = names - while time.time() < deadline: - left = names & self._ontap_snap_names() - if not left: - return True - time.sleep(5) - if fail: - self.fail("FlexVol snapshots %s still present after %ds" % (sorted(left), timeout)) - return False - - def _take_volume_snapshot(self, volume_id): - snap = Snapshot.create(self.apiClient, volume_id, - account=self.account.name, domainid=self.domain.id) - self._volume_snapshot_ids.append(snap.id) - self.assertEqual(snap.state, "BackedUp", - "Volume snapshot %s is %s, expected BackedUp" % (snap.id, snap.state)) - return snap - - def _take_vm_snapshot(self, vm_id): - snap = VmSnapshot.create(self.apiClient, vm_id, snapshotmemory="false", - name="ontap_%d" % random.randint(0, 999999)) - self._vm_snapshot_ids.append(snap.id) - self.assertEqual(snap.state, "Ready", - "VM snapshot %s is %s, expected Ready" % (snap.id, snap.state)) - return snap - - def _vm_snapshots_of(self, vm_id): - return VmSnapshot.list(self.apiClient, virtualmachineid=vm_id, listall=True) or [] - - def _delete_failed_vm_snapshots(self): - """Delete VM snapshots left in Error by a rejected create. - - A rejected createVMSnapshot (ONTAP refusing while a revert's clones - exist) leaves its record behind with no id the test ever saw. Any - Instance Snapshot, even in Error, blocks detach, resize and destroy. - """ - for vm in (self.__class__.vm, self.__class__.vm2): - if vm is None: - continue - try: - stale = [s for s in self._vm_snapshots_of(vm.id) - if (getattr(s, "state", "") or "").lower() == "error"] - except Exception as exc: - logger.warning("tearDown: could not list VM snapshots of %s: %s" - % (vm.id, exc)) - continue - for snap in stale: - try: - VmSnapshot.deleteVMSnapshot(self.apiClient, snap.id) - except Exception as exc: - logger.warning("tearDown: failed VM snapshot %s: %s" - % (snap.id, exc)) - - def _volume_snapshot_listed(self, snap_id): - listed = Snapshot.list(self.apiClient, id=snap_id, listall=True) or [] - return any(getattr(item, "id", None) == snap_id for item in listed) - - def _wait_until_gone(self, still_there, msg, timeout=180): - deadline = time.time() + timeout - while time.time() < deadline and still_there(): - time.sleep(5) - self.assertFalse(still_there(), msg) - - def _volume_revert_flow(self, disk): - """Write A, snapshot, write B, stop, revert, start; expect A.""" - vm = self._require_snapshot_vm() - volume_id = (self.__class__.volume.id if disk == "DATA" - else self._root_volume(vm.id).id) - token_a = new_token("before-volume-snapshot") - token_b = new_token("after-volume-snapshot") - self._write_marker(token_a, disks=(disk,)) - before = self._ontap_snap_names() - snap = self._take_volume_snapshot(volume_id) - new = self._assert_new_ontap_snaps(before, [snap], "volume", "%s volume snapshot" % disk) - self._write_marker(token_b, disks=(disk,)) - - self._stop_vm(vm.id) - Volume.revertToSnapshot(self.apiClient, snap.id) - self._assert_ontap_snaps_present(new, "after revert") - self._start_vm(vm.id) - self._assert_marker(token_a, disk=disk, - msg="after revert (write after snapshot was %s)" % token_b) - # ================================================================== # Test steps # ================================================================== @@ -796,27 +183,7 @@ def test_01_create_nfs3_pool(self): - Pool reaches 'Up' state in CloudStack - ONTAP: FlexVol is created and online """ - pool = self._create_pool() - self.__class__.pool = pool - self.__class__.pool_db_id = tcu.get_db_id( - self.dbConnection, "storage_pool", pool.id - ) - - self.assertEqual( - pool.state, "Up", - "Pool state should be 'Up', got '%s'" % pool.state - ) - - ontap_vol = self.ontap.get_volume(pool.name) - self.assertIsNotNone( - ontap_vol, - "ONTAP FlexVol not created for pool '%s'" % pool.name - ) - self.assertEqual( - ontap_vol.get("state"), "online", - "ONTAP FlexVol should be 'online', got '%s'" - % ontap_vol.get("state") - ) + self.step_01_create_pool() # ------------------------------------------------------------------ # Step 02 - Create CloudStack data volume on ONTAP pool @@ -830,29 +197,7 @@ def test_02_create_ontap_data_volume(self): - Volume is created and in 'Allocated' or 'Ready' state - ONTAP: FlexVol remains online """ - self.assertIsNotNone(self.__class__.pool, - "Pool absent — test_01 must pass first") - - pool = self.__class__.pool - vol = self._create_volume(pool.id) - self.__class__.volume = vol - self.assertIsNotNone(vol, "createVolume returned None") - - vol_state = self._volume_state(vol.id) - self.assertIn( - vol_state.lower(), ("allocated", "ready"), - "Volume should be 'Allocated' or 'Ready', got '%s'" % vol_state - ) - - ontap_vol = self.ontap.get_volume(pool.name) - self.assertIsNotNone( - ontap_vol, - "ONTAP FlexVol disappeared after data volume creation" - ) - self.assertEqual( - ontap_vol.get("state"), "online", - "ONTAP FlexVol should still be 'online' after volume creation" - ) + self.step_02_create_ontap_data_volume() # ------------------------------------------------------------------ # Step 03 - Deploy a VM @@ -869,39 +214,7 @@ def test_03_deploy_vm(self): - template_spool_ref for pool + template is Ready / DOWNLOADED - ONTAP: template cache file exists at the spool install_path """ - self.assertIsNotNone(self.__class__.pool, - "Pool absent — test_01 must pass first") - if self.__class__.template_id is None: - self.skipTest( - "No ready user KVM template available — " - "waiting for template download to complete" - ) - self.assertIsNotNone(self.__class__.service_offering_id, - "No service offering available — check setup") - - cmd = deployVirtualMachineAPI.deployVirtualMachineCmd() - cmd.zoneid = self.zone.id - cmd.templateid = self.__class__.template_id - cmd.serviceofferingid = self.__class__.service_offering_id - cmd.account = self.account.name - cmd.domainid = self.domain.id - if self.__class__.network_id: - cmd.networkids = self.__class__.network_id - - vm = self._deploy_vm(cmd) - self.assertIsNotNone(vm, "deployVirtualMachine returned None") - self.__class__.vm = vm - - vm_obj = self._poll_vm_state(vm.id, "Running") - self.assertEqual( - vm_obj.state, "Running", - "VM should be 'Running', got '%s'" % vm_obj.state - ) - - pool = self.__class__.pool - self._assert_root_on_pool(vm.id, pool) - spool = self._wait_for_ready_spool_ref(self.__class__.pool_db_id) - self._assert_cache_on_ontap(pool, spool) + self.step_03_deploy_vm() # ------------------------------------------------------------------ # Step 03a - Deploy a second VM — reuses the template cache @@ -977,78 +290,7 @@ def test_04_attach_volume_to_vm(self): - ONTAP: NFS3 volume data file created in FlexVol after attach (lazy creation) - VM remains 'Running' """ - if self.__class__.vm is None: - self.skipTest("VM not deployed — test_03 was skipped (no ready template)") - self.assertIsNotNone(self.__class__.volume, - "Volume absent — test_02 must pass first") - - vm = self.__class__.vm - vol = self.__class__.volume - - cmd = attachVolumeAPI.attachVolumeCmd() - cmd.id = vol.id - cmd.virtualmachineid = vm.id - attached = self.apiClient.attachVolume(cmd) - self.assertIsNotNone(attached, "attachVolume returned None") - - # On ONTAP/NFS shared storage CloudStack does not transition the volume - # state to 'In Use' — attachment is indicated by virtualmachineid being - # set on the volume record. Poll on that field instead of state. - deadline = time.time() + 120 - vol_vmid = None - while time.time() < deadline: - vols = self.apiClient.listVolumes(_list_vols_cmd(vol.id)) - vol_vmid = getattr(vols[0], "virtualmachineid", None) if vols else None - if vol_vmid: - break - time.sleep(5) - - self.assertEqual( - vol_vmid, vm.id, - "Volume should be attached to VM %s after attach, " - "got virtualmachineid=%s" % (vm.id, vol_vmid) - ) - - # VM must still be Running - vm_obj = self._poll_vm_state(vm.id, "Running", timeout=30) - self.assertEqual(vm_obj.state, "Running", - "VM should still be 'Running' after volume attach") - - # ONTAP FlexVol must remain online - pool = self.__class__.pool - ontap_vol = self.ontap.get_volume(pool.name) - self.assertIsNotNone(ontap_vol, "ONTAP FlexVol not found after attach") - self.assertEqual( - ontap_vol.get("state"), "online", - "ONTAP FlexVol should be 'online' after attach" - ) - - # ONTAP: NFS3 uses lazy file creation — the volume data file is - # materialised on the FlexVol only when CloudStack calls createAsync - # during attachVolume. Verify that the file now exists. - files = self.ontap.list_files_in_volume(pool.name) - vol_file = next((f for f in files if vol.id in f), None) - self.assertIsNotNone( - vol_file, - "No data file matching volume UUID '%s' found in FlexVol '%s' " - "after attach; files present: %s" % (vol.id, pool.name, files) - ) - - volumes = self.apiClient.listVolumes(_list_vols_cmd(vol.id)) or [] - self.assertTrue(volumes, "Attached volume is not listed in CloudStack") - initial_size = int(volumes[0].size) - self.__class__.initial_volume_size = initial_size - self.__class__.target_volume_size = ( - (initial_size // (1024 ** 3)) + 1 - ) * (1024 ** 3) - self.__class__.volume_path = vol_file - - backend_size = self._get_qcow2_virtual_size(pool.id, vol_file) - self.assertEqual( - backend_size, initial_size, - "Initial qcow2 virtual size should match the CloudStack volume size" - ) - + self.step_04_attach_volume_to_vm() # ------------------------------------------------------------------ # Step 05 - Stop VM — export policy must be retained @@ -1269,7 +511,6 @@ def test_08_start_vm_volume_accessible(self): self.__class__.target_volume_size, "KVM data-disk capacity does not reflect the NFS3 resize") - # ------------------------------------------------------------------ # Step 09 - Guest SSH access for snapshot checks # ------------------------------------------------------------------ @@ -1284,136 +525,17 @@ def test_09_open_ssh_and_write_root_data_files(self): through a port forward on the network's source-NAT IP - The DATA disk can be formatted, mounted and written """ - vm = self._require_snapshot_vm(ssh=False) - if not self.__class__.network_id: - self.skipTest("Snapshot steps need an Advanced zone guest network for SSH") - pool_id = self.__class__.pool.id - root = self._root_volume(vm.id) - self.assertEqual(getattr(root, "storageid", None), pool_id, - "ROOT volume is on '%s', not the ONTAP test pool" - % getattr(root, "storage", None)) - vols = self.apiClient.listVolumes(_list_vols_cmd(self.__class__.volume.id)) or [] - self.assertTrue(vols and getattr(vols[0], "virtualmachineid", None) == vm.id, - "DATA volume must be attached before the snapshot steps") - - host, port, _ = open_ssh_port(self.apiClient, vm.id, self.__class__.network_id) - self.__class__.vm_ssh = (host, port) - token = new_token("ssh-access-test") - self._write_marker(token, disks=("ROOT", "DATA")) - self._assert_marker(token, disk="ROOT", msg="guest access") - self._assert_marker(token, disk="DATA", msg="guest access") - - # ------------------------------------------------------------------ - # Steps 08-12 - Volume snapshots - # ------------------------------------------------------------------ - - @attr(tags=[TAG], required_hardware=True) - def test_10_root_volume_snapshot_create(self): - """ - VS-01: snapshot the ROOT volume of the running VM. - Verifies: state BackedUp; VM stays Running; one new FlexVol snapshot. - """ - vm = self._require_snapshot_vm() - before = self._ontap_snap_names() - snap = self._take_volume_snapshot(self._root_volume(vm.id).id) - self.assertEqual(self._vm_state(vm.id), "Running") - self._assert_new_ontap_snaps(before, [snap], "volume", "ROOT volume snapshot") - - @attr(tags=[TAG], required_hardware=True) - def test_11_data_volume_snapshot_create(self): - """ - VS-03: snapshot the attached DATA volume. - The snapshot is kept for step 14. - Verifies: state BackedUp; VM stays Running; one new FlexVol snapshot. - """ - vm = self._require_snapshot_vm() - token = new_token("data-s1") - self._write_marker(token, disks=("DATA",)) - before = self._ontap_snap_names() - snap = self._take_volume_snapshot(self.__class__.volume.id) - self.assertEqual(self._vm_state(vm.id), "Running") - new = self._assert_new_ontap_snaps(before, [snap], "volume", "DATA volume snapshot") - self._keep_data_snapshot(snap, new, token) - - @attr(tags=[TAG], required_hardware=True) - def test_12_volume_revert_running_vm_rejected(self): - """ - VS-19: reverting a volume snapshot while the VM is Running fails. - Verifies: error says the Instance is not shut down; VM stays Running; - the FlexVol snapshot remains. - """ - vm = self._require_snapshot_vm() - before = self._ontap_snap_names() - snap = self._take_volume_snapshot(self._root_volume(vm.id).id) - new = self._assert_new_ontap_snaps(before, [snap], "volume", "ROOT volume snapshot") - with self.assertRaises(Exception) as ctx: - Volume.revertToSnapshot(self.apiClient, snap.id) - self.assertIn("shutdown", str(ctx.exception).lower(), - "Unexpected error: %s" % ctx.exception) - self.assertEqual(self._vm_state(vm.id), "Running") - self._assert_ontap_snaps_present(new, "after rejected revert") - - @attr(tags=[TAG], required_hardware=True) - def test_13_root_volume_revert(self): - """ - VS-11: write A, snapshot ROOT, write B, stop, revert, start. - Verifies: ROOT marker is A; the FlexVol snapshot survives the revert. - """ - self._volume_revert_flow("ROOT") - - @attr(tags=[TAG], required_hardware=True) - def test_14_data_volume_revert(self): - """ - Take a second DATA snapshot, revert to the step 11 snapshot, then to - this later one, and delete both while the VM is still running. - Verifies: - - After revert to the older snapshot, the DATA marker is the step 11 - token and the later snapshot is still listed - - After revert to the later snapshot, the DATA marker is that token - - Both snapshots and their FlexVol snapshots are gone; the VM stays - Running and the later marker is unchanged - """ - vm = self._require_snapshot_vm() - older, token_older, ontap_older = self._adopt_kept_data_snapshot() - token_latest = new_token("data-s2") - self._write_marker(token_latest, disks=("DATA",)) - before = self._ontap_snap_names() - latest = self._take_volume_snapshot(self.__class__.volume.id) - ontap_latest = self._assert_new_ontap_snaps( - before, [latest], "volume", "latest DATA snapshot") - self._write_marker(new_token("data-after-both"), disks=("DATA",)) - - self._stop_vm(vm.id) - Volume.revertToSnapshot(self.apiClient, older.id) - self._start_vm(vm.id) - self._assert_marker(token_older, disk="DATA", - msg="after revert to the older snapshot") - self.assertTrue( - self._volume_snapshot_listed(latest.id), - "The later volume snapshot should still exist") - self._assert_ontap_snaps_present( - ontap_older | ontap_latest, "after revert to the older snapshot") - - self._stop_vm(vm.id) - Volume.revertToSnapshot(self.apiClient, latest.id) - self._start_vm(vm.id) - self._assert_marker(token_latest, disk="DATA", - msg="after revert to the latest snapshot") - - self._delete_volume_snapshot_while_running( - vm, latest, ontap_latest, token_latest) - self._delete_volume_snapshot_while_running( - vm, older, ontap_older, token_latest) + self.step_09_open_ssh_and_write_root_data_files() # ------------------------------------------------------------------ - # Steps 13-16 - VM snapshots + # Steps 10-13 - VM snapshots # ------------------------------------------------------------------ @attr(tags=[TAG], required_hardware=True) - def test_15_vm_snapshot_create_running(self): + def test_10_vm_snapshot_create_running(self): """ VMS-01: VM snapshot of the running VM (ROOT + DATA on one FlexVol). - Writes before-s1, then snapshots. The snapshot is kept for step 17. + Writes before-s1, then snapshots. The snapshot is kept for step 12. Verifies: state Ready; VM stays Running; one new FlexVol snapshot. """ vm = self._require_snapshot_vm() @@ -1426,11 +548,11 @@ def test_15_vm_snapshot_create_running(self): self._keep_vm_snapshot(snap, new, "vm_snap_running") @attr(tags=[TAG], required_hardware=True) - def test_16_vm_snapshot_create_stopped(self): + def test_11_vm_snapshot_create_stopped(self): """ VMS-03: VM snapshot of the stopped VM. Writes before-s2 while Running, then stops and snapshots. - The snapshot is kept for step 17. + The snapshot is kept for step 12. Verifies: state Ready; VM stays Stopped; one new FlexVol snapshot. """ vm = self._require_snapshot_vm() @@ -1444,10 +566,10 @@ def test_16_vm_snapshot_create_stopped(self): self._keep_vm_snapshot(snap, new, "vm_snap_stopped") @attr(tags=[TAG], required_hardware=True) - def test_17_vm_snapshot_s1_running_s2_stopped_revert(self): + def test_12_vm_snapshot_s1_running_s2_stopped_revert(self): """ VMS-09 (NFS ROOT + NFS DATA on the same pool): revert to the running - snapshot from step 15, then to the stopped snapshot from step 16. + snapshot from step 10, then to the stopped snapshot from step 11. Verifies: - After revert to S1: ROOT and DATA hold before-s1 - After revert to S2: ROOT and DATA hold before-s2 @@ -1481,7 +603,7 @@ def test_17_vm_snapshot_s1_running_s2_stopped_revert(self): vm, s2, self._ontap_names_for_snap(ontap_names, s2, "vm"), token_b) @attr(tags=[TAG], required_hardware=True) - def test_18_vm_snapshot_duplicate_requests(self): + def test_13_vm_snapshot_duplicate_requests(self): """ VMS-53: two VM snapshot requests for the same VM at the same time. A rejected request is retried on its own; one that already succeeded @@ -1531,61 +653,19 @@ def test_18_vm_snapshot_duplicate_requests(self): self._assert_new_ontap_snaps(before, ok, "vm", "duplicate VM snapshot requests") # ------------------------------------------------------------------ - # Steps 17-21 - Second VM on the same pool: isolation and concurrency + # Steps 14-16 - Second VM on the same pool: isolation and concurrency # ------------------------------------------------------------------ @attr(tags=[TAG], required_hardware=True) - def test_19_deploy_second_vm(self): + def test_14_deploy_second_vm(self): """ Deploy a second VM whose ROOT disk is on the same ONTAP pool. Verifies: VM Running; ROOT on the test pool; SSH works. """ - self._require_snapshot_vm() - cmd = deployVirtualMachineAPI.deployVirtualMachineCmd() - cmd.zoneid = self.zone.id - cmd.templateid = self.__class__.template_id - cmd.serviceofferingid = self.__class__.service_offering_id - cmd.account = self.account.name - cmd.domainid = self.domain.id - cmd.networkids = self.__class__.network_id - vm2 = self.apiClient.deployVirtualMachine(cmd) - self.__class__.vm2 = vm2 - self._poll_vm_state(vm2.id, "Running", timeout=900) - root = self._root_volume(vm2.id) - self.assertEqual(getattr(root, "storageid", None), self.__class__.pool.id, - "Second VM ROOT is not on the ONTAP test pool") - host, port, _ = open_ssh_port(self.apiClient, vm2.id, self.__class__.network_id) - self.__class__.vm2_ssh = (host, port) - token = new_token("second-vm-ssh-access-test") - self._write_marker(token, which="vm2") - self._assert_marker(token, which="vm2", msg="second VM access") - - @attr(tags=[TAG], required_hardware=True) - def test_20_volume_revert_leaves_other_vm_untouched(self): - """ - VS-28: two VMs on one FlexVol; revert VM-A's ROOT to its snapshot. - Verifies: VM-A is back at its snapshot; VM-B keeps data written after it. - """ - vm = self._require_snapshot_vm() - self._require_second_vm() - a1 = new_token("vm-a-before-snapshot") - a2 = new_token("vm-a-after-snapshot") - b1 = new_token("vm-b-before-snapshot") - b2 = new_token("vm-b-after-snapshot") - self._write_marker(a1) - self._write_marker(b1, which="vm2") - snap = self._take_volume_snapshot(self._root_volume(vm.id).id) - self._write_marker(a2) - self._write_marker(b2, which="vm2") - - self._stop_vm(vm.id) - Volume.revertToSnapshot(self.apiClient, snap.id) - self._start_vm(vm.id) - self._assert_marker(a1, msg="VM-A after revert") - self._assert_marker(b2, which="vm2", msg="VM-B after VM-A's revert") + self.step_19_deploy_second_vm() @attr(tags=[TAG], required_hardware=True) - def test_21_concurrent_vm_snapshots_two_vms(self): + def test_15_concurrent_vm_snapshots_two_vms(self): """ VMS-54: VM snapshots on two VMs of the same NFS pool at the same time. Verifies: both Ready and owned by their VMs; two distinct new FlexVol @@ -1611,41 +691,7 @@ def test_21_concurrent_vm_snapshots_two_vms(self): self._assert_new_ontap_snaps(before, [snap_a, snap_b], "vm", "concurrent VM snapshots") @attr(tags=[TAG], required_hardware=True) - def test_22_concurrent_volume_snapshot_and_revert(self): - """ - Volume snapshot of VM-A's ROOT while VM-B's ROOT reverts, at the same time. - A rejected snapshot or revert is retried on its own. - Verifies: VM-A snapshot BackedUp with its own FlexVol snapshot; VM-B is - back at its snapshot; VM-A data unchanged. - """ - vm = self._require_snapshot_vm() - vm2 = self._require_second_vm() - a1 = new_token("vm-a-current-data") - b1 = new_token("vm-b-before-snapshot") - b2 = new_token("vm-b-after-snapshot") - self._write_marker(a1) - self._write_marker(b1, which="vm2") - snap_b = self._take_volume_snapshot(self._root_volume(vm2.id).id) - self._write_marker(b2, which="vm2") - self._stop_vm(vm2.id) - before = self._ontap_snap_names() - root_a = self._root_volume(vm.id).id - - snap_a = _snapshot_and_revert_with_retry( - lambda: Snapshot.create(self.apiClient, root_a, - account=self.account.name, domainid=self.domain.id), - lambda: Volume.revertToSnapshot(self.apiClient, snap_b.id), - ) - self._volume_snapshot_ids.append(snap_a.id) - self.assertEqual(snap_a.state, "BackedUp") - self._assert_new_ontap_snaps(before, [snap_a], "volume", "VM-A snapshot during VM-B revert") - - self._start_vm(vm2.id) - self._assert_marker(b1, which="vm2", msg="VM-B after revert") - self._assert_marker(a1, msg="VM-A during VM-B revert") - - @attr(tags=[TAG], required_hardware=True) - def test_23_concurrent_vm_snapshot_and_revert(self): + def test_16_concurrent_vm_snapshot_and_revert(self): """ VM snapshot of VM-A while VM-B reverts to its VM snapshot, at the same time. A rejected snapshot or revert is retried on its own. @@ -1678,11 +724,11 @@ def test_23_concurrent_vm_snapshot_and_revert(self): self._assert_marker(a1, msg="VM-A during VM-B revert") # ------------------------------------------------------------------ - # Step 24 - Detach ONTAP data volume from the VM + # Step 17 - Detach ONTAP data volume from the VM # ------------------------------------------------------------------ @attr(tags=["vm_volume_workflow"], required_hardware=True) - def test_24_detach_volume_from_vm(self): + def test_17_detach_volume_from_vm(self): """ Detach the ONTAP data volume from the running VM. Verifies: @@ -1767,11 +813,11 @@ def test_24_detach_volume_from_vm(self): # ------------------------------------------------------------------ # ------------------------------------------------------------------ - # Step 25 - Grow detached data volume + # Step 18 - Grow detached data volume # ------------------------------------------------------------------ @attr(tags=["vm_volume_workflow"], required_hardware=True) - def test_25_grow_detached_volume(self): + def test_18_grow_detached_volume(self): """Grow the materialized qcow2 after it has been detached.""" self.assertIsNotNone(self.__class__.volume, "Volume absent — test_02 must pass first") @@ -1792,11 +838,11 @@ def test_25_grow_detached_volume(self): self.__class__.target_volume_size = detached_target # ------------------------------------------------------------------ - # Step 26 - Destroy the second VM while it still has a VM snapshot + # Step 19 - Destroy the second VM while it still has a VM snapshot # ------------------------------------------------------------------ @attr(tags=["vm_volume_workflow"], required_hardware=True) - def test_26_destroy_vm_with_vm_snapshot(self): + def test_19_destroy_vm_with_vm_snapshot(self): """ VMS-38: destroy (expunge) the second VM while it still has a VM snapshot. Verifies: destroy succeeds; the VM snapshot is no longer listed; its @@ -1824,11 +870,11 @@ def test_26_destroy_vm_with_vm_snapshot(self): self._wait_ontap_snaps_gone(new) # ------------------------------------------------------------------ - # Step 27 - Destroy VM, delete volume, delete pool + # Step 20 - Destroy VM, delete volume, delete pool # ------------------------------------------------------------------ @attr(tags=["vm_volume_workflow"], required_hardware=True) - def test_27_destroy_vm_and_cleanup(self): + def test_20_destroy_vm_and_cleanup(self): """ Destroy the VM, delete the ONTAP data volume, enter maintenance, then force-delete the pool. @@ -1842,106 +888,7 @@ def test_27_destroy_vm_and_cleanup(self): - ONTAP: FlexVol is deleted after pool removal - ONTAP: Export policy is removed after pool removal """ - self.assertIsNotNone(self.__class__.pool, - "Pool absent — test_01 must pass first") - - self._destroy_second_vm() - vm = self.__class__.vm - vol = self.__class__.volume - pool = self.__class__.pool - pool_name = pool.name - - # Stop VM if still running - if vm is not None: - vms = self.apiClient.listVirtualMachines(_list_vms_cmd(vm.id)) - current_state = vms[0].state.lower() if vms else "unknown" - if current_state not in ("stopped", "destroyed", - "expunging", "error"): - stop_cmd = stopVirtualMachineAPI.stopVirtualMachineCmd() - stop_cmd.id = vm.id - self.apiClient.stopVirtualMachine(stop_cmd) - self._poll_vm_state(vm.id, "Stopped", timeout=300) - - dest_cmd = destroyVirtualMachineAPI.destroyVirtualMachineCmd() - dest_cmd.id = vm.id - dest_cmd.expunge = True - self.apiClient.destroyVirtualMachine(dest_cmd) - self.__class__.vm = None - - spool = self._assert_single_ready_spool_ref( - self.__class__.pool_db_id) - self._assert_cache_on_ontap(pool, spool) - - # Delete the ONTAP data volume - if vol is not None: - vol_id = vol.id - cmd = deleteVolumeAPI.deleteVolumeCmd() - cmd.id = vol_id - self.apiClient.deleteVolume(cmd) - self.__class__.volume = None - - # ONTAP: NFS3 volume data file must be removed from the FlexVol - # after deleteVolume (CloudStack/libvirt deletes the file from the - # NFS mount as part of the destroy workflow). - files = self.ontap.list_files_in_volume(pool_name) - vol_file = next((f for f in files if vol_id in f), None) - self.assertIsNone( - vol_file, - "Volume data file for '%s' should be gone from FlexVol '%s' " - "after deleteVolume; files still present: %s" - % (vol_id, pool_name, files) - ) - - # Enter maintenance then delete the pool - maint_cmd = enableStorageMaintenance.enableStorageMaintenanceCmd() - maint_cmd.id = pool.id - self.apiClient.enableStorageMaintenance(maint_cmd) - self._poll_pool_state(pool.id, "Maintenance", timeout=120) - - # forced=True: the template cache (template_spool_ref) is still on - # the pool — it is only reclaimed by storage GC or pool deletion. - self._delete_pool(pool.id, forced=True) - self.__class__.pool = None - - # CloudStack: pool must be gone - try: - remaining = list_storage_pools(self.apiClient, id=pool.id) - except Exception: - remaining = None - self.assertFalse(remaining, - "Pool still listed in CloudStack after deletion") - - # ONTAP: FlexVol must be deleted - ontap_vol = self.ontap.get_volume(pool_name) - self.assertIsNone( - ontap_vol, - "ONTAP FlexVol '%s' still exists after pool deletion" % pool_name - ) - - # ONTAP: Export policy must be removed - ep_name = "cs-%s-%s" % (self.svm_name, pool_name) - ep = self.ontap.get_export_policy(ep_name) - self.assertIsNone( - ep, - "ONTAP export policy '%s' still exists after pool deletion" - % ep_name - ) - - -# --------------------------------------------------------------------------- -# Module-level helpers (used in tearDownClass and test helpers) -# --------------------------------------------------------------------------- - -def _list_vms_cmd(vm_id): - cmd = listVirtualMachinesAPI.listVirtualMachinesCmd() - cmd.id = vm_id - return cmd - - -def _list_vols_cmd(vol_id): - cmd = listVolumesAPI.listVolumesCmd() - cmd.id = vol_id - return cmd + self.step_27_destroy_vm_and_cleanup() def _run_concurrent(*callables): @@ -1965,22 +912,6 @@ def worker(index, fn): return results -def _is_rejected(exc): - """True when CloudStack or ONTAP refused the call because another one was in progress.""" - text = str(exc).lower() - return any(token in text for token in ( - "internal error", - "failed to create snapshot", - "failed to create instance snapshot", - "failed to revert", - "another operation", - "other active", - "try again later", - "in progress", - "busy", - )) - - def _snapshot_and_revert_with_retry(snapshot_fn, revert_fn, attempts=3, pause=15): """Run a snapshot and a revert together. @@ -2019,14 +950,3 @@ def _snapshot_and_revert_with_retry(snapshot_fn, revert_fn, attempts=3, pause=15 raise AssertionError( "Snapshot-while-revert failed after %d attempt(s): %s" % (attempt, last_errors)) - - -def _wait_for_vm_state(api_client, vm_id, target_state, timeout=120, - interval=5): - """Blocking wait for a VM to reach target_state (used in tearDownClass).""" - deadline = time.time() + timeout - while time.time() < deadline: - vms = api_client.listVirtualMachines(_list_vms_cmd(vm_id)) - if vms and vms[0].state.lower() == target_state.lower(): - return - time.sleep(interval) diff --git a/test/integration/plugins/ontap/nfs3/template/test_snapshot_to_template.py b/test/integration/plugins/ontap/nfs3/template/test_snapshot_to_template.py new file mode 100644 index 000000000000..c7f64ec4a1d7 --- /dev/null +++ b/test/integration/plugins/ontap/nfs3/template/test_snapshot_to_template.py @@ -0,0 +1,769 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +""" +Snapshot-to-template integration tests for ONTAP NFS3 primary storage (Marvin). + +Create templates from ROOT and DATA volume snapshots of a running VM, deploy VMs +from them, and check the snapshots and templates in CloudStack and in ONTAP. + +Tests are numbered test_01 ... test_16 and must run in that order. Each step +builds on the shared state established by the previous step. + +Workflow: + 01 Create the NFS3 primary storage pool on ONTAP + 02 Create a CloudStack data volume on the ONTAP pool + 03 Deploy a VM whose ROOT disk is on the ONTAP pool + 04 Attach the ONTAP data volume to the running VM + 05 Open an SSH port forward to the VM; write ROOT and DATA files + 06 Create a template from the running VM's root snapshot and deploy from it + 07 Template from an older root snapshot has file A and not file B + 08 Create templates from two root snapshots at the same time + 09 Delete the template; the snapshot stays BackedUp + 10 Delete the snapshot after the template exists; the template still deploys + 11 Template stores password-enabled, dynamically-scalable, and the OS type + 12 Create the template after its source VM is expunged + 13 Template from the DATA snapshot does not boot; the KVM host shows no OS loaded + 14 Reject createTemplate with an empty name or no OS type + 15 One of two creates from the same snapshot succeeds; the other is rejected, + leaves no template, and the snapshot stays BackedUp + 16 Destroy the VMs, delete the data volume and the pool + +Setup and cleanup steps are shared with the VM suite; see helpers/snapshot_base.py. + +Guest login for the CentOS 5.5 template comes from ontap.cfg +(cloudstack.templateUsername / templatePassword); see guest_ssh.py. + +Running: + bash test/integration/plugins/ontap/run_tests.sh nfs3_snapshot_to_template + +Note: Tests share class-level state (sequential). Always run the full suite. +""" + +import logging +import random +import re +import shlex +import time +from contextlib import contextmanager + +from nose.plugins.attrib import attr + +from marvin.cloudstackAPI import ( + createTemplate as createTemplateAPI, + deleteTemplate as deleteTemplateAPI, + deployVirtualMachine as deployVirtualMachineAPI, + listImageStores as listImageStoresAPI, + listTemplates as listTemplatesAPI, + listVolumes as listVolumesAPI, +) +from marvin.lib.base import Snapshot +from marvin.codes import JOB_SUCCEEDED + +from guest_ssh import GuestSsh, close_ssh_port, new_token, open_ssh_port + +from helpers.snapshot_base import OntapSnapshotBase +from ontap_test_base import _list_vms_cmd + + +logger = logging.getLogger("TestOntapNfs3SnapshotToTemplate") + +TAG = "nfs3_snapshot_to_template" + + +# --------------------------------------------------------------------------- +# Sequential workflow test class +# --------------------------------------------------------------------------- + +TEMPLATE_FILE_A = "/root/ontap-file-a" +TEMPLATE_FILE_B = "/root/ontap-file-b" + + +def _enabled(value): + return str(value).lower() in ("true", "1") + + +def _template_in_progress(status): + """True when a template status means it is still being created or copied.""" + status = (status or "").lower() + if not status or any(word in status for word in ("complete", "error", "fail")): + return False + return any(word in status for word in ("creat", "progress", "download", "install", "%")) + + +# A guest with no bootable device reads only the BIOS boot-sector probe from its root disk. +NO_BOOT_MAX_READ_BYTES = 8 * 1024 * 1024 + + +# Expected text when CloudStack refuses a second createTemplate for a snapshot that +# is already being used. The exact wording is logged by test_19. +CONCURRENT_REJECTION = re.compile( + r"(not in\s+\w*\s*state|backedup|already|in progress|in use|being (used|processed)" + r"|busy|concurrent|locked|another|NoTransitionException|Unable to transition" + r"|from Copying|duplicate)", re.IGNORECASE) + + +class TestOntapNfs3SnapshotToTemplate(OntapSnapshotBase): + """ + Create templates from snapshots on the ONTAP NFS3 pool and deploy VMs from them. + + All tests are sequential; state is carried on class attributes. + """ + + PROTOCOL = "NFS3" + + def setUp(self): + super(TestOntapNfs3SnapshotToTemplate, self).setUp() + self._template_ids = [] + self._extra_vm_ids = [] + self._extra_ssh_rules = [] + + def tearDown(self): + """Expunge the extra VMs and delete the templates, then run the base cleanup.""" + try: + self._cleanup_template_case() + finally: + super(TestOntapNfs3SnapshotToTemplate, self).tearDown() + + # ------------------------------------------------------------------ + # Steps 06-19 - Create a template from a volume snapshot, then deploy + # from it. Each step removes the templates, extra VMs and snapshots it + # created. + # ------------------------------------------------------------------ + + def _cleanup_template_case(self): + """Expunge the extra VMs, close the SSH rules, then delete the templates. + + A template cannot be deleted while a VM deployed from it still exists, so + the VMs go first. + """ + for vm_id in list(self._extra_vm_ids): + try: + self._stop_and_expunge_vm(vm_id) + except Exception as exc: + logger.warning("tearDown: VM %s: %s" % (vm_id, exc)) + self._extra_vm_ids = [] + for rule_id in list(self._extra_ssh_rules): + try: + close_ssh_port(self.apiClient, rule_id) + except Exception as exc: + logger.warning("tearDown: SSH rule %s: %s" % (rule_id, exc)) + self._extra_ssh_rules = [] + leftovers = [] + for template_id in list(self._template_ids): + try: + self._delete_template_with_retry(template_id) + except Exception as exc: + logger.warning("tearDown: template %s not deleted: %s" % (template_id, exc)) + leftovers.append(template_id) + self._template_ids = [] + self.assertFalse(leftovers, "Templates left behind by this test: %s" % leftovers) + + def _tpl_name(self, label): + return "snap-tpl-%s-%d" % (label, random.randint(0, 999999)) + + def _require_image_store(self): + cmd = listImageStoresAPI.listImageStoresCmd() + cmd.zoneid = self.zone.id + if not (self.apiClient.listImageStores(cmd) or []): + self.skipTest("Zone has no image store; createTemplate needs secondary storage") + + def _ostype_id(self): + cmd = listTemplatesAPI.listTemplatesCmd() + cmd.id = self.__class__.template_id + cmd.templatefilter = "executable" + cmd.zoneid = self.zone.id + listed = self.apiClient.listTemplates(cmd) or [] + ostype = getattr(listed[0], "ostypeid", None) if listed else None + self.assertTrue(ostype, "Suite template has no OS type") + return ostype + + def _template_record(self, template_id): + cmd = listTemplatesAPI.listTemplatesCmd() + cmd.id = template_id + cmd.templatefilter = "self" + cmd.zoneid = self.zone.id + cmd.account = self.account.name + cmd.domainid = self.domain.id + cmd.listall = True + try: + return self.apiClient.listTemplates(cmd) or [] + except Exception as exc: + # A create that CloudStack rejects is rolled back, and its id no + # longer exists. That is "no record", not an error. + if "entity does not exist" in str(exc): + return [] + raise + + def _wait_template_ready(self, template_id, timeout=1800): + deadline = time.time() + timeout + last = None + while time.time() < deadline: + listed = self._template_record(template_id) + if listed: + last = listed[0] + status = getattr(last, "status", None) or "" + if _enabled(getattr(last, "isready", False)) and status == "Download Complete": + return last + if "error" in status.lower() or status.lower().startswith("failed"): + self.fail("Template %s entered status %s" % (template_id, status)) + time.sleep(10) + self.fail("Template %s did not become Ready (last status %s)" + % (template_id, getattr(last, "status", None))) + + def _delete_template(self, template_id): + cmd = deleteTemplateAPI.deleteTemplateCmd() + cmd.id = template_id + cmd.zoneid = self.zone.id + self.apiClient.deleteTemplate(cmd) + if template_id in self._template_ids: + self._template_ids.remove(template_id) + + def _delete_template_with_retry(self, template_id, timeout=300): + """deleteTemplate, retried while CloudStack still rejects it (e.g. Not Ready).""" + deadline = time.time() + timeout + while True: + if not self._template_record(template_id): + if template_id in self._template_ids: + self._template_ids.remove(template_id) + return + try: + self._delete_template(template_id) + return + except Exception as exc: + if time.time() >= deadline: + raise + logger.info("deleteTemplate %s not accepted yet (%s); retrying" % (template_id, exc)) + time.sleep(10) + + def _wait_template_gone(self, template_id): + deadline = time.time() + 300 + while time.time() < deadline: + if not self._template_record(template_id): + return + time.sleep(5) + self.fail("Template %s is still listed after delete" % template_id) + + def _submit_template(self, snap_id, name, wait=True, ostype=True, **flags): + """createTemplate from a snapshot. wait=False returns the job id at once.""" + cmd = createTemplateAPI.createTemplateCmd() + cmd.name = name + cmd.displaytext = name + if ostype: + cmd.ostypeid = self._ostype_id() + cmd.snapshotid = snap_id + cmd.zoneid = self.zone.id + cmd.account = self.account.name + cmd.domainid = self.domain.id + cmd.ispublic = False + cmd.passwordenabled = flags.get("passwordenabled", False) + cmd.isdynamicallyscalable = flags.get("isdynamicallyscalable", False) + if not wait: + cmd.isAsync = "false" + response = self.apiClient.createTemplate(cmd) + template_id = getattr(response, "id", None) + if template_id: + self._template_ids.append(template_id) + return response + + def _create_ready_template(self, snap, ontap_names, name, suite_running=True, **flags): + """createTemplate from a snapshot, then check Ready, the snapshot and primary storage.""" + before = self._pool_files() + response = self._submit_template(snap.id, name, **flags) + ready = self._wait_template_ready(response.id) + self.assertEqual(self._pool_files(), before, + "Primary storage changed while creating template %s" % response.id) + self._assert_snapshot_kept(snap, ontap_names) + if suite_running: + self.assertEqual(self._vm_state(self.__class__.vm.id), "Running", + "Suite VM is not Running after template creation") + return ready + + def _assert_snapshot_kept(self, snap, ontap_names): + listed = Snapshot.list(self.apiClient, id=snap.id, listall=True) or [] + self.assertTrue(listed, "Snapshot %s is no longer listed" % snap.id) + self.assertEqual(listed[0].state, "BackedUp", + "Snapshot %s is %s, expected BackedUp" % (snap.id, listed[0].state)) + self._assert_ontap_snaps_present(ontap_names, "source snapshot") + + def _snapshot_volume(self, volume_id, label): + before = self._ontap_snap_names() + snap = self._take_volume_snapshot(volume_id) + names = self._assert_new_ontap_snaps(before, [snap], "volume", label) + return snap, names + + def _snapshot_root(self, vm, label): + return self._snapshot_volume(self._root_volume_for_vm(vm.id).id, label) + + def _deploy_cmd(self, template_id): + cmd = deployVirtualMachineAPI.deployVirtualMachineCmd() + cmd.zoneid = self.zone.id + cmd.templateid = template_id + cmd.serviceofferingid = self.__class__.service_offering_id + cmd.account = self.account.name + cmd.domainid = self.domain.id + if self.__class__.network_id: + cmd.networkids = self.__class__.network_id + return cmd + + def _deploy_from_template(self, template_id): + """Deploy a VM from a template and check its ROOT volume is on the pool.""" + vm = self._deploy_vm(self._deploy_cmd(template_id)) + self._extra_vm_ids.append(vm.id) + self._poll_vm_state(vm.id, "Running", timeout=900) + root = self._root_volume_for_vm(vm.id) + self.assertEqual(str(root.storageid), str(self.__class__.pool.id), + "VM %s root is not on the ONTAP pool" % vm.id) + return vm + + def _deploy_data_template(self, template_id): + """Deploy from a data-disk template. The VM must reach Running or the test fails.""" + try: + vm = self._deploy_vm(self._deploy_cmd(template_id)) + except Exception as exc: + self.fail("Deploy from the data-disk template failed (%s); expected the VM to " + "start and then fail to boot" % exc) + self._extra_vm_ids.append(vm.id) + self._poll_vm_state(vm.id, "Running", timeout=300) + return vm + + def _expunge_tracked(self, vm_id): + self._stop_and_expunge_vm(vm_id) + if vm_id in self._extra_vm_ids: + self._extra_vm_ids.remove(vm_id) + + def _data_disks(self, vm_id): + cmd = listVolumesAPI.listVolumesCmd() + cmd.virtualmachineid = vm_id + cmd.type = "DATADISK" + cmd.listall = True + return self.apiClient.listVolumes(cmd) or [] + + def _account_templates(self): + cmd = listTemplatesAPI.listTemplatesCmd() + cmd.templatefilter = "self" + cmd.zoneid = self.zone.id + cmd.account = self.account.name + cmd.domainid = self.domain.id + cmd.listall = True + return self.apiClient.listTemplates(cmd) or [] + + def _account_template_ids(self): + return {t.id for t in self._account_templates()} + + def _assert_no_template_in_progress(self, timeout=120): + """Fail if a template of the account stays in a creating or copying status.""" + deadline = time.time() + timeout + stuck = [] + while time.time() < deadline: + stuck = [(t.id, getattr(t, "status", None)) for t in self._account_templates() + if _template_in_progress(getattr(t, "status", None))] + if not stuck: + return + time.sleep(5) + self.fail("Templates still in progress after %ds: %s" % (timeout, stuck)) + + def _wait_snapshot_backed_up(self, snap_id, timeout=120): + deadline = time.time() + timeout + state = None + while time.time() < deadline: + listed = Snapshot.list(self.apiClient, id=snap_id, listall=True) or [] + state = listed[0].state if listed else None + if state == "BackedUp": + return + time.sleep(5) + self.fail("Snapshot %s is %s after the concurrent creates, expected BackedUp" + % (snap_id, state)) + + def _job_error_text(self, job): + result = getattr(job, "jobresult", None) + text = getattr(result, "errortext", None) + if text is None and isinstance(result, dict): + text = result.get("errortext") + return str(text if text is not None else result) + + def _vm_host_and_instance(self, vm_id): + """KVM host IP and libvirt domain name of a running VM.""" + vms = self.apiClient.listVirtualMachines(_list_vms_cmd(vm_id)) or [] + self.assertTrue(vms, "VM %s is not listed" % vm_id) + host_id = getattr(vms[0], "hostid", None) + instance = getattr(vms[0], "instancename", None) + self.assertTrue(host_id and instance, "VM %s has no host or instance name" % vm_id) + host_ip = next((h.ipaddress for h in (self.cluster_hosts or []) if h.id == host_id), None) + self.assertTrue(host_ip, "No cluster host with id %s for VM %s" % (host_id, vm_id)) + return host_ip, instance + + def _vm_root_read_bytes(self, host_ip, instance): + """Bytes the guest has read from its first (root) disk, from libvirt.""" + vm_arg = shlex.quote(str(instance)) + out = self._kvm_run( + host_ip, + "target=$(virsh domblklist {vm} --details | " + "awk '$2 == \"disk\" {{ print $3; exit }}'); " + "test -n \"$target\" && virsh domblkstat {vm} \"$target\" | " + "awk '$2 == \"rd_bytes\" {{ print $3; exit }}'".format(vm=vm_arg)) + text = "\n".join(out).strip() + self.assertTrue(text.isdigit(), + "Could not read rd_bytes for %s on %s, got %r" % (instance, host_ip, text)) + return int(text) + + def _assert_vm_has_no_bootable_disk(self, vm_id, settle=90, interval=30): + """Show on the KVM host that the guest never loaded an OS from its root disk. + + libvirt must report the domain running, so a host, network or capacity + failure cannot pass. The root disk read counter must then stay flat + and below NO_BOOT_MAX_READ_BYTES: a booting OS keeps reading, while a + guest with no bootable device only probes the boot sector. + """ + host_ip, instance = self._vm_host_and_instance(vm_id) + state = " ".join(self._kvm_run( + host_ip, "virsh domstate %s" % shlex.quote(str(instance)))).strip().lower() + self.assertEqual(state, "running", + "libvirt reports %s as %r on %s, expected running" % (instance, state, host_ip)) + time.sleep(settle) + first = self._vm_root_read_bytes(host_ip, instance) + time.sleep(interval) + second = self._vm_root_read_bytes(host_ip, instance) + logger.info("test_14: root disk reads of %s on %s: %d then %d bytes", + instance, host_ip, first, second) + self.assertEqual(second, first, + "Root disk reads of %s are still growing (%d -> %d bytes): " + "an OS is loading from it" % (instance, first, second)) + self.assertLessEqual( + second, NO_BOOT_MAX_READ_BYTES, + "Guest read %d bytes from its root disk; a guest with no bootable device " + "reads at most %d" % (second, NO_BOOT_MAX_READ_BYTES)) + return second + + @contextmanager + def _guest_of(self, vm_id, connect_timeout=600): + """SSH to any VM as the template user. The suite VM reuses its port forward.""" + cls = self.__class__ + if cls.vm is not None and vm_id == cls.vm.id and cls.vm_ssh: + host, port = cls.vm_ssh + rule = None + else: + host, port, rule = open_ssh_port(self.apiClient, vm_id, cls.network_id) + self._extra_ssh_rules.append(rule) + try: + with GuestSsh(host, port, self.guest_user, self.guest_password, + connect_timeout=connect_timeout) as guest: + yield guest + finally: + if rule is not None: + if rule in self._extra_ssh_rules: + self._extra_ssh_rules.remove(rule) + try: + close_ssh_port(self.apiClient, rule) + except Exception as exc: + logger.warning("could not close SSH rule %s: %s" % (rule, exc)) + + def _write_file(self, vm_id, path, token): + with self._guest_of(vm_id) as guest: + guest.run("echo '%s' > %s && sync" % (token, path)) + + def _read_file(self, vm_id, path, connect_timeout=600): + with self._guest_of(vm_id, connect_timeout=connect_timeout) as guest: + return guest.run("cat %s 2>/dev/null; true" % path).strip() + + def _write_data_disk_marker(self, vm_id, token): + with self._guest_of(vm_id) as guest: + guest.write_data_marker(token) + + @attr(tags=[TAG], required_hardware=True) + def test_01_create_nfs3_pool(self): + """Create the NFS3 primary storage pool on ONTAP.""" + self.step_01_create_pool() + + @attr(tags=[TAG], required_hardware=True) + def test_02_create_ontap_data_volume(self): + """Create a CloudStack data volume on the ONTAP pool.""" + self.step_02_create_ontap_data_volume() + + @attr(tags=[TAG], required_hardware=True) + def test_03_deploy_vm(self): + """Deploy a VM whose ROOT disk is on the ONTAP pool.""" + self.step_03_deploy_vm() + + @attr(tags=[TAG], required_hardware=True) + def test_04_attach_volume_to_vm(self): + """Attach the data volume to the running VM.""" + self.step_04_attach_volume_to_vm() + + @attr(tags=[TAG], required_hardware=True) + def test_05_open_ssh_and_write_root_data_files(self): + """Open an SSH port forward and write files to the ROOT and DATA disks.""" + self.step_09_open_ssh_and_write_root_data_files() + + @attr(tags=[TAG], required_hardware=True) + def test_06_create_template_from_root_snapshot(self): + """ + Snapshot the running VM's ROOT disk, create a template from the snapshot, + and deploy a VM from the template. The deployed VM must have the file + written before the snapshot. + """ + vm = self._require_snapshot_vm() + self._require_image_store() + token = new_token("root-template") + self._write_file(vm.id, TEMPLATE_FILE_A, token) + snap, names = self._snapshot_root(vm, "root snapshot for template") + template = self._create_ready_template(snap, names, self._tpl_name("root")) + found = self._read_file(self._deploy_from_template(template.id).id, TEMPLATE_FILE_A) + self.assertEqual(found, token, "Deployed VM has %r, expected %r" % (found, token)) + + @attr(tags=[TAG], required_hardware=True) + def test_07_template_from_older_root_snapshot(self): + """ + Take two ROOT snapshots, one after the other. The template made from the + older snapshot must have the older file and not the newer one. + """ + vm = self._require_snapshot_vm() + self._require_image_store() + token_a = new_token("older-a") + token_b = new_token("older-b") + self._write_file(vm.id, TEMPLATE_FILE_A, token_a) + snap, names = self._snapshot_root(vm, "older root snapshot") + self._write_file(vm.id, TEMPLATE_FILE_B, token_b) + self._snapshot_root(vm, "newer root snapshot") + template = self._create_ready_template(snap, names, self._tpl_name("older")) + deployed = self._deploy_from_template(template.id) + self.assertEqual(self._read_file(deployed.id, TEMPLATE_FILE_A), token_a) + self.assertNotEqual(self._read_file(deployed.id, TEMPLATE_FILE_B), token_b, + "Template from the older snapshot contains the later file") + + @attr(tags=[TAG], required_hardware=True) + def test_08_two_templates_from_two_snapshots(self): + """ + Submit two createTemplate calls without waiting, one per ROOT snapshot. + Both templates must reach Ready and both snapshots must stay BackedUp. + """ + vm = self._require_snapshot_vm() + self._require_image_store() + snap_a, names_a = self._snapshot_root(vm, "first of two snapshots") + snap_b, names_b = self._snapshot_root(vm, "second of two snapshots") + before = self._pool_files() + first = self._submit_template(snap_a.id, self._tpl_name("two-a"), wait=False) + second = self._submit_template(snap_b.id, self._tpl_name("two-b"), wait=False) + job_a = self._wait_async_job(first.jobid) + job_b = self._wait_async_job(second.jobid) + self.assertEqual(job_a.jobstatus, JOB_SUCCEEDED, + "Template from the first snapshot failed: %s" % job_a) + self.assertEqual(job_b.jobstatus, JOB_SUCCEEDED, + "Template from the second snapshot failed: %s" % job_b) + ready_a = self._wait_template_ready(first.id) + ready_b = self._wait_template_ready(second.id) + self.assertNotEqual(ready_a.id, ready_b.id, "Both templates have the same ID") + self._assert_snapshot_kept(snap_a, names_a) + self._assert_snapshot_kept(snap_b, names_b) + self.assertEqual(self._pool_files(), before, + "Primary storage changed while creating the two templates") + + @attr(tags=[TAG], required_hardware=True) + def test_09_delete_template_keeps_snapshot(self): + """ + Delete a ready template. The template is gone and its source snapshot is + still BackedUp in CloudStack and on ONTAP. + """ + vm = self._require_snapshot_vm() + self._require_image_store() + snap, names = self._snapshot_root(vm, "root snapshot for template delete") + template = self._create_ready_template(snap, names, self._tpl_name("delete-me")) + self._delete_template(template.id) + self._wait_template_gone(template.id) + self._assert_snapshot_kept(snap, names) + + @attr(tags=[TAG], required_hardware=True) + def test_10_delete_snapshot_keeps_template(self): + """ + Delete the source snapshot after its template is Ready. The template stays + Ready and still deploys with the file written before the snapshot. + """ + vm = self._require_snapshot_vm() + self._require_image_store() + token = new_token("snapshot-deleted") + self._write_file(vm.id, TEMPLATE_FILE_A, token) + snap, names = self._snapshot_root(vm, "snapshot deleted after template") + template = self._create_ready_template(snap, names, self._tpl_name("keeps-template")) + self._delete_volume_snapshot_with_retry(snap.id) + self._wait_until_gone( + lambda: self._volume_snapshot_listed(snap.id), + "Snapshot %s still listed after delete" % snap.id) + if snap.id in self._volume_snapshot_ids: + self._volume_snapshot_ids.remove(snap.id) + self._created_ontap_snaps -= set(names) + self._wait_ontap_snaps_gone(names) + ready = self._wait_template_ready(template.id) + self.assertTrue(_enabled(getattr(ready, "isready", False))) + found = self._read_file(self._deploy_from_template(template.id).id, TEMPLATE_FILE_A) + self.assertEqual(found, token) + + @attr(tags=[TAG], required_hardware=True) + def test_11_template_stores_attributes(self): + """ + Create a template with password-enabled and dynamically-scalable set. The + template must store both flags and the suite template's OS type. + """ + vm = self._require_snapshot_vm() + self._require_image_store() + snap, names = self._snapshot_root(vm, "root snapshot for attributes") + template = self._create_ready_template( + snap, names, self._tpl_name("attrs"), + passwordenabled=True, isdynamicallyscalable=True) + self.assertTrue(_enabled(getattr(template, "passwordenabled", False)), + "Template did not store passwordenabled") + self.assertTrue(_enabled(getattr(template, "isdynamicallyscalable", False)), + "Template did not store isdynamicallyscalable") + self.assertEqual(getattr(template, "ostypeid", None), self._ostype_id(), + "Template OS type is not the suite template's OS type") + + @attr(tags=[TAG], required_hardware=True) + def test_12_template_after_vm_expunged(self): + """ + Snapshot the ROOT disk of a second VM, expunge that VM, then create the + template from the snapshot. The template must deploy with the file. + """ + self._require_snapshot_vm() + self._require_image_store() + source = self._deploy_from_template(self.__class__.template_id) + token = new_token("vm-gone") + self._write_file(source.id, TEMPLATE_FILE_A, token) + snap, names = self._snapshot_root(source, "snapshot of VM that will be expunged") + self._expunge_tracked(source.id) + template = self._create_ready_template( + snap, names, self._tpl_name("after-expunge"), suite_running=True) + found = self._read_file(self._deploy_from_template(template.id).id, TEMPLATE_FILE_A) + self.assertEqual(found, token) + + @attr(tags=[TAG], required_hardware=True) + def test_13_data_snapshot_template_unbootable(self): + """ + Create a template from a DATA volume snapshot and deploy a VM from it. + The deployment must succeed and the VM must reach Running, so a network, + host or capacity failure fails the test. The KVM host must then show the + guest never loaded an OS: libvirt reports the domain running and its + root disk read counter stays flat and tiny, which is the BIOS probing + for a bootable device. SSH being unreachable is checked as well. + """ + vm = self._require_snapshot_vm() + self._require_data_attached(vm) + self._require_image_store() + self.assertTrue( + self.kvm_hosts_ssh_creds, + "No KVM host SSH credentials are configured for the host-side no-boot check") + snap, names = self._snapshot_volume(self.__class__.volume.id, + "data snapshot for template") + template = self._create_ready_template(snap, names, self._tpl_name("data-disk")) + deployed = self._deploy_data_template(template.id) + self._assert_vm_has_no_bootable_disk(deployed.id) + try: + self._read_file(deployed.id, TEMPLATE_FILE_A, connect_timeout=60) + except Exception as exc: + logger.info("test_13: SSH to the VM from the data-disk template failed " + "as expected: %s" % exc) + else: + self.fail("VM deployed from a data-disk snapshot template accepted SSH") + + @attr(tags=[TAG], required_hardware=True) + def test_14_reject_missing_template_fields(self): + """ + Call createTemplate once with an empty name and once with no OS type. Both + calls must be rejected and no template may be created. + """ + vm = self._require_snapshot_vm() + self._require_image_store() + snap, names = self._snapshot_root(vm, "snapshot for rejected template") + before = self._pool_files() + for label, name, ostype in (("empty name", "", True), + ("no OS type", self._tpl_name("no-os"), False)): + try: + response = self._submit_template(snap.id, name, ostype=ostype) + except Exception as exc: + logger.info("test_14: %s rejected: %s" % (label, exc)) + continue + self.fail("createTemplate with %s was accepted (template %s)" + % (label, getattr(response, "id", None))) + self.assertEqual(self._pool_files(), before, + "A rejected createTemplate changed primary storage") + self._assert_snapshot_kept(snap, names) + + @attr(tags=[TAG], required_hardware=True) + def test_15_reject_second_template_same_snapshot(self): + """ + Submit two createTemplate calls for one snapshot without waiting. Exactly + one must succeed and reach Ready. The other must be rejected with a + concurrent or duplicate-state error, either when it is submitted or as a + failed job. The losing template must not be Ready, no template may stay + in Creating, the account must gain exactly the winning template, and the + snapshot must return to BackedUp. + """ + vm = self._require_snapshot_vm() + self._require_image_store() + snap, names = self._snapshot_root(vm, "snapshot for two template creates") + before_ids = self._account_template_ids() + before_primary = self._pool_files() + + calls = [] + for label in ("race-a", "race-b"): + try: + response = self._submit_template(snap.id, self._tpl_name(label), wait=False) + except Exception as exc: + calls.append({"label": label, "response": None, "error": str(exc)}) + continue + calls.append({"label": label, "response": response, "error": None}) + for call in calls: + if call["response"] is None: + continue + job = self._wait_async_job(call["response"].jobid) + if job.jobstatus != JOB_SUCCEEDED: + call["error"] = self._job_error_text(job) + + outcome = [(c["label"], c["error"]) for c in calls] + logger.info("test_15: outcomes (label, error): %s", outcome) + winners = [c for c in calls if c["error"] is None] + losers = [c for c in calls if c["error"] is not None] + self.assertEqual(len(winners), 1, + "Expected one template create to succeed, outcomes: %s" % outcome) + self.assertEqual(len(losers), 1, + "Expected one template create to be rejected, outcomes: %s" % outcome) + winner, loser = winners[0], losers[0] + self.assertTrue( + CONCURRENT_REJECTION.search(loser["error"]), + "The losing create was not rejected for the concurrent or duplicate state: %s" + % loser["error"]) + + self._wait_template_ready(winner["response"].id) + loser_id = getattr(loser["response"], "id", None) if loser["response"] else None + if loser_id: + for record in self._template_record(loser_id): + self.assertFalse( + _enabled(getattr(record, "isready", False)), + "Losing template %s is Ready" % loser_id) + self._assert_no_template_in_progress() + added = self._account_template_ids() - before_ids + self.assertEqual( + added, {winner["response"].id}, + "Expected the account to gain only the winning template %s, gained %s" + % (winner["response"].id, sorted(added))) + self._wait_snapshot_backed_up(snap.id) + self._assert_snapshot_kept(snap, names) + self.assertEqual(self._pool_files(), before_primary, + "Primary storage changed after the two template creates") + + @attr(tags=[TAG], required_hardware=True) + def test_16_destroy_vm_and_cleanup(self): + """Destroy the VMs, delete the data volume and the pool.""" + self.step_27_destroy_vm_and_cleanup() diff --git a/test/integration/plugins/ontap/nfs3/volume/test_snapshot_to_volume.py b/test/integration/plugins/ontap/nfs3/volume/test_snapshot_to_volume.py new file mode 100644 index 000000000000..da859195a7a7 --- /dev/null +++ b/test/integration/plugins/ontap/nfs3/volume/test_snapshot_to_volume.py @@ -0,0 +1,826 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +""" +Snapshot-to-volume integration tests for ONTAP NFS3 primary storage (Marvin). + +Create volumes from ROOT and DATA volume snapshots of a running VM, attach them to +VMs, and check each new volume in CloudStack and in ONTAP. + +Tests are numbered test_01 ... test_22 and must run in that order. Each step +builds on the shared state established by the previous step. + +Workflow: + 01 Create the NFS3 primary storage pool on ONTAP + 02 Create and attach the data volume, deploy VM-A, and write ROOT and DATA files + 03 Deploy VM-B on the same pool + 04 Create a DATADISK (QCOW2) volume from a ROOT snapshot of VM-A + 05 Create a volume from a DATA snapshot; attach it and verify its marker + 06 Move a clone from VM-A to VM-B and verify its data + 07 Verify a clone is independent of its source + 08 Reject createVolume from a VM snapshot ID + 09 Reject a ROOT-snapshot clone with a smaller offering + 10 Reject attaching one clone to two VMs + 11 Delete a DATA snapshot while createVolume is in flight; no orphaned file + 12 Create a DATA-snapshot volume with the source offering and size + 13 Reject createVolume from a DATA snapshot with a disk offering + 14 Create three volumes concurrently from one snapshot + 15 Create a volume after its source volume is deleted + 16 Create a volume from a snapshot of a clone + 17 Reject createVolume when its FlexVol snapshot is missing + 18 Reject createVolume while the pool is Disabled; succeed once Up + 19 Reject createVolume with a nonexistent snapshot ID + 20 Reject createVolume when only another pool is available + 21 Reject createVolume when required snapshot metadata is missing + 22 Destroy both VMs, delete the data volume and the pool +Setup and cleanup steps are shared with the VM suite; see helpers/snapshot_base.py. + +Guest login for the CentOS 5.5 template comes from ontap.cfg +(cloudstack.templateUsername / templatePassword); see guest_ssh.py. + +Running: + bash test/integration/plugins/ontap/run_tests.sh nfs3_snapshot_to_volume + +Note: Tests share class-level state (sequential). Always run the full suite. +""" + +import logging +import random +import uuid +from concurrent.futures import ThreadPoolExecutor + +from nose.plugins.attrib import attr + +from marvin.cloudstackAPI import ( + attachVolume as attachVolumeAPI, + createVolume as createVolumeAPI, + deleteVolume as deleteVolumeAPI, + listVolumes as listVolumesAPI, +) +from marvin.lib.base import DiskOffering, Snapshot +from marvin.codes import JOB_SUCCEEDED + +from guest_ssh import new_token + +from helpers.snapshot_base import ( + REQUIRED_SNAPSHOT_DETAILS, + FAILED_VOLUME_STATES, + OntapSnapshotBase, + _guest_disk_names, +) +from ontap_test_base import _list_vols_cmd + + +logger = logging.getLogger("TestOntapNfs3SnapshotToVolume") + +TAG = "nfs3_snapshot_to_volume" + + + +# Size of the seeded source file for a volume that is never attached. +SOURCE_FILE_BYTES = 4 * 1024 * 1024 + +class TestOntapNfs3SnapshotToVolume(OntapSnapshotBase): + """ + Create volumes from snapshots on the ONTAP NFS3 pool and attach them to VMs. + + All tests are sequential; state is carried on class attributes. + """ + + PROTOCOL = "NFS3" + + def _clone_object_exists(self, clone): + """The clone's file is named after the volume UUID, inside the pool's FlexVol.""" + return any(clone.id in name for name in self._pool_objects_of(self.__class__.pool)) + + def _pool_objects_of(self, pool): + """Names of the files in the pool's FlexVol.""" + return set(self.ontap.list_files_in_volume(pool.name)) + + def _seed_volume_file(self, vol): + """Write a file named after the volume UUID, as attach would create it. + + A data volume gets its FlexVol file only when it is attached. A volume + created here and never attached has nothing for ONTAP to snapshot or + clone, so its file is written directly. + """ + self.ontap.write_file_in_volume(self.__class__.pool.name, vol.id, + SOURCE_FILE_BYTES) + self.assertTrue(self._clone_object_exists(vol), + "Seeded file for volume %s not found in the FlexVol" % vol.id) + + @attr(tags=[TAG], required_hardware=True) + def test_01_create_nfs3_pool(self): + """Create the NFS3 primary storage pool on ONTAP.""" + self.step_01_create_pool() + + @attr(tags=[TAG], required_hardware=True) + def test_02_prepare_vm_with_data_volume(self): + """Create the data volume, deploy the VM, attach it, and write ROOT and DATA files.""" + self.step_02_create_ontap_data_volume() + self.step_03_deploy_vm() + self.step_04_attach_volume_to_vm() + self.step_09_open_ssh_and_write_root_data_files() + + @attr(tags=[TAG], required_hardware=True) + def test_03_deploy_second_vm(self): + """Deploy a second VM on the same ONTAP pool.""" + self.step_19_deploy_second_vm() + + @attr(tags=[TAG], required_hardware=True) + def test_04_create_volume_from_root_snapshot(self): + """ + Create a volume from a ROOT volume snapshot of the running VM. + Verifies: + - the new volume reaches Ready on the ONTAP test pool + - CloudStack records it as DATADISK (not ROOT) with format QCOW2 + - ONTAP has a file for it inside the pool's FlexVol + """ + vm = self._require_snapshot_vm() + before = self._ontap_snap_names() + snap = self._take_volume_snapshot(self._root_volume_for_vm(vm.id).id) + self._assert_new_ontap_snaps(before, [snap], "volume", "ROOT snapshot for clone") + + clone = self._create_clone(snap.id) + try: + self.assertEqual(getattr(clone, "type", None), "DATADISK", + "Clone of a ROOT snapshot is %r, expected DATADISK" + % getattr(clone, "type", None)) + self.assertEqual(getattr(clone, "storageid", None), self.__class__.pool.id, + "Clone of a ROOT snapshot is not on the ONTAP test pool") + self.assertEqual(self._db_volume_format(clone.id), "QCOW2", + "Clone of a ROOT snapshot is not QCOW2 in the volumes table") + self.assertTrue(self._clone_object_exists(clone), + "ONTAP file for the clone of a ROOT snapshot is missing") + finally: + self._remove_clone(clone) + self._wait_clone_object_gone(clone) + + @attr(tags=[TAG], required_hardware=True) + def test_05_create_volume_from_data_snapshot(self): + """ + Create a volume from a DATA volume snapshot, attach it to the running VM + and read the snapshot-time marker from it. + Verifies: + - the clone reaches Ready and has its own file in ONTAP + - the clone holds the token written before the snapshot, not the one + written after it + - the clone detaches and is deleted, and its file is removed + """ + vm = self._require_snapshot_vm() + self._require_data_attached(vm) + token_snap = new_token("clone-snapshot-time") + token_after = new_token("clone-after-snapshot") + self._write_marker(token_snap, disks=("DATA",)) + before = self._ontap_snap_names() + snap = self._take_volume_snapshot(self.__class__.volume.id) + self._assert_new_ontap_snaps(before, [snap], "volume", "DATA snapshot for clone") + self._write_marker(token_after, disks=("DATA",)) + + clone = self._create_clone(snap.id) + try: + self.assertTrue(self._clone_object_exists(clone), + "ONTAP file for the data clone is missing") + dev = self._attach_clone(clone, vm.id, "vm") + found = self._clone_marker("vm", dev) + self.assertEqual( + found, token_snap, + "Clone marker is %r, expected snapshot-time %r (post-snapshot token was %r)" + % (found, token_snap, token_after)) + self._detach_clone(clone) + finally: + self._remove_clone(clone) + self._wait_clone_object_gone(clone) + + @attr(tags=[TAG], required_hardware=True) + def test_06_detach_and_reattach_clone_on_second_vm(self): + """ + Write to a clone attached to VM-A, detach it, attach it to VM-B and read + the data back. + Verifies: + - the write made on VM-A is read back on VM-A + - the clone's file stays in ONTAP while the clone is detached + - the same data is read on VM-B after the reattach + """ + vm = self._require_snapshot_vm() + vm2 = self._require_second_vm() + self._require_data_attached(vm) + before = self._ontap_snap_names() + snap = self._take_volume_snapshot(self.__class__.volume.id) + self._assert_new_ontap_snaps(before, [snap], "volume", "DATA snapshot for reattach") + + token = new_token("clone-written-on-vm-a") + clone = self._create_clone(snap.id) + try: + dev = self._attach_clone(clone, vm.id, "vm") + found = self._clone_marker("vm", dev, write=token) + self.assertEqual(found, token, "Write on VM-A read back as %r, expected %r" + % (found, token)) + self._detach_clone(clone) + self.assertTrue(self._clone_object_exists(clone), + "Clone file disappeared while the clone was detached") + dev2 = self._attach_clone(clone, vm2.id, "vm2") + found = self._clone_marker("vm2", dev2) + self.assertEqual(found, token, "Data read on VM-B is %r, expected %r" + % (found, token)) + finally: + self._remove_clone(clone) + self._wait_clone_object_gone(clone) + + @attr(tags=[TAG], required_hardware=True) + def test_07_clone_is_independent_of_source(self): + """ + Write to a clone, then to its source, and check each side keeps its own data. + Verifies: + - the clone holds the snapshot-time token, not the one written after it + - a write to the clone does not change the source DATA marker + - a write to the source does not change the clone marker + """ + vm = self._require_snapshot_vm() + self._require_data_attached(vm) + token_snap = new_token("independence-snapshot") + token_src = new_token("independence-source-after") + token_clone = new_token("independence-clone-write") + token_src_final = new_token("independence-source-final") + self._write_marker(token_snap, disks=("DATA",)) + before = self._ontap_snap_names() + snap = self._take_volume_snapshot(self.__class__.volume.id) + self._assert_new_ontap_snaps(before, [snap], "volume", "DATA snapshot for independence") + self._write_marker(token_src, disks=("DATA",)) + + clone = self._create_clone(snap.id) + try: + dev = self._attach_clone(clone, vm.id, "vm") + found = self._clone_marker("vm", dev) + self.assertEqual(found, token_snap, + "Clone marker is %r, expected snapshot-time %r" + % (found, token_snap)) + self._clone_marker("vm", dev, write=token_clone) + self._assert_marker(token_src, disk="DATA", msg="after write to the clone") + self._write_marker(token_src_final, disks=("DATA",)) + found = self._clone_marker("vm", dev) + self.assertEqual(found, token_clone, + "Clone marker changed after a source write: %r, expected %r" + % (found, token_clone)) + self._detach_clone(clone) + finally: + self._remove_clone(clone) + self._wait_clone_object_gone(clone) + + @attr(tags=[TAG], required_hardware=True) + def test_08_reject_clone_from_vm_snapshot(self): + """ + Pass a VM snapshot ID to createVolume. + Verifies: + - the request is rejected + - no volume record is left behind and no file is added to the FlexVol + - the VM snapshot is still Ready + """ + vm = self._require_snapshot_vm() + before = self._ontap_snap_names() + vm_snap = self._take_vm_snapshot_when_accepted(vm.id) + self._assert_new_ontap_snaps(before, [vm_snap], "vm", + "VM snapshot for rejected clone") + + message = self._expect_clone_rejected(vm_snap.id) + logger.info("test_08: createVolume from a VM snapshot rejected: %s" % message) + # CloudStack looks the ID up as a volume snapshot and does not find it. + # The error must name snapshotid, so a storage-side failure cannot pass here. + self.assertIn("snapshotid", message.lower(), + "Rejection does not name snapshotid: %s" % message) + self.assertIn("does not exist", message.lower(), + "Rejection is not an unknown-snapshot error: %s" % message) + + listed = [s for s in self._vm_snapshots_of(vm.id) if s.id == vm_snap.id] + self.assertTrue(listed and listed[0].state == "Ready", + "VM snapshot %s is not Ready after the rejected create" % vm_snap.id) + + @attr(tags=[TAG], required_hardware=True) + def test_09_reject_smaller_offering_for_root_snapshot(self): + """ + Create a volume from a ROOT snapshot with a disk offering smaller than + the ROOT disk. + Verifies: + - the request is rejected + - no volume record is left behind and no file is added to the FlexVol + """ + vm = self._require_snapshot_vm() + root = self._root_volume_for_vm(vm.id) + offering_gib = (int(root.size) - 1) // (1024 ** 3) + if offering_gib < 1: + self.skipTest("ROOT disk is %d bytes; no smaller offering of at least 1 GiB exists" + % int(root.size)) + before = self._ontap_snap_names() + snap = self._take_volume_snapshot(root.id) + self._assert_new_ontap_snaps(before, [snap], "volume", + "ROOT snapshot for rejected clone") + + small = DiskOffering.create( + self.apiClient, + { + "name": "OntapNFS3VMSmallDO_%d" % random.randint(0, 99999), + "displaytext": "Disk offering smaller than the ROOT disk", + "disksize": offering_gib, + "storagetype": "shared", + "tags": self.__class__.pool_tags, + }, + ) + try: + message = self._expect_clone_rejected(snap.id, disk_offering_id=small.id) + logger.info("test_09: %d GiB offering for a %d byte ROOT snapshot rejected: %s" + % (offering_gib, int(root.size), message)) + self.assertIn("Invalid size for volume creation", message, + "Rejection is not the size check: %s" % message) + finally: + try: + small.delete(self.apiClient) + except Exception as exc: + logger.warning("test_09: could not delete disk offering %s: %s" + % (small.id, exc)) + + @attr(tags=[TAG], required_hardware=True) + def test_10_reject_attach_of_attached_clone_to_second_vm(self): + """ + Attach a clone to VM-A, then try to attach it to VM-B without detaching. + Verifies: + - the second attach is rejected as already attached + - the clone still references VM-A + - VM-A still reads the clone marker + - the clone file stays in the FlexVol and no file is added + - VM-B sees no new disk + """ + vm = self._require_snapshot_vm() + vm2 = self._require_second_vm() + self._require_data_attached(vm) + before = self._ontap_snap_names() + snap = self._take_volume_snapshot(self.__class__.volume.id) + self._assert_new_ontap_snaps(before, [snap], "volume", "DATA snapshot for double attach") + + token = new_token("clone-attached-to-vm-a") + clone = self._create_clone(snap.id) + try: + dev = self._attach_clone(clone, vm.id, "vm") + found = self._clone_marker("vm", dev, write=token) + self.assertEqual(found, token, "Write on VM-A read back as %r, expected %r" + % (found, token)) + files_before = self._pool_objects_of(self.__class__.pool) + self.assertTrue(any(clone.id in name for name in files_before), + "Clone file is missing while attached to VM-A") + with self._guest("vm2") as guest: + vm2_disks_before = _guest_disk_names(guest) + + cmd = attachVolumeAPI.attachVolumeCmd() + cmd.id = clone.id + cmd.virtualmachineid = vm2.id + try: + self.apiClient.attachVolume(cmd) + except Exception as exc: + message = str(exc) + else: + self.fail("attachVolume of clone %s to VM-B was accepted while attached to VM-A" + % clone.id) + logger.info("test_10: second attach rejected: %s" % message) + # The admin attach path says "not attached to any VM"; the user path says "already attached". + lowered = message.lower() + self.assertTrue("not attached to any vm" in lowered or "already attached" in lowered, + "Rejection is not the attached-volume check: %s" % message) + + cmd = listVolumesAPI.listVolumesCmd() + cmd.id = clone.id + cmd.listall = True + listed = self.apiClient.listVolumes(cmd) or [] + self.assertTrue(listed, "Clone %s is no longer listed" % clone.id) + self.assertEqual(getattr(listed[0], "virtualmachineid", None), vm.id, + "Clone no longer references VM-A after the rejected attach") + self.assertTrue(self._clone_object_exists(clone), + "Clone file disappeared after the rejected attach") + added = self._pool_objects_of(self.__class__.pool) - files_before + self.assertFalse(added, "File(s) added to the FlexVol by the rejected attach: %s" + % sorted(added)) + with self._guest("vm2") as guest: + self.assertEqual(_guest_disk_names(guest), vm2_disks_before, + "VM-B gained a disk after the rejected attach") + found = self._clone_marker("vm", dev) + self.assertEqual(found, token, "VM-A reads %r after the rejected attach, expected %r" + % (found, token)) + self._detach_clone(clone) + finally: + self._remove_clone(clone) + self._wait_clone_object_gone(clone) + + @attr(tags=[TAG], required_hardware=True) + def test_11_delete_snapshot_during_create(self): + """ + Submit createVolume(snapshotid) without waiting for it, then delete the + DATA snapshot while the create is still in progress. + Verifies a deterministic outcome with no orphaned file: + - if createVolume succeeds: the volume is Ready as QCOW2 and exactly + one new file for it appears in the FlexVol; the clone and the + snapshot are then removed in this step + - if createVolume fails: no usable volume record is left behind, no + file is added to the FlexVol, and the snapshot is removed from both + CloudStack and ONTAP + - the VM stays Running and the FlexVol file set returns to its baseline + """ + vm = self._require_snapshot_vm() + self._require_data_attached(vm) + before = self._ontap_snap_names() + snap = self._take_volume_snapshot(self.__class__.volume.id) + ontap_names = self._assert_new_ontap_snaps(before, [snap], "volume", + "DATA snapshot for delete race") + + files_before = self._pool_objects_of(self.__class__.pool) + volumes_before = self._account_volume_ids() + + create_cmd = createVolumeAPI.createVolumeCmd() + create_cmd.isAsync = "false" + create_cmd.name = "%s_race_%d" % (self._vol_name_prefix, random.randint(0, 999999)) + create_cmd.zoneid = self.zone.id + create_cmd.account = self.account.name + create_cmd.domainid = self.domain.id + create_cmd.snapshotid = snap.id + submitted = self.apiClient.createVolume(create_cmd) + self._extra_volume_ids.append(submitted.id) + + delete_rejected = False + delete_err = None + try: + Snapshot({"id": snap.id}).delete(self.apiClient) + except Exception as exc: + delete_rejected = True + delete_err = exc + logger.info("test_11: deleteSnapshot during in-flight create refused: %s" % exc) + + job = self._wait_async_job(submitted.jobid) + create_succeeded = (job.jobstatus == JOB_SUCCEEDED) + logger.info("test_11: race finished (create_succeeded=%s, delete_rejected=%s)", + create_succeeded, delete_rejected) + self.assertFalse( + (not create_succeeded) and delete_rejected, + "Both createVolume (jobstatus=%s) and deleteSnapshot (%s) failed" + % (job.jobstatus, delete_err)) + + if create_succeeded: + clone = self._poll_volume_field(submitted.id, "state", "Ready", timeout=600) + self.assertIsNotNone( + clone, "Completed createVolume left volume %s not Ready" % submitted.id) + self.assertEqual(self._db_volume_format(clone.id), "QCOW2", + "Race clone is not QCOW2 in the volumes table") + self.assertEqual(self._account_volume_ids() - volumes_before, {clone.id}, + "Account volume set does not match the single created clone") + new_files = self._pool_objects_of(self.__class__.pool) - files_before + self.assertEqual( + len(new_files), 1, + "Expected 1 new file for the clone, found %s (orphaned or missing file)" + % sorted(new_files)) + self.assertIn(clone.id, next(iter(new_files)), + "New file %s does not match the clone %s" + % (sorted(new_files), clone.id)) + self._remove_clone(clone) + self._wait_clone_object_gone(clone) + else: + vols = self.apiClient.listVolumes(_list_vols_cmd(submitted.id)) or [] + state = getattr(vols[0], "state", None) if vols else None + self.assertTrue(state is None or state in FAILED_VOLUME_STATES, + "Failed createVolume left volume %s in state %s" + % (submitted.id, state)) + self.assertEqual(self._account_volume_ids(), volumes_before, + "Failed createVolume left a usable volume record behind") + self.assertEqual(self._pool_objects_of(self.__class__.pool), files_before, + "Failed createVolume left a file in the FlexVol") + if submitted.id in self._extra_volume_ids: + self._extra_volume_ids.remove(submitted.id) + + # Remove the snapshot. The delete may already have been accepted during + # the race, so only retry it while CloudStack still lists it. + if self._volume_snapshot_listed(snap.id): + self._delete_volume_snapshot_with_retry(snap.id) + self._wait_until_gone( + lambda: self._volume_snapshot_listed(snap.id), + "Volume snapshot %s still listed after the race" % snap.id) + if snap.id in self._volume_snapshot_ids: + self._volume_snapshot_ids.remove(snap.id) + self._created_ontap_snaps -= ontap_names + self._wait_ontap_snaps_gone(ontap_names) + + self.assertEqual(self._pool_objects_of(self.__class__.pool), files_before, + "FlexVol file set after test_11 differs from baseline") + self.assertEqual(self._vm_state(vm.id), "Running", + "VM is not Running after the delete race") + + @attr(tags=[TAG], required_hardware=True) + def test_12_create_volume_keeps_offering_and_size(self): + """ + createVolume(snapshotid) with no disk offering; the clone takes the source's. + Verifies: + - the clone is Ready as DATADISK and QCOW2 on the ONTAP test pool + - the clone has the source disk offering and size + - no cloneOfSnapshot volume detail is left on the clone + - ONTAP: the clone has its own file; the source file stays + """ + src = self._cs_volume(self.__class__.volume.id) + snap = self._take_volume_snapshot_when_accepted(self.__class__.volume.id) + clone = self._create_clone(snap.id) + try: + cloned = self._cs_volume(clone.id) + self.assertIsNotNone(cloned, "Clone not listed in CloudStack") + self.assertEqual(getattr(cloned, "type", None), "DATADISK", + "Clone type is %r, expected DATADISK" % getattr(cloned, "type", None)) + self.assertEqual(getattr(cloned, "storageid", None), self.__class__.pool.id, + "Clone is not on the ONTAP test pool") + self.assertEqual(cloned.diskofferingid, src.diskofferingid, + "Clone disk offering %s, expected source offering %s" + % (cloned.diskofferingid, src.diskofferingid)) + self.assertEqual(int(cloned.size), int(src.size), + "Clone size %s, expected %s" % (cloned.size, src.size)) + self.assertEqual(self._db_volume_format(clone.id), "QCOW2", + "Clone is not QCOW2 in the volumes table") + + rows = self.__class__.dbConnection.execute( + "SELECT id FROM volumes WHERE uuid = %s", params=(clone.id,)) + self.assertTrue(rows, "No volumes row for uuid %s" % clone.id) + leftover = self.__class__.dbConnection.execute( + "SELECT id FROM volume_details WHERE volume_id = %s AND name = %s", + params=(rows[0][0], "cloneOfSnapshot")) + self.assertFalse(leftover, "cloneOfSnapshot detail was left on the clone volume") + self.assertTrue(self._clone_object_exists(self.__class__.volume), + "Source file disappeared after the clone was made") + finally: + self._remove_clone(clone) + self._wait_clone_object_gone(clone) + self._finish_volume_snapshot(snap.id) + + @attr(tags=[TAG], required_hardware=True) + def test_13_reject_disk_offering_with_snapshot(self): + """ + Pass both snapshotid and diskofferingid to createVolume. CloudStack only + allows a disk offering with a ROOT volume snapshot; this snapshot is of a + DATA volume. + Verifies: + - the request is rejected with the ROOT-only message + - no volume record is left behind and no file is added to the FlexVol + """ + snap = self._take_volume_snapshot_when_accepted(self.__class__.volume.id) + message = self._expect_clone_rejected( + snap.id, disk_offering_id=self.__class__.disk_offering_id) + self.assertIn("Disk Offering ID cannot be passed", message, + "Rejection is not the ROOT-only disk offering rule: %s" % message) + self._finish_volume_snapshot(snap.id) + + @attr(tags=[TAG], required_hardware=True) + def test_14_create_volumes_concurrently_from_snapshot(self): + """ + Submit three createVolume(snapshotid) requests at the same moment. + Verifies: + - every request ends Ready as a DATADISK on the pool, and the three are distinct + - exactly three new files appear, one per volume (no orphans) + """ + snap = self._take_volume_snapshot_when_accepted(self.__class__.volume.id) + before = self._pool_objects_of(self.__class__.pool) + with ThreadPoolExecutor(max_workers=3) as executor: + futures = [executor.submit(self._attempt_clone, snap.id) for _ in range(3)] + results = [f.result() for f in futures] + for rejected, _ in results: + self.assertFalse(rejected, "A concurrent createVolume from snapshot failed") + volumes = [vol for _, vol in results] + for vol in volumes: + self.assertEqual(getattr(vol, "type", None), "DATADISK", + "Concurrent clone %s is not DATADISK" % vol.id) + self.assertEqual(getattr(vol, "storageid", None), self.__class__.pool.id, + "Concurrent clone %s is not on the ONTAP test pool" % vol.id) + self.assertEqual(len({v.id for v in volumes}), 3, + "Concurrent createVolume returned duplicate volumes") + + new = self._pool_objects_of(self.__class__.pool) - before + self.assertEqual(len(new), 3, + "Expected 3 new files, found %s (orphans or missing clones)" + % sorted(new)) + for vol in volumes: + matches = [name for name in new if vol.id in name] + self.assertEqual(len(matches), 1, + "Volume %s has %d files, expected 1" % (vol.id, len(matches))) + for vol in volumes: + self._remove_clone(vol) + for vol in volumes: + self._wait_clone_object_gone(vol) + self._finish_volume_snapshot(snap.id) + + @attr(tags=[TAG], required_hardware=True) + def test_15_create_volume_after_source_deleted(self): + """ + Snapshot a second data volume, delete that volume, then create a volume + from the kept snapshot. + Verifies: + - the deleted volume's file is removed from the FlexVol + - the new clone is Ready as QCOW2 on the pool and has its own file + """ + pool = self.__class__.pool + src2 = self._create_volume(pool.id) + self._extra_volume_ids.append(src2.id) + src2 = self._poll_volume_field(src2.id, "state", "Ready", timeout=600) + self.assertIsNotNone(src2, "Second source volume did not reach Ready") + self._seed_volume_file(src2) + snap2 = self._take_volume_snapshot_when_accepted(src2.id) + + cmd = deleteVolumeAPI.deleteVolumeCmd() + cmd.id = src2.id + self.apiClient.deleteVolume(cmd) + self._extra_volume_ids.remove(src2.id) + self._wait_until_gone(lambda: self._clone_object_exists(src2), + "File for deleted source %s still present" % src2.id) + + clone = self._create_clone(snap2.id) + try: + self.assertEqual(self._db_volume_format(clone.id), "QCOW2", + "Clone is not QCOW2 in the volumes table") + self.assertTrue(self._clone_object_exists(clone), + "ONTAP file for the clone is missing") + finally: + self._remove_clone(clone) + self._wait_clone_object_gone(clone) + self._finish_volume_snapshot(snap2.id) + + @attr(tags=[TAG], required_hardware=True) + def test_16_create_volume_from_snapshot_of_clone(self): + """ + Snapshot a clone of the DATA snapshot, then create a volume from that snapshot. + Verifies: + - the snapshot of the clone reaches BackedUp + - the new volume is Ready as QCOW2 on the pool and has its own file + """ + snap = self._take_volume_snapshot_when_accepted(self.__class__.volume.id) + clone = self._create_clone(snap.id) + clone_snap = self._take_volume_snapshot_when_accepted(clone.id) + self.assertEqual(clone_snap.state, "BackedUp", + "Snapshot of the clone is %s, expected BackedUp" % clone_snap.state) + + new = self._create_clone(clone_snap.id) + try: + self.assertEqual(self._db_volume_format(new.id), "QCOW2", + "New volume is not QCOW2 in the volumes table") + self.assertTrue(self._clone_object_exists(new), + "ONTAP file for the volume from the clone's snapshot is missing") + finally: + self._remove_clone(new) + self._wait_clone_object_gone(new) + self._finish_volume_snapshot(clone_snap.id) + self._remove_clone(clone) + self._wait_clone_object_gone(clone) + self._finish_volume_snapshot(snap.id) + + @attr(tags=[TAG], required_hardware=True) + def test_17_reject_create_when_ontap_snapshot_missing(self): + """ + CloudStack lists a snapshot as BackedUp, but its FlexVol snapshot was + deleted directly on ONTAP. + Verifies: + - createVolume(snapshotid) fails + - no volume record is left behind and no file is added to the FlexVol + """ + before = self._ontap_snap_names() + snap = self._take_volume_snapshot_when_accepted(self.__class__.volume.id) + new = self._ontap_snap_names() - before + self.assertEqual(len(new), 1, "Expected one new FlexVol snapshot, found %s" % sorted(new)) + ontap_name = new.pop() + + self.assertTrue(self.ontap.delete_snapshot(self.__class__.pool.name, ontap_name), + "FlexVol snapshot %s not found to delete" % ontap_name) + self._wait_until_gone(lambda: ontap_name in self._ontap_snap_names(), + "FlexVol snapshot %s still present" % ontap_name) + + message = self._expect_clone_rejected(snap.id) + logger.info("test_17: create from a snapshot missing on ONTAP rejected: %s" % message) + + @attr(tags=[TAG], required_hardware=True) + def test_18_reject_create_on_disabled_pool(self): + """ + Disable the pool; createVolume from the snapshot is rejected. Enable the + pool again; the same snapshot now gives a Ready clone. + Verifies: + - no file is added to the FlexVol while the pool is Disabled + - after the pool is Up again, the clone is Ready as QCOW2 with its own file + """ + pool = self.__class__.pool + snap = self._take_volume_snapshot_when_accepted(self.__class__.volume.id) + + self._set_pool_enabled(pool.id, False) + try: + self._expect_clone_rejected(snap.id) + finally: + self._set_pool_enabled(pool.id, True) + + clone = self._create_clone(snap.id) + try: + self.assertEqual(self._db_volume_format(clone.id), "QCOW2", + "Clone is not QCOW2 in the volumes table") + self.assertTrue(self._clone_object_exists(clone), + "ONTAP file for the clone is missing") + finally: + self._remove_clone(clone) + self._wait_clone_object_gone(clone) + self._finish_volume_snapshot(snap.id) + + @attr(tags=[TAG], required_hardware=True) + def test_19_reject_nonexistent_snapshot(self): + """ + createVolume with a random snapshot UUID. + Verifies: + - the request is rejected as an unknown snapshotid + - no volume record is left behind and no file is added to the FlexVol + """ + message = self._expect_clone_rejected(str(uuid.uuid4())) + logger.info("test_19: createVolume from an unknown snapshot rejected: %s" % message) + self.assertIn("snapshotid", message.lower(), + "Rejection does not name snapshotid: %s" % message) + self.assertIn("does not exist", message.lower(), + "Rejection is not an unknown-snapshot error: %s" % message) + + @attr(tags=[TAG], required_hardware=True) + def test_20_reject_create_on_different_pool(self): + """ + Create a second NFS3 pool and disable the suite pool, so the second pool + is the only one the allocator can choose. createVolume ignores storageid + when snapshotid is given. The suite pool is enabled again and the second + pool removed at the end of the test. + Verifies: + - the request is rejected, because a snapshot can only be cloned on the + pool that holds it + - no usable volume record and no file in either pool's FlexVol + """ + pool_a = self.__class__.pool + snap = self._take_volume_snapshot_when_accepted(self.__class__.volume.id) + pool_b = self._create_pool() + try: + self._poll_pool_state(pool_b.id, "Up", timeout=120) + try: + self._set_pool_enabled(pool_a.id, False) + message = self._expect_clone_rejected(snap.id, pools=[pool_a, pool_b]) + logger.info("test_20: create on the other pool rejected: %s" % message) + finally: + self._set_pool_enabled(pool_a.id, True) + finally: + self._remove_pool(pool_b) + self._finish_volume_snapshot(snap.id) + + @attr(tags=[TAG], required_hardware=True) + def test_21_reject_create_with_missing_snapshot_metadata(self): + """ + For each snapshot_details row the clone needs: delete it, attempt the + create, then restore it. With every row restored, creation succeeds, so + each failure came from the missing row. The error text is not checked. + This test edits the management database directly; if the run dies between + a delete and its restore, the snapshot stays unusable. + Verifies: + - each attempt is rejected with no usable volume record and no file + - with every row restored, a volume is created from the snapshot + """ + snap = self._take_volume_snapshot_when_accepted(self.__class__.volume.id) + db = self.__class__.dbConnection + rows = db.execute("SELECT id FROM snapshots WHERE uuid = %s", params=(snap.id,)) + self.assertTrue(rows, "No snapshots row for uuid %s" % snap.id) + snap_db_id = rows[0][0] + + for key in REQUIRED_SNAPSHOT_DETAILS: + found = db.execute( + "SELECT id, value FROM snapshot_details WHERE snapshot_id = %s AND name = %s", + params=(snap_db_id, key)) + self.assertTrue(found, "snapshot_details '%s' missing before the test" % key) + detail_id, value = found[0][0], found[0][1] + + db.execute("DELETE FROM snapshot_details WHERE id = %s", params=(detail_id,)) + try: + message = self._expect_clone_rejected(snap.id) + logger.info("test_21: create without '%s' rejected: %s" % (key, message)) + finally: + db.execute( + "INSERT INTO snapshot_details (snapshot_id, name, value) " + "VALUES (%s, %s, %s)", params=(snap_db_id, key, value)) + + clone = self._create_clone(snap.id) + try: + self.assertTrue(self._clone_object_exists(clone), + "ONTAP file for the clone is missing after the metadata was restored") + finally: + self._remove_clone(clone) + self._wait_clone_object_gone(clone) + self._finish_volume_snapshot(snap.id) + + @attr(tags=[TAG], required_hardware=True) + def test_22_destroy_vm_and_cleanup(self): + """Destroy the VMs, delete the data volume and the pool.""" + self.step_27_destroy_vm_and_cleanup() + diff --git a/test/integration/plugins/ontap/ontap_test_base.py b/test/integration/plugins/ontap/ontap_test_base.py index eb36929651a8..1d41318f504b 100644 --- a/test/integration/plugins/ontap/ontap_test_base.py +++ b/test/integration/plugins/ontap/ontap_test_base.py @@ -553,6 +553,32 @@ def list_luns_in_volume(self, svm_name, vol_name): return [r for r in data.get("records", []) if r.get("name", "").startswith(prefix)] + def list_luns_with_clone(self, svm_name, vol_name): + """Return LUN records in the FlexVol, each with its ``clone`` object. + + A LUN created as a clone reports ``clone.created_as_clone`` true. The + REST GET does not return ``clone.source``. ``space.size`` is the LUN + size in bytes. + """ + prefix = "/vol/%s/" % vol_name + data = self._get("/storage/luns", + params={"svm.name": svm_name, + "fields": "name,uuid,clone,space.size"}) + return [r for r in data.get("records", []) + if r.get("name", "").startswith(prefix)] + + def delete_snapshot(self, vol_name, snap_name): + """Delete one FlexVol snapshot by name. Returns False if not found.""" + vol = self.get_volume(vol_name) + if not vol: + return False + for snap in self.list_snapshots(vol_name): + if snap.get("name") == snap_name: + self._delete("/storage/volumes/%s/snapshots/%s" + % (vol["uuid"], snap["uuid"])) + return True + return False + def list_lun_maps_for_volume(self, svm_name, vol_name): """Return all LUN-map records for LUNs residing in the given FlexVol.""" prefix = "/vol/%s/" % vol_name @@ -744,6 +770,26 @@ def delete_file_in_volume(self, vol_name, file_path): raise return True + def get_snapshot_record(self, vol_name, snap_name): + """Return the full REST record (all fields) for one FlexVol snapshot. + + Diagnostics only: when ONTAP refuses to delete a snapshot, the record + shows what still owns or uses it. Failures are reported as text rather + than hidden, so the log says which lookup failed: the FlexVol, the + snapshot, or the REST call itself. + """ + vol = self.get_volume(vol_name) + if not vol or not vol.get("uuid"): + return "FlexVol '%s' not found" % vol_name + data = self._get( + "/storage/volumes/%s/snapshots" % vol["uuid"], + params={"name": snap_name, "fields": "*"}, + ) + records = data.get("records", []) or [] + if not records: + return "no ONTAP snapshot named '%s' on FlexVol '%s'" % (snap_name, vol_name) + return records[0] + def list_snapshots(self, vol_name): """Return FlexVol snapshot records (name, uuid) for the named volume. @@ -904,7 +950,7 @@ class OntapTestBase(cloudstackTestCase): # and can be briefly unreachable afterwards, which makes a VM start fail # with "Unable to apply dhcp entry on router". Every wait and retry below # is bounded so a genuine failure is reported, never waited out forever. - ROUTER_HEALTHY_TIMEOUT = 180 # seconds, per wait + ROUTER_HEALTHY_TIMEOUT = 600 # seconds, per wait ROUTER_POLL_INTERVAL = 10 # seconds VM_START_ATTEMPTS = 3 # total tries, including the first VM_START_RETRY_DELAY = 15 # seconds between tries @@ -2367,3 +2413,19 @@ def _wait_for_vm_state(api_client, vm_id, target_state, timeout=120, return vm_obj time.sleep(interval) return vm_obj + + +def _is_rejected(exc): + """True when CloudStack or ONTAP refused the call because another one was in progress.""" + text = str(exc).lower() + return any(token in text for token in ( + "internal error", + "failed to create snapshot", + "failed to create instance snapshot", + "failed to revert", + "another operation", + "other active", + "try again later", + "in progress", + "busy", + )) From 9f2e04e7dbd6af6940468641b8d1411b0cc5680c Mon Sep 17 00:00:00 2001 From: sp16743 Date: Wed, 2 Dec 2026 15:16:52 +0530 Subject: [PATCH 2/5] Automation for Snapshot to Volume and Template --- .../nfs3/instance/test_vm_volume_attach.py | 1184 ++++++++++++++++- 1 file changed, 1132 insertions(+), 52 deletions(-) diff --git a/test/integration/plugins/ontap/nfs3/instance/test_vm_volume_attach.py b/test/integration/plugins/ontap/nfs3/instance/test_vm_volume_attach.py index 08d5f75db504..c3b7e36a7316 100644 --- a/test/integration/plugins/ontap/nfs3/instance/test_vm_volume_attach.py +++ b/test/integration/plugins/ontap/nfs3/instance/test_vm_volume_attach.py @@ -19,7 +19,7 @@ Sequential workflow integration tests for NetApp ONTAP data volume lifecycle with a running virtual machine. -Tests are numbered test_01 ... test_20, plus test_03a and test_03b, and must +Tests are numbered test_01 ... test_27, plus test_03a and test_03b, and must run in that order. Each step builds on the shared state established by the previous step. @@ -41,24 +41,34 @@ 07 Verify shrinking the volume is rejected without changing its size 08 Start the VM — VM Running; volume still attached; FlexVol online 09 Open an SSH port forward to the VM; write ROOT and DATA files - 10 Write before-s1; VM snapshot of the running VM (kept for step 12) - 11 Write before-s2, stop, VM snapshot (kept for step 12) - 12 Revert to the step-10 snapshot, then to the step-11 snapshot, then + 10 Snapshot the ROOT volume of the running VM + 11 Snapshot the DATA volume of the running VM (kept for step 14) + 12 Revert a volume snapshot while the VM is Running — rejected + 13 ROOT volume revert: write before-snapshot, snapshot, write + after-snapshot, revert, file is back to before-snapshot + 14 DATA: snapshot again, revert to the step-11 snapshot then to this + one, then delete both while the VM is still running + 15 Write before-s1; VM snapshot of the running VM (kept for step 17) + 16 Write before-s2, stop, VM snapshot (kept for step 17) + 17 Revert to the step-15 snapshot, then to the step-16 snapshot, then delete both while the VM is still running - 13 Two VM snapshot requests for the same VM at once — both succeed - 14 Deploy a second VM whose ROOT disk is on the same pool - 15 VM snapshots of both VMs at the same time - 16 VM snapshot of VM-A while VM-B reverts to its VM snapshot - 17 Detach the ONTAP data volume from the VM - 18 Grow the detached data volume - 19 Expunge the second VM while it still has a VM snapshot - 20 Destroy VM (cache still survives); delete ONTAP volume; enter + 18 Two VM snapshot requests for the same VM at once — both succeed + 19 Deploy a second VM whose ROOT disk is on the same pool + 20 Revert VM-A's ROOT; VM-B's file is unchanged + 21 VM snapshots of both VMs at the same time + 22 Volume snapshot of VM-A while VM-B's ROOT reverts + 23 VM snapshot of VM-A while VM-B reverts to its VM snapshot + 24 Detach the ONTAP data volume from the VM + 25 Grow the detached data volume + 26 Expunge the second VM while it still has a VM snapshot + 27 Destroy VM (cache still survives); delete ONTAP volume; enter maintenance; force-delete pool Snapshot steps only create and verify; tearDown deletes every snapshot the -step created and waits for its FlexVol snapshot to go. Steps 10 and 11 keep -their VM snapshots so step 12 can revert to them and then delete both while -the VM is running. +step created and waits for its FlexVol snapshot to go. Step 11 keeps its +DATA snapshot so step 14 can revert to it and then delete both DATA +snapshots while the VM is running. Steps 15 and 16 keep their VM snapshots +so step 17 can revert to them and then delete both while the VM is running. Guest login for the CentOS 5.5 template comes from ontap.cfg (cloudstack.templateUsername / templatePassword); see guest_ssh.py. @@ -77,35 +87,115 @@ Note: Tests share class-level state (sequential). Always run the full suite. """ +import base64 import logging import random import threading import time +import unittest from nose.plugins.attrib import attr from marvin.cloudstackAPI import ( + attachVolume as attachVolumeAPI, + createNetwork as createNetworkAPI, + createStoragePool as createStoragePoolAPI, + deleteNetwork as deleteNetworkAPI, + deleteVolume as deleteVolumeAPI, deployVirtualMachine as deployVirtualMachineAPI, destroyVirtualMachine as destroyVirtualMachineAPI, detachVolume as detachVolumeAPI, + enableStorageMaintenance, + listNetworkOfferings as listNetworkOfferingsAPI, + listNetworks as listNetworksAPI, + listVirtualMachines as listVirtualMachinesAPI, listVolumes as listVolumesAPI, stopVirtualMachine as stopVirtualMachineAPI, + updateStoragePool as updateStoragePoolAPI, ) -from marvin.lib.base import VmSnapshot +from marvin.lib.base import ServiceOffering, Snapshot, StoragePool, VmSnapshot, Volume +from marvin.lib.common import list_storage_pools -from guest_ssh import new_token +from guest_ssh import GuestSsh, guest_credentials, new_token, open_ssh_port +from ontap_test_base import OntapRestClient, OntapTestBase, _parse_pool_details, get_datacenter_config from helpers import template_cache_util as tcu - -from helpers.snapshot_base import OntapSnapshotBase -from ontap_test_base import _is_rejected, _list_vols_cmd - +from helpers.template_cache_base import ( + find_ready_kvm_template, + tagged_compute_offering_data, + template_cache_capacity_bytes, + template_cache_tags, +) logger = logging.getLogger("TestOntapVMVolumeAttach") TAG = "vm_volume_workflow" -class TestOntapVMVolumeAttach(OntapSnapshotBase): +# --------------------------------------------------------------------------- +# Test data +# --------------------------------------------------------------------------- + +class TestData: + account = "account" + ontap = "ontap" + primaryStorage = "primaryStorage" + provider = "provider" + scope = "scope" + tags = "tags" + + DETAIL_USERNAME = "username" + DETAIL_PASSWORD = "password" + DETAIL_SVM_NAME = "svmName" + DETAIL_PROTOCOL = "protocol" + DETAIL_STORAGE_IP = "storageIP" + + ONTAP_MIN_VOLUME_SIZE = 1677721600 + # Used when ontap.cfg has neither templateCacheCapacitybytes nor capacitybytes. + DEFAULT_POOL_SIZE = 50 * 1024 ** 3 + + def __init__(self, storage_ip, svm_name, username, password, + protocol="NFS3", scope="CLUSTER", provider="NetApp ONTAP", + tags="ontap-nfs3", capacitybytes=None): + if not capacitybytes: + capacitybytes = TestData.DEFAULT_POOL_SIZE + encoded_password = base64.b64encode(password.encode()).decode() + self.testdata = { + TestData.ontap: { + TestData.DETAIL_STORAGE_IP: storage_ip, + TestData.DETAIL_SVM_NAME: svm_name, + TestData.DETAIL_USERNAME: username, + TestData.DETAIL_PASSWORD: password, + }, + TestData.account: { + "email": "ontap-vm-vol@test.com", + "firstname": "ONTAP", + "lastname": "VMVol", + "username": "ontap_vm_vol_%d" % random.randint(0, 9999), + "password": "password", + }, + TestData.primaryStorage: { + "name": "OntapVMVol_%d" % random.randint(0, 9999), + TestData.scope: scope, + TestData.provider: provider, + TestData.tags: tags, + "capacitybytes": capacitybytes, + "managed": True, + "details": { + TestData.DETAIL_USERNAME: username, + TestData.DETAIL_PASSWORD: encoded_password, + TestData.DETAIL_SVM_NAME: svm_name, + TestData.DETAIL_PROTOCOL: protocol, + TestData.DETAIL_STORAGE_IP: storage_ip, + }, + }, + } + + +# --------------------------------------------------------------------------- +# Sequential workflow test class +# --------------------------------------------------------------------------- + +class TestOntapVMVolumeAttach(OntapTestBase): """ Tests ONTAP data volume lifecycle with a running CloudStack VM whose ROOT volume is on the ONTAP pool (primary template cache). @@ -115,6 +205,351 @@ class TestOntapVMVolumeAttach(OntapSnapshotBase): PROTOCOL = "NFS3" + # ---- extra shared state beyond OntapTestBase ----------------------- + vm = None # running VirtualMachine + vm2 = None # second VM used only to verify template-cache reuse + template_id = None # KVM template ID discovered at setup + template_db_id = None # numeric vm_template.id (template_spool_ref key) + pool_db_id = None # numeric storage_pool.id (template_spool_ref key) + service_offering_id = None + network_id = None # None for Basic zones + _created_network_id = None # network created by this suite for Advanced zones + initial_volume_size = None + target_volume_size = None + volume_path = None + vm_ssh = None # (public_ip, public_port) forwarded to vm:22 + vm2_ssh = None + vm_snap_running = None # step 15 snapshot, reused by step 17 + vm_snap_stopped = None # step 16 snapshot, reused by step 17 + token_s1 = None + token_s2 = None + kept_ontap_snaps = None + data_snap_older = None # step 11 DATA snapshot, reused by step 14 + data_token_older = None + kept_data_ontap_snaps = None + guest_user = "root" + guest_password = "password" + + _vol_name_prefix = "OntapVMVol" + + # ---- setup --------------------------------------------------------- + + @classmethod + def setUpClass(cls): + super(TestOntapVMVolumeAttach, cls).setUpClass() + testclient = super( + TestOntapVMVolumeAttach, cls + ).getClsTestClient() + + cls.apiClient = testclient.getApiClient() + cls.dbConnection = testclient.getDbConnection() + config = get_datacenter_config(testclient, cls) + + ontap_cfg = config.get("ontap", {}) + pool_cfg = config.get("storagePool", {}) + storage_ip = ontap_cfg.get("storageIP", "") + svm_name = ontap_cfg.get("svmName", "") + username = ontap_cfg.get("username", "") + password = ontap_cfg.get("password", "") + nfs3_cfg = pool_cfg.get("protocols", {}).get("nfs3", {}) + if not nfs3_cfg.get("enabled", True): + raise unittest.SkipTest( + "NFS3 tests disabled in ontap.cfg " + "(set protocols.nfs3.enabled=true to enable)" + ) + protocol = "NFS3" + scope = pool_cfg.get("storagePoolScope", "CLUSTER") + provider = pool_cfg.get("storagePoolProvider", "NetApp ONTAP") + # Dedicated tag shared by the pool and the compute offering so the + # VM's ROOT volume is placed on this ONTAP pool (template cache path). + tags = template_cache_tags(nfs3_cfg, "nfs3") + capacitybytes = template_cache_capacity_bytes(pool_cfg) + + cls.testdata = TestData( + storage_ip, svm_name, username, password, + protocol=protocol, scope=scope, provider=provider, + tags=tags, capacitybytes=capacitybytes, + ).testdata + cls.ontap = OntapRestClient(storage_ip, username, password) + cls.svm_name = svm_name + + cls._setup_cloudstack_resources(config, cls.testdata[TestData.account]) + + cls.guest_user, cls.guest_password = guest_credentials(config) + + # Discover a suitable user KVM template in the zone (must be fully + # downloaded; system-type templates are excluded as they cannot be + # deployed as user VMs). + template = find_ready_kvm_template(cls.apiClient, cls.zone.id) + if template is not None: + cls.template_id = template.id + cls.template_db_id = tcu.get_db_id( + cls.dbConnection, "vm_template", cls.template_id + ) + else: + logger.warning( + "No ready user KVM template found in zone '%s'. " + "Tests that deploy VMs will be skipped until a template " + "finishes downloading." % cls.zone.name + ) + cls.template_id = None + + service_offering = ServiceOffering.create( + cls.apiClient, tagged_compute_offering_data(tags, "OntapNFS3VMSO") + ) + cls._cleanup.append(service_offering) + cls.service_offering_id = service_offering.id + + # Detect zone type; resolve network ID for Advanced zones + cls.network_id = None + zone_type = getattr(cls.zone, "networktype", "Basic") + if zone_type.lower() == "advanced": + # Find a network already accessible to the test account + net_cmd = listNetworksAPI.listNetworksCmd() + net_cmd.zoneid = cls.zone.id + net_cmd.account = cls.account.name + net_cmd.domainid = cls.domain.id + nets = cls.apiClient.listNetworks(net_cmd) or [] + if nets: + cls.network_id = nets[0].id + else: + # Create an Isolated guest network for the test account + no_cmd = listNetworkOfferingsAPI.listNetworkOfferingsCmd() + no_cmd.state = "Enabled" + no_cmd.guestiptype = "Isolated" + no_cmd.specifyvlan = "false" + no_offerings = cls.apiClient.listNetworkOfferings(no_cmd) or [] + snat_offering = next( + (o for o in no_offerings + if "SourceNat" in o.name and "Vpc" not in o.name + and "NSX" not in o.name and "Netris" not in o.name), + no_offerings[0] if no_offerings else None + ) + if snat_offering: + cn_cmd = createNetworkAPI.createNetworkCmd() + cn_cmd.zoneid = cls.zone.id + cn_cmd.networkofferingid = snat_offering.id + cn_cmd.name = "ontap-nfs3-vm-net-%d" % random.randint( + 0, 9999) + cn_cmd.displaytext = "ONTAP NFS3 VM test network" + cn_cmd.account = cls.account.name + cn_cmd.domainid = cls.domain.id + net = cls.apiClient.createNetwork(cn_cmd) + cls.network_id = net.id + cls._created_network_id = net.id + + @classmethod + def tearDownClass(cls): + """Destroy the VMs first, then delegate pool/volume cleanup to super.""" + cls._delete_kept_data_snapshot() + cls._delete_kept_vm_snapshots() + for vm in (cls.vm2, cls.vm): + if vm is None: + continue + try: + cls._stop_and_expunge_vm(vm.id) + except Exception as e: + logger.warning("tearDownClass: could not stop/destroy VM %s: " + "%s" % (vm.id, e)) + try: + dest_cmd = destroyVirtualMachineAPI.destroyVirtualMachineCmd() + dest_cmd.id = vm.id + dest_cmd.expunge = True + cls.apiClient.destroyVirtualMachine(dest_cmd) + except Exception as de: + logger.warning("tearDownClass: could not destroy VM %s: " + "%s" % (vm.id, de)) + cls.vm2 = None + cls.vm = None + + # Delete the guest network created for this account in Advanced zones. + if cls._created_network_id is not None: + try: + dn_cmd = deleteNetworkAPI.deleteNetworkCmd() + dn_cmd.id = cls._created_network_id + cls.apiClient.deleteNetwork(dn_cmd) + cls._created_network_id = None + except Exception as e: + logger.warning( + "tearDownClass: could not delete network %s: %s" + % (cls._created_network_id, e)) + + super(TestOntapVMVolumeAttach, cls).tearDownClass() + + @classmethod + def _stop_and_expunge_vm(cls, vm_id): + """Force-stop the VM if needed, then destroy it with expunge.""" + vms = cls.apiClient.listVirtualMachines(_list_vms_cmd(vm_id)) + current_state = vms[0].state if vms else "unknown" + if current_state.lower() not in ("stopped", "destroyed", + "expunging", "error"): + stop_cmd = stopVirtualMachineAPI.stopVirtualMachineCmd() + stop_cmd.id = vm_id + stop_cmd.forced = True + cls.apiClient.stopVirtualMachine(stop_cmd) + _wait_for_vm_state(cls.apiClient, vm_id, "Stopped", timeout=120) + dest_cmd = destroyVirtualMachineAPI.destroyVirtualMachineCmd() + dest_cmd.id = vm_id + dest_cmd.expunge = True + cls.apiClient.destroyVirtualMachine(dest_cmd) + + # ---- pool creation helper ----------------------------------------- + + def _create_pool(self): + ps = self.testdata[TestData.primaryStorage] + storage_ip = self.testdata[TestData.ontap][TestData.DETAIL_STORAGE_IP] + pool_name = "OntapVMVol_%d" % random.randint(0, 99999) + + cmd = createStoragePoolAPI.createStoragePoolCmd() + cmd.name = pool_name + cmd.url = "nfs://%s/ontap" % storage_ip + cmd.zoneid = self.zone.id + cmd.clusterid = self.cluster.id + cmd.podid = self.cluster.podid + cmd.scope = ps[TestData.scope] + cmd.provider = ps[TestData.provider] + cmd.tags = ps[TestData.tags] + cmd.capacitybytes = ps["capacitybytes"] + cmd.hypervisor = "KVM" + cmd.managed = True + + count = 1 + for key, value in ps["details"].items(): + setattr(cmd, "details[{}].{}".format(count, key), value) + count += 1 + + response = self.apiClient.createStoragePool(cmd) + return StoragePool(response.__dict__) + + # ---- VM state helpers ---------------------------------------------- + + def _volume_state(self, vol_id): + """Return the current CloudStack state string for a volume.""" + cmd = listVolumesAPI.listVolumesCmd() + cmd.id = vol_id + vols = self.apiClient.listVolumes(cmd) + return vols[0].state if vols else "unknown" + + # ---- snapshot step helpers (steps 09-23) --------------------------- + + def setUp(self): + super(TestOntapVMVolumeAttach, self).setUp() + self._volume_snapshot_ids = [] + self._vm_snapshot_ids = [] + self._extra_volume_ids = [] + self._created_ontap_snaps = set() + + def tearDown(self): + """ + Delete the snapshots and extra volumes a step created, then check + their FlexVol snapshots are gone from ONTAP. + """ + for snap_id in self._vm_snapshot_ids: + try: + VmSnapshot.deleteVMSnapshot(self.apiClient, snap_id) + except Exception as exc: + logger.warning("tearDown: VM snapshot %s: %s" % (snap_id, exc)) + self._delete_failed_vm_snapshots() + for snap_id in self._volume_snapshot_ids: + try: + Snapshot({"id": snap_id}).delete(self.apiClient) + except Exception as exc: + logger.warning("tearDown: volume snapshot %s: %s" % (snap_id, exc)) + for vol_id in self._extra_volume_ids: + try: + cmd = deleteVolumeAPI.deleteVolumeCmd() + cmd.id = vol_id + self.apiClient.deleteVolume(cmd) + except Exception as exc: + logger.warning("tearDown: volume %s: %s" % (vol_id, exc)) + if self._created_ontap_snaps and not self._wait_ontap_snaps_gone( + self._created_ontap_snaps, fail=False): + logger.warning("tearDown: FlexVol snapshots still present: %s" + % sorted(self._created_ontap_snaps)) + super(TestOntapVMVolumeAttach, self).tearDown() + + @classmethod + def _destroy_second_vm(cls): + if cls.vm2 is None: + return + try: + cmd = destroyVirtualMachineAPI.destroyVirtualMachineCmd() + cmd.id = cls.vm2.id + cmd.expunge = True + cls.apiClient.destroyVirtualMachine(cmd) + except Exception as exc: + logger.warning("Could not destroy second VM %s: %s" % (cls.vm2.id, exc)) + cls.vm2 = None + cls.vm2_ssh = None + + @classmethod + def _delete_kept_vm_snapshots(cls): + """Delete the step 15/16 snapshots when step 17 did not take them over.""" + for snap in (cls.vm_snap_running, cls.vm_snap_stopped): + if snap is None: + continue + try: + VmSnapshot.deleteVMSnapshot(cls.apiClient, snap.id) + except Exception as exc: + logger.warning("tearDownClass: VM snapshot %s: %s" % (snap.id, exc)) + cls.vm_snap_running = None + cls.vm_snap_stopped = None + cls.token_s1 = None + cls.token_s2 = None + cls.kept_ontap_snaps = set() + + @classmethod + def _delete_kept_data_snapshot(cls): + """Delete the step 11 DATA snapshot when step 14 did not take it over.""" + snap = cls.data_snap_older + if snap is None: + return + try: + Snapshot({"id": snap.id}).delete(cls.apiClient) + except Exception as exc: + logger.warning("tearDownClass: volume snapshot %s: %s" % (snap.id, exc)) + cls.data_snap_older = None + cls.data_token_older = None + cls.kept_data_ontap_snaps = set() + + def _keep_data_snapshot(self, snap, ontap_names, token): + """Leave the step 11 DATA snapshot in place for step 14.""" + if snap.id in self._volume_snapshot_ids: + self._volume_snapshot_ids.remove(snap.id) + names = set(ontap_names) + self._created_ontap_snaps -= names + self.__class__.data_snap_older = snap + self.__class__.data_token_older = token + self.__class__.kept_data_ontap_snaps = names + + def _adopt_kept_data_snapshot(self): + """Hand the step 11 DATA snapshot to step 14.""" + snap = self.__class__.data_snap_older + token = self.__class__.data_token_older + if snap is None or not token: + self.skipTest("DATA snapshot from test_11 is required") + ontap_names = set(self.__class__.kept_data_ontap_snaps or []) + self._volume_snapshot_ids.append(snap.id) + self._created_ontap_snaps |= ontap_names + self.__class__.data_snap_older = None + self.__class__.data_token_older = None + self.__class__.kept_data_ontap_snaps = set() + return snap, token, ontap_names + + def _delete_volume_snapshot_while_running(self, vm, snap, ontap_names, token): + """Delete a volume snapshot while its VM is still running.""" + Snapshot({"id": snap.id}).delete(self.apiClient) + if snap.id in self._volume_snapshot_ids: + self._volume_snapshot_ids.remove(snap.id) + names = set(ontap_names) + self._created_ontap_snaps -= names + self._wait_until_gone( + lambda: self._volume_snapshot_listed(snap.id), + "Volume snapshot %s still listed after delete" % snap.id) + self._wait_ontap_snaps_gone(names) + self.assertEqual(self._vm_state(vm.id), "Running") + self._assert_marker(token, disk="DATA", msg="after volume snapshot delete") + def _delete_vm_snapshot_while_running(self, vm, snap, ontap_names, token): """Delete a VM snapshot while that VM is still running.""" VmSnapshot.deleteVMSnapshot(self.apiClient, snap.id) @@ -137,7 +572,7 @@ def _ontap_names_for_snap(self, names, snap, kind): return {name for name in names if str(name).endswith(suffix)} def _keep_vm_snapshot(self, snap, ontap_names, which): - """Leave this VM snapshot in place for step 12.""" + """Leave this VM snapshot in place for step 17.""" if snap.id in self._vm_snapshot_ids: self._vm_snapshot_ids.remove(snap.id) names = set(ontap_names) @@ -150,13 +585,13 @@ def _keep_vm_snapshot(self, snap, ontap_names, which): setattr(self.__class__, which, snap) def _adopt_kept_vm_snapshots(self): - """Hand the step 10 and 11 snapshots to this step's tearDown.""" + """Hand the step 15 and 16 snapshots to this step's tearDown.""" s1 = self.__class__.vm_snap_running s2 = self.__class__.vm_snap_stopped token_a = self.__class__.token_s1 token_b = self.__class__.token_s2 if s1 is None or s2 is None or not token_a or not token_b: - self.skipTest("VM snapshots from test_10 and test_11 are required") + self.skipTest("VM snapshots from test_15 and test_16 are required") ontap_names = set(self.__class__.kept_ontap_snaps or []) self._vm_snapshot_ids.extend([s1.id, s2.id]) self._created_ontap_snaps |= ontap_names @@ -167,6 +602,184 @@ def _adopt_kept_vm_snapshots(self): self.__class__.kept_ontap_snaps = set() return s1, s2, token_a, token_b, ontap_names + def _require_snapshot_vm(self, ssh=True): + if self.__class__.vm is None: + self.skipTest("VM not deployed — test_03 was skipped (no ready template)") + if ssh and self.__class__.vm_ssh is None: + self.skipTest("Guest SSH not set up — test_09 must pass first") + self._start_vm(self.__class__.vm.id) + return self.__class__.vm + + def _require_second_vm(self): + self._require_snapshot_vm() + if self.__class__.vm2 is None or self.__class__.vm2_ssh is None: + self.skipTest("Second VM not deployed — test_19 must pass first") + self._start_vm(self.__class__.vm2.id) + return self.__class__.vm2 + + def _vm_state(self, vm_id): + vms = self.apiClient.listVirtualMachines(_list_vms_cmd(vm_id)) + return vms[0].state if vms else None + + def _stop_vm(self, vm_id): + if (self._vm_state(vm_id) or "").lower() == "stopped": + return + cmd = stopVirtualMachineAPI.stopVirtualMachineCmd() + cmd.id = vm_id + cmd.forced = True + self.apiClient.stopVirtualMachine(cmd) + self._poll_vm_state(vm_id, "Stopped", timeout=600) + + def _root_volume(self, vm_id): + cmd = listVolumesAPI.listVolumesCmd() + cmd.virtualmachineid = vm_id + cmd.type = "ROOT" + cmd.listall = True + vols = self.apiClient.listVolumes(cmd) or [] + self.assertTrue(vols, "No ROOT volume found for VM %s" % vm_id) + return vols[0] + + def _guest(self, which="vm"): + host, port = getattr(self.__class__, "%s_ssh" % which) + return GuestSsh(host, port, self.guest_user, self.guest_password) + + def _write_marker(self, token, which="vm", disks=("ROOT",)): + with self._guest(which) as guest: + if "ROOT" in disks: + guest.write_root_marker(token) + if "DATA" in disks: + guest.write_data_marker(token) + + def _assert_marker(self, token, which="vm", disk="ROOT", msg=""): + with self._guest(which) as guest: + found = guest.read_data_marker() if disk == "DATA" else guest.read_root_marker() + self.assertEqual(found, token, "%s: %s marker on %s is %r, expected %r" + % (msg, disk, which, found, token)) + + def _ontap_snap_names(self): + return {s.get("name") for s in self.ontap.list_snapshots(self.__class__.pool.name)} + + def _assert_new_ontap_snaps(self, before, snaps, kind, msg): + """Return the FlexVol snapshot created for each CloudStack snapshot. + + A volume snapshot is stored as ``..._cs`` and a VM snapshot as + ``..._vm``. ONTAP snapshots from its own schedule, such as + ``hourly.*`` or ``Anti_ransomware_*``, are ignored. + """ + new = self._ontap_snap_names() - before + prefix = "cs" if kind == "volume" else "vm" + table = "snapshots" if kind == "volume" else "vm_snapshots" + matched = set() + missing = [] + for snap in snaps: + db_id = tcu.get_db_id(self.dbConnection, table, snap.id) + suffix = "_%s%s" % (prefix, db_id) + hits = sorted(name for name in new if name.endswith(suffix)) + if len(hits) != 1: + missing.append("%s (suffix %s, matches %s)" % (snap.id, suffix, hits)) + else: + matched.add(hits[0]) + self.assertFalse( + missing, + "%s: FlexVol snapshot missing for %s; new FlexVol snapshots: %s" + % (msg, missing, sorted(new))) + ignored = new - matched + if ignored: + logger.info("%s: ignoring FlexVol snapshots not created by this step: %s", + msg, sorted(ignored)) + self._created_ontap_snaps |= matched + return matched + + def _assert_ontap_snaps_present(self, names, msg): + missing = set(names) - self._ontap_snap_names() + self.assertFalse(missing, "%s: FlexVol snapshots missing: %s" % (msg, sorted(missing))) + + def _wait_ontap_snaps_gone(self, names, timeout=180, fail=True): + names = set(names) + deadline = time.time() + timeout + left = names + while time.time() < deadline: + left = names & self._ontap_snap_names() + if not left: + return True + time.sleep(5) + if fail: + self.fail("FlexVol snapshots %s still present after %ds" % (sorted(left), timeout)) + return False + + def _take_volume_snapshot(self, volume_id): + snap = Snapshot.create(self.apiClient, volume_id, + account=self.account.name, domainid=self.domain.id) + self._volume_snapshot_ids.append(snap.id) + self.assertEqual(snap.state, "BackedUp", + "Volume snapshot %s is %s, expected BackedUp" % (snap.id, snap.state)) + return snap + + def _take_vm_snapshot(self, vm_id): + snap = VmSnapshot.create(self.apiClient, vm_id, snapshotmemory="false", + name="ontap_%d" % random.randint(0, 999999)) + self._vm_snapshot_ids.append(snap.id) + self.assertEqual(snap.state, "Ready", + "VM snapshot %s is %s, expected Ready" % (snap.id, snap.state)) + return snap + + def _vm_snapshots_of(self, vm_id): + return VmSnapshot.list(self.apiClient, virtualmachineid=vm_id, listall=True) or [] + + def _delete_failed_vm_snapshots(self): + """Delete VM snapshots left in Error by a rejected create. + + A rejected createVMSnapshot (ONTAP refusing while a revert's clones + exist) leaves its record behind with no id the test ever saw. Any + Instance Snapshot, even in Error, blocks detach, resize and destroy. + """ + for vm in (self.__class__.vm, self.__class__.vm2): + if vm is None: + continue + try: + stale = [s for s in self._vm_snapshots_of(vm.id) + if (getattr(s, "state", "") or "").lower() == "error"] + except Exception as exc: + logger.warning("tearDown: could not list VM snapshots of %s: %s" + % (vm.id, exc)) + continue + for snap in stale: + try: + VmSnapshot.deleteVMSnapshot(self.apiClient, snap.id) + except Exception as exc: + logger.warning("tearDown: failed VM snapshot %s: %s" + % (snap.id, exc)) + + def _volume_snapshot_listed(self, snap_id): + listed = Snapshot.list(self.apiClient, id=snap_id, listall=True) or [] + return any(getattr(item, "id", None) == snap_id for item in listed) + + def _wait_until_gone(self, still_there, msg, timeout=180): + deadline = time.time() + timeout + while time.time() < deadline and still_there(): + time.sleep(5) + self.assertFalse(still_there(), msg) + + def _volume_revert_flow(self, disk): + """Write A, snapshot, write B, stop, revert, start; expect A.""" + vm = self._require_snapshot_vm() + volume_id = (self.__class__.volume.id if disk == "DATA" + else self._root_volume(vm.id).id) + token_a = new_token("before-volume-snapshot") + token_b = new_token("after-volume-snapshot") + self._write_marker(token_a, disks=(disk,)) + before = self._ontap_snap_names() + snap = self._take_volume_snapshot(volume_id) + new = self._assert_new_ontap_snaps(before, [snap], "volume", "%s volume snapshot" % disk) + self._write_marker(token_b, disks=(disk,)) + + self._stop_vm(vm.id) + Volume.revertToSnapshot(self.apiClient, snap.id) + self._assert_ontap_snaps_present(new, "after revert") + self._start_vm(vm.id) + self._assert_marker(token_a, disk=disk, + msg="after revert (write after snapshot was %s)" % token_b) + # ================================================================== # Test steps # ================================================================== @@ -183,7 +796,27 @@ def test_01_create_nfs3_pool(self): - Pool reaches 'Up' state in CloudStack - ONTAP: FlexVol is created and online """ - self.step_01_create_pool() + pool = self._create_pool() + self.__class__.pool = pool + self.__class__.pool_db_id = tcu.get_db_id( + self.dbConnection, "storage_pool", pool.id + ) + + self.assertEqual( + pool.state, "Up", + "Pool state should be 'Up', got '%s'" % pool.state + ) + + ontap_vol = self.ontap.get_volume(pool.name) + self.assertIsNotNone( + ontap_vol, + "ONTAP FlexVol not created for pool '%s'" % pool.name + ) + self.assertEqual( + ontap_vol.get("state"), "online", + "ONTAP FlexVol should be 'online', got '%s'" + % ontap_vol.get("state") + ) # ------------------------------------------------------------------ # Step 02 - Create CloudStack data volume on ONTAP pool @@ -197,7 +830,29 @@ def test_02_create_ontap_data_volume(self): - Volume is created and in 'Allocated' or 'Ready' state - ONTAP: FlexVol remains online """ - self.step_02_create_ontap_data_volume() + self.assertIsNotNone(self.__class__.pool, + "Pool absent — test_01 must pass first") + + pool = self.__class__.pool + vol = self._create_volume(pool.id) + self.__class__.volume = vol + self.assertIsNotNone(vol, "createVolume returned None") + + vol_state = self._volume_state(vol.id) + self.assertIn( + vol_state.lower(), ("allocated", "ready"), + "Volume should be 'Allocated' or 'Ready', got '%s'" % vol_state + ) + + ontap_vol = self.ontap.get_volume(pool.name) + self.assertIsNotNone( + ontap_vol, + "ONTAP FlexVol disappeared after data volume creation" + ) + self.assertEqual( + ontap_vol.get("state"), "online", + "ONTAP FlexVol should still be 'online' after volume creation" + ) # ------------------------------------------------------------------ # Step 03 - Deploy a VM @@ -214,7 +869,39 @@ def test_03_deploy_vm(self): - template_spool_ref for pool + template is Ready / DOWNLOADED - ONTAP: template cache file exists at the spool install_path """ - self.step_03_deploy_vm() + self.assertIsNotNone(self.__class__.pool, + "Pool absent — test_01 must pass first") + if self.__class__.template_id is None: + self.skipTest( + "No ready user KVM template available — " + "waiting for template download to complete" + ) + self.assertIsNotNone(self.__class__.service_offering_id, + "No service offering available — check setup") + + cmd = deployVirtualMachineAPI.deployVirtualMachineCmd() + cmd.zoneid = self.zone.id + cmd.templateid = self.__class__.template_id + cmd.serviceofferingid = self.__class__.service_offering_id + cmd.account = self.account.name + cmd.domainid = self.domain.id + if self.__class__.network_id: + cmd.networkids = self.__class__.network_id + + vm = self._deploy_vm(cmd) + self.assertIsNotNone(vm, "deployVirtualMachine returned None") + self.__class__.vm = vm + + vm_obj = self._poll_vm_state(vm.id, "Running") + self.assertEqual( + vm_obj.state, "Running", + "VM should be 'Running', got '%s'" % vm_obj.state + ) + + pool = self.__class__.pool + self._assert_root_on_pool(vm.id, pool) + spool = self._wait_for_ready_spool_ref(self.__class__.pool_db_id) + self._assert_cache_on_ontap(pool, spool) # ------------------------------------------------------------------ # Step 03a - Deploy a second VM — reuses the template cache @@ -290,7 +977,78 @@ def test_04_attach_volume_to_vm(self): - ONTAP: NFS3 volume data file created in FlexVol after attach (lazy creation) - VM remains 'Running' """ - self.step_04_attach_volume_to_vm() + if self.__class__.vm is None: + self.skipTest("VM not deployed — test_03 was skipped (no ready template)") + self.assertIsNotNone(self.__class__.volume, + "Volume absent — test_02 must pass first") + + vm = self.__class__.vm + vol = self.__class__.volume + + cmd = attachVolumeAPI.attachVolumeCmd() + cmd.id = vol.id + cmd.virtualmachineid = vm.id + attached = self.apiClient.attachVolume(cmd) + self.assertIsNotNone(attached, "attachVolume returned None") + + # On ONTAP/NFS shared storage CloudStack does not transition the volume + # state to 'In Use' — attachment is indicated by virtualmachineid being + # set on the volume record. Poll on that field instead of state. + deadline = time.time() + 120 + vol_vmid = None + while time.time() < deadline: + vols = self.apiClient.listVolumes(_list_vols_cmd(vol.id)) + vol_vmid = getattr(vols[0], "virtualmachineid", None) if vols else None + if vol_vmid: + break + time.sleep(5) + + self.assertEqual( + vol_vmid, vm.id, + "Volume should be attached to VM %s after attach, " + "got virtualmachineid=%s" % (vm.id, vol_vmid) + ) + + # VM must still be Running + vm_obj = self._poll_vm_state(vm.id, "Running", timeout=30) + self.assertEqual(vm_obj.state, "Running", + "VM should still be 'Running' after volume attach") + + # ONTAP FlexVol must remain online + pool = self.__class__.pool + ontap_vol = self.ontap.get_volume(pool.name) + self.assertIsNotNone(ontap_vol, "ONTAP FlexVol not found after attach") + self.assertEqual( + ontap_vol.get("state"), "online", + "ONTAP FlexVol should be 'online' after attach" + ) + + # ONTAP: NFS3 uses lazy file creation — the volume data file is + # materialised on the FlexVol only when CloudStack calls createAsync + # during attachVolume. Verify that the file now exists. + files = self.ontap.list_files_in_volume(pool.name) + vol_file = next((f for f in files if vol.id in f), None) + self.assertIsNotNone( + vol_file, + "No data file matching volume UUID '%s' found in FlexVol '%s' " + "after attach; files present: %s" % (vol.id, pool.name, files) + ) + + volumes = self.apiClient.listVolumes(_list_vols_cmd(vol.id)) or [] + self.assertTrue(volumes, "Attached volume is not listed in CloudStack") + initial_size = int(volumes[0].size) + self.__class__.initial_volume_size = initial_size + self.__class__.target_volume_size = ( + (initial_size // (1024 ** 3)) + 1 + ) * (1024 ** 3) + self.__class__.volume_path = vol_file + + backend_size = self._get_qcow2_virtual_size(pool.id, vol_file) + self.assertEqual( + backend_size, initial_size, + "Initial qcow2 virtual size should match the CloudStack volume size" + ) + # ------------------------------------------------------------------ # Step 05 - Stop VM — export policy must be retained @@ -511,6 +1269,7 @@ def test_08_start_vm_volume_accessible(self): self.__class__.target_volume_size, "KVM data-disk capacity does not reflect the NFS3 resize") + # ------------------------------------------------------------------ # Step 09 - Guest SSH access for snapshot checks # ------------------------------------------------------------------ @@ -525,17 +1284,136 @@ def test_09_open_ssh_and_write_root_data_files(self): through a port forward on the network's source-NAT IP - The DATA disk can be formatted, mounted and written """ - self.step_09_open_ssh_and_write_root_data_files() + vm = self._require_snapshot_vm(ssh=False) + if not self.__class__.network_id: + self.skipTest("Snapshot steps need an Advanced zone guest network for SSH") + pool_id = self.__class__.pool.id + root = self._root_volume(vm.id) + self.assertEqual(getattr(root, "storageid", None), pool_id, + "ROOT volume is on '%s', not the ONTAP test pool" + % getattr(root, "storage", None)) + vols = self.apiClient.listVolumes(_list_vols_cmd(self.__class__.volume.id)) or [] + self.assertTrue(vols and getattr(vols[0], "virtualmachineid", None) == vm.id, + "DATA volume must be attached before the snapshot steps") + + host, port, _ = open_ssh_port(self.apiClient, vm.id, self.__class__.network_id) + self.__class__.vm_ssh = (host, port) + token = new_token("ssh-access-test") + self._write_marker(token, disks=("ROOT", "DATA")) + self._assert_marker(token, disk="ROOT", msg="guest access") + self._assert_marker(token, disk="DATA", msg="guest access") + + # ------------------------------------------------------------------ + # Steps 08-12 - Volume snapshots + # ------------------------------------------------------------------ + + @attr(tags=[TAG], required_hardware=True) + def test_10_root_volume_snapshot_create(self): + """ + VS-01: snapshot the ROOT volume of the running VM. + Verifies: state BackedUp; VM stays Running; one new FlexVol snapshot. + """ + vm = self._require_snapshot_vm() + before = self._ontap_snap_names() + snap = self._take_volume_snapshot(self._root_volume(vm.id).id) + self.assertEqual(self._vm_state(vm.id), "Running") + self._assert_new_ontap_snaps(before, [snap], "volume", "ROOT volume snapshot") + + @attr(tags=[TAG], required_hardware=True) + def test_11_data_volume_snapshot_create(self): + """ + VS-03: snapshot the attached DATA volume. + The snapshot is kept for step 14. + Verifies: state BackedUp; VM stays Running; one new FlexVol snapshot. + """ + vm = self._require_snapshot_vm() + token = new_token("data-s1") + self._write_marker(token, disks=("DATA",)) + before = self._ontap_snap_names() + snap = self._take_volume_snapshot(self.__class__.volume.id) + self.assertEqual(self._vm_state(vm.id), "Running") + new = self._assert_new_ontap_snaps(before, [snap], "volume", "DATA volume snapshot") + self._keep_data_snapshot(snap, new, token) + + @attr(tags=[TAG], required_hardware=True) + def test_12_volume_revert_running_vm_rejected(self): + """ + VS-19: reverting a volume snapshot while the VM is Running fails. + Verifies: error says the Instance is not shut down; VM stays Running; + the FlexVol snapshot remains. + """ + vm = self._require_snapshot_vm() + before = self._ontap_snap_names() + snap = self._take_volume_snapshot(self._root_volume(vm.id).id) + new = self._assert_new_ontap_snaps(before, [snap], "volume", "ROOT volume snapshot") + with self.assertRaises(Exception) as ctx: + Volume.revertToSnapshot(self.apiClient, snap.id) + self.assertIn("shutdown", str(ctx.exception).lower(), + "Unexpected error: %s" % ctx.exception) + self.assertEqual(self._vm_state(vm.id), "Running") + self._assert_ontap_snaps_present(new, "after rejected revert") + + @attr(tags=[TAG], required_hardware=True) + def test_13_root_volume_revert(self): + """ + VS-11: write A, snapshot ROOT, write B, stop, revert, start. + Verifies: ROOT marker is A; the FlexVol snapshot survives the revert. + """ + self._volume_revert_flow("ROOT") + + @attr(tags=[TAG], required_hardware=True) + def test_14_data_volume_revert(self): + """ + Take a second DATA snapshot, revert to the step 11 snapshot, then to + this later one, and delete both while the VM is still running. + Verifies: + - After revert to the older snapshot, the DATA marker is the step 11 + token and the later snapshot is still listed + - After revert to the later snapshot, the DATA marker is that token + - Both snapshots and their FlexVol snapshots are gone; the VM stays + Running and the later marker is unchanged + """ + vm = self._require_snapshot_vm() + older, token_older, ontap_older = self._adopt_kept_data_snapshot() + token_latest = new_token("data-s2") + self._write_marker(token_latest, disks=("DATA",)) + before = self._ontap_snap_names() + latest = self._take_volume_snapshot(self.__class__.volume.id) + ontap_latest = self._assert_new_ontap_snaps( + before, [latest], "volume", "latest DATA snapshot") + self._write_marker(new_token("data-after-both"), disks=("DATA",)) + + self._stop_vm(vm.id) + Volume.revertToSnapshot(self.apiClient, older.id) + self._start_vm(vm.id) + self._assert_marker(token_older, disk="DATA", + msg="after revert to the older snapshot") + self.assertTrue( + self._volume_snapshot_listed(latest.id), + "The later volume snapshot should still exist") + self._assert_ontap_snaps_present( + ontap_older | ontap_latest, "after revert to the older snapshot") + + self._stop_vm(vm.id) + Volume.revertToSnapshot(self.apiClient, latest.id) + self._start_vm(vm.id) + self._assert_marker(token_latest, disk="DATA", + msg="after revert to the latest snapshot") + + self._delete_volume_snapshot_while_running( + vm, latest, ontap_latest, token_latest) + self._delete_volume_snapshot_while_running( + vm, older, ontap_older, token_latest) # ------------------------------------------------------------------ - # Steps 10-13 - VM snapshots + # Steps 13-16 - VM snapshots # ------------------------------------------------------------------ @attr(tags=[TAG], required_hardware=True) - def test_10_vm_snapshot_create_running(self): + def test_15_vm_snapshot_create_running(self): """ VMS-01: VM snapshot of the running VM (ROOT + DATA on one FlexVol). - Writes before-s1, then snapshots. The snapshot is kept for step 12. + Writes before-s1, then snapshots. The snapshot is kept for step 17. Verifies: state Ready; VM stays Running; one new FlexVol snapshot. """ vm = self._require_snapshot_vm() @@ -548,11 +1426,11 @@ def test_10_vm_snapshot_create_running(self): self._keep_vm_snapshot(snap, new, "vm_snap_running") @attr(tags=[TAG], required_hardware=True) - def test_11_vm_snapshot_create_stopped(self): + def test_16_vm_snapshot_create_stopped(self): """ VMS-03: VM snapshot of the stopped VM. Writes before-s2 while Running, then stops and snapshots. - The snapshot is kept for step 12. + The snapshot is kept for step 17. Verifies: state Ready; VM stays Stopped; one new FlexVol snapshot. """ vm = self._require_snapshot_vm() @@ -566,10 +1444,10 @@ def test_11_vm_snapshot_create_stopped(self): self._keep_vm_snapshot(snap, new, "vm_snap_stopped") @attr(tags=[TAG], required_hardware=True) - def test_12_vm_snapshot_s1_running_s2_stopped_revert(self): + def test_17_vm_snapshot_s1_running_s2_stopped_revert(self): """ VMS-09 (NFS ROOT + NFS DATA on the same pool): revert to the running - snapshot from step 10, then to the stopped snapshot from step 11. + snapshot from step 15, then to the stopped snapshot from step 16. Verifies: - After revert to S1: ROOT and DATA hold before-s1 - After revert to S2: ROOT and DATA hold before-s2 @@ -603,7 +1481,7 @@ def test_12_vm_snapshot_s1_running_s2_stopped_revert(self): vm, s2, self._ontap_names_for_snap(ontap_names, s2, "vm"), token_b) @attr(tags=[TAG], required_hardware=True) - def test_13_vm_snapshot_duplicate_requests(self): + def test_18_vm_snapshot_duplicate_requests(self): """ VMS-53: two VM snapshot requests for the same VM at the same time. A rejected request is retried on its own; one that already succeeded @@ -653,19 +1531,61 @@ def test_13_vm_snapshot_duplicate_requests(self): self._assert_new_ontap_snaps(before, ok, "vm", "duplicate VM snapshot requests") # ------------------------------------------------------------------ - # Steps 14-16 - Second VM on the same pool: isolation and concurrency + # Steps 17-21 - Second VM on the same pool: isolation and concurrency # ------------------------------------------------------------------ @attr(tags=[TAG], required_hardware=True) - def test_14_deploy_second_vm(self): + def test_19_deploy_second_vm(self): """ Deploy a second VM whose ROOT disk is on the same ONTAP pool. Verifies: VM Running; ROOT on the test pool; SSH works. """ - self.step_19_deploy_second_vm() + self._require_snapshot_vm() + cmd = deployVirtualMachineAPI.deployVirtualMachineCmd() + cmd.zoneid = self.zone.id + cmd.templateid = self.__class__.template_id + cmd.serviceofferingid = self.__class__.service_offering_id + cmd.account = self.account.name + cmd.domainid = self.domain.id + cmd.networkids = self.__class__.network_id + vm2 = self.apiClient.deployVirtualMachine(cmd) + self.__class__.vm2 = vm2 + self._poll_vm_state(vm2.id, "Running", timeout=900) + root = self._root_volume(vm2.id) + self.assertEqual(getattr(root, "storageid", None), self.__class__.pool.id, + "Second VM ROOT is not on the ONTAP test pool") + host, port, _ = open_ssh_port(self.apiClient, vm2.id, self.__class__.network_id) + self.__class__.vm2_ssh = (host, port) + token = new_token("second-vm-ssh-access-test") + self._write_marker(token, which="vm2") + self._assert_marker(token, which="vm2", msg="second VM access") + + @attr(tags=[TAG], required_hardware=True) + def test_20_volume_revert_leaves_other_vm_untouched(self): + """ + VS-28: two VMs on one FlexVol; revert VM-A's ROOT to its snapshot. + Verifies: VM-A is back at its snapshot; VM-B keeps data written after it. + """ + vm = self._require_snapshot_vm() + self._require_second_vm() + a1 = new_token("vm-a-before-snapshot") + a2 = new_token("vm-a-after-snapshot") + b1 = new_token("vm-b-before-snapshot") + b2 = new_token("vm-b-after-snapshot") + self._write_marker(a1) + self._write_marker(b1, which="vm2") + snap = self._take_volume_snapshot(self._root_volume(vm.id).id) + self._write_marker(a2) + self._write_marker(b2, which="vm2") + + self._stop_vm(vm.id) + Volume.revertToSnapshot(self.apiClient, snap.id) + self._start_vm(vm.id) + self._assert_marker(a1, msg="VM-A after revert") + self._assert_marker(b2, which="vm2", msg="VM-B after VM-A's revert") @attr(tags=[TAG], required_hardware=True) - def test_15_concurrent_vm_snapshots_two_vms(self): + def test_21_concurrent_vm_snapshots_two_vms(self): """ VMS-54: VM snapshots on two VMs of the same NFS pool at the same time. Verifies: both Ready and owned by their VMs; two distinct new FlexVol @@ -691,7 +1611,41 @@ def test_15_concurrent_vm_snapshots_two_vms(self): self._assert_new_ontap_snaps(before, [snap_a, snap_b], "vm", "concurrent VM snapshots") @attr(tags=[TAG], required_hardware=True) - def test_16_concurrent_vm_snapshot_and_revert(self): + def test_22_concurrent_volume_snapshot_and_revert(self): + """ + Volume snapshot of VM-A's ROOT while VM-B's ROOT reverts, at the same time. + A rejected snapshot or revert is retried on its own. + Verifies: VM-A snapshot BackedUp with its own FlexVol snapshot; VM-B is + back at its snapshot; VM-A data unchanged. + """ + vm = self._require_snapshot_vm() + vm2 = self._require_second_vm() + a1 = new_token("vm-a-current-data") + b1 = new_token("vm-b-before-snapshot") + b2 = new_token("vm-b-after-snapshot") + self._write_marker(a1) + self._write_marker(b1, which="vm2") + snap_b = self._take_volume_snapshot(self._root_volume(vm2.id).id) + self._write_marker(b2, which="vm2") + self._stop_vm(vm2.id) + before = self._ontap_snap_names() + root_a = self._root_volume(vm.id).id + + snap_a = _snapshot_and_revert_with_retry( + lambda: Snapshot.create(self.apiClient, root_a, + account=self.account.name, domainid=self.domain.id), + lambda: Volume.revertToSnapshot(self.apiClient, snap_b.id), + ) + self._volume_snapshot_ids.append(snap_a.id) + self.assertEqual(snap_a.state, "BackedUp") + self._assert_new_ontap_snaps(before, [snap_a], "volume", "VM-A snapshot during VM-B revert") + + self._start_vm(vm2.id) + self._assert_marker(b1, which="vm2", msg="VM-B after revert") + self._assert_marker(a1, msg="VM-A during VM-B revert") + + @attr(tags=[TAG], required_hardware=True) + def test_23_concurrent_vm_snapshot_and_revert(self): """ VM snapshot of VM-A while VM-B reverts to its VM snapshot, at the same time. A rejected snapshot or revert is retried on its own. @@ -724,11 +1678,11 @@ def test_16_concurrent_vm_snapshot_and_revert(self): self._assert_marker(a1, msg="VM-A during VM-B revert") # ------------------------------------------------------------------ - # Step 17 - Detach ONTAP data volume from the VM + # Step 24 - Detach ONTAP data volume from the VM # ------------------------------------------------------------------ @attr(tags=["vm_volume_workflow"], required_hardware=True) - def test_17_detach_volume_from_vm(self): + def test_24_detach_volume_from_vm(self): """ Detach the ONTAP data volume from the running VM. Verifies: @@ -813,11 +1767,11 @@ def test_17_detach_volume_from_vm(self): # ------------------------------------------------------------------ # ------------------------------------------------------------------ - # Step 18 - Grow detached data volume + # Step 25 - Grow detached data volume # ------------------------------------------------------------------ @attr(tags=["vm_volume_workflow"], required_hardware=True) - def test_18_grow_detached_volume(self): + def test_25_grow_detached_volume(self): """Grow the materialized qcow2 after it has been detached.""" self.assertIsNotNone(self.__class__.volume, "Volume absent — test_02 must pass first") @@ -838,11 +1792,11 @@ def test_18_grow_detached_volume(self): self.__class__.target_volume_size = detached_target # ------------------------------------------------------------------ - # Step 19 - Destroy the second VM while it still has a VM snapshot + # Step 26 - Destroy the second VM while it still has a VM snapshot # ------------------------------------------------------------------ @attr(tags=["vm_volume_workflow"], required_hardware=True) - def test_19_destroy_vm_with_vm_snapshot(self): + def test_26_destroy_vm_with_vm_snapshot(self): """ VMS-38: destroy (expunge) the second VM while it still has a VM snapshot. Verifies: destroy succeeds; the VM snapshot is no longer listed; its @@ -870,11 +1824,11 @@ def test_19_destroy_vm_with_vm_snapshot(self): self._wait_ontap_snaps_gone(new) # ------------------------------------------------------------------ - # Step 20 - Destroy VM, delete volume, delete pool + # Step 27 - Destroy VM, delete volume, delete pool # ------------------------------------------------------------------ @attr(tags=["vm_volume_workflow"], required_hardware=True) - def test_20_destroy_vm_and_cleanup(self): + def test_27_destroy_vm_and_cleanup(self): """ Destroy the VM, delete the ONTAP data volume, enter maintenance, then force-delete the pool. @@ -888,7 +1842,106 @@ def test_20_destroy_vm_and_cleanup(self): - ONTAP: FlexVol is deleted after pool removal - ONTAP: Export policy is removed after pool removal """ - self.step_27_destroy_vm_and_cleanup() + self.assertIsNotNone(self.__class__.pool, + "Pool absent — test_01 must pass first") + + self._destroy_second_vm() + vm = self.__class__.vm + vol = self.__class__.volume + pool = self.__class__.pool + pool_name = pool.name + + # Stop VM if still running + if vm is not None: + vms = self.apiClient.listVirtualMachines(_list_vms_cmd(vm.id)) + current_state = vms[0].state.lower() if vms else "unknown" + if current_state not in ("stopped", "destroyed", + "expunging", "error"): + stop_cmd = stopVirtualMachineAPI.stopVirtualMachineCmd() + stop_cmd.id = vm.id + self.apiClient.stopVirtualMachine(stop_cmd) + self._poll_vm_state(vm.id, "Stopped", timeout=300) + + dest_cmd = destroyVirtualMachineAPI.destroyVirtualMachineCmd() + dest_cmd.id = vm.id + dest_cmd.expunge = True + self.apiClient.destroyVirtualMachine(dest_cmd) + self.__class__.vm = None + + spool = self._assert_single_ready_spool_ref( + self.__class__.pool_db_id) + self._assert_cache_on_ontap(pool, spool) + + # Delete the ONTAP data volume + if vol is not None: + vol_id = vol.id + cmd = deleteVolumeAPI.deleteVolumeCmd() + cmd.id = vol_id + self.apiClient.deleteVolume(cmd) + self.__class__.volume = None + + # ONTAP: NFS3 volume data file must be removed from the FlexVol + # after deleteVolume (CloudStack/libvirt deletes the file from the + # NFS mount as part of the destroy workflow). + files = self.ontap.list_files_in_volume(pool_name) + vol_file = next((f for f in files if vol_id in f), None) + self.assertIsNone( + vol_file, + "Volume data file for '%s' should be gone from FlexVol '%s' " + "after deleteVolume; files still present: %s" + % (vol_id, pool_name, files) + ) + + # Enter maintenance then delete the pool + maint_cmd = enableStorageMaintenance.enableStorageMaintenanceCmd() + maint_cmd.id = pool.id + self.apiClient.enableStorageMaintenance(maint_cmd) + self._poll_pool_state(pool.id, "Maintenance", timeout=120) + + # forced=True: the template cache (template_spool_ref) is still on + # the pool — it is only reclaimed by storage GC or pool deletion. + self._delete_pool(pool.id, forced=True) + self.__class__.pool = None + + # CloudStack: pool must be gone + try: + remaining = list_storage_pools(self.apiClient, id=pool.id) + except Exception: + remaining = None + self.assertFalse(remaining, + "Pool still listed in CloudStack after deletion") + + # ONTAP: FlexVol must be deleted + ontap_vol = self.ontap.get_volume(pool_name) + self.assertIsNone( + ontap_vol, + "ONTAP FlexVol '%s' still exists after pool deletion" % pool_name + ) + + # ONTAP: Export policy must be removed + ep_name = "cs-%s-%s" % (self.svm_name, pool_name) + ep = self.ontap.get_export_policy(ep_name) + self.assertIsNone( + ep, + "ONTAP export policy '%s' still exists after pool deletion" + % ep_name + ) + + +# --------------------------------------------------------------------------- +# Module-level helpers (used in tearDownClass and test helpers) +# --------------------------------------------------------------------------- + +def _list_vms_cmd(vm_id): + cmd = listVirtualMachinesAPI.listVirtualMachinesCmd() + cmd.id = vm_id + return cmd + + +def _list_vols_cmd(vol_id): + cmd = listVolumesAPI.listVolumesCmd() + cmd.id = vol_id + return cmd def _run_concurrent(*callables): @@ -912,6 +1965,22 @@ def worker(index, fn): return results +def _is_rejected(exc): + """True when CloudStack or ONTAP refused the call because another one was in progress.""" + text = str(exc).lower() + return any(token in text for token in ( + "internal error", + "failed to create snapshot", + "failed to create instance snapshot", + "failed to revert", + "another operation", + "other active", + "try again later", + "in progress", + "busy", + )) + + def _snapshot_and_revert_with_retry(snapshot_fn, revert_fn, attempts=3, pause=15): """Run a snapshot and a revert together. @@ -950,3 +2019,14 @@ def _snapshot_and_revert_with_retry(snapshot_fn, revert_fn, attempts=3, pause=15 raise AssertionError( "Snapshot-while-revert failed after %d attempt(s): %s" % (attempt, last_errors)) + + +def _wait_for_vm_state(api_client, vm_id, target_state, timeout=120, + interval=5): + """Blocking wait for a VM to reach target_state (used in tearDownClass).""" + deadline = time.time() + timeout + while time.time() < deadline: + vms = api_client.listVirtualMachines(_list_vms_cmd(vm_id)) + if vms and vms[0].state.lower() == target_state.lower(): + return + time.sleep(interval) From 20f4938fbc999dbbb11a5911163a4bbd43082d2c Mon Sep 17 00:00:00 2001 From: sp16743 Date: Wed, 2 Dec 2026 15:22:53 +0530 Subject: [PATCH 3/5] Update readme.md and test_cases.md --- test/integration/plugins/ontap/README.md | 8 +- test/integration/plugins/ontap/TEST_CASES.md | 82 ++++++++++++-------- test/integration/plugins/ontap/run_tests.sh | 4 + 3 files changed, 56 insertions(+), 38 deletions(-) diff --git a/test/integration/plugins/ontap/README.md b/test/integration/plugins/ontap/README.md index 78eabf1128fc..4c7fa024ca03 100644 --- a/test/integration/plugins/ontap/README.md +++ b/test/integration/plugins/ontap/README.md @@ -46,7 +46,7 @@ test/integration/plugins/ontap/ ├── guest_ssh.py # Guest SSH (paramiko) for the VM workflow suites ├── setup_env.sh # venv: Marvin plus requirements.txt ├── requirements.txt # setuptools, pyvmomi, paramiko pins -├── TEST_CASES.md # Full test case reference table (214 tests) +├── TEST_CASES.md # Full test case reference table (228 tests) ├── README.md # This file │ ├── nfs3/ @@ -386,7 +386,7 @@ another ONTAP pool is present. | NFS3 Pool with Volumes | `nfs3/pool/test_pool_with_volumes.py` | 12 | Lifecycle with a live volume, deletion with a pre-deleted FlexVol or export policy, and host cases for an inactive libvirt pool, a read-only NFS mount, and a deleted mount point | | NFS3 Zone-Scoped Pool | `nfs3/pool/test_zone_scoped_pool.py` | 5 | Zone-scoped pool create, grow and shrink with CloudStack/ONTAP/KVM verification, disable, enable, and delete | | NFS3 Volume Lifecycle | `nfs3/volume/test_volume_lifecycle.py` | 5 | Volume is metadata-only; FlexVol unchanged on delete | -| NFS3 VM + Volume Attach | `nfs3/instance/test_vm_volume_attach.py` | 22 | Full VM lifecycle with stopped-VM qcow2 grow, guest SSH and VM snapshots; ROOT on tagged pool seeds/reuses template cache, which survives VM delete | +| NFS3 VM + Volume Attach | `nfs3/instance/test_vm_volume_attach.py` | 29 | Full VM lifecycle with stopped-VM qcow2 grow, guest SSH, volume and VM snapshots; ROOT on tagged pool seeds/reuses template cache, which survives VM delete | | NFS3 Snapshot to Volume | `nfs3/volume/test_snapshot_to_volume.py` | 22 | Own VM setup, then volume snapshot and revert (VM-A and VM-B), volumes created from ROOT and DATA snapshots: attach, move between VMs, independence from the source, rejects (offering, missing snapshot, disabled or second pool, missing metadata), delete-during-create | | NFS3 Snapshot to Template | `nfs3/template/test_snapshot_to_template.py` | 16 | Own setup (pool, data volume, VM) then templates created from ROOT and DATA snapshots: deploy from them, expunged source, attributes, rejects | | NFS3 Template Cache Negative | `nfs3/template/test_template_cache_negative.py` | 3 | Tag mismatch; undersized pool; out-of-band cache delete | @@ -394,7 +394,7 @@ another ONTAP pool is present. | iSCSI Pool with Volumes | `iscsi/pool/test_pool_with_volumes.py` | 13 | Lifecycle with a live LUN, deletion with a pre-deleted FlexVol or igroups, maintenance with pre-deleted LUN maps, and host cases for a logged-out iSCSI session, an existing session during volume delete, and a replaced by-path symlink | | iSCSI Zone-Scoped Pool | `iscsi/pool/test_zone_scoped_pool.py` | 5 | Zone-scoped pool create, grow and shrink with CloudStack/ONTAP verification, disable, enable, and delete | | iSCSI Volume Lifecycle | `iscsi/volume/test_volume_lifecycle.py` | 5 | LUN created per CS volume; LUN removed on delete | -| iSCSI VM + Volume Attach | `iscsi/instance/test_vm_volume_attach.py` | 22 | Full VM lifecycle; stopped-VM LUN grow, LUN-map checks, guest SSH and VM snapshots; ROOT on tagged pool seeds/reuses `cs_tmpl_*` LUN cache | +| iSCSI VM + Volume Attach | `iscsi/instance/test_vm_volume_attach.py` | 29 | Full VM lifecycle; stopped-VM LUN grow, LUN-map checks, guest SSH, volume and VM snapshots; ROOT on tagged pool seeds/reuses `cs_tmpl_*` LUN cache | | iSCSI Snapshot to Volume | `iscsi/volume/test_snapshot_to_volume.py` | 23 | Own VM setup, then volume snapshot and revert (VM-A and VM-B), volumes created from ROOT and DATA snapshots: attach, move between VMs, independence from the source, rejects (offering, missing snapshot, disabled or second pool, missing metadata, duplicate name), delete-during-create | | iSCSI Snapshot to Template | `iscsi/template/test_snapshot_to_template.py` | 16 | Own setup (pool, data volume, VM) then templates created from ROOT and DATA snapshots: deploy from them, expunged source, attributes, rejects | | iSCSI Template Cache Negative | `iscsi/template/test_template_cache_negative.py` | 3 | Tag mismatch; undersized pool; out-of-band cache delete | @@ -413,7 +413,7 @@ For the goal, dependencies, and exact success criteria of every individual test, | `Lost connection to MySQL` | MySQL not accepting remote connections | Enable remote MySQL access (see Prerequisites §3) | | `sh: python: command not found` (repeated) | Marvin internal call — harmless on macOS | Ignore; Marvin Init still succeeds | | Pool state never reaches `Maintenance` | KVM agent not responding | Check `cloudstack-agent` on KVM host; verify host is connected in CloudStack UI | -| iSCSI `test_17` error 530 | KVM guest does not ACK SCSI hot-unplug | Detach of the data LUN from a running VM; see TEST_CASES.md Suite 10 `test_17_detach_volume_from_vm` | +| iSCSI `test_24` error 530 | KVM guest does not ACK SCSI hot-unplug | Detach of the data LUN from a running VM; see TEST_CASES.md Suite 10 `test_24_detach_volume_from_vm` | | ONTAP REST `401 Unauthorized` | Wrong credentials in `ontap.cfg` | Verify `username`/`password` under `ontap` section | | `ISCSI protocol is not enabled on SVM` / many pool tests EXCEPTION then FAIL | SVM iSCSI service off or no `data_iscsi` LIF | Enable iSCSI on the SVM and assign `default-data-iscsi` (or `default-data-blocks`) to at least one data LIF; `run_tests.sh` now fails this check before Marvin starts | | `No ready KVM user template available` | Template still downloading | Re-run `setup_zone` (step 12 waits for template readiness); or wait in CloudStack UI | diff --git a/test/integration/plugins/ontap/TEST_CASES.md b/test/integration/plugins/ontap/TEST_CASES.md index 1fe600eb394a..bbf8c1505b4b 100644 --- a/test/integration/plugins/ontap/TEST_CASES.md +++ b/test/integration/plugins/ontap/TEST_CASES.md @@ -19,7 +19,7 @@ # ONTAP Integration Test Cases -Complete reference for all 214 test cases across 16 test suites. +Complete reference for all 228 test cases across 16 test suites. Each suite is sequential — tests must run in numbered order; each step builds on state created by the previous step. --- @@ -133,7 +133,7 @@ Each suite is sequential — tests must run in numbered order; each step builds **File:** `nfs3/instance/test_vm_volume_attach.py` **Class:** `TestOntapVMVolumeAttach` **Tag:** `vm_volume_workflow` -**Total:** 22 tests | **Scope:** end-to-end — NFS3 pool, data volume resize, running VM (ROOT on the ONTAP pool via a tagged compute offering), primary template cache seed / reuse / survive VM delete, attach/detach, guest SSH and VM snapshots. Volume snapshot, revert and create-volume-from-snapshot cases run in the snapshot-to-volume suite; create-template-from-snapshot cases run in the snapshot-to-template suite. Guest login uses `guest_ssh.py` (paramiko) against the CentOS 5.5 template. +**Total:** 29 tests | **Scope:** end-to-end — NFS3 pool, data volume resize, running VM (ROOT on the ONTAP pool via a tagged compute offering), primary template cache seed / reuse / survive VM delete, attach/detach, guest SSH, volume snapshots, and VM snapshots. Guest login uses `guest_ssh.py` (paramiko) against the CentOS 5.5 template. | # | Test method | Goal | Depends on | CloudStack success criteria | ONTAP success criteria | Type | | --- | ------------- | ------ | ------------ | ----------------------------- | ------------------------ | ------ | @@ -148,17 +148,24 @@ Each suite is sequential — tests must run in numbered order; each step builds | 07 | `test_07_shrink_rejected` | Attempt to shrink the grown qcow2 volume with `shrinkok=true` | test_06 | Resize is rejected; grown size remains unchanged | qcow2 virtual size remains unchanged | negative | | 08 | `test_08_start_vm_volume_accessible` | Start the stopped VM | test_07 | `vm.state == "Running"`; KVM data-disk capacity equals target | FlexVol still `online` | positive | | 09 | `test_09_open_ssh_and_write_root_data_files` | Port-forward SSH to the guest and write ROOT and DATA marker files | test_08 (`vm`, `volume`, guest network) | ROOT and DATA both on the ONTAP pool; DATA still attached; SSH login succeeds; both markers read back | FlexVol still `online` | positive | -| 10 | `test_10_vm_snapshot_create_running` | VMS-01: VM snapshot of the running VM (kept for test_12) | test_09 | VM snapshot `Ready`; VM stays `Running` | One new FlexVol snapshot | positive | -| 11 | `test_11_vm_snapshot_create_stopped` | VMS-03: stop, VM snapshot, start (kept for test_12) | test_10 | VM snapshot `Ready` | One new FlexVol snapshot | positive | -| 12 | `test_12_vm_snapshot_s1_running_s2_stopped_revert` | VMS-09: revert to the test_10 snapshot, then to the test_11 snapshot, then delete both while the VM is running | test_10, test_11 | Each revert finishes; guest file matches that snapshot; both VM snapshots are then gone and the VM stays `Running` | FlexVol snapshots survive the reverts, then both are removed | positive | -| 13 | `test_13_vm_snapshot_duplicate_requests` | VMS-53: two VM snapshot requests for the same VM at once | test_12 | Both snapshots `Ready` (a rejected request is retried) | Two new FlexVol snapshots | positive | -| 14 | `test_14_deploy_second_vm` | Deploy VM-B whose ROOT disk is on the same ONTAP pool | test_13 | VM-B `Running`; ROOT `storageid` = pool | ROOT file present on the shared FlexVol | positive | -| 15 | `test_15_concurrent_vm_snapshots_two_vms` | VMS-54: VM snapshots of both VMs at the same time | test_14 | Both VM snapshots `Ready` | Two new FlexVol snapshots | positive | -| 16 | `test_16_concurrent_vm_snapshot_and_revert` | VM snapshot of VM-A while VM-B reverts to its VM snapshot | test_15 | Both operations finish; VM-A snapshot `Ready` | New FlexVol snapshot for VM-A | positive | -| 17 | `test_17_detach_volume_from_vm` | Hot-detach the ONTAP volume from the running VM (TDS Detach NFS3) | test_16 (`vm`, `volume`) | `volume.virtualmachineid` cleared; `volume.state == "Ready"` | FlexVol still `online`; data file **still present** (NFS3: file persists until `deleteVolume`, not on detach) | positive | -| 18 | `test_18_grow_detached_volume` | Grow the detached, materialized data volume | test_17 | API and DB size equal target | qcow2 virtual size equals target | positive | -| 19 | `test_19_destroy_vm_with_vm_snapshot` | VMS-38: expunge VM-B while it still has a VM snapshot | test_14 (VM-B) | VM-B no longer listed | VM-B's FlexVol snapshot removed | positive | -| 20 | `test_20_destroy_vm_and_cleanup` | Destroy VM (expunge), delete volume, enter maintenance, force-delete pool | test_18, test_19 | VM no longer listed; spool_ref still Ready after VM expunge; volume no longer listed; pool no longer listed | Cache file present after VM expunge; FlexVol deleted; export policy deleted | cleanup | +| 10 | `test_10_root_volume_snapshot_create` | VS-01: snapshot the ROOT volume of the running VM | test_09 | Snapshot `BackedUp`; VM stays `Running` | One new FlexVol snapshot | positive | +| 11 | `test_11_data_volume_snapshot_create` | VS-03: snapshot the attached DATA volume (kept for test_14) | test_10 | Snapshot `BackedUp`; VM stays `Running` | One new FlexVol snapshot, kept until test_14 | positive | +| 12 | `test_12_volume_revert_running_vm_rejected` | VS-19: revert a volume snapshot while the VM is Running | test_11 | Revert is rejected | FlexVol unchanged | negative | +| 13 | `test_13_root_volume_revert` | VS-11: write A, snapshot ROOT, write B, stop, revert, start | test_12 | After revert and start, ROOT marker is A | New FlexVol snapshot for the snapshot; revert snapshot removed in tearDown | positive | +| 14 | `test_14_data_volume_revert` | Snapshot DATA again, revert to the test_11 snapshot then to this one, then delete both while the VM is running | test_11, test_13 | Older revert restores the test_11 DATA marker and the later snapshot stays listed; later revert restores its marker; both snapshots are then gone and the VM stays `Running` | Both FlexVol snapshots remain through the older revert, then both are removed | positive | +| 15 | `test_15_vm_snapshot_create_running` | VMS-01: VM snapshot of the running VM (kept for test_17) | test_14 | VM snapshot `Ready`; VM stays `Running` | One new FlexVol snapshot | positive | +| 16 | `test_16_vm_snapshot_create_stopped` | VMS-03: stop, VM snapshot, start (kept for test_17) | test_15 | VM snapshot `Ready` | One new FlexVol snapshot | positive | +| 17 | `test_17_vm_snapshot_s1_running_s2_stopped_revert` | VMS-09: revert to the test_15 snapshot, then to the test_16 snapshot, then delete both while the VM is running | test_15, test_16 | Each revert finishes; guest file matches that snapshot; both VM snapshots are then gone and the VM stays `Running` | FlexVol snapshots survive the reverts, then both are removed | positive | +| 18 | `test_18_vm_snapshot_duplicate_requests` | VMS-53: two VM snapshot requests for the same VM at once | test_17 | Both snapshots `Ready` (a rejected request is retried) | Two new FlexVol snapshots | positive | +| 19 | `test_19_deploy_second_vm` | Deploy VM-B whose ROOT disk is on the same ONTAP pool | test_18 | VM-B `Running`; ROOT `storageid` = pool | ROOT file present on the shared FlexVol | positive | +| 20 | `test_20_volume_revert_leaves_other_vm_untouched` | VS-28: revert VM-A's ROOT | test_19 | VM-A's ROOT marker is restored; VM-B's file is unchanged | FlexVol stays `online` | positive | +| 21 | `test_21_concurrent_vm_snapshots_two_vms` | VMS-54: VM snapshots of both VMs at the same time | test_20 | Both VM snapshots `Ready` | Two new FlexVol snapshots | positive | +| 22 | `test_22_concurrent_volume_snapshot_and_revert` | Volume snapshot of VM-A's ROOT while VM-B's ROOT reverts | test_21 | Snapshot `BackedUp` and revert both finish (retried on error 530) | New FlexVol snapshot for the volume snapshot | positive | +| 23 | `test_23_concurrent_vm_snapshot_and_revert` | VM snapshot of VM-A while VM-B reverts to its VM snapshot | test_22 | Both operations finish; VM-A snapshot `Ready` | New FlexVol snapshot for VM-A | positive | +| 24 | `test_24_detach_volume_from_vm` | Hot-detach the ONTAP volume from the running VM (TDS Detach NFS3) | test_23 (`vm`, `volume`) | `volume.virtualmachineid` cleared; `volume.state == "Ready"` | FlexVol still `online`; data file **still present** (NFS3: file persists until `deleteVolume`, not on detach) | positive | +| 25 | `test_25_grow_detached_volume` | Grow the detached, materialized data volume | test_24 | API and DB size equal target | qcow2 virtual size equals target | positive | +| 26 | `test_26_destroy_vm_with_vm_snapshot` | VMS-38: expunge VM-B while it still has a VM snapshot | test_19 (VM-B) | VM-B no longer listed | VM-B's FlexVol snapshot removed | positive | +| 27 | `test_27_destroy_vm_and_cleanup` | Destroy VM (expunge), delete volume, enter maintenance, force-delete pool | test_25, test_26 | VM no longer listed; spool_ref still Ready after VM expunge; volume no longer listed; pool no longer listed | Cache file present after VM expunge; FlexVol deleted; export policy deleted | cleanup | --- @@ -167,7 +174,7 @@ Each suite is sequential — tests must run in numbered order; each step builds **File:** `nfs3/volume/test_snapshot_to_volume.py` **Class:** `TestOntapNfs3SnapshotToVolume` **Tag:** `nfs3_snapshot_to_volume` -**Total:** 22 tests | **Scope:** create volumes from ROOT and DATA volume snapshots of a running VM, attach them to VMs and check them in CloudStack and ONTAP. Moved out of the VM suite because the full VM suite takes a long time; setup (01–06) and cleanup reuse the same steps. Run this suite in full. +**Total:** 22 tests | **Scope:** dedicated create-volume-from-snapshot coverage for ROOT and DATA volume snapshots of a running VM, including attach and CloudStack/ONTAP checks. Setup (01–06) and cleanup reuse the same steps. Run this suite in full. | # | Test method | Goal | Depends on | CloudStack success criteria | ONTAP success criteria | Type | | --- | ------------- | ------ | ------------ | ----------------------------- | ------------------------ | ------ | @@ -200,7 +207,7 @@ Each suite is sequential — tests must run in numbered order; each step builds **File:** `nfs3/template/test_snapshot_to_template.py` **Class:** `TestOntapNfs3SnapshotToTemplate` **Tag:** `nfs3_snapshot_to_template` -**Total:** 16 tests | **Scope:** create templates from ROOT and DATA volume snapshots, deploy VMs from them and check the results in CloudStack and ONTAP. Moved out of the VM suite because the full VM suite takes a long time; setup (01–05) and cleanup reuse the same steps. Run this suite in full. +**Total:** 16 tests | **Scope:** dedicated create-template-from-snapshot coverage for ROOT and DATA volume snapshots, including VM deployment and CloudStack/ONTAP checks. Setup (01–05) and cleanup reuse the same steps. Run this suite in full. | # | Test method | Goal | Depends on | CloudStack success criteria | ONTAP success criteria | Type | | --- | ------------- | ------ | ------------ | ----------------------------- | ------------------------ | ------ | @@ -319,7 +326,7 @@ Each suite is sequential — tests must run in numbered order; each step builds **File:** `iscsi/instance/test_vm_volume_attach.py` **Class:** `TestOntapVMVolumeAttachISCSI` **Tag:** `iscsi_vm_workflow` -**Total:** 22 tests | **Scope:** end-to-end — iSCSI pool, data volume resize (LUN), running VM (ROOT on the ONTAP pool via a tagged compute offering), `cs_tmpl_` LUN cache seed / reuse / survive VM delete, attach/stop/start/detach, guest SSH and VM snapshots. Volume snapshot, revert and create-volume-from-snapshot cases run in the snapshot-to-volume suite; create-template-from-snapshot cases run in the snapshot-to-template suite. LUN-map checks are limited to the data volume's LUN. Guest login uses `guest_ssh.py` (paramiko) against the CentOS 5.5 template. +**Total:** 29 tests | **Scope:** end-to-end — iSCSI pool, data volume resize (LUN), running VM (ROOT on the ONTAP pool via a tagged compute offering), `cs_tmpl_` LUN cache seed / reuse / survive VM delete, attach/stop/start/detach, guest SSH, volume snapshots, and VM snapshots. LUN-map checks are limited to the data volume's LUN. Guest login uses `guest_ssh.py` (paramiko) against the CentOS 5.5 template. | # | Test method | Goal | Depends on | CloudStack success criteria | ONTAP success criteria | Type | | --- | ------------- | ------ | ------------ | ----------------------------- | ------------------------ | ------ | @@ -334,19 +341,26 @@ Each suite is sequential — tests must run in numbered order; each step builds | 07 | `test_07_shrink_rejected` | Attempt to shrink the grown LUN with `shrinkok=true` | test_06 | Resize is rejected; grown size remains unchanged | LUN `space.size` remains unchanged | negative | | 08 | `test_08_start_vm_lun_remapped` | Start VM — LUN-maps must be re-created (TDS VM Start iSCSI) | test_07 | `vm.state == "Running"` | ≥1 LUN-map re-created | positive | | 09 | `test_09_open_ssh_and_write_root_data_files` | Port-forward SSH to the guest and write ROOT and DATA marker files | test_08 (`vm`, `volume`, guest network) | ROOT and DATA both on the ONTAP pool; DATA still attached; SSH login succeeds; both markers read back | Data LUN still mapped | positive | -| 10 | `test_10_vm_snapshot_create_running` | VM snapshot of the running VM, ROOT + DATA LUNs (kept for test_12) | test_09 | VM snapshot `Ready`; VM stays `Running` | One new FlexVol snapshot | positive | -| 11 | `test_11_vm_snapshot_create_stopped` | Stop, VM snapshot, start (kept for test_12) | test_10 | VM snapshot `Ready` | One new FlexVol snapshot | positive | -| 12 | `test_12_vm_snapshot_s1_running_s2_stopped_revert` | VMS-09: revert to the test_10 snapshot, then to the test_11 snapshot, then delete both while the VM is running | test_10, test_11 | Each revert finishes; guest file matches that snapshot; both VM snapshots are then gone and the VM stays `Running` | FlexVol snapshots survive the reverts, then both are removed | positive | -| 13 | `test_13_vm_snapshot_duplicate_requests` | VMS-53: two VM snapshot requests for the same VM at once | test_12 | Both snapshots `Ready` (a rejected request is retried) | Two new FlexVol snapshots | positive | -| 14 | `test_14_deploy_second_vm` | Deploy VM-B whose ROOT LUN is on the same ONTAP pool | test_13 | VM-B `Running`; ROOT on pool | One more non-cache LUN; `cs_tmpl_*` still one | positive | -| 15 | `test_15_concurrent_vm_snapshots_two_vms` | VMS-55: VM snapshots of both VMs at the same time | test_14 | Both VM snapshots `Ready` | Two new FlexVol snapshots | positive | -| 16 | `test_16_concurrent_vm_snapshot_and_revert` | VM snapshot of VM-A while VM-B reverts to its VM snapshot | test_15 | Both operations finish; VM-A snapshot `Ready` | New FlexVol snapshot for VM-A | positive | -| 17 | `test_17_detach_volume_from_vm` | Hot-detach the iSCSI volume from the running VM (TDS Detach iSCSI) | test_16 (`vm`, `volume`) | `volume.virtualmachineid` cleared | 0 LUN-maps for the data LUN; LUN still in FlexVol | positive ⚠️ | -| 18 | `test_18_grow_detached_volume` | Grow the detached, materialized data volume | test_17 | API and DB size equal target | LUN `space.size` equals target | positive | -| 19 | `test_19_destroy_vm_with_vm_snapshot` | Expunge VM-B while it still has a VM snapshot | test_14 (VM-B) | VM-B no longer listed | VM-B ROOT LUN gone; `cs_tmpl_*` still present | positive | -| 20 | `test_20_destroy_vm_and_cleanup` | Destroy VM (expunge), delete volume, enter maintenance, delete pool | test_18, test_19 | VM gone; spool_ref still Ready after VM expunge; volume gone; pool gone | `cs_tmpl_*` present after VM expunge; FlexVol deleted; all LUNs and igroups deleted | cleanup | - -> ⚠️ **test_17 known status:** iSCSI hot-detach from a running VM relies on the KVM guest acknowledging the SCSI device removal. On this environment the guest does not acknowledge in time, causing CloudStack error 530. This is a KVM-host-level or guest-template limitation, not a test code defect. +| 10 | `test_10_root_volume_snapshot_create` | VS-01: snapshot the ROOT volume of the running VM | test_09 | Snapshot `BackedUp`; VM stays `Running` | One new FlexVol snapshot | positive | +| 11 | `test_11_data_volume_snapshot_create` | VS-03: snapshot the attached DATA volume (kept for test_14) | test_10 | Snapshot `BackedUp`; VM stays `Running` | One new FlexVol snapshot, kept until test_14 | positive | +| 12 | `test_12_volume_revert_running_vm_rejected` | VS-20: revert a volume snapshot while the VM is Running | test_11 | Revert is rejected | FlexVol unchanged | negative | +| 13 | `test_13_root_volume_revert` | VS-12: write A, snapshot ROOT, write B, stop, revert, start | test_12 | After revert and start, ROOT marker is A | New FlexVol snapshot for the snapshot; revert snapshot removed in tearDown | positive | +| 14 | `test_14_data_volume_revert` | Snapshot DATA again, revert to the test_11 snapshot then to this one, then delete both while the VM is running | test_11, test_13 | Older revert restores the test_11 DATA marker and the later snapshot stays listed; later revert restores its marker; both snapshots are then gone and the VM stays `Running` | Both FlexVol snapshots remain through the older revert, then both are removed | positive | +| 15 | `test_15_vm_snapshot_create_running` | VM snapshot of the running VM, ROOT + DATA LUNs (kept for test_17) | test_14 | VM snapshot `Ready`; VM stays `Running` | One new FlexVol snapshot | positive | +| 16 | `test_16_vm_snapshot_create_stopped` | Stop, VM snapshot, start (kept for test_17) | test_15 | VM snapshot `Ready` | One new FlexVol snapshot | positive | +| 17 | `test_17_vm_snapshot_s1_running_s2_stopped_revert` | VMS-09: revert to the test_15 snapshot, then to the test_16 snapshot, then delete both while the VM is running | test_15, test_16 | Each revert finishes; guest file matches that snapshot; both VM snapshots are then gone and the VM stays `Running` | FlexVol snapshots survive the reverts, then both are removed | positive | +| 18 | `test_18_vm_snapshot_duplicate_requests` | VMS-53: two VM snapshot requests for the same VM at once | test_17 | Both snapshots `Ready` (a rejected request is retried) | Two new FlexVol snapshots | positive | +| 19 | `test_19_deploy_second_vm` | Deploy VM-B whose ROOT LUN is on the same ONTAP pool | test_18 | VM-B `Running`; ROOT on pool | One more non-cache LUN; `cs_tmpl_*` still one | positive | +| 20 | `test_20_volume_revert_leaves_other_vm_untouched` | VS-28: revert VM-A's ROOT | test_19 | VM-A's ROOT marker is restored; VM-B's file is unchanged | FlexVol stays `online`; both ROOT LUNs remain | positive | +| 21 | `test_21_concurrent_vm_snapshots_two_vms` | VMS-55: VM snapshots of both VMs at the same time | test_20 | Both VM snapshots `Ready` | Two new FlexVol snapshots | positive | +| 22 | `test_22_concurrent_volume_snapshot_and_revert` | Volume snapshot of VM-A's ROOT while VM-B's ROOT reverts | test_21 | Snapshot `BackedUp` and revert both finish (retried on error 530) | New FlexVol snapshot for the volume snapshot | positive | +| 23 | `test_23_concurrent_vm_snapshot_and_revert` | VM snapshot of VM-A while VM-B reverts to its VM snapshot | test_22 | Both operations finish; VM-A snapshot `Ready` | New FlexVol snapshot for VM-A | positive | +| 24 | `test_24_detach_volume_from_vm` | Hot-detach the iSCSI volume from the running VM (TDS Detach iSCSI) | test_23 (`vm`, `volume`) | `volume.virtualmachineid` cleared | 0 LUN-maps for the data LUN; LUN still in FlexVol | positive ⚠️ | +| 25 | `test_25_grow_detached_volume` | Grow the detached, materialized data volume | test_24 | API and DB size equal target | LUN `space.size` equals target | positive | +| 26 | `test_26_destroy_vm_with_vm_snapshot` | Expunge VM-B while it still has a VM snapshot | test_19 (VM-B) | VM-B no longer listed | VM-B ROOT LUN gone; `cs_tmpl_*` still present | positive | +| 27 | `test_27_destroy_vm_and_cleanup` | Destroy VM (expunge), delete volume, enter maintenance, delete pool | test_25, test_26 | VM gone; spool_ref still Ready after VM expunge; volume gone; pool gone | `cs_tmpl_*` present after VM expunge; FlexVol deleted; all LUNs and igroups deleted | cleanup | + +> ⚠️ **test_24 known status:** iSCSI hot-detach from a running VM relies on the KVM guest acknowledging the SCSI device removal. On this environment the guest does not acknowledge in time, causing CloudStack error 530. This is a KVM-host-level or guest-template limitation, not a test code defect. --- @@ -355,7 +369,7 @@ Each suite is sequential — tests must run in numbered order; each step builds **File:** `iscsi/volume/test_snapshot_to_volume.py` **Class:** `TestOntapIscsiSnapshotToVolume` **Tag:** `iscsi_snapshot_to_volume` -**Total:** 23 tests | **Scope:** create volumes from ROOT and DATA volume snapshots of a running VM, attach them to VMs and check them in CloudStack and ONTAP. Moved out of the VM suite because the full VM suite takes a long time; setup (01–06) and cleanup reuse the same steps. Run this suite in full. +**Total:** 23 tests | **Scope:** dedicated create-volume-from-snapshot coverage for ROOT and DATA volume snapshots of a running VM, including attach and CloudStack/ONTAP checks. Setup (01–06) and cleanup reuse the same steps. Run this suite in full. | # | Test method | Goal | Depends on | CloudStack success criteria | ONTAP success criteria | Type | | --- | ------------- | ------ | ------------ | ----------------------------- | ------------------------ | ------ | @@ -389,7 +403,7 @@ Each suite is sequential — tests must run in numbered order; each step builds **File:** `iscsi/template/test_snapshot_to_template.py` **Class:** `TestOntapIscsiSnapshotToTemplate` **Tag:** `iscsi_snapshot_to_template` -**Total:** 16 tests | **Scope:** create templates from ROOT and DATA volume snapshots, deploy VMs from them and check the results in CloudStack and ONTAP. Moved out of the VM suite because the full VM suite takes a long time; setup (01–05) and cleanup reuse the same steps. Run this suite in full. +**Total:** 16 tests | **Scope:** dedicated create-template-from-snapshot coverage for ROOT and DATA volume snapshots, including VM deployment and CloudStack/ONTAP checks. Setup (01–05) and cleanup reuse the same steps. Run this suite in full. | # | Test method | Goal | Depends on | CloudStack success criteria | ONTAP success criteria | Type | | --- | ------------- | ------ | ------------ | ----------------------------- | ------------------------ | ------ | @@ -449,7 +463,7 @@ Each suite is sequential — tests must run in numbered order; each step builds | NFS3 Pool with Volumes | NFS3 | Cluster | 12 | ✅ | | NFS3 Zone-Scoped Pool | NFS3 | Zone | 5 | ✅ | | NFS3 Volume Lifecycle | NFS3 | Cluster | 5 | Original pure volume lifecycle suite | -| NFS3 VM + Volume Attach | NFS3 | Cluster | 22 | ⏳ resize and snapshot cases pending lab validation | +| NFS3 VM + Volume Attach | NFS3 | Cluster | 29 | ⏳ resize and snapshot cases pending lab validation | | NFS3 Snapshot to Volume | NFS3 | Cluster | 22 | 🆕 includes 10 cases moved from the volume lifecycle suite; not yet lab-run | | NFS3 Snapshot to Template | NFS3 | Cluster | 16 | 🆕 split out of the VM suite; not yet lab-run | | NFS3 Template Cache Negative | NFS3 | Cluster | 3 | 🆕 | @@ -457,8 +471,8 @@ Each suite is sequential — tests must run in numbered order; each step builds | iSCSI Pool with Volumes | iSCSI | Cluster | 13 | ✅ | | iSCSI Zone-Scoped Pool | iSCSI | Zone | 5 | ✅ | | iSCSI Volume Lifecycle | iSCSI | Cluster | 5 | Original pure volume lifecycle suite | -| iSCSI VM + Volume Attach | iSCSI | Cluster | 22 | ⏳ resize and snapshot cases pending lab validation; detach limitation | +| iSCSI VM + Volume Attach | iSCSI | Cluster | 29 | ⏳ resize and snapshot cases pending lab validation; detach limitation | | iSCSI Snapshot to Volume | iSCSI | Cluster | 23 | 🆕 includes 11 cases moved from the volume lifecycle suite; not yet lab-run | | iSCSI Snapshot to Template | iSCSI | Cluster | 16 | 🆕 split out of the VM suite; not yet lab-run | | iSCSI Template Cache Negative | iSCSI | Cluster | 3 | 🆕 | -| **Total** | | | **214** | **Resize and snapshot cases pending lab validation; snapshot-to-volume and snapshot-to-template suites not yet lab-run** | +| **Total** | | | **228** | **Resize and snapshot cases pending lab validation; snapshot-to-volume and snapshot-to-template suites not yet lab-run** | diff --git a/test/integration/plugins/ontap/run_tests.sh b/test/integration/plugins/ontap/run_tests.sh index 5a73adb22553..10b447783588 100755 --- a/test/integration/plugins/ontap/run_tests.sh +++ b/test/integration/plugins/ontap/run_tests.sh @@ -67,6 +67,8 @@ ISCSI_SUITES=( "iSCSI volume lifecycle|iscsi_volume|${ONTAP_DIR}/iscsi/volume/test_volume_lifecycle.py" "iSCSI zone-scoped pool|iscsi_zone_pool|${ONTAP_DIR}/iscsi/pool/test_zone_scoped_pool.py" "iSCSI VM volume workflow|iscsi_vm_workflow|${ONTAP_DIR}/iscsi/instance/test_vm_volume_attach.py" + "iSCSI snapshot to volume|iscsi_snapshot_to_volume|${ONTAP_DIR}/iscsi/volume/test_snapshot_to_volume.py" + "iSCSI snapshot to template|iscsi_snapshot_to_template|${ONTAP_DIR}/iscsi/template/test_snapshot_to_template.py" "iSCSI template cache negative|iscsi_template_cache_negative|${ONTAP_DIR}/iscsi/template/test_template_cache_negative.py" ) @@ -76,6 +78,8 @@ NFS3_SUITES=( "NFS3 volume lifecycle|nfs3_volume|${ONTAP_DIR}/nfs3/volume/test_volume_lifecycle.py" "NFS3 zone-scoped pool|zone_pool|${ONTAP_DIR}/nfs3/pool/test_zone_scoped_pool.py" "NFS3 VM volume attach|vm_volume_workflow|${ONTAP_DIR}/nfs3/instance/test_vm_volume_attach.py" + "NFS3 snapshot to volume|nfs3_snapshot_to_volume|${ONTAP_DIR}/nfs3/volume/test_snapshot_to_volume.py" + "NFS3 snapshot to template|nfs3_snapshot_to_template|${ONTAP_DIR}/nfs3/template/test_snapshot_to_template.py" "NFS3 template cache negative|nfs3_template_cache_negative|${ONTAP_DIR}/nfs3/template/test_template_cache_negative.py" ) From 69599377ddbb0cf497018a80c03674e672af772d Mon Sep 17 00:00:00 2001 From: sp16743 Date: Wed, 2 Dec 2026 15:37:54 +0530 Subject: [PATCH 4/5] snapshot suite updates --- test/integration/plugins/ontap/README.md | 4 ++-- test/integration/plugins/ontap/ontap_test_base.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/test/integration/plugins/ontap/README.md b/test/integration/plugins/ontap/README.md index 4c7fa024ca03..257ea72be218 100644 --- a/test/integration/plugins/ontap/README.md +++ b/test/integration/plugins/ontap/README.md @@ -58,7 +58,7 @@ test/integration/plugins/ontap/ │ │ ├── test_volume_lifecycle.py # Volume create/delete/negative-delete │ │ └── test_snapshot_to_volume.py # Create volumes from snapshots of a running VM, attach, rejects │ ├── instance/ -│ │ └── test_vm_volume_attach.py # Pool + volume + VM + resize, volume/VM snapshots, attach/detach + template cache +│ │ └── test_vm_volume_attach.py # Pool + volume + VM + resize, snapshots, attach/detach + template cache │ └── template/ │ ├── test_snapshot_to_template.py # Create templates from snapshots, deploy VMs from them │ └── test_template_cache_negative.py # Template-cache boundary cases @@ -72,7 +72,7 @@ test/integration/plugins/ontap/ │ ├── test_volume_lifecycle.py # LUN create/delete/negative-delete + create volume from snapshot │ └── test_snapshot_to_volume.py # Create volumes from snapshots of a running VM, attach, rejects ├── instance/ - │ └── test_vm_volume_attach.py # Pool + LUN + VM + resize, volume/VM snapshots, LUN-map lifecycle + template cache + │ └── test_vm_volume_attach.py # Pool + LUN + VM + resize, snapshots, LUN-map lifecycle + template cache └── template/ ├── test_snapshot_to_template.py # Create templates from snapshots, deploy VMs from them └── test_template_cache_negative.py # Template-cache boundary cases diff --git a/test/integration/plugins/ontap/ontap_test_base.py b/test/integration/plugins/ontap/ontap_test_base.py index 1d41318f504b..79024d48ffc7 100644 --- a/test/integration/plugins/ontap/ontap_test_base.py +++ b/test/integration/plugins/ontap/ontap_test_base.py @@ -950,7 +950,7 @@ class OntapTestBase(cloudstackTestCase): # and can be briefly unreachable afterwards, which makes a VM start fail # with "Unable to apply dhcp entry on router". Every wait and retry below # is bounded so a genuine failure is reported, never waited out forever. - ROUTER_HEALTHY_TIMEOUT = 600 # seconds, per wait + ROUTER_HEALTHY_TIMEOUT = 180 # seconds, per wait ROUTER_POLL_INTERVAL = 10 # seconds VM_START_ATTEMPTS = 3 # total tries, including the first VM_START_RETRY_DELAY = 15 # seconds between tries From ff474d5557abd741e87b0e768492c7accd604770 Mon Sep 17 00:00:00 2001 From: sp16743 Date: Wed, 2 Dec 2026 16:33:42 +0530 Subject: [PATCH 5/5] fix pre-commit failure --- .../plugins/ontap/nfs3/volume/test_snapshot_to_volume.py | 1 - 1 file changed, 1 deletion(-) diff --git a/test/integration/plugins/ontap/nfs3/volume/test_snapshot_to_volume.py b/test/integration/plugins/ontap/nfs3/volume/test_snapshot_to_volume.py index da859195a7a7..ef54abc13d50 100644 --- a/test/integration/plugins/ontap/nfs3/volume/test_snapshot_to_volume.py +++ b/test/integration/plugins/ontap/nfs3/volume/test_snapshot_to_volume.py @@ -823,4 +823,3 @@ def test_21_reject_create_with_missing_snapshot_metadata(self): def test_22_destroy_vm_and_cleanup(self): """Destroy the VMs, delete the data volume and the pool.""" self.step_27_destroy_vm_and_cleanup() -