github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/runsc/cmd/error.go (about)

     1  // Copyright 2019 The gVisor 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  package cmd
    16  
    17  import (
    18  	"encoding/json"
    19  	"fmt"
    20  	"io"
    21  	"os"
    22  	"time"
    23  
    24  	"github.com/google/subcommands"
    25  	"github.com/SagerNet/gvisor/pkg/log"
    26  )
    27  
    28  // ErrorLogger is where error messages should be written to. These messages are
    29  // consumed by containerd and show up to users of command line tools,
    30  // like docker/kubectl.
    31  var ErrorLogger io.Writer
    32  
    33  type jsonError struct {
    34  	Msg   string    `json:"msg"`
    35  	Level string    `json:"level"`
    36  	Time  time.Time `json:"time"`
    37  }
    38  
    39  // Errorf logs error to containerd log (--log), to stderr, and debug logs. It
    40  // returns subcommands.ExitFailure for convenience with subcommand.Execute()
    41  // methods:
    42  //    return Errorf("Danger! Danger!")
    43  //
    44  func Errorf(format string, args ...interface{}) subcommands.ExitStatus {
    45  	// If runsc is being invoked by docker or cri-o, then we might not have
    46  	// access to stderr, so we log a serious-looking warning in addition to
    47  	// writing to stderr.
    48  	log.Warningf("FATAL ERROR: "+format, args...)
    49  	fmt.Fprintf(os.Stderr, format+"\n", args...)
    50  
    51  	j := jsonError{
    52  		Msg:   fmt.Sprintf(format, args...),
    53  		Level: "error",
    54  		Time:  time.Now(),
    55  	}
    56  	b, err := json.Marshal(j)
    57  	if err != nil {
    58  		panic(err)
    59  	}
    60  	if ErrorLogger != nil {
    61  		ErrorLogger.Write(b)
    62  	}
    63  
    64  	return subcommands.ExitFailure
    65  }
    66  
    67  // Fatalf logs the same way as Errorf() does, plus *exits* the process.
    68  func Fatalf(format string, args ...interface{}) {
    69  	Errorf(format, args...)
    70  	// Return an error that is unlikely to be used by the application.
    71  	os.Exit(128)
    72  }