Blame SOURCES/bz1819965-1-ocf.py-update.patch

919373
--- a/heartbeat/ocf.py	2020-04-08 13:03:20.543477544 +0200
919373
+++ b/heartbeat/ocf.py	2020-04-06 10:23:45.950913519 +0200
919373
@@ -88,6 +88,10 @@
919373
 
919373
 OCF_RESOURCE_INSTANCE = env.get("OCF_RESOURCE_INSTANCE")
919373
 
919373
+OCF_ACTION = env.get("__OCF_ACTION")
919373
+if OCF_ACTION is None and len(argv) == 2:
919373
+	OCF_ACTION = argv[1]
919373
+
919373
 HA_DEBUG = env.get("HA_debug", 0)
919373
 HA_DATEFMT = env.get("HA_DATEFMT", "%b %d %T ")
919373
 HA_LOGFACILITY = env.get("HA_LOGFACILITY")
919373
@@ -135,3 +139,343 @@
919373
 	log.addHandler(dfh)
919373
 
919373
 logger = logging.LoggerAdapter(log, {'OCF_RESOURCE_INSTANCE': OCF_RESOURCE_INSTANCE})
919373
+
919373
+
919373
+_exit_reason_set = False
919373
+
919373
+def ocf_exit_reason(msg):
919373
+	"""
919373
+	Print exit error string to stderr.
919373
+
919373
+	Allows the OCF agent to provide a string describing
919373
+	why the exit code was returned.
919373
+	"""
919373
+	global _exit_reason_set
919373
+	cookie = env.get("OCF_EXIT_REASON_PREFIX", "ocf-exit-reason:")
919373
+	sys.stderr.write("{}{}\n".format(cookie, msg))
919373
+	sys.stderr.flush()
919373
+	logger.error(msg)
919373
+	_exit_reason_set = True
919373
+
919373
+
919373
+def have_binary(name):
919373
+	"""
919373
+	True if binary exists, False otherwise.
919373
+	"""
919373
+	def _access_check(fn):
919373
+		return (os.path.exists(fn) and
919373
+				os.access(fn, os.F_OK | os.X_OK) and
919373
+				not os.path.isdir(fn))
919373
+	if _access_check(name):
919373
+		return True
919373
+	path = env.get("PATH", os.defpath).split(os.pathsep)
919373
+	seen = set()
919373
+	for dir in path:
919373
+		dir = os.path.normcase(dir)
919373
+		if dir not in seen:
919373
+			seen.add(dir)
919373
+			name2 = os.path.join(dir, name)
919373
+			if _access_check(name2):
919373
+				return True
919373
+	return False
919373
+
919373
+
919373
+def is_true(val):
919373
+	"""
919373
+	Convert an OCF truth value to a
919373
+	Python boolean.
919373
+	"""
919373
+	return val in ("yes", "true", "1", 1, "YES", "TRUE", "ja", "on", "ON", True)
919373
+
919373
+
919373
+def is_probe():
919373
+	"""
919373
+	A probe is defined as a monitor operation
919373
+	with an interval of zero. This is called
919373
+	by Pacemaker to check the status of a possibly
919373
+	not running resource.
919373
+	"""
919373
+	return (OCF_ACTION == "monitor" and
919373
+			env.get("OCF_RESKEY_CRM_meta_interval", "") == "0")
919373
+
919373
+
919373
+def get_parameter(name, default=None):
919373
+	"""
919373
+	Extract the parameter value from the environment
919373
+	"""
919373
+	return env.get("OCF_RESKEY_{}".format(name), default)
919373
+
919373
+
919373
+def distro():
919373
+	"""
919373
+	Return name of distribution/platform.
919373
+
919373
+	If possible, returns "name/version", else
919373
+	just "name".
919373
+	"""
919373
+	import subprocess
919373
+	import platform
919373
+	try:
919373
+		ret = subprocess.check_output(["lsb_release", "-si"])
919373
+		if type(ret) != str:
919373
+			ret = ret.decode()
919373
+		distro = ret.strip()
919373
+		ret = subprocess.check_output(["lsb_release", "-sr"])
919373
+		if type(ret) != str:
919373
+			ret = ret.decode()
919373
+		version = ret.strip()
919373
+		return "{}/{}".format(distro, version)
919373
+	except Exception:
919373
+		if os.path.exists("/etc/debian_version"):
919373
+			return "Debian"
919373
+		if os.path.exists("/etc/SuSE-release"):
919373
+			return "SUSE"
919373
+		if os.path.exists("/etc/redhat-release"):
919373
+			return "Redhat"
919373
+	return platform.system()
919373
+
919373
+
919373
+class Parameter(object):
919373
+	def __init__(self, name, shortdesc, longdesc, content_type, unique, required, default):
919373
+		self.name = name
919373
+		self.shortdesc = shortdesc
919373
+		self.longdesc = longdesc
919373
+		self.content_type = content_type
919373
+		self.unique = unique
919373
+		self.required = required
919373
+		self.default = default
919373
+
919373
+	def __str__(self):
919373
+		return self.to_xml()
919373
+
919373
+	def to_xml(self):
919373
+		ret = '
919373
+		if self.unique:
919373
+			ret += ' unique="1"'
919373
+		if self.required:
919373
+			ret += ' required="1"'
919373
+		ret += ">\n"
919373
+		ret += '<longdesc lang="en">' + self.longdesc + '</longdesc>' + "\n"
919373
+		ret += '<shortdesc lang="en">' + self.shortdesc + '</shortdesc>' + "\n"
919373
+		ret += '
919373
+		if self.default is not None:
919373
+			ret += ' default="{}"'.format(self.default)
919373
+		ret += " />\n"
919373
+		ret += "</parameter>\n"
919373
+		return ret
919373
+
919373
+
919373
+
919373
+class Action(object):
919373
+	def __init__(self, name, timeout, interval, depth, role):
919373
+		self.name = name
919373
+		self.timeout = timeout
919373
+		self.interval = interval
919373
+		self.depth = depth
919373
+		self.role = role
919373
+
919373
+	def __str__(self):
919373
+		return self.to_xml()
919373
+
919373
+	def to_xml(self):
919373
+		def opt(s, name, var):
919373
+			if var is not None:
919373
+				if type(var) == int and name in ("timeout", "interval"):
919373
+					var = "{}s".format(var)
919373
+				return s + ' {}="{}"'.format(name, var)
919373
+			return s
919373
+		ret = '
919373
+		ret = opt(ret, "timeout", self.timeout)
919373
+		ret = opt(ret, "interval", self.interval)
919373
+		ret = opt(ret, "depth", self.depth)
919373
+		ret = opt(ret, "role", self.role)
919373
+		ret += " />\n"
919373
+		return ret
919373
+
919373
+
919373
+class Agent(object):
919373
+	"""
919373
+	OCF Resource Agent metadata XML generator helper.
919373
+
919373
+	Use add_parameter/add_action to define parameters
919373
+	and actions for the agent. Then call run() to
919373
+	start the agent main loop.
919373
+
919373
+	See doc/dev-guides/writing-python-agents.md for an example
919373
+	of how to use it.
919373
+	"""
919373
+
919373
+	def __init__(self, name, shortdesc, longdesc):
919373
+		self.name = name
919373
+		self.shortdesc = shortdesc
919373
+		self.longdesc = longdesc
919373
+		self.parameters = []
919373
+		self.actions = []
919373
+		self._handlers = {}
919373
+
919373
+	def add_parameter(self, name, shortdesc="", longdesc="", content_type="string", unique=False, required=False, default=None):
919373
+		for param in self.parameters:
919373
+			if param.name == name:
919373
+				raise ValueError("Parameter {} defined twice in metadata".format(name))
919373
+		self.parameters.append(Parameter(name=name,
919373
+										 shortdesc=shortdesc,
919373
+										 longdesc=longdesc,
919373
+										 content_type=content_type,
919373
+										 unique=unique,
919373
+										 required=required,
919373
+										 default=default))
919373
+		return self
919373
+
919373
+	def add_action(self, name, timeout=None, interval=None, depth=None, role=None, handler=None):
919373
+		self.actions.append(Action(name=name,
919373
+								   timeout=timeout,
919373
+								   interval=interval,
919373
+								   depth=depth,
919373
+								   role=role))
919373
+		if handler is not None:
919373
+			self._handlers[name] = handler
919373
+		return self
919373
+
919373
+	def __str__(self):
919373
+		return self.to_xml()
919373
+
919373
+	def to_xml(self):
919373
+		return """
919373
+
919373
+<resource-agent name="{name}">
919373
+<version>1.0</version>
919373
+<longdesc lang="en">
919373
+{longdesc}
919373
+</longdesc>
919373
+<shortdesc lang="en">{shortdesc}</shortdesc>
919373
+
919373
+<parameters>
919373
+{parameters}
919373
+</parameters>
919373
+
919373
+<actions>
919373
+{actions}
919373
+</actions>
919373
+
919373
+</resource-agent>
919373
+""".format(name=self.name,
919373
+		   longdesc=self.longdesc,
919373
+		   shortdesc=self.shortdesc,
919373
+		   parameters="".join(p.to_xml() for p in self.parameters),
919373
+		   actions="".join(a.to_xml() for a in self.actions))
919373
+
919373
+	def run(self):
919373
+		run(self)
919373
+
919373
+
919373
+def run(agent, handlers=None):
919373
+	"""
919373
+	Main loop implementation for resource agents.
919373
+	Does not return.
919373
+
919373
+	Arguments:
919373
+
919373
+	agent: Agent object.
919373
+
919373
+	handlers: Dict of action name to handler function.
919373
+
919373
+	Handler functions can take parameters as arguments,
919373
+	the run loop will read parameter values from the
919373
+	environment and pass to the handler.
919373
+	"""
919373
+	import inspect
919373
+
919373
+	agent._handlers.update(handlers or {})
919373
+	handlers = agent._handlers
919373
+
919373
+	def check_required_params():
919373
+		for p in agent.parameters:
919373
+			if p.required and get_parameter(p.name) is None:
919373
+				ocf_exit_reason("{}: Required parameter not set".format(p.name))
919373
+				sys.exit(OCF_ERR_CONFIGURED)
919373
+
919373
+	def call_handler(func):
919373
+		if hasattr(inspect, 'signature'):
919373
+			params = inspect.signature(func).parameters.keys()
919373
+		else:
919373
+			params = inspect.getargspec(func).args
919373
+		def value_for_parameter(param):
919373
+			val = get_parameter(param)
919373
+			if val is not None:
919373
+				return val
919373
+			for p in agent.parameters:
919373
+				if p.name == param:
919373
+					return p.default
919373
+		arglist = [value_for_parameter(p) for p in params]
919373
+		try:
919373
+			rc = func(*arglist)
919373
+			if rc is None:
919373
+				rc = OCF_SUCCESS
919373
+			return rc
919373
+		except Exception as err:
919373
+			if not _exit_reason_set:
919373
+				ocf_exit_reason(str(err))
919373
+			else:
919373
+				logger.error(str(err))
919373
+			return OCF_ERR_GENERIC
919373
+
919373
+	meta_data_action = False
919373
+	for action in agent.actions:
919373
+		if action.name == "meta-data":
919373
+			meta_data_action = True
919373
+			break
919373
+	if not meta_data_action:
919373
+		agent.add_action("meta-data", timeout=10)
919373
+
919373
+	if len(sys.argv) == 2 and sys.argv[1] in ("-h", "--help"):
919373
+		sys.stdout.write("usage: %s {%s}\n\n" % (sys.argv[0], "|".join(sorted(handlers.keys()))) +
919373
+		                 "Expects to have a fully populated OCF RA compliant environment set.\n")
919373
+		sys.exit(OCF_SUCCESS)
919373
+
919373
+	if OCF_ACTION is None:
919373
+		ocf_exit_reason("No action argument set")
919373
+		sys.exit(OCF_ERR_UNIMPLEMENTED)
919373
+	if OCF_ACTION in ('meta-data', 'usage', 'methods'):
919373
+		sys.stdout.write(agent.to_xml() + "\n")
919373
+		sys.exit(OCF_SUCCESS)
919373
+
919373
+	check_required_params()
919373
+	if OCF_ACTION in handlers:
919373
+		rc = call_handler(handlers[OCF_ACTION])
919373
+		sys.exit(rc)
919373
+	sys.exit(OCF_ERR_UNIMPLEMENTED)
919373
+
919373
+
919373
+if __name__ == "__main__":
919373
+	import unittest
919373
+
919373
+	class TestMetadata(unittest.TestCase):
919373
+		def test_noparams_noactions(self):
919373
+			m = Agent("foo", shortdesc="shortdesc", longdesc="longdesc")
919373
+			self.assertEqual("""
919373
+
919373
+<resource-agent name="foo">
919373
+<version>1.0</version>
919373
+<longdesc lang="en">
919373
+longdesc
919373
+</longdesc>
919373
+<shortdesc lang="en">shortdesc</shortdesc>
919373
+
919373
+<parameters>
919373
+
919373
+</parameters>
919373
+
919373
+<actions>
919373
+
919373
+</actions>
919373
+
919373
+</resource-agent>
919373
+""", str(m))
919373
+
919373
+		def test_params_actions(self):
919373
+			m = Agent("foo", shortdesc="shortdesc", longdesc="longdesc")
919373
+			m.add_parameter("testparam")
919373
+			m.add_action("start")
919373
+			self.assertEqual(str(m.actions[0]), '<action name="start" />\n')
919373
+
919373
+	unittest.main()