Debian Codegraph @

src/suggest/groonga_suggest_httpd.c

raw symbols SCIP
1 /*
2 Copyright (C) 2010-2015 Brazil
3 Copyright (C) 2020-2022 Sutou Kouhei <[email protected]>
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18 */
19
20 /* groonga origin headers */
21 #include <grn_str.h>
22 #include <grn_msgpack.h>
23
24 #include <stdio.h>
25 #include <signal.h>
26 #include <string.h>
27 #include <sys/types.h>
28 #include <sys/time.h>
29 #include <time.h>
30 #include <stdlib.h>
31 #include <unistd.h>
32 #include <err.h>
33
34 #include <fcntl.h>
35 #include <sys/queue.h>
36 #include <sys/socket.h>
37 #include <sys/types.h>
38 #include <netinet/in.h>
39 #include <sys/resource.h>
40
41 #include "zmq_compatible.h"
42 #include <event.h>
43 #include <evhttp.h>
44 #include <groonga.h>
45 #include <pthread.h>
46
47 #include "util.h"
48
49 #define DEFAULT_PORT 8080
50 #define DEFAULT_MAX_THREADS 8
51
52 #define CONST_STR_LEN(x) x, sizeof(x) - 1
53
54 #define LISTEN_BACKLOG 756
55 #define MIN_MAX_FDS 2048
56 #define MAX_THREADS 128 /* max 256 */
57
58 typedef enum {
59 RUN_MODE_NONE = 0,
60 RUN_MODE_USAGE,
61 RUN_MODE_DAEMON,
62 RUN_MODE_ERROR
63 } run_mode;
64
65 #define RUN_MODE_MASK 0x007f
66 #define RUN_MODE_ENABLE_MAX_FD_CHECK 0x0080
67
68
69 typedef struct {
70 grn_ctx *ctx;
71 grn_obj *db;
72 void *zmq_sock;
73 grn_obj cmd_buf;
74 grn_obj pass_through_parameters;
75 pthread_t thd;
76 uint32_t thread_id;
77 struct event_base *base;
78 struct evhttp *httpd;
79 struct event pulse;
80 const char *log_base_path;
81 FILE *log_file;
82 uint32_t log_count;
83 bool request_reopen_log_file;
84 } thd_data;
85
86 typedef struct {
87 const char *db_path;
88 const char *recv_endpoint;
89 pthread_t thd;
90 void *zmq_ctx;
91 } recv_thd_data;
92
93 #define CMD_BUF_SIZE 1024
94
95 static thd_data threads[MAX_THREADS];
96 static uint32_t default_max_threads = DEFAULT_MAX_THREADS;
97 static uint32_t max_threads;
98 static volatile sig_atomic_t loop = 1;
99 static grn_obj *db;
100 static uint32_t n_lines_per_log_file = 1000000;
101
102 static uint32_t
103 suggest_result(grn_ctx *ctx,
104 struct evbuffer *res_buf, const char *types, const char *query,
105 const char *target_name, int frequency_threshold,
106 double conditional_probability_threshold, int limit,
107 grn_obj *cmd_buf, grn_obj *pass_through_parameters)
108 {
109 if (target_name && types && query) {
110 GRN_BULK_REWIND(cmd_buf);
111 GRN_TEXT_PUTS(ctx, cmd_buf, "/d/suggest?table=item_");
112 grn_text_urlenc(ctx, cmd_buf, target_name, strlen(target_name));
113 GRN_TEXT_PUTS(ctx, cmd_buf, "&column=kana&types=");
114 grn_text_urlenc(ctx, cmd_buf, types, strlen(types));
115 GRN_TEXT_PUTS(ctx, cmd_buf, "&query=");
116 grn_text_urlenc(ctx, cmd_buf, query, strlen(query));
117 GRN_TEXT_PUTS(ctx, cmd_buf, "&frequency_threshold=");
118 grn_text_itoa(ctx, cmd_buf, frequency_threshold);
119 GRN_TEXT_PUTS(ctx, cmd_buf, "&conditional_probability_threshold=");
120 grn_text_ftoa(ctx, cmd_buf, conditional_probability_threshold);
121 GRN_TEXT_PUTS(ctx, cmd_buf, "&limit=");
122 grn_text_itoa(ctx, cmd_buf, limit);
123 if (GRN_TEXT_LEN(pass_through_parameters) > 0) {
124 GRN_TEXT_PUTS(ctx, cmd_buf, "&");
125 GRN_TEXT_PUT(ctx, cmd_buf,
126 GRN_TEXT_VALUE(pass_through_parameters),
127 GRN_TEXT_LEN(pass_through_parameters));
128 }
129 {
130 char *res;
131 int flags;
132 unsigned int res_len;
133
134 grn_ctx_send(ctx,
135 GRN_TEXT_VALUE(cmd_buf),
136 (unsigned int)GRN_TEXT_LEN(cmd_buf),
137 0);
138 grn_ctx_recv(ctx, &res, &res_len, &flags);
139
140 evbuffer_add(res_buf, res, res_len);
141 return res_len;
142 }
143 } else {
144 evbuffer_add(res_buf, "{}", 2);
145 return 2;
146 }
147 }
148
149 static void
150 log_send(struct evkeyvalq *output_headers, struct evbuffer *res_buf,
151 thd_data *thd, struct evkeyvalq *get_args)
152 {
153 uint64_t millisec;
154 int frequency_threshold, limit;
155 double conditional_probability_threshold;
156 const char *callback, *types, *query, *client_id, *target_name,
157 *learn_target_name;
158
159 GRN_BULK_REWIND(&(thd->pass_through_parameters));
160 parse_keyval(thd->ctx, get_args, &query, &types, &client_id, &target_name,
161 &learn_target_name, &callback, &millisec, &frequency_threshold,
162 &conditional_probability_threshold, &limit,
163 &(thd->pass_through_parameters));
164
165 /* send data to learn client */
166 if (thd->zmq_sock && millisec && client_id && query && learn_target_name) {
167 char c;
168 size_t l;
169 msgpack_packer pk;
170 msgpack_sbuffer sbuf;
171 size_t cnt;
172 int submit_flag = 0;
173
174 msgpack_sbuffer_init(&sbuf);
175 msgpack_packer_init(&pk, &sbuf, msgpack_sbuffer_write);
176
177 cnt = 4;
178 if (types && !strcmp(types, "submit")) {
179 cnt++;
180 types = NULL;
181 submit_flag = 1;
182 }
183 msgpack_pack_map(&pk, cnt);
184
185 c = 'i';
186 msgpack_pack_str(&pk, 1);
187 msgpack_pack_str_body(&pk, &c, 1);
188 l = strlen(client_id);
189 msgpack_pack_str(&pk, l);
190 msgpack_pack_str_body(&pk, client_id, l);
191
192 c = 'q';
193 msgpack_pack_str(&pk, 1);
194 msgpack_pack_str_body(&pk, &c, 1);
195 l = strlen(query);
196 msgpack_pack_str(&pk, l);
197 msgpack_pack_str_body(&pk, query, l);
198
199 c = 's';
200 msgpack_pack_str(&pk, 1);
201 msgpack_pack_str_body(&pk, &c, 1);
202 msgpack_pack_uint64(&pk, millisec);
203
204 c = 'l';
205 msgpack_pack_str(&pk, 1);
206 msgpack_pack_str_body(&pk, &c, 1);
207 l = strlen(learn_target_name);
208 msgpack_pack_str(&pk, l);
209 msgpack_pack_str_body(&pk, learn_target_name, l);
210
211 if (submit_flag) {
212 c = 't';
213 msgpack_pack_str(&pk, 1);
214 msgpack_pack_str_body(&pk, &c, 1);
215 msgpack_pack_true(&pk);
216 }
217 {
218 zmq_msg_t msg;
219 if (!zmq_msg_init_size(&msg, sbuf.size)) {
220 memcpy((void *)zmq_msg_data(&msg), sbuf.data, sbuf.size);
221 if (zmq_msg_send(&msg, thd->zmq_sock, 0) == -1) {
222 print_error("zmq_msg_send() error");
223 }
224 zmq_msg_close(&msg);
225 }
226 }
227 msgpack_sbuffer_destroy(&sbuf);
228 }
229 /* make result */
230 {
231 size_t content_length;
232 if (callback) {
233 evhttp_add_header(output_headers,
234 "Content-Type", "text/javascript; charset=UTF-8");
235 content_length = strlen(callback);
236 evbuffer_add(res_buf, callback, content_length);
237 evbuffer_add(res_buf, "(", 1);
238 content_length += suggest_result(thd->ctx,
239 res_buf, types, query, target_name,
240 frequency_threshold,
241 conditional_probability_threshold,
242 limit,
243 &(thd->cmd_buf),
244 &(thd->pass_through_parameters)) + 3;
245 evbuffer_add(res_buf, ");", 2);
246 } else {
247 evhttp_add_header(output_headers,
248 "Content-Type", "application/json; charset=UTF-8");
249 content_length = suggest_result(thd->ctx,
250 res_buf, types, query, target_name,
251 frequency_threshold,
252 conditional_probability_threshold,
253 limit,
254 &(thd->cmd_buf),
255 &(thd->pass_through_parameters));
256 }
257 {
258 #define NUM_BUF_SIZE 16
259 char num_buf[NUM_BUF_SIZE];
260 grn_snprintf(num_buf,
261 NUM_BUF_SIZE,
262 NUM_BUF_SIZE,
263 "%" GRN_FMT_SIZE,
264 content_length);
265 evhttp_add_header(output_headers, "Content-Length", num_buf);
266 #undef NUM_BUF_SIZE
267 }
268 }
269 }
270
271 static void
272 cleanup_httpd_thread(thd_data *thd) {
273 if (thd->log_file) {
274 fclose(thd->log_file);
275 }
276 if (thd->httpd) {
277 evhttp_free(thd->httpd);
278 }
279 if (thd->zmq_sock) {
280 zmq_close(thd->zmq_sock);
281 }
282 grn_obj_unlink(thd->ctx, &(thd->cmd_buf));
283 grn_obj_unlink(thd->ctx, &(thd->pass_through_parameters));
284 if (thd->ctx) {
285 grn_ctx_close(thd->ctx);
286 }
287 event_base_free(thd->base);
288 }
289
290 static void
291 close_log_file(thd_data *thread)
292 {
293 fclose(thread->log_file);
294 thread->log_file = NULL;
295 thread->request_reopen_log_file = false;
296 }
297
298 static void
299 generic_handler(struct evhttp_request *req, void *arg)
300 {
301 struct evkeyvalq args;
302 thd_data *thd = arg;
303
304 if (!loop) {
305 event_base_loopexit(thd->base, NULL);
306 return;
307 }
308 if (!req->uri) { return; }
309
310 evhttp_parse_query(req->uri, &args);
311 {
312 struct evbuffer *res_buf;
313 if (!(res_buf = evbuffer_new())) {
314 err(1, "failed to create response buffer");
315 }
316
317 evhttp_add_header(req->output_headers, "Connection", "close");
318
319 log_send(req->output_headers, res_buf, thd, &args);
320 evhttp_send_reply(req, HTTP_OK, "OK", res_buf);
321 evbuffer_free(res_buf);
322 /* logging */
323 {
324 if (thd->log_base_path) {
325 if (thd->log_file && thd->request_reopen_log_file) {
326 close_log_file(thd);
327 }
328 if (!thd->log_file) {
329 time_t n;
330 struct tm *t_st;
331 char p[PATH_MAX + 1];
332
333 time(&n);
334 t_st = localtime(&n);
335
336 grn_snprintf(p,
337 PATH_MAX,
338 PATH_MAX,
339 "%s%04d%02d%02d%02d%02d%02d-%02d",
340 thd->log_base_path,
341 t_st->tm_year + 1900,
342 t_st->tm_mon + 1,
343 t_st->tm_mday,
344 t_st->tm_hour,
345 t_st->tm_min,
346 t_st->tm_sec,
347 thd->thread_id);
348
349 if (!(thd->log_file = fopen(p, "a"))) {
350 print_error("cannot open log_file %s.", p);
351 } else {
352 thd->log_count = 0;
353 }
354 }
355 if (thd->log_file) {
356 fprintf(thd->log_file, "%s\n", req->uri);
357 thd->log_count++;
358 if (n_lines_per_log_file > 0 &&
359 thd->log_count >= n_lines_per_log_file) {
360 close_log_file(thd);
361 }
362 }
363 }
364 }
365 }
366 evhttp_clear_headers(&args);
367 }
368
369 static int
370 bind_socket(uint16_t port)
371 {
372 int nfd;
373 if ((nfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
374 print_error("cannot open socket for http.");
375 return -1;
376 } else {
377 int r, one = 1;
378 struct sockaddr_in addr;
379
380 r = setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(int));
381 memset(&addr, 0, sizeof(addr));
382 addr.sin_family = AF_INET;
383 addr.sin_addr.s_addr = INADDR_ANY;
384 addr.sin_port = htons(port);
385
386 if ((r = bind(nfd, (struct sockaddr *)&addr, sizeof(addr))) < 0) {
387 print_error("cannot bind socket for http.");
388 return r;
389 }
390 if ((r = listen(nfd, LISTEN_BACKLOG)) < 0) {
391 print_error("cannot listen socket for http.");
392 return r;
393 }
394 if ((r = fcntl(nfd, F_GETFL, 0)) < 0 || fcntl(nfd, F_SETFL, r | O_NONBLOCK) < 0 ) {
395 print_error("cannot fcntl socket for http.");
396 return -1;
397 }
398 return nfd;
399 }
400 }
401
402 static void
403 signal_handler(int sig)
404 {
405 loop = 0;
406 }
407
408 static void
409 signal_reopen_log_file(int sig)
410 {
411 uint32_t i;
412
413 for (i = 0; i < max_threads; i++) {
414 threads[i].request_reopen_log_file = true;
415 }
416 }
417
418 void
419 timeout_handler(int fd, short events, void *arg) {
420 thd_data *thd = arg;
421 if (!loop) {
422 event_base_loopexit(thd->base, NULL);
423 } else {
424 struct timeval tv = {1, 0};
425 evtimer_add(&(thd->pulse), &tv);
426 }
427 }
428
429 static void *
430 dispatch(void *arg)
431 {
432 event_base_dispatch((struct event_base *)arg);
433 return NULL;
434 }
435
436 static void
437 msgpack2json(msgpack_object *o, grn_ctx *ctx, grn_obj *buf)
438 {
439 switch (o->type) {
440 case MSGPACK_OBJECT_POSITIVE_INTEGER:
441 grn_text_ulltoa(ctx, buf, o->via.u64);
442 break;
443 case MSGPACK_OBJECT_STR:
444 grn_text_esc(ctx, buf,
445 MSGPACK_OBJECT_STR_PTR(o),
446 MSGPACK_OBJECT_STR_SIZE(o));
447 break;
448 case MSGPACK_OBJECT_ARRAY:
449 GRN_TEXT_PUTC(ctx, buf, '[');
450 {
451 uint32_t i;
452 for (i = 0; i < o->via.array.size; i++) {
453 msgpack2json(o->via.array.ptr, ctx, buf);
454 }
455 }
456 GRN_TEXT_PUTC(ctx, buf, ']');
457 break;
458 case MSGPACK_OBJECT_FLOAT64:
459 grn_text_ftoa(ctx, buf, MSGPACK_OBJECT_FLOAT64_VALUE(o));
460 break;
461 default:
462 print_error("cannot handle this msgpack type.");
463 }
464 }
465
466 static void
467 load_from_learner(msgpack_object *o, grn_ctx *ctx, grn_obj *cmd_buf)
468 {
469 if (o->type == MSGPACK_OBJECT_MAP && o->via.map.size) {
470 msgpack_object_kv *kv;
471 msgpack_object *key;
472 msgpack_object *value;
473 kv = &(o->via.map.ptr[0]);
474 key = &(kv->key);
475 value = &(kv->val);
476 if (key->type == MSGPACK_OBJECT_STR && MSGPACK_OBJECT_STR_SIZE(key) == 6 &&
477 !memcmp(MSGPACK_OBJECT_STR_PTR(key), CONST_STR_LEN("target"))) {
478 if (value->type == MSGPACK_OBJECT_STR) {
479 uint32_t i;
480 GRN_BULK_REWIND(cmd_buf);
481 GRN_TEXT_PUTS(ctx, cmd_buf, "load --table ");
482 GRN_TEXT_PUT(ctx, cmd_buf,
483 MSGPACK_OBJECT_STR_PTR(value),
484 MSGPACK_OBJECT_STR_SIZE(value));
485 grn_ctx_send(ctx,
486 GRN_TEXT_VALUE(cmd_buf),
487 (unsigned int)GRN_TEXT_LEN(cmd_buf),
488 GRN_CTX_MORE);
489 grn_ctx_send(ctx, CONST_STR_LEN("["), GRN_CTX_MORE);
490 if (MSGPACK_OBJECT_STR_SIZE(value) > 5) {
491 if (!memcmp(MSGPACK_OBJECT_STR_PTR(value), CONST_STR_LEN("item_")) ||
492 !memcmp(MSGPACK_OBJECT_STR_PTR(value), CONST_STR_LEN("pair_"))) {
493 char delim = '{';
494 GRN_BULK_REWIND(cmd_buf);
495 for (i = 1; i < o->via.map.size; i++) {
496 GRN_TEXT_PUTC(ctx, cmd_buf, delim);
497 kv = &(o->via.map.ptr[i]);
498 msgpack2json(&(kv->key), ctx, cmd_buf);
499 GRN_TEXT_PUTC(ctx, cmd_buf, ':');
500 msgpack2json(&(kv->val), ctx, cmd_buf);
501 delim = ',';
502 }
503 GRN_TEXT_PUTC(ctx, cmd_buf, '}');
504 /* printf("msg: %.*s\n", GRN_TEXT_LEN(cmd_buf), GRN_TEXT_VALUE(cmd_buf)); */
505 grn_ctx_send(ctx,
506 GRN_TEXT_VALUE(cmd_buf),
507 (unsigned int)GRN_TEXT_LEN(cmd_buf),
508 GRN_CTX_MORE);
509 }
510 }
511 grn_ctx_send(ctx, CONST_STR_LEN("]"), 0);
512 {
513 char *res;
514 int flags;
515 unsigned int res_len;
516 grn_ctx_recv(ctx, &res, &res_len, &flags);
517 }
518 }
519 }
520 }
521 }
522
523 static void
524 recv_handler(grn_ctx *ctx, void *zmq_recv_sock, msgpack_zone *mempool, grn_obj *cmd_buf)
525 {
526 zmq_msg_t msg;
527
528 if (zmq_msg_init(&msg)) {
529 print_error("cannot init zmq message.");
530 } else {
531 if (zmq_msg_recv(&msg, zmq_recv_sock, 0) == -1) {
532 print_error("cannot recv zmq message.");
533 } else {
534 msgpack_object obj;
535 msgpack_unpack_return ret;
536
537 ret = msgpack_unpack(zmq_msg_data(&msg), zmq_msg_size(&msg), NULL, mempool, &obj);
538 if (MSGPACK_UNPACK_SUCCESS == ret) {
539 load_from_learner(&obj, ctx, cmd_buf);
540 } else {
541 print_error("invalid recv data.");
542 }
543 msgpack_zone_clear(mempool);
544 }
545 zmq_msg_close(&msg);
546 }
547 }
548
549 static void *
550 recv_from_learner(void *arg)
551 {
552 void *zmq_recv_sock;
553 recv_thd_data *thd = arg;
554
555 if ((zmq_recv_sock = zmq_socket(thd->zmq_ctx, ZMQ_SUB))) {
556 if (!zmq_connect(zmq_recv_sock, thd->recv_endpoint)) {
557 grn_ctx ctx;
558 if (!grn_ctx_init(&ctx, 0)) {
559 if ((!grn_ctx_use(&ctx, db))) {
560 msgpack_zone *mempool;
561 if ((mempool = msgpack_zone_new(MSGPACK_ZONE_CHUNK_SIZE))) {
562 grn_obj cmd_buf;
563 zmq_pollitem_t items[] = {
564 { zmq_recv_sock, 0, ZMQ_POLLIN, 0}
565 };
566 GRN_TEXT_INIT(&cmd_buf, 0);
567 zmq_setsockopt(zmq_recv_sock, ZMQ_SUBSCRIBE, "", 0);
568 while (loop) {
569 zmq_poll(items, 1, 10000);
570 if (items[0].revents & ZMQ_POLLIN) {
571 recv_handler(&ctx, zmq_recv_sock, mempool, &cmd_buf);
572 }
573 }
574 grn_obj_unlink(&ctx, &cmd_buf);
575 msgpack_zone_free(mempool);
576 } else {
577 print_error("cannot create msgpack zone.");
578 }
579 /* db_close */
580 } else {
581 print_error("error in grn_db_open() on recv thread.");
582 }
583 grn_ctx_fin(&ctx);
584 } else {
585 print_error("error in grn_ctx_init() on recv thread.");
586 }
587 } else {
588 print_error("cannot create recv zmq_socket.");
589 }
590 } else {
591 print_error("cannot connect zmq_socket.");
592 }
593 return NULL;
594 }
595
596 static int
597 serve_threads(uint32_t nthreads, uint16_t port, const char *db_path, void *zmq_ctx,
598 const char *send_endpoint, const char *recv_endpoint,
599 const char *log_base_path)
600 {
601 int nfd;
602 uint32_t i;
603 if ((nfd = bind_socket(port)) < 0) {
604 print_error("cannot bind socket. please check port number with netstat.");
605 return -1;
606 }
607
608 for (i = 0; i < nthreads; i++) {
609 memset(&threads[i], 0, sizeof(threads[i]));
610 threads[i].request_reopen_log_file = false;
611 if (!(threads[i].base = event_init())) {
612 print_error("error in event_init() on thread %d.", i);
613 } else {
614 if (!(threads[i].httpd = evhttp_new(threads[i].base))) {
615 print_error("error in evhttp_new() on thread %d.", i);
616 } else {
617 int r;
618 if ((r = evhttp_accept_socket(threads[i].httpd, nfd))) {
619 print_error("error in evhttp_accept_socket() on thread %d.", i);
620 } else {
621 if (send_endpoint) {
622 if (!(threads[i].zmq_sock = zmq_socket(zmq_ctx, ZMQ_PUB))) {
623 print_error("cannot create zmq_socket.");
624 } else if (zmq_connect(threads[i].zmq_sock, send_endpoint)) {
625 print_error("cannot connect zmq_socket.");
626 zmq_close(threads[i].zmq_sock);
627 threads[i].zmq_sock = NULL;
628 } else {
629 uint64_t hwm = 1;
630 zmq_setsockopt(threads[i].zmq_sock, ZMQ_SNDHWM, &hwm, sizeof(uint64_t));
631 }
632 } else {
633 threads[i].zmq_sock = NULL;
634 }
635 if (!(threads[i].ctx = grn_ctx_open(0))) {
636 print_error("error in grn_ctx_open() on thread %d.", i);
637 } else if (grn_ctx_use(threads[i].ctx, db)) {
638 print_error("error in grn_db_open() on thread %d.", i);
639 } else {
640 GRN_TEXT_INIT(&(threads[i].cmd_buf), 0);
641 GRN_TEXT_INIT(&(threads[i].pass_through_parameters), 0);
642 threads[i].log_base_path = log_base_path;
643 threads[i].thread_id = i;
644 evhttp_set_gencb(threads[i].httpd, generic_handler, &threads[i]);
645 evhttp_set_timeout(threads[i].httpd, 10);
646 {
647 struct timeval tv = {1, 0};
648 evtimer_set(&(threads[i].pulse), timeout_handler, &threads[i]);
649 evtimer_add(&(threads[i].pulse), &tv);
650 }
651 if ((r = pthread_create(&(threads[i].thd), NULL, dispatch, threads[i].base))) {
652 print_error("error in pthread_create() on thread %d.", i);
653 }
654 }
655 }
656 }
657 }
658 }
659
660 /* recv thread from learner */
661 if (recv_endpoint) {
662 recv_thd_data rthd;
663 rthd.db_path = db_path;
664 rthd.recv_endpoint = recv_endpoint;
665 rthd.zmq_ctx = zmq_ctx;
666
667 if (pthread_create(&(rthd.thd), NULL, recv_from_learner, &rthd)) {
668 print_error("error in pthread_create() on thread %d.", i);
669 }
670 if (pthread_join(rthd.thd, NULL)) {
671 print_error("error in pthread_join() on thread %d.", i);
672 }
673 } else {
674 while (loop) { sleep(1); }
675 }
676
677 /* join all httpd thread */
678 for (i = 0; i < nthreads; i++) {
679 if (threads[i].thd) {
680 if (pthread_join(threads[i].thd, NULL)) {
681 print_error("error in pthread_join() on thread %d.", i);
682 }
683 }
684 cleanup_httpd_thread(&(threads[i]));
685 }
686 return 0;
687 }
688
689 static uint32_t
690 get_core_number(void)
691 {
692 #ifdef ACTUALLY_GET_CORE_NUMBER
693 #ifdef _SC_NPROCESSORS_CONF
694 return sysconf(_SC_NPROCESSORS_CONF);
695 #else /* _SC_NPROCESSORS_CONF */
696 int n_processors;
697 size_t length = sizeof(n_processors);
698 int mib[] = {CTL_HW, HW_NCPU};
699 if (sysctl(mib, sizeof(mib) / sizeof(mib[0]),
700 &n_processors, &length, NULL, 0) == 0 &&
701 length == sizeof(n_processors) &&
702 0 < n_processors) {
703 return n_processors;
704 } else {
705 return 1;
706 }
707 #endif /* _SC_NPROCESSORS_CONF */
708 #endif /* ACTUALLY_GET_CORE_NUMBER */
709 return 0;
710 }
711
712 static void
713 usage(FILE *output)
714 {
715 fprintf(
716 output,
717 "Usage: groonga-suggest-httpd [options...] db_path\n"
718 "db_path:\n"
719 " specify groonga database path which is used for suggestion.\n"
720 "\n"
721 "options:\n"
722 " -p, --port <port number> : http server port number\n"
723 " (default: %d)\n"
724 /*
725 " --address <ip/hostname> : server address to listen\n"
726 " (default: %s)\n"
727 */
728 " -c <thread number> : number of server threads\n"
729 " (deprecated. use --n-threads)\n"
730 " -t, --n-threads <thread number> : number of server threads\n"
731 " (default: %d)\n"
732 " -s, --send-endpoint <send endpoint> : send endpoint\n"
733 " (ex. tcp://example.com:1234)\n"
734 " -r, --receive-endpoint <receive endpoint> : receive endpoint\n"
735 " (ex. tcp://example.com:1235)\n"
736 " -l, --log-base-path <path prefix> : log path prefix\n"
737 " --n-lines-per-log-file <lines number> : number of lines in a log file\n"
738 " use 0 for disabling this\n"
739 " (default: %d)\n"
740 " -d, --daemon : daemonize\n"
741 " --disable-max-fd-check : disable max FD check on start\n"
742 " -h, --help : show this message\n",
743 DEFAULT_PORT, default_max_threads, n_lines_per_log_file);
744 }
745
746 int
747 main(int argc, char **argv)
748 {
749 uint16_t port_no = DEFAULT_PORT;
750 const char *max_threads_string = NULL, *port_string = NULL;
751 const char *address;
752 const char *send_endpoint = NULL, *recv_endpoint = NULL, *log_base_path = NULL;
753 const char *n_lines_per_log_file_string = NULL;
754 int n_processed_args, flags = RUN_MODE_ENABLE_MAX_FD_CHECK;
755 run_mode mode = RUN_MODE_NONE;
756
757 if (!(default_max_threads = get_core_number())) {
758 default_max_threads = DEFAULT_MAX_THREADS;
759 }
760
761 /* parse options */
762 {
763 static grn_str_getopt_opt opts[] = {
764 {'c', NULL, NULL, 0, GETOPT_OP_NONE}, /* deprecated */
765 {'t', "n-threads", NULL, 0, GETOPT_OP_NONE},
766 {'h', "help", NULL, RUN_MODE_USAGE, GETOPT_OP_UPDATE},
767 {'p', "port", NULL, 0, GETOPT_OP_NONE},
768 {'\0', "bind-address", NULL, 0, GETOPT_OP_NONE}, /* not supported yet */
769 {'s', "send-endpoint", NULL, 0, GETOPT_OP_NONE},
770 {'r', "receive-endpoint", NULL, 0, GETOPT_OP_NONE},
771 {'l', "log-base-path", NULL, 0, GETOPT_OP_NONE},
772 {'\0', "n-lines-per-log-file", NULL, 0, GETOPT_OP_NONE},
773 {'d', "daemon", NULL, RUN_MODE_DAEMON, GETOPT_OP_UPDATE},
774 {'\0', "disable-max-fd-check", NULL, RUN_MODE_ENABLE_MAX_FD_CHECK,
775 GETOPT_OP_OFF},
776 {'\0', NULL, NULL, 0, 0}
777 };
778 opts[0].arg = &max_threads_string;
779 opts[1].arg = &max_threads_string;
780 opts[3].arg = &port_string;
781 opts[4].arg = &address;
782 opts[5].arg = &send_endpoint;
783 opts[6].arg = &recv_endpoint;
784 opts[7].arg = &log_base_path;
785 opts[8].arg = &n_lines_per_log_file_string;
786
787 n_processed_args = grn_str_getopt(argc, argv, opts, &flags);
788 }
789
790 /* main */
791 mode = (flags & RUN_MODE_MASK);
792 if (n_processed_args < 0 ||
793 (argc - n_processed_args) != 1 ||
794 mode == RUN_MODE_ERROR) {
795 usage(stderr);
796 return EXIT_FAILURE;
797 } else if (mode == RUN_MODE_USAGE) {
798 usage(stdout);
799 return EXIT_SUCCESS;
800 } else {
801 grn_ctx ctx;
802 void *zmq_ctx;
803
804 if (max_threads_string) {
805 max_threads = (uint32_t)atoi(max_threads_string);
806 if (max_threads > MAX_THREADS) {
807 print_error("too many threads. limit to %d.", MAX_THREADS);
808 max_threads = MAX_THREADS;
809 }
810 } else {
811 max_threads = default_max_threads;
812 }
813
814 if (port_string) {
815 port_no = (uint16_t)atoi(port_string);
816 }
817
818 if (flags & RUN_MODE_ENABLE_MAX_FD_CHECK) {
819 /* check environment */
820 struct rlimit rlim;
821 if (!getrlimit(RLIMIT_NOFILE, &rlim)) {
822 if (rlim.rlim_max < MIN_MAX_FDS) {
823 print_error("too small max fds. %d required.", MIN_MAX_FDS);
824 return -1;
825 }
826 rlim.rlim_cur = rlim.rlim_cur;
827 setrlimit(RLIMIT_NOFILE, &rlim);
828 }
829 }
830
831 if (n_lines_per_log_file_string) {
832 int64_t n_lines;
833 n_lines = grn_atoll(n_lines_per_log_file_string,
834 n_lines_per_log_file_string + strlen(n_lines_per_log_file_string),
835 NULL);
836 if (n_lines < 0) {
837 print_error("--n-lines-per-log-file must be >= 0: <%s>",
838 n_lines_per_log_file_string);
839 return(EXIT_FAILURE);
840 }
841 if (n_lines > UINT32_MAX) {
842 print_error("--n-lines-per-log-file must be <= %ld: <%s>",
843 UINT32_MAX, n_lines_per_log_file_string);
844 return(EXIT_FAILURE);
845 }
846 n_lines_per_log_file = (uint32_t)n_lines;
847 }
848
849 if (mode == RUN_MODE_DAEMON) {
850 daemonize();
851 }
852
853 grn_init();
854 grn_ctx_init(&ctx, 0);
855 if ((db = grn_db_open(&ctx, argv[n_processed_args]))) {
856 if ((zmq_ctx = zmq_init(1))) {
857 signal(SIGTERM, signal_handler);
858 signal(SIGINT, signal_handler);
859 signal(SIGQUIT, signal_handler);
860 signal(SIGUSR1, signal_reopen_log_file);
861
862 serve_threads(max_threads, port_no, argv[n_processed_args], zmq_ctx,
863 send_endpoint, recv_endpoint, log_base_path);
864 zmq_term(zmq_ctx);
865 } else {
866 print_error("cannot create zmq context.");
867 }
868 grn_obj_close(&ctx, db);
869 } else {
870 print_error("cannot open db.");
871 }
872 grn_ctx_fin(&ctx);
873 grn_fin();
874 }
875 return 0;
876 }