SpEntity.cpp 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656
  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. if (pszPath.GetLength() == 0) {
  1555. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("SetNewPathToFirewall param error");
  1556. return Error_Param;
  1557. }
  1558. #ifdef _WIN32
  1559. auto addFirewall_worker = [this](std::string path)
  1560. {
  1561. return sp_AddFirewallRuleByPath(path.c_str()) ? Error_Succeed : Error_Bug;
  1562. };
  1563. std::future<ErrorCodeEnum> result = std::async(std::launch::async, addFirewall_worker, pszPath.GetData());
  1564. auto status = result.wait_for(std::chrono::milliseconds(maxWaitMs));
  1565. if (status == std::future_status::ready)
  1566. {
  1567. auto ret = result.get();
  1568. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("SetNewPathToFirewall ret:%d", ret);
  1569. return ret;
  1570. }
  1571. else
  1572. {
  1573. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("SetNewPathToFirewall run over %d milliseconds", maxWaitMs);
  1574. return Error_TimeOut;
  1575. }
  1576. #else
  1577. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("SetNewPathToFirewall not support uos");
  1578. return Error_NotSupport;
  1579. #endif // RVC_OS_WIN
  1580. }
  1581. ErrorCodeEnum SpEntity::GetEntityStaticInfo(WORD wEntitySerialNO, CEntityStaticInfo &Info)
  1582. {
  1583. sp_env_t *env = sp_get_env();
  1584. sp_entity_t *ent = sp_mod_mgr_find_entity_by_devel_id(env->mod_mgr, wEntitySerialNO);
  1585. return ::GetEntityStaticInfo(Info, ent);
  1586. }
  1587. ErrorCodeEnum SpEntity::GetEntityRunInfo(const char *pszEntityName, CEntityRunInfo &Info)
  1588. {
  1589. sp_env_t *env = sp_get_env();
  1590. if (!pszEntityName)
  1591. return Error_Null;
  1592. sp_mod_mgr_t *mod_mgr = env->mod_mgr;
  1593. sp_entity_t *ent = sp_mod_mgr_find_entity_by_name(mod_mgr, pszEntityName);
  1594. if (!ent)
  1595. return Error_NotExist;
  1596. Info.dwEntityInstanceID = (DWORD)ent->instance_id;
  1597. Info.tmFirstStart = ent->first_start_time;
  1598. Info.tmLastStart = ent->last_start_time;
  1599. Info.bService = !!ent->service_flag;
  1600. Info.eState = (EntityStateEnum)ent->state;
  1601. Info.tmBeginCurrentState = ent->state_start_time;
  1602. Info.dwProcessID = (DWORD)ent->mod->process.pid;
  1603. Info.eDebugLevel = (DebugLevelEnum)ent->cfg->debug_level;
  1604. Info.dwUserState = (DWORD)ent->user_state;
  1605. return Error_Succeed;
  1606. }
  1607. ErrorCodeEnum SpEntity::GetEntityName(WORD wEntityDevelopID, CSimpleStringA &strName)
  1608. {
  1609. sp_env_t *env = sp_get_env();
  1610. sp_entity_t *ent = sp_mod_mgr_find_entity_by_devel_id(env->mod_mgr, wEntityDevelopID);
  1611. if (ent) {
  1612. strName = ent->cfg->name;
  1613. } else {
  1614. return Error_NotExist;
  1615. }
  1616. return Error_Succeed;
  1617. }
  1618. ErrorCodeEnum SpEntity::GetEntityName(DWORD dwEntityInstanceID, CSimpleStringA &strName)
  1619. {
  1620. TOOLKIT_ASSERT(dwEntityInstanceID != 0);
  1621. sp_env_t *env = sp_get_env();
  1622. sp_entity_t *ent = sp_mod_mgr_find_entity_by_inst_id(env->mod_mgr, dwEntityInstanceID);
  1623. if (ent) {
  1624. strName = ent->cfg->name;
  1625. } else {
  1626. return Error_NotExist;
  1627. }
  1628. return Error_Succeed;
  1629. }
  1630. ErrorCodeEnum SpEntity::GetModuleName(DWORD nModuleID, CSimpleStringA &strName)
  1631. {
  1632. if (nModuleID != SP_INVALID_MOD_ID) {
  1633. sp_env_t *env = sp_get_env();
  1634. sp_mod_t *mod = sp_mod_mgr_find_module_by_idx(env->mod_mgr, nModuleID);
  1635. if (mod) {
  1636. strName = mod->cfg->name;
  1637. return Error_Succeed;
  1638. } else {
  1639. return Error_NotExist;
  1640. }
  1641. }
  1642. return Error_Param;
  1643. }
  1644. ErrorCodeEnum SpEntity::GetEntitySessionInfo(const char *pszEntityName, CAutoArray<CEntitySessionInfo> &Infos)
  1645. {
  1646. iobuffer_t *req_pkt = iobuffer_create(-1, -1);
  1647. iobuffer_t *ans_pkt = NULL;
  1648. auto rc = AskEntityByRPC(pszEntityName, ENTITY_CMD_REQ_QUERY_ENTITY_SESSIONS, &req_pkt, &ans_pkt);
  1649. if (rc == Error_Succeed)
  1650. {
  1651. int nCount(0);
  1652. iobuffer_read(ans_pkt, IOBUF_T_I4, &nCount, NULL);
  1653. auto pCfg = sp_get_env()->cfg;
  1654. Infos.Init(nCount);
  1655. for (int i = 0; i < nCount; ++i)
  1656. {
  1657. int nFromSvcID, nToSvcID, nBeginTime, nState, nStateBeginTime;
  1658. iobuffer_format_read(ans_pkt, "44444", &nFromSvcID, &nToSvcID, &nBeginTime, &nState, &nStateBeginTime);
  1659. Infos[i].strCallerEntity = sp_cfg_get_entity_by_idx(pCfg, nFromSvcID)->name;
  1660. Infos[i].strServiceEntity = sp_cfg_get_entity_by_idx(pCfg, nToSvcID)->name;
  1661. Infos[i].tmStart = CSmallDateTime(nBeginTime);
  1662. Infos[i].eState = (SessionStateEnum)nState;
  1663. Infos[i].tmBeginState = CSmallDateTime(nStateBeginTime);
  1664. }
  1665. }
  1666. if (req_pkt)
  1667. iobuffer_dec_ref(req_pkt);
  1668. if (ans_pkt)
  1669. iobuffer_dec_ref(ans_pkt);
  1670. return rc;
  1671. }
  1672. bool SpEntity::HasPrivilege()
  1673. {
  1674. return !!m_cfg_ent->privilege;
  1675. }
  1676. CSmartPointer<IEntityFunctionPrivilege> SpEntity::GetPrivilegeFunction()
  1677. {
  1678. return NULL;
  1679. }
  1680. ErrorCodeEnum SpEntity::PostQuit()
  1681. {
  1682. ErrorCodeEnum Error;
  1683. iobuffer_t *pkt = iobuffer_create(-1, -1);
  1684. int v = m_ent->cfg->idx;
  1685. iobuffer_write(pkt, IOBUF_T_I4, &v, 0);
  1686. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Pre PostQuit...");
  1687. Error = PostInfoShell(SHELL_CMD_INFO_ENTITY_QUIT, &pkt);
  1688. if (pkt)
  1689. iobuffer_dec_ref(pkt);
  1690. return Error;
  1691. }
  1692. ErrorCodeEnum SpEntity::PostReload()
  1693. {
  1694. ErrorCodeEnum Error;
  1695. iobuffer_t *pkt = iobuffer_create(-1, -1);
  1696. int v = m_ent->cfg->idx;
  1697. iobuffer_write(pkt, IOBUF_T_I4, &v, 0);
  1698. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Pre PostReload...");
  1699. Error = PostInfoShell(SHELL_CMD_INFO_ENTITY_RELOAD, &pkt);
  1700. if (pkt)
  1701. iobuffer_dec_ref(pkt);
  1702. return Error;
  1703. }
  1704. ErrorCodeEnum SpEntity::PostEntityTaskFIFO(ITaskSp *pTask)
  1705. {
  1706. threadpool_t *threadpool = sp_svc_get_threadpool(m_svc);
  1707. int rc;
  1708. rc = threadpool_post_workitem_fifo2(threadpool, NULL, &task_callback, pTask, (param_size_t)((intptr_t)this), 0);
  1709. return rc == 0 ? Error_Succeed : Error_Unexpect;
  1710. }
  1711. ErrorCodeEnum SpEntity::PostEntityTaskLIFO(ITaskSp *pTask)
  1712. {
  1713. threadpool_t *threadpool = sp_svc_get_threadpool(m_svc);
  1714. int rc;
  1715. rc = threadpool_post_workitem_lifo2(threadpool, NULL, &task_callback, pTask, (param_size_t)((intptr_t)this), 0);
  1716. return rc == 0 ? Error_Succeed : Error_Unexpect;
  1717. }
  1718. ErrorCodeEnum SpEntity::PostThreadPoolTask(ITaskSp *pTask)
  1719. {
  1720. int rc = threadpool_post_workitem_fifo2(m_tpool, NULL, &task_callback, pTask, (param_size_t)((intptr_t)this), 0);
  1721. return rc == 0 ? Error_Succeed : Error_Unexpect;
  1722. }
  1723. ErrorCodeEnum SpEntity::StartTcpBridgeServer(unsigned short port)
  1724. {
  1725. if (port >4506 || port < 4502)
  1726. return Error_Duplication;
  1727. #ifdef _DEBUG
  1728. const char *ip = "0.0.0.0";
  1729. #else
  1730. const char *ip = "127.0.0.1";
  1731. #endif
  1732. if (m_tbs)
  1733. return Error_Duplication;
  1734. int rc = sp_tbs_create(m_ses_mgr, ip, port, &m_tbs);
  1735. if (rc == 0) {
  1736. rc = sp_tbs_start(m_tbs);
  1737. if (rc != 0) {
  1738. sp_tbs_destroy(m_tbs);
  1739. m_tbs = NULL;
  1740. }
  1741. }
  1742. return SpTranslateError(rc);
  1743. }
  1744. ErrorCodeEnum SpEntity::StopTcpBridgeServer()
  1745. {
  1746. if (m_tbs) {
  1747. sp_tbs_stop(m_tbs);
  1748. sp_tbs_destroy(m_tbs);
  1749. m_tbs = NULL;
  1750. return Error_Succeed;
  1751. } else {
  1752. return Error_NotInit;
  1753. }
  1754. }
  1755. void SpEntity::SetPostLinkFun(postLink cur)
  1756. {
  1757. }
  1758. ErrorCodeEnum SpEntity::RequestCloseDelay(WORD nSecond)
  1759. {
  1760. return Error_NotImpl;
  1761. }
  1762. void SpEntity::SendLog(const LogTypeEnum eLogType,const SeverityLevelEnum eLevel,
  1763. DWORD dwUserEventCode,CAutoArray<DWORD> Param,const char *pszMessage)
  1764. {
  1765. LogMessage(eLogType, eLevel, 0, dwUserEventCode, Param, pszMessage);
  1766. }
  1767. ErrorCodeEnum SpEntity::VerifySignature(const char *pszSignedFile, CSimpleStringA &strErrInfo)
  1768. {
  1769. #ifdef RVC_OS_WIN
  1770. CCodeSignVerify verify;
  1771. CSignInfo signInfo;
  1772. if (!verify.VerifySignature(pszSignedFile, signInfo))
  1773. {
  1774. strErrInfo = verify.GetErrorMsg();
  1775. return Error_FailVerify;
  1776. }
  1777. // xkm@20140905: 检查签名证书Hash是否同SpBase签名证书Hash一致
  1778. sp_env_t *env = sp_get_env();
  1779. assert(env != NULL);
  1780. auto pShellCfg = env->cfg->shell_ini;
  1781. if (pShellCfg->spbase_sign_cert_hash != NULL && stricmp(pShellCfg->spbase_sign_cert_hash, signInfo.strSignCertHash) != 0)
  1782. {
  1783. strErrInfo = "签名证书非授权证书";
  1784. return Error_FailVerify;
  1785. }
  1786. strErrInfo = signInfo.strSignCertHash;
  1787. return Error_Succeed;
  1788. #else
  1789. strErrInfo = "TODO: not implement VerifySignature current times.";
  1790. //return Error_NotImpl;
  1791. #endif //RVC_OS_WIN
  1792. return Error_Succeed;
  1793. }
  1794. ErrorCodeEnum SpEntity::ShowFatalError(const char *pszMsg, SeverityLevelEnum eLevel)
  1795. {
  1796. #if defined(RVC_OS_WIN)
  1797. LogError(Severity_High, Error_Unrecover, 0, pszMsg);
  1798. #endif //RVC_OS_WIN
  1799. ErrorCodeEnum Error;
  1800. iobuffer_t *pkt = iobuffer_create(-1, -1);
  1801. int v = (int)eLevel;
  1802. iobuffer_write(pkt, IOBUF_T_I4, &v, 0);
  1803. #if defined(RVC_OS_LINUX)
  1804. CSimpleStringA strMsg = m_pEntityBase->GetEntityName();
  1805. strMsg += " V";
  1806. strMsg += m_pEntityBase->GetEntityVersion();
  1807. strMsg += ":][:"; /** arrange with QtGUIConsole to split entity name and msg content [Gifur@202128]*/
  1808. strMsg += pszMsg;
  1809. iobuffer_write(pkt, IOBUF_T_STR, (const char*)strMsg, -1);
  1810. #else
  1811. iobuffer_write(pkt, IOBUF_T_STR, pszMsg, -1);
  1812. #endif //RVC_OS_LINUX
  1813. Error = PostInfoShell(SHELL_CMD_INFO_FATAL_ERROR_DISPLAY, &pkt);
  1814. if (pkt)
  1815. iobuffer_dec_ref(pkt);
  1816. return Error;
  1817. }
  1818. ErrorCodeEnum SpEntity::ShowStartupInfo(const char *pszMsg)
  1819. {
  1820. LogEvent(Severity_High, 0, pszMsg);
  1821. ErrorCodeEnum Error;
  1822. iobuffer_t *pkt = iobuffer_create(-1, -1);
  1823. iobuffer_write(pkt, IOBUF_T_STR, pszMsg, -1);
  1824. Error = PostInfoShell(SHELL_CMD_INFO_STARTUP_INFO_DISPLAY, &pkt);
  1825. if (pkt)
  1826. iobuffer_dec_ref(pkt);
  1827. return Error;
  1828. }
  1829. void SpEntity::ResetEntityLastError()
  1830. {
  1831. if (m_ent) {
  1832. m_ent->last_err.sys_code = m_ent->last_err.usr_code = 0;
  1833. memset(m_ent->last_err.msg, '\0', sizeof(m_ent->last_err.msg));
  1834. }
  1835. }
  1836. ErrorCodeEnum SpEntity::GetRunningVersion(CSimpleString& ver)
  1837. {
  1838. char dstVer[SP_MAX_VER_LEN] = "";
  1839. auto ret = sp_cfg_getVer(dstVer);
  1840. if (ret == Error_Succeed)
  1841. ver = dstVer;
  1842. return (ErrorCodeEnum)ret;
  1843. }
  1844. ErrorCodeEnum SpEntity::GetRunningDepVersion(CSimpleString& ver)
  1845. {
  1846. char dstVer[SP_MAX_VER_LEN] = "";
  1847. auto ret = sp_cfg_getDepVer(dstVer);
  1848. if (ret == Error_Succeed)
  1849. ver = dstVer;
  1850. return (ErrorCodeEnum)ret;
  1851. }
  1852. struct ErrMsgStruct {
  1853. std::string VTMCode;
  1854. std::string errMsg;
  1855. // 带参数的构造函数,参数有默认值
  1856. ErrMsgStruct(const std::string& tmp_VTMCode = "", const std::string& tmp_errMsg = "") : VTMCode(tmp_VTMCode), errMsg(tmp_errMsg) {}
  1857. };
  1858. ErrorCodeEnum SpEntity::GetVTMErrMsg(DWORD dwUserCode, CSimpleStringA& strDescription, CSimpleStringA& strVTMCode)
  1859. {
  1860. sp_env_t* env = sp_get_env();
  1861. if (env->cfg->root_ini->vtm_err_msg_config == NULL || strlen(env->cfg->root_ini->vtm_err_msg_config) == 0)
  1862. {
  1863. strVTMCode = "RTA42F0";
  1864. strDescription = "微服务异常";
  1865. return ErrorCodeEnum::Error_NotConfig;
  1866. }
  1867. std::string userCodeStr = CSimpleString::Format("0x%X", dwUserCode).GetData();
  1868. std::transform(userCodeStr.begin(), userCodeStr.end(), userCodeStr.begin(), [](unsigned char c) { return std::tolower(c); });
  1869. static std::map<std::string, ErrMsgStruct> m_UserCodeToMsgTip;
  1870. static bool isInit = false;
  1871. if (!isInit)//Some entities may have no UserCode
  1872. {
  1873. CAutoArray<CSimpleStringA> strErrorCodeArr;
  1874. CAutoArray<CSimpleStringA> strDescriptionArr;
  1875. CAutoArray<CSimpleStringA> strRemarkArr;
  1876. ConvertStrToVTMErrMsg(env->cfg->root_ini->vtm_err_msg_config, strErrorCodeArr, strDescriptionArr, strRemarkArr);
  1877. auto intToHex = [](int num) -> std::string {
  1878. const char hexChars[] = "0123456789ABCDEF";
  1879. std::string hexStr;
  1880. // 将整数的每个字节转换为对应的16进制字符
  1881. for (int i = sizeof(num) - 1; i >= 0; --i) {
  1882. unsigned char byte = (num >> (8 * i)) & 0xFF;
  1883. if (byte == 0 && hexStr.empty()) {
  1884. continue; // 跳过前导零
  1885. }
  1886. hexStr += hexChars[byte >> 4];
  1887. hexStr += hexChars[byte & 0x0F];
  1888. }
  1889. return hexStr;
  1890. };
  1891. auto hexToInt = [](const std::string& hexStr)-> int {
  1892. std::stringstream ss;
  1893. ss << std::hex << hexStr;
  1894. int num;
  1895. ss >> num;
  1896. return num;
  1897. };
  1898. auto intTo36 = [](int num) -> std::string {
  1899. std::string base36Chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  1900. std::string base36Str;
  1901. while (num > 0) {
  1902. base36Str = base36Chars[num % 36] + base36Str;
  1903. num /= 36;
  1904. }
  1905. return base36Str;
  1906. };
  1907. int id = GetDevID();
  1908. auto idHexStr = intToHex(id);
  1909. if (idHexStr.length() != 4 || idHexStr[0] != '0')
  1910. {
  1911. strVTMCode = "RTA42F2";
  1912. strDescription = "实体Id异常";
  1913. return ErrorCodeEnum::Error_Unregisted;
  1914. }
  1915. std::string dstRTA = "RTA";
  1916. dstRTA.push_back(idHexStr[1]); //first
  1917. std::string lastTwoDigits = idHexStr.substr(idHexStr.length() - 2); // last two digits
  1918. int num = hexToInt(lastTwoDigits);
  1919. if (num < 0 || num >= 36) {
  1920. strVTMCode = "RTA42F2";
  1921. strDescription = "无法转换实体Id";
  1922. return ErrorCodeEnum::Error_DataCheck;
  1923. }
  1924. std::string base36Str = intTo36(num);
  1925. dstRTA.append(base36Str);
  1926. for (int i = 0; i < strErrorCodeArr.GetCount(); i++)
  1927. {
  1928. //if (strErrorCodeArr[i].IsStartWith(dstRTA.c_str(), true))
  1929. //{
  1930. std::string curRemark = strRemarkArr[i].GetData();
  1931. std::transform(curRemark.begin(), curRemark.end(), curRemark.begin(), [](unsigned char c) { return std::tolower(c); });
  1932. m_UserCodeToMsgTip.insert(std::make_pair(curRemark, ErrMsgStruct(strErrorCodeArr[i].GetData(), strDescriptionArr[i].GetData())));
  1933. //}
  1934. }
  1935. isInit = true;
  1936. }
  1937. if (m_UserCodeToMsgTip.find(userCodeStr) != m_UserCodeToMsgTip.end())
  1938. {
  1939. strVTMCode = m_UserCodeToMsgTip[userCodeStr].VTMCode.c_str();
  1940. strDescription = m_UserCodeToMsgTip[userCodeStr].errMsg.c_str();
  1941. return ErrorCodeEnum::Error_Succeed;
  1942. }
  1943. else
  1944. {
  1945. strVTMCode = "RTA42F1";
  1946. strDescription = "错误映射异常";
  1947. return ErrorCodeEnum::Error_NotExist;
  1948. }
  1949. }
  1950. CSimpleStringA SpEntity::UserCodeToRTACode(DWORD dwUserCode)
  1951. {
  1952. CSimpleStringA tmpDesc, tmpVtmCode("");
  1953. //transmit the return of GetVTMErrMsg directly
  1954. GetVTMErrMsg(dwUserCode, tmpDesc, tmpVtmCode);
  1955. return CSimpleStringA(tmpVtmCode);
  1956. }
  1957. ErrorCodeEnum SpEntity::SetSelfPriority(EntityPriorityEnum nPriority)
  1958. {
  1959. ErrorCodeEnum result(Error_Succeed);
  1960. CEntityRunInfo info;
  1961. result = GetEntityRunInfo(m_ent->cfg->name, info);
  1962. if (result == Error_Succeed) {
  1963. #if defined(_MSC_VER)
  1964. int priviliegeValue = TOOLKIT_PRIORITY_NORMAL;
  1965. switch (nPriority) {
  1966. case Priority_Low:
  1967. priviliegeValue = TOOLKIT_PRIORITY_LOW;
  1968. break;
  1969. case Priority_Below_Normal:
  1970. priviliegeValue = TOOLKIT_PRIORITY_BELOW_NORMAL;
  1971. break;
  1972. case Priority_Normal:
  1973. priviliegeValue = TOOLKIT_PRIORITY_NORMAL;
  1974. break;
  1975. case Priority_Above_Normal:
  1976. priviliegeValue = TOOLKIT_PRIORITY_ABOVE_NORMAL;
  1977. break;
  1978. case Priority_High:
  1979. priviliegeValue = TOOLKIT_PRIORITY_HIGH;
  1980. break;
  1981. case Priority_Highest:
  1982. priviliegeValue = TOOLKIT_PRIORITY_HIGHEST;
  1983. break;
  1984. default:
  1985. priviliegeValue = TOOLKIT_PRIORITY_NORMAL;
  1986. break;
  1987. }
  1988. int res = toolkit_os_setpriority(info.dwProcessID, priviliegeValue);
  1989. #else
  1990. auto func = [nPriority] {
  1991. switch (nPriority) {
  1992. case Priority_Low:
  1993. return TOOLKIT_PRIORITY_LOW;
  1994. case Priority_Below_Normal:
  1995. return TOOLKIT_PRIORITY_BELOW_NORMAL;
  1996. case Priority_Normal:
  1997. return TOOLKIT_PRIORITY_NORMAL;
  1998. case Priority_Above_Normal:
  1999. return TOOLKIT_PRIORITY_ABOVE_NORMAL;
  2000. case Priority_High:
  2001. return TOOLKIT_PRIORITY_HIGH;
  2002. case Priority_Highest:
  2003. return TOOLKIT_PRIORITY_HIGHEST;
  2004. default:
  2005. return TOOLKIT_PRIORITY_NORMAL;
  2006. }
  2007. };
  2008. int res = toolkit_os_setpriority(info.dwProcessID, func());
  2009. #endif //_MSC_VER
  2010. if (res != 0) {
  2011. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("toolkit_os_setpriority failed %s ", toolkit_strerror(res));
  2012. result = Error_Unexpect;
  2013. }
  2014. }
  2015. return result;
  2016. }
  2017. ErrorCodeEnum SpEntity::GetSelfPriority(EntityPriorityEnum& nPriority)
  2018. {
  2019. ErrorCodeEnum result(Error_Succeed);
  2020. CEntityRunInfo info;
  2021. result = GetEntityRunInfo(m_ent->cfg->name, info);
  2022. if (result == Error_Succeed) {
  2023. int priority;
  2024. int res = toolkit_os_getpriority(info.dwProcessID, &priority);
  2025. if (res != 0) {
  2026. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("toolkit_os_getpriority failed %s ", toolkit_strerror(res));
  2027. result = Error_Unexpect;
  2028. } else {
  2029. #if defined(_MSC_VER)
  2030. switch (priority) {
  2031. case TOOLKIT_PRIORITY_LOW:
  2032. nPriority = Priority_Low;
  2033. break;
  2034. case TOOLKIT_PRIORITY_BELOW_NORMAL:
  2035. nPriority = Priority_Below_Normal;
  2036. break;
  2037. case TOOLKIT_PRIORITY_NORMAL:
  2038. nPriority = Priority_Normal;
  2039. break;
  2040. case TOOLKIT_PRIORITY_ABOVE_NORMAL:
  2041. nPriority = Priority_Above_Normal;
  2042. break;
  2043. case TOOLKIT_PRIORITY_HIGH:
  2044. nPriority = Priority_High;
  2045. break;
  2046. case TOOLKIT_PRIORITY_HIGHEST:
  2047. nPriority = Priority_Highest;
  2048. break;
  2049. default:
  2050. nPriority = Priority_Unknown;
  2051. break;
  2052. }
  2053. #else
  2054. auto func = [](int value) {
  2055. switch (value) {
  2056. case TOOLKIT_PRIORITY_LOW:
  2057. return Priority_Low;
  2058. case TOOLKIT_PRIORITY_BELOW_NORMAL:
  2059. return Priority_Below_Normal;
  2060. case TOOLKIT_PRIORITY_NORMAL:
  2061. return Priority_Normal;
  2062. case TOOLKIT_PRIORITY_ABOVE_NORMAL:
  2063. return Priority_Above_Normal;
  2064. case TOOLKIT_PRIORITY_HIGH:
  2065. return Priority_High;
  2066. case TOOLKIT_PRIORITY_HIGHEST:
  2067. return Priority_Highest;
  2068. default:
  2069. return Priority_Unknown;
  2070. }
  2071. };
  2072. nPriority = func(priority);
  2073. #endif //_MSC_VER
  2074. }
  2075. }
  2076. return result;
  2077. }
  2078. void SpEntity::SetEntityLastError(ErrorCodeEnum systemCode, DWORD dwUserCode, const char* lpcszMessage)
  2079. {
  2080. if (m_ent) {
  2081. m_ent->last_err.sys_code = (uint32_t)systemCode;
  2082. m_ent->last_err.usr_code = dwUserCode;
  2083. if(lpcszMessage != NULL && strlen(lpcszMessage) < SP_ENTITY_ERRMSG_MAX_LEN)
  2084. strcpy_s(m_ent->last_err.msg, SP_ENTITY_ERRMSG_MAX_LEN, lpcszMessage);
  2085. else
  2086. memset(m_ent->last_err.msg, '\0', sizeof(m_ent->last_err.msg));
  2087. }
  2088. }
  2089. ErrorCodeEnum SpEntity::GetEntityLastError(const char* pszEntityName, CEntityLastErrorInfo& errInfo)
  2090. {
  2091. if (pszEntityName == NULL) {
  2092. return Error_Param;
  2093. }
  2094. if (strlen(pszEntityName) == 0) {
  2095. errInfo.eSysCode = (ErrorCodeEnum)m_ent->last_err.sys_code;
  2096. errInfo.dwUserCode = (DWORD)m_ent->last_err.sys_code;
  2097. errInfo.strErrMsg = (const char*)m_ent->last_err.msg;
  2098. } else {
  2099. sp_env_t* env = sp_get_env();
  2100. sp_mod_mgr_t* mod_mgr = env->mod_mgr;
  2101. sp_entity_t* ent = sp_mod_mgr_find_entity_by_name(mod_mgr, pszEntityName);
  2102. if (!ent) {
  2103. return Error_NotExist;
  2104. }
  2105. const EntityStateEnum entityState = (EntityStateEnum)ent->state;
  2106. errInfo.eSysCode = (ErrorCodeEnum)ent->last_err.sys_code;
  2107. errInfo.dwUserCode = (DWORD)ent->last_err.usr_code;
  2108. if (entityState == EntityState_Idle || entityState == EntityState_Busy || entityState == EntityState_Pause) {
  2109. errInfo.strErrMsg = (const char*)ent->last_err.msg;
  2110. } else {
  2111. errInfo.strErrMsg = CSimpleStringA::Format("%s %s", SpStrEntityState(entityState), (const char*)ent->last_err.msg);
  2112. }
  2113. }
  2114. return Error_Succeed;
  2115. }
  2116. ErrorCodeEnum SpEntity::InitLogCurrentThread()
  2117. {
  2118. #ifdef RVC_OS_WIN
  2119. SetthreadGroup(GetCurrentThreadId(), get_cfg_ent()->name);
  2120. getEntityResource()->m_Entity = this;
  2121. #else
  2122. GetSpModule()->SetThreadEntity(this);
  2123. #endif //_WIN32
  2124. return Error_Succeed;
  2125. }
  2126. ErrorCodeEnum SpEntity::ConnectRemoteEntity(CClientSessionBase *pClientSession,
  2127. const char *pszRemoteEntity,
  2128. const char *pszParam,
  2129. CSmartPointer<IAsynWaitSp> &pAsynWaitSp)
  2130. {
  2131. ErrorCodeEnum Error;
  2132. if (!pClientSession || !pszRemoteEntity)
  2133. return Error_Param;
  2134. if (pClientSession->m_pSessionFunction)
  2135. return Error_Param;
  2136. SpClientSessionFunction *pFunction = new SpClientSessionFunction(this, pClientSession, pszRemoteEntity);
  2137. Error = pFunction->Begin(pszParam);
  2138. if (Error == Error_Succeed) {
  2139. pClientSession->m_pSessionFunction = pFunction;
  2140. pAsynWaitSp.Attach(pFunction, pFunction->GetRefCountPtr());
  2141. } else {
  2142. pFunction->DecrementRef();
  2143. }
  2144. if (Error_Succeed != Error) {
  2145. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("connect to %s failed: %s.", pszRemoteEntity, SpStrError(Error));
  2146. } else {
  2147. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("connect to %s succ.", pszRemoteEntity);
  2148. }
  2149. return Error;
  2150. }
  2151. ErrorCodeEnum SpEntity::RedirectSession(CClientSessionBase *pClientSession)
  2152. {
  2153. return Error_NotImpl;
  2154. }
  2155. ErrorCodeEnum SpEntity::RedirectSession(const char *pszSuggestEntity)
  2156. {
  2157. if (pszSuggestEntity) {
  2158. sp_env_t *env = sp_get_env();
  2159. sp_entity_t *ent = sp_mod_mgr_find_entity_by_name(env->mod_mgr, pszSuggestEntity);
  2160. if (ent) {
  2161. m_redirect_entity_cache = ent;
  2162. return Error_Succeed;
  2163. } else {
  2164. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("RedirectSession failed, cannot find entity %s", pszSuggestEntity);
  2165. return Error_Param;
  2166. }
  2167. }
  2168. return Error_Param;
  2169. }
  2170. ErrorCodeEnum SpEntity::RedirectSubscribBroadcast(CUUID SubID, const char *pszSugguestEntity)
  2171. {
  2172. if (pszSugguestEntity) {
  2173. sp_entity_t *ent = sp_mod_mgr_find_entity_by_name(sp_get_env()->mod_mgr, pszSugguestEntity);
  2174. if (ent) {
  2175. sp_uid_t uid = SubID.m_nUUID64;
  2176. sp_mod_entity_stub_finish_redirect_subscribe(m_stub, &uid, ent->cfg->idx);
  2177. } else {
  2178. return Error_NotExist;
  2179. }
  2180. } else {
  2181. return Error_Param;
  2182. }
  2183. return Error_Succeed;
  2184. }
  2185. ErrorCodeEnum SpEntity::AskShell(int call_type, iobuffer_t **req_pkt, iobuffer_t **ans_pkt)
  2186. {
  2187. ErrorCodeEnum Error;
  2188. iobuffer_t *r_pkt = NULL;
  2189. if (!req_pkt || !*req_pkt || !ans_pkt)
  2190. return Error_Param;
  2191. if (*ans_pkt)
  2192. return Error_Param; // must be null so can return pkt
  2193. SpAsyncWaitRPC *pAsyncWait = new SpAsyncWaitRPC(this, req_pkt, call_type);
  2194. Error = pAsyncWait->Begin();
  2195. if (Error == Error_Succeed)
  2196. {
  2197. Error = pAsyncWait->WaitAnswer(INFINITE);
  2198. if (Error == Error_Succeed)
  2199. {
  2200. CAutoBuffer AnsBuf;
  2201. bool bEnd;
  2202. Error = pAsyncWait->AsyncGetAnswer(AnsBuf, bEnd);
  2203. if (Error == Error_Succeed)
  2204. {
  2205. iobuffer_t *pkt = iobuffer_create(-1, AnsBuf.GetCount());
  2206. iobuffer_write(pkt, IOBUF_T_BUF, &AnsBuf[0], AnsBuf.GetCount());
  2207. *ans_pkt = pkt;
  2208. }
  2209. }
  2210. }
  2211. pAsyncWait->DecrementRef(); // xkm@20150115
  2212. return Error;
  2213. }
  2214. ErrorCodeEnum SpEntity::AskEntityByRPC(const char *pszEntityName, int call_type, iobuffer_t **req_pkt, iobuffer_t **ans_pkt)
  2215. {
  2216. ErrorCodeEnum Error;
  2217. iobuffer_t *r_pkt = NULL;
  2218. if (!req_pkt || !*req_pkt || !ans_pkt)
  2219. return Error_Param;
  2220. if (*ans_pkt)
  2221. return Error_Param; // must be null so can return pkt
  2222. SpAsyncWaitRPC *pAsyncWait = new SpAsyncWaitRPC(this, req_pkt, call_type);
  2223. Error = pAsyncWait->Begin(pszEntityName);
  2224. if (Error == Error_Succeed)
  2225. {
  2226. Error = pAsyncWait->WaitAnswer(INFINITE);
  2227. if (Error == Error_Succeed)
  2228. {
  2229. CAutoBuffer AnsBuf;
  2230. bool bEnd;
  2231. Error = pAsyncWait->AsyncGetAnswer(AnsBuf, bEnd);
  2232. if (Error == Error_Succeed) {
  2233. iobuffer_t *pkt = iobuffer_create(-1, AnsBuf.GetCount());
  2234. iobuffer_write(pkt, IOBUF_T_BUF, &AnsBuf[0], AnsBuf.GetCount());
  2235. *ans_pkt = pkt;
  2236. }
  2237. }
  2238. }
  2239. pAsyncWait->DecrementRef(); // xkm@20150115
  2240. return Error;
  2241. }
  2242. 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)
  2243. {
  2244. SpEntity *pThis = static_cast<SpEntity*>(user_data);
  2245. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("on_rpc_req(), calltype: %d", call_type);
  2246. if (call_type == ENTITY_CMD_REQ_QUERY_ENTITY_SESSIONS)
  2247. {
  2248. pThis->OnQueryEntitySessions(epid, svc_id, rpc_id);
  2249. }
  2250. }
  2251. void SpEntity::OnQueryEntitySessions(int epid, int svc_id, int rpc_id)
  2252. {
  2253. int rc;
  2254. int nCount(0);
  2255. int nResult(0);
  2256. sp_ses_info_t* ret = sp_ses_mgr_get_ses_info(m_ses_mgr, &nCount);
  2257. iobuffer_t *ans_pkt = iobuffer_create(-1, -1);
  2258. iobuffer_write(ans_pkt, IOBUF_T_I4, &nResult, 0);
  2259. iobuffer_write(ans_pkt, IOBUF_T_I4, &nCount, 0);
  2260. for(int i=0; i<nCount; i++)
  2261. {
  2262. iobuffer_write(ans_pkt, IOBUF_T_I4, &ret[i].from_svc_id, 0);
  2263. iobuffer_write(ans_pkt, IOBUF_T_I4, &ret[i].to_svc_id, 0);
  2264. iobuffer_write(ans_pkt, IOBUF_T_I4, &ret[i].begin_time, 0);
  2265. iobuffer_write(ans_pkt, IOBUF_T_I4, &ret[i].state, 0);
  2266. iobuffer_write(ans_pkt, IOBUF_T_I4, &ret[i].state_begin_time, 0);
  2267. }
  2268. if (ret != NULL)
  2269. free(ret);
  2270. rc = sp_rpc_client_mgr_send_answer(m_rpc_mgr, epid, svc_id, rpc_id, &ans_pkt);
  2271. if (rc != 0) {
  2272. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("send rpc answer failed!");
  2273. }
  2274. if (ans_pkt) {
  2275. iobuffer_dec_ref(ans_pkt);
  2276. }
  2277. }
  2278. ErrorCodeEnum SpEntity::PostInfoShell(int call_type, iobuffer_t **info_pkt)
  2279. {
  2280. int rc;
  2281. rc = sp_rpc_client_mgr_one_way_call(get_rpc_mgr(),
  2282. SP_SHELL_MOD_ID,
  2283. SP_SHELL_SVC_ID,
  2284. call_type,
  2285. info_pkt);
  2286. return SpTranslateError(rc);
  2287. }
  2288. void SpEntity::FinishStart(ErrorCodeEnum Error)
  2289. {
  2290. sp_mod_entity_stub_finish_start(m_stub, Error);
  2291. if (Error == Error_Succeed) {
  2292. m_pEntityBase->OnStarted();
  2293. }
  2294. }
  2295. void SpEntity::FinishClose(ErrorCodeEnum Error)
  2296. {
  2297. sp_mod_entity_stub_finish_stop(m_stub, Error);
  2298. if (Error == Error_Succeed) {
  2299. Term();
  2300. }
  2301. }
  2302. void SpEntity::FinishPause(ErrorCodeEnum Error)
  2303. {
  2304. sp_mod_entity_stub_finish_pause(m_stub, Error);
  2305. if (Error == Error_Succeed) {
  2306. m_pEntityBase->OnPaused();
  2307. }
  2308. }
  2309. void SpEntity::FinishContinue(ErrorCodeEnum Error)
  2310. {
  2311. sp_mod_entity_stub_finish_continue(m_stub, Error);
  2312. if (Error == Error_Succeed) {
  2313. m_pEntityBase->OnContinued();
  2314. }
  2315. }
  2316. void SpEntity::FinishSelfTest(ErrorCodeEnum Error, DWORD dwResult)
  2317. {
  2318. //sp_mod_entity_stub_finish_test(m_stub, Error);
  2319. sp_mod_entity_stub_finish_exam(m_stub, Error, dwResult);
  2320. }