SpEntity.cpp 81 KB

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