forked from apple/foundationdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTDMetric.actor.h
executable file
·1373 lines (1154 loc) · 45 KB
/
TDMetric.actor.h
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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* TDMetric.actor.h
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2013-2018 Apple Inc. and the FoundationDB project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
// When actually compiled (NO_INTELLISENSE), include the generated version of this file. In intellisense use the source version.
#if defined(NO_INTELLISENSE) && !defined(FLOW_TDMETRIC_ACTOR_G_H)
#define FLOW_TDMETRIC_ACTOR_G_H
#include "TDMetric.actor.g.h"
#elif !defined(FLOW_TDMETRIC_ACTOR_H)
#define FLOW_TDMETRIC_ACTOR_H
#include "actorcompiler.h"
#include "flow.h"
#include "IndexedSet.h"
#include "network.h"
#include "Knobs.h"
#include "genericactors.actor.h"
#include "CompressedInt.h"
#include <algorithm>
#include <functional>
struct MetricNameRef {
MetricNameRef() {}
MetricNameRef(const StringRef& type, const StringRef& name, const StringRef &id)
: type(type), name(name), id(id) {
}
MetricNameRef(Arena& a, const MetricNameRef& copyFrom)
: type(a, copyFrom.type), name(a, copyFrom.name), id(a, copyFrom.id) {
}
StringRef type, name, id;
std::string toString() const {
return format("(%s,%s,%s,%s)", type.toString().c_str(), name.toString().c_str(), id.toString().c_str());
}
int expectedSize() const {
return type.expectedSize() + name.expectedSize();
}
};
extern std::string reduceFilename(std::string const &filename);
inline bool operator < (const MetricNameRef& l, const MetricNameRef& r ) {
int cmp = l.type.compare(r.type);
if(cmp == 0) {
cmp = l.name.compare(r.name);
if(cmp == 0)
cmp = l.id.compare(r.id);
}
return cmp < 0;
}
inline bool operator == (const MetricNameRef& l, const MetricNameRef& r ) {
return l.type == r.type && l.name == r.name && l.id == r.id;
}
inline bool operator != (const MetricNameRef& l, const MetricNameRef& r ) {
return !(l == r);
}
struct KeyWithWriter {
Standalone<StringRef> key;
BinaryWriter writer;
int writerOffset;
KeyWithWriter( Standalone<StringRef> const& key, BinaryWriter& writer, int writerOffset = 0) : key(key), writer(std::move(writer)), writerOffset(writerOffset) {}
KeyWithWriter( KeyWithWriter&& r ) : key(std::move(r.key)), writer(std::move(r.writer)), writerOffset(r.writerOffset) {}
void operator=( KeyWithWriter&& r ) { key = std::move(r.key); writer = std::move(r.writer); writerOffset = r.writerOffset; }
StringRef value() {
return StringRef(writer.toStringRef().substr(writerOffset));
}
};
// This is a very minimal interface for getting metric data from the DB which is needed
// to support continuing existing metric data series.
// It's lack of generality is intentional.
class IMetricDB {
public:
virtual ~IMetricDB() {}
// key should be the result of calling metricKey or metricFieldKey with time = 0
virtual Future<Optional<Standalone<StringRef>>> getLastBlock(Standalone<StringRef> key) = 0;
};
// Key generator for metric keys for various things.
struct MetricKeyRef {
MetricKeyRef() : level(-1) {}
MetricKeyRef(Arena& a, const MetricKeyRef& copyFrom)
: prefix(a, copyFrom.prefix), name(a, copyFrom.name), address(a, copyFrom.address),
fieldName(a, copyFrom.fieldName), fieldType(a, copyFrom.fieldType), level(copyFrom.level) {
}
StringRef prefix;
MetricNameRef name;
StringRef address;
StringRef fieldName;
StringRef fieldType;
uint64_t level;
int expectedSize() const {
return prefix.expectedSize() + name.expectedSize() + address.expectedSize() + fieldName.expectedSize() + fieldType.expectedSize();
}
template <typename T> inline MetricKeyRef withField(const T &field) const {
MetricKeyRef mk(*this);
mk.fieldName = field.name();
mk.fieldType = field.typeName();
return mk;
}
const Standalone<StringRef> packLatestKey() const;
const Standalone<StringRef> packDataKey(int64_t time = -1) const;
const Standalone<StringRef> packFieldRegKey() const;
bool isField() const { return fieldName.size() > 0 && fieldType.size() > 0; }
void writeField(BinaryWriter &wr) const;
void writeMetricName(BinaryWriter &wr) const;
};
struct MetricUpdateBatch {
std::vector<KeyWithWriter> inserts;
std::vector<KeyWithWriter> appends;
std::vector<std::pair<Standalone<StringRef>,Standalone<StringRef>>> updates;
std::vector<std::function<Future<Void>(IMetricDB *, MetricUpdateBatch *)>> callbacks;
void clear() {
inserts.clear();
appends.clear();
updates.clear();
callbacks.clear();
}
};
template<typename T>
inline const StringRef metricTypeName() {
// If this function does not compile then T is not a supported metric type
return T::metric_field_type();
}
#define MAKE_TYPENAME(T, S) template<> inline const StringRef metricTypeName<T>() { return LiteralStringRef(S); }
MAKE_TYPENAME(bool, "Bool")
MAKE_TYPENAME(int64_t, "Int64")
MAKE_TYPENAME(double, "Double")
MAKE_TYPENAME(Standalone<StringRef>, "String")
#undef MAKE_TYPENAME
struct BaseMetric;
// The collection of metrics that exist for a single process, at a single address.
class TDMetricCollection {
public:
TDMetricCollection() : currentTimeBytes(0) {}
// Metric Name to reference to its instance
Map<Standalone<MetricNameRef>, Reference<BaseMetric>, MapPair<Standalone<MetricNameRef>, Reference<BaseMetric>>, int> metricMap;
AsyncTrigger metricAdded;
AsyncTrigger metricEnabled;
AsyncTrigger metricRegistrationChanged;
// Initialize the collection. Once this returns true, metric data can be written to a database. Note that metric data can be logged
// before that time, just not written to a database.
bool init() {
// Get and store the local address in the metric collection, but only if it is not 0.0.0.0:0
if( address.size() == 0 ) {
NetworkAddress addr = g_network->getLocalAddress();
if(addr.ip != 0 && addr.port != 0)
address = StringRef(addr.toString());
}
return address.size() != 0;
}
// Returns the TDMetrics that the calling process should use
static TDMetricCollection* getTDMetrics() {
if(g_network == nullptr)
return nullptr;
return static_cast<TDMetricCollection*>((void*) g_network->global(INetwork::enTDMetrics));
}
Deque<uint64_t> rollTimes;
int64_t currentTimeBytes;
Standalone<StringRef> address;
void checkRoll(uint64_t t, int64_t usedBytes);
bool canLog(int level);
};
struct MetricData {
uint64_t start;
uint64_t rollTime;
uint64_t appendStart;
BinaryWriter writer;
explicit MetricData(uint64_t appendStart = 0) :
writer(AssumeVersion(currentProtocolVersion)),
start(0),
rollTime(std::numeric_limits<uint64_t>::max()),
appendStart(appendStart) {
}
MetricData( MetricData&& r ) noexcept(true) :
start(r.start),
rollTime(r.rollTime),
appendStart(r.appendStart),
writer(std::move(r.writer)) {
}
void operator=( MetricData&& r ) noexcept(true) {
start = r.start; rollTime = r.rollTime; appendStart = r.appendStart; writer = std::move(r.writer);
}
std::string toString();
};
// Some common methods to reduce code redundancy across different metric definitions
template<typename T, typename _ValueType = Void>
struct MetricUtil {
typedef _ValueType ValueType;
typedef T MetricType;
// Looks up a metric by name and id and returns a reference to it if it exists.
// Empty names will not be looked up.
// If create is true then a metric will be created with the given initial value if one could not be found to return.
// If a metric is created and name is not empty then the metric will be placed in the collection.
static Reference<T> getOrCreateInstance(StringRef const& name, StringRef const &id = StringRef(), bool create = false, ValueType initial = ValueType()) {
Reference<T> m;
TDMetricCollection *collection = TDMetricCollection::getTDMetrics();
// If there is a metric collect and this metric has a name then look it up in the collection
bool useMap = collection != nullptr && name.size() > 0;
MetricNameRef mname;
if(useMap) {
mname = MetricNameRef(T::metricType, name, id);
auto mi = collection->metricMap.find(mname);
if(mi != collection->metricMap.end()) {
m = mi->value.castTo<T>();
}
}
// If we don't have a valid metric reference yet and the create flag was set then create one and possibly put it in the map
if(!m && create) {
// Metric not found in collection but create is set then create it in the map
m = Reference<T>(new T(mname, initial));
if(useMap) {
collection->metricMap[mname] = m.template castTo<BaseMetric>();
collection->metricAdded.trigger();
}
}
return m;
}
// Lookup the T metric by name and return its value (or nullptr if it doesn't exist)
static T * lookupMetric(MetricNameRef const &name) {
auto it = T::metricMap().find(name);
if(it != T::metricMap().end())
return it->value;
return nullptr;
}
};
// index_sequence implementation since VS2013 doesn't have it yet
template <size_t... Ints> class index_sequence {
public:
static size_t size() { return sizeof...(Ints); }
};
template <size_t Start, typename Indices, size_t End>
struct make_index_sequence_impl;
template <size_t Start, size_t... Indices, size_t End>
struct make_index_sequence_impl<Start, index_sequence<Indices...>, End> {
typedef typename make_index_sequence_impl<
Start + 1, index_sequence<Indices..., Start>, End>::type type;
};
template <size_t End, size_t... Indices>
struct make_index_sequence_impl<End, index_sequence<Indices...>, End> {
typedef index_sequence<Indices...> type;
};
// The code that actually implements tuple_map
template <size_t I, typename F, typename... Tuples>
auto tuple_zip_invoke(F f, const Tuples &... ts) -> decltype( f(std::get<I>(ts)...) ) {
return f(std::get<I>(ts)...);
}
template <typename F, size_t... Is, typename... Tuples>
auto tuple_map_impl(F f, index_sequence<Is...>, const Tuples &... ts) -> decltype( std::make_tuple(tuple_zip_invoke<Is>(f, ts...)...) ) {
return std::make_tuple(tuple_zip_invoke<Is>(f, ts...)...);
}
// tuple_map( f(a,b), (a1,a2,a3), (b1,b2,b3) ) = (f(a1,b1), f(a2,b2), f(a3,b3))
template <typename F, typename Tuple, typename... Tuples>
auto tuple_map(F f, const Tuple &t, const Tuples &... ts) -> decltype( tuple_map_impl(f, typename make_index_sequence_impl<0, index_sequence<>, std::tuple_size<Tuple>::value>::type(), t, ts...) ) {
return tuple_map_impl(f, typename make_index_sequence_impl<0, index_sequence<>, std::tuple_size<Tuple>::value>::type(), t, ts...);
}
template <class T>
struct Descriptor {};
// FieldHeader is a serializable (FIXED SIZE!) and updatable Header type for Metric field levels.
// Update is via += with either a T or another FieldHeader
// Default implementation is sufficient for ints and doubles
template<typename T>
struct FieldHeader {
FieldHeader() : version(1), count(0), sum(0) {}
uint8_t version;
int64_t count;
// sum is a T if T is arithmetic, otherwise it's an int64_t
typename std::conditional<std::is_floating_point<T>::value, double, int64_t>::type sum;
void update(FieldHeader const &h) {
count += h.count;
sum += h.sum;
}
void update(T const &v) {
++count;
sum += v;
}
template<class Ar> void serialize(Ar &ar) {
ar & version;
ASSERT(version == 1);
ar & count & sum;
}
};
template <> inline void FieldHeader<Standalone<StringRef>>::update(Standalone<StringRef> const &v) {
++count;
sum += v.size();
}
// FieldValueBlockEncoding is a class for reading and writing encoded field values to and from field
// value data blocks. Note that an implementation can be stateful.
// Proper usage requires that a single Encoding instance is used to either write all field values to a metric
// data block or to read all field values from a metric value block. This usage pattern enables enables
// encoding and decoding values as deltas from previous values.
//
// The default implemenation works for ints and writes delta from the previous value.
template <typename T>
struct FieldValueBlockEncoding {
FieldValueBlockEncoding() : prev(0) {}
inline void write(BinaryWriter &w, T v) {
w << CompressedInt<T>(v - prev);
prev = v;
}
T read(BinaryReader &r) {
CompressedInt<T> v;
r >> v;
prev += v.value;
return prev;
}
T prev;
};
template <>
struct FieldValueBlockEncoding<double> {
inline void write(BinaryWriter &w, double v) {
w << v;
}
double read(BinaryReader &r) {
double v;
r >> v;
return v;
}
};
template <>
struct FieldValueBlockEncoding<bool> {
inline void write(BinaryWriter &w, bool v) {
w.serializeBytes( v ? LiteralStringRef("\x01") : LiteralStringRef("\x00") );
}
bool read(BinaryReader &r) {
uint8_t *v = (uint8_t *)r.readBytes(sizeof(uint8_t));
return *v != 0;
}
};
// Encoder for strings, writes deltas
template <>
struct FieldValueBlockEncoding<Standalone<StringRef>> {
inline void write(BinaryWriter &w, Standalone<StringRef> const &v) {
int reuse = 0;
int stop = std::min(v.size(), prev.size());
while(reuse < stop && v[reuse] == prev[reuse])
++reuse;
w << CompressedInt<int>(reuse) << CompressedInt<int>(v.size() - reuse);
if(v.size() > reuse)
w.serializeBytes(v.substr(reuse));
prev = v;
}
Standalone<StringRef> read(BinaryReader &r) {
CompressedInt<int> reuse;
CompressedInt<int> extra;
r >> reuse >> extra;
ASSERT(reuse.value >= 0 && extra.value >= 0 && reuse.value <= prev.size());
Standalone<StringRef> v = makeString(reuse.value + extra.value);
memcpy(mutateString(v), prev.begin(), reuse.value);
memcpy(mutateString(v) + reuse.value, r.readBytes(extra.value), extra.value);
prev = v;
return v;
}
// Using a Standalone<StringRef> for prev is efficient for writing but not great for reading.
Standalone<StringRef> prev;
};
// Field level for value type of T using header type of Header. Default header type is the default FieldHeader implementation for type T.
template <class T, class Header = FieldHeader<T>, class Encoder = FieldValueBlockEncoding<T>>
struct FieldLevel {
Deque<MetricData> metrics;
int64_t appendUsed;
Header header;
// The previous header and the last timestamp at which an out going MetricData block requires header patching
Optional<Header> previousHeader;
uint64_t lastTimeRequiringHeaderPatch;
Encoder enc;
explicit FieldLevel() : appendUsed(0) {
metrics.emplace_back(MetricData());
metrics.back().writer << header;
}
FieldLevel(FieldLevel &&f)
: metrics(std::move(f.metrics)), appendUsed(f.appendUsed), enc(f.enc), header(f.header),
previousHeader(f.previousHeader), lastTimeRequiringHeaderPatch(f.lastTimeRequiringHeaderPatch) {
}
// update Header, use Encoder to write T v
void log( T v, uint64_t t, bool& overflow, int64_t& bytes ) {
int lastLength = metrics.back().writer.getLength();
if( metrics.back().start == 0 )
metrics.back().start = t;
header.update(v);
enc.write(metrics.back().writer, v);
bytes += metrics.back().writer.getLength() - lastLength;
if(lastLength + appendUsed > FLOW_KNOBS->MAX_METRIC_SIZE)
overflow = true;
}
void nextKey( uint64_t t ) {
// If nothing has actually been written to the current block, don't add a new block,
// just modify this one if needed so that the next log call will set the ts for this block.
auto &m = metrics.back();
if(m.start == 0 && m.appendStart == 0)
return;
// This block would have appended but had no data so just reset it to a non-append block instead of adding a new one
if(m.appendStart != 0 && m.writer.getLength() == 0) {
m.appendStart = 0;
m.writer << header;
enc = Encoder();
return;
}
metrics.back().rollTime = t;
metrics.emplace_back(MetricData());
metrics.back().writer << header;
enc = Encoder();
appendUsed = 0;
}
void rollMetric( uint64_t t ) {
ASSERT(metrics.size());
if(metrics.back().start) {
metrics.back().rollTime = t;
appendUsed += metrics.back().writer.getLength();
if(metrics.back().appendStart)
metrics.emplace_back(MetricData(metrics.back().appendStart));
else
metrics.emplace_back(MetricData(metrics.back().start));
}
}
// Calculate header as of the end of a value block
static Header calculateHeader(StringRef block) {
BinaryReader r(block, AssumeVersion(currentProtocolVersion));
Header h;
r >> h;
Encoder dec;
while(!r.empty()) {
T v = dec.read(r);
h.update(v);
}
return h;
}
// Read header at position, update it with previousHeader, overwrite old header with new header.
static void updateSerializedHeader(StringRef buf, const Header &patch) {
BinaryReader r(buf, AssumeVersion(currentProtocolVersion));
Header h;
r >> h;
h.update(patch);
OverWriter w(mutateString(buf), buf.size(), AssumeVersion(currentProtocolVersion));
w << h;
}
// Flushes data blocks in metrics to batch, optionally patching headers if a header is given
void flushUpdates(MetricKeyRef const &mk, uint64_t rollTime, MetricUpdateBatch &batch) {
while(metrics.size()) {
auto& data = metrics.front();
if(data.start != 0 && data.rollTime <= rollTime) {
// If this data is to be appended, write it to the batch now.
if( data.appendStart ) {
batch.appends.push_back(KeyWithWriter(mk.packDataKey(data.appendStart), data.writer));
} else {
// Otherwise, insert but first, patch the header if this block is old enough
if(data.rollTime <= lastTimeRequiringHeaderPatch) {
ASSERT(previousHeader.present());
FieldLevel<T>::updateSerializedHeader(data.writer.toStringRef(), previousHeader.get());
}
batch.inserts.push_back(KeyWithWriter(mk.packDataKey(data.start), data.writer));
}
if(metrics.size() == 1) {
rollMetric(data.rollTime);
metrics.pop_front();
break;
}
metrics.pop_front();
}
else
break;
}
}
ACTOR static Future<Void> updatePreviousHeader(FieldLevel *self, IMetricDB *db, Standalone<MetricKeyRef> mk, uint64_t rollTime, MetricUpdateBatch *batch) {
Optional<Standalone<StringRef>> block = wait(db->getLastBlock(mk.packDataKey(-1)));
// If the block is present, use it
if(block.present()) {
// Calculate the previous data's final header value
Header oldHeader = calculateHeader(block.get());
// Set the previous header in self to this header for us in patching outgoing blocks
self->previousHeader = oldHeader;
// Update the header in self so the next new block created will be current
self->header.update(oldHeader);
// Any blocks already in the metrics queue will need to be patched at the time that they are
// flushed to the DB (which isn't necessarity part of the current flush) so set the last time
// that requires a patch to the time of the last MetricData in the queue
self->lastTimeRequiringHeaderPatch = self->metrics.back().rollTime;
}
else {
// Otherwise, there is no previous header so no headers need to be updated at all ever.
// Set the previous header to an empty header so that flush() sees that this process
// has already finished, and set lastTimeRequiringHeaderPatch to 0 since no blocks ever need to be patched.
self->previousHeader = Header();
self->lastTimeRequiringHeaderPatch = 0;
}
// Now flush the level data up to the rollTime argument and patch anything older than lastTimeRequiringHeaderPatch
self->flushUpdates(mk, rollTime, *batch);
return Void();
}
// Flush this level's data to the output batch.
// This function must NOT be called again until any callbacks added to batch have been completed.
void flush(const MetricKeyRef &mk, uint64_t rollTime, MetricUpdateBatch &batch) {
// Don't do anything if there is no data in the queue to flush.
if(metrics.empty() || metrics.front().start == 0)
return;
// If the previous header is present then just call flushUpdates now.
if(previousHeader.present())
return flushUpdates(mk, rollTime, batch);
Standalone<MetricKeyRef> mkCopy = mk;
// Previous header is not present so queue a callback which will update it
batch.callbacks.push_back([=](IMetricDB *db, MetricUpdateBatch *batch) mutable -> Future<Void> {
return updatePreviousHeader(this, db, mkCopy, rollTime, batch);
});
}
};
// A field Description to be used for continuous metrics, whose field name and type should never be accessed
struct NullDescriptor {
static StringRef name() { return StringRef(); }
};
// Descriptor must have the methods name() and typeName(). They can be either static or member functions (such as for runtime configurability).
// Descriptor is inherited so that syntatically Descriptor::fn() works in either case and so that an empty Descriptor with static methods
// will take up 0 space. EventField() accepts an optional Descriptor instance.
template <class T, class Descriptor = NullDescriptor, class FieldLevelType = FieldLevel<T>>
struct EventField : public Descriptor {
std::vector<FieldLevelType> levels;
EventField( EventField&& r ) noexcept(true) : Descriptor(r), levels(std::move(r.levels)) {}
void operator=( EventField&& r ) noexcept(true) {
levels = std::move(r.levels);
}
EventField(Descriptor d = Descriptor()) : Descriptor(d) {
}
static StringRef typeName() { return metricTypeName<T>(); }
void init() {
if(levels.size() != FLOW_KNOBS->MAX_METRIC_LEVEL) {
levels.clear();
levels.resize(FLOW_KNOBS->MAX_METRIC_LEVEL);
}
}
void log( T v, uint64_t t, int64_t l, bool& overflow, int64_t& bytes ) {
return levels[l].log(v, t, overflow, bytes);
}
void nextKey( uint64_t t, int level ) {
levels[level].nextKey(t);
}
void nextKeyAllLevels( uint64_t t ) {
for(int64_t i = 0; i < FLOW_KNOBS->MAX_METRIC_LEVEL; i++)
nextKey(t, i);
}
void rollMetric( uint64_t t ) {
for(int i = 0; i < levels.size(); i++) {
levels[i].rollMetric(t);
}
}
void flushField(MetricKeyRef const &mk, uint64_t rollTime, MetricUpdateBatch &batch) {
MetricKeyRef fk = mk.withField(*this);
for(int j = 0; j < levels.size(); ++j) {
fk.level = j;
levels[j].flush(fk, rollTime, batch);
}
}
// Writes and Event metric field registration key
void registerField( const MetricKeyRef &mk, std::vector<Standalone<StringRef>>& fieldKeys ) {
fieldKeys.push_back(mk.withField(*this).packFieldRegKey());
}
};
struct MakeEventField {
template <class Descriptor>
EventField<typename Descriptor::type, Descriptor> operator() (Descriptor) { return EventField<typename Descriptor::type, Descriptor>(); }
};
struct TimeDescriptor {
static StringRef name() { return LiteralStringRef("Time"); }
};
struct BaseMetric {
BaseMetric(MetricNameRef const &name) : metricName(name), pCollection(nullptr), registered(false), enabled(false) {
setConfig(false);
}
virtual ~BaseMetric() {
}
virtual void addref() = 0;
virtual void delref() = 0;
virtual void rollMetric(uint64_t t) = 0;
virtual void flushData(const MetricKeyRef &mk, uint64_t rollTime, MetricUpdateBatch &batch) = 0;
virtual void registerFields(const MetricKeyRef &mk, std::vector<Standalone<StringRef>>& fieldKeys) {};
// Set the metric's config. An assert will fail if the metric is enabled before the metrics collection is available.
void setConfig(bool enable, int minLogLevel = 0) {
bool wasEnabled = enabled;
enabled = enable;
minLevel = minLogLevel;
if(enable && pCollection == nullptr) {
pCollection = TDMetricCollection::getTDMetrics();
ASSERT(pCollection != nullptr);
}
if(wasEnabled != enable) {
if(enabled) {
onEnable();
pCollection->metricEnabled.trigger();
}
else
onDisable();
}
}
// Callbacks for when metric is Enabled or Disabled.
// Metrics should verify their underlying storage on Enable because they could have been initially created
// at a time when the knobs were not initialized.
virtual void onEnable() = 0;
virtual void onDisable() {};
// Combines checking this metric's configured minimum level and any collection-wide throttling
// This should only be called after it is determined that a metric is enabled.
bool canLog(int level) {
return level >= minLevel && pCollection->canLog(level);
}
Standalone<MetricNameRef> metricName;
bool enabled; // The metric is currently logging data
int minLevel; // The minimum level that will be logged.
// All metrics need a pointer to their collection for performance reasons - every time a data point is logged
// canLog must be called which uses the collection's canLog to decide based on the metric write queue.
TDMetricCollection *pCollection;
// The metric has been registered in its current form (some metrics can change and require re-reg)
bool registered;
};
struct BaseEventMetric : BaseMetric {
BaseEventMetric(MetricNameRef const &name) : BaseMetric(name) {
}
// Needed for MetricUtil
static const StringRef metricType;
Void getValue() const {
return Void();
}
virtual ~BaseEventMetric() {}
// Every metric should have a set method for its underlying type in order for MetricUtil::getOrCreateInstance
// to initialize it. In the case of event metrics there is no underlying type so the underlying type
// is Void and set does nothing.
void set(Void const &val) {}
virtual StringRef getTypeName() = 0;
};
template <class E>
struct EventMetric : E, ReferenceCounted<EventMetric<E>>, MetricUtil<EventMetric<E>>, BaseEventMetric {
EventField<int64_t, TimeDescriptor> time;
bool latestRecorded;
decltype( tuple_map( MakeEventField(), typename Descriptor<E>::fields() ) ) values;
virtual void addref() { ReferenceCounted<EventMetric<E>>::addref(); }
virtual void delref() { ReferenceCounted<EventMetric<E>>::delref(); }
EventMetric( MetricNameRef const &name, Void) : BaseEventMetric(name), latestRecorded(false) {
}
virtual ~EventMetric() {
}
virtual StringRef getTypeName() { return Descriptor<E>::typeName(); }
void onEnable() {
// Must initialize fields, previously knobs may not have been set.
time.init();
initFields( typename Descriptor<E>::field_indexes());
}
// Log the event.
// Returns the time that was logged for the event so that it can be passed to other events that need to be time-sync'd.
// NOTE: Do NOT use the same time for two consecutive loggings of the SAME event. This *could* cause there to be metric data
// blocks such that the last timestamp of one block is equal to the first timestamp of the next, which means if a search is done
// for the exact timestamp then the first event will not be found.
uint64_t log(uint64_t explicitTime = 0) {
if(!enabled)
return 0;
uint64_t t = explicitTime ? explicitTime : timer_int();
double x = g_random->random01();
int64_t l = 0;
if (x == 0.0)
l = FLOW_KNOBS->MAX_METRIC_LEVEL-1;
else
l = std::min(FLOW_KNOBS->MAX_METRIC_LEVEL-1, (int64_t)(::log(1.0/x) / FLOW_KNOBS->METRIC_LEVEL_DIVISOR));
if(!canLog(l))
return 0;
bool overflow = false;
int64_t bytes = 0;
time.log(t, t, l, overflow, bytes);
logFields( typename Descriptor<E>::field_indexes(), t, l, overflow, bytes );
if(overflow) {
time.nextKey(t, l);
nextKeys(typename Descriptor<E>::field_indexes(), t, l);
}
latestRecorded = false;
return t;
}
template <size_t... Is>
void logFields(index_sequence<Is...>, uint64_t t, int64_t l, bool& overflow, int64_t& bytes) {
auto _ = {
(std::get<Is>(values).log( std::tuple_element<Is, typename Descriptor<E>::fields>::type::get( static_cast<E&>(*this) ), t, l, overflow, bytes ), Void())...
};
}
template <size_t... Is>
void initFields(index_sequence<Is...>) {
auto _ = {
(std::get<Is>(values).init(), Void())...
};
}
template <size_t... Is>
void nextKeys(index_sequence<Is...>, uint64_t t, int64_t l ) {
auto _ = {
(std::get<Is>(values).nextKey(t, l),Void())...
};
}
virtual void flushData(MetricKeyRef const &mk, uint64_t rollTime, MetricUpdateBatch &batch) {
time.flushField( mk, rollTime, batch );
flushFields( typename Descriptor<E>::field_indexes(), mk, rollTime, batch );
if(!latestRecorded) {
batch.updates.push_back(std::make_pair(mk.packLatestKey(), StringRef()));
latestRecorded = true;
}
}
template <size_t... Is>
void flushFields(index_sequence<Is...>, MetricKeyRef const &mk, uint64_t rollTime, MetricUpdateBatch &batch ) {
auto _ = {
(std::get<Is>(values).flushField( mk, rollTime, batch ),Void())...
};
}
virtual void rollMetric( uint64_t t ) {
time.rollMetric(t);
rollFields( typename Descriptor<E>::field_indexes(), t );
}
template <size_t... Is>
void rollFields(index_sequence<Is...>, uint64_t t ) {
auto _ = {
(std::get<Is>(values).rollMetric( t ),Void())...
};
}
virtual void registerFields( MetricKeyRef const &mk, std::vector<Standalone<StringRef>>& fieldKeys ) {
time.registerField( mk, fieldKeys );
registerFields( typename Descriptor<E>::field_indexes(), mk, fieldKeys );
}
template <size_t... Is>
void registerFields(index_sequence<Is...>, const MetricKeyRef &mk, std::vector<Standalone<StringRef>>& fieldKeys ) {
auto _ = {
(std::get<Is>(values).registerField( mk, fieldKeys ),Void())...
};
}
protected:
bool it;
};
// A field Descriptor compatible with EventField but with name set at runtime
struct DynamicDescriptor {
DynamicDescriptor(const char *name)
: _name(StringRef((uint8_t *)name, strlen(name))) {}
StringRef name() const { return _name; }
private:
const Standalone<StringRef> _name;
};
template<typename T>
struct DynamicField;
struct DynamicFieldBase {
virtual ~DynamicFieldBase() {}
virtual StringRef fieldName() = 0;
virtual const StringRef getDerivedTypeName() = 0;
virtual void init() = 0;
virtual void clear() = 0;
virtual void log(uint64_t t, int64_t l, bool& overflow, int64_t& bytes ) = 0;
virtual void nextKey( uint64_t t, int level ) = 0;
virtual void nextKeyAllLevels( uint64_t t) = 0;
virtual void rollMetric( uint64_t t ) = 0;
virtual void flushField( MetricKeyRef const &mk, uint64_t rollTime, MetricUpdateBatch &batch) = 0;
virtual void registerField( MetricKeyRef const &mk, std::vector<Standalone<StringRef>>& fieldKeys ) = 0;
// Set the current value of this field from the value of another
virtual void setValueFrom(DynamicFieldBase *src, StringRef eventType) = 0;
// Create a new field of the same type and with the same current value as this one and with the given name
virtual DynamicFieldBase * createNewWithValue(const char *name) = 0;
// This does a fairly cheap and "safe" downcast without using dynamic_cast / RTTI by checking that the pointer value
// of the const char * type string is the same as getDerivedTypeName for this object.
template<typename T> DynamicField<T> * safe_downcast(StringRef eventType) {
if(getDerivedTypeName() == metricTypeName<T>())
return (DynamicField<T> *)this;
TraceEvent(SevWarnAlways, "ScopeEventFieldTypeMismatch")
.detail("EventType", eventType.toString())
.detail("FieldName", fieldName().toString())
.detail("OldType", getDerivedTypeName().toString())
.detail("NewType", metricTypeName<T>().toString());
return NULL;
}
};
template<typename T>
struct DynamicField : public DynamicFieldBase, EventField<T, DynamicDescriptor> {
typedef EventField<T, DynamicDescriptor> EventFieldType;
DynamicField(const char *name) : DynamicFieldBase(), EventFieldType(DynamicDescriptor(name)), value(T()) {}
virtual ~DynamicField() {}
StringRef fieldName() { return EventFieldType::name(); }
// Get the field's datatype, this is used as a form of RTTI by DynamicFieldBase::safe_downcast()
const StringRef getDerivedTypeName() { return metricTypeName<T>(); }
// Pure virtual implementations
void clear() { value = T(); }
void log(uint64_t t, int64_t l, bool& overflow, int64_t& bytes) {
return EventFieldType::log(value, t, l, overflow, bytes);
}
// Redirects to EventFieldType methods
void nextKey( uint64_t t, int level ) {
return EventFieldType::nextKey(t, level);
}
void nextKeyAllLevels( uint64_t t) {
return EventFieldType::nextKeyAllLevels(t);
}
void rollMetric( uint64_t t ) {
return EventFieldType::rollMetric(t);
}
void flushField(MetricKeyRef const &mk, uint64_t rollTime, MetricUpdateBatch &batch) {
return EventFieldType::flushField(mk, rollTime, batch);
}
void registerField(MetricKeyRef const &mk, std::vector<Standalone<StringRef>>& fieldKeys) {
return EventFieldType::registerField(mk, fieldKeys);
}
void init() {
return EventFieldType::init();
}
// Set this field's value to the value of another field of exactly the same type.
void setValueFrom(DynamicFieldBase *src, StringRef eventType) {
DynamicField<T> *s = src->safe_downcast<T>(eventType);
if(s != NULL)
set(s->value);
else
clear(); // Not really necessary with proper use but just in case it is better to clear than use an old value.
}
DynamicFieldBase * createNewWithValue(const char *name) {
DynamicField<T> *n = new DynamicField<T>(name);
n->set(value);
return n;
}
// Non virtuals
void set(T val) { value = val; }
private:
T value;
};
// A DynamicEventMetric is an EventMetric whose field set can be modified at runtime.
struct DynamicEventMetric : ReferenceCounted<DynamicEventMetric>, MetricUtil<DynamicEventMetric>, BaseEventMetric {
private:
EventField<int64_t, TimeDescriptor> time;
bool latestRecorded;
// TODO: A Standalone key type isn't ideal because on lookups a ref will be made Standalone just for the search
// All fields that are set with setField will be in fields.
std::map<Standalone<StringRef>, DynamicFieldBase *> fields;