123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221 |
- #pragma once
- #if defined(__cplusplus)
- #ifndef SPABASE_LINKED_AS_STATIC_LIBRARY
- #ifdef SPBASE_EXPORTS
- #ifndef SPBASE_API
- #define SPBASE_API __declspec(dllexport)
- #endif
- #else
- #ifndef SPBASE_API
- #define SPBASE_API __declspec(dllimport)
- #pragma comment(lib, "SpBase.lib")
- #endif
- #endif
- #else
- #define SPBASE_API
- #endif
- #endif // __cplusplus
- #include <time.h> // for time_t
- #include<wtypes.h>
- #if defined(__cplusplus)
- #include "SmartPointer.h"
- #include "SimpleString.h"
- #include "AutoArray.h"
- #endif // __cplusplus
- #include "ErrorCode.h"
- /** define the log message type */
- enum LogTypeEnum
- {
- Log_Ignore=0, // ignore
- Log_Event=1, //Run time event
- Log_Warning=2, //Warning
- Log_Error=3, //Error notify
- Log_Debug=4, //debug alert ec.Assert
- };
- /** define the framework internal behavior log */
- enum DebugLevelEnum
- {
- Debug_None=0, // ignore
- Debug_Low,
- Debug_Middle,
- Debug_High,
- };
- /** The log message level */
- enum SeverityLevelEnum
- {
- Severity_None=0, // ignore
- Severity_Low,
- Severity_Middle,
- Severity_High,
- };
- enum InstallStateEnum
- {
- Install_Active, // A
- Install_Pending, // I
- Install_SetToStart, // S
- Install_FailRun, // F
- Install_RollBack, // R
- Install_Upgraded, // U
- Install_Cancelled, // C
- Install_WaitConfirm, // W
- Install_Installed, // D, only used to LightPack
- };
- /** entity state */
- enum EntityStateEnum
- {
- EntityState_NoStart=0, //no start before
- EntityState_Starting, //Entity is doing initial
- EntityState_Idle, //after started succeed,and have no work
- EntityState_Busy, //Doing Request-Answer,timing,and Pausing or coninuing work
- EntityState_Pause, //Pause state
- EntityState_UnLoading, //doing cleanning after trigger close
- EntityState_Lost, //Entity block not respond or exception
- EntityState_Close, //After close,start before
- EntityState_Killed, //The entity terminated as block state
- };
- enum EntityCloseCauseEnum
- {
- CloseCause_Self=0, //Trigger close byte self
- CloseCause_Other, //another entity terminate the entity
- CloseCause_Lost, //The entity is Lost state, has to be released
- CloseCause_Dragged, //The same sp entity enter lost state,and has to be dragged to close
- CloseCause_ShellQuit, //shell end it as shell quit
- CloseCause_Crash,
- };
- /** session state */
- enum SessionStateEnum
- {
- SessionState_NotInit=0,
- SessionState_Live,
- SessionState_Pause,
- SessionState_Close,
- };
- /** reboot trigger reason code */
- enum RebootTriggerEnum
- {
- RebootTrigger_Unknown=0, //not alloc in api call.only not log for unknown reason so far
- RebootTrigger_Period, //daily or weekly
- RebootTrigger_FrameUpgrade, //reboot by update module£¬not reboot os
- RebootTrigger_OSUpgrade, //relate to outside the framework update, reboot os
- RebootTrigger_RollBack, //roll back to history version
- RebootTrigger_FailLoad, //load fail when framework start
- RebootTrigger_Resource, //reboot by health manager
- RebootTrigger_RunExcepition,//Exception lead to restart
- RebootTrigger_RunDead, //System is out of control in running ec watch dog reset or system dead
- RebootTrigger_Attacked, //framework is changed or invaded
- RebootTrigger_Powerdown, //Out side power is interrupt
- RebootTrigger_Repaired, //Framework has did some repair job in SafeLoad|Fault state and restart try to recover running
- RebootTrigger_ManualLocal, //reboot by local maintain
- RebootTrigger_ManualRemove, //reboot by remote maintain
- RebootTrigger_Unsubscribe, //The life of machine is over,and will not connect to backstage again
- };
- enum RebootWayEnum
- {
- RebootWay_Unknown=0, //If not log,only mark unknown
- RebootWay_Framework, //restart framework not os
- RebootWay_OS, //restart os not power
- RebootWay_Power, //restart os and power
- };
- enum EntityTestEnum
- {
- Test_ShakeHand=0,
- Test_Examine,
- Test_Reset,
- };
- enum ConfigTypeEnum
- {
- Config_Hardware, //Read only, for read entity hardware file
- Config_Software, //Read and write
- Config_Run, //Read and write. create in run time can't be upgrade or conver
- Config_Shell, //Read only, for read shell.ini file
- Config_Root, //Read only, for read root.ini file
- Config_CenterSetting, //read only
- };
- enum ScreenEnum
- {
- Screen_Operation=0, //just has a single Operation Screen
- Screen_OpAndInfo=1, //has double screen Operation screen and information screen
- Screen_OpAndMaintain=8, //has Operation screen and Maintain screen
- Screen_OpAndInfoAndMaintain=9,//has 3 screen Operation screen and information screen and Maintain screen
- };
- #if defined(__cplusplus)
- /** for sp-software and acm machine version type */
- class CVersion
- {
- private:
- union
- {
- unsigned __int64 m_nVersion64;
- struct//Intel CPU byte order,otherwise ,need to redefine
- {
- WORD m_nBuild;
- WORD m_nRevision;
- union
- {
- DWORD m_nVersion32;
- struct
- {
- WORD m_nMinor;
- WORD m_nMajor;
- };
- };
- };
- };
- public:
- inline WORD GetMajor(){return m_nMajor;}
- inline WORD GetMinor(){return m_nMinor;}
- inline WORD GetRevision(){return m_nRevision;}
- inline WORD GetBuild(){return m_nBuild;}
- inline unsigned __int64 GetVersion64(){return m_nVersion64;}
- inline DWORD GetVersion32(){return m_nVersion32;}
- inline CSimpleStringA ToString(){return CSimpleStringA::Format("%d.%d.%d.%d",m_nMajor,m_nMinor,m_nRevision,m_nBuild);}
- inline bool operator ==(CVersion &Version){return m_nVersion64==Version.m_nVersion64;}
- inline bool operator !=(CVersion &Version){return m_nVersion64!=Version.m_nVersion64;}
- inline bool operator <(CVersion &Version){return m_nVersion64<Version.m_nVersion64;}
- inline bool operator >(CVersion &Version){return m_nVersion64>Version.m_nVersion64;}
- inline bool operator <=(CVersion &Version){return m_nVersion64<=Version.m_nVersion64;}
- inline bool operator >=(CVersion &Version){return m_nVersion64>=Version.m_nVersion64;}
- inline bool IsCompatible(CVersion &Version){return m_nVersion32==Version.m_nVersion32;}
- inline bool IsUpgrade(CVersion &Version){return m_nVersion32>Version.m_nVersion32;}
- inline CVersion &operator=(const CVersion &Version){m_nVersion64=Version.m_nVersion64;return *this;}
- inline CVersion(WORD nMajor,WORD nMinor):m_nMajor(nMajor),m_nMinor(nMinor),m_nRevision(0),m_nBuild(0){}
- inline CVersion(WORD nMajor,WORD nMinor,WORD nRevision,WORD nBulid):m_nMajor(nMajor),m_nMinor(nMinor),m_nRevision(nRevision),m_nBuild(nBulid){}
- inline CVersion(const CVersion &Version):m_nVersion64(Version.m_nVersion64){}
- inline CVersion() : m_nVersion64(0) {}
- inline CVersion(__int64 nVersion) : m_nVersion64(nVersion){}
- inline bool IsValid(){return m_nVersion64 >0;}
- };
- class SPBASE_API CSmallDateTime
- {
- DWORD m_nTimeTicks;
- public:
- static CSmallDateTime BeginTime;
- static CSmallDateTime EndTime;
- static CSmallDateTime GetNow();
- inline CSmallDateTime(DWORD nTimeTicks = 0):m_nTimeTicks(nTimeTicks){}
- inline CSmallDateTime(const CSmallDateTime &DateTime):m_nTimeTicks(DateTime.m_nTimeTicks){}
- inline operator DWORD () const{return m_nTimeTicks;}
- inline const CSmallDateTime & operator =(const CSmallDateTime &DateTime){m_nTimeTicks=DateTime.m_nTimeTicks;return *this;}
- inline bool operator ==(const CSmallDateTime &DateTime){return m_nTimeTicks==DateTime.m_nTimeTicks;}
- inline bool operator !=(const CSmallDateTime &DateTime){return m_nTimeTicks!=DateTime.m_nTimeTicks;}
- inline bool operator <(const CSmallDateTime &DateTime){return m_nTimeTicks<DateTime.m_nTimeTicks;}
- inline bool operator >(const CSmallDateTime &DateTime){return m_nTimeTicks>DateTime.m_nTimeTicks;}
- inline bool operator <=(const CSmallDateTime &DateTime){return m_nTimeTicks<=DateTime.m_nTimeTicks;}
- inline bool operator >=(const CSmallDateTime &DateTime){return m_nTimeTicks>=DateTime.m_nTimeTicks;}
- __time64_t GetTime64();
- CSimpleStringA ToTimeString();
- SYSTEMTIME ToSystemTime();
- void FromSystemTime(const SYSTEMTIME &st);
- };
- class SPBASE_API CUUID
- {
-
- #ifndef SPABASE_LINKED_AS_STATIC_LIBRARY
- #ifndef SPBASE_EXPORTS
- protected:
- #else
- public:
- #endif
- #else
- public:
- #endif
-
- union//Intel CPU byte order,otherwise the need to redefine
- {
- unsigned __int64 m_nUUID64;
- struct
- {
- WORD m_nAppID; //the id of the server
- WORD m_nDsn; //inner a Second serial
- DWORD m_nTimeTicks;
- };
- };
- static WORD m_gAppID;
- public:
- inline CUUID(const CUUID &UUID):m_nUUID64(UUID.m_nUUID64){}
- inline CUUID(unsigned __int64 nUUID64 = 0):m_nUUID64(nUUID64){}
- inline CSmallDateTime GetTime(){return m_nTimeTicks;}
- inline operator unsigned __int64 () const{return m_nUUID64;}
- inline const CUUID & operator =(const CUUID &UUID){m_nUUID64=UUID.m_nUUID64;return *this;}
- inline bool operator ==(const CUUID &UUID){return m_nUUID64==UUID.m_nUUID64;}
- inline bool operator !=(const CUUID &UUID){return m_nUUID64!=UUID.m_nUUID64;}
- inline bool operator <(const CUUID &UUID){return m_nUUID64<UUID.m_nUUID64;}
- inline bool operator >(const CUUID &UUID){return m_nUUID64>UUID.m_nUUID64;}
- inline bool operator <=(const CUUID &UUID){return m_nUUID64<=UUID.m_nUUID64;}
- inline bool operator >=(const CUUID &UUID){return m_nUUID64>=UUID.m_nUUID64;}
- inline DWORD GetAppID(){return m_nAppID;}
- inline CSimpleStringA ToString() { return CSimpleStringA::Format("%016llX", m_nUUID64); }
- static CUUID Create(const CUUID &LastUUID);
- };
- /** for GPS, for longitude, east is +, west is -, for latitude, north is +, south is - */
- /* e.g. N22:33:09 convert to float is 22. 5525 */
- class SPBASE_API CSphereVector
- {
- private:
- float m_fLongitude;
- float m_fLatitude;
- public:
- inline float GetLongitude(){return m_fLongitude;}
- inline float GetLatitude(){return m_fLatitude;}
- inline CSphereVector(float fLongitude,float fLatitude):m_fLongitude(fLongitude),m_fLatitude(fLatitude){}
- inline CSphereVector() : m_fLatitude(0), m_fLongitude(0) {}
- void GetBinaryLongitude(BYTE longitude[4]);
- void GetBinaryLatitude(BYTE latitude[4]);
- };
- struct CInstallInfo
- {
- CVersion PreviousInstallVersion;
- CVersion InstallVersion;
- CSmallDateTime tmSwithOverDate;
- CSimpleStringA InstallPack;
- InstallStateEnum InstallState;
- };
- struct CLightPackInfo
- {
- CSimpleStringA strPackName;
- CSmallDateTime tmInstalledDate;
- InstallStateEnum State;
- };
- /** acm machine info, information filled at installation, at root.ini */
- struct CSystemStaticInfo : public CInstallInfo
- {
- CSimpleStringA strTerminalID;
- CSimpleStringA strMachineType;
- CVersion MachineVersion;
- ScreenEnum eScreen;
- CVersion LatterInstallVersion; // 0 version for none
- CAutoArray<CLightPackInfo> LightPackInfos;
- WORD nTotalRunCount;
- WORD nTodayRunCount;
- CSmallDateTime tmCreateDate;
- CSmallDateTime tmCurrentTime;
- CSimpleStringA strSite;
- CSphereVector EnrolGPS;
- CSimpleStringA strEnrolAddr;
- //CSimpleStringA strMachineModel;
- };
- /** acm system startup info */
- struct CSystemRunInfo
- {
- CSmallDateTime tmStart;
- DebugLevelEnum eDebugLevel;
- CAutoArray<CSimpleStringA> strRunningEntityNames;
- };
- /** boot info */
- struct CBootInfo
- {
- CVersion InstallVersion;
- CSmallDateTime tmStart; //the system start run time
- CSmallDateTime tmReboot; //The trigger reboot time and It is end of run from StartTime
- RebootTriggerEnum eTriggerReason;
- RebootWayEnum eWay;
- WORD wSameReasonTime;
- WORD wSameWayTime;
- };
- /** sp module info */
- struct CSpInfo
- {
- CSimpleStringA strAuthor;
- CSimpleStringA strCompany;
- CVersion SoftwareVersion;
- CAutoArray<CSimpleStringA> strEntitys;
- };
- /** entity configuration data */
- struct CEntityStaticInfo
- {
- WORD wEntityDevelopID;
- bool bStartedByShell; //config start by shell or not(other Entity)
- bool bHasPrivilege; //can support IEntityFunctionPrivilege interface
- bool bIndispensable; //must be start and work correct else framework will fall into "Fault" state
- CSimpleStringA strSpFileName;
- };
- /** entity session info */
- struct CEntitySessionInfo
- {
- CSimpleStringA strCallerEntity;
- CSimpleStringA strServiceEntity;
- CSmallDateTime tmStart;
- SessionStateEnum eState;
- CSmallDateTime tmBeginState;
- };
- /** entity running info */
- struct CEntityRunInfo
- {
- DWORD dwEntityInstanceID;
- CSmallDateTime tmFirstStart; //The Entity first started after framework start
- CSmallDateTime tmLastStart; //The nearest started of this entity instance
- bool bService;
- EntityStateEnum eState;
- CSmallDateTime tmBeginCurrentState;
- DebugLevelEnum eDebugLevel;
- DWORD dwUserState; //Self define state
- DWORD dwProcessID; //Process ID of os
- };
- struct BroadcastSubscribeInfo
- {
- CUUID SubID;
- CSimpleStringA strListener; // from entity's name
- CSimpleStringA strParam;
- };
- struct IReleasable
- {
- virtual ~IReleasable(){};
- };
- /**
- * entity timer for user, the timer will initialize when user call IEntityFunction::SetTimer,
- * until user call KillTimer
- * note: nTimerID is application defined value in Entity Scope !!!
- */
- struct ITimerListener
- {
- virtual void OnTimeout(DWORD dwTimerID) = 0;
- };
- /** subcribe-public pattern, sys variable used for tracking system-level events */
- struct ISysVarListener
- {
- virtual void OnSysVarEvent(const char *pszKey,
- const char *pszValue,const char *pszOldValue,const char *pszEntityName)=0;
- };
- struct IBroadcastListener
- {
- virtual void OnBroadcastEvent(CUUID SubID, const char *pszEntityName,DWORD dwMessageId, DWORD dwMessageSignature,CAutoBuffer Buffer)=0;
- };
- struct IEntityLifeListener
- {
- /* if pszTriggerEntity=null mean created by shell*/
- virtual void OnCreated(const char *pszEntityName,ErrorCodeEnum eOnStartErrorCode,const char *pszCallerEntity)=0;
- /*Call after the entity has close or killed, eOnCloseErrorCode notic if the entity do OnClose normally and resource has beed release*/
- virtual void OnClosed(const char *pszEntityName,EntityCloseCauseEnum eCloseCause,ErrorCodeEnum eOnCloseErrorCode,const char *pszCallerEntity)=0;
- /*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*/
- virtual void OnException(const char *pszEntityName,const char *pszFunctionName,EntityStateEnum eState,EntityStateEnum eLastState,ErrorCodeEnum eErrorCode)=0;
- };
- struct IEntityStateListener
- {
- virtual void OnEntityStateHook(const char *pszEntityName,const char *pszTriggerEntity,EntityStateEnum eState,EntityStateEnum eLastState)=0;
- virtual void OnUserStateHook(const char *pszEntityName,DWORD dwState,DWORD dwLastState)=0;
- virtual void OnCeateConnection(const char *pszCallerEntity,const char *pszServiceEntity)=0;
- virtual void OnCloseConnection(const char *pszCallerEntity,const char *pszServiceEntity)=0;
- };
- /** log hooker */
- struct ILogListener
- {
- virtual void OnLog(const CAutoArray<CUUID> &SubIDs, const CUUID nLogID,const LogTypeEnum eLogType, const SeverityLevelEnum eLevel,
- const DWORD dwSysError,const DWORD dwUserCode,const DWORD dwEntityInstanceID, const WORD wEntityDevelID,
- const CAutoArray<DWORD> &Param, const char *pszEntityName, const char *pszModuleName,const char *pszMessage) = 0;
- };
- struct IConfigInfo
- {
- virtual ConfigTypeEnum GetConfigType() = 0;
- /** read/write config via shell */
- virtual ErrorCodeEnum ReadConfigValue(const char *pszSection, const char *pszKey,CSimpleStringA &strValue) = 0;
- virtual ErrorCodeEnum ReadConfigValueInt(const char *pszSection, const char *pszKey, int &iValue) = 0;
- /** only can write self's section, pValue=NULL for delete */
- virtual ErrorCodeEnum WriteConfigValue(const char *pszSection, const char *pszKey, const char *pszValue) = 0;
- virtual ErrorCodeEnum WriteConfigValueInt(const char *pszSection, const char *pszKey, int iValue) = 0;
- /** read all key-value pairs */
- virtual ErrorCodeEnum ReadAllKeys(const char *pszSection, CAutoArray<CSimpleStringA> &strKeys) = 0;
- /** get all section values */
- virtual ErrorCodeEnum ReadAllSections(CAutoArray<CSimpleStringA> &strSections)=0;
- /** write hex int values, ig: "keyName=0x4F3D012A" */
- virtual ErrorCodeEnum WriteConfigValueHexInt(const char *pszSection, const char *pszKey, UINT64 nValue) = 0;
- virtual ErrorCodeEnum ReadConfigValueHexInt(const char *pszSection, const char *pszKey, UINT64 &nValue) = 0;
- };
- struct IAsynWaitSp;
- /** invoked when receive answer from remote */
- struct ICallbackListener
- {
- virtual void OnAnswer(CSmartPointer<IAsynWaitSp> pAsynWaitSp)=0;
- };
- struct IEntityPersistObject;
- /** object serialize mechanism, reader interface */
- struct IEntityPersistStreamRead
- {
- virtual ErrorCodeEnum Get(const char *pszKey,CSimpleStringA &strValue)=0;
- virtual ErrorCodeEnum Get(const char *pszKey,ULONGLONG &qwValue)=0;
- virtual ErrorCodeEnum Get(const char *pszKey,DWORD &dwValue)=0;
- virtual ErrorCodeEnum Get(const char *pszKey,WORD &wValue)=0;
- virtual ErrorCodeEnum Get(const char *pszKey,BYTE &cValue)=0;
- virtual ErrorCodeEnum Get(const char *pszKey,FLOAT &fValue)=0;
- virtual ErrorCodeEnum Get(const char *pszKey,DOUBLE &fValue)=0;
- virtual ErrorCodeEnum Get(const char *pszKey,IEntityPersistObject *pValue)=0;
- virtual ErrorCodeEnum GetArray(const char *pszKey,CAutoArray<CSimpleStringA> &strValues)=0;
- virtual ErrorCodeEnum GetArray(const char *pszKey,CAutoArray<ULONGLONG> &qwValues)=0;
- virtual ErrorCodeEnum GetArray(const char *pszKey,CAutoArray<DWORD> &dwValues)=0;
- virtual ErrorCodeEnum GetArray(const char *pszKey,CAutoArray<WORD> &wValues)=0;
- virtual ErrorCodeEnum GetArray(const char *pszKey,CAutoArray<BYTE> &cValues)=0;
- virtual ErrorCodeEnum GetArray(const char *pszKey,CAutoArray<FLOAT> &fValues)=0;
- virtual ErrorCodeEnum GetArray(const char *pszKey,CAutoArray<DOUBLE> &fValues)=0;
- };
- /** object serialize mechanism, writer interface */
- struct IEntityPersistStreamWrite
- {
- virtual ErrorCodeEnum Set(const char *pszKey,const char *pszValue)=0;
- virtual ErrorCodeEnum Set(const char *pszKey,const ULONGLONG qwValue)=0;
- virtual ErrorCodeEnum Set(const char *pszKey,const DWORD dwValue)=0;
- virtual ErrorCodeEnum Set(const char *pszKey,const WORD wValue)=0;
- virtual ErrorCodeEnum Set(const char *pszKey,const BYTE cValue)=0;
- virtual ErrorCodeEnum Set(const char *pszKey,const FLOAT fValue)=0;
- virtual ErrorCodeEnum Set(const char *pszKey,const DOUBLE fValue)=0;
- virtual ErrorCodeEnum Set(const char *pszKey,const IEntityPersistObject *pValue)=0;
- virtual ErrorCodeEnum SetArray(const char *pszKey,const CAutoArray<CSimpleStringA> &strValues)=0;
- virtual ErrorCodeEnum SetArray(const char *pszKey,const CAutoArray<ULONGLONG> &qwValues)=0;
- virtual ErrorCodeEnum SetArray(const char *pszKey,const CAutoArray<DWORD> &dwValues)=0;
- virtual ErrorCodeEnum SetArray(const char *pszKey,const CAutoArray<WORD> &wValues)=0;
- virtual ErrorCodeEnum SetArray(const char *pszKey,const CAutoArray<BYTE> &cValues)=0;
- virtual ErrorCodeEnum SetArray(const char *pszKey,const CAutoArray<FLOAT> &fValues)=0;
- virtual ErrorCodeEnum SetArray(const char *pszKey,const CAutoArray<DOUBLE> &fValues)=0;
- };
- /** object serialize mechanism, user-defined object need to inherits from this */
- struct IEntityPersistObject
- {
- virtual ErrorCodeEnum OnRead(CSmartPointer<IEntityPersistStreamRead> pStream)=0;
- virtual ErrorCodeEnum OnWrite(CSmartPointer<IEntityPersistStreamWrite> pStream) const =0;
- };
- /** task interface */
- struct ITaskSp
- {
- ITaskSp() : m_ref_cnt(1) {}
- virtual ~ITaskSp() {}
- virtual void IncRef() { InterlockedIncrement(&m_ref_cnt); }
- virtual void DecRef() { if (0 == InterlockedDecrement(&m_ref_cnt)) {delete this;} }
- virtual void Process() = 0;
- private:
- LONG m_ref_cnt;
- };
- class CClientSessionBase;
- class CServerSessionBase;
- struct IEntityFunctionPrivilege;
- /** normal entity service */
- struct IEntityFunction
- {
- virtual ~IEntityFunction() {}
- /** get CSystemStaticInfo information */
- virtual ErrorCodeEnum GetSystemStaticInfo(CSystemStaticInfo &Info) = 0;
- virtual ErrorCodeEnum GetInstallInfo(CVersion Version,CInstallInfo &Info) = 0; //include latter/current/history version
- virtual bool IsPackInstalled(const char *pPackName) = 0;
- /**
- * get path define in Root.ini,
- * pszKey : "Data", "Rec", "Temp", "SysLog", "InterLog","UploadVideo","UploadPhoto","Downloads","Upgraded","LatterInstall","Run","SysRoot","CenterSetting"
- */
- virtual ErrorCodeEnum GetPath(const char *pszKey,CSimpleStringA &strPath) = 0;
- /** get system running info */
- virtual ErrorCodeEnum GetSystemRunInfo(CSystemRunInfo &Info)=0;
- /** get busy entity number and startup entity number */
- virtual ErrorCodeEnum GetEntityBusyRate(WORD &nBusyEntity,WORD &nAllEntity)=0;
- /** get reboot info,if BeforeThisTime=CSmallDateTime::BeginTime,then return last time boot info,else return the start time before BeforeThisTime record*/
- virtual ErrorCodeEnum GetRebootInfo(CSmallDateTime BeforeThisTime,CBootInfo &Info)=0;
- /** get all sp entity module file name without full path */
- virtual ErrorCodeEnum GetAllRegistSpFile(CAutoArray<CSimpleStringA> &strSpNames)=0;
- /** get sp file info */
- virtual ErrorCodeEnum GetSpFileInfo(const char *pszSpName,CSpInfo &Info)=0;
- /** get all registered entity name */
- virtual ErrorCodeEnum GetAllRegistedEntity(CAutoArray<CSimpleStringA> &strEntityNames,CAutoArray<WORD> &wEntityDevelopIDs)=0;
- virtual ErrorCodeEnum GetAllStartedEntity(CAutoArray<CSimpleStringA> &strEntityNames,CAutoArray<DWORD> &dwEntityInstanceIDs)=0;
- /** get the entity of the current process running info */
- virtual ErrorCodeEnum GetSelfEntityRunInfo(CEntityRunInfo &Info) = 0;
- /** get entity config info */
- virtual ErrorCodeEnum GetEntityStaticInfo(const char *pszEntityName,CEntityStaticInfo &Info)=0;
- //virtual ErrorCodeEnum GetEntityStaticInfo(WORD wEntityDevelopID,CEntityStaticInfo &Info)=0;
- /** get entity state via shell */
- virtual ErrorCodeEnum GetEntityRunInfo(const char *pszEntityName, CEntityRunInfo &Info) = 0;
- /** get entity all session info */
- virtual ErrorCodeEnum GetEntitySessionInfo(const char *pszEntityName, CAutoArray<CEntitySessionInfo> &Infos)=0;
- /** get entity name from instance entity ID */
- virtual ErrorCodeEnum GetEntityName(DWORD dwEntityInstanceID, CSimpleStringA &strName) = 0;
- /** get entity name from develop entity ID */
- virtual ErrorCodeEnum GetEntityName(WORD wEntityDevelopID,CSimpleStringA &strName) = 0;
- /** ini file reader/writer utility */
- virtual ErrorCodeEnum OpenConfig(ConfigTypeEnum eConfigType,CSmartPointer<IConfigInfo> &pConfigInfo)=0;
- /** Set self define state enum for out side notice */
- virtual ErrorCodeEnum SetUserDefineState(DWORD dwState)=0;
- /** only the entity has been set in shell.ini can change the value*/
- virtual ErrorCodeEnum SetSysVar(const char *pszKey,const char *pszValue, bool bPersist =false)=0;
- /** get sys variable value */
- virtual ErrorCodeEnum GetSysVar(const char *pszKey,CSimpleStringA &strValue)=0;
- /**
- * install sys variable
- * @param pszKey the sys var key you want subscribe
- * @param pListener user callback interface
- * @param dwSysEventID user defined ID, must be unique in entity scope
- */
- virtual ErrorCodeEnum RegistSysVarEvent(const char *pszKey,ISysVarListener *pListener)=0;
- /*if pszKey=NULL mean unregist all keys event*/
- virtual ErrorCodeEnum UnregistSysVarEvent(const char *pszKey)=0;
- /**
- * every entity can broadcast messages, user entity can subscribe an entity's broadcast messages
- */
- virtual ErrorCodeEnum SendBroadcast(DWORD dwMessageId, DWORD dwMessageSignature,CAutoBuffer Buffer)=0;
- virtual ErrorCodeEnum GetBroadcastReceivers(CAutoArray<BroadcastSubscribeInfo> &Subscribers)=0;
- virtual ErrorCodeEnum SubscribeBroadcast(const char *pszRemoteEntity, const char *pszParam, IBroadcastListener *pListener, CUUID &SubscribeID)=0;
- virtual ErrorCodeEnum UnsubscribeBroadcast(CUUID SubscribeID)=0;
- virtual ErrorCodeEnum UnsubscribeBroadcast(const char *pszRemoteEntity)=0;
- /**
- * subscribe log via shell
- * @param listener user's specific callback, null to cancel
- * @param eLevel will get log more(or equal) importance than eLevel,
- * @param pszEntityName if not null will get log only for that "pszEntityName" appoint one
- * @param eSysError Error_IgnoreAll means accept any sys error
- * @param dwUserCode -2 means accept any user code, -1 means accept log which has user code(nonzero)
- * @param bIgnoreMessage if true then pszMessage will not be send to save bandwidth
- */
- virtual ErrorCodeEnum SubscribeLog(CUUID &SubscribeID, ILogListener *pListener,LogTypeEnum eLogType=Log_Ignore,SeverityLevelEnum eLevel=Severity_None,
- ErrorCodeEnum eSysError=Error_IgnoreAll,DWORD dwUserCode=0,const char *pszEntityName=NULL,bool bIgnoreMessage=true)=0;
- virtual ErrorCodeEnum UnsubscribeLog(CUUID SubscribeID)=0;
- /** force shell to dump a log file */
- virtual ErrorCodeEnum FlushLogFile()=0;
- /**
- * read persist object from framework's serialize directory
- * @param pszClass which class the object belongs
- * @param pszKey the object key, key is case-sensitive!!!
- * note: actually this object stores at dir %syspath%/Objects/<EntityName>/pszClass/pszKey
- * so pszClass and pszKey cannot contains chars which os file path specification forbidden, such as *, ?
- */
- virtual ErrorCodeEnum ReadPersistObject(const char *pszClass, const char *pszKey, IEntityPersistObject *pInstance)=0;
- /** write persist object to framework's serialize directory */
- virtual ErrorCodeEnum WritePersistObject(const char *pszClass, const char *pszKey, const IEntityPersistObject *pInstance)=0;
- /** get the number of persist object */
- virtual ErrorCodeEnum ReadNumOfPersistObject(const char *pClassName,DWORD &dwNum)=0;
- /** get class all objects keys */
- virtual ErrorCodeEnum GetPersistClassObjectKeys(const char *pClassName, CAutoArray<CSimpleStringA> &strKeys)=0;
- /** delete persist object */
- virtual ErrorCodeEnum DeleteKeyOfPersistObject(const char *pClassName,const char *pszKey)=0;
- /** walk through class objects of pClassName, Handle=0 find from beginning */
- virtual ErrorCodeEnum EnumKeyOfPersistObject(const char *pClassName,CSimpleStringA &strKey,DWORD &dwHandle)=0;
- /** delete all persist object of class pClassName */
- virtual ErrorCodeEnum CleanAllOfPersistObject(const char *pClassName)=0;
- /**
- * do async connect to remote entity service, after connected, then pClientSession->Onconnected will call
- * note: if return succeed, pClientSession will delete by system via OnDestroy
- * if return failed, pCilentSession need delete by user
- */
- virtual ErrorCodeEnum ConnectRemoteEntity(CClientSessionBase *pClientSession,
- const char *pszRemoteEntity,
- const char *pszParam,
- CSmartPointer<IAsynWaitSp> &pAsynWaitSp) = 0;
- /**redirect as bridged mode*/
- virtual ErrorCodeEnum RedirectSession(CClientSessionBase *pClientSession)=0;
-
- /**redirect when accepted*/
- virtual ErrorCodeEnum RedirectSession(const char *pszSuggestEntity)=0;
- /** redirect subscribe broadcast */
- virtual ErrorCodeEnum RedirectSubscribBroadcast(CUUID SubID, const char *pszSugguestEntity) = 0;
- /**
- * if entity want to close self, call this function to notify shell service,
- * then shell service will issue close command
- */
- virtual ErrorCodeEnum PostQuit() = 0;
-
- /**
- * Reload itself entity
- */
- virtual ErrorCodeEnum PostReload()=0;
- /**
- * timer functions, setup an periodic timer
- * @param nTimerID user defined ID, must unique in entity scope
- * @param pListener user override callback
- * @param dwInterval timer interval
- */
- virtual ErrorCodeEnum SetTimer(DWORD dwTimerID, ITimerListener *pListener, DWORD dwInterval)=0;
- virtual ErrorCodeEnum SetTimerData(DWORD dwTimerID, IReleasable *pData)=0;
- virtual ErrorCodeEnum GetTimerData(DWORD dwTimerID, CSmartPointer<IReleasable> &pData)=0;
- /*if dwTimerID=0 mean kill all Timer*/
- virtual ErrorCodeEnum KillTimer(DWORD dwTimerID)=0;
- virtual ErrorCodeEnum ResetTimer(DWORD dwTimerID, DWORD dwInterval)=0;
- virtual ErrorCodeEnum GetTimerInterval(DWORD dwTimerID, DWORD &dwInterval)=0;
- /** query whether this entity has privilege ? */
- virtual bool HasPrivilege()=0;
- /** get privilege pointer */
- virtual CSmartPointer<IEntityFunctionPrivilege> GetPrivilegeFunction() = 0;
- /** setup log for current thread(for user created thread) */
- virtual ErrorCodeEnum InitLogCurrentThread()=0;
- /**
- * start tcp bridge server at ip:port
- * note: mainly for silverlight usage
- * currently: silverlight only can use port range (4502-4506)
- * we provide silverlight policy server(tcp 943) at spshell.exe
- */
- virtual ErrorCodeEnum StartTcpBridgeServer(unsigned short port)=0;
- virtual ErrorCodeEnum StopTcpBridgeServer()=0;
- /**
- * post Task to entity's thread
- * FIFO(first in first out) queue tail, LIFO(last in first out)
- * queue head
- */
- virtual ErrorCodeEnum PostEntityTaskFIFO(ITaskSp *pTask) = 0;
- virtual ErrorCodeEnum PostEntityTaskLIFO(ITaskSp *pTask) = 0;
- /**
- * post task to thread pool
- */
- virtual ErrorCodeEnum PostThreadPoolTask(ITaskSp *pTask) = 0;
- /** request framework to delay closing */
- virtual ErrorCodeEnum RequestCloseDelay(WORD nSecond)=0;
- /** log along with params */
- virtual void SendLog(const LogTypeEnum eLogType,const SeverityLevelEnum eLevel,DWORD dwUserEventCode,CAutoArray<DWORD> Param,const char *pszMessage=NULL)=0;
- /*verify file code signature, if pass, strErrInfo is sign cert hash, else verify error info*/
- virtual ErrorCodeEnum VerifySignature(const char *pszSignedFile, CSimpleStringA &strErrInfo) = 0;
- /*show fatal error info when framework startup*/
- virtual ErrorCodeEnum ShowFatalError(const char *pszMsg) = 0;
- /*show important startup info when framework startup*/
- virtual ErrorCodeEnum ShowStartupInfo(const char *pszMsg) = 0;
- };
- /** normal entity no need to use this interface, use for update, health management, etc. */
- struct IEntityFunctionPrivilege
- {
- virtual ~IEntityFunctionPrivilege() {}
- /** if persist=true,the DebugLevel will be keep after restart */
- virtual ErrorCodeEnum SetSysDebugLevel(const char *pszEntityName,DebugLevelEnum eDebugLevel,bool bPersist=false)=0;
- /** get %SysRoot%\Ver\<version> 's config info */
- virtual ErrorCodeEnum GetSystemStaticInfoForVersion(CVersion verSoftware,CSystemStaticInfo &StaticInfo)=0;
- /** start a remote entity,if restart itself only been call in OnClose event,will ignore pAsynWaitSp,and will not wait*/
- virtual ErrorCodeEnum StartEntity(const char *pszEntityName, const char *pszCmdLine,CSmartPointer<IAsynWaitSp> &pAsynWaitSp)=0;
- /** close entity ,not use consultative mechanism */
- virtual ErrorCodeEnum StopEntity(const char *pszEntityName,CSmartPointer<IAsynWaitSp> &pAsynWaitSp)=0;
- /** require entity close and can use the consultative mechanisms */
- virtual ErrorCodeEnum CloseEntity(const char *pszEntityName,CSmartPointer<IAsynWaitSp> &pAsynWaitSp)=0;
- /** terminate entity forcefully */
- virtual ErrorCodeEnum TerminateEntity(const char *pszEntityName,CSmartPointer<IAsynWaitSp> &pAsynWaitSp)=0;
- /** pause entity */
- virtual ErrorCodeEnum PauseEntity(const char *pszEntityName,CSmartPointer<IAsynWaitSp> &pAsynWaitSp)=0;
- /** continue entity from paused state */
- virtual ErrorCodeEnum ContinueEntity(const char *pszEntityName,CSmartPointer<IAsynWaitSp> &pAsynWaitSp)=0;
- /** test whether entity state ok, a simple health-checking mechanism */
- virtual ErrorCodeEnum TestEntity(const char *pszEntityName,EntityTestEnum eTestType,CSmartPointer<IAsynWaitSp> &pAsynWaitSp)=0;
- /** register entity life event */
- virtual ErrorCodeEnum RegistEntityLifeEvent(IEntityLifeListener *pListener)=0;
- virtual ErrorCodeEnum UnregistLiftEvent()=0;
- /** register entity state event, when entity state changes, callback will be invoked */
- virtual ErrorCodeEnum RegistEntityStateEvent(const char *pszEntityName,IEntityStateListener *pListener)=0;
- /*If pszEntityName=NULL mean unregist all entity event*/
- virtual ErrorCodeEnum UnregistEntityStateEvent(const char *pszEntityName)=0;
-
- /** trigger reboot framework/machine */
- virtual ErrorCodeEnum Reboot(RebootTriggerEnum eTriggerReason,RebootWayEnum eWay)=0;
- /** show blue full-screen title, for example for system error, privilege */
- virtual ErrorCodeEnum DisplayBlueScreen(const char *pszTitle) = 0;
- /** hide blue screen */
- virtual ErrorCodeEnum UndisplayBlueScreen() = 0;
- /** SoftwareVersion used version class first 3 version No.
- if NewSoftwareVersion equal to current version or zero,
- create a new system path with a bigger Build No.
- if the path already exist delete it and rebuild it*/
- virtual ErrorCodeEnum CreateInstallNewVersion(CVersion NewSoftwareVersion,const char *pszPackageName)=0;
-
- /** Install in current version and path*/
- virtual ErrorCodeEnum BeginLightInstall(const char *pszPackageName)=0;
- //virtual ErrorCodeEnum SetUpdateSourcePath(const char *pszSourcePath)=0;
- /** Copy from [Temp]\[pszPackageName]\[pszRelativeFile] to install path,
- 1(copy only exisit); 2(copy only not exist); 3(copy always); 4(no copy if exist)*/
- virtual ErrorCodeEnum CopyFileToNewVersion(const char *pszRelativeFile, int nCopyMode)=0;
- /** pszRelativeName is in run path*/
- virtual ErrorCodeEnum DeleteFileInNewVersion(const char *pszRelativeName)=0;
- /** Set startup shell to last version shell,but not trigger to restart.next restart will run in last version path.*/
- virtual ErrorCodeEnum RollBackToPreviousVersion()=0;
- virtual ErrorCodeEnum RollBackToHistoryVersion(CVersion HistoryVersion)=0;
- /** Set startup shell to new version shell,next restart will run in new version path
- if bToSysInstall=true the SpShell.exe will not startup first,waiting Guardian.exe running install over,and started up by Guardian.exe*/
- virtual ErrorCodeEnum UpgradeToNewVersion(bool bToSysInstall)=0;
-
- /**If the update or rollback version succeed run, info the framework this version is ok*/
- virtual ErrorCodeEnum SetRunSucceed()=0;
- /**check if the pack has been installed*/
- virtual ErrorCodeEnum IsPackInstalled(const char *pszPackName, bool &bInstalled) = 0;
- /** os pack upgrade, run.ini has ToRun define */
- virtual ErrorCodeEnum BeginSysPackInstall(const char *pszPackageName, CSimpleStringA &strErrMsg) = 0;
- /**check if the syspack has been installed*/
- virtual ErrorCodeEnum IsInstalledSysPack(const char *pszPackageName) = 0;
- /** show system running output console, including all entity's syslog */
- virtual ErrorCodeEnum ShowOuputConsole() = 0;
- /**close output console */
- virtual ErrorCodeEnum CloseOuputConsole() = 0;
- };
- /**
- * service entity side transaction, we define call in two types:
- * 1) one way call, client send one way call packet, need no reply from server side
- * 2) two way call, client send request and server response
- * A transaction is a call context hosted by server entity, when one client
- * issues a call, at server entity side, compose a Transaction context object.
- */
- struct ITransactionContext
- {
- virtual ~ITransactionContext(){};
- /** decide whether client call is one way call */
- virtual bool IsOneWayCall() = 0;
- /** get request sequence id */
- virtual DWORD GetRequestID() = 0;
- /** get client buffer */
- virtual ErrorCodeEnum GetReceiveBuffer(DWORD &dwMessageID, DWORD &dwMessageSignature, CAutoBuffer &Buffer) = 0;
- /** send out response to client, only use in two way call scenario */
- virtual ErrorCodeEnum SendAnswer(CAutoBuffer Buffer, bool bEnd=true) = 0;
- /** send out response to client without buffer, this is the simplist case for the above one
- * 20160914: support return custom error: @dwUserError
- */
- virtual ErrorCodeEnum SendAnswer(ErrorCodeEnum eErrorCode, DWORD dwUserError=0) = 0;
- /** set response expired timeout value, in milliseconds */
- virtual ErrorCodeEnum SetExpireTime(DWORD dwMS) = 0;
- /** get this run process expire time left value, in milliseconds */
- virtual ErrorCodeEnum GetExpireTime(DWORD &dwWholeTime,DWORD &dwLeftTime) = 0;
- };
- /** The Module entity must implement the interface */
- class CEntityBase
- {
- public:
- CEntityBase():m_pEntityFunction(NULL) {}
- virtual ~CEntityBase() { delete m_pEntityFunction; }
- /** get entity service function */
- CSmartPointer<IEntityFunction> GetFunction() { return m_pEntityFunction; }
- #ifndef SPABASE_LINKED_AS_STATIC_LIBRARY
- #ifndef SPBASE_EXPORTS
- protected:
- #endif
- #endif
- /**
- * invoked when entity is being start, when starting operation finished user must call FinishStart
- * so the starting operation has prepared, then spbase.dll invokes OnStart
- */
- virtual void OnPreStart(CAutoArray<CSimpleStringA> strArgs,CSmartPointer<ITransactionContext> pTransactionContext) { pTransactionContext->SendAnswer(Error_Succeed) ;}
- virtual void OnStarted(){}
- /** invoked when entity pause */
- virtual void OnPrePause(CSmartPointer<ITransactionContext> pTransactionContext) {pTransactionContext->SendAnswer(Error_Succeed); }
- virtual void OnPaused(){}
- /** invoked when entity continue */
- virtual void OnPreContinue(CSmartPointer<ITransactionContext> pTransactionContext) { pTransactionContext->SendAnswer(Error_Succeed); }
- virtual void OnContinued(){}
- /** invoked when entity will be closed*/
- virtual void OnPreClose(EntityCloseCauseEnum eCloseCause,CSmartPointer<ITransactionContext> pTransactionContext) { pTransactionContext->SendAnswer(Error_Succeed); }
- /** user override this, so it is able to extend some complicated health-checking method */
- virtual void OnSelfTest(EntityTestEnum eTestType,CSmartPointer<ITransactionContext> pTransactionContext) { pTransactionContext->SendAnswer(Error_Succeed); }
- /** invoked when incoming new connection */
- virtual CServerSessionBase *OnNewSession(const char* /*pszRemoteEntityName*/, const char * /*pszParam*/){return NULL;}
- /**
- * if you want to redirection please override this function
- * and invoke IEntityFunciton::RedirectSubscribeBroadcast
- */
- virtual void OnBroadcastSubscribe(CUUID /*SubID*/, const char * /*pszFromEntityName*/, const char * /*pszParam*/) { }
- public:
- /** get this entity name */
- virtual const char *GetEntityName()const=0;
- /** is this entity hosts service ? */
- virtual bool IsService()const{return false;}
- #ifndef SPABASE_LINKED_AS_STATIC_LIBRARY
- #ifndef SPBASE_EXPORTS
- private:
- #endif
- #endif
- /** dont access directly because of inner usage */
- IEntityFunction* m_pEntityFunction;
- };
- /** server session service */
- struct IServerSessionFunction
- {
- virtual ~IServerSessionFunction() {}
- /** get client entity name */
- virtual const char *GetRemoteEntityName()=0;
- /** get current state of this session */
- virtual SessionStateEnum GetCurrentState()=0;
- /** close session */
- virtual ErrorCodeEnum CloseSession()=0;
- };
- /** server service stub, service entity must inherits and implements from here */
- class CServerSessionBase
- {
- public:
- CServerSessionBase() {}
- virtual ~CServerSessionBase(){delete m_pSessionFunction;}
- /** get function pointer */
- CSmartPointer<IServerSessionFunction> GetFunction(){return m_pSessionFunction;}
- #ifndef SPABASE_LINKED_AS_STATIC_LIBRARY
- #ifndef SPBASE_EXPORTS
- protected:
- #endif
- #endif
- /** invoked when receives request from client */
- virtual void OnRequest(CSmartPointer<ITransactionContext> pTransactionContext)=0;
- /** invoked when peer closed or network failed */
- virtual void OnClose(ErrorCodeEnum eErrorCode){}
- /** The same client entity can recall a function before the last call return */
- virtual bool IsSessionOverlap() { return true; }
- /** server message id is overlapped ? */
- virtual ErrorCodeEnum GetMessageAttr(DWORD dwMessageID, DWORD dwSignature, bool &bOverlap)=0;
- /** is exclusive ? */
- virtual bool IsExclusive() { return false; }
- #ifndef SPABASE_LINKED_AS_STATIC_LIBRARY
- #ifndef SPBASE_EXPORTS
- private:
- #endif
- #endif
- /** dont access directly because of inner usage */
- IServerSessionFunction* m_pSessionFunction;
- };
- /**
- * design for supporting async request, each request in client side is named a async wait sp
- * note: for two way call only
- */
- struct IAsynWaitSp:public IReleasable
- {
- /**Get Caller function name string */
- virtual const char *GetFuctionName()=0;
- virtual ErrorCodeEnum GetExpireTime(DWORD &dwWholeTime,DWORD &dwLeftTime)=0;
-
- /** wait for remote to answer */
- virtual ErrorCodeEnum WaitAnswer(DWORD dwTimeout = INFINITE) = 0;
- /** cancel the pending call */
- virtual ErrorCodeEnum CancelWait() = 0;
- /** decide whether operation is doing */
- virtual bool IsPending() = 0;
- /** get request message id */
- virtual DWORD GetMessageID() = 0;
- /**
- * when request has finished, call this method to fetch remote buffer
- * @param ReceivedBuffer get service side sent out buffer, can be zero length
- * @param bEnd the last response message received, this indicator support multiple return responses
- */
- virtual ErrorCodeEnum AsyncGetAnswer(CAutoBuffer &ReceiveBuffer, bool &bEnd) = 0;
- /**just get the result code */
- virtual ErrorCodeEnum AsyncGetAnswer()=0;
- virtual CSmartPointer<IReleasable> GetCallContext()=0;
- virtual bool GetCallback(CSmartPointer<ICallbackListener> &pCallback,CSmartPointer<IReleasable> &pContext)=0;
- /** set callback on, default is off(blocking). The context object inherit IReleasable and must rewrite deconstruction to release temp object*/
- virtual void SetCallback(ICallbackListener *pCallback,IReleasable *pContext=NULL) = 0;
- /** wait for remote to answer
- * @param dwUserError entity custom error code
- */
- virtual ErrorCodeEnum WaitAnswer(DWORD &dwUserError, DWORD dwTimeout) = 0;
- /**
- * when request has finished, call this method to fetch remote buffer
- * @param ReceivedBuffer get service side sent out buffer, can be zero length
- * @param bEnd the last response message received, this indicator support multiple return responses
- * @param dwUserError entity custom error code
- */
- virtual ErrorCodeEnum AsyncGetAnswer(CAutoBuffer &ReceiveBuffer, bool &bEnd, DWORD &dwUserError) = 0;
- };
- /** wait for multi IAsynWaitSp */
- SPBASE_API ErrorCodeEnum WaitMultiAnswers(CAutoArray<IAsynWaitSp *> arrAsynWaits, DWORD &dwRetIndex, bool bWaitAll=false, DWORD dwTimeOut = 0);
- /** client session */
- struct IClientSessionFunction:public IReleasable
- {
- /** one way call with buffer */
- virtual ErrorCodeEnum OnewayCall(DWORD dwMessageID, DWORD dwMessageSignature, CAutoBuffer Buffer)=0;
- /** one way call */
- virtual ErrorCodeEnum OnewayCall(DWORD dwMessageID, DWORD dwMessageSignature)=0;
- /**
- * two way call with buffer
- * @param nMessageID [in] application defined message id
- * @param Buffer [in] application defined buffer data
- * @param pAsynWaitSp [out], required
- * @param dwTimeOut [in],option,default used system 's timeout constant
- */
- virtual ErrorCodeEnum AsyncRequest(DWORD dwMessageID, DWORD dwMessageSignature, CAutoBuffer Buffer, CSmartPointer<IAsynWaitSp> &pAsynWaitSp, DWORD dwTimeOut = 0, DWORD dwReqId = -1)=0;
- /** call without buffer */
- virtual ErrorCodeEnum AsyncRequest(DWORD dwMessageID, DWORD dwMessageSignature, CSmartPointer<IAsynWaitSp> &pAsynWaitSp, DWORD dwTimeOut = 0, DWORD dwReqId = -1)=0;
- /** get peer entity name */
- virtual const char *GetRemoteEntityName()=0;
- /** get current state */
- virtual SessionStateEnum GetCurrentState() =0;
- /** close session */
- virtual ErrorCodeEnum CloseSession()=0;
- };
- /** client must implement this */
- class SPBASE_API CClientSessionBase
- {
- public:
- CClientSessionBase() : m_pSessionFunction(NULL) {}
- virtual ~CClientSessionBase();
- CSmartPointer<IClientSessionFunction> GetFunction() {return m_pSessionFunction;}
- /** invoked when connected ok, in async mode */
- virtual void OnConnectSucceed() {}
- /** invoked when peer closed or network failed */
- virtual void OnClose(ErrorCodeEnum /*eErrorCode*/) {}
- /** invoke when delete the object */
- virtual void OnDestroy() { delete this; }
- #ifndef SPABASE_LINKED_AS_STATIC_LIBRARY
- #ifndef SPBASE_EXPORTS
- private:
- #else
- public:
- #endif
- #endif
- IClientSessionFunction* m_pSessionFunction;
- };
- /** user module must inherit from ModuleBase */
- class SPBASE_API ModuleBase
- {
- public:
- ModuleBase();
- virtual ~ModuleBase();
- virtual ErrorCodeEnum Init();
- virtual ErrorCodeEnum Exit();
- virtual BOOL DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved);
- HINSTANCE GetInstance() { return m_hInstance; }
- static ModuleBase* GetModuleBase();
- protected:
- /** register your entity via this method to framework */
- ErrorCodeEnum RegistEntity(CEntityBase *pEntity);
- ErrorCodeEnum UnregistEntity(CEntityBase *pEntity);
- ErrorCodeEnum GetRegistEntity(const char *pszEntityName,CSmartPointer<CEntityBase> &pEntity);
- #ifndef SPABASE_LINKED_AS_STATIC_LIBRARY
- #ifndef SPBASE_EXPORTS
- protected:
- #else
- public:
- #endif
- #else
- public:
- #endif
- int m_nEntityCount;
- CEntityBase* m_pEntityArray[32];
- static ModuleBase* s_pModuleInst;
- HINSTANCE m_hInstance;
- };
- #define SP_BEGIN_ENTITY_MAP() \
- class SpEntityModuleStub : public ModuleBase \
- { \
- public: \
- SpEntityModuleStub() \
- {
- #define SP_ENTITY(cls) \
- m_pEntityArray[m_nEntityCount++] = dynamic_cast<CEntityBase*>(new cls());
- #define SP_END_ENTITY_MAP() \
- } \
- }; \
- SpEntityModuleStub g_ModuleInst; \
- extern "C" BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) \
- { \
- return g_ModuleInst.DllMain(hInstance, dwReason, lpReserved); \
- }
- /** log via shell */
- SPBASE_API void LogEvent(const SeverityLevelEnum eLevel,DWORD dwUserEventCode,const char *pszMessage);
- SPBASE_API void LogError(const SeverityLevelEnum eLevel, ErrorCodeEnum dwSysErrorCode,DWORD dwUserErrorCode,const char *pszMessage);
- SPBASE_API void LogWarn(const SeverityLevelEnum eLevel, ErrorCodeEnum dwSysErrorCode,DWORD dwUserErrorCode, const char *pszMessage);
- SPBASE_API void LogAssert(const char *pszMessage,const char *pszSourceFile,const int nLine);
- SPBASE_API void LogTrace(const char *pszMessage,const char *pszSourceFile,const int nLine);
- SPBASE_API CSimpleStringA GetSysErrMsg(int nErrCode);
- SPBASE_API const char *_GetFileName(const char *pszFilePath);
- #define LOG_TRACE(pMsg, ...) LogTrace(CSimpleStringA::Format(pMsg, __VA_ARGS__), _GetFileName(__FILE__), __LINE__)
- extern "C" SPBASE_API void Dbg(const char *str, ...);
- extern "C" SPBASE_API void vDbg(const char *str, va_list list);
- /** It is used out of the Entity class members */
- #ifdef _DEBUG
- #define LOG_ASSERT(f) do{if(!(f) && (1 == _CrtDbgReport(_CRT_ASSERT, _GetFileName(__FILE__), __LINE__, NULL, #f))) {_CrtDbgBreak(); LogAssert(#f,_GetFileName(__FILE__), __LINE__);}} while (0)
- #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)
- struct CScopeLog
- {
- 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);}
- ~CScopeLog() {Dbg("Leave %s, file: {%s} ,line: {%d}" , m_pszMsg, m_pszFile, m_nFileLine);}
- const char *m_pszMsg;
- const char *m_pszFile;
- int m_nFileLine;
- };
- #define LOG_FUNCTION() CScopeLog __FunctionScopeLog(__FUNCTION__, _GetFileName(__FILE__), __LINE__)
- #else//_DEBUG
- #define LOG_ASSERT(f) if(!(f)) LogAssert(#f,_GetFileName(__FILE__), __LINE__)
- #define LOG_ASSERT_MSG(f,pMsg, ...) do{ if(!(f)) LogAssert(CSimpleStringA::Format(pMsg, __VA_ARGS__),_GetFileName(__FILE__), __LINE__);} while (0)
- #define LOG_FUNCTION()
- #endif//_DEBUG
- #endif // __cplusplus
|