Skip to content

Commit

Permalink
fix,feat: support custom log path and fix logging leak in hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
aymanbagabas committed Jul 12, 2023
1 parent 91a4b2f commit bdd174d
Show file tree
Hide file tree
Showing 8 changed files with 61 additions and 23 deletions.
17 changes: 0 additions & 17 deletions cmd/soft/hook.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import (
"path/filepath"
"strings"

"github.com/charmbracelet/log"
"github.com/charmbracelet/soft-serve/server/backend"
"github.com/charmbracelet/soft-serve/server/config"
"github.com/charmbracelet/soft-serve/server/db"
Expand All @@ -37,35 +36,19 @@ var (
}

ctx = config.WithContext(ctx, cfg)

logPath := filepath.Join(cfg.DataPath, "log", "hooks.log")
f, err := os.OpenFile(logPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return fmt.Errorf("opening file: %w", err)
}

ctx = context.WithValue(ctx, logFileCtxKey, f)
logger := log.FromContext(ctx)
logger.SetOutput(f)
ctx = log.WithContext(ctx, logger)
cmd.SetContext(ctx)
db, err := db.Open(ctx, cfg.DB.Driver, cfg.DB.DataSource)
if err != nil {
return fmt.Errorf("open database: %w", err)
}

// Set up the backend
// TODO: support other backends
sb := backend.New(ctx, cfg, db)
ctx = backend.WithContext(ctx, sb)
cmd.SetContext(ctx)

return nil
},
PersistentPostRunE: func(cmd *cobra.Command, _ []string) error {
f := cmd.Context().Value(logFileCtxKey).(*os.File)
return f.Close()
},
}

hooksRunE = func(cmd *cobra.Command, args []string) error {
Expand Down
26 changes: 21 additions & 5 deletions cmd/soft/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,20 +57,27 @@ func init() {
}

func main() {
logger := newDefaultLogger()
logger, f, err := newDefaultLogger()
if err != nil {
log.Errorf("failed to create logger: %v", err)
}

if f != nil {
defer f.Close() // nolint: errcheck
}

// Set global logger
log.SetDefault(logger)

var opts []maxprocs.Option
if config.IsVerbose() {
opts = append(opts, maxprocs.Logger(logger.Debugf))
opts = append(opts, maxprocs.Logger(log.Debugf))
}

// Set the max number of processes to the number of CPUs
// This is useful when running soft serve in a container
if _, err := maxprocs.Set(opts...); err != nil {
logger.Warn("couldn't set automaxprocs", "error", err)
log.Warn("couldn't set automaxprocs", "error", err)
}

ctx := log.WithContext(context.Background(), logger)
Expand All @@ -80,7 +87,7 @@ func main() {
}

// newDefaultLogger returns a new logger with default settings.
func newDefaultLogger() *log.Logger {
func newDefaultLogger() (*log.Logger, *os.File, error) {
dp := config.DataPath()
cfg, err := config.ParseConfig(filepath.Join(dp, "config.yaml"))
if err != nil {
Expand Down Expand Up @@ -111,5 +118,14 @@ func newDefaultLogger() *log.Logger {
logger.SetFormatter(log.TextFormatter)
}

return logger
var f *os.File
if cfg.Log.Path != "" {
f, err = os.OpenFile(cfg.Log.Path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return nil, nil, err
}
logger.SetOutput(f)
}

return logger, f, nil
}
26 changes: 26 additions & 0 deletions cmd/soft/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,18 @@ import (
"time"

"github.com/charmbracelet/soft-serve/server"
"github.com/charmbracelet/soft-serve/server/backend"
"github.com/charmbracelet/soft-serve/server/config"
"github.com/charmbracelet/soft-serve/server/db"
"github.com/charmbracelet/soft-serve/server/db/migrate"
"github.com/charmbracelet/soft-serve/server/hooks"
"github.com/spf13/cobra"
)

var (
autoMigrate bool
rollback bool
initHooks bool

serveCmd = &cobra.Command{
Use: "serve",
Expand Down Expand Up @@ -69,6 +72,13 @@ var (
return fmt.Errorf("start server: %w", err)
}

if initHooks {
be := backend.New(ctx, cfg, db)
if err := initializeHooks(ctx, cfg, be); err != nil {
return fmt.Errorf("initialize hooks: %w", err)
}
}

done := make(chan os.Signal, 1)
lch := make(chan error, 1)
go func() {
Expand All @@ -95,5 +105,21 @@ var (
func init() {
serveCmd.Flags().BoolVarP(&autoMigrate, "auto-migrate", "", false, "automatically run database migrations")
serveCmd.Flags().BoolVarP(&rollback, "rollback", "", false, "rollback the last database migration")
serveCmd.Flags().BoolVarP(&initHooks, "init-hooks", "", false, "initialize the hooks directory and update hooks for all repositories")
rootCmd.AddCommand(serveCmd)
}

func initializeHooks(ctx context.Context, cfg *config.Config, be *backend.Backend) error {
repos, err := be.Repositories(ctx)
if err != nil {
return err
}

for _, repo := range repos {
if err := hooks.GenerateHooks(ctx, cfg, repo.Name()); err != nil {
return err
}
}

return nil
}
4 changes: 4 additions & 0 deletions server/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,10 @@ type LogConfig struct {
// Time format for the log `ts` field.
// Format must be described in Golang's time format.
TimeFormat string `env:"TIME_FORMAT" yaml:"time_format"`

// Path to a file to write logs to.
// If not set, logs will be written to stderr.
Path string `env:"PATH" yaml:"path"`
}

// DBConfig is the database connection configuration.
Expand Down
2 changes: 2 additions & 0 deletions server/config/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ log:
# Time format for the log "timestamp" field.
# Should be described in Golang's time format.
time_format: "{{ .Log.TimeFormat }}"
# Path to the log file. Leave empty to write to stderr.
#path: "{{ .Log.Path }}"
# The SSH server configuration.
ssh:
Expand Down
1 change: 1 addition & 0 deletions server/daemon/daemon.go
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,7 @@ func (d *GitDaemon) handleClient(conn net.Conn) {
"SOFT_SERVE_REPO_NAME=" + name,
"SOFT_SERVE_REPO_PATH=" + filepath.Join(reposDir, repo),
"SOFT_SERVE_HOST=" + host,
"SOFT_SERVE_LOG_PATH=" + filepath.Join(d.cfg.DataPath, "log", "hooks.log"),
}

// Add git protocol environment variable.
Expand Down
1 change: 1 addition & 0 deletions server/ssh/ssh.go
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,7 @@ func (ss *SSHServer) Middleware(cfg *config.Config) wish.Middleware {
"SOFT_SERVE_REPO_PATH=" + filepath.Join(reposDir, repo),
"SOFT_SERVE_PUBLIC_KEY=" + ak,
"SOFT_SERVE_USERNAME=" + s.User(),
"SOFT_SERVE_LOG_PATH=" + filepath.Join(cfg.DataPath, "log", "hooks.log"),
}

// Add ssh session & config environ
Expand Down
7 changes: 6 additions & 1 deletion server/web/git.go
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@ func withAccess(fn http.HandlerFunc) http.HandlerFunc {

func serviceRpc(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
cfg := config.FromContext(ctx)
logger := log.FromContext(ctx)
service, dir, repo := git.Service(pat.Param(r, "service")), pat.Param(r, "dir"), pat.Param(r, "repo")

Expand Down Expand Up @@ -252,7 +253,11 @@ func serviceRpc(w http.ResponseWriter, r *http.Request) {
}

if len(version) != 0 {
cmd.Env = append(cmd.Env, fmt.Sprintf("GIT_PROTOCOL=%s", version))
cmd.Env = append(cmd.Env, []string{
// TODO: add the rest of env vars when we support pushing using http
"SOFT_SERVE_LOG_PATH=" + filepath.Join(cfg.DataPath, "log", "hooks.log"),
fmt.Sprintf("GIT_PROTOCOL=%s", version),
}...)
}

// Handle gzip encoding
Expand Down

0 comments on commit bdd174d

Please sign in to comment.