github.com/unicornultrafoundation/go-u2u@v1.0.0-rc1.0.20240205080301-e74a83d3fadc/utils/errlock/errlock.go (about)

     1  package errlock
     2  
     3  import (
     4  	"io"
     5  	"io/ioutil"
     6  	"os"
     7  	"path"
     8  
     9  	"github.com/unicornultrafoundation/go-u2u/cmd/utils"
    10  )
    11  
    12  // Check if errlock is written
    13  func Check() {
    14  	locked, reason, eLockPath, _ := read(datadir)
    15  	if locked {
    16  		utils.Fatalf("Node isn't allowed to start due to a previous error. Please fix the issue and then delete file \"%s\". Error message:\n%s", eLockPath, reason)
    17  	}
    18  }
    19  
    20  var (
    21  	datadir string
    22  )
    23  
    24  // SetDefaultDatadir for errlock files
    25  func SetDefaultDatadir(dir string) {
    26  	datadir = dir
    27  }
    28  
    29  // Permanent error
    30  func Permanent(err error) {
    31  	eLockPath, _ := write(datadir, err.Error())
    32  	utils.Fatalf("Node is permanently stopping due to an issue. Please fix the issue and then delete file \"%s\". Error message:\n%s", eLockPath, err.Error())
    33  }
    34  
    35  func readAll(reader io.Reader, max int) ([]byte, error) {
    36  	buf := make([]byte, max)
    37  	consumed := 0
    38  	for {
    39  		n, err := reader.Read(buf[consumed:])
    40  		consumed += n
    41  		if consumed == len(buf) || err == io.EOF {
    42  			return buf[:consumed], nil
    43  		}
    44  		if err != nil {
    45  			return nil, err
    46  		}
    47  	}
    48  }
    49  
    50  // read errlock file
    51  func read(dir string) (bool, string, string, error) {
    52  	eLockPath := path.Join(dir, "errlock")
    53  
    54  	data, err := os.Open(eLockPath)
    55  	if err != nil {
    56  		return false, "", eLockPath, err
    57  	}
    58  	defer data.Close()
    59  
    60  	// read no more than N bytes
    61  	maxFileLen := 5000
    62  	eLockBytes, err := readAll(data, maxFileLen)
    63  	if err != nil {
    64  		return true, "", eLockPath, err
    65  	}
    66  	return true, string(eLockBytes), eLockPath, nil
    67  }
    68  
    69  // write errlock file
    70  func write(dir string, eLockStr string) (string, error) {
    71  	eLockPath := path.Join(dir, "errlock")
    72  
    73  	return eLockPath, ioutil.WriteFile(eLockPath, []byte(eLockStr), 0666) // assume no custom encoding needed
    74  }