Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
3 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
/***********************************************************************************************************************************
Protocol Parallel Executor
***********************************************************************************************************************************/
#include <build.h>
 
#include <string.h>
#include <sys/select.h>
 
#include "common/debug.h"
#include "common/log.h"
#include "common/macro.h"
#include "common/type/keyValue.h"
#include "common/type/list.h"
#include "protocol/helper.h"
#include "protocol/parallel.h"
 
/***********************************************************************************************************************************
Object type
***********************************************************************************************************************************/
typedef struct ProtocolParallelJobData
{
    ProtocolParallelJob *job;                                       // Job
    ProtocolClientSession *session;                                 // Protocol session for the job
} ProtocolParallelJobData;
 
struct ProtocolParallel
{
    TimeMSec timeout;                                               // Max time to wait for jobs before returning
    ParallelJobCallback *callbackFunction;                          // Function to get new jobs
    void *callbackData;                                             // Data to pass to callback function
 
    List *clientList;                                               // List of clients to process jobs
    List *jobList;                                                  // List of jobs to be processed
 
    ProtocolParallelJobData *clientJobList;                         // Jobs being processing by each client
 
    ProtocolParallelJobState state;                                 // Overall state of job processing
};
 
/**********************************************************************************************************************************/
FN_EXTERN ProtocolParallel *
protocolParallelNew(const TimeMSec timeout, ParallelJobCallback *const callbackFunction, void *const callbackData)
{
    FUNCTION_LOG_BEGIN(logLevelTrace);
        FUNCTION_LOG_PARAM(UINT64, timeout);
        FUNCTION_LOG_PARAM(FUNCTIONP, callbackFunction);
        FUNCTION_LOG_PARAM_P(VOID, callbackData);
    FUNCTION_LOG_END();
 
    ASSERT(callbackFunction != NULL);
    ASSERT(callbackData != NULL);
 
    OBJ_NEW_BEGIN(ProtocolParallel, .childQty = MEM_CONTEXT_QTY_MAX, .allocQty = MEM_CONTEXT_QTY_MAX)
    {
        *this = (ProtocolParallel)
        {
            .timeout = timeout,
            .callbackFunction = callbackFunction,
            .callbackData = callbackData,
            .clientList = lstNewP(sizeof(ProtocolClient *)),
            .jobList = lstNewP(sizeof(ProtocolParallelJob *)),
            .state = protocolParallelJobStatePending,
        };
    }
    OBJ_NEW_END();
 
    FUNCTION_LOG_RETURN(PROTOCOL_PARALLEL, this);
}
 
/**********************************************************************************************************************************/
FN_EXTERN void
protocolParallelClientAdd(ProtocolParallel *const this, ProtocolClient *const client)
{
    FUNCTION_LOG_BEGIN(logLevelTrace);
        FUNCTION_LOG_PARAM(PROTOCOL_PARALLEL, this);
        FUNCTION_LOG_PARAM(PROTOCOL_CLIENT, client);
    FUNCTION_LOG_END();
 
    ASSERT(this != NULL);
    ASSERT(client != NULL);
    ASSERT(this->state == protocolParallelJobStatePending);
 
    if (protocolClientIoReadFd(client) == -1)
        THROW(AssertError, "client with read fd is required");
 
    lstAdd(this->clientList, &client);
 
    FUNCTION_LOG_RETURN_VOID();
}
 
/**********************************************************************************************************************************/
FN_EXTERN unsigned int
protocolParallelProcess(ProtocolParallel *const this)
{
    FUNCTION_LOG_BEGIN(logLevelTrace);
        FUNCTION_LOG_PARAM(PROTOCOL_PARALLEL, this);
    FUNCTION_LOG_END();
 
    ASSERT(this != NULL);
    ASSERT(this->state != protocolParallelJobStateDone);
 
    unsigned int result = 0;
 
    MEM_CONTEXT_TEMP_BEGIN()
    {
        // If called for the first time, initialize processing
        if (this->state == protocolParallelJobStatePending)
        {
            MEM_CONTEXT_OBJ_BEGIN(this)
            {
                this->clientJobList = memNew(lstSize(this->clientList) * sizeof(ProtocolParallelJobData));
 
                for (unsigned int jobIdx = 0; jobIdx < lstSize(this->clientList); jobIdx++)
                    this->clientJobList[jobIdx] = (ProtocolParallelJobData){0};
            }
            MEM_CONTEXT_OBJ_END();
 
            this->state = protocolParallelJobStateRunning;
        }
 
        // Initialize the file descriptor set used for select
        fd_set selectSet;
        FD_ZERO(&selectSet);
        int fdMax = -1;
 
        // Find clients that are running jobs
        unsigned int clientRunningTotal = 0;
 
        for (unsigned int clientIdx = 0; clientIdx < lstSize(this->clientList); clientIdx++)
        {
            if (this->clientJobList[clientIdx].job != NULL)
            {
                int fd = protocolClientIoReadFd(*(ProtocolClient **)lstGet(this->clientList, clientIdx));
                FD_SET(fd, &selectSet);
 
                // Find the max file descriptor needed for select()
                MAX_ASSIGN(fdMax, fd);
 
                clientRunningTotal++;
            }
        }
 
        // If clients are running then wait for one to finish
        if (clientRunningTotal > 0)
        {
            // Initialize timeout struct used for select. Recreate this structure each time since Linux (at least) will modify it.
            struct timeval timeoutSelect;
            timeoutSelect.tv_sec = (time_t)(this->timeout / MSEC_PER_SEC);
            timeoutSelect.tv_usec = (suseconds_t)(this->timeout % MSEC_PER_SEC * 1000);
 
            // Determine if there is data to be read
            const int completed = select(fdMax + 1, &selectSet, NULL, NULL, &timeoutSelect);
            THROW_ON_SYS_ERROR(completed == -1, AssertError, "unable to select from parallel client(s)");
 
            // If any jobs have completed then get the results
            if (completed > 0)
            {
                for (unsigned int clientIdx = 0; clientIdx < lstSize(this->clientList); clientIdx++)
                {
                    ProtocolParallelJob *const job = this->clientJobList[clientIdx].job;
 
                    if (job != NULL &&
                        FD_ISSET(
                            protocolClientIoReadFd(*(ProtocolClient **)lstGet(this->clientList, clientIdx)),
                            &selectSet))
                    {
                        MEM_CONTEXT_TEMP_BEGIN()
                        {
                            TRY_BEGIN()
                            {
                                protocolParallelJobResultSet(
                                    job, protocolClientSessionResponse(this->clientJobList[clientIdx].session));
                            }
                            CATCH_ANY()
                            {
                                protocolParallelJobErrorSet(job, errorCode(), STR(errorMessage()));
                            }
                            TRY_END();
 
                            protocolParallelJobStateSet(job, protocolParallelJobStateDone);
                            this->clientJobList[clientIdx].job = NULL;
                            protocolClientSessionFree(this->clientJobList[clientIdx].session);
                        }
                        MEM_CONTEXT_TEMP_END();
                    }
                }
 
                result = (unsigned int)completed;
            }
        }
 
        // Find new jobs to be run
        for (unsigned int clientIdx = 0; clientIdx < lstSize(this->clientList); clientIdx++)
        {
            ProtocolClient **const clientRef = lstGet(this->clientList, clientIdx);
 
            // If nothing is running for this client and it has not already been freed
            if (this->clientJobList[clientIdx].job == NULL && *clientRef != NULL)
            {
                MEM_CONTEXT_BEGIN(lstMemContext(this->jobList))
                {
                    // Get a new job
                    ProtocolParallelJob *const job = this->callbackFunction(this->callbackData, clientIdx);
                    ProtocolClient *const client = *clientRef;
 
                    // If a new job was found
                    if (job != NULL)
                    {
                        // Add to the job list
                        lstAdd(this->jobList, &job);
 
                        // Put command
                        ProtocolClientSession *const session = protocolClientSessionNewP(
                            client, protocolParallelJobCommand(job), .async = true);
                        protocolClientSessionRequestAsyncP(session, .param = protocolParallelJobParam(job));
 
                        // Set client id and running state
                        protocolParallelJobProcessIdSet(job, clientIdx + 1);
                        protocolParallelJobStateSet(job, protocolParallelJobStateRunning);
 
                        this->clientJobList[clientIdx].job = job;
                        this->clientJobList[clientIdx].session = session;
                    }
                    // Else no more jobs for this client so free it. Clear the client reference so it is not freed again (and its
                    // freed memory read while logging) on a subsequent call.
                    else
                    {
                        protocolHelperFree(client);
                        *clientRef = NULL;
                    }
                }
                MEM_CONTEXT_END();
            }
        }
    }
    MEM_CONTEXT_TEMP_END();
 
    FUNCTION_LOG_RETURN(UINT, result);
}
 
/**********************************************************************************************************************************/
FN_EXTERN ProtocolParallelJob *
protocolParallelResult(ProtocolParallel *const this)
{
    FUNCTION_LOG_BEGIN(logLevelTrace);
        FUNCTION_LOG_PARAM(PROTOCOL_PARALLEL, this);
    FUNCTION_LOG_END();
 
    ASSERT(this != NULL);
    ASSERT(this->state == protocolParallelJobStateRunning);
 
    ProtocolParallelJob *result = NULL;
 
    // Find the next completed job
    for (unsigned int jobIdx = 0; jobIdx < lstSize(this->jobList); jobIdx++)
    {
        ProtocolParallelJob *job = *(ProtocolParallelJob **)lstGet(this->jobList, jobIdx);
 
        if (protocolParallelJobState(job) == protocolParallelJobStateDone)
        {
            result = protocolParallelJobMove(job, memContextCurrent());
            lstRemoveIdx(this->jobList, jobIdx);
            break;
        }
    }
 
    FUNCTION_LOG_RETURN(PROTOCOL_PARALLEL_JOB, result);
}
 
/**********************************************************************************************************************************/
FN_EXTERN bool
protocolParallelDone(ProtocolParallel *const this)
{
    FUNCTION_LOG_BEGIN(logLevelTrace);
        FUNCTION_LOG_PARAM(PROTOCOL_PARALLEL, this);
    FUNCTION_LOG_END();
 
    ASSERT(this != NULL);
    ASSERT(this->state != protocolParallelJobStatePending);
 
    // If there are no jobs left then we are done
    if (this->state != protocolParallelJobStateDone && lstEmpty(this->jobList))
        this->state = protocolParallelJobStateDone;
 
    FUNCTION_LOG_RETURN(BOOL, this->state == protocolParallelJobStateDone);
}
 
/**********************************************************************************************************************************/
FN_EXTERN void
protocolParallelToLog(const ProtocolParallel *const this, StringStatic *const debugLog)
{
    strStcCat(debugLog, "{state: ");
    strStcResultSizeInc(debugLog, strIdToLog(this->state, strStcRemains(debugLog), strStcRemainsSize(debugLog)));
    strStcFmt(debugLog, ", clientTotal: %u, jobTotal: %u}", lstSize(this->clientList), lstSize(this->jobList));
}