gitee.com/leisunstar/runtime@v0.0.0-20200521203717-5cef3e7b53f9/virtcontainers/hook/mock/hook.go (about)

     1  // Copyright (c) 2017 Intel Corporation
     2  //
     3  // SPDX-License-Identifier: Apache-2.0
     4  //
     5  
     6  package main
     7  
     8  import (
     9  	"encoding/json"
    10  	"fmt"
    11  	"io/ioutil"
    12  	"os"
    13  	"strconv"
    14  	"time"
    15  
    16  	specs "github.com/opencontainers/runtime-spec/specs-go"
    17  )
    18  
    19  var logFile = "/tmp/mock_hook.log"
    20  var testKey = "test-key"
    21  var testContainerID = "test-container-id"
    22  var testControllerID = "test-controller-id"
    23  
    24  func main() {
    25  	err := os.RemoveAll(logFile)
    26  	if err != nil {
    27  		os.Exit(1)
    28  	}
    29  
    30  	f, err := os.Create(logFile)
    31  	if err != nil {
    32  		os.Exit(1)
    33  	}
    34  	defer f.Close()
    35  
    36  	fmt.Fprintf(f, "args = %s\n", os.Args)
    37  
    38  	if len(os.Args) < 3 {
    39  		fmt.Fprintf(f, "At least 3 args expected, only %d received\n", len(os.Args))
    40  		os.Exit(1)
    41  	}
    42  
    43  	if os.Args[0] != testKey {
    44  		fmt.Fprintf(f, "args[0] should be \"%s\", received \"%s\" instead\n", testKey, os.Args[0])
    45  		os.Exit(1)
    46  	}
    47  
    48  	if os.Args[1] != testContainerID {
    49  		fmt.Fprintf(f, "argv[1] should be \"%s\", received \"%s\" instead\n", testContainerID, os.Args[1])
    50  		os.Exit(1)
    51  	}
    52  
    53  	if os.Args[2] != testControllerID {
    54  		fmt.Fprintf(f, "argv[2] should be \"%s\", received \"%s\" instead\n", testControllerID, os.Args[2])
    55  		os.Exit(1)
    56  	}
    57  
    58  	stateBuf, err := ioutil.ReadAll(os.Stdin)
    59  	if err != nil {
    60  		fmt.Fprintf(f, "Could not read on stdin: %s\n", err)
    61  		os.Exit(1)
    62  	}
    63  
    64  	var state specs.State
    65  	err = json.Unmarshal(stateBuf, &state)
    66  	if err != nil {
    67  		fmt.Fprintf(f, "Could not unmarshal HookState json: %s\n", err)
    68  		os.Exit(1)
    69  	}
    70  
    71  	if state.Pid < 1 {
    72  		fmt.Fprintf(f, "Invalid PID: %d\n", state.Pid)
    73  		os.Exit(1)
    74  	}
    75  
    76  	// Intended to sleep, so as to make the test passing/failing.
    77  	if len(os.Args) >= 4 {
    78  		timeout, err := strconv.Atoi(os.Args[3])
    79  		if err != nil {
    80  			fmt.Fprintf(f, "Could not retrieve timeout %s from args[3]\n", os.Args[3])
    81  			os.Exit(1)
    82  		}
    83  		time.Sleep(time.Duration(timeout) * time.Second)
    84  		if len(os.Args) == 5 {
    85  			msg := "panicking at user request"
    86  			fmt.Fprintln(f, msg)
    87  			panic(msg)
    88  		}
    89  	}
    90  }