35697a
--- fence-agents-4.2.1/agents/gce/fence_gce.py	2022-04-28 15:58:42.949723547 +0200
35697a
+++ fence-agents-4.2.1/agents/gce/fence_gce.py2	2022-04-28 15:59:21.054915265 +0200
35697a
@@ -1,10 +1,22 @@
35697a
 #!@PYTHON@ -tt
35697a
 
35697a
+#
35697a
+# Requires the googleapiclient and oauth2client
35697a
+# 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
35697a
+# RHEL 8.x: pysocks==1.7.1 httplib2==0.19.0
35697a
+# SLES 12.x: python-google-api-python-client python-oauth2client python-oauth2client-gce pysocks==1.7.1 httplib2==0.19.0
35697a
+# SLES 15.x: python3-google-api-python-client python3-oauth2client pysocks==1.7.1 httplib2==0.19.0
35697a
+#
35697a
+
35697a
 import atexit
35697a
 import logging
35697a
+import json
35697a
+import re
35697a
 import os
35697a
+import socket
35697a
 import sys
35697a
 import time
35697a
+
35697a
 if sys.version_info >= (3, 0):
35697a
   # Python 3 imports.
35697a
   import urllib.parse as urlparse
35697a
@@ -15,7 +27,7 @@
35697a
   import urllib2 as urlrequest
35697a
 sys.path.append("@FENCEAGENTSLIBDIR@")
35697a
 
35697a
-from fencing import fail_usage, run_delay, all_opt, atexit_handler, check_input, process_input, show_docs, fence_action
35697a
+from fencing import fail_usage, run_delay, all_opt, atexit_handler, check_input, process_input, show_docs, fence_action, run_command
35697a
 try:
35697a
   sys.path.insert(0, '/usr/lib/fence-agents/bundled/google')
35697a
   import httplib2
35697a
@@ -30,6 +42,85 @@
35697a
 
35697a
 METADATA_SERVER = 'http://metadata.google.internal/computeMetadata/v1/'
35697a
 METADATA_HEADERS = {'Metadata-Flavor': 'Google'}
35697a
+INSTANCE_LINK = 'https://www.googleapis.com/compute/v1/projects/{}/zones/{}/instances/{}'
35697a
+
35697a
+def run_on_fail(options):
35697a
+	if "--runonfail" in options:
35697a
+		run_command(options, options["--runonfail"])
35697a
+
35697a
+def fail_fence_agent(options, message):
35697a
+	run_on_fail(options)
35697a
+	fail_usage(message)
35697a
+
35697a
+def raise_fence_agent(options, message):
35697a
+	run_on_fail(options)
35697a
+	raise Exception(message)
35697a
+
35697a
+#
35697a
+# Will use baremetalsolution setting or the environment variable
35697a
+# FENCE_GCE_URI_REPLACEMENTS to replace the uri for calls to *.googleapis.com.
35697a
+#
35697a
+def replace_api_uri(options, http_request):
35697a
+	uri_replacements = []
35697a
+	# put any env var replacements first, then baremetalsolution if in options
35697a
+	if "FENCE_GCE_URI_REPLACEMENTS" in os.environ:
35697a
+		logging.debug("FENCE_GCE_URI_REPLACEMENTS environment variable exists")
35697a
+		env_uri_replacements = os.environ["FENCE_GCE_URI_REPLACEMENTS"]
35697a
+		try:
35697a
+			uri_replacements_json = json.loads(env_uri_replacements)
35697a
+			if isinstance(uri_replacements_json, list):
35697a
+				uri_replacements = uri_replacements_json
35697a
+			else:
35697a
+				logging.warning("FENCE_GCE_URI_REPLACEMENTS exists, but is not a JSON List")
35697a
+		except ValueError as e:
35697a
+			logging.warning("FENCE_GCE_URI_REPLACEMENTS exists but is not valid JSON")
35697a
+	if "--baremetalsolution" in options:
35697a
+		uri_replacements.append(
35697a
+			{
35697a
+				"matchlength": 4,
35697a
+				"match": "https://compute.googleapis.com/compute/v1/projects/(.*)/zones/(.*)/instances/(.*)/reset(.*)",
35697a
+				"replace": "https://baremetalsolution.googleapis.com/v1/projects/\\1/locations/\\2/instances/\\3:resetInstance\\4"
35697a
+			})
35697a
+	for uri_replacement in uri_replacements:
35697a
+		# each uri_replacement should have matchlength, match, and replace
35697a
+		if "matchlength" not in uri_replacement or "match" not in uri_replacement or "replace" not in uri_replacement:
35697a
+			logging.warning("FENCE_GCE_URI_REPLACEMENTS missing matchlength, match, or replace in %s" % uri_replacement)
35697a
+			continue
35697a
+		match = re.match(uri_replacement["match"], http_request.uri)
35697a
+		if match is None or len(match.groups()) != uri_replacement["matchlength"]:
35697a
+			continue
35697a
+		replaced_uri = re.sub(uri_replacement["match"], uri_replacement["replace"], http_request.uri)
35697a
+		match = re.match("https:\/\/.*.googleapis.com", replaced_uri)
35697a
+		if match is None or match.start() != 0:
35697a
+			logging.warning("FENCE_GCE_URI_REPLACEMENTS replace is not "
35697a
+				"targeting googleapis.com, ignoring it: %s" % replaced_uri)
35697a
+			continue
35697a
+		logging.debug("Replacing googleapis uri %s with %s" % (http_request.uri, replaced_uri))
35697a
+		http_request.uri = replaced_uri
35697a
+		break
35697a
+	return http_request
35697a
+
35697a
+def retry_api_execute(options, http_request):
35697a
+	replaced_http_request = replace_api_uri(options, http_request)
35697a
+	retries = 3
35697a
+	if options.get("--retries"):
35697a
+		retries = int(options.get("--retries"))
35697a
+	retry_sleep = 5
35697a
+	if options.get("--retrysleep"):
35697a
+		retry_sleep = int(options.get("--retrysleep"))
35697a
+	retry = 0
35697a
+	current_err = None
35697a
+	while retry <= retries:
35697a
+		if retry > 0:
35697a
+			time.sleep(retry_sleep)
35697a
+		try:
35697a
+			return replaced_http_request.execute()
35697a
+		except Exception as err:
35697a
+			current_err = err
35697a
+			logging.warning("Could not execute api call to: %s, retry: %s, "
35697a
+				"err: %s" % (replaced_http_request.uri, retry, str(err)))
35697a
+		retry += 1
35697a
+	raise current_err
35697a
 
35697a
 
35697a
 def translate_status(instance_status):
35697a
@@ -43,86 +134,174 @@
35697a
 
35697a
 def get_nodes_list(conn, options):
35697a
 	result = {}
35697a
+	if "--zone" not in options:
35697a
+		fail_fence_agent(options, "Failed: get_nodes_list: Please specify the --zone in the command")
35697a
 	try:
35697a
-		instanceList = conn.instances().list(project=options["--project"], zone=options["--zone"]).execute()
35697a
-		for instance in instanceList["items"]:
35697a
-			result[instance["id"]] = (instance["name"], translate_status(instance["status"]))
35697a
+		for zone in options["--zone"].split(","):
35697a
+			instanceList = retry_api_execute(options, conn.instances().list(
35697a
+				project=options["--project"],
35697a
+				zone=zone))
35697a
+			for instance in instanceList["items"]:
35697a
+				result[instance["id"]] = (instance["name"], translate_status(instance["status"]))
35697a
 	except Exception as err:
35697a
-		fail_usage("Failed: get_nodes_list: {}".format(str(err)))
35697a
+		fail_fence_agent(options, "Failed: get_nodes_list: {}".format(str(err)))
35697a
 
35697a
 	return result
35697a
 
35697a
 
35697a
 def get_power_status(conn, options):
35697a
+	logging.debug("get_power_status")
35697a
+	# if this is bare metal we need to just send back the opposite of the
35697a
+	# requested action: if on send off, if off send on
35697a
+	if "--baremetalsolution" in options:
35697a
+		if options.get("--action") == "on":
35697a
+			return "off"
35697a
+		else:
35697a
+			return "on"
35697a
+	# If zone is not listed for an entry we attempt to get it automatically
35697a
+	instance = options["--plug"]
35697a
+	zone = get_zone(conn, options, instance) if "--plugzonemap" not in options else options["--plugzonemap"][instance]
35697a
+	instance_status = get_instance_power_status(conn, options, instance, zone)
35697a
+	# If any of the instances do not match the intended status we return the
35697a
+	# the opposite status so that the fence agent can change it.
35697a
+	if instance_status != options.get("--action"):
35697a
+		return instance_status
35697a
+
35697a
+	return options.get("--action")
35697a
+
35697a
+
35697a
+def get_instance_power_status(conn, options, instance, zone):
35697a
 	try:
35697a
-		instance = conn.instances().get(
35697a
-				project=options["--project"],
35697a
-				zone=options["--zone"],
35697a
-				instance=options["--plug"]).execute()
35697a
+		instance = retry_api_execute(
35697a
+				options,
35697a
+				conn.instances().get(project=options["--project"], zone=zone, instance=instance))
35697a
 		return translate_status(instance["status"])
35697a
 	except Exception as err:
35697a
-		fail_usage("Failed: get_power_status: {}".format(str(err)))
35697a
+		fail_fence_agent(options, "Failed: get_instance_power_status: {}".format(str(err)))
35697a
 
35697a
 
35697a
-def wait_for_operation(conn, project, zone, operation):
35697a
+def check_for_existing_operation(conn, options, instance, zone, operation_type):
35697a
+	logging.debug("check_for_existing_operation")
35697a
+	if "--baremetalsolution" in options:
35697a
+		# There is no API for checking in progress operations
35697a
+		return False
35697a
+
35697a
+	project = options["--project"]
35697a
+	target_link = INSTANCE_LINK.format(project, zone, instance)
35697a
+	query_filter = '(targetLink = "{}") AND (operationType = "{}") AND (status = "RUNNING")'.format(target_link, operation_type)
35697a
+	result = retry_api_execute(
35697a
+			options,
35697a
+			conn.zoneOperations().list(project=project, zone=zone, filter=query_filter, maxResults=1))
35697a
+
35697a
+	if "items" in result and result["items"]:
35697a
+		logging.info("Existing %s operation found", operation_type)
35697a
+		return result["items"][0]
35697a
+
35697a
+
35697a
+def wait_for_operation(conn, options, zone, operation):
35697a
+	if 'name' not in operation:
35697a
+		logging.warning('Cannot wait for operation to complete, the'
35697a
+		' requested operation will continue asynchronously')
35697a
+		return False
35697a
+
35697a
+	wait_time = 0
35697a
+	project = options["--project"]
35697a
 	while True:
35697a
-		result = conn.zoneOperations().get(
35697a
+		result = retry_api_execute(options, conn.zoneOperations().get(
35697a
 			project=project,
35697a
 			zone=zone,
35697a
-			operation=operation['name']).execute()
35697a
+			operation=operation['name']))
35697a
 		if result['status'] == 'DONE':
35697a
 			if 'error' in result:
35697a
-				raise Exception(result['error'])
35697a
-			return
35697a
+				raise_fence_agent(options, result['error'])
35697a
+			return True
35697a
+
35697a
+		if "--errortimeout" in options and wait_time > int(options["--errortimeout"]):
35697a
+			raise_fence_agent(options, "Operation did not complete before the timeout.")
35697a
+
35697a
+		if "--warntimeout" in options and wait_time > int(options["--warntimeout"]):
35697a
+			logging.warning("Operation did not complete before the timeout.")
35697a
+			if "--runonwarn" in options:
35697a
+				run_command(options, options["--runonwarn"])
35697a
+			return False
35697a
+
35697a
+		wait_time = wait_time + 1
35697a
 		time.sleep(1)
35697a
 
35697a
 
35697a
 def set_power_status(conn, options):
35697a
+	logging.debug("set_power_status")
35697a
+	instance = options["--plug"]
35697a
+	# If zone is not listed for an entry we attempt to get it automatically
35697a
+	zone = get_zone(conn, options, instance) if "--plugzonemap" not in options else options["--plugzonemap"][instance]
35697a
+	set_instance_power_status(conn, options, instance, zone, options["--action"])
35697a
+
35697a
+
35697a
+def set_instance_power_status(conn, options, instance, zone, action):
35697a
+	logging.info("Setting power status of %s in zone %s", instance, zone)
35697a
+	project = options["--project"]
35697a
+
35697a
 	try:
35697a
-		if options["--action"] == "off":
35697a
-			logging.info("Issuing poweroff of %s in zone %s" % (options["--plug"], options["--zone"]))
35697a
-			operation = conn.instances().stop(
35697a
-					project=options["--project"],
35697a
-					zone=options["--zone"],
35697a
-					instance=options["--plug"]).execute()
35697a
-			wait_for_operation(conn, options["--project"], options["--zone"], operation)
35697a
-			logging.info("Poweroff of %s in zone %s complete" % (options["--plug"], options["--zone"]))
35697a
-		elif options["--action"] == "on":
35697a
-			logging.info("Issuing poweron of %s in zone %s" % (options["--plug"], options["--zone"]))
35697a
-			operation = conn.instances().start(
35697a
-					project=options["--project"],
35697a
-					zone=options["--zone"],
35697a
-					instance=options["--plug"]).execute()
35697a
-			wait_for_operation(conn, options["--project"], options["--zone"], operation)
35697a
-			logging.info("Poweron of %s in zone %s complete" % (options["--plug"], options["--zone"]))
35697a
+		if action == "off":
35697a
+			logging.info("Issuing poweroff of %s in zone %s", instance, zone)
35697a
+			operation = check_for_existing_operation(conn, options, instance, zone, "stop")
35697a
+			if operation and "--earlyexit" in options:
35697a
+				return
35697a
+			if not operation:
35697a
+				operation = retry_api_execute(
35697a
+						options,
35697a
+						conn.instances().stop(project=project, zone=zone, instance=instance))
35697a
+			logging.info("Poweroff command completed, waiting for the operation to complete")
35697a
+			if wait_for_operation(conn, options, zone, operation):
35697a
+				logging.info("Poweroff of %s in zone %s complete", instance, zone)
35697a
+		elif action == "on":
35697a
+			logging.info("Issuing poweron of %s in zone %s", instance, zone)
35697a
+			operation = check_for_existing_operation(conn, options, instance, zone, "start")
35697a
+			if operation and "--earlyexit" in options:
35697a
+				return
35697a
+			if not operation:
35697a
+				operation = retry_api_execute(
35697a
+						options,
35697a
+						conn.instances().start(project=project, zone=zone, instance=instance))
35697a
+			if wait_for_operation(conn, options, zone, operation):
35697a
+				logging.info("Poweron of %s in zone %s complete", instance, zone)
35697a
 	except Exception as err:
35697a
-		fail_usage("Failed: set_power_status: {}".format(str(err)))
35697a
-
35697a
+		fail_fence_agent(options, "Failed: set_instance_power_status: {}".format(str(err)))
35697a
 
35697a
 def power_cycle(conn, options):
35697a
+	logging.debug("power_cycle")
35697a
+	instance = options["--plug"]
35697a
+	# If zone is not listed for an entry we attempt to get it automatically
35697a
+	zone = get_zone(conn, options, instance) if "--plugzonemap" not in options else options["--plugzonemap"][instance]
35697a
+	return power_cycle_instance(conn, options, instance, zone)
35697a
+
35697a
+
35697a
+def power_cycle_instance(conn, options, instance, zone):
35697a
+	logging.info("Issuing reset of %s in zone %s", instance, zone)
35697a
+	project = options["--project"]
35697a
+
35697a
 	try:
35697a
-		logging.info('Issuing reset of %s in zone %s' % (options["--plug"], options["--zone"]))
35697a
-		operation = conn.instances().reset(
35697a
-				project=options["--project"],
35697a
-				zone=options["--zone"],
35697a
-				instance=options["--plug"]).execute()
35697a
-		wait_for_operation(conn, options["--project"], options["--zone"], operation)
35697a
-		logging.info('Reset of %s in zone %s complete' % (options["--plug"], options["--zone"]))
35697a
+		operation = check_for_existing_operation(conn, options, instance, zone, "reset")
35697a
+		if operation and "--earlyexit" in options:
35697a
+			return True
35697a
+		if not operation:
35697a
+			operation = retry_api_execute(
35697a
+					options,
35697a
+					conn.instances().reset(project=project, zone=zone, instance=instance))
35697a
+		logging.info("Reset command sent, waiting for the operation to complete")
35697a
+		if wait_for_operation(conn, options, zone, operation):
35697a
+			logging.info("Reset of %s in zone %s complete", instance, zone)
35697a
 		return True
35697a
 	except Exception as err:
35697a
-		logging.error("Failed: power_cycle: {}".format(str(err)))
35697a
-		return False
35697a
-
35697a
-
35697a
-def get_instance(conn, project, zone, instance):
35697a
-	request = conn.instances().get(
35697a
-			project=project, zone=zone, instance=instance)
35697a
-	return request.execute()
35697a
+		logging.exception("Failed: power_cycle")
35697a
+		raise err
35697a
 
35697a
 
35697a
-def get_zone(conn, project, instance):
35697a
+def get_zone(conn, options, instance):
35697a
+	logging.debug("get_zone");
35697a
+	project = options['--project']
35697a
 	fl = 'name="%s"' % instance
35697a
-	request = conn.instances().aggregatedList(project=project, filter=fl)
35697a
+	request = replace_api_uri(options, conn.instances().aggregatedList(project=project, filter=fl))
35697a
 	while request is not None:
35697a
 		response = request.execute()
35697a
 		zones = response.get('items', {})
35697a
@@ -130,9 +309,9 @@
35697a
 			for inst in zone.get('instances', []):
35697a
 				if inst['name'] == instance:
35697a
 					return inst['zone'].split("/")[-1]
35697a
-		request = conn.instances().aggregatedList_next(
35697a
-				previous_request=request, previous_response=response)
35697a
-	raise Exception("Unable to find instance %s" % (instance))
35697a
+		request = replace_api_uri(options, conn.instances().aggregatedList_next(
35697a
+				previous_request=request, previous_response=response))
35697a
+	raise_fence_agent(options, "Unable to find instance %s" % (instance))
35697a
 
35697a
 
35697a
 def get_metadata(metadata_key, params=None, timeout=None):
35697a
@@ -149,6 +328,7 @@
35697a
 	Raises:
35697a
 		urlerror.HTTPError: raises when the GET request fails.
35697a
 	"""
35697a
+	logging.debug("get_metadata");
35697a
 	timeout = timeout or 60
35697a
 	metadata_url = os.path.join(METADATA_SERVER, metadata_key)
35697a
 	params = urlparse.urlencode(params or {})
35697a
@@ -178,12 +358,50 @@
35697a
 	all_opt["stackdriver-logging"] = {
35697a
 		"getopt" : "",
35697a
 		"longopt" : "stackdriver-logging",
35697a
-		"help" : "--stackdriver-logging		Enable Logging to Stackdriver. Using stackdriver logging requires additional libraries (google-cloud-logging).",
35697a
-		"shortdesc" : "Stackdriver-logging support. Requires additional libraries (google-cloud-logging).",
35697a
-		"longdesc" : "If enabled IP failover logs will be posted to stackdriver logging. Using stackdriver logging requires additional libraries (google-cloud-logging).",
35697a
+		"help" : "--stackdriver-logging          Enable Logging to Stackdriver",
35697a
+		"shortdesc" : "Stackdriver-logging support.",
35697a
+		"longdesc" : "If enabled IP failover logs will be posted to stackdriver logging.",
35697a
 		"required" : "0",
35697a
 		"order" : 4
35697a
 	}
35697a
+	all_opt["baremetalsolution"] = {
35697a
+		"getopt" : "",
35697a
+		"longopt" : "baremetalsolution",
35697a
+		"help" : "--baremetalsolution            Enable on bare metal",
35697a
+		"shortdesc" : "If enabled this is a bare metal offering from google.",
35697a
+		"required" : "0",
35697a
+		"order" : 5
35697a
+	}
35697a
+	all_opt["apitimeout"] = {
35697a
+		"getopt" : ":",
35697a
+		"type" : "second",
35697a
+		"longopt" : "apitimeout",
35697a
+		"help" : "--apitimeout=[seconds]         Timeout to use for API calls",
35697a
+		"shortdesc" : "Timeout in seconds to use for API calls, default is 60.",
35697a
+		"required" : "0",
35697a
+		"default" : 60,
35697a
+		"order" : 6
35697a
+	}
35697a
+	all_opt["retries"] = {
35697a
+		"getopt" : ":",
35697a
+		"type" : "integer",
35697a
+		"longopt" : "retries",
35697a
+		"help" : "--retries=[retries]            Number of retries on failure for API calls",
35697a
+		"shortdesc" : "Number of retries on failure for API calls, default is 3.",
35697a
+		"required" : "0",
35697a
+		"default" : 3,
35697a
+		"order" : 7
35697a
+	}
35697a
+	all_opt["retrysleep"] = {
35697a
+		"getopt" : ":",
35697a
+		"type" : "second",
35697a
+		"longopt" : "retrysleep",
35697a
+		"help" : "--retrysleep=[seconds]         Time to sleep between API retries",
35697a
+		"shortdesc" : "Time to sleep in seconds between API retries, default is 5.",
35697a
+		"required" : "0",
35697a
+		"default" : 5,
35697a
+		"order" : 8
35697a
+	}
35697a
 	all_opt["serviceaccount"] = {
35697a
 		"getopt" : ":",
35697a
 		"longopt" : "serviceaccount",
35697a
@@ -192,13 +410,21 @@
35697a
 		"required" : "0",
35697a
 		"order" : 9
35697a
 	}
35697a
+	all_opt["plugzonemap"] = {
35697a
+		"getopt" : ":",
35697a
+		"longopt" : "plugzonemap",
35697a
+		"help" : "--plugzonemap=[plugzonemap]    Comma separated zone map when fencing multiple plugs",
35697a
+		"shortdesc" : "Comma separated zone map when fencing multiple plugs.",
35697a
+		"required" : "0",
35697a
+		"order" : 10
35697a
+	}
35697a
 	all_opt["proxyhost"] = {
35697a
 		"getopt" : ":",
35697a
 		"longopt" : "proxyhost",
35697a
 		"help" : "--proxyhost=[proxy_host]       The proxy host to use, if one is needed to access the internet (Example: 10.122.0.33)",
35697a
 		"shortdesc" : "If a proxy is used for internet access, the proxy host should be specified.",
35697a
 		"required" : "0",
35697a
-		"order" : 10
35697a
+		"order" : 11
35697a
 	}
35697a
 	all_opt["proxyport"] = {
35697a
 		"getopt" : ":",
35697a
@@ -207,7 +433,49 @@
35697a
 		"help" : "--proxyport=[proxy_port]       The proxy port to use, if one is needed to access the internet (Example: 3127)",
35697a
 		"shortdesc" : "If a proxy is used for internet access, the proxy port should be specified.",
35697a
 		"required" : "0",
35697a
-		"order" : 11
35697a
+		"order" : 12
35697a
+	}
35697a
+	all_opt["earlyexit"] = {
35697a
+		"getopt" : "",
35697a
+		"longopt" : "earlyexit",
35697a
+		"help" : "--earlyexit                    Return early if reset is already in progress",
35697a
+		"shortdesc" : "If an existing reset operation is detected, the fence agent will return before the operation completes with a 0 return code.",
35697a
+		"required" : "0",
35697a
+		"order" : 13
35697a
+	}
35697a
+	all_opt["warntimeout"] = {
35697a
+		"getopt" : ":",
35697a
+		"type" : "second",
35697a
+		"longopt" : "warntimeout",
35697a
+		"help" : "--warntimeout=[warn_timeout]   Timeout seconds before logging a warning and returning a 0 status code",
35697a
+		"shortdesc" : "If the operation is not completed within the timeout, the cluster operations are allowed to continue.",
35697a
+		"required" : "0",
35697a
+		"order" : 14
35697a
+	}
35697a
+	all_opt["errortimeout"] = {
35697a
+		"getopt" : ":",
35697a
+		"type" : "second",
35697a
+		"longopt" : "errortimeout",
35697a
+		"help" : "--errortimeout=[error_timeout] Timeout seconds before failing and returning a non-zero status code",
35697a
+		"shortdesc" : "If the operation is not completed within the timeout, cluster is notified of the operation failure.",
35697a
+		"required" : "0",
35697a
+		"order" : 15
35697a
+	}
35697a
+	all_opt["runonwarn"] = {
35697a
+		"getopt" : ":",
35697a
+		"longopt" : "runonwarn",
35697a
+		"help" : "--runonwarn=[run_on_warn]      If a timeout occurs and warning is generated, run the supplied command",
35697a
+		"shortdesc" : "If a timeout would occur while running the agent, then the supplied command is run.",
35697a
+		"required" : "0",
35697a
+		"order" : 16
35697a
+	}
35697a
+	all_opt["runonfail"] = {
35697a
+		"getopt" : ":",
35697a
+		"longopt" : "runonfail",
35697a
+		"help" : "--runonfail=[run_on_fail]      If a failure occurs, run the supplied command",
35697a
+		"shortdesc" : "If a failure would occur while running the agent, then the supplied command is run.",
35697a
+		"required" : "0",
35697a
+		"order" : 17
35697a
 	}
35697a
 
35697a
 
35697a
@@ -215,7 +483,9 @@
35697a
 	conn = None
35697a
 
35697a
 	device_opt = ["port", "no_password", "zone", "project", "stackdriver-logging",
35697a
-		"method", "serviceaccount", "proxyhost", "proxyport"]
35697a
+		"method", "baremetalsolution", "apitimeout", "retries", "retrysleep",
35697a
+		"serviceaccount", "plugzonemap", "proxyhost", "proxyport", "earlyexit",
35697a
+		"warntimeout", "errortimeout", "runonwarn", "runonfail"]
35697a
 
35697a
 	atexit.register(atexit_handler)
35697a
 
35697a
@@ -259,6 +529,11 @@
35697a
 			logging.error('Couldn\'t import google.cloud.logging, '
35697a
 				'disabling Stackdriver-logging support')
35697a
 
35697a
+  # if apitimeout is defined we set the socket timeout, if not we keep the
35697a
+  # socket default which is 60s
35697a
+	if options.get("--apitimeout"):
35697a
+		socket.setdefaulttimeout(options["--apitimeout"])
35697a
+
35697a
 	# Prepare cli
35697a
 	try:
35697a
 		serviceaccount = options.get("--serviceaccount")
35697a
@@ -291,20 +566,39 @@
35697a
 			conn = googleapiclient.discovery.build(
35697a
 				'compute', 'v1', credentials=credentials, cache_discovery=False)
35697a
 	except Exception as err:
35697a
-		fail_usage("Failed: Create GCE compute v1 connection: {}".format(str(err)))
35697a
+		fail_fence_agent(options, "Failed: Create GCE compute v1 connection: {}".format(str(err)))
35697a
 
35697a
 	# Get project and zone
35697a
 	if not options.get("--project"):
35697a
 		try:
35697a
 			options["--project"] = get_metadata('project/project-id')
35697a
 		except Exception as err:
35697a
-			fail_usage("Failed retrieving GCE project. Please provide --project option: {}".format(str(err)))
35697a
+			fail_fence_agent(options, "Failed retrieving GCE project. Please provide --project option: {}".format(str(err)))
35697a
 
35697a
-	if not options.get("--zone"):
35697a
-		try:
35697a
-			options["--zone"] = get_zone(conn, options['--project'], options['--plug'])
35697a
-		except Exception as err:
35697a
-			fail_usage("Failed retrieving GCE zone. Please provide --zone option: {}".format(str(err)))
35697a
+	if "--baremetalsolution" in options:
35697a
+		options["--zone"] = "none"
35697a
+
35697a
+	# Populates zone automatically if missing from the command
35697a
+	zones = [] if not "--zone" in options else options["--zone"].split(",")
35697a
+	options["--plugzonemap"] = {}
35697a
+	if "--plug" in options:
35697a
+		for i, instance in enumerate(options["--plug"].split(",")):
35697a
+			if len(zones) == 1:
35697a
+				# If only one zone is specified, use it across all plugs
35697a
+				options["--plugzonemap"][instance] = zones[0]
35697a
+				continue
35697a
+
35697a
+			if len(zones) - 1 >= i:
35697a
+				# If we have enough zones specified with the --zone flag use the zone at
35697a
+				# the same index as the plug
35697a
+				options["--plugzonemap"][instance] = zones[i]
35697a
+				continue
35697a
+
35697a
+			try:
35697a
+				# In this case we do not have a zone specified so we attempt to detect it
35697a
+				options["--plugzonemap"][instance] = get_zone(conn, options, instance)
35697a
+			except Exception as err:
35697a
+				fail_fence_agent(options, "Failed retrieving GCE zone. Please provide --zone option: {}".format(str(err)))
35697a
 
35697a
 	# Operate the fencing device
35697a
 	result = fence_action(conn, options, set_power_status, get_power_status, get_nodes_list, power_cycle)