SpBase.h 46 KB

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