-
Notifications
You must be signed in to change notification settings - Fork 0
/
message2gateway.cpp
151 lines (132 loc) · 2.03 KB
/
message2gateway.cpp
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
/**
* Read packet from nanomsg socket, parse and emit
*/
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <iostream>
#include <glog/logging.h>
#if defined(_WIN32) || defined(_WIN64)
#include <WinSock2.h>
#else
#endif
#include "platform.h"
#include "daemonize.h"
#include "message2gateway-config.h"
#include "errorcodes.h"
Config *config;
/**
* @return: 0- success
* @see errorcodes.h
*/
int run
(
Config *config
);
/**
* Return 0- success
*/
int stop
(
Config *config
);
int reload
(
Config *config
);
void stopNWait()
{
std::cerr << MSG_STOP;
stop(config);
}
void done()
{
if (config)
{
if (config->verbosity >= 2)
std::cerr << MSG_DONE;
}
}
int reslt;
void runner()
{
if (!config)
{
LOG(ERROR) << ERR_NO_CONFIG;
return;
}
int n = 0;
while (!config->stop_request)
{
reslt = run(config);
if (n >= config->retries)
break;
SLEEP(config->retry_delay);
n++;
}
}
void signalHandler(int signal)
{
switch(signal)
{
case SIGINT:
std::cerr << MSG_INTERRUPTED;
stopNWait();
done();
break;
#if defined(_WIN32) || defined(_WIN64)
#else
case SIGHUP:
std::cerr << MSG_RELOAD_CONFIG_REQUEST;
reload(config);
break;
#endif
default:
std::cerr << MSG_SIGNAL;
}
}
#if defined(_WIN32) || defined(_WIN64)
#else
void setSignalHandler(int signal)
{
struct sigaction action;
memset(&action, 0, sizeof(struct sigaction));
action.sa_handler = &signalHandler;
sigaction(signal, &action, NULL);
}
#endif
int main
(
int argc,
char *argv[]
)
{
// Signal handler
#if defined(_WIN32) || defined(_WIN64)
#else
setSignalHandler(SIGINT);
setSignalHandler(SIGHUP);
#endif
reslt = 0;
config = new Config(argc, argv);
if (!config)
exit(ERRCODE_NO_CONFIG);
if (config->error() != 0)
{
LOG(ERROR) << ERR_COMMAND;
exit(ERRCODE_COMMAND);
}
INIT_LOGGING(PROGRAM_NAME)
if (config->daemonize)
{
LOG(INFO) << MSG_DAEMONIZE;
Daemonize daemonize(PROGRAM_NAME, config->path, runner, stopNWait, done);
}
else
{
LOG(INFO) << MSG_START;
runner();
done();
}
return reslt;
}