SpEntity.cpp 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604
  1. #include "stdafx.h"
  2. #include "SpBase.h"
  3. #include "SpTimer.h"
  4. #include "SpMisc.h"
  5. #include "SpHelper.h"
  6. #include "SpBinaryPersistStream.h"
  7. #include "SpEntity.h"
  8. #include "SpModule.h"
  9. #include "SpAsyncWait.h"
  10. #include "SpClientSessionFunction.h"
  11. #include "SpServerSessionFunction.h"
  12. #include "sp_iom.h"
  13. #include "sp_svc.h"
  14. #include "sp_log.h"
  15. #include "sp_var.h"
  16. #include "sp_def.h"
  17. #include "sp_cfg.h"
  18. #include "sp_env.h"
  19. #include "sp_btr.h"
  20. #include "memutil.h"
  21. #include "strutil.h"
  22. #include "fileutil.h"
  23. #include "shm_array.h"
  24. #include "toolkit.h"
  25. #include "dbgutil.h"
  26. #include "def.h"
  27. #ifdef _WIN32
  28. #include "CodeSignVerify.h"
  29. #include "sp_checkEntity.h"
  30. #else
  31. #include "sp_dbg_export.h"
  32. #endif //_WIN32
  33. #include "sp_httpDefine.h"
  34. #include <iostream>
  35. #include <sstream>
  36. static void var_callback(sp_var_listener_t *listener,
  37. const char *key,
  38. const char *oldstr,
  39. const char *newstr,
  40. int client_id,
  41. void *user_data)
  42. {
  43. ISysVarListener *pListener = (ISysVarListener *)user_data;
  44. SpEntity *pEntity = (SpEntity*)sp_var_listener_get_tag(listener);
  45. #ifdef _WIN32
  46. SetthreadGroup(GetCurrentThreadId(), pEntity->get_cfg_ent()->name);
  47. getEntityResource()->m_Entity = pEntity;
  48. #else
  49. GetSpModule()->SetThreadEntity(pEntity);
  50. #endif //_WIN32
  51. sp_env_t *env = sp_get_env();
  52. sp_entity_t *ent = sp_mod_mgr_find_entity_by_idx(env->mod_mgr, client_id);
  53. if (ent) {
  54. if(strcmp(VAR_RSERVERD_KEY_TERM_STATE, key) != 0)
  55. pListener->OnSysVarEvent(key, newstr, oldstr, ent->cfg->name);
  56. else {
  57. AppBootStateEnum oldState = static_cast<AppBootStateEnum>(atoi(oldstr));
  58. AppBootStateEnum newState = static_cast<AppBootStateEnum>(atoi(newstr));
  59. (static_cast<ITerminalStateChangedListener*>(user_data))->OnStateChanged(oldState, newState, ent->cfg->name);
  60. }
  61. }
  62. else {
  63. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("cannot found the entity by id: %d", client_id);
  64. }
  65. }
  66. static void bcm_callback(sp_bcm_listener_t *listener,
  67. int from_client_id,
  68. int message_id,
  69. int message_sig,
  70. const void *buf,
  71. int len,
  72. void *user_data)
  73. {
  74. IBroadcastListener *pListener = (IBroadcastListener *)user_data;
  75. SpEntity *pEntity = (SpEntity*)sp_bcm_listener_get_tag(listener);
  76. sp_uid_t uid;
  77. #ifdef _WIN32
  78. SetthreadGroup(GetCurrentThreadId(), pEntity->get_cfg_ent()->name);
  79. getEntityResource()->m_Entity = pEntity;
  80. #else
  81. GetSpModule()->SetThreadEntity(pEntity);
  82. #endif //_WIN32
  83. sp_bcm_listener_get_uid(listener, &uid);
  84. sp_env_t *env = sp_get_env();
  85. sp_entity_t *ent = sp_mod_mgr_find_entity_by_idx(env->mod_mgr, from_client_id);
  86. if (ent) {
  87. CAutoBuffer Buf;
  88. Buf.Init(len);
  89. if (len > 0) {
  90. memcpy(&Buf[0], buf, len);
  91. }
  92. pListener->OnBroadcastEvent(CUUID(uid), ent->cfg->name, (DWORD)message_id, (DWORD)message_sig, Buf);
  93. }
  94. }
  95. static void on_log(void *inst,
  96. int nsub,
  97. u__int64_t *sub,
  98. int client_id,
  99. int log_epid,
  100. int client_instance_id,
  101. u__int64_t log_id,
  102. u__int64_t prev_rsn,
  103. u__int64_t curr_rsn,
  104. int original_rsn_type,
  105. int rsn_depth,
  106. unsigned int log_time,
  107. int log_type,
  108. int log_severity,
  109. int log_sys_error,
  110. int log_usr_error,
  111. int param_cnt,
  112. int *params,
  113. const char *msg,
  114. void *user_data,
  115. const char* bussId, const char* traceId, const char* spanId, const char* parentSpanId)
  116. {
  117. try
  118. {
  119. ILogListener *pListener = (ILogListener *)user_data;
  120. sp_entity_t *ent = sp_mod_mgr_find_entity_by_idx(sp_get_env()->mod_mgr, client_id);
  121. if (ent) {
  122. int i;
  123. CAutoArray<DWORD> arr;
  124. arr.Init(param_cnt);
  125. for (i = 0; i < param_cnt; ++i) {
  126. arr[i] = (DWORD)params[i];
  127. }
  128. CAutoArray<CUUID> subIDs;
  129. subIDs.Init(nsub);
  130. CUUID *pSub = (CUUID*)sub;
  131. for (i = 0; i < nsub; i++)
  132. subIDs[i] = pSub[i];
  133. linkContext cur;
  134. cur.Init(bussId, traceId, spanId, parentSpanId);
  135. pListener->OnLog(subIDs,
  136. CUUID(log_id), (LogTypeEnum)log_type, (SeverityLevelEnum)log_severity, log_sys_error, log_usr_error,
  137. ent->instance_id, ent->cfg->devel_id,
  138. arr, ent->cfg->name, ent->mod->cfg->name, msg, cur);
  139. }
  140. }
  141. catch (const std::exception& ex)
  142. {
  143. DbgWithLink(LOG_LEVEL_FATAL, LOG_TYPE_SYSTEM)("Exception occurs: %s at <%s>[%d]{%s}", ex.what(), __FUNCTION__, __LINE__, _GetFileName(__FILE__));
  144. //std::terminate();
  145. }
  146. }
  147. static void task_callback(threadpool_t *threadpool, void *arg, param_size_t param1, param_size_t param2)
  148. {
  149. ITaskSp *pTask = (ITaskSp*)arg;
  150. SpEntity *pEntity = (SpEntity*)param1;
  151. #ifdef _WIN32
  152. SetthreadGroup(GetCurrentThreadId(), pEntity->GetEntityBase()->GetEntityName());
  153. try {
  154. getEntityResource()->m_Entity = pEntity;
  155. pTask->Process();
  156. pTask->DecRef();
  157. }
  158. catch (...)
  159. {
  160. DbgWithLink(LOG_LEVEL_FATAL, LOG_TYPE_SYSTEM)("Exception occurs at <%s>[%d]{%s}", __FUNCTION__, __LINE__, _GetFileName(__FILE__));
  161. //std::terminate();
  162. }
  163. #else
  164. GetSpModule()->SetThreadEntity(pEntity);
  165. pTask->Process();
  166. pTask->DecRef();
  167. #endif //_WIN32
  168. }
  169. static void tpool_log(threadpool_t *threadpool, const char* str)
  170. {
  171. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)(str);
  172. }
  173. static ErrorCodeEnum GetEntityStaticInfo(CEntityStaticInfo &Info, sp_entity_t *ent)
  174. {
  175. sp_env_t *env = sp_get_env();
  176. if (ent) {
  177. bool bStartedByShell = false;
  178. for (int i = 0; i < env->cfg->shell_ini->arr_startlist->nelts; ++i) {
  179. sp_cfg_shell_entity_t * tmp_ent = ARRAY_IDX(env->cfg->shell_ini->arr_startlist, i, sp_cfg_shell_entity_t*);
  180. if (tmp_ent->idx == ent->cfg->idx) {
  181. bStartedByShell = true;
  182. break;
  183. }
  184. }
  185. Info.wEntityDevelopID = ent->cfg->devel_id;
  186. Info.strSpFileName = ent->mod->cfg->name;
  187. Info.bStartedByShell = bStartedByShell;
  188. Info.bIndispensable = true;
  189. Info.bHasPrivilege = !!ent->cfg->privilege;
  190. Info.version = CVersion(ent->cfg->version.major, ent->cfg->version.minor,
  191. ent->cfg->version.revision, ent->cfg->version.build);
  192. } else {
  193. return Error_NotExist;
  194. }
  195. return Error_Succeed;
  196. }
  197. SpEntity::SpEntity(SpModule *pModule, sp_entity_t *ent, sp_cfg_shell_entity_t *cfg_ent, CEntityBase *pEntityBase)
  198. : m_pModule(pModule), m_pEntityBase(pEntityBase), m_pTimerList(NULL), m_svc(NULL), m_var_client(NULL), m_log_client(NULL),
  199. m_ent(ent), m_cfg_ent(cfg_ent), m_tbs(NULL), m_bcm_client(NULL), m_arr_any_var(NULL), m_arr_bcm_listener(NULL), m_log_mgr(NULL)
  200. {
  201. if (m_ent != nullptr && m_pEntityBase != nullptr) {
  202. m_ent->service_flag = m_pEntityBase->IsService() ? 1 : 0;
  203. }
  204. memset(&m_arr_var[0], 0, sizeof(m_arr_var));
  205. }
  206. SpEntity::~SpEntity()
  207. {
  208. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("run ~SpEntity()");
  209. if (m_ent != nullptr && m_pEntityBase != nullptr) {
  210. #ifdef _WIN32
  211. getEntityResource()->m_Entity = NULL;
  212. #endif //_WIN32
  213. }
  214. }
  215. ErrorCodeEnum SpEntity::Init()
  216. {
  217. sp_mod_entity_stub_cb cb;
  218. int rc;
  219. threadpool_t *threadpool;
  220. rc = sp_svc_create(m_pModule->get_iom(), 0, m_ent->cfg->idx,m_ent->cfg->devel_id, &m_svc); //threadpool
  221. if (rc != 0) {
  222. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create svc failed!");
  223. return SpTranslateError(rc);
  224. }
  225. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create svc ok!");
  226. threadpool = sp_svc_get_threadpool(m_svc);
  227. threadpool_set_thread_decorator(threadpool, &SpEntity::__on_thread_init, &SpEntity::__on_thread_term, this); //Entity thread
  228. threadpool_create(&m_tpool);
  229. threadpool_set_log(m_tpool, &tpool_log);
  230. threadpool_set_thread_decorator(m_tpool, &SpEntity::__on_thread_init, &SpEntity::__on_thread_term, this);
  231. threadpool_start(m_tpool, 0, 64, 5*60*1000, 0);
  232. #ifdef _WIN32
  233. setModuleAliasName(GetEntityBase()->GetEntityName());
  234. #endif //_WIN32
  235. rc = sp_svc_start(m_svc);
  236. if (rc != 0) {
  237. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("start svc failed!");
  238. return SpTranslateError(rc);
  239. }
  240. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("start svc ok!");
  241. m_pTimerList = SpTimerListCreate(this);
  242. if (!m_pTimerList) {
  243. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create timer list failed!");
  244. return Error_Unexpect;
  245. }
  246. ResetEntityLastError();
  247. cb.on_entity_prestart = &SpEntity::__on_entity_prestart;
  248. cb.on_entity_stop = &SpEntity::__on_entity_stop;
  249. cb.on_entity_prepause = &SpEntity::__on_entity_prepause;
  250. cb.on_entity_test = &SpEntity::__on_entity_test;
  251. cb.on_entity_precontinue = &SpEntity::__on_entity_precontinue;
  252. cb.on_entity_redirect_subscribe = &SpEntity::__on_entity_redirect_subscribe;
  253. cb.user_data = this;
  254. rc = sp_mod_entity_stub_create(&cb, m_svc, &m_stub); //add a workItem mod_entity_on_pkt
  255. if (rc != 0) {
  256. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create entity stub failed!");
  257. return SpTranslateError(rc);
  258. }
  259. sp_rpc_client_mgr_callback mgr_cb = {SpEntity::__on_rpc_request, NULL, this};
  260. rc = sp_rpc_client_mgr_create(m_svc, &mgr_cb, &m_rpc_mgr); //Init variable m_rpc_mgr, callback handle
  261. if (rc != 0) {
  262. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create rpc client mgr failed!");
  263. return SpTranslateError(rc);
  264. }
  265. rc = sp_rpc_client_mgr_start(m_rpc_mgr); //add workItem mgr_on_pkt and mgr_on_sys
  266. if (rc != 0) {
  267. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("start rpc client mgr failed!");
  268. return SpTranslateError(rc);
  269. }
  270. sp_ses_mgr_callback_t ses_mgr_cb = {0};
  271. ses_mgr_cb.on_accept = &__on_accept;
  272. ses_mgr_cb.on_destroy = NULL;
  273. ses_mgr_cb.user_data = this;
  274. rc = sp_ses_mgr_create(m_svc, &ses_mgr_cb, &m_ses_mgr); //Init variable m_ses_mgr
  275. if (rc != 0) {
  276. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create ses mgr failed!");
  277. return SpTranslateError(rc);
  278. }
  279. rc = sp_ses_mgr_start(m_ses_mgr); //add workItem mgr_on_pkt and mgr_on_sys
  280. if (rc != 0) {
  281. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("start ses mgr failed!");
  282. return SpTranslateError(rc);
  283. }
  284. //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("start ses mgr ok!");
  285. rc = sp_log_client_create(m_svc, m_pModule->get_iom(), &m_log_client);
  286. if (rc != 0) {
  287. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create log client failed!");
  288. return SpTranslateError(rc);
  289. }
  290. //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("start entity log client ok!");
  291. rc = sp_var_client_create(m_svc, &m_var_client);
  292. if (rc != 0) {
  293. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create var client failed!");
  294. return SpTranslateError(rc);
  295. }
  296. //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create var client ok!");
  297. rc = sp_bcm_client_create(m_svc, &m_bcm_client);
  298. if (rc != 0) {
  299. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create bcm client failed!");
  300. return SpTranslateError(rc);
  301. }
  302. //DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create bcm client ok!");
  303. rc = sp_log_listener_mgr_create(m_svc, on_log, &m_log_mgr);
  304. if (rc == 0) {
  305. rc = sp_log_listener_mgr_start(m_log_mgr);
  306. if (rc != 0) {
  307. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create log mgr failed!");
  308. return SpTranslateError(rc);
  309. }
  310. }
  311. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("entity Init end!");
  312. m_arr_bcm_listener = array_make(0, sizeof(sp_bcm_listener_t*));
  313. return SpTranslateError(rc);
  314. }
  315. void SpEntity::Term()
  316. {
  317. SpTimerListStopAll(m_pTimerList);
  318. }
  319. void SpEntity::on_entity_prestart(int trigger_entity_id, int argc, char *argv[])
  320. {
  321. CAutoArray<CSimpleStringA> Args;
  322. Args.Init(argc);
  323. CSmartPointer<ITransactionContext> pTransactionContext;
  324. pTransactionContext.Attach(new SpMUITransactionContext(this, SpMUITransactionContext::OP_START));
  325. for (int i = 0; i < argc; ++i)
  326. Args[i] = argv[i];
  327. m_pEntityBase->OnPreStart(Args, pTransactionContext);
  328. }
  329. void SpEntity::on_entity_stop(int trigger_entity_id, int cause_code)
  330. {
  331. CSmartPointer<ITransactionContext> pTransactionContext;
  332. pTransactionContext.Attach(new SpMUITransactionContext(this, SpMUITransactionContext::OP_CLOSE));
  333. m_pEntityBase->OnPreClose((EntityCloseCauseEnum)cause_code, pTransactionContext);
  334. }
  335. void SpEntity::on_entity_prepause(int trigger_entity_id)
  336. {
  337. CSmartPointer<ITransactionContext> pTransactionContext;
  338. pTransactionContext.Attach(new SpMUITransactionContext(this, SpMUITransactionContext::OP_PAUSE));
  339. m_pEntityBase->OnPrePause(pTransactionContext);
  340. }
  341. void SpEntity::on_entity_precontinue(int trigger_entity_id)
  342. {
  343. CSmartPointer<ITransactionContext> pTransactionContext;
  344. pTransactionContext.Attach(new SpMUITransactionContext(this, SpMUITransactionContext::OP_CONTINUE));
  345. m_pEntityBase->OnPreContinue(pTransactionContext);
  346. }
  347. void SpEntity::on_entity_test(int trigger_entity_id, int test_type)
  348. {
  349. const EntityTestEnum testType = static_cast<EntityTestEnum>(test_type);
  350. CSmartPointer<ITransactionContext> pTransactionContext;
  351. pTransactionContext.Attach(new SpMUITransactionContext(this, SpMUITransactionContext::OP_SELFTEST));
  352. if (testType == Test_Examine) {
  353. m_pEntityBase->OnExam(pTransactionContext);
  354. } else {
  355. m_pEntityBase->OnSelfTest(testType, pTransactionContext);
  356. }
  357. }
  358. void SpEntity::on_entity_redirect_subscribe(sp_uid_t *uid, int from_entity_id, const char *param)
  359. {
  360. CUUID id(*uid);
  361. sp_entity_t *ent = sp_mod_mgr_find_entity_by_idx(sp_get_env()->mod_mgr, from_entity_id);
  362. if (ent) {
  363. m_pEntityBase->OnBroadcastSubscribe(id, ent->cfg->name, param);
  364. }
  365. }
  366. void SpEntity::__on_entity_prestart(sp_mod_entity_stub_t*, int trigger_entity_id, int argc, char* argv[], void* user_data)
  367. {
  368. SpEntity *pThis = static_cast<SpEntity*>(user_data);
  369. pThis->on_entity_prestart(trigger_entity_id, argc, argv);
  370. }
  371. void SpEntity::__on_entity_stop(sp_mod_entity_stub_t *, int trigger_entity_id, int cause_code, void *user_data)
  372. {
  373. SpEntity *pThis = static_cast<SpEntity*>(user_data);
  374. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("stop Entity");
  375. pThis->on_entity_stop(trigger_entity_id, cause_code);
  376. }
  377. void SpEntity::__on_entity_prepause(sp_mod_entity_stub_t *, int trigger_entity_id, void *user_data)
  378. {
  379. SpEntity *pThis = static_cast<SpEntity*>(user_data);
  380. pThis->on_entity_prepause(trigger_entity_id);
  381. }
  382. void SpEntity::__on_entity_precontinue(sp_mod_entity_stub_t *, int trigger_entity_id, void *user_data)
  383. {
  384. SpEntity *pThis = static_cast<SpEntity*>(user_data);
  385. pThis->on_entity_precontinue(trigger_entity_id);
  386. }
  387. void SpEntity::__on_entity_test(sp_mod_entity_stub_t *, int trigger_entity_id, int test_type, void *user_data)
  388. {
  389. SpEntity *pThis = static_cast<SpEntity*>(user_data);
  390. pThis->on_entity_test(trigger_entity_id, test_type);
  391. }
  392. void SpEntity::__on_entity_redirect_subscribe(sp_mod_entity_stub_t *, sp_uid_t *uid, int from_entity_id, const char *param, void *user_data)
  393. {
  394. SpEntity *pThis = static_cast<SpEntity*>(user_data);
  395. pThis->on_entity_redirect_subscribe(uid, from_entity_id, param);
  396. }
  397. int SpEntity::__on_accept(sp_ses_mgr_t *mgr, int epid, int svc_id, int conn_id, iobuffer_t **conn_pkt, int *redirect_entity_id, void *user_data)
  398. {
  399. SpEntity *pThis = static_cast<SpEntity*>(user_data);
  400. return pThis->on_accept(epid, svc_id, conn_id, conn_pkt, redirect_entity_id);
  401. }
  402. int SpEntity::on_accept(int epid, int svc_id, int conn_id, iobuffer_t **conn_pkt, int *redirect_entity_id)
  403. {
  404. sp_env_t *env = sp_get_env();
  405. ErrorCodeEnum Error = Error_Succeed;
  406. if (!m_pEntityBase->IsService()) {
  407. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("current entity is no registed as service type, please confirm it at code scope.");
  408. return Error_NotSupport;
  409. }
  410. sp_entity_t *remote_ent = sp_mod_mgr_find_entity_by_idx(env->mod_mgr, svc_id);
  411. if (!remote_ent) {
  412. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("cannot recognize the customer entity: %d!", svc_id);
  413. return Error_Bug;
  414. }
  415. char *pszParam = NULL;
  416. CServerSessionBase *pServerSessionBase = NULL;
  417. iobuffer_format_read(*conn_pkt, "s", &pszParam);
  418. try {
  419. m_redirect_entity_cache = NULL; // user can set entity_cache value in OnNewSession by invoking RedirectSession method
  420. pServerSessionBase = m_pEntityBase->OnNewSession(remote_ent->cfg->name, pszParam);
  421. } catch (...)
  422. {
  423. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("Exception occurs at <%s>[%d]{%s}", __FUNCTION__, __LINE__, _GetFileName(__FILE__));
  424. Error = Error_Exception;
  425. }
  426. FREE(pszParam);
  427. if (pServerSessionBase)
  428. {
  429. SpServerSessionFunction *pServerSessionFunction = new SpServerSessionFunction(this, pServerSessionBase, epid, svc_id, conn_id);
  430. pServerSessionBase->m_pSessionFunction = pServerSessionFunction;
  431. Error = pServerSessionFunction->Begin();
  432. if (Error != Error_Succeed)
  433. {
  434. delete pServerSessionBase; // this will also delete pServerSessionFunction
  435. }
  436. }
  437. else
  438. {
  439. if (m_redirect_entity_cache)
  440. {
  441. *redirect_entity_id = m_redirect_entity_cache->cfg->idx;
  442. Error = Error_Redirect;
  443. }
  444. else
  445. {
  446. Error = Error_NotImpl;
  447. }
  448. }
  449. return Error;
  450. }
  451. void SpEntity::on_thread_init()
  452. {
  453. #ifdef _WIN32
  454. SetthreadGroup(GetCurrentThreadId(), this->get_cfg_ent()->name);
  455. getEntityResource()->m_Entity = this;
  456. #else
  457. m_pModule->SetThreadEntity(this);
  458. #endif //_WIN32
  459. }
  460. void SpEntity::on_thread_term()
  461. {
  462. #ifdef _WIN32
  463. SetthreadGroup(GetCurrentThreadId(), this->get_cfg_ent()->name);
  464. getEntityResource()->m_Entity = NULL;
  465. #else
  466. m_pModule->SetThreadEntity(NULL);
  467. #endif //_WIN32
  468. }
  469. void SpEntity::__on_thread_init(threadpool_t *, void *arg)
  470. {
  471. SpEntity *pThis = static_cast<SpEntity*>(arg);
  472. pThis->on_thread_init();
  473. #ifndef _WIN32
  474. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("thread init, thread id:%u", GetCurrentThreadIdFromSys());
  475. #else
  476. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("thread init, thread id:%d", GetCurrentThreadId());
  477. #endif //NOT _WIN32
  478. }
  479. void SpEntity::__on_thread_term(threadpool_t *, void *arg)
  480. {
  481. SpEntity *pThis = static_cast<SpEntity*>(arg);
  482. pThis->on_thread_term();
  483. #if defined(_MSC_VER)
  484. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("thread term, thread id:%d", GetCurrentThreadId());
  485. #else
  486. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("thread term, thread id:%u", GetCurrentThreadIdFromSys());
  487. #endif //_MSC_VER
  488. }
  489. ErrorCodeEnum SpEntity::SetTimer(DWORD nTimerID, ITimerListener *pListener, DWORD dwInterval)
  490. {
  491. ErrorCodeEnum Error = Error_Succeed;
  492. if (!pListener)
  493. return Error_Param;
  494. SpTimerListLock(m_pTimerList);
  495. if (SpTimerListFind(m_pTimerList, nTimerID)) {
  496. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("timer id %d already in use!", nTimerID);
  497. Error = Error_AlreadyExist;
  498. } else {
  499. SpTimer *pTimer = SpTimerCreate(m_pTimerList, nTimerID, dwInterval, pListener);
  500. if (pTimer) {
  501. SpTimerListAdd(m_pTimerList, pTimer);
  502. Error = SpTimerStart(pTimer);
  503. if (Error) {
  504. SpTimerListRemove(m_pTimerList, pTimer);
  505. SpTimerDestroy(pTimer);
  506. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("start timer %d failed!", nTimerID);
  507. } else {
  508. //DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("timer %d added! interval = %d", nTimerID, dwInterval);
  509. }
  510. } else {
  511. Error = Error_Unexpect;
  512. }
  513. }
  514. SpTimerListUnlock(m_pTimerList);
  515. return Error;
  516. }
  517. ErrorCodeEnum SpEntity::SetTimerData(DWORD dwTimerID, IReleasable *pData)
  518. {
  519. ErrorCodeEnum Error = Error_Succeed;
  520. SpTimerListLock(m_pTimerList);
  521. SpTimer *pTimer = SpTimerListFind(m_pTimerList, dwTimerID);
  522. if (pTimer) {
  523. SpTimerSetUserData(pTimer, pData);
  524. } else {
  525. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("timer %d not found!", dwTimerID);
  526. Error = Error_NotExist;
  527. }
  528. SpTimerListUnlock(m_pTimerList);
  529. return Error;
  530. }
  531. ErrorCodeEnum SpEntity::GetTimerData(DWORD dwTimerID, CSmartPointer<IReleasable> &pData)
  532. {
  533. ErrorCodeEnum Error = Error_Succeed;
  534. SpTimerListLock(m_pTimerList);
  535. SpTimer *pTimer = SpTimerListFind(m_pTimerList, dwTimerID);
  536. if (pTimer) {
  537. SpTimerGetUserData(pTimer, pData);
  538. } else {
  539. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("timer %d not found!", dwTimerID);
  540. Error = Error_NotExist;
  541. }
  542. SpTimerListUnlock(m_pTimerList);
  543. return Error;
  544. }
  545. ErrorCodeEnum SpEntity::KillTimer(DWORD nTimerID)
  546. {
  547. ErrorCodeEnum Error = Error_Succeed;
  548. SpTimerListLock(m_pTimerList);
  549. SpTimer *pTimer = SpTimerListFind(m_pTimerList, nTimerID);
  550. if (pTimer) {
  551. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("timer %d killed!", nTimerID);
  552. SpTimerListRemove(m_pTimerList, pTimer);
  553. SpTimerStop(pTimer);
  554. SpTimerDestroy(pTimer);
  555. } else {
  556. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("timer %d has not set!", nTimerID);
  557. Error = Error_NotExist;
  558. }
  559. SpTimerListUnlock(m_pTimerList);
  560. return Error;
  561. }
  562. ErrorCodeEnum SpEntity::ResetTimer(DWORD nTimerID, DWORD dwInterval)
  563. {
  564. ErrorCodeEnum Error = Error_Succeed;
  565. SpTimerListLock(m_pTimerList);
  566. SpTimer *pTimer = SpTimerListFind(m_pTimerList, nTimerID);
  567. if (pTimer) {
  568. SpTimerSetInterval(pTimer, dwInterval);
  569. } else {
  570. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("timer %d has not set!", nTimerID);
  571. Error = Error_NotExist;
  572. }
  573. SpTimerListUnlock(m_pTimerList);
  574. return Error;
  575. }
  576. ErrorCodeEnum SpEntity::GetTimerInterval(DWORD nTimerID, DWORD &dwInterval)
  577. {
  578. ErrorCodeEnum Error = Error_Succeed;
  579. SpTimerListLock(m_pTimerList);
  580. SpTimer *pTimer = SpTimerListFind(m_pTimerList, nTimerID);
  581. if (pTimer) {
  582. dwInterval = SpTimerGetInterval(pTimer);
  583. } else {
  584. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("timer %d has not set!", nTimerID);
  585. Error = Error_NotExist;
  586. }
  587. SpTimerListUnlock(m_pTimerList);
  588. return Error;
  589. }
  590. ErrorCodeEnum SpEntity::ReadPersistObject(const char *pszClass, const char *pszKey, IEntityPersistObject *pInstance)
  591. {
  592. sp_env_t *env = sp_get_env();
  593. sp_pst_tree_t *tree;
  594. int rc;
  595. if (!pszClass || !pszKey || !pInstance)
  596. return Error_Param;
  597. rc = sp_pst_tree_load(env->dir->obj_path, m_ent->cfg->name, pszClass, pszKey, &tree);
  598. if (rc == 0) {
  599. sp_pst_elem_t *root = sp_pst_tree_get_root(tree);
  600. CSmartPointer<IEntityPersistStreamRead> pStream;
  601. pStream.Attach(new SpBinaryPersistStream(SpBinaryPersistStream::Read, root));
  602. rc = (int)pInstance->OnRead(pStream);
  603. sp_pst_tree_destroy(tree);
  604. }
  605. return SpTranslateError(rc);
  606. }
  607. ErrorCodeEnum SpEntity::WritePersistObject(const char *pszClass, const char *pszKey, const IEntityPersistObject *pInstance)
  608. {
  609. sp_env_t *env = sp_get_env();
  610. sp_pst_elem_t *root;
  611. int rc;
  612. if (!pszClass || !pszKey || !pInstance)
  613. return Error_Param;
  614. root = sp_pst_elem_create(NULL, pszKey);
  615. CSmartPointer<IEntityPersistStreamWrite> pStream;
  616. pStream.Attach(new SpBinaryPersistStream(SpBinaryPersistStream::Write, root));
  617. rc = (int)pInstance->OnWrite(pStream);
  618. if (rc == 0) {
  619. sp_pst_tree_t *tree;
  620. sp_pst_tree_create(&tree);
  621. sp_pst_tree_set_root(tree, root);
  622. rc = sp_pst_tree_save(env->dir->obj_path, m_ent->cfg->name, pszClass, pszKey, tree);
  623. sp_pst_tree_destroy(tree);
  624. } else {
  625. sp_pst_elem_destroy(root);
  626. }
  627. return SpTranslateError(rc);
  628. }
  629. ErrorCodeEnum SpEntity::ReadNumOfPersistObject(const char *pszClassName,DWORD &nNum)
  630. {
  631. if (!pszClassName)
  632. return Error_Param;
  633. sp_env_t *env = sp_get_env();
  634. int cnt;
  635. int rc = sp_pst_get_object_count(env->dir->obj_path, m_ent->cfg->name, pszClassName, &cnt);
  636. if (rc == 0)
  637. nNum = (DWORD)cnt;
  638. return SpTranslateError(rc);
  639. }
  640. ErrorCodeEnum SpEntity::GetPersistClassObjectKeys(const char *pszClassName, CAutoArray<CSimpleStringA> &strKeys)
  641. {
  642. if (!pszClassName)
  643. return Error_Param;
  644. sp_env_t *env = sp_get_env();
  645. array_header_t *arr = sp_pst_get_object_keys(env->dir->obj_path, m_ent->cfg->name, pszClassName);
  646. if (arr) {
  647. strKeys.Init(arr->nelts);
  648. for (int i = 0; i < arr->nelts; ++i)
  649. strKeys[i] = ARRAY_IDX(arr, i, char*);
  650. array_free2(arr);
  651. } else {
  652. strKeys.Init(0);
  653. }
  654. return Error_Succeed;
  655. }
  656. ErrorCodeEnum SpEntity::DeleteKeyOfPersistObject(const char *pszClassName,const char *pszKey)
  657. {
  658. if (!pszClassName || !pszKey)
  659. return Error_Param;
  660. sp_env_t *env = sp_get_env();
  661. int rc = sp_pst_delete_object(env->dir->obj_path, m_ent->cfg->name, pszClassName, pszKey);
  662. return SpTranslateError(rc);
  663. }
  664. ErrorCodeEnum SpEntity::EnumKeyOfPersistObject(const char *pszClass,CSimpleStringA &strKey,DWORD &handle)
  665. {
  666. if (!pszClass)
  667. return Error_Param;
  668. int rc = 0;
  669. sp_env_t *env = sp_get_env();
  670. struct HelperIterator {
  671. array_header_t *arr;
  672. int Current;
  673. } * pIterator = NULL;
  674. if (handle == 0) {
  675. pIterator = new HelperIterator();
  676. pIterator->arr = sp_pst_get_object_keys(env->dir->obj_path, m_ent->cfg->name, pszClass);
  677. if (!pIterator->arr) {
  678. delete pIterator;
  679. return Error_NotExist;
  680. }
  681. pIterator->Current = 0;
  682. #if defined(_MSC_VER)
  683. handle = (DWORD)pIterator;
  684. #else
  685. //TODO: x64 environment, depend on how to use the out-param
  686. handle = (uintptr_t)(static_cast<void*>(pIterator));
  687. #endif //_MSC_VER
  688. } else {
  689. pIterator = (HelperIterator *)handle;
  690. }
  691. if (pIterator->Current < pIterator->arr->nelts) {
  692. strKey = ARRAY_IDX(pIterator->arr, pIterator->Current, char*);
  693. pIterator->Current++;
  694. } else {
  695. if (pIterator->arr)
  696. array_free2(pIterator->arr);
  697. delete pIterator;
  698. handle = 0; // zero handle
  699. rc = Error_NotExist;// the end
  700. }
  701. return SpTranslateError(rc);
  702. }
  703. ErrorCodeEnum SpEntity::CleanAllOfPersistObject(const char *pszClass)
  704. {
  705. if (!pszClass)
  706. return Error_Param;
  707. sp_env_t *env = sp_get_env();
  708. int rc = sp_pst_delete_class_objects(env->dir->obj_path, m_ent->cfg->name, pszClass);
  709. return SpTranslateError(rc);
  710. }
  711. ErrorCodeEnum SpEntity::SubscribeLog(CUUID &SubscribeID, ILogListener *pListener,LogTypeEnum eLogType,
  712. SeverityLevelEnum eLevel, ErrorCodeEnum eSysError,DWORD dwUserCode,
  713. const char *pszEntityName,bool bIgnoreMessage)
  714. {
  715. _ASSERT(pListener);
  716. sp_entity_t *ent = NULL;
  717. if (pszEntityName) {
  718. ent = sp_mod_mgr_find_entity_by_name(sp_get_env()->mod_mgr, pszEntityName);
  719. if (!ent) {
  720. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("SubscribeLog failed! Entity %s not exist!", pszEntityName);
  721. return Error_NotExist;
  722. }
  723. }
  724. unsigned int listen_id = 0;
  725. int rc = sp_log_listener_mgr_subscribe(m_log_mgr, &listen_id, pListener, !!bIgnoreMessage,
  726. eLogType, ent ? ent->cfg->idx : -1, eLevel, eSysError, dwUserCode);
  727. if (rc == 0) {
  728. SubscribeID = listen_id;
  729. }
  730. return SpTranslateError(rc);
  731. }
  732. ErrorCodeEnum SpEntity::UnsubscribeLog(CUUID SubscribeID)
  733. {
  734. unsigned int listen_id = (unsigned int)SubscribeID;
  735. int rc = sp_log_listener_mgr_unsubscribe(m_log_mgr, listen_id);
  736. return SpTranslateError(rc);
  737. }
  738. ErrorCodeEnum SpEntity::FlushLogFile()
  739. {
  740. return LogFlush();
  741. }
  742. ErrorCodeEnum SpEntity::SetSysVar(const char *pszKey,const char *pszValue, bool bPersist)
  743. {
  744. int rc;
  745. _ASSERT(pszKey); // pszValue can be null, use for delete
  746. rc = sp_var_client_set((sp_var_client_t*)m_var_client, pszKey, pszValue, bPersist ? 1 : 0);
  747. return SpTranslateError(rc);
  748. }
  749. ErrorCodeEnum SpEntity::GetSysVar(const char *pszKey,CSimpleStringA &strValue)
  750. {
  751. sp_var_client_t* client = (sp_var_client_t*)m_var_client;
  752. int slen = 0;
  753. int rc;
  754. _ASSERT(pszKey);
  755. rc = sp_var_client_lock(client);
  756. if (rc == 0) {
  757. rc = sp_var_client_get(client, pszKey, NULL, &slen);
  758. if (rc == Error_TooSmallBuffer) {
  759. CSimpleStringA strTmp('\0', slen);
  760. rc = sp_var_client_get((sp_var_client_t*)m_var_client, pszKey, &strTmp[0], &slen);
  761. if (rc == 0)
  762. strValue = strTmp;
  763. }
  764. sp_var_client_unlock(client);
  765. }
  766. return SpTranslateError(rc);
  767. }
  768. ErrorCodeEnum SpEntity::RegistSysVarEvent(const char *pszKey,ISysVarListener *pListener)
  769. {
  770. int rc = 0;
  771. if (!pszKey || strlen(pszKey) == 0 || !pListener)
  772. return Error_Param;
  773. sp_env_t *env = sp_get_env();
  774. sp_var_listener_t **pp_var;
  775. if (strcmp(pszKey, "*") != 0) {
  776. sp_cfg_shell_sysevent_t *sysevent = sp_cfg_get_sysevent(env->cfg, pszKey);
  777. if (!sysevent)
  778. return Error_NotExist;
  779. if (m_arr_var[sysevent->idx])
  780. return Error_Duplication;
  781. pp_var = &m_arr_var[sysevent->idx];
  782. } else {
  783. if (m_arr_any_var)
  784. return Error_Duplication;
  785. pp_var = &m_arr_any_var;
  786. }
  787. sp_var_listener_t *listener;
  788. sp_var_listener_create(m_svc, pszKey, &var_callback, pListener, &listener);
  789. sp_var_listener_set_tag(listener, this);
  790. rc = sp_var_listener_subscribe(listener);
  791. if (rc == 0) {
  792. *pp_var = listener;
  793. } else {
  794. sp_var_listener_destroy(listener);
  795. }
  796. return SpTranslateError(rc);
  797. }
  798. ErrorCodeEnum SpEntity::UnregistSysVarEvent(const char *pszKey)
  799. {
  800. if (!pszKey || strlen(pszKey) == 0)
  801. return Error_Param;
  802. int rc = 0;
  803. if (strcmp(pszKey, "*") != 0) {
  804. sp_env_t *env = sp_get_env();
  805. sp_cfg_shell_sysevent_t *sysevent = sp_cfg_get_sysevent(env->cfg, pszKey);
  806. if (!sysevent)
  807. return Error_NotExist;
  808. sp_var_listener_t *listener = m_arr_var[sysevent->idx];
  809. if (listener) {
  810. int rc;
  811. rc = sp_var_listener_unsubscribe(listener);
  812. if (rc == 0) {
  813. sp_var_listener_destroy(listener);
  814. m_arr_var[sysevent->idx] = NULL;
  815. }
  816. } else {
  817. rc = Error_NotInit;
  818. }
  819. } else {
  820. if (m_arr_any_var != NULL)
  821. {
  822. rc = sp_var_listener_unsubscribe(m_arr_any_var);
  823. if (rc == 0)
  824. {
  825. sp_var_listener_destroy(m_arr_any_var);
  826. m_arr_any_var = NULL;
  827. }
  828. }
  829. }
  830. return SpTranslateError(rc);
  831. }
  832. ErrorCodeEnum SpEntity::RegistTerminalStateChangeEvent(ITerminalStateChangedListener* pListener)
  833. {
  834. return RegistSysVarEvent(VAR_RSERVERD_KEY_TERM_STATE, (ISysVarListener*)(void*)((uintptr_t)pListener));
  835. }
  836. ErrorCodeEnum SpEntity::UnregistTerminalStateChangeEvent()
  837. {
  838. return UnregistSysVarEvent(VAR_RSERVERD_KEY_TERM_STATE);
  839. }
  840. ErrorCodeEnum SpEntity::SendBroadcast(DWORD dwMessageId, DWORD dwMessageSignature,CAutoBuffer Buffer)
  841. {
  842. int rc;
  843. iobuffer_t *pkt = iobuffer_create(-1, Buffer.GetCount());
  844. iobuffer_write(pkt, IOBUF_T_BUF, &Buffer[0], Buffer.GetCount());
  845. rc = sp_bcm_client_bcast(m_bcm_client, dwMessageId, dwMessageSignature, &pkt);
  846. if (pkt)
  847. iobuffer_dec_ref(pkt);
  848. return SpTranslateError(rc);
  849. }
  850. ErrorCodeEnum SpEntity::GetBroadcastReceivers(CAutoArray<BroadcastSubscribeInfo> &Subscribers)
  851. {
  852. ErrorCodeEnum Error;
  853. iobuffer_t *req_pkt = iobuffer_create(-1, -1);
  854. iobuffer_t *ans_pkt = NULL;
  855. Error = AskShell(SHELL_CMD_REQ_GET_BCAST_RECEIVER, &req_pkt, &ans_pkt);
  856. if (Error == Error_Succeed) {
  857. sp_env_t *env = sp_get_env();
  858. int size;
  859. iobuffer_read(ans_pkt, IOBUF_T_I4, &size, NULL);
  860. Subscribers.Init(size);
  861. for (int i = 0; i < size; ++i) {
  862. int ent_id;
  863. sp_uid_t uid;
  864. char *param = NULL;
  865. iobuffer_format_read(ans_pkt, "84s", &uid, &ent_id, &param);
  866. Subscribers[i].SubID = CUUID(uid);
  867. sp_entity_t *ent = sp_mod_mgr_find_entity_by_idx(env->mod_mgr, ent_id);
  868. Subscribers[i].strListener = ent->cfg->name;
  869. Subscribers[i].strParam = param;
  870. FREE(param);
  871. }
  872. }
  873. if (req_pkt)
  874. iobuffer_dec_ref(req_pkt);
  875. if (ans_pkt)
  876. iobuffer_dec_ref(ans_pkt);
  877. return Error;
  878. }
  879. ErrorCodeEnum SpEntity::SubscribeBroadcast(const char *pszRemoteEntity, const char *pszParam,
  880. IBroadcastListener *pListener, CUUID &SubscribeID)
  881. {
  882. if (pszParam == NULL)
  883. pszParam = "";
  884. if (pListener == NULL)
  885. return Error_Param;
  886. sp_entity_t *remote_ent = sp_mod_mgr_find_entity_by_name(sp_get_env()->mod_mgr, pszRemoteEntity);
  887. if (remote_ent) {
  888. int rc;
  889. sp_uid_t uid;
  890. sp_bcm_listener_t *listener;
  891. sp_bcm_listener_cb cb = {0};
  892. cb.on_destroy = NULL;
  893. cb.on_message = &bcm_callback;
  894. cb.on_message_raw = NULL;
  895. cb.user_data = pListener;
  896. rc = sp_bcm_listener_create(m_svc, remote_ent->cfg->idx, pszParam, &cb, &listener);
  897. if (rc == 0) {
  898. rc = sp_bcm_listener_subscribe(listener, &uid);
  899. }
  900. if (rc != 0) {
  901. return SpTranslateError(rc);
  902. }
  903. SubscribeID = CUUID(uid);
  904. sp_bcm_listener_set_tag(listener, this);
  905. ARRAY_PUSH(m_arr_bcm_listener, sp_bcm_listener_t*) = listener;
  906. } else {
  907. return Error_NotExist;
  908. }
  909. return Error_Succeed;
  910. }
  911. ErrorCodeEnum SpEntity::UnsubscribeBroadcast(CUUID SubscribeID)
  912. {
  913. sp_bcm_listener_t *listener = NULL;
  914. int i;
  915. for (i = 0; i < m_arr_bcm_listener->nelts; ++i) {
  916. listener = ARRAY_IDX(m_arr_bcm_listener, i, sp_bcm_listener_t*);
  917. sp_uid_t uid;
  918. sp_bcm_listener_get_uid(listener, &uid);
  919. if (uid == SubscribeID.m_nUUID64) {
  920. ARRAY_DEL(m_arr_bcm_listener, i, sp_bcm_listener_t*);
  921. break;
  922. }
  923. }
  924. if (listener) {
  925. sp_bcm_listener_unsubscribe(listener);
  926. sp_bcm_listener_destroy(listener);
  927. return Error_Succeed;
  928. } else {
  929. return Error_NotExist;
  930. }
  931. }
  932. ErrorCodeEnum SpEntity::UnsubscribeBroadcast(const char *pszRemoteEntity)
  933. {
  934. if (pszRemoteEntity == NULL)
  935. return Error_Param;
  936. sp_entity_t *ent = sp_mod_mgr_find_entity_by_name(sp_get_env()->mod_mgr, pszRemoteEntity);
  937. if (!ent)
  938. return Error_NotExist;
  939. sp_bcm_listener_t *listener = NULL;
  940. int i;
  941. for (i = m_arr_bcm_listener->nelts-1; i >= 0; --i) {
  942. listener = ARRAY_IDX(m_arr_bcm_listener, i, sp_bcm_listener_t*);
  943. if (ent->cfg->idx == sp_bcm_listener_get_target_entity_id(listener)) {
  944. ARRAY_DEL(m_arr_bcm_listener, i, sp_bcm_listener_t*);
  945. sp_bcm_listener_unsubscribe(listener);
  946. sp_bcm_listener_destroy(listener);
  947. }
  948. }
  949. return Error_Succeed;
  950. }
  951. ErrorCodeEnum SpEntity::LogMessage( const LogTypeEnum LogType, const SeverityLevelEnum Level,
  952. DWORD dwSysErrorCode, DWORD dwUserErrorCode, const char *pMessage )
  953. {
  954. int nDevID = m_ent->cfg->devel_id;
  955. if (dwUserErrorCode != 0 && ((dwUserErrorCode >> 20) & nDevID) != nDevID) {
  956. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("[InvalidUserCode] devID: 0x%x, userCode: 0x%x", nDevID, dwUserErrorCode);
  957. }
  958. if (NULL == m_log_client) {
  959. return Error_Null;
  960. }
  961. auto rc = sp_log_client_logEx(m_log_client, LogType, Level, (int)dwSysErrorCode, (int)dwUserErrorCode, 0, 0,
  962. pMessage == NULL ? "" : pMessage, pMessage == NULL ? 0 : strlen(pMessage));
  963. if (rc != 0) {
  964. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("log message failed! raw msg: %s: %d", pMessage, rc);
  965. } else {
  966. if (-1 != dwUserErrorCode && 0 != dwUserErrorCode)//discard the dbg msg code
  967. {
  968. //DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("userCode: 0x%x send", dwUserErrorCode);
  969. }
  970. }
  971. /*存储当前实体最新一条错误信息*/
  972. if ((LogType == Log_Warning && (Level == Severity_High || Level == Severity_Middle))
  973. || LogType == Log_Error || LogType == Log_Fatal
  974. || (LogType == Log_Notify && (Level == Severity_High/* || Level == Severity_Middle*/))
  975. ) {
  976. SetEntityLastError((ErrorCodeEnum)dwSysErrorCode, dwUserErrorCode, pMessage);
  977. }
  978. return SpTranslateError(rc);
  979. }
  980. ErrorCodeEnum SpEntity::LogMessage(const LogTypeEnum LogType, const SeverityLevelEnum Level,
  981. DWORD iSysErrorCode, DWORD iUserErrorCode, CAutoArray<DWORD> Param,
  982. const char *pMessage)
  983. {
  984. // xkm@20160726: 校验 iUserErrorCode 是否合法
  985. int nDevID = m_ent->cfg->devel_id;
  986. if (iUserErrorCode != 0 && ((iUserErrorCode >> 20) & nDevID) != nDevID)
  987. {
  988. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("[InvalidUserCode] devID: 0x%x, userCode: 0x%x", nDevID, iUserErrorCode);
  989. }
  990. int rc;
  991. sp_log_client_t *client = (sp_log_client_t*)m_log_client;
  992. rc = sp_log_client_logEx(client, LogType, Level, (int)iSysErrorCode, (int)iUserErrorCode, (int)Param.GetCount(), (int*)&Param[0]
  993. , NULL == pMessage ? "" : pMessage, NULL == pMessage ? 0 : strlen(pMessage));
  994. if (rc != 0) {
  995. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("log message failed! raw msg: %s", pMessage);
  996. }
  997. return SpTranslateError(rc);
  998. }
  999. ErrorCodeEnum SpEntity::LogMessage(const LogTypeEnum LogType, const SeverityLevelEnum Level, DWORD iSysErrorCode, DWORD iUserErrorCode, const char* pMessage, const linkContext& t_context)
  1000. {
  1001. int nDevID = m_ent->cfg->devel_id;
  1002. if (iUserErrorCode != 0 && ((iUserErrorCode >> 20) & nDevID) != nDevID) {
  1003. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("[InvalidUserCode] devID: 0x%x, userCode: 0x%x", nDevID, iUserErrorCode);
  1004. }
  1005. if (NULL == m_log_client)
  1006. return Error_Null;
  1007. auto rc = sp_log_client_logWithLink(m_log_client, LogType, Level, (int)iSysErrorCode, (int)iUserErrorCode, 0, 0,
  1008. pMessage == NULL ? "" : pMessage, pMessage == NULL ? 0 : strlen(pMessage)
  1009. , t_context.bussinessId.GetData(), t_context.traceId.GetData(), t_context.spanId.GetData(), t_context.parentSpanId.GetData());
  1010. if (rc != 0) {
  1011. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("log message failed! raw msg: %s", pMessage);
  1012. }
  1013. else
  1014. {
  1015. if (-1 != iUserErrorCode && 0 != iUserErrorCode)//discard the dbg msg code
  1016. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("userCode: 0x%x send", iUserErrorCode);
  1017. }
  1018. return SpTranslateError(rc);
  1019. }
  1020. WORD SpEntity::GetDevID()
  1021. {
  1022. return m_ent->cfg->devel_id;
  1023. }
  1024. ErrorCodeEnum SpEntity::LogMessage(const LogTypeEnum LogType, const SeverityLevelEnum Level, DWORD iSysErrorCode, DWORD iUserErrorCode, CAutoArray<DWORD> Param, const char* pMessage, const linkContext& t_context)
  1025. {
  1026. int nDevID = m_ent->cfg->devel_id;
  1027. if (iUserErrorCode != 0 && ((iUserErrorCode >> 20) & nDevID) != nDevID)
  1028. {
  1029. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("[InvalidUserCode] devID: 0x%x, userCode: 0x%x", nDevID, iUserErrorCode);
  1030. }
  1031. int rc;
  1032. sp_log_client_t* client = (sp_log_client_t*)m_log_client;
  1033. rc = sp_log_client_logWithLink(client, LogType, Level, (int)iSysErrorCode, (int)iUserErrorCode, (int)Param.GetCount(), (int*)&Param[0]
  1034. , NULL == pMessage ? "" : pMessage, NULL == pMessage ? 0 : strlen(pMessage)
  1035. , t_context.bussinessId.GetData(), t_context.traceId.GetData(), t_context.spanId.GetData(), t_context.parentSpanId.GetData());
  1036. if (rc != 0) {
  1037. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("log message failed! raw msg: %s", pMessage);
  1038. }
  1039. return SpTranslateError(rc);
  1040. }
  1041. ErrorCodeEnum SpEntity::LogFlush()
  1042. {
  1043. int rc;
  1044. sp_log_client_t *client = (sp_log_client_t*)m_log_client;
  1045. rc = sp_log_client_flush(client);
  1046. if (rc != 0) {
  1047. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("flush log message failed!");
  1048. }
  1049. return SpTranslateError(rc);
  1050. }
  1051. ErrorCodeEnum SpEntity::OpenConfig(ConfigTypeEnum eConfigType,CSmartPointer<IConfigInfo> &spConfigInfo, bool forceFile)
  1052. {
  1053. IConfigInfo* pConfigInfo = NULL;
  1054. sp_env_t* env = sp_get_env();
  1055. sp_cfg_t* cfg = env->cfg;
  1056. sp_cfg_root_ini_t* root_ini = cfg->root_ini;
  1057. if (ConfigTypeEnum::Config_Root == eConfigType)
  1058. {
  1059. if (forceFile || cfg->root_ini->root_config == NULL || strlen(cfg->root_ini->root_config) == 0)
  1060. pConfigInfo = new SpIniConfig(this, eConfigType);
  1061. else
  1062. pConfigInfo = new SpRootMemConfig(this, eConfigType);
  1063. //Dbg("Use root cfg type :%s", pConfigInfo->storageInMem() ? "mem" : "ini");
  1064. }
  1065. else if (ConfigTypeEnum::Config_CenterSetting == eConfigType)
  1066. {
  1067. if (forceFile || cfg->root_ini->center_config == NULL || strlen(cfg->root_ini->center_config) == 0)
  1068. pConfigInfo = new SpIniConfig(this, eConfigType);
  1069. else
  1070. pConfigInfo = new SpRootMemConfig(this, eConfigType);
  1071. //Dbg("Use center cfg type :%s", pConfigInfo->storageInMem() ? "mem" : "ini");
  1072. }
  1073. else if (ConfigTypeEnum::Config_Shell == eConfigType)
  1074. {
  1075. if (forceFile || cfg->root_ini->shell_config == NULL || strlen(cfg->root_ini->shell_config) == 0)
  1076. pConfigInfo = new SpIniConfig(this, eConfigType);
  1077. else
  1078. pConfigInfo = new SpRootMemConfig(this, eConfigType);
  1079. }
  1080. else
  1081. pConfigInfo = new SpIniConfig(this, eConfigType);
  1082. spConfigInfo.Attach(pConfigInfo);
  1083. return Error_Succeed;
  1084. }
  1085. ErrorCodeEnum SpEntity::SetUserDefineState(DWORD dwState)
  1086. {
  1087. sp_env_t *env = sp_get_env();
  1088. sp_mod_mgr_t *mod_mgr = env->mod_mgr;
  1089. //sp_mod_mgr_lock(mod_mgr);
  1090. DWORD dwOldState = m_ent->user_state;
  1091. m_ent->user_state = dwState;
  1092. //sp_mod_mgr_unlock(mod_mgr);
  1093. // send state chage event to shell
  1094. if (dwOldState != dwState)
  1095. sp_mod_entity_stub_report_user_state_change(m_stub, dwOldState, dwState);
  1096. return Error_Succeed;
  1097. }
  1098. DWORD SpEntity::GetUserDefineState()
  1099. {
  1100. sp_env_t* env = sp_get_env();
  1101. sp_mod_mgr_t* mod_mgr = env->mod_mgr;
  1102. return (DWORD)(m_ent->user_state);
  1103. }
  1104. ErrorCodeEnum SpEntity::GetSystemStaticInfo(CSystemStaticInfo &Info)
  1105. {
  1106. sp_env_t *env = sp_get_env();
  1107. sp_cfg_t *cfg = env->cfg;
  1108. sp_dir_t* dir = env->dir;
  1109. sp_cfg_root_ini_t *root_ini = cfg->root_ini;
  1110. sp_cfg_install_ini_t *install_ini = cfg->install_ini;
  1111. int i;
  1112. sp_cfg_version_info_t *version_info;
  1113. Info.strTerminalID = CSimpleStringA(root_ini->terminal_no);
  1114. Info.strMachineType = CSimpleStringA(root_ini->machine_type);
  1115. Info.strManufacturer = CSimpleStringA(root_ini->manufacturer);
  1116. Info.MachineVersion = CVersion(root_ini->machine_version.major, root_ini->machine_version.minor, root_ini->machine_version.revision, root_ini->machine_version.build);
  1117. Info.LatterInstallVersion = CVersion(install_ini->latter_install_version.major, install_ini->latter_install_version.minor, install_ini->latter_install_version.revision, install_ini->latter_install_version.build);
  1118. if (install_ini->arr_light_pack->nelts > 0) {
  1119. Info.LightPackInfos.Init(install_ini->arr_light_pack->nelts);
  1120. }
  1121. for (i = 0; i < install_ini->arr_light_pack->nelts; ++i) {
  1122. sp_cfg_pack_info_t *pack = ARRAY_IDX(install_ini->arr_light_pack, i, sp_cfg_pack_info_t*);
  1123. Info.LightPackInfos[i].strPackName = CSimpleStringA(pack->name);
  1124. Info.LightPackInfos[i].State = (InstallStateEnum)pack->state;
  1125. Info.LightPackInfos[i].tmInstalledDate = CSmallDateTime(pack->install_time);
  1126. }
  1127. Info.nTotalRunCount = install_ini->total_run_count;
  1128. Info.nTodayRunCount = install_ini->today_run_count;
  1129. Info.tmCreateDate = install_ini->install_time;
  1130. Info.tmCurrentTime = install_ini->current_startup_time;
  1131. Info.strSite = CSimpleStringA(root_ini->site == NULL ? "" : root_ini->site);
  1132. Info.eScreen = (ScreenEnum)root_ini->screen;
  1133. Info.strEnrolAddr = CSimpleStringA(root_ini->enroll_address == NULL ? "" : root_ini->enroll_address);
  1134. Info.EnrolGPS = CSphereVector(root_ini->enroll_gps_x, root_ini->enroll_gps_y);
  1135. version_info = sp_cfg_find_previous_version_info(cfg, &install_ini->install_version);
  1136. if (version_info) {
  1137. Info.PreviousInstallVersion = CVersion(version_info->version.major, version_info->version.minor, version_info->version.revision, version_info->version.build);
  1138. } else {
  1139. Info.PreviousInstallVersion = CVersion(0, 0, 0, 0);
  1140. }
  1141. version_info = sp_cfg_find_version_info(cfg, &install_ini->install_version);
  1142. if (version_info)
  1143. {
  1144. Info.InstallVersion = CVersion(install_ini->install_version.major, install_ini->install_version.minor, install_ini->install_version.revision, install_ini->install_version.build);
  1145. Info.tmSwithOverDate = version_info->switch_time;
  1146. Info.InstallPack = CSimpleStringA(version_info->install_pack);
  1147. Info.InstallState = (InstallStateEnum)version_info->install_state;
  1148. }
  1149. if (dir->dep_ver_path == NULL) {
  1150. sp_dir_refresh_dep_path(env->dir);
  1151. }
  1152. if (dir->dep_ver_path != NULL) {
  1153. Info.CurrDepVersion = CSimpleStringA(strrchr(dir->dep_ver_path, SPLIT_SLASH) + 1);
  1154. }
  1155. return Error_Succeed;
  1156. }
  1157. ErrorCodeEnum SpEntity::GetInstallInfo(CVersion Version,CInstallInfo &Info)
  1158. {
  1159. sp_env_t *env = sp_get_env();
  1160. sp_cfg_t *cfg = env->cfg;
  1161. /*sp_cfg_root_ini_t *root_ini = cfg->root_ini;
  1162. sp_cfg_install_ini_t *install_ini = cfg->install_ini;*/
  1163. sp_cfg_version_info_t *version_info;
  1164. sp_version_t ver = {Version.GetMajor(), Version.GetMinor(), Version.GetRevision(), Version.GetBuild()};
  1165. version_info = sp_cfg_find_version_info(cfg, &ver);
  1166. if (version_info) {
  1167. Info.InstallPack = version_info->install_pack;
  1168. Info.InstallState = (InstallStateEnum)version_info->install_state;
  1169. Info.InstallVersion = Version;
  1170. Info.PreviousInstallVersion = CVersion(version_info->previous_version.major,
  1171. version_info->previous_version.minor,
  1172. version_info->previous_version.revision,
  1173. version_info->previous_version.build);
  1174. Info.tmSwithOverDate = version_info->switch_time;
  1175. } else {
  1176. return Error_NotExist;
  1177. }
  1178. return Error_Succeed;
  1179. }
  1180. ErrorCodeEnum SpEntity::GetPath(const char *pszKey,CSimpleStringA &strPath)
  1181. {
  1182. sp_env_t *env = sp_get_env();
  1183. ErrorCodeEnum Error = Error_Succeed;
  1184. if (!pszKey)
  1185. return Error_Null;
  1186. if (_stricmp(pszKey, "Root") == 0 || _stricmp(pszKey, "Run") == 0) {
  1187. strPath = env->dir->root_path;
  1188. } else if (_stricmp(pszKey, "RootVer") == 0) {
  1189. strPath = env->dir->root_ver_path;
  1190. } else if (_stricmp(pszKey, "Data") == 0) {
  1191. strPath = CSimpleStringA(env->dir->obj_path);
  1192. } else if (_stricmp(pszKey, "Bin") == 0) {
  1193. strPath = CSimpleStringA(env->dir->bin_path);
  1194. } else if (_stricmp(pszKey, "Cfg") == 0 || _stricmp(pszKey, "Etc") == 0) {
  1195. strPath = CSimpleStringA(env->dir->cfg_path);
  1196. } else if (_stricmp(pszKey, "Rec") == 0) {
  1197. strPath = CSimpleStringA(env->cfg->root_ini->ref_localvideo_path);
  1198. } else if (_stricmp(pszKey, "Temp") == 0 || _stricmp(pszKey, "Tmp") == 0) {
  1199. strPath = CSimpleStringA(env->cfg->root_ini->ref_tmp_path);
  1200. } else if (_stricmp(pszKey, "SysLog") == 0) {
  1201. strPath = CSimpleStringA(env->cfg->root_ini->ref_syslog_path);
  1202. } else if (_stricmp(pszKey, "InterLog") == 0) {
  1203. strPath = CSimpleStringA(env->cfg->root_ini->ref_intlog_path);
  1204. } else if (_stricmp(pszKey, "Base") == 0 || _stricmp(pszKey, "BaseDir") == 0) {
  1205. strPath = CSimpleStringA(env->dir->base_path);
  1206. } else if (_stricmp(pszKey, "SysRoot") == 0) {
  1207. strPath = CSimpleStringA(env->cfg->root_ini->ref_sysroot_path);
  1208. } else if (_stricmp(pszKey, "Photo") == 0 || _stricmp(pszKey, "UploadPhoto") == 0) {
  1209. strPath = CSimpleStringA(env->cfg->root_ini->ref_uploadphoto_path);
  1210. } else if (_stricmp(pszKey, "Download") == 0 || _stricmp(pszKey, "Downloads") == 0) {
  1211. strPath = CSimpleStringA(env->cfg->root_ini->ref_downloads_path);
  1212. } else if (_stricmp(pszKey, "Upgraded") == 0){
  1213. strPath = CSimpleStringA(env->cfg->root_ini->ref_upgraded_path);
  1214. } else if (_stricmp(pszKey, "Ad") == 0) {
  1215. strPath = CSimpleStringA(env->cfg->root_ini->ref_addata_path);
  1216. } else if (_stricmp(pszKey, "UploadPhoto") == 0) {
  1217. strPath = CSimpleStringA(env->cfg->root_ini->ref_uploadphoto_path);
  1218. } else if (_stricmp(pszKey, "UploadVideo") == 0) {
  1219. strPath = CSimpleStringA(env->cfg->root_ini->ref_uploadvideo_path);
  1220. } else if (_stricmp(pszKey, "Dbg") == 0) {
  1221. strPath = CSimpleStringA(env->dir->dbg_path);
  1222. } else if (_stricmp(pszKey, "Slv") == 0) {
  1223. strPath = CSimpleStringA(env->dir->slv_path);
  1224. }
  1225. else if (_stricmp(pszKey, "DepBase") == 0) {
  1226. strPath = CSimpleStringA(env->dir->dep_base_path);
  1227. }
  1228. else if (_stricmp(pszKey, "DepBak") == 0) {
  1229. strPath = CSimpleStringA(env->dir->dep_path);
  1230. }
  1231. else if (_stricmp(pszKey, "Dep") == 0) {
  1232. if (env->dir->dep_ver_path == NULL) {
  1233. sp_dir_refresh_dep_path(env->dir);
  1234. }
  1235. if (env->dir->dep_ver_path == NULL) {
  1236. Error = Error_NotInit;
  1237. }
  1238. else {
  1239. strPath = CSimpleStringA(env->dir->dep_ver_path);
  1240. }
  1241. }
  1242. else if (_stricmp(pszKey, "Ad0") == 0) {
  1243. strPath = CSimpleStringA(env->dir->ad0_path);
  1244. } else if (_stricmp(pszKey, "Dmp") == 0 || _stricmp(pszKey, "Dump") == 0) {
  1245. strPath = CSimpleStringA(env->dir->dmp_path);
  1246. } else if (_stricmp(pszKey, "RunInfo") == 0){
  1247. strPath = CSimpleStringA(env->dir->root_runinfo_path);
  1248. } else if (_stricmp(pszKey, "RunCfg") == 0) {
  1249. strPath = CSimpleStringA(env->dir->root_runinfo_path);
  1250. strPath += SPLIT_SLASH_STR;
  1251. strPath += "runcfg";
  1252. } else if (_stricmp(pszKey, "HardwareCfg") == 0) {
  1253. strPath = CSimpleStringA(env->dir->root_hardwarecfg_path);
  1254. } else if (_stricmp(pszKey, "CenterSetting") == 0) {
  1255. // return centersetting name by current site
  1256. strPath = CSimpleStringA(env->dir->cfg_path);
  1257. strPath += SPLIT_SLASH_STR;
  1258. strPath += "CenterSetting.ini";
  1259. } else if (_stricmp(pszKey, "rvc") == 0) {
  1260. strPath = CSimpleStringA(env->dir->rvc_path);
  1261. } else {
  1262. char *path = sp_cfg_get_path(env->cfg, pszKey);
  1263. if (path) {
  1264. strPath = path;
  1265. } else {
  1266. Error = Error_Param;
  1267. }
  1268. }
  1269. return Error;
  1270. }
  1271. ErrorCodeEnum SpEntity::GetSystemRunInfo(CSystemRunInfo &Info)
  1272. {
  1273. sp_env_t *env = sp_get_env();
  1274. sp_cfg_t *cfg = env->cfg;
  1275. Info.eDebugLevel = (DebugLevelEnum)cfg->shell_ini->shell_debug_level;
  1276. Info.tmStart = cfg->run_info->startup_time;
  1277. Info.dwBootOption = 0;
  1278. if (cfg->args->debug_mode)
  1279. Info.dwBootOption |= BootOption_Debug;
  1280. if (cfg->args->test_mode) {
  1281. if (cfg->args->test_mode & 1) {
  1282. Info.dwBootOption |= BootOption_Test;
  1283. }
  1284. if (cfg->args->test_mode & 2) {
  1285. Info.dwBootOption |= BootOption_Test;
  1286. Info.dwBootOption |= BootOption_Benchmark;
  1287. }
  1288. if (cfg->args->test_mode & 4) {
  1289. Info.dwBootOption |= BootOption_ST;
  1290. }
  1291. if (cfg->args->test_mode & 8) {
  1292. Info.dwBootOption |= BootOption_UAT;
  1293. }
  1294. }
  1295. #ifndef DEVOPS_ON_PRD
  1296. //非生产情况下,才支持测试模式
  1297. Info.autoTest = FALSE;
  1298. if (cfg->args->auto_test)
  1299. {
  1300. Info.autoTest = TRUE;
  1301. }
  1302. #endif
  1303. if (cfg->args->start_entities != NULL && strlen(cfg->args->start_entities) != 0) {
  1304. Info.dwBootOption |= BootOption_Entity;
  1305. }
  1306. if (!!cfg->args->root) {
  1307. Info.dwBootOption |= BootOption_RootPrivilege;
  1308. }
  1309. sp_mod_mgr_t *mod_mgr = env->mod_mgr;
  1310. sp_mod_t *pos;
  1311. array_header_t *arr = array_make(16, sizeof(char*));
  1312. list_for_each_entry(pos, sp_mod_mgr_get_module_list_head(mod_mgr), sp_mod_t, entry) {
  1313. if (pos->loaded) {
  1314. sp_entity_t *ent;
  1315. list_for_each_entry(ent, &pos->entity_list, sp_entity_t, entry) {
  1316. int state = ent->state;
  1317. if (state == EntityState_Idle || state == EntityState_Busy || state == EntityState_Pause) {
  1318. ARRAY_PUSH(arr, char*) = ent->cfg->name;
  1319. }
  1320. }
  1321. }
  1322. }
  1323. Info.strRunningEntityNames.Init(arr->nelts);
  1324. for (int i = 0; i < arr->nelts; ++i) {
  1325. Info.strRunningEntityNames[i] = CSimpleStringA(ARRAY_IDX(arr, i, char*));
  1326. }
  1327. array_free(arr);
  1328. Info.eAppBootState = (AppBootStateEnum)env->cfg->shell_ini->shell_state;
  1329. if (env == NULL || env->cfg == NULL || env->cfg->root_ini == NULL)
  1330. {
  1331. Info.bErrCfgWork = false;
  1332. Info.bBasicCfgWork = false;
  1333. return Error_Succeed;
  1334. }
  1335. if (env->cfg->root_ini->vtm_err_msg_config == NULL || strlen(env->cfg->root_ini->vtm_err_msg_config) == 0)
  1336. Info.bErrCfgWork = false;
  1337. else
  1338. Info.bErrCfgWork = true;
  1339. if (env->cfg->root_ini->root_config == NULL
  1340. || env->cfg->root_ini->center_config == NULL
  1341. || env->cfg->root_ini->shell_config == NULL
  1342. || strlen(env->cfg->root_ini->root_config) == 0
  1343. || strlen(env->cfg->root_ini->center_config) == 0
  1344. || strlen(env->cfg->root_ini->shell_config) == 0)
  1345. Info.bBasicCfgWork = false;
  1346. else
  1347. Info.bBasicCfgWork = true;
  1348. return Error_Succeed;
  1349. }
  1350. ErrorCodeEnum SpEntity::GetEntityBusyRate(WORD &nBusyEntity,WORD &nAllEntity)
  1351. {
  1352. sp_env_t *env = sp_get_env();
  1353. sp_mod_mgr_t *mod_mgr = env->mod_mgr;
  1354. int nAll(0), nBusy(0);
  1355. sp_mod_t *mod;
  1356. list_for_each_entry(mod, sp_mod_mgr_get_module_list_head(mod_mgr), sp_mod_t, entry)
  1357. {
  1358. if (mod->loaded)
  1359. {
  1360. sp_entity_t *ent;
  1361. list_for_each_entry(ent, &mod->entity_list, sp_entity_t, entry)
  1362. {
  1363. int state = ent->state;
  1364. if (state == EntityState_Idle || state == EntityState_Busy || state == EntityState_Pause)
  1365. nAll++;
  1366. if (state == EntityState_Busy)
  1367. nBusy++;
  1368. }
  1369. }
  1370. nBusyEntity = nBusy;
  1371. nAllEntity = nAll;
  1372. }
  1373. return Error_Succeed;
  1374. }
  1375. ErrorCodeEnum SpEntity::GetRebootInfo(CSmallDateTime BeforeThisTime, CBootInfo &Info)
  1376. {
  1377. CSimpleStringA strPath;
  1378. auto rc = GetPath("RunInfo", strPath);
  1379. if (rc != Error_Succeed)
  1380. return rc;
  1381. strPath += SPLIT_SLASH_STR "BootLog";
  1382. sp_env_t *env = sp_get_env();
  1383. auto pRec = sp_btr_get_rec_before(strPath, env->btr_ctx, BeforeThisTime);
  1384. if (pRec == NULL)
  1385. return Error_NotExist;
  1386. Info.tmStart = pRec->tm_start;
  1387. Info.tmReboot = pRec->tm_shutdown;
  1388. Info.InstallVersion = CVersion(pRec->version.major, pRec->version.minor, pRec->version.revision, pRec->version.build);
  1389. Info.eTriggerReason = (RebootTriggerEnum)pRec->shutdown_reason;
  1390. Info.eWay = (RebootWayEnum)pRec->shutdown_way;
  1391. Info.wSameReasonTime = pRec->shutdown_reason_cnt;
  1392. Info.wSameWayTime = pRec->shutdown_way_cnt;
  1393. delete pRec;
  1394. return Error_Succeed;
  1395. }
  1396. ErrorCodeEnum SpEntity::GetAllRegistSpFile(CAutoArray<CSimpleStringA> &Names)
  1397. {
  1398. sp_env_t *env = sp_get_env();
  1399. sp_cfg_t *cfg = env->cfg;
  1400. array_header_t *arr_module = cfg->shell_ini->arr_module;
  1401. Names.Init(arr_module->nelts);
  1402. for (int i = 0; i < arr_module->nelts; ++i) {
  1403. sp_cfg_shell_module_t* mod = ARRAY_IDX(arr_module, i, sp_cfg_shell_module_t*);
  1404. Names[i] = mod->name;
  1405. }
  1406. return Error_Succeed;
  1407. }
  1408. ErrorCodeEnum SpEntity::GetSpFileInfo(const char *pszSpName,CSpInfo &Info)
  1409. {
  1410. if (!pszSpName)
  1411. return Error_Null;
  1412. sp_env_t *env = sp_get_env();
  1413. sp_cfg_t *cfg = env->cfg;
  1414. sp_cfg_shell_module_t *cfg_mod = sp_cfg_get_module_by_name(cfg, pszSpName);
  1415. if (!cfg_mod)
  1416. return Error_NotExist;
  1417. Info.strAuthor = cfg_mod->author;
  1418. Info.strCompany = cfg_mod->company;
  1419. Info.SoftwareVersion = CVersion((WORD)cfg_mod->version.major,
  1420. (WORD)cfg_mod->version.minor,
  1421. (WORD)cfg_mod->version.revision,
  1422. (WORD)cfg_mod->version.build);
  1423. sp_mod_mgr_t *mod_mgr = env->mod_mgr;
  1424. sp_mod_t *mod = sp_mod_mgr_find_module_by_name(mod_mgr, pszSpName);
  1425. if (!mod)
  1426. return Error_NotExist;
  1427. sp_entity_t *ent;
  1428. int cnt = 0;
  1429. list_for_each_entry(ent, &mod->entity_list, sp_entity_t, entry) {
  1430. cnt++;
  1431. }
  1432. Info.strEntitys.Init(cnt);
  1433. int i = 0;
  1434. list_for_each_entry(ent, &mod->entity_list, sp_entity_t, entry) {
  1435. Info.strEntitys[i++] = ent->cfg->name;
  1436. }
  1437. return Error_Succeed;
  1438. }
  1439. ErrorCodeEnum SpEntity::GetAllRegistedEntity(CAutoArray<CSimpleStringA> &strEntityNames, CAutoArray<WORD> &wEntityDevelopIDs)
  1440. {
  1441. sp_env_t *env = sp_get_env();
  1442. sp_cfg_t *cfg = env->cfg;
  1443. array_header_t *arr_entity = cfg->shell_ini->arr_entity;
  1444. strEntityNames.Init(arr_entity->nelts-1);
  1445. wEntityDevelopIDs.Init(arr_entity->nelts-1);
  1446. for (int i = 1; i < arr_entity->nelts; ++i) { // from index 1, because zero for special entity, ie. spshell entity
  1447. sp_cfg_shell_entity_t *ent = ARRAY_IDX(arr_entity, i, sp_cfg_shell_entity_t*);
  1448. strEntityNames[i-1] = ent->name;
  1449. wEntityDevelopIDs[i-1] = ent->devel_id;
  1450. }
  1451. return Error_Succeed;
  1452. }
  1453. ErrorCodeEnum SpEntity::GetAllEntityStartInfo(CAutoArray<CSimpleStringA>& strEntityNames, CAutoArray<int>& strEntityIdx, CAutoArray<CEntityStartInfo>& Infos)
  1454. {
  1455. sp_env_t* env = sp_get_env();
  1456. sp_cfg_t* cfg = env->cfg;
  1457. array_header_t* arr_entity = cfg->shell_ini->arr_entity;
  1458. strEntityNames.Init(arr_entity->nelts);
  1459. strEntityIdx.Init(arr_entity->nelts);
  1460. Infos.Init(arr_entity->nelts);
  1461. for (int i = 0; i < arr_entity->nelts; ++i) {
  1462. sp_cfg_shell_entity_t* ent = ARRAY_IDX(arr_entity, i, sp_cfg_shell_entity_t*);
  1463. strEntityNames[i] = ent->name;
  1464. strEntityIdx[i] = ent->idx;
  1465. Infos[i].startTimes = ent->m_startTimes;
  1466. #if defined(_MSC_VER)
  1467. FileTimeToSystemTime(&ent->m_EntityStartTime.filetimePart, &(Infos[i].startTime));
  1468. FileTimeToSystemTime(&ent->m_EntityInitEndTime.filetimePart, &(Infos[i].InitEndTime));
  1469. FileTimeToSystemTime(&ent->m_EntityStartEndTime.filetimePart, &(Infos[i].startEndTime));
  1470. #else
  1471. memcpy(&Infos[i].startTime, &ent->m_EntityStartTime, sizeof(SYSTEMTIME));
  1472. memcpy(&Infos[i].InitEndTime, &ent->m_EntityInitEndTime, sizeof(SYSTEMTIME));
  1473. memcpy(&Infos[i].startEndTime, &ent->m_EntityStartEndTime, sizeof(SYSTEMTIME));
  1474. #endif //_MSC_VER
  1475. }
  1476. return Error_Succeed;
  1477. }
  1478. ErrorCodeEnum SpEntity::GetEntityLogPath(const char* pszEntityName, CEntityLogInfo& Info)
  1479. {
  1480. if (pszEntityName != NULL) {
  1481. sp_env_t* env = sp_get_env();
  1482. auto pEntity = sp_cfg_get_entity_by_name(env->cfg, pszEntityName);
  1483. if (pEntity != NULL) {
  1484. char tmp[MAX_PATH] = { 0 };
  1485. auto mod_name = pEntity->mod->name;
  1486. sp_dir_get_path(env->dir, SP_DIR_ENTITY_DBG_LOG, mod_name, tmp, sizeof(tmp));
  1487. Info.strLogPath = tmp;
  1488. return ErrorCodeEnum::Error_Succeed;
  1489. }
  1490. }
  1491. return ErrorCodeEnum::Error_Unexpect;
  1492. }
  1493. ErrorCodeEnum SpEntity::GetAllStartedEntity(CAutoArray<CSimpleStringA> &strEntityNames, CAutoArray<DWORD> &dwEntityInstanceIDs)
  1494. {
  1495. sp_env_t *env = sp_get_env();
  1496. sp_mod_mgr_t *mod_mgr = env->mod_mgr;
  1497. sp_mod_t *pos;
  1498. int i;
  1499. array_header_t *arr = array_make(16, sizeof(sp_entity_t*));
  1500. list_for_each_entry(pos, sp_mod_mgr_get_module_list_head(mod_mgr), sp_mod_t, entry) {
  1501. if (pos->loaded) {
  1502. sp_entity_t *ent;
  1503. list_for_each_entry(ent, &pos->entity_list, sp_entity_t, entry) {
  1504. int state = ent->state;
  1505. if (state == EntityState_Idle || state == EntityState_Busy || state == EntityState_Pause) {
  1506. ARRAY_PUSH(arr, sp_entity_t*) = ent;
  1507. }
  1508. }
  1509. }
  1510. }
  1511. strEntityNames.Init(arr->nelts);
  1512. dwEntityInstanceIDs.Init(arr->nelts);
  1513. for (i = 0; i < arr->nelts; ++i) {
  1514. sp_entity_t *ent = ARRAY_IDX(arr, i, sp_entity_t*);
  1515. strEntityNames[i] = ent->cfg->name;
  1516. dwEntityInstanceIDs[i] = ent->instance_id;
  1517. }
  1518. // {bug} forget array_free(arr)
  1519. array_free(arr);
  1520. return Error_Succeed;
  1521. }
  1522. ErrorCodeEnum SpEntity::GetSelfEntityRunInfo(CEntityRunInfo &Info)
  1523. {
  1524. return GetEntityRunInfo(m_ent->cfg->name, Info);
  1525. }
  1526. ErrorCodeEnum SpEntity::GetEntityStaticInfo(const char *pszEntityName,CEntityStaticInfo &Info)
  1527. {
  1528. if (!pszEntityName)
  1529. return Error_Null;
  1530. sp_env_t *env = sp_get_env();
  1531. sp_entity_t *ent = sp_mod_mgr_find_entity_by_name(env->mod_mgr, pszEntityName);
  1532. return ::GetEntityStaticInfo(Info, ent);
  1533. }
  1534. ErrorCodeEnum SpEntity::GetToken(CSimpleString &channelId, CSimpleString &token)
  1535. {
  1536. sp_env_t* env = sp_get_env();
  1537. channelId = env->cfg->shell_ini->channelId;
  1538. token = env->cfg->shell_ini->token;
  1539. if (channelId.GetLength() == 0 || token.GetLength() == 0)
  1540. return ErrorCodeEnum::Error_NotConfig;
  1541. else
  1542. return ErrorCodeEnum::Error_Succeed;
  1543. }
  1544. ErrorCodeEnum SpEntity::GetEntityStaticInfo(WORD wEntitySerialNO, CEntityStaticInfo &Info)
  1545. {
  1546. sp_env_t *env = sp_get_env();
  1547. sp_entity_t *ent = sp_mod_mgr_find_entity_by_devel_id(env->mod_mgr, wEntitySerialNO);
  1548. return ::GetEntityStaticInfo(Info, ent);
  1549. }
  1550. ErrorCodeEnum SpEntity::GetEntityRunInfo(const char *pszEntityName, CEntityRunInfo &Info)
  1551. {
  1552. sp_env_t *env = sp_get_env();
  1553. if (!pszEntityName)
  1554. return Error_Null;
  1555. sp_mod_mgr_t *mod_mgr = env->mod_mgr;
  1556. sp_entity_t *ent = sp_mod_mgr_find_entity_by_name(mod_mgr, pszEntityName);
  1557. if (!ent)
  1558. return Error_NotExist;
  1559. Info.dwEntityInstanceID = (DWORD)ent->instance_id;
  1560. Info.tmFirstStart = ent->first_start_time;
  1561. Info.tmLastStart = ent->last_start_time;
  1562. Info.bService = !!ent->service_flag;
  1563. Info.eState = (EntityStateEnum)ent->state;
  1564. Info.tmBeginCurrentState = ent->state_start_time;
  1565. Info.dwProcessID = (DWORD)ent->mod->process.pid;
  1566. Info.eDebugLevel = (DebugLevelEnum)ent->cfg->debug_level;
  1567. Info.dwUserState = (DWORD)ent->user_state;
  1568. return Error_Succeed;
  1569. }
  1570. ErrorCodeEnum SpEntity::GetEntityName(WORD wEntityDevelopID, CSimpleStringA &strName)
  1571. {
  1572. sp_env_t *env = sp_get_env();
  1573. sp_entity_t *ent = sp_mod_mgr_find_entity_by_devel_id(env->mod_mgr, wEntityDevelopID);
  1574. if (ent) {
  1575. strName = ent->cfg->name;
  1576. } else {
  1577. return Error_NotExist;
  1578. }
  1579. return Error_Succeed;
  1580. }
  1581. ErrorCodeEnum SpEntity::GetEntityName(DWORD dwEntityInstanceID, CSimpleStringA &strName)
  1582. {
  1583. TOOLKIT_ASSERT(dwEntityInstanceID != 0);
  1584. sp_env_t *env = sp_get_env();
  1585. sp_entity_t *ent = sp_mod_mgr_find_entity_by_inst_id(env->mod_mgr, dwEntityInstanceID);
  1586. if (ent) {
  1587. strName = ent->cfg->name;
  1588. } else {
  1589. return Error_NotExist;
  1590. }
  1591. return Error_Succeed;
  1592. }
  1593. ErrorCodeEnum SpEntity::GetModuleName(DWORD nModuleID, CSimpleStringA &strName)
  1594. {
  1595. if (nModuleID != SP_INVALID_MOD_ID) {
  1596. sp_env_t *env = sp_get_env();
  1597. sp_mod_t *mod = sp_mod_mgr_find_module_by_idx(env->mod_mgr, nModuleID);
  1598. if (mod) {
  1599. strName = mod->cfg->name;
  1600. return Error_Succeed;
  1601. } else {
  1602. return Error_NotExist;
  1603. }
  1604. }
  1605. return Error_Param;
  1606. }
  1607. ErrorCodeEnum SpEntity::GetEntitySessionInfo(const char *pszEntityName, CAutoArray<CEntitySessionInfo> &Infos)
  1608. {
  1609. iobuffer_t *req_pkt = iobuffer_create(-1, -1);
  1610. iobuffer_t *ans_pkt = NULL;
  1611. auto rc = AskEntityByRPC(pszEntityName, ENTITY_CMD_REQ_QUERY_ENTITY_SESSIONS, &req_pkt, &ans_pkt);
  1612. if (rc == Error_Succeed)
  1613. {
  1614. int nCount(0);
  1615. iobuffer_read(ans_pkt, IOBUF_T_I4, &nCount, NULL);
  1616. auto pCfg = sp_get_env()->cfg;
  1617. Infos.Init(nCount);
  1618. for (int i = 0; i < nCount; ++i)
  1619. {
  1620. int nFromSvcID, nToSvcID, nBeginTime, nState, nStateBeginTime;
  1621. iobuffer_format_read(ans_pkt, "44444", &nFromSvcID, &nToSvcID, &nBeginTime, &nState, &nStateBeginTime);
  1622. Infos[i].strCallerEntity = sp_cfg_get_entity_by_idx(pCfg, nFromSvcID)->name;
  1623. Infos[i].strServiceEntity = sp_cfg_get_entity_by_idx(pCfg, nToSvcID)->name;
  1624. Infos[i].tmStart = CSmallDateTime(nBeginTime);
  1625. Infos[i].eState = (SessionStateEnum)nState;
  1626. Infos[i].tmBeginState = CSmallDateTime(nStateBeginTime);
  1627. }
  1628. }
  1629. if (req_pkt)
  1630. iobuffer_dec_ref(req_pkt);
  1631. if (ans_pkt)
  1632. iobuffer_dec_ref(ans_pkt);
  1633. return rc;
  1634. }
  1635. bool SpEntity::HasPrivilege()
  1636. {
  1637. return !!m_cfg_ent->privilege;
  1638. }
  1639. CSmartPointer<IEntityFunctionPrivilege> SpEntity::GetPrivilegeFunction()
  1640. {
  1641. return NULL;
  1642. }
  1643. ErrorCodeEnum SpEntity::PostQuit()
  1644. {
  1645. ErrorCodeEnum Error;
  1646. iobuffer_t *pkt = iobuffer_create(-1, -1);
  1647. int v = m_ent->cfg->idx;
  1648. iobuffer_write(pkt, IOBUF_T_I4, &v, 0);
  1649. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Pre PostQuit...");
  1650. Error = PostInfoShell(SHELL_CMD_INFO_ENTITY_QUIT, &pkt);
  1651. if (pkt)
  1652. iobuffer_dec_ref(pkt);
  1653. return Error;
  1654. }
  1655. ErrorCodeEnum SpEntity::PostReload()
  1656. {
  1657. ErrorCodeEnum Error;
  1658. iobuffer_t *pkt = iobuffer_create(-1, -1);
  1659. int v = m_ent->cfg->idx;
  1660. iobuffer_write(pkt, IOBUF_T_I4, &v, 0);
  1661. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Pre PostReload...");
  1662. Error = PostInfoShell(SHELL_CMD_INFO_ENTITY_RELOAD, &pkt);
  1663. if (pkt)
  1664. iobuffer_dec_ref(pkt);
  1665. return Error;
  1666. }
  1667. ErrorCodeEnum SpEntity::PostEntityTaskFIFO(ITaskSp *pTask)
  1668. {
  1669. threadpool_t *threadpool = sp_svc_get_threadpool(m_svc);
  1670. int rc;
  1671. rc = threadpool_post_workitem_fifo2(threadpool, NULL, &task_callback, pTask, (param_size_t)((intptr_t)this), 0);
  1672. return rc == 0 ? Error_Succeed : Error_Unexpect;
  1673. }
  1674. ErrorCodeEnum SpEntity::PostEntityTaskLIFO(ITaskSp *pTask)
  1675. {
  1676. threadpool_t *threadpool = sp_svc_get_threadpool(m_svc);
  1677. int rc;
  1678. rc = threadpool_post_workitem_lifo2(threadpool, NULL, &task_callback, pTask, (param_size_t)((intptr_t)this), 0);
  1679. return rc == 0 ? Error_Succeed : Error_Unexpect;
  1680. }
  1681. ErrorCodeEnum SpEntity::PostThreadPoolTask(ITaskSp *pTask)
  1682. {
  1683. int rc = threadpool_post_workitem_fifo2(m_tpool, NULL, &task_callback, pTask, (param_size_t)((intptr_t)this), 0);
  1684. return rc == 0 ? Error_Succeed : Error_Unexpect;
  1685. }
  1686. ErrorCodeEnum SpEntity::StartTcpBridgeServer(unsigned short port)
  1687. {
  1688. if (port >4506 || port < 4502)
  1689. return Error_Duplication;
  1690. #ifdef _DEBUG
  1691. const char *ip = "0.0.0.0";
  1692. #else
  1693. const char *ip = "127.0.0.1";
  1694. #endif
  1695. if (m_tbs)
  1696. return Error_Duplication;
  1697. int rc = sp_tbs_create(m_ses_mgr, ip, port, &m_tbs);
  1698. if (rc == 0) {
  1699. rc = sp_tbs_start(m_tbs);
  1700. if (rc != 0) {
  1701. sp_tbs_destroy(m_tbs);
  1702. m_tbs = NULL;
  1703. }
  1704. }
  1705. return SpTranslateError(rc);
  1706. }
  1707. ErrorCodeEnum SpEntity::StopTcpBridgeServer()
  1708. {
  1709. if (m_tbs) {
  1710. sp_tbs_stop(m_tbs);
  1711. sp_tbs_destroy(m_tbs);
  1712. m_tbs = NULL;
  1713. return Error_Succeed;
  1714. } else {
  1715. return Error_NotInit;
  1716. }
  1717. }
  1718. void SpEntity::SetPostLinkFun(postLink cur)
  1719. {
  1720. }
  1721. ErrorCodeEnum SpEntity::RequestCloseDelay(WORD nSecond)
  1722. {
  1723. return Error_NotImpl;
  1724. }
  1725. void SpEntity::SendLog(const LogTypeEnum eLogType,const SeverityLevelEnum eLevel,
  1726. DWORD dwUserEventCode,CAutoArray<DWORD> Param,const char *pszMessage)
  1727. {
  1728. LogMessage(eLogType, eLevel, 0, dwUserEventCode, Param, pszMessage);
  1729. }
  1730. ErrorCodeEnum SpEntity::VerifySignature(const char *pszSignedFile, CSimpleStringA &strErrInfo)
  1731. {
  1732. #ifdef RVC_OS_WIN
  1733. CCodeSignVerify verify;
  1734. CSignInfo signInfo;
  1735. if (!verify.VerifySignature(pszSignedFile, signInfo))
  1736. {
  1737. strErrInfo = verify.GetErrorMsg();
  1738. return Error_FailVerify;
  1739. }
  1740. // xkm@20140905: 检查签名证书Hash是否同SpBase签名证书Hash一致
  1741. sp_env_t *env = sp_get_env();
  1742. assert(env != NULL);
  1743. auto pShellCfg = env->cfg->shell_ini;
  1744. if (pShellCfg->spbase_sign_cert_hash != NULL && stricmp(pShellCfg->spbase_sign_cert_hash, signInfo.strSignCertHash) != 0)
  1745. {
  1746. strErrInfo = "签名证书非授权证书";
  1747. return Error_FailVerify;
  1748. }
  1749. strErrInfo = signInfo.strSignCertHash;
  1750. return Error_Succeed;
  1751. #else
  1752. strErrInfo = "TODO: not implement VerifySignature current times.";
  1753. //return Error_NotImpl;
  1754. #endif //RVC_OS_WIN
  1755. return Error_Succeed;
  1756. }
  1757. ErrorCodeEnum SpEntity::ShowFatalError(const char *pszMsg, SeverityLevelEnum eLevel)
  1758. {
  1759. #if defined(RVC_OS_WIN)
  1760. LogError(Severity_High, Error_Unrecover, 0, pszMsg);
  1761. #endif //RVC_OS_WIN
  1762. ErrorCodeEnum Error;
  1763. iobuffer_t *pkt = iobuffer_create(-1, -1);
  1764. int v = (int)eLevel;
  1765. iobuffer_write(pkt, IOBUF_T_I4, &v, 0);
  1766. #if defined(RVC_OS_LINUX)
  1767. CSimpleStringA strMsg = m_pEntityBase->GetEntityName();
  1768. strMsg += " V";
  1769. strMsg += m_pEntityBase->GetEntityVersion();
  1770. strMsg += ":][:"; /** arrange with QtGUIConsole to split entity name and msg content [Gifur@202128]*/
  1771. strMsg += pszMsg;
  1772. iobuffer_write(pkt, IOBUF_T_STR, (const char*)strMsg, -1);
  1773. #else
  1774. iobuffer_write(pkt, IOBUF_T_STR, pszMsg, -1);
  1775. #endif //RVC_OS_LINUX
  1776. Error = PostInfoShell(SHELL_CMD_INFO_FATAL_ERROR_DISPLAY, &pkt);
  1777. if (pkt)
  1778. iobuffer_dec_ref(pkt);
  1779. return Error;
  1780. }
  1781. ErrorCodeEnum SpEntity::ShowStartupInfo(const char *pszMsg)
  1782. {
  1783. LogEvent(Severity_High, 0, pszMsg);
  1784. ErrorCodeEnum Error;
  1785. iobuffer_t *pkt = iobuffer_create(-1, -1);
  1786. iobuffer_write(pkt, IOBUF_T_STR, pszMsg, -1);
  1787. Error = PostInfoShell(SHELL_CMD_INFO_STARTUP_INFO_DISPLAY, &pkt);
  1788. if (pkt)
  1789. iobuffer_dec_ref(pkt);
  1790. return Error;
  1791. }
  1792. void SpEntity::ResetEntityLastError()
  1793. {
  1794. if (m_ent) {
  1795. m_ent->last_err.sys_code = m_ent->last_err.usr_code = 0;
  1796. memset(m_ent->last_err.msg, '\0', sizeof(m_ent->last_err.msg));
  1797. }
  1798. }
  1799. ErrorCodeEnum SpEntity::GetRunningVersion(CSimpleString& ver)
  1800. {
  1801. char dstVer[SP_MAX_VER_LEN] = "";
  1802. auto ret = sp_cfg_getVer(dstVer);
  1803. if (ret == Error_Succeed)
  1804. ver = dstVer;
  1805. return (ErrorCodeEnum)ret;
  1806. }
  1807. ErrorCodeEnum SpEntity::GetRunningDepVersion(CSimpleString& ver)
  1808. {
  1809. char dstVer[SP_MAX_VER_LEN] = "";
  1810. auto ret = sp_cfg_getDepVer(dstVer);
  1811. if (ret == Error_Succeed)
  1812. ver = dstVer;
  1813. return (ErrorCodeEnum)ret;
  1814. }
  1815. struct ErrMsgStruct {
  1816. std::string VTMCode;
  1817. std::string errMsg;
  1818. // 带参数的构造函数,参数有默认值
  1819. ErrMsgStruct(const std::string& tmp_VTMCode = "", const std::string& tmp_errMsg = "") : VTMCode(tmp_VTMCode), errMsg(tmp_errMsg) {}
  1820. };
  1821. ErrorCodeEnum SpEntity::GetVTMErrMsg(DWORD dwUserCode, CSimpleStringA& strDescription, CSimpleStringA& strVTMCode)
  1822. {
  1823. sp_env_t* env = sp_get_env();
  1824. if (env->cfg->root_ini->vtm_err_msg_config == NULL || strlen(env->cfg->root_ini->vtm_err_msg_config) == 0)
  1825. {
  1826. strVTMCode = "RTA42F0";
  1827. strDescription = "微服务异常";
  1828. return ErrorCodeEnum::Error_NotConfig;
  1829. }
  1830. std::string userCodeStr = CSimpleString::Format("0x%X", dwUserCode).GetData();
  1831. std::transform(userCodeStr.begin(), userCodeStr.end(), userCodeStr.begin(), [](unsigned char c) { return std::tolower(c); });
  1832. static std::map<std::string, ErrMsgStruct> m_UserCodeToMsgTip;
  1833. static bool isInit = false;
  1834. if (!isInit)//Some entities may have no UserCode
  1835. {
  1836. CAutoArray<CSimpleStringA> strErrorCodeArr;
  1837. CAutoArray<CSimpleStringA> strDescriptionArr;
  1838. CAutoArray<CSimpleStringA> strRemarkArr;
  1839. ConvertStrToVTMErrMsg(env->cfg->root_ini->vtm_err_msg_config, strErrorCodeArr, strDescriptionArr, strRemarkArr);
  1840. auto intToHex = [](int num) -> std::string {
  1841. const char hexChars[] = "0123456789ABCDEF";
  1842. std::string hexStr;
  1843. // 将整数的每个字节转换为对应的16进制字符
  1844. for (int i = sizeof(num) - 1; i >= 0; --i) {
  1845. unsigned char byte = (num >> (8 * i)) & 0xFF;
  1846. if (byte == 0 && hexStr.empty()) {
  1847. continue; // 跳过前导零
  1848. }
  1849. hexStr += hexChars[byte >> 4];
  1850. hexStr += hexChars[byte & 0x0F];
  1851. }
  1852. return hexStr;
  1853. };
  1854. auto hexToInt = [](const std::string& hexStr)-> int {
  1855. std::stringstream ss;
  1856. ss << std::hex << hexStr;
  1857. int num;
  1858. ss >> num;
  1859. return num;
  1860. };
  1861. auto intTo36 = [](int num) -> std::string {
  1862. std::string base36Chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  1863. std::string base36Str;
  1864. while (num > 0) {
  1865. base36Str = base36Chars[num % 36] + base36Str;
  1866. num /= 36;
  1867. }
  1868. return base36Str;
  1869. };
  1870. int id = GetDevID();
  1871. auto idHexStr = intToHex(id);
  1872. if (idHexStr.length() != 4 || idHexStr[0] != '0')
  1873. {
  1874. strVTMCode = "RTA42F2";
  1875. strDescription = "实体Id异常";
  1876. return ErrorCodeEnum::Error_Unregisted;
  1877. }
  1878. std::string dstRTA = "RTA";
  1879. dstRTA.push_back(idHexStr[1]); //first
  1880. std::string lastTwoDigits = idHexStr.substr(idHexStr.length() - 2); // last two digits
  1881. int num = hexToInt(lastTwoDigits);
  1882. if (num < 0 || num >= 36) {
  1883. strVTMCode = "RTA42F2";
  1884. strDescription = "无法转换实体Id";
  1885. return ErrorCodeEnum::Error_DataCheck;
  1886. }
  1887. std::string base36Str = intTo36(num);
  1888. dstRTA.append(base36Str);
  1889. for (int i = 0; i < strErrorCodeArr.GetCount(); i++)
  1890. {
  1891. //if (strErrorCodeArr[i].IsStartWith(dstRTA.c_str(), true))
  1892. //{
  1893. std::string curRemark = strRemarkArr[i].GetData();
  1894. std::transform(curRemark.begin(), curRemark.end(), curRemark.begin(), [](unsigned char c) { return std::tolower(c); });
  1895. m_UserCodeToMsgTip.insert(std::make_pair(curRemark, ErrMsgStruct(strErrorCodeArr[i].GetData(), strDescriptionArr[i].GetData())));
  1896. //}
  1897. }
  1898. isInit = true;
  1899. }
  1900. if (m_UserCodeToMsgTip.find(userCodeStr) != m_UserCodeToMsgTip.end())
  1901. {
  1902. strVTMCode = m_UserCodeToMsgTip[userCodeStr].VTMCode.c_str();
  1903. strDescription = m_UserCodeToMsgTip[userCodeStr].errMsg.c_str();
  1904. return ErrorCodeEnum::Error_Succeed;
  1905. }
  1906. else
  1907. {
  1908. strVTMCode = "RTA42F1";
  1909. strDescription = "错误映射异常";
  1910. return ErrorCodeEnum::Error_NotExist;
  1911. }
  1912. }
  1913. CSimpleStringA SpEntity::UserCodeToRTACode(DWORD dwUserCode)
  1914. {
  1915. CSimpleStringA tmpDesc, tmpVtmCode("");
  1916. //transmit the return of GetVTMErrMsg directly
  1917. GetVTMErrMsg(dwUserCode, tmpDesc, tmpVtmCode);
  1918. return CSimpleStringA(tmpVtmCode);
  1919. }
  1920. ErrorCodeEnum SpEntity::SetSelfPriority(EntityPriorityEnum nPriority)
  1921. {
  1922. ErrorCodeEnum result(Error_Succeed);
  1923. CEntityRunInfo info;
  1924. result = GetEntityRunInfo(m_ent->cfg->name, info);
  1925. if (result == Error_Succeed) {
  1926. #if defined(_MSC_VER)
  1927. int priviliegeValue = TOOLKIT_PRIORITY_NORMAL;
  1928. switch (nPriority) {
  1929. case Priority_Low:
  1930. priviliegeValue = TOOLKIT_PRIORITY_LOW;
  1931. break;
  1932. case Priority_Below_Normal:
  1933. priviliegeValue = TOOLKIT_PRIORITY_BELOW_NORMAL;
  1934. break;
  1935. case Priority_Normal:
  1936. priviliegeValue = TOOLKIT_PRIORITY_NORMAL;
  1937. break;
  1938. case Priority_Above_Normal:
  1939. priviliegeValue = TOOLKIT_PRIORITY_ABOVE_NORMAL;
  1940. break;
  1941. case Priority_High:
  1942. priviliegeValue = TOOLKIT_PRIORITY_HIGH;
  1943. break;
  1944. case Priority_Highest:
  1945. priviliegeValue = TOOLKIT_PRIORITY_HIGHEST;
  1946. break;
  1947. default:
  1948. priviliegeValue = TOOLKIT_PRIORITY_NORMAL;
  1949. break;
  1950. }
  1951. int res = toolkit_os_setpriority(info.dwProcessID, priviliegeValue);
  1952. #else
  1953. auto func = [nPriority] {
  1954. switch (nPriority) {
  1955. case Priority_Low:
  1956. return TOOLKIT_PRIORITY_LOW;
  1957. case Priority_Below_Normal:
  1958. return TOOLKIT_PRIORITY_BELOW_NORMAL;
  1959. case Priority_Normal:
  1960. return TOOLKIT_PRIORITY_NORMAL;
  1961. case Priority_Above_Normal:
  1962. return TOOLKIT_PRIORITY_ABOVE_NORMAL;
  1963. case Priority_High:
  1964. return TOOLKIT_PRIORITY_HIGH;
  1965. case Priority_Highest:
  1966. return TOOLKIT_PRIORITY_HIGHEST;
  1967. default:
  1968. return TOOLKIT_PRIORITY_NORMAL;
  1969. }
  1970. };
  1971. int res = toolkit_os_setpriority(info.dwProcessID, func());
  1972. #endif //_MSC_VER
  1973. if (res != 0) {
  1974. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("toolkit_os_setpriority failed %s ", toolkit_strerror(res));
  1975. result = Error_Unexpect;
  1976. }
  1977. }
  1978. return result;
  1979. }
  1980. ErrorCodeEnum SpEntity::GetSelfPriority(EntityPriorityEnum& nPriority)
  1981. {
  1982. ErrorCodeEnum result(Error_Succeed);
  1983. CEntityRunInfo info;
  1984. result = GetEntityRunInfo(m_ent->cfg->name, info);
  1985. if (result == Error_Succeed) {
  1986. int priority;
  1987. int res = toolkit_os_getpriority(info.dwProcessID, &priority);
  1988. if (res != 0) {
  1989. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("toolkit_os_getpriority failed %s ", toolkit_strerror(res));
  1990. result = Error_Unexpect;
  1991. } else {
  1992. #if defined(_MSC_VER)
  1993. switch (priority) {
  1994. case TOOLKIT_PRIORITY_LOW:
  1995. nPriority = Priority_Low;
  1996. break;
  1997. case TOOLKIT_PRIORITY_BELOW_NORMAL:
  1998. nPriority = Priority_Below_Normal;
  1999. break;
  2000. case TOOLKIT_PRIORITY_NORMAL:
  2001. nPriority = Priority_Normal;
  2002. break;
  2003. case TOOLKIT_PRIORITY_ABOVE_NORMAL:
  2004. nPriority = Priority_Above_Normal;
  2005. break;
  2006. case TOOLKIT_PRIORITY_HIGH:
  2007. nPriority = Priority_High;
  2008. break;
  2009. case TOOLKIT_PRIORITY_HIGHEST:
  2010. nPriority = Priority_Highest;
  2011. break;
  2012. default:
  2013. nPriority = Priority_Unknown;
  2014. break;
  2015. }
  2016. #else
  2017. auto func = [](int value) {
  2018. switch (value) {
  2019. case TOOLKIT_PRIORITY_LOW:
  2020. return Priority_Low;
  2021. case TOOLKIT_PRIORITY_BELOW_NORMAL:
  2022. return Priority_Below_Normal;
  2023. case TOOLKIT_PRIORITY_NORMAL:
  2024. return Priority_Normal;
  2025. case TOOLKIT_PRIORITY_ABOVE_NORMAL:
  2026. return Priority_Above_Normal;
  2027. case TOOLKIT_PRIORITY_HIGH:
  2028. return Priority_High;
  2029. case TOOLKIT_PRIORITY_HIGHEST:
  2030. return Priority_Highest;
  2031. default:
  2032. return Priority_Unknown;
  2033. }
  2034. };
  2035. nPriority = func(priority);
  2036. #endif //_MSC_VER
  2037. }
  2038. }
  2039. return result;
  2040. }
  2041. void SpEntity::SetEntityLastError(ErrorCodeEnum systemCode, DWORD dwUserCode, const char* lpcszMessage)
  2042. {
  2043. if (m_ent) {
  2044. m_ent->last_err.sys_code = (uint32_t)systemCode;
  2045. m_ent->last_err.usr_code = dwUserCode;
  2046. if(lpcszMessage != NULL && strlen(lpcszMessage) < SP_ENTITY_ERRMSG_MAX_LEN)
  2047. strcpy_s(m_ent->last_err.msg, SP_ENTITY_ERRMSG_MAX_LEN, lpcszMessage);
  2048. else
  2049. memset(m_ent->last_err.msg, '\0', sizeof(m_ent->last_err.msg));
  2050. }
  2051. }
  2052. ErrorCodeEnum SpEntity::GetEntityLastError(const char* pszEntityName, CEntityLastErrorInfo& errInfo)
  2053. {
  2054. if (pszEntityName == NULL) {
  2055. return Error_Param;
  2056. }
  2057. if (strlen(pszEntityName) == 0) {
  2058. errInfo.eSysCode = (ErrorCodeEnum)m_ent->last_err.sys_code;
  2059. errInfo.dwUserCode = (DWORD)m_ent->last_err.sys_code;
  2060. errInfo.strErrMsg = (const char*)m_ent->last_err.msg;
  2061. } else {
  2062. sp_env_t* env = sp_get_env();
  2063. sp_mod_mgr_t* mod_mgr = env->mod_mgr;
  2064. sp_entity_t* ent = sp_mod_mgr_find_entity_by_name(mod_mgr, pszEntityName);
  2065. if (!ent) {
  2066. return Error_NotExist;
  2067. }
  2068. const EntityStateEnum entityState = (EntityStateEnum)ent->state;
  2069. errInfo.eSysCode = (ErrorCodeEnum)ent->last_err.sys_code;
  2070. errInfo.dwUserCode = (DWORD)ent->last_err.usr_code;
  2071. if (entityState == EntityState_Idle || entityState == EntityState_Busy || entityState == EntityState_Pause) {
  2072. errInfo.strErrMsg = (const char*)ent->last_err.msg;
  2073. } else {
  2074. errInfo.strErrMsg = CSimpleStringA::Format("%s %s", SpStrEntityState(entityState), (const char*)ent->last_err.msg);
  2075. }
  2076. }
  2077. return Error_Succeed;
  2078. }
  2079. ErrorCodeEnum SpEntity::InitLogCurrentThread()
  2080. {
  2081. #ifdef RVC_OS_WIN
  2082. SetthreadGroup(GetCurrentThreadId(), get_cfg_ent()->name);
  2083. getEntityResource()->m_Entity = this;
  2084. #else
  2085. GetSpModule()->SetThreadEntity(this);
  2086. #endif //_WIN32
  2087. return Error_Succeed;
  2088. }
  2089. ErrorCodeEnum SpEntity::ConnectRemoteEntity(CClientSessionBase *pClientSession,
  2090. const char *pszRemoteEntity,
  2091. const char *pszParam,
  2092. CSmartPointer<IAsynWaitSp> &pAsynWaitSp)
  2093. {
  2094. ErrorCodeEnum Error;
  2095. if (!pClientSession || !pszRemoteEntity)
  2096. return Error_Param;
  2097. if (pClientSession->m_pSessionFunction)
  2098. return Error_Param;
  2099. SpClientSessionFunction *pFunction = new SpClientSessionFunction(this, pClientSession, pszRemoteEntity);
  2100. Error = pFunction->Begin(pszParam);
  2101. if (Error == Error_Succeed) {
  2102. pClientSession->m_pSessionFunction = pFunction;
  2103. pAsynWaitSp.Attach(pFunction, pFunction->GetRefCountPtr());
  2104. } else {
  2105. pFunction->DecrementRef();
  2106. }
  2107. if (Error_Succeed != Error) {
  2108. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("connect to %s failed: %s.", pszRemoteEntity, SpStrError(Error));
  2109. } else {
  2110. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("connect to %s succ.", pszRemoteEntity);
  2111. }
  2112. return Error;
  2113. }
  2114. ErrorCodeEnum SpEntity::RedirectSession(CClientSessionBase *pClientSession)
  2115. {
  2116. return Error_NotImpl;
  2117. }
  2118. ErrorCodeEnum SpEntity::RedirectSession(const char *pszSuggestEntity)
  2119. {
  2120. if (pszSuggestEntity) {
  2121. sp_env_t *env = sp_get_env();
  2122. sp_entity_t *ent = sp_mod_mgr_find_entity_by_name(env->mod_mgr, pszSuggestEntity);
  2123. if (ent) {
  2124. m_redirect_entity_cache = ent;
  2125. return Error_Succeed;
  2126. } else {
  2127. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("RedirectSession failed, cannot find entity %s", pszSuggestEntity);
  2128. return Error_Param;
  2129. }
  2130. }
  2131. return Error_Param;
  2132. }
  2133. ErrorCodeEnum SpEntity::RedirectSubscribBroadcast(CUUID SubID, const char *pszSugguestEntity)
  2134. {
  2135. if (pszSugguestEntity) {
  2136. sp_entity_t *ent = sp_mod_mgr_find_entity_by_name(sp_get_env()->mod_mgr, pszSugguestEntity);
  2137. if (ent) {
  2138. sp_uid_t uid = SubID.m_nUUID64;
  2139. sp_mod_entity_stub_finish_redirect_subscribe(m_stub, &uid, ent->cfg->idx);
  2140. } else {
  2141. return Error_NotExist;
  2142. }
  2143. } else {
  2144. return Error_Param;
  2145. }
  2146. return Error_Succeed;
  2147. }
  2148. ErrorCodeEnum SpEntity::AskShell(int call_type, iobuffer_t **req_pkt, iobuffer_t **ans_pkt)
  2149. {
  2150. ErrorCodeEnum Error;
  2151. iobuffer_t *r_pkt = NULL;
  2152. if (!req_pkt || !*req_pkt || !ans_pkt)
  2153. return Error_Param;
  2154. if (*ans_pkt)
  2155. return Error_Param; // must be null so can return pkt
  2156. SpAsyncWaitRPC *pAsyncWait = new SpAsyncWaitRPC(this, req_pkt, call_type);
  2157. Error = pAsyncWait->Begin();
  2158. if (Error == Error_Succeed)
  2159. {
  2160. Error = pAsyncWait->WaitAnswer(INFINITE);
  2161. if (Error == Error_Succeed)
  2162. {
  2163. CAutoBuffer AnsBuf;
  2164. bool bEnd;
  2165. Error = pAsyncWait->AsyncGetAnswer(AnsBuf, bEnd);
  2166. if (Error == Error_Succeed)
  2167. {
  2168. iobuffer_t *pkt = iobuffer_create(-1, AnsBuf.GetCount());
  2169. iobuffer_write(pkt, IOBUF_T_BUF, &AnsBuf[0], AnsBuf.GetCount());
  2170. *ans_pkt = pkt;
  2171. }
  2172. }
  2173. }
  2174. pAsyncWait->DecrementRef(); // xkm@20150115
  2175. return Error;
  2176. }
  2177. ErrorCodeEnum SpEntity::AskEntityByRPC(const char *pszEntityName, int call_type, iobuffer_t **req_pkt, iobuffer_t **ans_pkt)
  2178. {
  2179. ErrorCodeEnum Error;
  2180. iobuffer_t *r_pkt = NULL;
  2181. if (!req_pkt || !*req_pkt || !ans_pkt)
  2182. return Error_Param;
  2183. if (*ans_pkt)
  2184. return Error_Param; // must be null so can return pkt
  2185. SpAsyncWaitRPC *pAsyncWait = new SpAsyncWaitRPC(this, req_pkt, call_type);
  2186. Error = pAsyncWait->Begin(pszEntityName);
  2187. if (Error == Error_Succeed)
  2188. {
  2189. Error = pAsyncWait->WaitAnswer(INFINITE);
  2190. if (Error == Error_Succeed)
  2191. {
  2192. CAutoBuffer AnsBuf;
  2193. bool bEnd;
  2194. Error = pAsyncWait->AsyncGetAnswer(AnsBuf, bEnd);
  2195. if (Error == Error_Succeed) {
  2196. iobuffer_t *pkt = iobuffer_create(-1, AnsBuf.GetCount());
  2197. iobuffer_write(pkt, IOBUF_T_BUF, &AnsBuf[0], AnsBuf.GetCount());
  2198. *ans_pkt = pkt;
  2199. }
  2200. }
  2201. }
  2202. pAsyncWait->DecrementRef(); // xkm@20150115
  2203. return Error;
  2204. }
  2205. void SpEntity::__on_rpc_request(sp_rpc_client_mgr_t *mgr, int epid, int svc_id, int rpc_id, int call_type, iobuffer_t **req_pkt, void *user_data)
  2206. {
  2207. SpEntity *pThis = static_cast<SpEntity*>(user_data);
  2208. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("on_rpc_req(), calltype: %d", call_type);
  2209. if (call_type == ENTITY_CMD_REQ_QUERY_ENTITY_SESSIONS)
  2210. {
  2211. pThis->OnQueryEntitySessions(epid, svc_id, rpc_id);
  2212. }
  2213. }
  2214. void SpEntity::OnQueryEntitySessions(int epid, int svc_id, int rpc_id)
  2215. {
  2216. int rc;
  2217. int nCount(0);
  2218. int nResult(0);
  2219. sp_ses_info_t* ret = sp_ses_mgr_get_ses_info(m_ses_mgr, &nCount);
  2220. iobuffer_t *ans_pkt = iobuffer_create(-1, -1);
  2221. iobuffer_write(ans_pkt, IOBUF_T_I4, &nResult, 0);
  2222. iobuffer_write(ans_pkt, IOBUF_T_I4, &nCount, 0);
  2223. for(int i=0; i<nCount; i++)
  2224. {
  2225. iobuffer_write(ans_pkt, IOBUF_T_I4, &ret[i].from_svc_id, 0);
  2226. iobuffer_write(ans_pkt, IOBUF_T_I4, &ret[i].to_svc_id, 0);
  2227. iobuffer_write(ans_pkt, IOBUF_T_I4, &ret[i].begin_time, 0);
  2228. iobuffer_write(ans_pkt, IOBUF_T_I4, &ret[i].state, 0);
  2229. iobuffer_write(ans_pkt, IOBUF_T_I4, &ret[i].state_begin_time, 0);
  2230. }
  2231. if (ret != NULL)
  2232. free(ret);
  2233. rc = sp_rpc_client_mgr_send_answer(m_rpc_mgr, epid, svc_id, rpc_id, &ans_pkt);
  2234. if (rc != 0) {
  2235. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("send rpc answer failed!");
  2236. }
  2237. if (ans_pkt) {
  2238. iobuffer_dec_ref(ans_pkt);
  2239. }
  2240. }
  2241. ErrorCodeEnum SpEntity::PostInfoShell(int call_type, iobuffer_t **info_pkt)
  2242. {
  2243. int rc;
  2244. rc = sp_rpc_client_mgr_one_way_call(get_rpc_mgr(),
  2245. SP_SHELL_MOD_ID,
  2246. SP_SHELL_SVC_ID,
  2247. call_type,
  2248. info_pkt);
  2249. return SpTranslateError(rc);
  2250. }
  2251. void SpEntity::FinishStart(ErrorCodeEnum Error)
  2252. {
  2253. sp_mod_entity_stub_finish_start(m_stub, Error);
  2254. if (Error == Error_Succeed) {
  2255. m_pEntityBase->OnStarted();
  2256. }
  2257. }
  2258. void SpEntity::FinishClose(ErrorCodeEnum Error)
  2259. {
  2260. sp_mod_entity_stub_finish_stop(m_stub, Error);
  2261. if (Error == Error_Succeed) {
  2262. Term();
  2263. }
  2264. }
  2265. void SpEntity::FinishPause(ErrorCodeEnum Error)
  2266. {
  2267. sp_mod_entity_stub_finish_pause(m_stub, Error);
  2268. if (Error == Error_Succeed) {
  2269. m_pEntityBase->OnPaused();
  2270. }
  2271. }
  2272. void SpEntity::FinishContinue(ErrorCodeEnum Error)
  2273. {
  2274. sp_mod_entity_stub_finish_continue(m_stub, Error);
  2275. if (Error == Error_Succeed) {
  2276. m_pEntityBase->OnContinued();
  2277. }
  2278. }
  2279. void SpEntity::FinishSelfTest(ErrorCodeEnum Error, DWORD dwResult)
  2280. {
  2281. //sp_mod_entity_stub_finish_test(m_stub, Error);
  2282. sp_mod_entity_stub_finish_exam(m_stub, Error, dwResult);
  2283. }