disk_location.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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) Close() {
  270. l.volumesLock.Lock()
  271. for _, v := range l.volumes {
  272. v.Close()
  273. }
  274. l.volumesLock.Unlock()
  275. l.ecVolumesLock.Lock()
  276. for _, ecVolume := range l.ecVolumes {
  277. ecVolume.Close()
  278. }
  279. l.ecVolumesLock.Unlock()
  280. return
  281. }
  282. func (l *DiskLocation) LocateVolume(vid needle.VolumeId) (os.DirEntry, bool) {
  283. // println("LocateVolume", vid, "on", l.Directory)
  284. if dirEntries, err := os.ReadDir(l.Directory); err == nil {
  285. for _, entry := range dirEntries {
  286. // println("checking", entry.Name(), "...")
  287. volId, _, err := volumeIdFromFileName(entry.Name())
  288. // println("volId", volId, "err", err)
  289. if vid == volId && err == nil {
  290. return entry, true
  291. }
  292. }
  293. }
  294. return nil, false
  295. }
  296. func (l *DiskLocation) UnUsedSpace(volumeSizeLimit uint64) (unUsedSpace uint64) {
  297. l.volumesLock.RLock()
  298. defer l.volumesLock.RUnlock()
  299. for _, vol := range l.volumes {
  300. if vol.IsReadOnly() {
  301. continue
  302. }
  303. datSize, idxSize, _ := vol.FileStat()
  304. unUsedSpace += volumeSizeLimit - (datSize + idxSize)
  305. }
  306. return
  307. }
  308. func (l *DiskLocation) CheckDiskSpace() {
  309. for {
  310. if dir, e := filepath.Abs(l.Directory); e == nil {
  311. s := stats.NewDiskStatus(dir)
  312. stats.VolumeServerResourceGauge.WithLabelValues(l.Directory, "all").Set(float64(s.All))
  313. stats.VolumeServerResourceGauge.WithLabelValues(l.Directory, "used").Set(float64(s.Used))
  314. stats.VolumeServerResourceGauge.WithLabelValues(l.Directory, "free").Set(float64(s.Free))
  315. isLow, desc := l.MinFreeSpace.IsLow(s.Free, s.PercentFree)
  316. if isLow != l.isDiskSpaceLow {
  317. l.isDiskSpaceLow = !l.isDiskSpaceLow
  318. }
  319. logLevel := glog.Level(4)
  320. if l.isDiskSpaceLow {
  321. logLevel = glog.Level(0)
  322. }
  323. glog.V(logLevel).Infof("dir %s %s", dir, desc)
  324. }
  325. time.Sleep(time.Minute)
  326. }
  327. }