1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644 |
- #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"
- #include "sp_firewallControl.h"
- #else
- #include "sp_dbg_export.h"
- #endif //_WIN32
- #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 _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::SetNewPathToFirewall(CSimpleString &pszPath)
- {
- if (pszPath.GetLength() == 0) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("SetNewPathToFirewall param error");
- return Error_Param;
- }
- #ifdef _WIN32
- 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::seconds(30));
- if (status == std::future_status::ready)
- return result.get();
- else
- return Error_TimeOut;
- #else
- 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)
- {
- #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);
- }
|