-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathwarc.go
More file actions
254 lines (215 loc) · 7.19 KB
/
warc.go
File metadata and controls
254 lines (215 loc) · 7.19 KB
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
package warc
import (
"errors"
"fmt"
"io"
"os"
"path"
"strings"
"sync/atomic"
)
type compressionType string
const (
CompressionNone = compressionType("none")
CompressionGzip = compressionType("gzip")
CompressionZstd = compressionType("zstd")
)
var CompressionTypes = []compressionType{CompressionNone, CompressionGzip, CompressionZstd}
func MustCompressionTypeFromString(s string) compressionType {
switch strings.ToLower(s) {
case "none":
return CompressionNone
case "gzip":
return CompressionGzip
case "zstd":
return CompressionZstd
default:
panic(fmt.Sprintf("invalid compression type: %s", s))
}
}
// RotatorSettings is used to store the settings
// needed by recordWriter to write WARC files
type RotatorSettings struct {
// Content of the warcinfo record that will be written
// to all WARC files
WarcinfoContent Header
// Prefix used for WARC filenames, WARC 1.1 specifications
// recommend to name files this way:
// Prefix-Timestamp-Serial-Crawlhost.warc.gz
Prefix string
// Compression algorithm to use
Compression compressionType
// Payload digest calculation algorithm to use
digestAlgorithm DigestAlgorithm
// Path to a ZSTD compression dictionary to embed (and use) in .warc.zst files
CompressionDictionary string
// Directory where the created WARC files will be stored,
// default will be the current directory
OutputDirectory string
// WARCSize is in Megabytes
WARCSize float64
// WARCWriterPoolSize defines the number of parallel WARC writers
WARCWriterPoolSize int
}
var (
// Create a couple of counters for tracking various stats
DataTotal atomic.Int64
CDXDedupeTotalBytes atomic.Int64
DoppelgangerDedupeTotalBytes atomic.Int64
LocalDedupeTotalBytes atomic.Int64
CDXDedupeTotal atomic.Int64
DoppelgangerDedupeTotal atomic.Int64
LocalDedupeTotal atomic.Int64
)
// NewWARCRotator creates and return a channel that can be used
// to communicate records to be written to WARC files to the
// recordWriter function running in a goroutine
func (s *RotatorSettings) NewWARCRotator() (recordWriterChan chan *RecordBatch, doneChannels []chan bool, err error) {
recordWriterChan = make(chan *RecordBatch, 1)
// Create global atomicSerial number for numbering WARC files.
var serial = new(atomic.Uint64)
// Check the rotator settings and set default values
err = checkRotatorSettings(s)
if err != nil {
return recordWriterChan, doneChannels, err
}
var dictionary []byte
if s.CompressionDictionary != "" {
dictionary, err = os.ReadFile(s.CompressionDictionary)
if err != nil {
panic(fmt.Sprintf("failed to read compression dictionary file %s: %v", s.CompressionDictionary, err))
}
}
for i := 0; i < s.WARCWriterPoolSize; i++ {
doneChan := make(chan bool)
doneChannels = append(doneChannels, doneChan)
go recordWriter(s, recordWriterChan, doneChan, serial, dictionary)
}
return recordWriterChan, doneChannels, nil
}
// reset resets the compressed writer to write to a new output.
// This reuses the encoder's internal buffers.
func (w *Writer) Reset(output io.Writer) {
if w.Compressor != nil {
w.Compressor.Reset(output)
w.BufWriter.Reset(w.Compressor)
} else {
w.BufWriter.Reset(output)
}
}
// Close will flush the final output and close the stream.
// The function will block until everything has been written.
// The [Compressor] can still be re-used after calling this.
// If the [Compressor] is nil, this will just flush the [Writer.BufWriter].
func (w *Writer) FlushAndCloseCompressor() (err error) {
if w.Compressor != nil {
err1 := w.BufWriter.Flush()
err2 := w.Compressor.Close()
return errors.Join(err1, err2)
} else {
return w.BufWriter.Flush()
}
}
func getNextWARCFilename(outputDir, prefix string, compression compressionType, serial *atomic.Uint64) (nextWARCFilename string) {
nextWARCFilename = generateWARCFilename(prefix, compression, serial)
_, err := os.Stat(path.Join(outputDir, nextWARCFilename))
for !errors.Is(err, os.ErrNotExist) {
if err != nil && !errors.Is(err, os.ErrNotExist) {
panic(err)
}
nextWARCFilename = generateWARCFilename(prefix, compression, serial)
_, err = os.Stat(path.Join(outputDir, nextWARCFilename))
}
return
}
func recordWriter(settings *RotatorSettings, records chan *RecordBatch, done chan bool, serial *atomic.Uint64, dictionary []byte) {
var (
currentFileName = getNextWARCFilename(settings.OutputDirectory, settings.Prefix, settings.Compression, serial)
currentWarcinfoRecordID string
)
// Create and open the initial file
warcFile, err := os.Create(settings.OutputDirectory + currentFileName)
if err != nil {
panic(err)
}
// Initialize WARC writer (write dictionary if specified)
warcWriter, err := NewWriter(warcFile, currentFileName, settings.digestAlgorithm, settings.Compression, true, dictionary)
if err != nil {
panic(err)
}
// Write the info record
currentWarcinfoRecordID, err = warcWriter.WriteInfoRecord(settings.WarcinfoContent)
if err != nil {
panic(err)
}
for {
recordBatch, more := <-records
if more {
if isFileSizeExceeded(warcFile, settings.WARCSize) {
// WARC file size exceeded settings.WarcSize
// We flush the data and close the file
err = warcWriter.FlushAndCloseCompressor()
if err != nil {
panic(err)
}
err = warcFile.Close()
if err != nil {
panic(err)
}
// The WARC file is renamed to remove the .open suffix
err := os.Rename(path.Join(settings.OutputDirectory, currentFileName), strings.TrimSuffix(path.Join(settings.OutputDirectory, currentFileName), ".open"))
if err != nil {
panic(err)
}
// Create the new file and automatically increment the serial inside of GenerateWarcFileName
currentFileName = getNextWARCFilename(settings.OutputDirectory, settings.Prefix, settings.Compression, serial)
warcFile, err = os.Create(settings.OutputDirectory + currentFileName)
if err != nil {
panic(err)
}
// Initialize new WARC writer
warcWriter, err = NewWriter(warcFile, currentFileName, settings.digestAlgorithm, settings.Compression, true, dictionary)
if err != nil {
panic(err)
}
// Write the info record
currentWarcinfoRecordID, err = warcWriter.WriteInfoRecord(settings.WarcinfoContent)
if err != nil {
panic(err)
}
}
// Write all the records of the record batch
for _, record := range recordBatch.Records {
warcWriter.Reset(warcFile)
record.Header.Set("WARC-Date", recordBatch.CaptureTime)
record.Header.Set("WARC-Warcinfo-ID", "<urn:uuid:"+currentWarcinfoRecordID+">")
_, err := warcWriter.WriteRecord(record)
if err != nil {
panic(err)
}
}
if recordBatch.FeedbackChan != nil {
recordBatch.FeedbackChan <- struct{}{}
close(recordBatch.FeedbackChan)
}
} else {
// Channel has been closed
// We flush the data, close the file, and rename it
err = warcWriter.FlushAndCloseCompressor()
if err != nil {
panic(err)
}
err = warcFile.Close()
if err != nil {
panic(err)
}
// The WARC file is renamed to remove the .open suffix
err := os.Rename(settings.OutputDirectory+currentFileName, strings.TrimSuffix(settings.OutputDirectory+currentFileName, ".open"))
if err != nil {
panic(err)
}
done <- true
return
}
}
}