diff --git a/test/integration/plugins/ontap/README.md b/test/integration/plugins/ontap/README.md index 6a40a1402c2e..257ea72be218 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 (228 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 │ └── 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 └── 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`: @@ -383,12 +387,16 @@ another ONTAP pool is present. | 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 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 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). diff --git a/test/integration/plugins/ontap/TEST_CASES.md b/test/integration/plugins/ontap/TEST_CASES.md index 4145e3c5eb79..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 151 test cases across 12 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. --- @@ -169,6 +169,66 @@ Each suite is sequential — tests must run in numbered order; each step builds --- +## 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:** 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 | +| --- | ------------- | ------ | ------------ | ----------------------------- | ------------------------ | ------ | +| 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:** 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 | +| --- | ------------- | ------ | ------------ | ----------------------------- | ------------------------ | ------ | +| 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` @@ -304,6 +364,67 @@ Each suite is sequential — tests must run in numbered order; each step builds --- +## 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:** 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 | +| --- | ------------- | ------ | ------------ | ----------------------------- | ------------------------ | ------ | +| 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:** 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 | +| --- | ------------- | ------ | ------------ | ----------------------------- | ------------------------ | ------ | +| 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 +462,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 Volume Lifecycle | NFS3 | Cluster | 5 | Original pure volume lifecycle suite | | 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 | 🆕 | | 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 Volume Lifecycle | iSCSI | Cluster | 5 | Original pure volume lifecycle suite | | 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** | | | **151** | **Resize and snapshot cases pending lab validation** | +| **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/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/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..ef54abc13d50 --- /dev/null +++ b/test/integration/plugins/ontap/nfs3/volume/test_snapshot_to_volume.py @@ -0,0 +1,825 @@ +# 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..79024d48ffc7 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. @@ -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", + )) 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" )