1 /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
2
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15
16 #ifndef TENSORFLOW_CORE_LIB_MONITORING_GAUGE_H_
17 #define TENSORFLOW_CORE_LIB_MONITORING_GAUGE_H_
18
19 // We replace this implementation with a null implementation for mobile
20 // platforms.
21 #include "tensorflow/core/platform/platform.h"
22 #ifdef IS_MOBILE_PLATFORM
23 #include "tensorflow/core/lib/monitoring/mobile_gauge.h"
24 #else
25
26 #include <array>
27 #include <atomic>
28 #include <map>
29
30 #include "tensorflow/core/lib/monitoring/collection_registry.h"
31 #include "tensorflow/core/lib/monitoring/metric_def.h"
32 #include "tensorflow/core/platform/macros.h"
33 #include "tensorflow/core/platform/mutex.h"
34 #include "tensorflow/core/platform/thread_annotations.h"
35 #include "tensorflow/core/platform/types.h"
36
37 namespace tensorflow {
38 namespace monitoring {
39
40 // GaugeCell stores each value of a gauge.
41 //
42 // A cell can be passed off to a module which may repeatedly update it without
43 // needing further map-indexing computations. This improves both encapsulation
44 // (separate modules can own a cell each, without needing to know about the map
45 // to which both cells belong) and performance (since map indexing and
46 // associated locking are both avoided).
47 //
48 // This class is thread-safe.
49 template <typename T>
50 class GaugeCell {
51 public:
GaugeCell(const T & value)52 explicit GaugeCell(const T& value) : value_(value) {}
~GaugeCell()53 ~GaugeCell() {}
54
55 // Atomically sets the value.
56 void Set(const T& value) LOCKS_EXCLUDED(mu_);
57
58 // Retrieves the current value.
59 T value() const LOCKS_EXCLUDED(mu_);
60
61 private:
62 T value_ GUARDED_BY(mu_);
63 mutable mutex mu_;
64
65 TF_DISALLOW_COPY_AND_ASSIGN(GaugeCell);
66 };
67
68 // Explicit specialization of GaugeCell<int64>. Compared to the primary
69 // template, it uses atomic values as opposed to mutex. This class is
70 // thread-safe.
71 template <>
72 class GaugeCell<int64> {
73 public:
GaugeCell(int64 value)74 explicit GaugeCell(int64 value) : value_(value) {}
~GaugeCell()75 ~GaugeCell() {}
76
77 // Atomically sets the value.
78 void Set(int64 value);
79
80 // Retrieves the current value.
81 int64 value() const;
82
83 private:
84 std::atomic<int64> value_;
85
86 TF_DISALLOW_COPY_AND_ASSIGN(GaugeCell);
87 };
88
89 // Explicit specialization of GaugeCell<bool>. Compared to the primary
90 // template, it uses atomic values as opposed to mutex. This class is
91 // thread-safe.
92 template <>
93 class GaugeCell<bool> {
94 public:
GaugeCell(bool value)95 explicit GaugeCell(bool value) : value_(value) {}
~GaugeCell()96 ~GaugeCell() {}
97
98 // Atomically sets the value.
99 void Set(bool value);
100
101 // Retrieves the current value.
102 bool value() const;
103
104 private:
105 std::atomic<bool> value_;
106
107 TF_DISALLOW_COPY_AND_ASSIGN(GaugeCell);
108 };
109
110 // A stateful class for updating a gauge-like metric. Allowed ValueType are
111 // int64, string and bool.
112 //
113 // This class encapsulates a set of values (or a single value for a label-less
114 // metric). Each value is identified by a tuple of labels. The class allows the
115 // user to set each value.
116 //
117 // Gauge allocates storage and maintains a cell for each value. You can
118 // retrieve an individual cell using a label-tuple and update it separately.
119 // This improves performance since operations related to retrieval, like
120 // map-indexing and locking, are avoided.
121 //
122 // This class is thread-safe.
123 template <typename ValueType, int NumLabels>
124 class Gauge {
125 public:
~Gauge()126 ~Gauge() {
127 // Deleted here, before the metric_def is destroyed.
128 registration_handle_.reset();
129 }
130
131 // Creates the metric based on the metric-definition arguments.
132 //
133 // Example:
134 //
135 // auto* string_gauge_with_label = Gauge<string,1>::New(
136 // "/tensorflow/string_gauge_with_label",
137 // "String gauge with one label.", "MyLabelName");
138 //
139 // auto* integer_gauge = Gauge<int64, 0>::New("/tensorflow/integer_gauge",
140 // "Integer gauge")
141 //
142 // auto* bool_gauge = Gauge<bool, 0>::New("/tensorflow/bool_gauge",
143 // "Bool gauge")
144 template <typename... MetricDefArgs>
145 static Gauge* New(MetricDefArgs&&... metric_def_args);
146
147 // Retrieves the cell for the specified labels, creating it on demand if not
148 // already present.
149 template <typename... Labels>
150 GaugeCell<ValueType>* GetCell(const Labels&... labels) LOCKS_EXCLUDED(mu_);
151
152 private:
Gauge(const MetricDef<MetricKind::kGauge,ValueType,NumLabels> & metric_def)153 explicit Gauge(
154 const MetricDef<MetricKind::kGauge, ValueType, NumLabels>& metric_def)
155 : metric_def_(metric_def),
156 registration_handle_(CollectionRegistry::Default()->Register(
157 &metric_def_, [&](MetricCollectorGetter getter) {
158 auto metric_collector = getter.Get(&metric_def_);
159
160 mutex_lock l(mu_);
161 for (const auto& cell : cells_) {
162 metric_collector.CollectValue(cell.first, cell.second.value());
163 }
164 })) {}
165
166 mutable mutex mu_;
167
168 // The metric definition. This will be used to identify the metric when we
169 // register it for collection.
170 const MetricDef<MetricKind::kGauge, ValueType, NumLabels> metric_def_;
171
172 std::unique_ptr<CollectionRegistry::RegistrationHandle> registration_handle_;
173
174 using LabelArray = std::array<string, NumLabels>;
175 std::map<LabelArray, GaugeCell<ValueType> > cells_ GUARDED_BY(mu_);
176
177 TF_DISALLOW_COPY_AND_ASSIGN(Gauge);
178 };
179
180 ////
181 // Implementation details follow. API readers may skip.
182 ////
183 template <typename T>
Set(const T & value)184 void GaugeCell<T>::Set(const T& value) {
185 mutex_lock l(mu_);
186 value_ = value;
187 }
188
189 template <typename T>
value()190 T GaugeCell<T>::value() const {
191 mutex_lock l(mu_);
192 return value_;
193 }
194
Set(int64 value)195 inline void GaugeCell<int64>::Set(int64 value) { value_ = value; }
196
value()197 inline int64 GaugeCell<int64>::value() const { return value_; }
198
Set(bool value)199 inline void GaugeCell<bool>::Set(bool value) { value_ = value; }
200
value()201 inline bool GaugeCell<bool>::value() const { return value_; }
202
203 template <typename ValueType, int NumLabels>
204 template <typename... MetricDefArgs>
New(MetricDefArgs &&...metric_def_args)205 Gauge<ValueType, NumLabels>* Gauge<ValueType, NumLabels>::New(
206 MetricDefArgs&&... metric_def_args) {
207 static_assert(std::is_same<ValueType, int64>::value ||
208 std::is_same<ValueType, string>::value ||
209 std::is_same<ValueType, bool>::value,
210 "Gauge only allows int64 and string types.");
211 return new Gauge<ValueType, NumLabels>(
212 MetricDef<MetricKind::kGauge, ValueType, NumLabels>(
213 std::forward<MetricDefArgs>(metric_def_args)...));
214 }
215
216 template <typename ValueType, int NumLabels>
217 template <typename... Labels>
GetCell(const Labels &...labels)218 GaugeCell<ValueType>* Gauge<ValueType, NumLabels>::GetCell(
219 const Labels&... labels) LOCKS_EXCLUDED(mu_) {
220 // Provides a more informative error message than the one during array
221 // construction below.
222 static_assert(
223 sizeof...(Labels) == NumLabels,
224 "Mismatch between Gauge<ValueType, NumLabels> and number of labels "
225 "provided in GetCell(...).");
226
227 const LabelArray& label_array = {{labels...}};
228 mutex_lock l(mu_);
229 const auto found_it = cells_.find(label_array);
230 if (found_it != cells_.end()) {
231 return &(found_it->second);
232 }
233 return &(cells_
234 .emplace(std::piecewise_construct,
235 std::forward_as_tuple(label_array),
236 std::forward_as_tuple(ValueType()))
237 .first->second);
238 }
239
240 } // namespace monitoring
241 } // namespace tensorflow
242
243 #endif // IS_MOBILE_PLATFORM
244 #endif // TENSORFLOW_CORE_LIB_MONITORING_GAUGE_H_
245