numam-spdk/scripts/rpc/client.py
Daniel Verkamp a54e7e584b rpc.py: make 'verbose' a client parameter
Rather than requiring the 'verbose' flag as a parameter to
JSONRPCClient.call(), move it to the JSONRPCClient constructor so that
it can be set once.

This fixes the inconsistency between RPC method wrappers that passed
args.verbose and those that didn't; now, rpc.py -v works reliably for
all methods.

The JSONRPCClient.call() verbose parameter is maintained as well to
allow individual calls to be set to verbose if desired.

Change-Id: Iee385510cc9eb1d2984d3b9982055789dff188c6
Signed-off-by: Daniel Verkamp <daniel.verkamp@intel.com>
Reviewed-on: https://review.gerrithub.io/398508
Tested-by: SPDK Automated Test System <sys_sgsw@intel.com>
Reviewed-by: Jim Harris <james.r.harris@intel.com>
Reviewed-by: <shuhei.matsumoto.xt@hitachi.com>
2018-02-06 08:54:38 -05:00

85 lines
2.1 KiB
Python
Executable File

import json
import socket
try:
from shlex import quote
except ImportError:
from pipes import quote
def print_dict(d):
print json.dumps(d, indent=2)
def print_array(a):
print " ".join((quote(v) for v in a))
def int_arg(arg):
return int(arg, 0)
class JSONRPCClient(object):
def __init__(self, addr, port=None, verbose=False):
self.verbose = verbose
if addr.startswith('/'):
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sock.connect(addr)
else:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((addr, port))
def __del__(self):
self.sock.close()
def call(self, method, params={}, verbose=False):
req = {}
req['jsonrpc'] = '2.0'
req['method'] = method
req['id'] = 1
if (params):
req['params'] = params
reqstr = json.dumps(req)
verbose = verbose or self.verbose
if verbose:
print("request:")
print(json.dumps(req, indent=2))
self.sock.sendall(reqstr)
buf = ''
closed = False
response = {}
while not closed:
newdata = self.sock.recv(4096)
if (newdata == b''):
closed = True
buf += newdata
try:
response = json.loads(buf)
except ValueError:
continue # incomplete response; keep buffering
break
if not response:
if method == "kill_instance":
exit(0)
print "Connection closed with partial response:"
print buf
exit(1)
if 'error' in response:
print "Got JSON-RPC error response"
print "request:"
print_dict(json.loads(reqstr))
print "response:"
print_dict(response['error'])
exit(1)
if verbose:
print("response:")
print(json.dumps(response, indent=2))
return response['result']