-
Notifications
You must be signed in to change notification settings - Fork 5.6k
Expand file tree
/
Copy pathgolang_filter.cc
More file actions
1760 lines (1542 loc) · 62.7 KB
/
Copy pathgolang_filter.cc
File metadata and controls
1760 lines (1542 loc) · 62.7 KB
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 "contrib/golang/filters/http/source/golang_filter.h"
#include <cstddef>
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
#include "envoy/http/codes.h"
#include "source/common/buffer/buffer_impl.h"
#include "source/common/common/base64.h"
#include "source/common/common/enum_to_int.h"
#include "source/common/common/lock_guard.h"
#include "source/common/common/utility.h"
#include "source/common/grpc/common.h"
#include "source/common/grpc/context_impl.h"
#include "source/common/grpc/status.h"
#include "source/common/http/headers.h"
#include "source/common/http/http1/codec_impl.h"
#include "source/extensions/filters/common/expr/context.h"
#include "eval/public/cel_value.h"
#include "eval/public/containers/field_access.h"
#include "eval/public/containers/field_backed_list_impl.h"
#include "eval/public/containers/field_backed_map_impl.h"
#include "eval/public/structs/cel_proto_wrapper.h"
namespace Envoy {
namespace Extensions {
namespace HttpFilters {
namespace Golang {
void Filter::onHeadersModified() {
// Any changes to request headers can affect how the request is going to be
// routed. If we are changing the headers we also need to clear the route
// cache.
decoding_state_.getFilterCallbacks()->downstreamCallbacks()->clearRouteCache();
}
Http::LocalErrorStatus Filter::onLocalReply(const LocalReplyData& data) {
auto& state = getProcessorState();
ASSERT(state.isThreadSafe());
ENVOY_LOG(debug, "golang filter onLocalReply, state: {}, phase: {}, code: {}", state.stateStr(),
state.phaseStr(), int(data.code_));
return Http::LocalErrorStatus::Continue;
}
Http::FilterHeadersStatus Filter::decodeHeaders(Http::RequestHeaderMap& headers, bool end_stream) {
ProcessorState& state = decoding_state_;
ENVOY_LOG(debug, "golang filter decodeHeaders, state: {}, phase: {}, end_stream: {}",
state.stateStr(), state.phaseStr(), end_stream);
request_headers_ = &headers;
state.setEndStream(end_stream);
bool done = doHeaders(state, headers, end_stream);
return done ? Http::FilterHeadersStatus::Continue : Http::FilterHeadersStatus::StopIteration;
}
Http::FilterDataStatus Filter::decodeData(Buffer::Instance& data, bool end_stream) {
ProcessorState& state = decoding_state_;
ENVOY_LOG(debug,
"golang filter decodeData, state: {}, phase: {}, data length: {}, end_stream: {}",
state.stateStr(), state.phaseStr(), data.length(), end_stream);
state.setEndStream(end_stream);
bool done = doData(state, data, end_stream);
if (done) {
state.doDataList.moveOut(data);
return Http::FilterDataStatus::Continue;
}
return Http::FilterDataStatus::StopIterationNoBuffer;
}
Http::FilterTrailersStatus Filter::decodeTrailers(Http::RequestTrailerMap& trailers) {
ProcessorState& state = decoding_state_;
ENVOY_LOG(debug, "golang filter decodeTrailers, state: {}, phase: {}", state.stateStr(),
state.phaseStr());
state.setSeenTrailers();
bool done = doTrailer(state, trailers);
return done ? Http::FilterTrailersStatus::Continue : Http::FilterTrailersStatus::StopIteration;
}
Http::FilterHeadersStatus Filter::encodeHeaders(Http::ResponseHeaderMap& headers, bool end_stream) {
ProcessorState& state = getProcessorState();
ENVOY_LOG(debug, "golang filter encodeHeaders, state: {}, phase: {}, end_stream: {}",
state.stateStr(), state.phaseStr(), end_stream);
encoding_state_.setEndStream(end_stream);
// NP: may enter encodeHeaders in any phase & any state_,
// since other filters or filtermanager could call encodeHeaders or sendLocalReply in any time.
// eg. filtermanager may invoke sendLocalReply, when scheme is invalid,
// with "Sending local reply with details // http1.invalid_scheme" details.
if (state.state() != FilterState::Done) {
ENVOY_LOG(debug,
"golang filter enter encodeHeaders early, maybe sendLocalReply or encodeHeaders "
"happened, current state: {}, phase: {}",
state.stateStr(), state.phaseStr());
ENVOY_LOG(debug, "golang filter drain data buffer since enter encodeHeaders early");
// NP: is safe to overwrite it since go code won't read it directly
// need drain buffer to enable read when it's high watermark
state.drainBufferData();
// get the state before changing it.
bool in_go = state.isProcessingInGo();
if (in_go) {
// NP: wait go returns to avoid concurrency conflict in go side.
local_reply_waiting_go_ = true;
ENVOY_LOG(debug, "waiting go returns before handle the local reply from other filter");
// NP: save to another local_headers_ variable to avoid conflict,
// since the headers_ may be used in Go side.
local_headers_ = &headers;
// can not use "StopAllIterationAndWatermark" here, since Go decodeHeaders may return
// stopAndBuffer, that means it need data buffer and not continue header.
return Http::FilterHeadersStatus::StopIteration;
} else {
ENVOY_LOG(debug, "golang filter clear do data buffer before continue encodeHeader, "
"since no go code is running");
state.doDataList.clearAll();
}
}
enter_encoding_ = true;
bool done = doHeaders(encoding_state_, headers, end_stream);
return done ? Http::FilterHeadersStatus::Continue : Http::FilterHeadersStatus::StopIteration;
}
Http::FilterDataStatus Filter::encodeData(Buffer::Instance& data, bool end_stream) {
ProcessorState& state = getProcessorState();
ENVOY_LOG(debug,
"golang filter encodeData, state: {}, phase: {}, data length: {}, end_stream: {}",
state.stateStr(), state.phaseStr(), data.length(), end_stream);
encoding_state_.setEndStream(end_stream);
if (local_reply_waiting_go_) {
ENVOY_LOG(debug, "golang filter appending data to buffer");
encoding_state_.addBufferData(data);
return Http::FilterDataStatus::StopIterationNoBuffer;
}
bool done = doData(encoding_state_, data, end_stream);
if (done) {
state.doDataList.moveOut(data);
return Http::FilterDataStatus::Continue;
}
return Http::FilterDataStatus::StopIterationNoBuffer;
}
Http::FilterTrailersStatus Filter::encodeTrailers(Http::ResponseTrailerMap& trailers) {
ProcessorState& state = getProcessorState();
ENVOY_LOG(debug, "golang filter encodeTrailers, state: {}, phase: {}", state.stateStr(),
state.phaseStr());
encoding_state_.setSeenTrailers();
if (local_reply_waiting_go_) {
// NP: save to another local_trailers_ variable to avoid conflict,
// since the trailers_ may be used in Go side.
local_trailers_ = &trailers;
return Http::FilterTrailersStatus::StopIteration;
}
bool done = doTrailer(encoding_state_, trailers);
return done ? Http::FilterTrailersStatus::Continue : Http::FilterTrailersStatus::StopIteration;
}
void Filter::onDestroy() {
ENVOY_LOG(debug, "golang filter on destroy");
// do nothing, stream reset may happen before entering this filter.
if (req_ == nullptr) {
return;
}
{
Thread::LockGuard lock(mutex_);
if (has_destroyed_) {
ENVOY_LOG(debug, "golang filter has been destroyed");
return;
}
has_destroyed_ = true;
}
auto& state = getProcessorState();
auto reason = state.isProcessingInGo() ? DestroyReason::Terminate : DestroyReason::Normal;
dynamic_lib_->envoyGoFilterOnHttpDestroy(req_, int(reason));
}
// access_log is executed before the log of the stream filter
void Filter::log(const Formatter::HttpFormatterContext& log_context,
const StreamInfo::StreamInfo&) {
// `log` may be called multiple times with different log type
switch (log_context.accessLogType()) {
case Envoy::AccessLog::AccessLogType::DownstreamStart:
case Envoy::AccessLog::AccessLogType::DownstreamPeriodic:
case Envoy::AccessLog::AccessLogType::DownstreamEnd: {
auto& state = getProcessorState();
if (req_ == nullptr) {
// log called by AccessLogDownstreamStart will happen before doHeaders
initRequest(state);
request_headers_ = static_cast<Http::RequestOrResponseHeaderMap*>(
const_cast<Http::RequestHeaderMap*>(&log_context.requestHeaders()));
}
state.enterLog();
req_->phase = static_cast<int>(state.phase());
dynamic_lib_->envoyGoFilterOnHttpLog(req_, int(log_context.accessLogType()));
state.leaveLog();
} break;
default:
// skip calling with unsupported log types
break;
}
}
/*** common APIs for filter, both decode and encode ***/
GolangStatus Filter::doHeadersGo(ProcessorState& state, Http::RequestOrResponseHeaderMap& headers,
bool end_stream) {
ENVOY_LOG(debug, "golang filter passing data to golang, state: {}, phase: {}, end_stream: {}",
state.stateStr(), state.phaseStr(), end_stream);
if (req_ == nullptr) {
initRequest(state);
}
req_->phase = static_cast<int>(state.phase());
{
Thread::LockGuard lock(mutex_);
headers_ = &headers;
}
auto status = dynamic_lib_->envoyGoFilterOnHttpHeader(req_, end_stream ? 1 : 0, headers.size(),
headers.byteSize());
return static_cast<GolangStatus>(status);
}
bool Filter::doHeaders(ProcessorState& state, Http::RequestOrResponseHeaderMap& headers,
bool end_stream) {
ENVOY_LOG(debug, "golang filter doHeaders, state: {}, phase: {}, end_stream: {}",
state.stateStr(), state.phaseStr(), end_stream);
ASSERT(state.isBufferDataEmpty());
state.processHeader(end_stream);
auto status = doHeadersGo(state, headers, end_stream);
auto done = state.handleHeaderGolangStatus(status);
if (done) {
Thread::LockGuard lock(mutex_);
headers_ = nullptr;
}
return done;
}
bool Filter::doDataGo(ProcessorState& state, Buffer::Instance& data, bool end_stream) {
ENVOY_LOG(debug, "golang filter passing data to golang, state: {}, phase: {}, end_stream: {}",
state.stateStr(), state.phaseStr(), end_stream);
state.processData(end_stream);
Buffer::Instance& buffer = state.doDataList.push(data);
ASSERT(req_ != nullptr);
req_->phase = static_cast<int>(state.phase());
auto status = dynamic_lib_->envoyGoFilterOnHttpData(
req_, end_stream ? 1 : 0, reinterpret_cast<uint64_t>(&buffer), buffer.length());
return state.handleDataGolangStatus(static_cast<GolangStatus>(status));
}
bool Filter::doData(ProcessorState& state, Buffer::Instance& data, bool end_stream) {
ENVOY_LOG(debug, "golang filter doData, state: {}, phase: {}, end_stream: {}", state.stateStr(),
state.phaseStr(), end_stream);
bool done = false;
switch (state.state()) {
case FilterState::WaitingData:
done = doDataGo(state, data, end_stream);
break;
case FilterState::WaitingAllData:
if (end_stream) {
if (!state.isBufferDataEmpty()) {
// NP: new data = data_buffer_ + data
state.addBufferData(data);
data.move(state.getBufferData());
}
// check state again since data_buffer may be full and sendLocalReply with 413.
// TODO: better not trigger 413 here.
if (state.state() == FilterState::WaitingAllData) {
done = doDataGo(state, data, end_stream);
}
break;
}
// NP: not break, continue
FALLTHRU;
case FilterState::ProcessingHeader:
case FilterState::ProcessingData:
ENVOY_LOG(debug, "golang filter appending data to buffer");
state.addBufferData(data);
break;
default:
ENVOY_LOG(error, "unexpected state: {}", state.stateStr());
// TODO: terminate stream?
break;
}
ENVOY_LOG(debug, "golang filter doData, return: {}", done);
return done;
}
bool Filter::doTrailerGo(ProcessorState& state, Http::HeaderMap& trailers) {
ENVOY_LOG(debug, "golang filter passing trailers to golang, state: {}, phase: {}",
state.stateStr(), state.phaseStr());
state.processTrailer();
ASSERT(req_ != nullptr);
req_->phase = static_cast<int>(state.phase());
auto status =
dynamic_lib_->envoyGoFilterOnHttpHeader(req_, 1, trailers.size(), trailers.byteSize());
return state.handleTrailerGolangStatus(static_cast<GolangStatus>(status));
}
bool Filter::doTrailer(ProcessorState& state, Http::HeaderMap& trailers) {
ENVOY_LOG(debug, "golang filter doTrailer, state: {}, phase: {}", state.stateStr(),
state.phaseStr());
ASSERT(!state.getEndStream() && !state.isProcessingEndStream());
{
Thread::LockGuard lock(mutex_);
trailers_ = &trailers;
}
bool done = false;
Buffer::OwnedImpl body;
switch (state.state()) {
case FilterState::WaitingTrailer:
done = doTrailerGo(state, trailers);
break;
case FilterState::WaitingData:
done = doTrailerGo(state, trailers);
break;
case FilterState::WaitingAllData:
ENVOY_LOG(debug, "golang filter data buffer is empty: {}", state.isBufferDataEmpty());
// do data first
if (!state.isBufferDataEmpty()) {
done = doDataGo(state, state.getBufferData(), false);
// NP: can not use done as condition here, since done will be false
// maybe we can remove the done variable totally? by using state_ only?
// continue trailers
if (state.state() == FilterState::WaitingTrailer) {
state.continueDoData();
done = doTrailerGo(state, trailers);
}
} else {
state.continueDoData();
done = doTrailerGo(state, trailers);
}
break;
case FilterState::ProcessingHeader:
case FilterState::ProcessingData:
// do nothing, wait previous task
break;
default:
ENVOY_LOG(error, "unexpected state: {}", state.stateStr());
// TODO: terminate stream?
break;
}
ENVOY_LOG(debug, "golang filter doTrailer, return: {}", done);
return done;
}
/*** APIs for go call C ***/
void Filter::continueEncodeLocalReply(ProcessorState& state) {
ENVOY_LOG(debug,
"golang filter continue encodeHeader(local reply from other filters) after return from "
"go, current state: {}, phase: {}",
state.stateStr(), state.phaseStr());
ENVOY_LOG(debug, "golang filter drain do data buffer before continueEncodeLocalReply");
state.doDataList.clearAll();
local_reply_waiting_go_ = false;
// should use encoding_state_ now
enter_encoding_ = true;
auto header_end_stream = encoding_state_.getEndStream();
if (local_trailers_ != nullptr) {
Thread::LockGuard lock(mutex_);
trailers_ = local_trailers_;
header_end_stream = false;
}
if (!encoding_state_.isBufferDataEmpty()) {
header_end_stream = false;
}
// NP: we not overwrite state end_stream in doHeadersGo
encoding_state_.processHeader(header_end_stream);
auto status = doHeadersGo(encoding_state_, *local_headers_, header_end_stream);
continueStatusInternal(status);
}
void Filter::continueStatusInternal(GolangStatus status) {
ProcessorState& state = getProcessorState();
ASSERT(state.isThreadSafe());
auto saved_state = state.state();
if (local_reply_waiting_go_) {
ENVOY_LOG(debug,
"other filter already trigger sendLocalReply, ignoring the continue status: {}, "
"state: {}, phase: {}",
int(status), state.stateStr(), state.phaseStr());
continueEncodeLocalReply(state);
return;
}
auto done = state.handleGolangStatus(status);
if (done) {
switch (saved_state) {
case FilterState::ProcessingHeader:
// NP: should process data first filter seen the stream is end but go doesn't,
// otherwise, the next filter will continue with end_stream = true.
// NP: it is safe to continueDoData after continueProcessing
// that means injectDecodedDataToFilterChain after continueDecoding while stream is not end
if (state.isProcessingEndStream() || !state.isStreamEnd()) {
state.continueProcessing();
}
break;
case FilterState::ProcessingData:
state.continueDoData();
break;
case FilterState::ProcessingTrailer:
state.continueDoData();
state.continueProcessing();
break;
default:
ASSERT(0, "unexpected state");
}
}
// TODO: state should also grow in this case
// state == WaitingData && bufferData is empty && seen trailers
auto current_state = state.state();
if ((current_state == FilterState::WaitingData &&
(!state.isBufferDataEmpty() || state.getEndStream())) ||
(current_state == FilterState::WaitingAllData && state.isStreamEnd())) {
auto done = doDataGo(state, state.getBufferData(), state.getEndStream());
if (done) {
state.continueDoData();
} else {
// do not process trailers when data is not finished
return;
}
}
Thread::ReleasableLockGuard lock(mutex_);
if (state.state() == FilterState::WaitingTrailer && trailers_ != nullptr) {
auto trailers = trailers_;
lock.release();
auto done = doTrailerGo(state, *trailers);
if (done) {
state.continueProcessing();
}
}
}
void Filter::sendLocalReplyInternal(
Http::Code response_code, absl::string_view body_text,
std::function<void(Http::ResponseHeaderMap& headers)> modify_headers,
Grpc::Status::GrpcStatus grpc_status, absl::string_view details) {
ENVOY_LOG(debug, "sendLocalReply Internal, response code: {}", int(response_code));
ProcessorState& state = getProcessorState();
if (local_reply_waiting_go_) {
ENVOY_LOG(debug,
"other filter already invoked sendLocalReply or encodeHeaders, ignoring the local "
"reply from go, code: {}, body: {}, details: {}",
int(response_code), body_text, details);
continueEncodeLocalReply(state);
return;
}
ENVOY_LOG(debug, "golang filter drain do data buffer before sendLocalReply");
state.doDataList.clearAll();
// drain buffer data if it's not empty, before sendLocalReply
state.drainBufferData();
state.sendLocalReply(response_code, body_text, modify_headers, grpc_status, details);
}
CAPIStatus
Filter::sendLocalReply(Http::Code response_code, std::string body_text,
std::function<void(Http::ResponseHeaderMap& headers)> modify_headers,
Grpc::Status::GrpcStatus grpc_status, std::string details) {
// lock until this function return since it may running in a Go thread.
Thread::LockGuard lock(mutex_);
if (has_destroyed_) {
ENVOY_LOG(debug, "golang filter has been destroyed");
return CAPIStatus::CAPIFilterIsDestroy;
}
auto& state = getProcessorState();
if (!state.isProcessingInGo()) {
ENVOY_LOG(debug, "golang filter is not processing Go");
return CAPIStatus::CAPINotInGo;
}
ENVOY_LOG(debug, "sendLocalReply, response code: {}", int(response_code));
auto weak_ptr = weak_from_this();
state.getDispatcher().post(
[this, &state, weak_ptr, response_code, body_text, modify_headers, grpc_status, details] {
if (!weak_ptr.expired() && !hasDestroyed()) {
ASSERT(state.isThreadSafe());
sendLocalReplyInternal(response_code, body_text, modify_headers, grpc_status, details);
} else {
ENVOY_LOG(debug, "golang filter has gone or destroyed in sendLocalReply");
}
});
return CAPIStatus::CAPIOK;
};
CAPIStatus Filter::sendPanicReply(absl::string_view details) {
config_->stats().panic_error_.inc();
ENVOY_LOG(error, "[go_plugin_http][{}] {}", config_->pluginName(),
absl::StrCat("filter paniced with error details: ", details));
// We choose not to pass along the details in the response because
// we don't want to leak the operational details of the service for security reasons.
// Operators should be able to view the details via the log message above
// and use the stats for o11y
return sendLocalReply(Http::Code::InternalServerError, "error happened in filter\r\n", nullptr,
Grpc::Status::WellKnownGrpcStatus::Ok, "");
}
CAPIStatus Filter::continueStatus(GolangStatus status) {
// lock until this function return since it may running in a Go thread.
Thread::LockGuard lock(mutex_);
if (has_destroyed_) {
ENVOY_LOG(debug, "golang filter has been destroyed");
return CAPIStatus::CAPIFilterIsDestroy;
}
auto& state = getProcessorState();
if (!state.isProcessingInGo()) {
ENVOY_LOG(debug, "golang filter is not processing Go");
return CAPIStatus::CAPINotInGo;
}
ENVOY_LOG(debug, "golang filter continue from Go, status: {}, state: {}, phase: {}", int(status),
state.stateStr(), state.phaseStr());
auto weak_ptr = weak_from_this();
// TODO: skip post event to dispatcher, and return continue in the caller,
// when it's invoked in the current envoy thread, for better performance & latency.
state.getDispatcher().post([this, &state, weak_ptr, status] {
if (!weak_ptr.expired() && !hasDestroyed()) {
ASSERT(state.isThreadSafe());
continueStatusInternal(status);
} else {
ENVOY_LOG(debug, "golang filter has gone or destroyed in continueStatus event");
}
});
return CAPIStatus::CAPIOK;
}
CAPIStatus Filter::getHeader(absl::string_view key, uint64_t* value_data, int* value_len) {
Thread::LockGuard lock(mutex_);
if (has_destroyed_) {
ENVOY_LOG(debug, "golang filter has been destroyed");
return CAPIStatus::CAPIFilterIsDestroy;
}
auto& state = getProcessorState();
if (!state.isProcessingInGo()) {
ENVOY_LOG(debug, "golang filter is not processing Go");
return CAPIStatus::CAPINotInGo;
}
auto m = state.isProcessingHeader() ? headers_ : trailers_;
if (m == nullptr) {
ENVOY_LOG(debug, "invoking cgo api at invalid phase: {}", __func__);
return CAPIStatus::CAPIInvalidPhase;
}
auto result = m->get(Http::LowerCaseString(key));
if (!result.empty()) {
auto str = result[0]->value().getStringView();
*value_data = reinterpret_cast<uint64_t>(str.data());
*value_len = str.length();
}
return CAPIStatus::CAPIOK;
}
void copyHeaderMapToGo(Http::HeaderMap& m, GoString* go_strs, char* go_buf) {
auto i = 0;
m.iterate([&i, &go_strs, &go_buf](const Http::HeaderEntry& header) -> Http::HeaderMap::Iterate {
auto key = std::string(header.key().getStringView());
auto value = std::string(header.value().getStringView());
auto len = key.length();
// go_strs is the heap memory of go, and the length is twice the number of headers. So range it
// is safe.
go_strs[i].n = len;
go_strs[i].p = go_buf;
// go_buf is the heap memory of go, and the length is the total length of all keys and values in
// the header. So use memcpy is safe.
memcpy(go_buf, key.data(), len); // NOLINT(safe-memcpy)
go_buf += len;
i++;
len = value.length();
go_strs[i].n = len;
go_strs[i].p = go_buf;
memcpy(go_buf, value.data(), len); // NOLINT(safe-memcpy)
go_buf += len;
i++;
return Http::HeaderMap::Iterate::Continue;
});
}
CAPIStatus Filter::copyHeaders(GoString* go_strs, char* go_buf) {
Thread::LockGuard lock(mutex_);
if (has_destroyed_) {
ENVOY_LOG(debug, "golang filter has been destroyed");
return CAPIStatus::CAPIFilterIsDestroy;
}
auto& state = getProcessorState();
if (!state.isProcessingInGo()) {
ENVOY_LOG(debug, "golang filter is not processing Go");
return CAPIStatus::CAPINotInGo;
}
if (headers_ == nullptr) {
ENVOY_LOG(debug, "invoking cgo api at invalid phase: {}", __func__);
return CAPIStatus::CAPIInvalidPhase;
}
copyHeaderMapToGo(*headers_, go_strs, go_buf);
return CAPIStatus::CAPIOK;
}
// It won't take affect immidiately while it's invoked from a Go thread, instead, it will post a
// callback to run in the envoy worker thread.
CAPIStatus Filter::setHeader(absl::string_view key, absl::string_view value, headerAction act) {
Thread::LockGuard lock(mutex_);
if (has_destroyed_) {
ENVOY_LOG(debug, "golang filter has been destroyed");
return CAPIStatus::CAPIFilterIsDestroy;
}
auto& state = getProcessorState();
if (!state.isProcessingInGo()) {
ENVOY_LOG(debug, "golang filter is not processing Go");
return CAPIStatus::CAPINotInGo;
}
if (headers_ == nullptr) {
ENVOY_LOG(debug, "invoking cgo api at invalid phase: {}", __func__);
return CAPIStatus::CAPIInvalidPhase;
}
if (state.isThreadSafe()) {
// it's safe to write header in the safe thread.
switch (act) {
case HeaderAdd:
headers_->addCopy(Http::LowerCaseString(key), value);
break;
case HeaderSet:
headers_->setCopy(Http::LowerCaseString(key), value);
break;
default:
RELEASE_ASSERT(false, absl::StrCat("unknown header action: ", act));
}
onHeadersModified();
} else {
// should deep copy the string_view before post to dipatcher callback.
auto key_str = std::string(key);
auto value_str = std::string(value);
auto weak_ptr = weak_from_this();
// dispatch a callback to write header in the envoy safe thread, to make the write operation
// safety. otherwise, there might be race between reading in the envoy worker thread and writing
// in the Go thread.
state.getDispatcher().post([this, weak_ptr, key_str, value_str, act] {
if (!weak_ptr.expired() && !hasDestroyed()) {
Thread::LockGuard lock(mutex_);
switch (act) {
case HeaderAdd:
headers_->addCopy(Http::LowerCaseString(key_str), value_str);
break;
case HeaderSet:
headers_->setCopy(Http::LowerCaseString(key_str), value_str);
break;
default:
RELEASE_ASSERT(false, absl::StrCat("unknown header action: ", act));
}
onHeadersModified();
} else {
ENVOY_LOG(debug, "golang filter has gone or destroyed in setHeader");
}
});
}
return CAPIStatus::CAPIOK;
}
// It won't take affect immidiately while it's invoked from a Go thread, instead, it will post a
// callback to run in the envoy worker thread.
CAPIStatus Filter::removeHeader(absl::string_view key) {
Thread::LockGuard lock(mutex_);
if (has_destroyed_) {
ENVOY_LOG(debug, "golang filter has been destroyed");
return CAPIStatus::CAPIFilterIsDestroy;
}
auto& state = getProcessorState();
if (!state.isProcessingInGo()) {
ENVOY_LOG(debug, "golang filter is not processing Go");
return CAPIStatus::CAPINotInGo;
}
if (headers_ == nullptr) {
ENVOY_LOG(debug, "invoking cgo api at invalid phase: {}", __func__);
return CAPIStatus::CAPIInvalidPhase;
}
if (state.isThreadSafe()) {
// it's safe to write header in the safe thread.
headers_->remove(Http::LowerCaseString(key));
onHeadersModified();
} else {
// should deep copy the string_view before post to dipatcher callback.
auto key_str = std::string(key);
auto weak_ptr = weak_from_this();
// dispatch a callback to write header in the envoy safe thread, to make the write operation
// safety. otherwise, there might be race between reading in the envoy worker thread and writing
// in the Go thread.
state.getDispatcher().post([this, weak_ptr, key_str] {
if (!weak_ptr.expired() && !hasDestroyed()) {
Thread::LockGuard lock(mutex_);
headers_->remove(Http::LowerCaseString(key_str));
onHeadersModified();
} else {
ENVOY_LOG(debug, "golang filter has gone or destroyed in removeHeader");
}
});
}
return CAPIStatus::CAPIOK;
}
CAPIStatus Filter::copyBuffer(Buffer::Instance* buffer, char* data) {
// lock until this function return since it may running in a Go thread.
Thread::LockGuard lock(mutex_);
if (has_destroyed_) {
ENVOY_LOG(debug, "golang filter has been destroyed");
return CAPIStatus::CAPIFilterIsDestroy;
}
auto& state = getProcessorState();
if (!state.isProcessingInGo()) {
ENVOY_LOG(debug, "golang filter is not processing Go");
return CAPIStatus::CAPINotInGo;
}
if (!state.doDataList.checkExisting(buffer)) {
ENVOY_LOG(debug, "invoking cgo api at invalid phase: {}", __func__);
return CAPIStatus::CAPIInvalidPhase;
}
for (const Buffer::RawSlice& slice : buffer->getRawSlices()) {
// data is the heap memory of go, and the length is the total length of buffer. So use memcpy is
// safe.
memcpy(data, static_cast<const char*>(slice.mem_), slice.len_); // NOLINT(safe-memcpy)
data += slice.len_;
}
return CAPIStatus::CAPIOK;
}
CAPIStatus Filter::drainBuffer(Buffer::Instance* buffer, uint64_t length) {
// lock until this function return since it may running in a Go thread.
Thread::LockGuard lock(mutex_);
if (has_destroyed_) {
ENVOY_LOG(debug, "golang filter has been destroyed");
return CAPIStatus::CAPIFilterIsDestroy;
}
auto& state = getProcessorState();
if (!state.isProcessingInGo()) {
ENVOY_LOG(debug, "golang filter is not processing Go");
return CAPIStatus::CAPINotInGo;
}
if (!state.doDataList.checkExisting(buffer)) {
ENVOY_LOG(debug, "invoking cgo api at invalid phase: {}", __func__);
return CAPIStatus::CAPIInvalidPhase;
}
buffer->drain(length);
return CAPIStatus::CAPIOK;
}
CAPIStatus Filter::setBufferHelper(Buffer::Instance* buffer, absl::string_view& value,
bufferAction action) {
// lock until this function return since it may running in a Go thread.
Thread::LockGuard lock(mutex_);
if (has_destroyed_) {
ENVOY_LOG(debug, "golang filter has been destroyed");
return CAPIStatus::CAPIFilterIsDestroy;
}
auto& state = getProcessorState();
if (!state.isProcessingInGo()) {
ENVOY_LOG(debug, "golang filter is not processing Go");
return CAPIStatus::CAPINotInGo;
}
if (!state.doDataList.checkExisting(buffer)) {
ENVOY_LOG(debug, "invoking cgo api at invalid phase: {}", __func__);
return CAPIStatus::CAPIInvalidPhase;
}
if (action == bufferAction::Set) {
buffer->drain(buffer->length());
buffer->add(value);
} else if (action == bufferAction::Prepend) {
buffer->prepend(value);
} else {
buffer->add(value);
}
return CAPIStatus::CAPIOK;
}
CAPIStatus Filter::copyTrailers(GoString* go_strs, char* go_buf) {
Thread::LockGuard lock(mutex_);
if (has_destroyed_) {
ENVOY_LOG(debug, "golang filter has been destroyed");
return CAPIStatus::CAPIFilterIsDestroy;
}
auto& state = getProcessorState();
if (!state.isProcessingInGo()) {
ENVOY_LOG(debug, "golang filter is not processing Go");
return CAPIStatus::CAPINotInGo;
}
if (trailers_ == nullptr) {
ENVOY_LOG(debug, "invoking cgo api at invalid phase: {}", __func__);
return CAPIStatus::CAPIInvalidPhase;
}
copyHeaderMapToGo(*trailers_, go_strs, go_buf);
return CAPIStatus::CAPIOK;
}
CAPIStatus Filter::setTrailer(absl::string_view key, absl::string_view value, headerAction act) {
Thread::LockGuard lock(mutex_);
if (has_destroyed_) {
ENVOY_LOG(debug, "golang filter has been destroyed");
return CAPIStatus::CAPIFilterIsDestroy;
}
auto& state = getProcessorState();
if (!state.isProcessingInGo()) {
ENVOY_LOG(debug, "golang filter is not processing Go");
return CAPIStatus::CAPINotInGo;
}
if (trailers_ == nullptr) {
ENVOY_LOG(debug, "invoking cgo api at invalid phase: {}", __func__);
return CAPIStatus::CAPIInvalidPhase;
}
if (state.isThreadSafe()) {
switch (act) {
case HeaderAdd:
trailers_->addCopy(Http::LowerCaseString(key), value);
break;
case HeaderSet:
trailers_->setCopy(Http::LowerCaseString(key), value);
break;
default:
RELEASE_ASSERT(false, absl::StrCat("unknown header action: ", act));
}
} else {
// should deep copy the string_view before post to dipatcher callback.
auto key_str = std::string(key);
auto value_str = std::string(value);
auto weak_ptr = weak_from_this();
// dispatch a callback to write trailer in the envoy safe thread, to make the write operation
// safety. otherwise, there might be race between reading in the envoy worker thread and
// writing in the Go thread.
state.getDispatcher().post([this, weak_ptr, key_str, value_str, act] {
if (!weak_ptr.expired() && !hasDestroyed()) {
Thread::LockGuard lock(mutex_);
switch (act) {
case HeaderAdd:
trailers_->addCopy(Http::LowerCaseString(key_str), value_str);
break;
case HeaderSet:
trailers_->setCopy(Http::LowerCaseString(key_str), value_str);
break;
default:
RELEASE_ASSERT(false, absl::StrCat("unknown header action: ", act));
}
} else {
ENVOY_LOG(debug, "golang filter has gone or destroyed in setTrailer");
}
});
}
return CAPIStatus::CAPIOK;
}
CAPIStatus Filter::removeTrailer(absl::string_view key) {
Thread::LockGuard lock(mutex_);
if (has_destroyed_) {
ENVOY_LOG(debug, "golang filter has been destroyed");
return CAPIStatus::CAPIFilterIsDestroy;
}
auto& state = getProcessorState();
if (!state.isProcessingInGo()) {
ENVOY_LOG(debug, "golang filter is not processing Go");
return CAPIStatus::CAPINotInGo;
}
if (trailers_ == nullptr) {
ENVOY_LOG(debug, "invoking cgo api at invalid phase: {}", __func__);
return CAPIStatus::CAPIInvalidPhase;
}
if (state.isThreadSafe()) {
trailers_->remove(Http::LowerCaseString(key));
} else {
// should deep copy the string_view before post to dipatcher callback.
auto key_str = std::string(key);
auto weak_ptr = weak_from_this();
// dispatch a callback to write trailer in the envoy safe thread, to make the write operation
// safety. otherwise, there might be race between reading in the envoy worker thread and writing
// in the Go thread.
state.getDispatcher().post([this, weak_ptr, key_str] {
if (!weak_ptr.expired() && !hasDestroyed()) {
Thread::LockGuard lock(mutex_);
trailers_->remove(Http::LowerCaseString(key_str));
} else {
ENVOY_LOG(debug, "golang filter has gone or destroyed in removeTrailer");
}
});
}
return CAPIStatus::CAPIOK;
}
CAPIStatus Filter::getIntegerValue(int id, uint64_t* value) {
// lock until this function return since it may running in a Go thread.
Thread::LockGuard lock(mutex_);
if (has_destroyed_) {
ENVOY_LOG(debug, "golang filter has been destroyed");
return CAPIStatus::CAPIFilterIsDestroy;
}
auto& state = getProcessorState();
if (!state.isProcessingInGo()) {
ENVOY_LOG(debug, "golang filter is not processing Go");
return CAPIStatus::CAPINotInGo;
}
switch (static_cast<EnvoyValue>(id)) {
case EnvoyValue::Protocol:
if (!state.streamInfo().protocol().has_value()) {
return CAPIStatus::CAPIValueNotFound;
}
*value = static_cast<uint64_t>(state.streamInfo().protocol().value());
break;
case EnvoyValue::ResponseCode:
if (!state.streamInfo().responseCode().has_value()) {
return CAPIStatus::CAPIValueNotFound;
}
*value = state.streamInfo().responseCode().value();
break;
case EnvoyValue::AttemptCount: