github.com/sealerio/sealer@v0.11.1-0.20240507115618-f4f89c5853ae/pkg/debug/resizeevents.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  	"os"
    21  	"os/signal"
    22  
    23  	"golang.org/x/sys/unix"
    24  	"k8s.io/apimachinery/pkg/util/runtime"
    25  	"k8s.io/client-go/tools/remotecommand"
    26  )
    27  
    28  // monitorResizeEvents spawns a goroutine that waits for SIGWINCH signals (these indicate the
    29  // terminal has resized). After receiving a SIGWINCH, this gets the terminal size and tries to send
    30  // it to the resizeEvents channel. The goroutine stops when the stop channel is closed.
    31  func monitorResizeEvents(fd uintptr, resizeEvents chan<- remotecommand.TerminalSize, stop chan struct{}) {
    32  	go func() {
    33  		defer runtime.HandleCrash()
    34  
    35  		winch := make(chan os.Signal, 1)
    36  		signal.Notify(winch, unix.SIGWINCH)
    37  		defer signal.Stop(winch)
    38  
    39  		for {
    40  			select {
    41  			case <-winch:
    42  				size := GetSize(fd)
    43  				if size == nil {
    44  					return
    45  				}
    46  
    47  				// try to send size
    48  				select {
    49  				case resizeEvents <- *size:
    50  					// success
    51  				default:
    52  					// not sent
    53  				}
    54  			case <-stop:
    55  				return
    56  			}
    57  		}
    58  	}()
    59  }