2017-02-17 06:48:38 +00:00
|
|
|
package logging
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2018-10-25 20:22:04 +00:00
|
|
|
"io"
|
2017-02-17 06:48:38 +00:00
|
|
|
"net"
|
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2017-05-31 14:45:48 +00:00
|
|
|
socketPath = "./ctop.sock"
|
|
|
|
socketAddr = "0.0.0.0:9000"
|
2017-02-17 06:48:38 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var server struct {
|
|
|
|
wg sync.WaitGroup
|
|
|
|
ln net.Listener
|
|
|
|
}
|
|
|
|
|
|
|
|
func getListener() net.Listener {
|
2017-05-31 14:45:48 +00:00
|
|
|
var ln net.Listener
|
|
|
|
var err error
|
|
|
|
if debugModeTCP() {
|
|
|
|
ln, err = net.Listen("tcp", socketAddr)
|
|
|
|
} else {
|
|
|
|
ln, err = net.Listen("unix", socketPath)
|
|
|
|
}
|
2017-02-17 06:48:38 +00:00
|
|
|
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()
|
2017-02-18 03:37:00 +00:00
|
|
|
if server.ln != nil {
|
|
|
|
server.ln.Close()
|
|
|
|
}
|
2017-02-17 06:48:38 +00:00
|
|
|
}
|
|
|
|
|
2018-10-25 20:22:04 +00:00
|
|
|
func handler(wc io.WriteCloser) {
|
2017-02-17 06:48:38 +00:00
|
|
|
server.wg.Add(1)
|
|
|
|
defer server.wg.Done()
|
2018-10-25 20:22:04 +00:00
|
|
|
defer wc.Close()
|
2017-02-17 06:48:38 +00:00
|
|
|
for msg := range Log.tail() {
|
|
|
|
msg = fmt.Sprintf("%s\n", msg)
|
2018-10-25 20:22:04 +00:00
|
|
|
wc.Write([]byte(msg))
|
2017-02-17 06:48:38 +00:00
|
|
|
}
|
2018-10-25 20:22:04 +00:00
|
|
|
wc.Write([]byte("bye\n"))
|
2017-02-17 06:48:38 +00:00
|
|
|
}
|