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