1 ##############################################################################
2 # Copyright (c) 2015 Huawei Technologies Co.,Ltd and others.
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
14 from vstf.common import constants
16 LOG = logging.getLogger(__name__)
19 def json_defaults(obj):
20 if isinstance(obj, set):
27 if isinstance(msg, str):
30 return json.dumps(msg, default=json_defaults)
35 if isinstance(msg, str):
36 return json.loads(msg)
42 return str(uuid.uuid4())
45 def add_context(msg, **kwargs):
46 return {'head': kwargs, 'body': msg}
50 if "head" in msg.iterkeys():
57 if "body" in msg.iterkeys():
63 def get_corrid(context):
65 :param return: string of corrid or empty
67 if "corrid" in context.iterkeys():
68 return context['corrid']
74 # the message must be a string
75 if not isinstance(data, str):
76 raise ValueError("the data must be a string")
78 # the message's len must > 0
83 # the message's len must be less 999999999
84 if len(str(msg_len)) > constants.MSG_FLAG_LEN:
85 raise ValueError("the data's len too long")
87 data = (constants.MSG_FLAG % (msg_len)) + data
88 total_send = msg_len + constants.MSG_FLAG_LEN
91 while count < total_send:
92 sent = func(data[count:])
94 raise RuntimeError("socket connection broken")
100 def sendto(func, data, addr):
101 # the message must be a string
102 if not isinstance(data, str):
103 raise ValueError("the data must be a string")
105 # the message's len must > 0
110 # the message's len must be less 999999999
111 if len(str(msg_len)) > constants.MSG_FLAG_LEN:
112 raise ValueError("the data's len too long")
114 data = (constants.MSG_FLAG % (msg_len)) + data
115 total_send = msg_len + constants.MSG_FLAG_LEN
118 while count < total_send:
119 sent = func(data[count:], addr)
121 raise RuntimeError("socket connection broken")
128 head = func(constants.MSG_FLAG_LEN)
129 # the FIN change to '' in python
131 raise RuntimeError("socket connection broken")
133 if not head.isdigit():
134 raise ValueError("the msg head is not a num.")
139 while count < msg_len:
140 chunk = func(min(msg_len - count, constants.buff_size))
142 raise RuntimeError("socket connection broken")
146 return ''.join(chunks)
150 return traceback.format_exc()