Semaphore/services/tasks/TaskRunner_logging.go

88 lines
1.7 KiB
Go
Raw Normal View History

package tasks
import (
"bufio"
2016-05-01 13:24:09 +02:00
"encoding/json"
"fmt"
"os/exec"
"time"
"github.com/ansible-semaphore/semaphore/api/sockets"
"github.com/ansible-semaphore/semaphore/util"
log "github.com/sirupsen/logrus"
)
func (t *TaskRunner) Log2(msg string, now time.Time) {
2016-04-17 12:41:36 +02:00
for _, user := range t.users {
2016-05-01 13:24:09 +02:00
b, err := json.Marshal(&map[string]interface{}{
"type": "log",
2016-05-08 11:36:17 +02:00
"output": msg,
"time": now,
"task_id": t.Task.ID,
"project_id": t.Task.ProjectID,
2016-05-01 13:24:09 +02:00
})
util.LogPanic(err)
2016-05-01 13:24:09 +02:00
sockets.Message(user, b)
2016-04-17 12:41:36 +02:00
}
t.pool.logger <- logRecord{
task: t,
output: msg,
time: now,
}
}
func (t *TaskRunner) Log(msg string) {
t.Log2(msg, time.Now())
}
func (t *TaskRunner) Logf(format string, a ...any) {
t.Log2(fmt.Sprintf(format, a...), time.Now())
}
// Readln reads from the pipe
2017-07-12 04:08:00 +02:00
func Readln(r *bufio.Reader) (string, error) {
var (
isPrefix = true
err error
2017-07-12 04:08:00 +02:00
line, ln []byte
)
for isPrefix && err == nil {
line, isPrefix, err = r.ReadLine()
ln = append(ln, line...)
}
2017-07-12 04:08:00 +02:00
return string(ln), err
}
func (t *TaskRunner) logPipe(reader *bufio.Reader) {
2017-07-12 04:08:00 +02:00
line, err := Readln(reader)
for err == nil {
t.Log(line)
line, err = Readln(reader)
}
2017-07-12 04:08:00 +02:00
if err != nil && err.Error() != "EOF" {
2022-03-13 16:11:29 +01:00
//don't panic on these errors, sometimes it throws not dangerous "read |0: file already closed" error
util.LogWarningWithFields(err, log.Fields{"error": "Failed to read TaskRunner output"})
2017-07-12 04:08:00 +02:00
}
}
func (t *TaskRunner) LogCmd(cmd *exec.Cmd) {
stderr, _ := cmd.StderrPipe()
stdout, _ := cmd.StdoutPipe()
2017-07-12 04:08:00 +02:00
go t.logPipe(bufio.NewReader(stderr))
go t.logPipe(bufio.NewReader(stdout))
}
func (t *TaskRunner) panicOnError(err error, msg string) {
if err != nil {
t.Log(msg)
util.LogPanicWithFields(err, log.Fields{"error": msg})
}
}