move logging server into own file, improve cleanup

This commit is contained in:
Bradley Cicenas 2017-02-17 17:48:38 +11:00
parent 47360bc8e7
commit 2fdf68e876
3 changed files with 65 additions and 44 deletions

View File

@ -1,9 +1,6 @@
package logging package logging
import ( import (
"fmt"
"net"
"sync"
"time" "time"
"github.com/op/go-logging" "github.com/op/go-logging"
@ -11,12 +8,10 @@ import (
const ( const (
size = 1024 size = 1024
path = "/tmp/ctop.sock"
) )
var ( var (
Log *CTopLogger Log *CTopLogger
wg sync.WaitGroup
exited bool exited bool
level = logging.INFO level = logging.INFO
format = logging.MustStringFormatter( format = logging.MustStringFormatter(
@ -47,44 +42,6 @@ func Init() *CTopLogger {
return Log return Log
} }
func (log *CTopLogger) Exit() {
exited = true
wg.Wait()
}
func (log *CTopLogger) StartServer() {
ln, err := net.Listen("unix", path)
if err != nil {
panic(err)
}
go func() {
for {
conn, err := ln.Accept()
if err != nil {
if err, ok := err.(net.Error); ok && err.Temporary() {
continue
}
return
}
go log.handler(conn)
}
}()
log.Notice("logging server started")
}
func (log *CTopLogger) handler(conn net.Conn) {
wg.Add(1)
defer wg.Done()
defer conn.Close()
for msg := range log.tail() {
msg = fmt.Sprintf("%s\n", msg)
conn.Write([]byte(msg))
}
conn.Write([]byte("bye\n"))
}
func (log *CTopLogger) tail() chan string { func (log *CTopLogger) tail() chan string {
stream := make(chan string) stream := make(chan string)
@ -109,3 +66,8 @@ func (log *CTopLogger) tail() chan string {
return stream return stream
} }
func (log *CTopLogger) Exit() {
exited = true
StopServer()
}

59
logging/server.go Normal file
View File

@ -0,0 +1,59 @@
package logging
import (
"fmt"
"net"
"sync"
)
const (
path = "/tmp/ctop.sock"
)
var server struct {
wg sync.WaitGroup
ln net.Listener
}
func getListener() net.Listener {
ln, err := net.Listen("unix", path)
if err != nil {
panic(err)
}
return ln
}
func StartServer() {
server.ln = getListener()
go func() {
for {
conn, err := server.ln.Accept()
if err != nil {
if err, ok := err.(net.Error); ok && err.Temporary() {
continue
}
return
}
go handler(conn)
}
}()
Log.Notice("logging server started")
}
func StopServer() {
server.wg.Wait()
server.ln.Close()
}
func handler(conn net.Conn) {
server.wg.Add(1)
defer server.wg.Done()
defer conn.Close()
for msg := range Log.tail() {
msg = fmt.Sprintf("%s\n", msg)
conn.Write([]byte(msg))
}
conn.Write([]byte("bye\n"))
}

View File

@ -12,7 +12,7 @@ func main() {
config.Init() config.Init()
log = logging.Init() log = logging.Init()
if config.GetSwitchVal("loggingEnabled") { if config.GetSwitchVal("loggingEnabled") {
log.StartServer() logging.StartServer()
} }
if err := ui.Init(); err != nil { if err := ui.Init(); err != nil {
panic(err) panic(err)