12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531 |
- #include "stdafx.h"
- #include "SpBase.h"
- #include "SpTimer.h"
- #include "SpMisc.h"
- #include "SpHelper.h"
- #include "SpEntity.h"
- #include "SpModule.h"
- #include "SpAsyncWait.h"
- #include "SpClientSessionFunction.h"
- #include "SpServerSessionFunction.h"
- #include "sp_iom.h"
- #include "sp_svc.h"
- #include "sp_log.h"
- #include "sp_var.h"
- #include "sp_def.h"
- #include "sp_cfg.h"
- #include "sp_env.h"
- #include "sp_btr.h"
- #include "memutil.h"
- #include "strutil.h"
- #include "fileutil.h"
- #include "shm_array.h"
- #include "toolkit.h"
- #include "dbgutil.h"
- #include "def.h"
- #ifdef RVC_OS_WIN
- #include "CodeSignVerify.h"
- #include "sp_checkEntity.h"
- #include "sp_firewallControl.h"
- #else
- #include "sp_dbg_export.h"
- #endif //RVC_OS_WIN
- #include "sp_httpDefine.h"
- #include <iostream>
- #include <sstream>
- #include <future>
- #include <chrono>
- #include <thread>
- static void var_callback(sp_var_listener_t *listener,
- const char *key,
- const char *oldstr,
- const char *newstr,
- int client_id,
- void *user_data)
- {
- ISysVarListener *pListener = (ISysVarListener *)user_data;
- SpEntity *pEntity = (SpEntity*)sp_var_listener_get_tag(listener);
- #ifdef RVC_OS_WIN
- SetthreadGroup(GetCurrentThreadId(), pEntity->get_cfg_ent()->name);
- getEntityResource()->m_Entity = pEntity;
- #else
- GetSpModule()->SetThreadEntity(pEntity);
- #endif //RVC_OS_WIN
- sp_env_t *env = sp_get_env();
- sp_entity_t *ent = sp_mod_mgr_find_entity_by_idx(env->mod_mgr, client_id);
- if (ent) {
- if(strcmp(VAR_RSERVERD_KEY_TERM_STATE, key) != 0)
- pListener->OnSysVarEvent(key, newstr, oldstr, ent->cfg->name);
- else {
- AppBootStateEnum oldState = static_cast<AppBootStateEnum>(atoi(oldstr));
- AppBootStateEnum newState = static_cast<AppBootStateEnum>(atoi(newstr));
- (static_cast<ITerminalStateChangedListener*>(user_data))->OnStateChanged(oldState, newState, ent->cfg->name);
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("cannot found the entity by id: %d", client_id);
- }
- }
- static void bcm_callback(sp_bcm_listener_t *listener,
- int from_client_id,
- int message_id,
- int message_sig,
- const void *buf,
- int len,
- void *user_data)
- {
- IBroadcastListener *pListener = (IBroadcastListener *)user_data;
- SpEntity *pEntity = (SpEntity*)sp_bcm_listener_get_tag(listener);
- sp_uid_t uid;
- #ifdef RVC_OS_WIN
- SetthreadGroup(GetCurrentThreadId(), pEntity->get_cfg_ent()->name);
- getEntityResource()->m_Entity = pEntity;
- #else
- GetSpModule()->SetThreadEntity(pEntity);
- #endif //RVC_OS_WIN
- sp_bcm_listener_get_uid(listener, &uid);
- sp_env_t *env = sp_get_env();
- sp_entity_t *ent = sp_mod_mgr_find_entity_by_idx(env->mod_mgr, from_client_id);
- if (ent) {
- CAutoBuffer Buf;
- Buf.Init(len);
- if (len > 0) {
- memcpy(&Buf[0], buf, len);
- }
- pListener->OnBroadcastEvent(CUUID(uid), ent->cfg->name, (DWORD)message_id, (DWORD)message_sig, Buf);
- }
- }
- static void on_log(void *inst,
- int nsub,
- u__int64_t *sub,
- int client_id,
- int log_epid,
- int client_instance_id,
- u__int64_t log_id,
- u__int64_t prev_rsn,
- u__int64_t curr_rsn,
- int original_rsn_type,
- int rsn_depth,
- unsigned int log_time,
- int log_type,
- int log_severity,
- int log_sys_error,
- int log_usr_error,
- int param_cnt,
- int *params,
- const char *msg,
- void *user_data,
- const char* bussId, const char* traceId, const char* spanId, const char* parentSpanId)
- {
- try
- {
- ILogListener *pListener = (ILogListener *)user_data;
- sp_entity_t *ent = sp_mod_mgr_find_entity_by_idx(sp_get_env()->mod_mgr, client_id);
- if (ent) {
- int i;
- CAutoArray<DWORD> arr;
- arr.Init(param_cnt);
- for (i = 0; i < param_cnt; ++i) {
- arr[i] = (DWORD)params[i];
- }
- CAutoArray<CUUID> subIDs;
- subIDs.Init(nsub);
- CUUID *pSub = (CUUID*)sub;
- for (i = 0; i < nsub; i++)
- subIDs[i] = pSub[i];
- linkContext cur;
- cur.Init(bussId, traceId, spanId, parentSpanId);
- pListener->OnLog(subIDs,
- CUUID(log_id), (LogTypeEnum)log_type, (SeverityLevelEnum)log_severity, log_sys_error, log_usr_error,
- ent->instance_id, ent->cfg->devel_id,
- arr, ent->cfg->name, ent->mod->cfg->name, msg, cur);
- }
- }
- catch (const std::exception& ex)
- {
- DbgWithLink(LOG_LEVEL_FATAL, LOG_TYPE_SYSTEM)("Exception occurs: %s at <%s>[%d]{%s}", ex.what(), __FUNCTION__, __LINE__, _GetFileName(__FILE__));
- //std::terminate();
- }
-
- }
- static void task_callback(threadpool_t *threadpool, void *arg, param_size_t param1, param_size_t param2)
- {
- ITaskSp *pTask = (ITaskSp*)arg;
- SpEntity *pEntity = (SpEntity*)param1;
- #ifdef RVC_OS_WIN
- SetthreadGroup(GetCurrentThreadId(), pEntity->GetEntityBase()->GetEntityName());
- try {
- getEntityResource()->m_Entity = pEntity;
- pTask->Process();
- pTask->DecRef();
- }
- catch (...)
- {
- DbgWithLink(LOG_LEVEL_FATAL, LOG_TYPE_SYSTEM)("Exception occurs at <%s>[%d]{%s}", __FUNCTION__, __LINE__, _GetFileName(__FILE__));
- //std::terminate();
- }
- #else
- GetSpModule()->SetThreadEntity(pEntity);
- pTask->Process();
- pTask->DecRef();
- #endif //RVC_OS_WIN
- }
- static void tpool_log(threadpool_t *threadpool, const char* str)
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)(str);
- }
- static ErrorCodeEnum GetEntityStaticInfo(CEntityStaticInfo &Info, sp_entity_t *ent)
- {
- sp_env_t *env = sp_get_env();
- if (ent) {
- bool bStartedByShell = false;
- for (int i = 0; i < env->cfg->shell_ini->arr_startlist->nelts; ++i) {
- sp_cfg_shell_entity_t * tmp_ent = ARRAY_IDX(env->cfg->shell_ini->arr_startlist, i, sp_cfg_shell_entity_t*);
- if (tmp_ent->idx == ent->cfg->idx) {
- bStartedByShell = true;
- break;
- }
- }
- Info.wEntityDevelopID = ent->cfg->devel_id;
- Info.strSpFileName = ent->mod->cfg->name;
- Info.bStartedByShell = bStartedByShell;
- Info.bIndispensable = true;
- Info.bHasPrivilege = !!ent->cfg->privilege;
- Info.version = CVersion(ent->cfg->version.major, ent->cfg->version.minor,
- ent->cfg->version.revision, ent->cfg->version.build);
- } else {
- return Error_NotExist;
- }
- return Error_Succeed;
- }
- SpEntity::SpEntity(SpModule *pModule, sp_entity_t *ent, sp_cfg_shell_entity_t *cfg_ent, CEntityBase *pEntityBase)
- : m_pModule(pModule), m_pEntityBase(pEntityBase), m_pTimerList(NULL), m_svc(NULL), m_var_client(NULL), m_log_client(NULL),
- 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)
- {
- if (m_ent != nullptr && m_pEntityBase != nullptr) {
- m_ent->service_flag = m_pEntityBase->IsService() ? 1 : 0;
- }
- memset(&m_arr_var[0], 0, sizeof(m_arr_var));
- }
- SpEntity::~SpEntity()
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("run ~SpEntity()");
- if (m_ent != nullptr && m_pEntityBase != nullptr) {
- #ifdef RVC_OS_WIN
- getEntityResource()->m_Entity = NULL;
- #endif //RVC_OS_WIN
- }
- }
- ErrorCodeEnum SpEntity::Init()
- {
- sp_mod_entity_stub_cb cb;
- int rc;
- threadpool_t *threadpool;
- rc = sp_svc_create(m_pModule->get_iom(), 0, m_ent->cfg->idx,m_ent->cfg->devel_id, &m_svc); //threadpool
- if (rc != 0) {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create svc failed!");
- return SpTranslateError(rc);
- }
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create svc ok!");
- threadpool = sp_svc_get_threadpool(m_svc);
- threadpool_set_thread_decorator(threadpool, &SpEntity::__on_thread_init, &SpEntity::__on_thread_term, this); //Entity thread
- threadpool_create(&m_tpool);
- threadpool_set_log(m_tpool, &tpool_log);
- threadpool_set_thread_decorator(m_tpool, &SpEntity::__on_thread_init, &SpEntity::__on_thread_term, this);
- threadpool_start(m_tpool, 0, 64, 5*60*1000, 0);
- #ifdef RVC_OS_WIN
- setModuleAliasName(GetEntityBase()->GetEntityName());
- #endif //RVC_OS_WIN
- rc = sp_svc_start(m_svc);
- if (rc != 0) {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("start svc failed!");
- return SpTranslateError(rc);
- }
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("start svc ok!");
- m_pTimerList = SpTimerListCreate(this);
- if (!m_pTimerList) {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create timer list failed!");
- return Error_Unexpect;
- }
- ResetEntityLastError();
- cb.on_entity_prestart = &SpEntity::__on_entity_prestart;
- cb.on_entity_stop = &SpEntity::__on_entity_stop;
- cb.on_entity_prepause = &SpEntity::__on_entity_prepause;
- cb.on_entity_test = &SpEntity::__on_entity_test;
- cb.on_entity_precontinue = &SpEntity::__on_entity_precontinue;
- cb.on_entity_redirect_subscribe = &SpEntity::__on_entity_redirect_subscribe;
- cb.user_data = this;
- rc = sp_mod_entity_stub_create(&cb, m_svc, &m_stub); //add a workItem mod_entity_on_pkt
- if (rc != 0) {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create entity stub failed!");
- return SpTranslateError(rc);
- }
- sp_rpc_client_mgr_callback mgr_cb = {SpEntity::__on_rpc_request, NULL, this};
- rc = sp_rpc_client_mgr_create(m_svc, &mgr_cb, &m_rpc_mgr); //Init variable m_rpc_mgr, callback handle
- if (rc != 0) {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create rpc client mgr failed!");
- return SpTranslateError(rc);
- }
- rc = sp_rpc_client_mgr_start(m_rpc_mgr); //add workItem mgr_on_pkt and mgr_on_sys
- if (rc != 0) {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("start rpc client mgr failed!");
- return SpTranslateError(rc);
- }
- sp_ses_mgr_callback_t ses_mgr_cb = {0};
- ses_mgr_cb.on_accept = &__on_accept;
- ses_mgr_cb.on_destroy = NULL;
- ses_mgr_cb.user_data = this;
- rc = sp_ses_mgr_create(m_svc, &ses_mgr_cb, &m_ses_mgr); //Init variable m_ses_mgr
- if (rc != 0) {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create ses mgr failed!");
- return SpTranslateError(rc);
- }
- rc = sp_ses_mgr_start(m_ses_mgr); //add workItem mgr_on_pkt and mgr_on_sys
- if (rc != 0) {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("start ses mgr failed!");
- return SpTranslateError(rc);
- }
- //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("start ses mgr ok!");
- rc = sp_log_client_create(m_svc, m_pModule->get_iom(), &m_log_client);
- if (rc != 0) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create log client failed!");
- return SpTranslateError(rc);
- }
- //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("start entity log client ok!");
- rc = sp_var_client_create(m_svc, &m_var_client);
- if (rc != 0) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create var client failed!");
- return SpTranslateError(rc);
- }
- //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create var client ok!");
- rc = sp_bcm_client_create(m_svc, &m_bcm_client);
- if (rc != 0) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create bcm client failed!");
- return SpTranslateError(rc);
- }
- //DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create bcm client ok!");
- rc = sp_log_listener_mgr_create(m_svc, on_log, &m_log_mgr);
- if (rc == 0) {
- rc = sp_log_listener_mgr_start(m_log_mgr);
- if (rc != 0) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create log mgr failed!");
- return SpTranslateError(rc);
- }
- }
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("entity Init end!");
- m_arr_bcm_listener = array_make(0, sizeof(sp_bcm_listener_t*));
- return SpTranslateError(rc);
- }
- void SpEntity::Term()
- {
- SpTimerListStopAll(m_pTimerList);
-
- }
- void SpEntity::on_entity_prestart(int trigger_entity_id, int argc, char *argv[])
- {
- CAutoArray<CSimpleStringA> Args;
- Args.Init(argc);
- CSmartPointer<ITransactionContext> pTransactionContext;
- pTransactionContext.Attach(new SpMUITransactionContext(this, SpMUITransactionContext::OP_START));
- for (int i = 0; i < argc; ++i)
- Args[i] = argv[i];
- m_pEntityBase->OnPreStart(Args, pTransactionContext);
- }
- void SpEntity::on_entity_stop(int trigger_entity_id, int cause_code)
- {
- CSmartPointer<ITransactionContext> pTransactionContext;
- pTransactionContext.Attach(new SpMUITransactionContext(this, SpMUITransactionContext::OP_CLOSE));
- m_pEntityBase->OnPreClose((EntityCloseCauseEnum)cause_code, pTransactionContext);
- }
- void SpEntity::on_entity_prepause(int trigger_entity_id)
- {
- CSmartPointer<ITransactionContext> pTransactionContext;
- pTransactionContext.Attach(new SpMUITransactionContext(this, SpMUITransactionContext::OP_PAUSE));
- m_pEntityBase->OnPrePause(pTransactionContext);
- }
- void SpEntity::on_entity_precontinue(int trigger_entity_id)
- {
- CSmartPointer<ITransactionContext> pTransactionContext;
- pTransactionContext.Attach(new SpMUITransactionContext(this, SpMUITransactionContext::OP_CONTINUE));
- m_pEntityBase->OnPreContinue(pTransactionContext);
- }
- void SpEntity::on_entity_test(int trigger_entity_id, int test_type)
- {
- const EntityTestEnum testType = static_cast<EntityTestEnum>(test_type);
- CSmartPointer<ITransactionContext> pTransactionContext;
- pTransactionContext.Attach(new SpMUITransactionContext(this, SpMUITransactionContext::OP_SELFTEST));
- if (testType == Test_Examine) {
- m_pEntityBase->OnExam(pTransactionContext);
- } else {
- m_pEntityBase->OnSelfTest(testType, pTransactionContext);
- }
- }
- void SpEntity::on_entity_redirect_subscribe(sp_uid_t *uid, int from_entity_id, const char *param)
- {
- CUUID id(*uid);
- sp_entity_t *ent = sp_mod_mgr_find_entity_by_idx(sp_get_env()->mod_mgr, from_entity_id);
- if (ent) {
- m_pEntityBase->OnBroadcastSubscribe(id, ent->cfg->name, param);
- }
- }
- void SpEntity::__on_entity_prestart(sp_mod_entity_stub_t*, int trigger_entity_id, int argc, char* argv[], void* user_data)
- {
- SpEntity *pThis = static_cast<SpEntity*>(user_data);
- pThis->on_entity_prestart(trigger_entity_id, argc, argv);
- }
- void SpEntity::__on_entity_stop(sp_mod_entity_stub_t *, int trigger_entity_id, int cause_code, void *user_data)
- {
- SpEntity *pThis = static_cast<SpEntity*>(user_data);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("stop Entity");
- pThis->on_entity_stop(trigger_entity_id, cause_code);
- }
- void SpEntity::__on_entity_prepause(sp_mod_entity_stub_t *, int trigger_entity_id, void *user_data)
- {
- SpEntity *pThis = static_cast<SpEntity*>(user_data);
- pThis->on_entity_prepause(trigger_entity_id);
- }
- void SpEntity::__on_entity_precontinue(sp_mod_entity_stub_t *, int trigger_entity_id, void *user_data)
- {
- SpEntity *pThis = static_cast<SpEntity*>(user_data);
- pThis->on_entity_precontinue(trigger_entity_id);
- }
- void SpEntity::__on_entity_test(sp_mod_entity_stub_t *, int trigger_entity_id, int test_type, void *user_data)
- {
- SpEntity *pThis = static_cast<SpEntity*>(user_data);
- pThis->on_entity_test(trigger_entity_id, test_type);
- }
- 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)
- {
- SpEntity *pThis = static_cast<SpEntity*>(user_data);
- pThis->on_entity_redirect_subscribe(uid, from_entity_id, param);
- }
- 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)
- {
- SpEntity *pThis = static_cast<SpEntity*>(user_data);
- return pThis->on_accept(epid, svc_id, conn_id, conn_pkt, redirect_entity_id);
- }
- int SpEntity::on_accept(int epid, int svc_id, int conn_id, iobuffer_t **conn_pkt, int *redirect_entity_id)
- {
- sp_env_t *env = sp_get_env();
- ErrorCodeEnum Error = Error_Succeed;
- if (!m_pEntityBase->IsService()) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("current entity is no registed as service type, please confirm it at code scope.");
- return Error_NotSupport;
- }
- sp_entity_t *remote_ent = sp_mod_mgr_find_entity_by_idx(env->mod_mgr, svc_id);
- if (!remote_ent) {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("cannot recognize the customer entity: %d!", svc_id);
- return Error_Bug;
- }
-
- char *pszParam = NULL;
- CServerSessionBase *pServerSessionBase = NULL;
- iobuffer_format_read(*conn_pkt, "s", &pszParam);
- try {
- m_redirect_entity_cache = NULL; // user can set entity_cache value in OnNewSession by invoking RedirectSession method
- pServerSessionBase = m_pEntityBase->OnNewSession(remote_ent->cfg->name, pszParam);
- } catch (...)
- {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("Exception occurs at <%s>[%d]{%s}", __FUNCTION__, __LINE__, _GetFileName(__FILE__));
- Error = Error_Exception;
- }
- FREE(pszParam);
- if (pServerSessionBase)
- {
- SpServerSessionFunction *pServerSessionFunction = new SpServerSessionFunction(this, pServerSessionBase, epid, svc_id, conn_id);
- pServerSessionBase->m_pSessionFunction = pServerSessionFunction;
- Error = pServerSessionFunction->Begin();
- if (Error != Error_Succeed)
- {
- delete pServerSessionBase; // this will also delete pServerSessionFunction
- }
- }
- else
- {
- if (m_redirect_entity_cache)
- {
- *redirect_entity_id = m_redirect_entity_cache->cfg->idx;
- Error = Error_Redirect;
- }
- else
- {
- Error = Error_NotImpl;
- }
- }
- return Error;
- }
- void SpEntity::on_thread_init()
- {
- #ifdef RVC_OS_WIN
- SetthreadGroup(GetCurrentThreadId(), this->get_cfg_ent()->name);
- getEntityResource()->m_Entity = this;
- #else
- m_pModule->SetThreadEntity(this);
- #endif //RVC_OS_WIN
- }
- void SpEntity::on_thread_term()
- {
- #ifdef RVC_OS_WIN
- SetthreadGroup(GetCurrentThreadId(), this->get_cfg_ent()->name);
- getEntityResource()->m_Entity = NULL;
- #else
- m_pModule->SetThreadEntity(NULL);
- #endif //RVC_OS_WIN
- }
- void SpEntity::__on_thread_init(threadpool_t *, void *arg)
- {
- SpEntity *pThis = static_cast<SpEntity*>(arg);
- pThis->on_thread_init();
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("thread init, thread id:%u",
- #ifndef RVC_OS_WIN
- GetCurrentThreadIdFromSys());
- #else
- GetCurrentThreadId());
- #endif //NOT RVC_OS_WIN
- }
- void SpEntity::__on_thread_term(threadpool_t *, void *arg)
- {
- SpEntity *pThis = static_cast<SpEntity*>(arg);
- pThis->on_thread_term();
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("thread term, thread id:%d",
- #if defined(RVC_OS_WIN)
- GetCurrentThreadId());
- #else
- GetCurrentThreadIdFromSys());
- #endif //RVC_OS_WIN
- }
- ErrorCodeEnum SpEntity::SetTimer(DWORD nTimerID, ITimerListener *pListener, DWORD dwInterval)
- {
- ErrorCodeEnum Error = Error_Succeed;
- if (!pListener)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("timer id %d param error!", nTimerID);
- return Error_Param;
- }
- SpTimerListLock(m_pTimerList);
- if (SpTimerListFind(m_pTimerList, nTimerID)) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("timer id %d already in use!", nTimerID);
- Error = Error_AlreadyExist;
- } else {
- SpTimer *pTimer = SpTimerCreate(m_pTimerList, nTimerID, dwInterval, pListener);
- if (pTimer) {
- SpTimerListAdd(m_pTimerList, pTimer);
- Error = SpTimerStart(pTimer);
- if (Error) {
- SpTimerListRemove(m_pTimerList, pTimer);
- SpTimerDestroy(pTimer);
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("start timer %d failed!", nTimerID);
- } else {
- //DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("timer %d added! interval = %d", nTimerID, dwInterval);
- }
- } else {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("timer id %d create error!", nTimerID);
- Error = Error_Unexpect;
- }
- }
- SpTimerListUnlock(m_pTimerList);
- return Error;
- }
- ErrorCodeEnum SpEntity::SetTimerData(DWORD dwTimerID, IReleasable *pData)
- {
- ErrorCodeEnum Error = Error_Succeed;
- SpTimerListLock(m_pTimerList);
- SpTimer *pTimer = SpTimerListFind(m_pTimerList, dwTimerID);
- if (pTimer) {
- SpTimerSetUserData(pTimer, pData);
- } else {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("timer %d not found!", dwTimerID);
- Error = Error_NotExist;
- }
- SpTimerListUnlock(m_pTimerList);
- return Error;
- }
- ErrorCodeEnum SpEntity::GetTimerData(DWORD dwTimerID, CSmartPointer<IReleasable> &pData)
- {
- ErrorCodeEnum Error = Error_Succeed;
- SpTimerListLock(m_pTimerList);
- SpTimer *pTimer = SpTimerListFind(m_pTimerList, dwTimerID);
- if (pTimer) {
- SpTimerGetUserData(pTimer, pData);
- } else {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("timer %d not found!", dwTimerID);
- Error = Error_NotExist;
- }
- SpTimerListUnlock(m_pTimerList);
- return Error;
- }
- ErrorCodeEnum SpEntity::KillTimer(DWORD nTimerID)
- {
- ErrorCodeEnum Error = Error_Succeed;
- SpTimerListLock(m_pTimerList);
- SpTimer *pTimer = SpTimerListFind(m_pTimerList, nTimerID);
- if (pTimer) {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("timer %d killed!", nTimerID);
- SpTimerListRemove(m_pTimerList, pTimer);
- SpTimerStop(pTimer);
- SpTimerDestroy(pTimer);
- } else {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("timer %d has not set!", nTimerID);
- Error = Error_NotExist;
- }
- SpTimerListUnlock(m_pTimerList);
- return Error;
- }
- ErrorCodeEnum SpEntity::ResetTimer(DWORD nTimerID, DWORD dwInterval)
- {
- ErrorCodeEnum Error = Error_Succeed;
- SpTimerListLock(m_pTimerList);
- SpTimer *pTimer = SpTimerListFind(m_pTimerList, nTimerID);
- if (pTimer) {
- SpTimerSetInterval(pTimer, dwInterval);
- } else {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("timer %d has not set!", nTimerID);
- Error = Error_NotExist;
- }
- SpTimerListUnlock(m_pTimerList);
- return Error;
- }
- ErrorCodeEnum SpEntity::GetTimerInterval(DWORD nTimerID, DWORD &dwInterval)
- {
- ErrorCodeEnum Error = Error_Succeed;
- SpTimerListLock(m_pTimerList);
- SpTimer *pTimer = SpTimerListFind(m_pTimerList, nTimerID);
- if (pTimer) {
- dwInterval = SpTimerGetInterval(pTimer);
- } else {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("timer %d has not set!", nTimerID);
- Error = Error_NotExist;
- }
- SpTimerListUnlock(m_pTimerList);
- return Error;
- }
- ErrorCodeEnum SpEntity::SubscribeLog(CUUID &SubscribeID, ILogListener *pListener,LogTypeEnum eLogType,
- SeverityLevelEnum eLevel, ErrorCodeEnum eSysError,DWORD dwUserCode,
- const char *pszEntityName,bool bIgnoreMessage)
- {
- _ASSERT(pListener);
- sp_entity_t *ent = NULL;
- if (pszEntityName) {
- ent = sp_mod_mgr_find_entity_by_name(sp_get_env()->mod_mgr, pszEntityName);
- if (!ent) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("SubscribeLog failed! Entity %s not exist!", pszEntityName);
- return Error_NotExist;
- }
- }
- unsigned int listen_id = 0;
- int rc = sp_log_listener_mgr_subscribe(m_log_mgr, &listen_id, pListener, !!bIgnoreMessage,
- eLogType, ent ? ent->cfg->idx : -1, eLevel, eSysError, dwUserCode);
- if (rc == 0) {
- SubscribeID = listen_id;
- }
- return SpTranslateError(rc);
- }
- ErrorCodeEnum SpEntity::UnsubscribeLog(CUUID SubscribeID)
- {
- unsigned int listen_id = (unsigned int)SubscribeID;
- int rc = sp_log_listener_mgr_unsubscribe(m_log_mgr, listen_id);
- return SpTranslateError(rc);
- }
- ErrorCodeEnum SpEntity::FlushLogFile()
- {
- return LogFlush();
- }
- ErrorCodeEnum SpEntity::SetSysVar(const char *pszKey,const char *pszValue, bool bPersist)
- {
- int rc;
- _ASSERT(pszKey); // pszValue can be null, use for delete
- rc = sp_var_client_set((sp_var_client_t*)m_var_client, pszKey, pszValue, bPersist ? 1 : 0);
- return SpTranslateError(rc);
- }
- ErrorCodeEnum SpEntity::GetSysVar(const char *pszKey,CSimpleStringA &strValue)
- {
- sp_var_client_t* client = (sp_var_client_t*)m_var_client;
- int slen = 0;
- int rc;
- _ASSERT(pszKey);
- rc = sp_var_client_lock(client);
- if (rc == 0) {
- rc = sp_var_client_get(client, pszKey, NULL, &slen);
- if (rc == Error_TooSmallBuffer) {
- CSimpleStringA strTmp('\0', slen);
- rc = sp_var_client_get((sp_var_client_t*)m_var_client, pszKey, &strTmp[0], &slen);
- if (rc == 0)
- strValue = strTmp;
- }
- sp_var_client_unlock(client);
- }
- return SpTranslateError(rc);
- }
- ErrorCodeEnum SpEntity::RegistSysVarEvent(const char *pszKey,ISysVarListener *pListener)
- {
- int rc = 0;
- if (!pszKey || strlen(pszKey) == 0 || !pListener)
- return Error_Param;
- sp_env_t *env = sp_get_env();
- sp_var_listener_t **pp_var;
- if (strcmp(pszKey, "*") != 0) {
- sp_cfg_shell_sysevent_t *sysevent = sp_cfg_get_sysevent(env->cfg, pszKey);
- if (!sysevent)
- return Error_NotExist;
- if (m_arr_var[sysevent->idx])
- return Error_Duplication;
- pp_var = &m_arr_var[sysevent->idx];
- } else {
- if (m_arr_any_var)
- return Error_Duplication;
- pp_var = &m_arr_any_var;
- }
- sp_var_listener_t *listener;
- sp_var_listener_create(m_svc, pszKey, &var_callback, pListener, &listener);
- sp_var_listener_set_tag(listener, this);
- rc = sp_var_listener_subscribe(listener);
- if (rc == 0) {
- *pp_var = listener;
- } else {
- sp_var_listener_destroy(listener);
- }
- return SpTranslateError(rc);
- }
- ErrorCodeEnum SpEntity::UnregistSysVarEvent(const char *pszKey)
- {
- if (!pszKey || strlen(pszKey) == 0)
- return Error_Param;
- int rc = 0;
- if (strcmp(pszKey, "*") != 0) {
- sp_env_t *env = sp_get_env();
- sp_cfg_shell_sysevent_t *sysevent = sp_cfg_get_sysevent(env->cfg, pszKey);
- if (!sysevent)
- return Error_NotExist;
- sp_var_listener_t *listener = m_arr_var[sysevent->idx];
- if (listener) {
- int rc;
- rc = sp_var_listener_unsubscribe(listener);
- if (rc == 0) {
- sp_var_listener_destroy(listener);
- m_arr_var[sysevent->idx] = NULL;
- }
- } else {
- rc = Error_NotInit;
- }
- } else {
- if (m_arr_any_var != NULL)
- {
- rc = sp_var_listener_unsubscribe(m_arr_any_var);
- if (rc == 0)
- {
- sp_var_listener_destroy(m_arr_any_var);
- m_arr_any_var = NULL;
- }
- }
- }
- return SpTranslateError(rc);
- }
- ErrorCodeEnum SpEntity::RegistTerminalStateChangeEvent(ITerminalStateChangedListener* pListener)
- {
- return RegistSysVarEvent(VAR_RSERVERD_KEY_TERM_STATE, (ISysVarListener*)(void*)((uintptr_t)pListener));
- }
- ErrorCodeEnum SpEntity::UnregistTerminalStateChangeEvent()
- {
- return UnregistSysVarEvent(VAR_RSERVERD_KEY_TERM_STATE);
- }
- ErrorCodeEnum SpEntity::SendBroadcast(DWORD dwMessageId, DWORD dwMessageSignature,CAutoBuffer Buffer)
- {
- int rc;
- iobuffer_t *pkt = iobuffer_create(-1, Buffer.GetCount());
- iobuffer_write(pkt, IOBUF_T_BUF, &Buffer[0], Buffer.GetCount());
- rc = sp_bcm_client_bcast(m_bcm_client, dwMessageId, dwMessageSignature, &pkt);
- if (pkt)
- iobuffer_dec_ref(pkt);
- return SpTranslateError(rc);
- }
- ErrorCodeEnum SpEntity::GetBroadcastReceivers(CAutoArray<BroadcastSubscribeInfo> &Subscribers)
- {
- ErrorCodeEnum Error;
- iobuffer_t *req_pkt = iobuffer_create(-1, -1);
- iobuffer_t *ans_pkt = NULL;
- Error = AskShell(SHELL_CMD_REQ_GET_BCAST_RECEIVER, &req_pkt, &ans_pkt);
- if (Error == Error_Succeed) {
- sp_env_t *env = sp_get_env();
- int size;
- iobuffer_read(ans_pkt, IOBUF_T_I4, &size, NULL);
- Subscribers.Init(size);
- for (int i = 0; i < size; ++i) {
- int ent_id;
- sp_uid_t uid;
- char *param = NULL;
- iobuffer_format_read(ans_pkt, "84s", &uid, &ent_id, ¶m);
- Subscribers[i].SubID = CUUID(uid);
- sp_entity_t *ent = sp_mod_mgr_find_entity_by_idx(env->mod_mgr, ent_id);
- Subscribers[i].strListener = ent->cfg->name;
- Subscribers[i].strParam = param;
- FREE(param);
- }
- }
- if (req_pkt)
- iobuffer_dec_ref(req_pkt);
- if (ans_pkt)
- iobuffer_dec_ref(ans_pkt);
- return Error;
- }
- ErrorCodeEnum SpEntity::SubscribeBroadcast(const char *pszRemoteEntity, const char *pszParam,
- IBroadcastListener *pListener, CUUID &SubscribeID)
- {
- if (pszParam == NULL)
- pszParam = "";
- if (pListener == NULL)
- return Error_Param;
- sp_entity_t *remote_ent = sp_mod_mgr_find_entity_by_name(sp_get_env()->mod_mgr, pszRemoteEntity);
- if (remote_ent) {
- int rc;
- sp_uid_t uid;
- sp_bcm_listener_t *listener;
- sp_bcm_listener_cb cb = {0};
- cb.on_destroy = NULL;
- cb.on_message = &bcm_callback;
- cb.on_message_raw = NULL;
- cb.user_data = pListener;
- rc = sp_bcm_listener_create(m_svc, remote_ent->cfg->idx, pszParam, &cb, &listener);
- if (rc == 0) {
- rc = sp_bcm_listener_subscribe(listener, &uid);
- }
- if (rc != 0) {
- return SpTranslateError(rc);
- }
- SubscribeID = CUUID(uid);
- sp_bcm_listener_set_tag(listener, this);
- ARRAY_PUSH(m_arr_bcm_listener, sp_bcm_listener_t*) = listener;
- } else {
- return Error_NotExist;
- }
- return Error_Succeed;
- }
- ErrorCodeEnum SpEntity::UnsubscribeBroadcast(CUUID SubscribeID)
- {
- sp_bcm_listener_t *listener = NULL;
- int i;
- for (i = 0; i < m_arr_bcm_listener->nelts; ++i) {
- listener = ARRAY_IDX(m_arr_bcm_listener, i, sp_bcm_listener_t*);
- sp_uid_t uid;
- sp_bcm_listener_get_uid(listener, &uid);
- if (uid == SubscribeID.m_nUUID64) {
- ARRAY_DEL(m_arr_bcm_listener, i, sp_bcm_listener_t*);
- break;
- }
- }
- if (listener) {
- sp_bcm_listener_unsubscribe(listener);
- sp_bcm_listener_destroy(listener);
- return Error_Succeed;
- } else {
- return Error_NotExist;
- }
- }
- ErrorCodeEnum SpEntity::UnsubscribeBroadcast(const char *pszRemoteEntity)
- {
- if (pszRemoteEntity == NULL)
- return Error_Param;
- sp_entity_t *ent = sp_mod_mgr_find_entity_by_name(sp_get_env()->mod_mgr, pszRemoteEntity);
- if (!ent)
- return Error_NotExist;
- sp_bcm_listener_t *listener = NULL;
- int i;
- for (i = m_arr_bcm_listener->nelts-1; i >= 0; --i) {
- listener = ARRAY_IDX(m_arr_bcm_listener, i, sp_bcm_listener_t*);
- if (ent->cfg->idx == sp_bcm_listener_get_target_entity_id(listener)) {
- ARRAY_DEL(m_arr_bcm_listener, i, sp_bcm_listener_t*);
- sp_bcm_listener_unsubscribe(listener);
- sp_bcm_listener_destroy(listener);
- }
- }
- return Error_Succeed;
- }
- ErrorCodeEnum SpEntity::LogMessage( const LogTypeEnum LogType, const SeverityLevelEnum Level,
- DWORD dwSysErrorCode, DWORD dwUserErrorCode, const char *pMessage )
- {
- int nDevID = m_ent->cfg->devel_id;
- if (dwUserErrorCode != 0 && ((dwUserErrorCode >> 20) & nDevID) != nDevID) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("[InvalidUserCode] devID: 0x%x, userCode: 0x%x", nDevID, dwUserErrorCode);
- }
- if (NULL == m_log_client) {
- return Error_Null;
- }
- auto rc = sp_log_client_logEx(m_log_client, LogType, Level, (int)dwSysErrorCode, (int)dwUserErrorCode, 0, 0,
- pMessage == NULL ? "" : pMessage, pMessage == NULL ? 0 : strlen(pMessage));
- if (rc != 0) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("log message failed! raw msg: %s: %d", pMessage, rc);
- } else {
- if (-1 != dwUserErrorCode && 0 != dwUserErrorCode)//discard the dbg msg code
- {
- //DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("userCode: 0x%x send", dwUserErrorCode);
- }
- }
- /*存储当前实体最新一条错误信息*/
- if ((LogType == Log_Warning && (Level == Severity_High || Level == Severity_Middle))
- || LogType == Log_Error || LogType == Log_Fatal) {
- SetEntityLastError((ErrorCodeEnum)dwSysErrorCode, dwUserErrorCode, pMessage);
- }
- return SpTranslateError(rc);
- }
- ErrorCodeEnum SpEntity::LogMessage(const LogTypeEnum LogType, const SeverityLevelEnum Level,
- DWORD iSysErrorCode, DWORD iUserErrorCode, CAutoArray<DWORD> Param,
- const char *pMessage)
- {
- // xkm@20160726: 校验 iUserErrorCode 是否合法
- int nDevID = m_ent->cfg->devel_id;
- if (iUserErrorCode != 0 && ((iUserErrorCode >> 20) & nDevID) != nDevID)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("[InvalidUserCode] devID: 0x%x, userCode: 0x%x", nDevID, iUserErrorCode);
- }
- int rc;
- sp_log_client_t *client = (sp_log_client_t*)m_log_client;
- rc = sp_log_client_logEx(client, LogType, Level, (int)iSysErrorCode, (int)iUserErrorCode, (int)Param.GetCount(), (int*)&Param[0]
- , NULL == pMessage ? "" : pMessage, NULL == pMessage ? 0 : strlen(pMessage));
- if (rc != 0) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("log message failed! raw msg: %s", pMessage);
- }
- return SpTranslateError(rc);
- }
- ErrorCodeEnum SpEntity::LogMessage(const LogTypeEnum LogType, const SeverityLevelEnum Level, DWORD iSysErrorCode, DWORD iUserErrorCode, const char* pMessage, const linkContext& t_context)
- {
- int nDevID = m_ent->cfg->devel_id;
- if (iUserErrorCode != 0 && ((iUserErrorCode >> 20) & nDevID) != nDevID) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("[InvalidUserCode] devID: 0x%x, userCode: 0x%x", nDevID, iUserErrorCode);
- }
- if (NULL == m_log_client)
- return Error_Null;
- auto rc = sp_log_client_logWithLink(m_log_client, LogType, Level, (int)iSysErrorCode, (int)iUserErrorCode, 0, 0,
- pMessage == NULL ? "" : pMessage, pMessage == NULL ? 0 : strlen(pMessage)
- , t_context.bussinessId.GetData(), t_context.traceId.GetData(), t_context.spanId.GetData(), t_context.parentSpanId.GetData());
- if (rc != 0) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("log message failed! raw msg: %s", pMessage);
- }
- else
- {
- if (-1 != iUserErrorCode && 0 != iUserErrorCode)//discard the dbg msg code
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("userCode: 0x%x send", iUserErrorCode);
- }
- return SpTranslateError(rc);
- }
- WORD SpEntity::GetDevID()
- {
- return m_ent->cfg->devel_id;
- }
- ErrorCodeEnum SpEntity::LogMessage(const LogTypeEnum LogType, const SeverityLevelEnum Level, DWORD iSysErrorCode, DWORD iUserErrorCode, CAutoArray<DWORD> Param, const char* pMessage, const linkContext& t_context)
- {
- int nDevID = m_ent->cfg->devel_id;
- if (iUserErrorCode != 0 && ((iUserErrorCode >> 20) & nDevID) != nDevID)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("[InvalidUserCode] devID: 0x%x, userCode: 0x%x", nDevID, iUserErrorCode);
- }
- int rc;
- sp_log_client_t* client = (sp_log_client_t*)m_log_client;
- rc = sp_log_client_logWithLink(client, LogType, Level, (int)iSysErrorCode, (int)iUserErrorCode, (int)Param.GetCount(), (int*)&Param[0]
- , NULL == pMessage ? "" : pMessage, NULL == pMessage ? 0 : strlen(pMessage)
- , t_context.bussinessId.GetData(), t_context.traceId.GetData(), t_context.spanId.GetData(), t_context.parentSpanId.GetData());
- if (rc != 0) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("log message failed! raw msg: %s", pMessage);
- }
- return SpTranslateError(rc);
- }
- ErrorCodeEnum SpEntity::LogFlush()
- {
- int rc;
- sp_log_client_t *client = (sp_log_client_t*)m_log_client;
- rc = sp_log_client_flush(client);
- if (rc != 0) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("flush log message failed!");
- }
- return SpTranslateError(rc);
- }
- ErrorCodeEnum SpEntity::OpenConfig(ConfigTypeEnum eConfigType,CSmartPointer<IConfigInfo> &spConfigInfo, bool forceFile)
- {
- IConfigInfo* pConfigInfo = NULL;
- sp_env_t* env = sp_get_env();
- sp_cfg_t* cfg = env->cfg;
- if (ConfigTypeEnum::Config_Root == eConfigType)
- {
- if (forceFile || cfg->root_ini->root_config == NULL || strlen(cfg->root_ini->root_config) == 0)
- pConfigInfo = new SpIniConfig(this, eConfigType);
- else
- pConfigInfo = new SpRootMemConfig(this, eConfigType);
- //Dbg("Use root cfg type :%s", pConfigInfo->storageInMem() ? "mem" : "ini");
- }
- else if (ConfigTypeEnum::Config_CenterSetting == eConfigType)
- {
- if (forceFile || cfg->root_ini->center_config == NULL || strlen(cfg->root_ini->center_config) == 0)
- pConfigInfo = new SpIniConfig(this, eConfigType);
- else
- pConfigInfo = new SpRootMemConfig(this, eConfigType);
- //Dbg("Use center cfg type :%s", pConfigInfo->storageInMem() ? "mem" : "ini");
- }
- else if (ConfigTypeEnum::Config_Shell == eConfigType)
- {
- if (forceFile || cfg->root_ini->shell_config == NULL || strlen(cfg->root_ini->shell_config) == 0)
- pConfigInfo = new SpIniConfig(this, eConfigType);
- else
- pConfigInfo = new SpRootMemConfig(this, eConfigType);
- }
- else
- pConfigInfo = new SpIniConfig(this, eConfigType);
- spConfigInfo.Attach(pConfigInfo);
- return Error_Succeed;
- }
- ErrorCodeEnum SpEntity::SetUserDefineState(DWORD dwState)
- {
- sp_env_t *env = sp_get_env();
- //sp_mod_mgr_lock(mod_mgr);
- DWORD dwOldState = m_ent->user_state;
- m_ent->user_state = dwState;
- //sp_mod_mgr_unlock(mod_mgr);
- // send state chage event to shell
- if (dwOldState != dwState)
- sp_mod_entity_stub_report_user_state_change(m_stub, dwOldState, dwState);
- return Error_Succeed;
- }
- DWORD SpEntity::GetUserDefineState()
- {
- sp_env_t* env = sp_get_env();
- return (DWORD)(m_ent->user_state);
- }
- MachineTypeEnum SpEntity::GetMachineType(CSimpleStringA* outStrMachine)
- {
- MachineTypeEnum machineType(RVC_Unknown);
- CSystemStaticInfo stStaticinfo;
- CSimpleStringA strMachineType(true);
- auto rc = GetSystemStaticInfo(stStaticinfo);
- if (rc == Error_Succeed) {
- strMachineType = stStaticinfo.strMachineType;
- machineType = SpStr2MachineType(strMachineType);
- }
- if (outStrMachine != NULL) {
- (*outStrMachine) = strMachineType.GetData();
- }
- return machineType;
- }
- ErrorCodeEnum SpEntity::GetSystemStaticInfo(CSystemStaticInfo &Info)
- {
- sp_env_t *env = sp_get_env();
- sp_cfg_t *cfg = env->cfg;
- sp_dir_t* dir = env->dir;
- sp_cfg_root_ini_t *root_ini = cfg->root_ini;
- sp_cfg_install_ini_t *install_ini = cfg->install_ini;
- int i;
- sp_cfg_version_info_t *version_info;
- Info.strTerminalID = CSimpleStringA(root_ini->terminal_no);
- Info.strMachineType = CSimpleStringA(root_ini->machine_type);
- Info.strManufacturer = CSimpleStringA(root_ini->manufacturer);
- Info.MachineVersion = CVersion(root_ini->machine_version.major, root_ini->machine_version.minor, root_ini->machine_version.revision, root_ini->machine_version.build);
- 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);
- if (install_ini->arr_light_pack->nelts > 0) {
- Info.LightPackInfos.Init(install_ini->arr_light_pack->nelts);
- }
- for (i = 0; i < install_ini->arr_light_pack->nelts; ++i) {
- sp_cfg_pack_info_t *pack = ARRAY_IDX(install_ini->arr_light_pack, i, sp_cfg_pack_info_t*);
- Info.LightPackInfos[i].strPackName = CSimpleStringA(pack->name);
- Info.LightPackInfos[i].State = (InstallStateEnum)pack->state;
- Info.LightPackInfos[i].tmInstalledDate = CSmallDateTime(pack->install_time);
- }
- Info.nTotalRunCount = install_ini->total_run_count;
- Info.nTodayRunCount = install_ini->today_run_count;
- Info.tmCreateDate = install_ini->install_time;
- Info.tmCurrentTime = install_ini->current_startup_time;
- Info.strSite = CSimpleStringA(root_ini->site == NULL ? "" : root_ini->site);
- Info.eScreen = (ScreenEnum)root_ini->screen;
- Info.strEnrolAddr = CSimpleStringA(root_ini->enroll_address == NULL ? "" : root_ini->enroll_address);
- Info.EnrolGPS = CSphereVector(root_ini->enroll_gps_x, root_ini->enroll_gps_y);
- version_info = sp_cfg_find_previous_version_info(cfg, &install_ini->install_version);
- if (version_info) {
- Info.PreviousInstallVersion = CVersion(version_info->version.major, version_info->version.minor, version_info->version.revision, version_info->version.build);
- } else {
- Info.PreviousInstallVersion = CVersion(0, 0, 0, 0);
- }
- version_info = sp_cfg_find_version_info(cfg, &install_ini->install_version);
- if (version_info)
- {
- Info.InstallVersion = CVersion(install_ini->install_version.major, install_ini->install_version.minor, install_ini->install_version.revision, install_ini->install_version.build);
- Info.tmSwithOverDate = version_info->switch_time;
- Info.InstallPack = CSimpleStringA(version_info->install_pack);
- Info.InstallState = (InstallStateEnum)version_info->install_state;
- }
- if (dir->dep_ver_path == NULL) {
- sp_dir_refresh_dep_path(env->dir);
- }
- if (dir->dep_ver_path != NULL) {
- Info.CurrDepVersion = CSimpleStringA(strrchr(dir->dep_ver_path, SPLIT_SLASH) + 1);
- }
- return Error_Succeed;
- }
- ErrorCodeEnum SpEntity::GetInstallInfo(CVersion Version,CInstallInfo &Info)
- {
- sp_env_t *env = sp_get_env();
- sp_cfg_t *cfg = env->cfg;
- /*sp_cfg_root_ini_t *root_ini = cfg->root_ini;
- sp_cfg_install_ini_t *install_ini = cfg->install_ini;*/
- sp_cfg_version_info_t *version_info;
- sp_version_t ver = {Version.GetMajor(), Version.GetMinor(), Version.GetRevision(), Version.GetBuild()};
- version_info = sp_cfg_find_version_info(cfg, &ver);
- if (version_info) {
- Info.InstallPack = version_info->install_pack;
- Info.InstallState = (InstallStateEnum)version_info->install_state;
- Info.InstallVersion = Version;
- Info.PreviousInstallVersion = CVersion(version_info->previous_version.major,
- version_info->previous_version.minor,
- version_info->previous_version.revision,
- version_info->previous_version.build);
- Info.tmSwithOverDate = version_info->switch_time;
- } else {
- return Error_NotExist;
- }
- return Error_Succeed;
- }
- ErrorCodeEnum SpEntity::GetPath(const char *pszKey,CSimpleStringA &strPath)
- {
- sp_env_t *env = sp_get_env();
- ErrorCodeEnum Error = Error_Succeed;
- if (!pszKey)
- return Error_Null;
- if (_stricmp(pszKey, "Root") == 0 || _stricmp(pszKey, "Run") == 0) {
- strPath = env->dir->root_path;
- } else if (_stricmp(pszKey, "RootVer") == 0) {
- strPath = env->dir->root_ver_path;
- } else if (_stricmp(pszKey, "Data") == 0) {
- strPath = CSimpleStringA(env->dir->obj_path);
- } else if (_stricmp(pszKey, "Bin") == 0) {
- strPath = CSimpleStringA(env->dir->bin_path);
- } else if (_stricmp(pszKey, "Cfg") == 0 || _stricmp(pszKey, "Etc") == 0) {
- strPath = CSimpleStringA(env->dir->cfg_path);
- } else if (_stricmp(pszKey, "Rec") == 0) {
- strPath = CSimpleStringA(env->cfg->root_ini->ref_localvideo_path);
- } else if (_stricmp(pszKey, "Temp") == 0 || _stricmp(pszKey, "Tmp") == 0) {
- strPath = CSimpleStringA(env->cfg->root_ini->ref_tmp_path);
- } else if (_stricmp(pszKey, "SysLog") == 0) {
- strPath = CSimpleStringA(env->cfg->root_ini->ref_syslog_path);
- } else if (_stricmp(pszKey, "InterLog") == 0) {
- strPath = CSimpleStringA(env->cfg->root_ini->ref_intlog_path);
- } else if (_stricmp(pszKey, "Base") == 0 || _stricmp(pszKey, "BaseDir") == 0) {
- strPath = CSimpleStringA(env->dir->base_path);
- } else if (_stricmp(pszKey, "SysRoot") == 0) {
- strPath = CSimpleStringA(env->cfg->root_ini->ref_sysroot_path);
- } else if (_stricmp(pszKey, "Photo") == 0 || _stricmp(pszKey, "UploadPhoto") == 0) {
- strPath = CSimpleStringA(env->cfg->root_ini->ref_uploadphoto_path);
- } else if (_stricmp(pszKey, "Download") == 0 || _stricmp(pszKey, "Downloads") == 0) {
- strPath = CSimpleStringA(env->cfg->root_ini->ref_downloads_path);
- } else if (_stricmp(pszKey, "Upgraded") == 0){
- strPath = CSimpleStringA(env->cfg->root_ini->ref_upgraded_path);
- } else if (_stricmp(pszKey, "Ad") == 0) {
- strPath = CSimpleStringA(env->cfg->root_ini->ref_addata_path);
- } else if (_stricmp(pszKey, "UploadPhoto") == 0) {
- strPath = CSimpleStringA(env->cfg->root_ini->ref_uploadphoto_path);
- } else if (_stricmp(pszKey, "UploadVideo") == 0) {
- strPath = CSimpleStringA(env->cfg->root_ini->ref_uploadvideo_path);
- } else if (_stricmp(pszKey, "Dbg") == 0) {
- strPath = CSimpleStringA(env->dir->dbg_path);
- } else if (_stricmp(pszKey, "Slv") == 0) {
- strPath = CSimpleStringA(env->dir->slv_path);
- }
- else if (_stricmp(pszKey, "DepBase") == 0) {
- strPath = CSimpleStringA(env->dir->dep_base_path);
- }
- else if (_stricmp(pszKey, "DepBak") == 0) {
- strPath = CSimpleStringA(env->dir->dep_path);
- }
- else if (_stricmp(pszKey, "Dep") == 0) {
- if (env->dir->dep_ver_path == NULL) {
- sp_dir_refresh_dep_path(env->dir);
- }
- if (env->dir->dep_ver_path == NULL) {
- Error = Error_NotInit;
- }
- else {
- strPath = CSimpleStringA(env->dir->dep_ver_path);
- }
- }
- else if (_stricmp(pszKey, "Ad0") == 0) {
- strPath = CSimpleStringA(env->dir->ad0_path);
- } else if (_stricmp(pszKey, "Dmp") == 0 || _stricmp(pszKey, "Dump") == 0) {
- strPath = CSimpleStringA(env->dir->dmp_path);
- } else if (_stricmp(pszKey, "RunInfo") == 0){
- strPath = CSimpleStringA(env->dir->root_runinfo_path);
- } else if (_stricmp(pszKey, "RunCfg") == 0) {
- strPath = CSimpleStringA(env->dir->root_runinfo_path);
- strPath += SPLIT_SLASH_STR;
- strPath += "runcfg";
- } else if (_stricmp(pszKey, "HardwareCfg") == 0) {
- strPath = CSimpleStringA(env->dir->root_hardwarecfg_path);
- } else if (_stricmp(pszKey, "CenterSetting") == 0) {
- // return centersetting name by current site
- strPath = CSimpleStringA(env->dir->cfg_path);
- strPath += SPLIT_SLASH_STR;
- strPath += "CenterSetting.ini";
- } else if (_stricmp(pszKey, "rvc") == 0) {
- strPath = CSimpleStringA(env->dir->rvc_path);
- } else {
- char *path = sp_cfg_get_path(env->cfg, pszKey);
- if (path) {
- strPath = path;
- } else {
- Error = Error_Param;
- }
- }
- return Error;
- }
- ErrorCodeEnum SpEntity::GetSystemRunInfo(CSystemRunInfo &Info)
- {
- sp_env_t *env = sp_get_env();
- sp_cfg_t *cfg = env->cfg;
- Info.eDebugLevel = (DebugLevelEnum)cfg->shell_ini->shell_debug_level;
- Info.tmStart = cfg->run_info->startup_time;
- Info.dwBootOption = 0;
- if (cfg->args->debug_mode)
- Info.dwBootOption |= BootOption_Debug;
- if (cfg->args->test_mode) {
- if (cfg->args->test_mode & 1) {
- Info.dwBootOption |= BootOption_Test;
- }
- if (cfg->args->test_mode & 2) {
- Info.dwBootOption |= BootOption_Test;
- Info.dwBootOption |= BootOption_Benchmark;
- }
- if (cfg->args->test_mode & 4) {
- Info.dwBootOption |= BootOption_ST;
- }
- if (cfg->args->test_mode & 8) {
- Info.dwBootOption |= BootOption_UAT;
- }
- }
- #ifndef DEVOPS_ON_PRD
- //非生产情况下,才支持测试模式
- Info.autoTest = FALSE;
- if (cfg->args->auto_test)
- {
- Info.autoTest = TRUE;
- }
- #endif
- if (cfg->args->start_entities != NULL && strlen(cfg->args->start_entities) != 0) {
- Info.dwBootOption |= BootOption_Entity;
- }
- if (!!cfg->args->root) {
- Info.dwBootOption |= BootOption_RootPrivilege;
- }
- sp_mod_mgr_t *mod_mgr = env->mod_mgr;
- sp_mod_t *pos;
- array_header_t *arr = array_make(16, sizeof(char*));
- list_for_each_entry(pos, sp_mod_mgr_get_module_list_head(mod_mgr), sp_mod_t, entry) {
- if (pos->loaded) {
- sp_entity_t *ent;
- list_for_each_entry(ent, &pos->entity_list, sp_entity_t, entry) {
- int state = ent->state;
- if (state == EntityState_Idle || state == EntityState_Busy || state == EntityState_Pause) {
- ARRAY_PUSH(arr, char*) = ent->cfg->name;
- }
- }
- }
- }
- Info.strRunningEntityNames.Init(arr->nelts);
- for (int i = 0; i < arr->nelts; ++i) {
- Info.strRunningEntityNames[i] = CSimpleStringA(ARRAY_IDX(arr, i, char*));
- }
- array_free(arr);
- Info.eAppBootState = (AppBootStateEnum)env->cfg->shell_ini->shell_state;
- if (env == NULL || env->cfg == NULL || env->cfg->root_ini == NULL)
- {
- Info.bErrCfgWork = false;
- Info.bBasicCfgWork = false;
- return Error_Succeed;
- }
- if (env->cfg->root_ini->vtm_err_msg_config == NULL || strlen(env->cfg->root_ini->vtm_err_msg_config) == 0)
- Info.bErrCfgWork = false;
- else
- Info.bErrCfgWork = true;
- if (env->cfg->root_ini->root_config == NULL
- || env->cfg->root_ini->center_config == NULL
- || env->cfg->root_ini->shell_config == NULL
- || strlen(env->cfg->root_ini->root_config) == 0
- || strlen(env->cfg->root_ini->center_config) == 0
- || strlen(env->cfg->root_ini->shell_config) == 0)
- Info.bBasicCfgWork = false;
- else
- Info.bBasicCfgWork = true;
- return Error_Succeed;
- }
- ErrorCodeEnum SpEntity::GetEntityBusyRate(WORD &nBusyEntity,WORD &nAllEntity)
- {
- sp_env_t *env = sp_get_env();
- sp_mod_mgr_t *mod_mgr = env->mod_mgr;
- int nAll(0), nBusy(0);
- sp_mod_t *mod;
- list_for_each_entry(mod, sp_mod_mgr_get_module_list_head(mod_mgr), sp_mod_t, entry)
- {
- if (mod->loaded)
- {
- sp_entity_t *ent;
- list_for_each_entry(ent, &mod->entity_list, sp_entity_t, entry)
- {
- int state = ent->state;
- if (state == EntityState_Idle || state == EntityState_Busy || state == EntityState_Pause)
- nAll++;
-
- if (state == EntityState_Busy)
- nBusy++;
- }
- }
-
- nBusyEntity = nBusy;
- nAllEntity = nAll;
- }
- return Error_Succeed;
- }
- ErrorCodeEnum SpEntity::GetRebootInfo(CSmallDateTime BeforeThisTime, CBootInfo &Info)
- {
- CSimpleStringA strPath;
- auto rc = GetPath("RunInfo", strPath);
- if (rc != Error_Succeed)
- return rc;
- strPath += SPLIT_SLASH_STR "BootLog";
- sp_env_t *env = sp_get_env();
- auto pRec = sp_btr_get_rec_before(strPath, env->btr_ctx, BeforeThisTime);
- if (pRec == NULL)
- return Error_NotExist;
- Info.tmStart = pRec->tm_start;
- Info.tmReboot = pRec->tm_shutdown;
- Info.InstallVersion = CVersion(pRec->version.major, pRec->version.minor, pRec->version.revision, pRec->version.build);
- Info.eTriggerReason = (RebootTriggerEnum)pRec->shutdown_reason;
- Info.eWay = (RebootWayEnum)pRec->shutdown_way;
- Info.wSameReasonTime = pRec->shutdown_reason_cnt;
- Info.wSameWayTime = pRec->shutdown_way_cnt;
- delete pRec;
- return Error_Succeed;
- }
- ErrorCodeEnum SpEntity::GetAllRegistSpFile(CAutoArray<CSimpleStringA> &Names)
- {
- sp_env_t *env = sp_get_env();
- sp_cfg_t *cfg = env->cfg;
- array_header_t *arr_module = cfg->shell_ini->arr_module;
- Names.Init(arr_module->nelts);
- for (int i = 0; i < arr_module->nelts; ++i) {
- sp_cfg_shell_module_t* mod = ARRAY_IDX(arr_module, i, sp_cfg_shell_module_t*);
- Names[i] = mod->name;
- }
- return Error_Succeed;
- }
- ErrorCodeEnum SpEntity::GetSpFileInfo(const char *pszSpName,CSpInfo &Info)
- {
- if (!pszSpName)
- return Error_Null;
- sp_env_t *env = sp_get_env();
- sp_cfg_t *cfg = env->cfg;
- sp_cfg_shell_module_t *cfg_mod = sp_cfg_get_module_by_name(cfg, pszSpName);
- if (!cfg_mod)
- return Error_NotExist;
- Info.strAuthor = cfg_mod->author;
- Info.strCompany = cfg_mod->company;
- Info.SoftwareVersion = CVersion((WORD)cfg_mod->version.major,
- (WORD)cfg_mod->version.minor,
- (WORD)cfg_mod->version.revision,
- (WORD)cfg_mod->version.build);
- sp_mod_mgr_t *mod_mgr = env->mod_mgr;
- sp_mod_t *mod = sp_mod_mgr_find_module_by_name(mod_mgr, pszSpName);
- if (!mod)
- return Error_NotExist;
- sp_entity_t *ent;
- int cnt = 0;
- list_for_each_entry(ent, &mod->entity_list, sp_entity_t, entry) {
- cnt++;
- }
- Info.strEntitys.Init(cnt);
- int i = 0;
- list_for_each_entry(ent, &mod->entity_list, sp_entity_t, entry) {
- Info.strEntitys[i++] = ent->cfg->name;
- }
- return Error_Succeed;
- }
- ErrorCodeEnum SpEntity::GetAllRegistedEntity(CAutoArray<CSimpleStringA> &strEntityNames, CAutoArray<WORD> &wEntityDevelopIDs)
- {
- sp_env_t *env = sp_get_env();
- sp_cfg_t *cfg = env->cfg;
- array_header_t *arr_entity = cfg->shell_ini->arr_entity;
- strEntityNames.Init(arr_entity->nelts-1);
- wEntityDevelopIDs.Init(arr_entity->nelts-1);
- for (int i = 1; i < arr_entity->nelts; ++i) { // from index 1, because zero for special entity, ie. spshell entity
- sp_cfg_shell_entity_t *ent = ARRAY_IDX(arr_entity, i, sp_cfg_shell_entity_t*);
- strEntityNames[i-1] = ent->name;
- wEntityDevelopIDs[i-1] = ent->devel_id;
- }
- return Error_Succeed;
- }
- ErrorCodeEnum SpEntity::GetAllEntityStartInfo(CAutoArray<CSimpleStringA>& strEntityNames, CAutoArray<int>& strEntityIdx, CAutoArray<CEntityStartInfo>& Infos)
- {
- sp_env_t* env = sp_get_env();
- sp_cfg_t* cfg = env->cfg;
- array_header_t* arr_entity = cfg->shell_ini->arr_entity;
- strEntityNames.Init(arr_entity->nelts);
- strEntityIdx.Init(arr_entity->nelts);
- Infos.Init(arr_entity->nelts);
- for (int i = 0; i < arr_entity->nelts; ++i) {
- sp_cfg_shell_entity_t* ent = ARRAY_IDX(arr_entity, i, sp_cfg_shell_entity_t*);
- strEntityNames[i] = ent->name;
- strEntityIdx[i] = ent->idx;
- Infos[i].startTimes = ent->m_startTimes;
- #if defined(_MSC_VER)
- FileTimeToSystemTime(&ent->m_EntityStartTime.filetimePart, &(Infos[i].startTime));
- FileTimeToSystemTime(&ent->m_EntityInitEndTime.filetimePart, &(Infos[i].InitEndTime));
- FileTimeToSystemTime(&ent->m_EntityStartEndTime.filetimePart, &(Infos[i].startEndTime));
- #else
- memcpy(&Infos[i].startTime, &ent->m_EntityStartTime, sizeof(SYSTEMTIME));
- memcpy(&Infos[i].InitEndTime, &ent->m_EntityInitEndTime, sizeof(SYSTEMTIME));
- memcpy(&Infos[i].startEndTime, &ent->m_EntityStartEndTime, sizeof(SYSTEMTIME));
- #endif //_MSC_VER
- }
- return Error_Succeed;
- }
- ErrorCodeEnum SpEntity::GetEntityLogPath(const char* pszEntityName, CEntityLogInfo& Info)
- {
- if (pszEntityName != NULL) {
- sp_env_t* env = sp_get_env();
- auto pEntity = sp_cfg_get_entity_by_name(env->cfg, pszEntityName);
- if (pEntity != NULL) {
- char tmp[MAX_PATH] = { 0 };
- auto mod_name = pEntity->mod->name;
- sp_dir_get_path(env->dir, SP_DIR_ENTITY_DBG_LOG, mod_name, tmp, sizeof(tmp));
- Info.strLogPath = tmp;
- return ErrorCodeEnum::Error_Succeed;
- }
- }
- return ErrorCodeEnum::Error_Unexpect;
- }
- ErrorCodeEnum SpEntity::GetAllStartedEntity(CAutoArray<CSimpleStringA> &strEntityNames, CAutoArray<DWORD> &dwEntityInstanceIDs)
- {
- sp_env_t *env = sp_get_env();
- sp_mod_mgr_t *mod_mgr = env->mod_mgr;
- sp_mod_t *pos;
- int i;
- array_header_t *arr = array_make(16, sizeof(sp_entity_t*));
- list_for_each_entry(pos, sp_mod_mgr_get_module_list_head(mod_mgr), sp_mod_t, entry) {
- if (pos->loaded) {
- sp_entity_t *ent;
- list_for_each_entry(ent, &pos->entity_list, sp_entity_t, entry) {
- int state = ent->state;
- if (state == EntityState_Idle || state == EntityState_Busy || state == EntityState_Pause) {
- ARRAY_PUSH(arr, sp_entity_t*) = ent;
- }
- }
- }
- }
- strEntityNames.Init(arr->nelts);
- dwEntityInstanceIDs.Init(arr->nelts);
- for (i = 0; i < arr->nelts; ++i) {
- sp_entity_t *ent = ARRAY_IDX(arr, i, sp_entity_t*);
- strEntityNames[i] = ent->cfg->name;
- dwEntityInstanceIDs[i] = ent->instance_id;
- }
- // {bug} forget array_free(arr)
- array_free(arr);
- return Error_Succeed;
- }
- ErrorCodeEnum SpEntity::GetSelfEntityRunInfo(CEntityRunInfo &Info)
- {
- return GetEntityRunInfo(m_ent->cfg->name, Info);
- }
- ErrorCodeEnum SpEntity::GetEntityStaticInfo(const char *pszEntityName,CEntityStaticInfo &Info)
- {
- if (!pszEntityName)
- return Error_Null;
- sp_env_t *env = sp_get_env();
- sp_entity_t *ent = sp_mod_mgr_find_entity_by_name(env->mod_mgr, pszEntityName);
- return ::GetEntityStaticInfo(Info, ent);
- }
- ErrorCodeEnum SpEntity::GetToken(CSimpleString &channelId, CSimpleString &token)
- {
- sp_env_t* env = sp_get_env();
- channelId = env->cfg->shell_ini->channelId;
- token = env->cfg->shell_ini->token;
- if (channelId.GetLength() == 0 || token.GetLength() == 0)
- return ErrorCodeEnum::Error_NotConfig;
- else
- return ErrorCodeEnum::Error_Succeed;
- }
- ErrorCodeEnum SpEntity::SetNewPathToFirewall(CSimpleString &pszPath, int maxWaitMs)
- {
- if (pszPath.GetLength() == 0) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("SetNewPathToFirewall param error");
- return Error_Param;
- }
- #ifdef RVC_OS_WIN
- auto addFirewall_worker = [this](std::string path)
- {
- return sp_AddFirewallRuleByPath(path.c_str()) ? Error_Succeed : Error_Bug;
- };
- std::future<ErrorCodeEnum> result = std::async(std::launch::async, addFirewall_worker, pszPath.GetData());
- auto status = result.wait_for(std::chrono::milliseconds(maxWaitMs));
- if (status == std::future_status::ready)
- {
- auto ret = result.get();
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("SetNewPathToFirewall ret:%d", ret);
- return ret;
- }
- else
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("SetNewPathToFirewall run over %d milliseconds", maxWaitMs);
- return Error_TimeOut;
- }
- #else
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("SetNewPathToFirewall not support uos");
- return Error_NotSupport;
- #endif // RVC_OS_WIN
-
- }
- ErrorCodeEnum SpEntity::GetEntityStaticInfo(WORD wEntitySerialNO, CEntityStaticInfo &Info)
- {
- sp_env_t *env = sp_get_env();
- sp_entity_t *ent = sp_mod_mgr_find_entity_by_devel_id(env->mod_mgr, wEntitySerialNO);
- return ::GetEntityStaticInfo(Info, ent);
- }
- ErrorCodeEnum SpEntity::GetEntityRunInfo(const char *pszEntityName, CEntityRunInfo &Info)
- {
- sp_env_t *env = sp_get_env();
- if (!pszEntityName)
- return Error_Null;
- sp_mod_mgr_t *mod_mgr = env->mod_mgr;
- sp_entity_t *ent = sp_mod_mgr_find_entity_by_name(mod_mgr, pszEntityName);
- if (!ent)
- return Error_NotExist;
- Info.dwEntityInstanceID = (DWORD)ent->instance_id;
- Info.tmFirstStart = ent->first_start_time;
- Info.tmLastStart = ent->last_start_time;
- Info.bService = !!ent->service_flag;
- Info.eState = (EntityStateEnum)ent->state;
- Info.tmBeginCurrentState = ent->state_start_time;
- Info.dwProcessID = (DWORD)ent->mod->process.pid;
- Info.eDebugLevel = (DebugLevelEnum)ent->cfg->debug_level;
- Info.dwUserState = (DWORD)ent->user_state;
- return Error_Succeed;
- }
- ErrorCodeEnum SpEntity::GetEntityName(WORD wEntityDevelopID, CSimpleStringA &strName)
- {
- sp_env_t *env = sp_get_env();
- sp_entity_t *ent = sp_mod_mgr_find_entity_by_devel_id(env->mod_mgr, wEntityDevelopID);
- if (ent) {
- strName = ent->cfg->name;
- } else {
- return Error_NotExist;
- }
- return Error_Succeed;
- }
- ErrorCodeEnum SpEntity::GetEntityName(DWORD dwEntityInstanceID, CSimpleStringA &strName)
- {
- TOOLKIT_ASSERT(dwEntityInstanceID != 0);
- sp_env_t *env = sp_get_env();
- sp_entity_t *ent = sp_mod_mgr_find_entity_by_inst_id(env->mod_mgr, dwEntityInstanceID);
- if (ent) {
- strName = ent->cfg->name;
- } else {
- return Error_NotExist;
- }
- return Error_Succeed;
- }
- ErrorCodeEnum SpEntity::GetModuleName(DWORD nModuleID, CSimpleStringA &strName)
- {
- if (nModuleID != SP_INVALID_MOD_ID) {
- sp_env_t *env = sp_get_env();
- sp_mod_t *mod = sp_mod_mgr_find_module_by_idx(env->mod_mgr, nModuleID);
- if (mod) {
- strName = mod->cfg->name;
- return Error_Succeed;
- } else {
- return Error_NotExist;
- }
- }
- return Error_Param;
- }
- ErrorCodeEnum SpEntity::GetEntitySessionInfo(const char *pszEntityName, CAutoArray<CEntitySessionInfo> &Infos)
- {
- iobuffer_t *req_pkt = iobuffer_create(-1, -1);
- iobuffer_t *ans_pkt = NULL;
- auto rc = AskEntityByRPC(pszEntityName, ENTITY_CMD_REQ_QUERY_ENTITY_SESSIONS, &req_pkt, &ans_pkt);
- if (rc == Error_Succeed)
- {
- int nCount(0);
- iobuffer_read(ans_pkt, IOBUF_T_I4, &nCount, NULL);
- auto pCfg = sp_get_env()->cfg;
- Infos.Init(nCount);
- for (int i = 0; i < nCount; ++i)
- {
- int nFromSvcID, nToSvcID, nBeginTime, nState, nStateBeginTime;
- iobuffer_format_read(ans_pkt, "44444", &nFromSvcID, &nToSvcID, &nBeginTime, &nState, &nStateBeginTime);
-
- Infos[i].strCallerEntity = sp_cfg_get_entity_by_idx(pCfg, nFromSvcID)->name;
- Infos[i].strServiceEntity = sp_cfg_get_entity_by_idx(pCfg, nToSvcID)->name;
- Infos[i].tmStart = CSmallDateTime(nBeginTime);
- Infos[i].eState = (SessionStateEnum)nState;
- Infos[i].tmBeginState = CSmallDateTime(nStateBeginTime);
- }
- }
- if (req_pkt)
- iobuffer_dec_ref(req_pkt);
- if (ans_pkt)
- iobuffer_dec_ref(ans_pkt);
- return rc;
- }
- bool SpEntity::HasPrivilege()
- {
- return !!m_cfg_ent->privilege;
- }
- CSmartPointer<IEntityFunctionPrivilege> SpEntity::GetPrivilegeFunction()
- {
- return NULL;
- }
- ErrorCodeEnum SpEntity::PostQuit()
- {
- ErrorCodeEnum Error;
- iobuffer_t *pkt = iobuffer_create(-1, -1);
- int v = m_ent->cfg->idx;
- iobuffer_write(pkt, IOBUF_T_I4, &v, 0);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Pre PostQuit...");
- Error = PostInfoShell(SHELL_CMD_INFO_ENTITY_QUIT, &pkt);
- if (pkt)
- iobuffer_dec_ref(pkt);
- return Error;
- }
- ErrorCodeEnum SpEntity::PostReload()
- {
- ErrorCodeEnum Error;
- iobuffer_t *pkt = iobuffer_create(-1, -1);
- int v = m_ent->cfg->idx;
- iobuffer_write(pkt, IOBUF_T_I4, &v, 0);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Pre PostReload...");
- Error = PostInfoShell(SHELL_CMD_INFO_ENTITY_RELOAD, &pkt);
- if (pkt)
- iobuffer_dec_ref(pkt);
- return Error;
- }
- ErrorCodeEnum SpEntity::PostEntityTaskFIFO(ITaskSp *pTask)
- {
- threadpool_t *threadpool = sp_svc_get_threadpool(m_svc);
- int rc;
- rc = threadpool_post_workitem_fifo2(threadpool, NULL, &task_callback, pTask, (param_size_t)((intptr_t)this), 0);
- return rc == 0 ? Error_Succeed : Error_Unexpect;
- }
- ErrorCodeEnum SpEntity::PostEntityTaskLIFO(ITaskSp *pTask)
- {
- threadpool_t *threadpool = sp_svc_get_threadpool(m_svc);
- int rc;
- rc = threadpool_post_workitem_lifo2(threadpool, NULL, &task_callback, pTask, (param_size_t)((intptr_t)this), 0);
- return rc == 0 ? Error_Succeed : Error_Unexpect;
- }
- ErrorCodeEnum SpEntity::PostThreadPoolTask(ITaskSp *pTask)
- {
- int rc = threadpool_post_workitem_fifo2(m_tpool, NULL, &task_callback, pTask, (param_size_t)((intptr_t)this), 0);
- return rc == 0 ? Error_Succeed : Error_Unexpect;
- }
- ErrorCodeEnum SpEntity::StartTcpBridgeServer(unsigned short port)
- {
- if (port >4506 || port < 4502)
- return Error_Duplication;
- #ifdef _DEBUG
- const char *ip = "0.0.0.0";
- #else
- const char *ip = "127.0.0.1";
- #endif
- if (m_tbs)
- return Error_Duplication;
- int rc = sp_tbs_create(m_ses_mgr, ip, port, &m_tbs);
- if (rc == 0) {
- rc = sp_tbs_start(m_tbs);
- if (rc != 0) {
- sp_tbs_destroy(m_tbs);
- m_tbs = NULL;
- }
- }
- return SpTranslateError(rc);
- }
- ErrorCodeEnum SpEntity::StopTcpBridgeServer()
- {
- if (m_tbs) {
- sp_tbs_stop(m_tbs);
- sp_tbs_destroy(m_tbs);
- m_tbs = NULL;
- return Error_Succeed;
- } else {
- return Error_NotInit;
- }
- }
- void SpEntity::SetPostLinkFun(postLink cur)
- {
- }
- ErrorCodeEnum SpEntity::RequestCloseDelay(WORD nSecond)
- {
- return Error_NotImpl;
- }
- void SpEntity::SendLog(const LogTypeEnum eLogType,const SeverityLevelEnum eLevel,
- DWORD dwUserEventCode,CAutoArray<DWORD> Param,const char *pszMessage)
- {
- LogMessage(eLogType, eLevel, 0, dwUserEventCode, Param, pszMessage);
- }
- ErrorCodeEnum SpEntity::VerifySignature(const char *pszSignedFile, CSimpleStringA &strErrInfo)
- {
- #ifdef RVC_OS_WIN
- CCodeSignVerify verify;
- CSignInfo signInfo;
- if (!verify.VerifySignature(pszSignedFile, signInfo))
- {
- strErrInfo = verify.GetErrorMsg();
- return Error_FailVerify;
- }
- // xkm@20140905: 检查签名证书Hash是否同SpBase签名证书Hash一致
- sp_env_t *env = sp_get_env();
- assert(env != NULL);
- auto pShellCfg = env->cfg->shell_ini;
- if (pShellCfg->spbase_sign_cert_hash != NULL && stricmp(pShellCfg->spbase_sign_cert_hash, signInfo.strSignCertHash) != 0)
- {
- strErrInfo = "签名证书非授权证书";
- return Error_FailVerify;
- }
- strErrInfo = signInfo.strSignCertHash;
- return Error_Succeed;
- #else
- strErrInfo = "TODO: not implement VerifySignature current times.";
- //return Error_NotImpl;
- #endif //RVC_OS_WIN
- return Error_Succeed;
- }
- ErrorCodeEnum SpEntity::ShowFatalError(const char *pszMsg, SeverityLevelEnum eLevel)
- {
- //TODO: [Gifur@2025730]
- #if defined(RVC_OS_WIN)
- LogError(Severity_High, Error_Unrecover, 0, pszMsg);
- #endif //RVC_OS_WIN
- ErrorCodeEnum Error;
- iobuffer_t *pkt = iobuffer_create(-1, -1);
- int v = (int)eLevel;
- iobuffer_write(pkt, IOBUF_T_I4, &v, 0);
- #if defined(RVC_OS_LINUX)
- CSimpleStringA strMsg = m_pEntityBase->GetEntityName();
- strMsg += " V";
- strMsg += m_pEntityBase->GetEntityVersion();
- strMsg += ":][:"; /** arrange with QtGUIConsole to split entity name and msg content [Gifur@202128]*/
- strMsg += pszMsg;
- iobuffer_write(pkt, IOBUF_T_STR, (const char*)strMsg, -1);
- #else
- iobuffer_write(pkt, IOBUF_T_STR, pszMsg, -1);
- #endif //RVC_OS_LINUX
- Error = PostInfoShell(SHELL_CMD_INFO_FATAL_ERROR_DISPLAY, &pkt);
- if (pkt)
- iobuffer_dec_ref(pkt);
- return Error;
- }
- ErrorCodeEnum SpEntity::ShowStartupInfo(const char *pszMsg)
- {
- LogEvent(Severity_High, 0, pszMsg);
- ErrorCodeEnum Error;
- iobuffer_t *pkt = iobuffer_create(-1, -1);
- iobuffer_write(pkt, IOBUF_T_STR, pszMsg, -1);
- Error = PostInfoShell(SHELL_CMD_INFO_STARTUP_INFO_DISPLAY, &pkt);
- if (pkt)
- iobuffer_dec_ref(pkt);
- return Error;
- }
- void SpEntity::ResetEntityLastError()
- {
- if (m_ent) {
- m_ent->last_err.sys_code = m_ent->last_err.usr_code = 0;
- memset(m_ent->last_err.msg, '\0', sizeof(m_ent->last_err.msg));
- }
- }
- ErrorCodeEnum SpEntity::GetRunningVersion(CSimpleString& ver)
- {
- char dstVer[SP_MAX_VER_LEN] = "";
- auto ret = sp_cfg_getVer(dstVer);
- if (ret == Error_Succeed)
- ver = dstVer;
- return (ErrorCodeEnum)ret;
- }
- ErrorCodeEnum SpEntity::GetRunningDepVersion(CSimpleString& ver)
- {
- char dstVer[SP_MAX_VER_LEN] = "";
- auto ret = sp_cfg_getDepVer(dstVer);
- if (ret == Error_Succeed)
- ver = dstVer;
- return (ErrorCodeEnum)ret;
- }
- struct ErrMsgStruct {
- std::string VTMCode;
- std::string errMsg;
- // 带参数的构造函数,参数有默认值
- ErrMsgStruct(const std::string& tmp_VTMCode = "", const std::string& tmp_errMsg = "") : VTMCode(tmp_VTMCode), errMsg(tmp_errMsg) {}
- };
- ErrorCodeEnum SpEntity::GetVTMErrMsg(DWORD dwUserCode, CSimpleStringA& strDescription, CSimpleStringA& strVTMCode)
- {
- sp_env_t* env = sp_get_env();
- if (env->cfg->root_ini->vtm_err_msg_config == NULL || strlen(env->cfg->root_ini->vtm_err_msg_config) == 0)
- {
- strVTMCode = "RTA42F0";
- strDescription = "微服务异常";
- return ErrorCodeEnum::Error_NotConfig;
- }
- std::string userCodeStr = CSimpleString::Format("0x%X", dwUserCode).GetData();
- std::transform(userCodeStr.begin(), userCodeStr.end(), userCodeStr.begin(), [](unsigned char c) { return std::tolower(c); });
- static std::map<std::string, ErrMsgStruct> m_UserCodeToMsgTip;
- static bool isInit = false;
- if (!isInit)//Some entities may have no UserCode
- {
- CAutoArray<CSimpleStringA> strErrorCodeArr;
- CAutoArray<CSimpleStringA> strDescriptionArr;
- CAutoArray<CSimpleStringA> strRemarkArr;
- ConvertStrToVTMErrMsg(env->cfg->root_ini->vtm_err_msg_config, strErrorCodeArr, strDescriptionArr, strRemarkArr);
- auto intToHex = [](int num) -> std::string {
- const char hexChars[] = "0123456789ABCDEF";
- std::string hexStr;
- // 将整数的每个字节转换为对应的16进制字符
- for (int i = sizeof(num) - 1; i >= 0; --i) {
- unsigned char byte = (num >> (8 * i)) & 0xFF;
- if (byte == 0 && hexStr.empty()) {
- continue; // 跳过前导零
- }
- hexStr += hexChars[byte >> 4];
- hexStr += hexChars[byte & 0x0F];
- }
- return hexStr;
- };
- auto hexToInt = [](const std::string& hexStr)-> int {
- std::stringstream ss;
- ss << std::hex << hexStr;
- int num;
- ss >> num;
- return num;
- };
- auto intTo36 = [](int num) -> std::string {
- std::string base36Chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
- std::string base36Str;
- while (num > 0) {
- base36Str = base36Chars[num % 36] + base36Str;
- num /= 36;
- }
- return base36Str;
- };
- int id = GetDevID();
- auto idHexStr = intToHex(id);
- if (idHexStr.length() != 4 || idHexStr[0] != '0')
- {
- strVTMCode = "RTA42F2";
- strDescription = "实体Id异常";
- return ErrorCodeEnum::Error_Unregisted;
- }
- std::string dstRTA = "RTA";
- dstRTA.push_back(idHexStr[1]); //first
- std::string lastTwoDigits = idHexStr.substr(idHexStr.length() - 2); // last two digits
- int num = hexToInt(lastTwoDigits);
- if (num < 0 || num >= 36) {
- strVTMCode = "RTA42F2";
- strDescription = "无法转换实体Id";
- return ErrorCodeEnum::Error_DataCheck;
- }
- std::string base36Str = intTo36(num);
- dstRTA.append(base36Str);
- for (int i = 0; i < strErrorCodeArr.GetCount(); i++)
- {
- //if (strErrorCodeArr[i].IsStartWith(dstRTA.c_str(), true))
- //{
- std::string curRemark = strRemarkArr[i].GetData();
- std::transform(curRemark.begin(), curRemark.end(), curRemark.begin(), [](unsigned char c) { return std::tolower(c); });
- m_UserCodeToMsgTip.insert(std::make_pair(curRemark, ErrMsgStruct(strErrorCodeArr[i].GetData(), strDescriptionArr[i].GetData())));
- //}
- }
- isInit = true;
- }
- if (m_UserCodeToMsgTip.find(userCodeStr) != m_UserCodeToMsgTip.end())
- {
- strVTMCode = m_UserCodeToMsgTip[userCodeStr].VTMCode.c_str();
- strDescription = m_UserCodeToMsgTip[userCodeStr].errMsg.c_str();
- return ErrorCodeEnum::Error_Succeed;
- }
- else
- {
- strVTMCode = "RTA42F1";
- strDescription = "错误映射异常";
- return ErrorCodeEnum::Error_NotExist;
- }
- }
- CSimpleStringA SpEntity::UserCodeToRTACode(DWORD dwUserCode)
- {
- CSimpleStringA tmpDesc, tmpVtmCode("");
- //transmit the return of GetVTMErrMsg directly
- GetVTMErrMsg(dwUserCode, tmpDesc, tmpVtmCode);
- return CSimpleStringA(tmpVtmCode);
- }
- ErrorCodeEnum SpEntity::SetSelfPriority(EntityPriorityEnum nPriority)
- {
- ErrorCodeEnum result(Error_Succeed);
- CEntityRunInfo info;
- result = GetEntityRunInfo(m_ent->cfg->name, info);
- if (result == Error_Succeed) {
- #if defined(_MSC_VER)
- int priviliegeValue = TOOLKIT_PRIORITY_NORMAL;
- switch (nPriority) {
- case Priority_Low:
- priviliegeValue = TOOLKIT_PRIORITY_LOW;
- break;
- case Priority_Below_Normal:
- priviliegeValue = TOOLKIT_PRIORITY_BELOW_NORMAL;
- break;
- case Priority_Normal:
- priviliegeValue = TOOLKIT_PRIORITY_NORMAL;
- break;
- case Priority_Above_Normal:
- priviliegeValue = TOOLKIT_PRIORITY_ABOVE_NORMAL;
- break;
- case Priority_High:
- priviliegeValue = TOOLKIT_PRIORITY_HIGH;
- break;
- case Priority_Highest:
- priviliegeValue = TOOLKIT_PRIORITY_HIGHEST;
- break;
- default:
- priviliegeValue = TOOLKIT_PRIORITY_NORMAL;
- break;
- }
- int res = toolkit_os_setpriority(info.dwProcessID, priviliegeValue);
- #else
- auto func = [nPriority] {
- switch (nPriority) {
- case Priority_Low:
- return TOOLKIT_PRIORITY_LOW;
- case Priority_Below_Normal:
- return TOOLKIT_PRIORITY_BELOW_NORMAL;
- case Priority_Normal:
- return TOOLKIT_PRIORITY_NORMAL;
- case Priority_Above_Normal:
- return TOOLKIT_PRIORITY_ABOVE_NORMAL;
- case Priority_High:
- return TOOLKIT_PRIORITY_HIGH;
- case Priority_Highest:
- return TOOLKIT_PRIORITY_HIGHEST;
- default:
- return TOOLKIT_PRIORITY_NORMAL;
- }
- };
- int res = toolkit_os_setpriority(info.dwProcessID, func());
- #endif //_MSC_VER
- if (res != 0) {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("toolkit_os_setpriority failed %s ", toolkit_strerror(res));
- result = Error_Unexpect;
- }
- }
- return result;
- }
- ErrorCodeEnum SpEntity::GetSelfPriority(EntityPriorityEnum& nPriority)
- {
- ErrorCodeEnum result(Error_Succeed);
- CEntityRunInfo info;
- result = GetEntityRunInfo(m_ent->cfg->name, info);
- if (result == Error_Succeed) {
- int priority;
- int res = toolkit_os_getpriority(info.dwProcessID, &priority);
- if (res != 0) {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("toolkit_os_getpriority failed %s ", toolkit_strerror(res));
- result = Error_Unexpect;
- } else {
- #if defined(_MSC_VER)
- switch (priority) {
- case TOOLKIT_PRIORITY_LOW:
- nPriority = Priority_Low;
- break;
- case TOOLKIT_PRIORITY_BELOW_NORMAL:
- nPriority = Priority_Below_Normal;
- break;
- case TOOLKIT_PRIORITY_NORMAL:
- nPriority = Priority_Normal;
- break;
- case TOOLKIT_PRIORITY_ABOVE_NORMAL:
- nPriority = Priority_Above_Normal;
- break;
- case TOOLKIT_PRIORITY_HIGH:
- nPriority = Priority_High;
- break;
- case TOOLKIT_PRIORITY_HIGHEST:
- nPriority = Priority_Highest;
- break;
- default:
- nPriority = Priority_Unknown;
- break;
- }
- #else
- auto func = [](int value) {
- switch (value) {
- case TOOLKIT_PRIORITY_LOW:
- return Priority_Low;
- case TOOLKIT_PRIORITY_BELOW_NORMAL:
- return Priority_Below_Normal;
- case TOOLKIT_PRIORITY_NORMAL:
- return Priority_Normal;
- case TOOLKIT_PRIORITY_ABOVE_NORMAL:
- return Priority_Above_Normal;
- case TOOLKIT_PRIORITY_HIGH:
- return Priority_High;
- case TOOLKIT_PRIORITY_HIGHEST:
- return Priority_Highest;
- default:
- return Priority_Unknown;
- }
- };
- nPriority = func(priority);
- #endif //_MSC_VER
- }
- }
- return result;
- }
- void SpEntity::SetEntityLastError(ErrorCodeEnum systemCode, DWORD dwUserCode, const char* lpcszMessage)
- {
- if (m_ent) {
- m_ent->last_err.sys_code = (uint32_t)systemCode;
- m_ent->last_err.usr_code = dwUserCode;
- if(lpcszMessage != NULL && strlen(lpcszMessage) < SP_ENTITY_ERRMSG_MAX_LEN)
- strcpy_s(m_ent->last_err.msg, SP_ENTITY_ERRMSG_MAX_LEN, lpcszMessage);
- else
- memset(m_ent->last_err.msg, '\0', sizeof(m_ent->last_err.msg));
- }
- }
- ErrorCodeEnum SpEntity::GetEntityLastError(const char* pszEntityName, CEntityLastErrorInfo& errInfo)
- {
- if (pszEntityName == NULL) {
- return Error_Param;
- }
- if (strlen(pszEntityName) == 0) {
- errInfo.eSysCode = (ErrorCodeEnum)m_ent->last_err.sys_code;
- errInfo.dwUserCode = (DWORD)m_ent->last_err.sys_code;
- errInfo.strErrMsg = (const char*)m_ent->last_err.msg;
- } else {
- sp_env_t* env = sp_get_env();
- sp_mod_mgr_t* mod_mgr = env->mod_mgr;
- sp_entity_t* ent = sp_mod_mgr_find_entity_by_name(mod_mgr, pszEntityName);
- if (!ent) {
- return Error_NotExist;
- }
- const EntityStateEnum entityState = (EntityStateEnum)ent->state;
- errInfo.eSysCode = (ErrorCodeEnum)ent->last_err.sys_code;
- errInfo.dwUserCode = (DWORD)ent->last_err.usr_code;
- if (entityState == EntityState_Idle || entityState == EntityState_Busy || entityState == EntityState_Pause) {
- errInfo.strErrMsg = (const char*)ent->last_err.msg;
- } else {
- errInfo.strErrMsg = CSimpleStringA::Format("%s %s", SpStrEntityState(entityState), (const char*)ent->last_err.msg);
- }
- }
- return Error_Succeed;
- }
- ErrorCodeEnum SpEntity::InitLogCurrentThread()
- {
- #ifdef RVC_OS_WIN
- SetthreadGroup(GetCurrentThreadId(), get_cfg_ent()->name);
- getEntityResource()->m_Entity = this;
- #else
- GetSpModule()->SetThreadEntity(this);
- #endif //_WIN32
- return Error_Succeed;
- }
- ErrorCodeEnum SpEntity::ConnectRemoteEntity(CClientSessionBase *pClientSession,
- const char *pszRemoteEntity,
- const char *pszParam,
- CSmartPointer<IAsynWaitSp> &pAsynWaitSp)
- {
- ErrorCodeEnum Error;
- if (!pClientSession || !pszRemoteEntity)
- return Error_Param;
- if (pClientSession->m_pSessionFunction)
- return Error_Param;
- SpClientSessionFunction *pFunction = new SpClientSessionFunction(this, pClientSession, pszRemoteEntity);
- Error = pFunction->Begin(pszParam);
- if (Error == Error_Succeed) {
- pClientSession->m_pSessionFunction = pFunction;
- pAsynWaitSp.Attach(pFunction, pFunction->GetRefCountPtr());
- } else {
- pFunction->DecrementRef();
- }
- if (Error_Succeed != Error) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("connect to %s failed: %s.", pszRemoteEntity, SpStrError(Error));
- } else {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("connect to %s succ.", pszRemoteEntity);
- }
- return Error;
- }
- ErrorCodeEnum SpEntity::RedirectSession(CClientSessionBase *pClientSession)
- {
- return Error_NotImpl;
- }
- ErrorCodeEnum SpEntity::RedirectSession(const char *pszSuggestEntity)
- {
- if (pszSuggestEntity) {
- sp_env_t *env = sp_get_env();
- sp_entity_t *ent = sp_mod_mgr_find_entity_by_name(env->mod_mgr, pszSuggestEntity);
- if (ent) {
- m_redirect_entity_cache = ent;
- return Error_Succeed;
- } else {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("RedirectSession failed, cannot find entity %s", pszSuggestEntity);
- return Error_Param;
- }
- }
- return Error_Param;
- }
- ErrorCodeEnum SpEntity::RedirectSubscribBroadcast(CUUID SubID, const char *pszSugguestEntity)
- {
- if (pszSugguestEntity) {
- sp_entity_t *ent = sp_mod_mgr_find_entity_by_name(sp_get_env()->mod_mgr, pszSugguestEntity);
- if (ent) {
- sp_uid_t uid = SubID.m_nUUID64;
- sp_mod_entity_stub_finish_redirect_subscribe(m_stub, &uid, ent->cfg->idx);
- } else {
- return Error_NotExist;
- }
- } else {
- return Error_Param;
- }
- return Error_Succeed;
- }
- ErrorCodeEnum SpEntity::AskShell(int call_type, iobuffer_t **req_pkt, iobuffer_t **ans_pkt)
- {
- ErrorCodeEnum Error;
- if (!req_pkt || !*req_pkt || !ans_pkt)
- return Error_Param;
- if (*ans_pkt)
- return Error_Param; // must be null so can return pkt
- SpAsyncWaitRPC *pAsyncWait = new SpAsyncWaitRPC(this, req_pkt, call_type);
- Error = pAsyncWait->Begin();
- if (Error == Error_Succeed)
- {
- Error = pAsyncWait->WaitAnswer(INFINITE);
- if (Error == Error_Succeed)
- {
- CAutoBuffer AnsBuf;
- bool bEnd;
- Error = pAsyncWait->AsyncGetAnswer(AnsBuf, bEnd);
- if (Error == Error_Succeed)
- {
- iobuffer_t *pkt = iobuffer_create(-1, AnsBuf.GetCount());
- iobuffer_write(pkt, IOBUF_T_BUF, &AnsBuf[0], AnsBuf.GetCount());
- *ans_pkt = pkt;
- }
- }
- }
- pAsyncWait->DecrementRef(); // xkm@20150115
- return Error;
- }
- ErrorCodeEnum SpEntity::AskEntityByRPC(const char *pszEntityName, int call_type, iobuffer_t **req_pkt, iobuffer_t **ans_pkt)
- {
- ErrorCodeEnum Error;
- if (!req_pkt || !*req_pkt || !ans_pkt)
- return Error_Param;
- if (*ans_pkt)
- return Error_Param; // must be null so can return pkt
- SpAsyncWaitRPC *pAsyncWait = new SpAsyncWaitRPC(this, req_pkt, call_type);
- Error = pAsyncWait->Begin(pszEntityName);
- if (Error == Error_Succeed)
- {
- Error = pAsyncWait->WaitAnswer(INFINITE);
- if (Error == Error_Succeed)
- {
- CAutoBuffer AnsBuf;
- bool bEnd;
- Error = pAsyncWait->AsyncGetAnswer(AnsBuf, bEnd);
- if (Error == Error_Succeed) {
- iobuffer_t *pkt = iobuffer_create(-1, AnsBuf.GetCount());
- iobuffer_write(pkt, IOBUF_T_BUF, &AnsBuf[0], AnsBuf.GetCount());
- *ans_pkt = pkt;
- }
- }
- }
- pAsyncWait->DecrementRef(); // xkm@20150115
- return Error;
- }
- 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)
- {
- SpEntity *pThis = static_cast<SpEntity*>(user_data);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("on_rpc_req(), calltype: %d", call_type);
- if (call_type == ENTITY_CMD_REQ_QUERY_ENTITY_SESSIONS)
- {
- pThis->OnQueryEntitySessions(epid, svc_id, rpc_id);
- }
- }
- void SpEntity::OnQueryEntitySessions(int epid, int svc_id, int rpc_id)
- {
- int rc;
- int nCount(0);
- int nResult(0);
- sp_ses_info_t* ret = sp_ses_mgr_get_ses_info(m_ses_mgr, &nCount);
-
- iobuffer_t *ans_pkt = iobuffer_create(-1, -1);
- iobuffer_write(ans_pkt, IOBUF_T_I4, &nResult, 0);
- iobuffer_write(ans_pkt, IOBUF_T_I4, &nCount, 0);
- for(int i=0; i<nCount; i++)
- {
- iobuffer_write(ans_pkt, IOBUF_T_I4, &ret[i].from_svc_id, 0);
- iobuffer_write(ans_pkt, IOBUF_T_I4, &ret[i].to_svc_id, 0);
- iobuffer_write(ans_pkt, IOBUF_T_I4, &ret[i].begin_time, 0);
- iobuffer_write(ans_pkt, IOBUF_T_I4, &ret[i].state, 0);
- iobuffer_write(ans_pkt, IOBUF_T_I4, &ret[i].state_begin_time, 0);
- }
- if (ret != NULL)
- free(ret);
-
- rc = sp_rpc_client_mgr_send_answer(m_rpc_mgr, epid, svc_id, rpc_id, &ans_pkt);
- if (rc != 0) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("send rpc answer failed!");
- }
- if (ans_pkt) {
- iobuffer_dec_ref(ans_pkt);
- }
- }
- ErrorCodeEnum SpEntity::PostInfoShell(int call_type, iobuffer_t **info_pkt)
- {
- int rc;
- rc = sp_rpc_client_mgr_one_way_call(get_rpc_mgr(),
- SP_SHELL_MOD_ID,
- SP_SHELL_SVC_ID,
- call_type,
- info_pkt);
- return SpTranslateError(rc);
- }
- void SpEntity::FinishStart(ErrorCodeEnum Error)
- {
- sp_mod_entity_stub_finish_start(m_stub, Error);
- if (Error == Error_Succeed) {
- m_pEntityBase->OnStarted();
- }
- }
- void SpEntity::FinishClose(ErrorCodeEnum Error)
- {
- sp_mod_entity_stub_finish_stop(m_stub, Error);
- if (Error == Error_Succeed) {
- Term();
- }
- }
- void SpEntity::FinishPause(ErrorCodeEnum Error)
- {
- sp_mod_entity_stub_finish_pause(m_stub, Error);
- if (Error == Error_Succeed) {
- m_pEntityBase->OnPaused();
- }
- }
- void SpEntity::FinishContinue(ErrorCodeEnum Error)
- {
- sp_mod_entity_stub_finish_continue(m_stub, Error);
- if (Error == Error_Succeed) {
- m_pEntityBase->OnContinued();
- }
- }
- void SpEntity::FinishSelfTest(ErrorCodeEnum Error, DWORD dwResult)
- {
- //sp_mod_entity_stub_finish_test(m_stub, Error);
- sp_mod_entity_stub_finish_exam(m_stub, Error, dwResult);
- }
|