Skip to content

Commit 6b8e613

Browse files
committed
Don't crash stats filter when running out of memory.
Instead, print an error message (once) and stop attempting to collect block size statistics.
1 parent ea1f481 commit 6b8e613

File tree

1 file changed

+24
-20
lines changed

1 file changed

+24
-20
lines changed

filters/stats/stats.cpp

Lines changed: 24 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,26 @@ print_totals (uint64_t usecs)
154154
free (rate);
155155
}
156156

157+
static void
158+
inc_blksize_ctr (blksize_hist_t &hist, size_t blksize)
159+
{
160+
static bool out_of_memory = false;
161+
if (out_of_memory)
162+
return;
163+
164+
ACQUIRE_LOCK_FOR_CURRENT_SCOPE (&lock);
165+
166+
try {
167+
hist[blksize]++;
168+
}
169+
catch (std::bad_alloc) {
170+
// Avoid reporting the same error over and over again
171+
nbdkit_error ("out of memory for blocksize statistics");
172+
out_of_memory = true;
173+
return;
174+
}
175+
}
176+
157177
static void
158178
print_histogram (const blksize_hist_t hist, int count)
159179
{
@@ -324,11 +344,7 @@ stats_pread (nbdkit_next *next,
324344
struct timeval start;
325345
int r;
326346

327-
{
328-
ACQUIRE_LOCK_FOR_CURRENT_SCOPE (&lock);
329-
blksize_pread_st[count]++;
330-
}
331-
347+
inc_blksize_ctr (blksize_pread_st, count);
332348
gettimeofday (&start, NULL);
333349
r = next->pread (next, buf, count, offset, flags, err);
334350
if (r == 0) record_stat (&pread_st, count, &start);
@@ -345,11 +361,7 @@ stats_pwrite (nbdkit_next *next,
345361
struct timeval start;
346362
int r;
347363

348-
{
349-
ACQUIRE_LOCK_FOR_CURRENT_SCOPE (&lock);
350-
blksize_pwrite_st[count]++;
351-
}
352-
364+
inc_blksize_ctr (blksize_pwrite_st, count);
353365
gettimeofday (&start, NULL);
354366
r = next->pwrite (next, buf, count, offset, flags, err);
355367
if (r == 0) record_stat (&pwrite_st, count, &start);
@@ -366,11 +378,7 @@ stats_trim (nbdkit_next *next,
366378
struct timeval start;
367379
int r;
368380

369-
{
370-
ACQUIRE_LOCK_FOR_CURRENT_SCOPE (&lock);
371-
blksize_trim_st[count]++;
372-
}
373-
381+
inc_blksize_ctr (blksize_trim_st, count);
374382
gettimeofday (&start, NULL);
375383
r = next->trim (next, count, offset, flags, err);
376384
if (r == 0) record_stat (&trim_st, count, &start);
@@ -402,11 +410,7 @@ stats_zero (nbdkit_next *next,
402410
struct timeval start;
403411
int r;
404412

405-
{
406-
ACQUIRE_LOCK_FOR_CURRENT_SCOPE (&lock);
407-
blksize_zero_st[count]++;
408-
}
409-
413+
inc_blksize_ctr (blksize_zero_st, count);
410414
gettimeofday (&start, NULL);
411415
r = next->zero (next, count, offset, flags, err);
412416
if (r == 0) record_stat (&zero_st, count, &start);

0 commit comments

Comments
 (0)