-
Notifications
You must be signed in to change notification settings - Fork 3
/
compress.go
405 lines (350 loc) · 8.91 KB
/
compress.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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
// Copyright(c) 2022-2023 Intel Corporation. All rights reserved.
// Package qatzip implements Go bindings for the Intel® Quick Assist Technology compression library
package qatzip
import (
"bytes"
"context"
"encoding/binary"
"io"
"os"
"runtime/trace"
"strconv"
"time"
"github.com/DataDog/zstd"
)
// Writer implements an io.Writer. When written to, it sends compressed content to w.
type Writer struct {
w io.Writer
closed bool
wroteHeader bool
err error
q *QzBinding // internal QAT state
bounceBuf []byte
outputBuf *bytes.Buffer
bufferGrowth int
p params
ctx context.Context // context for tracing
task *trace.Task // task for tracing
perf *Perf // perfomance counters
}
const (
/* Gzip Header magic numbers */
gzipID1 uint8 = 0x1f
gzipID2 uint8 = 0x8b
gzipDeflate uint8 = 0x08
osType uint8 = 255 /* unknown OS type */
deflateMagic1 uint8 = 0x01
deflateMagic2 uint8 = 0xff
)
const (
/* LZ4 header magic numbers */
lz4ID uint32 = 0x184D2204
lz4FLG uint8 = 0x64
lz4BD uint8 = 0x40
lz4HC uint8 = 0xa7
lz4Magic1 uint8 = 0x05
lz4Magic2 uint8 = 0x5d
lz4Magic3 uint8 = 0xcc
lz4Magic4 uint8 = 0x02
)
const (
envAlgorithm = "QATGO_ALGORITHM"
envCompressionLvl = "QATGO_COMPRESSION_LEVEL"
)
// Performance counters
type Perf struct {
ReadTimeNS uint64 // time (ns) spent reading from r
WriteTimeNS uint64 // time (ns) spent writing to w
BytesIn uint64 // bytes sent to QATzip
BytesOut uint64 // bytes received from QATzip
EngineTimeNS uint64 // time (ns) spent in QATzip
CopyTimeNS uint64 // time (ns) spent copying buffers + reallocation
}
func applyEnvOptions(z *Writer) (err error) {
algorithmStr := os.Getenv(envAlgorithm)
if algorithmStr != "" {
algorithm, ok := algorithmConv[algorithmStr]
if !ok {
err = ErrParamAlgorithm
return err
}
if err := z.Apply(AlgorithmOption(algorithm)); err != nil {
return err
}
}
compLvlStr := os.Getenv(envCompressionLvl)
if compLvlStr != "" {
var compLvl int
if compLvl, err = strconv.Atoi(compLvlStr); err != nil {
err = ErrParamCompressionLevel
return err
}
if err := z.Apply(CompressionLevelOption(compLvl)); err != nil {
return err
}
}
return nil
}
// NewWriter creates a new Writer with output io.Writer w
func NewWriter(w io.Writer) *Writer {
z := new(Writer)
z.closed = true
z.p = defaultParams()
z.err = applyEnvOptions(z)
z.w = w
return z
}
// NewWriterLevel creates a new Writer with an additional compression level setting
func NewWriterLevel(w io.Writer, level int) (z *Writer, err error) {
z = NewWriter(w)
err = z.Apply(CompressionLevelOption(level))
return
}
// Writes an empty header and footer for gzip and lz4
// This is a workaround due to QATzip not supporting empty files
func (z *Writer) writeEmptyBuffer() (err error) {
var buf []byte
var le = binary.LittleEndian
switch z.p.Algorithm {
case DEFLATE:
hdr := [10]byte{0: gzipID1, 1: gzipID2, 2: gzipDeflate, 8: byte(z.p.Level), 9: osType}
magic := [5]byte{0: deflateMagic1, 3: deflateMagic2, 4: deflateMagic2}
ftr := [8]byte{}
buf = append(hdr[:], magic[:]...)
buf = append(buf, ftr[:]...)
case LZ4:
hdr := [4]byte{}
le.PutUint32(hdr[:4], lz4ID)
frm := [3]byte{0: lz4FLG, 1: lz4BD, 2: lz4HC}
end := [4]byte{}
magic := [4]byte{0: lz4Magic1, 1: lz4Magic2, 2: lz4Magic3, 3: lz4Magic4}
buf = append(hdr[:], frm[:]...)
buf = append(buf, end[:]...)
buf = append(buf, magic[:]...)
case ZSTD:
_, err := zstd.Compress(buf, buf)
if err != nil {
err = ErrFail
return err
}
default:
err = ErrUnsupportedFmt
return err
}
z.traceLogf(Med, "[write->output] header/footer")
_, err = z.w.Write(buf)
z.wroteHeader = true
return err
}
// Close closes Writer and flushes remaining data
func (z *Writer) Close() (err error) {
if z.closed {
z.err = ErrWriterClosed
return
}
z.traceLogf(Med, "[close] err:'%v'", z.err)
if z.err != nil {
return z.err
}
defer z.task.End()
if !z.wroteHeader && z.perf.BytesIn == 0 && len(z.bounceBuf) == 0 {
r := trace.StartRegion(z.ctx, "Qz(5) Empty Buffer")
z.err = z.writeEmptyBuffer()
r.End()
if z.err != nil {
return z.err
}
}
z.closed = true
r := trace.StartRegion(z.ctx, "Qz(4) Last Write")
defer r.End()
if z.err == nil {
z.q.SetLast(true)
err := z.flushBounceBuffer()
if err != nil {
z.q.Close()
return z.err
}
}
z.err = z.q.Close()
if z.err != nil {
return z.err
}
return
}
// Reset discards current state, loads applied options, and restarts session
func (z *Writer) Reset(w io.Writer) (err error) {
z.Close()
z.ctx, z.task = trace.NewTask(context.Background(), "Qz io.Writer")
if z.p.DebugLevel == None {
z.p.DebugLevel = getTraceLevel()
}
z.q, err = NewQzBinding()
if err != nil {
z.err = err
return
}
z.q.setParams(z.p)
if err = z.q.StartSession(); err != nil {
z.err = err
return
}
z.outputBuf = bytes.NewBuffer(make([]byte, z.p.OutputBufLength))
z.w = w
z.closed = false
z.err = nil
z.wroteHeader = false
z.bufferGrowth = z.p.BufferGrowth
z.bounceBuf = make([]byte, 0, z.p.BounceBufferLength)
z.perf = new(Perf)
return
}
// Write() inputs data from p and writes compressed output data io.Writer w
func (z *Writer) Write(p []byte) (n int, err error) {
if z.err != nil {
return 0, z.err
}
if z.q == nil {
if z.err = z.Reset(z.w); z.err != nil {
return 0, z.err
}
}
r := trace.StartRegion(z.ctx, "Qz(1) Write()")
defer r.End()
b := p
nw := 0
nb := 0
err = z.flushBounceBuffer()
if err != nil {
z.err = err
return 0, err
}
if z.p.InputBufferMode != NoLast {
if z.p.InputBufferMode == Bounce || len(p) <= z.p.BounceBufferLength {
t1 := time.Now().UnixNano()
if len(p) > len(z.bounceBuf) {
z.bounceBuf = make([]byte, 0, len(p))
}
z.bounceBuf = z.bounceBuf[:len(p)]
n = copy(z.bounceBuf, p)
t2 := time.Now().UnixNano()
z.perf.CopyTimeNS += uint64(t2 - t1)
return
}
if z.p.InputBufferMode == Reserve {
t1 := time.Now().UnixNano()
ibl := len(p) - z.p.BounceBufferLength
b = p[:ibl]
rb := p[ibl:]
z.bounceBuf = z.bounceBuf[:len(rb)]
nb = copy(z.bounceBuf, rb)
t2 := time.Now().UnixNano()
z.perf.CopyTimeNS += uint64(t2 - t1)
}
}
nw, err = z.compressWrite(b)
n = nw + nb
if err != nil {
z.err = err
return n, err
}
return
}
func (z *Writer) flushBounceBuffer() (err error) {
if len(z.bounceBuf) > 0 {
nw, err := z.compressWrite(z.bounceBuf)
if err != nil {
z.err = err
return err
}
if nw < len(z.bounceBuf) {
z.err = io.ErrShortWrite
return z.err
}
}
z.bounceBuf = z.bounceBuf[:0]
return
}
// Compresses transfer buffer
func (z *Writer) compressWrite(p []byte) (n int, err error) {
var t1, t2 int64 // for performance counters
if z.err != nil {
return 0, z.err
}
remainder := len(p) // bytes requested from input
produced := 0 // data copied into p[]
consumed := 0
for remainder > 0 {
if z.p.InputBufferMode == Last {
z.q.SetLast(true)
}
// compress input data
r := trace.StartRegion(z.ctx, "Qz(2) Compress")
t1 = time.Now().UnixNano()
in, out, err := z.q.Compress(p[consumed:], z.outputBuf.Bytes())
if err == nil {
z.perf.BytesIn += uint64(in)
z.perf.BytesOut += uint64(out)
t2 = time.Now().UnixNano()
z.perf.EngineTimeNS += uint64(t2 - t1)
}
r.End()
z.traceLogf(Med, "[write->qat] r:%v i:%v o:%v ibofs:%v obl:%v err:%v", remainder, in, out, consumed, z.outputBuf.Len(), err)
if err != nil {
if err == ErrBuffer {
// Grow output buffer, only in the case that it was not large enough for QAT to output any data.
if z.outputBuf.Len() == DefaultMaxBufferLength {
return consumed, err
}
t1 = time.Now().UnixNano()
newLength := z.outputBuf.Len() + z.bufferGrowth
if newLength > DefaultMaxBufferLength {
newLength = DefaultMaxBufferLength
}
z.traceLogf(Med, "[expand output buffer] o:%v n:%v", z.outputBuf.Len(), newLength)
z.outputBuf = bytes.NewBuffer(make([]byte, newLength))
t2 = time.Now().UnixNano()
z.perf.CopyTimeNS += uint64(t2 - t1)
continue
} else if err != ErrBuffer {
z.err = err
return consumed, err
}
}
z.wroteHeader = true
consumed += in
remainder -= in
produced = out
if produced > 0 {
r := trace.StartRegion(z.ctx, "Qz(3) Output Stream")
t1 = time.Now().UnixNano()
nw, err := z.w.Write(z.outputBuf.Bytes()[:produced])
t2 = time.Now().UnixNano()
z.perf.WriteTimeNS += uint64(t2 - t1)
r.End()
z.traceLogf(Med, "[write->output] nw:%v err:%v", nw, err)
if err != nil {
z.err = err
return consumed, err
}
}
}
return consumed, nil
}
// Get performance counters from Writer
func (z *Writer) GetPerf() Perf {
return *z.perf
}
// Apply options to Writer
func (z *Writer) Apply(options ...Option) (err error) {
if z.q != nil {
err = ErrApplyPostInit
return
}
for _, op := range options {
if err = op(z); err != nil {
return
}
}
return
}