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.

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