summaryrefslogtreecommitdiff
path: root/src/mongo/rpc/metadata/server_selection_metadata.cpp
blob: 9100fc18c556e566828e1bb2382bfaeb13953dfc (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
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
/*
 *    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/rpc/metadata/server_selection_metadata.h"

#include <tuple>
#include <utility>

#include "mongo/base/status_with.h"
#include "mongo/bson/util/bson_extract.h"
#include "mongo/client/dbclientinterface.h"
#include "mongo/db/jsobj.h"
#include "mongo/db/operation_context.h"
#include "mongo/util/assert_util.h"

namespace mongo {
namespace rpc {


namespace {

// Symbolic constant for the "$secondaryOk" metadata field. This field should be of boolean or
// numeric type, and is treated as a boolean.
const char kSecondaryOkFieldName[] = "$secondaryOk";

// Symbolic constant for the "$readPreference" metadata field. The field should be of Object type
// when present.
const char kReadPreferenceFieldName[] = "$readPreference";

const char kQueryOptionsFieldName[] = "$queryOptions";

const char kDollarQueryWrapper[] = "$query";
const char kQueryWrapper[] = "query";

/**
 * Utility to unwrap a '$query' or 'query' wrapped command object. The first element of the
 * returned tuple indicates whether the command was unwrapped, and the second element is either
 * the unwrapped command (if it was wrapped), or the original command if it was not.
 */
StatusWith<std::tuple<bool, BSONObj>> unwrapCommand(const BSONObj& maybeWrapped) {
    const auto firstElFieldName = maybeWrapped.firstElementFieldName();

    if ((firstElFieldName != StringData(kDollarQueryWrapper)) &&
        (firstElFieldName != StringData(kQueryWrapper))) {
        return std::make_tuple(false, maybeWrapped);
    }

    BSONElement inner;
    auto extractStatus =
        bsonExtractTypedField(maybeWrapped, firstElFieldName, mongo::Object, &inner);

    if (!extractStatus.isOK()) {
        return extractStatus;
    }

    return std::make_tuple(true, inner.Obj());
}

/**
 * Reads a top-level $readPreference field from a wrapped command.
 */
Status extractWrappedReadPreference(const BSONObj& wrappedCommand, BSONObjBuilder* metadataBob) {
    BSONElement readPrefEl;
    auto rpExtractStatus =
        bsonExtractTypedField(wrappedCommand, kReadPreferenceFieldName, mongo::Object, &readPrefEl);
    if (rpExtractStatus.isOK()) {
        metadataBob->append(readPrefEl);
    } else if (rpExtractStatus != ErrorCodes::NoSuchKey) {
        return rpExtractStatus;
    }

    return Status::OK();
}

/**
 * Reads a $readPreference from a $queryOptions subobject, if it exists, and writes it to
 * metadataBob. Writes out the original command excluding the $queryOptions subobject.
 */
Status extractUnwrappedReadPreference(const BSONObj& unwrappedCommand,
                                      BSONObjBuilder* commandBob,
                                      BSONObjBuilder* metadataBob) {
    BSONElement queryOptionsEl;
    BSONElement readPrefEl;

    auto queryOptionsExtractStatus = bsonExtractTypedField(
        unwrappedCommand, kQueryOptionsFieldName, mongo::Object, &queryOptionsEl);

    // If there is no queryOptions subobject, we write out the command and return.
    if (queryOptionsExtractStatus == ErrorCodes::NoSuchKey) {
        commandBob->appendElements(unwrappedCommand);
        return Status::OK();
    } else if (!queryOptionsExtractStatus.isOK()) {
        return queryOptionsExtractStatus;
    }

    // Write out the command excluding the $queryOptions field.
    for (const auto& elem : unwrappedCommand) {
        if (elem.fieldNameStringData() != kQueryOptionsFieldName) {
            commandBob->append(elem);
        }
    }

    auto rpExtractStatus = bsonExtractTypedField(
        queryOptionsEl.embeddedObject(), kReadPreferenceFieldName, mongo::Object, &readPrefEl);

    // If there is a $queryOptions field, we expect there to be a $readPreference.
    if (!rpExtractStatus.isOK()) {
        return rpExtractStatus;
    }

    metadataBob->append(readPrefEl);
    return Status::OK();
}

}  // namespace

const OperationContext::Decoration<ServerSelectionMetadata> ServerSelectionMetadata::get =
    OperationContext::declareDecoration<ServerSelectionMetadata>();

ServerSelectionMetadata::ServerSelectionMetadata(
    bool secondaryOk, boost::optional<ReadPreferenceSetting> readPreference)
    : _secondaryOk(secondaryOk), _readPreference(std::move(readPreference)) {}

StatusWith<ServerSelectionMetadata> ServerSelectionMetadata::readFromMetadata(
    const BSONObj& metadataObj) {
    return readFromMetadata(metadataObj.getField(fieldName()));
}

StatusWith<ServerSelectionMetadata> ServerSelectionMetadata::readFromMetadata(
    const BSONElement& metadataElem) {
    if (metadataElem.eoo()) {
        return ServerSelectionMetadata{};
    } else if (metadataElem.type() != mongo::Object) {
        return {ErrorCodes::TypeMismatch,
                str::stream() << "ServerSelectionMetadata element has incorrect type: expected"
                              << mongo::Object
                              << " but got "
                              << metadataElem.type()};
    }

    bool secondaryOk = false;
    boost::optional<ReadPreferenceSetting> readPreference;
    BSONElement rpElem;
    for (const auto& ssmElem : metadataElem.Obj()) {
        auto ssmElemFieldName = ssmElem.fieldNameStringData();
        if (ssmElemFieldName == kSecondaryOkFieldName) {
            secondaryOk = ssmElem.trueValue();
        } else if (ssmElemFieldName == kReadPreferenceFieldName) {
            if (ssmElem.type() != mongo::Object) {
                return Status(ErrorCodes::TypeMismatch,
                              str::stream() << "ReadPreference has incorrect type: expected"
                                            << mongo::Object
                                            << "but got"
                                            << metadataElem.type());
            }
            auto parsedRps = ReadPreferenceSetting::fromBSON(ssmElem.Obj());
            if (!parsedRps.isOK()) {
                return parsedRps.getStatus();
            }
            readPreference.emplace(std::move(parsedRps.getValue()));
        }
    }

    return ServerSelectionMetadata(secondaryOk, std::move(readPreference));
}

Status ServerSelectionMetadata::writeToMetadata(BSONObjBuilder* metadataBob) const {
    BSONObjBuilder ssmBob;
    if (isSecondaryOk()) {
        ssmBob.append(kSecondaryOkFieldName, 1);
    }

    if (getReadPreference()) {
        ssmBob.append(kReadPreferenceFieldName, getReadPreference()->toBSON());
    }

    auto ssm = ssmBob.done();
    if (!ssm.isEmpty()) {
        metadataBob->append(fieldName(), ssm);
    }

    return Status::OK();
}

BSONObj ServerSelectionMetadata::toBSON() const {
    BSONObjBuilder bob;
    writeToMetadata(&bob);
    return bob.obj();
}

Status ServerSelectionMetadata::downconvert(const BSONObj& command,
                                            const BSONObj& metadata,
                                            BSONObjBuilder* legacyCommand,
                                            int* legacyQueryFlags) {
    auto ssmElem = metadata.getField(fieldName());
    if (ssmElem.eoo()) {
        // slaveOk is false by default.
        *legacyQueryFlags &= ~mongo::QueryOption_SlaveOk;
        legacyCommand->appendElements(command);
        return Status::OK();
    } else if (ssmElem.type() != mongo::Object) {
        return {
            ErrorCodes::TypeMismatch,
            str::stream() << "ServerSelectionMetadata metadata element must be an object, but got "
                          << typeName(ssmElem.type())};
    }

    auto ssmObj = ssmElem.Obj();
    BSONElement secondaryOkElem;
    BSONElement readPreferenceElem;

    for (auto&& el : ssmObj) {
        auto fname = el.fieldNameStringData();
        if (fname == kSecondaryOkFieldName) {
            secondaryOkElem = std::move(el);
        } else if (fname == kReadPreferenceFieldName) {
            readPreferenceElem = std::move(el);
        }
    }

    if (!secondaryOkElem.eoo() && secondaryOkElem.trueValue()) {
        *legacyQueryFlags |= mongo::QueryOption_SlaveOk;
    } else {
        *legacyQueryFlags &= ~mongo::QueryOption_SlaveOk;
    }

    if (!readPreferenceElem.eoo()) {
        // Use 'query' to wrap query, then append read preference.

        // NOTE(amidvidy): Oddly, the _isSecondaryQuery implementation in dbclient_rs does
        // not unwrap the query properly - it only checks for 'query', and not
        // '$query'. We should probably standardize on one - drivers use '$query',
        // and the shell uses 'query'. See SERVER-18705 for details.

        // TODO: this may need to use the $queryOptions hack on mongos.
        legacyCommand->append(kQueryWrapper, command);
        legacyCommand->append(readPreferenceElem);
    } else {
        legacyCommand->appendElements(command);
    }

    return Status::OK();
}

Status ServerSelectionMetadata::upconvert(const BSONObj& legacyCommand,
                                          const int legacyQueryFlags,
                                          BSONObjBuilder* commandBob,
                                          BSONObjBuilder* metadataBob) {
    // The secondaryOK option is equivalent to the slaveOk bit being set on legacy commands.
    BSONObjBuilder ssmBob;
    if (legacyQueryFlags & QueryOption_SlaveOk) {
        ssmBob.append(kSecondaryOkFieldName, 1);
    }

    // First we need to check if we have a wrapped command. That is, a command of the form
    // {'$query': { 'commandName': 1, ...}, '$someOption': 5, ....}. Curiously, the field name
    // of the wrapped query can be either '$query', or 'query'.
    auto swUnwrapped = unwrapCommand(legacyCommand);
    if (!swUnwrapped.isOK()) {
        return swUnwrapped.getStatus();
    }

    BSONObj maybeUnwrapped;
    bool wasWrapped;
    std::tie(wasWrapped, maybeUnwrapped) = swUnwrapped.getValue();

    if (wasWrapped) {
        // Check if legacyCommand has an invalid $maxTimeMS option.
        // TODO: Move this check elsewhere when we handle upconverting/downconverting maxTimeMS.
        if (legacyCommand.hasField("$maxTimeMS")) {
            return Status(ErrorCodes::InvalidOptions,
                          "cannot use $maxTimeMS query option with "
                          "commands; use maxTimeMS command option "
                          "instead");
        }

        // If the command was wrapped, we can write out the upconverted command now, as there
        // is nothing else we need to remove from it.
        commandBob->appendElements(maybeUnwrapped);

        auto status = extractWrappedReadPreference(legacyCommand, &ssmBob);
        if (!status.isOK()) {
            return status;
        }
    } else {
        // If the command was not wrapped, we need to check for a readPreference sent by mongos
        // on the $queryOptions field of the command. If it is set, we remove it from the
        // upconverted command, so we need to pass the command builder along.

        auto status = extractUnwrappedReadPreference(maybeUnwrapped, commandBob, &ssmBob);
        if (!status.isOK()) {
            return status;
        }
    }

    auto ssm = ssmBob.done();
    if (!ssm.isEmpty()) {
        metadataBob->append(fieldName(), ssm);
    }
    return Status::OK();
}

bool ServerSelectionMetadata::isSecondaryOk() const {
    return _secondaryOk;
}

const boost::optional<ReadPreferenceSetting>& ServerSelectionMetadata::getReadPreference() const {
    return _readPreference;
}

bool ServerSelectionMetadata::canRunOnSecondary() const {
    return _secondaryOk ||
        (_readPreference && (_readPreference->pref != ReadPreference::PrimaryOnly));
}

}  // rpc
}  // mongo