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.

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