added zerolog

This commit is contained in:
2023-01-03 20:09:02 -06:00
parent 9d07298eb0
commit 6b85913316
5 changed files with 118 additions and 50 deletions

View File

@ -24,10 +24,44 @@ type Host struct {
}
type Command struct {
Remote bool
Remote bool
// command to run
Cmd string
// host on which to run cmd
Host string
/*
Shell specifies which shell to run the command in, if any
Not applicable when host is defined
*/
Shell string
RemoteHost Host
Cmd string
Args []string
// cmdArgs is an array that holds the arguments to cmd
CmdArgs []string
}
type BackyConfigFile struct {
/*
Cmds holds the commands for a list
key is the name of the command
*/
Cmds map[string]Command
/*
CmdLists holds the lists of commands to be run in order
key is the command list name
*/
CmdLists map[string][]string
/*
Hosts holds the Host config
key is the host
*/
Hosts map[string]Host
}
// BackupConfig is a configuration struct that is used to define backups
@ -43,12 +77,12 @@ type BackupConfig struct {
* Runs a backup configuration
*/
func (command Command) runCmd() logging.Logging {
func (command Command) RunCmd() logging.Logging {
var stdoutBuf, stderrBuf bytes.Buffer
var err error
var cmdArgs string
for _, v := range command.Args {
for _, v := range command.CmdArgs {
cmdArgs += v
}
@ -71,7 +105,7 @@ func (command Command) runCmd() logging.Logging {
defer s.Close()
cmd := command.Cmd
for _, a := range command.Args {
for _, a := range command.CmdArgs {
cmd += " " + a
}
@ -87,7 +121,7 @@ func (command Command) runCmd() logging.Logging {
// fmt.Printf("Output: %s\n", string(output))
} else {
// shell := "/bin/bash"
localCMD := exec.Command(command.Cmd, command.Args...)
localCMD := exec.Command(command.Cmd, command.CmdArgs...)
localCMD.Stdout = io.MultiWriter(os.Stdout, &stdoutBuf)
localCMD.Stderr = io.MultiWriter(os.Stderr, &stderrBuf)
err = localCMD.Run()
@ -108,3 +142,13 @@ func (command Command) runCmd() logging.Logging {
func New() BackupConfig {
return BackupConfig{}
}
// NewConfig initializes new config that holds information
// from the config file
func NewConfig() *BackyConfigFile {
return &BackyConfigFile{
Cmds: make(map[string]Command),
CmdLists: make(map[string][]string),
Hosts: make(map[string]Host),
}
}

View File

@ -3,7 +3,6 @@ package backy
import (
"errors"
"fmt"
"log"
"os"
"os/user"
"path/filepath"
@ -11,8 +10,10 @@ import (
"time"
"github.com/kevinburke/ssh_config"
"github.com/rs/zerolog"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/knownhosts"
"gopkg.in/natefinch/lumberjack.v2"
)
type SshConfig struct {
@ -53,6 +54,44 @@ func (config SshConfig) GetSSHConfig() (SshConfig, error) {
}
func (remoteConfig *Host) ConnectToSSHHost() (*ssh.Client, error) {
output := zerolog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.RFC3339}
output.FormatLevel = func(i interface{}) string {
return strings.ToUpper(fmt.Sprintf("| %-6s|", i))
}
output.FormatMessage = func(i interface{}) string {
return fmt.Sprintf("%s", i)
}
output.FormatFieldName = func(i interface{}) string {
return fmt.Sprintf("%s: ", i)
}
output.FormatFieldValue = func(i interface{}) string {
return strings.ToUpper(fmt.Sprintf("%s", i))
}
fileLogger := &lumberjack.Logger{
Filename: "./backy.log",
MaxSize: 500, // megabytes
MaxBackups: 3,
MaxAge: 28, //days
Compress: true, // disabled by default
}
// fileOutput := zerolog.ConsoleWriter{Out: fileLogger, TimeFormat: time.RFC3339}
// fileOutput.FormatLevel = func(i interface{}) string {
// return strings.ToUpper(fmt.Sprintf("| %-6s|", i))
// }
// fileOutput.FormatMessage = func(i interface{}) string {
// return fmt.Sprintf("%s", i)
// }
// fileOutput.FormatFieldName = func(i interface{}) string {
// return fmt.Sprintf("%s: ", i)
// }
// fileOutput.FormatFieldValue = func(i interface{}) string {
// return strings.ToUpper(fmt.Sprintf("%s", i))
// }
zerolog.TimeFieldFormat = time.RFC1123
writers := zerolog.MultiLevelWriter(os.Stdout, fileLogger)
log := zerolog.New(writers).With().Timestamp().Logger()
var sshClient *ssh.Client
var connectErr error
@ -92,35 +131,32 @@ func (remoteConfig *Host) ConnectToSSHHost() (*ssh.Client, error) {
port = "22"
}
remoteConfig.HostName[index] = hostName + ":" + port
println("HostName: " + remoteConfig.HostName[0])
}
}
// TODO: Add value/option to config for host key and add bool to check for host key
hostKeyCallback, err := knownhosts.New(khPath)
if err != nil {
log.Fatal("could not create hostkeycallback function: ", err)
log.Fatal().Err(err).Msg("could not create hostkeycallback function")
}
privateKey, err := os.ReadFile(remoteConfig.PrivateKeyPath)
if err != nil {
return nil, fmt.Errorf("read private key error: %w", err)
log.Fatal().Err(err).Msg("read private key error")
}
signer, err := ssh.ParsePrivateKey(privateKey)
if err != nil {
return nil, fmt.Errorf("parse private key error: %w", err)
log.Fatal().Err(err).Msg("parse private key error")
}
sshConfig := &ssh.ClientConfig{
User: remoteConfig.User,
Auth: []ssh.AuthMethod{ssh.PublicKeys(signer)},
HostKeyCallback: hostKeyCallback,
Timeout: 5 * time.Second,
}
for _, host := range remoteConfig.HostName {
println("Connecting to " + host)
log.Info().Msgf("Connecting to host %s", host)
sshClient, connectErr = ssh.Dial("tcp", host, sshConfig)
if connectErr != nil {
panic(fmt.Errorf("error when connecting to host %s: %w", host, connectErr))
log.Fatal().Err(connectErr).Str("host", host).Msg("error when connecting to host")
}
}
break

View File

@ -1,14 +1,5 @@
package logging
import (
"errors"
"fmt"
"log/syslog"
"os"
"github.com/spf13/viper"
)
type Logging struct {
Err error
Output string
@ -17,28 +8,3 @@ type Logging struct {
type Logfile struct {
LogfilePath string
}
func OpenLogFile(config *viper.Viper) (interface{}, error) {
var logFile *os.File
var syslogWriter *syslog.Writer
var err error
logType := config.GetString("global.logging.type")
if logType != "" {
switch logType {
case "file":
logFile, err = os.OpenFile(config.GetString("global.logging.file"), os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
if err != nil {
return nil, err
}
return logFile, nil
case "syslog":
syslogWriter, err = syslog.New(syslog.LOG_SYSLOG, "Backy")
if err != nil {
return nil, fmt.Errorf("Unable to set logfile: " + err.Error())
}
return syslogWriter, nil
}
}
return nil, errors.New("log type not specified; Please set global.logging.type in your config file")
}