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.

386 lines
9.1 KiB

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