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.

346 lines
9.6 KiB

10 years ago
12 years ago
12 years ago
10 years ago
  1. package storage
  2. import (
  3. "errors"
  4. "fmt"
  5. "strconv"
  6. "strings"
  7. "github.com/chrislusf/seaweedfs/weed/glog"
  8. "github.com/chrislusf/seaweedfs/weed/operation"
  9. "github.com/chrislusf/seaweedfs/weed/pb/master_pb"
  10. )
  11. const (
  12. MAX_TTL_VOLUME_REMOVAL_DELAY = 10 // 10 minutes
  13. )
  14. type MasterNodes struct {
  15. nodes []string
  16. leader string
  17. possibleLeader string
  18. }
  19. func (mn *MasterNodes) String() string {
  20. return fmt.Sprintf("nodes:%v, leader:%s", mn.nodes, mn.leader)
  21. }
  22. func NewMasterNodes(bootstrapNode string) (mn *MasterNodes) {
  23. mn = &MasterNodes{nodes: []string{bootstrapNode}, leader: ""}
  24. return
  25. }
  26. func (mn *MasterNodes) Reset() {
  27. if mn.leader != "" {
  28. mn.leader = ""
  29. glog.V(0).Infof("Resetting master nodes: %v", mn)
  30. }
  31. }
  32. func (mn *MasterNodes) SetPossibleLeader(possibleLeader string) {
  33. // TODO try to check this leader first
  34. mn.possibleLeader = possibleLeader
  35. }
  36. func (mn *MasterNodes) FindMaster() (leader string, err error) {
  37. if len(mn.nodes) == 0 {
  38. return "", errors.New("No master node found!")
  39. }
  40. if mn.leader == "" {
  41. for _, m := range mn.nodes {
  42. glog.V(4).Infof("Listing masters on %s", m)
  43. if leader, masters, e := operation.ListMasters(m); e == nil {
  44. if leader != "" {
  45. mn.nodes = append(masters, m)
  46. mn.leader = leader
  47. glog.V(2).Infof("current master nodes is %v", mn)
  48. break
  49. }
  50. } else {
  51. glog.V(4).Infof("Failed listing masters on %s: %v", m, e)
  52. }
  53. }
  54. }
  55. if mn.leader == "" {
  56. return "", errors.New("No master node available!")
  57. }
  58. return mn.leader, nil
  59. }
  60. /*
  61. * A VolumeServer contains one Store
  62. */
  63. type Store struct {
  64. Ip string
  65. Port int
  66. PublicUrl string
  67. Locations []*DiskLocation
  68. dataCenter string //optional informaton, overwriting master setting if exists
  69. rack string //optional information, overwriting master setting if exists
  70. connected bool
  71. VolumeSizeLimit uint64 //read from the master
  72. Client master_pb.Seaweed_SendHeartbeatClient
  73. NeedleMapType NeedleMapType
  74. }
  75. func (s *Store) String() (str string) {
  76. 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.VolumeSizeLimit)
  77. return
  78. }
  79. func NewStore(port int, ip, publicUrl string, dirnames []string, maxVolumeCounts []int, needleMapKind NeedleMapType) (s *Store) {
  80. s = &Store{Port: port, Ip: ip, PublicUrl: publicUrl, NeedleMapType: needleMapKind}
  81. s.Locations = make([]*DiskLocation, 0)
  82. for i := 0; i < len(dirnames); i++ {
  83. location := NewDiskLocation(dirnames[i], maxVolumeCounts[i])
  84. location.loadExistingVolumes(needleMapKind)
  85. s.Locations = append(s.Locations, location)
  86. }
  87. return
  88. }
  89. func (s *Store) AddVolume(volumeListString string, collection string, needleMapKind NeedleMapType, replicaPlacement string, ttlString string, preallocate int64) error {
  90. rt, e := NewReplicaPlacementFromString(replicaPlacement)
  91. if e != nil {
  92. return e
  93. }
  94. ttl, e := ReadTTL(ttlString)
  95. if e != nil {
  96. return e
  97. }
  98. for _, range_string := range strings.Split(volumeListString, ",") {
  99. if strings.Index(range_string, "-") < 0 {
  100. id_string := range_string
  101. id, err := NewVolumeId(id_string)
  102. if err != nil {
  103. return fmt.Errorf("Volume Id %s is not a valid unsigned integer!", id_string)
  104. }
  105. e = s.addVolume(VolumeId(id), collection, needleMapKind, rt, ttl, preallocate)
  106. } else {
  107. pair := strings.Split(range_string, "-")
  108. start, start_err := strconv.ParseUint(pair[0], 10, 64)
  109. if start_err != nil {
  110. return fmt.Errorf("Volume Start Id %s is not a valid unsigned integer!", pair[0])
  111. }
  112. end, end_err := strconv.ParseUint(pair[1], 10, 64)
  113. if end_err != nil {
  114. return fmt.Errorf("Volume End Id %s is not a valid unsigned integer!", pair[1])
  115. }
  116. for id := start; id <= end; id++ {
  117. if err := s.addVolume(VolumeId(id), collection, needleMapKind, rt, ttl, preallocate); err != nil {
  118. e = err
  119. }
  120. }
  121. }
  122. }
  123. return e
  124. }
  125. func (s *Store) DeleteCollection(collection string) (e error) {
  126. for _, location := range s.Locations {
  127. e = location.DeleteCollectionFromDiskLocation(collection)
  128. if e != nil {
  129. return
  130. }
  131. }
  132. return
  133. }
  134. func (s *Store) findVolume(vid VolumeId) *Volume {
  135. for _, location := range s.Locations {
  136. if v, found := location.FindVolume(vid); found {
  137. return v
  138. }
  139. }
  140. return nil
  141. }
  142. func (s *Store) findFreeLocation() (ret *DiskLocation) {
  143. max := 0
  144. for _, location := range s.Locations {
  145. currentFreeCount := location.MaxVolumeCount - location.VolumesLen()
  146. if currentFreeCount > max {
  147. max = currentFreeCount
  148. ret = location
  149. }
  150. }
  151. return ret
  152. }
  153. func (s *Store) addVolume(vid VolumeId, collection string, needleMapKind NeedleMapType, replicaPlacement *ReplicaPlacement, ttl *TTL, preallocate int64) error {
  154. if s.findVolume(vid) != nil {
  155. return fmt.Errorf("Volume Id %d already exists!", vid)
  156. }
  157. if location := s.findFreeLocation(); location != nil {
  158. glog.V(0).Infof("In dir %s adds volume:%v collection:%s replicaPlacement:%v ttl:%v",
  159. location.Directory, vid, collection, replicaPlacement, ttl)
  160. if volume, err := NewVolume(location.Directory, collection, vid, needleMapKind, replicaPlacement, ttl, preallocate); err == nil {
  161. location.SetVolume(vid, volume)
  162. return nil
  163. } else {
  164. return err
  165. }
  166. }
  167. return fmt.Errorf("No more free space left")
  168. }
  169. func (s *Store) Status() []*VolumeInfo {
  170. var stats []*VolumeInfo
  171. for _, location := range s.Locations {
  172. location.RLock()
  173. for k, v := range location.volumes {
  174. s := &VolumeInfo{
  175. Id: VolumeId(k),
  176. Size: v.ContentSize(),
  177. Collection: v.Collection,
  178. ReplicaPlacement: v.ReplicaPlacement,
  179. Version: v.Version(),
  180. FileCount: v.nm.FileCount(),
  181. DeleteCount: v.nm.DeletedCount(),
  182. DeletedByteCount: v.nm.DeletedSize(),
  183. ReadOnly: v.readOnly,
  184. Ttl: v.Ttl}
  185. stats = append(stats, s)
  186. }
  187. location.RUnlock()
  188. }
  189. sortVolumeInfos(stats)
  190. return stats
  191. }
  192. func (s *Store) SetDataCenter(dataCenter string) {
  193. s.dataCenter = dataCenter
  194. }
  195. func (s *Store) SetRack(rack string) {
  196. s.rack = rack
  197. }
  198. func (s *Store) CollectHeartbeat() *master_pb.Heartbeat {
  199. var volumeMessages []*master_pb.VolumeInformationMessage
  200. maxVolumeCount := 0
  201. var maxFileKey uint64
  202. for _, location := range s.Locations {
  203. maxVolumeCount = maxVolumeCount + location.MaxVolumeCount
  204. location.Lock()
  205. for k, v := range location.volumes {
  206. if maxFileKey < v.nm.MaxFileKey() {
  207. maxFileKey = v.nm.MaxFileKey()
  208. }
  209. if !v.expired(s.VolumeSizeLimit) {
  210. volumeMessage := &master_pb.VolumeInformationMessage{
  211. Id: uint32(k),
  212. Size: uint64(v.Size()),
  213. Collection: v.Collection,
  214. FileCount: uint64(v.nm.FileCount()),
  215. DeleteCount: uint64(v.nm.DeletedCount()),
  216. DeletedByteCount: v.nm.DeletedSize(),
  217. ReadOnly: v.readOnly,
  218. ReplicaPlacement: uint32(v.ReplicaPlacement.Byte()),
  219. Version: uint32(v.Version()),
  220. Ttl: v.Ttl.ToUint32(),
  221. }
  222. volumeMessages = append(volumeMessages, volumeMessage)
  223. } else {
  224. if v.exiredLongEnough(MAX_TTL_VOLUME_REMOVAL_DELAY) {
  225. location.deleteVolumeById(v.Id)
  226. glog.V(0).Infoln("volume", v.Id, "is deleted.")
  227. } else {
  228. glog.V(0).Infoln("volume", v.Id, "is expired.")
  229. }
  230. }
  231. }
  232. location.Unlock()
  233. }
  234. return &master_pb.Heartbeat{
  235. Ip: s.Ip,
  236. Port: uint32(s.Port),
  237. PublicUrl: s.PublicUrl,
  238. MaxVolumeCount: uint32(maxVolumeCount),
  239. MaxFileKey: maxFileKey,
  240. DataCenter: s.dataCenter,
  241. Rack: s.rack,
  242. Volumes: volumeMessages,
  243. }
  244. }
  245. func (s *Store) Close() {
  246. for _, location := range s.Locations {
  247. location.Close()
  248. }
  249. }
  250. func (s *Store) Write(i VolumeId, n *Needle) (size uint32, err error) {
  251. if v := s.findVolume(i); v != nil {
  252. if v.readOnly {
  253. err = fmt.Errorf("Volume %d is read only", i)
  254. return
  255. }
  256. // TODO: count needle size ahead
  257. if MaxPossibleVolumeSize >= v.ContentSize()+uint64(size) {
  258. size, err = v.writeNeedle(n)
  259. } else {
  260. err = fmt.Errorf("Volume Size Limit %d Exceeded! Current size is %d", s.VolumeSizeLimit, v.ContentSize())
  261. }
  262. return
  263. }
  264. glog.V(0).Infoln("volume", i, "not found!")
  265. err = fmt.Errorf("Volume %d not found!", i)
  266. return
  267. }
  268. func (s *Store) updateMaster() {
  269. if s.Client != nil {
  270. if e := s.Client.Send(s.CollectHeartbeat()); e != nil {
  271. glog.V(0).Infoln("error when reporting size:", e)
  272. }
  273. }
  274. }
  275. func (s *Store) Delete(i VolumeId, n *Needle) (uint32, error) {
  276. if v := s.findVolume(i); v != nil && !v.readOnly {
  277. return v.deleteNeedle(n)
  278. }
  279. return 0, nil
  280. }
  281. func (s *Store) ReadVolumeNeedle(i VolumeId, n *Needle) (int, error) {
  282. if v := s.findVolume(i); v != nil {
  283. return v.readNeedle(n)
  284. }
  285. return 0, fmt.Errorf("Volume %d not found!", i)
  286. }
  287. func (s *Store) GetVolume(i VolumeId) *Volume {
  288. return s.findVolume(i)
  289. }
  290. func (s *Store) HasVolume(i VolumeId) bool {
  291. v := s.findVolume(i)
  292. return v != nil
  293. }
  294. func (s *Store) MountVolume(i VolumeId) error {
  295. for _, location := range s.Locations {
  296. if found := location.LoadVolume(i, s.NeedleMapType); found == true {
  297. s.updateMaster()
  298. return nil
  299. }
  300. }
  301. return fmt.Errorf("Volume %d not found on disk", i)
  302. }
  303. func (s *Store) UnmountVolume(i VolumeId) error {
  304. for _, location := range s.Locations {
  305. if err := location.UnloadVolume(i); err == nil {
  306. s.updateMaster()
  307. return nil
  308. }
  309. }
  310. return fmt.Errorf("Volume %d not found on disk", i)
  311. }
  312. func (s *Store) DeleteVolume(i VolumeId) error {
  313. for _, location := range s.Locations {
  314. if error := location.deleteVolumeById(i); error == nil {
  315. s.updateMaster()
  316. return nil
  317. }
  318. }
  319. return fmt.Errorf("Volume %d not found on disk", i)
  320. }