Initial pgterminate code

This commit is contained in:
Julien Riou 2018-06-10 08:44:53 +02:00
parent 0487d635fc
commit 565c45a8fc
No known key found for this signature in database
GPG key ID: BA3E15176E45E85D
15 changed files with 697 additions and 0 deletions

29
notifier/console.go Normal file
View file

@ -0,0 +1,29 @@
package notifier
import (
"github.com/jouir/pgterminate/base"
"log"
)
// Console notifier structure
type Console struct {
sessions chan base.Session
}
// NewConsole creates a console notifier
func NewConsole(sessions chan base.Session) Notifier {
return &Console{
sessions: sessions,
}
}
// Run starts console notifier
func (c *Console) Run() {
for session := range c.sessions {
log.Printf("%s", session)
}
}
// Reload for handling SIGHUP signals
func (c *Console) Reload() {
}

55
notifier/file.go Normal file
View file

@ -0,0 +1,55 @@
package notifier
import (
"github.com/jouir/pgterminate/base"
"log"
"os"
"time"
)
// File structure for file notifier
type File struct {
handle *os.File
name string
sessions chan base.Session
}
// NewFile creates a file notifier
func NewFile(name string, sessions chan base.Session) Notifier {
return &File{
name: name,
sessions: sessions,
}
}
// Run starts the file notifier
func (f *File) Run() {
f.open()
defer f.terminate()
for session := range f.sessions {
timestamp := time.Now().Format(time.RFC3339)
_, err := f.handle.WriteString(timestamp + " " + session.String() + "\n")
base.Panic(err)
}
}
// open opens a log file
func (f *File) open() {
var err error
f.handle, err = os.OpenFile(f.name, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
base.Panic(err)
}
// Reload closes and re-open the file to be compatible with logrotate
func (f *File) Reload() {
log.Println("Re-opening log file", f.name)
f.handle.Close()
f.open()
}
// terminate closes the file
func (f *File) terminate() {
log.Println("Closing log file", f.name)
f.handle.Close()
}

20
notifier/notifier.go Normal file
View file

@ -0,0 +1,20 @@
package notifier
import (
"github.com/jouir/pgterminate/base"
)
// Notifier generic interface for implementing a notifier
type Notifier interface {
Run()
Reload()
}
// NewNotifier looks into Config to create a File or Console notifier and pass it
// the session channel for consuming sessions structs sent by terminator
func NewNotifier(ctx *base.Context) Notifier {
if ctx.Config.LogFile != "" {
return NewFile(ctx.Config.LogFile, ctx.Sessions)
}
return NewConsole(ctx.Sessions)
}