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.

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