« blib/lib/ForgeOps/Tracker/Integrations/PSGIPerformance.pm
↑ Summary
lib/ForgeOps/Tracker/SqlStatement.pm »
| 1 | package ForgeOps::Tracker::MetricBuffer; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | use threads; | ||
| 6 | use threads::shared; | ||
| 7 | use JSON::PP (); | ||
| 8 | use Scalar::Util qw(weaken); | ||
| 9 | use ForgeOps::Tracker::DeliveryStatus; | ||
| 10 | |||
| 11 | # Collects individual capture_metric()/capture_infrastructure_metric() calls in-process and | ||
| 12 | # periodically flushes them as one batch, rather than one network call per capture. Unlike | ||
| 13 | # PerformanceFlusher this keeps a *list* of individually meaningful entries instead of summing them | ||
| 14 | # into buckets: a customer's own signup or payment is exactly the kind of thing they will want a | ||
| 15 | # genuinely accurate count/sum of later, so the server stores one row per entry as-is. Ported from | ||
| 16 | # gems/forge_ops_tracker's metric_buffer.rb and infrastructure_metric_buffer.rb, which are the same | ||
| 17 | # class twice; here it is one class instantiated twice, told which client method and interval to use. | ||
| 18 | # | ||
| 19 | # Three deliberate differences from the Ruby buffers: | ||
| 20 | # | ||
| 21 | # - A flush snapshots the first N entries and, on success, removes exactly those N, instead of | ||
| 22 | # resetting the whole list, so an entry recorded while the request is in flight (the lock is not | ||
| 23 | # held around the network call) is kept for the next flush rather than lost. | ||
| 24 | # - The buffer is capped at MAX_ENTRIES, and once full further entries are dropped until a flush | ||
| 25 | # lets go of them: an unreachable server fails every flush, and an uncapped buffer would keep | ||
| 26 | # growing until the batch is given up on (see DeliveryStatus::settle). Dropping the newest rather than the oldest keeps the | ||
| 27 | # entries a flush is delivering at the front of the list, which is what makes removing exactly those | ||
| 28 | # afterward exact. | ||
| 29 | # - A NaN or infinite value is dropped at record time: JSON::PP would encode it as the invalid JSON | ||
| 30 | # token NaN/Inf and the server would reject the whole batch. | ||
| 31 | # | ||
| 32 | # Perl's ithreads share nothing by default (see PerformanceFlusher's own comment), so the entries live | ||
| 33 | # in a threads::shared array of JSON strings: a flat shared array sidesteps sharing nested structures. | ||
| 34 | # The background thread is started lazily on the first record, like DeliveryQueue's. An END block | ||
| 35 | # flushes whatever is left when the program ends normally, which is what a short-lived cron script that | ||
| 36 | # captures a few readings and falls off the end relies on. | ||
| 37 | use constant MAX_ENTRIES => 1000; | ||
| 38 | |||
| 39 | my @live_buffers; | ||
| 40 | |||
| 41 | sub new { | ||
| 42 | my ($class, $configuration, $deliver, $interval) = @_; | ||
| 43 | |||
| 44 | my @entries :shared; | ||
| 45 | my $lock = 1; | ||
| 46 | share($lock); | ||
| 47 | my $failed_flushes = 0; | ||
| 48 | share($failed_flushes); | ||
| 49 | |||
| 50 | my $self = bless { | ||
| 51 | configuration => $configuration, | ||
| 52 | deliver => $deliver, # takes an arrayref of hashrefs, returns a DeliveryStatus (or 1/0) | ||
| 53 | interval => $interval, # returns the flush interval in seconds | ||
| 54 | entries => \@entries, | ||
| 55 | lock => \$lock, | ||
| 56 | failed_flushes => \$failed_flushes, | ||
| 57 | worker => undef, | ||
| 58 | }, $class; | ||
| 59 | |||
| 60 | push @live_buffers, $self; | ||
| 61 | weaken($live_buffers[-1]); | ||
| 62 | return $self; | ||
| 63 | } | ||
| 64 | |||
| 65 | # Adds one entry (everything but recorded_at, which is stamped here); returns whether it was kept. | ||
| 66 | sub record { | ||
| 67 | my ($self, $entry) = @_; | ||
| 68 | my $value = $entry->{value}; | ||
| 69 | unless (defined $value && !ref($value) && $value =~ /\A-?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?\z/) { | ||
| 70 | $self->{configuration}->log('[forge-ops-tracker] dropped a metric with a non-numeric or non-finite value'); | ||
| 71 | return 0; | ||
| 72 | } | ||
| 73 | |||
| 74 | $self->_ensure_worker; | ||
| 75 | |||
| 76 | my $stamped = { %$entry, recorded_at => _now(), value => $value + 0 }; | ||
| 77 | lock(${ $self->{lock} }); | ||
| 78 | if (@{ $self->{entries} } >= MAX_ENTRIES) { | ||
| 79 | $self->{configuration}->log('[forge-ops-tracker] metric buffer full, dropping a metric'); | ||
| 80 | return 0; | ||
| 81 | } | ||
| 82 | push @{ $self->{entries} }, JSON::PP::encode_json($stamped); | ||
| 83 | return 1; | ||
| 84 | } | ||
| 85 | |||
| 86 | # Delivers everything buffered so far as one batch. A delivery that failed for now keeps every entry; | ||
| 87 | # a batch the server rejected, or the DeliveryStatus::MAX_FAILED_FLUSHES-th failure in a row, drops it. | ||
| 88 | sub flush { | ||
| 89 | my ($self) = @_; | ||
| 90 | |||
| 91 | my @snapshot; | ||
| 92 | { | ||
| 93 | lock(${ $self->{lock} }); | ||
| 94 | return unless @{ $self->{entries} }; | ||
| 95 | @snapshot = @{ $self->{entries} }; | ||
| 96 | } | ||
| 97 | |||
| 98 | my $result = eval { $self->{deliver}->([ map { JSON::PP::decode_json($_) } @snapshot ]) }; | ||
| 99 | if ($@) { | ||
| 100 | # A delivery that died is one more failed flush, not a reason to die into the caller. | ||
| 101 | eval { $self->{configuration}->log("[forge-ops-tracker] metric flush error: $@") }; | ||
| 102 | $result = 0; | ||
| 103 | } | ||
| 104 | my $status = ForgeOps::Tracker::DeliveryStatus::from($result); | ||
| 105 | |||
| 106 | lock(${ $self->{lock} }); | ||
| 107 | my ($release, $why) = ForgeOps::Tracker::DeliveryStatus::settle($self->{failed_flushes}, $status); | ||
| 108 | return unless $release; | ||
| 109 | if ($why) { | ||
| 110 | eval { $self->{configuration}->log('[forge-ops-tracker] dropping ' . scalar(@snapshot) . " buffered metrics: $why") }; | ||
| 111 | } | ||
| 112 | |||
| 113 | # Exactly the entries just sent: anything recorded while the request was in flight sits after | ||
| 114 | # them and stays for the next flush. | ||
| 115 | # shift in a loop: splice is not implemented for shared arrays. | ||
| 116 | shift @{ $self->{entries} } for 1 .. @snapshot; | ||
| 117 | } | ||
| 118 | |||
| 119 | sub count { | ||
| 120 | my ($self) = @_; | ||
| 121 | lock(${ $self->{lock} }); | ||
| 122 | return scalar @{ $self->{entries} }; | ||
| 123 | } | ||
| 124 | |||
| 125 | # Test-only: drops whatever is buffered without delivering it. | ||
| 126 | sub _clear { | ||
| 127 | my ($self) = @_; | ||
| 128 | lock(${ $self->{lock} }); | ||
| 129 | @{ $self->{entries} } = (); | ||
| 130 | } | ||
| 131 | |||
| 132 | sub _ensure_worker { | ||
| 133 | my ($self) = @_; | ||
| 134 | return if $self->{worker}; | ||
| 135 | |||
| 136 | my $buffer = $self; | ||
| 137 | $self->{worker} = threads->create(sub { | ||
| 138 | while (1) { | ||
| 139 | my $interval = $buffer->{interval}->(); | ||
| 140 | $interval = 60 unless $interval && $interval > 0; | ||
| 141 | sleep($interval); | ||
| 142 | |||
| 143 | # Per tick, not left to kill the loop: one bad flush must not stop every flush after it. | ||
| 144 | eval { $buffer->flush }; | ||
| 145 | if ($@) { | ||
| 146 | eval { $buffer->{configuration}->log("[forge-ops-tracker] metric flush error: $@") }; | ||
| 147 | } | ||
| 148 | } | ||
| 149 | }); | ||
| 150 | $self->{worker}->detach; | ||
| 151 | } | ||
| 152 | |||
| 153 | sub _now { | ||
| 154 | my @t = gmtime; | ||
| 155 | return sprintf('%04d-%02d-%02dT%02d:%02d:%02dZ', $t[5] + 1900, $t[4] + 1, @t[3, 2, 1, 0]); | ||
| 156 | } | ||
| 157 | |||
| 158 | # A normal program end: deliver whatever is still buffered (in the main thread only: a detached worker | ||
| 159 | # also runs END blocks in some Perl builds, and must not flush twice). | ||
| 160 | END { | ||
| 161 | if (threads->tid == 0) { | ||
| 162 | for my $buffer (grep { defined } @live_buffers) { | ||
| 163 | eval { $buffer->flush }; | ||
| 164 | } | ||
| 165 | } | ||
| 166 | } | ||
| 167 | |||
| 168 | 1; |