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.

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