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.

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