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.

429 lines
10 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. "github.com/google/uuid"
  16. )
  17. type DiskLocation struct {
  18. Directory string
  19. DirectoryUuid string
  20. IdxDirectory string
  21. DiskType types.DiskType
  22. MaxVolumeCount int
  23. OriginalMaxVolumeCount int
  24. MinFreeSpace util.MinFreeSpace
  25. volumes map[needle.VolumeId]*Volume
  26. volumesLock sync.RWMutex
  27. // erasure coding
  28. ecVolumes map[needle.VolumeId]*erasure_coding.EcVolume
  29. ecVolumesLock sync.RWMutex
  30. isDiskSpaceLow bool
  31. }
  32. func GenerateDirUuid(dir string) (dirUuidString string, err error) {
  33. glog.V(1).Infof("Getting uuid of volume directory:%s", dir)
  34. dirUuidString = ""
  35. fileName := dir + "/vol_dir.uuid"
  36. if !util.FileExists(fileName) {
  37. dirUuid, _ := uuid.NewRandom()
  38. dirUuidString = dirUuid.String()
  39. writeErr := util.WriteFile(fileName, []byte(dirUuidString), 0644)
  40. if writeErr != nil {
  41. return "", fmt.Errorf("failed to write uuid to %s : %v", fileName, writeErr)
  42. }
  43. } else {
  44. uuidData, readErr := os.ReadFile(fileName)
  45. if readErr != nil {
  46. return "", fmt.Errorf("failed to read uuid from %s : %v", fileName, readErr)
  47. }
  48. dirUuidString = string(uuidData)
  49. }
  50. return dirUuidString, nil
  51. }
  52. func NewDiskLocation(dir string, maxVolumeCount int, minFreeSpace util.MinFreeSpace, idxDir string, diskType types.DiskType) *DiskLocation {
  53. dir = util.ResolvePath(dir)
  54. if idxDir == "" {
  55. idxDir = dir
  56. } else {
  57. idxDir = util.ResolvePath(idxDir)
  58. }
  59. dirUuid, err := GenerateDirUuid(dir)
  60. if err != nil {
  61. glog.Fatalf("cannot generate uuid of dir %s: %v", dir, err)
  62. }
  63. location := &DiskLocation{
  64. Directory: dir,
  65. DirectoryUuid: dirUuid,
  66. IdxDirectory: idxDir,
  67. DiskType: diskType,
  68. MaxVolumeCount: maxVolumeCount,
  69. OriginalMaxVolumeCount: maxVolumeCount,
  70. MinFreeSpace: minFreeSpace,
  71. }
  72. location.volumes = make(map[needle.VolumeId]*Volume)
  73. location.ecVolumes = make(map[needle.VolumeId]*erasure_coding.EcVolume)
  74. go location.CheckDiskSpace()
  75. return location
  76. }
  77. func volumeIdFromFileName(filename string) (needle.VolumeId, string, error) {
  78. if isValidVolume(filename) {
  79. base := filename[:len(filename)-4]
  80. collection, volumeId, err := parseCollectionVolumeId(base)
  81. return volumeId, collection, err
  82. }
  83. return 0, "", fmt.Errorf("file is not a volume: %s", filename)
  84. }
  85. func parseCollectionVolumeId(base string) (collection string, vid needle.VolumeId, err error) {
  86. i := strings.LastIndex(base, "_")
  87. if i > 0 {
  88. collection, base = base[0:i], base[i+1:]
  89. }
  90. vol, err := needle.NewVolumeId(base)
  91. return collection, vol, err
  92. }
  93. func isValidVolume(basename string) bool {
  94. return strings.HasSuffix(basename, ".idx") || strings.HasSuffix(basename, ".vif")
  95. }
  96. func getValidVolumeName(basename string) string {
  97. if isValidVolume(basename) {
  98. return basename[:len(basename)-4]
  99. }
  100. return ""
  101. }
  102. func (l *DiskLocation) loadExistingVolume(dirEntry os.DirEntry, needleMapKind NeedleMapKind, skipIfEcVolumesExists bool) bool {
  103. basename := dirEntry.Name()
  104. if dirEntry.IsDir() {
  105. return false
  106. }
  107. volumeName := getValidVolumeName(basename)
  108. if volumeName == "" {
  109. return false
  110. }
  111. // skip if ec volumes exists
  112. if skipIfEcVolumesExists {
  113. if util.FileExists(l.Directory + "/" + volumeName + ".ecx") {
  114. return false
  115. }
  116. }
  117. // check for incomplete volume
  118. noteFile := l.Directory + "/" + volumeName + ".note"
  119. if util.FileExists(noteFile) {
  120. note, _ := os.ReadFile(noteFile)
  121. glog.Warningf("volume %s was not completed: %s", volumeName, string(note))
  122. removeVolumeFiles(l.Directory + "/" + volumeName)
  123. removeVolumeFiles(l.IdxDirectory + "/" + volumeName)
  124. return false
  125. }
  126. // parse out collection, volume id
  127. vid, collection, err := volumeIdFromFileName(basename)
  128. if err != nil {
  129. glog.Warningf("get volume id failed, %s, err : %s", volumeName, err)
  130. return false
  131. }
  132. // avoid loading one volume more than once
  133. l.volumesLock.RLock()
  134. _, found := l.volumes[vid]
  135. l.volumesLock.RUnlock()
  136. if found {
  137. glog.V(1).Infof("loaded volume, %v", vid)
  138. return true
  139. }
  140. // load the volume
  141. v, e := NewVolume(l.Directory, l.IdxDirectory, collection, vid, needleMapKind, nil, nil, 0, 0)
  142. if e != nil {
  143. glog.V(0).Infof("new volume %s error %s", volumeName, e)
  144. return false
  145. }
  146. l.SetVolume(vid, v)
  147. size, _, _ := v.FileStat()
  148. glog.V(0).Infof("data file %s, replication=%s v=%d size=%d ttl=%s",
  149. l.Directory+"/"+volumeName+".dat", v.ReplicaPlacement, v.Version(), size, v.Ttl.String())
  150. return true
  151. }
  152. func (l *DiskLocation) concurrentLoadingVolumes(needleMapKind NeedleMapKind, concurrency int) {
  153. task_queue := make(chan os.DirEntry, 10*concurrency)
  154. go func() {
  155. foundVolumeNames := make(map[string]bool)
  156. if dirEntries, err := os.ReadDir(l.Directory); err == nil {
  157. for _, entry := range dirEntries {
  158. volumeName := getValidVolumeName(entry.Name())
  159. if volumeName == "" {
  160. continue
  161. }
  162. if _, found := foundVolumeNames[volumeName]; !found {
  163. foundVolumeNames[volumeName] = true
  164. task_queue <- entry
  165. }
  166. }
  167. }
  168. close(task_queue)
  169. }()
  170. var wg sync.WaitGroup
  171. for workerNum := 0; workerNum < concurrency; workerNum++ {
  172. wg.Add(1)
  173. go func() {
  174. defer wg.Done()
  175. for fi := range task_queue {
  176. _ = l.loadExistingVolume(fi, needleMapKind, true)
  177. }
  178. }()
  179. }
  180. wg.Wait()
  181. }
  182. func (l *DiskLocation) loadExistingVolumes(needleMapKind NeedleMapKind) {
  183. l.concurrentLoadingVolumes(needleMapKind, 10)
  184. glog.V(0).Infof("Store started on dir: %s with %d volumes max %d", l.Directory, len(l.volumes), l.MaxVolumeCount)
  185. l.loadAllEcShards()
  186. glog.V(0).Infof("Store started on dir: %s with %d ec shards", l.Directory, len(l.ecVolumes))
  187. }
  188. func (l *DiskLocation) DeleteCollectionFromDiskLocation(collection string) (e error) {
  189. l.volumesLock.Lock()
  190. delVolsMap := l.unmountVolumeByCollection(collection)
  191. l.volumesLock.Unlock()
  192. l.ecVolumesLock.Lock()
  193. delEcVolsMap := l.unmountEcVolumeByCollection(collection)
  194. l.ecVolumesLock.Unlock()
  195. errChain := make(chan error, 2)
  196. var wg sync.WaitGroup
  197. wg.Add(2)
  198. go func() {
  199. for _, v := range delVolsMap {
  200. if err := v.Destroy(); err != nil {
  201. errChain <- err
  202. }
  203. }
  204. wg.Done()
  205. }()
  206. go func() {
  207. for _, v := range delEcVolsMap {
  208. v.Destroy()
  209. }
  210. wg.Done()
  211. }()
  212. go func() {
  213. wg.Wait()
  214. close(errChain)
  215. }()
  216. errBuilder := strings.Builder{}
  217. for err := range errChain {
  218. errBuilder.WriteString(err.Error())
  219. errBuilder.WriteString("; ")
  220. }
  221. if errBuilder.Len() > 0 {
  222. e = fmt.Errorf(errBuilder.String())
  223. }
  224. return
  225. }
  226. func (l *DiskLocation) deleteVolumeById(vid needle.VolumeId) (found bool, e error) {
  227. v, ok := l.volumes[vid]
  228. if !ok {
  229. return
  230. }
  231. e = v.Destroy()
  232. if e != nil {
  233. return
  234. }
  235. found = true
  236. delete(l.volumes, vid)
  237. return
  238. }
  239. func (l *DiskLocation) LoadVolume(vid needle.VolumeId, needleMapKind NeedleMapKind) bool {
  240. if fileInfo, found := l.LocateVolume(vid); found {
  241. return l.loadExistingVolume(fileInfo, needleMapKind, false)
  242. }
  243. return false
  244. }
  245. var ErrVolumeNotFound = fmt.Errorf("volume not found")
  246. func (l *DiskLocation) DeleteVolume(vid needle.VolumeId) error {
  247. l.volumesLock.Lock()
  248. defer l.volumesLock.Unlock()
  249. _, ok := l.volumes[vid]
  250. if !ok {
  251. return ErrVolumeNotFound
  252. }
  253. _, err := l.deleteVolumeById(vid)
  254. return err
  255. }
  256. func (l *DiskLocation) UnloadVolume(vid needle.VolumeId) error {
  257. l.volumesLock.Lock()
  258. defer l.volumesLock.Unlock()
  259. v, ok := l.volumes[vid]
  260. if !ok {
  261. return ErrVolumeNotFound
  262. }
  263. v.Close()
  264. delete(l.volumes, vid)
  265. return nil
  266. }
  267. func (l *DiskLocation) unmountVolumeByCollection(collectionName string) map[needle.VolumeId]*Volume {
  268. deltaVols := make(map[needle.VolumeId]*Volume, 0)
  269. for k, v := range l.volumes {
  270. if v.Collection == collectionName && !v.isCompacting && !v.isCommitCompacting {
  271. deltaVols[k] = v
  272. }
  273. }
  274. for k := range deltaVols {
  275. delete(l.volumes, k)
  276. }
  277. return deltaVols
  278. }
  279. func (l *DiskLocation) SetVolume(vid needle.VolumeId, volume *Volume) {
  280. l.volumesLock.Lock()
  281. defer l.volumesLock.Unlock()
  282. l.volumes[vid] = volume
  283. volume.location = l
  284. }
  285. func (l *DiskLocation) FindVolume(vid needle.VolumeId) (*Volume, bool) {
  286. l.volumesLock.RLock()
  287. defer l.volumesLock.RUnlock()
  288. v, ok := l.volumes[vid]
  289. return v, ok
  290. }
  291. func (l *DiskLocation) VolumesLen() int {
  292. l.volumesLock.RLock()
  293. defer l.volumesLock.RUnlock()
  294. return len(l.volumes)
  295. }
  296. func (l *DiskLocation) SetStopping() {
  297. l.volumesLock.Lock()
  298. for _, v := range l.volumes {
  299. v.SetStopping()
  300. }
  301. l.volumesLock.Unlock()
  302. return
  303. }
  304. func (l *DiskLocation) Close() {
  305. l.volumesLock.Lock()
  306. for _, v := range l.volumes {
  307. v.Close()
  308. }
  309. l.volumesLock.Unlock()
  310. l.ecVolumesLock.Lock()
  311. for _, ecVolume := range l.ecVolumes {
  312. ecVolume.Close()
  313. }
  314. l.ecVolumesLock.Unlock()
  315. return
  316. }
  317. func (l *DiskLocation) LocateVolume(vid needle.VolumeId) (os.DirEntry, bool) {
  318. // println("LocateVolume", vid, "on", l.Directory)
  319. if dirEntries, err := os.ReadDir(l.Directory); err == nil {
  320. for _, entry := range dirEntries {
  321. // println("checking", entry.Name(), "...")
  322. volId, _, err := volumeIdFromFileName(entry.Name())
  323. // println("volId", volId, "err", err)
  324. if vid == volId && err == nil {
  325. return entry, true
  326. }
  327. }
  328. }
  329. return nil, false
  330. }
  331. func (l *DiskLocation) UnUsedSpace(volumeSizeLimit uint64) (unUsedSpace uint64) {
  332. l.volumesLock.RLock()
  333. defer l.volumesLock.RUnlock()
  334. for _, vol := range l.volumes {
  335. if vol.IsReadOnly() {
  336. continue
  337. }
  338. datSize, idxSize, _ := vol.FileStat()
  339. unUsedSpace += volumeSizeLimit - (datSize + idxSize)
  340. }
  341. return
  342. }
  343. func (l *DiskLocation) CheckDiskSpace() {
  344. for {
  345. if dir, e := filepath.Abs(l.Directory); e == nil {
  346. s := stats.NewDiskStatus(dir)
  347. stats.VolumeServerResourceGauge.WithLabelValues(l.Directory, "all").Set(float64(s.All))
  348. stats.VolumeServerResourceGauge.WithLabelValues(l.Directory, "used").Set(float64(s.Used))
  349. stats.VolumeServerResourceGauge.WithLabelValues(l.Directory, "free").Set(float64(s.Free))
  350. isLow, desc := l.MinFreeSpace.IsLow(s.Free, s.PercentFree)
  351. if isLow != l.isDiskSpaceLow {
  352. l.isDiskSpaceLow = !l.isDiskSpaceLow
  353. }
  354. logLevel := glog.Level(4)
  355. if l.isDiskSpaceLow {
  356. logLevel = glog.Level(0)
  357. }
  358. glog.V(logLevel).Infof("dir %s %s", dir, desc)
  359. }
  360. time.Sleep(time.Minute)
  361. }
  362. }