-
-
Notifications
You must be signed in to change notification settings - Fork 37
/
rserver.c
1301 lines (1174 loc) · 37.1 KB
/
rserver.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
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2018, Peter Ohler, All rights reserved.
#include <netdb.h>
#include <netinet/tcp.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <sys/wait.h>
#include <ruby.h>
#include <ruby/thread.h>
#include <ruby/encoding.h>
#include "atomic.h"
#include "bind.h"
#include "con.h"
#include "debug.h"
#include "domain.h"
#include "dtime.h"
#include "err.h"
#include "graphql.h"
#include "http.h"
#include "log.h"
#include "page.h"
#include "pub.h"
#include "request.h"
#include "res.h"
#include "response.h"
#include "rhook.h"
#include "rresponse.h"
#include "rserver.h"
#include "rupgraded.h"
#include "server.h"
#include "sse.h"
#include "upgraded.h"
#include "websocket.h"
extern void agoo_shutdown();
extern sig_atomic_t agoo_stop;
static VALUE server_mod = Qundef;
static VALUE connect_sym;
static VALUE delete_sym;
static VALUE get_sym;
static VALUE head_sym;
static VALUE options_sym;
static VALUE post_sym;
static VALUE push_env_key;
static VALUE put_sym;
static VALUE patch_sym;
static VALUE rserver;
static ID call_id;
static ID each_id;
static ID on_close_id;
static ID on_drained_id;
static ID on_error_id;
static ID on_message_id;
static ID on_request_id;
static ID to_i_id;
static const char err500[] = "HTTP/1.1 500 Internal Server Error\r\n";
static double poll_timeout = 0.1;
struct _rServer the_rserver = {};
static void
server_mark(void *ptr) {
agooUpgraded up;
rb_gc_mark(rserver);
pthread_mutex_lock(&agoo_server.up_lock);
for (up = agoo_server.up_list; NULL != up; up = up->next) {
if (Qnil != (VALUE)up->ctx) {
rb_gc_mark((VALUE)up->ctx);
}
if (Qnil != (VALUE)up->env) {
rb_gc_mark((VALUE)up->env);
}
if (Qnil != (VALUE)up->wrap) {
rb_gc_mark((VALUE)up->wrap);
}
}
pthread_mutex_unlock(&agoo_server.up_lock);
}
static void
url_bind(VALUE rurl) {
struct _agooErr err = AGOO_ERR_INIT;
agooBind b = agoo_bind_url(&err, StringValuePtr(rurl));
if (AGOO_ERR_OK != err.code) {
rb_raise(rb_eArgError, "%s", err.msg);
}
agoo_server_bind(b);
}
static int
configure(agooErr err, int port, const char *root, VALUE options) {
if (AGOO_ERR_OK != agoo_pages_set_root(err, root)) {
return err->code;
}
agoo_server.thread_cnt = 0;
the_rserver.worker_cnt = 1;
the_rserver.uses = NULL;
atomic_init(&agoo_server.running, 0);
agoo_server.listen_thread = 0;
agoo_server.con_loops = NULL;
agoo_server.root_first = false;
agoo_server.binds = NULL;
if (Qnil != options) {
VALUE v;
if (Qnil != (v = rb_hash_lookup(options, ID2SYM(rb_intern("thread_count"))))) {
int tc = FIX2INT(v);
if (1 <= tc || tc < 1000) {
agoo_server.thread_cnt = tc;
} else {
rb_raise(rb_eArgError, "thread_count must be between 1 and 1000.");
}
}
if (Qnil != (v = rb_hash_lookup(options, ID2SYM(rb_intern("worker_count"))))) {
int wc = FIX2INT(v);
if (1 <= wc || wc < MAX_WORKERS) {
the_rserver.worker_cnt = wc;
} else {
rb_raise(rb_eArgError, "thread_count must be between 1 and %d.", MAX_WORKERS);
}
}
if (Qnil != (v = rb_hash_lookup(options, ID2SYM(rb_intern("poll_timeout"))))) {
double timeout = rb_num2dbl(v);
if (0.0001 <= timeout || timeout < 1.0) {
poll_timeout = timeout;
} else {
rb_raise(rb_eArgError, "poll_timeout must be between 0.0001 and 1.0.");
}
}
if (Qnil != (v = rb_hash_lookup(options, ID2SYM(rb_intern("max_push_pending"))))) {
int mpp = FIX2INT(v);
if (0 <= mpp || mpp < 1000) {
agoo_server.max_push_pending = mpp;
} else {
rb_raise(rb_eArgError, "max_push_pending must be between 0 and 1000.");
}
}
if (Qnil != (v = rb_hash_lookup(options, ID2SYM(rb_intern("pedantic"))))) {
agoo_server.pedantic = (Qtrue == v);
}
if (Qnil != (v = rb_hash_lookup(options, ID2SYM(rb_intern("root_first"))))) {
agoo_server.root_first = (Qtrue == v);
}
if (Qnil != (v = rb_hash_lookup(options, ID2SYM(rb_intern("Port"))))) {
if (rb_cInteger == rb_obj_class(v)) {
port = NUM2INT(v);
} else {
switch (rb_type(v)) {
case T_STRING:
port = atoi(StringValuePtr(v));
break;
case T_FIXNUM:
port = NUM2INT(v);
break;
default:
break;
}
}
}
if (Qnil != (v = rb_hash_lookup(options, ID2SYM(rb_intern("ssl_cert"))))) {
rb_check_type(v, T_STRING);
const char *cert =StringValuePtr(v);
if (Qnil != (v = rb_hash_lookup(options, ID2SYM(rb_intern("ssl_key"))))) {
rb_check_type(v, T_STRING);
const char *key =StringValuePtr(v);
if (AGOO_ERR_OK != agoo_server_ssl_init(err, cert, key)) {
rb_raise(rb_eArgError, "%s", err->msg);
}
} else {
rb_raise(rb_eArgError, "An ssl_key must be provided if an ssl_cert was provided.");
}
}
if (Qnil != (v = rb_hash_lookup(options, ID2SYM(rb_intern("bind"))))) {
int len;
int i;
switch (rb_type(v)) {
case T_STRING:
url_bind(v);
break;
case T_ARRAY:
len = (int)RARRAY_LEN(v);
for (i = 0; i < len; i++) {
url_bind(rb_ary_entry(v, i));
}
break;
default:
rb_raise(rb_eArgError, "bind option must be a String or Array of Strings.");
break;
}
}
if (Qnil != (v = rb_hash_lookup(options, ID2SYM(rb_intern("graphql"))))) {
const char *path;
agooHook get_hook;
agooHook post_hook;
agooHook options_hook;
agooHook head = NULL;
long plen;
VALUE hide_schema = Qnil;
rb_check_type(v, T_STRING);
if (AGOO_ERR_OK != gql_init(err)) {
return err->code;
}
path = StringValuePtr(v);
plen = (long)RSTRING_LEN(v);
get_hook = agoo_hook_func_create(AGOO_GET, path, gql_eval_get_hook, &agoo_server.eval_queue);
post_hook = agoo_hook_func_create(AGOO_POST, path, gql_eval_post_hook, &agoo_server.eval_queue);
options_hook = agoo_hook_func_create(AGOO_OPTIONS, path, gql_eval_options_hook, &agoo_server.eval_queue);
if (Qnil != (hide_schema = rb_hash_lookup(options, ID2SYM(rb_intern("hide_schema")))) && Qtrue == hide_schema) {
head = get_hook;
} else {
char schema_path[256];
agooHook dump_hook;
if ((int)sizeof(schema_path) - 8 < plen) {
rb_raise(rb_eArgError, "A graphql schema path is limited to %d characters.", (int)(sizeof(schema_path) - 8));
}
memcpy(schema_path, path, plen);
memcpy(schema_path + plen, "/schema", 8);
dump_hook = agoo_hook_func_create(AGOO_GET, schema_path, gql_dump_hook, &agoo_server.eval_queue);
dump_hook->next = get_hook;
head = dump_hook;
}
get_hook->next = post_hook;
post_hook->next = options_hook;
options_hook->next = agoo_server.hooks;
agoo_server.hooks = head;
}
if (Qnil != (v = rb_hash_lookup(options, ID2SYM(rb_intern("quiet"))))) {
if (Qtrue == v) {
agoo_info_cat.on = false;
}
}
if (Qnil != (v = rb_hash_lookup(options, ID2SYM(rb_intern("debug"))))) {
if (Qtrue == v) {
agoo_error_cat.on = true;
agoo_warn_cat.on = true;
agoo_info_cat.on = true;
agoo_debug_cat.on = true;
agoo_con_cat.on = true;
agoo_req_cat.on = true;
agoo_resp_cat.on = true;
agoo_eval_cat.on = true;
agoo_push_cat.on = true;
}
}
}
if (0 < port) {
agooBind b = agoo_bind_port(err, port);
if (AGOO_ERR_OK != err->code) {
rb_raise(rb_eArgError, "%s", err->msg);
}
agoo_server_bind(b);
}
return AGOO_ERR_OK;
}
/* Document-method: init
*
* call-seq: init(port, root, options)
*
* Configures the server that will listen on the designated _port_ and using
* the _root_ as the root of the static resources. This must be called before
* using other server methods. Logging is feature based and not level based
* and the options reflect that approach. If bind option is to be used instead
* of the port then set the port to zero.
*
* - *options* [_Hash_] server options
*
* - *:pedantic* [_true_|_false_] if true response header and status codes are checked and an exception raised if they violate the rack spec at https://github.com/rack/rack/blob/master/SPEC, https://tools.ietf.org/html/rfc3875#section-4.1.18, or https://tools.ietf.org/html/rfc7230.
*
* - *:thread_count* [_Integer_] number of ruby worker threads. Defaults to one. If zero then the _start_ function will not return but instead will proess using the thread that called _start_. Usually the default is best unless the workers are making IO calls.
*
* - *:worker_count* [_Integer_] number of workers to fork. Defaults to one which is not to fork.
*
* - *:poll_timeout* [_Float_] timeout seconds when polling. Default is 0.1. Lower gives faster response times but uses more CPU.
*
* - *:bind* [_String_|_Array_] a binding or array of binds. Examples are: "http ://127.0.0.1:6464", "unix:///tmp/agoo.socket", "http ://[::1]:6464, or to not restrict the address "http ://:6464".
*
* - *:graphql* [_String_] path to GraphQL endpoint if support for GraphQL is desired.
*
* - *:max_push_pending* [_Integer_] maximum number or outstanding push messages, less than 1000.
*
* - *:ssl_cert* [_String_] filepath to the SSL certificate file.
*
* - *:ssl_key* [_String_] filepath to the SSL private key file.
*
* - *:hide_schema* [_true_|_false_] if true the graphql/schema path is handled.
*/
static VALUE
rserver_init(int argc, VALUE *argv, VALUE self) {
struct _agooErr err = AGOO_ERR_INIT;
int port;
const char *root;
VALUE options = Qnil;
if (argc < 2 || 3 < argc) {
rb_raise(rb_eArgError, "Wrong number of arguments to Agoo::Server.configure.");
}
port = FIX2INT(argv[0]);
rb_check_type(argv[1], T_STRING);
root = StringValuePtr(argv[1]);
if (3 <= argc) {
options = argv[2];
}
if (AGOO_ERR_OK != agoo_server_setup(&err)) {
rb_raise(rb_eStandardError, "%s", err.msg);
}
agoo_server.ctx_nil_value = (void*)Qnil;
agoo_server.env_nil_value = (void*)Qnil;
if (AGOO_ERR_OK != configure(&err, port, root, options)) {
rb_raise(rb_eArgError, "%s", err.msg);
}
agoo_server.inited = true;
return Qnil;
}
static const char bad500[] = "HTTP/1.1 500 Internal Error\r\nConnection: Close\r\nContent-Length: ";
static VALUE
rescue_error(VALUE x, VALUE ignore) {
agooReq req = (agooReq)x;
volatile VALUE info = rb_errinfo();
volatile VALUE msg = rb_funcall(info, rb_intern("message"), 0);
const char *classname = rb_obj_classname(info);
const char *ms = rb_string_value_ptr(&msg);
if (NULL == req->up) {
char buf[1024];
int len = (int)(strlen(classname) + 2 + strlen(ms));
int cnt;
agooText message;
if ((int)(sizeof(buf) - sizeof(bad500) + 7) <= len) {
len = sizeof(buf) - sizeof(bad500) + 7;
}
cnt = snprintf(buf, sizeof(buf), "%s%d\r\n\r\n%s: %s", bad500, len, classname, ms);
message = agoo_text_create(buf, cnt);
req->res->close = true;
agoo_res_message_push(req->res, message);
agoo_queue_wakeup(&agoo_server.con_queue);
} else {
/*
volatile VALUE bt = rb_funcall(info, rb_intern("backtrace"), 0);
int blen = RARRAY_LEN(bt);
int i;
VALUE rline;
for (i = 0; i < blen; i++) {
rline = rb_ary_entry(bt, i);
}
*/
agoo_log_cat(&agoo_error_cat, "%s: %s", classname, ms);
}
return Qfalse;
}
static VALUE
handle_base_inner(VALUE x) {
agooReq req = (agooReq)(void*)x;
volatile VALUE rr = request_wrap(req);
volatile VALUE rres = response_new();
if (NULL != req->hook) {
rb_funcall((VALUE)req->hook->handler, on_request_id, 2, rr, rres);
}
DATA_PTR(rr) = NULL;
agoo_res_message_push(req->res, response_text(rres));
agoo_queue_wakeup(&agoo_server.con_queue);
return Qfalse;
}
static void*
handle_base(void *x) {
rb_rescue2(handle_base_inner, (VALUE)x, rescue_error, (VALUE)x, rb_eException, (VALUE)0);
return NULL;
}
static int
header_cb(VALUE key, VALUE value, VALUE tv) {
agooText *tp = (agooText*)tv;
const char *ks = StringValuePtr(key);
int klen = (int)RSTRING_LEN(key);
const char *vs = StringValuePtr(value);
int vlen = (int)RSTRING_LEN(value);
struct _agooErr err = AGOO_ERR_INIT;
if (agoo_server.pedantic) {
if (AGOO_ERR_OK != agoo_http_header_ok(&err, ks, klen, vs, vlen)) {
rb_raise(rb_eArgError, "%s", err.msg);
}
}
if (0 != strcasecmp("Content-Length", ks)) {
char *end = index(vs, '\n');
do {
end = index(vs, '\n');
*tp = agoo_text_append(*tp, ks, klen);
*tp = agoo_text_append(*tp, ": ", 2);
if (NULL == end) {
if (0 < vlen) {
*tp = agoo_text_append(*tp, vs, vlen);
}
} else {
if (vs < end) {
*tp = agoo_text_append(*tp, vs, (int)(end - vs));
}
vlen -= end - vs + 1;
vs = end + 1;
}
*tp = agoo_text_append(*tp, "\r\n", 2);
} while (NULL != end && 0 < vlen);
}
return ST_CONTINUE;
}
static VALUE
header_each_cb(VALUE kv, VALUE cb_arg, int argc, const VALUE *argv, VALUE blockarg) {
agooText *tp = (agooText*)cb_arg;
header_cb(rb_ary_entry(kv, 0), rb_ary_entry(kv, 1), (VALUE)tp);
return Qnil;
}
static VALUE
body_len_cb(VALUE v, VALUE cb_arg, int argc, const VALUE *argv, VALUE blockarg) {
int *sizep = (int*)cb_arg;
*sizep += (int)RSTRING_LEN(v);
return Qnil;
}
static VALUE
body_append_cb(VALUE v, VALUE cb_arg, int argc, const VALUE *argv, VALUE blockarg) {
agooText *tp = (agooText*)cb_arg;
*tp = agoo_text_append(*tp, StringValuePtr(v), (int)RSTRING_LEN(v));
return Qnil;
}
static VALUE
handle_rack_inner(VALUE x) {
agooReq req = (agooReq)x;
agooText t;
volatile VALUE env = request_env(req, request_wrap(req));
volatile VALUE res = Qnil;
volatile VALUE hv;
volatile VALUE bv;
int code;
const char *status_msg;
int bsize = 0;
if (NULL == req->hook) {
return Qfalse;
}
res = rb_funcall((VALUE)req->hook->handler, call_id, 1, env);
if (req->res->con->hijacked) {
agoo_queue_wakeup(&agoo_server.con_queue);
return Qfalse;
}
rb_check_type(res, T_ARRAY);
if (3 != RARRAY_LEN(res)) {
rb_raise(rb_eArgError, "a rack call() response must be an array of 3 members.");
}
hv = rb_ary_entry(res, 0);
if (RUBY_T_FIXNUM == rb_type(hv)) {
code = NUM2INT(hv);
} else {
code = NUM2INT(rb_funcall(hv, to_i_id, 0));
}
status_msg = agoo_http_code_message(code);
if ('\0' == *status_msg) {
rb_raise(rb_eArgError, "invalid rack call() response status code (%d).", code);
}
hv = rb_ary_entry(res, 1);
if (!rb_respond_to(hv, each_id)) {
rb_raise(rb_eArgError, "invalid rack call() response headers does not respond to each.");
}
bv = rb_ary_entry(res, 2);
if (!rb_respond_to(bv, each_id)) {
rb_raise(rb_eArgError, "invalid rack call() response body does not respond to each.");
}
if (NULL == (t = agoo_text_allocate(1024))) {
rb_raise(rb_eNoMemError, "Failed to allocate memory for a response.");
}
if (T_ARRAY == rb_type(bv)) {
int i;
int bcnt = (int)RARRAY_LEN(bv);
for (i = 0; i < bcnt; i++) {
bsize += (int)RSTRING_LEN(rb_ary_entry(bv, i));
}
} else {
if (AGOO_HEAD == req->method) {
// Rack wraps the response in two layers, Rack::Lint and
// Rack::BodyProxy. It each is called on either with the HEAD
// method an exception is raised so the length can not be
// determined. This digs down to get the actual response so the
// length can be calculated. A very special case.
if (0 == strcmp("Rack::BodyProxy", rb_obj_classname(bv))) {
volatile VALUE body = rb_ivar_get(bv, rb_intern("@body"));
if (Qnil != body) {
body = rb_ivar_get(body, rb_intern("@body"));
}
if (Qnil != body) {
body = rb_ivar_get(body, rb_intern("@body"));
}
if (rb_respond_to(body, each_id)) {
rb_block_call(body, each_id, 0, 0, body_len_cb, (VALUE)&bsize);
}
} else {
rb_block_call(bv, each_id, 0, 0, body_len_cb, (VALUE)&bsize);
}
} else {
rb_block_call(bv, each_id, 0, 0, body_len_cb, (VALUE)&bsize);
}
}
switch (code) {
case 100:
case 101:
case 102:
case 204:
case 205:
case 304:
// Content-Type and Content-Length can not be present
t->len = snprintf(t->text, 1024, "HTTP/1.1 %d %s\r\n", code, status_msg);
break;
default:
// Note that using simply sprintf causes an abort with travis OSX tests.
t->len = snprintf(t->text, 1024, "HTTP/1.1 %d %s\r\nContent-Length: %d\r\n", code, status_msg, bsize);
break;
}
if (code < 300) {
VALUE handler = Qnil;
switch (req->upgrade) {
case AGOO_UP_WS:
if (AGOO_CON_WS != req->res->con_kind ||
Qnil == (handler = rb_hash_lookup(env, push_env_key))) {
strcpy(t->text, err500);
t->len = sizeof(err500) - 1;
break;
}
req->hook = agoo_hook_create(AGOO_NONE, NULL, (void*)handler, PUSH_HOOK, &agoo_server.eval_queue);
rupgraded_create(req->res->con, handler, request_env(req, Qnil));
t->len = snprintf(t->text, 1024, "HTTP/1.1 101 %s\r\n", status_msg);
t = agoo_ws_add_headers(req, t);
break;
case AGOO_UP_SSE:
if (AGOO_CON_SSE != req->res->con_kind ||
Qnil == (handler = rb_hash_lookup(env, push_env_key))) {
strcpy(t->text, err500);
t->len = sizeof(err500) - 1;
break;
}
req->hook = agoo_hook_create(AGOO_NONE, NULL, (void*)handler, PUSH_HOOK, &agoo_server.eval_queue);
rupgraded_create(req->res->con, handler, request_env(req, Qnil));
t = agoo_sse_upgrade(req, t);
agoo_res_message_push(req->res, t);
agoo_queue_wakeup(&agoo_server.con_queue);
return Qfalse;
default:
break;
}
}
if (AGOO_HEAD == req->method) {
bsize = 0;
} else {
if (T_HASH == rb_type(hv)) {
rb_hash_foreach(hv, header_cb, (VALUE)&t);
} else {
rb_block_call(hv, each_id, 0, 0, header_each_cb, (VALUE)&t);
}
}
t = agoo_text_append(t, "\r\n", 2);
if (0 < bsize) {
if (T_ARRAY == rb_type(bv)) {
VALUE v;
int i;
int bcnt = (int)RARRAY_LEN(bv);
for (i = 0; i < bcnt; i++) {
v = rb_ary_entry(bv, i);
t = agoo_text_append(t, StringValuePtr(v), (int)RSTRING_LEN(v));
}
} else {
rb_block_call(bv, each_id, 0, 0, body_append_cb, (VALUE)&t);
}
}
agoo_res_message_push(req->res, t);
agoo_queue_wakeup(&agoo_server.con_queue);
return Qfalse;
}
static void*
handle_rack(void *x) {
//rb_gc_disable();
rb_rescue2(handle_rack_inner, (VALUE)x, rescue_error, (VALUE)x, rb_eException, (VALUE)0);
//rb_gc_enable();
//rb_gc();
return NULL;
}
static VALUE
handle_wab_inner(VALUE x) {
agooReq req = (agooReq)x;
volatile VALUE rr = request_wrap(req);
volatile VALUE rres = response_new();
if (NULL != req->hook) {
rb_funcall((VALUE)req->hook->handler, on_request_id, 2, rr, rres);
}
DATA_PTR(rr) = NULL;
agoo_res_message_push(req->res, response_text(rres));
agoo_queue_wakeup(&agoo_server.con_queue);
return Qfalse;
}
static void*
handle_wab(void *x) {
rb_rescue2(handle_wab_inner, (VALUE)x, rescue_error, (VALUE)x, rb_eException, (VALUE)0);
return NULL;
}
static VALUE
handle_push_inner(VALUE x) {
agooReq req = (agooReq)x;
switch (req->method) {
case AGOO_ON_MSG:
if (req->up->on_msg && NULL != req->hook) {
rb_funcall((VALUE)req->hook->handler, on_message_id, 2, (VALUE)req->up->wrap, rb_str_new(req->msg, req->mlen));
}
break;
case AGOO_ON_BIN:
if (req->up->on_msg && NULL != req->hook) {
volatile VALUE rstr = rb_str_new(req->msg, req->mlen);
rb_enc_associate(rstr, rb_ascii8bit_encoding());
rb_funcall((VALUE)req->hook->handler, on_message_id, 2, (VALUE)req->up->wrap, rstr);
}
break;
case AGOO_ON_CLOSE:
agoo_upgraded_ref(req->up);
agoo_server_publish(agoo_pub_close(req->up));
if (req->up->on_close && NULL != req->hook) {
rb_funcall((VALUE)req->hook->handler, on_close_id, 1, (VALUE)req->up->wrap);
}
break;
case AGOO_ON_SHUTDOWN:
if (NULL != req->hook) {
rb_funcall((VALUE)req->hook->handler, rb_intern("on_shutdown"), 1, (VALUE)req->up->wrap);
}
break;
case AGOO_ON_ERROR:
if (req->up->on_error && NULL != req->hook) {
volatile VALUE rstr = rb_str_new(req->msg, req->mlen);
rb_enc_associate(rstr, rb_ascii8bit_encoding());
rb_funcall((VALUE)req->hook->handler, on_error_id, 2, (VALUE)req->up->wrap, rstr);
}
break;
case AGOO_ON_EMPTY:
if (req->up->on_empty && NULL != req->hook) {
rb_funcall((VALUE)req->hook->handler, on_drained_id, 1, (VALUE)req->up->wrap);
}
break;
default:
break;
}
agoo_upgraded_release(req->up);
return Qfalse;
}
static void*
handle_push(void *x) {
rb_rescue2(handle_push_inner, (VALUE)x, rescue_error, (VALUE)x, rb_eException, (VALUE)0);
return NULL;
}
static void
handle_protected(agooReq req, bool gvi) {
if (NULL == req->hook) {
return;
}
switch (req->hook->type) {
case BASE_HOOK:
if (gvi) {
rb_thread_call_with_gvl(handle_base, req);
} else {
handle_base(req);
}
break;
case RACK_HOOK:
if (gvi) {
rb_thread_call_with_gvl(handle_rack, req);
} else {
handle_rack(req);
}
break;
case WAB_HOOK:
if (gvi) {
rb_thread_call_with_gvl(handle_wab, req);
} else {
handle_wab(req);
}
break;
case PUSH_HOOK:
if (gvi) {
rb_thread_call_with_gvl(handle_push, req);
} else {
handle_push(req);
}
break;
case FUNC_HOOK:
req->hook->func(req);
agoo_queue_wakeup(&agoo_server.con_queue);
break;
default: {
char buf[256];
int cnt = snprintf(buf, sizeof(buf), "HTTP/1.1 500 Internal Error\r\nConnection: Close\r\nContent-Length: 0\r\n\r\n");
agooText message = agoo_text_create(buf, cnt);
req->res->close = true;
agoo_res_message_push(req->res, message);
agoo_queue_wakeup(&agoo_server.con_queue);
break;
}
}
}
static void*
process_loop(void *ptr) {
agooReq req;
atomic_fetch_add(&agoo_server.running, 1);
while (agoo_server.active) {
if (NULL != (req = (agooReq)agoo_queue_pop(&agoo_server.eval_queue, poll_timeout))) {
handle_protected(req, true);
agoo_req_destroy(req);
}
if (agoo_stop) {
agoo_shutdown();
break;
}
agoo_queue_wakeup(&agoo_server.con_queue); // TBD remove if it doesn't speed up the response time
}
atomic_fetch_sub(&agoo_server.running, 1);
return NULL;
}
static VALUE
wrap_process_loop(void *ptr) {
rb_thread_call_without_gvl(process_loop, NULL, RUBY_UBF_IO, NULL);
return Qnil;
}
/* Document-method: start
*
* call-seq: start()
*
* Start the server.
*/
static VALUE
rserver_start(VALUE self) {
VALUE *vp;
int i;
int pid;
double giveup;
struct _agooErr err = AGOO_ERR_INIT;
VALUE agoo = rb_const_get_at(rb_cObject, rb_intern("Agoo"));
VALUE v = rb_const_get_at(agoo, rb_intern("VERSION"));
*the_rserver.worker_pids = getpid();
// If workers then set the loop_max based on the expected number of
// threads per worker.
if (1 < the_rserver.worker_cnt) {
agoo_server.loop_max /= the_rserver.worker_cnt;
if (agoo_server.loop_max < 1) {
agoo_server.loop_max = 1;
}
}
if (AGOO_ERR_OK != setup_listen(&err)) {
rb_raise(rb_eIOError, "%s", err.msg);
}
for (i = 1; i < the_rserver.worker_cnt; i++) {
VALUE rpid = rb_funcall(rb_cObject, rb_intern("fork"), 0);
if (Qnil == rpid) {
pid = 0;
} else {
pid = NUM2INT(rpid);
}
if (0 > pid) { // error, use single process
agoo_log_cat(&agoo_error_cat, "Failed to fork. %s.", strerror(errno));
break;
} else if (0 == pid) {
if (AGOO_ERR_OK != agoo_log_start(&err, true)) {
rb_raise(rb_eStandardError, "%s", err.msg);
}
break;
} else {
the_rserver.worker_pids[i] = pid;
}
}
if (AGOO_ERR_OK != agoo_server_start(&err, "Agoo", StringValuePtr(v))) {
rb_raise(rb_eStandardError, "%s", err.msg);
}
if (0 >= agoo_server.thread_cnt) {
agooReq req;
while (agoo_server.active) {
if (NULL != (req = (agooReq)agoo_queue_pop(&agoo_server.eval_queue, poll_timeout))) {
handle_protected(req, false);
agoo_req_destroy(req);
} else {
rb_thread_schedule();
}
if (agoo_stop) {
agoo_shutdown();
break;
}
}
} else {
if (NULL == (the_rserver.eval_threads = (VALUE*)AGOO_MALLOC(sizeof(VALUE) * (agoo_server.thread_cnt + 1)))) {
rb_raise(rb_eNoMemError, "Failed to allocate memory for the thread pool.");
}
for (i = agoo_server.thread_cnt, vp = the_rserver.eval_threads; 0 < i; i--, vp++) {
*vp = rb_thread_create(wrap_process_loop, NULL);
}
*vp = Qnil;
giveup = dtime() + 1.0;
while (dtime() < giveup) {
// The processing threads will not start until this thread
// releases ownership so do that and then see if the threads has
// been started yet.
rb_thread_schedule();
if (2 + agoo_server.thread_cnt <= (long)atomic_load(&agoo_server.running)) {
break;
}
}
}
return Qnil;
}
static void
stop_runners() {
// The preferred method of waiting for the ruby threads would be either a
// join or even a kill but since we may not have the gvl here that would
// cause a segfault. Instead we set a timeout and wait for the running
// counter to drop to zero.
if (NULL != the_rserver.eval_threads) {
double timeout = dtime() + 2.0;
while (dtime() < timeout) {
if (0 >= (long)atomic_load(&agoo_server.running)) {
break;
}
dsleep(0.02);
}
AGOO_FREE(the_rserver.eval_threads);
the_rserver.eval_threads = NULL;
}
}
/* Document-method: shutdown
*
* call-seq: shutdown()
*
* Shutdown the server. Logs and queues are flushed before shutting down.
*/
VALUE
rserver_shutdown(VALUE self) {
if (agoo_server.inited) {
agoo_server_shutdown("Agoo", stop_runners);
if (1 < the_rserver.worker_cnt && getpid() == *the_rserver.worker_pids) {
int i;
int status;
int exit_cnt = 1;
int j;
for (i = 1; i < the_rserver.worker_cnt; i++) {
kill(the_rserver.worker_pids[i], SIGKILL);
}
for (j = 0; j < 20; j++) {
for (i = 1; i < the_rserver.worker_cnt; i++) {
if (0 == the_rserver.worker_pids[i]) {
continue;
}
if (0 < waitpid(the_rserver.worker_pids[i], &status, WNOHANG)) {
if (WIFEXITED(status)) {
//printf("exited, status=%d for %d\n", agoo_server.worker_pids[i], WEXITSTATUS(status));
the_rserver.worker_pids[i] = 0;
exit_cnt++;
} else if (WIFSIGNALED(status)) {
//printf("*** killed by signal %d for %d\n", agoo_server.worker_pids[i], WTERMSIG(status));
the_rserver.worker_pids[i] = 0;
exit_cnt++;
}
}
}
if (the_rserver.worker_cnt <= exit_cnt) {
break;
}
dsleep(0.2);
}
if (exit_cnt < the_rserver.worker_cnt) {
printf("*-*-* Some workers did not exit.\n");
}
}
}
return Qnil;
}
/* Document-method: handle
*
* call-seq: handle(method, pattern, handler)
*
* Registers a handler for the HTTP method and path pattern specified. The
* path pattern follows glob like rules in that a single * matches a single
* token bounded by the `/` character and a double ** matches all remaining.
*/
static VALUE
handle(VALUE self, VALUE method, VALUE pattern, VALUE handler) {
agooHook hook;
agooMethod meth = AGOO_ALL;
const char *pat;
ID static_id = rb_intern("static?");
rb_check_type(pattern, T_STRING);
pat = StringValuePtr(pattern);
if (connect_sym == method) {
meth = AGOO_CONNECT;
} else if (delete_sym == method) {
meth = AGOO_DELETE;
} else if (get_sym == method) {
meth = AGOO_GET;
} else if (head_sym == method) {
meth = AGOO_HEAD;
} else if (options_sym == method) {
meth = AGOO_OPTIONS;
} else if (post_sym == method) {
meth = AGOO_POST;
} else if (put_sym == method) {
meth = AGOO_PUT;
} else if (patch_sym == method) {
meth = AGOO_PATCH;
} else if (Qnil == method) {
meth = AGOO_ALL;
} else {
rb_raise(rb_eArgError, "invalid method");
}
if (T_STRING == rb_type(handler)) {
handler = resolve_classpath(StringValuePtr(handler), RSTRING_LEN(handler));
}
if (rb_respond_to(handler, static_id)) {
if (Qtrue == rb_funcall(handler, static_id, 0)) {
VALUE res = rb_funcall(handler, call_id, 1, Qnil);
VALUE bv;
rb_check_type(res, T_ARRAY);