summaryrefslogtreecommitdiff
path: root/src/mongo/db/s/sharding_data_transform_cumulative_metrics.h
blob: 5e6949cf001e10f31686743c6cc58c0f57bba849 (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
/**
 *    Copyright (C) 2022-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.
 */

#pragma once

#include "mongo/bson/bsonobjbuilder.h"
#include "mongo/db/s/sharding_data_transform_metrics_observer_interface.h"
#include "mongo/db/service_context.h"
#include "mongo/platform/atomic_word.h"
#include "mongo/platform/mutex.h"
#include "mongo/util/duration.h"
#include "mongo/util/functional.h"
#include <set>

namespace mongo {

class ShardingDataTransformCumulativeMetrics {
public:
    enum class CoordinatorStateEnum : int32_t {
        kUnused = -1,
        kInitializing,
        kPreparingToDonate,
        kCloning,
        kApplying,
        kBlockingWrites,
        kAborting,
        kCommitting,
        kDone,
        kNumStates
    };

    enum class DonorStateEnum : int32_t {
        kUnused = -1,
        kPreparingToDonate,
        kDonatingInitialData,
        kDonatingOplogEntries,
        kPreparingToBlockWrites,
        kError,
        kBlockingWrites,
        kDone,
        kNumStates
    };

    enum class RecipientStateEnum : int32_t {
        kUnused = -1,
        kAwaitingFetchTimestamp,
        kCreatingCollection,
        kCloning,
        kApplying,
        kError,
        kStrictConsistency,
        kDone,
        kNumStates
    };

    using Role = ShardingDataTransformMetrics::Role;
    using InstanceObserver = ShardingDataTransformMetricsObserverInterface;
    using DeregistrationFunction = unique_function<void()>;


    static ShardingDataTransformCumulativeMetrics* getForResharding(ServiceContext* context);
    static ShardingDataTransformCumulativeMetrics* getForGlobalIndexes(ServiceContext* context);

    ShardingDataTransformCumulativeMetrics(const std::string& rootSectionName);
    [[nodiscard]] DeregistrationFunction registerInstanceMetrics(const InstanceObserver* metrics);
    int64_t getOldestOperationHighEstimateRemainingTimeMillis(Role role) const;
    int64_t getOldestOperationLowEstimateRemainingTimeMillis(Role role) const;
    size_t getObservedMetricsCount() const;
    size_t getObservedMetricsCount(Role role) const;
    void reportForServerStatus(BSONObjBuilder* bob) const;

    void onStarted();
    void onSuccess();
    void onFailure();
    void onCanceled();

    void setLastOpEndingChunkImbalance(int64_t imbalanceCount);

    /**
     * The before can be boost::none to represent the initial state transition and
     * after can be boost::none to represent cases where it is no longer active.
     */
    template <typename T>
    void onStateTransition(boost::optional<T> before, boost::optional<T> after);

    void onReadDuringCriticalSection();
    void onWriteDuringCriticalSection();
    void onWriteToStashedCollections();

    void onInsertApplied();
    void onUpdateApplied();
    void onDeleteApplied();
    void onOplogEntriesFetched(int64_t numEntries, Milliseconds elapsed);
    void onOplogEntriesApplied(int64_t numEntries);
    void onCloningTotalRemoteBatchRetrieval(Milliseconds elapsed);
    void onOplogLocalBatchApplied(Milliseconds elapsed);

    static const char* fieldNameFor(CoordinatorStateEnum state);
    static const char* fieldNameFor(DonorStateEnum state);
    static const char* fieldNameFor(RecipientStateEnum state);

    void onInsertsDuringCloning(int64_t count, int64_t bytes, const Milliseconds& elapsedTime);
    void onLocalInsertDuringOplogFetching(const Milliseconds& elapsedTime);
    void onBatchRetrievedDuringOplogApplying(const Milliseconds& elapsedTime);

private:
    struct MetricsComparer {
        inline bool operator()(const InstanceObserver* a, const InstanceObserver* b) const {
            auto aTime = a->getStartTimestamp();
            auto bTime = b->getStartTimestamp();
            if (aTime == bTime) {
                return a->getUuid() < b->getUuid();
            }
            return aTime < bTime;
        }
    };
    using MetricsSet = std::set<const InstanceObserver*, MetricsComparer>;
    using CoordinatorStateArray =
        std::array<AtomicWord<int64_t>, static_cast<size_t>(CoordinatorStateEnum::kNumStates)>;
    using DonorStateArray =
        std::array<AtomicWord<int64_t>, static_cast<size_t>(DonorStateEnum::kNumStates)>;
    using RecipientStateArray =
        std::array<AtomicWord<int64_t>, static_cast<size_t>(RecipientStateEnum::kNumStates)>;

    void reportActive(BSONObjBuilder* bob) const;
    void reportOldestActive(BSONObjBuilder* bob) const;
    void reportLatencies(BSONObjBuilder* bob) const;
    void reportCurrentInSteps(BSONObjBuilder* bob) const;

    MetricsSet& getMetricsSetForRole(Role role);
    const MetricsSet& getMetricsSetForRole(Role role) const;
    const InstanceObserver* getOldestOperation(WithLock, Role role) const;

    template <typename T>
    const AtomicWord<int64_t>* getStateCounter(T state) const;
    template <typename T>
    AtomicWord<int64_t>* getMutableStateCounter(T state);

    CoordinatorStateArray* getStateArrayFor(CoordinatorStateEnum state);
    const CoordinatorStateArray* getStateArrayFor(CoordinatorStateEnum state) const;
    DonorStateArray* getStateArrayFor(DonorStateEnum state);
    const DonorStateArray* getStateArrayFor(DonorStateEnum state) const;
    RecipientStateArray* getStateArrayFor(RecipientStateEnum state);
    const RecipientStateArray* getStateArrayFor(RecipientStateEnum state) const;

    MetricsSet::iterator insertMetrics(const InstanceObserver* metrics, MetricsSet& set);

    mutable Mutex _mutex;
    const std::string _rootSectionName;
    std::vector<MetricsSet> _instanceMetricsForAllRoles;
    AtomicWord<bool> _operationWasAttempted;

    AtomicWord<int64_t> _countStarted{0};
    AtomicWord<int64_t> _countSucceeded{0};
    AtomicWord<int64_t> _countFailed{0};
    AtomicWord<int64_t> _countCancelled{0};

    AtomicWord<int64_t> _insertsApplied{0};
    AtomicWord<int64_t> _updatesApplied{0};
    AtomicWord<int64_t> _deletesApplied{0};
    AtomicWord<int64_t> _oplogEntriesApplied{0};
    AtomicWord<int64_t> _oplogEntriesFetched{0};

    AtomicWord<int64_t> _totalBatchRetrievedDuringClone{0};
    AtomicWord<int64_t> _totalBatchRetrievedDuringCloneMillis{0};
    AtomicWord<int64_t> _oplogBatchApplied{0};
    AtomicWord<int64_t> _oplogBatchAppliedMillis{0};
    AtomicWord<int64_t> _documentsCopied{0};
    AtomicWord<int64_t> _bytesCopied{0};

    AtomicWord<int64_t> _lastOpEndingChunkImbalance{0};
    AtomicWord<int64_t> _readsDuringCriticalSection{0};
    AtomicWord<int64_t> _writesDuringCriticalSection{0};

    CoordinatorStateArray _coordinatorStateList;
    DonorStateArray _donorStateList;
    RecipientStateArray _recipientStateList;

    AtomicWord<int64_t> _collectionCloningTotalLocalBatchInserts{0};
    AtomicWord<int64_t> _collectionCloningTotalLocalInsertTimeMillis{0};
    AtomicWord<int64_t> _oplogFetchingTotalRemoteBatchesRetrieved{0};
    AtomicWord<int64_t> _oplogFetchingTotalRemoteBatchesRetrievalTimeMillis{0};
    AtomicWord<int64_t> _oplogFetchingTotalLocalInserts{0};
    AtomicWord<int64_t> _oplogFetchingTotalLocalInsertTimeMillis{0};
    AtomicWord<int64_t> _oplogApplyingTotalBatchesRetrieved{0};
    AtomicWord<int64_t> _oplogApplyingTotalBatchesRetrievalTimeMillis{0};
    AtomicWord<int64_t> _writesToStashedCollections{0};
};

template <typename T>
void ShardingDataTransformCumulativeMetrics::onStateTransition(boost::optional<T> before,
                                                               boost::optional<T> after) {
    if (before) {
        if (auto counter = getMutableStateCounter(*before)) {
            counter->fetchAndSubtract(1);
        }
    }

    if (after) {
        if (auto counter = getMutableStateCounter(*after)) {
            counter->fetchAndAdd(1);
        }
    }
}

template <typename T>
const AtomicWord<int64_t>* ShardingDataTransformCumulativeMetrics::getStateCounter(T state) const {
    if (state == T::kUnused) {
        return nullptr;
    }

    invariant(static_cast<size_t>(state) < static_cast<size_t>(T::kNumStates));
    return &((*getStateArrayFor(state))[static_cast<size_t>(state)]);
}

template <typename T>
AtomicWord<int64_t>* ShardingDataTransformCumulativeMetrics::getMutableStateCounter(T state) {
    if (state == T::kUnused) {
        return nullptr;
    }

    invariant(static_cast<size_t>(state) < static_cast<size_t>(T::kNumStates));
    return &((*getStateArrayFor(state))[static_cast<size_t>(state)]);
}

}  // namespace mongo