Copilot commented on code in PR #14320: URL: https://github.com/apache/cloudstack/pull/14320#discussion_r4677334957
########## scripts/vm/hypervisor/kvm/kvmvmactivity_rbd.py: ########## @@ -0,0 +1,220 @@ +#!/usr/bin/env python3 +# 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. + +# Ceph RBD flavor of kvmvmactivity.sh. +# +# On NFS/SharedMountPoint storage, VM disk activity is detected via the mtime +# of the volume files on the shared mount point. RBD volumes aren't files on +# a mount point, so instead activity is detected via RBD watchers: as long as +# qemu has an RBD image open (i.e. a VM using that volume is running +# somewhere), the image will have a live watcher. The most recent +# suspect-time/watcher-state is persisted as a RADOS object (per host) +# in place of the "ac-<host>" file used by the NFS/SMP scripts. +# +# The volumes are given in -u, or in a file with -U, which has no limit on the number +# of volumes: one argument of a command is limited to 128 KiB, which is about 3500 +# volumes. The file has the uuids separated by commas or by lines. +# +# The objects and the watchers are read and written over one connection to the Ceph +# cluster with the Python bindings of librados and librbd (python3-rados and +# python3-rbd), which is much faster than "rbd status" for each volume when a host has +# many volumes, see kvmha_rbd.py. The cephx key is not an argument, as it would be +# visible in the process list: it is read from the environment variable CEPH_KEY. +# +# Exit status: 0 with ALIVE or DEAD in the output, 2 if the arguments are not +# valid or if the state of the host could not be found out, which is not a DEAD host. + +import argparse +import os +import re +import sys +import time + +from kvmha_rbd import BindingsError, Ceph, check_bindings, CephError, WatchersError, DEFAULT_WRITE_TIMEOUT, KEY_ENV, heartbeat_max_age, silence_standard_error + +# the interval at which the agents write their heartbeat, if it is not given with -i +DEFAULT_HEARTBEAT_INTERVAL = 60 + + +class Parser(argparse.ArgumentParser): + def error(self, message): + # as the other arguments which are not valid: the exit status 2 says that it is not known whether the host is alive + self.print_usage(sys.stderr) + sys.exit(2) + + +def alive(): + print("=====> ALIVE <=====") + sys.exit(0) + + +def fail(message): + print("=====> %s <======" % message) + sys.exit(2) + + +def main(): + parser = Parser(description="Checks the VM activity of a KVM host on Ceph RBD storage", add_help=False) + parser.add_argument("-s", dest="mon_hosts", default="", help="ceph monitor host(s), comma separated") + parser.add_argument("-o", dest="pool", default="", help="ceph/rbd pool name") + parser.add_argument("-n", dest="user", default="", help="cephx auth user (optional, the key is then in " + KEY_ENV + ")") + parser.add_argument("-h", dest="host", default="", help="host") + parser.add_argument("-u", dest="images", default="", help="volume (rbd image) uuid list, separated by commas") + parser.add_argument("-U", dest="images_file", default="", + help="file with the volume (rbd image) uuid list, separated by commas or by lines, instead of -u") + parser.add_argument("-t", dest="time", default="", + help="current time in seconds (accepted for compatibility with kvmvmactivity.sh, not used)") + parser.add_argument("-d", dest="suspect_time", default="", help="suspect time") + parser.add_argument("-i", dest="interval", default="", + help="interval in seconds at which the agents write their heartbeat, default %d" % DEFAULT_HEARTBEAT_INTERVAL) + parser.add_argument("-w", dest="write_timeout", default="", + help="seconds after which the agent stops a write of the heartbeat, default %d" % DEFAULT_WRITE_TIMEOUT) + parser.add_argument("--help", action="help") + args = parser.parse_args() + + # first of all: the Python bindings are only suggested by the agent packages + try: + check_bindings(watchers=True) + except BindingsError as error: + fail("Unable to check the VM activity, %s" % error) + + key = os.environ.pop(KEY_ENV, "") + if not args.mon_hosts or not args.pool or not args.suspect_time: + sys.exit(2) + # the host (its GUID) names the heartbeat and activity objects + if not args.host: + sys.exit(2) + if args.user and not key: + sys.exit(2) + if not re.fullmatch(r"[0-9]+", args.suspect_time): + sys.exit(2) + suspect_time = int(args.suspect_time) + if args.interval and not re.fullmatch(r"[0-9]+", args.interval): + sys.exit(2) + interval = int(args.interval) if args.interval else DEFAULT_HEARTBEAT_INTERVAL + if args.write_timeout and not re.fullmatch(r"[0-9]+", args.write_timeout): + sys.exit(2) + write_timeout = int(args.write_timeout) if args.write_timeout else DEFAULT_WRITE_TIMEOUT + volumes = args.images + if args.images_file: + try: + with open(args.images_file) as images_file: + volumes = images_file.read() + except OSError: + sys.exit(2) + + silence_standard_error() + ceph = Ceph(args.mon_hosts, args.pool, args.user, key, watchers=True) + try: + check(ceph, args.pool, args.host, volumes, suspect_time, interval, write_timeout) + finally: + ceph.close() + + +def check(ceph, pool, host, volumes, suspect_time, interval, write_timeout): + heartbeat_object = "KVMHA-hb-" + host + activity_object = "KVMHA-ac-" + host + + # the reason why the heartbeat did not show that the host is alive, added to the messages about a DEAD host + heartbeat_note = "" + + def dead(reason): + print("=====> Considering host as DEAD due to %s.%s <======" % (reason, heartbeat_note)) + sys.exit(0) + + # First check: heartbeat object, same as kvmheartbeat_rbd.py + now = int(time.time()) + try: + heartbeat = ceph.read(heartbeat_object).strip() + if not re.fullmatch(r"[0-9]+", heartbeat): + heartbeat_note = " The RADOS object [%s] does not hold a heartbeat." % heartbeat_object + else: + age = now - int(heartbeat) + if age <= heartbeat_max_age(interval, write_timeout): + alive() + heartbeat_note = " The heartbeat in RADOS object [%s] is [%d] seconds old." % (heartbeat_object, age) + except CephError: + heartbeat_note = " The RADOS object [%s] could not be read, it does not exist or Ceph can not be reached." % heartbeat_object + + if not volumes.strip(): + dead("empty UUIDList") Review Comment: This can mark a host as DEAD even when the heartbeat state is unknown/unreadable (e.g., Ceph unreachable or missing/malformed heartbeat), which contradicts the intended semantics described in the PR (unknown should be exit status 2, never DEAD). Consider only declaring DEAD on an empty volume list if you already positively determined the heartbeat is stale (valid heartbeat object + age > max), otherwise return 'unable to tell' (exit 2) via fail()/sys.exit(2). ########## utils/src/main/java/com/cloud/utils/RbdUtils.java: ########## @@ -0,0 +1,78 @@ +// 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. + +package com.cloud.utils; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang3.StringUtils; + +public class RbdUtils { + + private RbdUtils() { + } + + /** + * Returns the Ceph monitors as expected by "--mon-host": the comma-separated monitors of the pool, trimmed + * and without empty entries. If the pool has a monitor port, it is added to each monitor which has none yet. + * + * @param sourceHost the comma-separated monitors, IPv4 or IPv6 addresses or host names + * @param sourcePort the port of the monitors, or 0 (or less) if the pool has none + */ + public static String getRbdMonitors(String sourceHost, int sourcePort) { + List<String> monitors = new ArrayList<>(); + for (String monitor : sourceHost.split(",")) { + monitor = monitor.trim(); + if (monitor.isEmpty()) { + continue; + } + monitors.add(sourcePort > 0 ? addPortToRbdMonitor(monitor, sourcePort) : monitor); + } + return String.join(",", monitors); + } Review Comment: `getRbdMonitors` will throw a NullPointerException if `sourceHost` is null (public utility method; no null contract documented). Consider handling null/blank inputs explicitly (e.g., return an empty string for blank input, or throw an IllegalArgumentException with a clear message) to avoid surprising NPEs. ########## plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/KVMStoragePoolManager.java: ########## @@ -445,27 +453,49 @@ public boolean disconnectPhysicalDisk(StoragePoolType type, String poolUuid, Str public synchronized boolean deleteStoragePool(StoragePoolType type, String uuid) { StorageAdaptor adaptor = getStorageAdaptor(type); - if (type == StoragePoolType.NetworkFilesystem) { - _haMonitor.unregisterStoragePool(uuid); - } - boolean deleteStatus = adaptor.deleteStoragePool(uuid); - synchronized (_storagePools) { - _storagePools.remove(uuid); - } - return deleteStatus; + return deleteStoragePoolWithoutHaMonitoring(type, uuid, () -> adaptor.deleteStoragePool(uuid)); } public boolean deleteStoragePool(StoragePoolType type, String uuid, Map<String, String> details) { StorageAdaptor adaptor = getStorageAdaptor(type); - boolean deleteStatus; - if (type == StoragePoolType.NetworkFilesystem) { + return deleteStoragePoolWithoutHaMonitoring(type, uuid, () -> { + if (type == StoragePoolType.NetworkFilesystem) { + return adaptor.deleteStoragePool(uuid); + } + // the other pool types, also RBD and SharedMountPoint, keep the delete which takes the details: it does not + // destroy the libvirt pool of a pool which is still used by the VMs, e.g. in maintenance of the pool + return adaptor.deleteStoragePool(uuid, details); + }); + } + + /** + * Deletes a storage pool after it is no longer monitored for HA. The monitor writes the heartbeats while it holds its lock, + * so none is on going when the pool is unregistered, and none is written while the pool is removed, which could fail + * and fence the host. If the pool is not deleted (the delete does not succeed or throws) it is still there, so it is + * monitored for HA again: the heartbeat of the host on it must go on, and it stays known to the manager as well. + * The types with HA support are libvirt storage pools, which are only not deleted if they are still there. For the + * other types a delete which does not succeed means that the adaptor has no such pool, so it is forgotten as before. + */ + private boolean deleteStoragePoolWithoutHaMonitoring(StoragePoolType type, String uuid, BooleanSupplier delete) { + boolean haSupported = HighAvailabilityManager.LIBVIRT_STORAGE_POOL_TYPES_WITH_HA_SUPPORT.contains(type); + KVMHABase.HAStoragePool haPool = null; + if (haSupported) { + haPool = _haMonitor.getStoragePool(uuid); _haMonitor.unregisterStoragePool(uuid); - deleteStatus = adaptor.deleteStoragePool(uuid); - } else { - deleteStatus = adaptor.deleteStoragePool(uuid, details); } - synchronized (_storagePools) { - _storagePools.remove(uuid); + boolean deleteStatus = false; + try { + deleteStatus = delete.getAsBoolean(); + } finally { + if (!deleteStatus && haPool != null) { + logger.warn("The storage pool {} was not deleted, so it is monitored for HA again.", uuid); + _haMonitor.addStoragePool(haPool); + } + } + if (deleteStatus || !haSupported) { + synchronized (_storagePools) { + _storagePools.remove(uuid); + } } return deleteStatus; } Review Comment: This relies on a subtle contract: for HA-supported pool types, `delete.getAsBoolean()` must return `false` only when the pool still exists (so it should remain in `_storagePools` and be re-monitored). If any HA-supported adaptor returns `false` to mean 'pool not found', this logic will retain stale entries and re-monitor a non-existent pool. Consider tightening/encoding this contract (e.g., adaptors throw on 'not found', or return a richer result/enum), or add an explicit existence check for HA-supported pools before deciding to keep `_storagePools` and re-add to the HA monitor. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
