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.

332 lines
8.1 KiB

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