progressmeter.c revision 1.5.4.1
1/*	$NetBSD: progressmeter.c,v 1.5.4.1 2015/04/30 06:07:30 riz Exp $	*/
2/* $OpenBSD: progressmeter.c,v 1.41 2015/01/14 13:54:13 djm Exp $ */
3/*
4 * Copyright (c) 2003 Nils Nordman.  All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 *    notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26
27#include "includes.h"
28__RCSID("$NetBSD: progressmeter.c,v 1.5.4.1 2015/04/30 06:07:30 riz Exp $");
29#include <sys/types.h>
30#include <sys/ioctl.h>
31#include <sys/uio.h>
32
33#include <errno.h>
34#include <signal.h>
35#include <stdio.h>
36#include <string.h>
37#include <time.h>
38#include <unistd.h>
39
40#include "progressmeter.h"
41#include "atomicio.h"
42#include "misc.h"
43
44#define DEFAULT_WINSIZE 80
45#define MAX_WINSIZE 512
46#define PADDING 1		/* padding between the progress indicators */
47#define UPDATE_INTERVAL 1	/* update the progress meter every second */
48#define STALL_TIME 5		/* we're stalled after this many seconds */
49
50/* determines whether we can output to the terminal */
51static int can_output(void);
52
53/* formats and inserts the specified size into the given buffer */
54static void format_size(char *, int, off_t);
55static void format_rate(char *, int, off_t);
56
57/* window resizing */
58static void sig_winch(int);
59static void setscreensize(void);
60
61/* updates the progressmeter to reflect the current state of the transfer */
62void refresh_progress_meter(void);
63
64/* signal handler for updating the progress meter */
65static void update_progress_meter(int);
66
67static time_t start;		/* start progress */
68static time_t last_update;	/* last progress update */
69static const char *file;	/* name of the file being transferred */
70static off_t start_pos;		/* initial position of transfer */
71static off_t end_pos;		/* ending position of transfer */
72static off_t cur_pos;		/* transfer position as of last refresh */
73static off_t last_pos;
74static off_t max_delta_pos = 0;
75static volatile off_t *counter;	/* progress counter */
76static long stalled;		/* how long we have been stalled */
77static int bytes_per_second;	/* current speed in bytes per second */
78static int win_size;		/* terminal window size */
79static volatile sig_atomic_t win_resized; /* for window resizing */
80
81/* units for format_size */
82static const char unit[] = " KMGT";
83
84static int
85can_output(void)
86{
87	return (getpgrp() == tcgetpgrp(STDOUT_FILENO));
88}
89
90static void
91format_rate(char *buf, int size, off_t bytes)
92{
93	int i;
94
95	bytes *= 100;
96	for (i = 0; bytes >= 100*1000 && unit[i] != 'T'; i++)
97		bytes = (bytes + 512) / 1024;
98	if (i == 0) {
99		i++;
100		bytes = (bytes + 512) / 1024;
101	}
102	snprintf(buf, size, "%3lld.%1lld%c%s",
103	    (long long) (bytes + 5) / 100,
104	    (long long) (bytes + 5) / 10 % 10,
105	    unit[i],
106	    i ? "B" : " ");
107}
108
109static void
110format_size(char *buf, int size, off_t bytes)
111{
112	int i;
113
114	for (i = 0; bytes >= 10000 && unit[i] != 'T'; i++)
115		bytes = (bytes + 512) / 1024;
116	snprintf(buf, size, "%4lld%c%s",
117	    (long long) bytes,
118	    unit[i],
119	    i ? "B" : " ");
120}
121
122void
123refresh_progress_meter(void)
124{
125	char buf[MAX_WINSIZE + 1];
126	time_t now;
127	off_t transferred;
128	double elapsed;
129	int percent;
130	off_t bytes_left;
131	int cur_speed;
132	int hours, minutes, seconds;
133	int i, len;
134	int file_len;
135	off_t delta_pos;
136
137	transferred = *counter - (cur_pos ? cur_pos : start_pos);
138	cur_pos = *counter;
139	now = monotime();
140	bytes_left = end_pos - cur_pos;
141
142	delta_pos = cur_pos - last_pos;
143	if (delta_pos > max_delta_pos)
144		max_delta_pos = delta_pos;
145
146	if (bytes_left > 0)
147		elapsed = now - last_update;
148	else {
149		elapsed = now - start;
150		/* Calculate true total speed when done */
151		transferred = end_pos - start_pos;
152		bytes_per_second = 0;
153	}
154
155	/* calculate speed */
156	if (elapsed != 0)
157		cur_speed = (transferred / elapsed);
158	else
159		cur_speed = transferred;
160
161#define AGE_FACTOR 0.9
162	if (bytes_per_second != 0) {
163		bytes_per_second = (bytes_per_second * AGE_FACTOR) +
164		    (cur_speed * (1.0 - AGE_FACTOR));
165	} else
166		bytes_per_second = cur_speed;
167
168	/* filename */
169	buf[0] = '\0';
170	file_len = win_size - 45;
171	if (file_len > 0) {
172		len = snprintf(buf, file_len + 1, "\r%s", file);
173		if (len < 0)
174			len = 0;
175		if (len >= file_len + 1)
176			len = file_len;
177		for (i = len; i < file_len; i++)
178			buf[i] = ' ';
179		buf[file_len] = '\0';
180	}
181
182	/* percent of transfer done */
183	if (end_pos != 0)
184		percent = ((float)cur_pos / end_pos) * 100;
185	else
186		percent = 100;
187	snprintf(buf + strlen(buf), win_size - strlen(buf) - 8,
188	    " %3d%% ", percent);
189
190	/* amount transferred */
191	format_size(buf + strlen(buf), win_size - strlen(buf),
192	    cur_pos);
193	strlcat(buf, " ", win_size);
194
195	/* bandwidth usage */
196	format_rate(buf + strlen(buf), win_size - strlen(buf),
197	    (off_t)bytes_per_second);
198	strlcat(buf, "/s ", win_size);
199
200	/* instantaneous rate */
201	if (bytes_left > 0)
202		format_rate(buf + strlen(buf), win_size - strlen(buf),
203			    delta_pos);
204	else
205		format_rate(buf + strlen(buf), win_size - strlen(buf),
206			    max_delta_pos);
207	strlcat(buf, "/s ", win_size);
208
209	/* ETA */
210	if (!transferred)
211		stalled += elapsed;
212	else
213		stalled = 0;
214
215	if (stalled >= STALL_TIME)
216		strlcat(buf, "- stalled -", win_size);
217	else if (bytes_per_second == 0 && bytes_left)
218		strlcat(buf, "  --:-- ETA", win_size);
219	else {
220		if (bytes_left > 0)
221			seconds = bytes_left / bytes_per_second;
222		else
223			seconds = elapsed;
224
225		hours = seconds / 3600;
226		seconds -= hours * 3600;
227		minutes = seconds / 60;
228		seconds -= minutes * 60;
229
230		if (hours != 0)
231			snprintf(buf + strlen(buf), win_size - strlen(buf),
232			    "%d:%02d:%02d", hours, minutes, seconds);
233		else
234			snprintf(buf + strlen(buf), win_size - strlen(buf),
235			    "  %02d:%02d", minutes, seconds);
236
237		if (bytes_left > 0)
238			strlcat(buf, " ETA", win_size);
239		else
240			strlcat(buf, "    ", win_size);
241	}
242
243	atomicio(vwrite, STDOUT_FILENO, buf, win_size - 1);
244	last_update = now;
245	last_pos = cur_pos;
246}
247
248/*ARGSUSED*/
249static void
250update_progress_meter(int ignore)
251{
252	int save_errno;
253
254	save_errno = errno;
255
256	if (win_resized) {
257		setscreensize();
258		win_resized = 0;
259	}
260	if (can_output())
261		refresh_progress_meter();
262
263	signal(SIGALRM, update_progress_meter);
264	alarm(UPDATE_INTERVAL);
265	errno = save_errno;
266}
267
268void
269start_progress_meter(const char *f, off_t filesize, off_t *ctr)
270{
271	start = last_update = monotime();
272	file = f;
273	start_pos = *ctr;
274	end_pos = filesize;
275	cur_pos = 0;
276	counter = ctr;
277	stalled = 0;
278	bytes_per_second = 0;
279
280	setscreensize();
281	if (can_output())
282		refresh_progress_meter();
283
284	signal(SIGALRM, update_progress_meter);
285	signal(SIGWINCH, sig_winch);
286	alarm(UPDATE_INTERVAL);
287}
288
289void
290stop_progress_meter(void)
291{
292	alarm(0);
293
294	if (!can_output())
295		return;
296
297	/* Ensure we complete the progress */
298	if (cur_pos != end_pos)
299		refresh_progress_meter();
300
301	atomicio(vwrite, STDOUT_FILENO, __UNCONST("\n"), 1);
302}
303
304/*ARGSUSED*/
305static void
306sig_winch(int sig)
307{
308	win_resized = 1;
309}
310
311static void
312setscreensize(void)
313{
314	struct winsize winsize;
315
316	if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &winsize) != -1 &&
317	    winsize.ws_col != 0) {
318		if (winsize.ws_col > MAX_WINSIZE)
319			win_size = MAX_WINSIZE;
320		else
321			win_size = winsize.ws_col;
322	} else
323		win_size = DEFAULT_WINSIZE;
324	win_size += 1;					/* trailing \0 */
325}
326