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.

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