You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

89 lines
2.1 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. package chunk_cache
  2. import (
  3. "fmt"
  4. "path"
  5. "sort"
  6. "github.com/chrislusf/seaweedfs/weed/glog"
  7. "github.com/chrislusf/seaweedfs/weed/storage"
  8. "github.com/chrislusf/seaweedfs/weed/storage/types"
  9. )
  10. type OnDiskCacheLayer struct {
  11. diskCaches []*ChunkCacheVolume
  12. }
  13. func NewOnDiskCacheLayer(dir, namePrefix string, diskSizeMB int64, segmentCount int) *OnDiskCacheLayer {
  14. volumeCount, volumeSize := int(diskSizeMB/30000), int64(30000)
  15. if volumeCount < segmentCount {
  16. volumeCount, volumeSize = segmentCount, diskSizeMB/int64(segmentCount)
  17. }
  18. c := &OnDiskCacheLayer{}
  19. for i := 0; i < volumeCount; i++ {
  20. fileName := path.Join(dir, fmt.Sprintf("%s_%d", namePrefix, i))
  21. diskCache, err := LoadOrCreateChunkCacheVolume(fileName, volumeSize*1024*1024)
  22. if err != nil {
  23. glog.Errorf("failed to add cache %s : %v", fileName, err)
  24. } else {
  25. c.diskCaches = append(c.diskCaches, diskCache)
  26. }
  27. }
  28. // keep newest cache to the front
  29. sort.Slice(c.diskCaches, func(i, j int) bool {
  30. return c.diskCaches[i].lastModTime.After(c.diskCaches[j].lastModTime)
  31. })
  32. return c
  33. }
  34. func (c *OnDiskCacheLayer) setChunk(needleId types.NeedleId, data []byte) {
  35. if c.diskCaches[0].fileSize+int64(len(data)) > c.diskCaches[0].sizeLimit {
  36. t, resetErr := c.diskCaches[len(c.diskCaches)-1].Reset()
  37. if resetErr != nil {
  38. glog.Errorf("failed to reset cache file %s", c.diskCaches[len(c.diskCaches)-1].fileName)
  39. return
  40. }
  41. for i := len(c.diskCaches) - 1; i > 0; i-- {
  42. c.diskCaches[i] = c.diskCaches[i-1]
  43. }
  44. c.diskCaches[0] = t
  45. }
  46. c.diskCaches[0].WriteNeedle(needleId, data)
  47. }
  48. func (c *OnDiskCacheLayer) getChunk(needleId types.NeedleId) (data []byte) {
  49. var err error
  50. for _, diskCache := range c.diskCaches {
  51. data, err = diskCache.GetNeedle(needleId)
  52. if err == storage.ErrorNotFound {
  53. continue
  54. }
  55. if err != nil {
  56. glog.Errorf("failed to read cache file %s id %d", diskCache.fileName, needleId)
  57. continue
  58. }
  59. if len(data) != 0 {
  60. return
  61. }
  62. }
  63. return nil
  64. }
  65. func (c *OnDiskCacheLayer) shutdown() {
  66. for _, diskCache := range c.diskCaches {
  67. diskCache.Shutdown()
  68. }
  69. }