store.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. package storage
  2. import (
  3. "fmt"
  4. "sync/atomic"
  5. "github.com/chrislusf/seaweedfs/weed/glog"
  6. "github.com/chrislusf/seaweedfs/weed/pb/master_pb"
  7. "github.com/chrislusf/seaweedfs/weed/stats"
  8. "github.com/chrislusf/seaweedfs/weed/storage/needle"
  9. . "github.com/chrislusf/seaweedfs/weed/storage/types"
  10. "google.golang.org/grpc"
  11. )
  12. const (
  13. MAX_TTL_VOLUME_REMOVAL_DELAY = 10 // 10 minutes
  14. )
  15. /*
  16. * A VolumeServer contains one Store
  17. */
  18. type Store struct {
  19. MasterAddress string
  20. grpcDialOption grpc.DialOption
  21. volumeSizeLimit uint64 //read from the master
  22. Ip string
  23. Port int
  24. PublicUrl string
  25. Locations []*DiskLocation
  26. dataCenter string //optional informaton, overwriting master setting if exists
  27. rack string //optional information, overwriting master setting if exists
  28. connected bool
  29. NeedleMapType NeedleMapType
  30. NewVolumesChan chan master_pb.VolumeShortInformationMessage
  31. DeletedVolumesChan chan master_pb.VolumeShortInformationMessage
  32. NewEcShardsChan chan master_pb.VolumeEcShardInformationMessage
  33. DeletedEcShardsChan chan master_pb.VolumeEcShardInformationMessage
  34. }
  35. func (s *Store) String() (str string) {
  36. str = fmt.Sprintf("Ip:%s, Port:%d, PublicUrl:%s, dataCenter:%s, rack:%s, connected:%v, volumeSizeLimit:%d", s.Ip, s.Port, s.PublicUrl, s.dataCenter, s.rack, s.connected, s.GetVolumeSizeLimit())
  37. return
  38. }
  39. func NewStore(grpcDialOption grpc.DialOption, port int, ip, publicUrl string, dirnames []string, maxVolumeCounts []int, needleMapKind NeedleMapType) (s *Store) {
  40. s = &Store{grpcDialOption: grpcDialOption, Port: port, Ip: ip, PublicUrl: publicUrl, NeedleMapType: needleMapKind}
  41. s.Locations = make([]*DiskLocation, 0)
  42. for i := 0; i < len(dirnames); i++ {
  43. location := NewDiskLocation(dirnames[i], maxVolumeCounts[i])
  44. location.loadExistingVolumes(needleMapKind)
  45. s.Locations = append(s.Locations, location)
  46. stats.VolumeServerMaxVolumeCounter.Add(float64(maxVolumeCounts[i]))
  47. }
  48. s.NewVolumesChan = make(chan master_pb.VolumeShortInformationMessage, 3)
  49. s.DeletedVolumesChan = make(chan master_pb.VolumeShortInformationMessage, 3)
  50. s.NewEcShardsChan = make(chan master_pb.VolumeEcShardInformationMessage, 3)
  51. s.DeletedEcShardsChan = make(chan master_pb.VolumeEcShardInformationMessage, 3)
  52. return
  53. }
  54. func (s *Store) AddVolume(volumeId needle.VolumeId, collection string, needleMapKind NeedleMapType, replicaPlacement string, ttlString string, preallocate int64, MemoryMapMaxSizeMb uint32) error {
  55. rt, e := NewReplicaPlacementFromString(replicaPlacement)
  56. if e != nil {
  57. return e
  58. }
  59. ttl, e := needle.ReadTTL(ttlString)
  60. if e != nil {
  61. return e
  62. }
  63. e = s.addVolume(volumeId, collection, needleMapKind, rt, ttl, preallocate, MemoryMapMaxSizeMb)
  64. return e
  65. }
  66. func (s *Store) DeleteCollection(collection string) (e error) {
  67. for _, location := range s.Locations {
  68. e = location.DeleteCollectionFromDiskLocation(collection)
  69. if e != nil {
  70. return
  71. }
  72. // let the heartbeat send the list of volumes, instead of sending the deleted volume ids to DeletedVolumesChan
  73. }
  74. return
  75. }
  76. func (s *Store) findVolume(vid needle.VolumeId) *Volume {
  77. for _, location := range s.Locations {
  78. if v, found := location.FindVolume(vid); found {
  79. return v
  80. }
  81. }
  82. return nil
  83. }
  84. func (s *Store) FindFreeLocation() (ret *DiskLocation) {
  85. max := 0
  86. for _, location := range s.Locations {
  87. currentFreeCount := location.MaxVolumeCount - location.VolumesLen()
  88. if currentFreeCount > max {
  89. max = currentFreeCount
  90. ret = location
  91. }
  92. }
  93. return ret
  94. }
  95. func (s *Store) addVolume(vid needle.VolumeId, collection string, needleMapKind NeedleMapType, replicaPlacement *ReplicaPlacement, ttl *needle.TTL, preallocate int64, memoryMapMaxSizeMb uint32) error {
  96. if s.findVolume(vid) != nil {
  97. return fmt.Errorf("Volume Id %d already exists!", vid)
  98. }
  99. if location := s.FindFreeLocation(); location != nil {
  100. glog.V(0).Infof("In dir %s adds volume:%v collection:%s replicaPlacement:%v ttl:%v",
  101. location.Directory, vid, collection, replicaPlacement, ttl)
  102. if volume, err := NewVolume(location.Directory, collection, vid, needleMapKind, replicaPlacement, ttl, preallocate, memoryMapMaxSizeMb); err == nil {
  103. location.SetVolume(vid, volume)
  104. glog.V(0).Infof("add volume %d", vid)
  105. s.NewVolumesChan <- master_pb.VolumeShortInformationMessage{
  106. Id: uint32(vid),
  107. Collection: collection,
  108. ReplicaPlacement: uint32(replicaPlacement.Byte()),
  109. Version: uint32(volume.Version()),
  110. Ttl: ttl.ToUint32(),
  111. }
  112. return nil
  113. } else {
  114. return err
  115. }
  116. }
  117. return fmt.Errorf("No more free space left")
  118. }
  119. func (s *Store) Status() []*VolumeInfo {
  120. var stats []*VolumeInfo
  121. for _, location := range s.Locations {
  122. location.RLock()
  123. for k, v := range location.volumes {
  124. s := &VolumeInfo{
  125. Id: needle.VolumeId(k),
  126. Size: v.ContentSize(),
  127. Collection: v.Collection,
  128. ReplicaPlacement: v.ReplicaPlacement,
  129. Version: v.Version(),
  130. FileCount: int(v.FileCount()),
  131. DeleteCount: int(v.DeletedCount()),
  132. DeletedByteCount: v.DeletedSize(),
  133. ReadOnly: v.readOnly,
  134. Ttl: v.Ttl,
  135. CompactRevision: uint32(v.CompactionRevision),
  136. }
  137. stats = append(stats, s)
  138. }
  139. location.RUnlock()
  140. }
  141. sortVolumeInfos(stats)
  142. return stats
  143. }
  144. func (s *Store) SetDataCenter(dataCenter string) {
  145. s.dataCenter = dataCenter
  146. }
  147. func (s *Store) SetRack(rack string) {
  148. s.rack = rack
  149. }
  150. func (s *Store) CollectHeartbeat() *master_pb.Heartbeat {
  151. var volumeMessages []*master_pb.VolumeInformationMessage
  152. maxVolumeCount := 0
  153. var maxFileKey NeedleId
  154. collectionVolumeSize := make(map[string]uint64)
  155. for _, location := range s.Locations {
  156. var deleteVids []needle.VolumeId
  157. maxVolumeCount = maxVolumeCount + location.MaxVolumeCount
  158. location.RLock()
  159. for _, v := range location.volumes {
  160. if maxFileKey < v.MaxFileKey() {
  161. maxFileKey = v.MaxFileKey()
  162. }
  163. if !v.expired(s.GetVolumeSizeLimit()) {
  164. volumeMessages = append(volumeMessages, v.ToVolumeInformationMessage())
  165. } else {
  166. if v.expiredLongEnough(MAX_TTL_VOLUME_REMOVAL_DELAY) {
  167. deleteVids = append(deleteVids, v.Id)
  168. } else {
  169. glog.V(0).Infoln("volume", v.Id, "is expired.")
  170. }
  171. }
  172. fileSize, _, _ := v.FileStat()
  173. collectionVolumeSize[v.Collection] += fileSize
  174. }
  175. location.RUnlock()
  176. if len(deleteVids) > 0 {
  177. // delete expired volumes.
  178. location.Lock()
  179. for _, vid := range deleteVids {
  180. location.deleteVolumeById(vid)
  181. glog.V(0).Infoln("volume", vid, "is deleted.")
  182. }
  183. location.Unlock()
  184. }
  185. }
  186. for col, size := range collectionVolumeSize {
  187. stats.VolumeServerDiskSizeGauge.WithLabelValues(col, "normal").Set(float64(size))
  188. }
  189. return &master_pb.Heartbeat{
  190. Ip: s.Ip,
  191. Port: uint32(s.Port),
  192. PublicUrl: s.PublicUrl,
  193. MaxVolumeCount: uint32(maxVolumeCount),
  194. MaxFileKey: NeedleIdToUint64(maxFileKey),
  195. DataCenter: s.dataCenter,
  196. Rack: s.rack,
  197. Volumes: volumeMessages,
  198. HasNoVolumes: len(volumeMessages) == 0,
  199. }
  200. }
  201. func (s *Store) Close() {
  202. for _, location := range s.Locations {
  203. location.Close()
  204. }
  205. }
  206. func (s *Store) WriteVolumeNeedle(i needle.VolumeId, n *needle.Needle) (size uint32, isUnchanged bool, err error) {
  207. if v := s.findVolume(i); v != nil {
  208. if v.readOnly {
  209. err = fmt.Errorf("volume %d is read only", i)
  210. return
  211. }
  212. if MaxPossibleVolumeSize >= v.ContentSize()+uint64(needle.GetActualSize(size, v.version)) {
  213. _, size, isUnchanged, err = v.writeNeedle(n)
  214. } else {
  215. err = fmt.Errorf("volume size limit %d exceeded! current size is %d", s.GetVolumeSizeLimit(), v.ContentSize())
  216. }
  217. return
  218. }
  219. glog.V(0).Infoln("volume", i, "not found!")
  220. err = fmt.Errorf("volume %d not found on %s:%d", i, s.Ip, s.Port)
  221. return
  222. }
  223. func (s *Store) DeleteVolumeNeedle(i needle.VolumeId, n *needle.Needle) (uint32, error) {
  224. if v := s.findVolume(i); v != nil {
  225. if v.readOnly {
  226. return 0, fmt.Errorf("volume %d is read only", i)
  227. }
  228. if MaxPossibleVolumeSize >= v.ContentSize()+uint64(needle.GetActualSize(0, v.version)) {
  229. return v.deleteNeedle(n)
  230. } else {
  231. return 0, fmt.Errorf("volume size limit %d exceeded! current size is %d", s.GetVolumeSizeLimit(), v.ContentSize())
  232. }
  233. }
  234. return 0, fmt.Errorf("volume %d not found on %s:%d", i, s.Ip, s.Port)
  235. }
  236. func (s *Store) ReadVolumeNeedle(i needle.VolumeId, n *needle.Needle) (int, error) {
  237. if v := s.findVolume(i); v != nil {
  238. return v.readNeedle(n)
  239. }
  240. return 0, fmt.Errorf("volume %d not found", i)
  241. }
  242. func (s *Store) GetVolume(i needle.VolumeId) *Volume {
  243. return s.findVolume(i)
  244. }
  245. func (s *Store) HasVolume(i needle.VolumeId) bool {
  246. v := s.findVolume(i)
  247. return v != nil
  248. }
  249. func (s *Store) MarkVolumeReadonly(i needle.VolumeId) error {
  250. v := s.findVolume(i)
  251. if v == nil {
  252. return fmt.Errorf("volume %d not found", i)
  253. }
  254. v.readOnly = true
  255. return nil
  256. }
  257. func (s *Store) MountVolume(i needle.VolumeId) error {
  258. for _, location := range s.Locations {
  259. if found := location.LoadVolume(i, s.NeedleMapType); found == true {
  260. glog.V(0).Infof("mount volume %d", i)
  261. v := s.findVolume(i)
  262. s.NewVolumesChan <- master_pb.VolumeShortInformationMessage{
  263. Id: uint32(v.Id),
  264. Collection: v.Collection,
  265. ReplicaPlacement: uint32(v.ReplicaPlacement.Byte()),
  266. Version: uint32(v.Version()),
  267. Ttl: v.Ttl.ToUint32(),
  268. }
  269. return nil
  270. }
  271. }
  272. return fmt.Errorf("volume %d not found on disk", i)
  273. }
  274. func (s *Store) UnmountVolume(i needle.VolumeId) error {
  275. v := s.findVolume(i)
  276. if v == nil {
  277. return nil
  278. }
  279. message := master_pb.VolumeShortInformationMessage{
  280. Id: uint32(v.Id),
  281. Collection: v.Collection,
  282. ReplicaPlacement: uint32(v.ReplicaPlacement.Byte()),
  283. Version: uint32(v.Version()),
  284. Ttl: v.Ttl.ToUint32(),
  285. }
  286. for _, location := range s.Locations {
  287. if err := location.UnloadVolume(i); err == nil {
  288. glog.V(0).Infof("UnmountVolume %d", i)
  289. s.DeletedVolumesChan <- message
  290. return nil
  291. }
  292. }
  293. return fmt.Errorf("volume %d not found on disk", i)
  294. }
  295. func (s *Store) DeleteVolume(i needle.VolumeId) error {
  296. v := s.findVolume(i)
  297. if v == nil {
  298. return nil
  299. }
  300. message := master_pb.VolumeShortInformationMessage{
  301. Id: uint32(v.Id),
  302. Collection: v.Collection,
  303. ReplicaPlacement: uint32(v.ReplicaPlacement.Byte()),
  304. Version: uint32(v.Version()),
  305. Ttl: v.Ttl.ToUint32(),
  306. }
  307. for _, location := range s.Locations {
  308. if error := location.deleteVolumeById(i); error == nil {
  309. glog.V(0).Infof("DeleteVolume %d", i)
  310. s.DeletedVolumesChan <- message
  311. return nil
  312. }
  313. }
  314. return fmt.Errorf("volume %d not found on disk", i)
  315. }
  316. func (s *Store) SetVolumeSizeLimit(x uint64) {
  317. atomic.StoreUint64(&s.volumeSizeLimit, x)
  318. }
  319. func (s *Store) GetVolumeSizeLimit() uint64 {
  320. return atomic.LoadUint64(&s.volumeSizeLimit)
  321. }