aboutsummaryrefslogtreecommitdiffstats
path: root/messagebus/src/vespa/messagebus/messagebus.cpp
blob: fc3950649d62768936c6cb41f385a0445c443a32 (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
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
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "messagebus.h"
#include "messenger.h"
#include "emptyreply.h"
#include "errorcode.h"
#include "sendproxy.h"
#include "protocolrepository.h"
#include <vespa/messagebus/network/inetwork.h>
#include <vespa/vespalib/util/exceptions.h>
#include <vespa/vespalib/util/gate.h>

#include <vespa/log/log.h>
LOG_SETUP(".messagebus");

using vespalib::make_string;
using namespace std::chrono_literals;

namespace {

/**
 * Implements a task for running the resender in the messenger thread. This task
 * acts as a proxy for the resender, allowing the task to be deleted without
 * affecting the resender itself.
 */
class ResenderTask : public mbus::Messenger::ITask {
private:
    mbus::Resender *_resender;

public:
    explicit ResenderTask(mbus::Resender &resender)
        : _resender(&resender)
    {
        // empty
    }

    void run() override {
        _resender->resendScheduled();
    }

    [[nodiscard]] uint8_t priority() const override {
        return 255;
    }
};

/**
 * Implements a task for monitoring shutdown of the messenger thread. This task
 * helps to determine whether or not there is any work left in either the
 * messenger or network thread.
 */
class ShutdownTask : public mbus::Messenger::ITask {
private:
    mbus::INetwork  &_net;
    mbus::Messenger &_msn;
    bool            &_done;
    vespalib::Gate  &_gate;

public:
    ShutdownTask(mbus::INetwork &net, mbus::Messenger &msn,
                 bool &done, vespalib::Gate &gate)
        : _net(net),
          _msn(msn),
          _done(done),
          _gate(gate)
    { }

    ~ShutdownTask() override {
        _gate.countDown();
    }

    void run() override {
        _net.postShutdownHook();
        _done = _msn.isEmpty();
    }

    [[nodiscard]] uint8_t priority() const override {
        return 255;
    }
};

} // anonymous

namespace mbus {

MessageBus::MessageBus(INetwork &net, ProtocolSet protocols) :
    _network(net),
    _lock(),
    _routingTables(),
    _sessions(),
    _protocolRepository(std::make_unique<ProtocolRepository>()),
    _msn(std::make_unique<Messenger>()),
    _resender(),
    _maxPendingCount(0),
    _maxPendingSize(0),
    _pendingCount(0),
    _pendingSize(0)
{
    MessageBusParams params;
    while (!protocols.empty()) {
        IProtocol::SP protocol = protocols.extract();
        if (protocol) {
            params.addProtocol(protocol);
        }
    }
    setup(params);
}

MessageBus::MessageBus(INetwork &net, const MessageBusParams &params) :
    _network(net),
    _lock(),
    _routingTables(),
    _sessions(),
    _protocolRepository(std::make_unique<ProtocolRepository>()),
    _msn(std::make_unique<Messenger>()),
    _resender(),
    _maxPendingCount(params.getMaxPendingCount()),
    _maxPendingSize(params.getMaxPendingSize()),
    _pendingCount(0),
    _pendingSize(0)
{
    setup(params);
}

MessageBus::~MessageBus()
{
    // all sessions must have been destroyed prior to this,
    // so no more traffic from clients
    _msn->discardRecurrentTasks(); // no more traffic from recurrent tasks
    _network.shutdown(); // no more traffic from network

    bool done = false;
    while (!done) {
        vespalib::Gate gate;
        _msn->enqueue(std::make_unique<ShutdownTask>(_network, *_msn, done, gate));
        gate.await();
    }
}

void
MessageBus::setup(const MessageBusParams &params)
{
    // Add all known protocols to the repository.
    for (uint32_t i = 0, len = params.getNumProtocols(); i < len; ++i) {
        _protocolRepository->putProtocol(params.getProtocol(i));
    }

    // Attach and start network.
    _network.attach(*this);
    if (!_network.start()) {
        throw vespalib::NetworkSetupFailureException("Failed to start network.");
    }
    if (!_network.waitUntilReady(120s)) {
        throw vespalib::NetworkSetupFailureException("Network failed to become ready in time.");
    }

    // Start messenger.
    IRetryPolicy::SP retryPolicy = params.getRetryPolicy();
    if (retryPolicy) {
        _resender = std::make_unique<Resender>(retryPolicy);

        _msn->addRecurrentTask(std::make_unique<ResenderTask>(*_resender));
    }
    if (!_msn->start()) {
        throw vespalib::NetworkSetupFailureException("Failed to start messenger.");
    }
}

SourceSession::UP
MessageBus::createSourceSession(IReplyHandler &handler)
{
    return createSourceSession(SourceSessionParams().setReplyHandler(handler));
}

SourceSession::UP
MessageBus::createSourceSession(IReplyHandler &handler,
                                const SourceSessionParams &params)
{
    return createSourceSession(SourceSessionParams(params).setReplyHandler(handler));
}

SourceSession::UP
MessageBus::createSourceSession(const SourceSessionParams &params)
{
    return SourceSession::UP(new SourceSession(*this, params));
}

IntermediateSession::UP
MessageBus::createIntermediateSession(const string &name,
                                      bool broadcastName,
                                      IMessageHandler &msgHandler,
                                      IReplyHandler &replyHandler)
{
    return createIntermediateSession(IntermediateSessionParams()
                                     .setName(name)
                                     .setBroadcastName(broadcastName)
                                     .setMessageHandler(msgHandler)
                                     .setReplyHandler(replyHandler));
}

IntermediateSession::UP
MessageBus::createIntermediateSession(const IntermediateSessionParams &params)
{
    std::lock_guard guard(_lock);
    IntermediateSession::UP ret(new IntermediateSession(*this, params));
    _sessions[params.getName()] = ret.get();
    if (params.getBroadcastName()) {
        _network.registerSession(params.getName());
    }
    return ret;
}

DestinationSession::UP
MessageBus::createDestinationSession(const string &name,
                                     bool broadcastName,
                                     IMessageHandler &handler)
{
    return createDestinationSession(DestinationSessionParams()
                                    .setName(name)
                                    .setBroadcastName(broadcastName)
                                    .setMessageHandler(handler));
}

DestinationSession::UP
MessageBus::createDestinationSession(const DestinationSessionParams &params)
{
    std::lock_guard guard(_lock);
    DestinationSession::UP ret(new DestinationSession(*this, params));
    if (!params.defer_registration()) {
        _sessions[params.getName()] = ret.get();
        if (params.getBroadcastName()) {
            _network.registerSession(params.getName());
        }
    }
    return ret;
}

void
MessageBus::register_session(IMessageHandler& session, const string& session_name, bool broadcast_name)
{
    std::lock_guard guard(_lock);
    assert(!_sessions.contains(session_name));
    _sessions[session_name] = &session;
    if (broadcast_name) {
        _network.registerSession(session_name);
    }
}

void
MessageBus::unregisterSession(const string &sessionName)
{
    std::lock_guard guard(_lock);
    _network.unregisterSession(sessionName);
    _sessions.erase(sessionName);
}

RoutingTable::SP
MessageBus::getRoutingTable(const string &protocol)
{
    std::lock_guard guard(_lock);
    auto itr = _routingTables.find(protocol);
    if (itr == _routingTables.end()) {
        return {}; // not found
    }
    return itr->second;
}

IRoutingPolicy::SP
MessageBus::getRoutingPolicy(const string &protocolName,
                             const string &policyName,
                             const string &policyParam)
{
    return _protocolRepository->getRoutingPolicy(protocolName, policyName, policyParam);
}

void
MessageBus::sync()
{
    _msn->sync();
    _network.sync(); // should not be necessary, as msn is intermediate
}

void
MessageBus::handleMessage(Message::UP msg)
{
    if (_resender && msg->hasBucketSequence()) {
        deliverError(std::move(msg), ErrorCode::SEQUENCE_ERROR,
                     "Bucket sequences not supported when resender is enabled.");
        return;
    }
    SendProxy &proxy = *(new SendProxy(*this, _network, _resender.get())); // deletes self
    _msn->deliverMessage(std::move(msg), proxy);
}

bool
MessageBus::setupRouting(RoutingSpec spec)
{
    std::map<string, RoutingTable::SP> rtm;
    for (uint32_t i = 0; i < spec.getNumTables(); ++i) {
        const RoutingTableSpec &cfg = spec.getTable(i);
        if (getProtocol(cfg.getProtocol()) == nullptr) { // protocol not found
            LOG(info, "Protocol '%s' is not supported, ignoring routing table.", cfg.getProtocol().c_str());
            continue;
        }
        rtm[cfg.getProtocol()] = std::make_shared<RoutingTable>(cfg);
    }
    {
        std::lock_guard guard(_lock);
        std::swap(_routingTables, rtm);
    }
    _protocolRepository->clearPolicyCache();
    return true;
}

IProtocol *
MessageBus::getProtocol(const string &name)
{
    return _protocolRepository->getProtocol(name);
}

IProtocol::SP
MessageBus::putProtocol(const IProtocol::SP & protocol)
{
    return _protocolRepository->putProtocol(protocol);
}

bool
MessageBus::checkPending(Message &msg)
{
    bool busy = false;
    const uint32_t size = msg.getApproxSize();
    {
        constexpr auto relaxed = std::memory_order_relaxed;
        const uint32_t maxCount = _maxPendingCount.load(relaxed);
        const uint32_t maxSize = _maxPendingSize.load(relaxed);
        if (maxCount > 0 || maxSize > 0) {
            busy = ((maxCount > 0 && _pendingCount.load(relaxed) >= maxCount) ||
                    (maxSize > 0 && _pendingSize.load(relaxed) >= maxSize));
            if (!busy) {
                _pendingCount.fetch_add(1, relaxed);
                _pendingSize.fetch_add(size, relaxed);
            }
        }
    }
    if (busy) {
        return false;
    }
    msg.setContext(Context(static_cast<uint64_t>(size)));
    msg.pushHandler(*this, *this);
    return true;
}

void
MessageBus::handleReply(Reply::UP reply)
{
    _pendingCount.fetch_sub(1, std::memory_order_relaxed);
    _pendingSize.fetch_sub(reply->getContext().value.UINT64,
                           std::memory_order_relaxed);
    IReplyHandler &handler = reply->getCallStack().pop(*reply);
    deliverReply(std::move(reply), handler);
}

void
MessageBus::handleDiscard(Context ctx)
{
    _pendingCount.fetch_sub(1, std::memory_order_relaxed);
    _pendingSize.fetch_sub(ctx.value.UINT64, std::memory_order_relaxed);
}

void
MessageBus::deliverMessage(Message::UP msg, const string &session)
{
    IMessageHandler *msgHandler = nullptr;
    {
        std::lock_guard guard(_lock);
        auto it = _sessions.find(session);
        if (it != _sessions.end()) {
            msgHandler = it->second;
        }
    }
    if (msgHandler == nullptr) {
        deliverError(std::move(msg), ErrorCode::UNKNOWN_SESSION,
                     make_string("Session '%s' does not exist.", session.c_str()));
    } else if (!checkPending(*msg)) {
        deliverError(std::move(msg), ErrorCode::SESSION_BUSY,
                     make_string("Session '%s' is busy, try again later.", session.c_str()));
    } else {
        _msn->deliverMessage(std::move(msg), *msgHandler);
    }
}

void
MessageBus::deliverError(Message::UP msg, uint32_t errCode, const string &errMsg)
{
    auto reply = std::make_unique<EmptyReply>();
    reply->swapState(*msg);
    reply->addError(Error(errCode, errMsg));

    IReplyHandler &replyHandler = reply->getCallStack().pop(*reply);
    deliverReply(std::move(reply), replyHandler);
}

void
MessageBus::deliverReply(Reply::UP reply, IReplyHandler &handler)
{
    _msn->deliverReply(std::move(reply), handler);
}

string
MessageBus::getConnectionSpec() const
{
    return _network.getConnectionSpec();
}

void
MessageBus::setMaxPendingCount(uint32_t maxCount)
{
    _maxPendingCount.store(maxCount, std::memory_order_relaxed);
}

void
MessageBus::setMaxPendingSize(uint32_t maxSize)
{
    _maxPendingSize.store(maxSize, std::memory_order_relaxed);
}

} // namespace mbus