summaryrefslogtreecommitdiff
path: root/src/mongo/rpc/rewrite_state_change_errors_test.cpp
blob: 66cda0cd0c227e1d6341bc13c9bb62c857681a5b (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
/**
 *    Copyright (C) 2021-present MongoDB, Inc.
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the Server Side Public License, version 1,
 *    as published by MongoDB, Inc.
 *
 *    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
 *    Server Side Public License for more details.
 *
 *    You should have received a copy of the Server Side Public License
 *    along with this program. If not, see
 *    <http://www.mongodb.com/licensing/server-side-public-license>.
 *
 *    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 Server Side 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/rpc/rewrite_state_change_errors.h"

#include "mongo/base/error_codes.h"
#include "mongo/bson/bsonobj.h"
#include "mongo/bson/bsonobjbuilder.h"
#include "mongo/db/service_context.h"
#include "mongo/rpc/message.h"
#include "mongo/rpc/op_msg.h"
#include "mongo/s/is_mongos.h"
#include "mongo/unittest/unittest.h"

namespace mongo::rpc {
namespace {

class RewriteStateChangeErrorsTest : public unittest::Test {
public:
    void setUp() override {
        _savedIsMongos = isMongos();
        setMongos(true);  // whole feature only happens on mongos
        RewriteStateChangeErrors::setEnabled(&*sc, true);
    }

    void tearDown() override {
        setMongos(_savedIsMongos);
    }

    /** Run rewrite on `obj` and return what it was remapped to if anything. */
    BSONObj rewriteObj(const BSONObj& obj) {
        if (auto newDoc = RewriteStateChangeErrors::rewrite(obj, &*opCtx))
            return *newDoc;
        return obj;
    }

    /** Make an error node corresponding to `ec`. */
    BSONObj errorObject(ErrorCodes::Error ec) {
        BSONObjBuilder bob;
        if (ec == ErrorCodes::OK)
            bob.append("ok", 1.);
        else
            bob.append("ok", 0.)
                .append("code", static_cast<int>(ec))
                .append("codeName", ErrorCodes::errorString(ec));
        return bob.obj();
    }

    /** Make an error node corresponding to `ec` with `errmsg`. */
    BSONObj errorObject(ErrorCodes::Error ec, std::string errmsg) {
        return BSONObjBuilder(errorObject(ec)).append("errmsg", errmsg).obj();
    }

    /** A few codes and what we expect them to be rewritten to. */
    struct InOutCode {
        ErrorCodes::Error in;
        ErrorCodes::Error out;
    };
    static constexpr InOutCode errorCodeScenarios[] = {
        {ErrorCodes::InterruptedAtShutdown, ErrorCodes::HostUnreachable},
        {ErrorCodes::ShutdownInProgress, ErrorCodes::HostUnreachable},
        {ErrorCodes::OK, ErrorCodes::OK},
        {ErrorCodes::BadValue, ErrorCodes::BadValue},
    };

    ServiceContext::UniqueServiceContext sc = ServiceContext::make();
    ServiceContext::UniqueClient cc = sc->makeClient("test", nullptr);
    ServiceContext::UniqueOperationContext opCtx = sc->makeOperationContext(cc.get());

private:
    bool _savedIsMongos;
};

// Rewrite Shutdown errors received from proxied commands.
TEST_F(RewriteStateChangeErrorsTest, Enabled) {
    for (auto&& [in, out] : errorCodeScenarios) {
        ASSERT_BSONOBJ_EQ(rewriteObj(errorObject(in)), errorObject(out));
    }
}

// Check that rewrite behavior can be disabled per-ServiceContext.
TEST_F(RewriteStateChangeErrorsTest, Disabled) {
    RewriteStateChangeErrors::setEnabled(&*sc, false);
    ASSERT_BSONOBJ_EQ(rewriteObj(errorObject(ErrorCodes::InterruptedAtShutdown)),
                      errorObject(ErrorCodes::InterruptedAtShutdown));
}

// Check that rewrite behavior can be disabled per-opCtx.
TEST_F(RewriteStateChangeErrorsTest, DisabledOpCtx) {
    RewriteStateChangeErrors::setEnabled(&*opCtx, false);
    ASSERT_BSONOBJ_EQ(rewriteObj(errorObject(ErrorCodes::InterruptedAtShutdown)),
                      errorObject(ErrorCodes::InterruptedAtShutdown));
}

// If locally shutting down, then shutdown errors must not be rewritten.
TEST_F(RewriteStateChangeErrorsTest, LocalShutdown) {
    sc->setKillAllOperations();
    ASSERT_BSONOBJ_EQ(rewriteObj(errorObject(ErrorCodes::InterruptedAtShutdown)),
                      errorObject(ErrorCodes::InterruptedAtShutdown));
}

TEST_F(RewriteStateChangeErrorsTest, RewriteErrmsg) {
    const std::pair<std::string, std::string> scenarios[] = {
        {"not master", "(NOT_PRIMARY)"},
        {"node is recovering", "(NODE_IS_RECOVERING)"},
        {"NOT master", "NOT master"},
        {"", ""},
        {" not masternot master ", " (NOT_PRIMARY)(NOT_PRIMARY) "},
        {"not masternode is recovering", "(NOT_PRIMARY)(NODE_IS_RECOVERING)"},
    };
    for (auto&& io : scenarios) {
        ASSERT_BSONOBJ_EQ(rewriteObj(errorObject(ErrorCodes::InterruptedAtShutdown, io.first)),
                          errorObject(ErrorCodes::HostUnreachable, io.second));
    }
}

// Can find and rewrite the `writeConcernError` in an `ok:1` response.
TEST_F(RewriteStateChangeErrorsTest, WriteConcernError) {
    // Make an OK object, and append a `writeConcernError` subobject bearing the `ec` error.
    auto wceObject = [&](ErrorCodes::Error ec) {
        return BSONObjBuilder(errorObject(ErrorCodes::OK))
            .append("writeConcernError", errorObject(ec))
            .obj();
    };
    for (auto&& [in, out] : errorCodeScenarios) {
        ASSERT_BSONOBJ_EQ(rewriteObj(wceObject(in)), wceObject(out));
    }
}

// Can find and rewrite the `writeErrors` array elements in an `ok:1` response.
TEST_F(RewriteStateChangeErrorsTest, WriteErrors) {
    // Make an OK object, and append a `writeErrors` subobject bearing the `ec` errors.
    auto weObject = [&](std::vector<ErrorCodes::Error> ecVec) {
        BSONObjBuilder bob(errorObject(ErrorCodes::OK));
        {
            BSONArrayBuilder bab(bob.subarrayStart("writeErrors"));
            for (ErrorCodes::Error ec : ecVec)
                bab.append(errorObject(ec));
        }
        return bob.obj();
    };
    for (auto&& [in, out] : errorCodeScenarios) {
        ASSERT_BSONOBJ_EQ(rewriteObj(weObject({in})), weObject({out}));
    }
    // Now try all the errorCodeScenarios as a single array of `writeErrors`.
    std::vector<ErrorCodes::Error> allIn, allOut;
    for (auto&& [in, out] : errorCodeScenarios) {
        allIn.push_back(in);
        allOut.push_back(out);
    }
    ASSERT_BSONOBJ_EQ(rewriteObj(weObject(allIn)), weObject(allOut));
}

}  // namespace
}  // namespace mongo::rpc