7 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
14 // Timestamper is the signature for a function that takes a timestamp and
15 // return a formated string value.
16 type Timestamper func(t time.Time) string
20 // ThrottledLogger.Logger -> ThrottledLogger.Write ->
21 // ThrottledLogger.buf -> ThrottledLogger.flusher -> goWriter ->
22 // ArvLogWriter.Write -> CollectionFileWriter.Write | Api.Create
24 // For stdout/stderr ReadWriteLines additionally runs as a goroutine to pull
25 // data from the stdout/stderr Reader and send to the Logger.
27 // ThrottledLogger accepts writes, prepends a timestamp to each line of the
28 // write, and periodically flushes to a downstream writer. It supports the
29 // "Logger" and "WriteCloser" interfaces.
30 type ThrottledLogger struct {
41 // RFC3339NanoFixed is a fixed-width version of time.RFC3339Nano.
42 const RFC3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00"
44 // RFC3339Timestamp formats t as RFC3339NanoFixed.
45 func RFC3339Timestamp(t time.Time) string {
46 return t.Format(RFC3339NanoFixed)
49 // Write to the internal buffer. Prepend a timestamp to each line of the input
51 func (tl *ThrottledLogger) Write(p []byte) (n int, err error) {
54 tl.buf = &bytes.Buffer{}
56 defer tl.Mutex.Unlock()
58 now := tl.Timestamper(time.Now().UTC())
59 sc := bufio.NewScanner(bytes.NewBuffer(p))
61 _, err = fmt.Fprintf(tl.buf, "%s %s\n", now, sc.Text())
62 if tl.Immediate != nil {
63 tl.Immediate.Printf("%s %s\n", now, sc.Text())
69 // Periodically check the current buffer; if not empty, send it on the
70 // channel to the goWriter goroutine.
71 func (tl *ThrottledLogger) flusher() {
72 bufchan := make(chan *bytes.Buffer)
73 bufterm := make(chan bool)
75 // Use a separate goroutine for the actual write so that the writes are
76 // actually initiated closer every 1s instead of every
77 // 1s + (time to it takes to write).
78 go goWriter(tl.writer, bufchan, bufterm)
81 time.Sleep(1 * time.Second)
84 if tl.buf != nil && tl.buf.Len() > 0 {
98 tl.flusherDone <- true
101 // Receive buffers from a channel and send to the underlying Writer
102 func goWriter(writer io.Writer, c <-chan *bytes.Buffer, t chan<- bool) {
104 writer.Write(b.Bytes())
109 // Close the flusher goroutine and wait for it to complete, then close the
110 // underlying Writer.
111 func (tl *ThrottledLogger) Close() error {
114 return tl.writer.Close()
118 // MaxLogLine is the maximum length of stdout/stderr lines before they are split.
122 // ReadWriteLines reads lines from a reader and writes to a Writer, with long
124 func ReadWriteLines(in io.Reader, writer io.Writer, done chan<- bool) {
125 reader := bufio.NewReaderSize(in, MaxLogLine)
128 line, isPrefix, err := reader.ReadLine()
131 } else if err != nil {
132 writer.Write([]byte(fmt.Sprintln("error reading container log:", err)))
139 if prefix == "" && suffix == "" {
142 writer.Write([]byte(fmt.Sprint(prefix, string(line), suffix)))
145 // Set up prefix for following line
155 // NewThrottledLogger creates a new thottled logger that
156 // (a) prepends timestamps to each line
157 // (b) batches log messages and only calls the underlying Writer at most once
159 func NewThrottledLogger(writer io.WriteCloser) *ThrottledLogger {
160 alw := &ThrottledLogger{}
161 alw.flusherDone = make(chan bool)
163 alw.Logger = log.New(alw, "", 0)
164 alw.Timestamper = RFC3339Timestamp
169 // ArvLogWriter implements a writer that writes to each of a WriteCloser
170 // (typically CollectionFileWriter) and creates an API server log entry.
171 type ArvLogWriter struct {
172 ArvClient IArvadosClient
175 writeCloser io.WriteCloser
178 func (arvlog *ArvLogWriter) Write(p []byte) (n int, err error) {
179 // Write to the next writer in the chain (a file in Keep)
181 if arvlog.writeCloser != nil {
182 _, err1 = arvlog.writeCloser.Write(p)
186 lr := arvadosclient.Dict{"log": arvadosclient.Dict{
187 "object_uuid": arvlog.UUID,
188 "event_type": arvlog.loggingStream,
189 "properties": map[string]string{"text": string(p)}}}
190 err2 := arvlog.ArvClient.Create("logs", lr, nil)
192 if err1 != nil || err2 != nil {
193 return 0, fmt.Errorf("%s ; %s", err1, err2)
198 // Close the underlying writer
199 func (arvlog *ArvLogWriter) Close() (err error) {
200 if arvlog.writeCloser != nil {
201 err = arvlog.writeCloser.Close()
202 arvlog.writeCloser = nil