SpEntity.cpp 80 KB

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