summaryrefslogtreecommitdiff
path: root/src/mongo/db/pipeline/memory_usage_tracker.h
blob: 8bf1e6437c64967225013e2767fe4285443ea392 (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.
 */

#pragma once

#include <memory>
#include <utility>

#include "mongo/stdx/unordered_map.h"
#include "mongo/util/str.h"

namespace mongo {

/**
 * This is a utility class for tracking memory usage across multiple arbitrary operators or
 * functions, which are identified by their string names.
 */
class MemoryUsageTracker {
public:
    class PerFunctionMemoryTracker {
    public:
        explicit PerFunctionMemoryTracker(MemoryUsageTracker* base) : base(base){};
        PerFunctionMemoryTracker() = delete;

        void update(long long diff) {
            tassert(5578603,
                    str::stream() << "Underflow on memory tracking, attempting to add " << diff
                                  << " but only " << _currentMemoryBytes << " available",
                    diff >= 0 || _currentMemoryBytes >= std::abs(diff));
            set(_currentMemoryBytes + diff);
        }

        void set(long long total) {
            if (total > _maxMemoryBytes)
                _maxMemoryBytes = total;
            long long prior = _currentMemoryBytes;
            _currentMemoryBytes = total;
            base->update(total - prior);
        }

        auto currentMemoryBytes() const {
            return _currentMemoryBytes;
        }

        auto maxMemoryBytes() const {
            return _maxMemoryBytes;
        }

        MemoryUsageTracker* base = nullptr;

    private:
        // Maximum memory consumption thus far observed for this function.
        long long _maxMemoryBytes = 0;
        // Tracks the current memory footprint.
        long long _currentMemoryBytes = 0;
    };

    MemoryUsageTracker(bool allowDiskUse = false, size_t maxMemoryUsageBytes = 0)
        : _allowDiskUse(allowDiskUse), _maxAllowedMemoryUsageBytes(maxMemoryUsageBytes) {}

    /**
     * Sets the new total for 'name', and updates the current total memory usage.
     */
    void set(StringData name, long long total) {
        (*this)[name].set(total);
    }

    /**
     * Sets the new current memory usage in bytes.
     */
    void set(long long total) {
        _memoryUsageBytes = total;
        if (_memoryUsageBytes > _maxMemoryUsageBytes) {
            _maxMemoryUsageBytes = _memoryUsageBytes;
        }
    }

    /**
     * Resets both the total memory usage as well as the per-function memory usage, but retains the
     * current value for maximum total memory usage.
     */
    void resetCurrent() {
        for (auto& [_, funcTracker] : _functionMemoryTracker) {
            funcTracker.set(0);
        }
        _memoryUsageBytes = 0;
    }

    /**
     * Provides read-only access to the function memory tracker for 'name'.
     */
    const PerFunctionMemoryTracker& operator[](StringData name) const {
        auto it = _functionMemoryTracker.find(_key(name));
        tassert(5466400,
                str::stream() << "Invalid call to memory usage tracker, could not find function "
                              << name,
                it != _functionMemoryTracker.end());
        return it->second;
    }

    /**
     * Non-const version, creates a new element if one doesn't exist and returns a reference to it.
     */
    PerFunctionMemoryTracker& operator[](StringData name) {
        auto [it, _] = _functionMemoryTracker.try_emplace(_key(name), this);
        return it->second;
    }

    /**
     * Updates the memory usage for 'name' by adding 'diff' to the current memory usage for
     * that function. Also updates the total memory usage.
     */
    void update(StringData name, long long diff) {
        (*this)[name].update(diff);
    }

    /**
     * Updates total memory usage.
     */
    void update(long long diff) {
        tassert(5578602,
                str::stream() << "Underflow on memory tracking, attempting to add " << diff
                              << " but only " << _memoryUsageBytes << " available",
                diff >= 0 || (int)_memoryUsageBytes >= -1 * diff);
        set(_memoryUsageBytes + diff);
    }

    auto currentMemoryBytes() const {
        return _memoryUsageBytes;
    }
    auto maxMemoryBytes() const {
        return _maxMemoryUsageBytes;
    }

    bool withinMemoryLimit() const {
        return _memoryUsageBytes <= static_cast<long long>(_maxAllowedMemoryUsageBytes);
    }

    const bool _allowDiskUse;
    const size_t _maxAllowedMemoryUsageBytes;

private:
    static absl::string_view _key(StringData s) {
        return {s.rawData(), s.size()};
    }

    // Tracks current memory used.
    long long _memoryUsageBytes = 0;
    long long _maxMemoryUsageBytes = 0;

    // Tracks memory consumption per function using the output field name as a key.
    stdx::unordered_map<std::string, PerFunctionMemoryTracker> _functionMemoryTracker;
};

}  // namespace mongo