-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
99 lines (83 loc) · 2.68 KB
/
main.c
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
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include "../include/ac.h"
#include "../include/tail.h"
#include "../include/file.h"
#include "../include/thread.h"
#include "../include/socket.h"
#include "../include/socket_ac.h"
static const char *mustEnv(const char *name) {
const char *value = getenv(name);
if (NULL == value) {
fprintf(stderr, "env name %s does not exists\n", name);
exit(EXIT_FAILURE);
}
return value;
}
static int toInt(const char *value) {
return (int)strtol(value, NULL, 0);
}
static struct socketInfo *createSocketInfo(void) {
const char *socket = mustEnv("SOCKET");
if (0 == strcmp("unix", socket)) {
return createUnixSocketInfo(mustEnv("SOCKET_PATH"));
} else if (0 == strcmp("tcp", socket)) {
return createTCPSocketInfo(toInt(mustEnv("TCP_PORT")));
} else {
fprintf(stderr, "unknown socket env value %s\n", socket);
exit(EXIT_FAILURE);
}
}
static void *createTimeVal(const char *name) {
const char *value = getenv(name);
if (NULL == value) {
return NULL;
}
return &(struct timeval){ toInt(value), 0 };
}
static int createBacklog(void) {
const char *value = getenv("BACKLOG");
if (NULL == value) {
return -1;
}
return toInt(value);
}
static int createWorkers(void) {
const char *value = getenv("WORKERS");
if (NULL == value) {
return getAvailableCores();
}
return toInt(value);
}
int main(void) {
const char *filePath = mustEnv("DICTIONARY");
if (0 != access(filePath, F_OK|R_OK)) {
fprintf(stderr, "dictionary does not exists %s\n", filePath);
exit(EXIT_FAILURE);
}
const int backlog = createBacklog();
struct socketInfo *socketInfo = createSocketInfo();
struct timeval *serverTimeout = createTimeVal("SERVER_TIMEOUT");
struct timeval *clientTimeout = createTimeVal("CLIENT_TIMEOUT");
struct fileData data = file_load(filePath);
HandlerData *handlerData = createHandlerData(data.automaton, data.tail, data.userDataList);
struct workerPool *pool = createWorkerPool(createWorkers(), socketJobHandler);
struct serverConfig *config = createServerConfig(
backlog,
clientTimeout,
serverTimeout,
ahoCorasickHandler,
handlerData
);
struct server *server = createServer(config, pool);
server_run(server, socketInfo);
serverConfig_free(config);
handlerData_free(handlerData);
socketInfo_free(socketInfo);
automaton_free(data.automaton);
if (NULL != data.tail) tail_free(data.tail);
if (NULL != serverTimeout) free(serverTimeout);
if (NULL != clientTimeout) free(clientTimeout);
}