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

#include "storagelink.h"
#include <vespa/storageapi/messageapi/storagecommand.h>
#include <vespa/storageapi/messageapi/storagereply.h>
#include <vespa/vespalib/util/backtrace.h>
#include <sstream>
#include <cassert>

#include <vespa/log/bufferedlogger.h>
LOG_SETUP(".application.link");

using namespace storage::api;

namespace storage {

StorageLink::StorageLink(const std::string& name,
                         MsgDownOnFlush allow_msg_down_during_flushing,
                         MsgUpOnClosed allow_msg_up_during_closed)
    : _name(name),
      _up(nullptr),
      _down(),
      _state(CREATED),
      _msg_down_during_flushing(allow_msg_down_during_flushing),
      _msg_up_during_closed(allow_msg_up_during_closed)
{
}

StorageLink::StorageLink(const std::string& name)
    : StorageLink(name, MsgDownOnFlush::Disallowed, MsgUpOnClosed::Disallowed)
{
}

StorageLink::~StorageLink() {
    LOG(debug, "Destructing link %s.", toString().c_str());
}

void StorageLink::push_back(StorageLink::UP link)
{
    if (getState() != CREATED) {
        LOG(error, "Attempted to alter chain by adding link %s after link %s while state is %s",
            link->toString().c_str(), toString().c_str(), stateToString(getState()));
        assert(false);
    }
    assert(link);
    if (isBottom()) {
        link->_up = this;
        _down = std::move(link);
    } else {
        _down->push_back(std::move(link));
    }
}

void StorageLink::open()
{
    // First tag all states as opened, as components are allowed to send
    // messages both ways in onOpen call, in case any component send message
    // up, the link receiving them should have their state as opened.
    StorageLink* link = this;
    while (true) {
        if (link->getState() != CREATED) {
            LOG(error, "During open(), link %s should be in CREATED state, not in state %s.",
                toString().c_str(), stateToString(link->getState()));
            assert(false);
        }
        link->_state = OPENED;
        if (!link->_down) {
            break;
        }
        link = link->_down.get();
    }
    // When give all links an onOpen call, bottoms up. Do it bottoms up, as
    // links are more likely to send messages down in their onOpen() call
    // than up. Thus, chances are best that the component is ready to
    // receive messages sent during onOpen().
    while (link != nullptr) {
        link->onOpen();
        link = link->_up;
    }
}

void StorageLink::doneInit()
{
    StorageLink* link = this;
    while (true) {
        link->onDoneInit();
        if (!link->_down) {
            break;
        }
        link = link->_down.get();
    }
}

void StorageLink::close()
{
    _state = CLOSING;
    LOG(debug, "Start close link %s.", toString().c_str());
    onClose();
    if (!isBottom()) {
        _down->close();
    }
    LOG(debug, "End close link %s.", toString().c_str());
}

void StorageLink::closeNextLink() {
    LOG(debug, "Start closeNextLink link %s.", toString().c_str());
    _down.reset();
    LOG(debug, "End closeNextLink link %s.", toString().c_str());
}

void StorageLink::flush()
{
    if (getState() != CLOSING) {
        LOG(error, "During flush(), link %s should be in CLOSING state, not in state %s.",
            toString().c_str(), stateToString(getState()));
        assert(false);
    }
    // First flush down to get all requests out of the system.
    _state = FLUSHINGDOWN;
    LOG(debug, "Flushing link %s on the way down.", toString().c_str());
    onFlush(true);
    LOG(debug, "Flushed link %s on the way down.", toString().c_str());
    if (!isBottom()) {
        _down->flush();
        // Then flush up to get replies out of the system
        LOG(debug, "Flushing link %s on the way back up.", toString().c_str());
        _state = FLUSHINGUP;
        onFlush(false);
        LOG(debug, "Flushed link %s on the way back up.", toString().c_str());
    } else {
        // Then flush up to get replies out of the system
        LOG(debug, "Flushing link %s on the way back up.", toString().c_str());
        _state = FLUSHINGUP;
        onFlush(false);
        LOG(debug, "Flushed link %s on the way back up.", toString().c_str());
    }
    _state = CLOSED;
    LOG(debug, "Link %s is now closed and should do nothing more.", toString().c_str());
}

void StorageLink::sendDown(const StorageMessage::SP& msg)
{
    // Verify acceptable state to send messages down
    switch(getState()) {
        case OPENED:
        case CLOSING:
        case FLUSHINGDOWN:
            break;
        case FLUSHINGUP:
            if (_msg_down_during_flushing == MsgDownOnFlush::Allowed) {
                break;
            }
            [[fallthrough]];
        default:
            LOG(error, "Link %s trying to send %s down while in state %s. Stacktrace: %s",
                toString().c_str(), msg->toString().c_str(), stateToString(getState()),
                vespalib::getStackTrace(0).c_str());
            assert(false);
    }
    assert(msg);
    LOG(spam, "Storage Link %s to handle %s", toString().c_str(), msg->toString().c_str());
    if (isBottom()) {
        LOG(spam, "Storage link %s at bottom of chain got message %s.", toString().c_str(), msg->toString().c_str());
        std::ostringstream ost;
        ost << "Unhandled message at bottom of chain " << *msg << " (message type "
            << msg->getType().getName() << "). " << vespalib::getStackTrace(0);
        if (!msg->getType().isReply()) {
            LOGBP(warning, "%s", ost.str().c_str());
            auto& cmd = dynamic_cast<StorageCommand&>(*msg);
            std::shared_ptr<StorageReply> reply(cmd.makeReply());

            if (reply) {
                reply->setResult(ReturnCode(ReturnCode::NOT_IMPLEMENTED, msg->getType().getName()));
                sendUp(reply);
            }
        } else {
            ost << " Return code: " << dynamic_cast<const StorageReply&>(*msg).getResult();
            LOGBP(warning, "%s", ost.str().c_str());
        }
    } else if (!_down->onDown(msg)) {
        _down->sendDown(msg);
    } else {
        LOG(spam, "Storage link %s handled message %s.",
            _down->toString().c_str(), msg->toString().c_str());
    }
}

void StorageLink::sendUp(const std::shared_ptr<StorageMessage> & msg)
{
    // Verify acceptable state to send messages up
    switch(getState()) {
        case OPENED:
        case CLOSING:
        case FLUSHINGDOWN:
        case FLUSHINGUP:
            break;
        case CLOSED:
            if (_msg_up_during_closed == MsgUpOnClosed::Allowed) {
                break;
            }
            [[fallthrough]];
        default:
            LOG(error, "Link %s trying to send %s up while in state %s. Stacktrace: %s",
                toString().c_str(), msg->toString(true).c_str(), stateToString(getState()),
                vespalib::getStackTrace(0).c_str());
            assert(false);
    }
    assert(msg);
    if (isTop()) {
        std::ostringstream ost;
        ost << "Unhandled message at top of chain " << *msg << ".";
        ost << vespalib::getStackTrace(0);
        if (!msg->getType().isReply()) {
            LOGBP(warning, "%s", ost.str().c_str());
            auto& cmd = dynamic_cast<StorageCommand&>(*msg);
            std::shared_ptr<StorageReply> reply(cmd.makeReply());

            if (reply.get()) {
                reply->setResult(ReturnCode(ReturnCode::NOT_IMPLEMENTED, msg->getType().getName()));
                sendDown(reply);
            }
        } else {
            ost << " Return code: " << dynamic_cast<const StorageReply&>(*msg).getResult();
            LOGBP(warning, "%s", ost.str().c_str());
        }
    } else if (!_up->onUp(msg)) {
        _up->sendUp(msg);
    }
}

void StorageLink::printChain(std::ostream& out, std::string indent) const {
    out << indent << "StorageChain(" << size();
    if (!isTop()) out << ", not top";
    out << ")";
    const StorageLink* lastlink = _up;
    for (const StorageLink* link = this; link != nullptr; link = link->_down.get()) {
        out << "\n";
        link->print(out, false, indent + "  ");
        if (link->_up != lastlink) out << ", broken linkage";
        lastlink = link;
    }
}

bool StorageLink::onDown(const std::shared_ptr<StorageMessage> & msg)
{
    return msg->callHandler(*this, msg);
}

bool StorageLink::onUp(const std::shared_ptr<StorageMessage> & msg)
{
    return msg->callHandler(*this, msg);
}

void
StorageLink::print(std::ostream& out, bool, const std::string&) const
{
    out << getName();
}

const char*
StorageLink::stateToString(State state)
{
    switch (state) {
    case CREATED:
        return "CREATED";
    case OPENED:
        return "OPENED";
    case CLOSING:
        return "CLOSING";
    case FLUSHINGDOWN:
        return "FLUSHINGDOWN";
    case FLUSHINGUP:
        return "FLUSHINGUP";
    case CLOSED:
        return "CLOSED";
    default:
        abort();
    }
}

std::ostream&
operator<<(std::ostream& out, StorageLink& link) {
    link.printChain(out);
    return out;
}

Queue::Queue() = default;
Queue::~Queue() = default;

bool
Queue::getNext(std::shared_ptr<api::StorageMessage>& msg, vespalib::duration timeout) {
    std::unique_lock sync(_lock);
    bool first = true;
    while (true) { // Max twice
        if (!_queue.empty()) {
            LOG(spam, "Picking message from queue");
            msg = std::move(_queue.front());
            _queue.pop();
            return true;
        }
        if ((timeout == vespalib::duration::zero()) || !first) {
            return false;
        }
        _cond.wait_for(sync, timeout);
        first = false;
    }

    return false;
}

void
Queue::enqueue(std::shared_ptr<api::StorageMessage> msg) {
    std::lock_guard sync(_lock);
    _queue.emplace(std::move(msg));
    _cond.notify_one();
}

void
Queue::signal() {
    std::lock_guard sync(_lock);
    _cond.notify_one();
}

size_t
Queue::size() const {
    std::lock_guard guard(_lock);
    return _queue.size();
}

}