SpBase.h 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318
  1. #ifndef _RVC_SPBASE_H_
  2. #define _RVC_SPBASE_H_
  3. #pragma once
  4. #if defined(__cplusplus)
  5. #ifdef SPABASE_LINKED_AS_STATIC_LIBRARY
  6. #define SPBASE_API
  7. #else //SPABASE_LINKED_AS_STATIC_LIBRARY
  8. #ifdef _WIN32
  9. #ifdef SPBASE_EXPORTS
  10. #ifndef SPBASE_API
  11. #define SPBASE_API __declspec(dllexport)
  12. #endif
  13. #else
  14. #ifndef SPBASE_API
  15. #define SPBASE_API __declspec(dllimport)
  16. //#pragma comment(lib, "SpBase.lib")
  17. #endif
  18. #endif
  19. # elif ( defined(__GNUC__) && __GNUC__ >= 4 )
  20. #define SPBASE_API __attribute__((visibility("default")))
  21. #else // _WIN32
  22. #define SPBASE_API
  23. #endif // _WIN32
  24. #endif //SPABASE_LINKED_AS_STATIC_LIBRARY
  25. #endif // __cplusplus
  26. #ifdef _WIN32
  27. #ifndef u__int64_t
  28. #define u__int64_t unsigned __int64
  29. #endif //u__int64_t
  30. #endif
  31. #include <time.h> // for time_t
  32. #ifdef _WIN32
  33. #include<wtypes.h>
  34. #else
  35. #include <winpr/library.h>
  36. #include <winpr/synch.h>
  37. #endif // _WIN32
  38. #if defined(__cplusplus)
  39. #include "SmartPointer.h"
  40. #include "SimpleString.h"
  41. #include "AutoArray.h"
  42. #endif // __cplusplus
  43. #include "ErrorCode.h"
  44. /** define the log message type */
  45. enum LogTypeEnum
  46. {
  47. Log_Ignore=0, // ignore
  48. Log_Event=1, // Run time event
  49. Log_Warning=2, // Warning
  50. Log_Error=3, // Error notify
  51. Log_Debug=4, // debug alert ec.Assert
  52. };
  53. /** define the framework internal behavior log */
  54. enum DebugLevelEnum
  55. {
  56. Debug_None=0, // ignore
  57. Debug_Low,
  58. Debug_Middle,
  59. Debug_High,
  60. };
  61. /** The log message level */
  62. enum SeverityLevelEnum
  63. {
  64. Severity_None=0, // ignore
  65. Severity_Low,
  66. Severity_Middle,
  67. Severity_High,
  68. };
  69. enum InstallStateEnum
  70. {
  71. Install_Active, // A
  72. Install_Pending, // I
  73. Install_SetToStart, // S
  74. Install_FailRun, // F
  75. Install_RollBack, // R
  76. Install_Upgraded, // U
  77. Install_Cancelled, // C
  78. Install_WaitConfirm, // W
  79. Install_Installed, // D, only used to LightPack
  80. };
  81. /** framework state*/
  82. enum FrameworkStateEnum
  83. {
  84. FrameworkState_NotInit = 0, /** the begin state*/
  85. FrameworkState_Booting, /** the entity is starting*/
  86. FrameworkState_Running, /** the machine is providing service*/
  87. FrameworkState_Breakdown, /** the machine is sick*/
  88. FrameworkState_Repairing, /** the machine is being maintained*/
  89. FrameworkState_Upgrading, /** the software is upgrading*/
  90. FrameworkState_Rollbacking, /** the software is rollback for some reason*/
  91. FrameworkState_Recoving /** the machine is reaching running state from other state*/
  92. };
  93. /** entity state */
  94. enum EntityStateEnum
  95. {
  96. EntityState_NoStart=0, //no start before
  97. EntityState_Starting, //Entity is doing initial
  98. EntityState_Idle, //after started succeed,and have no work
  99. EntityState_Busy, //Doing Request-Answer,timing,and Pausing or coninuing work
  100. // have no see assignment anywhere [4/21/2020 17:38 Gifur]
  101. EntityState_Pause, //Pause state
  102. EntityState_UnLoading, //doing cleanning after trigger close
  103. EntityState_Lost, //Entity block not respond or exception
  104. EntityState_Close, //After close,start before
  105. EntityState_Killed, //The entity terminated as block state
  106. EntityState_Passed, //The entity pass all test case
  107. EntityState_Failed // The entity fail to pass the test case.
  108. };
  109. enum EntityCloseCauseEnum
  110. {
  111. CloseCause_Self=0, //Trigger close byte self
  112. CloseCause_Other, //another entity terminate the entity
  113. CloseCause_Lost, //The entity is Lost state, has to be released
  114. CloseCause_Dragged, //The same sp entity enter lost state,and has to be dragged to close
  115. CloseCause_ShellQuit, //shell end it as shell quit
  116. CloseCause_Crash,
  117. };
  118. /** session state */
  119. enum SessionStateEnum
  120. {
  121. SessionState_NotInit=0,
  122. SessionState_Live,
  123. SessionState_Pause,
  124. SessionState_Close,
  125. };
  126. /** reboot trigger reason code */
  127. enum RebootTriggerEnum
  128. {
  129. RebootTrigger_Unknown=0, //not alloc in api call.only not log for unknown reason so far
  130. RebootTrigger_Period, //daily or weekly
  131. RebootTrigger_FrameUpgrade, //reboot by update module£¬not reboot os
  132. RebootTrigger_OSUpgrade, //relate to outside the framework update, reboot os
  133. RebootTrigger_RollBack, //roll back to history version
  134. RebootTrigger_FailLoad, //load fail when framework start
  135. RebootTrigger_Resource, //reboot by health manager
  136. RebootTrigger_RunExcepition, //Exception lead to restart
  137. RebootTrigger_RunDead, //System is out of control in running ec watch dog reset or system dead
  138. RebootTrigger_Attacked, //framework is changed or invaded
  139. RebootTrigger_Powerdown, //Out side power is interrupt
  140. RebootTrigger_Repaired, //Framework has did some repair job in SafeLoad|Fault state and restart try to recover running
  141. RebootTrigger_ManualLocal, //reboot by local maintain
  142. RebootTrigger_ManualRemove, //reboot by remote maintain
  143. RebootTrigger_Unsubscribe, //The life of machine is over,and will not connect to backstage again
  144. RebootTrigger_DeadForever, //As some reason such as test failed, we want Framework dead and not reboot. TODO: let the Gardian know.
  145. };
  146. enum RebootWayEnum
  147. {
  148. RebootWay_Unknown=0, //If not log,only mark unknown
  149. RebootWay_Framework, //restart framework not os
  150. RebootWay_OS, //restart os not power
  151. RebootWay_Power, //restart os and power
  152. };
  153. enum EntityTestEnum
  154. {
  155. Test_ShakeHand=0,
  156. Test_Examine, //no use at current time, even in selfcheck entity, they defined it but never call it.
  157. Test_Reset,
  158. };
  159. enum ConfigTypeEnum
  160. {
  161. Config_Hardware, //Read only, for read entity hardware file
  162. Config_Software, //Read and write
  163. Config_Run, //Read and write. create in run time can't be upgrade or conver
  164. Config_Shell, //Read only, for read shell.ini file
  165. Config_Root, //Read only, for read root.ini file
  166. Config_CenterSetting, //Read only
  167. };
  168. enum ScreenEnum
  169. {
  170. Screen_Operation=0, //just has a single Operation Screen
  171. Screen_OpAndInfo=1, //has double screen Operation screen and information screen
  172. Screen_OpAndMaintain=8, //has Operation screen and Maintain screen
  173. Screen_OpAndInfoAndMaintain=9, //has 3 screen Operation screen and information screen and Maintain screen
  174. };
  175. #if defined(__cplusplus)
  176. /** for sp-software and acm machine version type */
  177. class CVersion
  178. {
  179. private:
  180. union
  181. {
  182. u__int64_t m_nVersion64;
  183. struct//Intel CPU byte order,otherwise ,need to redefine
  184. {
  185. WORD m_nBuild;
  186. WORD m_nRevision;
  187. union
  188. {
  189. DWORD m_nVersion32;
  190. struct
  191. {
  192. WORD m_nMinor;
  193. WORD m_nMajor;
  194. };
  195. };
  196. };
  197. };
  198. public:
  199. inline WORD GetMajor(){return m_nMajor;}
  200. inline WORD GetMinor(){return m_nMinor;}
  201. inline WORD GetRevision(){return m_nRevision;}
  202. inline WORD GetBuild(){return m_nBuild;}
  203. inline u__int64_t GetVersion64(){return m_nVersion64;}
  204. inline DWORD GetVersion32(){return m_nVersion32;}
  205. inline CSimpleStringA ToString(){return CSimpleStringA::Format("%d.%d.%d.%d",m_nMajor,m_nMinor,m_nRevision,m_nBuild);}
  206. inline bool operator ==(CVersion &Version){return m_nVersion64==Version.m_nVersion64;}
  207. inline bool operator !=(CVersion &Version){return m_nVersion64!=Version.m_nVersion64;}
  208. inline bool operator <(CVersion &Version){return m_nVersion64<Version.m_nVersion64;}
  209. inline bool operator >(CVersion &Version){return m_nVersion64>Version.m_nVersion64;}
  210. inline bool operator <=(CVersion &Version){return m_nVersion64<=Version.m_nVersion64;}
  211. inline bool operator >=(CVersion &Version){return m_nVersion64>=Version.m_nVersion64;}
  212. inline bool IsCompatible(CVersion &Version){return m_nVersion32==Version.m_nVersion32;}
  213. inline bool IsUpgrade(CVersion &Version){return m_nVersion32>Version.m_nVersion32;}
  214. inline CVersion &operator=(const CVersion &Version){m_nVersion64=Version.m_nVersion64;return *this;}
  215. inline CVersion(WORD nMajor,WORD nMinor):m_nMajor(nMajor),m_nMinor(nMinor),m_nRevision(0),m_nBuild(0){}
  216. inline CVersion(WORD nMajor,WORD nMinor,WORD nRevision,WORD nBulid):m_nMajor(nMajor),m_nMinor(nMinor),m_nRevision(nRevision),m_nBuild(nBulid){}
  217. inline CVersion(const CVersion &Version):m_nVersion64(Version.m_nVersion64){}
  218. inline CVersion() : m_nVersion64(0) {}
  219. inline CVersion(__int64 nVersion) : m_nVersion64(nVersion){}
  220. inline bool IsValid(){return m_nVersion64 >0;}
  221. };
  222. class SPBASE_API CSmallDateTime
  223. {
  224. DWORD m_nTimeTicks;
  225. public:
  226. static CSmallDateTime BeginTime;
  227. static CSmallDateTime EndTime;
  228. static CSmallDateTime GetNow();
  229. inline CSmallDateTime(DWORD nTimeTicks = 0):m_nTimeTicks(nTimeTicks){}
  230. inline CSmallDateTime(const CSmallDateTime &DateTime):m_nTimeTicks(DateTime.m_nTimeTicks){}
  231. inline operator DWORD () const{return m_nTimeTicks;}
  232. inline const CSmallDateTime & operator =(const CSmallDateTime &DateTime){m_nTimeTicks=DateTime.m_nTimeTicks;return *this;}
  233. inline bool operator ==(const CSmallDateTime &DateTime){return m_nTimeTicks==DateTime.m_nTimeTicks;}
  234. inline bool operator !=(const CSmallDateTime &DateTime){return m_nTimeTicks!=DateTime.m_nTimeTicks;}
  235. inline bool operator <(const CSmallDateTime &DateTime){return m_nTimeTicks<DateTime.m_nTimeTicks;}
  236. inline bool operator >(const CSmallDateTime &DateTime){return m_nTimeTicks>DateTime.m_nTimeTicks;}
  237. inline bool operator <=(const CSmallDateTime &DateTime){return m_nTimeTicks<=DateTime.m_nTimeTicks;}
  238. inline bool operator >=(const CSmallDateTime &DateTime){return m_nTimeTicks>=DateTime.m_nTimeTicks;}
  239. __time64_t GetTime64();
  240. CSimpleStringA ToTimeString();
  241. SYSTEMTIME ToSystemTime();
  242. void FromSystemTime(const SYSTEMTIME &st);
  243. };
  244. class SPBASE_API CUUID
  245. {
  246. #ifdef _WIN32
  247. #if (!defined(SPABASE_LINKED_AS_STATIC_LIBRARY) && !defined(SPBASE_EXPORTS))
  248. protected:
  249. #else
  250. public:
  251. #endif
  252. #else
  253. public:
  254. #endif //_WIN32
  255. union//Intel CPU byte order,otherwise the need to redefine
  256. {
  257. u__int64_t m_nUUID64;
  258. struct
  259. {
  260. WORD m_nAppID; //the id of the server
  261. WORD m_nDsn; //inner a Second serial
  262. DWORD m_nTimeTicks;
  263. };
  264. };
  265. static WORD m_gAppID;
  266. public:
  267. inline CUUID(const CUUID &UUID):m_nUUID64(UUID.m_nUUID64){}
  268. inline CUUID(u__int64_t nUUID64 = 0):m_nUUID64(nUUID64){}
  269. inline CSmallDateTime GetTime(){return m_nTimeTicks;}
  270. inline operator u__int64_t () const{return m_nUUID64;}
  271. inline const CUUID & operator =(const CUUID &UUID){m_nUUID64=UUID.m_nUUID64;return *this;}
  272. inline bool operator ==(const CUUID &UUID){return m_nUUID64==UUID.m_nUUID64;}
  273. inline bool operator !=(const CUUID &UUID){return m_nUUID64!=UUID.m_nUUID64;}
  274. inline bool operator <(const CUUID &UUID){return m_nUUID64<UUID.m_nUUID64;}
  275. inline bool operator >(const CUUID &UUID){return m_nUUID64>UUID.m_nUUID64;}
  276. inline bool operator <=(const CUUID &UUID){return m_nUUID64<=UUID.m_nUUID64;}
  277. inline bool operator >=(const CUUID &UUID){return m_nUUID64>=UUID.m_nUUID64;}
  278. inline DWORD GetAppID() const {return m_nAppID;}
  279. inline CSimpleStringA ToString() const { return CSimpleStringA::Format("%016llX", m_nUUID64); }
  280. static CUUID Create(const CUUID &LastUUID);
  281. };
  282. /** for GPS, for longitude, east is +, west is -, for latitude, north is +, south is - */
  283. /* e.g. N22:33:09 convert to float is 22. 5525 */
  284. class SPBASE_API CSphereVector
  285. {
  286. private:
  287. float m_fLongitude;
  288. float m_fLatitude;
  289. public:
  290. inline float GetLongitude(){return m_fLongitude;}
  291. inline float GetLatitude(){return m_fLatitude;}
  292. inline CSphereVector(float fLongitude,float fLatitude):m_fLongitude(fLongitude),m_fLatitude(fLatitude){}
  293. inline CSphereVector() : m_fLatitude(0), m_fLongitude(0) {}
  294. void GetBinaryLongitude(BYTE longitude[4]);
  295. void GetBinaryLatitude(BYTE latitude[4]);
  296. };
  297. struct CInstallInfo
  298. {
  299. CVersion PreviousInstallVersion;
  300. CVersion InstallVersion;
  301. CSmallDateTime tmSwithOverDate;
  302. CSimpleStringA InstallPack;
  303. InstallStateEnum InstallState;
  304. };
  305. struct CLightPackInfo
  306. {
  307. CSimpleStringA strPackName;
  308. CSmallDateTime tmInstalledDate;
  309. InstallStateEnum State;
  310. };
  311. /** acm machine info, information filled at installation, at root.ini */
  312. struct CSystemStaticInfo : public CInstallInfo
  313. {
  314. CSimpleStringA strTerminalID;
  315. CSimpleStringA strMachineType;
  316. CVersion MachineVersion;
  317. ScreenEnum eScreen;
  318. CVersion LatterInstallVersion; // 0 version for none
  319. CAutoArray<CLightPackInfo> LightPackInfos;
  320. WORD nTotalRunCount;
  321. WORD nTodayRunCount;
  322. CSmallDateTime tmCreateDate;
  323. CSmallDateTime tmCurrentTime;
  324. CSimpleStringA strSite;
  325. CSphereVector EnrolGPS;
  326. CSimpleStringA strEnrolAddr;
  327. //CSimpleStringA strMachineModel;
  328. };
  329. /** acm system startup info */
  330. struct CSystemRunInfo
  331. {
  332. CSmallDateTime tmStart;
  333. DebugLevelEnum eDebugLevel;
  334. FrameworkStateEnum eState;
  335. CAutoArray<CSimpleStringA> strRunningEntityNames;
  336. };
  337. /** boot info */
  338. struct CBootInfo
  339. {
  340. CVersion InstallVersion;
  341. CSmallDateTime tmStart; //the system start run time
  342. CSmallDateTime tmReboot; //The trigger reboot time and It is end of run from StartTime
  343. RebootTriggerEnum eTriggerReason;
  344. RebootWayEnum eWay;
  345. WORD wSameReasonTime;
  346. WORD wSameWayTime;
  347. };
  348. /** sp module info */
  349. struct CSpInfo
  350. {
  351. CSimpleStringA strAuthor;
  352. CSimpleStringA strCompany;
  353. CVersion SoftwareVersion;
  354. CAutoArray<CSimpleStringA> strEntitys;
  355. };
  356. /** entity configuration data */
  357. struct CEntityStaticInfo
  358. {
  359. WORD wEntityDevelopID;
  360. bool bStartedByShell; //config start by shell or not(other Entity)
  361. bool bHasPrivilege; //can support IEntityFunctionPrivilege interface
  362. bool bIndispensable; //must be start and work correct else framework will fall into "Fault" state
  363. CSimpleStringA strSpFileName;
  364. };
  365. /** entity session info */
  366. struct CEntitySessionInfo
  367. {
  368. CSimpleStringA strCallerEntity;
  369. CSimpleStringA strServiceEntity;
  370. CSmallDateTime tmStart;
  371. SessionStateEnum eState;
  372. CSmallDateTime tmBeginState;
  373. };
  374. /** entity running info */
  375. struct CEntityRunInfo
  376. {
  377. DWORD dwEntityInstanceID;
  378. CSmallDateTime tmFirstStart; //The Entity first started after framework start
  379. CSmallDateTime tmLastStart; //The nearest started of this entity instance
  380. bool bService;
  381. EntityStateEnum eState;
  382. CSmallDateTime tmBeginCurrentState;
  383. DebugLevelEnum eDebugLevel;
  384. DWORD dwUserState; //Self define state
  385. DWORD dwProcessID; //Process ID of os
  386. };
  387. struct BroadcastSubscribeInfo
  388. {
  389. CUUID SubID;
  390. CSimpleStringA strListener; // from entity's name
  391. CSimpleStringA strParam;
  392. };
  393. struct IReleasable
  394. {
  395. virtual ~IReleasable(){};
  396. };
  397. /**
  398. * entity timer for user, the timer will initialize when user call IEntityFunction::SetTimer,
  399. * until user call KillTimer
  400. * note: nTimerID is application defined value in Entity Scope !!!
  401. */
  402. struct ITimerListener
  403. {
  404. virtual void OnTimeout(DWORD dwTimerID) = 0;
  405. };
  406. /** subcribe-public pattern, sys variable used for tracking system-level events */
  407. struct ISysVarListener
  408. {
  409. virtual void OnSysVarEvent(const char *pszKey,
  410. const char *pszValue,const char *pszOldValue,const char *pszEntityName)=0;
  411. };
  412. struct ITerminalStateChangedListener
  413. {
  414. virtual void OnStateChanged(FrameworkStateEnum oldState, FrameworkStateEnum curState, const char* triggerEntity) = 0;
  415. };
  416. struct IBroadcastListener
  417. {
  418. virtual void OnBroadcastEvent(CUUID SubID, const char *pszEntityName,DWORD dwMessageId, DWORD dwMessageSignature,CAutoBuffer Buffer)=0;
  419. };
  420. struct IEntityLifeListener
  421. {
  422. /* if pszTriggerEntity=null mean created by shell*/
  423. virtual void OnCreated(const char *pszEntityName,ErrorCodeEnum eOnStartErrorCode,const char *pszCallerEntity)=0;
  424. /*Call after the entity has close or killed, eOnCloseErrorCode notic if the entity do OnClose normally and resource has beed release*/
  425. virtual void OnClosed(const char *pszEntityName,EntityCloseCauseEnum eCloseCause,ErrorCodeEnum eOnCloseErrorCode,const char *pszCallerEntity)=0;
  426. /*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*/
  427. virtual void OnException(const char *pszEntityName,const char *pszFunctionName,EntityStateEnum eState,EntityStateEnum eLastState,ErrorCodeEnum eErrorCode)=0;
  428. };
  429. struct IEntityStateListener
  430. {
  431. virtual void OnEntityStateHook(const char *pszEntityName,const char *pszTriggerEntity,EntityStateEnum eState,EntityStateEnum eLastState)=0;
  432. virtual void OnUserStateHook(const char *pszEntityName,DWORD dwState,DWORD dwLastState)=0;
  433. virtual void OnCeateConnection(const char *pszCallerEntity,const char *pszServiceEntity)=0;
  434. virtual void OnCloseConnection(const char *pszCallerEntity,const char *pszServiceEntity)=0;
  435. };
  436. /** log hooker */
  437. struct ILogListener
  438. {
  439. virtual void OnLog(const CAutoArray<CUUID> &SubIDs, const CUUID nLogID,const LogTypeEnum eLogType, const SeverityLevelEnum eLevel,
  440. const DWORD dwSysError,const DWORD dwUserCode,const DWORD dwEntityInstanceID, const WORD wEntityDevelID,
  441. const CAutoArray<DWORD> &Param, const char *pszEntityName, const char *pszModuleName,const char *pszMessage) = 0;
  442. };
  443. struct IConfigInfo
  444. {
  445. virtual ConfigTypeEnum GetConfigType() = 0;
  446. /** read/write config via shell */
  447. virtual ErrorCodeEnum ReadConfigValue(const char *pszSection, const char *pszKey,CSimpleStringA &strValue) = 0;
  448. virtual ErrorCodeEnum ReadConfigValueInt(const char *pszSection, const char *pszKey, int &iValue) = 0;
  449. /** only can write self's section, pValue=NULL for delete */
  450. virtual ErrorCodeEnum WriteConfigValue(const char *pszSection, const char *pszKey, const char *pszValue) = 0;
  451. virtual ErrorCodeEnum WriteConfigValueInt(const char *pszSection, const char *pszKey, int iValue) = 0;
  452. /** read all key-value pairs */
  453. virtual ErrorCodeEnum ReadAllKeys(const char *pszSection, CAutoArray<CSimpleStringA> &strKeys) = 0;
  454. /** get all section values */
  455. virtual ErrorCodeEnum ReadAllSections(CAutoArray<CSimpleStringA> &strSections)=0;
  456. /** write hex int values, ig: "keyName=0x4F3D012A" */
  457. virtual ErrorCodeEnum WriteConfigValueHexInt(const char *pszSection, const char *pszKey, UINT64 nValue) = 0;
  458. virtual ErrorCodeEnum ReadConfigValueHexInt(const char *pszSection, const char *pszKey, UINT64 &nValue) = 0;
  459. };
  460. struct IAsynWaitSp;
  461. /** invoked when receive answer from remote */
  462. struct ICallbackListener
  463. {
  464. virtual void OnAnswer(CSmartPointer<IAsynWaitSp> pAsynWaitSp)=0;
  465. };
  466. struct IEntityPersistObject;
  467. /** object serialize mechanism, reader interface */
  468. struct IEntityPersistStreamRead
  469. {
  470. virtual ErrorCodeEnum Get(const char *pszKey,CSimpleStringA &strValue)=0;
  471. virtual ErrorCodeEnum Get(const char *pszKey,ULONGLONG &qwValue)=0;
  472. virtual ErrorCodeEnum Get(const char *pszKey,DWORD &dwValue)=0;
  473. virtual ErrorCodeEnum Get(const char *pszKey,WORD &wValue)=0;
  474. virtual ErrorCodeEnum Get(const char *pszKey,BYTE &cValue)=0;
  475. virtual ErrorCodeEnum Get(const char *pszKey,FLOAT &fValue)=0;
  476. virtual ErrorCodeEnum Get(const char *pszKey,DOUBLE &fValue)=0;
  477. virtual ErrorCodeEnum Get(const char *pszKey,IEntityPersistObject *pValue)=0;
  478. virtual ErrorCodeEnum GetArray(const char *pszKey,CAutoArray<CSimpleStringA> &strValues)=0;
  479. virtual ErrorCodeEnum GetArray(const char *pszKey,CAutoArray<ULONGLONG> &qwValues)=0;
  480. virtual ErrorCodeEnum GetArray(const char *pszKey,CAutoArray<DWORD> &dwValues)=0;
  481. virtual ErrorCodeEnum GetArray(const char *pszKey,CAutoArray<WORD> &wValues)=0;
  482. virtual ErrorCodeEnum GetArray(const char *pszKey,CAutoArray<BYTE> &cValues)=0;
  483. virtual ErrorCodeEnum GetArray(const char *pszKey,CAutoArray<FLOAT> &fValues)=0;
  484. virtual ErrorCodeEnum GetArray(const char *pszKey,CAutoArray<DOUBLE> &fValues)=0;
  485. };
  486. /** object serialize mechanism, writer interface */
  487. struct IEntityPersistStreamWrite
  488. {
  489. virtual ErrorCodeEnum Set(const char *pszKey,const char *pszValue)=0;
  490. virtual ErrorCodeEnum Set(const char *pszKey,const ULONGLONG qwValue)=0;
  491. virtual ErrorCodeEnum Set(const char *pszKey,const DWORD dwValue)=0;
  492. virtual ErrorCodeEnum Set(const char *pszKey,const WORD wValue)=0;
  493. virtual ErrorCodeEnum Set(const char *pszKey,const BYTE cValue)=0;
  494. virtual ErrorCodeEnum Set(const char *pszKey,const FLOAT fValue)=0;
  495. virtual ErrorCodeEnum Set(const char *pszKey,const DOUBLE fValue)=0;
  496. virtual ErrorCodeEnum Set(const char *pszKey,const IEntityPersistObject *pValue)=0;
  497. virtual ErrorCodeEnum SetArray(const char *pszKey,const CAutoArray<CSimpleStringA> &strValues)=0;
  498. virtual ErrorCodeEnum SetArray(const char *pszKey,const CAutoArray<ULONGLONG> &qwValues)=0;
  499. virtual ErrorCodeEnum SetArray(const char *pszKey,const CAutoArray<DWORD> &dwValues)=0;
  500. virtual ErrorCodeEnum SetArray(const char *pszKey,const CAutoArray<WORD> &wValues)=0;
  501. virtual ErrorCodeEnum SetArray(const char *pszKey,const CAutoArray<BYTE> &cValues)=0;
  502. virtual ErrorCodeEnum SetArray(const char *pszKey,const CAutoArray<FLOAT> &fValues)=0;
  503. virtual ErrorCodeEnum SetArray(const char *pszKey,const CAutoArray<DOUBLE> &fValues)=0;
  504. };
  505. /** object serialize mechanism, user-defined object need to inherits from this */
  506. struct IEntityPersistObject
  507. {
  508. virtual ErrorCodeEnum OnRead(CSmartPointer<IEntityPersistStreamRead> pStream)=0;
  509. virtual ErrorCodeEnum OnWrite(CSmartPointer<IEntityPersistStreamWrite> pStream) const =0;
  510. };
  511. /** task interface */
  512. struct ITaskSp
  513. {
  514. ITaskSp() : m_ref_cnt(1) {}
  515. virtual ~ITaskSp() {}
  516. virtual void IncRef() { InterlockedIncrement(&m_ref_cnt); }
  517. virtual void DecRef() { if (0 == InterlockedDecrement(&m_ref_cnt)) {delete this;} }
  518. virtual void Process() = 0;
  519. private:
  520. LONG m_ref_cnt;
  521. };
  522. class CClientSessionBase;
  523. class CServerSessionBase;
  524. struct IEntityFunctionPrivilege;
  525. /** normal entity service */
  526. struct IEntityFunction
  527. {
  528. virtual ~IEntityFunction() {}
  529. /** get CSystemStaticInfo information */
  530. virtual ErrorCodeEnum GetSystemStaticInfo(CSystemStaticInfo &Info) = 0;
  531. virtual ErrorCodeEnum GetInstallInfo(CVersion Version,CInstallInfo &Info) = 0; //include latter/current/history version
  532. virtual bool IsPackInstalled(const char *pPackName) = 0;
  533. /**
  534. * get path define in Root.ini,
  535. * pszKey : "Data", "Rec", "Temp", "SysLog", "InterLog","UploadVideo","UploadPhoto","Downloads","Upgraded","LatterInstall","Run","SysRoot","CenterSetting"
  536. */
  537. virtual ErrorCodeEnum GetPath(const char *pszKey,CSimpleStringA &strPath) = 0;
  538. /** get system running info */
  539. virtual ErrorCodeEnum GetSystemRunInfo(CSystemRunInfo &Info)=0;
  540. /** get busy entity number and startup entity number */
  541. virtual ErrorCodeEnum GetEntityBusyRate(WORD &nBusyEntity,WORD &nAllEntity)=0;
  542. /** get reboot info,if BeforeThisTime=CSmallDateTime::BeginTime,then return last time boot info,else return the start time before BeforeThisTime record*/
  543. virtual ErrorCodeEnum GetRebootInfo(CSmallDateTime BeforeThisTime,CBootInfo &Info)=0;
  544. /** get all sp entity module file name without full path */
  545. virtual ErrorCodeEnum GetAllRegistSpFile(CAutoArray<CSimpleStringA> &strSpNames)=0;
  546. /** get sp file info */
  547. virtual ErrorCodeEnum GetSpFileInfo(const char *pszSpName,CSpInfo &Info)=0;
  548. /** get all registered entity name */
  549. virtual ErrorCodeEnum GetAllRegistedEntity(CAutoArray<CSimpleStringA> &strEntityNames,CAutoArray<WORD> &wEntityDevelopIDs)=0;
  550. virtual ErrorCodeEnum GetAllStartedEntity(CAutoArray<CSimpleStringA> &strEntityNames,CAutoArray<DWORD> &dwEntityInstanceIDs)=0;
  551. /** get the entity of the current process running info */
  552. virtual ErrorCodeEnum GetSelfEntityRunInfo(CEntityRunInfo &Info) = 0;
  553. /** get entity config info */
  554. virtual ErrorCodeEnum GetEntityStaticInfo(const char *pszEntityName,CEntityStaticInfo &Info)=0;
  555. //virtual ErrorCodeEnum GetEntityStaticInfo(WORD wEntityDevelopID,CEntityStaticInfo &Info)=0;
  556. /** get entity state via shell */
  557. virtual ErrorCodeEnum GetEntityRunInfo(const char *pszEntityName, CEntityRunInfo &Info) = 0;
  558. /** get entity all session info */
  559. virtual ErrorCodeEnum GetEntitySessionInfo(const char *pszEntityName, CAutoArray<CEntitySessionInfo> &Infos)=0;
  560. /** get entity name from instance entity ID */
  561. virtual ErrorCodeEnum GetEntityName(DWORD dwEntityInstanceID, CSimpleStringA &strName) = 0;
  562. /** get entity name from develop entity ID */
  563. virtual ErrorCodeEnum GetEntityName(WORD wEntityDevelopID,CSimpleStringA &strName) = 0;
  564. /** ini file reader/writer utility */
  565. virtual ErrorCodeEnum OpenConfig(ConfigTypeEnum eConfigType,CSmartPointer<IConfigInfo> &pConfigInfo)=0;
  566. /** Set self define state enum for out side notice */
  567. virtual ErrorCodeEnum SetUserDefineState(DWORD dwState)=0;
  568. /** only the entity has been set in shell.ini can change the value*/
  569. virtual ErrorCodeEnum SetSysVar(const char *pszKey,const char *pszValue, bool bPersist =false)=0;
  570. /** get sys variable value */
  571. virtual ErrorCodeEnum GetSysVar(const char *pszKey,CSimpleStringA &strValue)=0;
  572. /**
  573. * install sys variable
  574. * @param pszKey the sys var key you want subscribe
  575. * @param pListener user callback interface
  576. * @param dwSysEventID user defined ID, must be unique in entity scope
  577. */
  578. virtual ErrorCodeEnum RegistSysVarEvent(const char *pszKey,ISysVarListener *pListener)=0;
  579. /*if pszKey=NULL mean unregist all keys event*/
  580. virtual ErrorCodeEnum UnregistSysVarEvent(const char *pszKey)=0;
  581. /*!
  582. * @brief
  583. * @param pListener the sub class boject pointer inherit ITerminalStateChangedListener and implement
  584. * OnStateChanged interface.
  585. * @return : Error_Succeed if regist successfully, other means failure.
  586. */
  587. virtual ErrorCodeEnum RegistTerminalStateChangeEvent(ITerminalStateChangedListener* pListener) = 0;
  588. /*!
  589. * @brief
  590. * @return : Error_Succeed if unregist successfully
  591. */
  592. virtual ErrorCodeEnum UnregistTerminalStateChangeEvent() = 0;
  593. /**
  594. * every entity can broadcast messages, user entity can subscribe an entity's broadcast messages
  595. */
  596. virtual ErrorCodeEnum SendBroadcast(DWORD dwMessageId, DWORD dwMessageSignature,CAutoBuffer Buffer)=0;
  597. virtual ErrorCodeEnum GetBroadcastReceivers(CAutoArray<BroadcastSubscribeInfo> &Subscribers)=0;
  598. virtual ErrorCodeEnum SubscribeBroadcast(const char *pszRemoteEntity, const char *pszParam, IBroadcastListener *pListener, CUUID &SubscribeID)=0;
  599. virtual ErrorCodeEnum UnsubscribeBroadcast(CUUID SubscribeID)=0;
  600. virtual ErrorCodeEnum UnsubscribeBroadcast(const char *pszRemoteEntity)=0;
  601. /**
  602. * subscribe log via shell
  603. * @param listener user's specific callback, null to cancel
  604. * @param eLevel will get log more(or equal) importance than eLevel,
  605. * @param pszEntityName if not null will get log only for that "pszEntityName" appoint one
  606. * @param eSysError Error_IgnoreAll means accept any sys error
  607. * @param dwUserCode -2 means accept any user code, -1 means accept log which has user code(nonzero)
  608. * @param bIgnoreMessage if true then pszMessage will not be send to save bandwidth
  609. */
  610. virtual ErrorCodeEnum SubscribeLog(CUUID &SubscribeID, ILogListener *pListener,LogTypeEnum eLogType=Log_Ignore,SeverityLevelEnum eLevel=Severity_None,
  611. ErrorCodeEnum eSysError=Error_IgnoreAll,DWORD dwUserCode=0,const char *pszEntityName=NULL,bool bIgnoreMessage=true)=0;
  612. virtual ErrorCodeEnum UnsubscribeLog(CUUID SubscribeID)=0;
  613. /** force shell to dump a log file */
  614. virtual ErrorCodeEnum FlushLogFile()=0;
  615. /**
  616. * read persist object from framework's serialize directory
  617. * @param pszClass which class the object belongs
  618. * @param pszKey the object key, key is case-sensitive!!!
  619. * note: actually this object stores at dir %syspath%/Objects/<EntityName>/pszClass/pszKey
  620. * so pszClass and pszKey cannot contains chars which os file path specification forbidden, such as *, ?
  621. */
  622. virtual ErrorCodeEnum ReadPersistObject(const char *pszClass, const char *pszKey, IEntityPersistObject *pInstance)=0;
  623. /** write persist object to framework's serialize directory */
  624. virtual ErrorCodeEnum WritePersistObject(const char *pszClass, const char *pszKey, const IEntityPersistObject *pInstance)=0;
  625. /** get the number of persist object */
  626. virtual ErrorCodeEnum ReadNumOfPersistObject(const char *pClassName,DWORD &dwNum)=0;
  627. /** get class all objects keys */
  628. virtual ErrorCodeEnum GetPersistClassObjectKeys(const char *pClassName, CAutoArray<CSimpleStringA> &strKeys)=0;
  629. /** delete persist object */
  630. virtual ErrorCodeEnum DeleteKeyOfPersistObject(const char *pClassName,const char *pszKey)=0;
  631. /** walk through class objects of pClassName, Handle=0 find from beginning */
  632. virtual ErrorCodeEnum EnumKeyOfPersistObject(const char *pClassName,CSimpleStringA &strKey,DWORD &dwHandle)=0;
  633. /** delete all persist object of class pClassName */
  634. virtual ErrorCodeEnum CleanAllOfPersistObject(const char *pClassName)=0;
  635. /**
  636. * do async connect to remote entity service, after connected, then pClientSession->Onconnected will call
  637. * note: if return succeed, pClientSession will delete by system via OnDestroy
  638. * if return failed, pCilentSession need delete by user
  639. */
  640. virtual ErrorCodeEnum ConnectRemoteEntity(CClientSessionBase *pClientSession,
  641. const char *pszRemoteEntity,
  642. const char *pszParam,
  643. CSmartPointer<IAsynWaitSp> &pAsynWaitSp) = 0;
  644. /**redirect as bridged mode*/
  645. virtual ErrorCodeEnum RedirectSession(CClientSessionBase *pClientSession)=0;
  646. /**redirect when accepted*/
  647. virtual ErrorCodeEnum RedirectSession(const char *pszSuggestEntity)=0;
  648. /** redirect subscribe broadcast */
  649. virtual ErrorCodeEnum RedirectSubscribBroadcast(CUUID SubID, const char *pszSugguestEntity) = 0;
  650. /**
  651. * if entity want to close self, call this function to notify shell service,
  652. * then shell service will issue close command
  653. */
  654. virtual ErrorCodeEnum PostQuit() = 0;
  655. /**
  656. * Reload itself entity
  657. */
  658. virtual ErrorCodeEnum PostReload()=0;
  659. /**
  660. * timer functions, setup an periodic timer
  661. * @param nTimerID user defined ID, must unique in entity scope
  662. * @param pListener user override callback
  663. * @param dwInterval timer interval
  664. */
  665. virtual ErrorCodeEnum SetTimer(DWORD dwTimerID, ITimerListener *pListener, DWORD dwInterval)=0;
  666. virtual ErrorCodeEnum SetTimerData(DWORD dwTimerID, IReleasable *pData)=0;
  667. virtual ErrorCodeEnum GetTimerData(DWORD dwTimerID, CSmartPointer<IReleasable> &pData)=0;
  668. /*if dwTimerID=0 mean kill all Timer*/
  669. virtual ErrorCodeEnum KillTimer(DWORD dwTimerID)=0;
  670. virtual ErrorCodeEnum ResetTimer(DWORD dwTimerID, DWORD dwInterval)=0;
  671. virtual ErrorCodeEnum GetTimerInterval(DWORD dwTimerID, DWORD &dwInterval)=0;
  672. /** query whether this entity has privilege ? */
  673. virtual bool HasPrivilege()=0;
  674. /** get privilege pointer */
  675. virtual CSmartPointer<IEntityFunctionPrivilege> GetPrivilegeFunction() = 0;
  676. /** setup log for current thread(for user created thread) */
  677. virtual ErrorCodeEnum InitLogCurrentThread()=0;
  678. /**
  679. * start tcp bridge server at ip:port
  680. * note: mainly for silverlight usage
  681. * currently: silverlight only can use port range (4502-4506)
  682. * we provide silverlight policy server(tcp 943) at spshell.exe
  683. */
  684. virtual ErrorCodeEnum StartTcpBridgeServer(unsigned short port)=0;
  685. virtual ErrorCodeEnum StopTcpBridgeServer()=0;
  686. /**
  687. * post Task to entity's thread
  688. * FIFO(first in first out) queue tail, LIFO(last in first out)
  689. * queue head
  690. */
  691. virtual ErrorCodeEnum PostEntityTaskFIFO(ITaskSp *pTask) = 0;
  692. virtual ErrorCodeEnum PostEntityTaskLIFO(ITaskSp *pTask) = 0;
  693. /**
  694. * post task to thread pool
  695. */
  696. virtual ErrorCodeEnum PostThreadPoolTask(ITaskSp *pTask) = 0;
  697. /** request framework to delay closing */
  698. virtual ErrorCodeEnum RequestCloseDelay(WORD nSecond)=0;
  699. /** log along with params */
  700. virtual void SendLog(const LogTypeEnum eLogType,const SeverityLevelEnum eLevel,DWORD dwUserEventCode,CAutoArray<DWORD> Param,const char *pszMessage=NULL)=0;
  701. /*verify file code signature, if pass, strErrInfo is sign cert hash, else verify error info*/
  702. virtual ErrorCodeEnum VerifySignature(const char *pszSignedFile, CSimpleStringA &strErrInfo) = 0;
  703. /*show fatal error info when framework startup*/
  704. virtual ErrorCodeEnum ShowFatalError(const char *pszMsg) = 0;
  705. /*show important startup info when framework startup*/
  706. virtual ErrorCodeEnum ShowStartupInfo(const char *pszMsg) = 0;
  707. };
  708. /** normal entity no need to use this interface, use for update, health management, etc. */
  709. struct IEntityFunctionPrivilege
  710. {
  711. virtual ~IEntityFunctionPrivilege() {}
  712. /** if persist=true,the DebugLevel will be keep after restart */
  713. virtual ErrorCodeEnum SetSysDebugLevel(const char *pszEntityName,DebugLevelEnum eDebugLevel,bool bPersist=false)=0;
  714. /*upate terminal current state*/
  715. virtual ErrorCodeEnum RefreshFrameworkState(FrameworkStateEnum eState) = 0;
  716. /** get %SysRoot%\Ver\<version> 's config info */
  717. virtual ErrorCodeEnum GetSystemStaticInfoForVersion(CVersion verSoftware,CSystemStaticInfo &StaticInfo)=0;
  718. /** start a remote entity,if restart itself only been call in OnClose event,will ignore pAsynWaitSp,and will not wait*/
  719. virtual ErrorCodeEnum StartEntity(const char *pszEntityName, const char *pszCmdLine,CSmartPointer<IAsynWaitSp> &pAsynWaitSp)=0;
  720. /** close entity ,not use consultative mechanism */
  721. virtual ErrorCodeEnum StopEntity(const char *pszEntityName,CSmartPointer<IAsynWaitSp> &pAsynWaitSp)=0;
  722. /** require entity close and can use the consultative mechanisms */
  723. virtual ErrorCodeEnum CloseEntity(const char *pszEntityName,CSmartPointer<IAsynWaitSp> &pAsynWaitSp)=0;
  724. /** terminate entity forcefully */
  725. virtual ErrorCodeEnum TerminateEntity(const char *pszEntityName,CSmartPointer<IAsynWaitSp> &pAsynWaitSp)=0;
  726. /** pause entity */
  727. virtual ErrorCodeEnum PauseEntity(const char *pszEntityName,CSmartPointer<IAsynWaitSp> &pAsynWaitSp)=0;
  728. /** continue entity from paused state */
  729. virtual ErrorCodeEnum ContinueEntity(const char *pszEntityName,CSmartPointer<IAsynWaitSp> &pAsynWaitSp)=0;
  730. /** test whether entity state ok, a simple health-checking mechanism */
  731. virtual ErrorCodeEnum TestEntity(const char *pszEntityName,EntityTestEnum eTestType,CSmartPointer<IAsynWaitSp> &pAsynWaitSp)=0;
  732. /** register entity life event */
  733. virtual ErrorCodeEnum RegistEntityLifeEvent(IEntityLifeListener *pListener)=0;
  734. virtual ErrorCodeEnum UnregistLiftEvent()=0;
  735. /** register entity state event, when entity state changes, callback will be invoked */
  736. virtual ErrorCodeEnum RegistEntityStateEvent(const char *pszEntityName,IEntityStateListener *pListener)=0;
  737. /*If pszEntityName=NULL mean unregist all entity event*/
  738. virtual ErrorCodeEnum UnregistEntityStateEvent(const char *pszEntityName)=0;
  739. /** trigger reboot framework/machine */
  740. virtual ErrorCodeEnum Reboot(RebootTriggerEnum eTriggerReason,RebootWayEnum eWay)=0;
  741. /** show blue full-screen title, for example for system error, privilege */
  742. virtual ErrorCodeEnum DisplayBlueScreen(const char *pszTitle) = 0;
  743. /** hide blue screen */
  744. virtual ErrorCodeEnum UndisplayBlueScreen() = 0;
  745. /** SoftwareVersion used version class first 3 version No.
  746. if NewSoftwareVersion equal to current version or zero,
  747. create a new system path with a bigger Build No.
  748. if the path already exist delete it and rebuild it*/
  749. virtual ErrorCodeEnum CreateInstallNewVersion(CVersion NewSoftwareVersion,const char *pszPackageName)=0;
  750. /** Install in current version and path*/
  751. virtual ErrorCodeEnum BeginLightInstall(const char *pszPackageName)=0;
  752. //virtual ErrorCodeEnum SetUpdateSourcePath(const char *pszSourcePath)=0;
  753. /** Copy from [Temp]\[pszPackageName]\[pszRelativeFile] to install path,
  754. 1(copy only exisit); 2(copy only not exist); 3(copy always); 4(no copy if exist)*/
  755. virtual ErrorCodeEnum CopyFileToNewVersion(const char *pszRelativeFile, int nCopyMode)=0;
  756. /** pszRelativeName is in run path*/
  757. virtual ErrorCodeEnum DeleteFileInNewVersion(const char *pszRelativeName)=0;
  758. /** Set startup shell to last version shell,but not trigger to restart.next restart will run in last version path.*/
  759. virtual ErrorCodeEnum RollBackToPreviousVersion()=0;
  760. virtual ErrorCodeEnum RollBackToHistoryVersion(CVersion HistoryVersion)=0;
  761. /** Set startup shell to new version shell,next restart will run in new version path
  762. if bToSysInstall=true the SpShell.exe will not startup first,waiting Guardian.exe running install over,and started up by Guardian.exe*/
  763. virtual ErrorCodeEnum UpgradeToNewVersion(bool bToSysInstall)=0;
  764. /**If the update or rollback version succeed run, info the framework this version is ok*/
  765. virtual ErrorCodeEnum SetRunSucceed()=0;
  766. /**check if the pack has been installed*/
  767. virtual ErrorCodeEnum IsPackInstalled(const char *pszPackName, bool &bInstalled) = 0;
  768. /** os pack upgrade, run.ini has ToRun define */
  769. virtual ErrorCodeEnum BeginSysPackInstall(const char *pszPackageName, CSimpleStringA &strErrMsg) = 0;
  770. /**check if the syspack has been installed*/
  771. virtual ErrorCodeEnum IsInstalledSysPack(const char *pszPackageName) = 0;
  772. /** show system running output console, including all entity's syslog */
  773. virtual ErrorCodeEnum ShowOuputConsole() = 0;
  774. /**close output console */
  775. virtual ErrorCodeEnum CloseOuputConsole() = 0;
  776. };
  777. /**
  778. * service entity side transaction, we define call in two types:
  779. * 1) one way call, client send one way call packet, need no reply from server side
  780. * 2) two way call, client send request and server response
  781. * A transaction is a call context hosted by server entity, when one client
  782. * issues a call, at server entity side, compose a Transaction context object.
  783. */
  784. struct ITransactionContext
  785. {
  786. virtual ~ITransactionContext(){};
  787. /** decide whether client call is one way call */
  788. virtual bool IsOneWayCall() = 0;
  789. /** get request sequence id */
  790. virtual DWORD GetRequestID() = 0;
  791. /** get client buffer */
  792. virtual ErrorCodeEnum GetReceiveBuffer(DWORD &dwMessageID, DWORD &dwMessageSignature, CAutoBuffer &Buffer) = 0;
  793. /** send out response to client, only use in two way call scenario */
  794. virtual ErrorCodeEnum SendAnswer(CAutoBuffer Buffer, bool bEnd=true) = 0;
  795. /** send out response to client without buffer, this is the simplist case for the above one
  796. * 20160914: support return custom error: @dwUserError
  797. */
  798. virtual ErrorCodeEnum SendAnswer(ErrorCodeEnum eErrorCode, DWORD dwUserError=0) = 0;
  799. /** set response expired timeout value, in milliseconds */
  800. virtual ErrorCodeEnum SetExpireTime(DWORD dwMS) = 0;
  801. /** get this run process expire time left value, in milliseconds */
  802. virtual ErrorCodeEnum GetExpireTime(DWORD &dwWholeTime,DWORD &dwLeftTime) = 0;
  803. };
  804. /** The Module entity must implement the interface */
  805. class CEntityBase
  806. {
  807. public:
  808. CEntityBase():m_pEntityFunction(NULL) {}
  809. virtual ~CEntityBase() { delete m_pEntityFunction; }
  810. /** get entity service function */
  811. CSmartPointer<IEntityFunction> GetFunction() { return m_pEntityFunction; }
  812. #ifdef _WIN32
  813. #if (!defined(SPABASE_LINKED_AS_STATIC_LIBRARY) && !defined(SPBASE_EXPORTS))
  814. protected:
  815. #endif
  816. #endif //_WIN32
  817. /**
  818. * invoked when entity is being start, when starting operation finished user must call FinishStart
  819. * so the starting operation has prepared, then spbase.dll invokes OnStart
  820. */
  821. virtual void OnPreStart(CAutoArray<CSimpleStringA> strArgs,CSmartPointer<ITransactionContext> pTransactionContext) { pTransactionContext->SendAnswer(Error_Succeed) ;}
  822. virtual void OnStarted(){}
  823. /** invoked when entity pause */
  824. virtual void OnPrePause(CSmartPointer<ITransactionContext> pTransactionContext) {pTransactionContext->SendAnswer(Error_Succeed); }
  825. virtual void OnPaused(){}
  826. /** invoked when entity continue */
  827. virtual void OnPreContinue(CSmartPointer<ITransactionContext> pTransactionContext) { pTransactionContext->SendAnswer(Error_Succeed); }
  828. virtual void OnContinued(){}
  829. /** invoked when entity will be closed*/
  830. virtual void OnPreClose(EntityCloseCauseEnum eCloseCause,CSmartPointer<ITransactionContext> pTransactionContext) { pTransactionContext->SendAnswer(Error_Succeed); }
  831. /** user override this, so it is able to extend some complicated health-checking method */
  832. virtual void OnSelfTest(EntityTestEnum eTestType,CSmartPointer<ITransactionContext> pTransactionContext) { pTransactionContext->SendAnswer(Error_Succeed); }
  833. /** invoked when incoming new connection */
  834. virtual CServerSessionBase *OnNewSession(const char* /*pszRemoteEntityName*/, const char * /*pszParam*/){return NULL;}
  835. /**
  836. * if you want to redirection please override this function
  837. * and invoke IEntityFunciton::RedirectSubscribeBroadcast
  838. */
  839. virtual void OnBroadcastSubscribe(CUUID /*SubID*/, const char * /*pszFromEntityName*/, const char * /*pszParam*/) { }
  840. public:
  841. /** get this entity name */
  842. virtual const char *GetEntityName()const=0;
  843. /** is this entity hosts service ? */
  844. virtual bool IsService()const{return false;}
  845. #ifdef _WIN32
  846. #if (!defined(SPABASE_LINKED_AS_STATIC_LIBRARY) && !defined(SPBASE_EXPORTS))
  847. private:
  848. #endif
  849. #endif //_WIN32
  850. /** dont access directly because of inner usage */
  851. IEntityFunction* m_pEntityFunction;
  852. };
  853. /** server session service */
  854. struct IServerSessionFunction
  855. {
  856. virtual ~IServerSessionFunction() {}
  857. /** get client entity name */
  858. virtual const char *GetRemoteEntityName()=0;
  859. /** get current state of this session */
  860. virtual SessionStateEnum GetCurrentState()=0;
  861. /** close session */
  862. virtual ErrorCodeEnum CloseSession()=0;
  863. };
  864. /** server service stub, service entity must inherits and implements from here */
  865. class CServerSessionBase
  866. {
  867. public:
  868. CServerSessionBase() {}
  869. virtual ~CServerSessionBase(){delete m_pSessionFunction;}
  870. /** get function pointer */
  871. CSmartPointer<IServerSessionFunction> GetFunction(){return m_pSessionFunction;}
  872. #ifdef _WIN32
  873. #if (!defined(SPABASE_LINKED_AS_STATIC_LIBRARY) && !defined(SPBASE_EXPORTS))
  874. protected:
  875. #endif
  876. #endif //_WIN32
  877. /** invoked when receives request from client */
  878. virtual void OnRequest(CSmartPointer<ITransactionContext> pTransactionContext)=0;
  879. /** invoked when peer closed or network failed */
  880. virtual void OnClose(ErrorCodeEnum eErrorCode){}
  881. /** The same client entity can recall a function before the last call return */
  882. virtual bool IsSessionOverlap() { return true; }
  883. /** server message id is overlapped ? */
  884. virtual ErrorCodeEnum GetMessageAttr(DWORD dwMessageID, DWORD dwSignature, bool &bOverlap)=0;
  885. /** is exclusive ? */
  886. virtual bool IsExclusive() { return false; }
  887. #ifdef _WIN32
  888. #if (!defined(SPABASE_LINKED_AS_STATIC_LIBRARY) && !defined(SPBASE_EXPORTS))
  889. private:
  890. #endif
  891. #endif //_WIN32
  892. /** dont access directly because of inner usage */
  893. IServerSessionFunction* m_pSessionFunction;
  894. };
  895. /**
  896. * design for supporting async request, each request in client side is named a async wait sp
  897. * note: for two way call only
  898. */
  899. struct IAsynWaitSp:public IReleasable
  900. {
  901. /**Get Caller function name string */
  902. virtual const char *GetFuctionName()=0;
  903. virtual ErrorCodeEnum GetExpireTime(DWORD &dwWholeTime,DWORD &dwLeftTime)=0;
  904. /** wait for remote to answer */
  905. virtual ErrorCodeEnum WaitAnswer(DWORD dwTimeout = INFINITE) = 0;
  906. /** cancel the pending call */
  907. virtual ErrorCodeEnum CancelWait() = 0;
  908. /** decide whether operation is doing */
  909. virtual bool IsPending() = 0;
  910. /** get request message id */
  911. virtual DWORD GetMessageID() = 0;
  912. /**
  913. * when request has finished, call this method to fetch remote buffer
  914. * @param ReceivedBuffer get service side sent out buffer, can be zero length
  915. * @param bEnd the last response message received, this indicator support multiple return responses
  916. */
  917. virtual ErrorCodeEnum AsyncGetAnswer(CAutoBuffer &ReceiveBuffer, bool &bEnd) = 0;
  918. /**just get the result code */
  919. virtual ErrorCodeEnum AsyncGetAnswer()=0;
  920. virtual CSmartPointer<IReleasable> GetCallContext()=0;
  921. virtual bool GetCallback(CSmartPointer<ICallbackListener> &pCallback,CSmartPointer<IReleasable> &pContext)=0;
  922. /** set callback on, default is off(blocking). The context object inherit IReleasable and must rewrite deconstruction to release temp object*/
  923. virtual void SetCallback(ICallbackListener *pCallback,IReleasable *pContext=NULL) = 0;
  924. /** wait for remote to answer
  925. * @param dwUserError entity custom error code
  926. */
  927. virtual ErrorCodeEnum WaitAnswer(DWORD &dwUserError, DWORD dwTimeout) = 0;
  928. /**
  929. * when request has finished, call this method to fetch remote buffer
  930. * @param ReceivedBuffer get service side sent out buffer, can be zero length
  931. * @param bEnd the last response message received, this indicator support multiple return responses
  932. * @param dwUserError entity custom error code
  933. */
  934. virtual ErrorCodeEnum AsyncGetAnswer(CAutoBuffer &ReceiveBuffer, bool &bEnd, DWORD &dwUserError) = 0;
  935. };
  936. /** wait for multi IAsynWaitSp */
  937. SPBASE_API ErrorCodeEnum WaitMultiAnswers(CAutoArray<IAsynWaitSp *> arrAsynWaits, DWORD &dwRetIndex, bool bWaitAll=false, DWORD dwTimeOut = 0);
  938. /** client session */
  939. struct IClientSessionFunction:public IReleasable
  940. {
  941. /** one way call with buffer */
  942. virtual ErrorCodeEnum OnewayCall(DWORD dwMessageID, DWORD dwMessageSignature, CAutoBuffer Buffer)=0;
  943. /** one way call */
  944. virtual ErrorCodeEnum OnewayCall(DWORD dwMessageID, DWORD dwMessageSignature)=0;
  945. /**
  946. * two way call with buffer
  947. * @param nMessageID [in] application defined message id
  948. * @param Buffer [in] application defined buffer data
  949. * @param pAsynWaitSp [out], required
  950. * @param dwTimeOut [in],option,default used system 's timeout constant
  951. */
  952. virtual ErrorCodeEnum AsyncRequest(DWORD dwMessageID, DWORD dwMessageSignature, CAutoBuffer Buffer, CSmartPointer<IAsynWaitSp> &pAsynWaitSp, DWORD dwTimeOut = 0, DWORD dwReqId = -1)=0;
  953. /** call without buffer */
  954. virtual ErrorCodeEnum AsyncRequest(DWORD dwMessageID, DWORD dwMessageSignature, CSmartPointer<IAsynWaitSp> &pAsynWaitSp, DWORD dwTimeOut = 0, DWORD dwReqId = -1)=0;
  955. /** get peer entity name */
  956. virtual const char *GetRemoteEntityName()=0;
  957. /** get current state */
  958. virtual SessionStateEnum GetCurrentState() =0;
  959. /** close session */
  960. virtual ErrorCodeEnum CloseSession()=0;
  961. };
  962. /** client must implement this */
  963. class SPBASE_API CClientSessionBase
  964. {
  965. public:
  966. CClientSessionBase() : m_pSessionFunction(NULL) {}
  967. virtual ~CClientSessionBase();
  968. CSmartPointer<IClientSessionFunction> GetFunction() {return m_pSessionFunction;}
  969. /** invoked when connected ok, in async mode */
  970. virtual void OnConnectSucceed() {}
  971. /** invoked when peer closed or network failed */
  972. virtual void OnClose(ErrorCodeEnum /*eErrorCode*/) {}
  973. /** invoke when delete the object */
  974. virtual void OnDestroy() { delete this; }
  975. #ifdef _WIN32
  976. #if (!defined(SPABASE_LINKED_AS_STATIC_LIBRARY) && !defined(SPBASE_EXPORTS))
  977. private:
  978. #else
  979. public:
  980. #endif
  981. #else
  982. public:
  983. #endif //_WIN32
  984. IClientSessionFunction* m_pSessionFunction;
  985. };
  986. /** user module must inherit from ModuleBase */
  987. class SPBASE_API ModuleBase
  988. {
  989. public:
  990. ModuleBase();
  991. virtual ~ModuleBase();
  992. virtual ErrorCodeEnum Init();
  993. virtual ErrorCodeEnum Exit();
  994. virtual BOOL DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved);
  995. HINSTANCE GetInstance() { return m_hInstance; }
  996. static ModuleBase* GetModuleBase();
  997. protected:
  998. /** register your entity via this method to framework */
  999. ErrorCodeEnum RegistEntity(CEntityBase *pEntity);
  1000. ErrorCodeEnum UnregistEntity(CEntityBase *pEntity);
  1001. ErrorCodeEnum GetRegistEntity(const char *pszEntityName,CSmartPointer<CEntityBase> &pEntity);
  1002. #ifdef _WIN32
  1003. #if (!defined(SPABASE_LINKED_AS_STATIC_LIBRARY) && !defined(SPBASE_EXPORTS))
  1004. protected:
  1005. #else
  1006. public:
  1007. #endif
  1008. #else
  1009. public:
  1010. #endif //_WIN32
  1011. int m_nEntityCount;
  1012. CEntityBase* m_pEntityArray[32];
  1013. static ModuleBase* s_pModuleInst;
  1014. HINSTANCE m_hInstance;
  1015. };
  1016. #define SP_BEGIN_ENTITY_MAP() \
  1017. class SpEntityModuleStub : public ModuleBase \
  1018. { \
  1019. public: \
  1020. SpEntityModuleStub() \
  1021. {
  1022. #define SP_ENTITY(cls) \
  1023. m_pEntityArray[m_nEntityCount++] = dynamic_cast<CEntityBase*>(new cls());
  1024. #ifdef _WIN32
  1025. #define SP_END_ENTITY_MAP() \
  1026. } \
  1027. }; \
  1028. SpEntityModuleStub g_ModuleInst; \
  1029. extern "C" BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) \
  1030. { \
  1031. return g_ModuleInst.DllMain(hInstance, dwReason, lpReserved); \
  1032. }
  1033. #else
  1034. #define SP_END_ENTITY_MAP() \
  1035. } \
  1036. }; \
  1037. SpEntityModuleStub g_ModuleInst; \
  1038. extern "C" void __attribute__((constructor)) SoMain() {\
  1039. g_ModuleInst.DllMain(NULL, DLL_PROCESS_ATTACH, NULL); \
  1040. }
  1041. /*
  1042. extern "C" void __attribute__((constructor)) SoEnd() {
  1043. DllMain(NULL, DLL_PROCESS_DETACH, NULL);
  1044. }
  1045. */
  1046. #endif //_WIN32
  1047. /** log via shell */
  1048. SPBASE_API void LogEvent(const SeverityLevelEnum eLevel,DWORD dwUserEventCode,const char *pszMessage);
  1049. SPBASE_API void LogError(const SeverityLevelEnum eLevel, ErrorCodeEnum dwSysErrorCode,DWORD dwUserErrorCode,const char *pszMessage);
  1050. SPBASE_API void LogWarn(const SeverityLevelEnum eLevel, ErrorCodeEnum dwSysErrorCode,DWORD dwUserErrorCode, const char *pszMessage);
  1051. SPBASE_API void LogAssert(const char *pszMessage,const char *pszSourceFile,const int nLine);
  1052. SPBASE_API void LogTrace(const char *pszMessage,const char *pszSourceFile,const int nLine);
  1053. SPBASE_API CSimpleStringA GetSysErrMsg(int nErrCode);
  1054. SPBASE_API const char *_GetFileName(const char *pszFilePath);
  1055. #ifdef _WIN32 //TODO: duplicate ?
  1056. #define LOG_TRACE(pMsg, ...) \
  1057. LogTrace(CSimpleStringA::Format(pMsg, __VA_ARGS__), _GetFileName(__FILE__), __LINE__)
  1058. #else
  1059. #define LOG_TRACE(pMsg, ...) \
  1060. LogTrace(CSimpleStringA::Format(pMsg, ##__VA_ARGS__), _GetFileName(__FILE__), __LINE__)
  1061. #endif //_WIN32
  1062. extern "C" SPBASE_API void Dbg(const char *str, ...);
  1063. extern "C" SPBASE_API void vDbg(const char *str, va_list list);
  1064. extern "C" SPBASE_API const char* SpStrError(ErrorCodeEnum errorCode);
  1065. #if ( ( defined(_DEBUG) && defined(_MSC_VER) ) || (defined(__linux__) && !defined(NDEBUG)) )
  1066. struct CScopeLog
  1067. {
  1068. CScopeLog(const char* pszMsg, const char* pszFile, int nFileLine) : m_pszMsg(pszMsg), m_pszFile(pszFile), m_nFileLine(nFileLine) { Dbg("Enter %s, file: {%s}, line: {%d}", m_pszMsg, m_pszFile, m_nFileLine); }
  1069. ~CScopeLog() { Dbg("Leave %s, file: {%s} ,line: {%d}", m_pszMsg, m_pszFile, m_nFileLine); }
  1070. const char* m_pszMsg;
  1071. const char* m_pszFile;
  1072. int m_nFileLine;
  1073. };
  1074. #define LOG_FUNCTION() CScopeLog __FunctionScopeLog(__FUNCTION__, _GetFileName(__FILE__), __LINE__)
  1075. #else
  1076. #define LOG_FUNCTION()
  1077. #endif
  1078. //TODO:
  1079. /** It is used out of the Entity class members */
  1080. #if ( (defined(_DEBUG) && defined(_MSC_VER)) )
  1081. #define LOG_ASSERT(f) do{if(!(f) && (1 == _CrtDbgReport(_CRT_ASSERT, _GetFileName(__FILE__), __LINE__, NULL, #f))) {_CrtDbgBreak(); LogAssert(#f,_GetFileName(__FILE__), __LINE__);}} while (0)
  1082. #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)
  1083. #else//( (defined(_DEBUG) && defined(_MSC_VER)))
  1084. #define LOG_ASSERT(f) if(!(f)) LogAssert(#f,_GetFileName(__FILE__), __LINE__)
  1085. #define LOG_ASSERT_MSG(f,pMsg, ...) do{ if(!(f)) LogAssert(CSimpleStringA::Format(pMsg, ##__VA_ARGS__),_GetFileName(__FILE__), __LINE__);} while (0)
  1086. #endif// ( (defined(_DEBUG) && defined(_MSC_VER)) )
  1087. #endif // __cplusplus
  1088. #endif //_RVC_SPBASE_H_