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.

349 lines
8.5 KiB

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