summaryrefslogtreecommitdiff
path: root/src/mongo/util/perfctr_collect.cpp
blob: c70f50fae3f8382b0a848b723683a99ad69f663e (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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
/**
 *    Copyright (C) 2018-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.
 */

#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kFTDC

#include "mongo/platform/basic.h"

#include "mongo/util/perfctr_collect.h"

#include "mongo/base/init.h"
#include "mongo/bson/bsonobjbuilder.h"
#include "mongo/util/log.h"
#include "mongo/util/scopeguard.h"
#include "mongo/util/str.h"
#include "mongo/util/text.h"

namespace mongo {

namespace {

// Handle to the PDH library so that we can format error messages.
HANDLE hPdhLibrary = nullptr;

/**
 * Load PDH.DLL for good error messages.
 */
MONGO_INITIALIZER(PdhInit)(InitializerContext* context) {

    hPdhLibrary = LoadLibraryW(L"pdh.dll");
    if (nullptr == hPdhLibrary) {
        DWORD gle = GetLastError();
        return {ErrorCodes::WindowsPdhError,
                str::stream() << "LoadLibrary of pdh.dll failed with "
                              << errnoWithDescription(gle)};
    }

    return Status::OK();
}

/**
 * Output an error message for ether PDH or the system.
 */
std::string errnoWithPdhDescription(PDH_STATUS status) {
    LPWSTR errorText = nullptr;

    if (!FormatMessageW(
            FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_FROM_SYSTEM |
                FORMAT_MESSAGE_ALLOCATE_BUFFER,
            hPdhLibrary,
            status,
            0,
            reinterpret_cast<LPWSTR>(
                &errorText),  // fudge the type so FormatMessageW uses it as an out parameter.
            0,
            nullptr)) {
        DWORD gle = GetLastError();
        return str::stream() << "Format message failed with " << gle << " for status " << status;
    }

    auto errorTextGuard = makeGuard([errorText] { LocalFree(errorText); });
    std::string utf8ErrorText = toUtf8String(errorText);

    auto size = utf8ErrorText.find_first_of("\r\n");
    if (size == std::string::npos) {
        size = utf8ErrorText.length();
    }

    return utf8ErrorText.substr(0, size);
}

/**
 * Format an error message for a PDH function call failure.
 */
std::string formatFunctionCallError(StringData functionName, PDH_STATUS status) {
    return str::stream() << functionName << " failed with '" << errnoWithPdhDescription(status)
                         << "'";
}

/**
 * Transform a vector of string data into a vector of strings.
 */
void transformStringDataVector(const std::vector<StringData>& input,
                               std::vector<std::string>* output) {
    output->reserve(input.size());
    for (const auto& str : input) {
        output->emplace_back(str.toString());
    }
}

/**
 * Check if a counter depends on system ticks per second to compute its value from raw values. This
 * is basically any counter that does not use 100NS as a base. FYI, if we query raw count counters,
 * we will get the system ticks as a time base.
 */
bool counterHasTickBasedTimeBase(uint32_t type) {
    return ((type & PERF_TYPE_COUNTER) == PERF_TYPE_COUNTER) &&
        ((type & PERF_TIMER_100NS) != PERF_TIMER_100NS);
}

}  // namespace

StatusWith<std::vector<std::string>> PerfCounterCollection::checkCounters(
    StringData name, const std::vector<StringData>& paths) {

    if (_counters.find(name.toString()) != _counters.end() ||
        _nestedCounters.find(name.toString()) != _nestedCounters.end()) {
        return Status(ErrorCodes::BadValue, str::stream() << "Duplicate group name for " << name);
    }

    std::vector<std::string> stringPaths;
    transformStringDataVector(paths, &stringPaths);

    // While duplicate counter paths are not a problem for PDH, they are a waste of time.
    std::sort(stringPaths.begin(), stringPaths.end());

    if (std::unique(stringPaths.begin(), stringPaths.end()) != stringPaths.end()) {
        return Status(ErrorCodes::BadValue,
                      str::stream() << "Duplicate counters in paths specified");
    }

    return {stringPaths};
}

Status PerfCounterCollection::addCountersGroup(StringData name,
                                               const std::vector<StringData>& paths) {

    auto swCounters = checkCounters(name, paths);
    if (!swCounters.getStatus().isOK()) {
        return swCounters.getStatus();
    }

    _counters.emplace(name.toString(), std::move(swCounters.getValue()));

    return Status::OK();
}

Status PerfCounterCollection::addCountersGroupedByInstanceName(
    StringData name, const std::vector<StringData>& paths) {

    auto swCounters = checkCounters(name, paths);
    if (!swCounters.getStatus().isOK()) {
        return swCounters.getStatus();
    }

    _nestedCounters.emplace(name.toString(), std::move(swCounters.getValue()));

    return Status::OK();
}

StatusWith<std::unique_ptr<PerfCounterCollector>> PerfCounterCollector::create(
    PerfCounterCollection builder) {
    auto pcc = std::unique_ptr<PerfCounterCollector>(new PerfCounterCollector());

    Status s = pcc->open();
    if (!s.isOK()) {
        return s;
    }

    for (const auto& kvp : builder._counters) {
        s = pcc->addCountersGroup(kvp.first, kvp.second);
        if (!s.isOK()) {
            return s;
        }
    }

    // Sort to enforce predictable output in final document
    std::sort(pcc->_counters.begin(),
              pcc->_counters.end(),
              [](const CounterGroup& a, const CounterGroup& b) { return a.name < b.name; });

    for (const auto& kvp : builder._nestedCounters) {
        s = pcc->addCountersGroupedByInstanceName(kvp.first, kvp.second);
        if (!s.isOK()) {
            return s;
        }
    }

    std::sort(
        pcc->_nestedCounters.begin(),
        pcc->_nestedCounters.end(),
        [](const NestedCounterGroup& a, const NestedCounterGroup& b) { return a.name < b.name; });

    pcc->checkForTicksTimeBase();

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

PerfCounterCollector::~PerfCounterCollector() {
    /*ignore*/ PdhCloseQuery(_query);
}

Status PerfCounterCollector::open() {

    PDH_STATUS status = PdhOpenQueryW(nullptr, NULL, &_query);
    if (status != ERROR_SUCCESS) {
        return {ErrorCodes::WindowsPdhError, formatFunctionCallError("PdhOpenQueryW", status)};
    }

    return Status::OK();
}

StatusWith<PerfCounterCollector::CounterInfo> PerfCounterCollector::addCounter(StringData path) {

    PDH_HCOUNTER counter{0};

    PDH_STATUS status =
        PdhAddCounterW(_query, toNativeString(path.toString().c_str()).c_str(), NULL, &counter);

    if (status != ERROR_SUCCESS) {
        return {ErrorCodes::WindowsPdhError, formatFunctionCallError("PdhAddCounterW", status)};
    }

    DWORD bufferSize = 0;

    status = PdhGetCounterInfoW(counter, false, &bufferSize, nullptr);

    if (status != PDH_MORE_DATA) {
        return {ErrorCodes::WindowsPdhError, formatFunctionCallError("PdhGetCounterInfoW", status)};
    }

    auto buf = std::make_unique<char[]>(bufferSize);
    auto counterInfo = reinterpret_cast<PPDH_COUNTER_INFO>(buf.get());

    status = PdhGetCounterInfoW(counter, false, &bufferSize, counterInfo);

    if (status != ERROR_SUCCESS) {
        return {ErrorCodes::WindowsPdhError, formatFunctionCallError("PdhGetCounterInfoW", status)};
    }

    // A full qualified path is as such:
    // "\\MYMACHINE\\Processor(0)\\% Idle Time"
    // MachineName \\ Object Name (Instance Name) \\ CounterName
    // Ex:
    //  MachineName: MYMACHINE
    //  Object Name: Processor
    //  InstanceName: 0
    //  CounterName: % Idle Time
    // We do not want to use Machine Name, but sometimes we want InstanceName
    //
    std::string firstName = str::stream() << '\\' << toUtf8String(counterInfo->szObjectName) << '\\'
                                          << toUtf8String(counterInfo->szCounterName);

    // Compute a second name
    std::string secondName(firstName);

    bool hasSecondValue = false;

    // Only include base for counters that need it
    if ((counterInfo->dwType & PERF_COUNTER_PRECISION) == PERF_COUNTER_PRECISION) {
        secondName += " Base";
        hasSecondValue = true;
    }

    // InstanceName is null for counters without instance names
    return {CounterInfo{std::move(firstName),
                        std::move(secondName),
                        hasSecondValue,
                        counterInfo->szInstanceName ? toUtf8String(counterInfo->szInstanceName)
                                                    : std::string(),
                        counterInfo->dwType,
                        counter}};
}

StatusWith<std::vector<PerfCounterCollector::CounterInfo>> PerfCounterCollector::addCounters(
    StringData path) {
    std::wstring pathWide = toNativeString(path.toString().c_str());
    DWORD pathListLength = 0;
    PDH_STATUS status = PdhExpandCounterPathW(pathWide.c_str(), nullptr, &pathListLength);

    if (status != PDH_MORE_DATA) {
        return {ErrorCodes::WindowsPdhError,
                str::stream() << formatFunctionCallError("PdhExpandCounterPathW", status)
                              << " for counter '"
                              << path
                              << "'"};
    }

    auto buf = std::make_unique<wchar_t[]>(pathListLength);

    status = PdhExpandCounterPathW(pathWide.c_str(), buf.get(), &pathListLength);

    if (status != ERROR_SUCCESS) {
        return {ErrorCodes::WindowsPdhError,
                formatFunctionCallError("PdhExpandCounterPathW", status)};
    }

    std::vector<CounterInfo> counters;

    // Windows' PdhExpandWildCardPathW returns a nullptr terminated array of nullptr separated
    // strings.
    std::vector<std::string> counterNames;

    const wchar_t* ptr = buf.get();
    while (ptr && *ptr) {
        counterNames.emplace_back(toUtf8String(ptr));
        ptr += wcslen(ptr) + 1;
    }

    // Sort to ensure we have a predictable ordering in the final BSON
    std::sort(counterNames.begin(), counterNames.end());

    for (const auto& name : counterNames) {

        auto swCounterInfo = addCounter(name);
        if (!swCounterInfo.isOK()) {
            return swCounterInfo.getStatus();
        }

        counters.emplace_back(std::move(swCounterInfo.getValue()));
    }

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

Status PerfCounterCollector::addCountersGroup(StringData groupName,
                                              const std::vector<std::string>& paths) {
    CounterGroup group;
    group.name = groupName.toString();

    for (const auto& path : paths) {
        auto swCounters = addCounters(path.c_str());
        if (!swCounters.isOK()) {
            return swCounters.getStatus();
        }

        auto newCounters = swCounters.getValue();

        std::copy(newCounters.begin(), newCounters.end(), std::back_inserter(group.counters));
    }

    _counters.emplace_back(group);

    return Status::OK();
}

Status PerfCounterCollector::addCountersGroupedByInstanceName(
    StringData groupName, const std::vector<std::string>& paths) {
    NestedCounterGroup group;
    group.name = groupName.toString();

    for (const auto& path : paths) {
        auto swCounters = addCounters(path.c_str());
        if (!swCounters.isOK()) {
            return swCounters.getStatus();
        }

        auto newCounters = swCounters.getValue();

        for (const auto& counter : newCounters) {
            // Verify the counter has an instance name.
            if (counter.instanceName.empty()) {
                return {ErrorCodes::BadValue,
                        str::stream() << "Counter '" << counter.firstName
                                      << "' must be an instance specific counter."};
            }

            // Skip counters in the _Total instance category.
            if (counter.instanceName == "_Total") {
                continue;
            }

            group.counters[counter.instanceName].emplace_back(std::move(counter));
        }
    }

    _nestedCounters.emplace_back(group);

    return Status::OK();
}

Status PerfCounterCollector::collectCounters(const std::vector<CounterInfo>& counters,
                                             BSONObjBuilder* builder) {
    for (const auto& counterInfo : counters) {

        DWORD dwType = 0;

        // Elapsed Time is an unusual counter in that being able to control the sample period for
        // the counter is uninteresting even though it is computed from two values. Just return the
        // computed value instead.
        if (counterInfo.type == PERF_ELAPSED_TIME) {
            PDH_FMT_COUNTERVALUE counterValue = {0};
            PDH_STATUS status = PdhGetFormattedCounterValue(
                counterInfo.handle, PDH_FMT_DOUBLE, &dwType, &counterValue);
            if (status != ERROR_SUCCESS) {
                return {ErrorCodes::WindowsPdhError,
                        formatFunctionCallError("PdhGetFormattedCounterValue", status)};
            }

            builder->append(counterInfo.firstName, counterValue.doubleValue);

        } else {

            PDH_RAW_COUNTER rawCounter = {0};
            PDH_STATUS status = PdhGetRawCounterValue(counterInfo.handle, &dwType, &rawCounter);
            if (status != ERROR_SUCCESS) {
                return {ErrorCodes::WindowsPdhError,
                        formatFunctionCallError("PdhGetRawCounterValue", status)};
            }

            if (counterInfo.hasSecondValue) {
                // Precise counters require the second value in the raw counter information
                builder->append(counterInfo.firstName, rawCounter.FirstValue);
                builder->append(counterInfo.secondName, rawCounter.SecondValue);
            } else {
                builder->append(counterInfo.firstName, rawCounter.FirstValue);
            }
        }
    }

    return Status::OK();
}

void PerfCounterCollector::checkForTicksTimeBase() {
    for (const auto& counterGroup : _counters) {
        for (const auto& counter : counterGroup.counters) {
            if (counterHasTickBasedTimeBase(counter.type)) {
                _timeBaseTicksCounter = &counter;
                return;
            }
        }
    }

    for (const auto& counterGroup : _nestedCounters) {
        for (const auto& instanceNamePair : counterGroup.counters) {
            for (const auto& counter : instanceNamePair.second) {
                if (counterHasTickBasedTimeBase(counter.type)) {
                    _timeBaseTicksCounter = &counter;
                    return;
                }
            }
        }
    }
}

Status PerfCounterCollector::collect(BSONObjBuilder* builder) {
    // Ask PDH to collect the counters
    PDH_STATUS status = PdhCollectQueryData(_query);
    if (status != ERROR_SUCCESS) {
        return {ErrorCodes::WindowsPdhError,
                formatFunctionCallError("PdhCollectQueryData", status)};
    }

    // Output timebase
    // Counters that are based on time either use 100NS or System Ticks Per Second.
    // We only need to output system ticks per second once if any counter depends on it.
    // This is typically 3320310.
    if (_timeBaseTicksCounter) {
        int64_t timebase;

        status = PdhGetCounterTimeBase(_timeBaseTicksCounter->handle, &timebase);
        if (status != ERROR_SUCCESS) {
            return {ErrorCodes::WindowsPdhError,
                    formatFunctionCallError("PdhGetCounterTimeBase", status)};
        }

        builder->append("timebase", timebase);
    }

    // Retrieve all the values that PDH collected for us.
    for (const auto& counterGroup : _counters) {
        BSONObjBuilder subObjBuilder(builder->subobjStart(counterGroup.name));

        Status s = collectCounters(counterGroup.counters, &subObjBuilder);
        if (!s.isOK()) {
            return s;
        }

        subObjBuilder.doneFast();
    }

    for (const auto& counterGroup : _nestedCounters) {
        BSONObjBuilder subObjBuilder(builder->subobjStart(counterGroup.name));

        for (const auto& instanceNamePair : counterGroup.counters) {
            BSONObjBuilder instSubObjBuilder(builder->subobjStart(instanceNamePair.first));

            Status s = collectCounters(instanceNamePair.second, &instSubObjBuilder);
            if (!s.isOK()) {
                return s;
            }

            instSubObjBuilder.doneFast();
        }

        subObjBuilder.doneFast();
    }

    return Status::OK();
}

}  // namespace mongo