-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathngx_pq_module.c
1578 lines (1534 loc) · 89.2 KB
/
ngx_pq_module.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
#include <ngx_http.h>
#include "ngx_http_upstream.c"
#undef OPENSSL_API_COMPAT
#include <internal/c.h>
#include <internal/libpq-int.h>
#include <internal/pqexpbuffer.h>
#include <libpq-fe.h>
extern ngx_int_t ngx_http_push_stream_add_msg_to_channel_my(ngx_log_t *log, ngx_str_t *id, ngx_str_t *text, ngx_str_t *event_id, ngx_str_t *event_type, ngx_flag_t store_messages, ngx_pool_t *temp_pool) __attribute__((weak));
extern ngx_int_t ngx_http_push_stream_delete_channel_my(ngx_log_t *log, ngx_str_t *id, u_char *text, size_t len, ngx_pool_t *temp_pool) __attribute__((weak));
typedef struct {
char *message;
ngx_log_handler_pt handler;
void *data;
} ngx_pq_log_t;
#define ngx_pq_log_error(level, log, err, msg, fmt, ...) do { \
ngx_pq_log_t original = { \
.data = log->data, \
.handler = log->handler, \
.message = (char *)(msg), \
}; \
(log)->data = &original; \
(log)->handler = ngx_pq_log_error_handler; \
ngx_log_error(level, log, err, fmt, ##__VA_ARGS__); \
} while (0)
ngx_module_t ngx_pq_module;
enum {
ngx_pq_type_execute = 1 << 0,
ngx_pq_type_location = 1 << 1,
ngx_pq_type_output = 1 << 2,
ngx_pq_type_prepare = 1 << 3,
ngx_pq_type_query = 1 << 4,
ngx_pq_type_upstream = 1 << 5,
};
enum {
ngx_pq_output_csv = 2,
ngx_pq_output_none = 0,
ngx_pq_output_plain = 3,
ngx_pq_output_value = 1,
};
typedef struct {
struct {
ngx_http_complex_value_t complex;
Oid value;
} oid;
struct {
ngx_http_complex_value_t complex;
ngx_str_t str;
} value;
} ngx_pq_argument_t;
typedef struct {
ngx_int_t index;
ngx_str_t str;
} ngx_pq_command_t;
typedef struct {
ngx_array_t options;
ngx_msec_t timeout;
PGContextVisibility show_context;
PGVerbosity errors;
} ngx_pq_connect_t;
typedef struct {
ngx_array_t queries;
ngx_http_complex_value_t complex;
ngx_http_upstream_conf_t upstream;
ngx_pq_connect_t connect;
} ngx_pq_loc_conf_t;
typedef struct {
ngx_array_t arguments;
ngx_array_t commands;
ngx_flag_t header;
ngx_flag_t string;
ngx_int_t index;
ngx_str_t null;
ngx_uint_t output;
ngx_uint_t type;
u_char delimiter;
u_char escape;
u_char quote;
struct {
ngx_http_complex_value_t complex;
ngx_str_t str;
} name;
} ngx_pq_query_t;
typedef struct {
ngx_str_t message;
ngx_uint_t level;
} ngx_pq_level_t;
typedef struct {
ngx_array_t levels;
ngx_array_t queries;
ngx_http_upstream_peer_t peer;
ngx_log_t *log;
ngx_pq_connect_t connect;
size_t buffer_size;
} ngx_pq_srv_conf_t;
typedef struct {
const char **paramValues;
ngx_pq_query_t *query;
ngx_queue_t queue;
Oid *paramTypes;
} ngx_pq_query_queue_t;
typedef struct {
ngx_queue_t queue;
ngx_str_t channel;
} ngx_pq_channel_queue_t;
typedef struct {
ngx_str_t column_name;
ngx_str_t constraint_name;
ngx_str_t context;
ngx_str_t datatype_name;
ngx_str_t internal_position;
ngx_str_t internal_query;
ngx_str_t message_detail;
ngx_str_t message_hint;
ngx_str_t message_primary;
ngx_str_t schema_name;
ngx_str_t severity;
ngx_str_t severity_nonlocalized;
ngx_str_t source_file;
ngx_str_t source_function;
ngx_str_t source_line;
ngx_str_t sqlstate;
ngx_str_t statement_position;
ngx_str_t table_name;
} ngx_pq_error_t;
typedef struct {
int inBufSize;
ngx_array_t variables;
ngx_connection_t *connection;
ngx_event_handler_pt read;
ngx_event_handler_pt write;
ngx_msec_t timeout;
ngx_queue_t queue;
ngx_uint_t count;
PGconn *conn;
} ngx_pq_save_t;
typedef struct {
ngx_array_t variables;
ngx_http_request_t *request;
ngx_int_t row;
ngx_peer_connection_t peer;
ngx_pq_error_t error;
ngx_pq_save_t *save;
ngx_queue_t queue;
ngx_uint_t type;
} ngx_pq_data_t;
typedef struct {
ngx_chain_t *cl;
ngx_int_t index;
} ngx_pq_variable_t;
static u_char *ngx_pq_log_error_handler(ngx_log_t *log, u_char *buf, size_t len) {
u_char *p = buf;
ngx_pq_log_t *original = log->data;
log->data = original->data;
log->handler = original->handler;
if (log->handler) p = log->handler(log, buf, len);
len -= p - buf;
buf = p;
if (original->message) {
int msg_len = strlen(original->message);
if (msg_len) {
if (original->message[msg_len - 1] == '\n') original->message[msg_len - 1] = '\0';
p = ngx_snprintf(buf, len, "\n%s", original->message);
buf = p;
}
}
return buf;
}
static ngx_int_t ngx_pq_output(ngx_pq_save_t *s, ngx_pq_data_t *d, ngx_pq_query_t *query, const u_char *data, size_t len) {
ngx_log_debug2(NGX_LOG_DEBUG_HTTP, s->connection->log, 0, "%*s", (int)len, data);
if (!len) return NGX_OK;
if (!d) return NGX_OK;
ngx_http_request_t *r = d->request;
if (query->index) {
ngx_array_t *variables;
ngx_connection_t *c;
if (query->type & ngx_pq_type_upstream) {
c = s->connection;
variables = &s->variables;
} else if (query->type & ngx_pq_type_location) {
c = r->connection;
variables = &d->variables;
} else return NGX_OK;
ngx_pq_variable_t *variable = variables->elts;
ngx_uint_t i;
for (i = 0; i < variables->nelts; i++) if (variable[i].index == query->index) break;
ngx_chain_t *cl;
if (i == variables->nelts) {
if (!variables->elts && ngx_array_init(&s->variables, c->pool, 1, sizeof(*variable)) != NGX_OK) { ngx_log_error(NGX_LOG_ERR, s->connection->log, 0, "ngx_array_init != NGX_OK"); return NGX_ERROR; }
if (!(variable = ngx_array_push(&s->variables))) { ngx_log_error(NGX_LOG_ERR, s->connection->log, 0, "!ngx_array_push"); return NGX_ERROR; }
ngx_memzero(variable, sizeof(*variable));
variable->index = query->index;
if (!(cl = variable->cl = ngx_alloc_chain_link(c->pool))) { ngx_log_error(NGX_LOG_ERR, s->connection->log, 0, "!ngx_alloc_chain_link"); return NGX_ERROR; }
} else {
variable = &variable[i];
cl = variable->cl;
if (!(cl = cl->next = ngx_alloc_chain_link(c->pool))) { ngx_log_error(NGX_LOG_ERR, s->connection->log, 0, "!ngx_alloc_chain_link"); return NGX_ERROR; }
}
cl->next = NULL;
if (!(cl->buf = ngx_create_temp_buf(c->pool, len))) { ngx_log_error(NGX_LOG_ERR, s->connection->log, 0, "!ngx_create_temp_buf"); return NGX_ERROR; }
cl->buf->last = ngx_copy(cl->buf->last, data, len);
} else if (query->output) {
ngx_http_upstream_t *u = r->upstream;
ngx_chain_t *cl, **ll;
for (cl = u->out_bufs, ll = &u->out_bufs; cl; cl = cl->next) ll = &cl->next;
if (!(cl = ngx_chain_get_free_buf(r->pool, &u->free_bufs))) { ngx_log_error(NGX_LOG_ERR, s->connection->log, 0, "!ngx_chain_get_free_buf"); return NGX_ERROR; }
*ll = cl;
ngx_buf_t *b = cl->buf;
if (b->start) ngx_pfree(r->pool, b->start);
if (!(b->start = ngx_palloc(r->pool, len))) { ngx_log_error(NGX_LOG_ERR, s->connection->log, 0, "!ngx_palloc"); return NGX_ERROR; }
b->end = b->start + len;
b->flush = 1;
b->last = ngx_copy(b->start, data, len);
b->memory = 1;
b->pos = b->start;
b->tag = u->output.tag;
b->temporary = 1;
}
return NGX_OK;
}
static ngx_int_t ngx_pq_copy_error(ngx_pq_data_t *d, PGresult *res, int fieldcode, ngx_uint_t offset) {
ngx_http_request_t *r = d->request;
char *err;
if (!(err = PQresultErrorField(res, fieldcode))) return NGX_OK;
ngx_str_t str = {ngx_strlen(err), (u_char *)err};
ngx_str_t *error = (ngx_str_t *)((u_char *)&d->error + offset);
if (!(error->data = ngx_pstrdup(r->pool, &str))) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "!ngx_pstrdup"); return NGX_ERROR; }
error->len = str.len;
return NGX_OK;
}
static ngx_int_t ngx_pq_res_command_ok(ngx_pq_save_t *s, ngx_pq_data_t *d, PGresult *res) {
char *value;
size_t len = 0;
if ((value = PQcmdStatus(res)) && (len = ngx_strlen(value))) { ngx_log_debug2(NGX_LOG_DEBUG_HTTP, s->connection->log, 0, "%s and %s", PQresStatus(PQresultStatus(res)), value); }
else { ngx_log_debug1(NGX_LOG_DEBUG_HTTP, s->connection->log, 0, "%s", PQresStatus(PQresultStatus(res))); }
if (s->count) { s->count--; return NGX_OK; }
if (!d) return NGX_OK;
if (ngx_queue_empty(&d->queue)) { ngx_log_error(NGX_LOG_ERR, s->connection->log, 0, "ngx_queue_empty"); return NGX_ERROR; }
ngx_queue_t *q = ngx_queue_head(&d->queue);
ngx_queue_remove(q);
ngx_pq_query_queue_t *qq = ngx_queue_data(q, ngx_pq_query_queue_t, queue);
ngx_pq_query_t *query = qq->query;
d->type = query->type;
if (ngx_http_push_stream_delete_channel_my && query->commands.nelts == 2 && len == sizeof("LISTEN") - 1 && !ngx_strncasecmp((u_char *)value, (u_char *)"LISTEN", sizeof("LISTEN") - 1)) {
ngx_pq_command_t *command = query->commands.elts;
command = &command[1];
ngx_log_debug1(NGX_LOG_DEBUG_HTTP, s->connection->log, 0, "%V", &command->str);
ngx_pq_channel_queue_t *cq;
ngx_connection_t *c = s->connection;
if (!(cq = ngx_pcalloc(c->pool, sizeof(*cq)))) { ngx_log_error(NGX_LOG_ERR, s->connection->log, 0, "!ngx_pcalloc"); return NGX_ERROR; }
ngx_queue_insert_tail(&s->queue, &cq->queue);
if (!(cq->channel.data = ngx_pstrdup(c->pool, &command->str))) { ngx_log_error(NGX_LOG_ERR, s->connection->log, 0, "!ngx_pstrdup"); return NGX_ERROR; }
cq->channel.len = command->str.len;
}
return NGX_OK;
}
static ngx_int_t ngx_pq_res_copy_out(ngx_pq_save_t *s, ngx_pq_data_t *d) {
ngx_log_debug0(NGX_LOG_DEBUG_HTTP, s->connection->log, 0, "PGRES_COPY_OUT");
char *buffer = NULL;
int len;
ngx_int_t rc = NGX_OK;
switch ((len = PQgetCopyData(s->conn, &buffer, 0))) {
case 0: break;
case -1: break;
case -2: ngx_pq_log_error(NGX_LOG_ERR, s->connection->log, 0, PQerrorMessage(s->conn), "PQgetCopyData == -2"); rc = NGX_HTTP_BAD_GATEWAY; break;
default:
if (!d) break;
if (ngx_queue_empty(&d->queue)) break;
ngx_queue_t *q = ngx_queue_head(&d->queue);
ngx_pq_query_queue_t *qq = ngx_queue_data(q, ngx_pq_query_queue_t, queue);
ngx_pq_query_t *query = qq->query;
d->type = query->type;
d->row++;
if (ngx_pq_output(s, d, query, (const u_char *)buffer, len) != NGX_OK) rc = NGX_ERROR;
break;
}
if (buffer) PQfreemem(buffer);
return rc;
}
static ngx_int_t ngx_pq_res_default(ngx_pq_save_t *s, ngx_pq_data_t *d, PGresult *res) {
char *value;
if ((value = PQcmdStatus(res)) && ngx_strlen(value)) { ngx_log_error(NGX_LOG_ERR, s->connection->log, 0, "%s and %s", PQresStatus(PQresultStatus(res)), value); }
else { ngx_log_error(NGX_LOG_ERR, s->connection->log, 0, "%s", PQresStatus(PQresultStatus(res))); }
if (s->count) { s->count--; return NGX_OK; }
if (!d) return NGX_OK;
if (ngx_queue_empty(&d->queue)) { ngx_log_error(NGX_LOG_ERR, s->connection->log, 0, "ngx_queue_empty"); return NGX_ERROR; }
ngx_queue_t *q = ngx_queue_head(&d->queue);
ngx_queue_remove(q);
ngx_pq_query_queue_t *qq = ngx_queue_data(q, ngx_pq_query_queue_t, queue);
ngx_pq_query_t *query = qq->query;
d->type = query->type;
return NGX_HTTP_BAD_GATEWAY;
}
static ngx_int_t ngx_pq_res_fatal_error(ngx_pq_save_t *s, ngx_pq_data_t *d, PGresult *res) {
char *value;
if ((value = PQcmdStatus(res)) && ngx_strlen(value)) { ngx_pq_log_error(NGX_LOG_ERR, s->connection->log, 0, PQresultErrorMessage(res), "%s and %s", PQresStatus(PQresultStatus(res)), value); }
else { ngx_pq_log_error(NGX_LOG_ERR, s->connection->log, 0, PQresultErrorMessage(res), "%s", PQresStatus(PQresultStatus(res))); }
if (s->count) { s->count--; return NGX_OK; }
if (!d) return NGX_OK;
if (ngx_queue_empty(&d->queue)) { ngx_log_error(NGX_LOG_ERR, s->connection->log, 0, "ngx_queue_empty"); return NGX_ERROR; }
ngx_queue_t *q = ngx_queue_head(&d->queue);
ngx_queue_remove(q);
ngx_pq_query_queue_t *qq = ngx_queue_data(q, ngx_pq_query_queue_t, queue);
ngx_pq_query_t *query = qq->query;
d->type = query->type;
if (ngx_pq_copy_error(d, res, PG_DIAG_SEVERITY, offsetof(ngx_pq_error_t, severity)) != NGX_OK) return NGX_ERROR;
if (ngx_pq_copy_error(d, res, PG_DIAG_SEVERITY_NONLOCALIZED, offsetof(ngx_pq_error_t, severity_nonlocalized)) != NGX_OK) return NGX_ERROR;
if (ngx_pq_copy_error(d, res, PG_DIAG_SQLSTATE, offsetof(ngx_pq_error_t, sqlstate)) != NGX_OK) return NGX_ERROR;
if (ngx_pq_copy_error(d, res, PG_DIAG_MESSAGE_PRIMARY, offsetof(ngx_pq_error_t, message_primary)) != NGX_OK) return NGX_ERROR;
if (ngx_pq_copy_error(d, res, PG_DIAG_MESSAGE_DETAIL, offsetof(ngx_pq_error_t, message_detail)) != NGX_OK) return NGX_ERROR;
if (ngx_pq_copy_error(d, res, PG_DIAG_MESSAGE_HINT, offsetof(ngx_pq_error_t, message_hint)) != NGX_OK) return NGX_ERROR;
if (ngx_pq_copy_error(d, res, PG_DIAG_STATEMENT_POSITION, offsetof(ngx_pq_error_t, statement_position)) != NGX_OK) return NGX_ERROR;
if (ngx_pq_copy_error(d, res, PG_DIAG_INTERNAL_POSITION, offsetof(ngx_pq_error_t, internal_position)) != NGX_OK) return NGX_ERROR;
if (ngx_pq_copy_error(d, res, PG_DIAG_INTERNAL_QUERY, offsetof(ngx_pq_error_t, internal_query)) != NGX_OK) return NGX_ERROR;
if (ngx_pq_copy_error(d, res, PG_DIAG_CONTEXT, offsetof(ngx_pq_error_t, context)) != NGX_OK) return NGX_ERROR;
if (ngx_pq_copy_error(d, res, PG_DIAG_SCHEMA_NAME, offsetof(ngx_pq_error_t, schema_name)) != NGX_OK) return NGX_ERROR;
if (ngx_pq_copy_error(d, res, PG_DIAG_TABLE_NAME, offsetof(ngx_pq_error_t, table_name)) != NGX_OK) return NGX_ERROR;
if (ngx_pq_copy_error(d, res, PG_DIAG_COLUMN_NAME, offsetof(ngx_pq_error_t, column_name)) != NGX_OK) return NGX_ERROR;
if (ngx_pq_copy_error(d, res, PG_DIAG_DATATYPE_NAME, offsetof(ngx_pq_error_t, datatype_name)) != NGX_OK) return NGX_ERROR;
if (ngx_pq_copy_error(d, res, PG_DIAG_CONSTRAINT_NAME, offsetof(ngx_pq_error_t, constraint_name)) != NGX_OK) return NGX_ERROR;
if (ngx_pq_copy_error(d, res, PG_DIAG_SOURCE_FILE, offsetof(ngx_pq_error_t, source_file)) != NGX_OK) return NGX_ERROR;
if (ngx_pq_copy_error(d, res, PG_DIAG_SOURCE_LINE, offsetof(ngx_pq_error_t, source_line)) != NGX_OK) return NGX_ERROR;
if (ngx_pq_copy_error(d, res, PG_DIAG_SOURCE_FUNCTION, offsetof(ngx_pq_error_t, source_function)) != NGX_OK) return NGX_ERROR;
return NGX_HTTP_BAD_GATEWAY;
}
static ngx_int_t ngx_pq_res_tuples_ok(ngx_pq_save_t *s, ngx_pq_data_t *d, PGresult *res) {
char *value;
if ((value = PQcmdStatus(res)) && ngx_strlen(value)) { ngx_log_debug1(NGX_LOG_DEBUG_HTTP, s->connection->log, 0, "PGRES_TUPLES_OK and %s", value); }
else { ngx_log_debug0(NGX_LOG_DEBUG_HTTP, s->connection->log, 0, "PGRES_TUPLES_OK"); }
if (s->count) { s->count--; return NGX_OK; }
if (!d) return NGX_OK;
if (ngx_queue_empty(&d->queue)) { ngx_log_error(NGX_LOG_ERR, s->connection->log, 0, "ngx_queue_empty"); return NGX_ERROR; }
ngx_queue_t *q = ngx_queue_head(&d->queue);
ngx_queue_remove(q);
ngx_pq_query_queue_t *qq = ngx_queue_data(q, ngx_pq_query_queue_t, queue);
ngx_pq_query_t *query = qq->query;
d->type = query->type;
if (query->header) {
if (d->type & ngx_pq_type_location && d->row > 0) if (ngx_pq_output(s, d, query, (const u_char *)"\n", sizeof("\n") - 1) != NGX_OK) return NGX_ERROR;
for (int col = 0; col < PQnfields(res); col++) {
if (col > 0) if (ngx_pq_output(s, d, query, &query->delimiter, sizeof(query->delimiter)) != NGX_OK) return NGX_ERROR;
if (query->string && query->quote) if (ngx_pq_output(s, d, query, &query->quote, sizeof(query->quote)) != NGX_OK) return NGX_ERROR;
const u_char *data = (const u_char *)PQfname(res, col);
ngx_uint_t len = ngx_strlen(data);
if (query->string && query->quote && query->escape) for (ngx_uint_t k = 0; k < len; k++) {
if (data[k] == query->quote) if (ngx_pq_output(s, d, query, &query->escape, sizeof(query->escape)) != NGX_OK) return NGX_ERROR;
if (ngx_pq_output(s, d, query, &data[k], sizeof(data[k])) != NGX_OK) return NGX_ERROR;
} else {
if (ngx_pq_output(s, d, query, (const u_char *)data, len) != NGX_OK) return NGX_ERROR;
}
if (query->string && query->quote) if (ngx_pq_output(s, d, query, &query->quote, sizeof(query->quote)) != NGX_OK) return NGX_ERROR;
}
}
for (int row = 0; row < PQntuples(res); row++, d->row++) {
if (row > 0 || query->header) if (ngx_pq_output(s, d, query, (const u_char *)"\n", sizeof("\n") - 1) != NGX_OK) return NGX_ERROR;
for (int col = 0; col < PQnfields(res); col++) {
if (col > 0) if (ngx_pq_output(s, d, query, &query->delimiter, sizeof(query->delimiter)) != NGX_OK) return NGX_ERROR;
if (PQgetisnull(res, row, col)) {
if (query->null.len) if (ngx_pq_output(s, d, query, query->null.data, query->null.len) != NGX_OK) return NGX_ERROR;
} else {
if (query->string && query->quote) if (ngx_pq_output(s, d, query, &query->quote, sizeof(query->quote)) != NGX_OK) return NGX_ERROR;
const u_char *data = (const u_char *)PQgetvalue(res, row, col);
ngx_uint_t len = PQgetlength(res, row, col);
if (query->string && query->quote && query->escape) for (ngx_uint_t k = 0; k < len; k++) {
if (data[k] == query->quote) if (ngx_pq_output(s, d, query, &query->escape, sizeof(query->escape)) != NGX_OK) return NGX_ERROR;
if (ngx_pq_output(s, d, query, &data[k], sizeof(data[k])) != NGX_OK) return NGX_ERROR;
} else {
if (ngx_pq_output(s, d, query, (const u_char *)data, len) != NGX_OK) return NGX_ERROR;
}
if (query->string && query->quote) if (ngx_pq_output(s, d, query, &query->quote, sizeof(query->quote)) != NGX_OK) return NGX_ERROR;
}
}
}
return NGX_OK;
}
static ngx_int_t ngx_pq_notify(ngx_pq_save_t *s) {
ngx_log_debug1(NGX_LOG_DEBUG_HTTP, s->connection->log, 0, "%s", __func__);
ngx_int_t rc = NGX_OK;
ngx_pool_t *p;
for (PGnotify *notify; (notify = PQnotifies(s->conn)); PQfreemem(notify)) {
ngx_log_debug3(NGX_LOG_DEBUG_HTTP, s->connection->log, 0, "relname=%s, extra=%s, be_pid=%i", notify->relname, notify->extra, notify->be_pid);
if (!ngx_http_push_stream_add_msg_to_channel_my) continue;
ngx_str_t id = { ngx_strlen(notify->relname), (u_char *)notify->relname };
ngx_str_t text = { ngx_strlen(notify->extra), (u_char *)notify->extra };
if (!(p = ngx_create_pool(4096 + id.len + text.len, s->connection->log))) { ngx_log_error(NGX_LOG_ERR, s->connection->log, 0, "!ngx_create_pool"); rc = NGX_ERROR; continue; }
if (rc == NGX_OK) switch ((rc = ngx_http_push_stream_add_msg_to_channel_my(s->connection->log, &id, &text, NULL, NULL, 1, p))) {
case NGX_ERROR: ngx_log_error(NGX_LOG_ERR, s->connection->log, 0, "ngx_http_push_stream_add_msg_to_channel_my == NGX_ERROR"); break;
case NGX_DECLINED: ngx_log_error(NGX_LOG_WARN, s->connection->log, 0, "ngx_http_push_stream_add_msg_to_channel_my == NGX_DECLINED"); {
for (ngx_queue_t *q = ngx_queue_head(&s->queue), *_; q != ngx_queue_sentinel(&s->queue) && (_ = ngx_queue_next(q)); q = _) {
ngx_pq_channel_queue_t *cq = ngx_queue_data(q, ngx_pq_channel_queue_t, queue);
if (cq->channel.len != id.len || ngx_strncmp(cq->channel.data, id.data, id.len)) continue;
ngx_queue_remove(q);
break;
}
#ifdef LIBPQ_HAS_PIPELINING
if (PQpipelineStatus(s->conn) == PQ_PIPELINE_OFF) if (!PQenterPipelineMode(s->conn)) { ngx_pq_log_error(NGX_LOG_ERR, s->connection->log, 0, PQerrorMessage(s->conn), "!PQenterPipelineMode"); rc = NGX_ERROR; goto destroy; }
#endif
PQExpBufferData sql;
initPQExpBuffer(&sql);
appendPQExpBufferStr(&sql, "UNLISTEN ");
char *str;
if (!(str = PQescapeIdentifier(s->conn, (char *)id.data, id.len))) { ngx_pq_log_error(NGX_LOG_ERR, s->connection->log, 0, PQerrorMessage(s->conn), "!PQescapeIdentifier"); rc = NGX_ERROR; goto term; }
appendPQExpBufferStr(&sql, str);
PQfreemem(str);
if (PQExpBufferDataBroken(sql)) { ngx_log_error(NGX_LOG_ERR, s->connection->log, 0, "PQExpBufferDataBroken"); rc = NGX_ERROR; goto term; }
if (!PQsendQueryParams(s->conn, sql.data, 0, NULL, NULL, NULL, NULL, 0)) { ngx_pq_log_error(NGX_LOG_ERR, s->connection->log, 0, PQerrorMessage(s->conn), "!PQsendQueryParams"); rc = NGX_ERROR; goto term; }
ngx_log_debug1(NGX_LOG_DEBUG_HTTP, s->connection->log, 0, "PQsendQueryParams('%s')", sql.data);
s->count++;
rc = NGX_OK;
term:
termPQExpBuffer(&sql);
} break;
case NGX_DONE: ngx_log_debug0(NGX_LOG_DEBUG_HTTP, s->connection->log, 0, "ngx_http_push_stream_add_msg_to_channel_my == NGX_DONE"); rc = NGX_OK; break;
case NGX_OK: ngx_log_debug0(NGX_LOG_DEBUG_HTTP, s->connection->log, 0, "ngx_http_push_stream_add_msg_to_channel_my == NGX_OK"); break;
default: ngx_log_error(NGX_LOG_ERR, s->connection->log, 0, "ngx_http_push_stream_add_msg_to_channel_my == %i", rc); break;
}
#ifdef LIBPQ_HAS_PIPELINING
destroy:
#endif
ngx_destroy_pool(p);
}
#ifdef LIBPQ_HAS_PIPELINING
if (PQpipelineStatus(s->conn) == PQ_PIPELINE_ON) if (!PQpipelineSync(s->conn)) { ngx_pq_log_error(NGX_LOG_ERR, s->connection->log, 0, PQerrorMessage(s->conn), "!PQpipelineSync"); rc = NGX_ERROR; }
#endif
return rc;
}
static ngx_int_t ngx_pq_queries(ngx_pq_save_t *s, ngx_pq_data_t *d, ngx_uint_t type) {
ngx_log_debug1(NGX_LOG_DEBUG_HTTP, s->connection->log, 0, "%s", __func__);
ngx_http_request_t *r = d->request;
ngx_http_upstream_t *u = r->upstream;
ngx_connection_t *c = s->connection;
c->read->active = 0;
c->write->active = 0;
if (c->read->timer_set) ngx_del_timer(c->read);
if (c->write->timer_set) ngx_del_timer(c->write);
ngx_int_t rc = NGX_ERROR;
PQExpBufferData name;
PQExpBufferData sql;
initPQExpBuffer(&name);
initPQExpBuffer(&sql);
#ifdef LIBPQ_HAS_PIPELINING
if (!PQenterPipelineMode(s->conn)) { ngx_pq_log_error(NGX_LOG_ERR, s->connection->log, 0, PQerrorMessage(s->conn), "!PQenterPipelineMode"); goto ret; }
#endif
ngx_pq_loc_conf_t *plcf = ngx_http_get_module_loc_conf(r, ngx_pq_module);
ngx_http_upstream_srv_conf_t *uscf = u->conf->upstream;
ngx_array_t *queries = &plcf->queries;
if (uscf->srv_conf && type & ngx_pq_type_upstream) {
ngx_pq_srv_conf_t *pscf = ngx_http_conf_upstream_srv_conf(uscf, ngx_pq_module);
if (pscf->queries.elts) queries = &pscf->queries;
}
if (!queries->nelts) { ngx_log_error(NGX_LOG_ERR, s->connection->log, 0, "!queries->nelts"); goto ret; }
ngx_pq_query_t *query = queries->elts;
for (ngx_uint_t i = 0; i < queries->nelts; i++) {
ngx_pq_query_queue_t *qq;
if (!(qq = ngx_pcalloc(r->pool, sizeof(*qq)))) { ngx_log_error(NGX_LOG_ERR, s->connection->log, 0, "!ngx_pcalloc"); goto ret; }
qq->query = &query[i];
ngx_queue_insert_tail(&d->queue, &qq->queue);
ngx_pq_argument_t *argument = query[i].arguments.elts;
if (!(qq->paramTypes = ngx_pcalloc(r->pool, query[i].arguments.nelts * sizeof(*qq->paramTypes)))) { ngx_log_error(NGX_LOG_ERR, s->connection->log, 0, "!ngx_pcalloc"); goto ret; }
if (!(qq->paramValues = ngx_pcalloc(r->pool, query[i].arguments.nelts * sizeof(*qq->paramValues)))) { ngx_log_error(NGX_LOG_ERR, s->connection->log, 0, "!ngx_pcalloc"); goto ret; }
for (ngx_uint_t j = 0; j < query[i].arguments.nelts; j++) {
if (query[i].type & (ngx_pq_type_query|ngx_pq_type_prepare)) {
if (argument[j].oid.complex.value.data) {
ngx_str_t value;
if (ngx_http_complex_value(r, &argument[j].oid.complex, &value) != NGX_OK) { ngx_log_error(NGX_LOG_ERR, s->connection->log, 0, "ngx_http_complex_value != NGX_OK"); goto ret; }
ngx_int_t n = ngx_atoi(value.data, value.len);
if (n == NGX_ERROR) { ngx_log_error(NGX_LOG_ERR, s->connection->log, 0, "ngx_atoi == NGX_ERROR"); goto ret; }
argument[j].oid.value = n;
}
qq->paramTypes[j] = argument[j].oid.value;
}
if (query[i].type & (ngx_pq_type_query|ngx_pq_type_execute)) {
if (argument[j].value.complex.value.data) {
ngx_str_t value;
if (ngx_http_complex_value(r, &argument[j].value.complex, &value) != NGX_OK) { ngx_log_error(NGX_LOG_ERR, s->connection->log, 0, "ngx_http_complex_value != NGX_OK"); goto ret; }
argument[j].value.str = value;
}
if (!(qq->paramValues[j] = ngx_pnalloc(r->pool, argument[j].value.str.len + 1))) { ngx_log_error(NGX_LOG_ERR, s->connection->log, 0, "!ngx_pnalloc"); goto ret; }
(void)ngx_cpystrn((u_char *)qq->paramValues[j], argument[j].value.str.data, argument[j].value.str.len + 1);
}
}
resetPQExpBuffer(&sql);
ngx_pq_command_t *command = query[i].commands.elts;
for (ngx_uint_t j = 0; j < query[i].commands.nelts; j++) if (command[j].index) {
char *str;
ngx_http_variable_value_t *value;
if (!(value = ngx_http_get_indexed_variable(r, command[j].index))) { ngx_log_error(NGX_LOG_ERR, s->connection->log, 0, "!ngx_http_get_indexed_variable"); goto ret; }
if (!(str = PQescapeIdentifier(s->conn, (char *)value->data, value->len))) { ngx_pq_log_error(NGX_LOG_ERR, s->connection->log, 0, PQerrorMessage(s->conn), "!PQescapeIdentifier"); goto ret; }
appendPQExpBufferStr(&sql, str);
PQfreemem(str);
} else appendBinaryPQExpBuffer(&sql, (char *)command[j].str.data, command[j].str.len);
if (PQExpBufferDataBroken(sql)) { ngx_log_error(NGX_LOG_ERR, s->connection->log, 0, "PQExpBufferDataBroken"); goto ret; }
if (query[i].type & ngx_pq_type_query) {
if (!PQsendQueryParams(s->conn, sql.data, query[i].arguments.nelts, qq->paramTypes, qq->paramValues, NULL, NULL, 0)) { ngx_pq_log_error(NGX_LOG_ERR, s->connection->log, 0, PQerrorMessage(s->conn), "!PQsendQueryParams"); rc = NGX_DECLINED; goto ret; }
ngx_log_debug1(NGX_LOG_DEBUG_HTTP, s->connection->log, 0, "PQsendQueryParams('%s')", sql.data);
} else {
resetPQExpBuffer(&name);
if (query[i].name.complex.value.data) {
ngx_str_t value;
if (ngx_http_complex_value(r, &query[i].name.complex, &value) != NGX_OK) { ngx_log_error(NGX_LOG_ERR, s->connection->log, 0, "ngx_http_complex_value != NGX_OK"); goto ret; }
appendBinaryPQExpBuffer(&name, (char *)value.data, value.len);
} else appendBinaryPQExpBuffer(&name, (char *)query[i].name.str.data, query[i].name.str.len);
if (PQExpBufferDataBroken(name)) { ngx_log_error(NGX_LOG_ERR, s->connection->log, 0, "PQExpBufferDataBroken"); goto ret; }
if (query[i].type & ngx_pq_type_prepare) {
if (!PQsendPrepare(s->conn, name.data, sql.data, query[i].arguments.nelts, qq->paramTypes)) { ngx_pq_log_error(NGX_LOG_ERR, s->connection->log, 0, PQerrorMessage(s->conn), "!PQsendPrepare"); rc = NGX_DECLINED; goto ret; }
ngx_log_debug2(NGX_LOG_DEBUG_HTTP, s->connection->log, 0, "PQsendPrepare('%s', '%s')", name.data, sql.data);
} else if (query[i].type & ngx_pq_type_execute) {
if (!PQsendQueryPrepared(s->conn, name.data, query[i].arguments.nelts, qq->paramValues, NULL, NULL, 0)) { ngx_pq_log_error(NGX_LOG_ERR, s->connection->log, 0, PQerrorMessage(s->conn), "!PQsendQueryPrepared"); rc = NGX_DECLINED; goto ret; }
ngx_log_debug1(NGX_LOG_DEBUG_HTTP, s->connection->log, 0, "PQsendQueryPrepared('%s')", name.data);
}
}
}
#ifdef LIBPQ_HAS_PIPELINING
if (!PQpipelineSync(s->conn)) { ngx_pq_log_error(NGX_LOG_ERR, s->connection->log, 0, PQerrorMessage(s->conn), "!PQpipelineSync"); goto ret; }
#endif
c->read->active = 1;
c->write->active = 0;
rc = NGX_AGAIN;
ret:
termPQExpBuffer(&name);
termPQExpBuffer(&sql);
d->row = 0;
return rc;
}
static ngx_int_t ngx_pq_poll(ngx_pq_save_t *s, ngx_pq_data_t *d) {
ngx_connection_t *c = s->connection;
for (;;) switch (PQconnectPoll(s->conn)) {
case PGRES_POLLING_ACTIVE: ngx_log_debug0(NGX_LOG_DEBUG_HTTP, s->connection->log, 0, "PGRES_POLLING_ACTIVE"); return NGX_AGAIN;
case PGRES_POLLING_FAILED: {
const char *message = PQerrorMessage(s->conn);
ngx_uint_t log_level = NGX_LOG_ERR;
ngx_http_request_t *r = d->request;
ngx_http_upstream_t *u = r->upstream;
ngx_http_upstream_srv_conf_t *uscf = u->conf->upstream;
if (uscf->srv_conf) {
ngx_pq_srv_conf_t *pscf = ngx_http_conf_upstream_srv_conf(uscf, ngx_pq_module);
ngx_array_t *levels = &pscf->levels;
ngx_pq_level_t *level = levels->elts;
for (ngx_uint_t i = 0; i < levels->nelts; i++) if (!ngx_strcmp((u_char *)message, level[i].message.data)) { log_level = level[i].level; break; }
}
ngx_pq_log_error(log_level, s->connection->log, 0, message, "PGRES_POLLING_FAILED");
return NGX_DECLINED;
}
case PGRES_POLLING_OK: ngx_log_debug0(NGX_LOG_DEBUG_HTTP, s->connection->log, 0, "PGRES_POLLING_OK"); return ngx_pq_queries(s, d, ngx_pq_type_location|ngx_pq_type_upstream);
case PGRES_POLLING_READING: ngx_log_debug0(NGX_LOG_DEBUG_HTTP, s->connection->log, 0, "PGRES_POLLING_READING"); c->read->active = 1; c->write->active = 0; return NGX_AGAIN;
case PGRES_POLLING_WRITING: ngx_log_debug0(NGX_LOG_DEBUG_HTTP, s->connection->log, 0, "PGRES_POLLING_WRITING"); c->read->active = 0; c->write->active = 1; break;
}
return NGX_AGAIN;
}
static ngx_int_t ngx_pq_result(ngx_pq_save_t *s, ngx_pq_data_t *d) {
ngx_log_debug1(NGX_LOG_DEBUG_HTTP, s->connection->log, 0, "%s", __func__);
if (!PQconsumeInput(s->conn)) { ngx_pq_log_error(NGX_LOG_ERR, s->connection->log, 0, PQerrorMessage(s->conn), "!PQconsumeInput"); return NGX_DECLINED; }
ngx_int_t rc = NGX_OK;
for (PGresult *res; ((res = PQgetResult(s->conn)) || (res = PQgetResult(s->conn))) && PQstatus(s->conn) == CONNECTION_OK; PQclear(res)) switch (PQresultStatus(res)) {
case PGRES_COMMAND_OK: rc = ngx_pq_res_command_ok(s, d, res); break;
case PGRES_COPY_OUT: rc = ngx_pq_res_copy_out(s, d); break;
case PGRES_FATAL_ERROR: rc = ngx_pq_res_fatal_error(s, d, res); break;
#ifdef LIBPQ_HAS_PIPELINING
case PGRES_PIPELINE_SYNC: ngx_log_debug0(NGX_LOG_DEBUG_HTTP, s->connection->log, 0, "PGRES_PIPELINE_SYNC"); break;
#endif
case PGRES_TUPLES_OK: rc = ngx_pq_res_tuples_ok(s, d, res); break;
default: rc = ngx_pq_res_default(s, d, res); break;
}
#ifdef LIBPQ_HAS_PIPELINING
if (PQstatus(s->conn) == CONNECTION_OK && !PQexitPipelineMode(s->conn)) { ngx_pq_log_error(NGX_LOG_ERR, s->connection->log, 0, PQerrorMessage(s->conn), "!PQexitPipelineMode"); return NGX_DECLINED; }
#endif
if (rc == NGX_OK) rc = ngx_pq_notify(s);
if (s->count) { ngx_log_error(NGX_LOG_ERR, s->connection->log, 0, "s->count = %i", s->count); return NGX_HTTP_BAD_GATEWAY; }
if (!d) return rc;
if (!ngx_queue_empty(&d->queue)) { ngx_log_error(NGX_LOG_ERR, s->connection->log, 0, "!ngx_queue_empty"); return NGX_HTTP_BAD_GATEWAY; }
if (rc == NGX_OK && d->type & ngx_pq_type_upstream) return ngx_pq_queries(s, d, ngx_pq_type_location);
if (s->conn->inBufSize > s->inBufSize) {
ngx_log_error(NGX_LOG_WARN, s->connection->log, 0, "inBufSize %i > %i", s->conn->inBufSize, s->inBufSize);
char *newbuf;
if (!(newbuf = realloc(s->conn->inBuffer, s->inBufSize))) { ngx_log_error(NGX_LOG_ERR, s->connection->log, 0, "!realloc"); return NGX_HTTP_BAD_GATEWAY; }
s->conn->inBuffer = newbuf;
s->conn->inBufSize = s->inBufSize;
}
return rc;
}
static void ngx_pq_save_cln_handler(void *data) {
ngx_pq_save_t *s = data;
ngx_connection_t *c = s->connection;
ngx_log_debug1(NGX_LOG_DEBUG_HTTP, c->log, 0, "%V", &c->addr_text);
if (ngx_del_conn) {
ngx_del_conn(c, NGX_CLOSE_EVENT);
} else {
ngx_del_event(c->read, NGX_READ_EVENT, NGX_CLOSE_EVENT);
ngx_del_event(c->write, NGX_WRITE_EVENT, NGX_CLOSE_EVENT);
}
if (s->conn) PQfinish(s->conn);
s->conn = NULL;
if (!ngx_terminate && !ngx_exiting && !c->error) while (!ngx_queue_empty(&s->queue)) {
ngx_queue_t *q = ngx_queue_head(&s->queue);
ngx_queue_remove(q);
ngx_pq_channel_queue_t *cq = ngx_queue_data(q, ngx_pq_channel_queue_t, queue);
ngx_log_debug1(NGX_LOG_DEBUG_HTTP, c->log, 0, "channel = %V", &cq->channel);
(void)ngx_http_push_stream_delete_channel_my(c->log, &cq->channel, NULL, 0, c->pool);
}
}
static void ngx_pq_notice_processor(void *arg, const char *message) {
ngx_pq_save_t *s = arg;
ngx_pq_log_error(NGX_LOG_NOTICE, s->connection->log, 0, message, "PGRES_NONFATAL_ERROR");
}
static ngx_int_t ngx_pq_peer_open(ngx_peer_connection_t *pc, void *data) {
ngx_log_debug1(NGX_LOG_DEBUG_HTTP, pc->log, 0, "%s", __func__);
ngx_pq_data_t *d = data;
ngx_pq_save_t *s;
ngx_http_request_t *r = d->request;
ngx_pq_loc_conf_t *plcf = ngx_http_get_module_loc_conf(r, ngx_pq_module);
size_t buffer_size = plcf->upstream.buffer_size;
ngx_http_upstream_t *u = r->upstream;
ngx_http_upstream_srv_conf_t *uscf = u->conf->upstream;
ngx_pq_connect_t *connect = &plcf->connect;
if (uscf->srv_conf) {
ngx_pq_srv_conf_t *pscf = ngx_http_conf_upstream_srv_conf(uscf, ngx_pq_module);
buffer_size = pscf->buffer_size;
connect = &pscf->connect;
}
plcf->upstream.connect_timeout = connect->timeout;
PQExpBufferData conninfo;
initPQExpBuffer(&conninfo);
ngx_str_t *option = connect->options.elts;
for (ngx_uint_t i = 0; i < connect->options.nelts; i++) {
if (i) appendPQExpBufferChar(&conninfo, ' ');
appendBinaryPQExpBuffer(&conninfo, (char *)option[i].data, option[i].len);
}
if (pc->sockaddr->sa_family != AF_UNIX) {
appendPQExpBufferStr(&conninfo, " host=");
ngx_http_upstream_server_t *us = uscf->servers->elts;
ngx_str_t host = uscf->host;
for (ngx_uint_t j = 0; j < uscf->servers->nelts; j++) if (us[j].name.data) for (ngx_uint_t k = 0; k < us[j].naddrs; k++) if (pc->sockaddr == us[j].addrs[k].sockaddr) { host = us[j].name; goto found; }
found:
while (host.len--) if (host.data[host.len] == ':') break;
appendBinaryPQExpBuffer(&conninfo, (char *)host.data, host.len);
}
ngx_str_t host = *pc->name;
ngx_str_t port = host;
while (host.len--) if (host.data[host.len] == ':') break;
port.data += host.len + 1;
port.len -= host.len + 1;
if (pc->sockaddr->sa_family != AF_UNIX) {
appendPQExpBufferStr(&conninfo, " hostaddr=");
appendBinaryPQExpBuffer(&conninfo, (char *)host.data, host.len);
} else {
appendPQExpBufferStr(&conninfo, " host=");
appendBinaryPQExpBuffer(&conninfo, (char *)host.data + 5, host.len - 5);
}
appendPQExpBufferStr(&conninfo, " port=");
appendBinaryPQExpBuffer(&conninfo, (char *)port.data, port.len);
ngx_int_t rc = NGX_ERROR;
if (PQExpBufferDataBroken(conninfo)) { ngx_log_error(NGX_LOG_ERR, pc->log, 0, "PQExpBufferDataBroken"); goto term; }
ngx_log_debug1(NGX_LOG_DEBUG_HTTP, pc->log, 0, "%s", conninfo.data);
PGconn *conn = PQconnectStart(conninfo.data);
if (PQstatus(conn) == CONNECTION_BAD) { ngx_pq_log_error(NGX_LOG_ERR, pc->log, 0, PQerrorMessage(conn), "CONNECTION_BAD"); goto finish; }
(void)PQsetErrorContextVisibility(conn, connect->show_context);
(void)PQsetErrorVerbosity(conn, connect->errors);
if (PQsetnonblocking(conn, 1) == -1) { ngx_pq_log_error(NGX_LOG_ERR, pc->log, 0, PQerrorMessage(conn), "PQsetnonblocking == -1"); goto finish; }
int fd;
if ((fd = PQsocket(conn)) < 0) { ngx_log_error(NGX_LOG_ERR, pc->log, 0, "PQsocket < 0"); goto finish; }
ngx_connection_t *c = ngx_get_connection(fd, pc->log);
if (!c) { ngx_log_error(NGX_LOG_ERR, pc->log, 0, "!ngx_get_connection"); goto finish; }
c->addr_text = *pc->name;
c->number = ngx_atomic_fetch_add(ngx_connection_counter, 1);
c->read->log = pc->log;
c->shared = 1;
c->start_time = ngx_current_msec;
c->type = pc->type ? pc->type : SOCK_STREAM;
c->write->log = pc->log;
if (!c->pool && !(c->pool = ngx_create_pool(128, pc->log))) { ngx_log_error(NGX_LOG_ERR, pc->log, 0, "!ngx_create_pool"); goto close; }
if (!(s = d->save = ngx_pcalloc(c->pool, sizeof(*s)))) { ngx_log_error(NGX_LOG_ERR, pc->log, 0, "!ngx_pcalloc"); goto destroy; }
s->inBufSize = ngx_max(conn->inBufSize, (int)buffer_size);
(void)PQsetNoticeProcessor(conn, ngx_pq_notice_processor, s);
ngx_queue_init(&s->queue);
ngx_pool_cleanup_t *cln;
if (!(cln = ngx_pool_cleanup_add(c->pool, 0))) { ngx_log_error(NGX_LOG_ERR, pc->log, 0, "!ngx_pool_cleanup_add"); goto destroy; }
cln->data = s;
cln->handler = ngx_pq_save_cln_handler;
if (ngx_add_conn) {
if (ngx_add_conn(c) != NGX_OK) { ngx_log_error(NGX_LOG_ERR, pc->log, 0, "ngx_add_conn != NGX_OK"); goto destroy; }
} else {
if (ngx_add_event(c->read, NGX_READ_EVENT, ngx_event_flags & NGX_USE_CLEAR_EVENT ? NGX_CLEAR_EVENT : NGX_LEVEL_EVENT) != NGX_OK) { ngx_log_error(NGX_LOG_ERR, pc->log, 0, "ngx_add_event != NGX_OK"); goto destroy; }
if (ngx_add_event(c->write, NGX_WRITE_EVENT, ngx_event_flags & NGX_USE_CLEAR_EVENT ? NGX_CLEAR_EVENT : NGX_LEVEL_EVENT) != NGX_OK) { ngx_log_error(NGX_LOG_ERR, pc->log, 0, "ngx_add_event != NGX_OK"); goto destroy; }
}
pc->connection = c;
rc = NGX_AGAIN;
s->conn = conn;
s->connection = c;
goto term;
destroy:
ngx_destroy_pool(c->pool);
close:
ngx_close_connection(c);
finish:
PQfinish(conn);
term:
termPQExpBuffer(&conninfo);
return rc;
}
static void ngx_pq_read_handler(ngx_event_t *ev) {
ngx_connection_t *c = ev->data;
ngx_log_debug1(NGX_LOG_DEBUG_HTTP, c->log, 0, "%V", &c->addr_text);
for (ngx_pool_cleanup_t *cln = c->pool->cleanup; cln; cln = cln->next) if (cln->handler == ngx_pq_save_cln_handler) {
ngx_pq_save_t *s = cln->data;
if (!ngx_terminate && !ngx_exiting && !c->error && !ev->error && !ev->timedout) {
if (s->timeout) ngx_add_timer(c->read, s->timeout);
if (ngx_pq_result(s, NULL) == NGX_OK) return;
}
return s->read(ev);
}
}
static void ngx_pq_write_handler(ngx_event_t *ev) {
ngx_connection_t *c = ev->data;
ngx_log_debug1(NGX_LOG_DEBUG_HTTP, c->log, 0, "%V", &c->addr_text);
for (ngx_pool_cleanup_t *cln = c->pool->cleanup; cln; cln = cln->next) if (cln->handler == ngx_pq_save_cln_handler) {
ngx_pq_save_t *s = cln->data;
return s->write(ev);
}
}
static ngx_int_t ngx_pq_peer_get(ngx_peer_connection_t *pc, void *data) {
ngx_log_debug1(NGX_LOG_DEBUG_HTTP, pc->log, 0, "%s", __func__);
ngx_pq_data_t *d = data;
ngx_int_t rc;
switch ((rc = d->peer.get(pc, d->peer.data))) {
case NGX_DONE: ngx_log_debug0(NGX_LOG_DEBUG_HTTP, pc->log, 0, "peer.get = NGX_DONE"); break;
case NGX_OK: ngx_log_debug0(NGX_LOG_DEBUG_HTTP, pc->log, 0, "peer.get = NGX_OK"); break;
default: ngx_log_debug1(NGX_LOG_DEBUG_HTTP, pc->log, 0, "peer.get = %i", rc); return rc;
}
if (!pc->connection) return ngx_pq_peer_open(pc, data);
ngx_connection_t *c = pc->connection;
for (ngx_pool_cleanup_t *cln = c->pool->cleanup; cln; cln = cln->next) if (cln->handler == ngx_pq_save_cln_handler) {
ngx_pq_save_t *s = d->save = cln->data;
if (PQstatus(s->conn) != CONNECTION_OK) { ngx_pq_log_error(NGX_LOG_ERR, pc->log, 0, PQerrorMessage(s->conn), "CONNECTION_BAD"); return NGX_DECLINED; }
return ngx_pq_queries(s, d, ngx_pq_type_location);
}
ngx_log_error(NGX_LOG_ERR, pc->log, 0, "!s");
return NGX_BUSY;
}
static void ngx_pq_peer_free(ngx_peer_connection_t *pc, void *data, ngx_uint_t state) {
ngx_log_debug1(NGX_LOG_DEBUG_HTTP, pc->log, 0, "state = %ui", state);
ngx_pq_data_t *d = data;
d->peer.free(pc, d->peer.data, state);
ngx_pq_save_t *s = d->save;
if (!s) return;
if (!ngx_queue_empty(&d->queue)) {
while (!ngx_queue_empty(&d->queue)) {
ngx_queue_t *q = ngx_queue_head(&d->queue);
ngx_queue_remove(q);
s->count++;
}
PGcancel *cancel;
if (s->conn && (cancel = PQgetCancel(s->conn))) {
char errbuf[256];
if (!PQcancel(cancel, errbuf, sizeof(errbuf))) ngx_pq_log_error(NGX_LOG_ERR, pc->log, 0, errbuf, "!PQcancel");
PQfreeCancel(cancel);
}
}
if (pc->connection) return;
ngx_http_request_t *r = d->request;
ngx_http_upstream_t *u = r->upstream;
ngx_http_upstream_srv_conf_t *uscf = u->conf->upstream;
ngx_pq_srv_conf_t *pscf = ngx_http_conf_upstream_srv_conf(uscf, ngx_pq_module);
if (!pscf) return;
ngx_connection_t *c = s->connection;
if (!c) return;
if (c->read->timer_set) s->timeout = c->read->timer.key - ngx_current_msec;
s->read = c->read->handler;
s->write = c->write->handler;
c->read->handler = ngx_pq_read_handler;
c->write->handler = ngx_pq_write_handler;
if (!pscf->log) return;
c->log = pscf->log;
c->pool->log = c->log;
c->read->log = c->log;
c->write->log = c->log;
}
static ngx_int_t ngx_pq_peer_init(ngx_http_request_t *r, ngx_http_upstream_srv_conf_t *uscf) {
ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "srv_conf = %s", uscf->srv_conf ? "true" : "false");
ngx_pq_data_t *d;
if (!(d = ngx_pcalloc(r->pool, sizeof(*d)))) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "!ngx_pcalloc"); return NGX_ERROR; }
ngx_queue_init(&d->queue);
if (uscf->srv_conf) {
ngx_pq_srv_conf_t *pscf = ngx_http_conf_upstream_srv_conf(uscf, ngx_pq_module);
if (pscf->peer.init(r, uscf) != NGX_OK) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "peer.init != NGX_OK"); return NGX_ERROR; }
} else {
if (ngx_http_upstream_init_round_robin_peer(r, uscf) != NGX_OK) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "ngx_http_upstream_init_round_robin_peer != NGX_OK"); return NGX_ERROR; }
}
ngx_http_upstream_t *u = r->upstream;
d->peer = u->peer;
d->request = r;
u->conf->upstream = uscf;
u->peer.data = d;
u->peer.free = ngx_pq_peer_free;
u->peer.get = ngx_pq_peer_get;
ngx_http_set_ctx(r, d, ngx_pq_module);
return NGX_OK;
}
static ngx_int_t ngx_pq_peer_init_upstream(ngx_conf_t *cf, ngx_http_upstream_srv_conf_t *uscf) {
if (uscf->srv_conf) {
ngx_pq_srv_conf_t *pscf = ngx_http_conf_upstream_srv_conf(uscf, ngx_pq_module);
if (pscf->peer.init_upstream(cf, uscf) != NGX_OK) { ngx_log_error(NGX_LOG_EMERG, cf->log, 0, "peer.init_upstream != NGX_OK"); return NGX_ERROR; }
pscf->peer.init = uscf->peer.init ? uscf->peer.init : ngx_http_upstream_init_round_robin_peer;
ngx_conf_init_size_value(pscf->buffer_size, (size_t)ngx_pagesize);
} else {
if (ngx_http_upstream_init_round_robin(cf, uscf) != NGX_OK) { ngx_log_error(NGX_LOG_EMERG, cf->log, 0, "ngx_http_upstream_init_round_robin != NGX_OK"); return NGX_ERROR; }
}
uscf->peer.init = ngx_pq_peer_init;
return NGX_OK;
}
static void ngx_http_upstream_next_my(ngx_http_request_t *r, ngx_http_upstream_t *u, ngx_uint_t ft_type) {
ngx_http_upstream_handler_pt read_event_handler = u->read_event_handler;
ngx_http_upstream_handler_pt write_event_handler = u->write_event_handler;
ngx_http_upstream_next(r, u, ft_type);
u->read_event_handler = read_event_handler;
u->write_event_handler = write_event_handler;
}
static void ngx_pq_event_handler(ngx_http_request_t *r, ngx_http_upstream_t *u) {
ngx_pq_data_t *d = ngx_http_get_module_ctx(r, ngx_pq_module);
ngx_pq_save_t *s = d->save;
ngx_connection_t *c = s->connection;
ngx_int_t rc = NGX_AGAIN;
switch (PQstatus(s->conn)) {
#if PG_VERSION_NUM >= 170000
case CONNECTION_ALLOCATED: ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "CONNECTION_ALLOCATED"); break;
#endif
case CONNECTION_AUTH_OK: ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "CONNECTION_AUTH_OK"); break;
case CONNECTION_AWAITING_RESPONSE: ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "CONNECTION_AWAITING_RESPONSE"); break;
case CONNECTION_BAD: ngx_pq_log_error(NGX_LOG_ERR, r->connection->log, 0, PQerrorMessage(s->conn), "CONNECTION_BAD"); rc = NGX_DECLINED; goto ret;
#if PG_VERSION_NUM >= 140000
case CONNECTION_CHECK_STANDBY: ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "CONNECTION_CHECK_STANDBY"); break;
#endif
#if PG_VERSION_NUM >= 130000
case CONNECTION_CHECK_TARGET: ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "CONNECTION_CHECK_TARGET"); break;
#endif
case CONNECTION_CHECK_WRITABLE: ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "CONNECTION_CHECK_WRITABLE"); break;
case CONNECTION_CONSUME: ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "CONNECTION_CONSUME"); break;
case CONNECTION_GSS_STARTUP: ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "CONNECTION_GSS_STARTUP"); break;
case CONNECTION_MADE: ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "CONNECTION_MADE"); break;
case CONNECTION_NEEDED: ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "CONNECTION_NEEDED"); break;
case CONNECTION_OK: ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "CONNECTION_OK");
if (c->read->timedout || c->write->timedout) return ngx_http_upstream_finalize_request(r, u, NGX_HTTP_GATEWAY_TIME_OUT);
rc = ngx_pq_result(s, d);
goto ret;
case CONNECTION_SETENV: ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "CONNECTION_SETENV"); break;
case CONNECTION_SSL_STARTUP: ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "CONNECTION_SSL_STARTUP"); break;
case CONNECTION_STARTED: ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "CONNECTION_STARTED"); break;
}
if (c->read->timedout || c->write->timedout) return ngx_http_upstream_next_my(r, u, NGX_HTTP_UPSTREAM_FT_TIMEOUT);
rc = ngx_pq_poll(s, d);
ret:
switch (rc) {
case NGX_AGAIN: break;
case NGX_BUSY: ngx_http_upstream_next_my(r, u, NGX_HTTP_UPSTREAM_FT_NOLIVE); break;
case NGX_DECLINED: ngx_http_upstream_next_my(r, u, NGX_HTTP_UPSTREAM_FT_ERROR); break;
case NGX_ERROR: ngx_http_upstream_next_my(r, u, NGX_HTTP_UPSTREAM_FT_ERROR); break;
default: ngx_http_upstream_finalize_request(r, u, rc); break;
}
}
static void ngx_pq_abort_request(ngx_http_request_t *r) {
ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "%s", __func__);
}
static ngx_int_t ngx_pq_create_request(ngx_http_request_t *r) {
ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "%s", __func__);
ngx_http_upstream_t *u = r->upstream;
ngx_pq_loc_conf_t *plcf = ngx_http_get_module_loc_conf(r, ngx_pq_module);
if (plcf->complex.value.data) {
ngx_str_t host;
if (ngx_http_complex_value(r, &plcf->complex, &host) != NGX_OK) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "ngx_http_complex_value != NGX_OK"); return NGX_ERROR; }
if (!host.len) { ngx_http_core_loc_conf_t *clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module); ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "empty \"pq_pass\" (was: \"%V\") in location \"%V\"", &plcf->complex.value, &clcf->name); return NGX_ERROR; }
if (!(u->resolved = ngx_pcalloc(r->pool, sizeof(*u->resolved)))) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "!ngx_pcalloc"); return NGX_ERROR; }
u->resolved->host = host;
u->resolved->no_port = 1;
}
if (!plcf->queries.nelts) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "!queries"); return NGX_ERROR; }
u->request_sent = 1; // force to reinit_request
return NGX_OK;
}
static void ngx_pq_finalize_request(ngx_http_request_t *r, ngx_int_t rc) {
ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "rc = %i", rc);
ngx_http_upstream_t *u = r->upstream;
u->keepalive = !u->headers_in.connection_close;
u->request_body_sent = 1;
ngx_pq_data_t *d = ngx_http_get_module_ctx(r, ngx_pq_module);
ngx_pq_save_t *s = d->save;
if (!s) return;
if (rc >= NGX_HTTP_SPECIAL_RESPONSE) return;
if (!r->headers_out.status) r->headers_out.status = NGX_HTTP_OK;
r->headers_out.content_length_n = 0;
for (ngx_chain_t *cl = u->out_bufs; cl; cl = cl->next) r->headers_out.content_length_n += cl->buf->last - cl->buf->pos;
rc = ngx_http_send_header(r);
if (rc == NGX_ERROR || rc > NGX_OK || r->header_only) return;
u->header_sent = 1;
if (!u->out_bufs) return;
if (ngx_http_output_filter(r, u->out_bufs) != NGX_OK) return;
ngx_chain_update_chains(r->pool, &u->free_bufs, &u->busy_bufs, &u->out_bufs, u->output.tag);
}
static ngx_int_t ngx_pq_process_header(ngx_http_request_t *r) {
ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "%s", __func__);
return NGX_OK;
}
static ngx_int_t ngx_pq_reinit_request(ngx_http_request_t *r) {
ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "%s", __func__);
ngx_http_upstream_t *u = r->upstream;
r->state = 0;
u->read_event_handler = ngx_pq_event_handler;
u->write_event_handler = ngx_pq_event_handler;
return NGX_OK;
}
static ngx_int_t ngx_pq_variable_get_handler(ngx_http_request_t *r, ngx_http_variable_value_t *v, uintptr_t data) {
ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "%s", __func__);
v->not_found = 1;
ngx_http_upstream_t *u = r->upstream;
if (!u) return NGX_OK;
ngx_pq_data_t *d = ngx_http_get_module_ctx(r, ngx_pq_module);
if (!d) return NGX_OK;
ngx_pq_save_t *s = d->save;
if (!s) return NGX_OK;
ngx_int_t index = data;
ngx_array_t *variables;
ngx_pq_variable_t *variable;
variables = &d->variables;
variable = variables->elts;
for (ngx_uint_t i = 0; i < variables->nelts; i++) if (variable[i].index == index) {
for (ngx_chain_t *cl = variable[i].cl; cl; cl = cl->next) v->len += cl->buf->last - cl->buf->pos;
u_char *p;
if (!(p = v->data = ngx_pnalloc(r->pool, v->len))) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "!ngx_pnalloc"); return NGX_ERROR; }
for (ngx_chain_t *cl = variable[i].cl; cl; cl = cl->next) p = ngx_copy(p, cl->buf->pos, cl->buf->last - cl->buf->pos);
v->no_cacheable = 0;
v->not_found = 0;
v->valid = 1;
return NGX_OK;
}
variables = &s->variables;
variable = variables->elts;
for (ngx_uint_t i = 0; i < variables->nelts; i++) if (variable[i].index == index) {
for (ngx_chain_t *cl = variable[i].cl; cl; cl = cl->next) v->len += cl->buf->last - cl->buf->pos;
u_char *p;
if (!(p = v->data = ngx_pnalloc(r->pool, v->len))) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "!ngx_pnalloc"); return NGX_ERROR; }
for (ngx_chain_t *cl = variable[i].cl; cl; cl = cl->next) p = ngx_copy(p, cl->buf->pos, cl->buf->last - cl->buf->pos);
v->no_cacheable = 0;
v->not_found = 0;
v->valid = 1;
return NGX_OK;
}
return NGX_OK;
}
typedef char *(*pq_func)(const PGconn *conn);
static ngx_int_t ngx_pq_conn_get_handler(ngx_http_request_t *r, ngx_http_variable_value_t *v, uintptr_t data) {
ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "%s", __func__);
v->not_found = 1;
ngx_http_upstream_t *u = r->upstream;
if (!u) return NGX_OK;
ngx_pq_data_t *d = ngx_http_get_module_ctx(r, ngx_pq_module);
if (!d) return NGX_OK;
ngx_pq_save_t *s = d->save;
if (!s) return NGX_OK;
pq_func function = (pq_func)data;
if (!(v->data = (u_char *)function(s->conn))) return NGX_OK;
if (!(v->len = ngx_strlen(v->data))) return NGX_OK;
v->valid = 1;
v->no_cacheable = 0;
v->not_found = 0;
return NGX_OK;
}