github.com/containerd/nerdctl@v1.7.7/pkg/signalutil/signals.go (about)

     1  /*
     2     Copyright The containerd 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 signalutil
    18  
    19  import (
    20  	gocontext "context"
    21  	"os"
    22  	"os/signal"
    23  	"syscall"
    24  
    25  	"github.com/containerd/containerd"
    26  	"github.com/containerd/errdefs"
    27  	"github.com/containerd/log"
    28  )
    29  
    30  // killer is from https://github.com/containerd/containerd/blob/v1.7.0-rc.2/cmd/ctr/commands/signals.go#L30-L32
    31  type killer interface {
    32  	Kill(gocontext.Context, syscall.Signal, ...containerd.KillOpts) error
    33  }
    34  
    35  // ForwardAllSignals forwards signals.
    36  // From https://github.com/containerd/containerd/blob/v1.7.0-rc.2/cmd/ctr/commands/signals.go#L34-L55
    37  func ForwardAllSignals(ctx gocontext.Context, task killer) chan os.Signal {
    38  	sigc := make(chan os.Signal, 128)
    39  	signal.Notify(sigc)
    40  	go func() {
    41  		for s := range sigc {
    42  			if canIgnoreSignal(s) {
    43  				log.G(ctx).Debugf("Ignoring signal %s", s)
    44  				continue
    45  			}
    46  			log.G(ctx).Debug("forwarding signal ", s)
    47  			if err := task.Kill(ctx, s.(syscall.Signal)); err != nil {
    48  				if errdefs.IsNotFound(err) {
    49  					log.G(ctx).WithError(err).Debugf("Not forwarding signal %s", s)
    50  					return
    51  				}
    52  				log.G(ctx).WithError(err).Errorf("forward signal %s", s)
    53  			}
    54  		}
    55  	}()
    56  	return sigc
    57  }
    58  
    59  // StopCatch stops and closes a channel.
    60  // From https://github.com/containerd/containerd/blob/v1.7.0-rc.2/cmd/ctr/commands/signals.go#L57-L61
    61  func StopCatch(sigc chan os.Signal) {
    62  	signal.Stop(sigc)
    63  	close(sigc)
    64  }