volume_layout.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. package topology
  2. import (
  3. "errors"
  4. "fmt"
  5. "math/rand"
  6. "sync"
  7. "time"
  8. "github.com/chrislusf/seaweedfs/weed/glog"
  9. "github.com/chrislusf/seaweedfs/weed/storage"
  10. "github.com/chrislusf/seaweedfs/weed/storage/needle"
  11. "github.com/chrislusf/seaweedfs/weed/storage/super_block"
  12. )
  13. type copyState int
  14. const (
  15. noCopies copyState = 0 + iota
  16. insufficientCopies
  17. enoughCopies
  18. )
  19. type volumeState string
  20. const (
  21. readOnlyState volumeState = "ReadOnly"
  22. oversizedState = "Oversized"
  23. )
  24. type stateIndicator func(copyState) bool
  25. func ExistCopies() stateIndicator {
  26. return func(state copyState) bool { return state != noCopies }
  27. }
  28. func NoCopies() stateIndicator {
  29. return func(state copyState) bool { return state == noCopies }
  30. }
  31. type volumesBinaryState struct {
  32. rp *super_block.ReplicaPlacement
  33. name volumeState // the name for volume state (eg. "Readonly", "Oversized")
  34. indicator stateIndicator // indicate whether the volumes should be marked as `name`
  35. copyMap map[needle.VolumeId]*VolumeLocationList
  36. }
  37. func NewVolumesBinaryState(name volumeState, rp *super_block.ReplicaPlacement, indicator stateIndicator) *volumesBinaryState {
  38. return &volumesBinaryState{
  39. rp: rp,
  40. name: name,
  41. indicator: indicator,
  42. copyMap: make(map[needle.VolumeId]*VolumeLocationList),
  43. }
  44. }
  45. func (v *volumesBinaryState) Dump() (res []uint32) {
  46. for vid, list := range v.copyMap {
  47. if v.indicator(v.copyState(list)) {
  48. res = append(res, uint32(vid))
  49. }
  50. }
  51. return
  52. }
  53. func (v *volumesBinaryState) IsTrue(vid needle.VolumeId) bool {
  54. list, _ := v.copyMap[vid]
  55. return v.indicator(v.copyState(list))
  56. }
  57. func (v *volumesBinaryState) Add(vid needle.VolumeId, dn *DataNode) {
  58. list, _ := v.copyMap[vid]
  59. if list != nil {
  60. list.Set(dn)
  61. return
  62. }
  63. list = NewVolumeLocationList()
  64. list.Set(dn)
  65. v.copyMap[vid] = list
  66. }
  67. func (v *volumesBinaryState) Remove(vid needle.VolumeId, dn *DataNode) {
  68. list, _ := v.copyMap[vid]
  69. if list != nil {
  70. list.Remove(dn)
  71. if list.Length() == 0 {
  72. delete(v.copyMap, vid)
  73. }
  74. }
  75. }
  76. func (v *volumesBinaryState) copyState(list *VolumeLocationList) copyState {
  77. if list == nil {
  78. return noCopies
  79. }
  80. if list.Length() < v.rp.GetCopyCount() {
  81. return insufficientCopies
  82. }
  83. return enoughCopies
  84. }
  85. // mapping from volume to its locations, inverted from server to volume
  86. type VolumeLayout struct {
  87. rp *super_block.ReplicaPlacement
  88. ttl *needle.TTL
  89. vid2location map[needle.VolumeId]*VolumeLocationList
  90. writables []needle.VolumeId // transient array of writable volume id
  91. readonlyVolumes *volumesBinaryState // readonly volumes
  92. oversizedVolumes *volumesBinaryState // oversized volumes
  93. volumeSizeLimit uint64
  94. replicationAsMin bool
  95. accessLock sync.RWMutex
  96. }
  97. type VolumeLayoutStats struct {
  98. TotalSize uint64
  99. UsedSize uint64
  100. FileCount uint64
  101. }
  102. func NewVolumeLayout(rp *super_block.ReplicaPlacement, ttl *needle.TTL, volumeSizeLimit uint64, replicationAsMin bool) *VolumeLayout {
  103. return &VolumeLayout{
  104. rp: rp,
  105. ttl: ttl,
  106. vid2location: make(map[needle.VolumeId]*VolumeLocationList),
  107. writables: *new([]needle.VolumeId),
  108. readonlyVolumes: NewVolumesBinaryState(readOnlyState, rp, ExistCopies()),
  109. oversizedVolumes: NewVolumesBinaryState(oversizedState, rp, ExistCopies()),
  110. volumeSizeLimit: volumeSizeLimit,
  111. replicationAsMin: replicationAsMin,
  112. }
  113. }
  114. func (vl *VolumeLayout) String() string {
  115. vl.accessLock.RLock()
  116. defer vl.accessLock.RUnlock()
  117. return fmt.Sprintf("rp:%v, ttl:%v, vid2location:%v, writables:%v, volumeSizeLimit:%v", vl.rp, vl.ttl, vl.vid2location, vl.writables, vl.volumeSizeLimit)
  118. }
  119. func (vl *VolumeLayout) RegisterVolume(v *storage.VolumeInfo, dn *DataNode) {
  120. vl.accessLock.Lock()
  121. defer vl.accessLock.Unlock()
  122. defer vl.rememberOversizedVolume(v, dn)
  123. if _, ok := vl.vid2location[v.Id]; !ok {
  124. vl.vid2location[v.Id] = NewVolumeLocationList()
  125. }
  126. vl.vid2location[v.Id].Set(dn)
  127. // 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())
  128. for _, dn := range vl.vid2location[v.Id].list {
  129. if vInfo, err := dn.GetVolumesById(v.Id); err == nil {
  130. if vInfo.ReadOnly {
  131. glog.V(1).Infof("vid %d removed from writable", v.Id)
  132. vl.removeFromWritable(v.Id)
  133. vl.readonlyVolumes.Add(v.Id, dn)
  134. return
  135. } else {
  136. vl.readonlyVolumes.Remove(v.Id, dn)
  137. }
  138. } else {
  139. glog.V(1).Infof("vid %d removed from writable", v.Id)
  140. vl.removeFromWritable(v.Id)
  141. vl.readonlyVolumes.Remove(v.Id, dn)
  142. return
  143. }
  144. }
  145. }
  146. func (vl *VolumeLayout) rememberOversizedVolume(v *storage.VolumeInfo, dn *DataNode) {
  147. if vl.isOversized(v) {
  148. vl.oversizedVolumes.Add(v.Id, dn)
  149. } else {
  150. vl.oversizedVolumes.Remove(v.Id, dn)
  151. }
  152. }
  153. func (vl *VolumeLayout) UnRegisterVolume(v *storage.VolumeInfo, dn *DataNode) {
  154. vl.accessLock.Lock()
  155. defer vl.accessLock.Unlock()
  156. // remove from vid2location map
  157. location, ok := vl.vid2location[v.Id]
  158. if !ok {
  159. return
  160. }
  161. if location.Remove(dn) {
  162. vl.readonlyVolumes.Remove(v.Id, dn)
  163. vl.oversizedVolumes.Remove(v.Id, dn)
  164. vl.ensureCorrectWritables(v.Id)
  165. if location.Length() == 0 {
  166. delete(vl.vid2location, v.Id)
  167. }
  168. }
  169. }
  170. func (vl *VolumeLayout) EnsureCorrectWritables(v *storage.VolumeInfo) {
  171. vl.accessLock.Lock()
  172. defer vl.accessLock.Unlock()
  173. vl.ensureCorrectWritables(v.Id)
  174. }
  175. func (vl *VolumeLayout) ensureCorrectWritables(vid needle.VolumeId) {
  176. if vl.enoughCopies(vid) && vl.isAllWritable(vid) {
  177. if !vl.oversizedVolumes.IsTrue(vid) {
  178. vl.setVolumeWritable(vid)
  179. }
  180. } else {
  181. vl.removeFromWritable(vid)
  182. }
  183. }
  184. func (vl *VolumeLayout) isAllWritable(vid needle.VolumeId) bool {
  185. for _, dn := range vl.vid2location[vid].list {
  186. if v, found := dn.volumes[vid]; found {
  187. if v.ReadOnly {
  188. return false
  189. }
  190. }
  191. }
  192. return true
  193. }
  194. func (vl *VolumeLayout) isOversized(v *storage.VolumeInfo) bool {
  195. return uint64(v.Size) >= vl.volumeSizeLimit
  196. }
  197. func (vl *VolumeLayout) isWritable(v *storage.VolumeInfo) bool {
  198. return !vl.isOversized(v) &&
  199. v.Version == needle.CurrentVersion &&
  200. !v.ReadOnly
  201. }
  202. func (vl *VolumeLayout) isEmpty() bool {
  203. vl.accessLock.RLock()
  204. defer vl.accessLock.RUnlock()
  205. return len(vl.vid2location) == 0
  206. }
  207. func (vl *VolumeLayout) Lookup(vid needle.VolumeId) []*DataNode {
  208. vl.accessLock.RLock()
  209. defer vl.accessLock.RUnlock()
  210. if location := vl.vid2location[vid]; location != nil {
  211. return location.list
  212. }
  213. return nil
  214. }
  215. func (vl *VolumeLayout) ListVolumeServers() (nodes []*DataNode) {
  216. vl.accessLock.RLock()
  217. defer vl.accessLock.RUnlock()
  218. for _, location := range vl.vid2location {
  219. nodes = append(nodes, location.list...)
  220. }
  221. return
  222. }
  223. func (vl *VolumeLayout) PickForWrite(count uint64, option *VolumeGrowOption) (*needle.VolumeId, uint64, *VolumeLocationList, error) {
  224. vl.accessLock.RLock()
  225. defer vl.accessLock.RUnlock()
  226. lenWriters := len(vl.writables)
  227. if lenWriters <= 0 {
  228. glog.V(0).Infoln("No more writable volumes!")
  229. return nil, 0, nil, errors.New("No more writable volumes!")
  230. }
  231. if option.DataCenter == "" {
  232. vid := vl.writables[rand.Intn(lenWriters)]
  233. locationList := vl.vid2location[vid]
  234. if locationList != nil {
  235. return &vid, count, locationList, nil
  236. }
  237. return nil, 0, nil, errors.New("Strangely vid " + vid.String() + " is on no machine!")
  238. }
  239. var vid needle.VolumeId
  240. var locationList *VolumeLocationList
  241. counter := 0
  242. for _, v := range vl.writables {
  243. volumeLocationList := vl.vid2location[v]
  244. for _, dn := range volumeLocationList.list {
  245. if dn.GetDataCenter().Id() == NodeId(option.DataCenter) {
  246. if option.Rack != "" && dn.GetRack().Id() != NodeId(option.Rack) {
  247. continue
  248. }
  249. if option.DataNode != "" && dn.Id() != NodeId(option.DataNode) {
  250. continue
  251. }
  252. counter++
  253. if rand.Intn(counter) < 1 {
  254. vid, locationList = v, volumeLocationList
  255. }
  256. }
  257. }
  258. }
  259. return &vid, count, locationList, nil
  260. }
  261. func (vl *VolumeLayout) GetActiveVolumeCount(option *VolumeGrowOption) int {
  262. vl.accessLock.RLock()
  263. defer vl.accessLock.RUnlock()
  264. if option.DataCenter == "" {
  265. return len(vl.writables)
  266. }
  267. counter := 0
  268. for _, v := range vl.writables {
  269. for _, dn := range vl.vid2location[v].list {
  270. if dn.GetDataCenter().Id() == NodeId(option.DataCenter) {
  271. if option.Rack != "" && dn.GetRack().Id() != NodeId(option.Rack) {
  272. continue
  273. }
  274. if option.DataNode != "" && dn.Id() != NodeId(option.DataNode) {
  275. continue
  276. }
  277. counter++
  278. }
  279. }
  280. }
  281. return counter
  282. }
  283. func (vl *VolumeLayout) removeFromWritable(vid needle.VolumeId) bool {
  284. toDeleteIndex := -1
  285. for k, id := range vl.writables {
  286. if id == vid {
  287. toDeleteIndex = k
  288. break
  289. }
  290. }
  291. if toDeleteIndex >= 0 {
  292. glog.V(0).Infoln("Volume", vid, "becomes unwritable")
  293. vl.writables = append(vl.writables[0:toDeleteIndex], vl.writables[toDeleteIndex+1:]...)
  294. return true
  295. }
  296. return false
  297. }
  298. func (vl *VolumeLayout) setVolumeWritable(vid needle.VolumeId) bool {
  299. for _, v := range vl.writables {
  300. if v == vid {
  301. return false
  302. }
  303. }
  304. glog.V(0).Infoln("Volume", vid, "becomes writable")
  305. vl.writables = append(vl.writables, vid)
  306. return true
  307. }
  308. func (vl *VolumeLayout) SetVolumeUnavailable(dn *DataNode, vid needle.VolumeId) bool {
  309. vl.accessLock.Lock()
  310. defer vl.accessLock.Unlock()
  311. if location, ok := vl.vid2location[vid]; ok {
  312. if location.Remove(dn) {
  313. vl.readonlyVolumes.Remove(vid, dn)
  314. vl.oversizedVolumes.Remove(vid, dn)
  315. if location.Length() < vl.rp.GetCopyCount() {
  316. glog.V(0).Infoln("Volume", vid, "has", location.Length(), "replica, less than required", vl.rp.GetCopyCount())
  317. return vl.removeFromWritable(vid)
  318. }
  319. }
  320. }
  321. return false
  322. }
  323. func (vl *VolumeLayout) SetVolumeAvailable(dn *DataNode, vid needle.VolumeId, isReadOnly bool) bool {
  324. vl.accessLock.Lock()
  325. defer vl.accessLock.Unlock()
  326. vInfo, err := dn.GetVolumesById(vid)
  327. if err != nil {
  328. return false
  329. }
  330. vl.vid2location[vid].Set(dn)
  331. if vInfo.ReadOnly || isReadOnly {
  332. return false
  333. }
  334. if vl.enoughCopies(vid) {
  335. return vl.setVolumeWritable(vid)
  336. }
  337. return false
  338. }
  339. func (vl *VolumeLayout) enoughCopies(vid needle.VolumeId) bool {
  340. locations := vl.vid2location[vid].Length()
  341. desired := vl.rp.GetCopyCount()
  342. return locations == desired || (vl.replicationAsMin && locations > desired)
  343. }
  344. func (vl *VolumeLayout) SetVolumeCapacityFull(vid needle.VolumeId) bool {
  345. vl.accessLock.Lock()
  346. defer vl.accessLock.Unlock()
  347. // glog.V(0).Infoln("Volume", vid, "reaches full capacity.")
  348. return vl.removeFromWritable(vid)
  349. }
  350. func (vl *VolumeLayout) ToMap() map[string]interface{} {
  351. m := make(map[string]interface{})
  352. m["replication"] = vl.rp.String()
  353. m["ttl"] = vl.ttl.String()
  354. m["writables"] = vl.writables
  355. //m["locations"] = vl.vid2location
  356. return m
  357. }
  358. func (vl *VolumeLayout) Stats() *VolumeLayoutStats {
  359. vl.accessLock.RLock()
  360. defer vl.accessLock.RUnlock()
  361. ret := &VolumeLayoutStats{}
  362. freshThreshold := time.Now().Unix() - 60
  363. for vid, vll := range vl.vid2location {
  364. size, fileCount := vll.Stats(vid, freshThreshold)
  365. ret.FileCount += uint64(fileCount)
  366. ret.UsedSize += size
  367. if vl.readonlyVolumes.IsTrue(vid) {
  368. ret.TotalSize += size
  369. } else {
  370. ret.TotalSize += vl.volumeSizeLimit
  371. }
  372. }
  373. return ret
  374. }