Blame SOURCES/bz1816203-fence_aws-1-fix-race-condition.patch

91f48e
From 1742baf17954c58a84b9c668a617bac78303ce95 Mon Sep 17 00:00:00 2001
91f48e
From: Guilherme Felix <fguilher@amazon.com>
91f48e
Date: Tue, 17 Mar 2020 13:18:38 +0000
91f48e
Subject: [PATCH 1/9] fence_aws: Fix fence race condition by checking local
91f48e
 instance status
91f48e
91f48e
---
91f48e
 agents/aws/fence_aws.py | 37 ++++++++++++++++++++++++++++++++++++-
91f48e
 1 file changed, 36 insertions(+), 1 deletion(-)
91f48e
91f48e
diff --git a/agents/aws/fence_aws.py b/agents/aws/fence_aws.py
91f48e
index 4a4d9de2..f37f68d6 100644
91f48e
--- a/agents/aws/fence_aws.py
91f48e
+++ b/agents/aws/fence_aws.py
91f48e
@@ -3,6 +3,7 @@
91f48e
 import sys, re
91f48e
 import logging
91f48e
 import atexit
91f48e
+import requests
91f48e
 sys.path.append("@FENCEAGENTSLIBDIR@")
91f48e
 from fencing import *
91f48e
 from fencing import fail, fail_usage, run_delay, EC_STATUS
91f48e
@@ -10,6 +11,17 @@
91f48e
 import boto3
91f48e
 from botocore.exceptions import ClientError, EndpointConnectionError, NoRegionError
91f48e
 
91f48e
+def get_instance_id():
91f48e
+	try:
91f48e
+		r = requests.get('http://169.254.169.254/latest/meta-data/instance-id')
91f48e
+		return r.content
91f48e
+	except HTTPError as http_err:
91f48e
+		logging.error('HTTP error occurred while trying to access EC2 metadata server: %s', http_err)
91f48e
+	except Exception as err:
91f48e
+		logging.error('A fatal error occurred while trying to access EC2 metadata server: %s', err)
91f48e
+	return None
91f48e
+	
91f48e
+
91f48e
 def get_nodes_list(conn, options):
91f48e
 	result = {}
91f48e
 	try:
91f48e
@@ -45,10 +57,33 @@ def get_power_status(conn, options):
91f48e
 		logging.error("Failed to get power status: %s", e)
91f48e
 		fail(EC_STATUS)
91f48e
 
91f48e
+def get_self_power_status(conn, options):
91f48e
+	try:
91f48e
+		instance = conn.instances.filter(Filters=[{"Name": "instance-id", "Values": [instance_id]}])
91f48e
+		state = list(instance)[0].state["Name"]
91f48e
+		if state == "running":
91f48e
+			logging.debug("Captured my (%s) state and it %s - returning OK - Proceeding with fencing",instance_id,state.upper())
91f48e
+			return "ok"
91f48e
+		else:
91f48e
+			logging.debug("Captured my (%s) state it is %s - returning Alert - Unable to fence other nodes",instance_id,state.upper())
91f48e
+			return "alert"
91f48e
+	
91f48e
+	except ClientError:
91f48e
+		fail_usage("Failed: Incorrect Access Key or Secret Key.")
91f48e
+	except EndpointConnectionError:
91f48e
+		fail_usage("Failed: Incorrect Region.")
91f48e
+	except IndexError:
91f48e
+		return "fail"
91f48e
+
91f48e
 def set_power_status(conn, options):
91f48e
+	my_instance = get_instance_id()
91f48e
 	try:
91f48e
 		if (options["--action"]=="off"):
91f48e
-			conn.instances.filter(InstanceIds=[options["--plug"]]).stop(Force=True)
91f48e
+			if (get_self_power_status(conn,myinstance) == "ok"):
91f48e
+				logging.info("Called StopInstance API call for %s", options["--plug"])
91f48e
+				conn.instances.filter(InstanceIds=[options["--plug"]]).stop(Force=True)
91f48e
+			else:
91f48e
+				logging.info("Skipping fencing as instance is not in running status")
91f48e
 		elif (options["--action"]=="on"):
91f48e
 			conn.instances.filter(InstanceIds=[options["--plug"]]).start()
91f48e
 	except Exception as e:
91f48e
91f48e
From 45e429b3132ebc9e78121c3fbb15f0bf46845a59 Mon Sep 17 00:00:00 2001
91f48e
From: Guilherme Felix <fguilher@amazon.com>
91f48e
Date: Tue, 17 Mar 2020 13:28:34 +0000
91f48e
Subject: [PATCH 2/9] fence_aws: Use local logger and improve logging
91f48e
 experience
91f48e
91f48e
---
91f48e
 agents/aws/fence_aws.py | 34 ++++++++++++++++++++++++++--------
91f48e
 1 file changed, 26 insertions(+), 8 deletions(-)
91f48e
91f48e
diff --git a/agents/aws/fence_aws.py b/agents/aws/fence_aws.py
91f48e
index f37f68d6..b0b6685a 100644
91f48e
--- a/agents/aws/fence_aws.py
91f48e
+++ b/agents/aws/fence_aws.py
91f48e
@@ -6,7 +6,7 @@
91f48e
 import requests
91f48e
 sys.path.append("@FENCEAGENTSLIBDIR@")
91f48e
 from fencing import *
91f48e
-from fencing import fail, fail_usage, run_delay, EC_STATUS
91f48e
+from fencing import fail, fail_usage, run_delay, EC_STATUS, SyslogLibHandler
91f48e
 
91f48e
 import boto3
91f48e
 from botocore.exceptions import ClientError, EndpointConnectionError, NoRegionError
91f48e
@@ -16,13 +16,14 @@ def get_instance_id():
91f48e
 		r = requests.get('http://169.254.169.254/latest/meta-data/instance-id')
91f48e
 		return r.content
91f48e
 	except HTTPError as http_err:
91f48e
-		logging.error('HTTP error occurred while trying to access EC2 metadata server: %s', http_err)
91f48e
+		logger.error('HTTP error occurred while trying to access EC2 metadata server: %s', http_err)
91f48e
 	except Exception as err:
91f48e
-		logging.error('A fatal error occurred while trying to access EC2 metadata server: %s', err)
91f48e
+		logger.error('A fatal error occurred while trying to access EC2 metadata server: %s', err)
91f48e
 	return None
91f48e
 	
91f48e
 
91f48e
 def get_nodes_list(conn, options):
91f48e
+	logger.info("Starting monitor operation")
91f48e
 	result = {}
91f48e
 	try:
91f48e
 		for instance in conn.instances.all():
91f48e
@@ -32,14 +33,16 @@ def get_nodes_list(conn, options):
91f48e
 	except EndpointConnectionError:
91f48e
 		fail_usage("Failed: Incorrect Region.")
91f48e
 	except Exception as e:
91f48e
-		logging.error("Failed to get node list: %s", e)
91f48e
-
91f48e
+		logger.error("Failed to get node list: %s", e)
91f48e
+	logger.debug("Monitor operation OK: %s",result)
91f48e
 	return result
91f48e
 
91f48e
 def get_power_status(conn, options):
91f48e
+	logger.debug("Starting status operation")
91f48e
 	try:
91f48e
 		instance = conn.instances.filter(Filters=[{"Name": "instance-id", "Values": [options["--plug"]]}])
91f48e
 		state = list(instance)[0].state["Name"]
91f48e
+		logger.info("Status operation for EC2 instance %s returned state: %s",options["--plug"],state.upper())
91f48e
 		if state == "running":
91f48e
 			return "on"
91f48e
 		elif state == "stopped":
91f48e
@@ -80,14 +83,14 @@ def set_power_status(conn, options):
91f48e
 	try:
91f48e
 		if (options["--action"]=="off"):
91f48e
 			if (get_self_power_status(conn,myinstance) == "ok"):
91f48e
-				logging.info("Called StopInstance API call for %s", options["--plug"])
91f48e
 				conn.instances.filter(InstanceIds=[options["--plug"]]).stop(Force=True)
91f48e
+				logger.info("Called StopInstance API call for %s", options["--plug"])
91f48e
 			else:
91f48e
-				logging.info("Skipping fencing as instance is not in running status")
91f48e
+				logger.info("Skipping fencing as instance is not in running status")
91f48e
 		elif (options["--action"]=="on"):
91f48e
 			conn.instances.filter(InstanceIds=[options["--plug"]]).start()
91f48e
 	except Exception as e:
91f48e
-		logging.error("Failed to power %s %s: %s", \
91f48e
+		logger.error("Failed to power %s %s: %s", \
91f48e
 				options["--action"], options["--plug"], e)
91f48e
 
91f48e
 def define_new_opts():
91f48e
@@ -142,6 +145,13 @@ def main():
91f48e
 
91f48e
 	run_delay(options)
91f48e
 
91f48e
+	if options.get("--verbose") is not None:
91f48e
+		lh = logging.FileHandler('/var/log/fence_aws_debug.log')
91f48e
+		logger.addHandler(lh)
91f48e
+		lhf = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
91f48e
+		lh.setFormatter(lhf)
91f48e
+		logger.setLevel(logging.DEBUG)
91f48e
+
91f48e
 	region = options.get("--region")
91f48e
 	access_key = options.get("--access-key")
91f48e
 	secret_key = options.get("--secret-key")
91f48e
@@ -157,4 +167,12 @@ def main():
91f48e
 	sys.exit(result)
91f48e
 
91f48e
 if __name__ == "__main__":
91f48e
+
91f48e
+	logger = logging.getLogger("fence_aws")
91f48e
+	logger.propagate = False
91f48e
+	logger.setLevel(logging.INFO)
91f48e
+	logger.addHandler(SyslogLibHandler())
91f48e
+	logger.getLogger('botocore.vendored').propagate = False
91f48e
+	
91f48e
+
91f48e
 	main()
91f48e
91f48e
From 00569921597b8007c67296ab8332747baf1e6fae Mon Sep 17 00:00:00 2001
91f48e
From: Guilherme Felix <fguilher@amazon.com>
91f48e
Date: Tue, 17 Mar 2020 13:33:02 +0000
91f48e
Subject: [PATCH 3/9] fence_aws: Decouple boto3 and botocore debug logging from
91f48e
 local logging
91f48e
91f48e
---
91f48e
 agents/aws/fence_aws.py | 26 +++++++++++++++++++++++++-
91f48e
 1 file changed, 25 insertions(+), 1 deletion(-)
91f48e
91f48e
diff --git a/agents/aws/fence_aws.py b/agents/aws/fence_aws.py
91f48e
index b0b6685a..11714315 100644
91f48e
--- a/agents/aws/fence_aws.py
91f48e
+++ b/agents/aws/fence_aws.py
91f48e
@@ -118,18 +118,27 @@ def define_new_opts():
91f48e
 		"required" : "0",
91f48e
 		"order" : 4
91f48e
 	}
91f48e
+	all_opt["boto3_debug"] = {
91f48e
+		"getopt" : "b:",
91f48e
+		"longopt" : "boto3_debug",
91f48e
+		"help" : "-b, --boto3_debug=on|off      Boto3 and Botocore library debug logging",
91f48e
+		"shortdesc": "Boto Lib debug",
91f48e
+		"required": "0",
91f48e
+		"order": 5
91f48e
+	}
91f48e
 
91f48e
 # Main agent method
91f48e
 def main():
91f48e
 	conn = None
91f48e
 
91f48e
-	device_opt = ["port", "no_password", "region", "access_key", "secret_key"]
91f48e
+	device_opt = ["port", "no_password", "region", "access_key", "secret_key", "boto3_debug"]
91f48e
 
91f48e
 	atexit.register(atexit_handler)
91f48e
 
91f48e
 	define_new_opts()
91f48e
 
91f48e
 	all_opt["power_timeout"]["default"] = "60"
91f48e
+	all_opt["boto3_debug"]["default"] = "off"
91f48e
 
91f48e
 	options = check_input(device_opt, process_input(device_opt))
91f48e
 
91f48e
@@ -151,6 +160,21 @@ def main():
91f48e
 		lhf = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
91f48e
 		lh.setFormatter(lhf)
91f48e
 		logger.setLevel(logging.DEBUG)
91f48e
+	
91f48e
+	if options["--boto3_debug"] != "on":
91f48e
+		boto3.set_stream_logger('boto3',logging.INFO)
91f48e
+		boto3.set_stream_logger('botocore',logging.INFO)
91f48e
+		logging.getLogger('botocore').propagate = False
91f48e
+		logging.getLogger('boto3').propagate = False
91f48e
+	else:
91f48e
+		log_format = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
91f48e
+		logging.getLogger('botocore').propagate = False
91f48e
+		logging.getLogger('boto3').propagate = False
91f48e
+		fdh = logging.FileHandler('/var/log/fence_aws_boto3.log')
91f48e
+		fdh.setFormatter(log_format)
91f48e
+		logging.getLogger('boto3').addHandler(fdh)
91f48e
+		logging.getLogger('botocore').addHandler(fdh)
91f48e
+		logging.debug("Boto debug level is %s and sending debug info to /var/log/fence_aws_boto3.log", options["--boto3_debug"])
91f48e
 
91f48e
 	region = options.get("--region")
91f48e
 	access_key = options.get("--access-key")
91f48e
91f48e
From ed309bd51dfd5e0fed30156e7a312d5b5a8f4bd4 Mon Sep 17 00:00:00 2001
91f48e
From: Guilherme Felix <fguilher@amazon.com>
91f48e
Date: Thu, 19 Mar 2020 16:02:47 +0000
91f48e
Subject: [PATCH 4/9] fence_aws: Fix typos and variable names
91f48e
91f48e
---
91f48e
 agents/aws/fence_aws.py | 6 +++---
91f48e
 1 file changed, 3 insertions(+), 3 deletions(-)
91f48e
91f48e
diff --git a/agents/aws/fence_aws.py b/agents/aws/fence_aws.py
91f48e
index 11714315..207631e8 100644
91f48e
--- a/agents/aws/fence_aws.py
91f48e
+++ b/agents/aws/fence_aws.py
91f48e
@@ -60,7 +60,7 @@ def get_power_status(conn, options):
91f48e
 		logging.error("Failed to get power status: %s", e)
91f48e
 		fail(EC_STATUS)
91f48e
 
91f48e
-def get_self_power_status(conn, options):
91f48e
+def get_self_power_status(conn, instance_id):
91f48e
 	try:
91f48e
 		instance = conn.instances.filter(Filters=[{"Name": "instance-id", "Values": [instance_id]}])
91f48e
 		state = list(instance)[0].state["Name"]
91f48e
@@ -82,7 +82,7 @@ def set_power_status(conn, options):
91f48e
 	my_instance = get_instance_id()
91f48e
 	try:
91f48e
 		if (options["--action"]=="off"):
91f48e
-			if (get_self_power_status(conn,myinstance) == "ok"):
91f48e
+			if (get_self_power_status(conn,my_instance) == "ok"):
91f48e
 				conn.instances.filter(InstanceIds=[options["--plug"]]).stop(Force=True)
91f48e
 				logger.info("Called StopInstance API call for %s", options["--plug"])
91f48e
 			else:
91f48e
@@ -196,7 +196,7 @@ def main():
91f48e
 	logger.propagate = False
91f48e
 	logger.setLevel(logging.INFO)
91f48e
 	logger.addHandler(SyslogLibHandler())
91f48e
-	logger.getLogger('botocore.vendored').propagate = False
91f48e
+	logging.getLogger('botocore.vendored').propagate = False
91f48e
 	
91f48e
 
91f48e
 	main()
91f48e
91f48e
From 624c652a95a676286af408898186186b7d7fcf55 Mon Sep 17 00:00:00 2001
91f48e
From: Guilherme Felix <fguilher@amazon.com>
91f48e
Date: Thu, 19 Mar 2020 16:58:45 +0000
91f48e
Subject: [PATCH 5/9] fence_aws: Missing brackets on boto3_debug metadata
91f48e
91f48e
---
91f48e
 agents/aws/fence_aws.py | 2 +-
91f48e
 1 file changed, 1 insertion(+), 1 deletion(-)
91f48e
91f48e
diff --git a/agents/aws/fence_aws.py b/agents/aws/fence_aws.py
91f48e
index 207631e8..8916f4a0 100644
91f48e
--- a/agents/aws/fence_aws.py
91f48e
+++ b/agents/aws/fence_aws.py
91f48e
@@ -121,7 +121,7 @@ def define_new_opts():
91f48e
 	all_opt["boto3_debug"] = {
91f48e
 		"getopt" : "b:",
91f48e
 		"longopt" : "boto3_debug",
91f48e
-		"help" : "-b, --boto3_debug=on|off      Boto3 and Botocore library debug logging",
91f48e
+		"help" : "-b, --boto3_debug=[on|off]      Boto3 and Botocore library debug logging",
91f48e
 		"shortdesc": "Boto Lib debug",
91f48e
 		"required": "0",
91f48e
 		"order": 5
91f48e
91f48e
From 7c641a6885c4ab67b7739a43892d92d95a6f566c Mon Sep 17 00:00:00 2001
91f48e
From: Guilherme Felix <fguilher@amazon.com>
91f48e
Date: Thu, 19 Mar 2020 17:04:31 +0000
91f48e
Subject: [PATCH 6/9] fence_aws: Fix travis build #1
91f48e
91f48e
---
91f48e
 agents/aws/fence_aws.py | 2 +-
91f48e
 1 file changed, 1 insertion(+), 1 deletion(-)
91f48e
91f48e
diff --git a/agents/aws/fence_aws.py b/agents/aws/fence_aws.py
91f48e
index 8916f4a0..f41a47e4 100644
91f48e
--- a/agents/aws/fence_aws.py
91f48e
+++ b/agents/aws/fence_aws.py
91f48e
@@ -121,7 +121,7 @@ def define_new_opts():
91f48e
 	all_opt["boto3_debug"] = {
91f48e
 		"getopt" : "b:",
91f48e
 		"longopt" : "boto3_debug",
91f48e
-		"help" : "-b, --boto3_debug=[on|off]      Boto3 and Botocore library debug logging",
91f48e
+		"help" : "-b, --boto3_debug=[option]      Boto3 and Botocore library debug logging",
91f48e
 		"shortdesc": "Boto Lib debug",
91f48e
 		"required": "0",
91f48e
 		"order": 5
91f48e
91f48e
From 257af7ccc9789646adc7abf1e7dbac744b756071 Mon Sep 17 00:00:00 2001
91f48e
From: Guilherme Felix <fguilher@amazon.com>
91f48e
Date: Fri, 20 Mar 2020 10:59:56 +0000
91f48e
Subject: [PATCH 7/9] fence_aws: Updated metadata XML file
91f48e
91f48e
---
91f48e
 tests/data/metadata/fence_aws.xml | 5 +++++
91f48e
 1 file changed, 5 insertions(+)
91f48e
91f48e
diff --git a/tests/data/metadata/fence_aws.xml b/tests/data/metadata/fence_aws.xml
91f48e
index 5e5d5d99..acfebb61 100644
91f48e
--- a/tests/data/metadata/fence_aws.xml
91f48e
+++ b/tests/data/metadata/fence_aws.xml
91f48e
@@ -36,6 +36,11 @@ For instructions see: https://boto3.readthedocs.io/en/latest/guide/quickstart.ht
91f48e
 		<content type="string"  />
91f48e
 		<shortdesc lang="en">Secret Key.</shortdesc>
91f48e
 	</parameter>
91f48e
+	<parameter name="boto3_debug" unique="0" required="0">
91f48e
+		<getopt mixed="-b, --boto3_debug=[option]" />
91f48e
+		<content type="string" default="off"  />
91f48e
+		<shortdesc lang="en">Boto Lib debug</shortdesc>
91f48e
+	</parameter>
91f48e
 	<parameter name="quiet" unique="0" required="0">
91f48e
 		<getopt mixed="-q, --quiet" />
91f48e
 		<content type="boolean"  />
91f48e
91f48e
From 8f78bc19356b5e07d0021aaf7da3fc4e712e00f0 Mon Sep 17 00:00:00 2001
91f48e
From: Guilherme Felix <fguilher@amazon.com>
91f48e
Date: Fri, 20 Mar 2020 12:13:16 +0000
91f48e
Subject: [PATCH 8/9] fence_aws: Moving logger config next to import statements
91f48e
 for visibility
91f48e
91f48e
---
91f48e
 agents/aws/fence_aws.py | 13 ++++++-------
91f48e
 1 file changed, 6 insertions(+), 7 deletions(-)
91f48e
91f48e
diff --git a/agents/aws/fence_aws.py b/agents/aws/fence_aws.py
91f48e
index f41a47e4..72fb8843 100644
91f48e
--- a/agents/aws/fence_aws.py
91f48e
+++ b/agents/aws/fence_aws.py
91f48e
@@ -11,6 +11,12 @@
91f48e
 import boto3
91f48e
 from botocore.exceptions import ClientError, EndpointConnectionError, NoRegionError
91f48e
 
91f48e
+logger = logging.getLogger("fence_aws")
91f48e
+logger.propagate = False
91f48e
+logger.setLevel(logging.INFO)
91f48e
+logger.addHandler(SyslogLibHandler())
91f48e
+logging.getLogger('botocore.vendored').propagate = False
91f48e
+	
91f48e
 def get_instance_id():
91f48e
 	try:
91f48e
 		r = requests.get('http://169.254.169.254/latest/meta-data/instance-id')
91f48e
@@ -192,11 +198,4 @@ def main():
91f48e
 
91f48e
 if __name__ == "__main__":
91f48e
 
91f48e
-	logger = logging.getLogger("fence_aws")
91f48e
-	logger.propagate = False
91f48e
-	logger.setLevel(logging.INFO)
91f48e
-	logger.addHandler(SyslogLibHandler())
91f48e
-	logging.getLogger('botocore.vendored').propagate = False
91f48e
-	
91f48e
-
91f48e
 	main()
91f48e
91f48e
From 570a05c425fe55008c8892ebaad8a73d36143909 Mon Sep 17 00:00:00 2001
91f48e
From: Guilherme Felix <fguilher@amazon.com>
91f48e
Date: Fri, 20 Mar 2020 14:17:55 +0000
91f48e
Subject: [PATCH 9/9] fence_aws: Remove empty line
91f48e
91f48e
---
91f48e
 agents/aws/fence_aws.py | 3 +--
91f48e
 1 file changed, 1 insertion(+), 2 deletions(-)
91f48e
91f48e
diff --git a/agents/aws/fence_aws.py b/agents/aws/fence_aws.py
91f48e
index 72fb8843..ed55f390 100644
91f48e
--- a/agents/aws/fence_aws.py
91f48e
+++ b/agents/aws/fence_aws.py
91f48e
@@ -197,5 +197,4 @@ def main():
91f48e
 	sys.exit(result)
91f48e
 
91f48e
 if __name__ == "__main__":
91f48e
-
91f48e
-	main()
91f48e
+	main()
91f48e
\ No newline at end of file