5 from vstf.common import constants
7 LOG = logging.getLogger(__name__)
10 def json_defaults(obj):
11 if isinstance(obj, set):
18 if isinstance(msg, str):
21 return json.dumps(msg, default=json_defaults)
26 if isinstance(msg, str):
27 return json.loads(msg)
33 return str(uuid.uuid4())
36 def add_context(msg, **kwargs):
37 return {'head': kwargs, 'body': msg}
41 if "head" in msg.iterkeys():
48 if "body" in msg.iterkeys():
54 def get_corrid(context):
56 :param return: string of corrid or empty
58 if "corrid" in context.iterkeys():
59 return context['corrid']
65 # the message must be a string
66 if not isinstance(data, str):
67 raise ValueError("the data must be a string")
69 # the message's len must > 0
74 # the message's len must be less 999999999
75 if len(str(msg_len)) > constants.MSG_FLAG_LEN:
76 raise ValueError("the data's len too long")
78 data = (constants.MSG_FLAG % (msg_len)) + data
79 total_send = msg_len + constants.MSG_FLAG_LEN
82 while count < total_send:
83 sent = func(data[count:])
85 raise RuntimeError("socket connection broken")
91 def sendto(func, data, addr):
92 # the message must be a string
93 if not isinstance(data, str):
94 raise ValueError("the data must be a string")
96 # the message's len must > 0
101 # the message's len must be less 999999999
102 if len(str(msg_len)) > constants.MSG_FLAG_LEN:
103 raise ValueError("the data's len too long")
105 data = (constants.MSG_FLAG % (msg_len)) + data
106 total_send = msg_len + constants.MSG_FLAG_LEN
109 while count < total_send:
110 sent = func(data[count:], addr)
112 raise RuntimeError("socket connection broken")
119 head = func(constants.MSG_FLAG_LEN)
120 # the FIN change to '' in python
122 raise RuntimeError("socket connection broken")
124 if not head.isdigit():
125 raise ValueError("the msg head is not a num.")
130 while count < msg_len:
131 chunk = func(min(msg_len - count, constants.buff_size))
133 raise RuntimeError("socket connection broken")
137 return ''.join(chunks)
141 return traceback.format_exc()