ec_shard.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package erasure_coding
  2. import (
  3. "fmt"
  4. "os"
  5. "path"
  6. "strconv"
  7. "github.com/chrislusf/seaweedfs/weed/stats"
  8. "github.com/chrislusf/seaweedfs/weed/storage/needle"
  9. )
  10. type ShardId uint8
  11. type EcVolumeShard struct {
  12. VolumeId needle.VolumeId
  13. ShardId ShardId
  14. Collection string
  15. dir string
  16. ecdFile *os.File
  17. ecdFileSize int64
  18. }
  19. func NewEcVolumeShard(dirname string, collection string, id needle.VolumeId, shardId ShardId) (v *EcVolumeShard, e error) {
  20. v = &EcVolumeShard{dir: dirname, Collection: collection, VolumeId: id, ShardId: shardId}
  21. baseFileName := v.FileName()
  22. // open ecd file
  23. if v.ecdFile, e = os.OpenFile(baseFileName+ToExt(int(shardId)), os.O_RDONLY, 0644); e != nil {
  24. return nil, fmt.Errorf("cannot read ec volume shard %s.%s: %v", baseFileName, ToExt(int(shardId)), e)
  25. }
  26. ecdFi, statErr := v.ecdFile.Stat()
  27. if statErr != nil {
  28. return nil, fmt.Errorf("can not stat ec volume shard %s.%s: %v", baseFileName, ToExt(int(shardId)), statErr)
  29. }
  30. v.ecdFileSize = ecdFi.Size()
  31. stats.VolumeServerVolumeCounter.WithLabelValues(v.Collection, "ec_shards").Inc()
  32. return
  33. }
  34. func (shard *EcVolumeShard) Size() int64 {
  35. return shard.ecdFileSize
  36. }
  37. func (shard *EcVolumeShard) String() string {
  38. return fmt.Sprintf("ec shard %v:%v, dir:%s, Collection:%s", shard.VolumeId, shard.ShardId, shard.dir, shard.Collection)
  39. }
  40. func (shard *EcVolumeShard) FileName() (fileName string) {
  41. return EcShardFileName(shard.Collection, shard.dir, int(shard.VolumeId))
  42. }
  43. func EcShardFileName(collection string, dir string, id int) (fileName string) {
  44. idString := strconv.Itoa(id)
  45. if collection == "" {
  46. fileName = path.Join(dir, idString)
  47. } else {
  48. fileName = path.Join(dir, collection+"_"+idString)
  49. }
  50. return
  51. }
  52. func EcShardBaseFileName(collection string, id int) (baseFileName string) {
  53. baseFileName = strconv.Itoa(id)
  54. if collection != "" {
  55. baseFileName = collection + "_" + baseFileName
  56. }
  57. return
  58. }
  59. func (shard *EcVolumeShard) Close() {
  60. if shard.ecdFile != nil {
  61. _ = shard.ecdFile.Close()
  62. shard.ecdFile = nil
  63. }
  64. }
  65. func (shard *EcVolumeShard) Destroy() {
  66. os.Remove(shard.FileName() + ToExt(int(shard.ShardId)))
  67. stats.VolumeServerVolumeCounter.WithLabelValues(shard.Collection, "ec_shards").Dec()
  68. }
  69. func (shard *EcVolumeShard) ReadAt(buf []byte, offset int64) (int, error) {
  70. return shard.ecdFile.ReadAt(buf, offset)
  71. }