metric_family.cc 9.87 KB
Newer Older
xiabo's avatar
xiabo committed
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
// Copyright (c) 2022, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//  * Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//  * Neither the name of NVIDIA CORPORATION nor the names of its
//    contributors may be used to endorse or promote products derived
//    from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#ifdef TRITON_ENABLE_METRICS

#include "metric_family.h"
#include "metrics.h"
#include "triton/common/logging.h"

namespace triton { namespace core {

//
// Implementation for TRITONSERVER_MetricFamily.
//
MetricFamily::MetricFamily(
    TRITONSERVER_MetricKind kind, const char* name, const char* description)
{
  auto registry = Metrics::GetRegistry();

  switch (kind) {
    case TRITONSERVER_METRIC_KIND_COUNTER:
      family_ = reinterpret_cast<void*>(&prometheus::BuildCounter()
                                             .Name(name)
                                             .Help(description)
                                             .Register(*registry));
      break;
    case TRITONSERVER_METRIC_KIND_GAUGE:
      family_ = reinterpret_cast<void*>(&prometheus::BuildGauge()
                                             .Name(name)
                                             .Help(description)
                                             .Register(*registry));
      break;
    default:
      throw std::invalid_argument(
          "Unsupported kind passed to MetricFamily constructor.");
  }

  kind_ = kind;
}

void*
MetricFamily::Add(std::map<std::string, std::string> label_map, Metric* metric)
{
  void* prom_metric = nullptr;
  switch (kind_) {
    case TRITONSERVER_METRIC_KIND_COUNTER: {
      auto counter_family_ptr =
          reinterpret_cast<prometheus::Family<prometheus::Counter>*>(family_);
      auto counter_ptr = &counter_family_ptr->Add(label_map);
      prom_metric = reinterpret_cast<void*>(counter_ptr);
      break;
    }
    case TRITONSERVER_METRIC_KIND_GAUGE: {
      auto gauge_family_ptr =
          reinterpret_cast<prometheus::Family<prometheus::Gauge>*>(family_);
      auto gauge_ptr = &gauge_family_ptr->Add(label_map);
      prom_metric = reinterpret_cast<void*>(gauge_ptr);
      break;
    }
    default:
      throw std::invalid_argument(
          "Unsupported family kind passed to Metric constructor.");
  }

  std::lock_guard<std::mutex> lk(metric_mtx_);
  ++prom_metric_ref_cnt_[prom_metric];
  child_metrics_.insert(metric);
  return prom_metric;
}

void
MetricFamily::Remove(void* prom_metric, Metric* metric)
{
  {
    // Remove reference to dependent Metric object
    std::lock_guard<std::mutex> lk(metric_mtx_);
    child_metrics_.erase(metric);
  }

  if (prom_metric == nullptr) {
    return;
  }

  {
    std::lock_guard<std::mutex> lk(metric_mtx_);
    const auto it = prom_metric_ref_cnt_.find(prom_metric);
    if (it != prom_metric_ref_cnt_.end()) {
      --it->second;
      if (it->second == 0) {
        prom_metric_ref_cnt_.erase(it);
      } else {
        // Done as it is not the last reference
        return;
      }
    }
  }

  switch (kind_) {
    case TRITONSERVER_METRIC_KIND_COUNTER: {
      auto counter_family_ptr =
          reinterpret_cast<prometheus::Family<prometheus::Counter>*>(family_);
      auto counter_ptr = reinterpret_cast<prometheus::Counter*>(prom_metric);
      counter_family_ptr->Remove(counter_ptr);
      break;
    }
    case TRITONSERVER_METRIC_KIND_GAUGE: {
      auto gauge_family_ptr =
          reinterpret_cast<prometheus::Family<prometheus::Gauge>*>(family_);
      auto gauge_ptr = reinterpret_cast<prometheus::Gauge*>(prom_metric);
      gauge_family_ptr->Remove(gauge_ptr);
      break;
    }
    default:
      // Invalid kind should be caught in constructor
      LOG_ERROR << "Unsupported kind in Metric destructor.";
      break;
  }
}

void
MetricFamily::InvalidateReferences()
{
  std::lock_guard<std::mutex> lk(metric_mtx_);
  for (auto& metric : child_metrics_) {
    if (metric != nullptr) {
      metric->Invalidate();
    }
  }
  child_metrics_.clear();
}

MetricFamily::~MetricFamily()
{
  if (NumMetrics() > 0) {
    LOG_WARNING << "MetricFamily was deleted before its child Metrics, this "
                   "should not happen. Make sure to delete all child Metrics "
                   "before deleting their MetricFamily.";
  }
  InvalidateReferences();
  // DLIS-4072: Support for removing metric families from registry
}

//
// Implementation for TRITONSERVER_Metric.
//
Metric::Metric(
    TRITONSERVER_MetricFamily* family,
    std::vector<const InferenceParameter*> labels)
{
  family_ = reinterpret_cast<MetricFamily*>(family);
  kind_ = family_->Kind();

  // Create map of labels from InferenceParameters
  std::map<std::string, std::string> label_map;
  for (const auto& param : labels) {
    if (param->Type() != TRITONSERVER_PARAMETER_STRING) {
      throw std::invalid_argument(
          "Parameter [" + param->Name() +
          "] must have a type of TRITONSERVER_PARAMETER_STRING to be "
          "added as a label.");
    }

    label_map[param->Name()] =
        std::string(reinterpret_cast<const char*>(param->ValuePointer()));
  }

  metric_ = family_->Add(label_map, this);
}

Metric::~Metric()
{
  if (family_ != nullptr) {
    family_->Remove(metric_, this);
  } else {
    LOG_WARNING << "Corresponding MetricFamily was deleted before this Metric, "
                   "this should not happen. Make sure to delete a Metric "
                   "before deleting its MetricFamily.";
  }
  // Catch lifetime management / invalid reference issues
  Invalidate();
}

void
Metric::Invalidate()
{
  family_ = nullptr;
  metric_ = nullptr;
}

TRITONSERVER_Error*
Metric::Value(double* value)
{
  if (metric_ == nullptr) {
    return TRITONSERVER_ErrorNew(
        TRITONSERVER_ERROR_INTERNAL,
        "Could not get metric value. Metric has been invalidated.");
  }

  switch (kind_) {
    case TRITONSERVER_METRIC_KIND_COUNTER: {
      auto counter_ptr = reinterpret_cast<prometheus::Counter*>(metric_);
      LOG_VERBOSE(1) << "SETTING COUNTER METRIC FROM: " << *value << " to "
                     << counter_ptr->Value();
      *value = counter_ptr->Value();
      break;
    }
    case TRITONSERVER_METRIC_KIND_GAUGE: {
      auto gauge_ptr = reinterpret_cast<prometheus::Gauge*>(metric_);
      LOG_VERBOSE(1) << "SETTING GAUGE METRIC FROM: " << *value << " to "
                     << gauge_ptr->Value();
      *value = gauge_ptr->Value();
      break;
    }
    default:
      return TRITONSERVER_ErrorNew(
          TRITONSERVER_ERROR_UNSUPPORTED,
          "Unsupported TRITONSERVER_MetricKind");
  }

  return nullptr;  // Success
}

TRITONSERVER_Error*
Metric::Increment(double value)
{
  if (metric_ == nullptr) {
    return TRITONSERVER_ErrorNew(
        TRITONSERVER_ERROR_INTERNAL,
        "Could not increment metric value. Metric has been invalidated.");
  }

  switch (kind_) {
    case TRITONSERVER_METRIC_KIND_COUNTER: {
      if (value < 0.0) {
        return TRITONSERVER_ErrorNew(
            TRITONSERVER_ERROR_INVALID_ARG,
            "TRITONSERVER_METRIC_KIND_COUNTER can only be incremented "
            "monotonically by non-negative values.");
      }

      auto counter_ptr = reinterpret_cast<prometheus::Counter*>(metric_);
      counter_ptr->Increment(value);
      break;
    }
    case TRITONSERVER_METRIC_KIND_GAUGE: {
      auto gauge_ptr = reinterpret_cast<prometheus::Gauge*>(metric_);
      // Gauge::Increment works for both positive and negative values as of
      // prometheus-cpp v1.0 but for now on v0.7 we defer call to
      // Increment/Decrement based on the sign of value
      // https://github.com/jupp0r/prometheus-cpp/blob/master/core/src/gauge.cc
      if (value < 0.0) {
        gauge_ptr->Decrement(-1.0 * value);
      } else {
        gauge_ptr->Increment(value);
      }
      break;
    }
    default:
      return TRITONSERVER_ErrorNew(
          TRITONSERVER_ERROR_UNSUPPORTED,
          "Unsupported TRITONSERVER_MetricKind");
  }

  return nullptr;  // Success
}

TRITONSERVER_Error*
Metric::Set(double value)
{
  if (metric_ == nullptr) {
    return TRITONSERVER_ErrorNew(
        TRITONSERVER_ERROR_INTERNAL,
        "Could not set metric value. Metric has been invalidated.");
  }

  switch (kind_) {
    case TRITONSERVER_METRIC_KIND_COUNTER: {
      return TRITONSERVER_ErrorNew(
          TRITONSERVER_ERROR_UNSUPPORTED,
          "TRITONSERVER_METRIC_KIND_COUNTER does not support Set");
    }
    case TRITONSERVER_METRIC_KIND_GAUGE: {
      auto gauge_ptr = reinterpret_cast<prometheus::Gauge*>(metric_);
      gauge_ptr->Set(value);
      break;
    }
    default:
      return TRITONSERVER_ErrorNew(
          TRITONSERVER_ERROR_UNSUPPORTED,
          "Unsupported TRITONSERVER_MetricKind");
  }

  return nullptr;  // Success
}

}}  // namespace triton::core

#endif  // TRITON_ENABLE_METRICS