SpBase.h 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713
  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 = "0000000000000000";
  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. };
  482. /** boot info */
  483. struct CBootInfo
  484. {
  485. CVersion InstallVersion;
  486. CSmallDateTime tmStart; //the system start run time
  487. CSmallDateTime tmReboot; //The trigger reboot time and It is end of run from StartTime
  488. RebootTriggerEnum eTriggerReason;
  489. RebootWayEnum eWay;
  490. WORD wSameReasonTime;
  491. WORD wSameWayTime;
  492. };
  493. /** sp module info */
  494. struct CSpInfo
  495. {
  496. CSimpleStringA strAuthor;
  497. CSimpleStringA strCompany;
  498. CVersion SoftwareVersion;
  499. CAutoArray<CSimpleStringA> strEntitys;
  500. };
  501. /** entity configuration data */
  502. struct CEntityStaticInfo
  503. {
  504. WORD wEntityDevelopID;
  505. bool bStartedByShell; //config start by shell or not(other Entity)
  506. bool bHasPrivilege; //can support IEntityFunctionPrivilege interface
  507. bool bIndispensable; //must be start and work correct else framework will fall into "Fault" state
  508. CSimpleStringA strSpFileName;
  509. CVersion version;
  510. };
  511. /** entity session info */
  512. struct CEntitySessionInfo
  513. {
  514. CSimpleStringA strCallerEntity;
  515. CSimpleStringA strServiceEntity;
  516. CSmallDateTime tmStart;
  517. SessionStateEnum eState;
  518. CSmallDateTime tmBeginState;
  519. };
  520. struct CEntityStartInfo
  521. {
  522. /** 应用当前实体的启动次数*/
  523. int startTimes;
  524. /** 收到启动实体的时间戳,第一次有效*/
  525. SYSTEMTIME startTime;
  526. /** 完成加载实体模块的时间戳,第一次有效,不判断是否加载失败*/
  527. SYSTEMTIME InitEndTime;
  528. /** 完成启动实体模块时间戳,第一次有效,不判断是否启动失败*/
  529. SYSTEMTIME startEndTime;
  530. };
  531. struct CEntityLastErrorInfo
  532. {
  533. ErrorCodeEnum eSysCode;
  534. DWORD dwUserCode;
  535. CSimpleStringA strErrMsg;
  536. };
  537. /** entity running info */
  538. struct CEntityRunInfo
  539. {
  540. DWORD dwEntityInstanceID;
  541. CSmallDateTime tmFirstStart; //The Entity first started after framework start
  542. CSmallDateTime tmLastStart; //The nearest started of this entity instance
  543. bool bService;
  544. EntityStateEnum eState;
  545. CSmallDateTime tmBeginCurrentState;
  546. DebugLevelEnum eDebugLevel;
  547. DWORD dwUserState; //Self define state
  548. DWORD dwProcessID; //Process ID of os
  549. };
  550. struct BroadcastSubscribeInfo
  551. {
  552. CUUID SubID;
  553. CSimpleStringA strListener; // from entity's name
  554. CSimpleStringA strParam;
  555. };
  556. struct IReleasable
  557. {
  558. virtual ~IReleasable(){};
  559. };
  560. /**
  561. * entity timer for user, the timer will initialize when user call IEntityFunction::SetTimer,
  562. * until user call KillTimer
  563. * note: nTimerID is application defined value in Entity Scope !!!
  564. */
  565. struct ITimerListener
  566. {
  567. virtual void OnTimeout(DWORD dwTimerID) = 0;
  568. };
  569. /** subcribe-public pattern, sys variable used for tracking system-level events */
  570. struct ISysVarListener
  571. {
  572. virtual void OnSysVarEvent(const char *pszKey,
  573. const char *pszValue,const char *pszOldValue,const char *pszEntityName)=0;
  574. };
  575. struct ITerminalStateChangedListener
  576. {
  577. virtual void OnStateChanged(FrameworkStateEnum oldState, FrameworkStateEnum curState, const char* triggerEntity) = 0;
  578. };
  579. struct IBroadcastListener
  580. {
  581. virtual void OnBroadcastEvent(CUUID SubID, const char* pszEntityName, DWORD dwMessageId, DWORD dwMessageSignature, CAutoBuffer Buffer) = 0;
  582. };
  583. struct IEntityLifeListener
  584. {
  585. /* if pszTriggerEntity=null mean created by shell*/
  586. virtual void OnCreated(const char* pszEntityName, ErrorCodeEnum eOnStartErrorCode, const char* pszCallerEntity) = 0;
  587. /*Call after the entity has close or killed, eOnCloseErrorCode notic if the entity do OnClose normally and resource has beed release*/
  588. virtual void OnClosed(const char* pszEntityName, EntityCloseCauseEnum eCloseCause, ErrorCodeEnum eOnCloseErrorCode, const char* pszCallerEntity) = 0;
  589. /*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*/
  590. virtual void OnException(const char* pszEntityName, const char* pszFunctionName, EntityStateEnum eState, EntityStateEnum eLastState, ErrorCodeEnum eErrorCode) = 0;
  591. };
  592. struct IEntityStateListener
  593. {
  594. virtual void OnEntityStateHook(const char* pszEntityName, const char* pszTriggerEntity, EntityStateEnum eState, EntityStateEnum eLastState) = 0;
  595. virtual void OnUserStateHook(const char* pszEntityName, DWORD dwState, DWORD dwLastState) = 0;
  596. virtual void OnCeateConnection(const char* pszCallerEntity, const char* pszServiceEntity) = 0;
  597. virtual void OnCloseConnection(const char* pszCallerEntity, const char* pszServiceEntity) = 0;
  598. };
  599. /** log hooker */
  600. struct ILogListener
  601. {
  602. virtual void OnLog(const CAutoArray<CUUID>& SubIDs, const CUUID nLogID, const LogTypeEnum eLogType, const SeverityLevelEnum eLevel,
  603. const DWORD dwSysError, const DWORD dwUserCode, const DWORD dwEntityInstanceID, const WORD wEntityDevelID,
  604. const CAutoArray<DWORD>& Param, const char* pszEntityName, const char* pszModuleName, const char* pszMessage, const linkContext& pLinkInfo) = 0;
  605. };
  606. struct IConfigInfo
  607. {
  608. virtual ConfigTypeEnum GetConfigType() = 0;
  609. virtual bool storageInMem() = 0;
  610. /** read/write config via shell */
  611. virtual ErrorCodeEnum ReadConfigValue(const char* pszSection, const char* pszKey, CSimpleStringA& strValue) = 0;
  612. virtual ErrorCodeEnum ReadConfigValueInt(const char* pszSection, const char* pszKey, int& iValue) = 0;
  613. /** only can write self's section, pValue=NULL for delete */
  614. virtual ErrorCodeEnum WriteConfigValue(const char* pszSection, const char* pszKey, const char* pszValue) = 0;
  615. virtual ErrorCodeEnum WriteConfigValueInt(const char* pszSection, const char* pszKey, int iValue) = 0;
  616. /** read all key-value pairs */
  617. virtual ErrorCodeEnum ReadAllKeys(const char* pszSection, CAutoArray<CSimpleStringA>& strKeys) = 0;
  618. /** get all section values */
  619. virtual ErrorCodeEnum ReadAllSections(CAutoArray<CSimpleStringA>& strSections) = 0;
  620. /** write hex int values, ig: "keyName=0x4F3D012A" */
  621. virtual ErrorCodeEnum WriteConfigValueHexInt(const char* pszSection, const char* pszKey, UINT64 nValue) = 0;
  622. virtual ErrorCodeEnum ReadConfigValueHexInt(const char* pszSection, const char* pszKey, UINT64& nValue) = 0;
  623. };
  624. struct IAsynWaitSp;
  625. /** invoked when receive answer from remote */
  626. struct ICallbackListener
  627. {
  628. virtual void OnAnswer(CSmartPointer<IAsynWaitSp> pAsynWaitSp) = 0;
  629. };
  630. struct IEntityPersistObject;
  631. /** object serialize mechanism, reader interface */
  632. struct IEntityPersistStreamRead
  633. {
  634. virtual ErrorCodeEnum Get(const char* pszKey, CSimpleStringA& strValue) = 0;
  635. virtual ErrorCodeEnum Get(const char* pszKey, ULONGLONG& qwValue) = 0;
  636. virtual ErrorCodeEnum Get(const char* pszKey, DWORD& dwValue) = 0;
  637. virtual ErrorCodeEnum Get(const char* pszKey, WORD& wValue) = 0;
  638. virtual ErrorCodeEnum Get(const char* pszKey, BYTE& cValue) = 0;
  639. virtual ErrorCodeEnum Get(const char* pszKey, FLOAT& fValue) = 0;
  640. virtual ErrorCodeEnum Get(const char* pszKey, DOUBLE& fValue) = 0;
  641. virtual ErrorCodeEnum Get(const char* pszKey, IEntityPersistObject* pValue) = 0;
  642. virtual ErrorCodeEnum GetArray(const char* pszKey, CAutoArray<CSimpleStringA>& strValues) = 0;
  643. virtual ErrorCodeEnum GetArray(const char* pszKey, CAutoArray<ULONGLONG>& qwValues) = 0;
  644. virtual ErrorCodeEnum GetArray(const char* pszKey, CAutoArray<DWORD>& dwValues) = 0;
  645. virtual ErrorCodeEnum GetArray(const char* pszKey, CAutoArray<WORD>& wValues) = 0;
  646. virtual ErrorCodeEnum GetArray(const char* pszKey, CAutoArray<BYTE>& cValues) = 0;
  647. virtual ErrorCodeEnum GetArray(const char* pszKey, CAutoArray<FLOAT>& fValues) = 0;
  648. virtual ErrorCodeEnum GetArray(const char* pszKey, CAutoArray<DOUBLE>& fValues) = 0;
  649. };
  650. /** object serialize mechanism, writer interface */
  651. struct IEntityPersistStreamWrite
  652. {
  653. virtual ErrorCodeEnum Set(const char* pszKey, const char* pszValue) = 0;
  654. virtual ErrorCodeEnum Set(const char* pszKey, const ULONGLONG qwValue) = 0;
  655. virtual ErrorCodeEnum Set(const char* pszKey, const DWORD dwValue) = 0;
  656. virtual ErrorCodeEnum Set(const char* pszKey, const WORD wValue) = 0;
  657. virtual ErrorCodeEnum Set(const char* pszKey, const BYTE cValue) = 0;
  658. virtual ErrorCodeEnum Set(const char* pszKey, const FLOAT fValue) = 0;
  659. virtual ErrorCodeEnum Set(const char* pszKey, const DOUBLE fValue) = 0;
  660. virtual ErrorCodeEnum Set(const char* pszKey, const IEntityPersistObject* pValue) = 0;
  661. virtual ErrorCodeEnum SetArray(const char* pszKey, const CAutoArray<CSimpleStringA>& strValues) = 0;
  662. virtual ErrorCodeEnum SetArray(const char* pszKey, const CAutoArray<ULONGLONG>& qwValues) = 0;
  663. virtual ErrorCodeEnum SetArray(const char* pszKey, const CAutoArray<DWORD>& dwValues) = 0;
  664. virtual ErrorCodeEnum SetArray(const char* pszKey, const CAutoArray<WORD>& wValues) = 0;
  665. virtual ErrorCodeEnum SetArray(const char* pszKey, const CAutoArray<BYTE>& cValues) = 0;
  666. virtual ErrorCodeEnum SetArray(const char* pszKey, const CAutoArray<FLOAT>& fValues) = 0;
  667. virtual ErrorCodeEnum SetArray(const char* pszKey, const CAutoArray<DOUBLE>& fValues) = 0;
  668. };
  669. /** object serialize mechanism, user-defined object need to inherits from this */
  670. struct IEntityPersistObject
  671. {
  672. virtual ErrorCodeEnum OnRead(CSmartPointer<IEntityPersistStreamRead> pStream) = 0;
  673. virtual ErrorCodeEnum OnWrite(CSmartPointer<IEntityPersistStreamWrite> pStream) const = 0;
  674. };
  675. /** task interface */
  676. struct ITaskSp
  677. {
  678. ITaskSp() : m_ref_cnt(1) {}
  679. virtual ~ITaskSp() {}
  680. virtual void IncRef() { InterlockedIncrement(&m_ref_cnt); }
  681. virtual void DecRef() { if (0 == InterlockedDecrement(&m_ref_cnt)) { delete this; } }
  682. virtual void Process() = 0;
  683. private:
  684. LONG m_ref_cnt;
  685. };
  686. class CClientSessionBase;
  687. class CServerSessionBase;
  688. struct IEntityFunctionPrivilege;
  689. //typedef int (*postLink)(const char *bussinessId, const char *traceId, const char *spanId, const char *parentSpanId);
  690. /** normal entity service */
  691. struct IEntityFunction
  692. {
  693. virtual ~IEntityFunction() {}
  694. /** get CSystemStaticInfo information */
  695. virtual ErrorCodeEnum GetSystemStaticInfo(CSystemStaticInfo& Info) = 0;
  696. virtual ErrorCodeEnum GetInstallInfo(CVersion Version, CInstallInfo& Info) = 0; //include latter/current/history version
  697. virtual bool IsPackInstalled(const char* pPackName) = 0;
  698. /**
  699. * get path define in Root.ini,
  700. * pszKey : "Data", "Rec", "Temp", "SysLog", "InterLog","UploadVideo","UploadPhoto","Downloads","Upgraded","LatterInstall","Run","SysRoot","CenterSetting"
  701. */
  702. virtual ErrorCodeEnum GetPath(const char* pszKey, CSimpleStringA& strPath) = 0;
  703. /** get system running info */
  704. virtual ErrorCodeEnum GetSystemRunInfo(CSystemRunInfo& Info) = 0;
  705. /** get busy entity number and startup entity number */
  706. virtual ErrorCodeEnum GetEntityBusyRate(WORD& nBusyEntity, WORD& nAllEntity) = 0;
  707. /** get reboot info,if BeforeThisTime=CSmallDateTime::BeginTime,then return last time boot info,else return the start time before BeforeThisTime record*/
  708. virtual ErrorCodeEnum GetRebootInfo(CSmallDateTime BeforeThisTime, CBootInfo& Info) = 0;
  709. /** get all sp entity module file name without full path */
  710. virtual ErrorCodeEnum GetAllRegistSpFile(CAutoArray<CSimpleStringA>& strSpNames) = 0;
  711. /** get sp file info */
  712. virtual ErrorCodeEnum GetSpFileInfo(const char* pszSpName, CSpInfo& Info) = 0;
  713. /** get all registered entity name */
  714. virtual ErrorCodeEnum GetAllRegistedEntity(CAutoArray<CSimpleStringA>& strEntityNames, CAutoArray<WORD>& wEntityDevelopIDs) = 0;
  715. virtual ErrorCodeEnum GetAllStartedEntity(CAutoArray<CSimpleStringA>& strEntityNames, CAutoArray<DWORD>& dwEntityInstanceIDs) = 0;
  716. /** get the entity of the current process running info */
  717. virtual ErrorCodeEnum GetSelfEntityRunInfo(CEntityRunInfo& Info) = 0;
  718. /** get entity config info */
  719. virtual ErrorCodeEnum GetEntityStaticInfo(const char* pszEntityName, CEntityStaticInfo& Info) = 0;
  720. //virtual ErrorCodeEnum GetEntityStaticInfo(WORD wEntityDevelopID,CEntityStaticInfo &Info)=0;
  721. /** get entity state via shell */
  722. virtual ErrorCodeEnum GetEntityRunInfo(const char* pszEntityName, CEntityRunInfo& Info) = 0;
  723. /** get entity all session info */
  724. virtual ErrorCodeEnum GetEntitySessionInfo(const char* pszEntityName, CAutoArray<CEntitySessionInfo>& Infos) = 0;
  725. /** get entity name from instance entity ID */
  726. virtual ErrorCodeEnum GetEntityName(DWORD dwEntityInstanceID, CSimpleStringA& strName) = 0;
  727. /** get entity name from develop entity ID */
  728. virtual ErrorCodeEnum GetEntityName(WORD wEntityDevelopID, CSimpleStringA& strName) = 0;
  729. /** ini file reader/writer utility */
  730. virtual ErrorCodeEnum OpenConfig(ConfigTypeEnum eConfigType, CSmartPointer<IConfigInfo>& pConfigInfo, bool forceFile = false) = 0;
  731. /** Set self define state enum for out side notice */
  732. virtual ErrorCodeEnum SetUserDefineState(DWORD dwState) = 0;
  733. virtual DWORD GetUserDefineState() = 0;
  734. /** only the entity has been set in shell.ini can change the value*/
  735. virtual ErrorCodeEnum SetSysVar(const char* pszKey, const char* pszValue, bool bPersist = false) = 0;
  736. /** get sys variable value */
  737. virtual ErrorCodeEnum GetSysVar(const char* pszKey, CSimpleStringA& strValue) = 0;
  738. virtual ErrorCodeEnum GetAllEntityStartInfo(CAutoArray<CSimpleStringA>& strEntityNames, CAutoArray<int>& strEntityIdx, CAutoArray<CEntityStartInfo>& Infos) = 0;
  739. virtual WORD GetDevID() = 0;
  740. /**
  741. * install sys variable
  742. * @param pszKey the sys var key you want subscribe
  743. * @param pListener user callback interface
  744. * @param dwSysEventID user defined ID, must be unique in entity scope
  745. */
  746. virtual ErrorCodeEnum RegistSysVarEvent(const char* pszKey, ISysVarListener* pListener) = 0;
  747. /*if pszKey=NULL mean unregist all keys event*/
  748. virtual ErrorCodeEnum UnregistSysVarEvent(const char *pszKey)=0;
  749. /*!
  750. * @brief
  751. * @param pListener the sub class boject pointer inherit ITerminalStateChangedListener and implement
  752. * OnStateChanged interface.
  753. * @return : Error_Succeed if regist successfully, other means failure.
  754. */
  755. virtual ErrorCodeEnum RegistTerminalStateChangeEvent(ITerminalStateChangedListener* pListener) = 0;
  756. /*!
  757. * @brief
  758. * @return : Error_Succeed if unregist successfully
  759. */
  760. virtual ErrorCodeEnum UnregistTerminalStateChangeEvent() = 0;
  761. /**
  762. * every entity can broadcast messages, user entity can subscribe an entity's broadcast messages
  763. */
  764. virtual ErrorCodeEnum SendBroadcast(DWORD dwMessageId, DWORD dwMessageSignature, CAutoBuffer Buffer) = 0;
  765. virtual ErrorCodeEnum GetBroadcastReceivers(CAutoArray<BroadcastSubscribeInfo>& Subscribers) = 0;
  766. virtual ErrorCodeEnum SubscribeBroadcast(const char* pszRemoteEntity, const char* pszParam, IBroadcastListener* pListener, CUUID& SubscribeID) = 0;
  767. virtual ErrorCodeEnum UnsubscribeBroadcast(CUUID SubscribeID) = 0;
  768. virtual ErrorCodeEnum UnsubscribeBroadcast(const char* pszRemoteEntity) = 0;
  769. /**
  770. * subscribe log via shell
  771. * @param listener user's specific callback, null to cancel
  772. * @param eLevel will get log more(or equal) importance than eLevel,
  773. * @param pszEntityName if not null will get log only for that "pszEntityName" appoint one
  774. * @param eSysError Error_IgnoreAll means accept any sys error
  775. * @param dwUserCode -2 means accept any user code, -1 means accept log which has user code(nonzero)
  776. * @param bIgnoreMessage if true then pszMessage will not be send to save bandwidth
  777. */
  778. virtual ErrorCodeEnum SubscribeLog(CUUID& SubscribeID, ILogListener* pListener, LogTypeEnum eLogType = Log_Ignore, SeverityLevelEnum eLevel = Severity_None,
  779. ErrorCodeEnum eSysError = Error_IgnoreAll, DWORD dwUserCode = 0, const char* pszEntityName = NULL, bool bIgnoreMessage = true) = 0;
  780. virtual ErrorCodeEnum UnsubscribeLog(CUUID SubscribeID) = 0;
  781. /** force shell to dump a log file */
  782. virtual ErrorCodeEnum FlushLogFile() = 0;
  783. /**
  784. * read persist object from framework's serialize directory
  785. * @param pszClass which class the object belongs
  786. * @param pszKey the object key, key is case-sensitive!!!
  787. * note: actually this object stores at dir %syspath%/Objects/<EntityName>/pszClass/pszKey
  788. * so pszClass and pszKey cannot contains chars which os file path specification forbidden, such as *, ?
  789. */
  790. virtual ErrorCodeEnum ReadPersistObject(const char* pszClass, const char* pszKey, IEntityPersistObject* pInstance) = 0;
  791. /** write persist object to framework's serialize directory */
  792. virtual ErrorCodeEnum WritePersistObject(const char* pszClass, const char* pszKey, const IEntityPersistObject* pInstance) = 0;
  793. /** get the number of persist object */
  794. virtual ErrorCodeEnum ReadNumOfPersistObject(const char* pClassName, DWORD& dwNum) = 0;
  795. /** get class all objects keys */
  796. virtual ErrorCodeEnum GetPersistClassObjectKeys(const char* pClassName, CAutoArray<CSimpleStringA>& strKeys) = 0;
  797. /** delete persist object */
  798. virtual ErrorCodeEnum DeleteKeyOfPersistObject(const char* pClassName, const char* pszKey) = 0;
  799. /** walk through class objects of pClassName, Handle=0 find from beginning */
  800. virtual ErrorCodeEnum EnumKeyOfPersistObject(const char* pClassName, CSimpleStringA& strKey, DWORD& dwHandle) = 0;
  801. /** delete all persist object of class pClassName */
  802. virtual ErrorCodeEnum CleanAllOfPersistObject(const char* pClassName) = 0;
  803. /**
  804. * do async connect to remote entity service, after connected, then pClientSession->Onconnected will call
  805. * note: if return succeed, pClientSession will delete by system via OnDestroy
  806. * if return failed, pCilentSession need delete by user
  807. */
  808. virtual ErrorCodeEnum ConnectRemoteEntity(CClientSessionBase* pClientSession,
  809. const char* pszRemoteEntity,
  810. const char* pszParam,
  811. CSmartPointer<IAsynWaitSp>& pAsynWaitSp) = 0;
  812. /**redirect as bridged mode*/
  813. virtual ErrorCodeEnum RedirectSession(CClientSessionBase* pClientSession) = 0;
  814. /**redirect when accepted*/
  815. virtual ErrorCodeEnum RedirectSession(const char* pszSuggestEntity) = 0;
  816. /** redirect subscribe broadcast */
  817. virtual ErrorCodeEnum RedirectSubscribBroadcast(CUUID SubID, const char* pszSugguestEntity) = 0;
  818. /**
  819. * if entity want to close self, call this function to notify shell service,
  820. * then shell service will issue close command
  821. */
  822. virtual ErrorCodeEnum PostQuit() = 0;
  823. /**
  824. * Reload itself entity
  825. */
  826. virtual ErrorCodeEnum PostReload() = 0;
  827. virtual ErrorCodeEnum SetSelfPriority(EntityPriorityEnum nPriority) = 0;
  828. virtual ErrorCodeEnum GetSelfPriority(EntityPriorityEnum& nPriority) = 0;
  829. /**
  830. * timer functions, setup an periodic timer
  831. * @param nTimerID user defined ID, must unique in entity scope
  832. * @param pListener user override callback
  833. * @param dwInterval timer interval
  834. */
  835. virtual ErrorCodeEnum SetTimer(DWORD dwTimerID, ITimerListener* pListener, DWORD dwInterval) = 0;
  836. virtual ErrorCodeEnum SetTimerData(DWORD dwTimerID, IReleasable* pData) = 0;
  837. virtual ErrorCodeEnum GetTimerData(DWORD dwTimerID, CSmartPointer<IReleasable>& pData) = 0;
  838. /*if dwTimerID=0 mean kill all Timer*/
  839. virtual ErrorCodeEnum KillTimer(DWORD dwTimerID) = 0;
  840. virtual ErrorCodeEnum ResetTimer(DWORD dwTimerID, DWORD dwInterval) = 0;
  841. virtual ErrorCodeEnum GetTimerInterval(DWORD dwTimerID, DWORD& dwInterval) = 0;
  842. /** query whether this entity has privilege ? */
  843. virtual bool HasPrivilege() = 0;
  844. /** get privilege pointer */
  845. virtual CSmartPointer<IEntityFunctionPrivilege> GetPrivilegeFunction() = 0;
  846. /** setup log for current thread(for user created thread) */
  847. virtual ErrorCodeEnum InitLogCurrentThread() = 0;
  848. /**
  849. * start tcp bridge server at ip:port
  850. * note: mainly for silverlight usage
  851. * currently: silverlight only can use port range (4502-4506)
  852. * we provide silverlight policy server(tcp 943) at spshell.exe
  853. */
  854. virtual ErrorCodeEnum StartTcpBridgeServer(unsigned short port) = 0;
  855. virtual ErrorCodeEnum StopTcpBridgeServer() = 0;
  856. //virtual void SetPostLinkFun(postLink cur) = 0;
  857. /**
  858. * post Task to entity's thread
  859. * FIFO(first in first out) queue tail, LIFO(last in first out)
  860. * queue head
  861. */
  862. virtual ErrorCodeEnum PostEntityTaskFIFO(ITaskSp* pTask) = 0;
  863. virtual ErrorCodeEnum PostEntityTaskLIFO(ITaskSp* pTask) = 0;
  864. /**
  865. * post task to thread pool
  866. */
  867. virtual ErrorCodeEnum PostThreadPoolTask(ITaskSp* pTask) = 0;
  868. /** request framework to delay closing */
  869. virtual ErrorCodeEnum RequestCloseDelay(WORD nSecond) = 0;
  870. /** log along with params */
  871. virtual void SendLog(const LogTypeEnum eLogType, const SeverityLevelEnum eLevel, DWORD dwUserEventCode, CAutoArray<DWORD> Param, const char* pszMessage = NULL) = 0;
  872. /*verify file code signature, if pass, strErrInfo is sign cert hash, else verify error info*/
  873. virtual ErrorCodeEnum VerifySignature(const char* pszSignedFile, CSimpleStringA& strErrInfo) = 0;
  874. /*show fatal error info when framework startup*/
  875. virtual ErrorCodeEnum ShowFatalError(const char *pszMsg, SeverityLevelEnum eLevel = Severity_None) = 0;
  876. /*show important startup info when framework startup*/
  877. virtual ErrorCodeEnum ShowStartupInfo(const char *pszMsg) = 0;
  878. virtual ErrorCodeEnum GetEntityLastError(const char* pszEntityName, CEntityLastErrorInfo& errInfo) = 0;
  879. virtual void ResetEntityLastError() = 0;
  880. virtual ErrorCodeEnum GetToken(CSimpleString& channelId, CSimpleString& token) = 0;
  881. /* GetRunningVersion
  882. currently return version in active.txt, may be it will return the version from micro sever latter.
  883. */
  884. virtual ErrorCodeEnum GetRunningVersion(CSimpleString& ver) = 0;
  885. virtual ErrorCodeEnum GetVTMErrMsg(DWORD dwUserCode, CSimpleStringA& strDescription, CSimpleStringA& strVTMCode) = 0;
  886. };
  887. class VTMInitParam{
  888. public:
  889. CSimpleString terminalNo;
  890. CSimpleString channelId;
  891. CSimpleString tokenSecret;
  892. CSimpleString CommonLaunchUrl;
  893. CSimpleString CenterConfigTotal;
  894. VTMInitParam(const char *terminal, const char* channel, const char* token,
  895. const char* launchUrl, const char* configTotal)
  896. : terminalNo(terminal), channelId(channel), tokenSecret(token),
  897. CommonLaunchUrl(launchUrl), CenterConfigTotal(configTotal) {}
  898. };
  899. class MemCfgParam {
  900. public:
  901. CSimpleString configType; //"centersetting", "root", "shell"
  902. CSimpleString module;
  903. CSimpleString name;
  904. CSimpleString value;
  905. MemCfgParam(const char* type, const char* mod, const char* n, const char* val)
  906. : configType(type), module(mod), name(n), value(val) {}
  907. };
  908. /** normal entity no need to use this interface, use for update, health management, etc. */
  909. struct IEntityFunctionPrivilege
  910. {
  911. virtual ~IEntityFunctionPrivilege() {}
  912. /** if persist=true,the DebugLevel will be keep after restart */
  913. virtual ErrorCodeEnum SetSysDebugLevel(const char *pszEntityName,DebugLevelEnum eDebugLevel,bool bPersist=false)=0;
  914. /*upate terminal current state*/
  915. virtual ErrorCodeEnum RefreshFrameworkState(FrameworkStateEnum eState) = 0;
  916. /** get %SysRoot%\Ver\<version> 's config info */
  917. virtual ErrorCodeEnum GetSystemStaticInfoForVersion(CVersion verSoftware, CSystemStaticInfo& StaticInfo) = 0;
  918. /** start a remote entity,if restart itself only been call in OnClose event,will ignore pAsynWaitSp,and will not wait*/
  919. virtual ErrorCodeEnum StartEntity(const char* pszEntityName, const char* pszCmdLine, CSmartPointer<IAsynWaitSp>& pAsynWaitSp) = 0;
  920. /** close entity ,not use consultative mechanism */
  921. virtual ErrorCodeEnum StopEntity(const char* pszEntityName, CSmartPointer<IAsynWaitSp>& pAsynWaitSp) = 0;
  922. /** require entity close and can use the consultative mechanisms */
  923. virtual ErrorCodeEnum CloseEntity(const char* pszEntityName, CSmartPointer<IAsynWaitSp>& pAsynWaitSp) = 0;
  924. /** terminate entity forcefully */
  925. virtual ErrorCodeEnum TerminateEntity(const char* pszEntityName, CSmartPointer<IAsynWaitSp>& pAsynWaitSp) = 0;
  926. /** pause entity */
  927. virtual ErrorCodeEnum PauseEntity(const char* pszEntityName, CSmartPointer<IAsynWaitSp>& pAsynWaitSp) = 0;
  928. /** continue entity from paused state */
  929. virtual ErrorCodeEnum ContinueEntity(const char* pszEntityName, CSmartPointer<IAsynWaitSp>& pAsynWaitSp) = 0;
  930. /** test whether entity state ok, a simple health-checking mechanism */
  931. virtual ErrorCodeEnum TestEntity(const char* pszEntityName, EntityTestEnum eTestType, CSmartPointer<IAsynWaitSp>& pAsynWaitSp) = 0;
  932. /** register entity life event */
  933. virtual ErrorCodeEnum RegistEntityLifeEvent(IEntityLifeListener* pListener) = 0;
  934. virtual ErrorCodeEnum UnregistLiftEvent() = 0;
  935. /** register entity state event, when entity state changes, callback will be invoked */
  936. virtual ErrorCodeEnum RegistEntityStateEvent(const char* pszEntityName, IEntityStateListener* pListener) = 0;
  937. /*If pszEntityName=NULL mean unregist all entity event*/
  938. virtual ErrorCodeEnum UnregistEntityStateEvent(const char *pszEntityName)=0;
  939. virtual ErrorCodeEnum GetSpecifiedEntityState(const char* pszEntityName, EntityStateEnum &eEntityState, DWORD& dwUserState) = 0;
  940. /** trigger reboot framework/machine */
  941. virtual ErrorCodeEnum Reboot(RebootTriggerEnum eTriggerReason, RebootWayEnum eWay) = 0;
  942. /** show blue full-screen title, for example for system error, privilege */
  943. virtual ErrorCodeEnum DisplayBlueScreen(const char* pszTitle) = 0;
  944. /** hide blue screen */
  945. virtual ErrorCodeEnum UndisplayBlueScreen() = 0;
  946. /** Install in current version and path*/
  947. virtual ErrorCodeEnum BeginLightInstall(const char* pszPackageName) = 0;
  948. virtual ErrorCodeEnum GenerateNewInstallCfg() = 0;
  949. //virtual ErrorCodeEnum SetUpdateSourcePath(const char *pszSourcePath)=0;
  950. /** Copy from [Temp]\[pszPackageName]\[pszRelativeFile] to install path,
  951. 1(copy only exisit); 2(copy only not exist); 3(copy always); 4(no copy if exist)*/
  952. virtual ErrorCodeEnum CopyFileToNewVersion(const char* pszRelativeFile, int nCopyMode) = 0;
  953. /** pszRelativeName is in run path*/
  954. virtual ErrorCodeEnum DeleteFileInNewVersion(const char* pszRelativeName) = 0;
  955. /** Set startup shell to last version shell,but not trigger to restart.next restart will run in last version path.*/
  956. virtual ErrorCodeEnum RollBackToPreviousVersion() = 0;
  957. virtual ErrorCodeEnum RollBackToHistoryVersion(CVersion HistoryVersion) = 0;
  958. /** Set startup shell to new version shell,next restart will run in new version path
  959. if bToSysInstall=true the SpShell.exe will not startup first,waiting Guardian.exe running install over,and started up by Guardian.exe*/
  960. virtual ErrorCodeEnum UpgradeToNewVersion(bool bToSysInstall) = 0;
  961. /**If the update or rollback version succeed run, info the framework this version is ok*/
  962. virtual ErrorCodeEnum SetRunSucceed() = 0;
  963. /**check if the pack has been installed*/
  964. virtual ErrorCodeEnum IsPackInstalled(const char* pszPackName, bool& bInstalled) = 0;
  965. /** os pack upgrade, run.ini has ToRun define */
  966. virtual ErrorCodeEnum BeginSysPackInstall(const char* pszPackageName, CSimpleStringA& strErrMsg) = 0;
  967. /**check if the syspack has been installed*/
  968. virtual ErrorCodeEnum IsInstalledSysPack(const char* pszPackageName) = 0;
  969. /** show system running output console, including all entity's syslog */
  970. virtual ErrorCodeEnum ShowOuputConsole() = 0;
  971. /**close output console */
  972. virtual ErrorCodeEnum CloseOuputConsole() = 0;
  973. /*Sets the scheduling priority of the process specified by entity name*/
  974. virtual ErrorCodeEnum SetEntityPriority(const char* pszEntityName, EntityPriorityEnum nPriority) = 0;
  975. virtual ErrorCodeEnum GetEntityPriority(const char* pszEntityName, EntityPriorityEnum& nPriority) = 0;
  976. /*begin log sender*/
  977. virtual ErrorCodeEnum BeginLogSend(const char* endpoint, const char* topicSys, const char* topicUser, const char* topicBeidou
  978. , const char* bussSys, const char* bussUser, const char* vtmWeb) = 0;
  979. /*update token*/
  980. virtual ErrorCodeEnum SetHttpToken(const char* channelId, const char* token) = 0;
  981. virtual void GetSendLogInfo(unsigned long* t_upload_TerminalSys_Suc, unsigned long* t_upload_TerminalUser_Suc,
  982. unsigned long* t_upload_BussinessSys_Suc, unsigned long* t_upload_BussinessUser_Suc, unsigned long* t_upload_beidou_Suc,
  983. unsigned long* t_upload_TerminalSys_Err, unsigned long* t_upload_TerminalUser_Err,
  984. unsigned long* t_upload_BussinessSys_Err, unsigned long* t_upload_BussinessUser_Err, unsigned long* t_upload_beidou_Err) = 0;
  985. //replace params with VTMInitParam; if one param in VTMInitParam equals to "", it will not replace to old value
  986. virtual ErrorCodeEnum InitCfgUrl(VTMInitParam &info) = 0;
  987. virtual ErrorCodeEnum InitCfgUrl(CSimpleString& channelId, CSimpleString& tokenSecret, CSimpleString& CommonLaunchUrl, CSimpleString& CenterConfigTotal) = 0;//old, will discard soon
  988. virtual ErrorCodeEnum TryUpdateCfg() = 0;
  989. virtual ErrorCodeEnum TryUpdateCenterCfg(bool& isUpdate, bool& isReset, CSimpleString& version) = 0;
  990. virtual ErrorCodeEnum TryUpdateToken(CSimpleString& oldToken, CSimpleString& newToken) = 0;
  991. virtual ErrorCodeEnum GetToken(CSimpleString& curToken) = 0;
  992. virtual ErrorCodeEnum WriteTerminalNoToRootIni(CSimpleString terminalNo) = 0;
  993. virtual ErrorCodeEnum ModifyMemCfgParam(MemCfgParam& info) = 0;
  994. virtual ErrorCodeEnum TryUpdateVTMERRMSG() = 0;
  995. virtual ErrorCodeEnum GetVTMErrMsgArr(CAutoArray<CSimpleStringA>& strErrorCodeArr,
  996. CAutoArray<CSimpleStringA>& strDescriptionArr, CAutoArray<CSimpleStringA>& strRemarkArr) = 0;
  997. };
  998. /**
  999. * service entity side transaction, we define call in two types:
  1000. * 1) one way call, client send one way call packet, need no reply from server side
  1001. * 2) two way call, client send request and server response
  1002. * A transaction is a call context hosted by server entity, when one client
  1003. * issues a call, at server entity side, compose a Transaction context object.
  1004. */
  1005. struct ITransactionContext
  1006. {
  1007. virtual ~ITransactionContext() {};
  1008. /** decide whether client call is one way call */
  1009. virtual bool IsOneWayCall() = 0;
  1010. /** get request sequence id */
  1011. virtual DWORD GetRequestID() = 0;
  1012. /** get client buffer */
  1013. virtual ErrorCodeEnum GetReceiveBuffer(DWORD& dwMessageID, DWORD& dwMessageSignature, CAutoBuffer& Buffer) = 0;
  1014. /** send out response to client, only use in two way call scenario */
  1015. virtual ErrorCodeEnum SendAnswer(CAutoBuffer Buffer, bool bEnd = true) = 0;
  1016. /** send out response to client without buffer, this is the simplist case for the above one
  1017. * 20160914: support return custom error: @dwUserError
  1018. */
  1019. virtual ErrorCodeEnum SendAnswer(ErrorCodeEnum eErrorCode, DWORD dwUserError = 0, CSimpleString str = "") = 0;
  1020. /** set response expired timeout value, in milliseconds */
  1021. virtual ErrorCodeEnum SetExpireTime(DWORD dwMS) = 0;
  1022. /** get this run process expire time left value, in milliseconds */
  1023. virtual ErrorCodeEnum GetExpireTime(DWORD& dwWholeTime, DWORD& dwLeftTime) = 0;
  1024. virtual ErrorCodeEnum GetLinkContext(linkContext& curLink) = 0;
  1025. };
  1026. /** The Module entity must implement the interface */
  1027. class CEntityBase
  1028. {
  1029. public:
  1030. CEntityBase():m_pEntityFunction(nullptr) {}
  1031. virtual ~CEntityBase() { if(m_pEntityFunction != nullptr) delete m_pEntityFunction; }
  1032. /** get entity service function */
  1033. virtual CSmartPointer<IEntityFunction> GetFunction() { return m_pEntityFunction; }
  1034. #ifdef RVC_OS_WIN
  1035. #if (!defined(SPABASE_LINKED_AS_STATIC_LIBRARY) && !defined(SPBASE_EXPORTS))
  1036. protected:
  1037. #endif
  1038. #endif //RVC_OS_WIN
  1039. /**
  1040. * invoked when entity is being start, when starting operation finished user must call FinishStart
  1041. * so the starting operation has prepared, then spbase.dll invokes OnStart
  1042. */
  1043. virtual void OnPreStart(CAutoArray<CSimpleStringA> strArgs, CSmartPointer<ITransactionContext> pTransactionContext) { pTransactionContext->SendAnswer(Error_Succeed); }
  1044. virtual void OnStarted() {}
  1045. /** invoked when entity pause */
  1046. virtual void OnPrePause(CSmartPointer<ITransactionContext> pTransactionContext) { pTransactionContext->SendAnswer(Error_Succeed); }
  1047. virtual void OnPaused() {}
  1048. /** invoked when entity continue */
  1049. virtual void OnPreContinue(CSmartPointer<ITransactionContext> pTransactionContext) { pTransactionContext->SendAnswer(Error_Succeed); }
  1050. virtual void OnContinued() {}
  1051. /** invoked when entity will be closed*/
  1052. virtual void OnPreClose(EntityCloseCauseEnum eCloseCause, CSmartPointer<ITransactionContext> pTransactionContext) { pTransactionContext->SendAnswer(Error_Succeed); }
  1053. /** user override this, so it is able to extend some complicated health-checking method */
  1054. virtual void OnSelfTest(EntityTestEnum eTestType, CSmartPointer<ITransactionContext> pTransactionContext) { pTransactionContext->SendAnswer(Error_Succeed); }
  1055. /*!
  1056. * [Gifur@2020519]
  1057. * override OnSelfTest with speicified EntityTestEnum::Test_Examine
  1058. */
  1059. virtual void OnExam(CSmartPointer<ITransactionContext> pTransactionContext) { pTransactionContext->SendAnswer(Error_NotImpl); }
  1060. /** invoked when incoming new connection user can RedirectSession in OnNewSession*/
  1061. virtual CServerSessionBase *OnNewSession(const char* /*pszRemoteEntityName*/, const char * /*pszParam*/){return NULL;}
  1062. /**
  1063. * if you want to redirection please override this function
  1064. * and invoke IEntityFunciton::RedirectSubscribeBroadcast
  1065. */
  1066. virtual void OnBroadcastSubscribe(CUUID /*SubID*/, const char* /*pszFromEntityName*/, const char* /*pszParam*/) { }
  1067. public:
  1068. /** get this entity name */
  1069. virtual const char* GetEntityName()const = 0;
  1070. /** get this entity version*/
  1071. virtual const char* GetEntityVersion() const { return MODULE_VERSION_FULL; }
  1072. /** is this entity hosts service ? */
  1073. virtual bool IsService()const{return false;}
  1074. #ifdef RVC_OS_WIN
  1075. #if (!defined(SPABASE_LINKED_AS_STATIC_LIBRARY) && !defined(SPBASE_EXPORTS))
  1076. private:
  1077. #endif
  1078. #endif //RVC_OS_WIN
  1079. /** dont access directly because of inner usage */
  1080. IEntityFunction* m_pEntityFunction;
  1081. };
  1082. /** server session service */
  1083. struct IServerSessionFunction
  1084. {
  1085. virtual ~IServerSessionFunction() {}
  1086. /** get client entity name */
  1087. virtual const char* GetRemoteEntityName() = 0;
  1088. /** get current state of this session */
  1089. virtual SessionStateEnum GetCurrentState() = 0;
  1090. /** close session */
  1091. virtual ErrorCodeEnum CloseSession() = 0;
  1092. };
  1093. /** server service stub, service entity must inherits and implements from here */
  1094. class CServerSessionBase
  1095. {
  1096. public:
  1097. CServerSessionBase() {}
  1098. virtual ~CServerSessionBase() { delete m_pSessionFunction; }
  1099. /** get function pointer */
  1100. CSmartPointer<IServerSessionFunction> GetFunction() { return m_pSessionFunction; }
  1101. #ifdef RVC_OS_WIN
  1102. #if (!defined(SPABASE_LINKED_AS_STATIC_LIBRARY) && !defined(SPBASE_EXPORTS))
  1103. protected:
  1104. #endif
  1105. #endif //RVC_OS_WIN
  1106. /** invoked when receives request from client */
  1107. virtual void OnRequest(CSmartPointer<ITransactionContext> pTransactionContext) = 0;
  1108. /** invoked when peer closed or network failed */
  1109. virtual void OnClose(ErrorCodeEnum eErrorCode) {}
  1110. /** The same client entity can recall a function before the last call return */
  1111. virtual bool IsSessionOverlap() { return true; }
  1112. /** server message id is overlapped ? */
  1113. virtual ErrorCodeEnum GetMessageAttr(DWORD dwMessageID, DWORD dwSignature, bool& bOverlap) = 0;
  1114. /** is exclusive ? */
  1115. virtual bool IsExclusive() { return false; }
  1116. #ifdef RVC_OS_WIN
  1117. #if (!defined(SPABASE_LINKED_AS_STATIC_LIBRARY) && !defined(SPBASE_EXPORTS))
  1118. private:
  1119. #endif
  1120. #endif //RVC_OS_WIN
  1121. /** dont access directly because of inner usage */
  1122. IServerSessionFunction* m_pSessionFunction;
  1123. };
  1124. /**
  1125. * design for supporting async request, each request in client side is named a async wait sp
  1126. * note: for two way call only
  1127. */
  1128. struct IAsynWaitSp :public IReleasable
  1129. {
  1130. /**Get Caller function name string */
  1131. virtual const char* GetFuctionName() = 0;
  1132. virtual ErrorCodeEnum GetExpireTime(DWORD& dwWholeTime, DWORD& dwLeftTime) = 0;
  1133. /** wait for remote to answer */
  1134. virtual ErrorCodeEnum WaitAnswer(DWORD dwTimeout = INFINITE) = 0;
  1135. /** cancel the pending call */
  1136. virtual ErrorCodeEnum CancelWait() = 0;
  1137. /** decide whether operation is doing */
  1138. virtual bool IsPending() = 0;
  1139. /** get request message id */
  1140. virtual DWORD GetMessageID() = 0;
  1141. /**
  1142. * when request has finished, call this method to fetch remote buffer
  1143. * @param ReceivedBuffer get service side sent out buffer, can be zero length
  1144. * @param bEnd the last response message received, this indicator support multiple return responses
  1145. */
  1146. virtual ErrorCodeEnum AsyncGetAnswer(CAutoBuffer& ReceiveBuffer, bool& bEnd) = 0;
  1147. /**just get the result code */
  1148. virtual ErrorCodeEnum AsyncGetAnswer()=0;
  1149. virtual ErrorCodeEnum AsyncGetAnswer(DWORD& dwUserError) = 0;
  1150. /**get the result code and user code*/
  1151. virtual ErrorCodeEnum AsyncGetAnswer(DWORD& dwUserError, CSimpleString& str) = 0;
  1152. virtual CSmartPointer<IReleasable> GetCallContext() = 0;
  1153. virtual bool GetCallback(CSmartPointer<ICallbackListener>& pCallback, CSmartPointer<IReleasable>& pContext) = 0;
  1154. /** set callback on, default is off(blocking). The context object inherit IReleasable and must rewrite deconstruction to release temp object*/
  1155. virtual void SetCallback(ICallbackListener* pCallback, IReleasable* pContext = NULL) = 0;
  1156. /** wait for remote to answer
  1157. * @param dwUserError entity custom error code
  1158. */
  1159. virtual ErrorCodeEnum WaitAnswer(DWORD& dwUserError, CSimpleString& str, DWORD dwTimeout) = 0;
  1160. /**
  1161. * when request has finished, call this method to fetch remote buffer
  1162. * @param ReceivedBuffer get service side sent out buffer, can be zero length
  1163. * @param bEnd the last response message received, this indicator support multiple return responses
  1164. * @param dwUserError entity custom error code
  1165. */
  1166. virtual ErrorCodeEnum AsyncGetAnswer(CAutoBuffer& ReceiveBuffer, bool& bEnd, DWORD& dwUserError, CSimpleString& str) = 0;
  1167. };
  1168. /** wait for multi IAsynWaitSp */
  1169. SPBASE_API ErrorCodeEnum WaitMultiAnswers(CAutoArray<IAsynWaitSp*> arrAsynWaits, DWORD& dwRetIndex, bool bWaitAll = false, DWORD dwTimeOut = 0);
  1170. /** client session */
  1171. struct IClientSessionFunction :public IReleasable
  1172. {
  1173. /** one way call with buffer */
  1174. virtual ErrorCodeEnum OnewayCall(DWORD dwMessageID, DWORD dwMessageSignature, CAutoBuffer Buffer) = 0;
  1175. /** one way call */
  1176. virtual ErrorCodeEnum OnewayCall(DWORD dwMessageID, DWORD dwMessageSignature) = 0;
  1177. //one way withContext
  1178. virtual ErrorCodeEnum OnewayCall(DWORD dwMessageID, DWORD dwMessageSignature, CAutoBuffer Buffer, linkContext& pContext) = 0;
  1179. virtual ErrorCodeEnum OnewayCall(DWORD dwMessageID, DWORD dwMessageSignature, linkContext& pContext) = 0;
  1180. /**
  1181. * two way call with buffer
  1182. * @param nMessageID [in] application defined message id
  1183. * @param Buffer [in] application defined buffer data
  1184. * @param pAsynWaitSp [out], required
  1185. * @param dwTimeOut [in],option,default used system 's timeout constant
  1186. */
  1187. virtual ErrorCodeEnum AsyncRequest(DWORD dwMessageID, DWORD dwMessageSignature, CAutoBuffer Buffer, CSmartPointer<IAsynWaitSp>& pAsynWaitSp, DWORD dwTimeOut = 0, DWORD dwReqId = -1) = 0;
  1188. //with linkContext
  1189. virtual ErrorCodeEnum AsyncRequest(DWORD dwMessageID, DWORD dwMessageSignature, CAutoBuffer Buffer, CSmartPointer<IAsynWaitSp>& pAsynWaitSp, linkContext& pContext, DWORD dwTimeOut = 0, DWORD dwReqId = -1) = 0;
  1190. virtual ErrorCodeEnum AsyncRequest(DWORD dwMessageID, DWORD dwMessageSignature, CSmartPointer<IAsynWaitSp>& pAsynWaitSp, linkContext& pContext, DWORD dwTimeOut = 0, DWORD dwReqId = -1) = 0;
  1191. /** call without buffer */
  1192. virtual ErrorCodeEnum AsyncRequest(DWORD dwMessageID, DWORD dwMessageSignature, CSmartPointer<IAsynWaitSp>& pAsynWaitSp, DWORD dwTimeOut = 0, DWORD dwReqId = -1) = 0;
  1193. /** get peer entity name */
  1194. virtual const char* GetRemoteEntityName() = 0;
  1195. /** get current state */
  1196. virtual SessionStateEnum GetCurrentState() = 0;
  1197. /** close session */
  1198. virtual ErrorCodeEnum CloseSession() = 0;
  1199. };
  1200. /** client must implement this */
  1201. class SPBASE_API CClientSessionBase
  1202. {
  1203. public:
  1204. CClientSessionBase() : m_pSessionFunction(NULL) {}
  1205. virtual ~CClientSessionBase();
  1206. CSmartPointer<IClientSessionFunction> GetFunction() { return m_pSessionFunction; }
  1207. /** invoked when connected ok, in async mode */
  1208. virtual void OnConnectSucceed() {}
  1209. /** invoked when peer closed or network failed */
  1210. virtual void OnClose(ErrorCodeEnum /*eErrorCode*/) {}
  1211. /** invoke when delete the object */
  1212. virtual void OnDestroy() { delete this; }
  1213. #ifdef RVC_OS_WIN
  1214. #if (!defined(SPABASE_LINKED_AS_STATIC_LIBRARY) && !defined(SPBASE_EXPORTS))
  1215. private:
  1216. #else
  1217. public:
  1218. #endif
  1219. #else
  1220. public:
  1221. #endif //RVC_OS_WIN
  1222. IClientSessionFunction* m_pSessionFunction;
  1223. };
  1224. /** user module must inherit from ModuleBase */
  1225. class SPBASE_API ModuleBase
  1226. {
  1227. public:
  1228. ModuleBase();
  1229. virtual ~ModuleBase();
  1230. virtual ErrorCodeEnum Init();
  1231. virtual ErrorCodeEnum Exit();
  1232. virtual BOOL DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved);
  1233. HINSTANCE GetInstance() { return m_hInstance; }
  1234. static ModuleBase* GetModuleBase();
  1235. protected:
  1236. /** register your entity via this method to framework */
  1237. ErrorCodeEnum RegistEntity(CEntityBase *pEntity);
  1238. ErrorCodeEnum UnregistEntity(CEntityBase *pEntity);
  1239. ErrorCodeEnum GetRegistEntity(const char *pszEntityName,CSmartPointer<CEntityBase> &pEntity);
  1240. #ifdef RVC_OS_WIN
  1241. #if (!defined(SPABASE_LINKED_AS_STATIC_LIBRARY) && !defined(SPBASE_EXPORTS))
  1242. protected:
  1243. #else
  1244. public:
  1245. #endif
  1246. #else
  1247. public:
  1248. #endif //RVC_OS_WIN
  1249. int m_nEntityCount;
  1250. CEntityBase* m_pEntityArray[32];
  1251. static ModuleBase* s_pModuleInst;
  1252. HINSTANCE m_hInstance;
  1253. };
  1254. #define SP_BEGIN_ENTITY_MAP() \
  1255. class SpEntityModuleStub : public ModuleBase \
  1256. { \
  1257. public: \
  1258. SpEntityModuleStub() \
  1259. {
  1260. #define SP_ENTITY(cls) \
  1261. m_pEntityArray[m_nEntityCount++] = dynamic_cast<CEntityBase*>(new cls());
  1262. #ifdef RVC_OS_WIN
  1263. #define SP_END_ENTITY_MAP() \
  1264. } \
  1265. }; \
  1266. SpEntityModuleStub g_ModuleInst; \
  1267. extern "C" BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) \
  1268. { \
  1269. return g_ModuleInst.DllMain(hInstance, dwReason, lpReserved); \
  1270. }
  1271. #else // RVC_OS_WIN
  1272. #define SP_END_ENTITY_MAP() \
  1273. } \
  1274. }; \
  1275. SpEntityModuleStub g_ModuleInst; \
  1276. extern "C" void __attribute__((constructor)) SoMain() {\
  1277. g_ModuleInst.DllMain(NULL, DLL_PROCESS_ATTACH, NULL); \
  1278. }
  1279. /*
  1280. extern "C" void __attribute__((constructor)) SoEnd() {
  1281. DllMain(NULL, DLL_PROCESS_DETACH, NULL);
  1282. }
  1283. */
  1284. #endif // RVC_OS_WIN
  1285. #include "log_define.h"
  1286. class SPBASE_API DbgToBeidou {
  1287. public:
  1288. DbgToBeidou(const linkContext& t_context, CSimpleStringA t_Api);//link, //当前调用的API
  1289. ~DbgToBeidou();
  1290. DbgToBeidou& setHost(CSimpleStringA t_host);//请求链接地址
  1291. DbgToBeidou& setReturnCode(CSimpleStringA t_returncode);
  1292. DbgToBeidou& setResponseTime(CSimpleStringA t_responseTime);
  1293. DbgToBeidou& setCallStack(CSimpleStringA t_callStack);//调用堆栈,格式("callStack":[{“xxx”:"xx","xxxx":sdfs}])
  1294. DbgToBeidou& setDbStack(CSimpleStringA t_dbStack);//格式("dbStack":[{“xxxxx”:"xxdfsdfs","xxddddxx":sdsddsdfs}])
  1295. DbgToBeidou& setTags(CSimpleStringA t_Tags);
  1296. DbgToBeidou& set_deployUnitId(CSimpleString t_deployUnitId);
  1297. DbgToBeidou& set_serviceUnitId(CSimpleString t_serviceUnitId);
  1298. DbgToBeidou& withLogProducer(void* t_logProducer);
  1299. void operator () () const;
  1300. private:
  1301. class Beidou_private;
  1302. Beidou_private* const m_priPtr;
  1303. char CharZero[2];
  1304. private:
  1305. DbgToBeidou(const DbgToBeidou&) : m_priPtr(NULL) {};
  1306. const DbgToBeidou& operator=(const DbgToBeidou&) { return *this; };
  1307. };
  1308. class SPBASE_API DbgWithLink {
  1309. public:
  1310. DbgWithLink(LOG_LEVEL_E t_level, LOG_TYPE_E t_type);
  1311. ~DbgWithLink();
  1312. //用户、系统日志均必填,交易处理结果代码,0表示处理成功,其他表示失败,可为系统本身的错误码,也可为后台系统返回的错误码
  1313. DbgWithLink& setResultCode(CSimpleStringA t_ResultCode);
  1314. //用户、系统日志均必填,业务跟踪ID, 32字节长度的字符串,唯一识别每笔请求
  1315. DbgWithLink& setTraceID(CSimpleStringA t_TraceID);
  1316. //用户、系统日志LOG_LEVEL_WARN以上必填
  1317. //交易处理结果信息,包括成功与失败信息,可为系统本身的成功/失败信息,也可为后台系统返回的成功/失败信息.
  1318. DbgWithLink& setResultMsg(CSimpleStringA t_ResultMsg);
  1319. //用户日志必填,日志码
  1320. //终端中标识各个交易如读卡、读取身份证等。如果终端由于客观原因无法识别交易场景,则可字段由上游传入。
  1321. DbgWithLink& setLogCode(CSimpleStringA t_LogCode);
  1322. DbgWithLink& setAPI(CSimpleStringA t_API);//用户日志必填,请求路径/接口名称.
  1323. DbgWithLink& setBussID(CSimpleStringA t_BussID);//用户日志必填,请求业务ID
  1324. DbgWithLink& setTipMsg(CSimpleStringA t_TipMsg);//用户日志LOG_LEVEL_WARN以上必填,直接向客户展示的报错信息.
  1325. DbgWithLink& setSourceType(CSimpleStringA t_SourceType);//系统日志LOG_LEVEL_FATAL必填,异常来源类型
  1326. DbgWithLink& setBeginTime(long t_BeginTime);//用户日志必填, 请求发送/接收时间
  1327. DbgWithLink& setEndTime(long t_EndTime);//用户日志必填, 响应接收 / 应答时间
  1328. DbgWithLink& setCostTime(long t_costTime);//消耗时间,自定义字段,单位ms
  1329. DbgWithLink& setVtmCode(CSimpleStringA t_VtmCode);//VtmCode,记录原告警
  1330. DbgWithLink& withLogProducer(void* t_logProducer);
  1331. DbgWithLink& withExtendLog(bool t_doLog);//是否log到文件中,并行阶段需要log到文件
  1332. void operator () (const char* str, ...) const;
  1333. void operator () () const;
  1334. private:
  1335. class Link_private;
  1336. Link_private* const m_priPtr;
  1337. private:
  1338. DbgWithLink(const DbgWithLink&) : m_priPtr(NULL) {};
  1339. const DbgWithLink& operator=(const DbgWithLink&) { return *this; };
  1340. };
  1341. class SPBASE_API EntityResource {
  1342. public:
  1343. static void setLink(const linkContext& cur);
  1344. static const linkContext& getLink();
  1345. static void clearLink();
  1346. static void setSaveFile(int t_saveFile) { m_saveFile = t_saveFile; };
  1347. static int getSaveFile() { return m_saveFile; };
  1348. private:
  1349. static linkContext m_link;
  1350. static int m_saveFile;
  1351. };
  1352. //创建日志存储模块,通常由sphost自动创建,不需要实体创建, CmptId, CmptName一般使用默认值
  1353. SPBASE_API void* create_log_producer_storage(CSimpleStringA entityName, CSimpleStringA item, CSimpleStringA filePath, CSimpleStringA CmptId, CSimpleString CmptName);
  1354. SPBASE_API void destroy_log_producer_storage(void* obj);
  1355. //创建日志上传模块,通常由spshell自动创建,然后上传
  1356. SPBASE_API void* create_log_producer_send(CSimpleStringA endpoint, CSimpleStringA topicSys, CSimpleStringA topicUser, CSimpleStringA topicBeidou, CSimpleStringA bussinessSys, CSimpleStringA bussinessUser, CSimpleStringA topicVTMWeb,
  1357. CSimpleStringA terminalNo, CSimpleStringA sn, CSimpleStringA filePath, int sendWaitTime);
  1358. SPBASE_API void destroy_log_producer_send();
  1359. //创建实体日志默认上传模块, SpShell 和 SpRun 中调用,内部调用 create_log_producer_storage
  1360. SPBASE_API bool create_log_producer_default(CSimpleStringA entityName, int idx);
  1361. SPBASE_API void destroy_log_producer_default();
  1362. SPBASE_API void load_debugLevelInCentersetting(const char* fileName);
  1363. SPBASE_API bool refreshLogLevel();
  1364. SPBASE_API int getCurLogLevel();
  1365. SPBASE_API ErrorCodeEnum GetAllEntityIdx(CAutoArray<CSimpleStringA>& strEntityNames, CAutoArray<WORD>& wEntityDevelopIDs);
  1366. /** log via shell */
  1367. SPBASE_API void LogEvent(const SeverityLevelEnum eLevel,DWORD dwUserEventCode,const char *pszMessage);
  1368. SPBASE_API void LogError(const SeverityLevelEnum eLevel, ErrorCodeEnum dwSysErrorCode,DWORD dwUserErrorCode,const char *pszMessage);
  1369. SPBASE_API void LogWarn(const SeverityLevelEnum eLevel, ErrorCodeEnum dwSysErrorCode,DWORD dwUserErrorCode, const char *pszMessage);
  1370. SPBASE_API void LogFatal(const SeverityLevelEnum eLevel, ErrorCodeEnum dwSysErrorCode, DWORD dwUserErrorCode, const char* pszMessage);
  1371. SPBASE_API void LogAssert(const char *pszMessage,const char *pszSourceFile,const int nLine);
  1372. SPBASE_API void LogTrace(const char *pszMessage,const char *pszSourceFile,const int nLine);
  1373. SPBASE_API void LogNotify(const NotifyLevelEnum eLevel, ErrorCodeEnum dwSysErrorCode, DWORD dwUserErrorCode, const char* pszMessage);
  1374. SPBASE_API void LogEvent(const SeverityLevelEnum eLevel, DWORD dwUserEventCode, const char* pszMessage, const linkContext& t_context);
  1375. SPBASE_API void LogError(const SeverityLevelEnum eLevel, ErrorCodeEnum dwSysErrorCode, DWORD dwUserErrorCode, const char* pszMessage, const linkContext& t_context);
  1376. SPBASE_API void LogWarn(const SeverityLevelEnum eLevel, ErrorCodeEnum dwSysErrorCode, DWORD dwUserErrorCode, const char* pszMessage, const linkContext& t_context);
  1377. SPBASE_API void LogFatal(const SeverityLevelEnum eLevel, ErrorCodeEnum dwSysErrorCode, DWORD dwUserErrorCode, const char* pszMessage, const linkContext& t_context);
  1378. SPBASE_API void LogAssert(const char* pszMessage, const char* pszSourceFile, const int nLine, const linkContext& t_context);
  1379. SPBASE_API void LogTrace(const char* pszMessage, const char* pszSourceFile, const int nLine, const linkContext& t_context);
  1380. SPBASE_API CSimpleStringA GetSysErrMsg(int nErrCode);
  1381. SPBASE_API const char *_GetFileName(const char *pszFilePath);
  1382. #ifdef RVC_OS_LINUX
  1383. /*
  1384. 基于当前mod中包含有restful模块,需要把数据从framework中传递到librestful,会比较困难
  1385. (1)实际上大部分实体都没有加载restful模块,所以难以进行显示调用进行初始化。
  1386. (2)初始化的时机难以把握,因为使用restful的位置各不相同
  1387. (3)目前有大致5个实体有用到librestfulSDK,采用回调函数传参的方式,把token功能传入到mod的librestfulSDK中。
  1388. (4)此方式为临时方案,使用策略模式,封装了算法SpGetToken(),通过函数传递的方式将该策略注入到类HttpClientRequestConfig中
  1389. */
  1390. #define MAX_TOKEN_LEN 256
  1391. SPBASE_API void SpGetToken(char* channelId, char* token);
  1392. #endif
  1393. #ifdef RVC_OS_WIN //TODO: duplicate ?
  1394. #define LOG_TRACE(pMsg, ...) \
  1395. LogTrace(CSimpleStringA::Format(pMsg, __VA_ARGS__), _GetFileName(__FILE__), __LINE__)
  1396. #else
  1397. #define LOG_TRACE(pMsg, ...) \
  1398. LogTrace(CSimpleStringA::Format(pMsg, ##__VA_ARGS__), _GetFileName(__FILE__), __LINE__)
  1399. #endif //RVC_OS_WIN
  1400. extern "C" SPBASE_API void Dbg(const char *str, ...);
  1401. extern "C" SPBASE_API void vDbg(const char *str, va_list list);
  1402. extern "C" SPBASE_API const char* SpStrError(ErrorCodeEnum errorCode);
  1403. struct CScopeLog
  1404. {
  1405. CScopeLog(const char* pszMsg, const char* pszFile, int nFileLine)
  1406. : m_pszMsg(pszMsg), m_pszFile(pszFile), m_nFileLine(nFileLine)
  1407. {
  1408. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Enter %s, file: {%s}, line: {%d}", m_pszMsg, m_pszFile, m_nFileLine);
  1409. }
  1410. ~CScopeLog() { DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Leave %s, file: {%s} ,line: {%d}", m_pszMsg, m_pszFile, m_nFileLine); }
  1411. const char* m_pszMsg;
  1412. const char* m_pszFile;
  1413. int m_nFileLine;
  1414. };
  1415. #define LOG_FUNCTION() CScopeLog __FunctionScopeLog(__FUNCTION__, _GetFileName(__FILE__), __LINE__)
  1416. //TODO:
  1417. /** It is used out of the Entity class members */
  1418. #if ( (defined(_DEBUG) && defined(_MSC_VER)) )
  1419. #define LOG_ASSERT(f) do{if(!(f) && (1 == _CrtDbgReport(_CRT_ASSERT, _GetFileName(__FILE__), __LINE__, NULL, #f))) {_CrtDbgBreak(); LogAssert(#f,_GetFileName(__FILE__), __LINE__);}} while (0)
  1420. #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)
  1421. #else//( (defined(_DEBUG) && defined(_MSC_VER)))
  1422. #define LOG_ASSERT(f) if(!(f)) LogAssert(#f,_GetFileName(__FILE__), __LINE__)
  1423. #define LOG_ASSERT_MSG(f,pMsg, ...) do{ if(!(f)) LogAssert(CSimpleStringA::Format(pMsg, ##__VA_ARGS__),_GetFileName(__FILE__), __LINE__);} while (0)
  1424. #endif// ( (defined(_DEBUG) && defined(_MSC_VER)) )
  1425. #endif // __cplusplus
  1426. #endif //_RVC_SPBASE_H_