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 prepends a timestamp to each line of the input data and
50 // appends to the internal buffer. Each line is also logged to
51 // tl.Immediate, if tl.Immediate is not nil.
52 func (tl *ThrottledLogger) Write(p []byte) (n int, err error) {
55 tl.buf = &bytes.Buffer{}
57 defer tl.Mutex.Unlock()
59 now := tl.Timestamper(time.Now().UTC())
60 sc := bufio.NewScanner(bytes.NewBuffer(p))
61 for err == nil && sc.Scan() {
62 out := fmt.Sprintf("%s %s\n", now, sc.Bytes())
63 if tl.Immediate != nil {
64 tl.Immediate.Print(out[:len(out)-1])
66 _, err = io.WriteString(tl.buf, out)
77 // Periodically check the current buffer; if not empty, send it on the
78 // channel to the goWriter goroutine.
79 func (tl *ThrottledLogger) flusher() {
80 bufchan := make(chan *bytes.Buffer)
81 bufterm := make(chan bool)
83 // Use a separate goroutine for the actual write so that the writes are
84 // actually initiated closer every 1s instead of every
85 // 1s + (time to it takes to write).
86 go goWriter(tl.writer, bufchan, bufterm)
89 time.Sleep(1 * time.Second)
92 if tl.buf != nil && tl.buf.Len() > 0 {
106 tl.flusherDone <- true
109 // Receive buffers from a channel and send to the underlying Writer
110 func goWriter(writer io.Writer, c <-chan *bytes.Buffer, t chan<- bool) {
112 writer.Write(b.Bytes())
117 // Close the flusher goroutine and wait for it to complete, then close the
118 // underlying Writer.
119 func (tl *ThrottledLogger) Close() error {
122 return tl.writer.Close()
126 // MaxLogLine is the maximum length of stdout/stderr lines before they are split.
130 // ReadWriteLines reads lines from a reader and writes to a Writer, with long
132 func ReadWriteLines(in io.Reader, writer io.Writer, done chan<- bool) {
133 reader := bufio.NewReaderSize(in, MaxLogLine)
136 line, isPrefix, err := reader.ReadLine()
139 } else if err != nil {
140 writer.Write([]byte(fmt.Sprintln("error reading container log:", err)))
147 if prefix == "" && suffix == "" {
150 writer.Write([]byte(fmt.Sprint(prefix, string(line), suffix)))
153 // Set up prefix for following line
163 // NewThrottledLogger creates a new thottled logger that
164 // (a) prepends timestamps to each line
165 // (b) batches log messages and only calls the underlying Writer at most once
167 func NewThrottledLogger(writer io.WriteCloser) *ThrottledLogger {
168 tl := &ThrottledLogger{}
169 tl.flusherDone = make(chan bool)
171 tl.Logger = log.New(tl, "", 0)
172 tl.Timestamper = RFC3339Timestamp
177 // ArvLogWriter is an io.WriteCloser that processes each write by
178 // writing it through to another io.WriteCloser (typically a
179 // CollectionFileWriter) and creating an Arvados log entry.
180 type ArvLogWriter struct {
181 ArvClient IArvadosClient
184 writeCloser io.WriteCloser
187 func (arvlog *ArvLogWriter) Write(p []byte) (n int, err error) {
188 // Write to the next writer in the chain (a file in Keep)
190 if arvlog.writeCloser != nil {
191 _, err1 = arvlog.writeCloser.Write(p)
195 lr := arvadosclient.Dict{"log": arvadosclient.Dict{
196 "object_uuid": arvlog.UUID,
197 "event_type": arvlog.loggingStream,
198 "properties": map[string]string{"text": string(p)}}}
199 err2 := arvlog.ArvClient.Create("logs", lr, nil)
201 if err1 != nil || err2 != nil {
202 return 0, fmt.Errorf("%s ; %s", err1, err2)
207 // Close the underlying writer
208 func (arvlog *ArvLogWriter) Close() (err error) {
209 if arvlog.writeCloser != nil {
210 err = arvlog.writeCloser.Close()
211 arvlog.writeCloser = nil