added main.go

This commit is contained in:
Andreas Neue 2018-06-21 11:22:54 +02:00
parent dcf7b24db8
commit 3be5b12690
1 changed files with 74 additions and 0 deletions

74
main.go Normal file
View File

@ -0,0 +1,74 @@
// vi:ts=4:sts=4:sw=4:noet:tw=72
//
// logforward
//
// Copyright (c) 2018 Andreas Neue <an@dnix.de>
package main
import (
"bufio"
"bytes"
"compress/gzip"
"flag"
"fmt"
"os"
"time"
"git.dnix.de/an/xlog"
goscp "github.com/bramvdbogaerde/go-scp"
"github.com/bramvdbogaerde/go-scp/auth"
"golang.org/x/crypto/ssh"
)
var (
bufferLimit = flag.Int("b", 1024*1024*1024, "Buffer size limit")
scpUser = flag.String("u", "", "User")
scpHost = flag.String("h", "localhost:22", "Host:Port")
scpKey = flag.String("k", "", "Key")
filePrefix = flag.String("p", "log-", "Filename prefix")
)
func init() {
flag.Parse()
}
func main() {
log := ""
reader := bufio.NewReader(os.Stdin)
for {
time.Sleep(1 * time.Microsecond)
line, err := reader.ReadString('\n')
if err != nil {
xlog.Error(err.Error())
} else {
log += line
fmt.Printf("%d\r", len(log))
if len(log) >= *bufferLimit {
l := []byte(log)
go gzipAndSend(l)
log = ""
}
}
}
}
func gzipAndSend(l []byte) {
var b bytes.Buffer
fmt.Printf("\nSending buffer ...\n")
w := gzip.NewWriter(&b)
w.Write(l)
w.Close()
r := bufio.NewReader(&b)
clientConfig, _ := auth.PrivateKey(*scpUser, *scpKey, ssh.InsecureIgnoreHostKey())
client := goscp.NewClient(*scpHost, &clientConfig)
err := client.Connect()
if err != nil {
fmt.Printf(err.Error() + "\n")
return
}
t := time.Now()
date := t.Format("20060102150405")
client.CopyFile(r, *filePrefix+date+".gz", "0644")
fmt.Printf("Buffer sent\n")
}