SpEntity.cpp 77 KB

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