SpBase.h 67 KB

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