KBEngine Module
The KBEngine module provides Python script control for analyzing and dumping specific types of logs.
Member Functions
def getCustomCfg( key, default=None ):
def addTimer( initialOffset, repeatOffset=0, callbackObj=None ):
def delTimer( id ):
def deregisterAcceptFileDescriptor( fileDescriptor ):
def deregisterReadDataFileDescriptor( fileDescriptor ):
[废弃] def deregisterReadFileDescriptor( fileDescriptor ):
[废弃] def deregisterWriteFileDescriptor( fileDescriptor ):
def registerAcceptFileDescriptor( fileDescriptor, callback ):
def registerReadDataFileDescriptor( fileDescriptor, callback ):
[废弃] def registerReadFileDescriptor( fileDescriptor, callback ):
[废弃] def registerWriteFileDescriptor( fileDescriptor, callback ):
def writeFileDescriptor( fileDescriptor, data, callback ):
def urlopen( url, callback, postData, headers ):
Callback Functions
def onLoggerAppReady( ):
def onLoggerAppShutDown( ):
def onLogWrote( datas ):
def onReadyForShutDown( ):
Member Function Documentation
def getCustomCfg( key, default=None ):
Available since: 2.8.2
Description:
Reads a custom configuration item from the <customCfg> section of the server configuration file. This API is read-only; scripts cannot modify configuration values through it.
Each item is described by a unified <param> node: name is the key used by scripts, type controls the Python object type returned to scripts, and the node text is the configuration value. desc is only documentation in the configuration file and is not loaded into runtime memory.
Supported type values: bool, int, float, string, dict, and list.
When the item exists, the return type is determined only by the XML type, not by the default argument. When the item does not exist, this function returns default if it is provided, otherwise it returns None.
Configuration example:
<customCfg>
<param name="battle.maxPlayers" type="int" desc="max players per battle">100</param>
<param name="battle.enableRank" type="bool" desc="enable battle rank">true</param>
<param name="battle.speedScale" type="float" desc="battle speed scale">1.0</param>
<param name="battle.welcome" type="string" desc="welcome text">hello</param>
<param name="battle.dropRates" type="dict" desc="drop rate config">{"gold": 1.2, "item": 0.05}</param>
<param name="battle.spawnPoints" type="list" desc="spawn point ids">[1, 2, 3]</param>
</customCfg>Example:
import KBEngine
maxPlayers = KBEngine.getCustomCfg("battle.maxPlayers", 100)
enableRank = KBEngine.getCustomCfg("battle.enableRank", False)
dropRates = KBEngine.getCustomCfg("battle.dropRates", {})
spawnPoints = KBEngine.getCustomCfg("battle.spawnPoints", [])
# Returns None when the key does not exist and no default value is provided.
missingValue = KBEngine.getCustomCfg("battle.null")Parameters:
key: string, the custom configuration item name, corresponding to <param name="...">.
default: optional object returned when the configuration item does not exist. If omitted, None is returned.
Returns:
The Python object converted according to type when the item exists; otherwise default or None.
def addTimer( initialOffset, repeatOffset=0, callbackObj=None ):
Description:
Registers a timer, which is triggered by the callback function callbackObj. The callback function will be executed for the first time after "initialOffset" seconds, and then every "repeatOffset" seconds.
Example:
# Example of using addTimer
import KBEngine
# Add a timer, execute for the first time after 5 seconds, then every 1 second, user parameter is 9
KBEngine.addTimer( 5, 1, onTimer_Callbackfun )
# Add a timer, execute after 1 second, user parameter defaults to 0
KBEngine.addTimer( 1, onTimer_Callbackfun )
def onTimer_Callbackfun( id ):
print("onTimer_Callbackfun called: id %i" % ( id ))
# if this is a repeating timer, when it is no longer needed, call the following function to remove it:
# KBEngine.delTimer( id )Parameters:
initialOffset: float, the interval (seconds) from registration to the first callback.
repeatOffset: float, the interval (seconds) between each execution after the first callback. Must be removed with delTimer, otherwise it will repeat indefinitely. Values less than or equal to 0 will be ignored.
callbackObj: function, the specified callback function object.
Returns:
integer, returns the internal id of the timer, which can be used to remove the timer with delTimer.
def delTimer( id ):
Description:
The delTimer function is used to remove a registered timer. The removed timer will no longer execute. Timers that only execute once are automatically removed after the callback, so there is no need to remove them with delTimer. If delTimer is called with an invalid id (e.g., already removed), an error will occur.
See KBEngine.addTimer for an example of using timers.
Parameters:
id: integer, specifies the timer id to remove.
def deregisterAcceptFileDescriptor( fileDescriptor ):
Description:
Unregisters the accept completion callback for a listening socket. Call this before stopping the listener or closing the listener fd, so late accept completions are not delivered to script after the listener has been closed.
Parameters:
fileDescriptor: integer, the listening socket fd previously registered with registerAcceptFileDescriptor.
def deregisterReadDataFileDescriptor( fileDescriptor ):
Description:
Unregisters the read completion/data callback for a connected socket. Before closing a client connection, call this API first, then close the socket and remove the fd from script-side containers such as _clients and protocol buffers.
Parameters:
fileDescriptor: integer, a connected socket fd previously registered with registerReadDataFileDescriptor.
[废弃] def deregisterReadFileDescriptor( fileDescriptor ):
Deprecated:
The old readiness-based read deregistration API is deprecated. Script code must choose the deregistration API according to fd type, so listener fds and connected socket fds are not accidentally removed through the same entry point.
Use instead:
- Listener fd: deregisterAcceptFileDescriptor.
- Connected socket fd: deregisterReadDataFileDescriptor.
Calling this old API raises an error telling the script to use the new completion API.
[废弃] def deregisterWriteFileDescriptor( fileDescriptor ):
Deprecated:
The old readiness-based write deregistration API is deprecated. The new writeFileDescriptor API submits writes per request and automatically cleans up its internal write handler after completion, so script code does not explicitly unregister writable fds.
Calling this old API raises an error telling the script to use the new completion API.
def registerAcceptFileDescriptor( fileDescriptor, callback ):
Description:
Registers an accept completion callback for a listening socket. This API is used with a listener fd. After the lower network layer completes an accept operation, the accepted client fd is delivered to script. Script code should no longer wait for the listener to become readable or call accept() by itself.
This is the new completion API replacing the old listener usage of registerReadFileDescriptor.
Callback format:
def onAccept(listenerFD, clientFD, errorCode):
passParameters:
fileDescriptor: integer, the listening socket fd.
callback: function called when accept completes. listenerFD is the listening fd, clientFD is the accepted connection fd, and errorCode is 0 on success or non-zero on accept failure.
Usage:
In onAccept, keep a script-side socket object for clientFD so the fd is not closed by GC, then call registerReadDataFileDescriptor to receive read completions for that connection.
def registerReadDataFileDescriptor( fileDescriptor, callback ):
Description:
Registers a read completion/data callback for a connected socket. After the lower network layer completes recv, the received bytes are delivered directly to script. Script code should no longer wait for fd readability or call recv() on this fd, because doing so bypasses the completion queue and lifecycle management.
This is the new completion API replacing the old connected-socket usage of registerReadFileDescriptor.
Callback format:
def onRead(fd, data, errorCode):
passParameters:
fileDescriptor: integer, a connected socket fd.
callback: function called when recv completes. fd is the connection fd, data is the bytes read in this completion, and errorCode is 0 on success or non-zero on read failure.
Usage:
A completion only means one lower-level recv has completed; it does not guarantee that a full application-level packet has arrived. Script code should still buffer and frame data according to its own protocol. If data is empty or errorCode != 0, usually close the connection after calling deregisterReadDataFileDescriptor.
[废弃] def registerReadFileDescriptor( fileDescriptor, callback ):
Deprecated:
The old readiness-based read notification API is deprecated. The completion backend no longer reports “fd is readable” to script. A listener should use accept completion, and a connected socket should use read data completion.
Use instead:
- Listener fd: registerAcceptFileDescriptor.
- Connected socket fd: registerReadDataFileDescriptor.
Calling this old API raises an error telling the script to use the new completion API.
[废弃] def registerWriteFileDescriptor( fileDescriptor, callback ):
Deprecated:
The old readiness-based write notification API is deprecated. The completion backend no longer reports “fd is writable” to script. Submit data with writeFileDescriptor and receive onWriteComplete(fd, bytesWritten, errorCode) instead.
Calling this old API raises an error telling the script to use the new completion API.
def writeFileDescriptor( fileDescriptor, data, callback ):
Description:
Submits one asynchronous write request. data must be bytes. The lower network layer copies it into its send queue. Script code should not register a writable-fd callback anymore. When the send completes, the completion callback supplied for this write request is called.
This is the new completion API replacing the old registerWriteFileDescriptor / deregisterWriteFileDescriptor writable-notification model.
Callback format:
def onWriteComplete(fd, bytesWritten, errorCode):
passParameters:
fileDescriptor: integer, a connected socket fd.
data: bytes, the data to send.
callback: function called when the write completes. fd is the connection fd, bytesWritten is the number of bytes completed for this request, and errorCode is 0 on success or non-zero on write failure.
Usage:
Each call may provide its own callback. For short connections, close the fd in onWriteComplete; for long connections, keep the connection open and continue receiving data through registerReadDataFileDescriptor.
def urlopen( url, callback, postData, headers ):
Description:
This script function provides asynchronous HTTP/HTTPS requests.
Parameters:
url: A valid HTTP/HTTPS URL, string type.
callback: Optional parameter, a callback object (such as a function) with the result of the request. This callback takes 5 parameters: HTTP response code (e.g., 200), response content, HTTP headers, success status, and the request URL.
Example Declaration:
def onHttpCallback(httpcode, data, headers, success, url):
print(httpcode, data, headers, success, url)As shown above:
httpcode: The HTTP response code, an integer value.
data: The response content, a string.
headers: The HTTP headers returned by the server, e.g., {"Content-Type": "application/x-www-form-urlencoded"}, a dictionary.
success: Whether the request was successful. If there was an error, this is False. You can use httpcode to further determine the error.
url: The URL used for the request.
postData: Optional parameter. By default, a GET request is made to the server. If you need a POST request, provide the content to POST, and the engine will automatically use POST. It is bytes.
headers: Optional parameter. The HTTP headers to use for the request, e.g., {"Content-Type": "application/x-www-form-urlencoded"}, a dictionary.
Callback Function Documentation
def onLoggerAppReady( ):
Description:
This function is called when the current process is ready.
Note: This callback must be implemented in the entry module (kbengine_defaults.xml->entryScriptFile).
def onLoggerAppShutDown( ):
Description:
This function is called when the process is shutting down.
Note: This callback must be implemented in the entry module (kbengine_defaults.xml->entryScriptFile).
def onLogWrote( datas ):
Description:
If this function is implemented in the script, when the logger process receives a new log, this callback function is called.
Database interfaces are defined in kbengine_defaults.xml->dbmgr->databaseInterfaces.
Note: This callback must be implemented in the entry module (kbengine_defaults.xml->entryScriptFile).
Parameters:
datas: bytes, log data.
def onReadyForShutDown( ):
Description:
If this function is implemented in the script, it will be called when the process is about to exit.
You can use this callback to control the timing of process exit.
Note: This callback must be implemented in the entry module (kbengine_defaults.xml->entryScriptFile).
Returns:
bool, if True is returned, the process is allowed to proceed with exit. If any other value is returned, the process will ask again after a while.