fence-agents: master - fencing: Replace all short (getopt) options in code by their long variants

Marek GrĂ¡c marx at fedoraproject.org
Sat Nov 24 10:45:42 UTC 2012


Gitweb:        http://git.fedorahosted.org/git/?p=fence-agents.git;a=commitdiff;h=f89876f8e4e5add91ba0472ef3b0c3aa8ff4d51f
Commit:        f89876f8e4e5add91ba0472ef3b0c3aa8ff4d51f
Parent:        d1eb3d350ba6a5e494a8ef9cf610a5359691cc1f
Author:        Marek 'marx' Grac <mgrac at redhat.com>
AuthorDate:    Fri Nov 23 15:54:34 2012 +0100
Committer:     Marek 'marx' Grac <mgrac at redhat.com>
CommitterDate: Sat Nov 24 11:36:29 2012 +0100

fencing: Replace all short (getopt) options in code by their long variants

Short (getopt) arguments are supported as before but all internal structures now
should use their long variants. This makes code more readable and we should more
easilly avoid problems when overloading short getopt on command line (e.g. -d).
---
 fence/agents/cisco_ucs/fence_cisco_ucs.py     |   18 +++++++-------
 fence/agents/eaton_snmp/fence_eaton_snmp.py   |   20 ++++++++--------
 fence/agents/eps/fence_eps.py                 |   20 ++++++++--------
 fence/agents/ipdu/fence_ipdu.py               |    4 +-
 fence/agents/lib/fencing.py.py                |   30 ++++++++++--------------
 fence/agents/rhevm/fence_rhevm.py             |    8 +++---
 fence/agents/rsb/fence_rsb.py                 |    6 ++--
 fence/agents/virsh/fence_virsh.py             |    4 +-
 fence/agents/vmware_soap/fence_vmware_soap.py |    2 +-
 fence/agents/wti/fence_wti.py                 |    2 +-
 fence/agents/xenapi/fence_xenapi.py           |   22 +++++++++---------
 11 files changed, 66 insertions(+), 70 deletions(-)

diff --git a/fence/agents/cisco_ucs/fence_cisco_ucs.py b/fence/agents/cisco_ucs/fence_cisco_ucs.py
index 335c5e7..12fcd87 100644
--- a/fence/agents/cisco_ucs/fence_cisco_ucs.py
+++ b/fence/agents/cisco_ucs/fence_cisco_ucs.py
@@ -18,7 +18,7 @@ RE_GET_DESC = re.compile(" descr=\"(.*?)\"", re.IGNORECASE)
 
 def get_power_status(conn, options):
 	res = send_command(options, \
-		"<configResolveDn cookie=\"" + options["cookie"] + "\" inHierarchical=\"false\" dn=\"org-root" + options["-s"] + \
+		"<configResolveDn cookie=\"" + options["cookie"] + "\" inHierarchical=\"false\" dn=\"org-root" + options["--suborg"] + \
 		"/ls-" + options["--plug"] + "/power\"/>", \
 		 int(options["--shell-timeout"]))
 
@@ -41,7 +41,7 @@ def set_power_status(conn, options):
 	
 	res = send_command(options, \
 		"<configConfMos cookie=\"" + options["cookie"] + "\" inHierarchical=\"no\">" + \
-		"<inConfigs><pair key=\"org-root" + options["-s"] + "/ls-" + options["--plug"] + "/power\">" + \
+		"<inConfigs><pair key=\"org-root" + options["--suborg"] + "/ls-" + options["--plug"] + "/power\">" + \
 		"<lsPower dn=\"org-root/ls-" + options["--plug"] + "/power\" state=\"" + action + "\" status=\"modified\" />" + \
 		"</pair></inConfigs></configConfMos>", \
 		int(options["--shell-timeout"]))
@@ -70,12 +70,12 @@ def get_list(conn, options):
 
 def send_command(opt, command, timeout):
 	## setup correct URL
-	if opt.has_key("-z"):
+	if opt.has_key("--ssl"):
 		url = "https:"
 	else:
 		url = "http:"
 
-	url += "//" + opt["-a"] + ":" + str(opt["-u"]) + "/nuova"
+	url += "//" + opt["--ip"] + ":" + str(opt["--ipport"]) + "/nuova"
 
 	## send command through pycurl
 	c = pycurl.Curl()
@@ -122,11 +122,11 @@ used with Cisco UCS to fence machines."
 
 	##
 	## Modify suborg to format /suborg
-	if options["-s"] != "":
-		if options["-s"].startswith("/") == False:
-			options["-s"] = "/" + options["-s"]
-		if options["-s"].endswith("/") == True:
-			options["-s"] = options["-s"][0:-1]
+	if options["--suborg"] != "":
+		if options["--suborg"].startswith("/") == False:
+			options["--suborg"] = "/" + options["--suborg"]
+		if options["--suborg"].endswith("/") == True:
+			options["--suborg"] = options["--suborg"][0:-1]
 
 	##
 	## Fence operations
diff --git a/fence/agents/eaton_snmp/fence_eaton_snmp.py b/fence/agents/eaton_snmp/fence_eaton_snmp.py
index e8bdad9..bf6aa9e 100644
--- a/fence/agents/eaton_snmp/fence_eaton_snmp.py
+++ b/fence/agents/eaton_snmp/fence_eaton_snmp.py
@@ -89,19 +89,19 @@ def eaton_resolv_port_id(conn, options):
 
 	# Restore the increment, that was removed in main for ePDU Managed
 	if (device.ident_str == "Eaton Switched ePDU"):
-		options["-n"] = str(int(options["-n"]) + 1)
+		options["--plug"] = str(int(options["--plug"]) + 1)
 
 	# Now we resolv port_id/switch_id
-	if ((options["-n"].isdigit()) and ((not device.has_switches) or (options["-s"].isdigit()))):
-		port_id = int(options["-n"])
+	if ((options["--plug"].isdigit()) and ((not device.has_switches) or (options["--switch"].isdigit()))):
+		port_id = int(options["--plug"])
 
 		if (device.has_switches):
-			switch_id = int(options["-s"])
+			switch_id = int(options["--switch"])
 	else:
 		table = conn.walk(device.outlet_table_oid, 30)
 
 		for x in table:
-			if (x[1].strip('"')==options["-n"]):
+			if (x[1].strip('"')==options["--plug"]):
 				t = x[0].split('.')
 				if (device.has_switches):
 					port_id = int(t[len(t)-1])
@@ -115,8 +115,8 @@ def eaton_resolv_port_id(conn, options):
 	if (port_id==None):
 		# Restore index offset, to provide a valid error output on Managed ePDU
 		if (device.ident_str != "Eaton Switched ePDU"):
-			options["-n"] = str(int(options["-n"]) + 1)
-		fail_usage("Can't find port with name %s!"%(options["-n"]))
+			options["--plug"] = str(int(options["--plug"]) + 1)
+		fail_usage("Can't find port with name %s!"%(options["--plug"]))
 
 def get_power_status(conn, options):
 	global port_id, after_set
@@ -156,7 +156,7 @@ def set_power_status(conn, options):
 
 	oid = ((device.has_switches) and device.control_oid%(switch_id, port_id) or device.control_oid%(port_id))
 
-	conn.set(oid,(options["-o"]=="on" and device.turn_on or device.turn_off))
+	conn.set(oid,(options["--action"]=="on" and device.turn_on or device.turn_off))
 
 
 def get_outlets_status(conn, options):
@@ -213,8 +213,8 @@ def main():
 	# Plug indexing start from zero on ePDU Managed, so we substract '1' from
 	# the user's given plug number.
 	# For Switched ePDU, we will add this back again later.
-	if ((options.has_key("-n")) and (options["-n"].isdigit())):
-		options["-n"] = str(int(options["-n"]) - 1)
+	if ((options.has_key("--plug")) and (options["--plug"].isdigit())):
+		options["--plug"] = str(int(options["--plug"]) - 1)
 
 	docs = { }
 	docs["shortdesc"] = "Fence agent for Eaton over SNMP"
diff --git a/fence/agents/eps/fence_eps.py b/fence/agents/eps/fence_eps.py
index 59fb36b..94f862a 100644
--- a/fence/agents/eps/fence_eps.py
+++ b/fence/agents/eps/fence_eps.py
@@ -25,9 +25,9 @@ def eps_log(options, str):
 def eps_run_command(options, params):
 	try:
 		# New http connection
-		conn = httplib.HTTPConnection(options["-a"])
+		conn = httplib.HTTPConnection(options["--ip"])
 
-		request_str = "/"+options["-c"]
+		request_str = "/"+options["--page"]
 
 		if (params!=""):
 			request_str += "?"+params
@@ -35,12 +35,12 @@ def eps_run_command(options, params):
 		eps_log(options, "GET "+request_str+"\n")
 		conn.putrequest('GET', request_str)
 
-		if (options.has_key("-l")):
-			if (not options.has_key("-p")):
-				options["-p"] = "" # Default is empty password
+		if (options.has_key("--login")):
+			if (not options.has_key("--password")):
+				options["--password"] = "" # Default is empty password
 				
 			# String for Authorization header
-			auth_str = 'Basic ' + string.strip(base64.encodestring(options["-l"]+':'+options["-p"]))
+			auth_str = 'Basic ' + string.strip(base64.encodestring(options["--login"]+':'+options["--password"]))
 			eps_log(options, "Authorization:"+auth_str+"\n")
 			conn.putheader('Authorization', auth_str)
 
@@ -73,16 +73,16 @@ def get_power_status(conn, options):
 	for out_num, out_stat in status:
 		result[out_num] = ("",(out_stat=="1" and "on" or "off"))
 
-	if (not (options["-o"] in ['monitor','list'])):
-		if (not (options["-n"] in result)):
+	if (not (options["--action"] in ['monitor','list'])):
+		if (not (options["--plug"] in result)):
 			fail_usage("Failed: You have to enter existing physical plug!")
 		else:
-			return result[options["-n"]][1]
+			return result[options["--plug"]][1]
 	else:
 		return result
 
 def set_power_status(conn, options):
-	ret_val = eps_run_command(options, "P%s=%s"%(options["-n"], (options["-o"]=="on" and "1" or "0")))
+	ret_val = eps_run_command(options, "P%s=%s"%(options["--plug"], (options["--action"]=="on" and "1" or "0")))
 
 # Define new option
 def eps_define_new_opts():
diff --git a/fence/agents/ipdu/fence_ipdu.py b/fence/agents/ipdu/fence_ipdu.py
index d133832..8b722e9 100644
--- a/fence/agents/ipdu/fence_ipdu.py
+++ b/fence/agents/ipdu/fence_ipdu.py
@@ -66,11 +66,11 @@ def ipdu_resolv_port_id(conn, options):
 		ipdu_set_device(conn, options)
 
 	# Now we resolv port_id/switch_id
-	if ((options["--plug"].isdigit()) and ((not device.has_switches) or (options["-s"].isdigit()))):
+	if ((options["--plug"].isdigit()) and ((not device.has_switches) or (options["--switch"].isdigit()))):
 		port_id = int(options["--plug"])
 
 		if (device.has_switches):
-			switch_id = int(options["-s"])
+			switch_id = int(options["--switch"])
 	else:
 		table = conn.walk(device.outlet_table_oid, 30)
 
diff --git a/fence/agents/lib/fencing.py.py b/fence/agents/lib/fencing.py.py
index 9affaa8..6f911b2 100644
--- a/fence/agents/lib/fencing.py.py
+++ b/fence/agents/lib/fencing.py.py
@@ -222,7 +222,8 @@ all_opt = {
 		"order" : 1 },
 	"managed" : {
 		"getopt" : "s:",
-		"help" : "-s <id>                        Name of the managed system",
+		"longopt" : "managed"
+		"help" : "-s, --managed=<id>             Name of the managed system",
 		"required" : "0",
 		"shortdesc" : "Managed system name",
 		"order" : 1 },
@@ -503,15 +504,15 @@ def metadata(avail_opt, options, docs):
 			default = ""
 			if all_opt[option].has_key("default"):
 				default = "default=\""+str(all_opt[option]["default"])+"\""
-			elif options.has_key("-" + all_opt[option]["getopt"][:-1]):
-				if options["-" + all_opt[option]["getopt"][:-1]]:
+			elif options.has_key("--" + all_opt[option]["longopt"]) and all_opt[option]["getopt"].endswith(":"):
+				if options["--" + all_opt[option]["longopt"]]:
 					try:
-						default = "default=\"" + options["-" + all_opt[option]["getopt"][:-1]] + "\""
+						default = "default=\"" + options["--" + all_opt[option]["longopt"]] + "\""
 					except TypeError:
 						## @todo/@note: Currently there is no clean way how to handle lists
 						## we can create a string from it but we can't set it on command line
-						default = "default=\"" + str(options["-" + all_opt[option]["getopt"][:-1]]) +"\""
-			elif options.has_key("-" + all_opt[option]["getopt"]):
+						default = "default=\"" + str(options["--" + all_opt[option]["longopt"]]) +"\""
+			elif options.has_key("--" + all_opt[option]["longopt"]):
 				default = "default=\"true\" "
 
 			mixed = all_opt[option]["help"]
@@ -584,7 +585,7 @@ def process_input(avail_opt):
 		except getopt.GetoptError, error:
 			fail_usage("Parse error: " + error.msg)
 
-		## Transform longopt to short one which are used in fencing agents
+		## Transform short getopt to long one which are used in fencing agents
 		#####
 		old_opt = opt
 		opt = { }
@@ -592,7 +593,6 @@ def process_input(avail_opt):
 			if o.startswith("--"):
 				for x in all_opt.keys():
 					if all_opt[x].has_key("longopt") and "--" + all_opt[x]["longopt"] == o:
-						opt["-" + all_opt[x]["getopt"].rstrip(":")] = dict(old_opt)[o]
 						opt["--" + all_opt[x]["longopt"]] = dict(old_opt)[o]
 			else:
 				for x in all_opt.keys():
@@ -645,9 +645,9 @@ def process_input(avail_opt):
 				continue
 
 			if all_opt[name]["getopt"].endswith(":"):
-				opt["-"+all_opt[name]["getopt"].rstrip(":")] = value
-			elif ((value == "1") or (value.lower() == "yes") or (value.lower() == "on") or (value.lower() == "true")):
-				opt["-"+all_opt[name]["getopt"]] = "1"
+				opt["--"+all_opt[name]["longopt"].rstrip(":")] = value
+			elif value.lower() in [ "1", "yes", "on", "true" ]:
+				opt["--"+all_opt[name]["longopt"]] = "1"
 	return opt
 
 ##
@@ -671,22 +671,18 @@ def check_input(device_opt, opt):
 
 	## In special cases (show help, metadata or version) we don't need to check anything
 	#####
-	if options.has_key("-h") or options.has_key("-V") or (options.has_key("--action") and options["--action"].lower() == "metadata"):
+	if options.has_key("--help") or options.has_key("--version") or (options.has_key("--action") and options["--action"].lower() == "metadata"):
 		return options
 
 	## Set default values
 	#####
 	for opt in device_opt:
 		if all_opt[opt].has_key("default"):
-			getopt_short = "-" + all_opt[opt]["getopt"].rstrip(":")
 			getopt_long  = "--" + all_opt[opt]["longopt"]
-			if 0 == options.has_key(getopt_short):
-				options[getopt_short] = all_opt[opt]["default"]
 			if 0 == options.has_key(getopt_long):
 				options[getopt_long] = all_opt[opt]["default"]
 
 	options["--action"] = options["--action"].lower()
-	options["-o"] = options["-o"].lower()
 
 	if options.has_key("--verbose"):
 		options["log"] = LOG_MODE_VERBOSE
@@ -725,7 +721,7 @@ def check_input(device_opt, opt):
 	if (0 == options.has_key("--username")) and device_opt.count("login") and (device_opt.count("no_login") == 0):
 		fail_usage("Failed: You have to set login name")
 
-	if 0 == options.has_key("--ip") and 0 == options.has_key("-s"):
+	if 0 == options.has_key("--ip") and 0 == options.has_key("--managed"):
 		fail_usage("Failed: You have to enter fence address")
 
 	if (device_opt.count("no_password") == 0):
diff --git a/fence/agents/rhevm/fence_rhevm.py b/fence/agents/rhevm/fence_rhevm.py
index 0d4de57..cb61df5 100644
--- a/fence/agents/rhevm/fence_rhevm.py
+++ b/fence/agents/rhevm/fence_rhevm.py
@@ -69,12 +69,12 @@ def get_list(conn, options):
 
 def send_command(opt, command, method = "GET"):
 	## setup correct URL
-	if opt.has_key("-z"):
+	if opt.has_key("--ssl"):
 		url = "https:"
 	else:
 		url = "http:"
 
-	url += "//" + opt["-a"] + ":" + str(opt["-u"]) + "/api/" + command
+	url += "//" + opt["--ip"] + ":" + str(opt["--ipport"]) + "/api/" + command
 
 	## send command through pycurl
 	c = pycurl.Curl()
@@ -82,8 +82,8 @@ def send_command(opt, command, method = "GET"):
 	c.setopt(pycurl.URL, url)
 	c.setopt(pycurl.HTTPHEADER, [ "Content-type: application/xml", "Accept: application/xml" ])
 	c.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_BASIC)
-	c.setopt(pycurl.USERPWD, opt["-l"] + ":" + opt["-p"])
-	c.setopt(pycurl.TIMEOUT, int(opt["-Y"]))
+	c.setopt(pycurl.USERPWD, opt["--login"] + ":" + opt["--password"])
+	c.setopt(pycurl.TIMEOUT, int(opt["--shell-timeout"]))
 	c.setopt(pycurl.SSL_VERIFYPEER, 0)
 	c.setopt(pycurl.SSL_VERIFYHOST, 0)
 
diff --git a/fence/agents/rsb/fence_rsb.py b/fence/agents/rsb/fence_rsb.py
index 45a0c06..100836c 100755
--- a/fence/agents/rsb/fence_rsb.py
+++ b/fence/agents/rsb/fence_rsb.py
@@ -52,11 +52,11 @@ def main():
 
 	opt = process_input(device_opt)
 	# option -n for backward compatibility (-n is normally port no)
-	if 1 == opt.has_key("-n"):
-		opt["-u"] = opt["-n"]
+	if 1 == opt.has_key("--telnet_port"):
+		opt["--port"] = opt["--telnet_port"]
 
 	# set default port for telnet only
-	if 0 == opt.has_key("-x") and 0 == opt.has_key("-u"):
+	if 0 == opt.has_key("--ssh") and 0 == opt.has_key("--ipport"):
 		opt["--ipport"] = 3172
 	options = check_input(device_opt, opt)
 
diff --git a/fence/agents/virsh/fence_virsh.py b/fence/agents/virsh/fence_virsh.py
index 2e1474a..81edf6a 100644
--- a/fence/agents/virsh/fence_virsh.py
+++ b/fence/agents/virsh/fence_virsh.py
@@ -16,7 +16,7 @@ BUILD_DATE=""
 #END_VERSION_GENERATION
 
 def get_outlets_status(conn, options):
-	if options.has_key("-d"):
+	if options.has_key("--use-sudo"):
 		prefix = SUDO_PATH + " "
 	else:
 		prefix = ""
@@ -48,7 +48,7 @@ def get_power_status(conn, options):
 		return outlets[options["--plug"]][1]
 
 def set_power_status(conn, options):
-	if options.has_key("-d"):
+	if options.has_key("--use-sudo"):
 		prefix = SUDO_PATH + " "
 	else:
 		prefix = ""
diff --git a/fence/agents/vmware_soap/fence_vmware_soap.py b/fence/agents/vmware_soap/fence_vmware_soap.py
index 9eef969..2572464 100644
--- a/fence/agents/vmware_soap/fence_vmware_soap.py
+++ b/fence/agents/vmware_soap/fence_vmware_soap.py
@@ -19,7 +19,7 @@ def soap_login(options):
 	else:
 		url = "http://"
 	
-	url += options["--ip"] + ":" + str(options["-u"]) + "/sdk"
+	url += options["--ip"] + ":" + str(options["--ipport"]) + "/sdk"
 	conn = Client(url + "/vimService.wsdl")
 	conn.set_options(location = url)
 
diff --git a/fence/agents/wti/fence_wti.py b/fence/agents/wti/fence_wti.py
index 76c0f26..b12648d 100644
--- a/fence/agents/wti/fence_wti.py
+++ b/fence/agents/wti/fence_wti.py
@@ -111,7 +111,7 @@ is running because the connection will block any necessary fencing actions."
 			try:
 				conn = fspawn(options, TELNET_PATH)
 				conn.send("set binary\n")
-				conn.send("open %s -%s\n"%(options["--ip"], options["-u"]))
+				conn.send("open %s -%s\n"%(options["--ip"], options["--ipport"]))
 			except pexpect.ExceptionPexpect, ex:
 				sys.stderr.write(str(ex) + "\n")
 				sys.stderr.write("Due to limitations, binary dependencies on fence agents "
diff --git a/fence/agents/xenapi/fence_xenapi.py b/fence/agents/xenapi/fence_xenapi.py
index 51ebf52..adec13e 100644
--- a/fence/agents/xenapi/fence_xenapi.py
+++ b/fence/agents/xenapi/fence_xenapi.py
@@ -45,7 +45,7 @@ BUILD_DATE=""
 EC_BAD_SESSION 		= 1
 # Find the status of the port given in the -U flag of options.
 def get_power_fn(session, options):
-	if options.has_key("-v"):
+	if options.has_key("--verbose"):
 		verbose = True
 	else:
 		verbose = False
@@ -77,7 +77,7 @@ def get_power_fn(session, options):
 
 # Set the state of the port given in the -U flag of options.
 def set_power_fn(session, options):
-	action = options["-o"].lower()
+	action = options["--action"].lower()
 	
 	try:
 		# Get a reference to the vm specified in the UUID or vm_name/port parameter
@@ -102,7 +102,7 @@ def set_power_fn(session, options):
 # Function to populate an array of virtual machines and their status
 def get_outlet_list(session, options):
 	result = {}
-	if options.has_key("-v"):
+	if options.has_key("--verbose"):
 		verbose = True
 	else:
 		verbose = False
@@ -129,9 +129,9 @@ def get_outlet_list(session, options):
 
 # Function to initiate the XenServer session via the XenAPI library.
 def connect_and_login(options):
-	url = options["-s"]
-	username = options["-l"]
-	password = options["-p"]
+	url = options["--session-url"]
+	username = options["--login"]
+	password = options["--passwd"]
 
 	try:
 		# Create the XML RPC session to the specified URL.
@@ -152,14 +152,14 @@ def connect_and_login(options):
 # this is tried first as this is the only properly unique identifier.
 # Exceptions are not handled in this function, code that calls this must be ready to handle them.
 def return_vm_reference(session, options):
-	if options.has_key("-v"):
+	if options.has_key("--verbose"):
 		verbose = True
 	else:
 		verbose = False
 
 	# Case where the UUID has been specified
-	if options.has_key("-U"):
-		uuid = options["-U"].lower()
+	if options.has_key("--uid"):
+		uuid = options["--uid"].lower()
 		# When using the -n parameter for name, we get an error message (in verbose
 		# mode) that tells us that we didn't find a VM. To immitate that here we
 		# need to catch and re-raise the exception produced by get_by_uuid.
@@ -172,8 +172,8 @@ def return_vm_reference(session, options):
 		
 
 	# Case where the vm_name/port has been specified
-	if options.has_key("-n"):
-		vm_name = options["-n"]
+	if options.has_key("--plug"):
+		vm_name = options["--plug"]
 		vm_arr = session.xenapi.VM.get_by_name_label(vm_name)
 		# Need to make sure that we only have one result as the vm_name may
 		# not be unique. Average case, so do it first.


More information about the cluster-commits mailing list