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.

307 lines
8.8 KiB

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