-
Notifications
You must be signed in to change notification settings - Fork 13
/
mcbp_session.cxx
1952 lines (1807 loc) · 84.2 KB
/
mcbp_session.cxx
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
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2020-2021 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mcbp_session.hxx"
#include "core/config_listener.hxx"
#include "core/diagnostics.hxx"
#include "core/impl/bootstrap_state_listener.hxx"
#include "core/logger/logger.hxx"
#include "core/mcbp/codec.hxx"
#include "core/mcbp/queue_request.hxx"
#include "core/meta/version.hxx"
#include "core/operation_map.hxx"
#include "core/origin.hxx"
#include "core/ping_reporter.hxx"
#include "core/protocol/client_request.hxx"
#include "core/protocol/cmd_cluster_map_change_notification.hxx"
#include "core/protocol/cmd_get.hxx"
#include "core/protocol/cmd_get_cluster_config.hxx"
#include "core/protocol/cmd_get_error_map.hxx"
#include "core/protocol/cmd_hello.hxx"
#include "core/protocol/cmd_noop.hxx"
#include "core/protocol/cmd_sasl_auth.hxx"
#include "core/protocol/cmd_sasl_list_mechs.hxx"
#include "core/protocol/cmd_sasl_step.hxx"
#include "core/protocol/cmd_select_bucket.hxx"
#include "core/protocol/hello_feature_fmt.hxx"
#include "core/protocol/server_request.hxx"
#include "core/sasl/client.h"
#include "core/sasl/error_fmt.h"
#include "core/topology/capabilities_fmt.hxx"
#include "core/topology/configuration_fmt.hxx"
#include "mcbp_context.hxx"
#include "mcbp_message.hxx"
#include "mcbp_parser.hxx"
#include "retry_orchestrator.hxx"
#include "streams.hxx"
#include <couchbase/build_config.hxx>
#include <couchbase/error_codes.hxx>
#include <couchbase/fmt/retry_reason.hxx>
#include <asio.hpp>
#include <spdlog/fmt/bin_to_hex.h>
#include <cstring>
#include <utility>
namespace
{
template<typename Container>
struct mcbp_header_view {
const Container& buf_;
mcbp_header_view(const Container& buf)
: buf_{ buf }
{
}
};
struct mcbp_header_layout {
std::uint8_t magic;
std::uint8_t opcode;
union {
std::uint16_t normal;
struct {
std::uint8_t framing_extras;
std::uint8_t key;
} alt;
} keylen;
std::uint8_t extlen;
std::uint8_t datatype;
std::uint16_t specific;
std::uint32_t bodylen;
std::uint32_t opaque;
std::uint64_t cas;
[[nodiscard]] constexpr auto specific_name() const -> std::string_view
{
if (magic == 0x18 || magic == 0x81) {
return "status";
}
return "vbucket";
}
[[nodiscard]] constexpr auto key_length() const -> std::uint16_t
{
if (magic == 0x18 || magic == 0x08) {
return keylen.alt.key;
}
return couchbase::core::utils::byte_swap(keylen.normal);
}
[[nodiscard]] constexpr auto framing_extras_length() const -> std::uint8_t
{
if (magic == 0x18 || magic == 0x08) {
return keylen.alt.framing_extras;
}
return 0;
}
};
} // namespace
template<typename Container>
struct fmt::formatter<mcbp_header_view<Container>> {
template<typename ParseContext>
constexpr auto parse(ParseContext& ctx)
{
return ctx.begin();
}
template<typename FormatContext>
auto format(const mcbp_header_view<Container>& view, FormatContext& ctx) const
{
if (view.buf_.size() < sizeof(couchbase::core::io::binary_header)) {
return format_to(ctx.out(), "{:n}", spdlog::to_hex(view.buf_));
}
const auto* header = reinterpret_cast<const mcbp_header_layout*>(view.buf_.data());
return format_to(
ctx.out(),
"{{magic=0x{:x}, opcode=0x{:x}, fextlen={}, keylen={}, extlen={}, datatype={}, {}={}, bodylen={}, opaque={}, cas={}}}",
header->magic,
header->opcode,
header->framing_extras_length(),
header->key_length(),
header->extlen,
header->datatype,
header->specific_name(),
couchbase::core::utils::byte_swap(header->specific),
couchbase::core::utils::byte_swap(header->bodylen),
couchbase::core::utils::byte_swap(header->opaque),
couchbase::core::utils::byte_swap(header->cas));
}
};
namespace couchbase::core::io
{
struct connection_endpoints {
connection_endpoints(asio::ip::tcp::endpoint remote_endpoint, asio::ip::tcp::endpoint local_endpoint)
: remote{ std::move(remote_endpoint) }
, remote_address{ remote.address().to_string() }
, remote_address_with_port{ remote.protocol() == asio::ip::tcp::v6() ? fmt::format("[{}]:{}", remote_address, remote.port())
: fmt::format("{}:{}", remote_address, remote.port()) }
, local{ std::move(local_endpoint) }
, local_address{ local.address().to_string() }
, local_address_with_port{ local.protocol() == asio::ip::tcp::v6() ? fmt::format("[{}]:{}", local_address, local.port())
: fmt::format("{}:{}", local_address, local.port()) }
{
}
asio::ip::tcp::endpoint remote;
std::string remote_address{};
std::string remote_address_with_port{};
asio::ip::tcp::endpoint local;
std::string local_address{};
std::string local_address_with_port{};
};
class collection_cache
{
private:
std::map<std::string, std::uint32_t> cid_map_{ { "_default._default", 0 } };
public:
[[nodiscard]] std::optional<std::uint32_t> get(const std::string& path)
{
Expects(!path.empty());
if (auto ptr = cid_map_.find(path); ptr != cid_map_.end()) {
return ptr->second;
}
return std::nullopt;
}
void update(const std::string& path, std::uint32_t id)
{
Expects(!path.empty());
cid_map_[path] = id;
}
void reset()
{
cid_map_.clear();
cid_map_["_default._default"] = 0;
}
};
class mcbp_session_impl
: public std::enable_shared_from_this<mcbp_session_impl>
, public operation_map
{
class bootstrap_handler : public std::enable_shared_from_this<bootstrap_handler>
{
private:
std::shared_ptr<mcbp_session_impl> session_;
sasl::ClientContext sasl_;
std::atomic_bool stopped_{ false };
std::string last_error_message_;
public:
~bootstrap_handler()
{
stop();
}
void stop()
{
bool expected_state{ false };
stopped_.compare_exchange_strong(expected_state, true);
}
static auto sasl_mechanisms(const std::shared_ptr<mcbp_session_impl>& session) -> std::vector<std::string>
{
if (const auto user_mechanisms = session->origin_.credentials().allowed_sasl_mechanisms; user_mechanisms.has_value()) {
return user_mechanisms.value();
}
if (session->is_tls_) {
return { "PLAIN" };
}
return { "SCRAM-SHA512", "SCRAM-SHA256", "SCRAM-SHA1" };
}
std::string last_error_message() &&
{
return std::move(last_error_message_);
}
[[nodiscard]] const std::string& last_error_message() const&
{
return last_error_message_;
}
explicit bootstrap_handler(std::shared_ptr<mcbp_session_impl> session)
: session_(std::move(session))
, sasl_([origin = session_->origin_]() { return origin.username(); },
[origin = session_->origin_]() { return origin.password(); },
sasl_mechanisms(session_))
{
protocol::client_request<protocol::hello_request_body> hello_req;
if (session_->origin_.options().enable_unordered_execution) {
hello_req.body().enable_unordered_execution();
}
if (session_->origin_.options().enable_clustermap_notification) {
hello_req.body().enable_clustermap_change_notification();
hello_req.body().enable_deduplicate_not_my_vbucket_clustermap();
}
if (session_->origin_.options().enable_compression) {
hello_req.body().enable_compression();
}
if (session_->origin_.options().enable_mutation_tokens) {
hello_req.body().enable_mutation_tokens();
}
hello_req.opaque(session_->next_opaque());
auto user_agent =
meta::user_agent_for_mcbp(session_->client_id_, session_->id_, session_->origin_.options().user_agent_extra, 250);
hello_req.body().user_agent(user_agent);
CB_LOG_DEBUG("{} user_agent={}, requested_features=[{}]",
session_->log_prefix_,
user_agent,
utils::join_strings_fmt(hello_req.body().features(), ", "));
session_->write(hello_req.data());
if (!session_->origin_.credentials().uses_certificate()) {
protocol::client_request<protocol::sasl_list_mechs_request_body> list_req;
list_req.opaque(session_->next_opaque());
session_->write(list_req.data());
protocol::client_request<protocol::sasl_auth_request_body> auth_req;
auto [sasl_code, sasl_payload] = sasl_.start();
auth_req.opaque(session_->next_opaque());
auth_req.body().mechanism(sasl_.get_name());
auth_req.body().sasl_data(sasl_payload);
session_->write(auth_req.data());
}
session_->flush();
}
void complete(std::error_code ec)
{
if (bool expected_state{ false }; stopped_.compare_exchange_strong(expected_state, true)) {
session_->invoke_bootstrap_handler(ec);
}
}
void auth_success()
{
session_->authenticated_ = true;
if (session_->supports_feature(protocol::hello_feature::xerror)) {
protocol::client_request<protocol::get_error_map_request_body> errmap_req;
errmap_req.opaque(session_->next_opaque());
session_->write(errmap_req.data());
}
if (session_->bucket_name_) {
protocol::client_request<protocol::select_bucket_request_body> sb_req;
sb_req.opaque(session_->next_opaque());
sb_req.body().bucket_name(session_->bucket_name_.value());
session_->write(sb_req.data());
}
protocol::client_request<protocol::get_cluster_config_request_body> cfg_req;
cfg_req.opaque(session_->next_opaque());
session_->write(cfg_req.data());
session_->flush();
}
void handle(mcbp_message&& msg)
{
if (stopped_ || !session_) {
return;
}
Expects(protocol::is_valid_magic(msg.header.magic));
switch (auto magic = static_cast<protocol::magic>(msg.header.magic)) {
case protocol::magic::client_response:
case protocol::magic::alt_client_response:
Expects(protocol::is_valid_client_opcode(msg.header.opcode));
switch (auto status = static_cast<key_value_status_code>(msg.header.status())) {
case key_value_status_code::rate_limited_max_commands:
case key_value_status_code::rate_limited_max_connections:
case key_value_status_code::rate_limited_network_egress:
case key_value_status_code::rate_limited_network_ingress:
last_error_message_ = fmt::format(
"unable to bootstrap MCBP session (bucket={}, opcode={}, status={}), the user has reached rate limit",
session_->bucket_name_.value_or(""),
protocol::client_opcode(msg.header.opcode),
status);
CB_LOG_DEBUG("{} {}", session_->log_prefix_, last_error_message_);
return complete(errc::common::rate_limited);
case key_value_status_code::scope_size_limit_exceeded:
last_error_message_ = fmt::format(
"unable to bootstrap MCBP session (bucket={}, opcode={}, status={}), the user has reached quota limit",
session_->bucket_name_.value_or(""),
protocol::client_opcode(msg.header.opcode),
status);
CB_LOG_DEBUG("{} {}", session_->log_prefix_, last_error_message_);
return complete(errc::common::quota_limited);
default:
break;
}
switch (auto opcode = static_cast<protocol::client_opcode>(msg.header.opcode)) {
case protocol::client_opcode::hello: {
protocol::client_response<protocol::hello_response_body> resp(std::move(msg));
if (resp.status() == key_value_status_code::success) {
session_->supported_features_ = resp.body().supported_features();
CB_LOG_DEBUG("{} supported_features=[{}]",
session_->log_prefix_,
utils::join_strings_fmt(session_->supported_features_, ", "));
if (session_->origin_.credentials().uses_certificate()) {
CB_LOG_DEBUG("{} skip SASL authentication, because TLS certificate was specified",
session_->log_prefix_);
return auth_success();
}
} else {
last_error_message_ = fmt::format(
"unexpected message status during bootstrap: {} (opaque={})", resp.error_message(), resp.opaque());
CB_LOG_WARNING("{} {}", session_->log_prefix_, last_error_message_);
return complete(errc::network::handshake_failure);
}
} break;
case protocol::client_opcode::sasl_list_mechs: {
protocol::client_response<protocol::sasl_list_mechs_response_body> resp(std::move(msg));
if (resp.status() != key_value_status_code::success) {
last_error_message_ = fmt::format(
"unexpected message status during bootstrap: {} (opaque={})", resp.error_message(), resp.opaque());
CB_LOG_WARNING("{} {}", session_->log_prefix_, last_error_message_);
return complete(errc::common::authentication_failure);
}
} break;
case protocol::client_opcode::sasl_auth: {
protocol::client_response<protocol::sasl_auth_response_body> resp(std::move(msg));
if (resp.status() == key_value_status_code::success) {
return auth_success();
}
if (resp.status() == key_value_status_code::auth_continue) {
auto [sasl_code, sasl_payload] = sasl_.step(resp.body().value());
if (sasl_code == sasl::error::OK) {
return auth_success();
}
if (sasl_code == sasl::error::CONTINUE) {
protocol::client_request<protocol::sasl_step_request_body> req;
req.opaque(session_->next_opaque());
req.body().mechanism(sasl_.get_name());
req.body().sasl_data(sasl_payload);
session_->write_and_flush(req.data());
} else {
last_error_message_ =
fmt::format("unable to authenticate: (sasl_code={}, opaque={})", sasl_code, resp.opaque());
CB_LOG_ERROR("{} {}", session_->log_prefix_, last_error_message_);
return complete(errc::common::authentication_failure);
}
} else {
last_error_message_ = fmt::format("{} unexpected message status during bootstrap: {} (opaque={})",
session_->log_prefix_,
resp.error_message(),
resp.opaque());
CB_LOG_WARNING("{} {}", session_->log_prefix_, last_error_message_);
return complete(errc::common::authentication_failure);
}
} break;
case protocol::client_opcode::sasl_step: {
protocol::client_response<protocol::sasl_step_response_body> resp(std::move(msg));
if (resp.status() == key_value_status_code::success) {
return auth_success();
}
last_error_message_ =
fmt::format("unable to authenticate (opcode={}, status={}, opaque={})", opcode, resp.status(), resp.opaque());
CB_LOG_ERROR("{} {}", session_->log_prefix_, last_error_message_);
return complete(errc::common::authentication_failure);
}
case protocol::client_opcode::get_error_map: {
protocol::client_response<protocol::get_error_map_response_body> resp(std::move(msg));
if (resp.status() == key_value_status_code::success) {
session_->error_map_.emplace(resp.body().errmap());
} else {
last_error_message_ = fmt::format("unexpected message status during bootstrap: {} (opaque={}, {:n})",
resp.error_message(),
resp.opaque(),
spdlog::to_hex(resp.header()));
CB_LOG_WARNING("{} {}", session_->log_prefix_, last_error_message_);
return complete(errc::network::protocol_error);
}
} break;
case protocol::client_opcode::select_bucket: {
protocol::client_response<protocol::select_bucket_response_body> resp(std::move(msg));
if (resp.status() == key_value_status_code::success) {
CB_LOG_DEBUG("{} selected bucket: {}", session_->log_prefix_, session_->bucket_name_.value_or(""));
session_->bucket_selected_ = true;
} else if (resp.status() == key_value_status_code::not_found) {
last_error_message_ =
fmt::format("kv_engine node does not have configuration propagated yet (opcode={}, status={}, opaque={})",
opcode,
resp.status(),
resp.opaque());
CB_LOG_DEBUG("{} {}", session_->log_prefix_, last_error_message_);
return complete(errc::network::configuration_not_available);
} else if (resp.status() == key_value_status_code::no_access) {
last_error_message_ = fmt::format("unable to select bucket: {}, probably the bucket does not exist",
session_->bucket_name_.value_or(""));
CB_LOG_DEBUG("{} {}", session_->log_prefix_, last_error_message_);
session_->bucket_selected_ = false;
return complete(errc::common::bucket_not_found);
} else {
last_error_message_ = fmt::format("unexpected message status during bootstrap: {} (opaque={}, {:n})",
resp.error_message(),
resp.opaque(),
spdlog::to_hex(resp.header()));
CB_LOG_WARNING("{} {}", session_->log_prefix_, last_error_message_);
return complete(errc::common::bucket_not_found);
}
} break;
case protocol::client_opcode::get_cluster_config: {
protocol::cmd_info info{ session_->connection_endpoints_.remote_address,
session_->connection_endpoints_.remote.port() };
if (session_->origin_.options().dump_configuration) {
std::string_view config_text{ reinterpret_cast<const char*>(msg.body.data()), msg.body.size() };
CB_LOG_TRACE(
"{} configuration from get_cluster_config request (bootstrap, size={}, endpoint=\"{}:{}\"), {}",
session_->log_prefix_,
config_text.size(),
info.endpoint_address,
info.endpoint_port,
config_text);
}
protocol::client_response<protocol::get_cluster_config_response_body> resp(std::move(msg), info);
if (resp.status() == key_value_status_code::success) {
session_->update_configuration(resp.body().config());
complete({});
} else if (resp.status() == key_value_status_code::not_found) {
last_error_message_ =
fmt::format("kv_engine node does not have configuration propagated yet (opcode={}, status={}, opaque={})",
opcode,
resp.status(),
resp.opaque());
CB_LOG_DEBUG("{} {}", session_->log_prefix_, last_error_message_);
return complete(errc::network::configuration_not_available);
} else if (resp.status() == key_value_status_code::no_bucket && !session_->bucket_name_) {
// bucket-less session, but the server wants bucket
session_->supports_gcccp_ = false;
CB_LOG_WARNING("{} this server does not support GCCCP, open bucket before making any cluster-level command",
session_->log_prefix_);
session_->update_configuration(topology::make_blank_configuration(
session_->connection_endpoints_.remote_address, session_->connection_endpoints_.remote.port(), 0));
complete({});
} else {
last_error_message_ = fmt::format("unexpected message status during bootstrap: {} (opaque={}, {:n})",
resp.error_message(),
resp.opaque(),
spdlog::to_hex(resp.header()));
CB_LOG_WARNING("{} {}", session_->log_prefix_, last_error_message_);
return complete(errc::network::protocol_error);
}
} break;
default:
last_error_message_ = fmt::format("unexpected message during bootstrap: {}", opcode);
CB_LOG_WARNING("{} {}", session_->log_prefix_, last_error_message_);
return complete(errc::network::protocol_error);
}
break;
case protocol::magic::server_request:
Expects(protocol::is_valid_server_request_opcode(msg.header.opcode));
switch (static_cast<protocol::server_opcode>(msg.header.opcode)) {
case protocol::server_opcode::cluster_map_change_notification: {
protocol::cmd_info info{ session_->bootstrap_hostname_, session_->bootstrap_port_number_ };
if (session_->origin_.options().dump_configuration) {
std::string_view config_text{ reinterpret_cast<const char*>(msg.body.data()), msg.body.size() };
CB_LOG_TRACE(
"{} configuration from cluster_map_change_notification request (size={}, endpoint=\"{}:{}\"), {}",
session_->log_prefix_,
config_text.size(),
info.endpoint_address,
info.endpoint_port,
config_text);
}
protocol::server_request<protocol::cluster_map_change_notification_request_body> req(std::move(msg), info);
std::optional<topology::configuration> config = req.body().config();
if (session_ && config.has_value()) {
if ((!config->bucket.has_value() && req.body().bucket().empty()) ||
(session_->bucket_name_.has_value() && !req.body().bucket().empty() &&
session_->bucket_name_.value() == req.body().bucket())) {
session_->update_configuration(std::move(config.value()));
}
}
} break;
default:
CB_LOG_WARNING("{} unexpected server request: opcode={:x}, opaque={}{:a}{:a}",
session_->log_prefix_,
msg.header.opcode,
utils::byte_swap(msg.header.opaque),
spdlog::to_hex(msg.header_data()),
spdlog::to_hex(msg.body));
}
break;
case protocol::magic::client_request:
case protocol::magic::alt_client_request:
case protocol::magic::server_response:
CB_LOG_WARNING("{} unexpected magic: {} (opcode={:x}, opaque={}){:a}{:a}",
session_->log_prefix_,
magic,
msg.header.opcode,
utils::byte_swap(msg.header.opaque),
spdlog::to_hex(msg.header_data()),
spdlog::to_hex(msg.body));
break;
}
}
};
class message_handler : public std::enable_shared_from_this<message_handler>
{
private:
std::shared_ptr<mcbp_session_impl> session_;
std::atomic_bool stopped_{ false };
public:
explicit message_handler(std::shared_ptr<mcbp_session_impl> session)
: session_(std::move(session))
{
}
~message_handler()
{
stop();
}
void start()
{
}
void stop()
{
}
void handle(mcbp_message&& msg)
{
if (stopped_ || !session_) {
return;
}
Expects(protocol::is_valid_magic(msg.header.magic));
switch (auto magic = static_cast<protocol::magic>(msg.header.magic)) {
case protocol::magic::client_response:
case protocol::magic::alt_client_response:
Expects(protocol::is_valid_client_opcode(msg.header.opcode));
switch (auto opcode = static_cast<protocol::client_opcode>(msg.header.opcode)) {
case protocol::client_opcode::get_cluster_config: {
protocol::cmd_info info{ session_->bootstrap_hostname_, session_->bootstrap_port_number_ };
if (session_->origin_.options().dump_configuration) {
std::string_view config_text{ reinterpret_cast<const char*>(msg.body.data()), msg.body.size() };
CB_LOG_TRACE("{} configuration from get_cluster_config response (size={}, endpoint=\"{}:{}\"), {}",
session_->log_prefix_,
config_text.size(),
info.endpoint_address,
info.endpoint_port,
config_text);
}
protocol::client_response<protocol::get_cluster_config_response_body> resp(std::move(msg), info);
if (resp.status() == key_value_status_code::success) {
if (session_) {
session_->update_configuration(resp.body().config());
}
} else {
CB_LOG_WARNING("{} unexpected message status: {} (opaque={})",
session_->log_prefix_,
resp.error_message(),
resp.opaque());
}
} break;
case protocol::client_opcode::noop:
case protocol::client_opcode::get_collections_manifest:
case protocol::client_opcode::get_collection_id:
case protocol::client_opcode::get:
case protocol::client_opcode::get_and_lock:
case protocol::client_opcode::get_and_touch:
case protocol::client_opcode::get_meta:
case protocol::client_opcode::get_replica:
case protocol::client_opcode::touch:
case protocol::client_opcode::insert:
case protocol::client_opcode::replace:
case protocol::client_opcode::upsert:
case protocol::client_opcode::append:
case protocol::client_opcode::prepend:
case protocol::client_opcode::remove:
case protocol::client_opcode::observe_seqno:
case protocol::client_opcode::unlock:
case protocol::client_opcode::increment:
case protocol::client_opcode::range_scan_create:
case protocol::client_opcode::range_scan_continue:
case protocol::client_opcode::range_scan_cancel:
case protocol::client_opcode::decrement:
case protocol::client_opcode::subdoc_multi_lookup:
case protocol::client_opcode::subdoc_multi_mutation: {
std::uint16_t status = utils::byte_swap(msg.header.specific);
if (status == static_cast<std::uint16_t>(key_value_status_code::not_my_vbucket)) {
session_->handle_not_my_vbucket(msg);
}
std::uint32_t opaque = utils::byte_swap(msg.header.opaque);
if (session_->handle_request(opcode, status, opaque, std::move(msg))) {
CB_LOG_TRACE("{} MCBP invoked operation handler: opcode={}, opaque={}, status={}",
session_->log_prefix_,
opcode,
opaque,
protocol::status_to_string(status));
} else {
CB_LOG_DEBUG("{} unexpected orphan response: opcode={}, opaque={}, status={}",
session_->log_prefix_,
opcode,
opaque,
protocol::status_to_string(status));
}
} break;
default:
CB_LOG_WARNING("{} unexpected client response: opcode={}, opaque={}{:a}{:a})",
session_->log_prefix_,
opcode,
msg.header.opaque,
spdlog::to_hex(msg.header_data()),
spdlog::to_hex(msg.body));
}
break;
case protocol::magic::server_request:
Expects(protocol::is_valid_server_request_opcode(msg.header.opcode));
switch (static_cast<protocol::server_opcode>(msg.header.opcode)) {
case protocol::server_opcode::cluster_map_change_notification: {
protocol::cmd_info info{ session_->bootstrap_hostname_, session_->bootstrap_port_number_ };
if (session_->origin_.options().dump_configuration) {
std::string_view config_text{ reinterpret_cast<const char*>(msg.body.data()), msg.body.size() };
CB_LOG_TRACE(
"{} configuration from cluster_map_change_notification request (size={}, endpoint=\"{}:{}\"), {}",
session_->log_prefix_,
config_text.size(),
info.endpoint_address,
info.endpoint_port,
config_text);
}
protocol::server_request<protocol::cluster_map_change_notification_request_body> req(std::move(msg), info);
std::optional<topology::configuration> config = req.body().config();
if (session_ && config.has_value()) {
if ((!config->bucket.has_value() && req.body().bucket().empty()) ||
(session_->bucket_name_.has_value() && !req.body().bucket().empty() &&
session_->bucket_name_.value() == req.body().bucket())) {
session_->update_configuration(std::move(config.value()));
}
}
} break;
default:
CB_LOG_WARNING("{} unexpected server request: opcode={:x}, opaque={}{:a}{:a}",
session_->log_prefix_,
msg.header.opcode,
msg.header.opaque,
spdlog::to_hex(msg.header_data()),
spdlog::to_hex(msg.body));
}
break;
case protocol::magic::client_request:
case protocol::magic::alt_client_request:
case protocol::magic::server_response:
CB_LOG_WARNING("{} unexpected magic: {} (opcode={:x}, opaque={}){:a}{:a}",
session_->log_prefix_,
magic,
msg.header.opcode,
msg.header.opaque,
spdlog::to_hex(msg.header_data()),
spdlog::to_hex(msg.body));
break;
}
}
};
public:
mcbp_session_impl() = delete;
mcbp_session_impl(std::string_view client_id,
asio::io_context& ctx,
couchbase::core::origin origin,
std::shared_ptr<impl::bootstrap_state_listener> state_listener,
std::optional<std::string> bucket_name = {},
std::vector<protocol::hello_feature> known_features = {})
: client_id_(client_id)
, ctx_(ctx)
, resolver_(ctx_)
, stream_(std::make_unique<plain_stream_impl>(ctx_))
, bootstrap_deadline_(ctx_)
, connection_deadline_(ctx_)
, retry_backoff_(ctx_)
, ping_deadline_(ctx_)
, origin_{ std::move(origin) }
, bucket_name_{ std::move(bucket_name) }
, supported_features_{ std::move(known_features) }
, is_tls_{ false }
, state_listener_{ std::move(state_listener) }
, codec_{ { supported_features_.begin(), supported_features_.end() } }
{
log_prefix_ = fmt::format("[{}/{}/{}/{}]", client_id_, id_, stream_->log_prefix(), bucket_name_.value_or("-"));
}
mcbp_session_impl(std::string_view client_id,
asio::io_context& ctx,
asio::ssl::context& tls,
couchbase::core::origin origin,
std::shared_ptr<impl::bootstrap_state_listener> state_listener,
std::optional<std::string> bucket_name = {},
std::vector<protocol::hello_feature> known_features = {})
: client_id_(client_id)
, ctx_(ctx)
, resolver_(ctx_)
, stream_(std::make_unique<tls_stream_impl>(ctx_, tls))
, bootstrap_deadline_(ctx_)
, connection_deadline_(ctx_)
, retry_backoff_(ctx_)
, ping_deadline_(ctx_)
, origin_(std::move(origin))
, bucket_name_(std::move(bucket_name))
, supported_features_(std::move(known_features))
, is_tls_{ true }
, state_listener_{ std::move(state_listener) }
, codec_{ { supported_features_.begin(), supported_features_.end() } }
{
log_prefix_ = fmt::format("[{}/{}/{}/{}]", client_id_, id_, stream_->log_prefix(), bucket_name_.value_or("-"));
}
~mcbp_session_impl()
{
CB_LOG_DEBUG("{} destroy MCBP connection", log_prefix_);
stop(retry_reason::do_not_retry);
}
[[nodiscard]] const std::string& log_prefix() const
{
return log_prefix_;
}
std::string remote_address() const
{
return connection_endpoints_.remote_address_with_port;
}
std::string local_address() const
{
return connection_endpoints_.local_address_with_port;
}
[[nodiscard]] diag::endpoint_diag_info diag_info() const
{
return { service_type::key_value,
id_,
last_active_.time_since_epoch().count() == 0 ? std::nullopt
: std::make_optional(std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::steady_clock::now() - last_active_)),
remote_address(),
local_address(),
state_,
bucket_name_ };
}
void ping(std::shared_ptr<diag::ping_reporter> handler, std::optional<std::chrono::milliseconds> timeout)
{
if (!bootstrapped_) {
handler->report({
service_type::key_value,
id_,
std::chrono::microseconds(0),
remote_address(),
local_address(),
diag::ping_state::error,
bucket_name_,
last_bootstrap_error_message_.has_value() ? last_bootstrap_error_message_.value()
: "Bootstrap incomplete, cannot perform ping.",
});
return;
}
protocol::client_request<protocol::mcbp_noop_request_body> req;
req.opaque(next_opaque());
write_and_subscribe(req.opaque(),
req.data(false),
[start = std::chrono::steady_clock::now(), self = shared_from_this(), handler](
std::error_code ec,
retry_reason reason,
io::mcbp_message&& /* msg */,
std::optional<key_value_error_map_info> /* error_info */) {
diag::ping_state state = diag::ping_state::ok;
std::optional<std::string> error{};
if (ec) {
if (ec == errc::common::unambiguous_timeout || ec == errc::common::ambiguous_timeout) {
state = diag::ping_state::timeout;
} else {
state = diag::ping_state::error;
}
error.emplace(fmt::format("code={}, message={}, reason={}", ec.value(), ec.message(), reason));
}
handler->report({
service_type::key_value,
self->id_,
std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - start),
self->remote_address(),
self->local_address(),
state,
self->bucket_name_,
error,
});
});
ping_deadline_.expires_after(timeout.value_or(origin_.options().key_value_timeout));
ping_deadline_.async_wait([self = this->shared_from_this(), opaque = req.opaque()](std::error_code ec) {
if (ec == asio::error::operation_aborted) {
return;
}
static_cast<void>(self->cancel(opaque, errc::common::unambiguous_timeout, retry_reason::do_not_retry));
});
}
[[nodiscard]] mcbp_context context() const
{
return { config_, supported_features_ };
}
void bootstrap(utils::movable_function<void(std::error_code, topology::configuration)>&& callback,
bool retry_on_bucket_not_found = false)
{
retry_bootstrap_on_bucket_not_found_ = retry_on_bucket_not_found;
bootstrap_callback_ = std::move(callback);
bootstrap_deadline_.expires_after(origin_.options().bootstrap_timeout);
bootstrap_deadline_.async_wait([self = shared_from_this()](std::error_code ec) {
if (ec == asio::error::operation_aborted || self->stopped_) {
return;
}
if (!ec) {
ec = errc::common::unambiguous_timeout;
}
if (self->state_listener_) {
self->state_listener_->report_bootstrap_error(fmt::format("{}:{}", self->bootstrap_hostname_, self->bootstrap_port_), ec);
}
CB_LOG_WARNING("{} unable to bootstrap in time", self->log_prefix_);
if (auto h = std::move(self->bootstrap_callback_); h) {
h(ec, {});
}
self->stop(retry_reason::do_not_retry);
});
initiate_bootstrap();
}
void initiate_bootstrap()
{
if (stopped_) {
return;
}
bootstrapped_ = false;
if (bootstrap_handler_) {
last_bootstrap_error_message_ = std::move(bootstrap_handler_)->last_error_message();
}
bootstrap_handler_ = nullptr;
state_ = diag::endpoint_state::connecting;
if (stream_->is_open()) {
std::string old_id = stream_->id();
stream_->reopen();
CB_LOG_TRACE(R"({} reopen socket connection "{}" -> "{}", host="{}", port={})",
log_prefix_,
old_id,
stream_->id(),
bootstrap_hostname_,
bootstrap_port_);
}
if (origin_.exhausted()) {
auto backoff = std::chrono::milliseconds(500);
CB_LOG_DEBUG("{} reached the end of list of bootstrap nodes, waiting for {}ms before restart", log_prefix_, backoff.count());
retry_backoff_.expires_after(backoff);
retry_backoff_.async_wait([self = shared_from_this()](std::error_code ec) mutable {
if (ec == asio::error::operation_aborted || self->stopped_) {
return;
}
self->origin_.restart();
self->initiate_bootstrap();
});
return;
}
std::tie(bootstrap_hostname_, bootstrap_port_) = origin_.next_address();
bootstrap_port_number_ = gsl::narrow_cast<std::uint16_t>(std::stoul(bootstrap_port_, nullptr, 10));
bootstrap_address_ = fmt::format("{}:{}", bootstrap_hostname_, bootstrap_port_);
log_prefix_ =
fmt::format("[{}/{}/{}/{}] <{}>", client_id_, id_, stream_->log_prefix(), bucket_name_.value_or("-"), bootstrap_address_);
CB_LOG_DEBUG("{} attempt to establish MCBP connection", log_prefix_);
async_resolve(origin_.options().use_ip_protocol,
resolver_,
bootstrap_hostname_,
bootstrap_port_,
std::bind(&mcbp_session_impl::on_resolve, shared_from_this(), std::placeholders::_1, std::placeholders::_2));
}
[[nodiscard]] const std::string& id() const
{
return id_;
}
[[nodiscard]] bool is_stopped() const
{
return stopped_;
}
[[nodiscard]] bool is_bootstrapped() const
{
return bootstrapped_;
}
void on_stop(utils::movable_function<void()> handler)
{
on_stop_handler_ = std::move(handler);
}
void stop(retry_reason reason)
{
if (stopped_) {
return;
}
state_ = diag::endpoint_state::disconnecting;
CB_LOG_DEBUG("{} stop MCBP connection, reason={}", log_prefix_, reason);
stopped_ = true;
bootstrap_deadline_.cancel();
connection_deadline_.cancel();
retry_backoff_.cancel();
ping_deadline_.cancel();
resolver_.cancel();
stream_->close([](std::error_code) {});
if (auto h = std::move(bootstrap_handler_); h) {
h->stop();
}
if (auto h = std::move(handler_); h) {
h->stop();
}
std::error_code ec = errc::common::request_canceled;
if (!bootstrapped_) {
if (auto h = std::move(bootstrap_callback_); h) {
h(ec, {});
}
}
{
std::scoped_lock lock(command_handlers_mutex_);
for (auto& [opaque, handler] : command_handlers_) {
if (handler) {
CB_LOG_DEBUG("{} MCBP cancel operation during session close, opaque={}, ec={}", log_prefix_, opaque, ec.message());
auto fun = std::move(handler);
fun(ec, reason, {}, {});
}
}
command_handlers_.clear();
}
{