12 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
15 // Timestamper is the signature for a function that takes a timestamp and
16 // return a formated string value.
17 type Timestamper func(t time.Time) string
21 // ThrottledLogger.Logger -> ThrottledLogger.Write ->
22 // ThrottledLogger.buf -> ThrottledLogger.flusher ->
23 // ArvLogWriter.Write -> CollectionFileWriter.Write | Api.Create
25 // For stdout/stderr ReadWriteLines additionally runs as a goroutine to pull
26 // data from the stdout/stderr Reader and send to the Logger.
28 // ThrottledLogger accepts writes, prepends a timestamp to each line of the
29 // write, and periodically flushes to a downstream writer. It supports the
30 // "Logger" and "WriteCloser" interfaces.
31 type ThrottledLogger struct {
36 stopping chan struct{}
42 // RFC3339NanoFixed is a fixed-width version of time.RFC3339Nano.
43 const RFC3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00"
45 // RFC3339Timestamp formats t as RFC3339NanoFixed.
46 func RFC3339Timestamp(t time.Time) string {
47 return t.Format(RFC3339NanoFixed)
50 // Write prepends a timestamp to each line of the input data and
51 // appends to the internal buffer. Each line is also logged to
52 // tl.Immediate, if tl.Immediate is not nil.
53 func (tl *ThrottledLogger) Write(p []byte) (n int, err error) {
55 defer tl.Mutex.Unlock()
58 tl.buf = &bytes.Buffer{}
61 now := tl.Timestamper(time.Now().UTC())
62 sc := bufio.NewScanner(bytes.NewBuffer(p))
63 for err == nil && sc.Scan() {
64 out := fmt.Sprintf("%s %s\n", now, sc.Bytes())
65 if tl.Immediate != nil {
66 tl.Immediate.Print(out[:len(out)-1])
68 _, err = io.WriteString(tl.buf, out)
79 // Periodically check the current buffer; if not empty, send it on the
80 // channel to the goWriter goroutine.
81 func (tl *ThrottledLogger) flusher() {
82 ticker := time.NewTicker(time.Second)
84 for stopping := false; !stopping; {
87 // flush tl.buf, then exit the loop
92 var ready *bytes.Buffer
95 ready, tl.buf = tl.buf, nil
98 if ready != nil && ready.Len() > 0 {
99 tl.writer.Write(ready.Bytes())
105 // Close the flusher goroutine and wait for it to complete, then close the
106 // underlying Writer.
107 func (tl *ThrottledLogger) Close() error {
115 return tl.writer.Close()
119 // MaxLogLine is the maximum length of stdout/stderr lines before they are split.
123 // ReadWriteLines reads lines from a reader and writes to a Writer, with long
125 func ReadWriteLines(in io.Reader, writer io.Writer, done chan<- bool) {
126 reader := bufio.NewReaderSize(in, MaxLogLine)
129 line, isPrefix, err := reader.ReadLine()
132 } else if err != nil {
133 writer.Write([]byte(fmt.Sprintln("error reading container log:", err)))
140 if prefix == "" && suffix == "" {
143 writer.Write([]byte(fmt.Sprint(prefix, string(line), suffix)))
146 // Set up prefix for following line
156 // NewThrottledLogger creates a new thottled logger that
157 // (a) prepends timestamps to each line
158 // (b) batches log messages and only calls the underlying Writer at most once
160 func NewThrottledLogger(writer io.WriteCloser) *ThrottledLogger {
161 tl := &ThrottledLogger{}
162 tl.stopping = make(chan struct{})
163 tl.stopped = make(chan struct{})
165 tl.Logger = log.New(tl, "", 0)
166 tl.Timestamper = RFC3339Timestamp
171 // ArvLogWriter is an io.WriteCloser that processes each write by
172 // writing it through to another io.WriteCloser (typically a
173 // CollectionFileWriter) and creating an Arvados log entry.
174 type ArvLogWriter struct {
175 ArvClient IArvadosClient
178 writeCloser io.WriteCloser
181 func (arvlog *ArvLogWriter) Write(p []byte) (n int, err error) {
182 // Write to the next writer in the chain (a file in Keep)
184 if arvlog.writeCloser != nil {
185 _, err1 = arvlog.writeCloser.Write(p)
189 lr := arvadosclient.Dict{"log": arvadosclient.Dict{
190 "object_uuid": arvlog.UUID,
191 "event_type": arvlog.loggingStream,
192 "properties": map[string]string{"text": string(p)}}}
193 err2 := arvlog.ArvClient.Create("logs", lr, nil)
195 if err1 != nil || err2 != nil {
196 return 0, fmt.Errorf("%s ; %s", err1, err2)
201 // Close the underlying writer
202 func (arvlog *ArvLogWriter) Close() (err error) {
203 if arvlog.writeCloser != nil {
204 err = arvlog.writeCloser.Close()
205 arvlog.writeCloser = nil