disk_location.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. package storage
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. "sync"
  9. "time"
  10. "github.com/chrislusf/seaweedfs/weed/glog"
  11. "github.com/chrislusf/seaweedfs/weed/stats"
  12. "github.com/chrislusf/seaweedfs/weed/storage/erasure_coding"
  13. "github.com/chrislusf/seaweedfs/weed/storage/needle"
  14. )
  15. type DiskLocation struct {
  16. Directory string
  17. MaxVolumeCount int
  18. MinFreeSpacePercent float32
  19. volumes map[needle.VolumeId]*Volume
  20. volumesLock sync.RWMutex
  21. // erasure coding
  22. ecVolumes map[needle.VolumeId]*erasure_coding.EcVolume
  23. ecVolumesLock sync.RWMutex
  24. isDiskSpaceLow bool
  25. }
  26. func NewDiskLocation(dir string, maxVolumeCount int, minFreeSpacePercent float32) *DiskLocation {
  27. location := &DiskLocation{Directory: dir, MaxVolumeCount: maxVolumeCount, MinFreeSpacePercent: minFreeSpacePercent}
  28. location.volumes = make(map[needle.VolumeId]*Volume)
  29. location.ecVolumes = make(map[needle.VolumeId]*erasure_coding.EcVolume)
  30. go location.CheckDiskSpace()
  31. return location
  32. }
  33. func (l *DiskLocation) volumeIdFromPath(dir os.FileInfo) (needle.VolumeId, string, error) {
  34. name := dir.Name()
  35. if !dir.IsDir() && strings.HasSuffix(name, ".idx") {
  36. base := name[:len(name)-len(".idx")]
  37. collection, volumeId, err := parseCollectionVolumeId(base)
  38. return volumeId, collection, err
  39. }
  40. return 0, "", fmt.Errorf("Path is not a volume: %s", name)
  41. }
  42. func parseCollectionVolumeId(base string) (collection string, vid needle.VolumeId, err error) {
  43. i := strings.LastIndex(base, "_")
  44. if i > 0 {
  45. collection, base = base[0:i], base[i+1:]
  46. }
  47. vol, err := needle.NewVolumeId(base)
  48. return collection, vol, err
  49. }
  50. func (l *DiskLocation) loadExistingVolume(fileInfo os.FileInfo, needleMapKind NeedleMapType) bool {
  51. name := fileInfo.Name()
  52. if !fileInfo.IsDir() && strings.HasSuffix(name, ".idx") {
  53. vid, collection, err := l.volumeIdFromPath(fileInfo)
  54. if err != nil {
  55. glog.Warningf("get volume id failed, %s, err : %s", name, err)
  56. return false
  57. }
  58. // void loading one volume more than once
  59. l.volumesLock.RLock()
  60. _, found := l.volumes[vid]
  61. l.volumesLock.RUnlock()
  62. if found {
  63. glog.V(1).Infof("loaded volume, %v", vid)
  64. return true
  65. }
  66. v, e := NewVolume(l.Directory, collection, vid, needleMapKind, nil, nil, 0, 0)
  67. if e != nil {
  68. glog.V(0).Infof("new volume %s error %s", name, e)
  69. return false
  70. }
  71. l.SetVolume(vid, v)
  72. size, _, _ := v.FileStat()
  73. glog.V(0).Infof("data file %s, replicaPlacement=%s v=%d size=%d ttl=%s",
  74. l.Directory+"/"+name, v.ReplicaPlacement, v.Version(), size, v.Ttl.String())
  75. return true
  76. }
  77. return false
  78. }
  79. func (l *DiskLocation) concurrentLoadingVolumes(needleMapKind NeedleMapType, concurrency int) {
  80. task_queue := make(chan os.FileInfo, 10*concurrency)
  81. go func() {
  82. if dirs, err := ioutil.ReadDir(l.Directory); err == nil {
  83. for _, dir := range dirs {
  84. task_queue <- dir
  85. }
  86. }
  87. close(task_queue)
  88. }()
  89. var wg sync.WaitGroup
  90. for workerNum := 0; workerNum < concurrency; workerNum++ {
  91. wg.Add(1)
  92. go func() {
  93. defer wg.Done()
  94. for dir := range task_queue {
  95. _ = l.loadExistingVolume(dir, needleMapKind)
  96. }
  97. }()
  98. }
  99. wg.Wait()
  100. }
  101. func (l *DiskLocation) loadExistingVolumes(needleMapKind NeedleMapType) {
  102. l.concurrentLoadingVolumes(needleMapKind, 10)
  103. glog.V(0).Infof("Store started on dir: %s with %d volumes max %d", l.Directory, len(l.volumes), l.MaxVolumeCount)
  104. l.loadAllEcShards()
  105. glog.V(0).Infof("Store started on dir: %s with %d ec shards", l.Directory, len(l.ecVolumes))
  106. }
  107. func (l *DiskLocation) DeleteCollectionFromDiskLocation(collection string) (e error) {
  108. l.volumesLock.Lock()
  109. delVolsMap := l.unmountVolumeByCollection(collection)
  110. l.volumesLock.Unlock()
  111. l.ecVolumesLock.Lock()
  112. delEcVolsMap := l.unmountEcVolumeByCollection(collection)
  113. l.ecVolumesLock.Unlock()
  114. errChain := make(chan error, 2)
  115. var wg sync.WaitGroup
  116. wg.Add(2)
  117. go func() {
  118. for _, v := range delVolsMap {
  119. if err := v.Destroy(); err != nil {
  120. errChain <- err
  121. }
  122. }
  123. wg.Done()
  124. }()
  125. go func() {
  126. for _, v := range delEcVolsMap {
  127. v.Destroy()
  128. }
  129. wg.Done()
  130. }()
  131. go func() {
  132. wg.Wait()
  133. close(errChain)
  134. }()
  135. errBuilder := strings.Builder{}
  136. for err := range errChain {
  137. errBuilder.WriteString(err.Error())
  138. errBuilder.WriteString("; ")
  139. }
  140. if errBuilder.Len() > 0 {
  141. e = fmt.Errorf(errBuilder.String())
  142. }
  143. return
  144. }
  145. func (l *DiskLocation) deleteVolumeById(vid needle.VolumeId) (found bool, e error) {
  146. v, ok := l.volumes[vid]
  147. if !ok {
  148. return
  149. }
  150. e = v.Destroy()
  151. if e != nil {
  152. return
  153. }
  154. found = true
  155. delete(l.volumes, vid)
  156. return
  157. }
  158. func (l *DiskLocation) LoadVolume(vid needle.VolumeId, needleMapKind NeedleMapType) bool {
  159. if fileInfo, found := l.LocateVolume(vid); found {
  160. return l.loadExistingVolume(fileInfo, needleMapKind)
  161. }
  162. return false
  163. }
  164. func (l *DiskLocation) DeleteVolume(vid needle.VolumeId) error {
  165. l.volumesLock.Lock()
  166. defer l.volumesLock.Unlock()
  167. _, ok := l.volumes[vid]
  168. if !ok {
  169. return fmt.Errorf("Volume not found, VolumeId: %d", vid)
  170. }
  171. _, err := l.deleteVolumeById(vid)
  172. return err
  173. }
  174. func (l *DiskLocation) UnloadVolume(vid needle.VolumeId) error {
  175. l.volumesLock.Lock()
  176. defer l.volumesLock.Unlock()
  177. v, ok := l.volumes[vid]
  178. if !ok {
  179. return fmt.Errorf("Volume not loaded, VolumeId: %d", vid)
  180. }
  181. v.Close()
  182. delete(l.volumes, vid)
  183. return nil
  184. }
  185. func (l *DiskLocation) unmountVolumeByCollection(collectionName string) map[needle.VolumeId]*Volume {
  186. deltaVols := make(map[needle.VolumeId]*Volume, 0)
  187. for k, v := range l.volumes {
  188. if v.Collection == collectionName && !v.isCompacting {
  189. deltaVols[k] = v
  190. }
  191. }
  192. for k := range deltaVols {
  193. delete(l.volumes, k)
  194. }
  195. return deltaVols
  196. }
  197. func (l *DiskLocation) SetVolume(vid needle.VolumeId, volume *Volume) {
  198. l.volumesLock.Lock()
  199. defer l.volumesLock.Unlock()
  200. l.volumes[vid] = volume
  201. volume.location = l
  202. }
  203. func (l *DiskLocation) FindVolume(vid needle.VolumeId) (*Volume, bool) {
  204. l.volumesLock.RLock()
  205. defer l.volumesLock.RUnlock()
  206. v, ok := l.volumes[vid]
  207. return v, ok
  208. }
  209. func (l *DiskLocation) VolumesLen() int {
  210. l.volumesLock.RLock()
  211. defer l.volumesLock.RUnlock()
  212. return len(l.volumes)
  213. }
  214. func (l *DiskLocation) Close() {
  215. l.volumesLock.Lock()
  216. for _, v := range l.volumes {
  217. v.Close()
  218. }
  219. l.volumesLock.Unlock()
  220. l.ecVolumesLock.Lock()
  221. for _, ecVolume := range l.ecVolumes {
  222. ecVolume.Close()
  223. }
  224. l.ecVolumesLock.Unlock()
  225. return
  226. }
  227. func (l *DiskLocation) LocateVolume(vid needle.VolumeId) (os.FileInfo, bool) {
  228. if fileInfos, err := ioutil.ReadDir(l.Directory); err == nil {
  229. for _, fileInfo := range fileInfos {
  230. volId, _, err := l.volumeIdFromPath(fileInfo)
  231. if vid == volId && err == nil {
  232. return fileInfo, true
  233. }
  234. }
  235. }
  236. return nil, false
  237. }
  238. func (l *DiskLocation) UnUsedSpace(volumeSizeLimit uint64) (unUsedSpace uint64) {
  239. l.volumesLock.RLock()
  240. defer l.volumesLock.RUnlock()
  241. for _, vol := range l.volumes {
  242. if vol.IsReadOnly() {
  243. continue
  244. }
  245. datSize, idxSize, _ := vol.FileStat()
  246. unUsedSpace += volumeSizeLimit - (datSize + idxSize)
  247. }
  248. return
  249. }
  250. func (l *DiskLocation) CheckDiskSpace() {
  251. for {
  252. if dir, e := filepath.Abs(l.Directory); e == nil {
  253. s := stats.NewDiskStatus(dir)
  254. if (s.PercentFree < l.MinFreeSpacePercent) != l.isDiskSpaceLow {
  255. l.isDiskSpaceLow = !l.isDiskSpaceLow
  256. }
  257. if l.isDiskSpaceLow {
  258. glog.V(0).Infof("dir %s freePercent %.2f%% < min %.2f%%, isLowDiskSpace: %v", dir, s.PercentFree, l.MinFreeSpacePercent, l.isDiskSpaceLow)
  259. } else {
  260. glog.V(4).Infof("dir %s freePercent %.2f%% < min %.2f%%, isLowDiskSpace: %v", dir, s.PercentFree, l.MinFreeSpacePercent, l.isDiskSpaceLow)
  261. }
  262. }
  263. time.Sleep(time.Minute)
  264. }
  265. }