Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Importing pterm causes program to not exit on SIGINT and SIGTERM #562

Closed
adombeck opened this issue Aug 26, 2023 · 7 comments · Fixed by #570
Closed

Importing pterm causes program to not exit on SIGINT and SIGTERM #562

adombeck opened this issue Aug 26, 2023 · 7 comments · Fixed by #570
Labels
bug Something isn't working

Comments

@adombeck
Copy link
Contributor

The signal handlers for os.Interrupt and syscall.SIGTERM registered in the init function prevent Go's default behavior when receiving such a signal (exiting with an exit code which depends on the OS and/or signal):

pterm/pterm.go

Lines 31 to 43 in e376aa8

func init() {
color.ForceColor()
// Make the cursor visible when the program stops
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
signal.Notify(c, syscall.SIGTERM)
go func() {
for range c {
cursor.Show()
}
}()
}

In effect, any program which merely imports pterm does not exit when handling a SIGINT (e.g. by pressing Ctrl+C) or a SIGTERM (e.g. by calling kill $PID).

@adombeck adombeck added the bug Something isn't working label Aug 26, 2023
@adombeck
Copy link
Contributor Author

adombeck commented Aug 26, 2023

This could be fixed by re-raising the signal in the init function after handling it:

diff --git a/pterm.go b/pterm.go
index 09557157..82397ed0 100644
--- a/pterm.go
+++ b/pterm.go
@@ -7,11 +7,13 @@
 package pterm
 
 import (
	"atomicgo.dev/cursor"
	"github.com/gookit/color"
+	"fmt"
 	"os"
 	"os/signal"
 	"syscall"
 )
 
 var (
@@ -36,8 +38,21 @@ func init() {
 	signal.Notify(c, os.Interrupt)
 	signal.Notify(c, syscall.SIGTERM)
 	go func() {
-               for range c {
+               for s := range c {
                        cursor.Show()
+
+                       // Re-raise the signal to trigger the default behavior
+                       signal.Stop(c)
+                       p, err := os.FindProcess(os.Getpid())
+                       if err != nil {
+                               _, _ = fmt.Fprintf(os.Stderr, "pterm: Failed to re-raise %s: %v\n", s, err)
+                               continue
+                       }
+                       err = p.Signal(s)
+                       if err != nil {
+                               _, _ = fmt.Fprintf(os.Stderr, "pterm: Failed to re-raise %s: %v\n", s, err)
+                               continue
+                       }
                }
        }()
 }

 }

However, this could lead to other unexpected behavior: Any other handlers registered by the program via signal.Notify would receive the same signal twice, because the Go runtime sends each signal to all handlers registered for that signal.

The only clean solution I see is to not register any signal handler in pterm and instead provide methods which the consumer can call themself to ensure that the cursor is restored. The ProgressbarPrinter already provides a Stop() method which can be used for that, for example like this:

func DownloadWithProgressbar() {
	p := pterm.DefaultProgressbar.WithTotal(len(fakeInstallList)).WithTitle("Downloading stuff")

	// Ensure that the progressbar printer is stopped when receiving a
	// terminating signal
	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
	go func() {
		<-sigs
		p.Stop()
		os.Exit(1)
	}()
	defer signal.Stop(sigs)

	p.Start()

	for i := 0; i < p.Total; i++ {
		if i == 6 {
			time.Sleep(time.Second * 3) // Simulate a slow download.
		}
		p.UpdateTitle("Downloading " + fakeInstallList[i])         // Update the title of the progressbar.
		pterm.Success.Println("Downloading " + fakeInstallList[i]) // If a progressbar is running, each print will be printed above the progressbar.
		p.Increment()                                              // Increment the progressbar by one. Use Add(x int) to increment by a custom amount.
		time.Sleep(time.Millisecond * 350)                         // Sleep 350 milliseconds.
	}
}

The other cases where cursor.Hide is currently called in pterm are InteractiveSelectPrinter.Show and InteractiveMultiselectPrinter.Show. Those do not yet provide methods to clean up the terminal.

adombeck added a commit to adombeck/pterm that referenced this issue Aug 28, 2023
The signal handlers registered in the init function prevent Go's default
behavior (exiting with an exit code which depends on the OS and/or signal)
when receiving such a signal.

This commit re-raises the signal after handling it, triggering the
default behavior unless the consumer registered it's own handlers.

Note that this could lead to other unexpected behavior: Any other handlers
registered by the consumer via signal.Notify receive the same signal
twice, because the Go runtime sends each signal to all handlers registered
for that signal.
adombeck added a commit to adombeck/pterm that referenced this issue Aug 28, 2023
The signal handlers registered in the init function prevent Go's default
behavior (exiting with an exit code which depends on the OS and/or signal)
when receiving such a signal.

This commit re-raises the signal after handling it, triggering the
default behavior unless the consumer registered it's own handlers.

Note that this could lead to other unexpected behavior: Any other handlers
registered by the consumer via signal.Notify receive the same signal
twice, because the Go runtime sends each signal to all handlers registered
for that signal.
adombeck added a commit to adombeck/pterm that referenced this issue Aug 28, 2023
The signal handlers registered in the init function prevent Go's default
behavior (exiting with an exit code which depends on the OS and/or signal)
when receiving such a signal.

This commit re-raises the signal after handling it, triggering the
default behavior unless the consumer registered it's own handlers.

Note that this could lead to other unexpected behavior: Any other handlers
registered by the consumer via signal.Notify receive the same signal
twice, because the Go runtime sends each signal to all handlers registered
for that signal.
@MarvinJWendt
Copy link
Member

MarvinJWendt commented Aug 29, 2023

Hi @adombeck, I think this was closed by accident (as a side-effect of closing another issue, that referenced this one). If the issue still persists, you can re-open this one :)

@adombeck
Copy link
Contributor Author

Thanks, this was indeed closed by accident.

@adombeck adombeck reopened this Aug 30, 2023
@MarvinJWendt
Copy link
Member

MarvinJWendt commented Sep 2, 2023

Hi, I will definitely look into this.

The only clean solution I see is to not register any signal handler in pterm and instead provide methods which the consumer can call themself to ensure that the cursor is restored. The ProgressbarPrinter already provides a Stop() method which can be used for that, for example like this:

The problem with this is that if a user kills the process in the middle of a progressbar (or similar printer), then the Stop() method is not executed. This causes the cursor to remain hidden until the terminal is restarted.

Your example shows, how a user would have to implement the signal handling by himself, but I think this is not in favor of PTerms simplicity philosophy. Every PTerm printer should be usable without any extra setup.

@adombeck
Copy link
Contributor Author

adombeck commented Sep 3, 2023

How about registering the signal handler in ProgressbarPrinter.Start (and InteractiveSelectPrinter.Show / InteractiveMultiselectPrinter.Show) instead of init and making that optional via ProgressbarPrinter.WithoutSignalHandling or something like that.

@MarvinJWendt MarvinJWendt linked a pull request Sep 15, 2023 that will close this issue
@MarvinJWendt
Copy link
Member

MarvinJWendt commented Sep 15, 2023

I removed the whole signal handling in #570. I think PTerm should not mess with signal handling. While this could cause that the cursor disappears, when crtl+c is pressed while the cursor is hidden, I still think it's the better option. There would be no optimal solution, if we handle signals inside PTerm. There would always be an edge-case, where a user wants to handle the signal by himself.

Appending to that, many terminals unhide the cursor, as soon as the user starts typing.

Thanks for pointing it out, and sorry for the long wait.

@MarvinJWendt
Copy link
Member

Released in v0.12.68

adamwg added a commit to upbound/up that referenced this issue May 13, 2024
In older versions, the pterm library we use for pretty-printing intercepted
SIGINT and SIGTERM. This signal handling was set up in the pacakge's `init`
function, so any code that ran before we set up our own signal handler couldn't
be killed with Ctrl-C.

The signal handling was removed from pterm in a more recent version (see
[1]). Updating to the latest fixes the issue where we couldn't kill `up login`
with Ctrl-C (#526).

[1] pterm/pterm#562

Fixes #526

Signed-off-by: Adam Wolfe Gordon <adam.wolfegordon@upbound.io>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants