| 1 |
package fastcache |
| 2 |
|
| 3 |
import ( |
| 4 |
"encoding/binary" |
| 5 |
"fmt" |
| 6 |
"io" |
| 7 |
"io/ioutil" |
| 8 |
"os" |
| 9 |
"path/filepath" |
| 10 |
"regexp" |
| 11 |
"runtime" |
| 12 |
|
| 13 |
"github.com/golang/snappy" |
| 14 |
) |
| 15 |
|
| 16 |
// SaveToFile atomically saves cache data to the given filePath using a single |
| 17 |
// CPU core. |
| 18 |
// |
| 19 |
// SaveToFile may be called concurrently with other operations on the cache. |
| 20 |
// |
| 21 |
// The saved data may be loaded with LoadFromFile*. |
| 22 |
// |
| 23 |
// See also SaveToFileConcurrent for faster saving to file. |
| 24 |
func (c *Cache) SaveToFile(filePath string) error { |
| 25 |
return c.SaveToFileConcurrent(filePath, 1) |
| 26 |
} |
| 27 |
|
| 28 |
// SaveToFileConcurrent saves cache data to the given filePath using concurrency |
| 29 |
// CPU cores. |
| 30 |
// |
| 31 |
// SaveToFileConcurrent may be called concurrently with other operations |
| 32 |
// on the cache. |
| 33 |
// |
| 34 |
// The saved data may be loaded with LoadFromFile*. |
| 35 |
// |
| 36 |
// See also SaveToFile. |
| 37 |
func (c *Cache) SaveToFileConcurrent(filePath string, concurrency int) error { |
| 38 |
// Create dir if it doesn't exist. |
| 39 |
dir := filepath.Dir(filePath) |
| 40 |
if _, err := os.Stat(dir); err != nil { |
| 41 |
if !os.IsNotExist(err) { |
| 42 |
return fmt.Errorf("cannot stat %q: %s", dir, err) |
| 43 |
} |
| 44 |
if err := os.MkdirAll(dir, 0755); err != nil { |
| 45 |
return fmt.Errorf("cannot create dir %q: %s", dir, err) |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
// Save cache data into a temporary directory. |
| 50 |
tmpDir, err := ioutil.TempDir(dir, "fastcache.tmp.") |
| 51 |
if err != nil { |
| 52 |
return fmt.Errorf("cannot create temporary dir inside %q: %s", dir, err) |
| 53 |
} |
| 54 |
defer func() { |
| 55 |
if tmpDir != "" { |
| 56 |
_ = os.RemoveAll(tmpDir) |
| 57 |
} |
| 58 |
}() |
| 59 |
gomaxprocs := runtime.GOMAXPROCS(-1) |
| 60 |
if concurrency <= 0 || concurrency > gomaxprocs { |
| 61 |
concurrency = gomaxprocs |
| 62 |
} |
| 63 |
if err := c.save(tmpDir, concurrency); err != nil { |
| 64 |
return fmt.Errorf("cannot save cache data to temporary dir %q: %s", tmpDir, err) |
| 65 |
} |
| 66 |
|
| 67 |
// Remove old filePath contents, since os.Rename may return |
| 68 |
// error if filePath dir exists. |
| 69 |
if err := os.RemoveAll(filePath); err != nil { |
| 70 |
return fmt.Errorf("cannot remove old contents at %q: %s", filePath, err) |
| 71 |
} |
| 72 |
if err := os.Rename(tmpDir, filePath); err != nil { |
| 73 |
return fmt.Errorf("cannot move temporary dir %q to %q: %s", tmpDir, filePath, err) |
| 74 |
} |
| 75 |
tmpDir = "" |
| 76 |
return nil |
| 77 |
} |
| 78 |
|
| 79 |
// LoadFromFileMaxBytes loads cache data from the specified filePath, |
| 80 |
// enforcing that the cache capacity matches the provided maxBytes value. |
| 81 |
// |
| 82 |
// Returns an error if the stored cache's capacity differs from maxBytes. |
| 83 |
// |
| 84 |
// See SaveToFile* for functions that persist cache data to a file. |
| 85 |
func LoadFromFileMaxBytes(filePath string, maxBytes int) (*Cache, error) { |
| 86 |
return load(filePath, maxBytes) |
| 87 |
} |
| 88 |
|
| 89 |
// LoadFromFile loads cache data from the given filePath. |
| 90 |
// |
| 91 |
// See SaveToFile* for saving cache data to file. |
| 92 |
func LoadFromFile(filePath string) (*Cache, error) { |
| 93 |
return load(filePath, 0) |
| 94 |
} |
| 95 |
|
| 96 |
// LoadFromFileOrNew tries loading cache data from the given filePath. |
| 97 |
// |
| 98 |
// The function falls back to creating new cache with the given maxBytes |
| 99 |
// capacity if error occurs during loading the cache from file. |
| 100 |
func LoadFromFileOrNew(filePath string, maxBytes int) *Cache { |
| 101 |
c, err := load(filePath, maxBytes) |
| 102 |
if err == nil { |
| 103 |
return c |
| 104 |
} |
| 105 |
return New(maxBytes) |
| 106 |
} |
| 107 |
|
| 108 |
func (c *Cache) save(dir string, workersCount int) error { |
| 109 |
if err := saveMetadata(c, dir); err != nil { |
| 110 |
return err |
| 111 |
} |
| 112 |
|
| 113 |
// Save buckets by workersCount concurrent workers. |
| 114 |
workCh := make(chan int, workersCount) |
| 115 |
results := make(chan error) |
| 116 |
for i := range workersCount { |
| 117 |
go func(workerNum int) { |
| 118 |
results <- saveBuckets(c.buckets[:], workCh, dir, workerNum) |
| 119 |
}(i) |
| 120 |
} |
| 121 |
// Feed workers with work |
| 122 |
for i := range c.buckets[:] { |
| 123 |
workCh <- i |
| 124 |
} |
| 125 |
close(workCh) |
| 126 |
|
| 127 |
// Read results. |
| 128 |
var err error |
| 129 |
for range workersCount { |
| 130 |
result := <-results |
| 131 |
if result != nil && err == nil { |
| 132 |
err = result |
| 133 |
} |
| 134 |
} |
| 135 |
return err |
| 136 |
} |
| 137 |
|
| 138 |
func load(filePath string, maxBytes int) (*Cache, error) { |
| 139 |
maxBucketChunks, err := loadMetadata(filePath) |
| 140 |
if err != nil { |
| 141 |
return nil, err |
| 142 |
} |
| 143 |
if maxBytes > 0 { |
| 144 |
maxBucketBytes := uint64((maxBytes + bucketsCount - 1) / bucketsCount) |
| 145 |
expectedBucketChunks := (maxBucketBytes + chunkSize - 1) / chunkSize |
| 146 |
if maxBucketChunks != expectedBucketChunks { |
| 147 |
return nil, fmt.Errorf("cache file %s contains unexpected number of bucket chunks; got %d; want %d", filePath, maxBucketChunks, expectedBucketChunks) |
| 148 |
} |
| 149 |
} |
| 150 |
|
| 151 |
// Read bucket files from filePath dir. |
| 152 |
d, err := os.Open(filePath) |
| 153 |
if err != nil { |
| 154 |
return nil, fmt.Errorf("cannot open %q: %w", filePath, err) |
| 155 |
} |
| 156 |
defer func() { |
| 157 |
_ = d.Close() |
| 158 |
}() |
| 159 |
fis, err := d.Readdir(-1) |
| 160 |
if err != nil { |
| 161 |
return nil, fmt.Errorf("cannot read files from %q: %s", filePath, err) |
| 162 |
} |
| 163 |
results := make(chan error) |
| 164 |
workersCount := 0 |
| 165 |
var c Cache |
| 166 |
for _, fi := range fis { |
| 167 |
fn := fi.Name() |
| 168 |
if fi.IsDir() || !dataFileRegexp.MatchString(fn) { |
| 169 |
continue |
| 170 |
} |
| 171 |
workersCount++ |
| 172 |
go func(dataPath string) { |
| 173 |
results <- loadBuckets(c.buckets[:], dataPath, maxBucketChunks) |
| 174 |
}(filePath + "/" + fn) |
| 175 |
} |
| 176 |
err = nil |
| 177 |
for range workersCount { |
| 178 |
result := <-results |
| 179 |
if result != nil && err == nil { |
| 180 |
err = result |
| 181 |
} |
| 182 |
} |
| 183 |
if err != nil { |
| 184 |
return nil, err |
| 185 |
} |
| 186 |
// Initialize buckets, which could be missing due to incomplete or corrupted files in the cache. |
| 187 |
// It is better initializing such buckets instead of returning error, since the rest of buckets |
| 188 |
// contain valid data. |
| 189 |
for i := range c.buckets[:] { |
| 190 |
b := &c.buckets[i] |
| 191 |
if len(b.chunks) == 0 { |
| 192 |
b.chunks = make([][]byte, maxBucketChunks) |
| 193 |
b.m = make(map[uint64]uint64) |
| 194 |
} |
| 195 |
} |
| 196 |
return &c, nil |
| 197 |
} |
| 198 |
|
| 199 |
func saveMetadata(c *Cache, dir string) error { |
| 200 |
metadataPath := dir + "/metadata.bin" |
| 201 |
metadataFile, err := os.Create(metadataPath) |
| 202 |
if err != nil { |
| 203 |
return fmt.Errorf("cannot create %q: %s", metadataPath, err) |
| 204 |
} |
| 205 |
defer func() { |
| 206 |
_ = metadataFile.Close() |
| 207 |
}() |
| 208 |
maxBucketChunks := uint64(cap(c.buckets[0].chunks)) |
| 209 |
if err := writeUint64(metadataFile, maxBucketChunks); err != nil { |
| 210 |
return fmt.Errorf("cannot write maxBucketChunks=%d to %q: %s", maxBucketChunks, metadataPath, err) |
| 211 |
} |
| 212 |
return nil |
| 213 |
} |
| 214 |
|
| 215 |
func loadMetadata(dir string) (uint64, error) { |
| 216 |
metadataPath := dir + "/metadata.bin" |
| 217 |
metadataFile, err := os.Open(metadataPath) |
| 218 |
if err != nil { |
| 219 |
return 0, fmt.Errorf("cannot open %q: %w", metadataPath, err) |
| 220 |
} |
| 221 |
defer func() { |
| 222 |
_ = metadataFile.Close() |
| 223 |
}() |
| 224 |
maxBucketChunks, err := readUint64(metadataFile) |
| 225 |
if err != nil { |
| 226 |
return 0, fmt.Errorf("cannot read maxBucketChunks from %q: %s", metadataPath, err) |
| 227 |
} |
| 228 |
if maxBucketChunks == 0 { |
| 229 |
return 0, fmt.Errorf("invalid maxBucketChunks=0 read from %q", metadataPath) |
| 230 |
} |
| 231 |
return maxBucketChunks, nil |
| 232 |
} |
| 233 |
|
| 234 |
var dataFileRegexp = regexp.MustCompile(`^data\.\d+\.bin$`) |
| 235 |
|
| 236 |
func saveBuckets(buckets []bucket, workCh <-chan int, dir string, workerNum int) error { |
| 237 |
dataPath := fmt.Sprintf("%s/data.%d.bin", dir, workerNum) |
| 238 |
dataFile, err := os.Create(dataPath) |
| 239 |
if err != nil { |
| 240 |
return fmt.Errorf("cannot create %q: %s", dataPath, err) |
| 241 |
} |
| 242 |
defer func() { |
| 243 |
_ = dataFile.Close() |
| 244 |
}() |
| 245 |
zw := snappy.NewBufferedWriter(dataFile) |
| 246 |
for bucketNum := range workCh { |
| 247 |
if err := writeUint64(zw, uint64(bucketNum)); err != nil { |
| 248 |
return fmt.Errorf("cannot write bucketNum=%d to %q: %s", bucketNum, dataPath, err) |
| 249 |
} |
| 250 |
if err := buckets[bucketNum].Save(zw); err != nil { |
| 251 |
return fmt.Errorf("cannot save bucket[%d] to %q: %s", bucketNum, dataPath, err) |
| 252 |
} |
| 253 |
} |
| 254 |
if err := zw.Close(); err != nil { |
| 255 |
return fmt.Errorf("cannot close snappy.Writer for %q: %s", dataPath, err) |
| 256 |
} |
| 257 |
return nil |
| 258 |
} |
| 259 |
|
| 260 |
func loadBuckets(buckets []bucket, dataPath string, maxChunks uint64) error { |
| 261 |
dataFile, err := os.Open(dataPath) |
| 262 |
if err != nil { |
| 263 |
return fmt.Errorf("cannot open %q: %s", dataPath, err) |
| 264 |
} |
| 265 |
defer func() { |
| 266 |
_ = dataFile.Close() |
| 267 |
}() |
| 268 |
zr := snappy.NewReader(dataFile) |
| 269 |
for { |
| 270 |
bucketNum, err := readUint64(zr) |
| 271 |
if err == io.EOF { |
| 272 |
// Reached the end of file. |
| 273 |
return nil |
| 274 |
} |
| 275 |
if bucketNum >= uint64(len(buckets)) { |
| 276 |
return fmt.Errorf("unexpected bucketNum read from %q: %d; must be smaller than %d", dataPath, bucketNum, len(buckets)) |
| 277 |
} |
| 278 |
if err := buckets[bucketNum].Load(zr, maxChunks); err != nil { |
| 279 |
return fmt.Errorf("cannot load bucket[%d] from %q: %s", bucketNum, dataPath, err) |
| 280 |
} |
| 281 |
} |
| 282 |
} |
| 283 |
|
| 284 |
func (b *bucket) Save(w io.Writer) error { |
| 285 |
b.mu.Lock() |
| 286 |
b.cleanLocked() |
| 287 |
b.mu.Unlock() |
| 288 |
|
| 289 |
b.mu.RLock() |
| 290 |
defer b.mu.RUnlock() |
| 291 |
|
| 292 |
// Store b.idx, b.gen and b.m to w. |
| 293 |
|
| 294 |
bIdx := b.idx |
| 295 |
bGen := b.gen |
| 296 |
chunksLen := 0 |
| 297 |
for _, chunk := range b.chunks { |
| 298 |
if chunk == nil { |
| 299 |
break |
| 300 |
} |
| 301 |
chunksLen++ |
| 302 |
} |
| 303 |
kvs := make([]byte, 0, 2*8*len(b.m)) |
| 304 |
var u64Buf [8]byte |
| 305 |
for k, v := range b.m { |
| 306 |
binary.LittleEndian.PutUint64(u64Buf[:], k) |
| 307 |
kvs = append(kvs, u64Buf[:]...) |
| 308 |
binary.LittleEndian.PutUint64(u64Buf[:], v) |
| 309 |
kvs = append(kvs, u64Buf[:]...) |
| 310 |
} |
| 311 |
|
| 312 |
if err := writeUint64(w, bIdx); err != nil { |
| 313 |
return fmt.Errorf("cannot write b.idx: %s", err) |
| 314 |
} |
| 315 |
if err := writeUint64(w, bGen); err != nil { |
| 316 |
return fmt.Errorf("cannot write b.gen: %s", err) |
| 317 |
} |
| 318 |
if err := writeUint64(w, uint64(len(kvs))/2/8); err != nil { |
| 319 |
return fmt.Errorf("cannot write len(b.m): %s", err) |
| 320 |
} |
| 321 |
if _, err := w.Write(kvs); err != nil { |
| 322 |
return fmt.Errorf("cannot write b.m: %s", err) |
| 323 |
} |
| 324 |
|
| 325 |
// Store b.chunks to w. |
| 326 |
if err := writeUint64(w, uint64(chunksLen)); err != nil { |
| 327 |
return fmt.Errorf("cannot write len(b.chunks): %s", err) |
| 328 |
} |
| 329 |
for chunkIdx := range chunksLen { |
| 330 |
chunk := b.chunks[chunkIdx][:chunkSize] |
| 331 |
if _, err := w.Write(chunk); err != nil { |
| 332 |
return fmt.Errorf("cannot write b.chunks[%d]: %s", chunkIdx, err) |
| 333 |
} |
| 334 |
} |
| 335 |
|
| 336 |
return nil |
| 337 |
} |
| 338 |
|
| 339 |
func (b *bucket) Load(r io.Reader, maxChunks uint64) error { |
| 340 |
if maxChunks == 0 { |
| 341 |
return fmt.Errorf("the number of chunks per bucket cannot be zero") |
| 342 |
} |
| 343 |
bIdx, err := readUint64(r) |
| 344 |
if err != nil { |
| 345 |
return fmt.Errorf("cannot read b.idx: %s", err) |
| 346 |
} |
| 347 |
bGen, err := readUint64(r) |
| 348 |
if err != nil { |
| 349 |
return fmt.Errorf("cannot read b.gen: %s", err) |
| 350 |
} |
| 351 |
kvsLen, err := readUint64(r) |
| 352 |
if err != nil { |
| 353 |
return fmt.Errorf("cannot read len(b.m): %s", err) |
| 354 |
} |
| 355 |
kvsLen *= 2 * 8 |
| 356 |
kvs := make([]byte, kvsLen) |
| 357 |
if _, err := io.ReadFull(r, kvs); err != nil { |
| 358 |
return fmt.Errorf("cannot read b.m: %s", err) |
| 359 |
} |
| 360 |
m := make(map[uint64]uint64, kvsLen/2/8) |
| 361 |
for len(kvs) > 0 { |
| 362 |
k := binary.LittleEndian.Uint64(kvs) |
| 363 |
kvs = kvs[8:] |
| 364 |
v := binary.LittleEndian.Uint64(kvs) |
| 365 |
kvs = kvs[8:] |
| 366 |
m[k] = v |
| 367 |
} |
| 368 |
|
| 369 |
maxBytes := maxChunks * chunkSize |
| 370 |
if maxBytes >= maxBucketSize { |
| 371 |
return fmt.Errorf("too big maxBytes=%d; should be smaller than %d", maxBytes, maxBucketSize) |
| 372 |
} |
| 373 |
chunks := make([][]byte, maxChunks) |
| 374 |
chunksLen, err := readUint64(r) |
| 375 |
if err != nil { |
| 376 |
return fmt.Errorf("cannot read len(b.chunks): %s", err) |
| 377 |
} |
| 378 |
if chunksLen > uint64(maxChunks) { |
| 379 |
return fmt.Errorf("chunksLen=%d cannot exceed maxChunks=%d", chunksLen, maxChunks) |
| 380 |
} |
| 381 |
currChunkIdx := bIdx / chunkSize |
| 382 |
if currChunkIdx > 0 && currChunkIdx >= chunksLen { |
| 383 |
return fmt.Errorf("too big bIdx=%d; should be smaller than %d", bIdx, chunksLen*chunkSize) |
| 384 |
} |
| 385 |
for chunkIdx := range chunksLen { |
| 386 |
chunk := getChunk() |
| 387 |
chunks[chunkIdx] = chunk |
| 388 |
if _, err := io.ReadFull(r, chunk); err != nil { |
| 389 |
// Free up allocated chunks before returning the error. |
| 390 |
for _, chunk := range chunks { |
| 391 |
if chunk != nil { |
| 392 |
putChunk(chunk) |
| 393 |
} |
| 394 |
} |
| 395 |
return fmt.Errorf("cannot read b.chunks[%d]: %s", chunkIdx, err) |
| 396 |
} |
| 397 |
} |
| 398 |
// Adjust len for the chunk pointed by currChunkIdx. |
| 399 |
if chunksLen > 0 { |
| 400 |
chunkLen := bIdx % chunkSize |
| 401 |
chunks[currChunkIdx] = chunks[currChunkIdx][:chunkLen] |
| 402 |
} |
| 403 |
|
| 404 |
b.mu.Lock() |
| 405 |
for _, chunk := range b.chunks { |
| 406 |
putChunk(chunk) |
| 407 |
} |
| 408 |
b.chunks = chunks |
| 409 |
b.m = m |
| 410 |
b.idx = bIdx |
| 411 |
b.gen = bGen |
| 412 |
b.mu.Unlock() |
| 413 |
|
| 414 |
return nil |
| 415 |
} |
| 416 |
|
| 417 |
func writeUint64(w io.Writer, u uint64) error { |
| 418 |
var u64Buf [8]byte |
| 419 |
binary.LittleEndian.PutUint64(u64Buf[:], u) |
| 420 |
_, err := w.Write(u64Buf[:]) |
| 421 |
return err |
| 422 |
} |
| 423 |
|
| 424 |
func readUint64(r io.Reader) (uint64, error) { |
| 425 |
var u64Buf [8]byte |
| 426 |
if _, err := io.ReadFull(r, u64Buf[:]); err != nil { |
| 427 |
return 0, err |
| 428 |
} |
| 429 |
u := binary.LittleEndian.Uint64(u64Buf[:]) |
| 430 |
return u, nil |
| 431 |
} |