Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion test/integration/plugins/ontap/check_ontap_prereqs.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,12 @@ def main(argv):
print("Unknown protocol filter: %s" % wanted, file=sys.stderr)
return 2

# ontap.cfg starts with "#" licence lines, which Marvin accepts but
# json.load does not.
with open(cfg_path, encoding="utf-8") as stream:
config = json.load(stream)
config = json.loads("".join(
line for line in stream if not line.lstrip().startswith("#")
))

ontap = config.get("ontap") or {}
pool = config.get("storagePool") or {}
Expand Down
316 changes: 316 additions & 0 deletions test/integration/plugins/ontap/helpers/residue_cleanup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,316 @@
# 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.

"""Remove only the ONTAP and KVM-host objects that this environment created.

The ONTAP filer can be shared with other machines running the same tests.
A name prefix such as "OntapMigration" is therefore NOT proof that an object
is ours. Ownership comes from this CloudStack's own database:

* a FlexVol is ours only if its name is the name of a storage pool in this
CloudStack's ``storage_pool`` table (live or removed) AND ONTAP created it
while that pool existed (the name alone can collide with another machine);
* an export policy is ours if its FlexVol was just deleted as ours, or its
pool name is ours and every client in its rules is one of our hosts;
* an igroup is ours only if it is named for a host UUID in this CloudStack's
``host`` table, and only when it has no LUN maps;
* QoS policies are never touched. Their names ("cs_0_to_500_iops_vs0") are
shared by design.

On the KVM hosts, only objects that CloudStack does not know about are
removed: libvirt pools and mounts for pool UUIDs missing from CloudStack,
libvirt domains for instances missing from CloudStack, and iSCSI disks whose
LUN no longer exists on the filer and which no running domain uses.

Every function takes its dependencies as arguments, so it can be tested with
fakes. Each step is independent: one failure is logged and the next step
still runs.
"""

import datetime
import logging
import re

logger = logging.getLogger("ResidueCleanup")

UUID_RE = re.compile(
r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
)
INSTANCE_RE = re.compile(r"^i-\d+-\d+-VM$")


# ---------------------------------------------------------------------------
# ONTAP
# ---------------------------------------------------------------------------

# A FlexVol counts as ours only if ONTAP created it while one of our storage
# pools with that name existed. The tolerance covers clock skew between the
# filer and the CloudStack database.
TIME_TOLERANCE = datetime.timedelta(minutes=5)


def parse_time(value):
"""ISO or "YYYY-MM-DD HH:MM:SS" (UTC) text -> aware UTC datetime or None."""
if value is None:
return None
if isinstance(value, datetime.datetime):
moment = value
else:
text = str(value).strip().replace(" ", "T", 1)
if text.endswith("Z"):
text = text[:-1] + "+00:00"
try:
moment = datetime.datetime.fromisoformat(text)
except ValueError:
return None
if moment.tzinfo is None:
moment = moment.replace(tzinfo=datetime.timezone.utc)
return moment.astimezone(datetime.timezone.utc)


def _created_within_pool_lifetime(create_time, windows):
"""True if create_time lies inside any (created, removed) window."""
moment = parse_time(create_time)
if moment is None:
return False
for created, removed in windows:
start = parse_time(created)
end = parse_time(removed)
if start is None:
continue
if moment < start - TIME_TOLERANCE:
continue
if end is not None and moment > end + TIME_TOLERANCE:
continue
return True
return False


def _normalise_client(match):
return str(match).strip().split("/", 1)[0]


def sweep_ontap(ontap, svm_name, owned_pools, owned_host_uuids, host_ips,
igroup_name, pool_prefix="OntapMigration"):
"""Delete only the ONTAP objects that this CloudStack created.

ontap OntapRestClient
owned_pools {pool name: [(created, removed_or_None), ...]} for every
storage pool this CloudStack has had, live or removed
owned_host_uuids uuids of every host this CloudStack has had
host_ips ip addresses of those hosts
igroup_name igroup_name(host_uuid) -> igroup name used by the plugin
Returns {"volumes", "export_policies", "igroups", "skipped"}.
"""
report = {"volumes": [], "export_policies": [], "igroups": [],
"skipped": []}
owned_ips = {_normalise_client(ip) for ip in (host_ips or ())}

deleted_volumes = set()
try:
volumes = ontap.list_volumes(svm_name, pool_prefix + "*")
except Exception as exc:
logger.warning("Could not list ONTAP volumes: %s", exc)
volumes = []
for volume in volumes:
name = volume["name"]
windows = owned_pools.get(name)
if not windows or not _created_within_pool_lifetime(
volume.get("create_time"), windows):
report["skipped"].append(("volume", name))
continue
try:
for lun_path in ontap.list_lun_paths_in_volume(svm_name, name):
ontap.delete_lun(svm_name, lun_path)
ontap.delete_flexvol_in_svm(svm_name, name)
report["volumes"].append(name)
deleted_volumes.add(name)
except Exception as exc:
logger.warning("Could not delete FlexVol %s: %s", name, exc)

try:
policies = ontap.list_export_policy_names(
svm_name, "cs-%s-%s*" % (svm_name, pool_prefix)
)
except Exception as exc:
logger.warning("Could not list ONTAP export policies: %s", exc)
policies = []
prefix = "cs-%s-" % svm_name
for name in policies:
pool_name = name[len(prefix):] if name.startswith(prefix) else None
try:
if pool_name in deleted_volumes:
owned = True
elif pool_name in owned_pools:
clients = ontap.export_policy_clients(svm_name, name)
owned = bool(clients) and all(
_normalise_client(c) in owned_ips for c in clients)
else:
owned = False
if not owned:
report["skipped"].append(("export-policy", name))
continue
ontap.delete_export_policy_in_svm(svm_name, name)
report["export_policies"].append(name)
except Exception as exc:
logger.warning("Could not delete export policy %s: %s", name, exc)

owned_igroups = {igroup_name(uuid) for uuid in (owned_host_uuids or ())}
try:
igroups = ontap.list_igroup_names(svm_name)
except Exception as exc:
logger.warning("Could not list ONTAP igroups: %s", exc)
igroups = []
for name in igroups:
if name not in owned_igroups:
report["skipped"].append(("igroup", name))
continue
try:
if ontap.igroup_lun_map_count(svm_name, name) > 0:
report["skipped"].append(("igroup-in-use", name))
continue
ontap.delete_igroup(svm_name, name)
report["igroups"].append(name)
except Exception as exc:
logger.warning("Could not delete igroup %s: %s", name, exc)
return report


# ---------------------------------------------------------------------------
# KVM hosts
# ---------------------------------------------------------------------------

def _lines(text):
return [line.strip() for line in str(text or "").splitlines()
if line.strip()]


def sweep_host(run, host, known_pool_uuids, known_instance_names,
live_lun_wwids):
"""Remove objects on one KVM host that CloudStack and ONTAP no longer know.

run run(host, command) -> output text
known_pool_uuids uuids of every storage pool CloudStack still has
known_instance_names instance names of every VM CloudStack still has
live_lun_wwids wwids ("600a0980...") of every LUN on the SVM, or
None when they could not be read (then no iSCSI
disk is removed)
Returns {"pools": [...], "mounts": [...], "domains": [...],
"scsi_disks": [...]}.
"""
report = {"pools": [], "mounts": [], "domains": [], "scsi_disks": []}
known_pools = {str(u).lower() for u in (known_pool_uuids or ())}

# libvirt storage pools whose name is a CloudStack pool uuid CloudStack
# no longer has.
try:
names = _lines(run(host, "virsh pool-list --all --name 2>/dev/null"))
except Exception as exc:
logger.warning("Could not list libvirt pools on %s: %s", host, exc)
names = []
for name in names:
if UUID_RE.match(name) and name.lower() not in known_pools:
try:
run(host,
"virsh pool-destroy %(n)s >/dev/null 2>&1; "
"virsh pool-undefine %(n)s >/dev/null 2>&1; "
"umount /mnt/%(n)s >/dev/null 2>&1; "
"rmdir /mnt/%(n)s >/dev/null 2>&1; true" % {"n": name})
report["pools"].append(name)
except Exception as exc:
logger.warning("Could not remove libvirt pool %s on %s: %s",
name, host, exc)

# NFS mounts under /mnt for a pool uuid CloudStack no longer has.
try:
mounts = _lines(run(
host, "awk '$2 ~ /^\\/mnt\\// {print $2}' /proc/mounts"))
except Exception as exc:
logger.warning("Could not list mounts on %s: %s", host, exc)
mounts = []
for mount in mounts:
uuid = mount.rsplit("/", 1)[-1]
if UUID_RE.match(uuid) and uuid.lower() not in known_pools:
try:
run(host, "umount %(m)s >/dev/null 2>&1; "
"rmdir %(m)s >/dev/null 2>&1; true" % {"m": mount})
report["mounts"].append(mount)
except Exception as exc:
logger.warning("Could not unmount %s on %s: %s",
mount, host, exc)

# libvirt domains of VMs CloudStack no longer has.
known_names = set(known_instance_names or ())
try:
domains = _lines(run(host, "virsh list --all --name 2>/dev/null"))
except Exception as exc:
logger.warning("Could not list domains on %s: %s", host, exc)
domains = []
for domain in domains:
if INSTANCE_RE.match(domain) and domain not in known_names:
try:
run(host, "virsh destroy %(d)s >/dev/null 2>&1; "
"virsh undefine %(d)s --nvram >/dev/null 2>&1 || "
"virsh undefine %(d)s >/dev/null 2>&1; true"
% {"d": domain})
report["domains"].append(domain)
except Exception as exc:
logger.warning("Could not remove domain %s on %s: %s",
domain, host, exc)

# iSCSI disks whose LUN is gone from the filer and which no running
# domain uses.
if live_lun_wwids is None:
# The filer's LUN list could not be read. Without it there is no way
# to tell a stale disk from a live one, so remove none.
logger.warning("No LUN list for %s; leaving iSCSI disks alone", host)
return report
live = {str(w).lower() for w in live_lun_wwids}
try:
listing = _lines(run(
host,
"for d in /sys/block/sd*; do "
"n=$(basename $d); "
"bp=$(ls -l /dev/disk/by-path 2>/dev/null "
"| awk -v n=$n '$NF ~ (\"/\" n \"$\") {print $9}' "
"| grep -m1 iscsi); "
"[ -n \"$bp\" ] || continue; "
"w=$(cat $d/device/wwid 2>/dev/null | sed 's/^naa\\.//'); "
"st=$(cat $d/device/state 2>/dev/null); "
"used=0; "
"for dom in $(virsh list --name 2>/dev/null); do "
"virsh dumpxml $dom 2>/dev/null "
"| grep -qE \"/dev/$n|$bp|$w\" && used=1; done; "
"echo \"$n|$w|$st|$used\"; done"
))
except Exception as exc:
logger.warning("Could not list iSCSI disks on %s: %s", host, exc)
listing = []
for line in listing:
parts = line.split("|")
if len(parts) != 4:
continue
dev, wwid, state, used = parts
if used == "1" or wwid.lower() in live:
continue
try:
run(host, "echo 1 > /sys/block/%s/device/delete" % dev)
report["scsi_disks"].append("%s(%s,%s)" % (dev, wwid, state))
except Exception as exc:
logger.warning("Could not remove SCSI disk %s on %s: %s",
dev, host, exc)
return report
Loading
Loading