global command

This commit is contained in:
Mikaël Cluseau
2019-03-08 12:21:29 +11:00
parent 9e597e8a4d
commit 7741051b20
41 changed files with 886 additions and 1583 deletions

36
pkg/sys/config.go Normal file
View File

@ -0,0 +1,36 @@
package sys
import (
"log"
"sync"
"novit.nc/direktil/pkg/config"
)
const cfgPath = "/config.yaml"
var (
cfg *config.Config
cfgLock sync.Mutex
)
func Config() *config.Config {
if cfg != nil {
return cfg
}
cfgLock.Lock()
defer cfgLock.Unlock()
if cfg != nil {
return cfg
}
c, err := config.Load(cfgPath)
if err != nil {
log.Fatal("FATAL: failed to load config: ", err)
}
cfg = c
return cfg
}

19
pkg/sys/mount.go Normal file
View File

@ -0,0 +1,19 @@
package sys
import (
"log"
"os"
"syscall"
)
func Mount(source, target, fstype string, flags uintptr, data string) {
if _, err := os.Stat(target); os.IsNotExist(err) {
Mkdir(target, 0755)
}
if err := syscall.Mount(source, target, fstype, flags, data); err != nil {
log.Fatalf("FATAL: mount %q %q -t %q -o %q failed: %v", source, target, fstype, data, err)
}
log.Printf("mounted %q", target)
}

87
pkg/sys/sys.go Normal file
View File

@ -0,0 +1,87 @@
package sys
import (
"log"
"os"
"os/exec"
"path/filepath"
"time"
"github.com/fsnotify/fsnotify"
)
func Run(cmd string, args ...string) (err error) {
c := exec.Command(cmd, args...)
c.Stdout = os.Stdout
c.Stderr = os.Stderr
if err = c.Run(); err != nil {
log.Printf("command %s %q failed: %v", cmd, args, err)
}
return
}
func MustRun(cmd string, args ...string) {
if err := Run(cmd, args...); err != nil {
log.Fatal("FATAL: mandatory command did not succeed")
}
}
func Mkdir(dir string, mode os.FileMode) {
if err := os.MkdirAll(dir, mode); err != nil {
log.Fatalf("FATAL: mkdir %q failed: %v", dir, err)
}
}
func FileExists(path string) bool {
_, err := os.Stat(path)
if err != nil {
if !os.IsNotExist(err) {
log.Printf("WARNING: failed to stat %q, assuming not exist: %v", path, err)
}
return false
}
return true
}
func WaitFile(path string, timeout <-chan time.Time) {
if FileExists(path) {
return
}
watch, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal("FATAL: fsnotify: failed to create: ", err)
}
defer watch.Close()
dir := filepath.Dir(path)
if err = watch.Add(dir); err != nil {
log.Fatalf("FATAL: fsnotify: failed to add %s: %v", dir, err)
}
go func() {
for err := range watch.Errors {
log.Fatal("FATAL: fsnotify: error: ", err)
}
}()
timedOut := false
for !timedOut {
select {
case <-watch.Events:
// skip
case <-timeout:
timedOut = true
}
if FileExists(path) {
return
}
}
log.Fatal("FATAL: timed out waiting for ", path)
}