Blame SOURCES/bz2079889-fence_gce-update.patch

3012c9
--- fence-agents-4.10.0/agents/gce/fence_gce.py	2022-04-29 10:13:50.317888041 +0200
3012c9
+++ fence-agents-4.10.0/agents/gce/fence_gce.py2	2022-04-29 10:17:54.813248566 +0200
3012c9
@@ -2,10 +2,10 @@
3012c9
 
3012c9
 #
3012c9
 # Requires the googleapiclient and oauth2client
3012c9
-# RHEL 7.x: google-api-python-client==1.6.7 python-gflags==2.0 pyasn1==0.4.8 rsa==3.4.2
3012c9
-# RHEL 8.x: nothing additional needed
3012c9
-# SLES 12.x: python-google-api-python-client python-oauth2client python-oauth2client-gce
3012c9
-# SLES 15.x: python3-google-api-python-client python3-oauth2client python3-oauth2client-gce
3012c9
+# RHEL 7.x: google-api-python-client==1.6.7 python-gflags==2.0 pyasn1==0.4.8 rsa==3.4.2 pysocks==1.7.1 httplib2==0.19.0
3012c9
+# RHEL 8.x: pysocks==1.7.1 httplib2==0.19.0
3012c9
+# SLES 12.x: python-google-api-python-client python-oauth2client python-oauth2client-gce pysocks==1.7.1 httplib2==0.19.0
3012c9
+# SLES 15.x: python3-google-api-python-client python3-oauth2client pysocks==1.7.1 httplib2==0.19.0
3012c9
 #
3012c9
 
3012c9
 import atexit
3012c9
@@ -27,7 +27,7 @@
3012c9
   import urllib2 as urlrequest
3012c9
 sys.path.append("@FENCEAGENTSLIBDIR@")
3012c9
 
3012c9
-from fencing import fail_usage, run_delay, all_opt, atexit_handler, check_input, process_input, show_docs, fence_action
3012c9
+from fencing import fail_usage, run_delay, all_opt, atexit_handler, check_input, process_input, show_docs, fence_action, run_command
3012c9
 try:
3012c9
   sys.path.insert(0, '/usr/lib/fence-agents/support/google')
3012c9
   import httplib2
3012c9
@@ -42,6 +42,19 @@
3012c9
 
3012c9
 METADATA_SERVER = 'http://metadata.google.internal/computeMetadata/v1/'
3012c9
 METADATA_HEADERS = {'Metadata-Flavor': 'Google'}
3012c9
+INSTANCE_LINK = 'https://www.googleapis.com/compute/v1/projects/{}/zones/{}/instances/{}'
3012c9
+
3012c9
+def run_on_fail(options):
3012c9
+	if "--runonfail" in options:
3012c9
+		run_command(options, options["--runonfail"])
3012c9
+
3012c9
+def fail_fence_agent(options, message):
3012c9
+	run_on_fail(options)
3012c9
+	fail_usage(message)
3012c9
+
3012c9
+def raise_fence_agent(options, message):
3012c9
+	run_on_fail(options)
3012c9
+	raise Exception(message)
3012c9
 
3012c9
 #
3012c9
 # Will use baremetalsolution setting or the environment variable
3012c9
@@ -66,7 +79,7 @@
3012c9
 			{
3012c9
 				"matchlength": 4,
3012c9
 				"match": "https://compute.googleapis.com/compute/v1/projects/(.*)/zones/(.*)/instances/(.*)/reset(.*)",
3012c9
-				"replace": "https://baremetalsolution.googleapis.com/v1alpha1/projects/\\1/locations/\\2/instances/\\3:resetInstance\\4"
3012c9
+				"replace": "https://baremetalsolution.googleapis.com/v1/projects/\\1/locations/\\2/instances/\\3:resetInstance\\4"
3012c9
 			})
3012c9
 	for uri_replacement in uri_replacements:
3012c9
 		# each uri_replacement should have matchlength, match, and replace
3012c9
@@ -121,14 +134,17 @@
3012c9
 
3012c9
 def get_nodes_list(conn, options):
3012c9
 	result = {}
3012c9
+	if "--zone" not in options:
3012c9
+		fail_fence_agent(options, "Failed: get_nodes_list: Please specify the --zone in the command")
3012c9
 	try:
3012c9
-		instanceList = retry_api_execute(options, conn.instances().list(
3012c9
-			project=options["--project"],
3012c9
-			zone=options["--zone"]))
3012c9
-		for instance in instanceList["items"]:
3012c9
-			result[instance["id"]] = (instance["name"], translate_status(instance["status"]))
3012c9
+		for zone in options["--zone"].split(","):
3012c9
+			instanceList = retry_api_execute(options, conn.instances().list(
3012c9
+				project=options["--project"],
3012c9
+				zone=zone))
3012c9
+			for instance in instanceList["items"]:
3012c9
+				result[instance["id"]] = (instance["name"], translate_status(instance["status"]))
3012c9
 	except Exception as err:
3012c9
-		fail_usage("Failed: get_nodes_list: {}".format(str(err)))
3012c9
+		fail_fence_agent(options, "Failed: get_nodes_list: {}".format(str(err)))
3012c9
 
3012c9
 	return result
3012c9
 
3012c9
@@ -142,23 +158,54 @@
3012c9
 			return "off"
3012c9
 		else:
3012c9
 			return "on"
3012c9
+	# If zone is not listed for an entry we attempt to get it automatically
3012c9
+	instance = options["--plug"]
3012c9
+	zone = get_zone(conn, options, instance) if "--plugzonemap" not in options else options["--plugzonemap"][instance]
3012c9
+	instance_status = get_instance_power_status(conn, options, instance, zone)
3012c9
+	# If any of the instances do not match the intended status we return the
3012c9
+	# the opposite status so that the fence agent can change it.
3012c9
+	if instance_status != options.get("--action"):
3012c9
+		return instance_status
3012c9
+
3012c9
+	return options.get("--action")
3012c9
+
3012c9
+
3012c9
+def get_instance_power_status(conn, options, instance, zone):
3012c9
 	try:
3012c9
-		instance = retry_api_execute(options, conn.instances().get(
3012c9
-				project=options["--project"],
3012c9
-				zone=options["--zone"],
3012c9
-				instance=options["--plug"]))
3012c9
+		instance = retry_api_execute(
3012c9
+				options,
3012c9
+				conn.instances().get(project=options["--project"], zone=zone, instance=instance))
3012c9
 		return translate_status(instance["status"])
3012c9
 	except Exception as err:
3012c9
-		fail_usage("Failed: get_power_status: {}".format(str(err)))
3012c9
+		fail_fence_agent(options, "Failed: get_instance_power_status: {}".format(str(err)))
3012c9
 
3012c9
 
3012c9
-def wait_for_operation(conn, options, operation):
3012c9
+def check_for_existing_operation(conn, options, instance, zone, operation_type):
3012c9
+	logging.debug("check_for_existing_operation")
3012c9
+	if "--baremetalsolution" in options:
3012c9
+		# There is no API for checking in progress operations
3012c9
+		return False
3012c9
+
3012c9
+	project = options["--project"]
3012c9
+	target_link = INSTANCE_LINK.format(project, zone, instance)
3012c9
+	query_filter = '(targetLink = "{}") AND (operationType = "{}") AND (status = "RUNNING")'.format(target_link, operation_type)
3012c9
+	result = retry_api_execute(
3012c9
+			options,
3012c9
+			conn.zoneOperations().list(project=project, zone=zone, filter=query_filter, maxResults=1))
3012c9
+
3012c9
+	if "items" in result and result["items"]:
3012c9
+		logging.info("Existing %s operation found", operation_type)
3012c9
+		return result["items"][0]
3012c9
+
3012c9
+
3012c9
+def wait_for_operation(conn, options, zone, operation):
3012c9
 	if 'name' not in operation:
3012c9
 		logging.warning('Cannot wait for operation to complete, the'
3012c9
 		' requested operation will continue asynchronously')
3012c9
-		return
3012c9
+		return False
3012c9
+
3012c9
+	wait_time = 0
3012c9
 	project = options["--project"]
3012c9
-	zone = options["--zone"]
3012c9
 	while True:
3012c9
 		result = retry_api_execute(options, conn.zoneOperations().get(
3012c9
 			project=project,
3012c9
@@ -166,56 +213,93 @@
3012c9
 			operation=operation['name']))
3012c9
 		if result['status'] == 'DONE':
3012c9
 			if 'error' in result:
3012c9
-				raise Exception(result['error'])
3012c9
-			return
3012c9
+				raise_fence_agent(options, result['error'])
3012c9
+			return True
3012c9
+
3012c9
+		if "--errortimeout" in options and wait_time > int(options["--errortimeout"]):
3012c9
+			raise_fence_agent(options, "Operation did not complete before the timeout.")
3012c9
+
3012c9
+		if "--warntimeout" in options and wait_time > int(options["--warntimeout"]):
3012c9
+			logging.warning("Operation did not complete before the timeout.")
3012c9
+			if "--runonwarn" in options:
3012c9
+				run_command(options, options["--runonwarn"])
3012c9
+			return False
3012c9
+
3012c9
+		wait_time = wait_time + 1
3012c9
 		time.sleep(1)
3012c9
 
3012c9
 
3012c9
 def set_power_status(conn, options):
3012c9
-	logging.debug("set_power_status");
3012c9
+	logging.debug("set_power_status")
3012c9
+	instance = options["--plug"]
3012c9
+	# If zone is not listed for an entry we attempt to get it automatically
3012c9
+	zone = get_zone(conn, options, instance) if "--plugzonemap" not in options else options["--plugzonemap"][instance]
3012c9
+	set_instance_power_status(conn, options, instance, zone, options["--action"])
3012c9
+
3012c9
+
3012c9
+def set_instance_power_status(conn, options, instance, zone, action):
3012c9
+	logging.info("Setting power status of %s in zone %s", instance, zone)
3012c9
+	project = options["--project"]
3012c9
+
3012c9
 	try:
3012c9
-		if options["--action"] == "off":
3012c9
-			logging.info("Issuing poweroff of %s in zone %s" % (options["--plug"], options["--zone"]))
3012c9
-			operation = retry_api_execute(options, conn.instances().stop(
3012c9
-					project=options["--project"],
3012c9
-					zone=options["--zone"],
3012c9
-					instance=options["--plug"]))
3012c9
+		if action == "off":
3012c9
+			logging.info("Issuing poweroff of %s in zone %s", instance, zone)
3012c9
+			operation = check_for_existing_operation(conn, options, instance, zone, "stop")
3012c9
+			if operation and "--earlyexit" in options:
3012c9
+				return
3012c9
+			if not operation:
3012c9
+				operation = retry_api_execute(
3012c9
+						options,
3012c9
+						conn.instances().stop(project=project, zone=zone, instance=instance))
3012c9
 			logging.info("Poweroff command completed, waiting for the operation to complete")
3012c9
-			wait_for_operation(conn, options, operation)
3012c9
-			logging.info("Poweroff of %s in zone %s complete" % (options["--plug"], options["--zone"]))
3012c9
-		elif options["--action"] == "on":
3012c9
-			logging.info("Issuing poweron of %s in zone %s" % (options["--plug"], options["--zone"]))
3012c9
-			operation = retry_api_execute(options, conn.instances().start(
3012c9
-					project=options["--project"],
3012c9
-					zone=options["--zone"],
3012c9
-					instance=options["--plug"]))
3012c9
-			wait_for_operation(conn, options, operation)
3012c9
-			logging.info("Poweron of %s in zone %s complete" % (options["--plug"], options["--zone"]))
3012c9
+			if wait_for_operation(conn, options, zone, operation):
3012c9
+				logging.info("Poweroff of %s in zone %s complete", instance, zone)
3012c9
+		elif action == "on":
3012c9
+			logging.info("Issuing poweron of %s in zone %s", instance, zone)
3012c9
+			operation = check_for_existing_operation(conn, options, instance, zone, "start")
3012c9
+			if operation and "--earlyexit" in options:
3012c9
+				return
3012c9
+			if not operation:
3012c9
+				operation = retry_api_execute(
3012c9
+						options,
3012c9
+						conn.instances().start(project=project, zone=zone, instance=instance))
3012c9
+			if wait_for_operation(conn, options, zone, operation):
3012c9
+				logging.info("Poweron of %s in zone %s complete", instance, zone)
3012c9
 	except Exception as err:
3012c9
-		fail_usage("Failed: set_power_status: {}".format(str(err)))
3012c9
-
3012c9
+		fail_fence_agent(options, "Failed: set_instance_power_status: {}".format(str(err)))
3012c9
 
3012c9
 def power_cycle(conn, options):
3012c9
-	logging.debug("power_cycle");
3012c9
+	logging.debug("power_cycle")
3012c9
+	instance = options["--plug"]
3012c9
+	# If zone is not listed for an entry we attempt to get it automatically
3012c9
+	zone = get_zone(conn, options, instance) if "--plugzonemap" not in options else options["--plugzonemap"][instance]
3012c9
+	return power_cycle_instance(conn, options, instance, zone)
3012c9
+
3012c9
+
3012c9
+def power_cycle_instance(conn, options, instance, zone):
3012c9
+	logging.info("Issuing reset of %s in zone %s", instance, zone)
3012c9
+	project = options["--project"]
3012c9
+
3012c9
 	try:
3012c9
-		logging.info('Issuing reset of %s in zone %s' % (options["--plug"], options["--zone"]))
3012c9
-		operation = retry_api_execute(options, conn.instances().reset(
3012c9
-				project=options["--project"],
3012c9
-				zone=options["--zone"],
3012c9
-				instance=options["--plug"]))
3012c9
-		logging.info("Reset command completed, waiting for the operation to complete")
3012c9
-		wait_for_operation(conn, options, operation)
3012c9
-		logging.info('Reset of %s in zone %s complete' % (options["--plug"], options["--zone"]))
3012c9
+		operation = check_for_existing_operation(conn, options, instance, zone, "reset")
3012c9
+		if operation and "--earlyexit" in options:
3012c9
+			return True
3012c9
+		if not operation:
3012c9
+			operation = retry_api_execute(
3012c9
+					options,
3012c9
+					conn.instances().reset(project=project, zone=zone, instance=instance))
3012c9
+		logging.info("Reset command sent, waiting for the operation to complete")
3012c9
+		if wait_for_operation(conn, options, zone, operation):
3012c9
+			logging.info("Reset of %s in zone %s complete", instance, zone)
3012c9
 		return True
3012c9
 	except Exception as err:
3012c9
-		logging.error("Failed: power_cycle: {}".format(str(err)))
3012c9
-		return False
3012c9
+		logging.exception("Failed: power_cycle")
3012c9
+		raise err
3012c9
 
3012c9
 
3012c9
-def get_zone(conn, options):
3012c9
+def get_zone(conn, options, instance):
3012c9
 	logging.debug("get_zone");
3012c9
 	project = options['--project']
3012c9
-	instance = options['--plug']
3012c9
 	fl = 'name="%s"' % instance
3012c9
 	request = replace_api_uri(options, conn.instances().aggregatedList(project=project, filter=fl))
3012c9
 	while request is not None:
3012c9
@@ -227,7 +311,7 @@
3012c9
 					return inst['zone'].split("/")[-1]
3012c9
 		request = replace_api_uri(options, conn.instances().aggregatedList_next(
3012c9
 				previous_request=request, previous_response=response))
3012c9
-	raise Exception("Unable to find instance %s" % (instance))
3012c9
+	raise_fence_agent(options, "Unable to find instance %s" % (instance))
3012c9
 
3012c9
 
3012c9
 def get_metadata(metadata_key, params=None, timeout=None):
3012c9
@@ -326,13 +410,21 @@
3012c9
 		"required" : "0",
3012c9
 		"order" : 9
3012c9
 	}
3012c9
+	all_opt["plugzonemap"] = {
3012c9
+		"getopt" : ":",
3012c9
+		"longopt" : "plugzonemap",
3012c9
+		"help" : "--plugzonemap=[plugzonemap]    Comma separated zone map when fencing multiple plugs",
3012c9
+		"shortdesc" : "Comma separated zone map when fencing multiple plugs.",
3012c9
+		"required" : "0",
3012c9
+		"order" : 10
3012c9
+	}
3012c9
 	all_opt["proxyhost"] = {
3012c9
 		"getopt" : ":",
3012c9
 		"longopt" : "proxyhost",
3012c9
 		"help" : "--proxyhost=[proxy_host]       The proxy host to use, if one is needed to access the internet (Example: 10.122.0.33)",
3012c9
 		"shortdesc" : "If a proxy is used for internet access, the proxy host should be specified.",
3012c9
 		"required" : "0",
3012c9
-		"order" : 10
3012c9
+		"order" : 11
3012c9
 	}
3012c9
 	all_opt["proxyport"] = {
3012c9
 		"getopt" : ":",
3012c9
@@ -341,7 +433,49 @@
3012c9
 		"help" : "--proxyport=[proxy_port]       The proxy port to use, if one is needed to access the internet (Example: 3127)",
3012c9
 		"shortdesc" : "If a proxy is used for internet access, the proxy port should be specified.",
3012c9
 		"required" : "0",
3012c9
-		"order" : 11
3012c9
+		"order" : 12
3012c9
+	}
3012c9
+	all_opt["earlyexit"] = {
3012c9
+		"getopt" : "",
3012c9
+		"longopt" : "earlyexit",
3012c9
+		"help" : "--earlyexit                    Return early if reset is already in progress",
3012c9
+		"shortdesc" : "If an existing reset operation is detected, the fence agent will return before the operation completes with a 0 return code.",
3012c9
+		"required" : "0",
3012c9
+		"order" : 13
3012c9
+	}
3012c9
+	all_opt["warntimeout"] = {
3012c9
+		"getopt" : ":",
3012c9
+		"type" : "second",
3012c9
+		"longopt" : "warntimeout",
3012c9
+		"help" : "--warntimeout=[warn_timeout]   Timeout seconds before logging a warning and returning a 0 status code",
3012c9
+		"shortdesc" : "If the operation is not completed within the timeout, the cluster operations are allowed to continue.",
3012c9
+		"required" : "0",
3012c9
+		"order" : 14
3012c9
+	}
3012c9
+	all_opt["errortimeout"] = {
3012c9
+		"getopt" : ":",
3012c9
+		"type" : "second",
3012c9
+		"longopt" : "errortimeout",
3012c9
+		"help" : "--errortimeout=[error_timeout] Timeout seconds before failing and returning a non-zero status code",
3012c9
+		"shortdesc" : "If the operation is not completed within the timeout, cluster is notified of the operation failure.",
3012c9
+		"required" : "0",
3012c9
+		"order" : 15
3012c9
+	}
3012c9
+	all_opt["runonwarn"] = {
3012c9
+		"getopt" : ":",
3012c9
+		"longopt" : "runonwarn",
3012c9
+		"help" : "--runonwarn=[run_on_warn]      If a timeout occurs and warning is generated, run the supplied command",
3012c9
+		"shortdesc" : "If a timeout would occur while running the agent, then the supplied command is run.",
3012c9
+		"required" : "0",
3012c9
+		"order" : 16
3012c9
+	}
3012c9
+	all_opt["runonfail"] = {
3012c9
+		"getopt" : ":",
3012c9
+		"longopt" : "runonfail",
3012c9
+		"help" : "--runonfail=[run_on_fail]      If a failure occurs, run the supplied command",
3012c9
+		"shortdesc" : "If a failure would occur while running the agent, then the supplied command is run.",
3012c9
+		"required" : "0",
3012c9
+		"order" : 17
3012c9
 	}
3012c9
 
3012c9
 
3012c9
@@ -350,7 +484,8 @@
3012c9
 
3012c9
 	device_opt = ["port", "no_password", "zone", "project", "stackdriver-logging",
3012c9
 		"method", "baremetalsolution", "apitimeout", "retries", "retrysleep",
3012c9
-		"serviceaccount", "proxyhost", "proxyport"]
3012c9
+		"serviceaccount", "plugzonemap", "proxyhost", "proxyport", "earlyexit",
3012c9
+		"warntimeout", "errortimeout", "runonwarn", "runonfail"]
3012c9
 
3012c9
 	atexit.register(atexit_handler)
3012c9
 
3012c9
@@ -431,22 +566,39 @@
3012c9
 			conn = googleapiclient.discovery.build(
3012c9
 				'compute', 'v1', credentials=credentials, cache_discovery=False)
3012c9
 	except Exception as err:
3012c9
-		fail_usage("Failed: Create GCE compute v1 connection: {}".format(str(err)))
3012c9
+		fail_fence_agent(options, "Failed: Create GCE compute v1 connection: {}".format(str(err)))
3012c9
 
3012c9
 	# Get project and zone
3012c9
 	if not options.get("--project"):
3012c9
 		try:
3012c9
 			options["--project"] = get_metadata('project/project-id')
3012c9
 		except Exception as err:
3012c9
-			fail_usage("Failed retrieving GCE project. Please provide --project option: {}".format(str(err)))
3012c9
+			fail_fence_agent(options, "Failed retrieving GCE project. Please provide --project option: {}".format(str(err)))
3012c9
 
3012c9
 	if "--baremetalsolution" in options:
3012c9
 		options["--zone"] = "none"
3012c9
-	if not options.get("--zone"):
3012c9
-		try:
3012c9
-			options["--zone"] = get_zone(conn, options)
3012c9
-		except Exception as err:
3012c9
-			fail_usage("Failed retrieving GCE zone. Please provide --zone option: {}".format(str(err)))
3012c9
+
3012c9
+	# Populates zone automatically if missing from the command
3012c9
+	zones = [] if not "--zone" in options else options["--zone"].split(",")
3012c9
+	options["--plugzonemap"] = {}
3012c9
+	if "--plug" in options:
3012c9
+		for i, instance in enumerate(options["--plug"].split(",")):
3012c9
+			if len(zones) == 1:
3012c9
+				# If only one zone is specified, use it across all plugs
3012c9
+				options["--plugzonemap"][instance] = zones[0]
3012c9
+				continue
3012c9
+
3012c9
+			if len(zones) - 1 >= i:
3012c9
+				# If we have enough zones specified with the --zone flag use the zone at
3012c9
+				# the same index as the plug
3012c9
+				options["--plugzonemap"][instance] = zones[i]
3012c9
+				continue
3012c9
+
3012c9
+			try:
3012c9
+				# In this case we do not have a zone specified so we attempt to detect it
3012c9
+				options["--plugzonemap"][instance] = get_zone(conn, options, instance)
3012c9
+			except Exception as err:
3012c9
+				fail_fence_agent(options, "Failed retrieving GCE zone. Please provide --zone option: {}".format(str(err)))
3012c9
 
3012c9
 	# Operate the fencing device
3012c9
 	result = fence_action(conn, options, set_power_status, get_power_status, get_nodes_list, power_cycle)