gofmt daemon

pull/3/head
Simon Let 7 years ago
parent 3b90a42240
commit bf9167e96a
  1. 291
      daemon/resh-daemon.go

@ -1,171 +1,170 @@
package main package main
import ( import (
"encoding/json" "encoding/json"
//"flag" //"flag"
"log" "github.com/BurntSushi/toml"
"io/ioutil" common "github.com/curusarn/resh/common"
"path/filepath" "io/ioutil"
"os" "log"
"os/exec" "net/http"
"os/user" "os"
"strconv" "os/exec"
"strings" "os/user"
"net/http" "path/filepath"
common "github.com/curusarn/resh/common" "strconv"
"github.com/BurntSushi/toml" "strings"
) )
func main() { func main() {
usr, _ := user.Current() usr, _ := user.Current()
dir := usr.HomeDir dir := usr.HomeDir
pidfilePath := filepath.Join(dir, ".resh/resh.pid") pidfilePath := filepath.Join(dir, ".resh/resh.pid")
configPath := filepath.Join(dir, ".config/resh.toml") configPath := filepath.Join(dir, ".config/resh.toml")
outputPath := filepath.Join(dir, ".resh/history.json") outputPath := filepath.Join(dir, ".resh/history.json")
logPath := filepath.Join(dir, ".resh/daemon.log") logPath := filepath.Join(dir, ".resh/daemon.log")
f, err := os.OpenFile(logPath, os.O_RDWR | os.O_CREATE | os.O_APPEND, 0644) f, err := os.OpenFile(logPath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
if err != nil { if err != nil {
log.Fatal("Error opening file:", err) log.Fatal("Error opening file:", err)
} }
defer f.Close() defer f.Close()
log.SetOutput(f) log.SetOutput(f)
log.SetPrefix(strconv.Itoa(os.Getpid()) + " | ") log.SetPrefix(strconv.Itoa(os.Getpid()) + " | ")
var config common.Config var config common.Config
if _, err := toml.DecodeFile(configPath, &config); err != nil { if _, err := toml.DecodeFile(configPath, &config); err != nil {
log.Println("Error reading config", err) log.Println("Error reading config", err)
return return
} }
res, err := isDaemonRunning(config.Port) res, err := isDaemonRunning(config.Port)
if err != nil { if err != nil {
log.Println("Error while checking if the daemon is runnnig", err) log.Println("Error while checking if the daemon is runnnig", err)
} }
if res { if res {
log.Println("Daemon is already running - exiting!") log.Println("Daemon is already running - exiting!")
return return
} }
_, err = os.Stat(pidfilePath) _, err = os.Stat(pidfilePath)
if err == nil { if err == nil {
log.Println("Pidfile exists") log.Println("Pidfile exists")
// kill daemon // kill daemon
err = killDaemon(pidfilePath) err = killDaemon(pidfilePath)
if err != nil { if err != nil {
log.Println("Error while killing daemon", err) log.Println("Error while killing daemon", err)
} }
} }
err = ioutil.WriteFile(pidfilePath, []byte(strconv.Itoa(os.Getpid())), 0644) err = ioutil.WriteFile(pidfilePath, []byte(strconv.Itoa(os.Getpid())), 0644)
if err != nil { if err != nil {
log.Fatal("Could not create pidfile", err) log.Fatal("Could not create pidfile", err)
} }
runServer(config.Port, outputPath) runServer(config.Port, outputPath)
err = os.Remove(pidfilePath) err = os.Remove(pidfilePath)
if err != nil { if err != nil {
log.Println("Could not delete pidfile", err) log.Println("Could not delete pidfile", err)
} }
} }
func statusHandler(w http.ResponseWriter, r *http.Request) { func statusHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("OK\n")) w.Write([]byte("OK\n"))
log.Println("Status OK") log.Println("Status OK")
} }
type recordHandler struct { type recordHandler struct {
OutputPath string OutputPath string
} }
func (h *recordHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { func (h *recordHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("OK\n")) w.Write([]byte("OK\n"))
record := common.Record{} record := common.Record{}
jsn, err := ioutil.ReadAll(r.Body) jsn, err := ioutil.ReadAll(r.Body)
if err != nil { if err != nil {
log.Println("Error reading the body", err) log.Println("Error reading the body", err)
return return
} }
err = json.Unmarshal(jsn, &record) err = json.Unmarshal(jsn, &record)
if err != nil { if err != nil {
log.Println("Decoding error: ", err) log.Println("Decoding error: ", err)
log.Println("Payload: ", jsn) log.Println("Payload: ", jsn)
return return
} }
f, err := os.OpenFile(h.OutputPath, f, err := os.OpenFile(h.OutputPath,
os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil { if err != nil {
log.Println("Could not open file", err) log.Println("Could not open file", err)
return return
} }
defer f.Close() defer f.Close()
_, err = f.Write(append(jsn, []byte("\n")...)) _, err = f.Write(append(jsn, []byte("\n")...))
if err != nil { if err != nil {
log.Printf("Error while writing: %v, %s\n", record, err) log.Printf("Error while writing: %v, %s\n", record, err)
return return
} }
log.Println("Received: ", record.CmdLine) log.Println("Received: ", record.CmdLine)
// fmt.Println("cmd:", r.CmdLine) // fmt.Println("cmd:", r.CmdLine)
// fmt.Println("pwd:", r.Pwd) // fmt.Println("pwd:", r.Pwd)
// fmt.Println("git:", r.GitWorkTree) // fmt.Println("git:", r.GitWorkTree)
// fmt.Println("exit_code:", r.ExitCode) // fmt.Println("exit_code:", r.ExitCode)
} }
func runServer(port int, outputPath string) { func runServer(port int, outputPath string) {
http.HandleFunc("/status", statusHandler) http.HandleFunc("/status", statusHandler)
http.Handle("/record", &recordHandler{OutputPath: outputPath}) http.Handle("/record", &recordHandler{OutputPath: outputPath})
http.ListenAndServe(":" + strconv.Itoa(port) , nil) http.ListenAndServe(":"+strconv.Itoa(port), nil)
} }
func killDaemon(pidfile string) error { func killDaemon(pidfile string) error {
dat, err := ioutil.ReadFile(pidfile) dat, err := ioutil.ReadFile(pidfile)
if err != nil { if err != nil {
log.Println("Reading pid file failed", err) log.Println("Reading pid file failed", err)
} }
log.Print(string(dat)) log.Print(string(dat))
pid, err := strconv.Atoi(strings.TrimSuffix(string(dat), "\n")) pid, err := strconv.Atoi(strings.TrimSuffix(string(dat), "\n"))
if err != nil { if err != nil {
log.Fatal("Pidfile contents are malformed", err) log.Fatal("Pidfile contents are malformed", err)
} }
cmd := exec.Command("kill", strconv.Itoa(pid)) cmd := exec.Command("kill", strconv.Itoa(pid))
err = cmd.Run() err = cmd.Run()
if err != nil { if err != nil {
log.Printf("Command finished with error: %v", err) log.Printf("Command finished with error: %v", err)
return err return err
} }
return nil return nil
} }
func isDaemonRunning(port int) (bool, error) { func isDaemonRunning(port int) (bool, error) {
url := "http://localhost:" + strconv.Itoa(port) + "/status" url := "http://localhost:" + strconv.Itoa(port) + "/status"
resp, err := http.Get(url) resp, err := http.Get(url)
if err != nil { if err != nil {
log.Println("Error while checking daemon status - " + log.Println("Error while checking daemon status - "+
"it's probably not running!", err) "it's probably not running!", err)
return false, err return false, err
} }
defer resp.Body.Close() defer resp.Body.Close()
return true, nil return true, nil
//body, err := ioutil.ReadAll(resp.Body) //body, err := ioutil.ReadAll(resp.Body)
// dat, err := ioutil.ReadFile(pidfile)
// dat, err := ioutil.ReadFile(pidfile) // if err != nil {
// if err != nil { // log.Println("Reading pid file failed", err)
// log.Println("Reading pid file failed", err) // return false, err
// return false, err // }
// } // log.Print(string(dat))
// log.Print(string(dat)) // pid, err := strconv.ParseInt(string(dat), 10, 64)
// pid, err := strconv.ParseInt(string(dat), 10, 64) // if err != nil {
// if err != nil { // log.Fatal(err)
// log.Fatal(err) // }
// } // process, err := os.FindProcess(int(pid))
// process, err := os.FindProcess(int(pid)) // if err != nil {
// if err != nil { // log.Printf("Failed to find process: %s\n", err)
// log.Printf("Failed to find process: %s\n", err) // return false, err
// return false, err // } else {
// } else { // err := process.Signal(syscall.Signal(0))
// err := process.Signal(syscall.Signal(0)) // log.Printf("process.Signal on pid %d returned: %v\n", pid, err)
// log.Printf("process.Signal on pid %d returned: %v\n", pid, err) // }
// } // return true, nil
// return true, nil
} }

Loading…
Cancel
Save