1
0
mirror of https://github.com/nxshock/gron.git synced 2024-11-27 03:41:00 +05:00

Merge JobConfig to Job structure

This commit is contained in:
nxshock 2022-03-29 19:45:31 +05:00
parent 15142efdd4
commit 8784211f7b
4 changed files with 32 additions and 66 deletions

View File

@ -60,12 +60,12 @@ func handleForceStart(w http.ResponseWriter, r *http.Request) {
for _, jobEntry := range jobEntries { for _, jobEntry := range jobEntries {
job := jobEntry.Job.(*Job) job := jobEntry.Job.(*Job)
if job.FileName == jobName { if job.Name == jobName {
host, _, err := net.SplitHostPort(r.RemoteAddr) host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil { if err != nil {
host = r.RemoteAddr host = r.RemoteAddr
} }
log.WithField("job", "http_server").Printf("forced start %s from %s", job.FileName, host) log.WithField("job", "http_server").Printf("forced start %s from %s", job.Name, host)
go job.Run() go job.Run()
time.Sleep(time.Second / 4) // wait some time for job start time.Sleep(time.Second / 4) // wait some time for job start
http.Redirect(w, r, "/", http.StatusTemporaryRedirect) http.Redirect(w, r, "/", http.StatusTemporaryRedirect)

50
job.go
View File

@ -14,20 +14,17 @@ import (
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
// JobConfig is a TOML representation of job
type JobConfig struct { type JobConfig struct {
Cron string Cron string // cron decription
Command string Command string // command for execution
Description string Description string // job description
} }
type Job struct { type Job struct {
Name string // from filename Name string // from filename
Cron string // cron decription JobConfig
Command string // command for execution
Params []string // command params
FileName string // short job name
Description string // job description
// Fields for stats // Fields for stats
CurrentRunningCount int CurrentRunningCount int
@ -48,15 +45,9 @@ func readJob(filePath string) (*Job, error) {
return nil, err return nil, err
} }
command, params := parseCommand(jobConfig.Command)
job := &Job{ job := &Job{
Name: strings.TrimSuffix(filepath.Base(filePath), filepath.Ext(filePath)), Name: strings.TrimSuffix(filepath.Base(filePath), filepath.Ext(filePath)),
Cron: jobConfig.Cron, JobConfig: jobConfig}
Command: command,
Params: params,
FileName: strings.TrimSuffix(filepath.Base(filePath), filepath.Ext(filepath.Base(filePath))),
Description: jobConfig.Description}
return job, nil return job, nil
} }
@ -67,6 +58,21 @@ func (js *JobConfig) Write() {
ioutil.WriteFile("job.conf", buf.Bytes(), 0644) ioutil.WriteFile("job.conf", buf.Bytes(), 0644)
} }
func (j *Job) CommandAndParams() (command string, params []string) {
quoted := false
items := strings.FieldsFunc(j.JobConfig.Command, func(r rune) bool {
if r == '"' {
quoted = !quoted
}
return !quoted && r == ' '
})
for i := range items {
items[i] = strings.Trim(items[i], `"`)
}
return items[0], items[1:]
}
func (j *Job) Run() { func (j *Job) Run() {
startTime := time.Now() startTime := time.Now()
@ -75,7 +81,7 @@ func (j *Job) Run() {
j.LastStartTime = startTime.Format(config.TimeFormat) j.LastStartTime = startTime.Format(config.TimeFormat)
globalMutex.Unlock() globalMutex.Unlock()
jobLogFile, _ := os.OpenFile(filepath.Join(config.LogFilesPath, j.FileName+".txt"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644) jobLogFile, _ := os.OpenFile(filepath.Join(config.LogFilesPath, j.Name+".txt"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
defer jobLogFile.Close() defer jobLogFile.Close()
defer jobLogFile.WriteString("\n") defer jobLogFile.WriteString("\n")
@ -83,17 +89,19 @@ func (j *Job) Run() {
l.SetOutput(jobLogFile) l.SetOutput(jobLogFile)
l.SetFormatter(log.StandardLogger().Formatter) l.SetFormatter(log.StandardLogger().Formatter)
log.WithField("job", j.FileName).Info("started") log.WithField("job", j.Name).Info("started")
l.Info("started") l.Info("started")
cmd := exec.Command(j.Command, j.Params...) command, params := j.CommandAndParams()
cmd := exec.Command(command, params...)
cmd.Stdout = jobLogFile cmd.Stdout = jobLogFile
cmd.Stderr = jobLogFile cmd.Stderr = jobLogFile
err := cmd.Run() err := cmd.Run()
if err != nil { if err != nil {
log.WithField("job", j.FileName).Error(err.Error()) log.WithField("job", j.Name).Error(err.Error())
l.WithField("job", j.FileName).Error(err.Error()) l.WithField("job", j.Name).Error(err.Error())
globalMutex.Lock() globalMutex.Lock()
j.LastError = err.Error() j.LastError = err.Error()
@ -105,7 +113,7 @@ func (j *Job) Run() {
} }
endTime := time.Now() endTime := time.Now()
log.WithField("job", j.FileName).Infof("finished (%s)", endTime.Sub(startTime).Truncate(time.Second).String()) log.WithField("job", j.Name).Infof("finished (%s)", endTime.Sub(startTime).Truncate(time.Second).String())
l.Infof("finished (%s)", endTime.Sub(startTime).Truncate(time.Second).String()) l.Infof("finished (%s)", endTime.Sub(startTime).Truncate(time.Second).String())
globalMutex.Lock() globalMutex.Lock()

View File

@ -1,22 +0,0 @@
package main
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestReadJob(t *testing.T) {
expectedJob := &Job{
Name: "job",
Cron: "* * * * *",
Command: "command",
Params: []string{"param1 param1", "param2"},
FileName: "job",
Description: "comment"}
job, err := readJob("tests/job.conf")
assert.NoError(t, err)
assert.Equal(t, expectedJob, job)
}

View File

@ -1,20 +0,0 @@
package main
import (
"strings"
)
func parseCommand(s string) (command string, params []string) {
quoted := false
items := strings.FieldsFunc(s, func(r rune) bool {
if r == '"' {
quoted = !quoted
}
return !quoted && r == ' '
})
for i := range items {
items[i] = strings.Trim(items[i], `"`)
}
return items[0], items[1:]
}