123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604 |
- #include "stdafx.h"
- #include "SpBase.h"
- #include "SpTimer.h"
- #include "SpMisc.h"
- #include "SpHelper.h"
- #include "SpBinaryPersistStream.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 _WIN32
- #include "CodeSignVerify.h"
- #include "sp_checkEntity.h"
- #else
- #include "sp_dbg_export.h"
- #endif //_WIN32
- #include "sp_httpDefine.h"
- #include <iostream>
- #include <sstream>
- 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 _WIN32
- SetthreadGroup(GetCurrentThreadId(), pEntity->get_cfg_ent()->name);
- getEntityResource()->m_Entity = pEntity;
- #else
- GetSpModule()->SetThreadEntity(pEntity);
- #endif //_WIN32
- 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 _WIN32
- SetthreadGroup(GetCurrentThreadId(), pEntity->get_cfg_ent()->name);
- getEntityResource()->m_Entity = pEntity;
- #else
- GetSpModule()->SetThreadEntity(pEntity);
- #endif //_WIN32
- 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 _WIN32
- 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 //_WIN32
- }
- 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 _WIN32
- getEntityResource()->m_Entity = NULL;
- #endif //_WIN32
- }
- }
- 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 _WIN32
- setModuleAliasName(GetEntityBase()->GetEntityName());
- #endif //_WIN32
- 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 _WIN32
- SetthreadGroup(GetCurrentThreadId(), this->get_cfg_ent()->name);
- getEntityResource()->m_Entity = this;
- #else
- m_pModule->SetThreadEntity(this);
- #endif //_WIN32
- }
- void SpEntity::on_thread_term()
- {
- #ifdef _WIN32
- SetthreadGroup(GetCurrentThreadId(), this->get_cfg_ent()->name);
- getEntityResource()->m_Entity = NULL;
- #else
- m_pModule->SetThreadEntity(NULL);
- #endif //_WIN32
- }
- void SpEntity::__on_thread_init(threadpool_t *, void *arg)
- {
- SpEntity *pThis = static_cast<SpEntity*>(arg);
- pThis->on_thread_init();
- #ifndef _WIN32
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("thread init, thread id:%u", GetCurrentThreadIdFromSys());
- #else
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("thread init, thread id:%d", GetCurrentThreadId());
- #endif //NOT _WIN32
- }
- void SpEntity::__on_thread_term(threadpool_t *, void *arg)
- {
- SpEntity *pThis = static_cast<SpEntity*>(arg);
- pThis->on_thread_term();
- #if defined(_MSC_VER)
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("thread term, thread id:%d", GetCurrentThreadId());
- #else
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("thread term, thread id:%u", GetCurrentThreadIdFromSys());
- #endif //_MSC_VER
- }
- ErrorCodeEnum SpEntity::SetTimer(DWORD nTimerID, ITimerListener *pListener, DWORD dwInterval)
- {
- ErrorCodeEnum Error = Error_Succeed;
- if (!pListener)
- 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 {
- 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::ReadPersistObject(const char *pszClass, const char *pszKey, IEntityPersistObject *pInstance)
- {
- sp_env_t *env = sp_get_env();
- sp_pst_tree_t *tree;
- int rc;
- if (!pszClass || !pszKey || !pInstance)
- return Error_Param;
- rc = sp_pst_tree_load(env->dir->obj_path, m_ent->cfg->name, pszClass, pszKey, &tree);
- if (rc == 0) {
- sp_pst_elem_t *root = sp_pst_tree_get_root(tree);
- CSmartPointer<IEntityPersistStreamRead> pStream;
- pStream.Attach(new SpBinaryPersistStream(SpBinaryPersistStream::Read, root));
- rc = (int)pInstance->OnRead(pStream);
- sp_pst_tree_destroy(tree);
- }
-
- return SpTranslateError(rc);
- }
- ErrorCodeEnum SpEntity::WritePersistObject(const char *pszClass, const char *pszKey, const IEntityPersistObject *pInstance)
- {
- sp_env_t *env = sp_get_env();
- sp_pst_elem_t *root;
- int rc;
- if (!pszClass || !pszKey || !pInstance)
- return Error_Param;
- root = sp_pst_elem_create(NULL, pszKey);
- CSmartPointer<IEntityPersistStreamWrite> pStream;
- pStream.Attach(new SpBinaryPersistStream(SpBinaryPersistStream::Write, root));
- rc = (int)pInstance->OnWrite(pStream);
- if (rc == 0) {
- sp_pst_tree_t *tree;
- sp_pst_tree_create(&tree);
- sp_pst_tree_set_root(tree, root);
- rc = sp_pst_tree_save(env->dir->obj_path, m_ent->cfg->name, pszClass, pszKey, tree);
- sp_pst_tree_destroy(tree);
- } else {
- sp_pst_elem_destroy(root);
- }
- return SpTranslateError(rc);
- }
- ErrorCodeEnum SpEntity::ReadNumOfPersistObject(const char *pszClassName,DWORD &nNum)
- {
- if (!pszClassName)
- return Error_Param;
- sp_env_t *env = sp_get_env();
- int cnt;
- int rc = sp_pst_get_object_count(env->dir->obj_path, m_ent->cfg->name, pszClassName, &cnt);
- if (rc == 0)
- nNum = (DWORD)cnt;
- return SpTranslateError(rc);
- }
- ErrorCodeEnum SpEntity::GetPersistClassObjectKeys(const char *pszClassName, CAutoArray<CSimpleStringA> &strKeys)
- {
- if (!pszClassName)
- return Error_Param;
- sp_env_t *env = sp_get_env();
- array_header_t *arr = sp_pst_get_object_keys(env->dir->obj_path, m_ent->cfg->name, pszClassName);
- if (arr) {
- strKeys.Init(arr->nelts);
- for (int i = 0; i < arr->nelts; ++i)
- strKeys[i] = ARRAY_IDX(arr, i, char*);
- array_free2(arr);
- } else {
- strKeys.Init(0);
- }
- return Error_Succeed;
- }
- ErrorCodeEnum SpEntity::DeleteKeyOfPersistObject(const char *pszClassName,const char *pszKey)
- {
- if (!pszClassName || !pszKey)
- return Error_Param;
- sp_env_t *env = sp_get_env();
- int rc = sp_pst_delete_object(env->dir->obj_path, m_ent->cfg->name, pszClassName, pszKey);
- return SpTranslateError(rc);
- }
- ErrorCodeEnum SpEntity::EnumKeyOfPersistObject(const char *pszClass,CSimpleStringA &strKey,DWORD &handle)
- {
- if (!pszClass)
- return Error_Param;
- int rc = 0;
- sp_env_t *env = sp_get_env();
- struct HelperIterator {
- array_header_t *arr;
- int Current;
- } * pIterator = NULL;
- if (handle == 0) {
- pIterator = new HelperIterator();
- pIterator->arr = sp_pst_get_object_keys(env->dir->obj_path, m_ent->cfg->name, pszClass);
- if (!pIterator->arr) {
- delete pIterator;
- return Error_NotExist;
- }
- pIterator->Current = 0;
- #if defined(_MSC_VER)
- handle = (DWORD)pIterator;
- #else
- //TODO: x64 environment, depend on how to use the out-param
- handle = (uintptr_t)(static_cast<void*>(pIterator));
- #endif //_MSC_VER
- } else {
- pIterator = (HelperIterator *)handle;
- }
- if (pIterator->Current < pIterator->arr->nelts) {
- strKey = ARRAY_IDX(pIterator->arr, pIterator->Current, char*);
- pIterator->Current++;
- } else {
- if (pIterator->arr)
- array_free2(pIterator->arr);
- delete pIterator;
- handle = 0; // zero handle
- rc = Error_NotExist;// the end
- }
- return SpTranslateError(rc);
- }
- ErrorCodeEnum SpEntity::CleanAllOfPersistObject(const char *pszClass)
- {
- if (!pszClass)
- return Error_Param;
- sp_env_t *env = sp_get_env();
- int rc = sp_pst_delete_class_objects(env->dir->obj_path, m_ent->cfg->name, pszClass);
- return SpTranslateError(rc);
- }
- 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
- || (LogType == Log_Notify && (Level == Severity_High/* || Level == Severity_Middle*/))
- ) {
- 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;
- sp_cfg_root_ini_t* root_ini = cfg->root_ini;
- 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_t *mod_mgr = env->mod_mgr;
- //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();
- sp_mod_mgr_t* mod_mgr = env->mod_mgr;
- return (DWORD)(m_ent->user_state);
- }
- 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::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)
- {
- #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;
- iobuffer_t *r_pkt = NULL;
- 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;
- iobuffer_t *r_pkt = NULL;
- 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);
- }
|