forked from trivago/gollum
/
spoolfile.go
239 lines (203 loc) · 6.68 KB
/
spoolfile.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
// Copyright 2015-2016 trivago GmbH
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package producer
import (
"encoding/base64"
"fmt"
"github.com/trivago/gollum/core"
"github.com/trivago/gollum/core/log"
"github.com/trivago/gollum/shared"
"io"
"io/ioutil"
"os"
"path/filepath"
"sync/atomic"
"time"
)
type spoolFile struct {
file *os.File
batch core.MessageBatch
assembly core.WriterAssembly
fileCreated time.Time
streamName string
basePath string
prod *Spooling
source core.MessageSource
readCount int64
writeCount int64
lastMetricUpdate time.Time
roll chan struct{}
reader *shared.BufferedReader
}
const maxSpoolFileNumber = 99999999 // maximum file number defined by %08d -> 8 digits
const spoolFileFormatString = "%s/%08d.spl"
func newSpoolFile(prod *Spooling, streamName string, source core.MessageSource) *spoolFile {
spool := &spoolFile{
file: nil,
batch: core.NewMessageBatch(prod.batchMaxCount),
assembly: core.NewWriterAssembly(nil, prod.Drop, prod.GetFormatter()),
fileCreated: time.Now(),
streamName: streamName,
basePath: prod.path + "/" + streamName,
prod: prod,
source: source,
lastMetricUpdate: time.Now(),
reader: shared.NewBufferedReader(prod.bufferSizeByte, shared.BufferedReaderFlagDelimiter, 0, "\n"),
roll: make(chan struct{}, 1),
}
shared.Metric.New(spoolingMetricWrite + streamName)
shared.Metric.New(spoolingMetricWriteSec + streamName)
shared.Metric.New(spoolingMetricRead + streamName)
shared.Metric.New(spoolingMetricReadSec + streamName)
go spool.read()
return spool
}
func (spool *spoolFile) triggerRoll() {
spool.roll <- struct{}{}
}
func (spool *spoolFile) flush() {
spool.batch.Flush(spool.assembly.Write)
}
func (spool *spoolFile) close() {
for !spool.batch.IsEmpty() {
spool.batch.Flush(spool.assembly.Write)
spool.batch.WaitForFlush(spool.prod.GetShutdownTimeout())
}
spool.file.Close()
}
func (spool *spoolFile) getAndResetCounts() (read int64, write int64) {
return atomic.SwapInt64(&spool.readCount, 0), atomic.SwapInt64(&spool.writeCount, 0)
}
func (spool *spoolFile) countRead() {
atomic.AddInt64(&spool.readCount, 1)
}
func (spool *spoolFile) countWrite() {
atomic.AddInt64(&spool.writeCount, 1)
}
func (spool *spoolFile) getFileNumbering() (min int, max int) {
min, max = maxSpoolFileNumber+1, 0
files, _ := ioutil.ReadDir(spool.basePath)
for _, file := range files {
if filepath.Ext(file.Name()) == ".spl" {
base := filepath.Base(file.Name())
number, _ := shared.Btoi([]byte(base)) // Because we need leading zero support
min = shared.MinI(min, int(number))
max = shared.MaxI(max, int(number))
}
}
return min, max
}
func (spool *spoolFile) openOrRotate(force bool) bool {
err := spool.batch.AfterFlushDo(func() error {
fileSize := int64(0)
if spool.file != nil {
fileInfo, err := spool.file.Stat()
if err != nil {
return err // ### return, filestat error ###
}
fileSize = fileInfo.Size()
}
if force || spool.file == nil ||
fileSize >= spool.prod.maxFileSize ||
(fileSize > 0 && time.Since(spool.fileCreated) > spool.prod.maxFileAge) {
_, maxSuffix := spool.getFileNumbering()
spoolFileName := fmt.Sprintf(spoolFileFormatString, spool.basePath, maxSuffix+1)
newFile, err := os.OpenFile(spoolFileName, os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
return err // ### return, could not open file ###
}
// Set writer and update internal state
spool.assembly.SetWriter(newFile)
if spool.file != nil {
spool.file.Close()
}
spool.file = newFile
spool.fileCreated = time.Now()
Log.Debug.Print("Spooler opened ", spoolFileName, " for writing")
}
return nil
})
if err != nil {
Log.Error.Print("Spooling: ", err)
return false
}
return true
}
func (spool *spoolFile) decode(data []byte, sequence uint64) {
// Base64 decode, than deserialize
decoded := make([]byte, base64.StdEncoding.DecodedLen(len(data)))
if size, err := base64.StdEncoding.Decode(decoded, data); err != nil {
Log.Error.Print("Spool file read: ", err)
} else if msg, err := core.DeserializeMessage(decoded[:size]); err != nil {
Log.Error.Print("Spool file read: ", err)
} else {
spool.prod.routeToOrigin(msg)
}
}
func (spool *spoolFile) read() {
spool.prod.AddWorker()
defer spool.prod.WorkerDone()
for spool.prod.IsActive() {
minSuffix, _ := spool.getFileNumbering()
spoolFileName := fmt.Sprintf(spoolFileFormatString, spool.basePath, minSuffix)
if minSuffix == 0 || minSuffix > maxSpoolFileNumber || (spool.file != nil && spool.file.Name() == spoolFileName) {
if minSuffix > maxSpoolFileNumber {
Log.Debug.Print("Spool read sleeps (no file)")
} else {
Log.Debug.Printf("Spool read waits for %s", spoolFileName)
}
spool.prod.WorkerDone() // to avoid being stuck during shutdown
retry := time.After(spool.prod.maxFileAge / 2)
select {
case <-retry:
case <-spool.roll:
}
spool.prod.AddWorker() // worker done is always called at exit
continue // ### continue, try again ###
}
file, err := os.OpenFile(spoolFileName, os.O_RDONLY, 0600)
if err != nil {
Log.Error.Print("Spool read open error ", err)
continue // ### continue, try again ###
}
Log.Debug.Print("Spooler opened ", spoolFileName, " for reading")
spool.reader.Reset(0)
readFailed := false
for spool.prod.IsActive() {
// Only spool back if target is not busy
if spool.source != nil && spool.source.IsBlocked() {
time.Sleep(time.Millisecond * 100)
continue // ### contine, busy source ###
}
// Any error cancels the loop
if err := spool.reader.ReadAll(file, spool.decode); err != nil {
if err != io.EOF {
readFailed = true
Log.Error.Print("Spool read error: ", err)
}
break // ### break, read error or EOF ###
}
}
file.Close()
if readFailed {
// Rename file for future processing
Log.Debug.Print("Spooler renamed ", spoolFileName)
os.Rename(spoolFileName, spoolFileName+".failed")
} else {
// Delete file
Log.Debug.Print("Spooler removes ", spoolFileName)
os.Remove(spoolFileName)
}
}
}