github.com/alibaba/sealer@v0.8.6-0.20220430115802-37a2bdaa8173/pkg/debug/term.go (about)

     1  /*
     2  Copyright 2016 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package debug
    18  
    19  import (
    20  	"io"
    21  	"os"
    22  
    23  	"github.com/alibaba/sealer/logger"
    24  
    25  	"github.com/moby/term"
    26  )
    27  
    28  // SafeFunc is a function to be invoked by TTY.
    29  type SafeFunc func() error
    30  
    31  // TTY helps invoke a function and preserve the state of the terminal, even if the process is
    32  // terminated during execution. It also provides support for terminal resizing for remote command
    33  // attachment.
    34  type TTY struct {
    35  	// In is a reader representing stdin. It is a required field.
    36  	In io.Reader
    37  	// Out is a writer representing stdout. It must be set to support terminal resizing. It is an
    38  	// optional field.
    39  	Out io.Writer
    40  	// Raw is true if the terminal should be set raw.
    41  	Raw bool
    42  	// TryDev indicates the TTY should try to open /dev/tty if the provided input
    43  	// is not a file descriptor.
    44  	TryDev bool
    45  	// Parent is an optional interrupt handler provided to this function - if provided
    46  	// it will be invoked after the terminal state is restored. If it is not provided,
    47  	// a signal received during the TTY will result in os.Exit(0) being invoked.
    48  	Parent *Handler
    49  
    50  	// sizeQueue is set after a call to MonitorSize() and is used to monitor SIGWINCH signals when the
    51  	// user's terminal resizes.
    52  	sizeQueue *sizeQueue
    53  }
    54  
    55  // IsTerminalIn returns true if t.In is a terminal. Does not check /dev/tty
    56  // even if TryDev is set.
    57  func (t TTY) IsTerminalIn() bool {
    58  	return IsTerminal(t.In)
    59  }
    60  
    61  // IsTerminalOut returns true if t.Out is a terminal. Does not check /dev/tty
    62  // even if TryDev is set.
    63  func (t TTY) IsTerminalOut() bool {
    64  	return IsTerminal(t.Out)
    65  }
    66  
    67  // IsTerminal returns whether the passed object is a terminal or not
    68  func IsTerminal(i interface{}) bool {
    69  	_, terminal := term.GetFdInfo(i)
    70  	return terminal
    71  }
    72  
    73  // Safe invokes the provided function and will attempt to ensure that when the
    74  // function returns (or a termination signal is sent) that the terminal state
    75  // is reset to the condition it was in prior to the function being invoked.
    76  // If Raw is true the terminal will be put into raw mode prior to calling the function.
    77  func (t TTY) Safe(fn SafeFunc) error {
    78  	// If the input file descriptor is not a TTY and TryDev is true, the /dev/tty file
    79  	// will be opened (if available).
    80  	inFd, isTerminal := term.GetFdInfo(t.In)
    81  
    82  	if !isTerminal && t.TryDev {
    83  		if f, err := os.Open("/dev/tty"); err == nil {
    84  			defer func() {
    85  				if err := f.Close(); err != nil {
    86  					logger.Fatal("failed to close file")
    87  				}
    88  			}()
    89  			inFd = f.Fd()
    90  			isTerminal = term.IsTerminal(inFd)
    91  		}
    92  	}
    93  
    94  	if !isTerminal {
    95  		return fn()
    96  	}
    97  
    98  	var state *term.State
    99  	var err error
   100  	if t.Raw {
   101  		state, err = term.MakeRaw(inFd)
   102  	} else {
   103  		state, err = term.SaveState(inFd)
   104  	}
   105  	if err != nil {
   106  		return err
   107  	}
   108  	return Chain(t.Parent, func() {
   109  		if t.sizeQueue != nil {
   110  			t.sizeQueue.stop()
   111  		}
   112  
   113  		if err := term.RestoreTerminal(inFd, state); err != nil {
   114  			return
   115  		}
   116  	}).Run(fn)
   117  }