+ Must be called before quitting the program and while exactly one thread is
+ running.
+
+ """
+ pycurl.global_cleanup()
+
+
+def _ConfigRpcCurl(curl):
+ noded_cert = str(constants.NODED_CERT_FILE)
+
+ curl.setopt(pycurl.FOLLOWLOCATION, False)
+ curl.setopt(pycurl.CAINFO, noded_cert)
+ curl.setopt(pycurl.SSL_VERIFYHOST, 0)
+ curl.setopt(pycurl.SSL_VERIFYPEER, True)
+ curl.setopt(pycurl.SSLCERTTYPE, "PEM")
+ curl.setopt(pycurl.SSLCERT, noded_cert)
+ curl.setopt(pycurl.SSLKEYTYPE, "PEM")
+ curl.setopt(pycurl.SSLKEY, noded_cert)
+ curl.setopt(pycurl.CONNECTTIMEOUT, _RPC_CONNECT_TIMEOUT)
+
+
+# Aliasing this module avoids the following warning by epydoc: "Warning: No
+# information available for ganeti.rpc._RpcThreadLocal's base threading.local"
+_threading = threading
+
+
+class _RpcThreadLocal(_threading.local):
+ def GetHttpClientPool(self):
+ """Returns a per-thread HTTP client pool.
+
+ @rtype: L{http.client.HttpClientPool}
+
+ """
+ try:
+ pool = self.hcp
+ except AttributeError:
+ pool = http.client.HttpClientPool(_ConfigRpcCurl)
+ self.hcp = pool
+
+ return pool
+
+
+# Remove module alias (see above)
+del _threading
+
+
+_thread_local = _RpcThreadLocal()
+
+
+def _RpcTimeout(secs):
+ """Timeout decorator.
+
+ When applied to a rpc call_* function, it updates the global timeout
+ table with the given function/timeout.
+
+ """
+ def decorator(f):
+ name = f.__name__
+ assert name.startswith("call_")
+ _TIMEOUTS[name[len("call_"):]] = secs
+ return f
+ return decorator
+
+
+def RunWithRPC(fn):
+ """RPC-wrapper decorator.
+
+ When applied to a function, it runs it with the RPC system
+ initialized, and it shutsdown the system afterwards. This means the
+ function must be called without RPC being initialized.
+
+ """
+ def wrapper(*args, **kwargs):
+ Init()
+ try:
+ return fn(*args, **kwargs)
+ finally:
+ Shutdown()
+ return wrapper
+
+
+class RpcResult(object):
+ """RPC Result class.
+
+ This class holds an RPC result. It is needed since in multi-node
+ calls we can't raise an exception just because one one out of many
+ failed, and therefore we use this class to encapsulate the result.
+
+ @ivar data: the data payload, for successful results, or None
+ @ivar call: the name of the RPC call
+ @ivar node: the name of the node to which we made the call
+ @ivar offline: whether the operation failed because the node was
+ offline, as opposed to actual failure; offline=True will always
+ imply failed=True, in order to allow simpler checking if
+ the user doesn't care about the exact failure mode
+ @ivar fail_msg: the error message if the call failed
+
+ """
+ def __init__(self, data=None, failed=False, offline=False,
+ call=None, node=None):
+ self.offline = offline
+ self.call = call
+ self.node = node
+
+ if offline:
+ self.fail_msg = "Node is marked offline"
+ self.data = self.payload = None
+ elif failed:
+ self.fail_msg = self._EnsureErr(data)
+ self.data = self.payload = None
+ else:
+ self.data = data
+ if not isinstance(self.data, (tuple, list)):
+ self.fail_msg = ("RPC layer error: invalid result type (%s)" %
+ type(self.data))
+ self.payload = None
+ elif len(data) != 2:
+ self.fail_msg = ("RPC layer error: invalid result length (%d), "
+ "expected 2" % len(self.data))
+ self.payload = None
+ elif not self.data[0]:
+ self.fail_msg = self._EnsureErr(self.data[1])
+ self.payload = None
+ else:
+ # finally success
+ self.fail_msg = None
+ self.payload = data[1]
+
+ for attr_name in ["call", "data", "fail_msg",
+ "node", "offline", "payload"]:
+ assert hasattr(self, attr_name), "Missing attribute %s" % attr_name
+
+ @staticmethod
+ def _EnsureErr(val):
+ """Helper to ensure we return a 'True' value for error."""
+ if val:
+ return val
+ else:
+ return "No error information"
+
+ def Raise(self, msg, prereq=False, ecode=None):
+ """If the result has failed, raise an OpExecError.
+
+ This is used so that LU code doesn't have to check for each
+ result, but instead can call this function.
+
+ """
+ if not self.fail_msg:
+ return
+
+ if not msg: # one could pass None for default message
+ msg = ("Call '%s' to node '%s' has failed: %s" %
+ (self.call, self.node, self.fail_msg))
+ else:
+ msg = "%s: %s" % (msg, self.fail_msg)
+ if prereq:
+ ec = errors.OpPrereqError
+ else:
+ ec = errors.OpExecError
+ if ecode is not None:
+ args = (msg, ecode)
+ else:
+ args = (msg, )
+ raise ec(*args) # pylint: disable-msg=W0142
+
+
+def _AddressLookup(node_list,
+ ssc=ssconf.SimpleStore,
+ nslookup_fn=netutils.Hostname.GetIP):
+ """Return addresses for given node names.
+
+ @type node_list: list
+ @param node_list: List of node names
+ @type ssc: class
+ @param ssc: SimpleStore class that is used to obtain node->ip mappings
+ @type nslookup_fn: callable
+ @param nslookup_fn: function use to do NS lookup
+ @rtype: list of addresses and/or None's
+ @returns: List of corresponding addresses, if found