Skip to content

Use stderr for terminal progress output, etc - #6474

Open
edquist wants to merge 10 commits into
rclone:masterfrom
edquist:stderr-terminal
Open

edquist wants to merge 10 commits into
rclone:masterfrom
edquist:stderr-terminal

Conversation

@edquist

@edquist edquist commented Sep 30, 2022

Copy link
Copy Markdown

What is the purpose of this change?

Avoid mixing rclone command output with progress output by sending terminal output to stderr.

Discussion:

The --progress option produces output designed for the terminal, and the terminal library sent all its output to stdout.

This is a problem for any command that produces output for further processing, when combined with --progress, because the main command output and the progress output are then sent together to stdout.

This is most obviously a problem for the rclone 'cat' command. Say you want to retrieve a large file but output to a pipe for further processing, rather than write it to a file. But you also want rclone to display its progress output as you wait for the transfer. Because both the 'cat' output and the progress output go to stdout, this leaves the progress output as garbage data within the streamed cat output, and also prevents the progress output from being displayed.

Notably, other rclone commands like 'ls', 'lsjson', and even 'm5dsum', produce meaningful progress output with the --progress option, but when mixed with the regular command output, it makes both the progress output and the command output unusable.

The simple solution here is to send output intended for the terminal (including progress output) to stderr instead of stdout. This way the rclone command output can be redirected as desired from stdout, and the progress output will still go to the terminal attached to stderr.

If for some reason the user wants to capture/redirect the terminal/progress output for some other purpose, stderr can be redirected instead.

Was the change discussed in an issue or in the forum before?

Hey look at that. Yes, seems someone else reported an issue for it also.

Fixes #3743.

Checklist

  • I have read the contribution guidelines.
  • I have added tests for all changes in this PR if appropriate.
  • I have added documentation for the changes if appropriate.
  • All commit messages are in house style.
  • I'm done, this Pull Request is ready for review :-)

@ncw

ncw commented Sep 30, 2022

Copy link
Copy Markdown
Member

Did you read through #3743 ? My favourite idea in that is to write to /dev/tty directly so you can then redirect stdout / stderr however you like.

The cross platform way of doing this would be to call ttyname

There is a library for this here: https://github.com/ericlagergren/go-gnulib/tree/master/ttyname - however that looks complicated and could be buggy.

So I think it would probably be easier and more compatible to shell out to the tty command to get the name of the tty, open that and use it as the file descriptor.

What do you think of that idea?

@edquist

edquist commented Sep 30, 2022 •

Copy link
Copy Markdown
Author

Hi @ncw, thanks for your response.

I read through #3743, along with the related forum discussion. (Though I admit I did not find these until writing up my PR, when I got to the "Was the change discussed in an issue or in the forum before?" part.)

What I see in both the forum discussion and the github issue is repeatedly people see sending progress output to stderr (as I have done in this PR) as a solution.

I understand that the (slight) pitfal of sending the "terminal" output to stderr instead of stdout is that you end up combining error messages with other "terminal" output. Though this is still better than combining it with the main command output, which breaks pipelines for any command whose output is used for further processing.

I understand your suggestion to come up with yet another stream concept, to have three categories - the main command output, error messages, and other terminal output. That would also solve the main bug, which is that progress output should not be mixed with the main command output to stdout. If someone had implemented that, I do not think I would feel the need to do it differently.

Though as you can see, that was suggested in the forum and in the issue back in June, and no one seems to have fancied implementing it. Indeed, the forum topic "was automatically closed 60 days after the last reply. New replies are no longer allowed."

So, already I would prefer a straightforward, working solution over a clever idea that no one seems to care to implement.

Do we know of any cases of people that actually rely on parsing stderr output and use the --progress option? Because if nobody is doing that then presumably nobody will have a problem with using stderr instead of /dev/tty.

You also mention ttyname(3) and tty(1) as being "cross-platform" and "compatible" ways to get the terminal device path, though I imagine that won't solve the problem for Windows users.

But even if we were to limit the discussion to Linux, I think I still prefer to send the terminal/progress output to stderr explicitly, because this allows for some other interesting games like redirecting stderr to a different terminal window.

This occasionally comes up for me when monitoring long running shell pipelines, where each step in the pipeline sends its main output to stdout and its verbose informational/terminal/progress output to stderr. Rather than have all the programs in the pipeline fight over displaying supplemental/progress info on the same terminal, you can redirect each one's stderr to a separate terminal window. (It might sound exotic, but it's really rather nice once you set it up.)

Anyway, you'd lose the ability to do things like that if you force progress output to go to the controlling tty / whatever ttyname(3) / tty(1) report.

...

I guess if you were really gung-ho about it you could make it an option -- something like --terminal=DEVICE (with the default being either /dev/tty or whatever ttyname(3) or tty(1) return -- or stderr on Windows), and all of the lib/terminal output (including progress output) would get sent there. Then you could make everybody happy.

But that is certainly beyond my itch to scratch here.

I hope this simple, straightforward fix for the currently broken situation (which it looks like a number of others have requested also) is at least a step in the right direction! :)

Thanks for your consideration!

Avoid mixing rclone command output with progress output by sending
terminal output to stderr.

Discussion:

The --progress option produces output designed for the terminal, and the
terminal library sent all its output to stdout.

This is a problem for any command that produces output for further
processing, when combined with --progress, because the main command
output and the progress output are then sent together to stdout.

This is most obviously a problem for the rclone 'cat' command.  Say you
want to retrieve a large file but output to a pipe for further
processing, rather than write it to a file.  But you also want rclone to
display its progress output as you wait for the transfer.  Because both
the 'cat' output and the progress output go to stdout, this leaves the
progress output as garbage data within the streamed cat output, and also
prevents the progress output from being displayed.

Notably, other rclone commands like 'ls', 'lsjson', and even 'm5dsum',
produce meaningful progress output with the --progress option, but when
mixed with the regular command output, it makes both the progress output
and the command output unusable.

The simple solution here is to send output intended for the terminal
(including progress output) to stderr instead of stdout.  This way the
rclone command output can be redirected as desired from stdout, and the
progress output will still go to the terminal attached to stderr.

If for some reason the user wants to capture/redirect the
terminal/progress output for some other purpose, stderr can be
redirected instead.
@ncw

ncw commented Oct 1, 2022

Copy link
Copy Markdown
Member

I think there main problem with just using stderr is that currently -P and --log-file together work. You see progress in the terminal but logs go to the file.

If we send -P output to stderr then it will go to the log file

This might only be a problem on Windows.

Can you confirm that this patch does/doesn't send the -P output to the --log-file on Linux and Windows?

@edquist

edquist commented Oct 4, 2022

Copy link
Copy Markdown
Author

That makes sense. I can try out the changes with -P/--progress and --log-file together on Linux; I don't have a dev setup for Windows. I can look into that if need be.

Here are my initial thoughts looking things over.

The key bit about the --log-file option is it causes redirectStderr(f) to be called from InitLogging -

https://github.com/rclone/rclone/blob/v1.59.2/fs/log/logflags/logflags.go#L15
https://github.com/rclone/rclone/blob/v1.59.2/fs/log/log.go#L130

My read of the unix case is that the fd for the log file will be dup2'd to fd 2, causing all further writes to stderr to go to that file. As far as I can tell that would include the --progress output, if that output simply goes to stderr instead of stdout. However I also see in the unix handling of redirectStderr() that there is already the idea of dup'ing a copy of the original stderr for the password prompt output before redirecting the log-file output:

https://github.com/rclone/rclone/blob/v1.59.2/fs/log/redirect_stderr_unix.go#L18

So, perhaps we could use that config.PasswordPromptOutput for the progress output also. (If you like we could even rename this config variable to something like TerminalOutput to make it more general.)

As for the windows case, I don't see anything going on in redirectStderr() to save (dup) the original stderr. I don't know what the equivalent windows kernel32 call to accomplish that would look like, or if it's possible. If this is not trivial to do, and you would prefer to preserve the existing windows behavior for --progress with --log-file, I guess my thought is that in the lib/terminal setup, for windows we could just set the terminal Out to os.Stdout explicitly here, which would match the existing behavior. And then perhaps if a windows user comes along who is sufficiently interested and able, they could implement something as appropriate for the windows case.

What do you think? I've updated the PR with my suggestions.

PasswordPromptOutput is a dup'ed copy of the stderr that the program
started with - in particular, before any redirection for --log-file
was applied.
--progress and --log-file should be usable together, but windows
does not currently preserve the original stderr in
config.PasswordPromptOutput; so use stdout explicitly to match the
old behavior.
First, move this variable in order to avoid circular imports between
config and terminal.  (config already depends on terminal.)

But also, it seems PasswordPromptOutput conceptually fits well in
terminal, as the idea is for it to store the output for the terminal.
Give it a more general name as it gets used for other terminal things
like progress output
The terminal title output should go to the same place as the rest of the
terminal output.  It's important _not_ to send it to stdout, where it
would get included with the main program output when redirected to a
file - for instance with the rclone cat command.
fmt.Println writes to stdout, which may be redirected and wrongly
included with the main program output (like the cat command)
instead of written to the terminal output.

Note the rest of the progress output goes to terminal.Out in
printProgress via terminal.Write()
@edquist

edquist commented Oct 6, 2022 •

Copy link
Copy Markdown
Author

Hi @ncw, I've updated the PR to fix a few gotchas, and now I've verified --progress/-P and --log-file work properly together on Linux, including when redirecting stdout to a file (like with rclone cat). I designed my changes so that Windows should continue to behave as it used to (--progress and --log-file still work together, but --progress is still unusable when redirecting stdout), but I don't have a dev setup handy to build and test on Windows. I could use help verifying this if that's easy for you.

As mentioned in my previous comment, I'm taking advantage of the existing PasswordPromptOutput for terminal/progress output now, rather than writing to stderr directly. PasswordPromptOutput was apparently designed specifically for user interaction on a terminal, and is a dup'ed copy of the program's original stderr, which does not get redirected when --log-file is specified.

The gotchas in particular were:

  • I moved the PasswordPromptOutput var from config to terminal, to avoid circular imports between config and terminal.
    In particular: config already imports terminal, so it does not work to refer back to config.PasswordPromptOutput from terminal. But also PasswordPromptOutput seems to make sense in terminal as the concept is for it to refer to the user-facing device (ie the terminal), and we will be using it for other terminal-intended output.
  • Relatedly, I've renamed PasswordPromptOutput to be more general, now calling it TerminalOutput.
  • WriteTerminalTitle previously wrote specifically to stdout (using fmt.Printf), but now it writes to TerminalOutput.
    This is necessary for correctness if redirecting the main program output.
  • startProgress previously wrote its final newline to stdout specifically (using fmt.Println), but now it writes to terminal.Out, which is where the rest of the progress output goes (the color-wrapped version of TerminalOutput).
    This also is necessary for correctness if redirecting the main program output. For instance rclone cat remote:file --progress > file would result in an extra newline being written to the file, and missing on the terminal.
  • As mentioned above, for the Windows case, I'm preserving the old behavior by setting the terminal Out to os.Stdout.
    This will also preserve the broken behavior on Windows for --progress when redirecting stdout, so not to interfere with currently working uses of --progress with --log-file.
    Notably, the tricky bit here to get everything else to work in the Windows case is that the password prompts use TerminalOutput (the original os.Stderr or a dup'd copy) while the rest of the progress output goes through terminal.Out, which on Windows is just os.Stdout.

...

Future directions:

From here there would also be room in the future to add a --terminal=DEVICE option (with e.g., /dev/tty as a default if it exists, otherwise stderr) to be used for TerminalOutput. As I mentioned before, there is a small use case for sending progress output somewhere other than the controlling terminal for the process, which can be done by redirecting stderr or providing an option.

Also the SyncPrintf from operations here probably only needs to be called if (1) --progress is enabled and (2) stdout and the terminal output refer to the same device. Now that it is possible to enable --progress and redirect the main program output, the extra locking around the writes seem to be superfluous (though not harmful) if they are not going to the same place.

I think those can be left for separate PRs though.

...

Let me know if you have any thoughts about this current approach!

@ncw

ncw commented Oct 6, 2022

Copy link
Copy Markdown
Member

I had a play with this.

On linux, this indicates that some things are still writing to stderr I think.

$ rclone about -Pvv ~/go/src/github.com/rclone/rclone --log-file /tmp/z >/dev/null
Transferred:              0 B / 0 B, -, 0 B/s, ETA -
Elapsed time:         0.0s

This does work under Windows just fine and that is because we use the windows console API to write to the console when -P is in effect (effectively writing to the windows equivalent of /dev/tty).

Windows is complicated though because it can run under cygwin which works more like a unix terminal with TERM set - that is this case here:

		} else if runtime.GOOS == "windows" && os.Getenv("TERM") != "" {
			// If TERM is set just use stdout
			Out = os.Stdout

So, perhaps we could use that config.PasswordPromptOutput for the progress output also. (If you like we could even rename this config variable to something like TerminalOutput to make it more general.)

There is already an exported variable called Out from terminal and I think making another called TerminalOutput is confusing!

In general things that want to write to the terminal should use terminal.Out and I think that includes the password prompt stuff in fs/config/ui.go (otherwise under Windows+Cygwin + --log-file the prompts will go to the log file`).

Maybe we should rename TerminalOutput to RawOut and make sure the only reference externally to that is in fs/log/redirect_stderr_unix.go where it gets overridden.

I think we are getting there with this - well done :-) I have a horrible suspicion that we might need to make the actual output destination of -P configurable otherwise people are going to complain that we broke their workflows, but that is a relatively easy thing to do later if needed.

Can you do another iteration with the above suggestions, then we can get our resident Windows guru to take a look too.

Thank you

We're going to try to avoid TerminalOut except for redirectStderr,
which overrides that var with a duped copy of stderr.
it was confusing to have a terminal.Out along with a TerminalOutput
as this duped copy now gets used for progress output, too.
@edquist

edquist commented Oct 6, 2022 •

Copy link
Copy Markdown
Author

On linux, this indicates that some things are still writing to stderr I think.

Yeah with --log-file and redirecting stdout, the progress output displayed there is going to the dup'ed copy of the original stderr. The stderr for the process (fd 2) gets redirected to the log file, but the copy (perhaps fd 3) stays open to the terminal, and that's where the progress output is getting sent.

This does work under Windows just fine and that is because we use the windows console API to write to the console when -P is in effect (effectively writing to the windows equivalent of /dev/tty).

That's encouraging to hear. Most of the complication comes from trying to make this all work for both Windows and Linux/unix at the same time. (More on that in a bit.)

Windows is complicated though because it can run under cygwin which works more like a unix terminal with TERM set

Ah, I see! I had misread that os.Getenv("TERM") != "" as having an ==.

Well then, I wonder if we can treat the cygwin case like the other unix cases? I mean removing the else if block you mentioned entirely. Do you have any insight into why the cygwin case for a terminal would write directly to stdout rather than going through the colorable wrapper?

There is already an exported variable called Out from terminal and I think making another called TerminalOutput is confusing!

Yes I agree! :) Sorry about that. At first I wanted (and tried) to use just Out, getting rid of what is now TerminalOutput, but I got thwarted by a couple things that didn't quite seem to work -- including concerns about the handling of the Windows case (which I did not realize was specific to cygwin).

In general things that want to write to the terminal should use terminal.Out and I think that includes the password prompt stuff in fs/config/ui.go (otherwise under Windows+Cygwin + --log-file the prompts will go to the log file`).

Alright I can make that change. One question this raises for me is, does the Windows+Cygwin case use the redirectStderr from redirect_stderr_windows.go, or from redirect_stderr_unix.go? And if redirect_stderr_windows.go, would it work (and make sense) to use redirect_stderr_unix.go instead?

The problem I'm potentially seeing is: if the Windows+Cygwin case uses redirect_stderr_windows.go, then TerminalOutput/RawOut will stay at os.Stderr (which can get redirected to the log file), rather than get the dup'ed copy of stderr. Meanwhile terminal.Out for Windows+Cygwin is os.Stdout, which might get redirected to a file. And so either way you could get the password prompt redirected somewhere. On the other hand, if redirect_stderr_unix.go gets used for Windows+Cygwin, then TerminalOutput/RawOut gets the dup'ed copy of stderr, which doesn't go to the log file. So for instance you could then send the password prompt to RawOut without it going to the log file, while sending it to terminal.Out can be redirected if its set explicitly to os.Stdout (or os.Stderr).

Almost makes me want to get a Windows+Cygwin setup going to find out.

Maybe we should rename TerminalOutput to RawOut and make sure the only reference externally to that is in fs/log/redirect_stderr_unix.go where it gets overridden.

Sure, that's a better name. And I think you're right - we need to keep this around to refer to the dup'ed copy of stderr for the log-file redirection. If not for that maybe we could have gotten rid of this TerminalOutput/RawOut var entirely.

I have a horrible suspicion that we might need to make the actual output destination of -P configurable otherwise people are going to complain that we broke their workflows, but that is a relatively easy thing to do later if needed.

Could be. Yeah at first I did not have a whole lot of motivation to make any fancy changes for this PR, because it seemed we could just swap out os.Stdout with os.Stderr. But yeah it's turned out to take a bit more to fix things properly, which provides some extra motivation in itself.

Can you do another iteration with the above suggestions, then we can get our resident Windows guru to take a look too.

Sure thing, updated.

Again the main question I'd like to draw attention to is how to handle this part:

		} else if runtime.GOOS == "windows" && os.Getenv("TERM") != "" {
			// If TERM is set just use stdout
			Out = os.Stdout

Do we:

  1. keep this as-is,
  2. set Out = os.Stderr instead,
  3. set Out = RawOut instead, or
  4. drop this whole else-if block

?

If the Windows+Cygwin case can do the unix-style redirect (with the dup'ed copy of stderr), then I imagine we can do 4. Otherwise I think the password prompt won't work in 2 & 3 with --log-file, nor in 1 when redirecting stdout to a file.

@ncw ncw modified the milestones: v1.61, v1.62 Dec 5, 2022
@ncw

ncw commented Dec 5, 2022

Copy link
Copy Markdown
Member

Sorry for the delay in responding

On linux, this indicates that some things are still writing to stderr I think.

Yeah with --log-file and redirecting stdout, the progress output displayed there is going to the dup'ed copy of the original stderr. The stderr for the process (fd 2) gets redirected to the log file, but the copy (perhaps fd 3) stays open to the terminal, and that's where the progress output is getting sent.

This does work under Windows just fine and that is because we use the windows console API to write to the console when -P is in effect (effectively writing to the windows equivalent of /dev/tty).

That's encouraging to hear. Most of the complication comes from trying to make this all work for both Windows and Linux/unix at the same time. (More on that in a bit.)

Windows is complicated though because it can run under cygwin which works more like a unix terminal with TERM set

Ah, I see! I had misread that os.Getenv("TERM") != "" as having an ==.

Well then, I wonder if we can treat the cygwin case like the other unix cases? I mean removing the else if block you mentioned entirely. Do you have any insight into why the cygwin case for a terminal would write directly to stdout rather than going through the colorable wrapper?

Isn't that because its going to a windows console which implements the colouring itself?

There is already an exported variable called Out from terminal and I think making another called TerminalOutput is confusing!

Yes I agree! :) Sorry about that. At first I wanted (and tried) to use just Out, getting rid of what is now TerminalOutput, but I got thwarted by a couple things that didn't quite seem to work -- including concerns about the handling of the Windows case (which I did not realize was specific to cygwin).

In general things that want to write to the terminal should use terminal.Out and I think that includes the password prompt stuff in fs/config/ui.go (otherwise under Windows+Cygwin + --log-file the prompts will go to the log file`).

Alright I can make that change. One question this raises for me is, does the Windows+Cygwin case use the redirectStderr from redirect_stderr_windows.go, or from redirect_stderr_unix.go? And if redirect_stderr_windows.go, would it work (and make sense) to use redirect_stderr_unix.go instead?

It will use the windows version, and no I don't think the stderr unix version would work unless compiled against cygwin which I don't want to do.

The problem I'm potentially seeing is: if the Windows+Cygwin case uses redirect_stderr_windows.go, then TerminalOutput/RawOut will stay at os.Stderr (which can get redirected to the log file), rather than get the dup'ed copy of stderr. Meanwhile terminal.Out for Windows+Cygwin is os.Stdout, which might get redirected to a file. And so either way you could get the password prompt redirected somewhere. On the other hand, if redirect_stderr_unix.go gets used for Windows+Cygwin, then TerminalOutput/RawOut gets the dup'ed copy of stderr, which doesn't go to the log file. So for instance you could then send the password prompt to RawOut without it going to the log file, while sending it to terminal.Out can be redirected if its set explicitly to os.Stdout (or os.Stderr).

Almost makes me want to get a Windows+Cygwin setup going to find out.

Maybe we should rename TerminalOutput to RawOut and make sure the only reference externally to that is in fs/log/redirect_stderr_unix.go where it gets overridden.

Sure, that's a better name. And I think you're right - we need to keep this around to refer to the dup'ed copy of stderr for the log-file redirection. If not for that maybe we could have gotten rid of this TerminalOutput/RawOut var entirely.

I have a horrible suspicion that we might need to make the actual output destination of -P configurable otherwise people are going to complain that we broke their workflows, but that is a relatively easy thing to do later if needed.

Could be. Yeah at first I did not have a whole lot of motivation to make any fancy changes for this PR, because it seemed we could just swap out os.Stdout with os.Stderr. But yeah it's turned out to take a bit more to fix things properly, which provides some extra motivation in itself.

Can you do another iteration with the above suggestions, then we can get our resident Windows guru to take a look too.

Sure thing, updated.

Again the main question I'd like to draw attention to is how to handle this part:

		} else if runtime.GOOS == "windows" && os.Getenv("TERM") != "" {
			// If TERM is set just use stdout
			Out = os.Stdout

Do we:

  1. keep this as-is,
  2. set Out = os.Stderr instead,
  3. set Out = RawOut instead, or
  4. drop this whole else-if block

Probably 2 or 3 but I think it is going to need some experimentation with rclone on cygwin to work it out!

If the Windows+Cygwin case can do the unix-style redirect (with the dup'ed copy of stderr), then I imagine we can do 4. Otherwise I think the password prompt won't work in 2 & 3 with --log-file, nor in 1 when redirecting stdout to a file.

I don't think unix style redirect is possible alas unless we link with cygwin libc which is a whole can of worms.

TBH cygwin is getting more irrelevant with the advent of WSL - I can't see why you'd use it instead of WSL now-a-days.

I marked this Pull as a target for 1.61 - do you think that is feasible?

@ncw ncw modified the milestones: v1.62, v1.61 Dec 6, 2022
@edquist

edquist commented Dec 13, 2022 •

Copy link
Copy Markdown
Author

Thanks @ncw for the feedback; sorry it's been a while and I've lost track of what the remaining issues were. I'll have to review.

I marked this Pull as a target for 1.61 - do you think that is feasible?

What is the timeline for this release? Ah I see now, Dec 20. Sure, I'll try to work through the remaining items this week!

@ncw ncw removed this from the v1.61 milestone Feb 20, 2023
@ncw ncw added this to the v1.62 milestone Feb 20, 2023
@ncw

ncw commented Mar 24, 2023

Copy link
Copy Markdown
Member

Ha! We've missed 1.62 but I'd like to line this up for 1.63. Now is a good time to merge things which might be controversial like this patch.

Have you got time to finish it @edquist ?

@ncw ncw modified the milestones: v1.62, v1.63 May 9, 2023
@ncw ncw modified the milestones: v1.63, v1.64 Jul 1, 2023
@ncw ncw modified the milestones: v1.64, v1.65 Sep 11, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

"rclone cat" doesn't work with "--progress"

2 participants