summaryrefslogtreecommitdiffstats
path: root/storage/src/tests/storageserver/rpc/storage_api_rpc_service_test.cpp
blob: 69259ee08ec9295363c708c5a6f8baadad272496 (plain) (blame)
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
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include <vespa/document/base/testdocman.h>
#include <vespa/document/repo/documenttyperepo.h>
#include <vespa/document/test/make_document_bucket.h>
#include <vespa/documentapi/loadtypes/loadtypeset.h>
#include <vespa/messagebus/testlib/slobrok.h>
#include <vespa/slobrok/sbmirror.h>
#include <vespa/storage/storageserver/rpc/storage_api_rpc_service.h>
#include <vespa/storage/storageserver/rpc/shared_rpc_resources.h>
#include <vespa/storage/storageserver/rpc/message_codec_provider.h>
#include <vespa/storage/storageserver/rpc/caching_rpc_target_resolver.h>
#include <vespa/storage/storageserver/communicationmanager.h>
#include <vespa/storage/storageserver/rpcrequestwrapper.h>
#include <vespa/storage/storageserver/message_dispatcher.h>
#include <vespa/storageapi/message/persistence.h>
#include <tests/common/testhelper.h>
#include <vespa/vespalib/gtest/gtest.h>
#include <vespa/vespalib/util/host_name.h>
#include <vespa/vespalib/util/stringfmt.h>
#include <gmock/gmock.h>
#include <condition_variable>
#include <deque>
#include <functional>
#include <memory>
#include <mutex>
#include <stdexcept>
#include <string>

#include <thread>

using namespace ::testing;
using namespace document::test;
using namespace std::chrono_literals;

namespace storage::rpc {

namespace {

constexpr std::chrono::duration message_timeout = 60s;
constexpr std::chrono::duration slobrok_register_timeout = 60s;

class LockingMockOperationDispatcher : public MessageDispatcher {
    using MessageQueueType = std::deque<std::shared_ptr<api::StorageMessage>>;

    mutable std::mutex              _mutex;
    mutable std::condition_variable _cond;
    MessageQueueType                _enqueued;
public:
    LockingMockOperationDispatcher();
    ~LockingMockOperationDispatcher() override;

    void dispatch_sync(std::shared_ptr<api::StorageMessage> msg) override {
        std::lock_guard lock(_mutex);
        _enqueued.emplace_back(std::move(msg));
        _cond.notify_all();
    }

    void dispatch_async(std::shared_ptr<api::StorageMessage> msg) override {
        std::lock_guard lock(_mutex);
        _enqueued.emplace_back(std::move(msg));
        _cond.notify_all();
    }

    [[nodiscard]] bool empty() const noexcept {
        std::lock_guard lock(_mutex);
        return _enqueued.empty();
    }

    void wait_until_n_messages_received(size_t n) const {
        std::unique_lock lock(_mutex);
        const auto deadline = std::chrono::steady_clock::now() + message_timeout;
        if (!_cond.wait_until(lock, deadline, [this, n]{ return (_enqueued.size() == n); })) {
            throw std::runtime_error("Timed out waiting for message");
        }
    }

    [[nodiscard]] std::shared_ptr<api::StorageMessage> pop_first_message() {
        std::lock_guard lock(_mutex);
        assert(!_enqueued.empty());
        auto msg = std::move(_enqueued.front());
        _enqueued.pop_front();
        return msg;
    }
};

LockingMockOperationDispatcher::LockingMockOperationDispatcher()  = default;
LockingMockOperationDispatcher::~LockingMockOperationDispatcher() = default;

api::StorageMessageAddress make_address(uint16_t node_index, bool is_distributor) {
    return {"coolcluster", (is_distributor ? lib::NodeType::DISTRIBUTOR : lib::NodeType::STORAGE), node_index};
}

vespalib::string to_slobrok_id(const api::StorageMessageAddress& address) {
    // TODO factor out slobrok ID generation code to be independent of resolver?
    return CachingRpcTargetResolver::address_to_slobrok_id(address);
}

class StorageApiNode {
    vdstestlib::DirConfig                             _config;
    std::shared_ptr<const document::DocumentTypeRepo> _doc_type_repo;
    std::shared_ptr<const documentapi::LoadTypeSet>   _load_type_set;
    LockingMockOperationDispatcher                    _messages;
    std::unique_ptr<MessageCodecProvider>             _codec_provider;
    std::unique_ptr<SharedRpcResources>               _shared_rpc_resources;
    std::unique_ptr<StorageApiRpcService>             _service;
    api::StorageMessageAddress                        _node_address;
    vespalib::string                                  _slobrok_id;
public:
    StorageApiNode(uint16_t node_index, bool is_distributor, const mbus::Slobrok& slobrok)
        : _config(getStandardConfig(true)),
          _doc_type_repo(document::TestDocRepo().getTypeRepoSp()),
          _load_type_set(std::make_shared<documentapi::LoadTypeSet>()),
          _node_address(make_address(node_index, is_distributor)),
          _slobrok_id(to_slobrok_id(_node_address))
    {
        auto& cfg = _config.getConfig("stor-server");
        cfg.set("node_index", std::to_string(node_index));
        cfg.set("is_distributor", is_distributor ? "true" : "false");
        addSlobrokConfig(_config, slobrok);

        _shared_rpc_resources = std::make_unique<SharedRpcResources>(_config.getConfigId(), 0, 1);
        // TODO make codec provider into interface so we can test decode-failures more easily?
        _codec_provider = std::make_unique<MessageCodecProvider>(_doc_type_repo, _load_type_set);
        StorageApiRpcService::Params params;
        _service = std::make_unique<StorageApiRpcService>(_messages, *_shared_rpc_resources, *_codec_provider, params);

        _shared_rpc_resources->start_server_and_register_slobrok(_slobrok_id);
        // Explicitly wait until we are visible in Slobrok. Just waiting for mirror readiness is not enough.
        wait_until_visible_in_slobrok(_slobrok_id);
    }

    void wait_until_visible_in_slobrok(vespalib::stringref id) {
        const auto deadline = std::chrono::steady_clock::now() + slobrok_register_timeout;
        while (_shared_rpc_resources->slobrok_mirror().lookup(id).empty()) {
            if (std::chrono::steady_clock::now() > deadline) {
                throw std::runtime_error("Timed out waiting for node to be visible in Slobrok");
            }
            std::this_thread::sleep_for(10ms);
        }
    }

    const api::StorageMessageAddress& node_address() const noexcept { return _node_address; }

    std::shared_ptr<api::PutCommand> create_dummy_put_command() const {
        auto doc_type = _doc_type_repo->getDocumentType("testdoctype1");
        auto doc = std::make_shared<document::Document>(*doc_type, document::DocumentId("id:foo:testdoctype1::bar"));
        doc->setFieldValue(doc->getField("hstringval"), std::make_unique<document::StringFieldValue>("hello world"));
        return std::make_shared<api::PutCommand>(makeDocumentBucket(document::BucketId(0)), std::move(doc), 100);
    }

    void send_request_verify_not_bounced(std::shared_ptr<api::StorageCommand> req) {
        if (!_messages.empty()) {
            throw std::runtime_error("Node had pending messages before send");
        }
        _service->send_rpc_v1_request(std::move(req));
        if (!_messages.empty()) {
            throw std::runtime_error("RPC request was bounced. Most likely due to missing Slobrok mapping");
        }
    }

    void send_request(std::shared_ptr<api::StorageCommand> req) {
        _service->send_rpc_v1_request(std::move(req));
    }

    // TODO move StorageTransportContext away from communicationmanager.h
    // TODO refactor reply handling to avoid duping detail code with CommunicationManager?
    void send_response(const std::shared_ptr<api::StorageReply>& reply) {
        std::unique_ptr<StorageTransportContext> context(dynamic_cast<StorageTransportContext*>(
                reply->getTransportContext().release()));
        assert(context);
        _service->encode_rpc_v1_response(*context->_request->raw_request(), *reply);
        context->_request->returnRequest();
    }

    [[nodiscard]] std::shared_ptr<api::StorageMessage> wait_and_receive_single_message() {
        _messages.wait_until_n_messages_received(1);
        return _messages.pop_first_message();
    }
};

} // anonymous namespace

// TODO consider completely mocking Slobrok to avoid any race conditions during node registration
struct StorageApiRpcServiceTest : Test {
    mbus::Slobrok _slobrok;
    std::unique_ptr<StorageApiNode> _node_0;
    std::unique_ptr<StorageApiNode> _node_1;

    StorageApiRpcServiceTest()
        : _slobrok(),
          _node_0(std::make_unique<StorageApiNode>(1, true, _slobrok)),
          _node_1(std::make_unique<StorageApiNode>(4, false, _slobrok))
    {
        // FIXME ugh, this isn't particularly pretty...
        _node_0->wait_until_visible_in_slobrok(to_slobrok_id(_node_1->node_address()));
        _node_1->wait_until_visible_in_slobrok(to_slobrok_id(_node_0->node_address()));
    }
    ~StorageApiRpcServiceTest() override;

    static api::StorageMessageAddress non_existing_address() {
        return make_address(100, false);
    }

    [[nodiscard]] std::shared_ptr<api::PutCommand> send_and_receive_put_command_at_node_1(
            const std::function<void(api::PutCommand&)>& req_mutator) {
        auto cmd = _node_0->create_dummy_put_command();
        cmd->setAddress(_node_1->node_address());
        req_mutator(*cmd);
        _node_0->send_request_verify_not_bounced(cmd);

        auto recv_msg = _node_1->wait_and_receive_single_message();
        auto recv_as_put = std::dynamic_pointer_cast<api::PutCommand>(recv_msg);
        assert(recv_as_put);
        return recv_as_put;
    }
    [[nodiscard]] std::shared_ptr<api::PutCommand> send_and_receive_put_command_at_node_1() {
        return send_and_receive_put_command_at_node_1([]([[maybe_unused]] auto& cmd){});
    }

    [[nodiscard]] std::shared_ptr<api::PutReply> respond_and_receive_put_reply_at_node_0(
            const std::shared_ptr<api::PutCommand>& cmd,
            const std::function<void(api::StorageReply&)>& reply_mutator) {
        auto reply = std::shared_ptr<api::StorageReply>(cmd->makeReply());
        reply_mutator(*reply);
        _node_1->send_response(reply);

        auto recv_reply = _node_0->wait_and_receive_single_message();
        auto recv_as_put_reply = std::dynamic_pointer_cast<api::PutReply>(recv_reply);
        assert(recv_as_put_reply);
        return recv_as_put_reply;
    }

    [[nodiscard]] std::shared_ptr<api::PutReply> respond_and_receive_put_reply_at_node_0(
            const std::shared_ptr<api::PutCommand>& cmd) {
        return respond_and_receive_put_reply_at_node_0(cmd, []([[maybe_unused]] auto& reply){});
    }
};

StorageApiRpcServiceTest::~StorageApiRpcServiceTest() = default;

TEST_F(StorageApiRpcServiceTest, can_send_and_respond_to_request_end_to_end) {
    auto cmd = _node_0->create_dummy_put_command();
    cmd->setAddress(_node_1->node_address());
    _node_0->send_request_verify_not_bounced(cmd);

    auto recv_msg = _node_1->wait_and_receive_single_message();
    auto* put_cmd = dynamic_cast<api::PutCommand*>(recv_msg.get());
    ASSERT_TRUE(put_cmd != nullptr);
    auto reply = std::shared_ptr<api::StorageReply>(put_cmd->makeReply());
    _node_1->send_response(reply);

    auto recv_reply = _node_0->wait_and_receive_single_message();
    auto* put_reply = dynamic_cast<api::PutReply*>(recv_reply.get());
    ASSERT_TRUE(put_reply != nullptr);
}

TEST_F(StorageApiRpcServiceTest, send_to_unknown_address_bounces_with_error_reply) {
    auto cmd = _node_0->create_dummy_put_command();
    cmd->setAddress(non_existing_address());
    _node_0->send_request(cmd);

    auto bounced_msg = _node_0->wait_and_receive_single_message();
    auto* put_reply = dynamic_cast<api::PutReply*>(bounced_msg.get());
    ASSERT_TRUE(put_reply != nullptr);

    auto expected_code = static_cast<api::ReturnCode::Result>(mbus::ErrorCode::NO_ADDRESS_FOR_SERVICE);
    auto expected_msg = vespalib::make_string(
            "The address of service '%s' could not be resolved. It is not currently "
            "registered with the Vespa name server. "
            "The service must be having problems, or the routing configuration is wrong. "
            "Address resolution attempted from host '%s'",
            to_slobrok_id(non_existing_address()).c_str(), vespalib::HostName::get().c_str());

    EXPECT_EQ(put_reply->getResult(), api::ReturnCode(expected_code, expected_msg));
}

TEST_F(StorageApiRpcServiceTest, request_metadata_is_propagated_to_receiver) {
    auto recv_cmd = send_and_receive_put_command_at_node_1([](auto& cmd){
        cmd.getTrace().setLevel(7);
        cmd.setTimeout(1337s);
    });
    EXPECT_EQ(recv_cmd->getTrace().getLevel(), 7);
    EXPECT_EQ(recv_cmd->getTimeout(), 1337s);
}

TEST_F(StorageApiRpcServiceTest, response_trace_is_propagated_to_sender) {
    auto recv_cmd = send_and_receive_put_command_at_node_1([](auto& cmd){
        cmd.getTrace().setLevel(1);
    });
    auto recv_reply = respond_and_receive_put_reply_at_node_0(recv_cmd, [](auto& reply){
        reply.getTrace().trace(1, "Doing cool things", false);
    });
    auto trace_str = recv_reply->getTrace().toString();
    EXPECT_THAT(trace_str, HasSubstr("Doing cool things"));
}

TEST_F(StorageApiRpcServiceTest, response_trace_only_propagated_if_trace_level_set) {
    auto recv_cmd = send_and_receive_put_command_at_node_1();
    auto recv_reply = respond_and_receive_put_reply_at_node_0(recv_cmd, [](auto& reply){
        reply.getTrace().trace(1, "Doing cool things", false);
    });
    auto trace_str = recv_reply->getTrace().toString();
    EXPECT_THAT(trace_str, Not(HasSubstr("Doing cool things")));
}

}