-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.h
529 lines (434 loc) · 13.9 KB
/
server.h
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
#ifndef __SERVER_H__
#define __SERVER_H__
#include <sys/stat.h>
#include <stdlib.h>
#include <cstring>
#include <csignal>
#include <fstream>
#include <memory>
#include <iostream>
#include <string>
#include <evhttp.h>
#include <event2/event.h>
#include <event2/http.h>
#include <event2/http_compat.h>
#include <event2/http_struct.h>
#include <hiredis/hiredis.h>
#include "log.h"
#include "config.h"
#define DEBUG LOG_TYPE::LOG_DEBUG
#define INFO LOG_TYPE::LOG_INFO
#define WARN LOG_TYPE::LOG_WARN
#define ERROR LOG_TYPE::LOG_ERROR
using std::make_shared;
using std::shared_ptr;
using std::string;
using std::unique_ptr;
// redis 连接
class RedisServer;
static unique_ptr<RedisServer> redis_server = nullptr;
struct UsedKeys
{
string total_visit_count{"cs_tvc"};
string page_cache{"cs_pc"};
string visit_record_map{"cs_vrm"};
};
class RedisServer
{
public:
RedisServer(string addr, int port, short db = 0)
: redis_addr(addr), redis_port(port), redis_db(db) { connect_redis(); }
~RedisServer() { redisFree(conn.release()); }
/**
* add visited web page into Redis cache
*/
void insert_cache(shared_ptr<const string> page_link, shared_ptr<string> page);
/**
* query if the web page of the page link in Redis cache
*/
bool query_cache(shared_ptr<const string> page_link, shared_ptr<string> page);
/**
* add a record into Redis cache if someone visit any page
*/
void add_visit_record(shared_ptr<const string> page_link);
/**
* get the page link and visit time of the most popular (end-start) pages
*/
bool get_visit_record(shared_ptr<string> page, int start, int end);
/**
* anyone visit any page, total visit count +1
*/
void add_total_visit_count();
/**
* get the total visit count of all pages
*/
long long get_total_visit_count();
/**
* make a connection to the redis server
*/
bool connect_redis();
/**
* checke if we are connecting the Redis server
*/
bool check_connect() { return (nullptr == conn) ? false : true; }
// void free_redis();
private:
UsedKeys keys;
string redis_addr;
int redis_port;
short redis_db;
int retry_count = 0;
bool redis_is_health = true;
unique_ptr<redisContext> conn = nullptr;
};
void RedisServer::insert_cache(shared_ptr<const string> page_link,
shared_ptr<string> page)
{
if (nullptr == page_link || nullptr == page || !redis_is_health)
return;
if (nullptr == conn && !connect_redis())
return;
// string key{"pageCache"};
string key{keys.page_cache};
unique_ptr<redisReply> reply((redisReply *)redisCommand(conn.get(), "HSET %s %s %s", key.c_str(), page_link->c_str(), page->c_str()));
if (nullptr == reply)
{
LOG(WARN, "page_link:%s reply_type:%d", page_link->c_str(), -1);
return;
}
if (reply->type == REDIS_REPLY_ERROR)
{
LOG(WARN, "page_link:%s reply:%s", page_link->c_str(), reply->str);
}
freeReplyObject(reply.release());
}
void RedisServer::add_total_visit_count()
{
if (!redis_is_health || (nullptr == conn && !connect_redis()))
return;
string key{keys.total_visit_count};
unique_ptr<redisReply> reply((redisReply *)redisCommand(conn.get(), "INCR %s", key.c_str()));
if (nullptr == reply)
{
LOG(WARN, "INCR totalVisitCount failed reply_type:%d", -1);
return;
}
if (reply->type == REDIS_REPLY_ERROR)
{
LOG(WARN, "reply:%s", reply->str);
}
freeReplyObject(reply.release());
}
long long RedisServer::get_total_visit_count()
{
if (!redis_is_health || (nullptr == conn && !connect_redis()))
return -1;
string key{keys.total_visit_count};
unique_ptr<redisReply> reply((redisReply *)redisCommand(conn.get(), "GET %s", key.c_str()));
if (nullptr == reply || reply->type == REDIS_REPLY_ERROR)
{
LOG(WARN, "get totalVisitCount failed %d", (reply != nullptr) ? reply->type : -1);
return -1;
}
return atoi(reply->str);
}
void RedisServer::add_visit_record(shared_ptr<const string> page_link)
{
if (nullptr == page_link || !redis_is_health)
return;
if (nullptr == conn && !connect_redis())
return;
add_total_visit_count();
string key{keys.visit_record_map};
unique_ptr<redisReply> reply((redisReply *)redisCommand(conn.get(), "ZINCRBY %s 1 %s", key.c_str(), page_link->c_str()));
if (nullptr == reply)
{
LOG(WARN, "page_link:%s reply_type:%d", page_link->c_str(), -1);
return;
}
if (reply->type == REDIS_REPLY_ERROR)
{
LOG(WARN, "page_link:%s reply:%s", page_link->c_str(), reply->str);
}
freeReplyObject(reply.release());
return;
}
bool RedisServer::get_visit_record(shared_ptr<string> page, int start, int end)
{
if (!redis_is_health || (nullptr == conn && !connect_redis()))
return false;
string key{keys.visit_record_map};
unique_ptr<redisReply> reply((redisReply *)redisCommand(conn.get(), "ZREVRANGE %s %d %d WITHSCORES", key.c_str(), start, end));
if (nullptr == reply)
{
LOG(WARN, "reply_type:%d", -1);
return false;
}
if (reply->type == REDIS_REPLY_ERROR)
{
LOG(WARN, "reply:%s", reply->str);
freeReplyObject(reply.release());
return false;
}
if (reply->type == REDIS_REPLY_ARRAY)
{
int n = reply->elements;
string tmp;
for (int i = 0; i < n; ++i)
{
if (i % 2)
{
/*TODO I know it's ugly, because I am not sure the reply type of ZREVRANGE. in the future I will modify the code */
(reply->element[i]->type == REDIS_REPLY_STRING) ? tmp.append(reply->element[i]->str) : tmp.append(std::to_string(reply->element[i]->integer));
tmp.append("</br>");
page->append(tmp);
tmp = "";
}
else
{
(reply->element[i]->type == REDIS_REPLY_STRING) ? tmp.append(reply->element[i]->str) : tmp.append(std::to_string(reply->element[i]->integer));
tmp.append("<br>[VISIT COUNT]:");
}
}
}
freeReplyObject(reply.release());
return true;
}
bool RedisServer::query_cache(shared_ptr<const string> page_link, shared_ptr<string> page)
{
if (nullptr == page_link || !redis_is_health)
return false;
if (nullptr == conn && !connect_redis())
return false;
add_visit_record(page_link);
string key{keys.page_cache};
unique_ptr<redisReply> reply((redisReply *)redisCommand(conn.get(), "HGET %s %s", key.c_str(), page_link->c_str()));
if (nullptr == reply)
{
LOG(WARN, "page_link:%s reply_type:%d", page_link->c_str(), -1);
return false;
}
// query result is null means the page isn't in Redis cache
if (reply->type == REDIS_REPLY_NIL)
{
freeReplyObject(reply.release());
return false;
}
if (reply->type != REDIS_REPLY_STRING)
{
LOG(WARN, "page_link:%s reply_type:%d", page_link->c_str(), reply->type);
freeReplyObject(reply.release());
return false;
}
page->append(reply->str);
freeReplyObject(reply.release());
return true;
}
bool RedisServer::connect_redis()
{
if (retry_count > MAX_RETRY_COUNT)
{
redis_is_health = false;
return false;
}
conn.reset(redisConnect(redis_addr.c_str(), redis_port));
if (conn->err)
{
LOG(ERROR, "error_flag:%d, addr:%s port: %d", conn->err, redis_addr.c_str(), redis_port);
retry_count += 1;
return false;
}
#ifdef NEED_AUTH
unique_ptr<redisReply> reply((redisReply *)redisCommand(conn.get(), "AUTH %s", REDIS_PASSWORD));
if (nullptr == reply)
{
LOG(INFO, "reply is null");
return false;
}
if (reply->type == REDIS_REPLY_ERROR)
{
LOG(ERROR, "redis AUTH error addr:%s port:%d, password:%s", redis_addr.c_str(), redis_port, REDIS_PASSWORD);
freeReplyObject(reply.release());
return false;
}
#endif
if (redis_db != 0)
{
unique_ptr<redisReply> reply2((redisReply *)redisCommand(conn.get(), "SELECT %d", redis_db));
if (nullptr == reply2)
{
LOG(ERROR, "select db error db:%d", redis_db);
}
if (reply2->type == REDIS_REPLY_ERROR)
{
LOG(ERROR, "reply:%s", reply2->str);
freeReplyObject(reply2.release());
return false;
}
}
LOG(INFO, "redis connect success! addr:%s port:%d", redis_addr.c_str(), redis_port);
retry_count = 0;
return true;
}
inline unique_ptr<const string> parse_request_path(struct evhttp_request *req)
{
if (nullptr == req)
return nullptr;
string uri{evhttp_request_get_uri(req)};
if (uri == "")
{
LOG(INFO, "URI is null");
return nullptr;
}
struct evhttp_uri *decode_uri = evhttp_uri_parse(uri.c_str());
if (nullptr == decode_uri)
{
LOG(INFO, "decode_uri is null");
evhttp_send_error(req, HTTP_BADREQUEST, 0);
return nullptr;
}
unique_ptr<string> path(new string(evhttp_uri_get_path(decode_uri)));
evhttp_uri_free(decode_uri);
return path;
}
void visit_info_cb(struct evhttp_request *req, void *arg)
{
if (nullptr == req)
{
LOG(ERROR, "visit_info request is null");
return;
}
long long total_visit_cnt = redis_server->get_total_visit_count();
shared_ptr<string> page(new string);
redis_server->get_visit_record(page, 0, WANT_VISIT_COUNT);
struct evbuffer *retbuff = evbuffer_new();
if (nullptr == retbuff)
return;
string html1 = R"(<html> <head> <meta charset="UTF-8"></head><body> Total Visit Count:)";
string html2 = R"(</body></html>)";
evbuffer_add_printf(retbuff, "%s %lld</br> %s %s",
html1.c_str(), total_visit_cnt, page->c_str(), html2.c_str());
// HTTP header
evhttp_add_header(req->output_headers, "Server", "HTTP v1.1");
evhttp_add_header(req->output_headers, "Content-Type", "text/html");
evhttp_add_header(req->output_headers, "Connection", "close");
evhttp_send_reply(req, HTTP_OK, "OK", retbuff);
}
void get_cb(struct evhttp_request *req, void *arg)
{
if (nullptr == req)
{
LOG(INFO, "get request is null");
return;
}
shared_ptr<const string> path_old(parse_request_path(req));
if (nullptr == path_old)
{
LOG(INFO, "path is null");
return;
}
/* TODO In the future, take out the common code below,
and delete path, just use path_old as the common page link */
// shared_ptr<string> path(new string(*path_old.get()));
/* remove the first character '/' */
shared_ptr<string> path(new string(path_old->substr(1)));
/* check if file is exist before open it */
struct stat buf;
if (stat(path->c_str(), &buf) == -1)
{
LOG(WARN, "file not exist file:%s", path->c_str());
path->assign("404.html");
}
#ifdef HIDE_LOG_FILE
if (path->compare("website.log") == 0)
{
path->assign("404.html");
}
#endif
LOG(DEBUG, "path:%s", path.get());
struct evbuffer *retbuff = evbuffer_new();
if (nullptr == retbuff)
return;
shared_ptr<string> page(new string);
string::size_type i = path->rfind('.');
if (i == string::npos)
{
LOG(INFO, "error page link:%s", path->c_str());
path->assign("404.html");
i = path->rfind('.');
}
const string ext = path->substr(i);
string content_type;
if (ext.compare(".html") == 0 || ext.compare(".htm") == 0)
content_type = "text/html;charset=utf-8";
else if (ext.compare(".ico") == 0)
content_type = "image/x-icon";
else if (ext.compare(".js") == 0)
content_type = "application/x-javascript";
else if (ext.compare(".css") == 0)
content_type = "text/css";
else if (ext.compare(".pdf") == 0)
content_type = "application/pdf";
else if (ext.compare(".png") == 0)
content_type = "application/x-png";
else if (ext.compare(".svg") == 0)
content_type = "text/xml";
else if (ext.compare(".ttf") == 0)
content_type = "application/x-font-truetype";
else if (ext.compare(".woff") ==0 || ext.compare(".woff2") == 0)
content_type = "application/x-font-woff";
else
{
LOG(INFO, "unknown extension:%s", ext.c_str());
/* take unknow files types as plain file*/
content_type = "text/plain;charset=utf-8";
}
do
{
/* query page in Redis Cache */
if (redis_server->query_cache(path, page))
{
evbuffer_add_printf(retbuff, "%s\n", page->c_str());
LOG(DEBUG, "get page from cache path_link:%s", path->c_str());
break;
}
std::ifstream file(*path);
shared_ptr<string> buffer(new string);
if (!file.is_open())
{
LOG(WARN, "open file error file:%s", path->c_str());
path->assign("404.html");
}
string tmp;
/* TODO the read file method is wrong to binary file */
while (getline(file, tmp))
{
/* append a '\n' to avoid getline() strip '\n' */
buffer->append(tmp.append("\n"));
}
file.close();
evbuffer_add_printf(retbuff, "%s\n", buffer->c_str());
redis_server->insert_cache(path, buffer);
} while (0);
// HTTP header
evhttp_add_header(req->output_headers, "Server", "HTTP v1.1");
evhttp_add_header(req->output_headers,
"Content-Type", content_type.c_str());
evhttp_add_header(req->output_headers, "Connection", "close");
evhttp_send_reply(req, HTTP_OK, "OK", retbuff);
evbuffer_free(retbuff);
}
/* signal function */
void signal_handler(int sig)
{
switch (sig)
{
case SIGTERM:
case SIGHUP:
case SIGQUIT:
case SIGINT:
event_loopbreak();
break;
}
}
#endif // __SERVER_H__