volume_layout.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. package topology
  2. import (
  3. "errors"
  4. "fmt"
  5. "math/rand"
  6. "sync"
  7. "sync/atomic"
  8. "time"
  9. "github.com/seaweedfs/seaweedfs/weed/storage/types"
  10. "github.com/seaweedfs/seaweedfs/weed/glog"
  11. "github.com/seaweedfs/seaweedfs/weed/storage"
  12. "github.com/seaweedfs/seaweedfs/weed/storage/needle"
  13. "github.com/seaweedfs/seaweedfs/weed/storage/super_block"
  14. )
  15. type copyState int
  16. const (
  17. noCopies copyState = 0 + iota
  18. insufficientCopies
  19. enoughCopies
  20. )
  21. type volumeState string
  22. const (
  23. readOnlyState volumeState = "ReadOnly"
  24. oversizedState = "Oversized"
  25. crowdedState = "Crowded"
  26. )
  27. type stateIndicator func(copyState) bool
  28. func ExistCopies() stateIndicator {
  29. return func(state copyState) bool { return state != noCopies }
  30. }
  31. func NoCopies() stateIndicator {
  32. return func(state copyState) bool { return state == noCopies }
  33. }
  34. type volumesBinaryState struct {
  35. rp *super_block.ReplicaPlacement
  36. name volumeState // the name for volume state (eg. "Readonly", "Oversized")
  37. indicator stateIndicator // indicate whether the volumes should be marked as `name`
  38. copyMap map[needle.VolumeId]*VolumeLocationList
  39. }
  40. func NewVolumesBinaryState(name volumeState, rp *super_block.ReplicaPlacement, indicator stateIndicator) *volumesBinaryState {
  41. return &volumesBinaryState{
  42. rp: rp,
  43. name: name,
  44. indicator: indicator,
  45. copyMap: make(map[needle.VolumeId]*VolumeLocationList),
  46. }
  47. }
  48. func (v *volumesBinaryState) Dump() (res []uint32) {
  49. for vid, list := range v.copyMap {
  50. if v.indicator(v.copyState(list)) {
  51. res = append(res, uint32(vid))
  52. }
  53. }
  54. return
  55. }
  56. func (v *volumesBinaryState) IsTrue(vid needle.VolumeId) bool {
  57. list, _ := v.copyMap[vid]
  58. return v.indicator(v.copyState(list))
  59. }
  60. func (v *volumesBinaryState) Add(vid needle.VolumeId, dn *DataNode) {
  61. list, _ := v.copyMap[vid]
  62. if list != nil {
  63. list.Set(dn)
  64. return
  65. }
  66. list = NewVolumeLocationList()
  67. list.Set(dn)
  68. v.copyMap[vid] = list
  69. }
  70. func (v *volumesBinaryState) Remove(vid needle.VolumeId, dn *DataNode) {
  71. list, _ := v.copyMap[vid]
  72. if list != nil {
  73. list.Remove(dn)
  74. if list.Length() == 0 {
  75. delete(v.copyMap, vid)
  76. }
  77. }
  78. }
  79. func (v *volumesBinaryState) copyState(list *VolumeLocationList) copyState {
  80. if list == nil {
  81. return noCopies
  82. }
  83. if list.Length() < v.rp.GetCopyCount() {
  84. return insufficientCopies
  85. }
  86. return enoughCopies
  87. }
  88. // mapping from volume to its locations, inverted from server to volume
  89. type VolumeLayout struct {
  90. growRequestCount int32
  91. growRequestTime time.Time
  92. rp *super_block.ReplicaPlacement
  93. ttl *needle.TTL
  94. diskType types.DiskType
  95. vid2location map[needle.VolumeId]*VolumeLocationList
  96. writables []needle.VolumeId // transient array of writable volume id
  97. crowded map[needle.VolumeId]struct{}
  98. readonlyVolumes *volumesBinaryState // readonly volumes
  99. oversizedVolumes *volumesBinaryState // oversized volumes
  100. vacuumedVolumes map[needle.VolumeId]time.Time
  101. volumeSizeLimit uint64
  102. replicationAsMin bool
  103. accessLock sync.RWMutex
  104. }
  105. type VolumeLayoutStats struct {
  106. TotalSize uint64
  107. UsedSize uint64
  108. FileCount uint64
  109. }
  110. func NewVolumeLayout(rp *super_block.ReplicaPlacement, ttl *needle.TTL, diskType types.DiskType, volumeSizeLimit uint64, replicationAsMin bool) *VolumeLayout {
  111. return &VolumeLayout{
  112. rp: rp,
  113. ttl: ttl,
  114. diskType: diskType,
  115. vid2location: make(map[needle.VolumeId]*VolumeLocationList),
  116. writables: *new([]needle.VolumeId),
  117. crowded: make(map[needle.VolumeId]struct{}),
  118. readonlyVolumes: NewVolumesBinaryState(readOnlyState, rp, ExistCopies()),
  119. oversizedVolumes: NewVolumesBinaryState(oversizedState, rp, ExistCopies()),
  120. vacuumedVolumes: make(map[needle.VolumeId]time.Time),
  121. volumeSizeLimit: volumeSizeLimit,
  122. replicationAsMin: replicationAsMin,
  123. }
  124. }
  125. func (vl *VolumeLayout) String() string {
  126. return fmt.Sprintf("rp:%v, ttl:%v, writables:%v, volumeSizeLimit:%v", vl.rp, vl.ttl, vl.writables, vl.volumeSizeLimit)
  127. }
  128. func (vl *VolumeLayout) RegisterVolume(v *storage.VolumeInfo, dn *DataNode) {
  129. vl.accessLock.Lock()
  130. defer vl.accessLock.Unlock()
  131. defer vl.rememberOversizedVolume(v, dn)
  132. if _, ok := vl.vid2location[v.Id]; !ok {
  133. vl.vid2location[v.Id] = NewVolumeLocationList()
  134. }
  135. vl.vid2location[v.Id].Set(dn)
  136. // glog.V(4).Infof("volume %d added to %s len %d copy %d", v.Id, dn.Id(), vl.vid2location[v.Id].Length(), v.ReplicaPlacement.GetCopyCount())
  137. for _, dn := range vl.vid2location[v.Id].list {
  138. if vInfo, err := dn.GetVolumesById(v.Id); err == nil {
  139. if vInfo.ReadOnly {
  140. glog.V(1).Infof("vid %d removed from writable", v.Id)
  141. vl.removeFromWritable(v.Id)
  142. vl.readonlyVolumes.Add(v.Id, dn)
  143. return
  144. } else {
  145. vl.readonlyVolumes.Remove(v.Id, dn)
  146. }
  147. } else {
  148. glog.V(1).Infof("vid %d removed from writable", v.Id)
  149. vl.removeFromWritable(v.Id)
  150. vl.readonlyVolumes.Remove(v.Id, dn)
  151. return
  152. }
  153. }
  154. }
  155. func (vl *VolumeLayout) rememberOversizedVolume(v *storage.VolumeInfo, dn *DataNode) {
  156. if vl.isOversized(v) {
  157. vl.oversizedVolumes.Add(v.Id, dn)
  158. } else {
  159. vl.oversizedVolumes.Remove(v.Id, dn)
  160. }
  161. }
  162. func (vl *VolumeLayout) UnRegisterVolume(v *storage.VolumeInfo, dn *DataNode) {
  163. vl.accessLock.Lock()
  164. defer vl.accessLock.Unlock()
  165. // remove from vid2location map
  166. location, ok := vl.vid2location[v.Id]
  167. if !ok {
  168. return
  169. }
  170. if location.Remove(dn) {
  171. vl.readonlyVolumes.Remove(v.Id, dn)
  172. vl.oversizedVolumes.Remove(v.Id, dn)
  173. vl.ensureCorrectWritables(v.Id)
  174. if location.Length() == 0 {
  175. delete(vl.vid2location, v.Id)
  176. }
  177. }
  178. }
  179. func (vl *VolumeLayout) EnsureCorrectWritables(v *storage.VolumeInfo) {
  180. vl.accessLock.Lock()
  181. defer vl.accessLock.Unlock()
  182. vl.ensureCorrectWritables(v.Id)
  183. }
  184. func (vl *VolumeLayout) ensureCorrectWritables(vid needle.VolumeId) {
  185. if vl.enoughCopies(vid) && vl.isAllWritable(vid) {
  186. if !vl.oversizedVolumes.IsTrue(vid) {
  187. vl.setVolumeWritable(vid)
  188. }
  189. } else {
  190. if !vl.enoughCopies(vid) {
  191. glog.V(0).Infof("volume %d does not have enough copies", vid)
  192. }
  193. if !vl.isAllWritable(vid) {
  194. glog.V(0).Infof("volume %d are not all writable", vid)
  195. }
  196. glog.V(0).Infof("volume %d remove from writable", vid)
  197. vl.removeFromWritable(vid)
  198. }
  199. }
  200. func (vl *VolumeLayout) isAllWritable(vid needle.VolumeId) bool {
  201. for _, dn := range vl.vid2location[vid].list {
  202. if v, getError := dn.GetVolumesById(vid); getError == nil {
  203. if v.ReadOnly {
  204. return false
  205. }
  206. }
  207. }
  208. return true
  209. }
  210. func (vl *VolumeLayout) isOversized(v *storage.VolumeInfo) bool {
  211. return uint64(v.Size) >= vl.volumeSizeLimit
  212. }
  213. func (vl *VolumeLayout) isWritable(v *storage.VolumeInfo) bool {
  214. return !vl.isOversized(v) &&
  215. v.Version == needle.CurrentVersion &&
  216. !v.ReadOnly
  217. }
  218. func (vl *VolumeLayout) isEmpty() bool {
  219. vl.accessLock.RLock()
  220. defer vl.accessLock.RUnlock()
  221. return len(vl.vid2location) == 0
  222. }
  223. func (vl *VolumeLayout) Lookup(vid needle.VolumeId) []*DataNode {
  224. vl.accessLock.RLock()
  225. defer vl.accessLock.RUnlock()
  226. if location := vl.vid2location[vid]; location != nil {
  227. return location.list
  228. }
  229. return nil
  230. }
  231. func (vl *VolumeLayout) ListVolumeServers() (nodes []*DataNode) {
  232. vl.accessLock.RLock()
  233. defer vl.accessLock.RUnlock()
  234. for _, location := range vl.vid2location {
  235. nodes = append(nodes, location.list...)
  236. }
  237. return
  238. }
  239. func (vl *VolumeLayout) PickForWrite(count uint64, option *VolumeGrowOption) (*needle.VolumeId, uint64, *VolumeLocationList, error) {
  240. vl.accessLock.RLock()
  241. defer vl.accessLock.RUnlock()
  242. lenWriters := len(vl.writables)
  243. if lenWriters <= 0 {
  244. //glog.V(0).Infoln("No more writable volumes!")
  245. return nil, 0, nil, errors.New("No more writable volumes!")
  246. }
  247. if option.DataCenter == "" && option.Rack == "" && option.DataNode == "" {
  248. vid := vl.writables[rand.Intn(lenWriters)]
  249. locationList := vl.vid2location[vid]
  250. if locationList != nil {
  251. return &vid, count, locationList, nil
  252. }
  253. return nil, 0, nil, errors.New("Strangely vid " + vid.String() + " is on no machine!")
  254. }
  255. var vid needle.VolumeId
  256. var locationList *VolumeLocationList
  257. counter := 0
  258. for _, v := range vl.writables {
  259. volumeLocationList := vl.vid2location[v]
  260. for _, dn := range volumeLocationList.list {
  261. if option.DataCenter != "" && dn.GetDataCenter().Id() != NodeId(option.DataCenter) {
  262. continue
  263. }
  264. if option.Rack != "" && dn.GetRack().Id() != NodeId(option.Rack) {
  265. continue
  266. }
  267. if option.DataNode != "" && dn.Id() != NodeId(option.DataNode) {
  268. continue
  269. }
  270. counter++
  271. if rand.Intn(counter) < 1 {
  272. vid, locationList = v, volumeLocationList.Copy()
  273. }
  274. }
  275. }
  276. return &vid, count, locationList, nil
  277. }
  278. func (vl *VolumeLayout) HasGrowRequest() bool {
  279. if atomic.LoadInt32(&vl.growRequestCount) > 0 &&
  280. vl.growRequestTime.Add(time.Minute).After(time.Now()) {
  281. return true
  282. }
  283. return false
  284. }
  285. func (vl *VolumeLayout) AddGrowRequest() {
  286. vl.growRequestTime = time.Now()
  287. atomic.AddInt32(&vl.growRequestCount, 1)
  288. }
  289. func (vl *VolumeLayout) DoneGrowRequest() {
  290. vl.growRequestTime = time.Unix(0, 0)
  291. atomic.StoreInt32(&vl.growRequestCount, 0)
  292. }
  293. func (vl *VolumeLayout) ShouldGrowVolumes(option *VolumeGrowOption) bool {
  294. active, crowded := vl.GetActiveVolumeCount(option)
  295. //glog.V(0).Infof("active volume: %d, high usage volume: %d\n", active, high)
  296. return active <= crowded
  297. }
  298. func (vl *VolumeLayout) GetActiveVolumeCount(option *VolumeGrowOption) (active, crowded int) {
  299. vl.accessLock.RLock()
  300. defer vl.accessLock.RUnlock()
  301. if option.DataCenter == "" {
  302. return len(vl.writables), len(vl.crowded)
  303. }
  304. for _, v := range vl.writables {
  305. for _, dn := range vl.vid2location[v].list {
  306. if dn.GetDataCenter().Id() == NodeId(option.DataCenter) {
  307. if option.Rack != "" && dn.GetRack().Id() != NodeId(option.Rack) {
  308. continue
  309. }
  310. if option.DataNode != "" && dn.Id() != NodeId(option.DataNode) {
  311. continue
  312. }
  313. active++
  314. info, _ := dn.GetVolumesById(v)
  315. if float64(info.Size) > float64(vl.volumeSizeLimit)*option.Threshold() {
  316. crowded++
  317. }
  318. }
  319. }
  320. }
  321. return
  322. }
  323. func (vl *VolumeLayout) removeFromWritable(vid needle.VolumeId) bool {
  324. toDeleteIndex := -1
  325. for k, id := range vl.writables {
  326. if id == vid {
  327. toDeleteIndex = k
  328. break
  329. }
  330. }
  331. if toDeleteIndex >= 0 {
  332. glog.V(0).Infoln("Volume", vid, "becomes unwritable")
  333. vl.writables = append(vl.writables[0:toDeleteIndex], vl.writables[toDeleteIndex+1:]...)
  334. vl.removeFromCrowded(vid)
  335. return true
  336. }
  337. return false
  338. }
  339. func (vl *VolumeLayout) setVolumeWritable(vid needle.VolumeId) bool {
  340. for _, v := range vl.writables {
  341. if v == vid {
  342. return false
  343. }
  344. }
  345. glog.V(0).Infoln("Volume", vid, "becomes writable")
  346. vl.writables = append(vl.writables, vid)
  347. return true
  348. }
  349. func (vl *VolumeLayout) SetVolumeReadOnly(dn *DataNode, vid needle.VolumeId) bool {
  350. vl.accessLock.Lock()
  351. defer vl.accessLock.Unlock()
  352. if _, ok := vl.vid2location[vid]; ok {
  353. vl.readonlyVolumes.Add(vid, dn)
  354. return vl.removeFromWritable(vid)
  355. }
  356. return true
  357. }
  358. func (vl *VolumeLayout) SetVolumeWritable(dn *DataNode, vid needle.VolumeId) bool {
  359. vl.accessLock.Lock()
  360. defer vl.accessLock.Unlock()
  361. if _, ok := vl.vid2location[vid]; ok {
  362. vl.readonlyVolumes.Remove(vid, dn)
  363. }
  364. if vl.enoughCopies(vid) {
  365. return vl.setVolumeWritable(vid)
  366. }
  367. return false
  368. }
  369. func (vl *VolumeLayout) SetVolumeUnavailable(dn *DataNode, vid needle.VolumeId) bool {
  370. vl.accessLock.Lock()
  371. defer vl.accessLock.Unlock()
  372. if location, ok := vl.vid2location[vid]; ok {
  373. if location.Remove(dn) {
  374. vl.readonlyVolumes.Remove(vid, dn)
  375. vl.oversizedVolumes.Remove(vid, dn)
  376. if location.Length() < vl.rp.GetCopyCount() {
  377. glog.V(0).Infoln("Volume", vid, "has", location.Length(), "replica, less than required", vl.rp.GetCopyCount())
  378. return vl.removeFromWritable(vid)
  379. }
  380. }
  381. }
  382. return false
  383. }
  384. func (vl *VolumeLayout) SetVolumeAvailable(dn *DataNode, vid needle.VolumeId, isReadOnly, isFullCapacity bool) bool {
  385. vl.accessLock.Lock()
  386. defer vl.accessLock.Unlock()
  387. vInfo, err := dn.GetVolumesById(vid)
  388. if err != nil {
  389. return false
  390. }
  391. vl.vid2location[vid].Set(dn)
  392. if vInfo.ReadOnly || isReadOnly || isFullCapacity {
  393. return false
  394. }
  395. if vl.enoughCopies(vid) {
  396. return vl.setVolumeWritable(vid)
  397. }
  398. return false
  399. }
  400. func (vl *VolumeLayout) enoughCopies(vid needle.VolumeId) bool {
  401. locations := vl.vid2location[vid].Length()
  402. desired := vl.rp.GetCopyCount()
  403. return locations == desired || (vl.replicationAsMin && locations > desired)
  404. }
  405. func (vl *VolumeLayout) SetVolumeCapacityFull(vid needle.VolumeId) bool {
  406. vl.accessLock.Lock()
  407. defer vl.accessLock.Unlock()
  408. wasWritable := vl.removeFromWritable(vid)
  409. if wasWritable {
  410. glog.V(0).Infof("Volume %d reaches full capacity.", vid)
  411. }
  412. return wasWritable
  413. }
  414. func (vl *VolumeLayout) removeFromCrowded(vid needle.VolumeId) {
  415. delete(vl.crowded, vid)
  416. }
  417. func (vl *VolumeLayout) setVolumeCrowded(vid needle.VolumeId) {
  418. if _, ok := vl.crowded[vid]; !ok {
  419. vl.crowded[vid] = struct{}{}
  420. glog.V(0).Infoln("Volume", vid, "becomes crowded")
  421. }
  422. }
  423. func (vl *VolumeLayout) SetVolumeCrowded(vid needle.VolumeId) {
  424. // since delete is guarded by accessLock.Lock(),
  425. // and is always called in sequential order,
  426. // RLock() should be safe enough
  427. vl.accessLock.RLock()
  428. defer vl.accessLock.RUnlock()
  429. for _, v := range vl.writables {
  430. if v == vid {
  431. vl.setVolumeCrowded(vid)
  432. break
  433. }
  434. }
  435. }
  436. type VolumeLayoutInfo struct {
  437. Replication string `json:"replication"`
  438. TTL string `json:"ttl"`
  439. Writables []needle.VolumeId `json:"writables"`
  440. Collection string `json:"collection"`
  441. }
  442. func (vl *VolumeLayout) ToInfo() (info VolumeLayoutInfo) {
  443. info.Replication = vl.rp.String()
  444. info.TTL = vl.ttl.String()
  445. info.Writables = vl.writables
  446. //m["locations"] = vl.vid2location
  447. return
  448. }
  449. func (vl *VolumeLayout) Stats() *VolumeLayoutStats {
  450. vl.accessLock.RLock()
  451. defer vl.accessLock.RUnlock()
  452. ret := &VolumeLayoutStats{}
  453. freshThreshold := time.Now().Unix() - 60
  454. for vid, vll := range vl.vid2location {
  455. size, fileCount := vll.Stats(vid, freshThreshold)
  456. ret.FileCount += uint64(fileCount)
  457. ret.UsedSize += size * uint64(vll.Length())
  458. if vl.readonlyVolumes.IsTrue(vid) {
  459. ret.TotalSize += size * uint64(vll.Length())
  460. } else {
  461. ret.TotalSize += vl.volumeSizeLimit * uint64(vll.Length())
  462. }
  463. }
  464. return ret
  465. }