740027
From af2a4ed22594badd2719c0123441d69b17bd8328 Mon Sep 17 00:00:00 2001
740027
From: Federico Simoncelli <fsimonce@redhat.com>
740027
Date: Fri, 26 Sep 2014 17:12:32 +0000
740027
Subject: [PATCH] dd: new status=progress level to print stats periodically
740027
740027
* src/dd.c: Report the transfer progress every second when the
740027
new status=progress level is used.  Adjust the handling and
740027
description of the status= option so that they're treated as
740027
mutually exclusive levels, rather than flags with implicit precedence.
740027
* doc/coreutils.texi (dd invocation): Document the new progress
740027
status level.  Reference the new level in the description of SIGUSR1.
740027
* tests/dd/stats.sh: Add new test for status=progress.
740027
* tests/dd/misc.sh: Change so status=none only takes precedence
740027
if it's the last level specified.
740027
---
740027
diff --git a/doc/coreutils.texi b/doc/coreutils.texi
740027
index 7d32af5..03bb710 100644
740027
--- a/doc/coreutils.texi
740027
+++ b/doc/coreutils.texi
740027
@@ -8631,24 +8631,32 @@ will ensure that @samp{count=} corresponds to complete input blocks
740027
 rather than the traditional POSIX specified behavior of counting
740027
 input read operations.
740027
 
740027
-@item status=@var{which}
740027
+@item status=@var{level}
740027
 @opindex status
740027
 Transfer information is normally output to stderr upon
740027
 receipt of the @samp{INFO} signal or when @command{dd} exits.
740027
-Specifying @var{which} will identify which information to suppress.
740027
+Specifying @var{level} will adjust the amount of information printed,
740027
+with the last @var{level} specified taking precedence.
740027
 
740027
 @table @samp
740027
 
740027
-@item noxfer
740027
-@opindex noxfer @r{dd status=}
740027
-Do not print the transfer rate and volume statistics
740027
-that normally make up the last status line.
740027
-
740027
 @item none
740027
 @opindex none @r{dd status=}
740027
 Do not print any informational or warning messages to stderr.
740027
 Error messages are output as normal.
740027
 
740027
+@item noxfer
740027
+@opindex noxfer @r{dd status=}
740027
+Do not print the final transfer rate and volume statistics
740027
+that normally make up the last status line.
740027
+
740027
+@item progress
740027
+@opindex progress @r{dd status=}
740027
+Print the transfer rate and volume statistics on stderr,
740027
+when processing each input block.  Statistics are output
740027
+on a single line at most once every second, but updates
740027
+can be delayed when waiting on I/O.
740027
+
740027
 @end table
740027
 
740027
 @item conv=@var{conversion}[,@var{conversion}]@dots{}
740027
@@ -9033,6 +9041,9 @@ The above script will output in the following format
740027
 5120000000 bytes (5.1 GB) copied, 18.913 seconds, 271 MB/s
740027
 @end example
740027
 
740027
+Note also the @samp{status=progress} option which periodically updates
740027
+the last line of the transfer statistics above.
740027
+
740027
 @vindex POSIXLY_CORRECT
740027
 On systems lacking the @samp{INFO} signal @command{dd} responds to the
740027
 @samp{USR1} signal instead, unless the @env{POSIXLY_CORRECT}
740027
diff --git a/src/dd.c b/src/dd.c
740027
index d22ec59..4018190 100644
740027
--- a/src/dd.c
740027
+++ b/src/dd.c
740027
@@ -34,6 +34,7 @@
740027
 #include "long-options.h"
740027
 #include "quote.h"
740027
 #include "quotearg.h"
740027
+#include "verror.h"
740027
 #include "xstrtol.h"
740027
 #include "xtime.h"
740027
 
740027
@@ -132,11 +133,13 @@ enum
740027
     C_SPARSE = 0200000
740027
   };
740027
 
740027
-/* Status bit masks.  */
740027
+/* Status levels.  */
740027
 enum
740027
   {
740027
-    STATUS_NOXFER = 01,
740027
-    STATUS_NONE = 02
740027
+    STATUS_NONE = 1,
740027
+    STATUS_NOXFER = 2,
740027
+    STATUS_DEFAULT = 3,
740027
+    STATUS_PROGRESS = 4
740027
   };
740027
 
740027
 /* The name of the input file, or NULL for the standard input. */
740027
@@ -188,7 +191,7 @@ static int input_flags = 0;
740027
 static int output_flags = 0;
740027
 
740027
 /* Status flags for what is printed to stderr.  */
740027
-static int status_flags = 0;
740027
+static int status_level = STATUS_DEFAULT;
740027
 
740027
 /* If nonzero, filter characters through the translation table.  */
740027
 static bool translation_needed = false;
740027
@@ -211,6 +214,12 @@ static uintmax_t w_bytes = 0;
740027
 /* Time that dd started.  */
740027
 static xtime_t start_time;
740027
 
740027
+/* Previous time for periodic progress.  */
740027
+static xtime_t previous_time;
740027
+
740027
+/* Whether a '\n' is pending after writing progress.  */
740027
+static bool newline_pending;
740027
+
740027
 /* True if input is seekable.  */
740027
 static bool input_seekable;
740027
 
740027
@@ -373,8 +382,9 @@ static struct symbol_value const flags[] =
740027
 /* Status, for status="...".  */
740027
 static struct symbol_value const statuses[] =
740027
 {
740027
-  {"noxfer",	STATUS_NOXFER},
740027
   {"none",	STATUS_NONE},
740027
+  {"noxfer",	STATUS_NOXFER},
740027
+  {"progress",	STATUS_PROGRESS},
740027
   {"",		0}
740027
 };
740027
 
740027
@@ -517,6 +527,25 @@ maybe_close_stdout (void)
740027
     _exit (EXIT_FAILURE);
740027
 }
740027
 
740027
+/* Like error() but handle any pending newline.  */
740027
+
740027
+static void _GL_ATTRIBUTE_FORMAT ((__printf__, 3, 4))
740027
+nl_error (int status, int errnum, const char *fmt, ...)
740027
+{
740027
+  if (newline_pending)
740027
+    {
740027
+      fputc ('\n', stderr);
740027
+      newline_pending = false;
740027
+    }
740027
+
740027
+  va_list ap;
740027
+  va_start (ap, fmt);
740027
+  verror (status, errnum, fmt, ap);
740027
+  va_end (ap);
740027
+}
740027
+
740027
+#define error nl_error
740027
+
740027
 void
740027
 usage (int status)
740027
 {
740027
@@ -546,8 +575,10 @@ Copy a file, converting and formatting according to the operands.\n\
740027
   oflag=FLAGS     write as per the comma separated symbol list\n\
740027
   seek=N          skip N obs-sized blocks at start of output\n\
740027
   skip=N          skip N ibs-sized blocks at start of input\n\
740027
-  status=WHICH    WHICH info to suppress outputting to stderr;\n\
740027
-                  'noxfer' suppresses transfer stats, 'none' suppresses all\n\
740027
+  status=LEVEL    The LEVEL of information to print to stderr;\n\
740027
+                  'none' suppresses everything but error messages,\n\
740027
+                  'noxfer' suppresses the final transfer statistics,\n\
740027
+                  'progress' shows periodic transfer statistics\n\
740027
 "), stdout);
740027
       fputs (_("\
740027
 \n\
740027
@@ -724,8 +755,7 @@ multiple_bits_set (int i)
740027
 /* Print transfer statistics.  */
740027
 
740027
 static void
740027
-print_stats (void)
740027
-{
740027
+print_xfer_stats (xtime_t progress_time) {
740027
   char hbuf[LONGEST_HUMAN_READABLE + 1];
740027
   int human_opts =
740027
     (human_autoscale | human_round_to_nearest
740027
@@ -733,23 +763,8 @@ print_stats (void)
740027
   double delta_s;
740027
   char const *bytes_per_second;
740027
 
740027
-  if (status_flags & STATUS_NONE)
740027
-    return;
740027
-
740027
-  fprintf (stderr,
740027
-           _("%"PRIuMAX"+%"PRIuMAX" records in\n"
740027
-             "%"PRIuMAX"+%"PRIuMAX" records out\n"),
740027
-           r_full, r_partial, w_full, w_partial);
740027
-
740027
-  if (r_truncate != 0)
740027
-    fprintf (stderr,
740027
-             ngettext ("%"PRIuMAX" truncated record\n",
740027
-                       "%"PRIuMAX" truncated records\n",
740027
-                       select_plural (r_truncate)),
740027
-             r_truncate);
740027
-
740027
-  if (status_flags & STATUS_NOXFER)
740027
-    return;
740027
+  if (progress_time)
740027
+    fputc ('\r', stderr);
740027
 
740027
   /* Use integer arithmetic to compute the transfer rate,
740027
      since that makes it easy to use SI abbreviations.  */
740027
@@ -761,7 +776,8 @@ print_stats (void)
740027
            w_bytes,
740027
            human_readable (w_bytes, hbuf, human_opts, 1, 1));
740027
 
740027
-  xtime_t now = gethrxtime ();
740027
+  xtime_t now = progress_time ? progress_time : gethrxtime ();
740027
+
740027
   if (start_time < now)
740027
     {
740027
       double XTIME_PRECISIONe0 = XTIME_PRECISION;
740027
@@ -787,7 +803,42 @@ print_stats (void)
740027
      but that was incorrect for languages like Polish.  To fix this
740027
      bug we now use SI symbols even though they're a bit more
740027
      confusing in English.  */
740027
-  fprintf (stderr, _(", %g s, %s/s\n"), delta_s, bytes_per_second);
740027
+  char const *time_fmt = _(", %g s, %s/s\n");;
740027
+  if (progress_time)
740027
+    time_fmt = _(", %.6f s, %s/s");  /* OK with '\r' as increasing width.  */
740027
+  fprintf (stderr, time_fmt, delta_s, bytes_per_second);
740027
+
740027
+  newline_pending = !!progress_time;
740027
+}
740027
+
740027
+static void
740027
+print_stats (void)
740027
+{
740027
+  if (status_level == STATUS_NONE)
740027
+    return;
740027
+
740027
+  if (newline_pending)
740027
+    {
740027
+      fputc ('\n', stderr);
740027
+      newline_pending = false;
740027
+    }
740027
+
740027
+  fprintf (stderr,
740027
+           _("%"PRIuMAX"+%"PRIuMAX" records in\n"
740027
+             "%"PRIuMAX"+%"PRIuMAX" records out\n"),
740027
+           r_full, r_partial, w_full, w_partial);
740027
+
740027
+  if (r_truncate != 0)
740027
+    fprintf (stderr,
740027
+             ngettext ("%"PRIuMAX" truncated record\n",
740027
+                       "%"PRIuMAX" truncated records\n",
740027
+                       select_plural (r_truncate)),
740027
+             r_truncate);
740027
+
740027
+  if (status_level == STATUS_NOXFER)
740027
+    return;
740027
+
740027
+  print_xfer_stats (0);
740027
 }
740027
 
740027
 /* An ordinary signal was received; arrange for the program to exit.  */
740027
@@ -1035,7 +1086,7 @@ iread (int fd, char *buf, size_t size)
740027
       if (0 < prev_nread && prev_nread < size)
740027
         {
740027
           uintmax_t prev = prev_nread;
740027
-          if (!(status_flags & STATUS_NONE))
740027
+          if (status_level != STATUS_NONE)
740027
             error (0, 0, ngettext (("warning: partial read (%"PRIuMAX" byte); "
740027
                                     "suggest iflag=fullblock"),
740027
                                    ("warning: partial read (%"PRIuMAX" bytes); "
740027
@@ -1086,7 +1137,7 @@ iwrite (int fd, char const *buf, size_t size)
740027
     {
740027
       int old_flags = fcntl (STDOUT_FILENO, F_GETFL);
740027
       if (fcntl (STDOUT_FILENO, F_SETFL, old_flags & ~O_DIRECT) != 0
740027
-          && !(status_flags & STATUS_NONE))
740027
+          && status_level != STATUS_NONE)
740027
         error (0, errno, _("failed to turn off O_DIRECT: %s"),
740027
                quote (output_file));
740027
 
740027
@@ -1219,7 +1270,7 @@ operand_matches (char const *str, char const *pattern, char delim)
740027
 
740027
 static int
740027
 parse_symbols (char const *str, struct symbol_value const *table,
740027
-               char const *error_msgid)
740027
+               bool exclusive, char const *error_msgid)
740027
 {
740027
   int value = 0;
740027
 
740027
@@ -1241,7 +1292,10 @@ parse_symbols (char const *str, struct symbol_value const *table,
740027
             }
740027
         }
740027
 
740027
-      value |= entry->value;
740027
+      if (exclusive)
740027
+        value = entry->value;
740027
+      else
740027
+        value |= entry->value;
740027
       if (!strcomma)
740027
         break;
740027
       str = strcomma + 1;
740027
@@ -1316,17 +1370,17 @@ scanargs (int argc, char *const *argv)
740027
       else if (operand_is (name, "of"))
740027
         output_file = val;
740027
       else if (operand_is (name, "conv"))
740027
-        conversions_mask |= parse_symbols (val, conversions,
740027
+        conversions_mask |= parse_symbols (val, conversions, false,
740027
                                            N_("invalid conversion"));
740027
       else if (operand_is (name, "iflag"))
740027
-        input_flags |= parse_symbols (val, flags,
740027
+        input_flags |= parse_symbols (val, flags, false,
740027
                                       N_("invalid input flag"));
740027
       else if (operand_is (name, "oflag"))
740027
-        output_flags |= parse_symbols (val, flags,
740027
+        output_flags |= parse_symbols (val, flags, false,
740027
                                        N_("invalid output flag"));
740027
       else if (operand_is (name, "status"))
740027
-        status_flags |= parse_symbols (val, statuses,
740027
-                                       N_("invalid status flag"));
740027
+        status_level = parse_symbols (val, statuses, true,
740027
+                                      N_("invalid status level"));
740027
       else
740027
         {
740027
           bool invalid = false;
740027
@@ -1613,7 +1667,7 @@ skip_via_lseek (char const *filename, int fdesc, off_t offset, int whence)
740027
       && ioctl (fdesc, MTIOCGET, &s2) == 0
740027
       && MT_SAME_POSITION (s1, s2))
740027
     {
740027
-      if (!(status_flags & STATUS_NONE))
740027
+      if (status_level != STATUS_NONE)
740027
         error (0, 0, _("warning: working around lseek kernel bug for file "
740027
                        "(%s)\n  of mt_type=0x%0lx -- "
740027
                        "see <sys/mtio.h> for the list of types"),
740027
@@ -1787,7 +1841,7 @@ advance_input_after_read_error (size_t nbytes)
740027
           if (offset == input_offset)
740027
             return true;
740027
           diff = input_offset - offset;
740027
-          if (! (0 <= diff && diff <= nbytes) && !(status_flags & STATUS_NONE))
740027
+          if (! (0 <= diff && diff <= nbytes) && status_level != STATUS_NONE)
740027
             error (0, 0, _("warning: invalid file offset after failed read"));
740027
           if (0 <= skip_via_lseek (input_file, STDIN_FILENO, diff, SEEK_CUR))
740027
             return true;
740027
@@ -1986,7 +2040,7 @@ dd_copy (void)
740027
              2. pipe has not enough data
740027
              3. partial reads  */
740027
       if ((us_blocks || (!input_offset_overflow && us_bytes))
740027
-          && !(status_flags & STATUS_NONE))
740027
+          && status_level != STATUS_NONE)
740027
         {
740027
           error (0, 0,
740027
                  _("%s: cannot skip to specified offset"), quote (input_file));
740027
@@ -2029,6 +2083,19 @@ dd_copy (void)
740027
 
740027
   while (1)
740027
     {
740027
+      if (status_level == STATUS_PROGRESS)
740027
+        {
740027
+          xtime_t progress_time = gethrxtime ();
740027
+          uintmax_t delta_xtime = progress_time;
740027
+          delta_xtime -= previous_time;
740027
+          double XTIME_PRECISIONe0 = XTIME_PRECISION;
740027
+          if (delta_xtime / XTIME_PRECISIONe0 > 1)
740027
+            {
740027
+              print_xfer_stats (progress_time);
740027
+              previous_time = progress_time;
740027
+            }
740027
+        }
740027
+
740027
       if (r_partial + r_full >= max_records + !!max_bytes)
740027
         break;
740027
 
740027
@@ -2053,7 +2120,7 @@ dd_copy (void)
740027
 
740027
       if (nread < 0)
740027
         {
740027
-          if (!(conversions_mask & C_NOERROR) || !(status_flags & STATUS_NONE))
740027
+          if (!(conversions_mask & C_NOERROR) || status_level != STATUS_NONE)
740027
             error (0, errno, _("error reading %s"), quote (input_file));
740027
 
740027
           if (conversions_mask & C_NOERROR)
740027
@@ -2345,7 +2412,7 @@ main (int argc, char **argv)
740027
         }
740027
     }
740027
 
740027
-  start_time = gethrxtime ();
740027
+  start_time = previous_time = gethrxtime ();
740027
 
740027
   exit_status = dd_copy ();
740027
 
740027
diff --git a/tests/dd/misc.sh b/tests/dd/misc.sh
740027
index f877fdd..34dfba7 100755
740027
--- a/tests/dd/misc.sh
740027
+++ b/tests/dd/misc.sh
740027
@@ -35,9 +35,12 @@ dd status=none if=$tmp_in of=/dev/null 2> err || fail=1
740027
 test -s err && { cat err; fail=1; }
740027
 dd status=none if=$tmp_in skip=2 of=/dev/null 2> err || fail=1
740027
 test -s err && { cat err; fail=1; }
740027
-# check status=none is cumulative with status=noxfer
740027
-dd status=none status=noxfer if=$tmp_in of=/dev/null 2> err || fail=1
740027
+# check later status=none overrides earlier status=noxfer
740027
+dd status=noxfer status=none if=$tmp_in of=/dev/null 2> err || fail=1
740027
 test -s err && { cat err; fail=1; }
740027
+# check later status=noxfer overrides earlier status=none
740027
+dd status=none status=noxfer if=$tmp_in of=/dev/null 2> err || fail=1
740027
+compare /dev/null err && fail=1
740027
 
740027
 dd if=$tmp_in of=$tmp_out 2> /dev/null || fail=1
740027
 compare $tmp_in $tmp_out || fail=1
740027
diff --git a/tests/dd/stats.sh b/tests/dd/stats.sh
740027
new file mode 100755
740027
index 0000000..24b8c49 100755
740027
--- /dev/null
740027
+++ b/tests/dd/stats.sh
740027
@@ -0,0 +1,65 @@
740027
+#!/bin/sh
740027
+# Check stats output for SIG{INFO,USR1} and status=progress
740027
+
740027
+# Copyright (C) 2014 Free Software Foundation, Inc.
740027
+
740027
+# This program is free software: you can redistribute it and/or modify
740027
+# it under the terms of the GNU General Public License as published by
740027
+# the Free Software Foundation, either version 3 of the License, or
740027
+# (at your option) any later version.
740027
+
740027
+# This program is distributed in the hope that it will be useful,
740027
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
740027
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
740027
+# GNU General Public License for more details.
740027
+
740027
+# You should have received a copy of the GNU General Public License
740027
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
740027
+
740027
+. "${srcdir=.}/tests/init.sh"; path_prepend_ ./src
740027
+print_ver_ dd
740027
+
740027
+env kill -l | grep '^INFO$' && SIGINFO='INFO' || SIGINFO='USR1'
740027
+
740027
+# This to avoid races in the USR1 case
740027
+# as the dd process will terminate by default until
740027
+# it has its handler enabled.
740027
+trap '' $SIGINFO
740027
+
740027
+mkfifo_or_skip_ fifo
740027
+
740027
+for open in '' '1'; do
740027
+  # Run dd with the fullblock iflag to avoid short reads
740027
+  # which can be triggered by reception of signals
740027
+  dd iflag=fullblock if=/dev/zero of=fifo count=100 bs=5000000 2>err & pid=$!
740027
+
740027
+  # Note if we sleep here we give dd a chance to exec and block on open.
740027
+  # Otherwise we're probably testing SIG_IGN in the forked shell or early dd.
740027
+  test "$open" && sleep .1
740027
+
740027
+  # dd will block on open until fifo is opened for reading.
740027
+  # Timeout in case dd goes away erroneously which we check for below.
740027
+  timeout 10 sh -c 'wc -c < fifo > nwritten' &
740027
+
740027
+  # Send lots of signals immediately to ensure dd not killed due
740027
+  # to race setting handler, or blocking on open of fifo.
740027
+  # Many signals also check that short reads are handled.
740027
+  until ! kill -s $SIGINFO $pid 2>/dev/null; do
740027
+    sleep .01
740027
+  done
740027
+
740027
+  wait
740027
+
740027
+  # Ensure all data processed and at least last status written
740027
+  grep '500000000 bytes .* copied' err || { cat err; fail=1; }
740027
+done
740027
+
740027
+progress_output()
740027
+{
740027
+  { sleep "$1"; echo 1; } | dd bs=1 status=progress of=/dev/null 2>err
740027
+  # Progress output should be for "byte ... copied", while final is "bytes ..."
740027
+  grep 'byte .* copied' err
740027
+}
740027
+retry_delay_ progress_output 1 4 || { cat err; fail=1; }
740027
+
740027
+Exit $fail
740027
--
740027
cgit v0.9.0.2