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.

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