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.

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