-
Notifications
You must be signed in to change notification settings - Fork 267
/
storage.go
404 lines (317 loc) · 9.35 KB
/
storage.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
/*
* Copyright 2022 The Dragonfly Authors
*
* 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.
*/
//go:generate mockgen -destination mocks/storage_mock.go -source storage.go -package mocks
package storage
import (
"errors"
"fmt"
"io"
"io/fs"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"sort"
"sync"
"time"
"github.com/gocarina/gocsv"
logger "d7y.io/dragonfly/v2/internal/dflog"
)
const (
// DefaultMaxSize is the default maximum size of record file
DefaultMaxSize = 100
// DefaultMaxBackups is the default maximum count of backup
DefaultMaxBackups = 10
// DefaultBufferSize is the default size of buffer container
DefaultBufferSize = 100
)
const (
// RecordFilePrefix is prefix of record file name
RecordFilePrefix = "record"
// RecordFileExt is extension of record file name
RecordFileExt = "csv"
)
const (
// Peer has been downloaded successfully
PeerStateSucceeded = iota
// Peer has been downloaded failed
PeerStateFailed
// Peer has been back-to-source downloaded successfully
PeerStateBackToSourceSucceeded
// Peer has been back-to-source downloaded failed
PeerStateBackToSourceFailed
)
const (
// megabyte is the converted factor of MaxSize and bytes
megabyte = 1024 * 1024
// backupTimeFormat is the timestamp format of backup filename
backupTimeFormat = "2006-01-02T15-04-05.000"
)
// Record contains content for record
type Record struct {
// ID is peer id
ID string `csv:"id"`
// IP is host ip
IP string `csv:"ip"`
// Hostname is host name
Hostname string `csv:"hostname"`
// BizTag is peer biz tag
BizTag string `csv:"bizTag"`
// Cost is the task download time(millisecond)
Cost uint32 `csv:"cost"`
// PieceCount is total piece count
PieceCount int32 `csv:"pieceCount"`
// TotalPieceCount is total piece count
TotalPieceCount int32 `csv:"totalPieceCount"`
// ContentLength is task total content length
ContentLength int64 `csv:"contentLength"`
// SecurityDomain is security domain of host
SecurityDomain string `csv:"securityDomain"`
// IDC is internet data center of host
IDC string `csv:"idc"`
// NetTopology is network topology of host
// Example: switch|router|...
NetTopology string `csv:"netTopology"`
// Location is location of host
// Example: country|province|...
Location string `csv:"location"`
// FreeUploadLoad is free upload load of host
FreeUploadLoad int32 `csv:"freeUpoladLoad"`
// State is the download state of the peer
State int `csv:"state"`
// CreateAt is peer create nanosecond time
CreateAt int64 `csv:"createAt"`
// UpdateAt is peer update nanosecond time
UpdateAt int64 `csv:"updateAt"`
// ParentID is parent peer id
ParentID string `csv:"parentID"`
// ParentIP is parent host ip
ParentIP string `csv:"parentIP"`
// ParentHostname is parent host name
ParentHostname string `csv:"parentHostname"`
// ParentBizTag is parent peer biz tag
ParentBizTag string `csv:"parentBizTag"`
// ParentPieceCount is parent total piece count
ParentPieceCount int32 `csv:"parentPieceCount"`
// ParentSecurityDomain is parent security domain of host
ParentSecurityDomain string `csv:"parentSecurityDomain"`
// ParentIDC is parent internet data center of host
ParentIDC string `csv:"parentIDC"`
// ParentNetTopology is parent network topology of host
// Example: switch|router|...
ParentNetTopology string `csv:"parentNetTopology"`
// ParentLocation is parent location of host
// Example: country|province|...
ParentLocation string `csv:"parentLocation"`
// ParentFreeUploadLoad is parent free upload load of host
ParentFreeUploadLoad int32 `csv:"parentFreeUploadLoad"`
// ParentIsCDN is used as tag cdn
ParentIsCDN bool `csv:"parentIsCDN"`
// ParentCreateAt is parent peer create nanosecond time
ParentCreateAt int64 `csv:"parentCreateAt"`
// ParentUpdateAt is parent peer update nanosecond time
ParentUpdateAt int64 `csv:"parentUpdateAt"`
}
// Storage is the interface used for storage
type Storage interface {
// Create inserts the record into csv file
Create(Record) error
// List returns all of records in csv file
List() ([]Record, error)
// Clear removes all record files
Clear() error
}
// storage provides storage function
type storage struct {
baseDir string
filename string
maxSize int64
maxBackups int
buffer []Record
bufferSize int
mu *sync.RWMutex
}
// Option is a functional option for configuring the Storage
type Option func(s *storage)
// WithMaxSize sets the maximum size in megabytes of storage file
func WithMaxSize(maxSize int) Option {
return func(s *storage) {
s.maxSize = int64(maxSize * megabyte)
}
}
// WithMaxBackups sets the maximum number of storage files to retain
func WithMaxBackups(maxBackups int) Option {
return func(s *storage) {
s.maxBackups = maxBackups
}
}
// WithCacheSize sets the size of buffer container,
// if the buffer is full, write all the records in the buffer to the file
func WithBufferSize(bufferSize int) Option {
return func(s *storage) {
s.bufferSize = bufferSize
s.buffer = make([]Record, 0, bufferSize)
}
}
// New returns a new Storage instence
func New(baseDir string, options ...Option) (Storage, error) {
s := &storage{
baseDir: baseDir,
filename: filepath.Join(baseDir, fmt.Sprintf("%s.%s", RecordFilePrefix, RecordFileExt)),
maxSize: DefaultMaxSize * megabyte,
maxBackups: DefaultMaxBackups,
buffer: make([]Record, 0, DefaultBufferSize),
bufferSize: DefaultBufferSize,
mu: &sync.RWMutex{},
}
for _, opt := range options {
opt(s)
}
file, err := os.OpenFile(s.filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return nil, err
}
file.Close()
return s, nil
}
// Create inserts the record into csv file
func (s *storage) Create(record Record) error {
s.mu.Lock()
defer s.mu.Unlock()
// Write records to file
if len(s.buffer) >= s.bufferSize {
if err := s.create(s.buffer...); err != nil {
return err
}
// Keep allocated memory
s.buffer = s.buffer[:0]
}
// Write records to buffer
s.buffer = append(s.buffer, record)
return nil
}
// List returns all of records in csv file
func (s *storage) List() ([]Record, error) {
s.mu.RLock()
defer s.mu.RUnlock()
fileInfos, err := s.backups()
if err != nil {
return nil, err
}
var readers []io.Reader
var closers []io.ReadCloser
defer func() {
for _, closer := range closers {
if err := closer.Close(); err != nil {
logger.Error(err)
}
}
}()
for _, fileInfo := range fileInfos {
file, err := os.Open(filepath.Join(s.baseDir, fileInfo.Name()))
if err != nil {
return nil, err
}
readers = append(readers, file)
closers = append(closers, file)
}
var records []Record
if err := gocsv.UnmarshalWithoutHeaders(io.MultiReader(readers...), &records); err != nil {
return nil, err
}
return records, nil
}
// Clear removes all records
func (s *storage) Clear() error {
s.mu.Lock()
defer s.mu.Unlock()
fileInfos, err := s.backups()
if err != nil {
return err
}
for _, fileInfo := range fileInfos {
filename := filepath.Join(s.baseDir, fileInfo.Name())
if err := os.Remove(filename); err != nil {
return err
}
}
return nil
}
// create inserts the records into csv file
func (s *storage) create(records ...Record) error {
file, err := s.openFile()
if err != nil {
return err
}
defer file.Close()
if err := gocsv.MarshalWithoutHeaders(records, file); err != nil {
return err
}
return nil
}
// openFile opens the record file and removes record files that exceed the total size
func (s *storage) openFile() (*os.File, error) {
fileInfo, err := os.Stat(s.filename)
if err != nil {
return nil, err
}
if s.maxSize <= fileInfo.Size() {
if err := os.Rename(s.filename, s.backupFilename()); err != nil {
return nil, err
}
}
fileInfos, err := s.backups()
if err != nil {
return nil, err
}
if s.maxBackups < len(fileInfos)+1 {
filename := filepath.Join(s.baseDir, fileInfos[0].Name())
if err := os.Remove(filename); err != nil {
return nil, err
}
}
file, err := os.OpenFile(s.filename, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0600)
if err != nil {
return nil, err
}
return file, nil
}
// backupFilename generates file name of backup files
func (s *storage) backupFilename() string {
timestamp := time.Now().Format(backupTimeFormat)
return filepath.Join(s.baseDir, fmt.Sprintf("%s-%s.%s", RecordFilePrefix, timestamp, RecordFileExt))
}
// backupFilename returns backup file information
func (s *storage) backups() ([]fs.FileInfo, error) {
fileInfos, err := ioutil.ReadDir(s.baseDir)
if err != nil {
return nil, err
}
var backups []fs.FileInfo
regexp := regexp.MustCompile(RecordFilePrefix)
for _, fileInfo := range fileInfos {
if !fileInfo.IsDir() && regexp.MatchString(fileInfo.Name()) {
backups = append(backups, fileInfo)
}
}
if len(backups) <= 0 {
return nil, errors.New("backup does not exist")
}
sort.Slice(backups, func(i, j int) bool {
return backups[i].ModTime().Before(backups[j].ModTime())
})
return backups, nil
}