Skip to content

Commit

Permalink
added bbolt fetch logs
Browse files Browse the repository at this point in the history
  • Loading branch information
ivcosla committed Aug 20, 2019
1 parent c0b37d5 commit 9ca33f9
Showing 1 changed file with 47 additions and 2 deletions.
49 changes: 47 additions & 2 deletions pkg/app/log.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,24 @@
package app

import (
"bytes"
"fmt"
"log"
"time"

"go.etcd.io/bbolt"
)

// LogStore stores logs from apps, for later consumption from the hypervisor
type LogStore interface {

// Store saves given log in db
Store(t time.Time, string) error

// LogSince returns the logs since given timestamp. For optimal performance,
// the timestamp should exist in the store (you can get it from previous logs),
// otherwise the DB will be sequentially iterated until finding entries older than given timestamp
LogsSince(t time.Time) ([]string, error)
}

type boltDBappLogs struct {
Expand Down Expand Up @@ -36,6 +47,40 @@ func newBoltDB(path, appName string) (LogStore, error) {
return &boltDBappLogs{db, b}, nil
}

func (l *boltDBappLogs) LogsSince(time time.Time) ([]string, error) {
err := l.db.View()
// LogSince implements LogStore
func (l *boltDBappLogs) LogsSince(t time.Time) ([]string, error) {
logs := make([]string, 0)

err := l.db.View(func(tx *bbolt.Tx) error {
b := tx.Bucket(l.bucket)

c := b.Cursor()
if k, _ := c.Seek([]byte(t.Format(time.RFC3339))); k != nil {
iterateFromKey(c, logs)
} else {
iterateFromBeginning(c, t, logs)
}

return nil
})

return logs, err
}

func iterateFromKey(c *bbolt.Cursor, logs []string) {
for k, v := c.Next(); k != nil; k, v = c.Next() {
logs = append(logs, fmt.Sprintf("%s-%s", string(k), string(v)))
}
}

func iterateFromBeginning(c *bbolt.Cursor, t time.Time, logs []string) {
parsedT := []byte(t.UTC().Format(time.RFC3339))

for k, v := c.First(); k != nil; k, v = c.Next() {
if bytes.Compare(parsedT, k) < 0 {
continue
}

logs = append(logs, fmt.Sprintf("%s-%s", string(k), string(v)))
}
}

0 comments on commit 9ca33f9

Please sign in to comment.