github.com/GoogleContainerTools/skaffold@v1.39.18/pkg/skaffold/build/misc/graceful.go (about)

     1  /*
     2  Copyright 2019 The Skaffold 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 misc
    18  
    19  import (
    20  	"context"
    21  	"os"
    22  	"os/exec"
    23  	"runtime"
    24  	"sync"
    25  	"time"
    26  
    27  	"github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log"
    28  )
    29  
    30  // For testing
    31  var (
    32  	gracePeriod = 2 * time.Second
    33  )
    34  
    35  func HandleGracefulTermination(ctx context.Context, cmd *exec.Cmd) error {
    36  	done := make(chan bool, 1) // Non blocking
    37  	defer close(done)
    38  
    39  	var wg sync.WaitGroup
    40  	wg.Add(1)
    41  	go func() {
    42  		defer wg.Done()
    43  
    44  		select {
    45  		case <-ctx.Done():
    46  			// On windows we can't send specific signals to processes, so we kill the process immediately
    47  			if runtime.GOOS == "windows" {
    48  				cmd.Process.Kill()
    49  				return
    50  			}
    51  
    52  			log.Entry(ctx).Debug("Sending SIGINT to process", cmd.Process.Pid)
    53  			if err := cmd.Process.Signal(os.Interrupt); err != nil {
    54  				// kill process on error
    55  				cmd.Process.Kill()
    56  				return
    57  			}
    58  
    59  			// wait 2 seconds or wait for the process to complete
    60  			select {
    61  			case <-time.After(gracePeriod):
    62  				log.Entry(ctx).Debug("Killing process", cmd.Process.Pid)
    63  				// forcefully kill process after grace period
    64  				cmd.Process.Kill()
    65  			case <-done:
    66  				return
    67  			}
    68  		case <-done:
    69  			return
    70  		}
    71  	}()
    72  
    73  	err := cmd.Wait()
    74  	done <- true
    75  	wg.Wait()
    76  	return err
    77  }