diff --git a/fence/agents/lpar/fence_lpar.py b/fence/agents/lpar/fence_lpar.py index c1bf7d7e..6676e1c6 100644 --- a/fence/agents/lpar/fence_lpar.py +++ b/fence/agents/lpar/fence_lpar.py @@ -1,159 +1,159 @@ #!/usr/bin/python -tt ##### ## ## The Following Agent Has Been Tested On: ## ## Version ## +---------------------------------------------+ ## Tested on HMC ## ##### import sys, re import atexit sys.path.append("@FENCEAGENTSLIBDIR@") from fencing import * from fencing import fail, fail_usage, EC_STATUS_HMC #BEGIN_VERSION_GENERATION RELEASE_VERSION="" REDHAT_COPYRIGHT="" BUILD_DATE="" #END_VERSION_GENERATION def get_power_status(conn, options): if options["--hmc-version"] == "3": conn.send("lssyscfg -r lpar -m " + options["--managed"] + " -n " + options["--plug"] + " -F name,state\n") conn.log_expect(options["--command-prompt"], int(options["--power-timeout"])) try: status = re.compile("^" + options["--plug"] + ",(.*?),.*$", re.IGNORECASE | re.MULTILINE).search(conn.before).group(1) except AttributeError: fail(EC_STATUS_HMC) elif options["--hmc-version"] == "4": conn.send("lssyscfg -r lpar -m "+ options["--managed"] + " --filter 'lpar_names=" + options["--plug"] + "'\n") conn.log_expect(options["--command-prompt"], int(options["--power-timeout"])) try: status = re.compile(",state=(.*?),", re.IGNORECASE).search(conn.before).group(1) except AttributeError: fail(EC_STATUS_HMC) ## ## Transformation to standard ON/OFF status if possible if status in ["Running", "Open Firmware", "Shutting Down", "Starting"]: status = "on" else: status = "off" return status def set_power_status(conn, options): if options["--hmc-version"] == "3": conn.send("chsysstate -o " + options["--action"] + " -r lpar -m " + options["--managed"] + " -n " + options["--plug"] + "\n") conn.log_expect(options["--command-prompt"], int(options["--power-timeout"])) elif options["--hmc-version"] == "4": if options["--action"] == "on": conn.send("chsysstate -o on -r lpar -m " + options["--managed"] + " -n " + options["--plug"] + " -f `lssyscfg -r lpar -F curr_profile " + " -m " + options["--managed"] + " --filter \"lpar_names=" + options["--plug"] + "\"`\n") else: conn.send("chsysstate -o shutdown -r lpar --immed" + " -m " + options["--managed"] + " -n " + options["--plug"] + "\n") conn.log_expect(options["--command-prompt"], int(options["--power-timeout"])) def get_lpar_list(conn, options): outlets = {} if options["--hmc-version"] == "3": conn.send("query_partition_names -m " + options["--managed"] + "\n") conn.log_expect(options["--command-prompt"], int(options["--power-timeout"])) ## We have to remove first 3 lines (command + header) and last line (part of new prompt) #### res = re.search("^.+?\n(.+?\n){2}(.*)\n.*$", conn.before, re.S) if res == None: fail_usage("Unable to parse output of list command") lines = res.group(2).split("\n") for outlet_line in lines: outlets[outlet_line.rstrip()] = ("", "") elif options["--hmc-version"] == "4": conn.send("lssyscfg -r lpar -m " + options["--managed"] + " -F name:state\n") conn.log_expect(options["--command-prompt"], int(options["--power-timeout"])) ## We have to remove first line (command) and last line (part of new prompt) #### res = re.search("^.+?\n(.*)\n.*$", conn.before, re.S) if res == None: fail_usage("Unable to parse output of list command") lines = res.group(1).split("\n") for outlet_line in lines: (port, status) = outlet_line.split(":") outlets[port] = ("", status) return outlets def define_new_opts(): all_opt["managed"] = { "getopt" : "s:", "longopt" : "managed", "help" : "-s, --managed=[id] Name of the managed system", "required" : "0", "shortdesc" : "Managed system name", "order" : 1} all_opt["hmc_version"] = { "getopt" : "H:", "longopt" : "hmc-version", "help" : "-H, --hmc-version=[version] Force HMC version to use: (3|4) (default: 4)", "required" : "0", "shortdesc" : "Force HMC version to use", "default" : "4", "choices" : ["3", "4"], "order" : 1} def main(): device_opt = ["ipaddr", "login", "passwd", "secure", "cmd_prompt", \ "port", "managed", "hmc_version"] atexit.register(atexit_handler) define_new_opts() all_opt["login_timeout"]["default"] = "15" all_opt["secure"]["default"] = "1" all_opt["cmd_prompt"]["default"] = [r":~>", r"]\$", r"\$ "] options = check_input(device_opt, process_input(device_opt), other_conditions = True) docs = {} docs["shortdesc"] = "Fence agent for IBM LPAR" docs["longdesc"] = "" docs["vendorurl"] = "http://www.ibm.com" show_docs(options, docs) if not options.has_key("--managed"): fail_usage("Failed: You have to enter name of managed system") - if options["--action"] == "validate-all": - sys.exit(0) + if options["--action"] == "validate-all": + sys.exit(0) ## ## Operate the fencing device #### conn = fence_login(options) result = fence_action(conn, options, set_power_status, get_power_status, get_lpar_list) fence_logout(conn, "quit\r\n") sys.exit(result) if __name__ == "__main__": main() diff --git a/fence/agents/mpath/fence_mpath.py b/fence/agents/mpath/fence_mpath.py index b2464b0d..94c3163d 100644 --- a/fence/agents/mpath/fence_mpath.py +++ b/fence/agents/mpath/fence_mpath.py @@ -1,247 +1,247 @@ #!/usr/bin/python -tt import sys import stat import re import os import logging import atexit sys.path.append("@FENCEAGENTSLIBDIR@") from fencing import fail_usage, run_command, atexit_handler, check_input, process_input, show_docs from fencing import fence_action, all_opt, run_delay #BEGIN_VERSION_GENERATION RELEASE_VERSION="" REDHAT_COPYRIGHT="" BUILD_DATE="" #END_VERSION_GENERATION def get_status(conn, options): del conn status = "off" for dev in options["devices"]: is_block_device(dev) if options["--key"] in get_registration_keys(options, dev): status = "on" else: logging.debug("No registration for key "\ + options["--key"] + " on device " + dev + "\n") return status def set_status(conn, options): del conn count = 0 if options["--action"] == "on": for dev in options["devices"]: is_block_device(dev) register_dev(options, dev) if options["--key"] not in get_registration_keys(options, dev): count += 1 logging.debug("Failed to register key "\ + options["--key"] + "on device " + dev + "\n") continue dev_write(options, dev) if get_reservation_key(options, dev) is None \ and not reserve_dev(options, dev) \ and get_reservation_key(options, dev) is None: count += 1 logging.debug("Failed to create reservation (key="\ + options["--key"] + ", device=" + dev + ")\n") else: dev_keys = dev_read(options) for dev in options["devices"]: is_block_device(dev) if options["--key"] in get_registration_keys(options, dev): preempt_abort(options, dev_keys[dev], dev) for dev in options["devices"]: if options["--key"] in get_registration_keys(options, dev): count += 1 logging.debug("Failed to remove key "\ + options["--key"] + " on device " + dev + "\n") continue if not get_reservation_key(options, dev): count += 1 logging.debug("No reservation exists on device " + dev + "\n") if count: logging.error("Failed to verify " + str(count) + " device(s)") sys.exit(1) #run command, returns dict, ret["err"] = exit code; ret["out"] = output def run_cmd(options, cmd): ret = {} if options.has_key("--use-sudo"): prefix = options["--sudo-path"] + " " else: prefix = "" (ret["err"], ret["out"], _) = run_command(options, prefix + cmd) ret["out"] = "".join([i for i in ret["out"] if i is not None]) return ret # check if device exist and is block device def is_block_device(dev): if not os.path.exists(dev): fail_usage("Failed: device \"" + dev + "\" does not exist") if not stat.S_ISBLK(os.stat(dev).st_mode): fail_usage("Failed: device \"" + dev + "\" is not a block device") # cancel registration def preempt_abort(options, host, dev): cmd = options["--mpathpersist-path"] + " -o --preempt-abort --prout-type=5 --param-rk=" + host +" --param-sark=" + options["--key"] +"-d " + dev return not bool(run_cmd(options, cmd)["err"]) def register_dev(options, dev): cmd = options["--mpathpersist-path"] + " -o --register --param-sark=" + options["--key"] + " -d " + dev #cmd return code != 0 but registration can be successful return not bool(run_cmd(options, cmd)["err"]) def reserve_dev(options, dev): cmd = options["--mpathpersist-path"] + " -o --reserv --prout-type=5 --param-rk=" + options["--key"] + " -d " + dev return not bool(run_cmd(options, cmd)["err"]) def get_reservation_key(options, dev): cmd = options["--mpathpersist-path"] + " -i -r -d " + dev out = run_cmd(options, cmd) if out["err"]: fail_usage("Cannot get reservation key") match = re.search(r"\s+key\s*=\s*0x(\S+)\s+", out["out"], re.IGNORECASE) return match.group(1) if match else None def get_registration_keys(options, dev): keys = [] cmd = options["--mpathpersist-path"] + " -i -k -d " + dev out = run_cmd(options, cmd) if out["err"]: fail_usage("Cannot get registration keys") for line in out["out"].split("\n"): match = re.search(r"\s+0x(\S+)\s*", line) if match: keys.append(match.group(1)) return keys def dev_write(options, dev): file_path = options["--store-path"] + "/mpath.devices" if not os.path.isdir(os.path.dirname(options["--store-path"])): os.makedirs(os.path.dirname(options["--store-path"])) try: store_fh = open(file_path, "a+") except IOError: fail_usage("Failed: Cannot open file \""+ file_path + "\"") out = store_fh.read() if not re.search(r"^" + dev + r"\s+", out): store_fh.write(dev + "\t" + options["--key"] + "\n") store_fh.close() def dev_read(options): dev_key = {} file_path = options["--store-path"] + "/mpath.devices" try: store_fh = open(file_path, "r") except IOError: fail_usage("Failed: Cannot open file \"" + file_path + "\"") # get not empty lines from file for (device, key) in [line.strip().split() for line in store_fh if line.strip()]: dev_key[device] = key store_fh.close() return dev_key def define_new_opts(): all_opt["devices"] = { "getopt" : "d:", "longopt" : "devices", "help" : "-d, --devices=[devices] List of devices to use for current operation", "required" : "0", "shortdesc" : "List of devices to use for current operation. Devices can \ be comma-separated list of device-mapper multipath devices (eg. /dev/dm-3). \ Each device must support SCSI-3 persistent reservations.", "order": 1 } all_opt["key"] = { "getopt" : "k:", "longopt" : "key", "help" : "-k, --key=[key] Key to use for the current operation", "required" : "1", "shortdesc" : "Key to use for the current operation. This key should be \ unique to a node and have to be written in /etc/multipath.conf. For the \"on\" action, the key specifies the key use to \ register the local node. For the \"off\" action, this key specifies the key to \ be removed from the device(s).", "order": 1 } all_opt["mpathpersist_path"] = { "getopt" : ":", "longopt" : "mpathpersist-path", "help" : "--mpathpersist-path=[path] Path to mpathpersist binary", "required" : "0", "shortdesc" : "Path to mpathpersist binary", "default" : "@MPATH_PATH@", "order": 200 } all_opt["store_path"] = { "getopt" : ":", "longopt" : "store-path", "help" : "--store-path=[path] Path to directory containing cached keys", "required" : "0", "shortdesc" : "Path to directory where fence agent can store information", "default" : "@STORE_PATH@", "order": 200 } def main(): atexit.register(atexit_handler) device_opt = ["no_login", "no_password", "devices", "key", "sudo", \ "fabric_fencing", "on_target", "store_path", "mpathpersist_path"] define_new_opts() options = check_input(device_opt, process_input(device_opt), other_conditions=True) docs = {} docs["shortdesc"] = "Fence agent for multipath persistent reservation" docs["longdesc"] = "fence_mpath is an I/O fencing agent that uses SCSI-3 \ persistent reservations to control access multipath devices. Underlying \ devices must support SCSI-3 persistent reservations (SPC-3 or greater) as \ well as the \"preempt-and-abort\" subcommand.\nThe fence_mpath agent works by \ having an unique key for each pair of node and device that has to be set also \ in /etc/multipath.conf. Once registered, a single node will become the reservation holder \ by creating a \"write exclusive, registrants only\" reservation on the \ device(s). The result is that only registered nodes may write to the \ device(s). When a node failure occurs, the fence_mpath agent will remove the \ key belonging to the failed node from the device(s). The failed node will no \ longer be able to write to the device(s). A manual reboot is required." docs["vendorurl"] = "https://www.sourceware.org/dm/" show_docs(options, docs) run_delay(options) # Input control BEGIN if not "--key" in options: fail_usage("Failed: key is required") - if options["--action"] == "validate-all": - sys.exit(0) + if options["--action"] == "validate-all": + sys.exit(0) options["devices"] = options["--devices"].split(",") if not options["devices"]: fail_usage("Failed: No devices found") # Input control END result = fence_action(None, options, set_status, get_status) sys.exit(result) if __name__ == "__main__": main() diff --git a/fence/agents/zvm/fence_zvmip.py b/fence/agents/zvm/fence_zvmip.py index 6d09b685..60dd8946 100644 --- a/fence/agents/zvm/fence_zvmip.py +++ b/fence/agents/zvm/fence_zvmip.py @@ -1,175 +1,175 @@ #!/usr/bin/python -tt import sys import atexit import socket import struct import logging sys.path.append("@FENCEAGENTSLIBDIR@") from fencing import * from fencing import fail, fail_usage, run_delay, EC_LOGIN_DENIED, EC_TIMED_OUT #BEGIN_VERSION_GENERATION RELEASE_VERSION="" REDHAT_COPYRIGHT="" BUILD_DATE="" #END_VERSION_GENERATION INT4 = 4 def open_socket(options): try: if "--inet6-only" in options: protocol = socket.AF_INET6 elif "--inet4-only" in options: protocol = socket.AF_INET else: protocol = 0 (_, _, _, _, addr) = socket.getaddrinfo( \ options["--ip"], options["--ipport"], protocol, 0, socket.IPPROTO_TCP, socket.AI_PASSIVE )[0] except socket.gaierror: fail(EC_LOGIN_DENIED) conn = socket.socket() conn.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) conn.settimeout(float(options["--shell-timeout"])) try: conn.connect(addr) except socket.error: fail(EC_LOGIN_DENIED) return conn def smapi_pack_string(string): return struct.pack("!i%ds" % (len(string)), len(string), string) def prepare_smapi_command(options, smapi_function, additional_args): packet_size = 3*INT4 + len(smapi_function) + len(options["--username"]) + len(options["--password"]) for arg in additional_args: packet_size += INT4 + len(arg) command = struct.pack("!i", packet_size) command += smapi_pack_string(smapi_function) command += smapi_pack_string(options["--username"]) command += smapi_pack_string(options["--password"]) for arg in additional_args: command += smapi_pack_string(arg) return command def get_power_status(conn, options): del conn # '*' = list all active images (return_code, reason_code, images_active) = \ get_list_of_images(options, "Image_Status_Query", "*") logging.debug("Image_Status_Query results are (%d,%d)", return_code, reason_code) (return_code, reason_code, images_defined) = \ get_list_of_images(options, "Image_Name_Query_DM", options["--username"]) logging.debug("Image_Name_Query_DM results are (%d,%d)", return_code, reason_code) if ["list", "monitor"].count(options["--action"]) == 1: return dict([(i, ("", "on" if i in images_active else "off")) for i in images_defined]) else: status = "error" if options["--plug"].upper() in images_defined: if options["--plug"].upper() in images_active: status = "on" else: status = "off" return status def set_power_status(conn, options): conn = open_socket(options) packet = None if options["--action"] == "on": packet = prepare_smapi_command(options, "Image_Activate", [options["--plug"]]) elif options["--action"] == "off": packet = prepare_smapi_command(options, "Image_Deactivate", [options["--plug"], "IMMED"]) conn.send(packet) request_id = struct.unpack("!i", conn.recv(INT4))[0] (output_len, request_id, return_code, reason_code) = struct.unpack("!iiii", conn.recv(INT4 * 4)) logging.debug("Image_(De)Activate results are (%d,%d)", return_code, reason_code) conn.close() return def get_list_of_images(options, command, data_as_plug): conn = open_socket(options) packet = prepare_smapi_command(options, command, [data_as_plug]) conn.send(packet) request_id = struct.unpack("!i", conn.recv(INT4))[0] (output_len, request_id, return_code, reason_code) = struct.unpack("!iiii", conn.recv(INT4 * 4)) images = set() if output_len > 3*INT4: array_len = struct.unpack("!i", conn.recv(INT4))[0] data = "" while True: read_data = conn.recv(1024, socket.MSG_WAITALL) data += read_data if array_len == len(data): break elif not read_data: logging.error("Failed: Not enough data read from socket") fail(EC_TIMED_OUT) parsed_len = 0 while parsed_len < array_len: string_len = struct.unpack("!i", data[parsed_len:parsed_len+INT4])[0] parsed_len += INT4 image_name = struct.unpack("!%ds" % (string_len), data[parsed_len:parsed_len+string_len])[0] parsed_len += string_len images.add(image_name) conn.close() return (return_code, reason_code, images) def main(): device_opt = ["ipaddr", "login", "passwd", "port", "method"] atexit.register(atexit_handler) all_opt["ipport"]["default"] = "44444" all_opt["shell_timeout"]["default"] = "5.0" options = check_input(device_opt, process_input(device_opt), other_conditions=True) if len(options.get("--plug", "")) > 8: fail_usage("Failed: Name of image can not be longer than 8 characters") - if options["--action"] == "validate-all": - sys.exit(0) + if options["--action"] == "validate-all": + sys.exit(0) docs = {} docs["shortdesc"] = "Fence agent for use with z/VM Virtual Machines" docs["longdesc"] = """The fence_zvm agent is intended to be used with with z/VM SMAPI service via TCP/IP To use this agent the z/VM SMAPI service needs to be configured to allow the virtual machine running this agent to connect to it and issue the image_recycle operation. This involves updating the VSMWORK1 AUTHLIST VMSYS:VSMWORK1. file. The entry should look something similar to this: Column 1 Column 66 Column 131 | | | V V V XXXXXXXX ALL IMAGE_OPERATIONS Where XXXXXXX is the name of the virtual machine used in the authuser field of the request. """ docs["vendorurl"] = "http://www.ibm.com" show_docs(options, docs) run_delay(options) result = fence_action(None, options, set_power_status, get_power_status, get_power_status) sys.exit(result) if __name__ == "__main__": main()