def get_fabric_servers(self, fabric_cnx=None):
"""Get all MySQL Fabric instances
This method looks up the other MySQL Fabric instances which uses
the same metadata. The returned list contains dictionaries with
connection information such ass host and port. For example:
[
{'host': 'fabric_prod_1.example.com', 'port': 32274 },
{'host': 'fabric_prod_2.example.com', 'port': 32274 },
]
Returns a list of dictionaries
"""
inst = fabric_cnx or self.get_instance()
result = []
err_msg = "Looking up Fabric servers failed using {host}:{port}: {err}"
try:
fset = inst.execute('dump', 'fabric_nodes',
"protocol." + self._protocol)
for row in fset.rows():
result.append({'host': row.host, 'port': row.port})
except (Fault, socket.error) as exc:
msg = err_msg.format(err=str(exc), host=inst.handler.host,
port=inst.handler.port)
raise InterfaceError(msg)
except (TypeError, AttributeError) as exc:
msg = err_msg.format(
err="No Fabric server available ({0})".format(exc),
host=inst.handler.host, port=inst.handler.port)
raise InterfaceError(msg)
try:
fabric_uuid = uuid.UUID(fset.fabric_uuid_str)
except TypeError:
fabric_uuid = uuid.uuid4()
fabric_version = 0
return fabric_uuid, fabric_version, fset.ttl, result
python类Fault()的实例源码
def authenticate(self):
"""Determine the current domain and zone IDs for the domain."""
try:
payload = self.api.domain.info(self.apikey, self.domain)
self.domain_id = payload['id']
self.zone_id = payload['zone_id']
except xmlrpclib.Fault as err:
raise Exception("Failed to authenticate: '{0}'".format(err))
# Create record. If record already exists with the same content, do nothing'
def get_fabric_servers(self, fabric_cnx=None):
"""Get all MySQL Fabric instances
This method looks up the other MySQL Fabric instances which uses
the same metadata. The returned list contains dictionaries with
connection information such ass host and port. For example:
[
{'host': 'fabric_prod_1.example.com', 'port': 32274 },
{'host': 'fabric_prod_2.example.com', 'port': 32274 },
]
Returns a list of dictionaries
"""
inst = fabric_cnx or self.get_instance()
result = []
err_msg = "Looking up Fabric servers failed using {host}:{port}: {err}"
try:
fset = inst.execute('dump', 'fabric_nodes',
"protocol." + self._protocol)
for row in fset.rows():
result.append({'host': row.host, 'port': row.port})
except (Fault, socket.error) as exc:
msg = err_msg.format(err=str(exc), host=inst.handler.host,
port=inst.handler.port)
raise InterfaceError(msg)
except (TypeError, AttributeError) as exc:
msg = err_msg.format(
err="No Fabric server available ({0})".format(exc),
host=inst.handler.host, port=inst.handler.port)
raise InterfaceError(msg)
try:
fabric_uuid = uuid.UUID(fset.fabric_uuid_str)
except TypeError:
fabric_uuid = uuid.uuid4()
fabric_version = 0
return fabric_uuid, fabric_version, fset.ttl, result
def test_repr(self):
f = xmlrpclib.Fault(42, 'Test Fault')
self.assertEqual(repr(f), "<Fault 42: 'Test Fault'>")
self.assertEqual(repr(f), str(f))
def test_dump_fault(self):
f = xmlrpclib.Fault(42, 'Test Fault')
s = xmlrpclib.dumps((f,))
(newf,), m = xmlrpclib.loads(s)
self.assertEqual(newf, {'faultCode': 42, 'faultString': 'Test Fault'})
self.assertEqual(m, None)
s = xmlrpclib.Marshaller().dumps(f)
self.assertRaises(xmlrpclib.Fault, xmlrpclib.loads, s)
def test_path1(self):
p = xmlrpclib.ServerProxy(URL+"/foo")
self.assertEqual(p.pow(6,8), 6**8)
self.assertRaises(xmlrpclib.Fault, p.add, 6, 8)
def test_path2(self):
p = xmlrpclib.ServerProxy(URL+"/foo/bar")
self.assertEqual(p.add(6,8), 6+8)
self.assertRaises(xmlrpclib.Fault, p.pow, 6, 8)
def test_path3(self):
p = xmlrpclib.ServerProxy(URL+"/is/broken")
self.assertRaises(xmlrpclib.Fault, p.add, 6, 8)
#A test case that verifies that a server using the HTTP/1.1 keep-alive mechanism
#does indeed serve subsequent requests on the same connection
def _marshaled_dispatch(self, data, dispatch_method = None, path = None):
"""Dispatches an XML-RPC method from marshalled (XML) data.
XML-RPC methods are dispatched from the marshalled (XML) data
using the _dispatch method and the result is returned as
marshalled data. For backwards compatibility, a dispatch
function can be provided as an argument (see comment in
SimpleXMLRPCRequestHandler.do_POST) but overriding the
existing method through subclassing is the preferred means
of changing method dispatch behavior.
"""
try:
params, method = loads(data)
# generate response
if dispatch_method is not None:
response = dispatch_method(method, params)
else:
response = self._dispatch(method, params)
# wrap response in a singleton tuple
response = (response,)
response = dumps(response, methodresponse=1,
allow_none=self.allow_none, encoding=self.encoding)
except Fault as fault:
response = dumps(fault, allow_none=self.allow_none,
encoding=self.encoding)
except:
# report exception back to server
exc_type, exc_value, exc_tb = sys.exc_info()
response = dumps(
Fault(1, "%s:%s" % (exc_type, exc_value)),
encoding=self.encoding, allow_none=self.allow_none,
)
return response.encode(self.encoding)
def system_multicall(self, call_list):
"""system.multicall([{'methodName': 'add', 'params': [2, 2]}, ...]) => \
[[4], ...]
Allows the caller to package multiple XML-RPC calls into a single
request.
See http://www.xmlrpc.com/discuss/msgReader$1208
"""
results = []
for call in call_list:
method_name = call['methodName']
params = call['params']
try:
# XXX A marshalling error in any response will fail the entire
# multicall. If someone cares they should fix this.
results.append([self._dispatch(method_name, params)])
except Fault as fault:
results.append(
{'faultCode' : fault.faultCode,
'faultString' : fault.faultString}
)
except:
exc_type, exc_value, exc_tb = sys.exc_info()
results.append(
{'faultCode' : 1,
'faultString' : "%s:%s" % (exc_type, exc_value)}
)
return results
def _marshaled_dispatch(self, data, dispatch_method = None, path = None):
try:
response = self.dispatchers[path]._marshaled_dispatch(
data, dispatch_method, path)
except:
# report low level exception back to server
# (each dispatcher should have handled their own
# exceptions)
exc_type, exc_value = sys.exc_info()[:2]
response = dumps(
Fault(1, "%s:%s" % (exc_type, exc_value)),
encoding=self.encoding, allow_none=self.allow_none)
response = response.encode(self.encoding)
return response
def ri_find_wrapper(switch_instance, vlan=None, ip_address=None, bandwith=100, mtu=1500, vrf=0):
"""Wrapper of "find" function for RouteInterface table.
Notes:
This is temporary function.
Args:
switch_instance(object): Switch instance
vlan(str): Vlan on which route interface is implemented.
ip_address(str): IP address of route interface.
mtu(int): MTU of route interface.
bandwith(int): Bandwith of route interface
vrf(int): Virtual route Id
Returns:
row
Examples::
_ri_find_wrapper(env.switch[1], vlan=10, ip_address="10.0.10.1/24", mtu=100, bandwith=1500, vrf=0)
"""
try:
result = switch_instance.nb.RouteInterface.find(vlan, ip_address, bandwith, mtu, vrf)
except XMLRPCFault:
result = switch_instance.nb.RouteInterface.find(ip_address)
return result
def pass_xmlrpc_fault(func):
"""Decorator to create raises functions with predefined xmlrpclib. Fault exception.
"""
def wrapper(*args, **kwargs):
"""Decorator to create raises functions with predefined xmlrpclib.
"""
return func(XMLRPCFault, *args, **kwargs)
return wrapper
def test_repr(self):
f = xmlrpclib.Fault(42, 'Test Fault')
self.assertEqual(repr(f), "<Fault 42: 'Test Fault'>")
self.assertEqual(repr(f), str(f))
def test_dump_fault(self):
f = xmlrpclib.Fault(42, 'Test Fault')
s = xmlrpclib.dumps((f,))
(newf,), m = xmlrpclib.loads(s)
self.assertEqual(newf, {'faultCode': 42, 'faultString': 'Test Fault'})
self.assertEqual(m, None)
s = xmlrpclib.Marshaller().dumps(f)
self.assertRaises(xmlrpclib.Fault, xmlrpclib.loads, s)
def test_path1(self):
p = xmlrpclib.ServerProxy(URL+"/foo")
self.assertEqual(p.pow(6,8), 6**8)
self.assertRaises(xmlrpclib.Fault, p.add, 6, 8)
def test_path2(self):
p = xmlrpclib.ServerProxy(URL+"/foo/bar")
self.assertEqual(p.add(6,8), 6+8)
self.assertRaises(xmlrpclib.Fault, p.pow, 6, 8)
def test_path3(self):
p = xmlrpclib.ServerProxy(URL+"/is/broken")
self.assertRaises(xmlrpclib.Fault, p.add, 6, 8)
#A test case that verifies that a server using the HTTP/1.1 keep-alive mechanism
#does indeed serve subsequent requests on the same connection
def xmlrpc_search(self):
try:
query = self.query_from_xmlrpc(self.request.body)
log.debug("xmlrpc_search {0}".format(query))
hits = self.search_index_packages(query)
response = dumps((hits,), methodresponse=1, encoding='utf-8')
except Exception as e:
log.exception("Error in xmlrpc_search")
response = dumps(Fault(1, repr(e)), encoding='utf-8')
return Response(response)
def test_repr(self):
f = xmlrpclib.Fault(42, 'Test Fault')
self.assertEqual(repr(f), "<Fault 42: 'Test Fault'>")
self.assertEqual(repr(f), str(f))