github.com/rclone/rclone@v1.66.1-0.20240517100346-7b89735ae726/fs/accounting/accounting_unix.go (about)

     1  // Accounting and limiting reader
     2  // Unix specific functions.
     3  
     4  //go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris
     5  
     6  package accounting
     7  
     8  import (
     9  	"os"
    10  	"os/signal"
    11  	"syscall"
    12  
    13  	"github.com/rclone/rclone/fs"
    14  )
    15  
    16  // startSignalHandler() sets a signal handler to catch SIGUSR2 and toggle throttling.
    17  func (tb *tokenBucket) startSignalHandler() {
    18  	signals := make(chan os.Signal, 1)
    19  	signal.Notify(signals, syscall.SIGUSR2)
    20  
    21  	go func() {
    22  		// This runs forever, but blocks until the signal is received.
    23  		for {
    24  			<-signals
    25  
    26  			func() {
    27  				tb.mu.Lock()
    28  				defer tb.mu.Unlock()
    29  
    30  				// if there's no bandwidth limit configured now, do nothing
    31  				if !tb.currLimit.Bandwidth.IsSet() {
    32  					fs.Debugf(nil, "SIGUSR2 received but no bandwidth limit configured right now, ignoring")
    33  					return
    34  				}
    35  
    36  				tb.toggledOff = !tb.toggledOff
    37  				tb.curr, tb.prev = tb.prev, tb.curr
    38  				s := "disabled"
    39  				if !tb.curr._isOff() {
    40  					s = "enabled"
    41  				}
    42  
    43  				fs.Logf(nil, "Bandwidth limit %s by user", s)
    44  			}()
    45  		}
    46  	}()
    47  }