-
Notifications
You must be signed in to change notification settings - Fork 7
/
logfilesaver.go
94 lines (77 loc) · 1.89 KB
/
logfilesaver.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"sync"
"github.com/screwdriver-cd/log-service/sduploader"
)
// storedLogLine is a representation of logs for permanent storage in the Store
type storedLogLine struct {
Time int64 `json:"t"`
Message string `json:"m"`
Line int `json:"n"`
StepName string `json:"s"`
}
type logFile struct {
lineCount int
savedLineCount int
mutex *sync.RWMutex
storePath string
uploader sduploader.SDUploader
file *os.File
}
// newLogFile returns a logFile object for saving a single file to the Store.
func newLogFile(uploader sduploader.SDUploader, logFolder string, storePath string) (*logFile, error) {
file, err := ioutil.TempFile(logFolder, filepath.Base(storePath))
if err != nil {
return &logFile{}, fmt.Errorf("creating temporary file for %s: %v", storePath, err)
}
return &logFile{
mutex: &sync.RWMutex{},
storePath: storePath,
uploader: uploader,
file: file,
}, nil
}
// Save synchronously saves the logfile to the data store
func (l *logFile) Save() error {
l.mutex.Lock()
defer l.mutex.Unlock()
if l.lineCount == l.savedLineCount {
return nil
}
log.Println("Uploading", l.file.Name())
err := l.uploader.Upload(l.storePath, l.file.Name())
if err == nil {
l.savedLineCount = l.lineCount
}
return err
}
// Write is an io.Writer that writes to the logfile.
func (l *logFile) Write(p []byte) (int, error) {
l.mutex.Lock()
defer l.mutex.Unlock()
n, err := l.file.Write(p)
if err == nil {
l.lineCount++
}
return n, err
}
// Close closes the underlying file handle in the logFile object
func (l *logFile) Close() error {
l.mutex.Lock()
defer l.mutex.Unlock()
// If the file is already closed, make this a no-op
if l.file == nil {
return nil
}
f := l.file
if err := f.Close(); err != nil {
return err
}
l.file = nil
return os.Remove(f.Name())
}