30 #include <sys/types.h>
39 #include "boost/tuple/tuple.hpp"
52 const std::map<std::string, std::string>& parsed_options,
53 const std::string& option_string)
57 std::map<std::string, std::string>::const_iterator iter;
59 iter = parsed_options.find(
"new_style");
60 gen_newstyle_ = (iter != parsed_options.end());
62 iter = parsed_options.find(
"slots");
63 gen_slots_ = (iter != parsed_options.end());
65 iter = parsed_options.find(
"dynamic");
66 gen_dynamic_ = (iter != parsed_options.end());
70 gen_dynbaseclass_ =
"TBase";
71 gen_dynbaseclass_exc_ =
"TExceptionBase";
72 import_dynbase_ =
"from thrift.protocol.TBase import TBase, TExceptionBase\n";
75 iter = parsed_options.find(
"dynbase");
76 if (iter != parsed_options.end()) {
78 gen_dynbaseclass_ = (iter->second);
81 iter = parsed_options.find(
"dynexc");
82 if (iter != parsed_options.end()) {
83 gen_dynbaseclass_exc_ = (iter->second);
86 iter = parsed_options.find(
"dynimport");
87 if (iter != parsed_options.end()) {
89 import_dynbase_ = (iter->second);
92 iter = parsed_options.find(
"twisted");
93 gen_twisted_ = (iter != parsed_options.end());
95 iter = parsed_options.find(
"utf8strings");
96 gen_utf8strings_ = (iter != parsed_options.end());
98 copy_options_ = option_string;
101 out_dir_base_ =
"gen-py.twisted";
103 out_dir_base_ =
"gen-py";
111 void init_generator();
112 void close_generator();
118 void generate_typedef (
t_typedef* ttypedef);
119 void generate_enum (
t_enum* tenum);
120 void generate_const (
t_const* tconst);
121 void generate_struct (
t_struct* tstruct);
122 void generate_xception (
t_struct* txception);
123 void generate_service (
t_service* tservice);
125 void generate_sandesh (
t_sandesh* tsandesh);
133 void generate_py_struct(
t_struct* tstruct,
bool is_exception);
134 void generate_py_struct_definition(std::ofstream& out,
t_struct* tstruct,
bool is_xception=
false,
bool is_result=
false);
135 void generate_py_struct_reader(std::ofstream& out,
t_struct* tstruct);
136 void generate_py_struct_writer(std::ofstream& out,
t_struct* tstruct);
137 void generate_py_struct_required_validator(std::ofstream& out,
t_struct* tstruct);
138 void generate_py_function_helpers(
t_function* tfunction);
140 void generate_py_struct_logger(std::ofstream& out,
t_struct* tstruct);
141 void generate_py_struct_sizeof(std::ofstream& out,
t_struct* tstruct);
148 void generate_py_sandesh(
t_sandesh *tsandesh);
149 void generate_py_sandesh_definition(std::ofstream& out,
t_sandesh* tsandesh);
150 void generate_py_sandesh_reader(std::ofstream& out,
t_sandesh* tsandesh);
151 void generate_py_sandesh_writer(std::ofstream& out,
t_sandesh* tsandesh);
152 void generate_py_sandesh_compare(std::ofstream& out,
t_sandesh* tsandesh);
153 void generate_py_sandesh_required_validator(std::ofstream& out,
t_sandesh* tsandesh);
154 void generate_py_sandesh_http_request_handler(std::ofstream& out,
t_sandesh* tsandesh);
155 void generate_py_sandesh_http_attr(ofstream& out,
156 t_type *ftype,
const std::string& namel,
const std::string& namer);
157 void generate_py_sandesh_skeleton_request(std::ofstream& out,
t_sandesh* tsandesh);
158 void generate_py_sandesh_request_list(std::ofstream& out);
159 void generate_py_sandesh_http_request_list(std::ofstream& out,
t_sandesh* tsandesh);
160 void generate_struct_log(std::ofstream& out, std::string prefix, std::string log_str);
161 void generate_container_log(std::ofstream& out, std::string prefix,
t_type* ttype,
string log_str);
162 void generate_field_log(std::ofstream& out,
t_field *tfield, std::string log_str, std::string prefix);
163 void generate_py_sandesh_logger(std::ofstream& out,
t_sandesh* tsandesh);
164 void generate_py_sandesh_hint(std::ofstream& out,
t_sandesh* tsandesh);
165 void generate_py_sandesh_async(std::ofstream& out,
t_sandesh* tsandesh);
166 void generate_py_sandesh_request(std::ofstream& out,
t_sandesh* tsandesh);
167 void generate_py_sandesh_response(std::ofstream& out,
t_sandesh* tsandesh);
168 void generate_py_sandesh_uve(std::ofstream& out,
t_sandesh* tsandesh,
bool update);
169 void generate_py_sandesh_uve_list(std::ofstream& out);
170 void generate_py_sandesh_alarm_list(std::ofstream& out);
171 void generate_py_sandesh_trace(std::ofstream& out,
t_sandesh* tsandesh);
172 void generate_py_sandesh_sizeof(std::ofstream& out,
t_sandesh* tsandesh);
176 void generate_py_sizeof(std::ofstream& out,
const vector<t_field*>& fields);
183 void generate_service_helpers (
t_service* tservice);
184 void generate_service_interface (
t_service* tservice);
185 void generate_service_client (
t_service* tservice);
186 void generate_service_remote (
t_service* tservice);
187 void generate_service_server (
t_service* tservice);
194 void generate_deserialize_field (std::ofstream &out,
196 std::string prefix=
"",
199 void generate_deserialize_struct (std::ofstream &out,
201 std::string prefix=
"");
203 void generate_deserialize_container (std::ofstream &out,
205 std::string prefix=
"");
207 void generate_deserialize_set_element (std::ofstream &out,
209 std::string prefix=
"");
211 void generate_deserialize_map_element (std::ofstream &out,
213 std::string prefix=
"");
215 void generate_deserialize_list_element (std::ofstream &out,
217 std::string prefix=
"");
219 void generate_serialize_field (std::ofstream &out,
221 std::string prefix=
"");
223 void generate_serialize_struct (std::ofstream &out,
225 std::string prefix=
"");
228 void generate_serialize_sandesh (std::ofstream &out,
230 std::string prefix=
"");
233 void generate_serialize_container (std::ofstream &out,
235 std::string prefix=
"");
237 void generate_serialize_map_element (std::ofstream &out,
242 void generate_serialize_set_element (std::ofstream &out,
246 void generate_serialize_list_element (std::ofstream &out,
259 const char* subheader);
268 std::string py_autogen_comment();
269 std::string future_imports();
271 std::string py_autogen_sandesh_request_skeleton_comment();
272 void py_autogen_sandesh_http_request_open(std::ofstream& out);
273 void py_autogen_sandesh_http_request_close(std::ofstream& out);
275 std::string py_imports();
276 std::string render_includes();
277 std::string render_fastbinary_includes();
279 std::string render_sandesh_includes();
281 std::string declare_argument(
t_field* tfield);
282 std::string render_field_default_value(
t_field* tfield);
283 std::string type_name(
t_type* ttype);
284 std::string function_signature(
t_function* tfunction, std::string prefix=
"");
285 std::string function_signature_if(
t_function* tfunction, std::string prefix=
"");
286 std::string argument_list(
t_struct* tstruct);
287 std::string type_to_enum(
t_type* ttype);
288 std::string type_to_spec_args(
t_type* ttype);
291 return sub_namespace ==
"twisted";
296 std::string twisted_module = program->
get_namespace(
"py.twisted");
297 if(!twisted_module.empty()){
298 return twisted_module;
303 if (real_module.empty()) {
345 std::vector<std::string> sandesh_req_list_;
350 std::vector<boost::tuple<std::string, std::string> > sandesh_uve_list_;
355 std::vector<boost::tuple<std::string, std::string> > sandesh_alarm_list_;
366 std::ofstream f_request_impl_;
367 std::ofstream f_http_request_;
383 string module = get_real_py_module(program_, gen_twisted_);
384 package_dir_ = get_out_dir();
387 MKDIR(package_dir_.c_str());
388 std::ofstream init_py((package_dir_+
"/__init__.py").c_str());
390 if (module.empty()) {
393 string::size_type pos = module.find(
'.');
394 if (pos == string::npos) {
396 package_dir_ += module;
400 package_dir_ += module.substr(0, pos);
401 module.erase(0, pos+1);
406 string f_types_name = package_dir_+
"/"+
"ttypes.py";
407 f_types_.open(f_types_name.c_str());
409 string f_consts_name = package_dir_+
"/"+
"constants.py";
410 f_consts_.open(f_consts_name.c_str());
412 string f_init_name = package_dir_+
"/__init__.py";
414 f_init.open(f_init_name.c_str());
416 "__all__ = ['ttypes', 'constants'";
417 vector<t_service*> services = program_->get_services();
418 vector<t_service*>::iterator sv_iter;
419 for (sv_iter = services.begin(); sv_iter != services.end(); ++sv_iter) {
420 f_init <<
", '" << (*sv_iter)->get_name() <<
"'";
422 f_init <<
"]" << endl;
427 py_autogen_comment() << endl <<
428 py_imports() << endl <<
429 future_imports() << endl <<
430 render_includes() << endl <<
431 render_fastbinary_includes() <<
432 render_sandesh_includes() <<
436 py_autogen_comment() << endl <<
437 py_imports() << endl <<
438 "from .ttypes import *" << endl <<
441 string f_request_impl_name = package_dir_+
"/request_skeleton.py";
442 f_request_impl_.open(f_request_impl_name.c_str());
444 py_autogen_comment() << endl;
446 py_autogen_sandesh_request_skeleton_comment() << endl;
448 string f_http_request_name = package_dir_+
"/http_request.py";
449 f_http_request_.open(f_http_request_name.c_str());
451 py_autogen_comment() << endl;
453 "from . import ttypes" << endl;
454 py_autogen_sandesh_http_request_open(f_http_request_);
462 const vector<t_program*>& includes = program_->get_includes();
464 for (
size_t i = 0; i < includes.size(); ++i) {
465 result +=
"from ." + get_real_py_module(includes[i], gen_twisted_) +
466 " import ttypes as " + get_real_py_module(includes[i], gen_twisted_) +
"_ttypes\n";
468 if (includes.size() > 0) {
480 hdr += std::string(import_dynbase_);
484 "from pysandesh.transport import TTransport\n"
485 "from pysandesh.protocol import TBinaryProtocol, TProtocol\n"
487 " from pysandesh.protocol import fastbinary\n"
489 " fastbinary = None\n";
492 "from thrift.transport import TTransport\n"
493 "from thrift.protocol import TBinaryProtocol, TProtocol\n"
495 " from thrift.protocol import fastbinary\n"
497 " fastbinary = None\n";
504 string t_py_generator::render_sandesh_includes() {
505 std::string module = get_real_py_module(program_, gen_twisted_);
506 std::string sandesh_includes(
"\n");
508 "from io import StringIO\n"
511 "from sys import getsizeof\n"
512 "from itertools import chain\n";
513 if (module !=
"sandesh") {
516 "from pysandesh import sandesh_base\n"
517 "from pysandesh.sandesh_http import SandeshHttp\n"
518 "from pysandesh.sandesh_uve import SandeshUVETypeMaps\n"
519 "from pysandesh.util import UTCTimestampUsec, UTCTimestampUsecToString\n"
520 "from pysandesh import util\n"
521 "from pysandesh.gen_py.sandesh.constants import *\n";
523 return sandesh_includes;
536 "# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING\n" +
538 "# options string: " + copy_options_ +
"\n" +
539 "# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.\n" +
544 "# Autogenerated by Thrift Compiler \n" +
546 "# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING\n" +
548 "# options string: " + copy_options_ +
"\n" +
559 string(
"from pysandesh.Thrift import TType, TMessageType, TException");
562 string(
"from thrift.Thrift import TType, TMessageType, TException");
570 std::string future_imports(
"\n");
571 return future_imports;
579 generate_py_sandesh_request_list(f_types_);
580 generate_py_sandesh_uve_list(f_types_);
581 generate_py_sandesh_alarm_list(f_types_);
587 f_request_impl_.close();
588 py_autogen_sandesh_http_request_close(f_http_request_);
589 f_http_request_.close();
609 std::ostringstream to_string_mapping, from_string_mapping;
613 (gen_newstyle_ ?
"(object)" :
"") <<
614 (gen_dynamic_ ?
"(" + gen_dynbaseclass_ +
")" :
"") <<
617 generate_python_docstring(f_types_, tenum);
619 to_string_mapping << indent() <<
"_VALUES_TO_NAMES = {" << endl;
620 from_string_mapping << indent() <<
"_NAMES_TO_VALUES = {" << endl;
623 vector<t_enum_value*>::iterator c_iter;
624 for (c_iter = constants.begin(); c_iter != constants.end(); ++c_iter) {
625 int value = (*c_iter)->get_value();
626 indent(f_types_) << (*c_iter)->get_name() <<
" = " << value << endl;
630 indent() << indent() << value <<
": \"" <<
631 escape_string((*c_iter)->get_name()) <<
"\"," << endl;
632 from_string_mapping <<
633 indent() << indent() <<
'"' << escape_string((*c_iter)->get_name()) <<
634 "\": " << value <<
',' << endl;
636 to_string_mapping << indent() <<
"}" << endl;
637 from_string_mapping << indent() <<
"}" << endl;
641 f_types_ << to_string_mapping.str() << endl << from_string_mapping.str() << endl;
652 indent(f_consts_) << name <<
" = " << render_const_value(
type, value);
663 std::ostringstream out;
665 if (
type->is_base_type()) {
670 case t_base_type::TYPE_STATIC_CONST_STRING:
671 case t_base_type::TYPE_XML:
673 out <<
'"' << get_escaped_string(value) <<
'"';
676 out << (value->
get_integer() > 0 ?
"True" :
"False");
683 case t_base_type::TYPE_U16:
684 case t_base_type::TYPE_U32:
685 case t_base_type::TYPE_U64:
686 case t_base_type::TYPE_IPV4:
698 case t_base_type::TYPE_UUID:
699 out <<
"uuid.UUID('{" << get_escaped_string(value) <<
"}')";
701 case t_base_type::TYPE_IPADDR:
702 out <<
"netaddr.IPAddress('" << value->
get_string() <<
"')";
708 }
else if (
type->is_enum()) {
710 }
else if (
type->is_struct() ||
type->is_xception()) {
711 out <<
type->get_name() <<
"(**{" << endl;
713 const vector<t_field*>& fields = ((
t_struct*)
type)->get_members();
714 vector<t_field*>::const_iterator f_iter;
715 const map<t_const_value*, t_const_value*>& val = value->
get_map();
716 map<t_const_value*, t_const_value*>::const_iterator v_iter;
717 for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
718 t_type* field_type = NULL;
719 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
720 if ((*f_iter)->get_name() == v_iter->first->get_string()) {
721 field_type = (*f_iter)->get_type();
724 if (field_type == NULL) {
725 throw "type error: " +
type->get_name() +
" has no field " + v_iter->first->get_string();
730 out << render_const_value(field_type, v_iter->second);
735 }
else if (
type->is_map()) {
740 const map<t_const_value*, t_const_value*>& val = value->
get_map();
741 map<t_const_value*, t_const_value*>::const_iterator v_iter;
742 for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
744 out << render_const_value(ktype, v_iter->first);
746 out << render_const_value(vtype, v_iter->second);
751 }
else if (
type->is_list() ||
type->is_set()) {
753 if (
type->is_list()) {
758 if (
type->is_set()) {
763 const vector<t_const_value*>& val = value->
get_list();
764 vector<t_const_value*>::const_iterator v_iter;
765 for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
767 out << render_const_value(etype, *v_iter);
772 if (
type->is_set()) {
776 throw "CANNOT GENERATE CONSTANT FOR TYPE: " +
type->get_name();
786 generate_py_struct(tstruct,
false);
796 generate_py_struct(txception,
true);
799 void t_py_generator::generate_sandesh(
t_sandesh* tsandesh) {
800 generate_py_sandesh(tsandesh);
808 generate_py_struct_definition(f_types_, tstruct, is_exception);
821 const vector<t_field*>& members = tstruct->
get_members();
823 vector<t_field*>::const_iterator m_iter;
829 out <<
"(" << gen_dynbaseclass_exc_ <<
")";
831 out <<
"(TException)";
836 }
else if (gen_dynamic_) {
837 out <<
"(" << gen_dynbaseclass_ <<
")";
842 generate_python_docstring(out, tstruct);
867 indent(out) <<
"__slots__ = [ " << endl;
869 for (m_iter = sorted_members.begin(); m_iter != sorted_members.end(); ++m_iter) {
870 indent(out) <<
"'" << (*m_iter)->get_name() <<
"'," << endl;
873 indent(out) <<
" ]" << endl << endl;
881 if (sorted_members.empty() || (sorted_members[0]->get_key() >= 0)) {
882 indent(out) <<
"thrift_spec = (" << endl;
885 int sorted_keys_pos = 0;
886 for (m_iter = sorted_members.begin(); m_iter != sorted_members.end(); ++m_iter) {
888 for (; sorted_keys_pos != (*m_iter)->get_key(); sorted_keys_pos++) {
889 indent(out) <<
"None, # " << sorted_keys_pos << endl;
892 indent(out) <<
"(" << (*m_iter)->get_key() <<
", "
893 << type_to_enum((*m_iter)->get_type()) <<
", "
894 <<
"'" << (*m_iter)->get_name() <<
"'" <<
", "
895 << type_to_spec_args((*m_iter)->get_type()) <<
", "
896 << render_field_default_value(*m_iter) <<
", "
898 <<
" # " << sorted_keys_pos
905 indent(out) <<
")" << endl << endl;
907 indent(out) <<
"thrift_spec = None" << endl;
911 if (members.size() > 0) {
913 indent() <<
"def __init__(self,";
915 for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
918 t_type*
type = get_true_type((*m_iter)->get_type());
919 if (
type->is_static_const_string()) {
924 out <<
" " << declare_argument(*m_iter) <<
",";
931 for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
934 if (!
type->is_base_type() && !
type->is_enum() && (*m_iter)->get_value() != NULL) {
936 "if " << (*m_iter)->get_name() <<
" is " <<
"self.thrift_spec[" <<
937 (*m_iter)->get_key() <<
"][4]:" << endl;
938 indent(out) <<
" " << (*m_iter)->get_name() <<
" = " <<
939 render_field_default_value(*m_iter) << endl;
941 }
else if (
type->is_static_const_string()) {
943 "self." << (*m_iter)->get_name() <<
" = " <<
944 render_const_value(
type, (*m_iter)->get_value()) << endl;
950 "self." << (*m_iter)->get_name() <<
" = " << (*m_iter)->get_name() << endl;
957 for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
958 if ((*m_iter)->get_name() ==
"name") {
959 std::map<std::string, std::string>::iterator it;
960 it = (*m_iter)->annotations_.find(
"key");
961 if (it != (*m_iter)->annotations_.end()) {
962 indent(out) <<
"self._table = '" << it->second <<
"'" << endl;
975 generate_py_struct_reader(out, tstruct);
976 generate_py_struct_writer(out, tstruct);
980 generate_py_struct_logger(out, tstruct);
981 generate_py_struct_sizeof(out, tstruct);
989 indent() <<
"def __str__(self):" << endl <<
990 indent() <<
" return repr(self)" << endl <<
998 indent() <<
"def __repr__(self):" << endl <<
999 indent() <<
" L = ['%s=%r' % (key, value)" << endl <<
1000 indent() <<
" for key, value in self.__dict__.items()]" << endl <<
1001 indent() <<
" return '%s(%s)' % (self.__class__.__name__, ', '.join(L))" << endl <<
1006 indent() <<
"def __eq__(self, other):" << endl;
1009 indent() <<
"return isinstance(other, self.__class__) and "
1010 "self.__dict__ == other.__dict__" << endl;
1015 indent() <<
"def __ne__(self, other):" << endl;
1019 indent() <<
"return not (self == other)" << endl;
1026 indent() <<
"def __hash__(self):" << endl;
1030 indent() <<
"return id(self)" << endl;
1032 }
else if (!gen_dynamic_) {
1036 indent() <<
"def __repr__(self):" << endl <<
1037 indent() <<
" L = ['%s=%r' % (key, getattr(self, key))" << endl <<
1038 indent() <<
" for key in self.__slots__]" << endl <<
1039 indent() <<
" return '%s(%s)' % (self.__class__.__name__, ', '.join(L))" << endl <<
1044 indent() <<
"def __eq__(self, other):" << endl <<
1045 indent() <<
" if not isinstance(other, self.__class__):" << endl <<
1046 indent() <<
" return False" << endl <<
1047 indent() <<
" for attr in self.__slots__:" << endl <<
1048 indent() <<
" my_val = getattr(self, attr)" << endl <<
1049 indent() <<
" other_val = getattr(other, attr)" << endl <<
1050 indent() <<
" if my_val != other_val:" << endl <<
1051 indent() <<
" return False" << endl <<
1052 indent() <<
" return True" << endl <<
1056 indent() <<
"def __ne__(self, other):" << endl <<
1057 indent() <<
" return not (self == other)" << endl <<
1068 const vector<t_field*>& fields = tstruct->
get_members();
1069 vector<t_field*>::const_iterator f_iter;
1072 "def read(self, iprot):" << endl;
1076 "if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated "
1077 "and isinstance(iprot.trans, TTransport.CReadableTransport) "
1078 "and self.thrift_spec is not None "
1079 "and fastbinary is not None:" << endl;
1083 "fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))" << endl;
1095 "read_cnt = 0" << endl;
1100 "length = iprot.readStructBegin()" << endl;
1102 "if length < 0: return -1" << endl;
1104 "read_cnt += length" << endl;
1107 "iprot.readStructBegin()" << endl;
1112 "while True:" << endl;
1118 "(length, fname, ftype, fid) = iprot.readFieldBegin()" << endl;
1120 "if length < 0: return -1" << endl;
1122 "read_cnt += length" << endl;
1125 "(fname, ftype, fid) = iprot.readFieldBegin()" << endl;
1130 "if ftype == TType.STOP:" << endl;
1140 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1149 out <<
"fid == " << (*f_iter)->get_key() <<
":" << endl;
1156 indent() <<
"else:" << endl <<
1157 indent() <<
" iprot.skip(ftype)" << endl;
1163 indent() <<
"else:" << endl <<
1164 indent() <<
" iprot.skip(ftype)" << endl;
1169 "length = iprot.readFieldEnd()" << endl;
1171 "if length < 0: return -1" << endl;
1173 "read_cnt += length" << endl;
1176 "iprot.readFieldEnd()" << endl;
1183 "length = iprot.readStructEnd()" << endl;
1185 "if length < 0: return -1" << endl;
1187 "read_cnt += length" << endl;
1190 "iprot.readStructEnd()" << endl;
1195 "return read_cnt" << endl;
1206 vector<t_field*>::const_iterator f_iter;
1209 "def write(self, oprot):" << endl;
1213 "if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated "
1214 "and self.thrift_spec is not None "
1215 "and fastbinary is not None:" << endl;
1219 "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))" << endl;
1231 "if oprot.writeStructBegin(self.__class__.__name__) < 0: return -1" << endl;
1234 "oprot.writeStructBegin('" << name <<
"')" << endl;
1237 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1241 "if self." << (*f_iter)->get_name() <<
" is not None:" << endl;
1244 "annotations = {}" << endl;
1245 if (!((*f_iter)->annotations_.empty())) {
1246 std::map<std::string, std::string>::iterator it;
1247 for (it = (*f_iter)->annotations_.begin(); it != (*f_iter)->annotations_.end(); it++) {
1248 if (((*f_iter)->get_name() ==
"name") && (it->first ==
"key")) {
1249 indent(out) <<
"if self._table is None or self._table == '': return -1" << endl;
1250 indent(out) <<
"annotations['key'] = " <<
"self._table" << endl;
1252 indent(out) <<
"annotations['" << (*it).first <<
"'] = '" <<
1253 (*it).second <<
"'" << endl;
1258 "if oprot.writeFieldBegin(" <<
1259 "'" << (*f_iter)->get_name() <<
"', " <<
1261 (*f_iter)->get_key() <<
", annotations) < 0: return -1" << endl;
1264 "if self." << (*f_iter)->get_name() <<
" is not None:" << endl;
1267 "oprot.writeFieldBegin(" <<
1268 "'" << (*f_iter)->get_name() <<
"', " <<
1270 (*f_iter)->get_key() <<
")" << endl;
1279 "if oprot.writeFieldEnd() < 0: return -1" << endl;
1282 "oprot.writeFieldEnd()" << endl;
1290 indent() <<
"if oprot.writeFieldStop() < 0: return -1" << endl <<
1291 indent() <<
"if oprot.writeStructEnd() < 0: return -1" << endl <<
1292 indent() <<
"return 0" << endl;
1295 indent() <<
"oprot.writeFieldStop()" << endl <<
1296 indent() <<
"oprot.writeStructEnd()" << endl;
1307 indent(out) <<
"def validate(self):" << endl;
1310 const vector<t_field*>& fields = tstruct->
get_members();
1312 if (fields.size() > 0) {
1313 vector<t_field*>::const_iterator f_iter;
1315 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1318 indent(out) <<
"if self." << field->
get_name() <<
" is None:" << endl;
1319 indent(out) <<
" raise TProtocol.TProtocolException(message='Required field " <<
1320 field->
get_name() <<
" is unset!')" << endl;
1325 indent(out) <<
"return" << endl << endl;
1330 void t_py_generator::generate_py_sandesh(
t_sandesh *tsandesh) {
1331 generate_py_sandesh_definition(
f_types_, tsandesh);
1334 void t_py_generator::generate_py_sandesh_definition(ofstream& out,
1336 const vector<t_field*>& members = tsandesh->
get_members();
1338 vector<t_field*>::const_iterator m_iter;
1341 std::string base_class;
1342 if (sandesh_type->is_sandesh_system()) {
1343 base_class =
"sandesh_base.SandeshSystem";
1344 }
else if (sandesh_type->is_sandesh_object()) {
1345 base_class =
"sandesh_base.SandeshObject";
1346 }
else if (sandesh_type->is_sandesh_flow()) {
1347 if (sandesh_type->is_sandesh_session()) {
1348 base_class =
"sandesh_base.SandeshFlowSession";
1350 base_class =
"sandesh_base.SandeshFlow";
1352 }
else if (sandesh_type->is_sandesh_request()) {
1353 base_class =
"sandesh_base.SandeshRequest";
1354 }
else if (sandesh_type->is_sandesh_response()) {
1355 base_class =
"sandesh_base.SandeshResponse";
1356 }
else if (sandesh_type->is_sandesh_uve()) {
1357 base_class =
"sandesh_base.SandeshUVE";
1358 }
else if (sandesh_type->is_sandesh_dynamic_uve()) {
1359 base_class =
"sandesh_base.SandeshDynamicUVE";
1360 }
else if (sandesh_type->is_sandesh_alarm()) {
1361 base_class =
"sandesh_base.SandeshAlarm";
1362 }
else if (sandesh_type->is_sandesh_trace() ||
1363 sandesh_type->is_sandesh_trace_object()) {
1364 base_class =
"sandesh_base.SandeshTrace";
1366 throw "compiler error: unsupported sandesh type " +
1372 out <<
"(" << base_class <<
"):" << endl;
1399 indent(out) <<
"__slots__ = [ " << endl;
1401 for (m_iter = sorted_members.begin(); m_iter != sorted_members.end(); ++m_iter) {
1402 indent(out) <<
"'" << (*m_iter)->get_name() <<
"'," << endl;
1405 indent(out) <<
" ]" << endl << endl;
1413 if (sorted_members.empty() || (sorted_members[0]->get_key() >= 0)) {
1414 indent(out) <<
"thrift_spec = (" << endl;
1417 int sorted_keys_pos = 0;
1418 for (m_iter = sorted_members.begin(); m_iter != sorted_members.end(); ++m_iter) {
1420 for (; sorted_keys_pos != (*m_iter)->get_key(); sorted_keys_pos++) {
1421 indent(out) <<
"None, # " << sorted_keys_pos << endl;
1424 indent(out) <<
"(" << (*m_iter)->get_key() <<
", "
1426 <<
"'" << (*m_iter)->get_name() <<
"'" <<
", "
1430 <<
" # " << sorted_keys_pos
1437 indent(out) <<
")" << endl << endl;
1439 indent(out) <<
"thrift_spec = None" << endl << endl;
1442 if (sandesh_type->is_sandesh_system()) {
1443 indent(out) <<
"rate_limit_buffer = util.deque(maxlen=sandesh_base."
1444 "SandeshSystem._DEFAULT_SEND_RATELIMIT)" << endl << endl;
1445 indent(out) <<
"do_rate_limit_drop_log = True" << endl << endl;
1450 indent() <<
"def __init__(self";
1452 for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
1455 if (
type->is_static_const_string()) {
1462 if (sandesh_type->is_sandesh_system() ||
1463 sandesh_type->is_sandesh_object() ||
1464 sandesh_type->is_sandesh_flow()) {
1465 out <<
", category='" <<
"__default__" <<
1466 "', level=SandeshLevel.SYS_INFO";
1468 if (sandesh_type->is_sandesh_uve() ||
1469 sandesh_type->is_sandesh_dynamic_uve() ||
1470 sandesh_type->is_sandesh_alarm()) {
1471 out <<
", table=None";
1473 out <<
", sandesh=sandesh_base.sandesh_global):" << endl;
1476 if (sandesh_type->is_sandesh_trace()) {
1477 indent(out) << base_class <<
1478 ".__init__(self, type=SandeshType.TRACE)" << endl;
1479 }
else if (sandesh_type->is_sandesh_trace_object()) {
1480 indent(out) << base_class <<
1481 ".__init__(self, type=SandeshType.TRACE_OBJECT)" << endl;
1483 indent(out) << base_class <<
".__init__(self)" << endl;
1486 for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
1489 if (!
type->is_base_type() && !
type->is_enum() && (*m_iter)->get_value() != NULL) {
1491 "if " << (*m_iter)->get_name() <<
" is " <<
"self.thrift_spec[" <<
1492 (*m_iter)->get_key() <<
"][4]:" << endl;
1493 indent(out) <<
" " << (*m_iter)->get_name() <<
" = " <<
1495 }
else if (
type->is_static_const_string()) {
1497 "self." << (*m_iter)->get_name() <<
" = " <<
1501 "self." << (*m_iter)->get_name() <<
" = " << (*m_iter)->get_name() << endl;
1505 indent(out) <<
"self._scope = sandesh.scope()" << endl;
1506 indent(out) <<
"self._module = sandesh.module()" << endl;
1507 indent(out) <<
"self._source = sandesh.source_id()" << endl;
1508 indent(out) <<
"self._node_type = sandesh.node_type()" << endl;
1509 indent(out) <<
"self._instance_id = sandesh.instance_id()" << endl;
1510 indent(out) <<
"self._seqnum = 0" << endl;
1511 indent(out) <<
"self._timestamp = UTCTimestampUsec()" << endl;
1513 generate_py_sandesh_hint(out, tsandesh);
1514 if (sandesh_type->is_sandesh_system() ||
1515 sandesh_type->is_sandesh_object() ||
1516 sandesh_type->is_sandesh_flow()) {
1517 indent(out) <<
"self._category = category" << endl;
1518 indent(out) <<
"self._level = level" << endl;
1520 if (sandesh_type->is_sandesh_uve() ||
1521 sandesh_type->is_sandesh_dynamic_uve() ||
1522 sandesh_type->is_sandesh_alarm()) {
1523 indent(out) <<
"if table is not None:" << endl;
1525 indent(out) <<
"self.data._table = table" << endl;
1533 if (sandesh_type->is_sandesh_system() ||
1534 sandesh_type->is_sandesh_object() ||
1535 sandesh_type->is_sandesh_flow()) {
1536 generate_py_sandesh_async(out, tsandesh);
1537 }
else if (sandesh_type->is_sandesh_request()) {
1538 generate_py_sandesh_request(out, tsandesh);
1539 }
else if (sandesh_type->is_sandesh_response()) {
1540 generate_py_sandesh_response(out, tsandesh);
1541 }
else if (sandesh_type->is_sandesh_uve() ||
1542 sandesh_type->is_sandesh_alarm()) {
1543 generate_py_sandesh_uve(out, tsandesh,
true);
1544 }
else if (sandesh_type->is_sandesh_dynamic_uve()) {
1545 generate_py_sandesh_uve(out, tsandesh,
false);
1546 }
else if (sandesh_type->is_sandesh_trace() ||
1547 sandesh_type->is_sandesh_trace_object()) {
1548 generate_py_sandesh_trace(out, tsandesh);
1551 generate_py_sandesh_logger(out, tsandesh);
1554 generate_py_sandesh_reader(out, tsandesh);
1555 generate_py_sandesh_writer(out, tsandesh);
1558 generate_py_sandesh_compare(out, tsandesh);
1559 generate_py_sandesh_sizeof(out, tsandesh);
1565 indent() <<
"def __repr__(self):" << endl <<
1566 indent() <<
" L = ['%s=%r' % (key, value)" << endl <<
1567 indent() <<
" for key, value in self.__dict__.items()]" << endl <<
1568 indent() <<
" return '%s(%s)' % (self.__class__.__name__, ', '.join(L))" << endl <<
1573 indent() <<
"def __eq__(self, other):" << endl;
1576 indent() <<
"return isinstance(other, self.__class__) and "
1577 "self.__dict__ == other.__dict__" << endl;
1582 indent() <<
"def __ne__(self, other):" << endl;
1586 indent() <<
"return not (self == other)" << endl;
1592 indent() <<
"def __repr__(self):" << endl <<
1593 indent() <<
" L = ['%s=%r' % (key, getattr(self, key))" << endl <<
1594 indent() <<
" for key in self.__slots__]" << endl <<
1595 indent() <<
" return '%s(%s)' % (self.__class__.__name__, ', '.join(L))" << endl <<
1600 indent() <<
"def __eq__(self, other):" << endl <<
1601 indent() <<
" if not isinstance(other, self.__class__):" << endl <<
1602 indent() <<
" return False" << endl <<
1603 indent() <<
" for attr in self.__slots__:" << endl <<
1604 indent() <<
" my_val = getattr(self, attr)" << endl <<
1605 indent() <<
" other_val = getattr(other, attr)" << endl <<
1606 indent() <<
" if my_val != other_val:" << endl <<
1607 indent() <<
" return False" << endl <<
1608 indent() <<
" return True" << endl <<
1612 indent() <<
"def __ne__(self, other):" << endl <<
1613 indent() <<
" return not (self == other)" << endl <<
1622 void t_py_generator::generate_py_sandesh_reader(ofstream& out,
1624 const vector<t_field*>& fields = tsandesh->
get_members();
1625 vector<t_field*>::const_iterator f_iter;
1628 "def read(self, iprot):" << endl;
1632 "if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated "
1633 "and isinstance(iprot.trans, TTransport.CReadableTransport) "
1634 "and self.thrift_spec is not None "
1635 "and fastbinary is not None:" << endl;
1639 "fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))" << endl;
1641 "return -1" << endl;
1645 "read_cnt = 0" << endl;
1648 "(length, sandesh_name) = iprot.readSandeshBegin()" << endl;
1650 "if length < 0: return -1" << endl;
1652 "read_cnt += length" << endl;
1656 "while True:" << endl;
1661 "(length, fname, ftype, fid) = iprot.readFieldBegin()" << endl;
1663 "if length < 0: return -1" << endl;
1665 "read_cnt += length" << endl;
1669 "if ftype == TType.STOP:" << endl;
1679 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1688 out <<
"fid == " << (*f_iter)->get_key() <<
":" << endl;
1695 indent() <<
"else:" << endl <<
1696 indent() <<
" iprot.skip(ftype)" << endl;
1702 indent() <<
"else:" << endl <<
1703 indent() <<
" iprot.skip(ftype)" << endl;
1707 "length = iprot.readFieldEnd()" << endl;
1709 "if length < 0: return -1" << endl;
1711 "read_cnt += length" << endl;
1716 "length = iprot.readSandeshEnd()" << endl;
1718 "if length < 0: return -1" << endl;
1720 "read_cnt += length" << endl;
1723 "return read_cnt" << endl;
1729 void t_py_generator::generate_py_sandesh_writer(ofstream& out,
1732 vector<t_field*>::const_iterator f_iter;
1735 "def write(self, oprot):" << endl;
1739 "if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated "
1740 "and self.thrift_spec is not None "
1741 "and fastbinary is not None:" << endl;
1745 "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))" << endl;
1751 "if oprot.writeSandeshBegin(self.__class__.__name__) < 0: return -1" << endl;
1752 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1755 "if self." << (*f_iter)->get_name() <<
" is not None:" << endl;
1758 "annotations = {}" << endl;
1759 if (!((*f_iter)->annotations_.empty())) {
1760 std::map<std::string, std::string>::iterator it;
1761 for (it = (*f_iter)->annotations_.begin(); it != (*f_iter)->annotations_.end(); it++) {
1762 indent(out) <<
"annotations['" << (*it).first <<
"'] = '" <<
1763 (*it).second <<
"'" << endl;
1767 "if oprot.writeFieldBegin(" <<
1768 "'" << (*f_iter)->get_name() <<
"', " <<
1770 (*f_iter)->get_key() <<
", annotations) < 0: return -1" << endl;
1777 "if oprot.writeFieldEnd() < 0: return -1" << endl;
1784 "if oprot.writeFieldStop() < 0: return -1" << endl;
1786 "if oprot.writeSandeshEnd() < 0: return -1" << endl;
1791 generate_py_sandesh_required_validator(out, tsandesh);
1796 void t_py_generator::generate_py_sandesh_required_validator(ofstream& out,
1798 indent(out) <<
"def validate(self):" << endl;
1801 const vector<t_field*>& fields = tsandesh->
get_members();
1803 if (fields.size() > 0) {
1804 vector<t_field*>::const_iterator f_iter;
1806 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1809 indent(out) <<
"if self." << field->
get_name() <<
" is None:" << endl;
1810 indent(out) <<
" raise TProtocol.TProtocolException(message='Required field " <<
1811 field->
get_name() <<
" is unset!')" << endl;
1816 indent(out) <<
"return" << endl << endl;
1820 void t_py_generator::generate_py_sandesh_compare(ofstream& out,
1823 vector<t_field*>::const_iterator f_iter;
1826 "def compare(self, other):" << endl;
1829 "if not isinstance(other, self.__class__):" << endl;
1832 "return False" << endl;
1835 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1837 "if self." << (*f_iter)->get_name() <<
" != " <<
1838 "other." << (*f_iter)->get_name() <<
":" << endl;
1840 indent(out) <<
"return False" << endl;
1844 indent(out) <<
"return True" << endl << endl;
1848 void t_py_generator::generate_py_sandesh_http_attr(ofstream& out,
1849 t_type *ftype,
const std::string& namel,
const std::string& namer) {
1856 "if bottle.request.query." << namer <<
":" << endl;
1860 "sandesh_req." << namel <<
" = str(" <<
1861 "bottle.request.query." << namer <<
")" << endl;
1862 }
else if (bftype == t_base_type::TYPE_UUID) {
1863 indent(out) <<
"try:" << endl;
1865 indent(out) <<
"sandesh_req." << namel <<
" = uuid.UUID("
1866 <<
"bottle.request.query." << namer <<
")" << endl;
1868 indent(out) <<
"except ValueError:" << endl;
1870 indent(out) <<
"return SandeshHttp.http_error('Invalid value for "
1871 << namel <<
":" << namer <<
"')" << endl;
1873 }
else if (bftype == t_base_type::TYPE_IPADDR) {
1874 indent(out) <<
"try:" << endl;
1876 indent(out) <<
"sandesh_req." << namel <<
" = netaddr.IPAddress("
1877 <<
"bottle.request.query." << namer <<
")" << endl;
1879 indent(out) <<
"except ValueError:" << endl;
1881 indent(out) <<
"return SandeshHttp.http_error('Invalid value for "
1882 << namel <<
":" << namer <<
"')" << endl;
1890 bftype == t_base_type::TYPE_U16 ||
1891 bftype == t_base_type::TYPE_U32 ||
1892 bftype == t_base_type::TYPE_U64 ||
1893 bftype == t_base_type::TYPE_IPV4);
1898 "sandesh_req." << namel <<
" = int(" <<
1899 "bottle.request.query." << namer <<
")" << endl;
1902 "except ValueError:" << endl;
1905 "return SandeshHttp.http_error('Invalid data provided in Sandesh Request')" << endl;
1915 void t_py_generator::generate_py_sandesh_http_request_handler(ofstream& out,
1918 vector<t_field*>::const_iterator f_iter;
1921 "@staticmethod" << endl;
1923 "def handle_http_request(sandesh=sandesh_base.sandesh_global):" << endl;
1926 "sandesh_req = " << tsandesh->
get_name() <<
"()" << endl;
1928 "if not sandesh_req:" << endl;
1930 indent(out) <<
"return SandeshHttp.http_error('Sandesh Request \"" << tsandesh->
get_name() <<
1931 "\" not implemented')" << endl;
1933 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1934 t_type *ftype = (*f_iter)->get_type();
1935 if (f_iter == fields.begin()) {
1936 generate_py_sandesh_http_attr(out, ftype, (*f_iter)->get_name(),
"x");
1938 generate_py_sandesh_http_attr(out, ftype, (*f_iter)->get_name(), (*f_iter)->get_name());
1941 indent(out) <<
"sandesh_req._context = bottle.request.url" << endl;
1942 indent(out) <<
"handle_req_fn = getattr(sandesh_req, \"handle_request\", None)" << endl;
1943 indent(out) <<
"if callable(handle_req_fn):" << endl;
1945 indent(out) <<
"handle_req_fn(sandesh_req)" << endl;
1947 indent(out) <<
"else:" << endl;
1949 indent(out) <<
"return SandeshHttp.http_error('Sandesh Request \"" << tsandesh->
get_name() <<
1950 "\" not implemented')" << endl;
1952 indent(out) <<
"resp = SandeshHttp.get_http_response()" << endl;
1953 indent(out) <<
"if resp:" << endl;
1955 indent(out) <<
"return resp" << endl;
1957 indent(out) <<
"else:" << endl;
1959 indent(out) <<
"return SandeshHttp.http_error('No Response for Sandesh Request \"" <<
1960 tsandesh->
get_name() <<
"\"')" << endl;
1967 void t_py_generator::generate_py_sandesh_request_list(ofstream& out) {
1968 out << endl << endl;
1969 out <<
"_SANDESH_REQUEST_LIST = [" << endl;
1970 std::vector<std::string>::const_iterator it;
1971 for (it = sandesh_req_list_.begin(); it != sandesh_req_list_.end(); ++it) {
1972 indent(out) << *it <<
"," << endl;
1977 void t_py_generator::generate_py_sandesh_http_request_list(ofstream& out,
1980 "{ 'uri':" <<
"'/Snh_" << tsandesh->
get_name() <<
"'" <<
1981 ", 'method':" <<
"ttypes." << tsandesh->
get_name() <<
".handle_http_request " <<
1985 void t_py_generator::py_autogen_sandesh_http_request_open(ofstream& out) {
1988 "_HTTP_REQUEST_LIST = [" << endl;
1991 void t_py_generator::py_autogen_sandesh_http_request_close(ofstream& out) {
1992 out <<
"]" << endl << endl;
1995 std::string t_py_generator::py_autogen_sandesh_request_skeleton_comment() {
1998 "# This autogenerated skeleton file illustrates the implementation of" +
2000 "# derived class to handle the sandesh request." +
2004 void t_py_generator::generate_py_sandesh_skeleton_request(ofstream& out,
2006 const vector<t_field*>& members = tsandesh->
get_members();
2007 vector<t_field*>::const_iterator m_iter;
2010 "# Create a derived class from \"" << tsandesh->
get_name() <<
"\" to handle ";
2012 "# the sandesh request. Add this derived class \"" << tsandesh->
get_name() <<
"_derived\"";
2014 "# in module " << tsandesh->
get_name() <<
"_derived.py and " <<
2015 "add it in your package" << endl;
2018 "class " << tsandesh->
get_name() <<
"_derived";
2019 out <<
"(" << tsandesh->
get_name() <<
"):" << endl;
2023 if (members.size() > 0) {
2025 indent() <<
"def __init__(self):" << endl;
2030 for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
2033 if (
type->is_static_const_string()) {
2043 out <<
indent() <<
"def handle_request(self):" << endl;
2046 "# Add your code to handle the \"" << tsandesh->
get_name() <<
2047 "\" request" << endl;
2054 void t_py_generator::generate_struct_log(ofstream& out,
2058 log_str <<
".write('<< ')" << endl;
2060 log_str <<
".write(" << prefix <<
".log())" << endl;
2062 log_str <<
".write('>>')" << endl;
2065 void t_py_generator::generate_container_log(ofstream& out,
2070 string kiter =
tmp(
"kiter");
2071 string viter =
tmp(
"viter");
2073 log_str <<
".write('{ ')" << endl;
2075 "for " << kiter <<
"," << viter <<
" in " << prefix <<
".items():" << endl;
2077 t_field kfield(((
t_map*)ttype)->get_key_type(), kiter);
2078 generate_field_log(out, &kfield, log_str,
"");
2080 log_str <<
".write(' : ')" << endl;
2081 t_field vfield(((
t_map*)ttype)->get_val_type(), viter);
2082 generate_field_log(out, &vfield, log_str,
"");
2085 log_str <<
".write(' }')" << endl;
2086 }
else if (ttype->
is_set()) {
2087 string iter =
tmp(
"iter");
2089 log_str <<
".write('( ')" << endl;
2091 "for " << iter <<
" in " << prefix <<
":" << endl;
2093 t_field efield(((
t_set*)ttype)->get_elem_type(), iter);
2094 generate_field_log(out, &efield, log_str,
"");
2096 log_str <<
".write(', ')" << endl;
2099 log_str <<
".write(' )')" << endl;
2100 }
else if (ttype->
is_list()) {
2101 string iter =
tmp(
"iter");
2103 log_str <<
".write('[ ')" << endl;
2105 "for " << iter <<
" in " << prefix <<
":" << endl;
2108 generate_field_log(out, &efield, log_str,
"");
2110 log_str <<
".write(', ')" << endl;
2113 log_str <<
".write(' ]')" << endl;
2117 void t_py_generator::generate_field_log(ofstream& out,
2123 if (
type->is_struct() ||
type->is_xception()) {
2124 generate_struct_log(out, prefix + tfield->
get_name(), log_str);
2125 }
else if (
type->is_container()) {
2126 generate_container_log(out, prefix + tfield->
get_name(),
type, log_str);
2127 }
else if (
type->is_base_type() ||
type->is_enum()) {
2128 string name = prefix + tfield->
get_name();
2129 if (
type->is_base_type()) {
2135 case t_base_type::TYPE_STATIC_CONST_STRING:
2136 case t_base_type::TYPE_XML:
2138 log_str <<
".write(" << name <<
")" << endl;
2142 "if " << name <<
":" << endl;
2145 log_str <<
".write('True')" << endl;
2151 log_str <<
".write('False')" << endl;
2156 log_str <<
".write(hex(" << name <<
"))" << endl;
2160 log_str <<
".write(str(" << name <<
"))" << endl;
2164 log_str <<
".write(str(" << name <<
"))" << endl;
2168 log_str <<
".write(str(" << name <<
"))" << endl;
2170 case t_base_type::TYPE_U16:
2172 log_str <<
".write(str(" << name <<
"))" << endl;
2174 case t_base_type::TYPE_U32:
2176 log_str <<
".write(str(" << name <<
"))" << endl;
2178 case t_base_type::TYPE_U64:
2180 log_str <<
".write(str(" << name <<
"))" << endl;
2184 log_str <<
".write(str(" << name <<
"))" << endl;
2186 case t_base_type::TYPE_IPV4:
2187 indent(out) <<
"import socket, struct" << endl;
2189 log_str <<
".write(socket.inet_ntoa(struct.pack('!L'," << name <<
")))" << endl;
2191 case t_base_type::TYPE_IPADDR:
2193 log_str <<
".write(str(" << name <<
"))" << endl;
2195 case t_base_type::TYPE_UUID:
2197 log_str <<
".write(str(" << name <<
"))" << endl;
2202 }
else if (
type->is_enum()) {
2204 log_str <<
".write(str(" << name <<
"))" << endl;
2207 printf(
"DO NOT KNOW HOW TO GENERATE LOG FOR FIELD '%s' TYPE '%s'\n",
2209 type->get_name().c_str());
2213 void t_py_generator::generate_py_sandesh_logger(ofstream &out,
2215 const vector<t_field*>& fields = tsandesh->
get_members();
2216 vector<t_field*>::const_iterator f_iter;
2219 std::string log_str =
"log_str";
2221 "def log(self, trace=False):" << endl;
2224 log_str <<
" = StringIO()" << endl;
2226 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
2229 indent(out) <<
"if trace:" << endl;
2231 indent(out) << log_str <<
".write(str(self._timestamp))" << endl;
2232 indent(out) << log_str <<
".write(' ')" << endl;
2235 if (sandesh_type->is_sandesh_system() ||
2236 sandesh_type->is_sandesh_object() ||
2237 sandesh_type->is_sandesh_flow()) {
2239 "if self._category is not None:" << endl;
2241 indent(out) << log_str <<
".write(self._category)" << endl;
2243 indent(out) << log_str <<
".write(' [')" << endl;
2244 indent(out) << log_str <<
".write(SandeshLevel._VALUES_TO_NAMES["
2245 <<
"self._level])" << endl;
2246 indent(out) << log_str <<
".write(']: ')" << endl;
2248 indent(out) << log_str <<
".write(self.__class__.__name__ + " <<
2252 "if self." << (*f_iter)->get_name() <<
" is not None:" << endl;
2254 if (sandesh_type->is_sandesh_system() ||
2255 sandesh_type->is_sandesh_trace()) {
2256 generate_field_log(out, *f_iter, log_str,
"self.");
2257 indent(out) << log_str <<
".write(' ')" << endl;
2259 indent(out) << log_str <<
2260 ".write('" << (*f_iter)->get_name() <<
" = ')"<< endl;
2261 generate_field_log(out, *f_iter, log_str,
"self.");
2262 indent(out) << log_str <<
".write(' ')" << endl;
2267 "return log_str.getvalue()" << endl << endl;
2271 void t_py_generator::generate_py_struct_logger(ofstream &out,
2273 const vector<t_field*>& fields = tstruct->
get_members();
2274 vector<t_field*>::const_iterator f_iter;
2276 std::string log_str =
"log_str";
2278 "def log(self):" << endl;
2281 log_str <<
" = StringIO()" << endl;
2283 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
2285 "if self." << (*f_iter)->get_name() <<
" is not None:" << endl;
2288 bool write_fname =
true;
2289 if (
type->is_base_type()) {
2291 if (tbase == t_base_type::TYPE_STATIC_CONST_STRING) {
2292 write_fname =
false;
2297 log_str <<
".write('" << (*f_iter)->get_name() <<
" = ')"<< endl;
2299 generate_field_log(out, *f_iter, log_str,
"self.");
2301 log_str <<
".write(' ')" << endl;
2305 "return log_str.getvalue()" << endl << endl;
2309 void t_py_generator::generate_py_sizeof(std::ofstream& out,
2310 const vector<t_field*>& fields) {
2311 indent(out) <<
"def __sizeof__(self):" << endl;
2313 indent(out) <<
"size = 0" << endl;
2314 vector<t_field*>::const_iterator f_iter;
2315 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
2316 std::string fname((*f_iter)->get_name());
2317 indent(out) <<
"if self." << fname <<
" is not None:" << endl;
2319 indent(out) <<
"size += getsizeof(self." << fname <<
")" << endl;
2321 if (
type->is_container()) {
2322 if (
type->is_map()) {
2324 "size += sum(map(getsizeof, chain.from_iterable(iter(self." <<
2325 fname <<
".items()))))" << endl;
2329 "size += sum(map(getsizeof, self." << fname <<
"))" << endl;
2334 indent(out) <<
"return size" << endl << endl;
2338 void t_py_generator::generate_py_struct_sizeof(std::ofstream& out,
2340 const vector<t_field*>& fields = tstruct->
get_members();
2341 generate_py_sizeof(out, fields);
2344 void t_py_generator::generate_py_sandesh_sizeof(std::ofstream& out,
2346 const vector<t_field*>& fields = tsandesh->
get_members();
2347 generate_py_sizeof(out, fields);
2350 void t_py_generator::generate_py_sandesh_hint(ofstream& out,
2353 string shints =
"0";
2355 if (has_key_annotation) {
2356 shints +=
" | SANDESH_KEY_HINT";
2359 indent(out) <<
"self._hints = " << shints << endl;
2362 void t_py_generator::generate_py_sandesh_trace(std::ofstream& out,
2366 void t_py_generator::generate_py_sandesh_async(std::ofstream& out,
2370 void t_py_generator::generate_py_sandesh_request(std::ofstream& out,
2373 generate_py_sandesh_http_request_handler(out, tsandesh);
2375 sandesh_req_list_.push_back(tsandesh->
get_name());
2377 generate_py_sandesh_http_request_list(f_http_request_, tsandesh);
2379 generate_py_sandesh_skeleton_request(f_request_impl_, tsandesh);
2382 void t_py_generator::generate_py_sandesh_response(std::ofstream& out,
2386 void t_py_generator::generate_py_sandesh_uve(std::ofstream& out,
2389 const vector<t_field*>& fields = tsandesh->
get_members();
2390 vector<t_field*>::const_iterator f_iter = fields.begin();
2391 assert((*f_iter)->get_name() ==
"data");
2395 out <<
indent() <<
"def update_uve(self, tdata):" << endl;
2398 const vector<t_field*>& sfields = ts->
get_members();
2399 vector<t_field*>::const_iterator s_iter;
2401 for (s_iter = sfields.begin(); s_iter != sfields.end(); ++s_iter) {
2402 out <<
indent() <<
"if self.data." << (*s_iter)->get_name() <<
" is not None:" << endl;
2404 out <<
indent() <<
"tdata." << (*s_iter)->get_name() <<
" = self.data." <<
2405 (*s_iter)->get_name() << endl;
2408 out <<
indent() <<
"return tdata" << endl;
2410 assert(f_iter == fields.end());
2416 if (sandesh_type->is_sandesh_uve() || sandesh_type->is_sandesh_dynamic_uve()) {
2418 sandesh_uve_list_.push_back(boost::make_tuple(tsandesh->
get_name(),
2420 }
else if (sandesh_type->is_sandesh_alarm()) {
2422 sandesh_alarm_list_.push_back(boost::make_tuple(tsandesh->
get_name(),
2427 void t_py_generator::generate_py_sandesh_uve_list(ofstream& out) {
2428 out << endl << endl;
2429 out <<
"_SANDESH_UVE_LIST = [" << endl;
2430 std::vector<boost::tuple<std::string, std::string> >::const_iterator it;
2431 for (it = sandesh_uve_list_.begin(); it != sandesh_uve_list_.end(); ++it) {
2432 indent(out) <<
"(" << it->get<0>() <<
", " << it->get<1>() <<
")," << endl;
2437 void t_py_generator::generate_py_sandesh_alarm_list(ofstream& out) {
2438 out << endl << endl;
2439 out <<
"_SANDESH_ALARM_LIST = [" << endl;
2440 std::vector<boost::tuple<std::string, std::string> >::const_iterator it;
2441 for (it = sandesh_alarm_list_.begin(); it != sandesh_alarm_list_.end();
2443 indent(out) <<
"(" << it->get<0>() <<
", " << it->get<1>() <<
")," << endl;
2469 "from .ttypes import *" << endl <<
2470 "from thrift.Thrift import TProcessor" << endl <<
2475 "from zope.interface import Interface, implements" << endl <<
2476 "from twisted.internet import defer" << endl <<
2477 "from thrift.transport import TTwisted" << endl;
2500 vector<t_function*>::iterator f_iter;
2503 "# HELPER FUNCTIONS AND STRUCTURES" << endl;
2505 for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
2506 t_struct* ts = (*f_iter)->get_arglist();
2526 const vector<t_field*>& fields = xs->
get_members();
2527 vector<t_field*>::const_iterator f_iter;
2528 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
2541 string extends =
"";
2542 string extends_if =
"";
2545 extends_if =
"(" + extends +
".Iface)";
2548 extends_if =
"(Interface)";
2550 extends_if =
"(object)";
2555 "class Iface" << extends_if <<
":" << endl;
2559 if (functions.empty()) {
2561 indent() <<
"pass" << endl;
2563 vector<t_function*>::iterator f_iter;
2564 for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
2570 indent() <<
"pass" << endl << endl;
2586 string extends =
"";
2587 string extends_client =
"";
2591 extends_client =
"(" + extends +
".Client)";
2593 extends_client = extends +
".Client, ";
2597 extends_client =
"(object)";
2603 "class Client" << extends_client <<
":" << endl <<
2604 " implements(Iface)" << endl << endl;
2607 "class Client(" << extends_client <<
"Iface):" << endl;
2615 indent() <<
"def __init__(self, transport, oprot_factory):" << endl;
2618 indent() <<
"def __init__(self, iprot, oprot=None):" << endl;
2620 if (extends.empty()) {
2623 indent() <<
" self._transport = transport" << endl <<
2624 indent() <<
" self._oprot_factory = oprot_factory" << endl <<
2625 indent() <<
" self._seqid = 0" << endl <<
2626 indent() <<
" self._reqs = {}" << endl <<
2630 indent() <<
" self._iprot = self._oprot = iprot" << endl <<
2631 indent() <<
" if oprot is not None:" << endl <<
2632 indent() <<
" self._oprot = oprot" << endl <<
2633 indent() <<
" self._seqid = 0" << endl <<
2639 indent() <<
" " << extends <<
".Client.__init__(self, transport, oprot_factory)" << endl <<
2643 indent() <<
" " << extends <<
".Client.__init__(self, iprot, oprot)" << endl <<
2650 vector<t_function*>::const_iterator f_iter;
2651 for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
2652 t_struct* arg_struct = (*f_iter)->get_arglist();
2653 const vector<t_field*>& fields = arg_struct->
get_members();
2654 vector<t_field*>::const_iterator fld_iter;
2655 string funname = (*f_iter)->get_name();
2664 if (!(*f_iter)->is_oneway()) {
2666 "d = self._reqs[self._seqid] = defer.Deferred()" << endl;
2671 "self.send_" << funname <<
"(";
2674 for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) {
2684 if (!(*f_iter)->is_oneway()) {
2689 if (!(*f_iter)->get_returntype()->is_void()) {
2693 "self.recv_" << funname <<
"()" << endl;
2698 indent() <<
"return defer.succeed(None)" << endl;
2709 std::string argsname = (*f_iter)->get_name() +
"_args";
2714 indent() <<
"oprot = self._oprot_factory.getProtocol(self._transport)" << endl <<
2716 "oprot.writeMessageBegin('" << (*f_iter)->get_name() <<
"', TMessageType.CALL, self._seqid)"
2720 indent() <<
"self._oprot.writeMessageBegin('" << (*f_iter)->get_name() <<
"', TMessageType.CALL, self._seqid)" << endl;
2724 indent() <<
"args = " << argsname <<
"()" << endl;
2726 for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) {
2728 indent() <<
"args." << (*fld_iter)->get_name() <<
" = " << (*fld_iter)->get_name() << endl;
2734 indent() <<
"args.write(oprot)" << endl <<
2735 indent() <<
"oprot.writeMessageEnd()" << endl <<
2736 indent() <<
"oprot.trans.flush()" << endl;
2739 indent() <<
"args.write(self._oprot)" << endl <<
2740 indent() <<
"self._oprot.writeMessageEnd()" << endl <<
2741 indent() <<
"self._oprot.trans.flush()" << endl;
2746 if (!(*f_iter)->is_oneway()) {
2747 std::string resultname = (*f_iter)->get_name() +
"_result";
2753 indent() <<
"def recv_" << (*f_iter)->get_name() <<
2754 "(self, iprot, mtype, rseqid):" << endl;
2757 t_function recv_function((*f_iter)->get_returntype(),
2758 string(
"recv_") + (*f_iter)->get_name(),
2769 indent() <<
"d = self._reqs.pop(rseqid)" << endl;
2772 indent() <<
"(fname, mtype, rseqid) = self._iprot.readMessageBegin()" << endl;
2776 indent() <<
"if mtype == TMessageType.EXCEPTION:" << endl <<
2777 indent() <<
" x = TApplicationException()" << endl;
2781 indent() <<
" x.read(iprot)" << endl <<
2782 indent() <<
" iprot.readMessageEnd()" << endl <<
2783 indent() <<
" return d.errback(x)" << endl <<
2784 indent() <<
"result = " << resultname <<
"()" << endl <<
2785 indent() <<
"result.read(iprot)" << endl <<
2786 indent() <<
"iprot.readMessageEnd()" << endl;
2789 indent() <<
" x.read(self._iprot)" << endl <<
2790 indent() <<
" self._iprot.readMessageEnd()" << endl <<
2791 indent() <<
" raise x" << endl <<
2792 indent() <<
"result = " << resultname <<
"()" << endl <<
2793 indent() <<
"result.read(self._iprot)" << endl <<
2794 indent() <<
"self._iprot.readMessageEnd()" << endl;
2798 if (!(*f_iter)->get_returntype()->is_void()) {
2800 indent() <<
"if result.success is not None:" << endl;
2803 indent() <<
" return d.callback(result.success)" << endl;
2806 indent() <<
" return result.success" << endl;
2810 t_struct* xs = (*f_iter)->get_xceptions();
2811 const std::vector<t_field*>& xceptions = xs->
get_members();
2812 vector<t_field*>::const_iterator x_iter;
2813 for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
2815 indent() <<
"if result." << (*x_iter)->get_name() <<
" is not None:" << endl;
2818 indent() <<
" return d.errback(result." << (*x_iter)->get_name() <<
")" << endl;
2822 indent() <<
" raise result." << (*x_iter)->get_name() <<
"" << endl;
2827 if ((*f_iter)->get_returntype()->is_void()) {
2830 "return d.callback(None)" << endl;
2838 indent() <<
"return d.errback(TApplicationException(TApplicationException.MISSING_RESULT, \"" << (*f_iter)->get_name() <<
" failed: unknown result\"))" << endl;
2841 indent() <<
"raise TApplicationException(TApplicationException.MISSING_RESULT, \"" << (*f_iter)->get_name() <<
" failed: unknown result\");" << endl;
2863 vector<t_function*>::iterator f_iter;
2867 f_remote.open(f_remote_name.c_str());
2870 "#!/usr/bin/env python" << endl <<
2872 "import sys" << endl <<
2873 "import pprint" << endl <<
2874 "from urlparse import urlparse" << endl <<
2875 "from thrift.transport import TTransport" << endl <<
2876 "from thrift.transport import TSocket" << endl <<
2877 "from thrift.transport import THttpClient" << endl <<
2878 "from thrift.protocol import TBinaryProtocol" << endl <<
2883 "from .ttypes import *" << endl <<
2887 "if len(sys.argv) <= 1 or sys.argv[1] == '--help':" << endl <<
2888 " print ''" << endl <<
2889 " print 'Usage: ' + sys.argv[0] + ' [-h host[:port]] [-u url] [-f[ramed]] function [arg1 [arg2...]]'" << endl <<
2890 " print ''" << endl <<
2891 " print 'Functions:'" << endl;
2892 for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
2894 " print ' " << (*f_iter)->get_returntype()->get_name() <<
" " << (*f_iter)->get_name() <<
"(";
2895 t_struct* arg_struct = (*f_iter)->get_arglist();
2896 const std::vector<t_field*>& args = arg_struct->
get_members();
2897 vector<t_field*>::const_iterator a_iter;
2898 int num_args = args.size();
2900 for (
int i = 0; i < num_args; ++i) {
2907 args[i]->get_type()->get_name() <<
" " << args[i]->get_name();
2909 f_remote <<
")'" << endl;
2912 " print ''" << endl <<
2913 " sys.exit(0)" << endl <<
2917 "pp = pprint.PrettyPrinter(indent = 2)" << endl <<
2918 "host = 'localhost'" << endl <<
2919 "port = 9090" << endl <<
2920 "uri = ''" << endl <<
2921 "framed = False" << endl <<
2922 "http = False" << endl <<
2923 "argi = 1" << endl <<
2925 "if sys.argv[argi] == '-h':" << endl <<
2926 " parts = sys.argv[argi+1].split(':')" << endl <<
2927 " host = parts[0]" << endl <<
2928 " if len(parts) > 1:" << endl <<
2929 " port = int(parts[1])" << endl <<
2930 " argi += 2" << endl <<
2932 "if sys.argv[argi] == '-u':" << endl <<
2933 " url = urlparse(sys.argv[argi+1])" << endl <<
2934 " parts = url[1].split(':')" << endl <<
2935 " host = parts[0]" << endl <<
2936 " if len(parts) > 1:" << endl <<
2937 " port = int(parts[1])" << endl <<
2939 " port = 80" << endl <<
2940 " uri = url[2]" << endl <<
2941 " if url[4]:" << endl <<
2942 " uri += '?%s' % url[4]" << endl <<
2943 " http = True" << endl <<
2944 " argi += 2" << endl <<
2946 "if sys.argv[argi] == '-f' or sys.argv[argi] == '-framed':" << endl <<
2947 " framed = True" << endl <<
2948 " argi += 1" << endl <<
2950 "cmd = sys.argv[argi]" << endl <<
2951 "args = sys.argv[argi+1:]" << endl <<
2953 "if http:" << endl <<
2954 " transport = THttpClient.THttpClient(host, port, uri)" << endl <<
2956 " socket = TSocket.TSocket(host, port)" << endl <<
2957 " if framed:" << endl <<
2958 " transport = TTransport.TFramedTransport(socket)" << endl <<
2960 " transport = TTransport.TBufferedTransport(socket)" << endl <<
2961 "protocol = TBinaryProtocol.TBinaryProtocol(transport)" << endl <<
2962 "client = " <<
service_name_ <<
".Client(protocol)" << endl <<
2963 "transport.open()" << endl <<
2969 for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
2976 t_struct* arg_struct = (*f_iter)->get_arglist();
2977 const std::vector<t_field*>& args = arg_struct->
get_members();
2978 vector<t_field*>::const_iterator a_iter;
2979 int num_args = args.size();
2982 "if cmd == '" << (*f_iter)->get_name() <<
"':" << endl <<
2983 " if len(args) != " << num_args <<
":" << endl <<
2984 " print '" << (*f_iter)->get_name() <<
" requires " << num_args <<
" args'" << endl <<
2985 " sys.exit(1)" << endl <<
2986 " pp.pprint(client." << (*f_iter)->get_name() <<
"(";
2987 for (
int i = 0; i < num_args; ++i) {
2988 if (args[i]->get_type()->is_string()) {
2989 f_remote <<
"args[" << i <<
"],";
2991 f_remote <<
"eval(args[" << i <<
"]),";
2994 f_remote <<
"))" << endl;
2998 f_remote <<
"else:" << endl;
2999 f_remote <<
" print 'Unrecognized method %s' % cmd" << endl;
3000 f_remote <<
" sys.exit(1)" << endl;
3003 f_remote <<
"transport.close()" << endl;
3011 chmod(f_remote_name.c_str(),
3034 vector<t_function*>::iterator f_iter;
3036 string extends =
"";
3037 string extends_processor =
"";
3040 extends_processor = extends +
".Processor, ";
3046 "class Processor(" << extends_processor <<
"TProcessor):" << endl <<
3047 " implements(Iface)" << endl << endl;
3050 "class Processor(" << extends_processor <<
"Iface, TProcessor):" << endl;
3056 "def __init__(self, handler):" << endl;
3058 if (extends.empty()) {
3061 indent() <<
"self._handler = Iface(handler)" << endl;
3064 indent() <<
"self._handler = handler" << endl;
3068 indent() <<
"self._processMap = {}" << endl;
3072 indent() << extends <<
".Processor.__init__(self, Iface(handler))" << endl;
3075 indent() << extends <<
".Processor.__init__(self, handler)" << endl;
3078 for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
3080 indent() <<
"self._processMap[\"" << (*f_iter)->get_name() <<
"\"] = Processor.process_" << (*f_iter)->get_name() << endl;
3087 "def process(self, iprot, oprot):" << endl;
3091 indent() <<
"(name, type, seqid) = iprot.readMessageBegin()" << endl;
3097 indent() <<
"if name not in self._processMap:" << endl <<
3098 indent() <<
" iprot.skip(TType.STRUCT)" << endl <<
3099 indent() <<
" iprot.readMessageEnd()" << endl <<
3100 indent() <<
" x = TApplicationException(TApplicationException.UNKNOWN_METHOD, 'Unknown function %s' % (name))" << endl <<
3101 indent() <<
" oprot.writeMessageBegin(name, TMessageType.EXCEPTION, seqid)" << endl <<
3102 indent() <<
" x.write(oprot)" << endl <<
3103 indent() <<
" oprot.writeMessageEnd()" << endl <<
3104 indent() <<
" oprot.trans.flush()" << endl;
3108 indent() <<
" return defer.succeed(None)" << endl;
3111 indent() <<
" return" << endl;
3115 indent() <<
"else:" << endl;
3119 indent() <<
" return self._processMap[name](self, seqid, iprot, oprot)" << endl;
3122 indent() <<
" self._processMap[name](self, seqid, iprot, oprot)" << endl;
3126 indent() <<
"return True" << endl;
3133 for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
3151 "def process_" << tfunction->
get_name() <<
3152 "(self, seqid, iprot, oprot):" << endl;
3155 string argsname = tfunction->
get_name() +
"_args";
3156 string resultname = tfunction->
get_name() +
"_result";
3159 indent() <<
"args = " << argsname <<
"()" << endl <<
3160 indent() <<
"args.read(iprot)" << endl <<
3161 indent() <<
"iprot.readMessageEnd()" << endl;
3164 const std::vector<t_field*>& xceptions = xs->
get_members();
3165 vector<t_field*>::const_iterator x_iter;
3170 indent() <<
"result = " << resultname <<
"()" << endl;
3176 const std::vector<t_field*>& fields = arg_struct->
get_members();
3177 vector<t_field*>::const_iterator f_iter;
3180 indent() <<
"d = defer.maybeDeferred(self._handler." <<
3183 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
3189 f_service_ <<
"args." << (*f_iter)->get_name();
3196 indent() <<
"return d" << endl;
3204 "d.addCallback(self.write_results_success_" <<
3205 tfunction->
get_name() <<
", result, seqid, oprot)" << endl;
3207 if (xceptions.size() > 0) {
3210 "d.addErrback(self.write_results_exception_" <<
3211 tfunction->
get_name() <<
", result, seqid, oprot)" << endl;
3215 indent() <<
"return d" << endl;
3221 "def write_results_success_" << tfunction->
get_name() <<
3222 "(self, success, result, seqid, oprot):" << endl;
3225 indent() <<
"result.success = success" << endl <<
3226 indent() <<
"oprot.writeMessageBegin(\"" << tfunction->
get_name() <<
3227 "\", TMessageType.REPLY, seqid)" << endl <<
3228 indent() <<
"result.write(oprot)" << endl <<
3229 indent() <<
"oprot.writeMessageEnd()" << endl <<
3230 indent() <<
"oprot.trans.flush()" << endl;
3235 if (!tfunction->
is_oneway() && xceptions.size() > 0) {
3237 "def write_results_exception_" << tfunction->
get_name() <<
3238 "(self, error, result, seqid, oprot):" << endl;
3241 indent() <<
"try:" << endl;
3245 indent() <<
" error.raiseException()" << endl;
3246 for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
3248 indent() <<
"except " <<
type_name((*x_iter)->get_type()) <<
", " << (*x_iter)->get_name() <<
":" << endl;
3252 indent() <<
"result." << (*x_iter)->get_name() <<
" = " << (*x_iter)->get_name() << endl;
3256 indent() <<
"pass" << endl;
3260 indent() <<
"oprot.writeMessageBegin(\"" << tfunction->
get_name() <<
3261 "\", TMessageType.REPLY, seqid)" << endl <<
3262 indent() <<
"result.write(oprot)" << endl <<
3263 indent() <<
"oprot.writeMessageEnd()" << endl <<
3264 indent() <<
"oprot.trans.flush()" << endl;
3271 if (xceptions.size() > 0) {
3273 indent() <<
"try:" << endl;
3279 const std::vector<t_field*>& fields = arg_struct->
get_members();
3280 vector<t_field*>::const_iterator f_iter;
3287 "self._handler." << tfunction->
get_name() <<
"(";
3289 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
3295 f_service_ <<
"args." << (*f_iter)->get_name();
3299 if (!tfunction->
is_oneway() && xceptions.size() > 0) {
3301 for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
3303 indent() <<
"except " <<
type_name((*x_iter)->get_type()) <<
", " << (*x_iter)->get_name() <<
":" << endl;
3307 indent() <<
"result." << (*x_iter)->get_name() <<
" = " << (*x_iter)->get_name() << endl;
3311 indent() <<
"pass" << endl;
3319 indent() <<
"return" << endl;
3326 indent() <<
"oprot.writeMessageBegin(\"" << tfunction->
get_name() <<
"\", TMessageType.REPLY, seqid)" << endl <<
3327 indent() <<
"result.write(oprot)" << endl <<
3328 indent() <<
"oprot.writeMessageEnd()" << endl <<
3329 indent() <<
"oprot.trans.flush()" << endl;
3347 if (
type->is_void()) {
3348 throw "CANNOT GENERATE DESERIALIZE CODE FOR void TYPE: " +
3352 string name = prefix + tfield->
get_name();
3354 if (
type->is_struct() ||
type->is_xception()) {
3358 }
else if (
type->is_container()) {
3360 }
else if (
type->is_base_type() ||
type->is_enum()) {
3363 "(length, " << name <<
") = iprot.";
3365 name <<
" = iprot.";
3367 if (
type->is_base_type()) {
3371 throw "compiler error: cannot serialize void field in a struct: " +
3376 case t_base_type::TYPE_STATIC_CONST_STRING:
3379 out <<
"readString();";
3381 out <<
"readString().decode('utf-8')";
3385 case t_base_type::TYPE_XML:
3386 out <<
"readXML();";
3388 case t_base_type::TYPE_UUID:
3389 out <<
"readUUID();";
3393 out <<
"readBool();";
3396 out <<
"readByte();";
3399 out <<
"readI16();";
3402 out <<
"readI32();";
3405 out <<
"readI64();";
3408 case t_base_type::TYPE_U16:
3409 out <<
"readU16();";
3411 case t_base_type::TYPE_U32:
3412 out <<
"readU32();";
3414 case t_base_type::TYPE_U64:
3415 out <<
"readU64();";
3417 case t_base_type::TYPE_IPV4:
3418 out <<
"readIPV4();";
3420 case t_base_type::TYPE_IPADDR:
3421 out <<
"readIPADDR()";
3425 out <<
"readDouble();";
3430 }
else if (
type->is_enum()) {
3431 out <<
"readI32();";
3435 indent(out) <<
"if length < 0: return -1" << endl;
3436 indent(out) <<
"read_cnt += length" << endl;
3439 printf(
"DO NOT KNOW HOW TO DESERIALIZE FIELD '%s' TYPE '%s'\n",
3453 indent() <<
"read_cnt += " << prefix <<
".read(iprot)" << endl;
3455 indent() << prefix <<
".read(iprot)" << endl;
3466 string size =
tmp(
"_size");
3467 string ktype =
tmp(
"_ktype");
3468 string vtype =
tmp(
"_vtype");
3469 string etype =
tmp(
"_etype");
3479 indent() << prefix <<
" = {}" << endl <<
3481 indent() <<
"(length, " << ktype <<
", " << vtype <<
", " << size <<
" ) = iprot.readMapBegin() " << endl <<
3482 indent() <<
"read_cnt += length" << endl;
3484 indent() <<
"(" << ktype <<
", " << vtype <<
", " << size <<
" ) = iprot.readMapBegin() " << endl;
3486 }
else if (ttype->
is_set()) {
3488 indent() << prefix <<
" = set()" << endl <<
3490 indent() <<
"(length, " << etype <<
", " << size <<
") = iprot.readSetBegin()" << endl <<
3491 indent() <<
"read_cnt += length" << endl;
3493 indent() <<
"(" << etype <<
", " << size <<
") = iprot.readSetBegin()" << endl;
3495 }
else if (ttype->
is_list()) {
3497 indent() << prefix <<
" = []" << endl <<
3499 indent() <<
"(length, " << etype <<
", " << size <<
") = iprot.readListBegin()" << endl <<
3500 indent() <<
"read_cnt += length" << endl;
3502 indent() <<
"(" << etype <<
", " << size <<
") = iprot.readListBegin()" << endl;
3507 string i =
tmp(
"_i");
3509 "for " << i <<
" in range(" << size <<
"):" << endl;
3515 }
else if (ttype->
is_set()) {
3519 indent(out) <<
"read_cnt += iprot.readContainerElementBegin()" << endl;
3525 indent(out) <<
"read_cnt += iprot.readContainerElementEnd()" << endl;
3528 }
else if (ttype->
is_list()) {
3532 indent(out) <<
"read_cnt += iprot.readContainerElementBegin()" << endl;
3538 indent(out) <<
"read_cnt += iprot.readContainerElementEnd()" << endl;
3548 indent(out) <<
"read_cnt += iprot.readMapEnd()" << endl;
3550 indent(out) <<
"iprot.readMapEnd()" << endl;
3552 }
else if (ttype->
is_set()) {
3554 indent(out) <<
"read_cnt += iprot.readSetEnd()" << endl;
3556 indent(out) <<
"iprot.readSetEnd()" << endl;
3558 }
else if (ttype->
is_list()) {
3560 indent(out) <<
"read_cnt += iprot.readListEnd()" << endl;
3562 indent(out) <<
"iprot.readListEnd()" << endl;
3574 string key =
tmp(
"_key");
3575 string val =
tmp(
"_val");
3582 indent(out) <<
"read_cnt += iprot.readContainerElementBegin()" << endl;
3588 indent(out) <<
"read_cnt += iprot.readContainerElementEnd()" << endl;
3595 indent(out) <<
"read_cnt += iprot.readContainerElementBegin()" << endl;
3601 indent(out) <<
"read_cnt += iprot.readContainerElementEnd()" << endl;
3606 prefix <<
"[" << key <<
"] = " << val << endl;
3615 string elem =
tmp(
"_elem");
3621 prefix <<
".add(" << elem <<
")" << endl;
3630 string elem =
tmp(
"_elem");
3636 prefix <<
".append(" << elem <<
")" << endl;
3652 if (
type->is_void()) {
3653 throw "CANNOT GENERATE SERIALIZE CODE FOR void TYPE: " +
3657 if (
type->is_struct() ||
type->is_xception()) {
3661 }
else if (
type->is_container()) {
3665 }
else if (
type->is_base_type() ||
type->is_enum()) {
3667 string name = prefix + tfield->
get_name();
3672 if (
type->is_base_type()) {
3677 "compiler error: cannot serialize void field in a struct: " + name;
3681 case t_base_type::TYPE_STATIC_CONST_STRING:
3684 out <<
"writeString(" << name <<
")";
3686 out <<
"writeString(" << name <<
".encode('utf-8'))";
3690 case t_base_type::TYPE_XML:
3691 out <<
"writeXML(" << name <<
")";
3693 case t_base_type::TYPE_UUID:
3694 out <<
"writeUUID(" << name <<
")";
3698 out <<
"writeBool(" << name <<
")";
3701 out <<
"writeByte(" << name <<
")";
3704 out <<
"writeI16(" << name <<
")";
3707 out <<
"writeI32(" << name <<
")";
3710 out <<
"writeI64(" << name <<
")";
3713 case t_base_type::TYPE_U16:
3714 out <<
"writeU16(" << name <<
")";
3716 case t_base_type::TYPE_U32:
3717 out <<
"writeU32(" << name <<
")";
3719 case t_base_type::TYPE_U64:
3720 out <<
"writeU64(" << name <<
")";
3722 case t_base_type::TYPE_IPV4:
3723 out <<
"writeIPV4(" << name <<
")";
3725 case t_base_type::TYPE_IPADDR:
3726 out <<
"writeIPADDR(" << name <<
")";
3730 out <<
"writeDouble(" << name <<
")";
3735 }
else if (
type->is_enum()) {
3736 out <<
"writeI32(" << name <<
")";
3738 out <<
" < 0: return -1" << endl;
3740 }
else if (
type->is_sandesh()) {
3745 printf(
"DO NOT KNOW HOW TO SERIALIZE FIELD '%s%s' TYPE '%s'\n",
3748 type->get_name().c_str());
3763 "if " << prefix <<
".write(oprot) < 0: return -1" << endl;
3773 void t_py_generator::generate_serialize_sandesh(ofstream &out,
3778 "if " << prefix <<
".write(oprot) < 0: return -1" << endl;
3787 "if oprot.writeMapBegin(" <<
3790 "len(" << prefix <<
")) < 0: return -1" << endl;
3791 }
else if (ttype->
is_set()) {
3793 "if oprot.writeSetBegin(" <<
3795 "len(" << prefix <<
")) < 0: return -1" << endl;
3796 }
else if (ttype->
is_list()) {
3798 "if oprot.writeListBegin(" <<
3800 "len(" << prefix <<
")) < 0: return -1" << endl;
3804 string kiter =
tmp(
"kiter");
3805 string viter =
tmp(
"viter");
3807 "for " << kiter <<
"," << viter <<
" in " << prefix <<
".items():" << endl;
3811 }
else if (ttype->
is_set()) {
3812 string iter =
tmp(
"iter");
3814 "for " << iter <<
" in " << prefix <<
":" << endl;
3819 indent(out) <<
"if oprot.writeContainerElementBegin() < 0: return -1" << endl;
3825 indent(out) <<
"if oprot.writeContainerElementEnd() < 0: return -1" << endl;
3829 }
else if (ttype->
is_list()) {
3830 string iter =
tmp(
"iter");
3832 "for " << iter <<
" in " << prefix <<
":" << endl;
3837 indent(out) <<
"if oprot.writeContainerElementBegin() < 0: return -1" << endl;
3843 indent(out) <<
"if oprot.writeContainerElementEnd() < 0: return -1" << endl;
3851 "if oprot.writeMapEnd() < 0: return -1" << endl;
3852 }
else if (ttype->
is_set()) {
3854 "if oprot.writeSetEnd() < 0: return -1" << endl;
3855 }
else if (ttype->
is_list()) {
3857 "if oprot.writeListEnd() < 0: return -1" << endl;
3872 indent(out) <<
"if oprot.writeContainerElementBegin() < 0: return -1" << endl;
3879 indent(out) <<
"if oprot.writeContainerElementEnd() < 0: return -1" << endl;
3886 indent(out) <<
"if oprot.writeContainerElementBegin() < 0: return -1" << endl;
3893 indent(out) <<
"if oprot.writeContainerElementEnd() < 0: return -1" << endl;
3940 const char* subheader) {
3941 bool has_doc =
false;
3948 const vector<t_field*>& fields = tstruct->
get_members();
3949 if (fields.size() > 0) {
3954 ss << subheader <<
":\n";
3955 vector<t_field*>::const_iterator p_iter;
3956 for (p_iter = fields.begin(); p_iter != fields.end(); ++p_iter) {
3994 std::ostringstream result;
3995 result << tfield->
get_name() <<
"=";
3997 result <<
"thrift_spec[" <<
4002 return result.str();
4042 string signature = prefix + tfunction->
get_name() +
"(";
4044 signature +=
"self, ";
4057 const vector<t_field*>& fields = tstruct->
get_members();
4058 vector<t_field*>::const_iterator f_iter;
4060 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
4066 result += (*f_iter)->get_name();
4076 if (program != NULL && program !=
program_) {
4088 if (
type->is_base_type()) {
4092 throw "NO T_VOID CONSTRUCT";
4094 return "TType.STRING";
4096 return "TType.BOOL";
4098 return "TType.BYTE";
4106 return "TType.DOUBLE";
4108 case t_base_type::TYPE_XML:
4110 case t_base_type::TYPE_UUID:
4111 return "TType.UUID";
4112 case t_base_type::TYPE_U16:
4114 case t_base_type::TYPE_U32:
4116 case t_base_type::TYPE_U64:
4118 case t_base_type::TYPE_IPV4:
4119 return "TType.IPV4";
4120 case t_base_type::TYPE_IPADDR:
4121 return "TType.IPADDR";
4122 case t_base_type::TYPE_STATIC_CONST_STRING:
4123 return "TType.STRING";
4124 case t_base_type::TYPE_SANDESH_SYSTEM:
4125 return "TType.STRING";
4126 case t_base_type::TYPE_SANDESH_REQUEST:
4127 return "TType.STRING";
4128 case t_base_type::TYPE_SANDESH_RESPONSE:
4129 return "TType.STRING";
4130 case t_base_type::TYPE_SANDESH_TRACE:
4131 return "TType.STRING";
4132 case t_base_type::TYPE_SANDESH_TRACE_OBJECT:
4133 return "TType.STRING";
4134 case t_base_type::TYPE_SANDESH_BUFFER:
4135 return "TTytpe.STRING";
4136 case t_base_type::TYPE_SANDESH_UVE:
4137 return "TTytpe.STRING";
4138 case t_base_type::TYPE_SANDESH_DYNAMIC_UVE:
4139 return "TTytpe.STRING";
4140 case t_base_type::TYPE_SANDESH_ALARM:
4141 return "TTytpe.STRING";
4142 case t_base_type::TYPE_SANDESH_OBJECT:
4143 return "TTytpe.STRING";
4144 case t_base_type::TYPE_SANDESH_FLOW:
4145 return "TTytpe.STRING";
4146 case t_base_type::TYPE_SANDESH_SESSION:
4147 return "TTytpe.STRING";
4150 }
else if (
type->is_enum()) {
4152 }
else if (
type->is_struct() ||
type->is_xception()) {
4153 return "TType.STRUCT";
4155 }
else if (
type->is_sandesh()) {
4156 return "TType.SANDESH";
4158 }
else if (
type->is_map()) {
4160 }
else if (
type->is_set()) {
4162 }
else if (
type->is_list()) {
4163 return "TType.LIST";
4166 throw "INVALID TYPE IN type_to_enum: " +
type->get_name();
4172 ttype = ((
t_typedef*)ttype)->get_type();
4179 }
else if (ttype->
is_map()) {
4187 }
else if (ttype->
is_set()) {
4193 }
else if (ttype->
is_list()) {
4200 throw "INVALID TYPE IN type_to_spec_args: " + ttype->
get_name();
4205 " new_style: Generate new-style classes.\n" \
4206 " twisted: Generate Twisted-friendly RPC services.\n" \
4207 " utf8strings: Encode/decode strings using utf8 in the generated code.\n" \
4208 " slots: Generate code using slots for instance members.\n" \
4209 " dynamic: Generate dynamic code, less code generated but slower.\n" \
4210 " dynbase=CLS Derive generated classes from class CLS instead of TBase.\n" \
4211 " dynexc=CLS Derive generated exceptions from CLS instead of TExceptionBase.\n" \
4212 " dynimport='from foo.bar import CLS'\n" \
4213 " Add an import line to generated code to find the dynbase class.\n")
static std::string t_base_name(t_base tbase)
const std::vector< t_const_value * > & get_list() const
double get_double() const
std::string get_string() const
t_const_value_type get_type() const
const std::map< t_const_value *, t_const_value * > & get_map() const
int64_t get_integer() const
t_type * get_type() const
std::string get_name() const
t_const_value * get_value() const
const std::string & get_doc() const
const std::vector< t_enum_value * > & get_constants()
t_const_value * get_value()
const std::string & get_name() const
t_type * get_type() const
t_type * get_returntype() const
t_struct * get_arglist() const
t_struct * get_xceptions() const
const std::string & get_name() const
std::string tmp(std::string name)
std::string service_name_
void generate_docstring_comment(std::ofstream &out, const std::string &comment_start, const std::string &line_prefix, const std::string &contents, const std::string &comment_end)
static t_type * get_true_type(t_type *type)
t_type * get_elem_type() const
t_type * get_key_type() const
t_type * get_val_type() const
const std::string & get_namespace() const
const std::string & get_name() const
void generate_py_struct(t_struct *tstruct, bool is_exception)
void generate_py_struct_definition(std::ofstream &out, t_struct *tstruct, bool is_xception=false, bool is_result=false)
std::string render_fastbinary_includes()
std::string copy_options_
std::string render_const_value(t_type *type, t_const_value *value)
void generate_enum(t_enum *tenum)
std::string type_to_spec_args(t_type *ttype)
void generate_struct(t_struct *tstruct)
void generate_python_docstring(std::ofstream &out, t_function *tfunction)
void generate_deserialize_map_element(std::ofstream &out, t_map *tmap, std::string prefix="")
std::string gen_dynbaseclass_
std::string py_autogen_comment()
void generate_serialize_set_element(std::ofstream &out, t_set *tmap, std::string iter)
static bool is_valid_namespace(const std::string &sub_namespace)
void generate_serialize_map_element(std::ofstream &out, t_map *tmap, std::string kiter, std::string viter)
void generate_py_struct_writer(std::ofstream &out, t_struct *tstruct)
void generate_deserialize_list_element(std::ofstream &out, t_list *tlist, std::string prefix="")
std::string argument_list(t_struct *tstruct)
std::string future_imports()
void generate_deserialize_container(std::ofstream &out, t_type *ttype, std::string prefix="")
std::string type_to_enum(t_type *ttype)
void generate_py_function_helpers(t_function *tfunction)
void generate_py_struct_required_validator(std::ofstream &out, t_struct *tstruct)
void generate_python_docstring(std::ofstream &out, t_struct *tstruct)
void generate_service_server(t_service *tservice)
void generate_serialize_list_element(std::ofstream &out, t_list *tlist, std::string iter)
void generate_deserialize_struct(std::ofstream &out, t_struct *tstruct, std::string prefix="")
void generate_deserialize_set_element(std::ofstream &out, t_set *tset, std::string prefix="")
void generate_serialize_container(std::ofstream &out, t_type *ttype, std::string prefix="")
void generate_py_struct_reader(std::ofstream &out, t_struct *tstruct)
void generate_python_docstring(std::ofstream &out, t_doc *tdoc, t_struct *tstruct, const char *subheader)
void generate_xception(t_struct *txception)
std::string import_dynbase_
std::string function_signature(t_function *tfunction, std::string prefix="")
std::string type_name(t_type *ttype)
void generate_process_function(t_service *tservice, t_function *tfunction)
void generate_python_docstring(std::ofstream &out, t_doc *tdoc)
void generate_service(t_service *tservice)
std::string function_signature_if(t_function *tfunction, std::string prefix="")
void generate_serialize_field(std::ofstream &out, t_field *tfield, std::string prefix="")
std::string gen_dynbaseclass_exc_
void generate_service_client(t_service *tservice)
void generate_service_interface(t_service *tservice)
void generate_service_remote(t_service *tservice)
void generate_typedef(t_typedef *ttypedef)
void generate_const(t_const *tconst)
void generate_serialize_struct(std::ofstream &out, t_struct *tstruct, std::string prefix="")
static std::string get_real_py_module(const t_program *program, bool gen_twisted)
std::string declare_argument(t_field *tfield)
t_py_generator(t_program *program, const std::map< std::string, std::string > &parsed_options, const std::string &option_string)
std::string render_includes()
void generate_service_helpers(t_service *tservice)
std::string render_field_default_value(t_field *tfield)
void generate_deserialize_field(std::ofstream &out, t_field *tfield, std::string prefix="", bool inclass=false)
virtual bool has_key_annotation() const
const t_type * get_type()
t_service * get_extends()
const std::vector< t_function * > & get_functions() const
t_type * get_elem_type() const
bool append(t_field *elem)
const members_type & get_sorted_members()
const members_type & get_members()
virtual bool is_service() const
const uint32_t get_4byte_fingerprint() const
virtual bool is_set() const
virtual bool is_xception() const
virtual bool is_struct() const
virtual bool is_enum() const
virtual const std::string & get_name() const
t_program * get_program()
virtual bool is_base_type() const
virtual bool is_list() const
virtual bool is_typedef() const
virtual bool is_map() const
virtual bool is_void() const
#define THRIFT_REGISTER_GENERATOR(language, long_name, doc)