github.com/rkt/rkt@v1.30.1-0.20200224141603-171c416fac02/stage1/stop_kvm/stop_kvm.go (about)

     1  // Copyright 2016 The rkt Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  //+build linux
    16  
    17  package main
    18  
    19  import (
    20  	"flag"
    21  	"fmt"
    22  	"io/ioutil"
    23  	"os"
    24  	"syscall"
    25  
    26  	rktlog "github.com/rkt/rkt/pkg/log"
    27  	"github.com/rkt/rkt/stage1/common/ssh"
    28  )
    29  
    30  var (
    31  	force bool
    32  	log   *rktlog.Logger
    33  )
    34  
    35  func init() {
    36  	flag.BoolVar(&force, "force", false, "Forced stop")
    37  }
    38  
    39  func readIntFromFile(path string) (i int, err error) {
    40  	b, err := ioutil.ReadFile(path)
    41  	if err != nil {
    42  		return
    43  	}
    44  	_, err = fmt.Sscanf(string(b), "%d", &i)
    45  	return
    46  }
    47  
    48  func main() {
    49  	flag.Parse()
    50  
    51  	if force {
    52  		pid, err := readIntFromFile("pid")
    53  		if err != nil {
    54  			fmt.Fprintf(os.Stderr, "error reading pid: %v\n", err)
    55  			os.Exit(254)
    56  		}
    57  
    58  		if err := syscall.Kill(pid, syscall.SIGKILL); err != nil {
    59  			fmt.Fprintf(os.Stderr, "error sending %v: %v\n", syscall.SIGKILL, err)
    60  			os.Exit(254)
    61  		}
    62  		return
    63  	}
    64  
    65  	// ExecSSH() should return only with error
    66  	log.Error(ssh.ExecSSH([]string{"systemctl", "halt"}))
    67  	os.Exit(254)
    68  }