Skip to content

Commit

Permalink
chore: refactor, filelogger
Browse files Browse the repository at this point in the history
  • Loading branch information
Adis Durakovic committed Mar 13, 2024
1 parent 6b8ec56 commit 1e99a33
Show file tree
Hide file tree
Showing 6 changed files with 179 additions and 82 deletions.
79 changes: 79 additions & 0 deletions internal/filelogger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package internal

import (
"encoding/json"
"os"
"path/filepath"
"time"

"github.com/adrg/xdg"
"github.com/charmbracelet/log"
)

func getPath() string {
return filepath.Join(xdg.CacheHome, "resticity")
}

func getFile(t string) string {
d := time.Now().Format("2006-01-02")
f := filepath.Join(getPath(), t+"_"+d+".log")
return f
}

func appendToFile(f string, m ChanMsg) {

if _, err := os.Stat(f); os.IsNotExist(err) {
_, err := os.Create(f)
if err != nil {
log.Error("filelogger: create "+f, "error", err)
return
}
}

d, err := json.Marshal(m)
if err != nil {
log.Error("filelogger: marshal "+f, "error", err)
return
}

if err := WriteFile(f, []byte(d)); err != nil {
log.Error("filelogger: write "+f, "error", err)
}

}

func WriteFile(name string, data []byte) error {
f, err := os.OpenFile(name, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
return err
}

defer f.Close()

if _, err = f.WriteString(string(data) + "\n"); err != nil {
return err
}
return nil
}

func NewFileLogger(outputChan *chan ChanMsg, errorChan *chan ChanMsg) {
if _, err := os.Stat(getPath()); os.IsNotExist(err) {
os.Mkdir(getPath(), 0755)
}
log.Info("filelogger", "path", getPath())
for {
select {
case o := <-*outputChan:
if os.Getenv("LOG_TO_FILE") == "true" {
f := getFile("logs")
appendToFile(f, o)
}
break
case e := <-*errorChan:
f := getFile("error")
appendToFile(f, e)
break
}

}
}
2 changes: 2 additions & 0 deletions internal/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,11 @@ func NewResticity() (Resticity, error) {

outputChan := make(chan ChanMsg)
errorChan := make(chan ChanMsg)
go NewFileLogger(&outputChan, &errorChan)
settings := NewSettings(flagArgs.ConfigFile)
restic := NewRestic(settings, &outputChan, &errorChan)
scheduler, err := NewScheduler(settings, restic, &outputChan, &errorChan)

return Resticity{flagArgs, outputChan, errorChan, settings, restic, scheduler}, err
}

Expand Down
8 changes: 4 additions & 4 deletions internal/restic.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"os"
"os/exec"
"strings"
"time"

"github.com/charmbracelet/log"
)
Expand Down Expand Up @@ -40,12 +41,11 @@ func (r *Restic) PipeOutErr(
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
go func(t string) {
msg := ChanMsg{Id: "", Msg: t}
msg := ChanMsg{Id: "", Msg: t, Time: time.Now()}
if job != nil {
msg.Id = job.Id
}
(*r.OutputCh) <- msg
log.Debug("pipeout", "out", t)
}(scanner.Text())

sout.WriteString(scanner.Text())
Expand All @@ -64,12 +64,11 @@ func (r *Restic) PipeOutErr(
for scanner.Scan() {

go func(t string) {
msg := ChanMsg{Id: "", Msg: t}
msg := ChanMsg{Id: "", Msg: t, Time: time.Now()}
if job != nil {
msg.Id = job.Id
}
(*r.OutputCh) <- msg
log.Debug("pipeout", "out", t)
}(scanner.Text())
serr.WriteString(scanner.Text())
}
Expand Down Expand Up @@ -199,6 +198,7 @@ func (r *Restic) RunSchedule(
if job == nil {
return
}
(*r.OutputCh) <- ChanMsg{Id: job.Schedule.Id, Msg: "{\"running\": true}", Time: time.Now()}
toRepository := r.settings.GetRepositoryById(job.Schedule.ToRepositoryId)
fromRepository := r.settings.GetRepositoryById(job.Schedule.FromRepositoryId)
backup := r.settings.GetBackupById(job.Schedule.BackupId)
Expand Down
32 changes: 20 additions & 12 deletions internal/scheduler.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@ type Job struct {
Force bool `json:"force"`
Ctx context.Context
Cancel context.CancelFunc
// OutChan chan string
// ErrChan chan string
}

type Scheduler struct {
Expand All @@ -29,8 +27,8 @@ type Scheduler struct {
Jobs []Job
jmu sync.Mutex
settings *Settings
outputCh *chan ChanMsg
errorCh *chan ChanMsg
OutputCh *chan ChanMsg
ErrorCh *chan ChanMsg
}

func NewScheduler(
Expand All @@ -43,8 +41,8 @@ func NewScheduler(
s := &Scheduler{}
s.settings = settings
s.restic = restic
s.outputCh = outch
s.errorCh = errch
s.OutputCh = outch
s.ErrorCh = errch
if gc, err := gocron.NewScheduler(); err == nil {
s.Gocron = gc
s.Gocron.Start()
Expand All @@ -58,7 +56,7 @@ func NewScheduler(
func (s *Scheduler) RunJobById(id string) {
for i, j := range s.Jobs {
if j.Id == id {
log.Debug("Running job manually", "id", id)
log.Info("Running job manually", "id", id)
s.Jobs[i].Force = true

if err := j.job.RunNow(); err != nil {
Expand All @@ -72,6 +70,7 @@ func (s *Scheduler) RunJobById(id string) {
func (s *Scheduler) StopJobById(id string) {
for _, j := range s.Jobs {
if j.Id == id {
(*s.OutputCh) <- ChanMsg{Id: j.Schedule.Id, Msg: "{\"running\": false}", Time: time.Now()}
j.Cancel()
break
}
Expand All @@ -83,8 +82,6 @@ func (s *Scheduler) DeleteRunningJob(id string) {
defer s.jmu.Unlock()
for i, j := range s.Jobs {
if j.Id == id {
msg := ChanMsg{Id: id, Msg: "{\"running\": false}"}
(*s.outputCh) <- msg

log.Debug("Stopping running job", "id", id)
s.Jobs[i].Running = false
Expand All @@ -110,9 +107,8 @@ func (s *Scheduler) SetRunningJob(id string) {
defer s.jmu.Unlock()
for i, j := range s.Jobs {
if j.Id == id {

s.Jobs[i].Running = true
msg := ChanMsg{Id: id, Msg: "{\"running\": true}"}
(*s.outputCh) <- msg
log.Debug("Setting forced running job", "id", id)

break
Expand Down Expand Up @@ -170,11 +166,20 @@ func (s *Scheduler) RescheduleBackups() {
gocron.WithEventListeners(
gocron.BeforeJobRuns(func(jobID uuid.UUID, jobName string) {

log.Debug("before job run", "id", jobName)
(*s.OutputCh) <- ChanMsg{Id: jobName, Msg: "{\"running\": true}", Time: time.Now()}

log.Debug(
"before job run",
"id",
jobName,
)
s.SetRunningJob(jobName)
}),
gocron.AfterJobRuns(
func(jobID uuid.UUID, jobName string) {

(*s.OutputCh) <- ChanMsg{Id: jobName, Msg: "{\"running\": false}", Time: time.Now()}

log.Debug("after job run", "res", "success", "id", jobName)
s.DeleteRunningJob(jobName)
s.RecreateCtx(jobName)
Expand All @@ -183,6 +188,9 @@ func (s *Scheduler) RescheduleBackups() {
),
gocron.AfterJobRunsWithError(
func(jobID uuid.UUID, jobName string, err error) {

(*s.OutputCh) <- ChanMsg{Id: jobName, Msg: "{\"running\": false}", Time: time.Now()}

log.Debug("after job run", "res", "error", "id", jobName, "err", err)
s.DeleteRunningJob(jobName)
s.RecreateCtx(jobName)
Expand Down
Loading

0 comments on commit 1e99a33

Please sign in to comment.