SpBase.h 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716
  1. #ifndef _RVC_SPBASE_H_
  2. #define _RVC_SPBASE_H_
  3. #pragma once
  4. #include "PlatformDef.h"
  5. #if defined(__cplusplus)
  6. #ifdef SPABASE_LINKED_AS_STATIC_LIBRARY
  7. #define SPBASE_API
  8. #define EXPORT_DECLARE(retType) retType
  9. #else //SPABASE_LINKED_AS_STATIC_LIBRARY
  10. #ifdef RVC_OS_WIN
  11. #ifdef SPBASE_EXPORTS
  12. #ifndef SPBASE_API
  13. #define SPBASE_API __declspec(dllexport)
  14. #endif
  15. #else
  16. #ifndef SPBASE_API
  17. #define SPBASE_API __declspec(dllimport)
  18. #endif
  19. #endif
  20. #define EXPORT_DECLARE(retType) __declspec(dllexport) retType
  21. # elif ( defined(__GNUC__) && __GNUC__ >= 4 )
  22. #define SPBASE_API __attribute__((visibility("default")))
  23. #define EXPORT_DECLARE(retType) __attribute__((visibility("default"))) retType
  24. #else // RVC_OS_WIN
  25. #define SPBASE_API
  26. #define EXPORT_DECLARE(retType) retType
  27. #endif // RVC_OS_WIN
  28. #endif //SPABASE_LINKED_AS_STATIC_LIBRARY
  29. #endif // __cplusplus
  30. #ifdef RVC_OS_WIN
  31. #ifndef u__int64_t
  32. #define u__int64_t unsigned __int64
  33. #endif //u__int64_t
  34. #endif
  35. #include <time.h> // for time_t
  36. #ifdef RVC_OS_WIN
  37. #include<wtypes.h>
  38. #else
  39. #include <winpr/library.h>
  40. #include <winpr/synch.h>
  41. #endif // RVC_OS_WIN
  42. #if defined(__cplusplus)
  43. #include "SmartPointer.h"
  44. #include "SimpleString.h"
  45. #include "AutoArray.h"
  46. #endif // __cplusplus
  47. #include "ErrorCode.h"
  48. #ifndef MODULE_VERSION_FULL
  49. #define MODULE_VERSION_FULL "0.0.0"
  50. #endif
  51. /** define the log message type */
  52. enum LogTypeEnum
  53. {
  54. Log_Ignore=0, // ignore
  55. Log_Event=1, // Run time event
  56. Log_Warning=2, // Warning
  57. Log_Error=3, // Error notify
  58. Log_Debug=4, // debug alert ec.Assert
  59. Log_Fatal = 5, // Fatal notify
  60. Log_Notify = 6 //User notify
  61. };
  62. /** define the framework internal behavior log */
  63. enum DebugLevelEnum
  64. {
  65. Debug_None = 0, // ignore
  66. Debug_Low,
  67. Debug_Middle,
  68. Debug_High,
  69. };
  70. /** The log message level */
  71. enum SeverityLevelEnum
  72. {
  73. Severity_None=0, // ignore
  74. Severity_Low,
  75. Severity_Middle,
  76. Severity_High
  77. };
  78. enum NotifyLevelEnum
  79. {
  80. Notify_None = 0, // ignore
  81. Notify_Info,
  82. Notify_Warn,
  83. Notify_Error
  84. };
  85. enum InstallStateEnum
  86. {
  87. Install_Active, // A
  88. Install_Pending, // I
  89. Install_SetToStart, // S
  90. Install_FailRun, // F
  91. Install_RollBack, // R
  92. Install_Upgraded, // U
  93. Install_Cancelled, // C
  94. Install_WaitConfirm, // W
  95. Install_Installed, // D, only used to LightPack
  96. };
  97. /** framework state*/
  98. enum FrameworkStateEnum
  99. {
  100. FrameworkState_NotInit = 0, /** the begin state*/
  101. FrameworkState_NotConfig, /** the factory mode, not config*/
  102. FrameworkState_Booting, /** the entity is starting*/
  103. FrameworkState_Running, /** the machine has enter business page*/
  104. FrameworkState_Serving, /** the machine is providing business service*/
  105. FrameworkState_Breakdown, /** the machine is sick*/
  106. FrameworkState_Repairing, /** the machine is being maintained*/
  107. FrameworkState_Upgrading, /** the software is upgrading*/
  108. FrameworkState_Rollbacking, /** the software is rollback for some reason*/
  109. FrameworkState_Recoving, /** the machine is reaching running state from other state*/
  110. FrameworkState_NotDisturb /**/
  111. };
  112. /** entity state */
  113. enum EntityStateEnum
  114. {
  115. EntityState_NoStart=0, //no start before
  116. EntityState_Starting, //Entity is doing initial
  117. EntityState_Idle, //after started succeed,and have no work
  118. EntityState_Busy, //Doing Request-Answer,timing,and Pausing or coninuing work
  119. // have no see assignment anywhere [4/21/2020 17:38 Gifur]
  120. EntityState_Pause, //Pause state
  121. EntityState_UnLoading, //doing cleanning after trigger close
  122. EntityState_Lost, //Entity block not respond or exception
  123. EntityState_Close, //After close,start before
  124. EntityState_Killed, //The entity terminated as block state
  125. EntityState_Passed, //The entity pass all test case
  126. EntityState_Failed // The entity fail to pass the test case.
  127. };
  128. enum EntityCloseCauseEnum
  129. {
  130. CloseCause_Self=0, //Trigger close byte self
  131. CloseCause_Other, //another entity terminate the entity
  132. CloseCause_Lost, //The entity is Lost state, has to be released
  133. CloseCause_Dragged, //The same sp entity enter lost state,and has to be dragged to close
  134. CloseCause_ShellQuit, //shell end it as shell quit
  135. CloseCause_Crash,
  136. };
  137. /** session state */
  138. enum SessionStateEnum
  139. {
  140. SessionState_NotInit=0,
  141. SessionState_Live,
  142. SessionState_Pause,
  143. SessionState_Close,
  144. };
  145. /** reboot trigger reason code */
  146. enum RebootTriggerEnum
  147. {
  148. RebootTrigger_Unknown=0, //not alloc in api call.only not log for unknown reason so far
  149. RebootTrigger_Period, //daily or weekly
  150. RebootTrigger_FrameUpgrade, //reboot by update module,not reboot os
  151. RebootTrigger_OSUpgrade, //relate to outside the framework update, reboot os
  152. RebootTrigger_RollBack, //roll back to history version
  153. RebootTrigger_FailLoad, //load fail when framework start
  154. RebootTrigger_Resource, //reboot by health manager
  155. RebootTrigger_RunExcepition, //Exception lead to restart
  156. RebootTrigger_RunDead, //System is out of control in running ec watch dog reset or system dead
  157. RebootTrigger_Attacked, //framework is changed or invaded
  158. RebootTrigger_Powerdown, //Out side power is interrupt
  159. RebootTrigger_Repaired, //Framework has did some repair job in SafeLoad|Fault state and restart try to recover running
  160. RebootTrigger_ManualLocal, //reboot by local maintain
  161. RebootTrigger_ManualRemove, //reboot by remote maintain
  162. RebootTrigger_Unsubscribe, //The life of machine is over,and will not connect to backstage again
  163. RebootTrigger_DeadForever, //As some reason such as test failed, we want Framework dead and not reboot. TODO: let the Gardian know.
  164. };
  165. enum RebootWayEnum
  166. {
  167. RebootWay_Unknown=0, //If not log,only mark unknown
  168. RebootWay_Framework, //restart framework not os
  169. RebootWay_OS, //restart os not power
  170. RebootWay_Power, //restart os and power
  171. };
  172. enum EntityTestEnum
  173. {
  174. Test_ShakeHand=0,
  175. Test_Examine, //no use at current time, even in selfcheck entity, they defined it but never call it.
  176. Test_Reset,
  177. };
  178. enum ConfigTypeEnum
  179. {
  180. Config_Hardware, //Read only, for read entity hardware file
  181. Config_Software, //Read and write
  182. Config_Run, //Read and write. create in run time can't be upgrade or conver
  183. Config_Shell, //Read only, for read shell.ini file
  184. Config_Root, //Read only, for read root.ini file
  185. Config_CenterSetting, //Read only
  186. Config_Cache //Read and write, store at runcfg/Global.ini
  187. };
  188. enum ScreenEnum
  189. {
  190. Screen_Operation=0, //just has a single Operation Screen
  191. Screen_OpAndInfo=1, //has double screen Operation screen and information screen
  192. Screen_OpAndMaintain=8, //has Operation screen and Maintain screen
  193. Screen_OpAndInfoAndMaintain=9, //has 3 screen Operation screen and information screen and Maintain screen
  194. };
  195. enum EntityPriorityEnum
  196. {
  197. Priority_Low,
  198. Priority_Below_Normal,
  199. Priority_Normal,
  200. Priority_Above_Normal,
  201. Priority_High,
  202. Priority_Highest,
  203. Priority_Unknown
  204. };
  205. #if defined(__cplusplus)
  206. /** for sp-software and acm machine version type */
  207. class CVersion
  208. {
  209. private:
  210. union
  211. {
  212. u__int64_t m_nVersion64;
  213. struct//Intel CPU byte order,otherwise ,need to redefine
  214. {
  215. WORD m_nBuild;
  216. WORD m_nRevision;
  217. union
  218. {
  219. DWORD m_nVersion32;
  220. struct
  221. {
  222. WORD m_nMinor;
  223. WORD m_nMajor;
  224. };
  225. };
  226. };
  227. };
  228. public:
  229. inline WORD GetMajor(){return m_nMajor;}
  230. inline WORD GetMinor(){return m_nMinor;}
  231. inline WORD GetRevision(){return m_nRevision;}
  232. inline WORD GetBuild(){return m_nBuild;}
  233. inline u__int64_t GetVersion64(){return m_nVersion64;}
  234. inline DWORD GetVersion32(){return m_nVersion32;}
  235. inline CSimpleStringA ToString(){return CSimpleStringA::Format("%d.%d.%d.%d",m_nMajor,m_nMinor,m_nRevision,m_nBuild);}
  236. inline bool operator ==(CVersion &Version){return m_nVersion64==Version.m_nVersion64;}
  237. inline bool operator !=(CVersion &Version){return m_nVersion64!=Version.m_nVersion64;}
  238. inline bool operator <(CVersion &Version){return m_nVersion64<Version.m_nVersion64;}
  239. inline bool operator >(CVersion &Version){return m_nVersion64>Version.m_nVersion64;}
  240. inline bool operator <=(CVersion &Version){return m_nVersion64<=Version.m_nVersion64;}
  241. inline bool operator >=(CVersion &Version){return m_nVersion64>=Version.m_nVersion64;}
  242. inline bool IsCompatible(CVersion &Version){return m_nVersion32==Version.m_nVersion32;}
  243. inline bool IsUpgrade(CVersion &Version){return m_nVersion32>Version.m_nVersion32;}
  244. inline CVersion &operator=(const CVersion &Version){m_nVersion64=Version.m_nVersion64;return *this;}
  245. inline CVersion(WORD nMajor,WORD nMinor):m_nMajor(nMajor),m_nMinor(nMinor),m_nRevision(0),m_nBuild(0){}
  246. inline CVersion(WORD nMajor,WORD nMinor,WORD nRevision,WORD nBulid):m_nMajor(nMajor),m_nMinor(nMinor),m_nRevision(nRevision),m_nBuild(nBulid){}
  247. inline CVersion(const CVersion &Version):m_nVersion64(Version.m_nVersion64){}
  248. inline CVersion() : m_nVersion64(0) {}
  249. inline CVersion(__int64 nVersion) : m_nVersion64(nVersion){}
  250. inline bool IsValid(){return m_nVersion64 >0;}
  251. };
  252. SPBASE_API void GetLibVersion(CVersion& version);
  253. SPBASE_API LPCSTR GetLibBuildDate();
  254. class SPBASE_API CSmallDateTime
  255. {
  256. /** 单位是秒 [Gifur@2022324]*/
  257. DWORD m_nTimeTicks;
  258. public:
  259. static CSmallDateTime BeginTime;
  260. static CSmallDateTime EndTime;
  261. static CSmallDateTime GetNow();
  262. inline CSmallDateTime(DWORD nTimeTicks = 0):m_nTimeTicks(nTimeTicks){}
  263. inline CSmallDateTime(const CSmallDateTime &DateTime):m_nTimeTicks(DateTime.m_nTimeTicks){}
  264. inline operator DWORD () const{return m_nTimeTicks;}
  265. inline const CSmallDateTime & operator =(const CSmallDateTime &DateTime){m_nTimeTicks=DateTime.m_nTimeTicks;return *this;}
  266. inline bool operator ==(const CSmallDateTime &DateTime){return m_nTimeTicks==DateTime.m_nTimeTicks;}
  267. inline bool operator !=(const CSmallDateTime &DateTime){return m_nTimeTicks!=DateTime.m_nTimeTicks;}
  268. inline bool operator <(const CSmallDateTime &DateTime){return m_nTimeTicks<DateTime.m_nTimeTicks;}
  269. inline bool operator >(const CSmallDateTime &DateTime){return m_nTimeTicks>DateTime.m_nTimeTicks;}
  270. inline bool operator <=(const CSmallDateTime &DateTime){return m_nTimeTicks<=DateTime.m_nTimeTicks;}
  271. inline bool operator >=(const CSmallDateTime &DateTime){return m_nTimeTicks>=DateTime.m_nTimeTicks;}
  272. __time64_t GetTime64();
  273. /** format string: YYYY-MM-DD hh:mm:ss*/
  274. CSimpleStringA ToTimeString();
  275. SYSTEMTIME ToSystemTime();
  276. void FromSystemTime(const SYSTEMTIME &st);
  277. };
  278. class SPBASE_API CUUID
  279. {
  280. #ifdef RVC_OS_WIN
  281. #if (!defined(SPABASE_LINKED_AS_STATIC_LIBRARY) && !defined(SPBASE_EXPORTS))
  282. protected:
  283. #else
  284. public:
  285. #endif
  286. #else
  287. public:
  288. #endif //RVC_OS_WIN
  289. union//Intel CPU byte order,otherwise the need to redefine
  290. {
  291. u__int64_t m_nUUID64;
  292. struct
  293. {
  294. WORD m_nAppID; //the id of the server
  295. WORD m_nDsn; //inner a Second serial
  296. DWORD m_nTimeTicks;
  297. };
  298. };
  299. static WORD m_gAppID;
  300. public:
  301. inline CUUID(const CUUID &UUID):m_nUUID64(UUID.m_nUUID64){}
  302. inline CUUID(u__int64_t nUUID64 = 0):m_nUUID64(nUUID64){}
  303. inline CSmallDateTime GetTime(){return m_nTimeTicks;}
  304. inline operator u__int64_t () const{return m_nUUID64;}
  305. inline const CUUID & operator =(const CUUID &UUID){m_nUUID64=UUID.m_nUUID64;return *this;}
  306. inline bool operator ==(const CUUID &UUID){return m_nUUID64==UUID.m_nUUID64;}
  307. inline bool operator !=(const CUUID &UUID){return m_nUUID64!=UUID.m_nUUID64;}
  308. inline bool operator <(const CUUID &UUID){return m_nUUID64<UUID.m_nUUID64;}
  309. inline bool operator >(const CUUID &UUID){return m_nUUID64>UUID.m_nUUID64;}
  310. inline bool operator <=(const CUUID &UUID){return m_nUUID64<=UUID.m_nUUID64;}
  311. inline bool operator >=(const CUUID &UUID){return m_nUUID64>=UUID.m_nUUID64;}
  312. inline DWORD GetAppID() const {return m_nAppID;}
  313. inline CSimpleStringA ToString() const { return CSimpleStringA::Format("%016llX", m_nUUID64); }
  314. static CUUID Create(const CUUID &LastUUID);
  315. static CUUID Create(const CUUID& LastUUID, const CSmallDateTime& DateTime);
  316. };
  317. /** for GPS, for longitude, east is +, west is -, for latitude, north is +, south is - */
  318. /* e.g. N22:33:09 convert to float is 22.5525 */
  319. class SPBASE_API CSphereVector
  320. {
  321. private:
  322. float m_fLongitude;
  323. float m_fLatitude;
  324. public:
  325. inline float GetLongitude(){return m_fLongitude;}
  326. inline float GetLatitude(){return m_fLatitude;}
  327. inline CSphereVector(float fLongitude,float fLatitude):m_fLongitude(fLongitude),m_fLatitude(fLatitude){}
  328. inline CSphereVector() : m_fLatitude(0), m_fLongitude(0) {}
  329. /*将浮点型的经度转成度分秒表示法,第4个字节表示经度方向,负浮点数表示西部,返回'W',正浮点数表示东部,返回 'E'*/
  330. void GetBinaryLongitude(BYTE longitude[4]);
  331. /*将浮点型的纬度转成度分秒表示法,第4个字节表示纬度方向,负浮点数表示南部,返回'S',正浮点数表示北部,返回 'N'*/
  332. void GetBinaryLatitude(BYTE latitude[4]);
  333. };
  334. struct CInstallInfo
  335. {
  336. CVersion PreviousInstallVersion;
  337. CVersion InstallVersion;
  338. CSmallDateTime tmSwithOverDate;
  339. CSimpleStringA InstallPack;
  340. InstallStateEnum InstallState;
  341. };
  342. struct CLightPackInfo
  343. {
  344. CSimpleStringA strPackName;
  345. CSmallDateTime tmInstalledDate;
  346. InstallStateEnum State;
  347. };
  348. #define LINKINFO_BUSSID_LEN 32
  349. #define LINKINFO_TRACEID_LEN 32
  350. #define LINKINFO_SPANID_LEN 16
  351. #define LINKINFO_PARENTSPANID_LEN 16
  352. SPBASE_API CSimpleStringA uuid4_generateStr(int len);
  353. struct linkContext
  354. {
  355. CSimpleStringA bussinessId;
  356. CSimpleStringA traceId;
  357. CSimpleStringA spanId;
  358. CSimpleStringA parentSpanId;
  359. linkContext():bussinessId(true), traceId(true), spanId(true), parentSpanId(true){}
  360. linkContext(CSimpleStringA t_bussinessId, CSimpleStringA t_traceId, CSimpleStringA t_spanId, CSimpleStringA t_parentSpanId) {
  361. bussinessId = t_bussinessId;
  362. traceId = t_traceId;
  363. spanId = t_spanId;
  364. parentSpanId = t_parentSpanId;
  365. }
  366. void Init(const char* t_bussId, const char* t_traceId, const char* t_spanId, const char* t_parentSpanId)
  367. {
  368. if (t_bussId && t_traceId && t_spanId && t_parentSpanId)
  369. {
  370. char copy_bussId[LINKINFO_BUSSID_LEN + 1], copy_traceId[LINKINFO_TRACEID_LEN + 1];
  371. char copy_spanId[LINKINFO_SPANID_LEN + 1], copy_parentSpanId[LINKINFO_PARENTSPANID_LEN + 1];
  372. memset(copy_bussId, 0, sizeof(copy_bussId));
  373. memset(copy_traceId, 0, sizeof(copy_traceId));
  374. memset(copy_spanId, 0, sizeof(copy_spanId));
  375. memset(copy_parentSpanId, 0, sizeof(copy_parentSpanId));
  376. memcpy(copy_bussId, t_bussId, LINKINFO_BUSSID_LEN);
  377. memcpy(copy_traceId, t_traceId, LINKINFO_TRACEID_LEN);
  378. memcpy(copy_spanId, t_spanId, LINKINFO_SPANID_LEN);
  379. memcpy(copy_parentSpanId, t_parentSpanId, LINKINFO_PARENTSPANID_LEN);
  380. bussinessId = copy_bussId;
  381. traceId = copy_traceId;
  382. spanId = copy_spanId;
  383. parentSpanId = copy_parentSpanId;
  384. }
  385. }
  386. linkContext& operator=(const linkContext& tmp) {
  387. bussinessId = tmp.bussinessId;
  388. traceId = tmp.traceId;
  389. spanId = tmp.spanId;
  390. parentSpanId = tmp.parentSpanId;
  391. return *this;
  392. }
  393. void clear() {
  394. bussinessId = "";
  395. traceId = "";
  396. spanId = "";
  397. parentSpanId = "";
  398. }
  399. linkContext upgradeLink() const {
  400. if (bussinessId.GetLength() == 0 || traceId.GetLength() == 0)
  401. return *this;
  402. else
  403. return linkContext(bussinessId, traceId, uuid4_generateStr(LINKINFO_SPANID_LEN), spanId);
  404. }
  405. linkContext upgradeLinkAndSave() {
  406. if (bussinessId.GetLength() == 0 || traceId.GetLength() == 0)
  407. return *this;
  408. else {
  409. spanId = uuid4_generateStr(LINKINFO_SPANID_LEN);
  410. parentSpanId = spanId;
  411. return *this;
  412. }
  413. }
  414. bool checkEmpty() const {
  415. return (bussinessId.GetLength() == 0 || traceId.GetLength() == 0);
  416. }
  417. void AutoGenerate() {
  418. bussinessId = "VTMAutoGen";
  419. traceId = uuid4_generateStr(LINKINFO_TRACEID_LEN);
  420. spanId = uuid4_generateStr(LINKINFO_SPANID_LEN);
  421. parentSpanId = "0";
  422. }
  423. };
  424. /** acm machine info, information filled at installation, at root.ini */
  425. struct CSystemStaticInfo : public CInstallInfo
  426. {
  427. CSystemStaticInfo() :
  428. strTerminalID(""),
  429. strMachineType(""),
  430. eScreen(ScreenEnum::Screen_Operation), // 设置一个默认值
  431. nTotalRunCount(0), // 初始化为 0 或其他适当的默认值
  432. nTodayRunCount(0), // 初始化为 0 或其他适当的默认值
  433. tmCreateDate(), // 使用默认构造函数初始化 SmallDateTime
  434. tmCurrentTime(), // 使用默认构造函数初始化 SmallDateTime
  435. strSite(""),
  436. EnrolGPS(),
  437. strEnrolAddr(""),
  438. strManufacturer(""),
  439. strMachineModel(""),
  440. strMachineSN("")
  441. {
  442. // 在构造函数中进行额外的初始化工作,如果需要的话
  443. }
  444. CSimpleStringA strTerminalID;
  445. CSimpleStringA strMachineType;
  446. CVersion MachineVersion;
  447. ScreenEnum eScreen;
  448. CVersion LatterInstallVersion; // 0 version for none
  449. CAutoArray<CLightPackInfo> LightPackInfos;
  450. WORD nTotalRunCount;
  451. WORD nTodayRunCount;
  452. CSmallDateTime tmCreateDate;
  453. CSmallDateTime tmCurrentTime;
  454. CSimpleStringA strSite;
  455. CSphereVector EnrolGPS;
  456. CSimpleStringA strEnrolAddr;
  457. CSimpleStringA strManufacturer;
  458. CSimpleStringA strMachineModel;
  459. CSimpleStringA strMachineSN;
  460. };
  461. /** map to spshell launch options.*/
  462. enum SystemBootOptionEnum
  463. {
  464. BootOption_Default = 0,
  465. BootOption_Test = 1, /** mapping to sp_cfg::sp_cfg_start_args_t::test_mode & 1 */
  466. BootOption_Entity = (1 << 1), /** mapping to sp_cfg::sp_cfg_start_args_t::start_entities flag */
  467. BootOption_Debug = (1 << 2), /** mapping to sp_cfg::sp_cfg_start_args_t::debug_mode */
  468. BootOption_Benchmark = (1 << 3), /** mapping to sp_cfg::sp_cfg_start_args_t::test_mode & 2*/
  469. BootOption_RootPrivilege = (1 << 4), /** run as root privilege*/
  470. BootOption_ST = (1 << 5), /** run as st mode, mapping to sp_cfg::sp_cfg_start_args_t::test_mode & 4*/
  471. BootOption_UAT = (1 << 6) /** run as uat mode,mapping to sp_cfg::sp_cfg_start_args_t::test_mode & 8*/
  472. };
  473. /** acm system startup info */
  474. struct CSystemRunInfo
  475. {
  476. CSmallDateTime tmStart;
  477. DebugLevelEnum eDebugLevel;
  478. FrameworkStateEnum eState;
  479. DWORD dwBootOption;
  480. CAutoArray<CSimpleStringA> strRunningEntityNames;
  481. bool bBasicCfgWork;
  482. bool bErrCfgWork;
  483. };
  484. /** boot info */
  485. struct CBootInfo
  486. {
  487. CVersion InstallVersion;
  488. CSmallDateTime tmStart; //the system start run time
  489. CSmallDateTime tmReboot; //The trigger reboot time and It is end of run from StartTime
  490. RebootTriggerEnum eTriggerReason;
  491. RebootWayEnum eWay;
  492. WORD wSameReasonTime;
  493. WORD wSameWayTime;
  494. };
  495. /** sp module info */
  496. struct CSpInfo
  497. {
  498. CSimpleStringA strAuthor;
  499. CSimpleStringA strCompany;
  500. CVersion SoftwareVersion;
  501. CAutoArray<CSimpleStringA> strEntitys;
  502. };
  503. /** entity configuration data */
  504. struct CEntityStaticInfo
  505. {
  506. WORD wEntityDevelopID;
  507. bool bStartedByShell; //config start by shell or not(other Entity)
  508. bool bHasPrivilege; //can support IEntityFunctionPrivilege interface
  509. bool bIndispensable; //must be start and work correct else framework will fall into "Fault" state
  510. CSimpleStringA strSpFileName;
  511. CVersion version;
  512. };
  513. /** entity session info */
  514. struct CEntitySessionInfo
  515. {
  516. CSimpleStringA strCallerEntity;
  517. CSimpleStringA strServiceEntity;
  518. CSmallDateTime tmStart;
  519. SessionStateEnum eState;
  520. CSmallDateTime tmBeginState;
  521. };
  522. struct CEntityStartInfo
  523. {
  524. /** 应用当前实体的启动次数*/
  525. int startTimes;
  526. /** 收到启动实体的时间戳,第一次有效*/
  527. SYSTEMTIME startTime;
  528. /** 完成加载实体模块的时间戳,第一次有效,不判断是否加载失败*/
  529. SYSTEMTIME InitEndTime;
  530. /** 完成启动实体模块时间戳,第一次有效,不判断是否启动失败*/
  531. SYSTEMTIME startEndTime;
  532. };
  533. struct CEntityLastErrorInfo
  534. {
  535. ErrorCodeEnum eSysCode;
  536. DWORD dwUserCode;
  537. CSimpleStringA strErrMsg;
  538. };
  539. /** entity running info */
  540. struct CEntityRunInfo
  541. {
  542. DWORD dwEntityInstanceID;
  543. CSmallDateTime tmFirstStart; //The Entity first started after framework start
  544. CSmallDateTime tmLastStart; //The nearest started of this entity instance
  545. bool bService;
  546. EntityStateEnum eState;
  547. CSmallDateTime tmBeginCurrentState;
  548. DebugLevelEnum eDebugLevel;
  549. DWORD dwUserState; //Self define state
  550. DWORD dwProcessID; //Process ID of os
  551. };
  552. /** entity log info */
  553. struct CEntityLogInfo
  554. {
  555. CSimpleStringA strLogPath;
  556. };
  557. struct BroadcastSubscribeInfo
  558. {
  559. CUUID SubID;
  560. CSimpleStringA strListener; // from entity's name
  561. CSimpleStringA strParam;
  562. };
  563. struct IReleasable
  564. {
  565. virtual ~IReleasable(){};
  566. };
  567. /**
  568. * entity timer for user, the timer will initialize when user call IEntityFunction::SetTimer,
  569. * until user call KillTimer
  570. * note: nTimerID is application defined value in Entity Scope !!!
  571. */
  572. struct ITimerListener
  573. {
  574. virtual void OnTimeout(DWORD dwTimerID) = 0;
  575. };
  576. /** subcribe-public pattern, sys variable used for tracking system-level events */
  577. struct ISysVarListener
  578. {
  579. virtual void OnSysVarEvent(const char *pszKey,
  580. const char *pszValue,const char *pszOldValue,const char *pszEntityName)=0;
  581. };
  582. struct ITerminalStateChangedListener
  583. {
  584. virtual void OnStateChanged(FrameworkStateEnum oldState, FrameworkStateEnum curState, const char* triggerEntity) = 0;
  585. };
  586. struct IBroadcastListener
  587. {
  588. virtual void OnBroadcastEvent(CUUID SubID, const char* pszEntityName, DWORD dwMessageId, DWORD dwMessageSignature, CAutoBuffer Buffer) = 0;
  589. };
  590. struct IEntityLifeListener
  591. {
  592. /* if pszTriggerEntity=null mean created by shell*/
  593. virtual void OnCreated(const char* pszEntityName, ErrorCodeEnum eOnStartErrorCode, const char* pszCallerEntity) = 0;
  594. /*Call after the entity has close or killed, eOnCloseErrorCode notic if the entity do OnClose normally and resource has beed release*/
  595. virtual void OnClosed(const char* pszEntityName, EntityCloseCauseEnum eCloseCause, ErrorCodeEnum eOnCloseErrorCode, const char* pszCallerEntity) = 0;
  596. /*1 case is entity raise exception and catch by framework,but not mean the entity will close,2 case is the entity is enter lost state*/
  597. virtual void OnException(const char* pszEntityName, const char* pszFunctionName, EntityStateEnum eState, EntityStateEnum eLastState, ErrorCodeEnum eErrorCode) = 0;
  598. };
  599. struct IEntityStateListener
  600. {
  601. virtual void OnEntityStateHook(const char* pszEntityName, const char* pszTriggerEntity, EntityStateEnum eState, EntityStateEnum eLastState) = 0;
  602. virtual void OnUserStateHook(const char* pszEntityName, DWORD dwState, DWORD dwLastState) = 0;
  603. virtual void OnCeateConnection(const char* pszCallerEntity, const char* pszServiceEntity) = 0;
  604. virtual void OnCloseConnection(const char* pszCallerEntity, const char* pszServiceEntity) = 0;
  605. };
  606. /** log hooker */
  607. struct ILogListener
  608. {
  609. virtual void OnLog(const CAutoArray<CUUID>& SubIDs, const CUUID nLogID, const LogTypeEnum eLogType, const SeverityLevelEnum eLevel,
  610. const DWORD dwSysError, const DWORD dwUserCode, const DWORD dwEntityInstanceID, const WORD wEntityDevelID,
  611. const CAutoArray<DWORD>& Param, const char* pszEntityName, const char* pszModuleName, const char* pszMessage, const linkContext& pLinkInfo) = 0;
  612. };
  613. struct IConfigInfo
  614. {
  615. virtual ConfigTypeEnum GetConfigType() = 0;
  616. virtual bool storageInMem() = 0;
  617. /** read/write config via shell */
  618. virtual ErrorCodeEnum ReadConfigValue(const char* pszSection, const char* pszKey, CSimpleStringA& strValue) = 0;
  619. virtual ErrorCodeEnum ReadConfigValueInt(const char* pszSection, const char* pszKey, int& iValue) = 0;
  620. /** only can write self's section, pValue=NULL for delete */
  621. virtual ErrorCodeEnum WriteConfigValue(const char* pszSection, const char* pszKey, const char* pszValue) = 0;
  622. virtual ErrorCodeEnum WriteConfigValueInt(const char* pszSection, const char* pszKey, int iValue) = 0;
  623. /** read all key-value pairs */
  624. virtual ErrorCodeEnum ReadAllKeys(const char* pszSection, CAutoArray<CSimpleStringA>& strKeys) = 0;
  625. /** get all section values */
  626. virtual ErrorCodeEnum ReadAllSections(CAutoArray<CSimpleStringA>& strSections) = 0;
  627. /** write hex int values, ig: "keyName=0x4F3D012A" */
  628. virtual ErrorCodeEnum WriteConfigValueHexInt(const char* pszSection, const char* pszKey, UINT64 nValue) = 0;
  629. virtual ErrorCodeEnum ReadConfigValueHexInt(const char* pszSection, const char* pszKey, UINT64& nValue) = 0;
  630. };
  631. struct IAsynWaitSp;
  632. /** invoked when receive answer from remote */
  633. struct ICallbackListener
  634. {
  635. virtual void OnAnswer(CSmartPointer<IAsynWaitSp> pAsynWaitSp) = 0;
  636. };
  637. struct IEntityPersistObject;
  638. /** object serialize mechanism, reader interface */
  639. struct IEntityPersistStreamRead
  640. {
  641. virtual ErrorCodeEnum Get(const char* pszKey, CSimpleStringA& strValue) = 0;
  642. virtual ErrorCodeEnum Get(const char* pszKey, ULONGLONG& qwValue) = 0;
  643. virtual ErrorCodeEnum Get(const char* pszKey, DWORD& dwValue) = 0;
  644. virtual ErrorCodeEnum Get(const char* pszKey, WORD& wValue) = 0;
  645. virtual ErrorCodeEnum Get(const char* pszKey, BYTE& cValue) = 0;
  646. virtual ErrorCodeEnum Get(const char* pszKey, FLOAT& fValue) = 0;
  647. virtual ErrorCodeEnum Get(const char* pszKey, DOUBLE& fValue) = 0;
  648. virtual ErrorCodeEnum Get(const char* pszKey, IEntityPersistObject* pValue) = 0;
  649. virtual ErrorCodeEnum GetArray(const char* pszKey, CAutoArray<CSimpleStringA>& strValues) = 0;
  650. virtual ErrorCodeEnum GetArray(const char* pszKey, CAutoArray<ULONGLONG>& qwValues) = 0;
  651. virtual ErrorCodeEnum GetArray(const char* pszKey, CAutoArray<DWORD>& dwValues) = 0;
  652. virtual ErrorCodeEnum GetArray(const char* pszKey, CAutoArray<WORD>& wValues) = 0;
  653. virtual ErrorCodeEnum GetArray(const char* pszKey, CAutoArray<BYTE>& cValues) = 0;
  654. virtual ErrorCodeEnum GetArray(const char* pszKey, CAutoArray<FLOAT>& fValues) = 0;
  655. virtual ErrorCodeEnum GetArray(const char* pszKey, CAutoArray<DOUBLE>& fValues) = 0;
  656. };
  657. /** object serialize mechanism, writer interface */
  658. struct IEntityPersistStreamWrite
  659. {
  660. virtual ErrorCodeEnum Set(const char* pszKey, const char* pszValue) = 0;
  661. virtual ErrorCodeEnum Set(const char* pszKey, const ULONGLONG qwValue) = 0;
  662. virtual ErrorCodeEnum Set(const char* pszKey, const DWORD dwValue) = 0;
  663. virtual ErrorCodeEnum Set(const char* pszKey, const WORD wValue) = 0;
  664. virtual ErrorCodeEnum Set(const char* pszKey, const BYTE cValue) = 0;
  665. virtual ErrorCodeEnum Set(const char* pszKey, const FLOAT fValue) = 0;
  666. virtual ErrorCodeEnum Set(const char* pszKey, const DOUBLE fValue) = 0;
  667. virtual ErrorCodeEnum Set(const char* pszKey, const IEntityPersistObject* pValue) = 0;
  668. virtual ErrorCodeEnum SetArray(const char* pszKey, const CAutoArray<CSimpleStringA>& strValues) = 0;
  669. virtual ErrorCodeEnum SetArray(const char* pszKey, const CAutoArray<ULONGLONG>& qwValues) = 0;
  670. virtual ErrorCodeEnum SetArray(const char* pszKey, const CAutoArray<DWORD>& dwValues) = 0;
  671. virtual ErrorCodeEnum SetArray(const char* pszKey, const CAutoArray<WORD>& wValues) = 0;
  672. virtual ErrorCodeEnum SetArray(const char* pszKey, const CAutoArray<BYTE>& cValues) = 0;
  673. virtual ErrorCodeEnum SetArray(const char* pszKey, const CAutoArray<FLOAT>& fValues) = 0;
  674. virtual ErrorCodeEnum SetArray(const char* pszKey, const CAutoArray<DOUBLE>& fValues) = 0;
  675. };
  676. /** object serialize mechanism, user-defined object need to inherits from this */
  677. struct IEntityPersistObject
  678. {
  679. virtual ErrorCodeEnum OnRead(CSmartPointer<IEntityPersistStreamRead> pStream) = 0;
  680. virtual ErrorCodeEnum OnWrite(CSmartPointer<IEntityPersistStreamWrite> pStream) const = 0;
  681. };
  682. /** task interface */
  683. struct ITaskSp
  684. {
  685. ITaskSp() : m_ref_cnt(1) {}
  686. virtual ~ITaskSp() {}
  687. virtual void IncRef() { InterlockedIncrement(&m_ref_cnt); }
  688. virtual void DecRef() { if (0 == InterlockedDecrement(&m_ref_cnt)) { delete this; } }
  689. virtual void Process() = 0;
  690. private:
  691. LONG m_ref_cnt;
  692. };
  693. class CClientSessionBase;
  694. class CServerSessionBase;
  695. struct IEntityFunctionPrivilege;
  696. //typedef int (*postLink)(const char *bussinessId, const char *traceId, const char *spanId, const char *parentSpanId);
  697. /** normal entity service */
  698. struct IEntityFunction
  699. {
  700. virtual ~IEntityFunction() {}
  701. /** get CSystemStaticInfo information */
  702. virtual ErrorCodeEnum GetSystemStaticInfo(CSystemStaticInfo& Info) = 0;
  703. virtual ErrorCodeEnum GetInstallInfo(CVersion Version, CInstallInfo& Info) = 0; //include latter/current/history version
  704. virtual bool IsPackInstalled(const char* pPackName) = 0;
  705. /**
  706. * get path define in Root.ini,
  707. * pszKey : "Data", "Rec", "Temp", "SysLog", "InterLog","UploadVideo","UploadPhoto","Downloads","Upgraded","LatterInstall","Run","SysRoot","CenterSetting"
  708. */
  709. virtual ErrorCodeEnum GetPath(const char* pszKey, CSimpleStringA& strPath) = 0;
  710. /** get system running info */
  711. virtual ErrorCodeEnum GetSystemRunInfo(CSystemRunInfo& Info) = 0;
  712. /** get busy entity number and startup entity number */
  713. virtual ErrorCodeEnum GetEntityBusyRate(WORD& nBusyEntity, WORD& nAllEntity) = 0;
  714. /** get reboot info,if BeforeThisTime=CSmallDateTime::BeginTime,then return last time boot info,else return the start time before BeforeThisTime record*/
  715. virtual ErrorCodeEnum GetRebootInfo(CSmallDateTime BeforeThisTime, CBootInfo& Info) = 0;
  716. /** get all sp entity module file name without full path */
  717. virtual ErrorCodeEnum GetAllRegistSpFile(CAutoArray<CSimpleStringA>& strSpNames) = 0;
  718. /** get sp file info */
  719. virtual ErrorCodeEnum GetSpFileInfo(const char* pszSpName, CSpInfo& Info) = 0;
  720. /** get all registered entity name */
  721. virtual ErrorCodeEnum GetAllRegistedEntity(CAutoArray<CSimpleStringA>& strEntityNames, CAutoArray<WORD>& wEntityDevelopIDs) = 0;
  722. virtual ErrorCodeEnum GetAllStartedEntity(CAutoArray<CSimpleStringA>& strEntityNames, CAutoArray<DWORD>& dwEntityInstanceIDs) = 0;
  723. /** get the entity of the current process running info */
  724. virtual ErrorCodeEnum GetSelfEntityRunInfo(CEntityRunInfo& Info) = 0;
  725. /** get entity config info */
  726. virtual ErrorCodeEnum GetEntityStaticInfo(const char* pszEntityName, CEntityStaticInfo& Info) = 0;
  727. //virtual ErrorCodeEnum GetEntityStaticInfo(WORD wEntityDevelopID,CEntityStaticInfo &Info)=0;
  728. /** get entity state via shell */
  729. virtual ErrorCodeEnum GetEntityRunInfo(const char* pszEntityName, CEntityRunInfo& Info) = 0;
  730. /** get entity all session info */
  731. virtual ErrorCodeEnum GetEntitySessionInfo(const char* pszEntityName, CAutoArray<CEntitySessionInfo>& Infos) = 0;
  732. /** get entity name from instance entity ID */
  733. virtual ErrorCodeEnum GetEntityName(DWORD dwEntityInstanceID, CSimpleStringA& strName) = 0;
  734. /** get entity name from develop entity ID */
  735. virtual ErrorCodeEnum GetEntityName(WORD wEntityDevelopID, CSimpleStringA& strName) = 0;
  736. /** ini file reader/writer utility */
  737. virtual ErrorCodeEnum OpenConfig(ConfigTypeEnum eConfigType, CSmartPointer<IConfigInfo>& pConfigInfo, bool forceFile = false) = 0;
  738. /** Set self define state enum for out side notice */
  739. virtual ErrorCodeEnum SetUserDefineState(DWORD dwState) = 0;
  740. virtual DWORD GetUserDefineState() = 0;
  741. /** only the entity has been set in shell.ini can change the value*/
  742. virtual ErrorCodeEnum SetSysVar(const char* pszKey, const char* pszValue, bool bPersist = false) = 0;
  743. /** get sys variable value */
  744. virtual ErrorCodeEnum GetSysVar(const char* pszKey, CSimpleStringA& strValue) = 0;
  745. virtual ErrorCodeEnum GetAllEntityStartInfo(CAutoArray<CSimpleStringA>& strEntityNames, CAutoArray<int>& strEntityIdx, CAutoArray<CEntityStartInfo>& Infos) = 0;
  746. /** get entity log path via shell */
  747. virtual ErrorCodeEnum GetEntityLogPath(const char* pszEntityName, CEntityLogInfo& Info) = 0;
  748. virtual WORD GetDevID() = 0;
  749. /**
  750. * install sys variable
  751. * @param pszKey the sys var key you want subscribe
  752. * @param pListener user callback interface
  753. * @param dwSysEventID user defined ID, must be unique in entity scope
  754. */
  755. virtual ErrorCodeEnum RegistSysVarEvent(const char* pszKey, ISysVarListener* pListener) = 0;
  756. /*if pszKey=NULL mean unregist all keys event*/
  757. virtual ErrorCodeEnum UnregistSysVarEvent(const char *pszKey)=0;
  758. /*!
  759. * @brief
  760. * @param pListener the sub class boject pointer inherit ITerminalStateChangedListener and implement
  761. * OnStateChanged interface.
  762. * @return : Error_Succeed if regist successfully, other means failure.
  763. */
  764. virtual ErrorCodeEnum RegistTerminalStateChangeEvent(ITerminalStateChangedListener* pListener) = 0;
  765. /*!
  766. * @brief
  767. * @return : Error_Succeed if unregist successfully
  768. */
  769. virtual ErrorCodeEnum UnregistTerminalStateChangeEvent() = 0;
  770. /**
  771. * every entity can broadcast messages, user entity can subscribe an entity's broadcast messages
  772. */
  773. virtual ErrorCodeEnum SendBroadcast(DWORD dwMessageId, DWORD dwMessageSignature, CAutoBuffer Buffer) = 0;
  774. virtual ErrorCodeEnum GetBroadcastReceivers(CAutoArray<BroadcastSubscribeInfo>& Subscribers) = 0;
  775. virtual ErrorCodeEnum SubscribeBroadcast(const char* pszRemoteEntity, const char* pszParam, IBroadcastListener* pListener, CUUID& SubscribeID) = 0;
  776. virtual ErrorCodeEnum UnsubscribeBroadcast(CUUID SubscribeID) = 0;
  777. virtual ErrorCodeEnum UnsubscribeBroadcast(const char* pszRemoteEntity) = 0;
  778. /**
  779. * subscribe log via shell
  780. * @param listener user's specific callback, null to cancel
  781. * @param eLevel will get log more(or equal) importance than eLevel,
  782. * @param pszEntityName if not null will get log only for that "pszEntityName" appoint one
  783. * @param eSysError Error_IgnoreAll means accept any sys error
  784. * @param dwUserCode -2 means accept any user code, -1 means accept log which has user code(nonzero)
  785. * @param bIgnoreMessage if true then pszMessage will not be send to save bandwidth
  786. */
  787. virtual ErrorCodeEnum SubscribeLog(CUUID& SubscribeID, ILogListener* pListener, LogTypeEnum eLogType = Log_Ignore, SeverityLevelEnum eLevel = Severity_None,
  788. ErrorCodeEnum eSysError = Error_IgnoreAll, DWORD dwUserCode = 0, const char* pszEntityName = NULL, bool bIgnoreMessage = true) = 0;
  789. virtual ErrorCodeEnum UnsubscribeLog(CUUID SubscribeID) = 0;
  790. /** force shell to dump a log file */
  791. virtual ErrorCodeEnum FlushLogFile() = 0;
  792. /**
  793. * read persist object from framework's serialize directory
  794. * @param pszClass which class the object belongs
  795. * @param pszKey the object key, key is case-sensitive!!!
  796. * note: actually this object stores at dir %syspath%/Objects/<EntityName>/pszClass/pszKey
  797. * so pszClass and pszKey cannot contains chars which os file path specification forbidden, such as *, ?
  798. */
  799. virtual ErrorCodeEnum ReadPersistObject(const char* pszClass, const char* pszKey, IEntityPersistObject* pInstance) = 0;
  800. /** write persist object to framework's serialize directory */
  801. virtual ErrorCodeEnum WritePersistObject(const char* pszClass, const char* pszKey, const IEntityPersistObject* pInstance) = 0;
  802. /** get the number of persist object */
  803. virtual ErrorCodeEnum ReadNumOfPersistObject(const char* pClassName, DWORD& dwNum) = 0;
  804. /** get class all objects keys */
  805. virtual ErrorCodeEnum GetPersistClassObjectKeys(const char* pClassName, CAutoArray<CSimpleStringA>& strKeys) = 0;
  806. /** delete persist object */
  807. virtual ErrorCodeEnum DeleteKeyOfPersistObject(const char* pClassName, const char* pszKey) = 0;
  808. /** walk through class objects of pClassName, Handle=0 find from beginning */
  809. virtual ErrorCodeEnum EnumKeyOfPersistObject(const char* pClassName, CSimpleStringA& strKey, DWORD& dwHandle) = 0;
  810. /** delete all persist object of class pClassName */
  811. virtual ErrorCodeEnum CleanAllOfPersistObject(const char* pClassName) = 0;
  812. /**
  813. * do async connect to remote entity service, after connected, then pClientSession->Onconnected will call
  814. * note: if return succeed, pClientSession will delete by system via OnDestroy
  815. * if return failed, pCilentSession need delete by user
  816. */
  817. virtual ErrorCodeEnum ConnectRemoteEntity(CClientSessionBase* pClientSession,
  818. const char* pszRemoteEntity,
  819. const char* pszParam,
  820. CSmartPointer<IAsynWaitSp>& pAsynWaitSp) = 0;
  821. /**redirect as bridged mode*/
  822. virtual ErrorCodeEnum RedirectSession(CClientSessionBase* pClientSession) = 0;
  823. /**redirect when accepted*/
  824. virtual ErrorCodeEnum RedirectSession(const char* pszSuggestEntity) = 0;
  825. /** redirect subscribe broadcast */
  826. virtual ErrorCodeEnum RedirectSubscribBroadcast(CUUID SubID, const char* pszSugguestEntity) = 0;
  827. /**
  828. * if entity want to close self, call this function to notify shell service,
  829. * then shell service will issue close command
  830. */
  831. virtual ErrorCodeEnum PostQuit() = 0;
  832. /**
  833. * Reload itself entity
  834. */
  835. virtual ErrorCodeEnum PostReload() = 0;
  836. virtual ErrorCodeEnum SetSelfPriority(EntityPriorityEnum nPriority) = 0;
  837. virtual ErrorCodeEnum GetSelfPriority(EntityPriorityEnum& nPriority) = 0;
  838. /**
  839. * timer functions, setup an periodic timer
  840. * @param nTimerID user defined ID, must unique in entity scope
  841. * @param pListener user override callback
  842. * @param dwInterval timer interval
  843. */
  844. virtual ErrorCodeEnum SetTimer(DWORD dwTimerID, ITimerListener* pListener, DWORD dwInterval) = 0;
  845. virtual ErrorCodeEnum SetTimerData(DWORD dwTimerID, IReleasable* pData) = 0;
  846. virtual ErrorCodeEnum GetTimerData(DWORD dwTimerID, CSmartPointer<IReleasable>& pData) = 0;
  847. /*if dwTimerID=0 mean kill all Timer*/
  848. virtual ErrorCodeEnum KillTimer(DWORD dwTimerID) = 0;
  849. virtual ErrorCodeEnum ResetTimer(DWORD dwTimerID, DWORD dwInterval) = 0;
  850. virtual ErrorCodeEnum GetTimerInterval(DWORD dwTimerID, DWORD& dwInterval) = 0;
  851. /** query whether this entity has privilege ? */
  852. virtual bool HasPrivilege() = 0;
  853. /** get privilege pointer */
  854. virtual CSmartPointer<IEntityFunctionPrivilege> GetPrivilegeFunction() = 0;
  855. /** setup log for current thread(for user created thread) */
  856. virtual ErrorCodeEnum InitLogCurrentThread() = 0;
  857. /**
  858. * start tcp bridge server at ip:port
  859. * note: mainly for silverlight usage
  860. * currently: silverlight only can use port range (4502-4506)
  861. * we provide silverlight policy server(tcp 943) at spshell.exe
  862. */
  863. virtual ErrorCodeEnum StartTcpBridgeServer(unsigned short port) = 0;
  864. virtual ErrorCodeEnum StopTcpBridgeServer() = 0;
  865. //virtual void SetPostLinkFun(postLink cur) = 0;
  866. /**
  867. * post Task to entity's thread
  868. * FIFO(first in first out) queue tail, LIFO(last in first out)
  869. * queue head
  870. */
  871. virtual ErrorCodeEnum PostEntityTaskFIFO(ITaskSp* pTask) = 0;
  872. virtual ErrorCodeEnum PostEntityTaskLIFO(ITaskSp* pTask) = 0;
  873. /**
  874. * post task to thread pool
  875. */
  876. virtual ErrorCodeEnum PostThreadPoolTask(ITaskSp* pTask) = 0;
  877. /** request framework to delay closing */
  878. virtual ErrorCodeEnum RequestCloseDelay(WORD nSecond) = 0;
  879. /** log along with params */
  880. virtual void SendLog(const LogTypeEnum eLogType, const SeverityLevelEnum eLevel, DWORD dwUserEventCode, CAutoArray<DWORD> Param, const char* pszMessage = NULL) = 0;
  881. /*verify file code signature, if pass, strErrInfo is sign cert hash, else verify error info*/
  882. virtual ErrorCodeEnum VerifySignature(const char* pszSignedFile, CSimpleStringA& strErrInfo) = 0;
  883. /*show fatal error info when framework startup*/
  884. virtual ErrorCodeEnum ShowFatalError(const char *pszMsg, SeverityLevelEnum eLevel = Severity_None) = 0;
  885. /*show important startup info when framework startup*/
  886. virtual ErrorCodeEnum ShowStartupInfo(const char *pszMsg) = 0;
  887. virtual ErrorCodeEnum GetEntityLastError(const char* pszEntityName, CEntityLastErrorInfo& errInfo) = 0;
  888. virtual void ResetEntityLastError() = 0;
  889. virtual ErrorCodeEnum GetToken(CSimpleString& channelId, CSimpleString& token) = 0;
  890. /* GetRunningVersion
  891. currently return version in active.txt, may be it will return the version from micro sever latter.
  892. */
  893. virtual ErrorCodeEnum GetRunningVersion(CSimpleString& ver) = 0;
  894. virtual ErrorCodeEnum GetVTMErrMsg(DWORD dwUserCode, CSimpleStringA& strDescription, CSimpleStringA& strVTMCode) = 0;
  895. };
  896. class VTMInitParam{
  897. public:
  898. CSimpleString terminalNo;
  899. CSimpleString channelId;
  900. CSimpleString tokenSecret;
  901. CSimpleString CommonLaunchUrl;
  902. CSimpleString CenterConfigTotal;
  903. VTMInitParam(const char *terminal, const char* channel, const char* token,
  904. const char* launchUrl, const char* configTotal)
  905. : terminalNo(terminal), channelId(channel), tokenSecret(token),
  906. CommonLaunchUrl(launchUrl), CenterConfigTotal(configTotal) {}
  907. };
  908. class MemCfgParam {
  909. public:
  910. CSimpleString configType; //"centersetting", "root", "shell"
  911. CSimpleString module;
  912. CSimpleString name;
  913. CSimpleString value;
  914. MemCfgParam(const char* type, const char* mod, const char* n, const char* val)
  915. : configType(type), module(mod), name(n), value(val) {}
  916. };
  917. /** normal entity no need to use this interface, use for update, health management, etc. */
  918. struct IEntityFunctionPrivilege
  919. {
  920. virtual ~IEntityFunctionPrivilege() {}
  921. /*upate terminal current state*/
  922. virtual ErrorCodeEnum RefreshFrameworkState(FrameworkStateEnum eState) = 0;
  923. /** get %SysRoot%\Ver\<version> 's config info */
  924. virtual ErrorCodeEnum GetSystemStaticInfoForVersion(CVersion verSoftware, CSystemStaticInfo& StaticInfo) = 0;
  925. /** start a remote entity,if restart itself only been call in OnClose event,will ignore pAsynWaitSp,and will not wait*/
  926. virtual ErrorCodeEnum StartEntity(const char* pszEntityName, const char* pszCmdLine, CSmartPointer<IAsynWaitSp>& pAsynWaitSp) = 0;
  927. /** close entity ,not use consultative mechanism */
  928. virtual ErrorCodeEnum StopEntity(const char* pszEntityName, CSmartPointer<IAsynWaitSp>& pAsynWaitSp) = 0;
  929. /** require entity close and can use the consultative mechanisms */
  930. virtual ErrorCodeEnum CloseEntity(const char* pszEntityName, CSmartPointer<IAsynWaitSp>& pAsynWaitSp) = 0;
  931. /** terminate entity forcefully */
  932. virtual ErrorCodeEnum TerminateEntity(const char* pszEntityName, CSmartPointer<IAsynWaitSp>& pAsynWaitSp) = 0;
  933. /** pause entity */
  934. virtual ErrorCodeEnum PauseEntity(const char* pszEntityName, CSmartPointer<IAsynWaitSp>& pAsynWaitSp) = 0;
  935. /** continue entity from paused state */
  936. virtual ErrorCodeEnum ContinueEntity(const char* pszEntityName, CSmartPointer<IAsynWaitSp>& pAsynWaitSp) = 0;
  937. /** test whether entity state ok, a simple health-checking mechanism */
  938. virtual ErrorCodeEnum TestEntity(const char* pszEntityName, EntityTestEnum eTestType, CSmartPointer<IAsynWaitSp>& pAsynWaitSp) = 0;
  939. /** register entity life event */
  940. virtual ErrorCodeEnum RegistEntityLifeEvent(IEntityLifeListener* pListener) = 0;
  941. virtual ErrorCodeEnum UnregistLiftEvent() = 0;
  942. /** register entity state event, when entity state changes, callback will be invoked */
  943. virtual ErrorCodeEnum RegistEntityStateEvent(const char* pszEntityName, IEntityStateListener* pListener) = 0;
  944. /*If pszEntityName=NULL mean unregist all entity event*/
  945. virtual ErrorCodeEnum UnregistEntityStateEvent(const char *pszEntityName)=0;
  946. virtual ErrorCodeEnum GetSpecifiedEntityState(const char* pszEntityName, EntityStateEnum &eEntityState, DWORD& dwUserState) = 0;
  947. /** trigger reboot framework/machine */
  948. virtual ErrorCodeEnum Reboot(RebootTriggerEnum eTriggerReason, RebootWayEnum eWay) = 0;
  949. /** show blue full-screen title, for example for system error, privilege */
  950. virtual ErrorCodeEnum DisplayBlueScreen(const char* pszTitle) = 0;
  951. /** hide blue screen */
  952. virtual ErrorCodeEnum UndisplayBlueScreen() = 0;
  953. /** Install in current version and path*/
  954. virtual ErrorCodeEnum BeginLightInstall(const char* pszPackageName) = 0;
  955. virtual ErrorCodeEnum GenerateNewInstallCfg() = 0;
  956. //virtual ErrorCodeEnum SetUpdateSourcePath(const char *pszSourcePath)=0;
  957. /** Copy from [Temp]\[pszPackageName]\[pszRelativeFile] to install path,
  958. 1(copy only exisit); 2(copy only not exist); 3(copy always); 4(no copy if exist)*/
  959. virtual ErrorCodeEnum CopyFileToNewVersion(const char* pszRelativeFile, int nCopyMode) = 0;
  960. /** pszRelativeName is in run path*/
  961. virtual ErrorCodeEnum DeleteFileInNewVersion(const char* pszRelativeName) = 0;
  962. /** Set startup shell to last version shell,but not trigger to restart.next restart will run in last version path.*/
  963. virtual ErrorCodeEnum RollBackToPreviousVersion() = 0;
  964. virtual ErrorCodeEnum RollBackToHistoryVersion(CVersion HistoryVersion) = 0;
  965. /** Set startup shell to new version shell,next restart will run in new version path
  966. if bToSysInstall=true the SpShell.exe will not startup first,waiting Guardian.exe running install over,and started up by Guardian.exe*/
  967. virtual ErrorCodeEnum UpgradeToNewVersion(bool bToSysInstall) = 0;
  968. /**If the update or rollback version succeed run, info the framework this version is ok*/
  969. virtual ErrorCodeEnum SetRunSucceed() = 0;
  970. /**check if the pack has been installed*/
  971. virtual ErrorCodeEnum IsPackInstalled(const char* pszPackName, bool& bInstalled) = 0;
  972. /** os pack upgrade, run.ini has ToRun define */
  973. virtual ErrorCodeEnum BeginSysPackInstall(const char* pszPackageName, CSimpleStringA& strErrMsg) = 0;
  974. /**check if the syspack has been installed*/
  975. virtual ErrorCodeEnum IsInstalledSysPack(const char* pszPackageName) = 0;
  976. /** show system running output console, including all entity's syslog */
  977. virtual ErrorCodeEnum ShowOuputConsole() = 0;
  978. /**close output console */
  979. virtual ErrorCodeEnum CloseOuputConsole() = 0;
  980. /*Sets the scheduling priority of the process specified by entity name*/
  981. virtual ErrorCodeEnum SetEntityPriority(const char* pszEntityName, EntityPriorityEnum nPriority) = 0;
  982. virtual ErrorCodeEnum GetEntityPriority(const char* pszEntityName, EntityPriorityEnum& nPriority) = 0;
  983. /*begin log sender*/
  984. virtual ErrorCodeEnum BeginLogSend(const char* endpoint, const char* topicSys, const char* topicUser, const char* topicBeidou, const char* bussSys, const char* bussUser) = 0;
  985. /*update token*/
  986. virtual ErrorCodeEnum SetHttpToken(const char* channelId, const char* token) = 0;
  987. virtual void GetSendLogInfo(unsigned long* t_upload_TerminalSys_Suc, unsigned long* t_upload_TerminalUser_Suc,
  988. unsigned long* t_upload_BussinessSys_Suc, unsigned long* t_upload_BussinessUser_Suc, unsigned long* t_upload_beidou_Suc,
  989. unsigned long* t_upload_TerminalSys_Err, unsigned long* t_upload_TerminalUser_Err,
  990. unsigned long* t_upload_BussinessSys_Err, unsigned long* t_upload_BussinessUser_Err, unsigned long* t_upload_beidou_Err) = 0;
  991. //replace params with VTMInitParam; if one param in VTMInitParam equals to "", it will not replace to old value
  992. virtual ErrorCodeEnum InitCfgUrl(VTMInitParam &info) = 0;
  993. virtual ErrorCodeEnum TryUpdateCfg() = 0;
  994. virtual ErrorCodeEnum TryUpdateCenterCfg(bool& isUpdate, bool& isReset, CSimpleString& version) = 0;
  995. virtual ErrorCodeEnum TryUpdateToken(CSimpleString& oldToken, CSimpleString& newToken) = 0;
  996. virtual ErrorCodeEnum GetToken(CSimpleString& curToken) = 0;
  997. virtual ErrorCodeEnum WriteTerminalNoToRootIni(CSimpleString terminalNo) = 0;
  998. virtual ErrorCodeEnum ModifyMemCfgParam(MemCfgParam& info) = 0;
  999. virtual ErrorCodeEnum TryUpdateVTMERRMSG() = 0;
  1000. virtual ErrorCodeEnum GetVTMErrMsgArr(CAutoArray<CSimpleStringA>& strErrorCodeArr,
  1001. CAutoArray<CSimpleStringA>& strDescriptionArr, CAutoArray<CSimpleStringA>& strRemarkArr) = 0;
  1002. };
  1003. /**
  1004. * service entity side transaction, we define call in two types:
  1005. * 1) one way call, client send one way call packet, need no reply from server side
  1006. * 2) two way call, client send request and server response
  1007. * A transaction is a call context hosted by server entity, when one client
  1008. * issues a call, at server entity side, compose a Transaction context object.
  1009. */
  1010. struct ITransactionContext
  1011. {
  1012. virtual ~ITransactionContext() {};
  1013. /** decide whether client call is one way call */
  1014. virtual bool IsOneWayCall() = 0;
  1015. /** get request sequence id */
  1016. virtual DWORD GetRequestID() = 0;
  1017. /** get client buffer */
  1018. virtual ErrorCodeEnum GetReceiveBuffer(DWORD& dwMessageID, DWORD& dwMessageSignature, CAutoBuffer& Buffer) = 0;
  1019. /** send out response to client, only use in two way call scenario */
  1020. virtual ErrorCodeEnum SendAnswer(CAutoBuffer Buffer, bool bEnd = true) = 0;
  1021. /** send out response to client without buffer, this is the simplist case for the above one
  1022. * 20160914: support return custom error: @dwUserError
  1023. */
  1024. virtual ErrorCodeEnum SendAnswer(ErrorCodeEnum eErrorCode, DWORD dwUserError = 0, CSimpleString str = "") = 0;
  1025. /** set response expired timeout value, in milliseconds */
  1026. virtual ErrorCodeEnum SetExpireTime(DWORD dwMS) = 0;
  1027. /** get this run process expire time left value, in milliseconds */
  1028. virtual ErrorCodeEnum GetExpireTime(DWORD& dwWholeTime, DWORD& dwLeftTime) = 0;
  1029. virtual ErrorCodeEnum GetLinkContext(linkContext& curLink) = 0;
  1030. };
  1031. /** The Module entity must implement the interface */
  1032. class CEntityBase
  1033. {
  1034. public:
  1035. CEntityBase():m_pEntityFunction(nullptr) {}
  1036. virtual ~CEntityBase() { if(m_pEntityFunction != nullptr) delete m_pEntityFunction; }
  1037. /** get entity service function */
  1038. virtual CSmartPointer<IEntityFunction> GetFunction() { return m_pEntityFunction; }
  1039. #ifdef RVC_OS_WIN
  1040. #if (!defined(SPABASE_LINKED_AS_STATIC_LIBRARY) && !defined(SPBASE_EXPORTS))
  1041. protected:
  1042. #endif
  1043. #endif //RVC_OS_WIN
  1044. /**
  1045. * invoked when entity is being start, when starting operation finished user must call FinishStart
  1046. * so the starting operation has prepared, then spbase.dll invokes OnStart
  1047. */
  1048. virtual void OnPreStart(CAutoArray<CSimpleStringA> strArgs, CSmartPointer<ITransactionContext> pTransactionContext) { pTransactionContext->SendAnswer(Error_Succeed); }
  1049. virtual void OnStarted() {}
  1050. /** invoked when entity pause */
  1051. virtual void OnPrePause(CSmartPointer<ITransactionContext> pTransactionContext) { pTransactionContext->SendAnswer(Error_Succeed); }
  1052. virtual void OnPaused() {}
  1053. /** invoked when entity continue */
  1054. virtual void OnPreContinue(CSmartPointer<ITransactionContext> pTransactionContext) { pTransactionContext->SendAnswer(Error_Succeed); }
  1055. virtual void OnContinued() {}
  1056. /** invoked when entity will be closed*/
  1057. virtual void OnPreClose(EntityCloseCauseEnum eCloseCause, CSmartPointer<ITransactionContext> pTransactionContext) { pTransactionContext->SendAnswer(Error_Succeed); }
  1058. /** user override this, so it is able to extend some complicated health-checking method */
  1059. virtual void OnSelfTest(EntityTestEnum eTestType, CSmartPointer<ITransactionContext> pTransactionContext) { pTransactionContext->SendAnswer(Error_Succeed); }
  1060. /*!
  1061. * [Gifur@2020519]
  1062. * override OnSelfTest with speicified EntityTestEnum::Test_Examine
  1063. */
  1064. virtual void OnExam(CSmartPointer<ITransactionContext> pTransactionContext) { pTransactionContext->SendAnswer(Error_NotImpl); }
  1065. /** invoked when incoming new connection user can RedirectSession in OnNewSession*/
  1066. virtual CServerSessionBase *OnNewSession(const char* /*pszRemoteEntityName*/, const char * /*pszParam*/){return NULL;}
  1067. /**
  1068. * if you want to redirection please override this function
  1069. * and invoke IEntityFunciton::RedirectSubscribeBroadcast
  1070. */
  1071. virtual void OnBroadcastSubscribe(CUUID /*SubID*/, const char* /*pszFromEntityName*/, const char* /*pszParam*/) { }
  1072. public:
  1073. /** get this entity name */
  1074. virtual const char* GetEntityName()const = 0;
  1075. /** get this entity version*/
  1076. virtual const char* GetEntityVersion() const { return MODULE_VERSION_FULL; }
  1077. /** is this entity hosts service ? */
  1078. virtual bool IsService()const{return false;}
  1079. #ifdef RVC_OS_WIN
  1080. #if (!defined(SPABASE_LINKED_AS_STATIC_LIBRARY) && !defined(SPBASE_EXPORTS))
  1081. private:
  1082. #endif
  1083. #endif //RVC_OS_WIN
  1084. /** dont access directly because of inner usage */
  1085. IEntityFunction* m_pEntityFunction;
  1086. };
  1087. /** server session service */
  1088. struct IServerSessionFunction
  1089. {
  1090. virtual ~IServerSessionFunction() {}
  1091. /** get client entity name */
  1092. virtual const char* GetRemoteEntityName() = 0;
  1093. /** get current state of this session */
  1094. virtual SessionStateEnum GetCurrentState() = 0;
  1095. /** close session */
  1096. virtual ErrorCodeEnum CloseSession() = 0;
  1097. };
  1098. /** server service stub, service entity must inherits and implements from here */
  1099. class CServerSessionBase
  1100. {
  1101. public:
  1102. CServerSessionBase() {}
  1103. virtual ~CServerSessionBase() { delete m_pSessionFunction; }
  1104. /** get function pointer */
  1105. CSmartPointer<IServerSessionFunction> GetFunction() { return m_pSessionFunction; }
  1106. #ifdef RVC_OS_WIN
  1107. #if (!defined(SPABASE_LINKED_AS_STATIC_LIBRARY) && !defined(SPBASE_EXPORTS))
  1108. protected:
  1109. #endif
  1110. #endif //RVC_OS_WIN
  1111. /** invoked when receives request from client */
  1112. virtual void OnRequest(CSmartPointer<ITransactionContext> pTransactionContext) = 0;
  1113. /** invoked when peer closed or network failed */
  1114. virtual void OnClose(ErrorCodeEnum eErrorCode) {}
  1115. /** The same client entity can recall a function before the last call return */
  1116. virtual bool IsSessionOverlap() { return true; }
  1117. /** server message id is overlapped ? */
  1118. virtual ErrorCodeEnum GetMessageAttr(DWORD dwMessageID, DWORD dwSignature, bool& bOverlap) = 0;
  1119. /** is exclusive ? */
  1120. virtual bool IsExclusive() { return false; }
  1121. #ifdef RVC_OS_WIN
  1122. #if (!defined(SPABASE_LINKED_AS_STATIC_LIBRARY) && !defined(SPBASE_EXPORTS))
  1123. private:
  1124. #endif
  1125. #endif //RVC_OS_WIN
  1126. /** dont access directly because of inner usage */
  1127. IServerSessionFunction* m_pSessionFunction;
  1128. };
  1129. /**
  1130. * design for supporting async request, each request in client side is named a async wait sp
  1131. * note: for two way call only
  1132. */
  1133. struct IAsynWaitSp :public IReleasable
  1134. {
  1135. /**Get Caller function name string */
  1136. virtual const char* GetFuctionName() = 0;
  1137. virtual ErrorCodeEnum GetExpireTime(DWORD& dwWholeTime, DWORD& dwLeftTime) = 0;
  1138. /** wait for remote to answer */
  1139. virtual ErrorCodeEnum WaitAnswer(DWORD dwTimeout = INFINITE) = 0;
  1140. /** cancel the pending call */
  1141. virtual ErrorCodeEnum CancelWait() = 0;
  1142. /** decide whether operation is doing */
  1143. virtual bool IsPending() = 0;
  1144. /** get request message id */
  1145. virtual DWORD GetMessageID() = 0;
  1146. /**
  1147. * when request has finished, call this method to fetch remote buffer
  1148. * @param ReceivedBuffer get service side sent out buffer, can be zero length
  1149. * @param bEnd the last response message received, this indicator support multiple return responses
  1150. */
  1151. virtual ErrorCodeEnum AsyncGetAnswer(CAutoBuffer& ReceiveBuffer, bool& bEnd) = 0;
  1152. /**just get the result code */
  1153. virtual ErrorCodeEnum AsyncGetAnswer()=0;
  1154. virtual ErrorCodeEnum AsyncGetAnswer(DWORD& dwUserError) = 0;
  1155. /**get the result code and user code*/
  1156. virtual ErrorCodeEnum AsyncGetAnswer(DWORD& dwUserError, CSimpleString& str) = 0;
  1157. virtual CSmartPointer<IReleasable> GetCallContext() = 0;
  1158. virtual bool GetCallback(CSmartPointer<ICallbackListener>& pCallback, CSmartPointer<IReleasable>& pContext) = 0;
  1159. /** set callback on, default is off(blocking). The context object inherit IReleasable and must rewrite deconstruction to release temp object*/
  1160. virtual void SetCallback(ICallbackListener* pCallback, IReleasable* pContext = NULL) = 0;
  1161. /** wait for remote to answer
  1162. * @param dwUserError entity custom error code
  1163. */
  1164. virtual ErrorCodeEnum WaitAnswer(DWORD& dwUserError, CSimpleString& str, DWORD dwTimeout) = 0;
  1165. /**
  1166. * when request has finished, call this method to fetch remote buffer
  1167. * @param ReceivedBuffer get service side sent out buffer, can be zero length
  1168. * @param bEnd the last response message received, this indicator support multiple return responses
  1169. * @param dwUserError entity custom error code
  1170. */
  1171. virtual ErrorCodeEnum AsyncGetAnswer(CAutoBuffer& ReceiveBuffer, bool& bEnd, DWORD& dwUserError, CSimpleString& str) = 0;
  1172. };
  1173. /** wait for multi IAsynWaitSp */
  1174. SPBASE_API ErrorCodeEnum WaitMultiAnswers(CAutoArray<IAsynWaitSp*> arrAsynWaits, DWORD& dwRetIndex, bool bWaitAll = false, DWORD dwTimeOut = 0);
  1175. /** client session */
  1176. struct IClientSessionFunction :public IReleasable
  1177. {
  1178. /** one way call with buffer */
  1179. virtual ErrorCodeEnum OnewayCall(DWORD dwMessageID, DWORD dwMessageSignature, CAutoBuffer Buffer) = 0;
  1180. /** one way call */
  1181. virtual ErrorCodeEnum OnewayCall(DWORD dwMessageID, DWORD dwMessageSignature) = 0;
  1182. //one way withContext
  1183. virtual ErrorCodeEnum OnewayCall(DWORD dwMessageID, DWORD dwMessageSignature, CAutoBuffer Buffer, linkContext& pContext) = 0;
  1184. virtual ErrorCodeEnum OnewayCall(DWORD dwMessageID, DWORD dwMessageSignature, linkContext& pContext) = 0;
  1185. /**
  1186. * two way call with buffer
  1187. * @param nMessageID [in] application defined message id
  1188. * @param Buffer [in] application defined buffer data
  1189. * @param pAsynWaitSp [out], required
  1190. * @param dwTimeOut [in],option,default used system 's timeout constant
  1191. */
  1192. virtual ErrorCodeEnum AsyncRequest(DWORD dwMessageID, DWORD dwMessageSignature, CAutoBuffer Buffer, CSmartPointer<IAsynWaitSp>& pAsynWaitSp, DWORD dwTimeOut = 0, DWORD dwReqId = -1) = 0;
  1193. //with linkContext
  1194. virtual ErrorCodeEnum AsyncRequest(DWORD dwMessageID, DWORD dwMessageSignature, CAutoBuffer Buffer, CSmartPointer<IAsynWaitSp>& pAsynWaitSp, linkContext& pContext, DWORD dwTimeOut = 0, DWORD dwReqId = -1) = 0;
  1195. virtual ErrorCodeEnum AsyncRequest(DWORD dwMessageID, DWORD dwMessageSignature, CSmartPointer<IAsynWaitSp>& pAsynWaitSp, linkContext& pContext, DWORD dwTimeOut = 0, DWORD dwReqId = -1) = 0;
  1196. /** call without buffer */
  1197. virtual ErrorCodeEnum AsyncRequest(DWORD dwMessageID, DWORD dwMessageSignature, CSmartPointer<IAsynWaitSp>& pAsynWaitSp, DWORD dwTimeOut = 0, DWORD dwReqId = -1) = 0;
  1198. /** get peer entity name */
  1199. virtual const char* GetRemoteEntityName() = 0;
  1200. /** get current state */
  1201. virtual SessionStateEnum GetCurrentState() = 0;
  1202. /** close session */
  1203. virtual ErrorCodeEnum CloseSession() = 0;
  1204. };
  1205. /** client must implement this */
  1206. class SPBASE_API CClientSessionBase
  1207. {
  1208. public:
  1209. CClientSessionBase() : m_pSessionFunction(NULL) {}
  1210. virtual ~CClientSessionBase();
  1211. CSmartPointer<IClientSessionFunction> GetFunction() { return m_pSessionFunction; }
  1212. /** invoked when connected ok, in async mode */
  1213. virtual void OnConnectSucceed() {}
  1214. /** invoked when peer closed or network failed */
  1215. virtual void OnClose(ErrorCodeEnum /*eErrorCode*/) {}
  1216. /** invoke when delete the object */
  1217. virtual void OnDestroy() { delete this; }
  1218. #ifdef RVC_OS_WIN
  1219. #if (!defined(SPABASE_LINKED_AS_STATIC_LIBRARY) && !defined(SPBASE_EXPORTS))
  1220. private:
  1221. #else
  1222. public:
  1223. #endif
  1224. #else
  1225. public:
  1226. #endif //RVC_OS_WIN
  1227. IClientSessionFunction* m_pSessionFunction;
  1228. };
  1229. /** user module must inherit from ModuleBase */
  1230. class SPBASE_API ModuleBase
  1231. {
  1232. public:
  1233. ModuleBase();
  1234. virtual ~ModuleBase();
  1235. virtual ErrorCodeEnum Init();
  1236. virtual ErrorCodeEnum Exit();
  1237. virtual BOOL DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved);
  1238. HINSTANCE GetInstance() { return m_hInstance; }
  1239. static ModuleBase* GetModuleBase();
  1240. protected:
  1241. /** register your entity via this method to framework */
  1242. ErrorCodeEnum RegistEntity(CEntityBase *pEntity);
  1243. ErrorCodeEnum UnregistEntity(CEntityBase *pEntity);
  1244. ErrorCodeEnum GetRegistEntity(const char *pszEntityName,CSmartPointer<CEntityBase> &pEntity);
  1245. #ifdef RVC_OS_WIN
  1246. #if (!defined(SPABASE_LINKED_AS_STATIC_LIBRARY) && !defined(SPBASE_EXPORTS))
  1247. protected:
  1248. #else
  1249. public:
  1250. #endif
  1251. #else
  1252. public:
  1253. #endif //RVC_OS_WIN
  1254. int m_nEntityCount;
  1255. CEntityBase* m_pEntityArray[32];
  1256. static ModuleBase* s_pModuleInst;
  1257. HINSTANCE m_hInstance;
  1258. };
  1259. #define SP_BEGIN_ENTITY_MAP() \
  1260. class SpEntityModuleStub : public ModuleBase \
  1261. { \
  1262. public: \
  1263. SpEntityModuleStub() \
  1264. {
  1265. #define SP_ENTITY(cls) \
  1266. m_pEntityArray[m_nEntityCount++] = dynamic_cast<CEntityBase*>(new cls());
  1267. #ifdef RVC_OS_WIN
  1268. #define SP_END_ENTITY_MAP() \
  1269. } \
  1270. }; \
  1271. SpEntityModuleStub g_ModuleInst; \
  1272. extern "C" BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) \
  1273. { \
  1274. return g_ModuleInst.DllMain(hInstance, dwReason, lpReserved); \
  1275. }
  1276. #else // RVC_OS_WIN
  1277. #define SP_END_ENTITY_MAP() \
  1278. } \
  1279. }; \
  1280. SpEntityModuleStub g_ModuleInst; \
  1281. extern "C" void __attribute__((constructor)) SoMain() {\
  1282. g_ModuleInst.DllMain(NULL, DLL_PROCESS_ATTACH, NULL); \
  1283. }
  1284. /*
  1285. extern "C" void __attribute__((constructor)) SoEnd() {
  1286. DllMain(NULL, DLL_PROCESS_DETACH, NULL);
  1287. }
  1288. */
  1289. #endif // RVC_OS_WIN
  1290. #include "log_define.h"
  1291. class SPBASE_API DbgToBeidou {
  1292. public:
  1293. DbgToBeidou(const linkContext& t_context, CSimpleStringA t_Api);//link, //当前调用的API
  1294. ~DbgToBeidou();
  1295. DbgToBeidou& setHost(CSimpleStringA t_host);//请求链接地址
  1296. DbgToBeidou& setReturnCode(CSimpleStringA t_returncode);
  1297. DbgToBeidou& setResponseTime(CSimpleStringA t_responseTime);
  1298. DbgToBeidou& setCallStack(CSimpleStringA t_callStack);//调用堆栈,格式("callStack":[{“xxx”:"xx","xxxx":sdfs}])
  1299. DbgToBeidou& setDbStack(CSimpleStringA t_dbStack);//格式("dbStack":[{“xxxxx”:"xxdfsdfs","xxddddxx":sdsddsdfs}])
  1300. DbgToBeidou& setTags(CSimpleStringA t_Tags);
  1301. DbgToBeidou& withLogProducer(void* t_logProducer);
  1302. void operator () () const;
  1303. private:
  1304. class Beidou_private;
  1305. Beidou_private* const m_priPtr;
  1306. char CharZero[2];
  1307. private:
  1308. DbgToBeidou(const DbgToBeidou&) : m_priPtr(NULL) {};
  1309. const DbgToBeidou& operator=(const DbgToBeidou&) { return *this; };
  1310. };
  1311. class SPBASE_API DbgWithLink {
  1312. public:
  1313. DbgWithLink(LOG_LEVEL_E t_level, LOG_TYPE_E t_type);
  1314. ~DbgWithLink();
  1315. //用户、系统日志均必填,交易处理结果代码,0表示处理成功,其他表示失败,可为系统本身的错误码,也可为后台系统返回的错误码
  1316. DbgWithLink& setResultCode(CSimpleStringA t_ResultCode);
  1317. //用户、系统日志均必填,业务跟踪ID, 32字节长度的字符串,唯一识别每笔请求
  1318. DbgWithLink& setTraceID(CSimpleStringA t_TraceID);
  1319. //用户、系统日志LOG_LEVEL_WARN以上必填
  1320. //交易处理结果信息,包括成功与失败信息,可为系统本身的成功/失败信息,也可为后台系统返回的成功/失败信息.
  1321. DbgWithLink& setResultMsg(CSimpleStringA t_ResultMsg);
  1322. //用户日志必填,日志码
  1323. //终端中标识各个交易如读卡、读取身份证等。如果终端由于客观原因无法识别交易场景,则可字段由上游传入。
  1324. DbgWithLink& setLogCode(CSimpleStringA t_LogCode);
  1325. DbgWithLink& setAPI(CSimpleStringA t_API);//用户日志必填,请求路径/接口名称.
  1326. DbgWithLink& setBussID(CSimpleStringA t_BussID);//用户日志必填,请求业务ID
  1327. DbgWithLink& setTipMsg(CSimpleStringA t_TipMsg);//用户日志LOG_LEVEL_WARN以上必填,直接向客户展示的报错信息.
  1328. DbgWithLink& setSourceType(CSimpleStringA t_SourceType);//系统日志LOG_LEVEL_FATAL必填,异常来源类型
  1329. DbgWithLink& setBeginTime(long t_BeginTime);//用户日志必填, 请求发送/接收时间
  1330. DbgWithLink& setEndTime(long t_EndTime);//用户日志必填, 响应接收 / 应答时间
  1331. DbgWithLink& setCostTime(long t_costTime);//消耗时间,自定义字段,单位ms
  1332. DbgWithLink& setVtmCode(CSimpleStringA t_VtmCode);//VtmCode,记录原告警
  1333. DbgWithLink& withLogProducer(void* t_logProducer);
  1334. DbgWithLink& withExtendLog(bool t_doLog);//是否log到文件中,并行阶段需要log到文件
  1335. void operator () (const char* str, ...) const;
  1336. void operator () () const;
  1337. private:
  1338. class Link_private;
  1339. Link_private* const m_priPtr;
  1340. private:
  1341. DbgWithLink(const DbgWithLink&) : m_priPtr(NULL) {};
  1342. const DbgWithLink& operator=(const DbgWithLink&) { return *this; };
  1343. };
  1344. class SPBASE_API EntityResource {
  1345. public:
  1346. static void setLink(const linkContext& cur);
  1347. static const linkContext& getLink();
  1348. static void clearLink();
  1349. static void setSaveFile(int t_saveFile) { m_saveFile = t_saveFile; };
  1350. static int getSaveFile() { return m_saveFile; };
  1351. private:
  1352. static linkContext m_link;
  1353. static int m_saveFile;
  1354. };
  1355. //创建日志存储模块,通常由sphost自动创建,不需要实体创建
  1356. SPBASE_API void* create_log_producer_storage(CSimpleStringA entityName, CSimpleStringA item, CSimpleStringA filePath);
  1357. SPBASE_API void destroy_log_producer_storage(void* obj);
  1358. //创建日志上传模块,通常由spshell自动创建,然后上传
  1359. SPBASE_API void* create_log_producer_send(CSimpleStringA endpoint, CSimpleStringA topicSys, CSimpleStringA topicUser, CSimpleStringA topicBeidou, CSimpleStringA bussinessSys, CSimpleStringA bussinessUser,
  1360. CSimpleStringA terminalNo, CSimpleStringA sn, CSimpleStringA filePath, int sendWaitTime);
  1361. SPBASE_API void destroy_log_producer_send();
  1362. //创建实体日志默认上传模块, SpShell 和 SpRun 中调用,内部调用 create_log_producer_storage
  1363. SPBASE_API bool create_log_producer_default(CSimpleStringA entityName, int idx);
  1364. SPBASE_API void destroy_log_producer_default();
  1365. SPBASE_API void load_debugLevelInCentersetting(const char* fileName);
  1366. SPBASE_API bool refreshLogLevel();
  1367. SPBASE_API int getCurLogLevel();
  1368. SPBASE_API ErrorCodeEnum GetAllEntityIdx(CAutoArray<CSimpleStringA>& strEntityNames, CAutoArray<WORD>& wEntityDevelopIDs);
  1369. /** log via shell */
  1370. SPBASE_API void LogEvent(const SeverityLevelEnum eLevel,DWORD dwUserEventCode,const char *pszMessage);
  1371. SPBASE_API void LogError(const SeverityLevelEnum eLevel, ErrorCodeEnum dwSysErrorCode,DWORD dwUserErrorCode,const char *pszMessage);
  1372. SPBASE_API void LogWarn(const SeverityLevelEnum eLevel, ErrorCodeEnum dwSysErrorCode,DWORD dwUserErrorCode, const char *pszMessage);
  1373. SPBASE_API void LogFatal(const SeverityLevelEnum eLevel, ErrorCodeEnum dwSysErrorCode, DWORD dwUserErrorCode, const char* pszMessage);
  1374. SPBASE_API void LogAssert(const char *pszMessage,const char *pszSourceFile,const int nLine);
  1375. SPBASE_API void LogTrace(const char *pszMessage,const char *pszSourceFile,const int nLine);
  1376. SPBASE_API void LogNotify(const NotifyLevelEnum eLevel, ErrorCodeEnum dwSysErrorCode, DWORD dwUserErrorCode, const char* pszMessage);
  1377. SPBASE_API void LogEvent(const SeverityLevelEnum eLevel, DWORD dwUserEventCode, const char* pszMessage, const linkContext& t_context);
  1378. SPBASE_API void LogError(const SeverityLevelEnum eLevel, ErrorCodeEnum dwSysErrorCode, DWORD dwUserErrorCode, const char* pszMessage, const linkContext& t_context);
  1379. SPBASE_API void LogWarn(const SeverityLevelEnum eLevel, ErrorCodeEnum dwSysErrorCode, DWORD dwUserErrorCode, const char* pszMessage, const linkContext& t_context);
  1380. SPBASE_API void LogFatal(const SeverityLevelEnum eLevel, ErrorCodeEnum dwSysErrorCode, DWORD dwUserErrorCode, const char* pszMessage, const linkContext& t_context);
  1381. SPBASE_API void LogAssert(const char* pszMessage, const char* pszSourceFile, const int nLine, const linkContext& t_context);
  1382. SPBASE_API void LogTrace(const char* pszMessage, const char* pszSourceFile, const int nLine, const linkContext& t_context);
  1383. SPBASE_API CSimpleStringA GetSysErrMsg(int nErrCode);
  1384. SPBASE_API const char *_GetFileName(const char *pszFilePath);
  1385. #ifdef RVC_OS_LINUX
  1386. /*
  1387. 基于当前mod中包含有restful模块,需要把数据从framework中传递到librestful,会比较困难
  1388. (1)实际上大部分实体都没有加载restful模块,所以难以进行显示调用进行初始化。
  1389. (2)初始化的时机难以把握,因为使用restful的位置各不相同
  1390. (3)目前有大致5个实体有用到librestfulSDK,采用回调函数传参的方式,把token功能传入到mod的librestfulSDK中。
  1391. (4)此方式为临时方案,使用策略模式,封装了算法SpGetToken(),通过函数传递的方式将该策略注入到类HttpClientRequestConfig中
  1392. */
  1393. #define MAX_TOKEN_LEN 256
  1394. SPBASE_API void SpGetToken(char* channelId, char* token);
  1395. #endif
  1396. #ifdef RVC_OS_WIN //TODO: duplicate ?
  1397. #define LOG_TRACE(pMsg, ...) \
  1398. LogTrace(CSimpleStringA::Format(pMsg, __VA_ARGS__), _GetFileName(__FILE__), __LINE__)
  1399. #else
  1400. #define LOG_TRACE(pMsg, ...) \
  1401. LogTrace(CSimpleStringA::Format(pMsg, ##__VA_ARGS__), _GetFileName(__FILE__), __LINE__)
  1402. #endif //RVC_OS_WIN
  1403. extern "C" SPBASE_API void Dbg(const char *str, ...);
  1404. extern "C" SPBASE_API void vDbg(const char *str, va_list list);
  1405. extern "C" SPBASE_API const char* SpStrError(ErrorCodeEnum errorCode);
  1406. struct CScopeLog
  1407. {
  1408. CScopeLog(const char* pszMsg, const char* pszFile, int nFileLine)
  1409. : m_pszMsg(pszMsg), m_pszFile(pszFile), m_nFileLine(nFileLine)
  1410. {
  1411. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Enter %s, file: {%s}, line: {%d}", m_pszMsg, m_pszFile, m_nFileLine);
  1412. }
  1413. ~CScopeLog() { DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Leave %s, file: {%s} ,line: {%d}", m_pszMsg, m_pszFile, m_nFileLine); }
  1414. const char* m_pszMsg;
  1415. const char* m_pszFile;
  1416. int m_nFileLine;
  1417. };
  1418. #define LOG_FUNCTION() CScopeLog __FunctionScopeLog(__FUNCTION__, _GetFileName(__FILE__), __LINE__)
  1419. //TODO:
  1420. /** It is used out of the Entity class members */
  1421. #if ( (defined(_DEBUG) && defined(_MSC_VER)) )
  1422. #define LOG_ASSERT(f) do{if(!(f) && (1 == _CrtDbgReport(_CRT_ASSERT, _GetFileName(__FILE__), __LINE__, NULL, #f))) {_CrtDbgBreak(); LogAssert(#f,_GetFileName(__FILE__), __LINE__);}} while (0)
  1423. #define LOG_ASSERT_MSG(f,pMsg, ...) do{if(!(f) && (1 == _CrtDbgReport(_CRT_ASSERT, _GetFileName(__FILE__), __LINE__, NULL, CSimpleStringA::Format(pMsg, __VA_ARGS__)))) _CrtDbgBreak(); LogAssert(pMsg,_GetFileName(__FILE__), __LINE__);} while (0)
  1424. #else//( (defined(_DEBUG) && defined(_MSC_VER)))
  1425. #define LOG_ASSERT(f) if(!(f)) LogAssert(#f,_GetFileName(__FILE__), __LINE__)
  1426. #define LOG_ASSERT_MSG(f,pMsg, ...) do{ if(!(f)) LogAssert(CSimpleStringA::Format(pMsg, ##__VA_ARGS__),_GetFileName(__FILE__), __LINE__);} while (0)
  1427. #endif// ( (defined(_DEBUG) && defined(_MSC_VER)) )
  1428. #endif // __cplusplus
  1429. #endif //_RVC_SPBASE_H_