summaryrefslogtreecommitdiff
path: root/src/mongo/executor/downconvert_find_and_getmore_commands.cpp
blob: 667c955988ffe1cd17676ab2c1919ab94344fb51 (plain)
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
/**
 *    Copyright (C) 2015 MongoDB Inc.
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *    As a special exception, the copyright holders give permission to link the
 *    code of portions of this program with the OpenSSL library under certain
 *    conditions as described in each individual source file and distribute
 *    linked combinations including the program with the OpenSSL library. You
 *    must comply with the GNU Affero General Public License in all respects for
 *    all of the code used other than as permitted herein. If you modify file(s)
 *    with this exception, you may extend this exception to your version of the
 *    file(s), but you are not obligated to do so. If you do not wish to do so,
 *    delete this exception statement from your version. If you delete this
 *    exception statement from all source files in the program, then also delete
 *    it in the license file.
 */

#include "mongo/platform/basic.h"

#include "mongo/executor/downconvert_find_and_getmore_commands.h"

#include <memory>
#include <string>
#include <tuple>

#include "mongo/base/data_range_cursor.h"
#include "mongo/base/data_type_validated.h"
#include "mongo/base/status_with.h"
#include "mongo/client/constants.h"
#include "mongo/client/dbclientinterface.h"
#include "mongo/db/cursor_id.h"
#include "mongo/db/namespace_string.h"
#include "mongo/db/query/cursor_response.h"
#include "mongo/db/query/getmore_request.h"
#include "mongo/executor/remote_command_request.h"
#include "mongo/executor/remote_command_response.h"
#include "mongo/rpc/get_status_from_command_result.h"
#include "mongo/rpc/metadata/server_selection_metadata.h"
#include "mongo/rpc/object_check.h"
#include "mongo/util/assert_util.h"
#include "mongo/util/net/message.h"

namespace mongo {
namespace executor {

namespace {

StatusWith<std::tuple<CursorId, BSONArray>> getBatchFromReply(std::int32_t requestId,
                                                              const Message& response) {
    auto header = response.header();
    if (header.getNetworkOp() != mongo::opReply) {
        return {ErrorCodes::ProtocolError,
                str::stream() << "Expected to be decoding an OP_REPLY but got "
                              << mongo::networkOpToString(header.getNetworkOp())};
    }

    if (header.getResponseToMsgId() != requestId) {
        return {ErrorCodes::ProtocolError,
                str::stream() << "responseTo field of OP_REPLY header with value '"
                              << header.getResponseToMsgId()
                              << "' does not match requestId '"
                              << requestId
                              << "'"};
    }

    if ((header.dataLen() < 0) ||
        (static_cast<std::size_t>(header.dataLen()) > mongo::MaxMessageSizeBytes)) {
        return {ErrorCodes::InvalidLength,
                str::stream() << "Received message has invalid length field with value "
                              << header.dataLen()};
    }

    QueryResult::View qr = response.header().view2ptr();

    auto resultFlags = qr.getResultFlags();

    if (resultFlags & ResultFlag_CursorNotFound) {
        return {ErrorCodes::CursorNotFound,
                str::stream() << "Cursor with id '" << qr.getCursorId() << "' not found"};
    }

    // Use CDRC directly instead of DocumentRange as DocumentRange has a throwing API.
    ConstDataRangeCursor cdrc{qr.data(), qr.data() + header.dataLen()};

    if (resultFlags & ResultFlag_ErrSet) {
        if (qr.getNReturned() != 1) {
            return {ErrorCodes::BadValue,
                    str::stream() << "ResultFlag_ErrSet flag set on reply, but nReturned was '"
                                  << qr.getNReturned()
                                  << "' - expected 1"};
        }
        // Convert error document to a Status.
        // Will throw if first document is invalid BSON.
        auto first = cdrc.readAndAdvance<Validated<BSONObj>>();
        if (!first.isOK()) {
            return first.getStatus();
        }

        // Convert error document to a status.
        return getStatusFromCommandResult(first.getValue());
    }

    Validated<BSONObj> nextObj;
    BSONArrayBuilder batch;
    while (!cdrc.empty() && batch.arrSize() < qr.getNReturned()) {
        auto readStatus = cdrc.readAndAdvance(&nextObj);
        if (!readStatus.isOK()) {
            return readStatus;
        }
        batch.append(nextObj.val);
    }
    if (qr.getNReturned() != batch.arrSize()) {
        return {ErrorCodes::InvalidLength,
                str::stream() << "Count of documents in OP_REPLY message (" << batch.arrSize()
                              << ") did not match the value specified in the nReturned field ("
                              << qr.getNReturned()
                              << ")"};
    }

    return {std::make_tuple(qr.getCursorId(), batch.arr())};
}

}  // namespace

StatusWith<Message> downconvertFindCommandRequest(const RemoteCommandRequest& request) {
    const auto& cmdObj = request.cmdObj;
    const NamespaceString nss(request.dbname, cmdObj.firstElement().String());
    if (!nss.isValid()) {
        return {ErrorCodes::InvalidNamespace,
                str::stream() << "Invalid collection name: " << nss.ns()};
    }

    const std::string& ns = nss.ns();

    // It is a little heavy handed to use LiteParsedQuery to convert the command object to
    // query() arguments but we get validation and consistent behavior with the find
    // command implementation on the remote server.
    auto lpqStatus = LiteParsedQuery::makeFromFindCommand(nss, cmdObj, false);
    if (!lpqStatus.isOK()) {
        return lpqStatus.getStatus();
    }

    auto lpq = std::move(lpqStatus.getValue());

    // We are downconverting a find command, and find command can only have ntoreturn
    // if it was generated by mongos.
    invariant(!lpq->getNToReturn());
    Query query(lpq->getFilter());
    if (!lpq->getSort().isEmpty()) {
        query.sort(lpq->getSort());
    }
    if (!lpq->getHint().isEmpty()) {
        query.hint(lpq->getHint());
    }
    if (!lpq->getMin().isEmpty()) {
        query.minKey(lpq->getMin());
    }
    if (!lpq->getMax().isEmpty()) {
        query.minKey(lpq->getMax());
    }
    if (lpq->isExplain()) {
        query.explain();
    }
    if (lpq->isSnapshot()) {
        query.snapshot();
    }

    const int nToReturn = lpq->getLimit().value_or(0) * -1;
    const int nToSkip = lpq->getSkip().value_or(0);
    const BSONObj* fieldsToReturn = &lpq->getProj();
    int queryOptions = lpq->getOptions();  // non-const so we can set slaveOk if we need to
    const int batchSize = lpq->getBatchSize().value_or(0);

    const int nextBatchSize = [batchSize, nToReturn]() {
        if (nToReturn == 0)
            return batchSize;
        if (batchSize == 0)
            return nToReturn;
        return batchSize < nToReturn ? batchSize : nToReturn;
    }();

    // We can't downconvert all metadata, since we aren't sending a command, but we do need to
    // downconvert $secondaryOk to the slaveOK bit.
    auto ssm = rpc::ServerSelectionMetadata::readFromMetadata(
        request.metadata.getField(rpc::ServerSelectionMetadata::fieldName()));
    if (!ssm.isOK()) {
        return ssm.getStatus();
    }
    if (ssm.getValue().isSecondaryOk()) {
        queryOptions |= mongo::QueryOption_SlaveOk;
    }

    Message message;
    assembleQueryRequest(
        ns, query.obj, nextBatchSize, nToSkip, fieldsToReturn, queryOptions, message);

    return {std::move(message)};
}

StatusWith<RemoteCommandResponse> upconvertLegacyQueryResponse(std::int32_t requestId,
                                                               StringData cursorNamespace,
                                                               const Message& response) {
    auto swBatch = getBatchFromReply(requestId, response);
    if (!swBatch.isOK()) {
        return swBatch.getStatus();
    }

    BSONArray batch;
    CursorId cursorId;
    std::tie(cursorId, batch) = std::move(swBatch.getValue());

    BSONObjBuilder result;
    appendCursorResponseObject(cursorId, cursorNamespace, std::move(batch), &result);
    // Using Command::appendCommandStatus would create a circular dep, so it's simpler to just do
    // this.
    result.append("ok", 1.0);

    RemoteCommandResponse upconvertedResponse;
    upconvertedResponse.data = result.obj();

    return {std::move(upconvertedResponse)};
}

StatusWith<Message> downconvertGetMoreCommandRequest(const RemoteCommandRequest& request) {
    auto swGetMoreRequest = GetMoreRequest::parseFromBSON(request.dbname, request.cmdObj);
    if (!swGetMoreRequest.isOK()) {
        return swGetMoreRequest.getStatus();
    }

    auto getMoreRequest = std::move(swGetMoreRequest.getValue());

    BufBuilder b;
    b.appendNum(std::int32_t{0});  // reserved bits
    b.appendStr(getMoreRequest.nss.ns());
    // Without this static cast, we will append batchSize as an int64 and get an invalid message.
    b.appendNum(static_cast<std::int32_t>(getMoreRequest.batchSize.value_or(0)));
    b.appendNum(getMoreRequest.cursorid);
    Message m;
    m.setData(dbGetMore, b.buf(), b.len());

    return {std::move(m)};
}

StatusWith<RemoteCommandResponse> upconvertLegacyGetMoreResponse(std::int32_t requestId,
                                                                 StringData cursorNamespace,
                                                                 const Message& response) {
    auto swBatch = getBatchFromReply(requestId, response);
    if (!swBatch.isOK()) {
        return swBatch.getStatus();
    }

    BSONArray batch;
    CursorId cursorId;

    std::tie(cursorId, batch) = std::move(swBatch.getValue());

    BSONObjBuilder result;
    appendGetMoreResponseObject(cursorId, cursorNamespace, std::move(batch), &result);
    result.append("ok", 1.0);

    RemoteCommandResponse resp;
    resp.data = result.obj();

    return {std::move(resp)};
}

}  // namespace mongo
}  // namespace executor