83 lines
1.7 KiB
Go
Raw Permalink Normal View History

2015-10-21 12:15:19 -07:00
package common
import (
"fmt"
"io/ioutil"
"os"
"os/signal"
2017-10-04 00:13:58 -04:00
"syscall"
2015-10-21 12:15:19 -07:00
)
type logger interface {
Info(msg string, keyvals ...interface{})
}
// TrapSignal catches the SIGTERM/SIGINT and executes cb function. After that it exits
// with code 0.
func TrapSignal(logger logger, cb func()) {
2015-10-21 12:15:19 -07:00
c := make(chan os.Signal, 1)
2017-10-04 00:13:58 -04:00
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
2015-10-21 12:15:19 -07:00
go func() {
for sig := range c {
logger.Info(fmt.Sprintf("captured %v, exiting...", sig))
2015-10-21 12:15:19 -07:00
if cb != nil {
cb()
}
os.Exit(0)
2015-10-21 12:15:19 -07:00
}
}()
}
2017-11-03 23:51:39 -05:00
// Kill the running process by sending itself SIGTERM.
2017-10-27 11:01:40 -04:00
func Kill() error {
2017-11-03 23:51:39 -05:00
p, err := os.FindProcess(os.Getpid())
if err != nil {
return err
}
return p.Signal(syscall.SIGTERM)
2017-10-27 11:01:40 -04:00
}
2015-10-21 12:15:19 -07:00
func Exit(s string) {
fmt.Printf(s + "\n")
os.Exit(1)
}
2015-12-03 23:44:24 -08:00
func EnsureDir(dir string, mode os.FileMode) error {
2015-10-21 12:15:19 -07:00
if _, err := os.Stat(dir); os.IsNotExist(err) {
2015-12-03 23:44:24 -08:00
err := os.MkdirAll(dir, mode)
2015-10-21 12:15:19 -07:00
if err != nil {
return fmt.Errorf("Could not create directory %v. %v", dir, err)
}
}
return nil
}
func FileExists(filePath string) bool {
_, err := os.Stat(filePath)
return !os.IsNotExist(err)
}
func ReadFile(filePath string) ([]byte, error) {
return ioutil.ReadFile(filePath)
}
func MustReadFile(filePath string) []byte {
fileBytes, err := ioutil.ReadFile(filePath)
if err != nil {
Exit(fmt.Sprintf("MustReadFile failed: %v", err))
2015-10-21 12:15:19 -07:00
return nil
}
return fileBytes
}
2015-12-03 23:56:50 -08:00
func WriteFile(filePath string, contents []byte, mode os.FileMode) error {
return ioutil.WriteFile(filePath, contents, mode)
2015-10-21 12:15:19 -07:00
}
2015-12-03 23:56:50 -08:00
func MustWriteFile(filePath string, contents []byte, mode os.FileMode) {
err := WriteFile(filePath, contents, mode)
2015-10-21 12:15:19 -07:00
if err != nil {
Exit(fmt.Sprintf("MustWriteFile failed: %v", err))
2015-10-21 12:15:19 -07:00
}
}