forked from triton-inference-server/server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_server.cc
2808 lines (2501 loc) · 93.1 KB
/
http_server.cc
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 2019-2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "src/servers/http_server.h"
#include <event2/buffer.h>
#include <google/protobuf/text_format.h>
#include <google/protobuf/util/json_util.h>
#include <re2/re2.h>
#include <algorithm>
#include <list>
#include <thread>
#include "src/core/constants.h"
#include "src/core/logging.h"
#include "src/core/model_config.h"
#include "src/servers/classification.h"
#include "src/servers/data_compressor.h"
#define TRITONJSON_STATUSTYPE TRITONSERVER_Error*
#define TRITONJSON_STATUSRETURN(M) \
return TRITONSERVER_ErrorNew(TRITONSERVER_ERROR_INTERNAL, (M).c_str())
#define TRITONJSON_STATUSSUCCESS nullptr
#include "triton/common/triton_json.h"
#ifdef TRITON_ENABLE_GPU
extern "C" {
#include <b64/cdecode.h>
}
#endif // TRITON_ENABLE_GPU
#ifdef TRITON_ENABLE_TRACING
#include "src/servers/tracer.h"
#endif // TRITON_ENABLE_TRACING
namespace nvidia { namespace inferenceserver {
TRITONSERVER_Error*
HTTPServer::Start()
{
if (!worker_.joinable()) {
evbase_ = event_base_new();
htp_ = evhtp_new(evbase_, NULL);
evhtp_enable_flag(htp_, EVHTP_FLAG_ENABLE_NODELAY);
evhtp_set_gencb(htp_, HTTPServer::Dispatch, this);
evhtp_use_threads_wexit(htp_, NULL, NULL, thread_cnt_, NULL);
evhtp_bind_socket(htp_, "0.0.0.0", port_, 1024);
// Set listening event for breaking event loop
evutil_socketpair(AF_UNIX, SOCK_STREAM, 0, fds_);
break_ev_ = event_new(evbase_, fds_[0], EV_READ, StopCallback, evbase_);
event_add(break_ev_, NULL);
worker_ = std::thread(event_base_loop, evbase_, 0);
return nullptr;
}
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_ALREADY_EXISTS, "HTTP server is already running.");
}
TRITONSERVER_Error*
HTTPServer::Stop()
{
if (worker_.joinable()) {
// Notify event loop to break via fd write
send(fds_[1], &evbase_, sizeof(event_base*), 0);
worker_.join();
event_free(break_ev_);
evutil_closesocket(fds_[0]);
evutil_closesocket(fds_[1]);
evhtp_unbind_socket(htp_);
evhtp_free(htp_);
event_base_free(evbase_);
return nullptr;
}
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_UNAVAILABLE, "HTTP server is not running.");
}
void
HTTPServer::StopCallback(int sock, short events, void* arg)
{
struct event_base* base = (struct event_base*)arg;
event_base_loopbreak(base);
}
void
HTTPServer::Dispatch(evhtp_request_t* req, void* arg)
{
(static_cast<HTTPServer*>(arg))->Handle(req);
}
#ifdef TRITON_ENABLE_METRICS
void
HTTPMetricsServer::Handle(evhtp_request_t* req)
{
LOG_VERBOSE(1) << "HTTP request: " << req->method << " "
<< req->uri->path->full;
if (req->method != htp_method_GET) {
evhtp_send_reply(req, EVHTP_RES_METHNALLOWED);
return;
}
evhtp_res res = EVHTP_RES_BADREQ;
// Call to metric endpoint should not have any trailing string
if (RE2::FullMatch(std::string(req->uri->path->full), api_regex_)) {
TRITONSERVER_Metrics* metrics = nullptr;
TRITONSERVER_Error* err =
TRITONSERVER_ServerMetrics(server_.get(), &metrics);
if (err == nullptr) {
const char* base;
size_t byte_size;
err = TRITONSERVER_MetricsFormatted(
metrics, TRITONSERVER_METRIC_PROMETHEUS, &base, &byte_size);
if (err == nullptr) {
res = EVHTP_RES_OK;
evbuffer_add(req->buffer_out, base, byte_size);
}
}
TRITONSERVER_MetricsDelete(metrics);
TRITONSERVER_ErrorDelete(err);
}
evhtp_send_reply(req, res);
}
#ifdef TRITON_ENABLE_METRICS
TRITONSERVER_Error*
HTTPMetricsServer::Create(
const std::shared_ptr<TRITONSERVER_Server>& server, const int32_t port,
const int thread_cnt, std::unique_ptr<HTTPServer>* metrics_server)
{
metrics_server->reset(new HTTPMetricsServer(server, port, thread_cnt));
const std::string addr = "0.0.0.0:" + std::to_string(port);
LOG_INFO << "Started Metrics Service at " << addr;
return nullptr;
}
#endif // TRITON_ENABLE_METRICS
#endif // TRITON_ENABLE_METRICS
namespace {
// Allocate an evbuffer of size 'byte_size'. Return the 'evb' and
// the 'base' address of the buffer contents.
TRITONSERVER_Error*
AllocEVBuffer(const size_t byte_size, evbuffer** evb, void** base)
{
evbuffer* evhttp_buffer = evbuffer_new();
if (evhttp_buffer == nullptr) {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
"failed to create evbuffer for output tensor");
}
// Reserve requested space in evbuffer...
struct evbuffer_iovec output_iovec;
if (evbuffer_reserve_space(evhttp_buffer, byte_size, &output_iovec, 1) != 1) {
evbuffer_free(evhttp_buffer);
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
std::string(
"failed to reserve " + std::to_string(byte_size) +
" bytes in output tensor buffer")
.c_str());
}
if (output_iovec.iov_len < byte_size) {
evbuffer_free(evhttp_buffer);
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
std::string(
"reserved " + std::to_string(output_iovec.iov_len) +
" bytes in output tensor buffer, need " + std::to_string(byte_size))
.c_str());
}
output_iovec.iov_len = byte_size;
*base = output_iovec.iov_base;
// Immediately commit the buffer space. We are relying on evbuffer
// not to relocate this space. Because we request a contiguous
// chunk every time (above by allowing only a single entry in
// output_iovec), this seems to be a valid assumption.
if (evbuffer_commit_space(evhttp_buffer, &output_iovec, 1) != 0) {
*base = nullptr;
evbuffer_free(evhttp_buffer);
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
"failed to commit output tensors to output buffer");
}
*evb = evhttp_buffer;
return nullptr; // success
}
TRITONSERVER_Error*
JsonBytesArrayByteSize(
triton::common::TritonJson::Value& tensor_data, size_t* byte_size)
{
*byte_size = 0;
for (size_t i = 0; i < tensor_data.ArraySize(); i++) {
triton::common::TritonJson::Value el;
RETURN_IF_ERR(tensor_data.At(i, &el));
// Recurse if not last dimension...
TRITONSERVER_Error* assert_err =
el.AssertType(triton::common::TritonJson::ValueType::ARRAY);
if (assert_err == nullptr) {
RETURN_IF_ERR(JsonBytesArrayByteSize(el, byte_size));
} else {
// Serialized data size is the length of the string itself plus
// 4 bytes to record the string length.
const char* str;
size_t len = 0;
RETURN_MSG_IF_ERR(
el.AsString(&str, &len), "Unable to parse JSON bytes array");
*byte_size += len + sizeof(uint32_t);
}
TRITONSERVER_ErrorDelete(assert_err);
}
return nullptr; // success
}
TRITONSERVER_Error*
ReadDataFromJsonHelper(
char* base, const TRITONSERVER_DataType dtype,
triton::common::TritonJson::Value& tensor_data, int* counter,
int64_t expected_cnt)
{
// FIXME should invert loop and switch so don't have to do a switch
// each iteration.
for (size_t i = 0; i < tensor_data.ArraySize(); i++) {
triton::common::TritonJson::Value el;
RETURN_IF_ERR(tensor_data.At(i, &el));
// Recurse if not last dimension...
TRITONSERVER_Error* assert_err =
el.AssertType(triton::common::TritonJson::ValueType::ARRAY);
if (assert_err == nullptr) {
RETURN_IF_ERR(
ReadDataFromJsonHelper(base, dtype, el, counter, expected_cnt));
} else {
// Check if writing to 'serialized' is overrunning the expected byte_size
if (*counter >= expected_cnt) {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
"Shape does not match true shape of 'data' field");
}
switch (dtype) {
case TRITONSERVER_TYPE_BOOL: {
bool b = false;
RETURN_IF_ERR(el.AsBool(&b));
uint8_t* data_vec = reinterpret_cast<uint8_t*>(base);
// FIXME for unsigned should bounds check and raise error
// since otherwise the actually used value will be
// unexpected.
data_vec[*counter] = (uint8_t)(b ? 1 : 0);
*counter += 1;
break;
}
case TRITONSERVER_TYPE_UINT8: {
uint64_t ui = 0;
RETURN_IF_ERR(el.AsUInt(&ui));
uint8_t* data_vec = reinterpret_cast<uint8_t*>(base);
data_vec[*counter] = (uint8_t)ui;
*counter += 1;
break;
}
case TRITONSERVER_TYPE_UINT16: {
uint64_t ui = 0;
RETURN_IF_ERR(el.AsUInt(&ui));
uint16_t* data_vec = reinterpret_cast<uint16_t*>(base);
data_vec[*counter] = (uint16_t)ui;
*counter += 1;
break;
}
case TRITONSERVER_TYPE_UINT32: {
uint64_t ui = 0;
RETURN_IF_ERR(el.AsUInt(&ui));
uint32_t* data_vec = reinterpret_cast<uint32_t*>(base);
data_vec[*counter] = (uint32_t)ui;
*counter += 1;
break;
}
case TRITONSERVER_TYPE_UINT64: {
uint64_t ui = 0;
RETURN_IF_ERR(el.AsUInt(&ui));
uint64_t* data_vec = reinterpret_cast<uint64_t*>(base);
data_vec[*counter] = ui;
*counter += 1;
break;
}
case TRITONSERVER_TYPE_INT8: {
// FIXME for signed type just assigning to smaller type is
// "implementation defined" and so really need to bounds
// check.
int64_t si = 0;
RETURN_IF_ERR(el.AsInt(&si));
int8_t* data_vec = reinterpret_cast<int8_t*>(base);
data_vec[*counter] = (int8_t)si;
*counter += 1;
break;
}
case TRITONSERVER_TYPE_INT16: {
int64_t si = 0;
RETURN_IF_ERR(el.AsInt(&si));
int16_t* data_vec = reinterpret_cast<int16_t*>(base);
data_vec[*counter] = (int16_t)si;
*counter += 1;
break;
}
case TRITONSERVER_TYPE_INT32: {
int64_t si = 0;
RETURN_IF_ERR(el.AsInt(&si));
int32_t* data_vec = reinterpret_cast<int32_t*>(base);
data_vec[*counter] = (int32_t)si;
*counter += 1;
break;
}
case TRITONSERVER_TYPE_INT64: {
int64_t si = 0;
RETURN_IF_ERR(el.AsInt(&si));
int64_t* data_vec = reinterpret_cast<int64_t*>(base);
data_vec[*counter] = si;
*counter += 1;
break;
}
case TRITONSERVER_TYPE_FP32: {
double fp64 = 0;
RETURN_IF_ERR(el.AsDouble(&fp64));
float* data_vec = reinterpret_cast<float*>(base);
data_vec[*counter] = fp64;
*counter += 1;
break;
}
case TRITONSERVER_TYPE_FP64: {
double fp64 = 0;
RETURN_IF_ERR(el.AsDouble(&fp64));
double* data_vec = reinterpret_cast<double*>(base);
data_vec[*counter] = fp64;
*counter += 1;
break;
}
case TRITONSERVER_TYPE_BYTES: {
const char* cstr;
size_t len = 0;
RETURN_IF_ERR(el.AsString(&cstr, &len));
if (static_cast<int64_t>(*counter + len + sizeof(uint32_t)) >
expected_cnt) {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
"Shape does not match true shape of 'data' field");
}
memcpy(
base + *counter, reinterpret_cast<char*>(&len), sizeof(uint32_t));
std::copy(cstr, cstr + len, base + *counter + sizeof(uint32_t));
*counter += len + sizeof(uint32_t);
break;
}
default:
break;
}
}
TRITONSERVER_ErrorDelete(assert_err);
}
return nullptr; // success
}
TRITONSERVER_Error*
ReadDataFromJson(
const char* tensor_name, triton::common::TritonJson::Value& tensor_data,
char* base, const TRITONSERVER_DataType dtype, int64_t expected_cnt)
{
int counter = 0;
switch (dtype) {
// FP16 not supported via JSON
case TRITONSERVER_TYPE_FP16:
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INVALID_ARG,
std::string(
"receiving FP16 data via JSON is not supported. Please use the "
"binary data format for input " +
std::string(tensor_name))
.c_str());
case TRITONSERVER_TYPE_INVALID:
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INVALID_ARG,
std::string("invalid datatype for input " + std::string(tensor_name))
.c_str());
default:
RETURN_MSG_IF_ERR(
ReadDataFromJsonHelper(
base, dtype, tensor_data, &counter, expected_cnt),
"Unable to parse 'data'");
break;
}
// Check if 'ReadDataFromJsonHelper' reads less than the expected byte size
if (counter != expected_cnt) {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
"Unable to parse 'data': Shape does not match true shape of 'data' "
"field");
}
return nullptr;
}
TRITONSERVER_Error*
WriteDataToJsonCheck(
const std::string& output_name, const size_t byte_size,
const size_t expected_size)
{
if (byte_size != expected_size) {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
std::string(
"output tensor shape does not match size of output for '" +
output_name + "'")
.c_str());
}
return nullptr; // success
}
TRITONSERVER_Error*
WriteDataToJson(
triton::common::TritonJson::Value* data_json,
const std::string& output_name, const TRITONSERVER_DataType datatype,
const void* base, const size_t byte_size, const size_t element_count)
{
switch (datatype) {
case TRITONSERVER_TYPE_BOOL: {
const uint8_t* bool_base = reinterpret_cast<const uint8_t*>(base);
if (byte_size != (element_count * sizeof(uint8_t))) {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
std::string(
"output tensor shape does not match size of output for '" +
output_name + "'")
.c_str());
}
for (size_t e = 0; e < element_count; ++e) {
data_json->AppendBool((bool_base[e] == 0) ? false : true);
}
break;
}
case TRITONSERVER_TYPE_UINT8: {
RETURN_IF_ERR(WriteDataToJsonCheck(
output_name, byte_size, sizeof(uint8_t) * element_count));
const uint8_t* cbase = reinterpret_cast<const uint8_t*>(base);
for (size_t e = 0; e < element_count; ++e) {
data_json->AppendUInt(cbase[e]);
}
break;
}
case TRITONSERVER_TYPE_UINT16: {
RETURN_IF_ERR(WriteDataToJsonCheck(
output_name, byte_size, sizeof(uint16_t) * element_count));
const uint16_t* cbase = reinterpret_cast<const uint16_t*>(base);
for (size_t e = 0; e < element_count; ++e) {
data_json->AppendUInt(cbase[e]);
}
break;
}
case TRITONSERVER_TYPE_UINT32: {
RETURN_IF_ERR(WriteDataToJsonCheck(
output_name, byte_size, sizeof(uint32_t) * element_count));
const uint32_t* cbase = reinterpret_cast<const uint32_t*>(base);
for (size_t e = 0; e < element_count; ++e) {
data_json->AppendUInt(cbase[e]);
}
break;
}
case TRITONSERVER_TYPE_UINT64: {
RETURN_IF_ERR(WriteDataToJsonCheck(
output_name, byte_size, sizeof(uint64_t) * element_count));
const uint64_t* cbase = reinterpret_cast<const uint64_t*>(base);
for (size_t e = 0; e < element_count; ++e) {
data_json->AppendUInt(cbase[e]);
}
break;
}
case TRITONSERVER_TYPE_INT8: {
RETURN_IF_ERR(WriteDataToJsonCheck(
output_name, byte_size, sizeof(int8_t) * element_count));
const int8_t* cbase = reinterpret_cast<const int8_t*>(base);
for (size_t e = 0; e < element_count; ++e) {
data_json->AppendInt(cbase[e]);
}
break;
}
case TRITONSERVER_TYPE_INT16: {
RETURN_IF_ERR(WriteDataToJsonCheck(
output_name, byte_size, sizeof(int16_t) * element_count));
const int16_t* cbase = reinterpret_cast<const int16_t*>(base);
for (size_t e = 0; e < element_count; ++e) {
data_json->AppendInt(cbase[e]);
}
break;
}
case TRITONSERVER_TYPE_INT32: {
RETURN_IF_ERR(WriteDataToJsonCheck(
output_name, byte_size, sizeof(int32_t) * element_count));
const int32_t* cbase = reinterpret_cast<const int32_t*>(base);
for (size_t e = 0; e < element_count; ++e) {
data_json->AppendInt(cbase[e]);
}
break;
}
case TRITONSERVER_TYPE_INT64: {
RETURN_IF_ERR(WriteDataToJsonCheck(
output_name, byte_size, sizeof(int64_t) * element_count));
const int64_t* cbase = reinterpret_cast<const int64_t*>(base);
for (size_t e = 0; e < element_count; ++e) {
data_json->AppendInt(cbase[e]);
}
break;
}
// FP16 not supported via JSON
case TRITONSERVER_TYPE_FP16:
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INVALID_ARG,
"sending FP16 data via JSON is not supported. Please use the "
"binary data format for output");
case TRITONSERVER_TYPE_FP32: {
RETURN_IF_ERR(WriteDataToJsonCheck(
output_name, byte_size, sizeof(float) * element_count));
const float* cbase = reinterpret_cast<const float*>(base);
for (size_t e = 0; e < element_count; ++e) {
data_json->AppendDouble(cbase[e]);
}
break;
}
case TRITONSERVER_TYPE_FP64: {
RETURN_IF_ERR(WriteDataToJsonCheck(
output_name, byte_size, sizeof(double) * element_count));
const double* cbase = reinterpret_cast<const double*>(base);
for (size_t e = 0; e < element_count; ++e) {
data_json->AppendDouble(cbase[e]);
}
break;
}
case TRITONSERVER_TYPE_BYTES: {
const char* cbase = reinterpret_cast<const char*>(base);
size_t offset = 0;
for (size_t e = 0; e < element_count; ++e) {
if ((offset + sizeof(uint32_t)) > byte_size) {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
std::string(
"output tensor shape does not match size of output for '" +
output_name + "'")
.c_str());
}
const size_t len = *(reinterpret_cast<const uint32_t*>(cbase + offset));
offset += sizeof(uint32_t);
if ((offset + len) > byte_size) {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INTERNAL,
std::string(
"output tensor shape does not match size of output for '" +
output_name + "'")
.c_str());
}
// Can use stringref because 'base' buffer is not deleted
// until response is deleted and that happens after this json
// is serialized.
data_json->AppendStringRef(cbase + offset, len);
offset += len;
}
break;
}
case TRITONSERVER_TYPE_INVALID:
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INVALID_ARG,
"Invalid data type for output tensor");
}
return nullptr; // success
}
void
EVBufferAddErrorJson(evbuffer* buffer, TRITONSERVER_Error* err)
{
const char* message = TRITONSERVER_ErrorMessage(err);
triton::common::TritonJson::Value response(
triton::common::TritonJson::ValueType::OBJECT);
response.AddStringRef("error", message, strlen(message));
triton::common::TritonJson::WriteBuffer buffer_json;
response.Write(&buffer_json);
evbuffer_add(buffer, buffer_json.Base(), buffer_json.Size());
}
TRITONSERVER_Error*
CheckBinaryInputData(
triton::common::TritonJson::Value& request_input, bool* is_binary,
size_t* byte_size)
{
*is_binary = false;
triton::common::TritonJson::Value params_json;
if (request_input.Find("parameters", ¶ms_json)) {
triton::common::TritonJson::Value binary_data_size_json;
if (params_json.Find("binary_data_size", &binary_data_size_json)) {
RETURN_MSG_IF_ERR(
binary_data_size_json.AsUInt(byte_size),
"Unable to parse 'binary_data_size'");
*is_binary = true;
}
}
return nullptr; // success
}
TRITONSERVER_Error*
CheckBinaryOutputData(
triton::common::TritonJson::Value& request_output, bool* is_binary)
{
*is_binary = false;
triton::common::TritonJson::Value params_json;
if (request_output.Find("parameters", ¶ms_json)) {
triton::common::TritonJson::Value binary_data_json;
if (params_json.Find("binary_data", &binary_data_json)) {
RETURN_MSG_IF_ERR(
binary_data_json.AsBool(is_binary), "Unable to parse 'binary_data'");
}
}
return nullptr; // success
}
TRITONSERVER_Error*
CheckSharedMemoryData(
triton::common::TritonJson::Value& request_input, bool* use_shm,
const char** shm_region, uint64_t* offset, uint64_t* byte_size)
{
*use_shm = false;
*offset = 0;
*byte_size = 0;
triton::common::TritonJson::Value params_json;
if (request_input.Find("parameters", ¶ms_json)) {
{
triton::common::TritonJson::Value region_json;
if (params_json.Find("shared_memory_region", ®ion_json)) {
*use_shm = true;
size_t len;
RETURN_MSG_IF_ERR(
region_json.AsString(shm_region, &len),
"Unable to parse 'shared_memory_region'");
}
}
{
triton::common::TritonJson::Value offset_json;
if (params_json.Find("shared_memory_offset", &offset_json)) {
RETURN_MSG_IF_ERR(
offset_json.AsUInt(offset),
"Unable to parse 'shared_memory_offset'");
}
}
{
triton::common::TritonJson::Value size_json;
if (params_json.Find("shared_memory_byte_size", &size_json)) {
RETURN_MSG_IF_ERR(
size_json.AsUInt(byte_size),
"Unable to parse 'shared_memory_byte_size'");
}
}
}
return nullptr; // success
}
TRITONSERVER_Error*
CheckClassificationOutput(
triton::common::TritonJson::Value& request_output, uint64_t* num_classes)
{
*num_classes = 0;
triton::common::TritonJson::Value params_json;
if (request_output.Find("parameters", ¶ms_json)) {
triton::common::TritonJson::Value cls_json;
if (params_json.Find("classification", &cls_json)) {
RETURN_MSG_IF_ERR(
cls_json.AsUInt(num_classes), "Unable to set 'classification'");
}
}
return nullptr; // success
}
TRITONSERVER_Error*
ValidateInputContentType(triton::common::TritonJson::Value& io)
{
bool has_data = false;
bool has_binary = false;
bool has_shared_memory = false;
has_data = io.Find("data");
triton::common::TritonJson::Value params_json;
if (io.Find("parameters", ¶ms_json)) {
has_binary = params_json.Find("binary_data_size");
has_shared_memory = params_json.Find("shared_memory_region");
}
int set_count = has_data + has_binary + has_shared_memory;
if (set_count != 1) {
std::string err_str =
"Input must set only one of the following fields: 'data', "
"'binary_data_size' in 'parameters', 'shared_memory_region' in "
"'parameters'. But";
if (set_count == 0) {
err_str += " no field is set";
} else {
err_str += " set";
if (has_data) {
err_str += " 'data'";
}
if (has_binary) {
err_str += " 'binary_data_size'";
}
if (has_shared_memory) {
err_str += " 'shared_memory_region'";
}
}
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INVALID_ARG, err_str.c_str());
}
return nullptr; // success
}
TRITONSERVER_Error*
ValidateOutputParameter(triton::common::TritonJson::Value& io)
{
triton::common::TritonJson::Value params_json;
if (io.Find("parameters", ¶ms_json)) {
const bool has_shared_memory = params_json.Find("shared_memory_region");
if (has_shared_memory) {
// Currently shared memory can't set with classification because
// cls results are not stored in shared memory, internally it is computed
// based on results in shared memory.
if (params_json.Find("classification")) {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INVALID_ARG,
"Output can't set both 'shared_memory_region' and "
"'classification'");
}
triton::common::TritonJson::Value binary_data_json;
if (params_json.Find("binary_data", &binary_data_json)) {
bool is_binary;
RETURN_MSG_IF_ERR(
binary_data_json.AsBool(&is_binary), "Unable to set 'binary_data'");
if (is_binary) {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INVALID_ARG,
"Output can't set both 'shared_memory_region' and 'binary_data'");
}
}
}
}
return nullptr; // success
}
TRITONSERVER_Error*
EVBufferToJson(
triton::common::TritonJson::Value* document, evbuffer_iovec* v, int* v_idx,
const size_t length, int n)
{
size_t offset = 0, remaining_length = length;
char* json_base;
std::vector<char> json_buffer;
// No need to memcpy when number of iovecs is 1
if ((n > 0) and (v[0].iov_len >= remaining_length)) {
json_base = static_cast<char*>(v[0].iov_base);
if (v[0].iov_len > remaining_length) {
v[0].iov_base = static_cast<void*>(json_base + remaining_length);
v[0].iov_len -= remaining_length;
remaining_length = 0;
} else if (v[0].iov_len == remaining_length) {
remaining_length = 0;
*v_idx += 1;
}
} else {
json_buffer.resize(length);
json_base = json_buffer.data();
while ((remaining_length > 0) && (*v_idx < n)) {
char* base = static_cast<char*>(v[*v_idx].iov_base);
size_t base_size;
if (v[*v_idx].iov_len > remaining_length) {
base_size = remaining_length;
v[*v_idx].iov_base = static_cast<void*>(base + remaining_length);
v[*v_idx].iov_len -= remaining_length;
remaining_length = 0;
} else {
base_size = v[*v_idx].iov_len;
remaining_length -= v[*v_idx].iov_len;
*v_idx += 1;
}
memcpy(json_base + offset, base, base_size);
offset += base_size;
}
}
if (remaining_length != 0) {
return TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_INVALID_ARG,
std::string(
"unexpected size for request JSON, expecting " +
std::to_string(remaining_length) + " more bytes")
.c_str());
}
RETURN_IF_ERR(document->Parse(json_base, length));
return nullptr; // success
}
std::string
CompressionTypeUsed(const std::string accept_encoding)
{
std::vector<std::string> encodings;
size_t offset = 0;
size_t delimeter_pos = accept_encoding.find(',');
while (delimeter_pos != std::string::npos) {
encodings.emplace_back(
accept_encoding.substr(offset, delimeter_pos - offset));
offset = delimeter_pos + 1;
delimeter_pos = accept_encoding.find(',', offset);
}
std::string res = "identity";
double weight = 0;
encodings.emplace_back(accept_encoding.substr(offset));
for (const auto& encoding : encodings) {
auto start_pos = encoding.find_first_not_of(' ');
auto weight_pos = encoding.find(";q=");
// Skip if the encoding is malformed
if ((start_pos == std::string::npos) ||
((weight_pos != std::string::npos) && (start_pos >= weight_pos))) {
continue;
}
const std::string type =
(weight_pos == std::string::npos)
? encoding.substr(start_pos)
: encoding.substr(start_pos, weight_pos - start_pos);
double type_weight = 1;
if (weight_pos != std::string::npos) {
try {
type_weight = std::stod(encoding.substr(weight_pos + 3));
}
catch (const std::invalid_argument& ia) {
continue;
}
}
if (((type == "identity") || (type == "deflate") || (type == "gzip")) &&
(type_weight > weight)) {
res = type;
weight = type_weight;
}
}
return res;
}
} // namespace
HTTPAPIServer::HTTPAPIServer(
const std::shared_ptr<TRITONSERVER_Server>& server,
nvidia::inferenceserver::TraceManager* trace_manager,
const std::shared_ptr<SharedMemoryManager>& shm_manager, const int32_t port,
const int thread_cnt)
: HTTPServer(port, thread_cnt), server_(server),
trace_manager_(trace_manager), shm_manager_(shm_manager),
allocator_(nullptr), server_regex_(R"(/v2(?:/health/(live|ready))?)"),
model_regex_(
R"(/v2/models/([^/]+)(?:/versions/([0-9]+))?(?:/(infer|ready|config|stats))?)"),
modelcontrol_regex_(
R"(/v2/repository(?:/([^/]+))?/(index|models/([^/]+)/(load|unload)))"),
systemsharedmemory_regex_(
R"(/v2/systemsharedmemory(?:/region/([^/]+))?/(status|register|unregister))"),
cudasharedmemory_regex_(
R"(/v2/cudasharedmemory(?:/region/([^/]+))?/(status|register|unregister))")
{
// FIXME, don't cache server metadata. The http endpoint should
// not be deciding that server metadata will not change during
// execution.
TRITONSERVER_Message* message = nullptr;
server_metadata_err_ = TRITONSERVER_ServerMetadata(server_.get(), &message);
if (server_metadata_err_ == nullptr) {
const char* buffer;
size_t byte_size;
server_metadata_err_ =
TRITONSERVER_MessageSerializeToJson(message, &buffer, &byte_size);
server_metadata_ = std::string(buffer, byte_size);
}
if (message != nullptr) {
TRITONSERVER_MessageDelete(message);
}
FAIL_IF_ERR(
TRITONSERVER_ResponseAllocatorNew(
&allocator_, InferResponseAlloc, InferResponseFree,
nullptr /* start_fn */),
"creating response allocator");
}
HTTPAPIServer::~HTTPAPIServer()
{
if (server_metadata_err_ != nullptr) {
TRITONSERVER_ErrorDelete(server_metadata_err_);
}
LOG_TRITONSERVER_ERROR(
TRITONSERVER_ResponseAllocatorDelete(allocator_),
"deleting response allocator");
}
TRITONSERVER_Error*
HTTPAPIServer::InferResponseAlloc(
TRITONSERVER_ResponseAllocator* allocator, const char* tensor_name,
size_t byte_size, TRITONSERVER_MemoryType preferred_memory_type,
int64_t preferred_memory_type_id, void* userp, void** buffer,
void** buffer_userp, TRITONSERVER_MemoryType* actual_memory_type,
int64_t* actual_memory_type_id)
{
AllocPayload* payload = reinterpret_cast<AllocPayload*>(userp);
std::unordered_map<std::string, AllocPayload::OutputInfo*>& output_map =
payload->output_map_;
const AllocPayload::OutputInfo::Kind default_output_kind =
payload->default_output_kind_;
*buffer = nullptr;
*buffer_userp = nullptr;
*actual_memory_type = preferred_memory_type;
*actual_memory_type_id = preferred_memory_type_id;
AllocPayload::OutputInfo* info = nullptr;