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.

409 lines
13 KiB

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