27 #include <sys/types.h>
36 #include "boost/tuple/tuple.hpp"
49 const std::map<std::string, std::string>& parsed_options,
50 const std::string& option_string)
54 std::map<std::string, std::string>::const_iterator iter;
56 iter = parsed_options.find(
"new_style");
57 gen_newstyle_ = (iter != parsed_options.end());
59 iter = parsed_options.find(
"slots");
60 gen_slots_ = (iter != parsed_options.end());
62 iter = parsed_options.find(
"dynamic");
63 gen_dynamic_ = (iter != parsed_options.end());
67 gen_dynbaseclass_ =
"TBase";
68 gen_dynbaseclass_exc_ =
"TExceptionBase";
69 import_dynbase_ =
"from thrift.protocol.TBase import TBase, TExceptionBase\n";
72 iter = parsed_options.find(
"dynbase");
73 if (iter != parsed_options.end()) {
75 gen_dynbaseclass_ = (iter->second);
78 iter = parsed_options.find(
"dynexc");
79 if (iter != parsed_options.end()) {
80 gen_dynbaseclass_exc_ = (iter->second);
83 iter = parsed_options.find(
"dynimport");
84 if (iter != parsed_options.end()) {
86 import_dynbase_ = (iter->second);
89 iter = parsed_options.find(
"twisted");
90 gen_twisted_ = (iter != parsed_options.end());
92 iter = parsed_options.find(
"utf8strings");
93 gen_utf8strings_ = (iter != parsed_options.end());
95 copy_options_ = option_string;
98 out_dir_base_ =
"gen-py.twisted";
100 out_dir_base_ =
"gen-py";
108 void init_generator();
109 void close_generator();
115 void generate_typedef (
t_typedef* ttypedef);
116 void generate_enum (
t_enum* tenum);
117 void generate_const (
t_const* tconst);
118 void generate_struct (
t_struct* tstruct);
119 void generate_xception (
t_struct* txception);
120 void generate_service (
t_service* tservice);
122 void generate_sandesh (
t_sandesh* tsandesh);
130 void generate_py_struct(
t_struct* tstruct,
bool is_exception);
131 void generate_py_struct_definition(std::ofstream& out,
t_struct* tstruct,
bool is_xception=
false,
bool is_result=
false);
132 void generate_py_struct_reader(std::ofstream& out,
t_struct* tstruct);
133 void generate_py_struct_writer(std::ofstream& out,
t_struct* tstruct);
134 void generate_py_struct_required_validator(std::ofstream& out,
t_struct* tstruct);
135 void generate_py_function_helpers(
t_function* tfunction);
137 void generate_py_struct_logger(std::ofstream& out,
t_struct* tstruct);
138 void generate_py_struct_sizeof(std::ofstream& out,
t_struct* tstruct);
145 void generate_py_sandesh(
t_sandesh *tsandesh);
146 void generate_py_sandesh_definition(std::ofstream& out,
t_sandesh* tsandesh);
147 void generate_py_sandesh_reader(std::ofstream& out,
t_sandesh* tsandesh);
148 void generate_py_sandesh_writer(std::ofstream& out,
t_sandesh* tsandesh);
149 void generate_py_sandesh_compare(std::ofstream& out,
t_sandesh* tsandesh);
150 void generate_py_sandesh_required_validator(std::ofstream& out,
t_sandesh* tsandesh);
151 void generate_py_sandesh_http_request_handler(std::ofstream& out,
t_sandesh* tsandesh);
152 void generate_py_sandesh_http_attr(ofstream& out,
153 t_type *ftype,
const std::string& namel,
const std::string& namer);
154 void generate_py_sandesh_skeleton_request(std::ofstream& out,
t_sandesh* tsandesh);
155 void generate_py_sandesh_request_list(std::ofstream& out);
156 void generate_py_sandesh_http_request_list(std::ofstream& out,
t_sandesh* tsandesh);
157 void generate_struct_log(std::ofstream& out, std::string prefix, std::string log_str);
158 void generate_container_log(std::ofstream& out, std::string prefix,
t_type* ttype,
string log_str);
159 void generate_field_log(std::ofstream& out,
t_field *tfield, std::string log_str, std::string prefix);
160 void generate_py_sandesh_logger(std::ofstream& out,
t_sandesh* tsandesh);
161 void generate_py_sandesh_hint(std::ofstream& out,
t_sandesh* tsandesh);
162 void generate_py_sandesh_async(std::ofstream& out,
t_sandesh* tsandesh);
163 void generate_py_sandesh_request(std::ofstream& out,
t_sandesh* tsandesh);
164 void generate_py_sandesh_response(std::ofstream& out,
t_sandesh* tsandesh);
165 void generate_py_sandesh_uve(std::ofstream& out,
t_sandesh* tsandesh,
bool update);
166 void generate_py_sandesh_uve_list(std::ofstream& out);
167 void generate_py_sandesh_alarm_list(std::ofstream& out);
168 void generate_py_sandesh_trace(std::ofstream& out,
t_sandesh* tsandesh);
169 void generate_py_sandesh_sizeof(std::ofstream& out,
t_sandesh* tsandesh);
173 void generate_py_sizeof(std::ofstream& out,
const vector<t_field*>& fields);
180 void generate_service_helpers (
t_service* tservice);
181 void generate_service_interface (
t_service* tservice);
182 void generate_service_client (
t_service* tservice);
183 void generate_service_remote (
t_service* tservice);
184 void generate_service_server (
t_service* tservice);
191 void generate_deserialize_field (std::ofstream &out,
193 std::string prefix=
"",
196 void generate_deserialize_struct (std::ofstream &out,
198 std::string prefix=
"");
200 void generate_deserialize_container (std::ofstream &out,
202 std::string prefix=
"");
204 void generate_deserialize_set_element (std::ofstream &out,
206 std::string prefix=
"");
208 void generate_deserialize_map_element (std::ofstream &out,
210 std::string prefix=
"");
212 void generate_deserialize_list_element (std::ofstream &out,
214 std::string prefix=
"");
216 void generate_serialize_field (std::ofstream &out,
218 std::string prefix=
"");
220 void generate_serialize_struct (std::ofstream &out,
222 std::string prefix=
"");
225 void generate_serialize_sandesh (std::ofstream &out,
227 std::string prefix=
"");
230 void generate_serialize_container (std::ofstream &out,
232 std::string prefix=
"");
234 void generate_serialize_map_element (std::ofstream &out,
239 void generate_serialize_set_element (std::ofstream &out,
243 void generate_serialize_list_element (std::ofstream &out,
247 void generate_python_docstring (std::ofstream& out,
250 void generate_python_docstring (std::ofstream& out,
253 void generate_python_docstring (std::ofstream& out,
256 const char* subheader);
258 void generate_python_docstring (std::ofstream& out,
265 std::string py_autogen_comment();
266 std::string future_imports();
268 std::string py_autogen_sandesh_request_skeleton_comment();
269 void py_autogen_sandesh_http_request_open(std::ofstream& out);
270 void py_autogen_sandesh_http_request_close(std::ofstream& out);
272 std::string py_imports();
273 std::string render_includes();
274 std::string render_fastbinary_includes();
276 std::string render_sandesh_includes();
278 std::string declare_argument(
t_field* tfield);
279 std::string render_field_default_value(
t_field* tfield);
280 std::string type_name(
t_type* ttype);
281 std::string function_signature(
t_function* tfunction, std::string prefix=
"");
282 std::string function_signature_if(
t_function* tfunction, std::string prefix=
"");
283 std::string argument_list(
t_struct* tstruct);
284 std::string type_to_enum(
t_type* ttype);
285 std::string type_to_spec_args(
t_type* ttype);
288 return sub_namespace ==
"twisted";
293 std::string twisted_module = program->
get_namespace(
"py.twisted");
294 if(!twisted_module.empty()){
295 return twisted_module;
300 if (real_module.empty()) {
342 std::vector<std::string> sandesh_req_list_;
347 std::vector<boost::tuple<std::string, std::string> > sandesh_uve_list_;
352 std::vector<boost::tuple<std::string, std::string> > sandesh_alarm_list_;
363 std::ofstream f_request_impl_;
364 std::ofstream f_http_request_;
380 string module = get_real_py_module(program_, gen_twisted_);
381 package_dir_ = get_out_dir();
384 MKDIR(package_dir_.c_str());
385 std::ofstream init_py((package_dir_+
"/__init__.py").c_str());
387 if (module.empty()) {
390 string::size_type pos = module.find(
'.');
391 if (pos == string::npos) {
393 package_dir_ += module;
397 package_dir_ += module.substr(0, pos);
398 module.erase(0, pos+1);
403 string f_types_name = package_dir_+
"/"+
"ttypes.py";
404 f_types_.open(f_types_name.c_str());
406 string f_consts_name = package_dir_+
"/"+
"constants.py";
407 f_consts_.open(f_consts_name.c_str());
409 string f_init_name = package_dir_+
"/__init__.py";
411 f_init.open(f_init_name.c_str());
413 "__all__ = ['ttypes', 'constants'";
414 vector<t_service*> services = program_->get_services();
415 vector<t_service*>::iterator sv_iter;
416 for (sv_iter = services.begin(); sv_iter != services.end(); ++sv_iter) {
417 f_init <<
", '" << (*sv_iter)->get_name() <<
"'";
419 f_init <<
"]" << endl;
424 py_autogen_comment() << endl <<
425 py_imports() << endl <<
426 future_imports() << endl <<
427 render_includes() << endl <<
428 render_fastbinary_includes() <<
429 render_sandesh_includes() <<
433 py_autogen_comment() << endl <<
434 py_imports() << endl <<
435 "from .ttypes import *" << endl <<
438 string f_request_impl_name = package_dir_+
"/request_skeleton.py";
439 f_request_impl_.open(f_request_impl_name.c_str());
441 py_autogen_comment() << endl;
443 py_autogen_sandesh_request_skeleton_comment() << endl;
445 string f_http_request_name = package_dir_+
"/http_request.py";
446 f_http_request_.open(f_http_request_name.c_str());
448 py_autogen_comment() << endl;
450 "from . import ttypes" << endl;
451 py_autogen_sandesh_http_request_open(f_http_request_);
459 const vector<t_program*>& includes = program_->get_includes();
461 for (
size_t i = 0; i < includes.size(); ++i) {
462 result +=
"from ." + get_real_py_module(includes[i], gen_twisted_) +
463 " import ttypes as " + get_real_py_module(includes[i], gen_twisted_) +
"_ttypes\n";
465 if (includes.size() > 0) {
477 hdr += std::string(import_dynbase_);
481 "from pysandesh.transport import TTransport\n"
482 "from pysandesh.protocol import TBinaryProtocol, TProtocol\n"
484 " from pysandesh.protocol import fastbinary\n"
486 " fastbinary = None\n";
489 "from thrift.transport import TTransport\n"
490 "from thrift.protocol import TBinaryProtocol, TProtocol\n"
492 " from thrift.protocol import fastbinary\n"
494 " fastbinary = None\n";
501 string t_py_generator::render_sandesh_includes() {
502 std::string module = get_real_py_module(program_, gen_twisted_);
503 std::string sandesh_includes(
"\n");
505 "from io import StringIO\n"
508 "from sys import getsizeof\n"
509 "from itertools import chain\n";
510 if (module !=
"sandesh") {
513 "from pysandesh import sandesh_base\n"
514 "from pysandesh.sandesh_http import SandeshHttp\n"
515 "from pysandesh.sandesh_uve import SandeshUVETypeMaps\n"
516 "from pysandesh.util import UTCTimestampUsec, UTCTimestampUsecToString\n"
517 "from pysandesh import util\n"
518 "from pysandesh.gen_py.sandesh.constants import *\n";
520 return sandesh_includes;
533 "# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING\n" +
535 "# options string: " + copy_options_ +
"\n" +
536 "# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.\n" +
541 "# Autogenerated by Thrift Compiler \n" +
543 "# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING\n" +
545 "# options string: " + copy_options_ +
"\n" +
556 string(
"from pysandesh.Thrift import TType, TMessageType, TException");
559 string(
"from thrift.Thrift import TType, TMessageType, TException");
567 std::string future_imports(
"\n");
568 return future_imports;
576 generate_py_sandesh_request_list(f_types_);
577 generate_py_sandesh_uve_list(f_types_);
578 generate_py_sandesh_alarm_list(f_types_);
584 f_request_impl_.close();
585 py_autogen_sandesh_http_request_close(f_http_request_);
586 f_http_request_.close();
606 std::ostringstream to_string_mapping, from_string_mapping;
610 (gen_newstyle_ ?
"(object)" :
"") <<
611 (gen_dynamic_ ?
"(" + gen_dynbaseclass_ +
")" :
"") <<
614 generate_python_docstring(f_types_, tenum);
616 to_string_mapping << indent() <<
"_VALUES_TO_NAMES = {" << endl;
617 from_string_mapping << indent() <<
"_NAMES_TO_VALUES = {" << endl;
620 vector<t_enum_value*>::iterator c_iter;
621 for (c_iter = constants.begin(); c_iter != constants.end(); ++c_iter) {
622 int value = (*c_iter)->get_value();
623 indent(f_types_) << (*c_iter)->get_name() <<
" = " << value << endl;
627 indent() << indent() << value <<
": \"" <<
628 escape_string((*c_iter)->get_name()) <<
"\"," << endl;
629 from_string_mapping <<
630 indent() << indent() <<
'"' << escape_string((*c_iter)->get_name()) <<
631 "\": " << value <<
',' << endl;
633 to_string_mapping << indent() <<
"}" << endl;
634 from_string_mapping << indent() <<
"}" << endl;
638 f_types_ << to_string_mapping.str() << endl << from_string_mapping.str() << endl;
649 indent(f_consts_) << name <<
" = " << render_const_value(type, value);
659 type = get_true_type(type);
660 std::ostringstream out;
667 case t_base_type::TYPE_STATIC_CONST_STRING:
668 case t_base_type::TYPE_XML:
670 out <<
'"' << get_escaped_string(value) <<
'"';
673 out << (value->
get_integer() > 0 ?
"True" :
"False");
680 case t_base_type::TYPE_U16:
681 case t_base_type::TYPE_U32:
682 case t_base_type::TYPE_U64:
683 case t_base_type::TYPE_IPV4:
695 case t_base_type::TYPE_UUID:
696 out <<
"uuid.UUID('{" << get_escaped_string(value) <<
"}')";
698 case t_base_type::TYPE_IPADDR:
699 out <<
"netaddr.IPAddress('" << value->
get_string() <<
"')";
708 out << type->
get_name() <<
"(**{" << endl;
710 const vector<t_field*>& fields = ((
t_struct*)type)->get_members();
711 vector<t_field*>::const_iterator f_iter;
712 const map<t_const_value*, t_const_value*>& val = value->
get_map();
713 map<t_const_value*, t_const_value*>::const_iterator v_iter;
714 for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
715 t_type* field_type = NULL;
716 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
717 if ((*f_iter)->get_name() == v_iter->first->get_string()) {
718 field_type = (*f_iter)->get_type();
721 if (field_type == NULL) {
722 throw "type error: " + type->
get_name() +
" has no field " + v_iter->first->get_string();
727 out << render_const_value(field_type, v_iter->second);
732 }
else if (type->
is_map()) {
737 const map<t_const_value*, t_const_value*>& val = value->
get_map();
738 map<t_const_value*, t_const_value*>::const_iterator v_iter;
739 for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
741 out << render_const_value(ktype, v_iter->first);
743 out << render_const_value(vtype, v_iter->second);
751 etype = ((
t_list*)type)->get_elem_type();
753 etype = ((
t_set*)type)->get_elem_type();
760 const vector<t_const_value*>& val = value->
get_list();
761 vector<t_const_value*>::const_iterator v_iter;
762 for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
764 out << render_const_value(etype, *v_iter);
773 throw "CANNOT GENERATE CONSTANT FOR TYPE: " + type->
get_name();
783 generate_py_struct(tstruct,
false);
793 generate_py_struct(txception,
true);
796 void t_py_generator::generate_sandesh(
t_sandesh* tsandesh) {
797 generate_py_sandesh(tsandesh);
805 generate_py_struct_definition(f_types_, tstruct, is_exception);
818 const vector<t_field*>& members = tstruct->
get_members();
820 vector<t_field*>::const_iterator m_iter;
826 out <<
"(" << gen_dynbaseclass_exc_ <<
")";
828 out <<
"(TException)";
833 }
else if (gen_dynamic_) {
834 out <<
"(" << gen_dynbaseclass_ <<
")";
839 generate_python_docstring(out, tstruct);
864 indent(out) <<
"__slots__ = [ " << endl;
866 for (m_iter = sorted_members.begin(); m_iter != sorted_members.end(); ++m_iter) {
867 indent(out) <<
"'" << (*m_iter)->get_name() <<
"'," << endl;
870 indent(out) <<
" ]" << endl << endl;
878 if (sorted_members.empty() || (sorted_members[0]->get_key() >= 0)) {
879 indent(out) <<
"thrift_spec = (" << endl;
882 int sorted_keys_pos = 0;
883 for (m_iter = sorted_members.begin(); m_iter != sorted_members.end(); ++m_iter) {
885 for (; sorted_keys_pos != (*m_iter)->get_key(); sorted_keys_pos++) {
886 indent(out) <<
"None, # " << sorted_keys_pos << endl;
889 indent(out) <<
"(" << (*m_iter)->get_key() <<
", "
890 << type_to_enum((*m_iter)->get_type()) <<
", "
891 <<
"'" << (*m_iter)->get_name() <<
"'" <<
", "
892 << type_to_spec_args((*m_iter)->get_type()) <<
", "
893 << render_field_default_value(*m_iter) <<
", "
895 <<
" # " << sorted_keys_pos
902 indent(out) <<
")" << endl << endl;
904 indent(out) <<
"thrift_spec = None" << endl;
908 if (members.size() > 0) {
910 indent() <<
"def __init__(self,";
912 for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
915 t_type*
type = get_true_type((*m_iter)->get_type());
916 if (type->is_static_const_string()) {
921 out <<
" " << declare_argument(*m_iter) <<
",";
928 for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
933 "if " << (*m_iter)->get_name() <<
" is " <<
"self.thrift_spec[" <<
934 (*m_iter)->get_key() <<
"][4]:" << endl;
935 indent(out) <<
" " << (*m_iter)->get_name() <<
" = " <<
936 render_field_default_value(*m_iter) << endl;
938 }
else if (type->is_static_const_string()) {
940 "self." << (*m_iter)->get_name() <<
" = " <<
941 render_const_value(type, (*m_iter)->get_value()) << endl;
947 "self." << (*m_iter)->get_name() <<
" = " << (*m_iter)->get_name() << endl;
954 for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
955 if ((*m_iter)->get_name() ==
"name") {
956 std::map<std::string, std::string>::iterator it;
957 it = (*m_iter)->annotations_.find(
"key");
958 if (it != (*m_iter)->annotations_.end()) {
959 indent(out) <<
"self._table = '" << it->second <<
"'" << endl;
972 generate_py_struct_reader(out, tstruct);
973 generate_py_struct_writer(out, tstruct);
977 generate_py_struct_logger(out, tstruct);
978 generate_py_struct_sizeof(out, tstruct);
986 indent() <<
"def __str__(self):" << endl <<
987 indent() <<
" return repr(self)" << endl <<
995 indent() <<
"def __repr__(self):" << endl <<
996 indent() <<
" L = ['%s=%r' % (key, value)" << endl <<
997 indent() <<
" for key, value in self.__dict__.items()]" << endl <<
998 indent() <<
" return '%s(%s)' % (self.__class__.__name__, ', '.join(L))" << endl <<
1003 indent() <<
"def __eq__(self, other):" << endl;
1006 indent() <<
"return isinstance(other, self.__class__) and "
1007 "self.__dict__ == other.__dict__" << endl;
1012 indent() <<
"def __ne__(self, other):" << endl;
1016 indent() <<
"return not (self == other)" << endl;
1023 indent() <<
"def __hash__(self):" << endl;
1027 indent() <<
"return id(self)" << endl;
1029 }
else if (!gen_dynamic_) {
1033 indent() <<
"def __repr__(self):" << endl <<
1034 indent() <<
" L = ['%s=%r' % (key, getattr(self, key))" << endl <<
1035 indent() <<
" for key in self.__slots__]" << endl <<
1036 indent() <<
" return '%s(%s)' % (self.__class__.__name__, ', '.join(L))" << endl <<
1041 indent() <<
"def __eq__(self, other):" << endl <<
1042 indent() <<
" if not isinstance(other, self.__class__):" << endl <<
1043 indent() <<
" return False" << endl <<
1044 indent() <<
" for attr in self.__slots__:" << endl <<
1045 indent() <<
" my_val = getattr(self, attr)" << endl <<
1046 indent() <<
" other_val = getattr(other, attr)" << endl <<
1047 indent() <<
" if my_val != other_val:" << endl <<
1048 indent() <<
" return False" << endl <<
1049 indent() <<
" return True" << endl <<
1053 indent() <<
"def __ne__(self, other):" << endl <<
1054 indent() <<
" return not (self == other)" << endl <<
1065 const vector<t_field*>& fields = tstruct->
get_members();
1066 vector<t_field*>::const_iterator f_iter;
1069 "def read(self, iprot):" << endl;
1073 "if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated "
1074 "and isinstance(iprot.trans, TTransport.CReadableTransport) "
1075 "and self.thrift_spec is not None "
1076 "and fastbinary is not None:" << endl;
1080 "fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))" << endl;
1092 "read_cnt = 0" << endl;
1097 "length = iprot.readStructBegin()" << endl;
1099 "if length < 0: return -1" << endl;
1101 "read_cnt += length" << endl;
1104 "iprot.readStructBegin()" << endl;
1109 "while True:" << endl;
1115 "(length, fname, ftype, fid) = iprot.readFieldBegin()" << endl;
1117 "if length < 0: return -1" << endl;
1119 "read_cnt += length" << endl;
1122 "(fname, ftype, fid) = iprot.readFieldBegin()" << endl;
1127 "if ftype == TType.STOP:" << endl;
1137 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1146 out <<
"fid == " << (*f_iter)->get_key() <<
":" << endl;
1153 indent() <<
"else:" << endl <<
1154 indent() <<
" iprot.skip(ftype)" << endl;
1160 indent() <<
"else:" << endl <<
1161 indent() <<
" iprot.skip(ftype)" << endl;
1166 "length = iprot.readFieldEnd()" << endl;
1168 "if length < 0: return -1" << endl;
1170 "read_cnt += length" << endl;
1173 "iprot.readFieldEnd()" << endl;
1180 "length = iprot.readStructEnd()" << endl;
1182 "if length < 0: return -1" << endl;
1184 "read_cnt += length" << endl;
1187 "iprot.readStructEnd()" << endl;
1192 "return read_cnt" << endl;
1203 vector<t_field*>::const_iterator f_iter;
1206 "def write(self, oprot):" << endl;
1210 "if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated "
1211 "and self.thrift_spec is not None "
1212 "and fastbinary is not None:" << endl;
1216 "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))" << endl;
1228 "if oprot.writeStructBegin(self.__class__.__name__) < 0: return -1" << endl;
1231 "oprot.writeStructBegin('" << name <<
"')" << endl;
1234 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1238 "if self." << (*f_iter)->get_name() <<
" is not None:" << endl;
1241 "annotations = {}" << endl;
1242 if (!((*f_iter)->annotations_.empty())) {
1243 std::map<std::string, std::string>::iterator it;
1244 for (it = (*f_iter)->annotations_.begin(); it != (*f_iter)->annotations_.end(); it++) {
1245 if (((*f_iter)->get_name() ==
"name") && (it->first ==
"key")) {
1246 indent(out) <<
"if self._table is None or self._table is '': return -1" << endl;
1247 indent(out) <<
"annotations['key'] = " <<
"self._table" << endl;
1249 indent(out) <<
"annotations['" << (*it).first <<
"'] = '" <<
1250 (*it).second <<
"'" << endl;
1255 "if oprot.writeFieldBegin(" <<
1256 "'" << (*f_iter)->get_name() <<
"', " <<
1258 (*f_iter)->get_key() <<
", annotations) < 0: return -1" << endl;
1261 "if self." << (*f_iter)->get_name() <<
" is not None:" << endl;
1264 "oprot.writeFieldBegin(" <<
1265 "'" << (*f_iter)->get_name() <<
"', " <<
1267 (*f_iter)->get_key() <<
")" << endl;
1276 "if oprot.writeFieldEnd() < 0: return -1" << endl;
1279 "oprot.writeFieldEnd()" << endl;
1287 indent() <<
"if oprot.writeFieldStop() < 0: return -1" << endl <<
1288 indent() <<
"if oprot.writeStructEnd() < 0: return -1" << endl <<
1289 indent() <<
"return 0" << endl;
1292 indent() <<
"oprot.writeFieldStop()" << endl <<
1293 indent() <<
"oprot.writeStructEnd()" << endl;
1304 indent(out) <<
"def validate(self):" << endl;
1307 const vector<t_field*>& fields = tstruct->
get_members();
1309 if (fields.size() > 0) {
1310 vector<t_field*>::const_iterator f_iter;
1312 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1315 indent(out) <<
"if self." << field->
get_name() <<
" is None:" << endl;
1316 indent(out) <<
" raise TProtocol.TProtocolException(message='Required field " <<
1317 field->
get_name() <<
" is unset!')" << endl;
1322 indent(out) <<
"return" << endl << endl;
1327 void t_py_generator::generate_py_sandesh(
t_sandesh *tsandesh) {
1328 generate_py_sandesh_definition(
f_types_, tsandesh);
1331 void t_py_generator::generate_py_sandesh_definition(ofstream& out,
1333 const vector<t_field*>& members = tsandesh->
get_members();
1335 vector<t_field*>::const_iterator m_iter;
1338 std::string base_class;
1339 if (sandesh_type->is_sandesh_system()) {
1340 base_class =
"sandesh_base.SandeshSystem";
1341 }
else if (sandesh_type->is_sandesh_object()) {
1342 base_class =
"sandesh_base.SandeshObject";
1343 }
else if (sandesh_type->is_sandesh_flow()) {
1344 if (sandesh_type->is_sandesh_session()) {
1345 base_class =
"sandesh_base.SandeshFlowSession";
1347 base_class =
"sandesh_base.SandeshFlow";
1349 }
else if (sandesh_type->is_sandesh_request()) {
1350 base_class =
"sandesh_base.SandeshRequest";
1351 }
else if (sandesh_type->is_sandesh_response()) {
1352 base_class =
"sandesh_base.SandeshResponse";
1353 }
else if (sandesh_type->is_sandesh_uve()) {
1354 base_class =
"sandesh_base.SandeshUVE";
1355 }
else if (sandesh_type->is_sandesh_dynamic_uve()) {
1356 base_class =
"sandesh_base.SandeshDynamicUVE";
1357 }
else if (sandesh_type->is_sandesh_alarm()) {
1358 base_class =
"sandesh_base.SandeshAlarm";
1359 }
else if (sandesh_type->is_sandesh_trace() ||
1360 sandesh_type->is_sandesh_trace_object()) {
1361 base_class =
"sandesh_base.SandeshTrace";
1363 throw "compiler error: unsupported sandesh type " +
1369 out <<
"(" << base_class <<
"):" << endl;
1396 indent(out) <<
"__slots__ = [ " << endl;
1398 for (m_iter = sorted_members.begin(); m_iter != sorted_members.end(); ++m_iter) {
1399 indent(out) <<
"'" << (*m_iter)->get_name() <<
"'," << endl;
1402 indent(out) <<
" ]" << endl << endl;
1410 if (sorted_members.empty() || (sorted_members[0]->get_key() >= 0)) {
1411 indent(out) <<
"thrift_spec = (" << endl;
1414 int sorted_keys_pos = 0;
1415 for (m_iter = sorted_members.begin(); m_iter != sorted_members.end(); ++m_iter) {
1417 for (; sorted_keys_pos != (*m_iter)->get_key(); sorted_keys_pos++) {
1418 indent(out) <<
"None, # " << sorted_keys_pos << endl;
1421 indent(out) <<
"(" << (*m_iter)->get_key() <<
", "
1423 <<
"'" << (*m_iter)->get_name() <<
"'" <<
", "
1427 <<
" # " << sorted_keys_pos
1434 indent(out) <<
")" << endl << endl;
1436 indent(out) <<
"thrift_spec = None" << endl << endl;
1439 if (sandesh_type->is_sandesh_system()) {
1440 indent(out) <<
"rate_limit_buffer = util.deque(maxlen=sandesh_base."
1441 "SandeshSystem._DEFAULT_SEND_RATELIMIT)" << endl << endl;
1442 indent(out) <<
"do_rate_limit_drop_log = True" << endl << endl;
1447 indent() <<
"def __init__(self";
1449 for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
1452 if (type->is_static_const_string()) {
1459 if (sandesh_type->is_sandesh_system() ||
1460 sandesh_type->is_sandesh_object() ||
1461 sandesh_type->is_sandesh_flow()) {
1462 out <<
", category='" <<
"__default__" <<
1463 "', level=SandeshLevel.SYS_INFO";
1465 if (sandesh_type->is_sandesh_uve() ||
1466 sandesh_type->is_sandesh_dynamic_uve() ||
1467 sandesh_type->is_sandesh_alarm()) {
1468 out <<
", table=None";
1470 out <<
", sandesh=sandesh_base.sandesh_global):" << endl;
1473 if (sandesh_type->is_sandesh_trace()) {
1474 indent(out) << base_class <<
1475 ".__init__(self, type=SandeshType.TRACE)" << endl;
1476 }
else if (sandesh_type->is_sandesh_trace_object()) {
1477 indent(out) << base_class <<
1478 ".__init__(self, type=SandeshType.TRACE_OBJECT)" << endl;
1480 indent(out) << base_class <<
".__init__(self)" << endl;
1483 for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
1485 t_type* type = (*m_iter)->get_type();
1488 "if " << (*m_iter)->get_name() <<
" is " <<
"self.thrift_spec[" <<
1489 (*m_iter)->get_key() <<
"][4]:" << endl;
1490 indent(out) <<
" " << (*m_iter)->get_name() <<
" = " <<
1492 }
else if (type->is_static_const_string()) {
1494 "self." << (*m_iter)->get_name() <<
" = " <<
1498 "self." << (*m_iter)->get_name() <<
" = " << (*m_iter)->get_name() << endl;
1502 indent(out) <<
"self._scope = sandesh.scope()" << endl;
1503 indent(out) <<
"self._module = sandesh.module()" << endl;
1504 indent(out) <<
"self._source = sandesh.source_id()" << endl;
1505 indent(out) <<
"self._node_type = sandesh.node_type()" << endl;
1506 indent(out) <<
"self._instance_id = sandesh.instance_id()" << endl;
1507 indent(out) <<
"self._seqnum = 0" << endl;
1508 indent(out) <<
"self._timestamp = UTCTimestampUsec()" << endl;
1510 generate_py_sandesh_hint(out, tsandesh);
1511 if (sandesh_type->is_sandesh_system() ||
1512 sandesh_type->is_sandesh_object() ||
1513 sandesh_type->is_sandesh_flow()) {
1514 indent(out) <<
"self._category = category" << endl;
1515 indent(out) <<
"self._level = level" << endl;
1517 if (sandesh_type->is_sandesh_uve() ||
1518 sandesh_type->is_sandesh_dynamic_uve() ||
1519 sandesh_type->is_sandesh_alarm()) {
1520 indent(out) <<
"if table is not None:" << endl;
1522 indent(out) <<
"self.data._table = table" << endl;
1530 if (sandesh_type->is_sandesh_system() ||
1531 sandesh_type->is_sandesh_object() ||
1532 sandesh_type->is_sandesh_flow()) {
1533 generate_py_sandesh_async(out, tsandesh);
1534 }
else if (sandesh_type->is_sandesh_request()) {
1535 generate_py_sandesh_request(out, tsandesh);
1536 }
else if (sandesh_type->is_sandesh_response()) {
1537 generate_py_sandesh_response(out, tsandesh);
1538 }
else if (sandesh_type->is_sandesh_uve() ||
1539 sandesh_type->is_sandesh_alarm()) {
1540 generate_py_sandesh_uve(out, tsandesh,
true);
1541 }
else if (sandesh_type->is_sandesh_dynamic_uve()) {
1542 generate_py_sandesh_uve(out, tsandesh,
false);
1543 }
else if (sandesh_type->is_sandesh_trace() ||
1544 sandesh_type->is_sandesh_trace_object()) {
1545 generate_py_sandesh_trace(out, tsandesh);
1548 generate_py_sandesh_logger(out, tsandesh);
1551 generate_py_sandesh_reader(out, tsandesh);
1552 generate_py_sandesh_writer(out, tsandesh);
1555 generate_py_sandesh_compare(out, tsandesh);
1556 generate_py_sandesh_sizeof(out, tsandesh);
1562 indent() <<
"def __repr__(self):" << endl <<
1563 indent() <<
" L = ['%s=%r' % (key, value)" << endl <<
1564 indent() <<
" for key, value in self.__dict__.items()]" << endl <<
1565 indent() <<
" return '%s(%s)' % (self.__class__.__name__, ', '.join(L))" << endl <<
1570 indent() <<
"def __eq__(self, other):" << endl;
1573 indent() <<
"return isinstance(other, self.__class__) and "
1574 "self.__dict__ == other.__dict__" << endl;
1579 indent() <<
"def __ne__(self, other):" << endl;
1583 indent() <<
"return not (self == other)" << endl;
1589 indent() <<
"def __repr__(self):" << endl <<
1590 indent() <<
" L = ['%s=%r' % (key, getattr(self, key))" << endl <<
1591 indent() <<
" for key in self.__slots__]" << endl <<
1592 indent() <<
" return '%s(%s)' % (self.__class__.__name__, ', '.join(L))" << endl <<
1597 indent() <<
"def __eq__(self, other):" << endl <<
1598 indent() <<
" if not isinstance(other, self.__class__):" << endl <<
1599 indent() <<
" return False" << endl <<
1600 indent() <<
" for attr in self.__slots__:" << endl <<
1601 indent() <<
" my_val = getattr(self, attr)" << endl <<
1602 indent() <<
" other_val = getattr(other, attr)" << endl <<
1603 indent() <<
" if my_val != other_val:" << endl <<
1604 indent() <<
" return False" << endl <<
1605 indent() <<
" return True" << endl <<
1609 indent() <<
"def __ne__(self, other):" << endl <<
1610 indent() <<
" return not (self == other)" << endl <<
1619 void t_py_generator::generate_py_sandesh_reader(ofstream& out,
1621 const vector<t_field*>& fields = tsandesh->
get_members();
1622 vector<t_field*>::const_iterator f_iter;
1625 "def read(self, iprot):" << endl;
1629 "if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated "
1630 "and isinstance(iprot.trans, TTransport.CReadableTransport) "
1631 "and self.thrift_spec is not None "
1632 "and fastbinary is not None:" << endl;
1636 "fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))" << endl;
1638 "return -1" << endl;
1642 "read_cnt = 0" << endl;
1645 "(length, sandesh_name) = iprot.readSandeshBegin()" << endl;
1647 "if length < 0: return -1" << endl;
1649 "read_cnt += length" << endl;
1653 "while True:" << endl;
1658 "(length, fname, ftype, fid) = iprot.readFieldBegin()" << endl;
1660 "if length < 0: return -1" << endl;
1662 "read_cnt += length" << endl;
1666 "if ftype == TType.STOP:" << endl;
1676 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1685 out <<
"fid == " << (*f_iter)->get_key() <<
":" << endl;
1692 indent() <<
"else:" << endl <<
1693 indent() <<
" iprot.skip(ftype)" << endl;
1699 indent() <<
"else:" << endl <<
1700 indent() <<
" iprot.skip(ftype)" << endl;
1704 "length = iprot.readFieldEnd()" << endl;
1706 "if length < 0: return -1" << endl;
1708 "read_cnt += length" << endl;
1713 "length = iprot.readSandeshEnd()" << endl;
1715 "if length < 0: return -1" << endl;
1717 "read_cnt += length" << endl;
1720 "return read_cnt" << endl;
1726 void t_py_generator::generate_py_sandesh_writer(ofstream& out,
1729 vector<t_field*>::const_iterator f_iter;
1732 "def write(self, oprot):" << endl;
1736 "if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated "
1737 "and self.thrift_spec is not None "
1738 "and fastbinary is not None:" << endl;
1742 "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))" << endl;
1748 "if oprot.writeSandeshBegin(self.__class__.__name__) < 0: return -1" << endl;
1749 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1752 "if self." << (*f_iter)->get_name() <<
" is not None:" << endl;
1755 "annotations = {}" << endl;
1756 if (!((*f_iter)->annotations_.empty())) {
1757 std::map<std::string, std::string>::iterator it;
1758 for (it = (*f_iter)->annotations_.begin(); it != (*f_iter)->annotations_.end(); it++) {
1759 indent(out) <<
"annotations['" << (*it).first <<
"'] = '" <<
1760 (*it).second <<
"'" << endl;
1764 "if oprot.writeFieldBegin(" <<
1765 "'" << (*f_iter)->get_name() <<
"', " <<
1767 (*f_iter)->get_key() <<
", annotations) < 0: return -1" << endl;
1774 "if oprot.writeFieldEnd() < 0: return -1" << endl;
1781 "if oprot.writeFieldStop() < 0: return -1" << endl;
1783 "if oprot.writeSandeshEnd() < 0: return -1" << endl;
1788 generate_py_sandesh_required_validator(out, tsandesh);
1793 void t_py_generator::generate_py_sandesh_required_validator(ofstream& out,
1795 indent(out) <<
"def validate(self):" << endl;
1798 const vector<t_field*>& fields = tsandesh->
get_members();
1800 if (fields.size() > 0) {
1801 vector<t_field*>::const_iterator f_iter;
1803 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1806 indent(out) <<
"if self." << field->
get_name() <<
" is None:" << endl;
1807 indent(out) <<
" raise TProtocol.TProtocolException(message='Required field " <<
1808 field->
get_name() <<
" is unset!')" << endl;
1813 indent(out) <<
"return" << endl << endl;
1817 void t_py_generator::generate_py_sandesh_compare(ofstream& out,
1820 vector<t_field*>::const_iterator f_iter;
1823 "def compare(self, other):" << endl;
1826 "if not isinstance(other, self.__class__):" << endl;
1829 "return False" << endl;
1832 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1834 "if self." << (*f_iter)->get_name() <<
" != " <<
1835 "other." << (*f_iter)->get_name() <<
":" << endl;
1837 indent(out) <<
"return False" << endl;
1841 indent(out) <<
"return True" << endl << endl;
1845 void t_py_generator::generate_py_sandesh_http_attr(ofstream& out,
1846 t_type *ftype,
const std::string& namel,
const std::string& namer) {
1853 "if bottle.request.query." << namer <<
":" << endl;
1857 "sandesh_req." << namel <<
" = str(" <<
1858 "bottle.request.query." << namer <<
")" << endl;
1859 }
else if (bftype == t_base_type::TYPE_UUID) {
1860 indent(out) <<
"try:" << endl;
1862 indent(out) <<
"sandesh_req." << namel <<
" = uuid.UUID("
1863 <<
"bottle.request.query." << namer <<
")" << endl;
1865 indent(out) <<
"except ValueError:" << endl;
1867 indent(out) <<
"return SandeshHttp.http_error('Invalid value for "
1868 << namel <<
":" << namer <<
"')" << endl;
1870 }
else if (bftype == t_base_type::TYPE_IPADDR) {
1871 indent(out) <<
"try:" << endl;
1873 indent(out) <<
"sandesh_req." << namel <<
" = netaddr.IPAddress("
1874 <<
"bottle.request.query." << namer <<
")" << endl;
1876 indent(out) <<
"except ValueError:" << endl;
1878 indent(out) <<
"return SandeshHttp.http_error('Invalid value for "
1879 << namel <<
":" << namer <<
"')" << endl;
1887 bftype == t_base_type::TYPE_U16 ||
1888 bftype == t_base_type::TYPE_U32 ||
1889 bftype == t_base_type::TYPE_U64 ||
1890 bftype == t_base_type::TYPE_IPV4);
1895 "sandesh_req." << namel <<
" = int(" <<
1896 "bottle.request.query." << namer <<
")" << endl;
1899 "except ValueError:" << endl;
1902 "return SandeshHttp.http_error('Invalid data provided in Sandesh Request')" << endl;
1912 void t_py_generator::generate_py_sandesh_http_request_handler(ofstream& out,
1915 vector<t_field*>::const_iterator f_iter;
1918 "@staticmethod" << endl;
1920 "def handle_http_request(sandesh=sandesh_base.sandesh_global):" << endl;
1923 "sandesh_req = " << tsandesh->
get_name() <<
"()" << endl;
1925 "if not sandesh_req:" << endl;
1927 indent(out) <<
"return SandeshHttp.http_error('Sandesh Request \"" << tsandesh->
get_name() <<
1928 "\" not implemented')" << endl;
1930 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1931 t_type *ftype = (*f_iter)->get_type();
1932 if (f_iter == fields.begin()) {
1933 generate_py_sandesh_http_attr(out, ftype, (*f_iter)->
get_name(),
"x");
1935 generate_py_sandesh_http_attr(out, ftype, (*f_iter)->
get_name(), (*f_iter)->get_name());
1938 indent(out) <<
"sandesh_req._context = bottle.request.url" << endl;
1939 indent(out) <<
"handle_req_fn = getattr(sandesh_req, \"handle_request\", None)" << endl;
1940 indent(out) <<
"if callable(handle_req_fn):" << endl;
1942 indent(out) <<
"handle_req_fn(sandesh_req)" << endl;
1944 indent(out) <<
"else:" << endl;
1946 indent(out) <<
"return SandeshHttp.http_error('Sandesh Request \"" << tsandesh->
get_name() <<
1947 "\" not implemented')" << endl;
1949 indent(out) <<
"resp = SandeshHttp.get_http_response()" << endl;
1950 indent(out) <<
"if resp:" << endl;
1952 indent(out) <<
"return resp" << endl;
1954 indent(out) <<
"else:" << endl;
1956 indent(out) <<
"return SandeshHttp.http_error('No Response for Sandesh Request \"" <<
1957 tsandesh->
get_name() <<
"\"')" << endl;
1964 void t_py_generator::generate_py_sandesh_request_list(ofstream& out) {
1965 out << endl << endl;
1966 out <<
"_SANDESH_REQUEST_LIST = [" << endl;
1967 std::vector<std::string>::const_iterator it;
1968 for (it = sandesh_req_list_.begin(); it != sandesh_req_list_.end(); ++it) {
1969 indent(out) << *it <<
"," << endl;
1974 void t_py_generator::generate_py_sandesh_http_request_list(ofstream& out,
1977 "{ 'uri':" <<
"'/Snh_" << tsandesh->
get_name() <<
"'" <<
1978 ", 'method':" <<
"ttypes." << tsandesh->
get_name() <<
".handle_http_request " <<
1982 void t_py_generator::py_autogen_sandesh_http_request_open(ofstream& out) {
1985 "_HTTP_REQUEST_LIST = [" << endl;
1988 void t_py_generator::py_autogen_sandesh_http_request_close(ofstream& out) {
1989 out <<
"]" << endl << endl;
1992 std::string t_py_generator::py_autogen_sandesh_request_skeleton_comment() {
1995 "# This autogenerated skeleton file illustrates the implementation of" +
1997 "# derived class to handle the sandesh request." +
2001 void t_py_generator::generate_py_sandesh_skeleton_request(ofstream& out,
2003 const vector<t_field*>& members = tsandesh->
get_members();
2004 vector<t_field*>::const_iterator m_iter;
2007 "# Create a derived class from \"" << tsandesh->
get_name() <<
"\" to handle ";
2009 "# the sandesh request. Add this derived class \"" << tsandesh->
get_name() <<
"_derived\"";
2011 "# in module " << tsandesh->
get_name() <<
"_derived.py and " <<
2012 "add it in your package" << endl;
2015 "class " << tsandesh->
get_name() <<
"_derived";
2016 out <<
"(" << tsandesh->
get_name() <<
"):" << endl;
2020 if (members.size() > 0) {
2022 indent() <<
"def __init__(self):" << endl;
2027 for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
2030 if (type->is_static_const_string()) {
2040 out <<
indent() <<
"def handle_request(self):" << endl;
2043 "# Add your code to handle the \"" << tsandesh->
get_name() <<
2044 "\" request" << endl;
2051 void t_py_generator::generate_struct_log(ofstream& out,
2055 log_str <<
".write('<< ')" << endl;
2057 log_str <<
".write(" << prefix <<
".log())" << endl;
2059 log_str <<
".write('>>')" << endl;
2062 void t_py_generator::generate_container_log(ofstream& out,
2067 string kiter =
tmp(
"kiter");
2068 string viter =
tmp(
"viter");
2070 log_str <<
".write('{ ')" << endl;
2072 "for " << kiter <<
"," << viter <<
" in " << prefix <<
".items():" << endl;
2074 t_field kfield(((
t_map*)ttype)->get_key_type(), kiter);
2075 generate_field_log(out, &kfield, log_str,
"");
2077 log_str <<
".write(' : ')" << endl;
2078 t_field vfield(((
t_map*)ttype)->get_val_type(), viter);
2079 generate_field_log(out, &vfield, log_str,
"");
2082 log_str <<
".write(' }')" << endl;
2083 }
else if (ttype->
is_set()) {
2084 string iter =
tmp(
"iter");
2086 log_str <<
".write('( ')" << endl;
2088 "for " << iter <<
" in " << prefix <<
":" << endl;
2090 t_field efield(((
t_set*)ttype)->get_elem_type(), iter);
2091 generate_field_log(out, &efield, log_str,
"");
2093 log_str <<
".write(', ')" << endl;
2096 log_str <<
".write(' )')" << endl;
2097 }
else if (ttype->
is_list()) {
2098 string iter =
tmp(
"iter");
2100 log_str <<
".write('[ ')" << endl;
2102 "for " << iter <<
" in " << prefix <<
":" << endl;
2105 generate_field_log(out, &efield, log_str,
"");
2107 log_str <<
".write(', ')" << endl;
2110 log_str <<
".write(' ]')" << endl;
2114 void t_py_generator::generate_field_log(ofstream& out,
2121 generate_struct_log(out, prefix + tfield->
get_name(), log_str);
2123 generate_container_log(out, prefix + tfield->
get_name(),
type, log_str);
2125 string name = prefix + tfield->
get_name();
2132 case t_base_type::TYPE_STATIC_CONST_STRING:
2133 case t_base_type::TYPE_XML:
2135 log_str <<
".write(" << name <<
")" << endl;
2139 "if " << name <<
":" << endl;
2142 log_str <<
".write('True')" << endl;
2148 log_str <<
".write('False')" << endl;
2153 log_str <<
".write(hex(" << name <<
"))" << endl;
2157 log_str <<
".write(str(" << name <<
"))" << endl;
2161 log_str <<
".write(str(" << name <<
"))" << endl;
2165 log_str <<
".write(str(" << name <<
"))" << endl;
2167 case t_base_type::TYPE_U16:
2169 log_str <<
".write(str(" << name <<
"))" << endl;
2171 case t_base_type::TYPE_U32:
2173 log_str <<
".write(str(" << name <<
"))" << endl;
2175 case t_base_type::TYPE_U64:
2177 log_str <<
".write(str(" << name <<
"))" << endl;
2181 log_str <<
".write(str(" << name <<
"))" << endl;
2183 case t_base_type::TYPE_IPV4:
2184 indent(out) <<
"import socket, struct" << endl;
2186 log_str <<
".write(socket.inet_ntoa(struct.pack('!L'," << name <<
")))" << endl;
2188 case t_base_type::TYPE_IPADDR:
2190 log_str <<
".write(str(" << name <<
"))" << endl;
2192 case t_base_type::TYPE_UUID:
2194 log_str <<
".write(str(" << name <<
"))" << endl;
2201 log_str <<
".write(str(" << name <<
"))" << endl;
2204 printf(
"DO NOT KNOW HOW TO GENERATE LOG FOR FIELD '%s' TYPE '%s'\n",
2210 void t_py_generator::generate_py_sandesh_logger(ofstream &out,
2212 const vector<t_field*>& fields = tsandesh->
get_members();
2213 vector<t_field*>::const_iterator f_iter;
2216 std::string log_str =
"log_str";
2218 "def log(self, trace=False):" << endl;
2221 log_str <<
" = StringIO()" << endl;
2223 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
2226 indent(out) <<
"if trace:" << endl;
2228 indent(out) << log_str <<
".write(str(self._timestamp))" << endl;
2229 indent(out) << log_str <<
".write(' ')" << endl;
2232 if (sandesh_type->is_sandesh_system() ||
2233 sandesh_type->is_sandesh_object() ||
2234 sandesh_type->is_sandesh_flow()) {
2236 "if self._category is not None:" << endl;
2238 indent(out) << log_str <<
".write(self._category)" << endl;
2240 indent(out) << log_str <<
".write(' [')" << endl;
2241 indent(out) << log_str <<
".write(SandeshLevel._VALUES_TO_NAMES["
2242 <<
"self._level])" << endl;
2243 indent(out) << log_str <<
".write(']: ')" << endl;
2245 indent(out) << log_str <<
".write(self.__class__.__name__ + " <<
2249 "if self." << (*f_iter)->get_name() <<
" is not None:" << endl;
2251 if (sandesh_type->is_sandesh_system() ||
2252 sandesh_type->is_sandesh_trace()) {
2253 generate_field_log(out, *f_iter, log_str,
"self.");
2254 indent(out) << log_str <<
".write(' ')" << endl;
2256 indent(out) << log_str <<
2257 ".write('" << (*f_iter)->get_name() <<
" = ')"<< endl;
2258 generate_field_log(out, *f_iter, log_str,
"self.");
2259 indent(out) << log_str <<
".write(' ')" << endl;
2264 "return log_str.getvalue()" << endl << endl;
2268 void t_py_generator::generate_py_struct_logger(ofstream &out,
2270 const vector<t_field*>& fields = tstruct->
get_members();
2271 vector<t_field*>::const_iterator f_iter;
2273 std::string log_str =
"log_str";
2275 "def log(self):" << endl;
2278 log_str <<
" = StringIO()" << endl;
2280 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
2282 "if self." << (*f_iter)->get_name() <<
" is not None:" << endl;
2285 bool write_fname =
true;
2288 if (tbase == t_base_type::TYPE_STATIC_CONST_STRING) {
2289 write_fname =
false;
2294 log_str <<
".write('" << (*f_iter)->get_name() <<
" = ')"<< endl;
2296 generate_field_log(out, *f_iter, log_str,
"self.");
2298 log_str <<
".write(' ')" << endl;
2302 "return log_str.getvalue()" << endl << endl;
2306 void t_py_generator::generate_py_sizeof(std::ofstream& out,
2307 const vector<t_field*>& fields) {
2308 indent(out) <<
"def __sizeof__(self):" << endl;
2310 indent(out) <<
"size = 0" << endl;
2311 vector<t_field*>::const_iterator f_iter;
2312 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
2313 std::string fname((*f_iter)->get_name());
2314 indent(out) <<
"if self." << fname <<
" is not None:" << endl;
2316 indent(out) <<
"size += getsizeof(self." << fname <<
")" << endl;
2321 "size += sum(map(getsizeof, chain.from_iterable(iter(self." <<
2322 fname <<
".items()))))" << endl;
2326 "size += sum(map(getsizeof, self." << fname <<
"))" << endl;
2331 indent(out) <<
"return size" << endl << endl;
2335 void t_py_generator::generate_py_struct_sizeof(std::ofstream& out,
2337 const vector<t_field*>& fields = tstruct->
get_members();
2338 generate_py_sizeof(out, fields);
2341 void t_py_generator::generate_py_sandesh_sizeof(std::ofstream& out,
2343 const vector<t_field*>& fields = tsandesh->
get_members();
2344 generate_py_sizeof(out, fields);
2347 void t_py_generator::generate_py_sandesh_hint(ofstream& out,
2350 string shints =
"0";
2352 if (has_key_annotation) {
2353 shints +=
" | SANDESH_KEY_HINT";
2356 indent(out) <<
"self._hints = " << shints << endl;
2359 void t_py_generator::generate_py_sandesh_trace(std::ofstream& out,
2363 void t_py_generator::generate_py_sandesh_async(std::ofstream& out,
2367 void t_py_generator::generate_py_sandesh_request(std::ofstream& out,
2370 generate_py_sandesh_http_request_handler(out, tsandesh);
2372 sandesh_req_list_.push_back(tsandesh->
get_name());
2374 generate_py_sandesh_http_request_list(f_http_request_, tsandesh);
2376 generate_py_sandesh_skeleton_request(f_request_impl_, tsandesh);
2379 void t_py_generator::generate_py_sandesh_response(std::ofstream& out,
2383 void t_py_generator::generate_py_sandesh_uve(std::ofstream& out,
2386 const vector<t_field*>& fields = tsandesh->
get_members();
2387 vector<t_field*>::const_iterator f_iter = fields.begin();
2388 assert((*f_iter)->get_name() ==
"data");
2392 out <<
indent() <<
"def update_uve(self, tdata):" << endl;
2394 assert(t->is_struct());
2395 const vector<t_field*>& sfields = ts->get_members();
2396 vector<t_field*>::const_iterator s_iter;
2398 for (s_iter = sfields.begin(); s_iter != sfields.end(); ++s_iter) {
2399 out <<
indent() <<
"if self.data." << (*s_iter)->get_name() <<
" is not None:" << endl;
2401 out <<
indent() <<
"tdata." << (*s_iter)->get_name() <<
" = self.data." <<
2402 (*s_iter)->get_name() << endl;
2405 out <<
indent() <<
"return tdata" << endl;
2407 assert(f_iter == fields.end());
2413 if (sandesh_type->is_sandesh_uve() || sandesh_type->is_sandesh_dynamic_uve()) {
2415 sandesh_uve_list_.push_back(boost::make_tuple(tsandesh->
get_name(),
2417 }
else if (sandesh_type->is_sandesh_alarm()) {
2419 sandesh_alarm_list_.push_back(boost::make_tuple(tsandesh->
get_name(),
2424 void t_py_generator::generate_py_sandesh_uve_list(ofstream& out) {
2425 out << endl << endl;
2426 out <<
"_SANDESH_UVE_LIST = [" << endl;
2427 std::vector<boost::tuple<std::string, std::string> >::const_iterator it;
2428 for (it = sandesh_uve_list_.begin(); it != sandesh_uve_list_.end(); ++it) {
2429 indent(out) <<
"(" << it->get<0>() <<
", " << it->get<1>() <<
")," << endl;
2434 void t_py_generator::generate_py_sandesh_alarm_list(ofstream& out) {
2435 out << endl << endl;
2436 out <<
"_SANDESH_ALARM_LIST = [" << endl;
2437 std::vector<boost::tuple<std::string, std::string> >::const_iterator it;
2438 for (it = sandesh_alarm_list_.begin(); it != sandesh_alarm_list_.end();
2440 indent(out) <<
"(" << it->get<0>() <<
", " << it->get<1>() <<
")," << endl;
2466 "from .ttypes import *" << endl <<
2467 "from thrift.Thrift import TProcessor" << endl <<
2472 "from zope.interface import Interface, implements" << endl <<
2473 "from twisted.internet import defer" << endl <<
2474 "from thrift.transport import TTwisted" << endl;
2497 vector<t_function*>::iterator f_iter;
2500 "# HELPER FUNCTIONS AND STRUCTURES" << endl;
2502 for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
2503 t_struct* ts = (*f_iter)->get_arglist();
2519 result.append(&success);
2523 const vector<t_field*>& fields = xs->
get_members();
2524 vector<t_field*>::const_iterator f_iter;
2525 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
2526 result.append(*f_iter);
2538 string extends =
"";
2539 string extends_if =
"";
2542 extends_if =
"(" + extends +
".Iface)";
2545 extends_if =
"(Interface)";
2547 extends_if =
"(object)";
2552 "class Iface" << extends_if <<
":" << endl;
2556 if (functions.empty()) {
2558 indent() <<
"pass" << endl;
2560 vector<t_function*>::iterator f_iter;
2561 for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
2567 indent() <<
"pass" << endl << endl;
2583 string extends =
"";
2584 string extends_client =
"";
2588 extends_client =
"(" + extends +
".Client)";
2590 extends_client = extends +
".Client, ";
2594 extends_client =
"(object)";
2600 "class Client" << extends_client <<
":" << endl <<
2601 " implements(Iface)" << endl << endl;
2604 "class Client(" << extends_client <<
"Iface):" << endl;
2612 indent() <<
"def __init__(self, transport, oprot_factory):" << endl;
2615 indent() <<
"def __init__(self, iprot, oprot=None):" << endl;
2617 if (extends.empty()) {
2620 indent() <<
" self._transport = transport" << endl <<
2621 indent() <<
" self._oprot_factory = oprot_factory" << endl <<
2622 indent() <<
" self._seqid = 0" << endl <<
2623 indent() <<
" self._reqs = {}" << endl <<
2627 indent() <<
" self._iprot = self._oprot = iprot" << endl <<
2628 indent() <<
" if oprot is not None:" << endl <<
2629 indent() <<
" self._oprot = oprot" << endl <<
2630 indent() <<
" self._seqid = 0" << endl <<
2636 indent() <<
" " << extends <<
".Client.__init__(self, transport, oprot_factory)" << endl <<
2640 indent() <<
" " << extends <<
".Client.__init__(self, iprot, oprot)" << endl <<
2647 vector<t_function*>::const_iterator f_iter;
2648 for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
2649 t_struct* arg_struct = (*f_iter)->get_arglist();
2650 const vector<t_field*>& fields = arg_struct->
get_members();
2651 vector<t_field*>::const_iterator fld_iter;
2652 string funname = (*f_iter)->get_name();
2661 if (!(*f_iter)->is_oneway()) {
2663 "d = self._reqs[self._seqid] = defer.Deferred()" << endl;
2668 "self.send_" << funname <<
"(";
2671 for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) {
2681 if (!(*f_iter)->is_oneway()) {
2686 if (!(*f_iter)->get_returntype()->is_void()) {
2690 "self.recv_" << funname <<
"()" << endl;
2695 indent() <<
"return defer.succeed(None)" << endl;
2706 std::string argsname = (*f_iter)->get_name() +
"_args";
2711 indent() <<
"oprot = self._oprot_factory.getProtocol(self._transport)" << endl <<
2713 "oprot.writeMessageBegin('" << (*f_iter)->get_name() <<
"', TMessageType.CALL, self._seqid)"
2717 indent() <<
"self._oprot.writeMessageBegin('" << (*f_iter)->get_name() <<
"', TMessageType.CALL, self._seqid)" << endl;
2721 indent() <<
"args = " << argsname <<
"()" << endl;
2723 for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) {
2725 indent() <<
"args." << (*fld_iter)->get_name() <<
" = " << (*fld_iter)->get_name() << endl;
2731 indent() <<
"args.write(oprot)" << endl <<
2732 indent() <<
"oprot.writeMessageEnd()" << endl <<
2733 indent() <<
"oprot.trans.flush()" << endl;
2736 indent() <<
"args.write(self._oprot)" << endl <<
2737 indent() <<
"self._oprot.writeMessageEnd()" << endl <<
2738 indent() <<
"self._oprot.trans.flush()" << endl;
2743 if (!(*f_iter)->is_oneway()) {
2744 std::string resultname = (*f_iter)->get_name() +
"_result";
2750 indent() <<
"def recv_" << (*f_iter)->get_name() <<
2751 "(self, iprot, mtype, rseqid):" << endl;
2754 t_function recv_function((*f_iter)->get_returntype(),
2755 string(
"recv_") + (*f_iter)->get_name(),
2766 indent() <<
"d = self._reqs.pop(rseqid)" << endl;
2769 indent() <<
"(fname, mtype, rseqid) = self._iprot.readMessageBegin()" << endl;
2773 indent() <<
"if mtype == TMessageType.EXCEPTION:" << endl <<
2774 indent() <<
" x = TApplicationException()" << endl;
2778 indent() <<
" x.read(iprot)" << endl <<
2779 indent() <<
" iprot.readMessageEnd()" << endl <<
2780 indent() <<
" return d.errback(x)" << endl <<
2781 indent() <<
"result = " << resultname <<
"()" << endl <<
2782 indent() <<
"result.read(iprot)" << endl <<
2783 indent() <<
"iprot.readMessageEnd()" << endl;
2786 indent() <<
" x.read(self._iprot)" << endl <<
2787 indent() <<
" self._iprot.readMessageEnd()" << endl <<
2788 indent() <<
" raise x" << endl <<
2789 indent() <<
"result = " << resultname <<
"()" << endl <<
2790 indent() <<
"result.read(self._iprot)" << endl <<
2791 indent() <<
"self._iprot.readMessageEnd()" << endl;
2795 if (!(*f_iter)->get_returntype()->is_void()) {
2797 indent() <<
"if result.success is not None:" << endl;
2800 indent() <<
" return d.callback(result.success)" << endl;
2803 indent() <<
" return result.success" << endl;
2807 t_struct* xs = (*f_iter)->get_xceptions();
2808 const std::vector<t_field*>& xceptions = xs->
get_members();
2809 vector<t_field*>::const_iterator x_iter;
2810 for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
2812 indent() <<
"if result." << (*x_iter)->get_name() <<
" is not None:" << endl;
2815 indent() <<
" return d.errback(result." << (*x_iter)->get_name() <<
")" << endl;
2819 indent() <<
" raise result." << (*x_iter)->get_name() <<
"" << endl;
2824 if ((*f_iter)->get_returntype()->is_void()) {
2827 "return d.callback(None)" << endl;
2835 indent() <<
"return d.errback(TApplicationException(TApplicationException.MISSING_RESULT, \"" << (*f_iter)->get_name() <<
" failed: unknown result\"))" << endl;
2838 indent() <<
"raise TApplicationException(TApplicationException.MISSING_RESULT, \"" << (*f_iter)->get_name() <<
" failed: unknown result\");" << endl;
2860 vector<t_function*>::iterator f_iter;
2864 f_remote.open(f_remote_name.c_str());
2867 "#!/usr/bin/env python" << endl <<
2869 "import sys" << endl <<
2870 "import pprint" << endl <<
2871 "from urlparse import urlparse" << endl <<
2872 "from thrift.transport import TTransport" << endl <<
2873 "from thrift.transport import TSocket" << endl <<
2874 "from thrift.transport import THttpClient" << endl <<
2875 "from thrift.protocol import TBinaryProtocol" << endl <<
2879 "import " << service_name_ << endl <<
2880 "from .ttypes import *" << endl <<
2884 "if len(sys.argv) <= 1 or sys.argv[1] == '--help':" << endl <<
2885 " print ''" << endl <<
2886 " print 'Usage: ' + sys.argv[0] + ' [-h host[:port]] [-u url] [-f[ramed]] function [arg1 [arg2...]]'" << endl <<
2887 " print ''" << endl <<
2888 " print 'Functions:'" << endl;
2889 for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
2891 " print ' " << (*f_iter)->get_returntype()->get_name() <<
" " << (*f_iter)->get_name() <<
"(";
2892 t_struct* arg_struct = (*f_iter)->get_arglist();
2893 const std::vector<t_field*>& args = arg_struct->
get_members();
2894 vector<t_field*>::const_iterator a_iter;
2895 int num_args = args.size();
2897 for (
int i = 0; i < num_args; ++i) {
2904 args[i]->get_type()->get_name() <<
" " << args[i]->get_name();
2906 f_remote <<
")'" << endl;
2909 " print ''" << endl <<
2910 " sys.exit(0)" << endl <<
2914 "pp = pprint.PrettyPrinter(indent = 2)" << endl <<
2915 "host = 'localhost'" << endl <<
2916 "port = 9090" << endl <<
2917 "uri = ''" << endl <<
2918 "framed = False" << endl <<
2919 "http = False" << endl <<
2920 "argi = 1" << endl <<
2922 "if sys.argv[argi] == '-h':" << endl <<
2923 " parts = sys.argv[argi+1].split(':')" << endl <<
2924 " host = parts[0]" << endl <<
2925 " if len(parts) > 1:" << endl <<
2926 " port = int(parts[1])" << endl <<
2927 " argi += 2" << endl <<
2929 "if sys.argv[argi] == '-u':" << endl <<
2930 " url = urlparse(sys.argv[argi+1])" << endl <<
2931 " parts = url[1].split(':')" << endl <<
2932 " host = parts[0]" << endl <<
2933 " if len(parts) > 1:" << endl <<
2934 " port = int(parts[1])" << endl <<
2936 " port = 80" << endl <<
2937 " uri = url[2]" << endl <<
2938 " if url[4]:" << endl <<
2939 " uri += '?%s' % url[4]" << endl <<
2940 " http = True" << endl <<
2941 " argi += 2" << endl <<
2943 "if sys.argv[argi] == '-f' or sys.argv[argi] == '-framed':" << endl <<
2944 " framed = True" << endl <<
2945 " argi += 1" << endl <<
2947 "cmd = sys.argv[argi]" << endl <<
2948 "args = sys.argv[argi+1:]" << endl <<
2950 "if http:" << endl <<
2951 " transport = THttpClient.THttpClient(host, port, uri)" << endl <<
2953 " socket = TSocket.TSocket(host, port)" << endl <<
2954 " if framed:" << endl <<
2955 " transport = TTransport.TFramedTransport(socket)" << endl <<
2957 " transport = TTransport.TBufferedTransport(socket)" << endl <<
2958 "protocol = TBinaryProtocol.TBinaryProtocol(transport)" << endl <<
2959 "client = " << service_name_ <<
".Client(protocol)" << endl <<
2960 "transport.open()" << endl <<
2966 for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
2973 t_struct* arg_struct = (*f_iter)->get_arglist();
2974 const std::vector<t_field*>& args = arg_struct->
get_members();
2975 vector<t_field*>::const_iterator a_iter;
2976 int num_args = args.size();
2979 "if cmd == '" << (*f_iter)->get_name() <<
"':" << endl <<
2980 " if len(args) != " << num_args <<
":" << endl <<
2981 " print '" << (*f_iter)->get_name() <<
" requires " << num_args <<
" args'" << endl <<
2982 " sys.exit(1)" << endl <<
2983 " pp.pprint(client." << (*f_iter)->get_name() <<
"(";
2984 for (
int i = 0; i < num_args; ++i) {
2985 if (args[i]->get_type()->is_string()) {
2986 f_remote <<
"args[" << i <<
"],";
2988 f_remote <<
"eval(args[" << i <<
"]),";
2991 f_remote <<
"))" << endl;
2995 f_remote <<
"else:" << endl;
2996 f_remote <<
" print 'Unrecognized method %s' % cmd" << endl;
2997 f_remote <<
" sys.exit(1)" << endl;
3000 f_remote <<
"transport.close()" << endl;
3008 chmod(f_remote_name.c_str(),
3031 vector<t_function*>::iterator f_iter;
3033 string extends =
"";
3034 string extends_processor =
"";
3037 extends_processor = extends +
".Processor, ";
3043 "class Processor(" << extends_processor <<
"TProcessor):" << endl <<
3044 " implements(Iface)" << endl << endl;
3047 "class Processor(" << extends_processor <<
"Iface, TProcessor):" << endl;
3053 "def __init__(self, handler):" << endl;
3055 if (extends.empty()) {
3058 indent() <<
"self._handler = Iface(handler)" << endl;
3061 indent() <<
"self._handler = handler" << endl;
3065 indent() <<
"self._processMap = {}" << endl;
3069 indent() << extends <<
".Processor.__init__(self, Iface(handler))" << endl;
3072 indent() << extends <<
".Processor.__init__(self, handler)" << endl;
3075 for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
3077 indent() <<
"self._processMap[\"" << (*f_iter)->get_name() <<
"\"] = Processor.process_" << (*f_iter)->get_name() << endl;
3084 "def process(self, iprot, oprot):" << endl;
3088 indent() <<
"(name, type, seqid) = iprot.readMessageBegin()" << endl;
3094 indent() <<
"if name not in self._processMap:" << endl <<
3095 indent() <<
" iprot.skip(TType.STRUCT)" << endl <<
3096 indent() <<
" iprot.readMessageEnd()" << endl <<
3097 indent() <<
" x = TApplicationException(TApplicationException.UNKNOWN_METHOD, 'Unknown function %s' % (name))" << endl <<
3098 indent() <<
" oprot.writeMessageBegin(name, TMessageType.EXCEPTION, seqid)" << endl <<
3099 indent() <<
" x.write(oprot)" << endl <<
3100 indent() <<
" oprot.writeMessageEnd()" << endl <<
3101 indent() <<
" oprot.trans.flush()" << endl;
3105 indent() <<
" return defer.succeed(None)" << endl;
3108 indent() <<
" return" << endl;
3112 indent() <<
"else:" << endl;
3116 indent() <<
" return self._processMap[name](self, seqid, iprot, oprot)" << endl;
3119 indent() <<
" self._processMap[name](self, seqid, iprot, oprot)" << endl;
3123 indent() <<
"return True" << endl;
3130 for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
3148 "def process_" << tfunction->
get_name() <<
3149 "(self, seqid, iprot, oprot):" << endl;
3152 string argsname = tfunction->
get_name() +
"_args";
3153 string resultname = tfunction->
get_name() +
"_result";
3156 indent() <<
"args = " << argsname <<
"()" << endl <<
3157 indent() <<
"args.read(iprot)" << endl <<
3158 indent() <<
"iprot.readMessageEnd()" << endl;
3161 const std::vector<t_field*>& xceptions = xs->
get_members();
3162 vector<t_field*>::const_iterator x_iter;
3167 indent() <<
"result = " << resultname <<
"()" << endl;
3173 const std::vector<t_field*>& fields = arg_struct->
get_members();
3174 vector<t_field*>::const_iterator f_iter;
3177 indent() <<
"d = defer.maybeDeferred(self._handler." <<
3180 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
3186 f_service_ <<
"args." << (*f_iter)->get_name();
3193 indent() <<
"return d" << endl;
3201 "d.addCallback(self.write_results_success_" <<
3202 tfunction->
get_name() <<
", result, seqid, oprot)" << endl;
3204 if (xceptions.size() > 0) {
3207 "d.addErrback(self.write_results_exception_" <<
3208 tfunction->
get_name() <<
", result, seqid, oprot)" << endl;
3212 indent() <<
"return d" << endl;
3218 "def write_results_success_" << tfunction->
get_name() <<
3219 "(self, success, result, seqid, oprot):" << endl;
3222 indent() <<
"result.success = success" << endl <<
3223 indent() <<
"oprot.writeMessageBegin(\"" << tfunction->
get_name() <<
3224 "\", TMessageType.REPLY, seqid)" << endl <<
3225 indent() <<
"result.write(oprot)" << endl <<
3226 indent() <<
"oprot.writeMessageEnd()" << endl <<
3227 indent() <<
"oprot.trans.flush()" << endl;
3232 if (!tfunction->
is_oneway() && xceptions.size() > 0) {
3234 "def write_results_exception_" << tfunction->
get_name() <<
3235 "(self, error, result, seqid, oprot):" << endl;
3238 indent() <<
"try:" << endl;
3242 indent() <<
" error.raiseException()" << endl;
3243 for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
3245 indent() <<
"except " <<
type_name((*x_iter)->get_type()) <<
", " << (*x_iter)->get_name() <<
":" << endl;
3249 indent() <<
"result." << (*x_iter)->get_name() <<
" = " << (*x_iter)->get_name() << endl;
3253 indent() <<
"pass" << endl;
3257 indent() <<
"oprot.writeMessageBegin(\"" << tfunction->
get_name() <<
3258 "\", TMessageType.REPLY, seqid)" << endl <<
3259 indent() <<
"result.write(oprot)" << endl <<
3260 indent() <<
"oprot.writeMessageEnd()" << endl <<
3261 indent() <<
"oprot.trans.flush()" << endl;
3268 if (xceptions.size() > 0) {
3270 indent() <<
"try:" << endl;
3276 const std::vector<t_field*>& fields = arg_struct->
get_members();
3277 vector<t_field*>::const_iterator f_iter;
3284 "self._handler." << tfunction->
get_name() <<
"(";
3286 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
3292 f_service_ <<
"args." << (*f_iter)->get_name();
3296 if (!tfunction->
is_oneway() && xceptions.size() > 0) {
3298 for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
3300 indent() <<
"except " <<
type_name((*x_iter)->get_type()) <<
", " << (*x_iter)->get_name() <<
":" << endl;
3304 indent() <<
"result." << (*x_iter)->get_name() <<
" = " << (*x_iter)->get_name() << endl;
3308 indent() <<
"pass" << endl;
3316 indent() <<
"return" << endl;
3323 indent() <<
"oprot.writeMessageBegin(\"" << tfunction->
get_name() <<
"\", TMessageType.REPLY, seqid)" << endl <<
3324 indent() <<
"result.write(oprot)" << endl <<
3325 indent() <<
"oprot.writeMessageEnd()" << endl <<
3326 indent() <<
"oprot.trans.flush()" << endl;
3345 throw "CANNOT GENERATE DESERIALIZE CODE FOR void TYPE: " +
3349 string name = prefix + tfield->
get_name();
3360 "(length, " << name <<
") = iprot.";
3362 name <<
" = iprot.";
3368 throw "compiler error: cannot serialize void field in a struct: " +
3373 case t_base_type::TYPE_STATIC_CONST_STRING:
3376 out <<
"readString();";
3378 out <<
"readString().decode('utf-8')";
3382 case t_base_type::TYPE_XML:
3383 out <<
"readXML();";
3385 case t_base_type::TYPE_UUID:
3386 out <<
"readUUID();";
3390 out <<
"readBool();";
3393 out <<
"readByte();";
3396 out <<
"readI16();";
3399 out <<
"readI32();";
3402 out <<
"readI64();";
3405 case t_base_type::TYPE_U16:
3406 out <<
"readU16();";
3408 case t_base_type::TYPE_U32:
3409 out <<
"readU32();";
3411 case t_base_type::TYPE_U64:
3412 out <<
"readU64();";
3414 case t_base_type::TYPE_IPV4:
3415 out <<
"readIPV4();";
3417 case t_base_type::TYPE_IPADDR:
3418 out <<
"readIPADDR()";
3422 out <<
"readDouble();";
3428 out <<
"readI32();";
3432 indent(out) <<
"if length < 0: return -1" << endl;
3433 indent(out) <<
"read_cnt += length" << endl;
3436 printf(
"DO NOT KNOW HOW TO DESERIALIZE FIELD '%s' TYPE '%s'\n",
3450 indent() <<
"read_cnt += " << prefix <<
".read(iprot)" << endl;
3452 indent() << prefix <<
".read(iprot)" << endl;
3463 string size =
tmp(
"_size");
3464 string ktype =
tmp(
"_ktype");
3465 string vtype =
tmp(
"_vtype");
3466 string etype =
tmp(
"_etype");
3476 indent() << prefix <<
" = {}" << endl <<
3478 indent() <<
"(length, " << ktype <<
", " << vtype <<
", " << size <<
" ) = iprot.readMapBegin() " << endl <<
3479 indent() <<
"read_cnt += length" << endl;
3481 indent() <<
"(" << ktype <<
", " << vtype <<
", " << size <<
" ) = iprot.readMapBegin() " << endl;
3483 }
else if (ttype->
is_set()) {
3485 indent() << prefix <<
" = set()" << endl <<
3487 indent() <<
"(length, " << etype <<
", " << size <<
") = iprot.readSetBegin()" << endl <<
3488 indent() <<
"read_cnt += length" << endl;
3490 indent() <<
"(" << etype <<
", " << size <<
") = iprot.readSetBegin()" << endl;
3492 }
else if (ttype->
is_list()) {
3494 indent() << prefix <<
" = []" << endl <<
3496 indent() <<
"(length, " << etype <<
", " << size <<
") = iprot.readListBegin()" << endl <<
3497 indent() <<
"read_cnt += length" << endl;
3499 indent() <<
"(" << etype <<
", " << size <<
") = iprot.readListBegin()" << endl;
3504 string i =
tmp(
"_i");
3506 "for " << i <<
" in range(" << size <<
"):" << endl;
3512 }
else if (ttype->
is_set()) {
3516 indent(out) <<
"read_cnt += iprot.readContainerElementBegin()" << endl;
3522 indent(out) <<
"read_cnt += iprot.readContainerElementEnd()" << endl;
3525 }
else if (ttype->
is_list()) {
3529 indent(out) <<
"read_cnt += iprot.readContainerElementBegin()" << endl;
3535 indent(out) <<
"read_cnt += iprot.readContainerElementEnd()" << endl;
3545 indent(out) <<
"read_cnt += iprot.readMapEnd()" << endl;
3547 indent(out) <<
"iprot.readMapEnd()" << endl;
3549 }
else if (ttype->
is_set()) {
3551 indent(out) <<
"read_cnt += iprot.readSetEnd()" << endl;
3553 indent(out) <<
"iprot.readSetEnd()" << endl;
3555 }
else if (ttype->
is_list()) {
3557 indent(out) <<
"read_cnt += iprot.readListEnd()" << endl;
3559 indent(out) <<
"iprot.readListEnd()" << endl;
3571 string key =
tmp(
"_key");
3572 string val =
tmp(
"_val");
3578 if (kttype->is_base_type() || kttype->is_enum()) {
3579 indent(out) <<
"read_cnt += iprot.readContainerElementBegin()" << endl;
3584 if (kttype->is_base_type() || kttype->is_enum()) {
3585 indent(out) <<
"read_cnt += iprot.readContainerElementEnd()" << endl;
3592 indent(out) <<
"read_cnt += iprot.readContainerElementBegin()" << endl;
3598 indent(out) <<
"read_cnt += iprot.readContainerElementEnd()" << endl;
3603 prefix <<
"[" << key <<
"] = " << val << endl;
3612 string elem =
tmp(
"_elem");
3618 prefix <<
".add(" << elem <<
")" << endl;
3627 string elem =
tmp(
"_elem");
3633 prefix <<
".append(" << elem <<
")" << endl;
3650 throw "CANNOT GENERATE SERIALIZE CODE FOR void TYPE: " +
3664 string name = prefix + tfield->
get_name();
3674 "compiler error: cannot serialize void field in a struct: " + name;
3678 case t_base_type::TYPE_STATIC_CONST_STRING:
3681 out <<
"writeString(" << name <<
")";
3683 out <<
"writeString(" << name <<
".encode('utf-8'))";
3687 case t_base_type::TYPE_XML:
3688 out <<
"writeXML(" << name <<
")";
3690 case t_base_type::TYPE_UUID:
3691 out <<
"writeUUID(" << name <<
")";
3695 out <<
"writeBool(" << name <<
")";
3698 out <<
"writeByte(" << name <<
")";
3701 out <<
"writeI16(" << name <<
")";
3704 out <<
"writeI32(" << name <<
")";
3707 out <<
"writeI64(" << name <<
")";
3710 case t_base_type::TYPE_U16:
3711 out <<
"writeU16(" << name <<
")";
3713 case t_base_type::TYPE_U32:
3714 out <<
"writeU32(" << name <<
")";
3716 case t_base_type::TYPE_U64:
3717 out <<
"writeU64(" << name <<
")";
3719 case t_base_type::TYPE_IPV4:
3720 out <<
"writeIPV4(" << name <<
")";
3722 case t_base_type::TYPE_IPADDR:
3723 out <<
"writeIPADDR(" << name <<
")";
3727 out <<
"writeDouble(" << name <<
")";
3733 out <<
"writeI32(" << name <<
")";
3735 out <<
" < 0: return -1" << endl;
3737 }
else if (type->is_sandesh()) {
3738 generate_serialize_sandesh(out, (
t_sandesh*)type,
3742 printf(
"DO NOT KNOW HOW TO SERIALIZE FIELD '%s%s' TYPE '%s'\n",
3760 "if " << prefix <<
".write(oprot) < 0: return -1" << endl;
3770 void t_py_generator::generate_serialize_sandesh(ofstream &out,
3775 "if " << prefix <<
".write(oprot) < 0: return -1" << endl;
3784 "if oprot.writeMapBegin(" <<
3787 "len(" << prefix <<
")) < 0: return -1" << endl;
3788 }
else if (ttype->
is_set()) {
3790 "if oprot.writeSetBegin(" <<
3792 "len(" << prefix <<
")) < 0: return -1" << endl;
3793 }
else if (ttype->
is_list()) {
3795 "if oprot.writeListBegin(" <<
3797 "len(" << prefix <<
")) < 0: return -1" << endl;
3801 string kiter =
tmp(
"kiter");
3802 string viter =
tmp(
"viter");
3804 "for " << kiter <<
"," << viter <<
" in " << prefix <<
".items():" << endl;
3808 }
else if (ttype->
is_set()) {
3809 string iter =
tmp(
"iter");
3811 "for " << iter <<
" in " << prefix <<
":" << endl;
3816 indent(out) <<
"if oprot.writeContainerElementBegin() < 0: return -1" << endl;
3822 indent(out) <<
"if oprot.writeContainerElementEnd() < 0: return -1" << endl;
3826 }
else if (ttype->
is_list()) {
3827 string iter =
tmp(
"iter");
3829 "for " << iter <<
" in " << prefix <<
":" << endl;
3834 indent(out) <<
"if oprot.writeContainerElementBegin() < 0: return -1" << endl;
3840 indent(out) <<
"if oprot.writeContainerElementEnd() < 0: return -1" << endl;
3848 "if oprot.writeMapEnd() < 0: return -1" << endl;
3849 }
else if (ttype->
is_set()) {
3851 "if oprot.writeSetEnd() < 0: return -1" << endl;
3852 }
else if (ttype->
is_list()) {
3854 "if oprot.writeListEnd() < 0: return -1" << endl;
3869 indent(out) <<
"if oprot.writeContainerElementBegin() < 0: return -1" << endl;
3876 indent(out) <<
"if oprot.writeContainerElementEnd() < 0: return -1" << endl;
3883 indent(out) <<
"if oprot.writeContainerElementBegin() < 0: return -1" << endl;
3890 indent(out) <<
"if oprot.writeContainerElementEnd() < 0: return -1" << endl;
3937 const char* subheader) {
3938 bool has_doc =
false;
3945 const vector<t_field*>& fields = tstruct->
get_members();
3946 if (fields.size() > 0) {
3951 ss << subheader <<
":\n";
3952 vector<t_field*>::const_iterator p_iter;
3953 for (p_iter = fields.begin(); p_iter != fields.end(); ++p_iter) {
3991 std::ostringstream result;
3992 result << tfield->
get_name() <<
"=";
3994 result <<
"thrift_spec[" <<
3999 return result.str();
4039 string signature = prefix + tfunction->
get_name() +
"(";
4041 signature +=
"self, ";
4054 const vector<t_field*>& fields = tstruct->
get_members();
4055 vector<t_field*>::const_iterator f_iter;
4057 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
4063 result += (*f_iter)->get_name();
4073 if (program != NULL && program !=
program_) {
4089 throw "NO T_VOID CONSTRUCT";
4091 return "TType.STRING";
4093 return "TType.BOOL";
4095 return "TType.BYTE";
4103 return "TType.DOUBLE";
4105 case t_base_type::TYPE_XML:
4107 case t_base_type::TYPE_UUID:
4108 return "TType.UUID";
4109 case t_base_type::TYPE_U16:
4111 case t_base_type::TYPE_U32:
4113 case t_base_type::TYPE_U64:
4115 case t_base_type::TYPE_IPV4:
4116 return "TType.IPV4";
4117 case t_base_type::TYPE_IPADDR:
4118 return "TType.IPADDR";
4119 case t_base_type::TYPE_STATIC_CONST_STRING:
4120 return "TType.STRING";
4121 case t_base_type::TYPE_SANDESH_SYSTEM:
4122 return "TType.STRING";
4123 case t_base_type::TYPE_SANDESH_REQUEST:
4124 return "TType.STRING";
4125 case t_base_type::TYPE_SANDESH_RESPONSE:
4126 return "TType.STRING";
4127 case t_base_type::TYPE_SANDESH_TRACE:
4128 return "TType.STRING";
4129 case t_base_type::TYPE_SANDESH_TRACE_OBJECT:
4130 return "TType.STRING";
4131 case t_base_type::TYPE_SANDESH_BUFFER:
4132 return "TTytpe.STRING";
4133 case t_base_type::TYPE_SANDESH_UVE:
4134 return "TTytpe.STRING";
4135 case t_base_type::TYPE_SANDESH_DYNAMIC_UVE:
4136 return "TTytpe.STRING";
4137 case t_base_type::TYPE_SANDESH_ALARM:
4138 return "TTytpe.STRING";
4139 case t_base_type::TYPE_SANDESH_OBJECT:
4140 return "TTytpe.STRING";
4141 case t_base_type::TYPE_SANDESH_FLOW:
4142 return "TTytpe.STRING";
4143 case t_base_type::TYPE_SANDESH_SESSION:
4144 return "TTytpe.STRING";
4150 return "TType.STRUCT";
4152 }
else if (type->is_sandesh()) {
4153 return "TType.SANDESH";
4155 }
else if (type->
is_map()) {
4157 }
else if (type->
is_set()) {
4160 return "TType.LIST";
4163 throw "INVALID TYPE IN type_to_enum: " + type->
get_name();
4169 ttype = ((
t_typedef*)ttype)->get_type();
4176 }
else if (ttype->
is_map()) {
4184 }
else if (ttype->
is_set()) {
4190 }
else if (ttype->
is_list()) {
4197 throw "INVALID TYPE IN type_to_spec_args: " + ttype->
get_name();
4202 " new_style: Generate new-style classes.\n" \
4203 " twisted: Generate Twisted-friendly RPC services.\n" \
4204 " utf8strings: Encode/decode strings using utf8 in the generated code.\n" \
4205 " slots: Generate code using slots for instance members.\n" \
4206 " dynamic: Generate dynamic code, less code generated but slower.\n" \
4207 " dynbase=CLS Derive generated classes from class CLS instead of TBase.\n" \
4208 " dynexc=CLS Derive generated exceptions from CLS instead of TExceptionBase.\n" \
4209 " dynimport='from foo.bar import CLS'\n" \
4210 " Add an import line to generated code to find the dynbase class.\n")
virtual bool is_xception() const
const std::string & get_name() const
std::string type_name(t_type *ttype)
void generate_serialize_set_element(std::ofstream &out, t_set *tmap, std::string iter)
static bool is_valid_namespace(const std::string &sub_namespace)
std::string tmp(std::string name)
void generate_deserialize_map_element(std::ofstream &out, t_map *tmap, std::string prefix="")
void generate_py_struct_definition(std::ofstream &out, t_struct *tstruct, bool is_xception=false, bool is_result=false)
void generate_service(t_service *tservice)
std::string future_imports()
static std::string t_base_name(t_base tbase)
const std::string & get_name() const
const uint32_t get_4byte_fingerprint() const
std::string type_to_spec_args(t_type *ttype)
virtual bool is_map() const
const std::string & get_name() const
void generate_deserialize_list_element(std::ofstream &out, t_list *tlist, std::string prefix="")
void generate_deserialize_field(std::ofstream &out, t_field *tfield, std::string prefix="", bool inclass=false)
std::string type_to_enum(t_type *ttype)
const members_type & get_sorted_members()
virtual bool is_enum() const
t_type * get_type() const
virtual bool is_base_type() const
void generate_py_struct_required_validator(std::ofstream &out, t_struct *tstruct)
void generate_service_helpers(t_service *tservice)
void generate_python_docstring(std::ofstream &out, t_struct *tstruct)
std::string gen_dynbaseclass_
t_py_generator(t_program *program, const std::map< std::string, std::string > &parsed_options, const std::string &option_string)
t_type * get_returntype() const
const std::map< t_const_value *, t_const_value * > & get_map() const
const members_type & get_members()
int64_t get_integer() const
t_type * get_key_type() const
void generate_py_function_helpers(t_function *tfunction)
std::string service_name_
t_const_value_type get_type() const
void generate_service_interface(t_service *tservice)
virtual bool is_container() const
void generate_serialize_map_element(std::ofstream &out, t_map *tmap, std::string kiter, std::string viter)
virtual bool is_typedef() const
t_type * get_type() const
t_struct * get_xceptions() const
t_type * get_elem_type() const
void generate_deserialize_container(std::ofstream &out, t_type *ttype, std::string prefix="")
void generate_struct(t_struct *tstruct)
void generate_service_server(t_service *tservice)
virtual bool is_set() const
void generate_deserialize_set_element(std::ofstream &out, t_set *tset, std::string prefix="")
std::string gen_dynbaseclass_exc_
std::string get_name() const
void generate_serialize_field(std::ofstream &out, t_field *tfield, std::string prefix="")
virtual bool is_void() const
void generate_typedef(t_typedef *ttypedef)
t_const_value * get_value() const
void generate_deserialize_struct(std::ofstream &out, t_struct *tstruct, std::string prefix="")
t_type * get_elem_type() const
void generate_xception(t_struct *txception)
t_type * get_val_type() const
std::string argument_list(t_struct *tstruct)
void generate_process_function(t_service *tservice, t_function *tfunction)
const std::vector< t_function * > & get_functions() const
std::string copy_options_
void generate_service_client(t_service *tservice)
virtual const std::string & get_name() const
std::string declare_argument(t_field *tfield)
virtual bool is_list() const
virtual bool has_key_annotation() const
const std::vector< t_enum_value * > & get_constants()
void generate_serialize_struct(std::ofstream &out, t_struct *tstruct, std::string prefix="")
std::string get_string() const
static t_type * get_true_type(t_type *type)
double get_double() const
const std::string & get_namespace() const
t_program * get_program()
virtual bool is_struct() const
t_service * get_extends()
void generate_serialize_list_element(std::ofstream &out, t_list *tlist, std::string iter)
const std::string & get_doc() const
const t_type * get_type()
std::string function_signature(t_function *tfunction, std::string prefix="")
void generate_py_struct_reader(std::ofstream &out, t_struct *tstruct)
std::string render_field_default_value(t_field *tfield)
std::string import_dynbase_
void generate_service_remote(t_service *tservice)
std::string function_signature_if(t_function *tfunction, std::string prefix="")
std::string render_fastbinary_includes()
std::string render_includes()
t_const_value * get_value()
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 std::string get_real_py_module(const t_program *program, bool gen_twisted)
std::string render_const_value(t_type *type, t_const_value *value)
std::string py_autogen_comment()
void generate_enum(t_enum *tenum)
virtual bool is_service() const
void generate_serialize_container(std::ofstream &out, t_type *ttype, std::string prefix="")
void generate_py_struct(t_struct *tstruct, bool is_exception)
void generate_const(t_const *tconst)
void generate_py_struct_writer(std::ofstream &out, t_struct *tstruct)
#define THRIFT_REGISTER_GENERATOR(language, long_name, doc)
const std::vector< t_const_value * > & get_list() const
t_struct * get_arglist() const