CMSDK 2.0.1
Cross-platform C++ base library and SDK for the Psyclone AIOS platform
Loading...
Searching...
No Matches
RequestGateway.h
Go to the documentation of this file.
1
43#if !defined(_REQUESTGATEWAY_H_)
44#define _REQUESTGATEWAY_H_
45
46#pragma once
47
48#include "Stats.h"
49#include "NetworkManager.h"
50#include "RequestExecutor.h"
51#include "RequestClient.h"
52
53
54namespace cmlabs{
55
61public:
62 CallLogEntry(uint64 id = 0) {
63 this->id = id;
65 longRequest = false;
66 port = 0;
69 }
70 virtual ~CallLogEntry() {};
71
73 std::string toJSON() {
74 if (!id || !startTime || !source || !conType || !messageType)
75 return "";
77 "{\"id\":%llu, \"port\":%u, \"source\":\"%u.%u.%u.%u:%u\", \"connectiontype\":\"%s\", \"messagetype\":\"%s\", "
78 "\"requesttype\":\"%s\", \"longrequest\": \"%s\", \"status\": \"%s\", \"request\": \"%s\", \"output\": \"%s\", "
79 "\"executorid\":%llu, \"clientid\":%llu, \"accountid\":%u, "
80 "\"requestsize\":%u, \"replysize\":%u, "
81 "\"requesttime\": \"%s\", \"duration\": \"%.3f\", \"queuetime\": \"%.3f\", \"processtime\": \"%.3f\"}\n",
83 ((conType == 1) ? "Client" : (conType == 2) ? "Web" : "Websocket"),
84 ((messageType == 1) ? "Binary" : (messageType == 2) ? "HTTP" : "HTTPS"),
86 (longRequest ? "true" : "false"),
87 status.c_str(), requestPath.c_str(), output.c_str(),
91 (double)(endTime - startTime)/1000.0,
92 (double)queueTime/1000.0,
93 (double)processTime/1000.0
94 );
95 }
96
97 uint64 id;
98 uint8 conType;
101 uint64 source;
102 uint16 port;
103 uint64 executorID;
104 uint64 clientID;
105 uint32 accountID;
106 uint64 startTime;
107 uint64 endTime;
108 uint64 queueTime;
109 uint64 processTime;
111 uint32 requestSize;
112 uint32 replySize;
113 std::string status;
114 std::string requestPath;
115 std::string agent;
116 std::string output;
117};
118
119
120
121
123// RequestGateway
125
139public:
147 static bool UnitTest(uint16 port, uint32 executorCount, uint32 gatewayCount, uint32 clientCount, uint32 webCount, uint32 webSocketCount, double sendfreq, int32 reconnect, uint32 payload, uint32 processTime, uint32 runtime);
148
151
153 RequestGateway(uint32 id, const char* version = NULL);
154 virtual ~RequestGateway();
155
160 bool init(const char* sslCertPath = NULL, const char* sslKeyPath = NULL);
161
165 bool setWebServerInfo(const char* name, const char* rootdir, const char* indexfile);
167 bool setExternalAPILabel(const char* label);
169 bool setInternalAPILabel(const char* label);
171 bool setCacheFiles(bool cache);
173 bool setResponseType(const char* type);
175 bool setLongRequestLimit(uint32 limit);
178 bool setExecutorHeartbeatTimeout(uint32 timeout);
181 bool setMaxExecutorRequestTimeout(uint32 timeout);
188
193 bool addPort(uint16 port, uint8 encryption, bool enableHTTP = false, uint32 timeout = 3000);
196 bool addGateway(uint32 id, std::string addr, uint16 port);
199 bool addAuthUser(const char* user, const char* password);
200
202 bool receiveNetworkEvent(NetworkEvent* evt, NetworkChannel* channel, uint64 conid);
204 bool receiveMessage(DataMessage* msg, NetworkChannel* channel, uint64 conid);
207 bool receiveHTTPRequest(HTTPRequest* req, NetworkChannel* channel, uint64 conid);
209 bool receiveWebsocketData(WebsocketData* wsData, NetworkChannel* channel, uint64 conid);
210
211protected:
214 bool runExec();
217 bool runClient();
218
220 bool callInternalAPI(const char* apiName, HTTPRequest* req, NetworkChannel* channel, uint64 conid);
222 bool callExternalAPI(const char* apiName, HTTPRequest* req, NetworkChannel* channel, uint64 conid);
223
225 bool sendRestartToExecutor(uint64 id);
229 bool distributeDeadExecutorRequests(std::list<RequestReply*>& shortQueue, std::list<RequestReply*>& longQueue);
230
236 uint64 getBestExecutorID(std::string requestString, uint32 reqSize, bool& isLongReq);
237 //std::list<RequestConnection> getTopExecutors(std::string requestString, uint32 reqSize, bool& isLongReq);
238 //bool sendToExecutor(RequestReply* reply);
240 bool replyToClient(DataMessage* msg);
245 bool addToRequestQueue(DataMessage* msg, uint64 origin, uint64 conID, uint64 clientRef);
248
251 bool addToCallLog(
252 uint64 id,
253 uint8 conType,
254 uint8 messageType,
255 bool longRequest,
256 uint64 source,
257 uint16 port,
258 uint64 executorID,
259 uint64 clientID,
260 uint64 startTime,
261 uint64 endTime,
262 uint64 queueTime,
263 uint64 processTime,
264 uint8 requestType,
265 uint32 requestSize,
266 uint32 replySize,
267 const char* status,
268 const char* requestPath,
269 const char* agent,
270 const char* output
271 );
273 std::list<CallLogEntry*> callLog;
274 uint32 callLogMax;
276
279 std::map<uint64,RequestConnection> executors;
280 std::map<uint64,RequestConnection> clients;
281 std::map<uint64,RequestConnection> webClients;
282 std::map<uint64,RequestConnection> webSockets;
285 std::map<uint64,RequestReply*> requestMap;
286 std::vector<std::string> longReqNames;
287 std::map<std::string, uint64> httpAuth;
288
290 //uint32 threadID;
293 uint64 lastRefID;
298
299 uint32 id;
300 uint16 port;
309 bool replyXML;
310
311 std::string webServerName;
312 std::string rootdir;
313 std::string indexFilename;
314 std::string versionString;
315
316 std::string internalAPITitle;
317 std::string externalAPITitle;
318
321 //std::map<uint64, MovingAverage> shortAvgStatsExec;
322 //std::map<uint64, MovingAverage> shortAvgStatsClients;
323 //std::map<uint64, MovingAverage> shortAvgStatsWeb;
324 //std::map<uint64, MovingAverage> longAvgStatsExec;
325 //std::map<uint64, MovingAverage> longAvgStatsClients;
326 //std::map<uint64, MovingAverage> longAvgStatsWeb;
327};
328
333
334}
335
336#endif // _REQUESTGATEWAY_H_
Connection/channel management layer: multi-protocol listeners, typed dispatch, HTTP client — and the ...
Request-system client side: RequestReply futures, RequestQueue, gateway connection records and the Re...
Request-system worker side: RequestExecutor pulls requests from a RequestGateway, processes them and ...
Thread-safe running statistics over a sliding window of samples.
#define THREAD_RET
Definition Utils.h:127
#define THREAD_FUNCTION_CALL
Definition Utils.h:129
#define GETIPADDRESSQUADPORT(a)
Definition Utils.h:1481
#define THREAD_ARG
Definition Utils.h:130
uint64 executorID
Executor that processed the request.
uint64 endTime
Reply completion time (ms epoch).
uint32 requestSize
Request payload size in bytes.
uint16 port
Gateway port the call arrived on.
uint64 queueTime
Time spent queued before dispatch (µs).
uint64 processTime
Time spent processing in the executor (µs).
uint8 conType
Ingress type — 1: client 2: web 3: websocket.
CallLogEntry(uint64 id=0)
uint8 messageType
Wire format — 1: message 2: http 3: https.
uint64 source
Caller endpoint packed as uint64.
uint32 replySize
Reply payload size in bytes.
std::string output
Output/diagnostic note.
uint64 id
Unique call id.
virtual ~CallLogEntry()
std::string agent
Caller's User-Agent (web ingress).
uint64 clientID
Client connection id.
uint64 startTime
Request arrival time (ms epoch).
uint8 requestType
HTTP_* method id (for web ingress).
std::string requestPath
Request name/URI.
uint32 accountID
Authenticated account id (0 if anonymous).
bool longRequest
Whether the request was classified long.
std::string toJSON()
std::string status
Outcome status text.
The central Psyclone data container: a self-contained binary message with typed, named user entries.
A parsed or generated HTTP request (also used for WebSocket upgrade handshakes).
Circular-buffer moving statistics: query average, sum and per-second throughput over recent time wind...
One logical network interface: a group of listeners/connections with shared dispatch.
Central owner of all channels, listeners and connections in a process.
uint32 longReqLimit
Concurrent long-request cap per executor.
bool setResponseType(const char *type)
Choose the reply serialisation ("xml" or "json").
std::map< std::string, uint64 > httpAuth
Basic-auth users (user -> credential hash).
std::map< uint64, RequestReply * > requestMap
In-flight requests by gateway ref id.
bool addAuthUser(const char *user, const char *password)
Add a basic-auth user for the web interface/APIs.
bool distributeDeadExecutorRequests(std::list< RequestReply * > &shortQueue, std::list< RequestReply * > &longQueue)
Requeue a dead executor's outstanding requests onto surviving executors.
friend THREAD_RET THREAD_FUNCTION_CALL RequestGatewayClientRun(THREAD_ARG arg)
Thread entry point for the gateway's client-side loop.
uint64 systemStartTime
Gateway start time (ms epoch), for uptime reporting.
uint64 execSentCount
Messages sent to executors.
bool receiveWebsocketData(WebsocketData *wsData, NetworkChannel *channel, uint64 conid)
NetworkReceiver hook: WebSocket ingress carrying request payloads.
uint32 executorHeartbeatTimeout
Silence threshold before an executor is declared dead (ms).
std::map< uint64, RequestConnection > webSockets
Connected WebSocket clients by id.
bool receiveMessage(DataMessage *msg, NetworkChannel *channel, uint64 conid)
NetworkReceiver hook: binary requests/replies/heartbeats from clients and executors.
NetworkChannel * channel
Channel carrying all gateway traffic.
uint64 callLogCount
Total calls logged since start.
utils::Mutex callLogMutex
Guards the call log.
bool callInternalAPI(const char *apiName, HTTPRequest *req, NetworkChannel *channel, uint64 conid)
Handle a management/API call on the internal API label.
std::map< uint64, RequestConnection > executors
Connected executors by id.
uint64 lastRefID
Last issued gateway reference id.
std::string indexFilename
Default index file name.
std::string externalAPITitle
URI label of the external (public) API.
bool setCacheFiles(bool cache)
Enable/disable HTTP caching headers for served files.
bool setMaxExecutorRequestTimeout(uint32 timeout)
Set the maximum time a request may sit with an executor before being failed/retried.
uint32 id
This gateway's id.
bool setExecutorHeartbeatTimeout(uint32 timeout)
Set how long an executor may go silent before being declared dead (its queue is then redistributed).
std::string webServerName
Server header name of the built-in web server.
uint16 port
Primary listening port.
utils::WaitQueue< RequestReply * > execQ
Requests awaiting executor dispatch.
uint32 maxRequestProcessingSize
Backpressure: max requests dispatched concurrently.
std::vector< std::string > longReqNames
Request names classified as long.
bool receiveHTTPRequest(HTTPRequest *req, NetworkChannel *channel, uint64 conid)
NetworkReceiver hook: web ingress — serves files, APIs, or converts the request into an internal Data...
std::string rootdir
Document root for file serving.
bool callExternalAPI(const char *apiName, HTTPRequest *req, NetworkChannel *channel, uint64 conid)
Handle a public API call on the external API label.
std::map< uint64, RequestConnection > webClients
Connected HTTP clients by id.
bool addToCallLog(uint64 id, uint8 conType, uint8 messageType, bool longRequest, uint64 source, uint16 port, uint64 executorID, uint64 clientID, uint64 startTime, uint64 endTime, uint64 queueTime, uint64 processTime, uint8 requestType, uint32 requestSize, uint32 replySize, const char *status, const char *requestPath, const char *agent, const char *output)
Append one completed call to the rolling call log (trimmed to callLogMax).
uint64 execReceivedCount
Messages received from executors.
bool setQueuingParameters(uint32 maxRequestQueueSize, uint32 maxRequestProcessingSize, uint32 priorityThreshold)
Tune queuing/backpressure behaviour.
bool sslSupport
True when an SSL certificate was configured.
uint64 clientReceivedCount
Messages received from clients.
std::string versionString
Version shown in status pages.
MovingAverage shortAvgStats
Rolling latency stats for short requests.
bool addGateway(uint32 id, std::string addr, uint16 port)
Register a peer gateway (multi-gateway federation).
uint32 threadIDClient
Client-side worker thread id.
MovingAverage longAvgStats
Rolling latency stats for long requests.
bool cacheFiles
Send caching headers for served files.
uint32 maxRequestQueueSize
Backpressure: max queued requests before TOOBUSY.
bool setLongRequestLimit(uint32 limit)
Cap concurrent long requests per executor.
std::string internalAPITitle
URI label of the internal (management) API.
std::map< uint64, RequestConnection > clients
Connected binary clients by id.
bool setExternalAPILabel(const char *label)
Set the URI label under which the external (public) API is exposed.
uint64 getBestExecutorID(std::string requestString, uint32 reqSize, bool &isLongReq)
Pick the executor to receive a request — the core load-balancing decision, based on reported queue si...
NetworkManager * manager
Owned network stack (listeners + connections).
bool addPort(uint16 port, uint8 encryption, bool enableHTTP=false, uint32 timeout=3000)
Open a listening port for clients/executors (call before init()).
uint32 maxExecutorRequestTimeoutMS
Max time a request may sit with an executor (ms).
bool sendRestartToExecutor(uint64 id)
Ask an executor to restart itself (sent when it misbehaves).
bool setInternalAPILabel(const char *label)
Set the URI label under which the internal (management) API is exposed.
utils::WaitQueuePointer< DataMessage * > replyQ
Replies awaiting client routing.
std::list< CallLogEntry * > callLog
Rolling log of completed calls (owned).
bool setWebServerInfo(const char *name, const char *rootdir, const char *indexfile)
Configure the built-in file web server.
RequestGateway(uint32 id, const char *version=NULL)
bool runClient()
Client-side worker loop: route replies back to callers, expire timed-out requests.
friend THREAD_RET THREAD_FUNCTION_CALL RequestGatewayExecRun(THREAD_ARG arg)
Thread entry point for the gateway's executor-side loop.
bool runExec()
Executor-side worker loop: dispatch queued requests, watch heartbeats, redistribute dead executors' w...
utils::Mutex mutex
Guards shared gateway state.
uint32 priorityThreshold
Queue length above which priority ordering applies.
static bool UnitTest(uint16 port, uint32 executorCount, uint32 gatewayCount, uint32 clientCount, uint32 webCount, uint32 webSocketCount, double sendfreq, int32 reconnect, uint32 payload, uint32 processTime, uint32 runtime)
End-to-end stress test spinning up a gateway plus the given numbers of executors, extra gateways and ...
bool addToRequestQueue(DataMessage *msg, uint64 origin, uint64 conID, uint64 clientRef)
Wrap an incoming message in a RequestReply and enqueue it for dispatch.
bool addRequestReplyToRequestQueue(RequestReply *reply)
Enqueue an already-wrapped request (e.g.
uint32 callLogMax
Max entries kept in callLog.
bool init(const char *sslCertPath=NULL, const char *sslKeyPath=NULL)
Start the gateway threads and network stack.
bool receiveNetworkEvent(NetworkEvent *evt, NetworkChannel *channel, uint64 conid)
NetworkReceiver hook: connect/disconnect events for clients and executors.
bool replyXML
Reply in XML (true) or JSON (false).
bool replyToClient(DataMessage *msg)
Route a reply message back to the client that issued the request.
uint64 clientSentCount
Messages sent to clients.
Future/handle for one in-flight request: holds the request message, the eventual reply,...
Runnable()
Initialise flags: not running, allowed to continue.
One WebSocket frame/message (RFC 6455): parsing, generation and control frames.
Recursive mutual-exclusion lock, optionally named for cross-process use.
Definition Utils.h:463
Thread-safe FIFO queue with blocking waits, the workhorse producer/consumer channel in CMSDK.
Definition Utils.h:703
WaitQueue specialization for owned heap pointers: clear()/destructor delete remaining entries.
Definition Utils.h:823
std::string PrintTimeString(uint64 t, bool local=true, bool us=true, bool ms=true)
Definition PsyTime.cpp:676
THREAD_RET THREAD_FUNCTION_CALL RequestGatewayExecRun(THREAD_ARG arg)
Thread entry point for the gateway's executor-side loop.
THREAD_RET THREAD_FUNCTION_CALL RequestGatewayClientRun(THREAD_ARG arg)
Thread entry point for the gateway's client-side loop.
std::string StringFormat(const char *format,...)
printf into a std::string.
Definition Utils.cpp:6884
static char HTTP_Type[][8]
HTTP method name strings, indexed by the HTTP_* method ids (index 0 unused).
Notification of a connection lifecycle change (connect, disconnect, buffer state.....