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.

344 lines
9.8 KiB

12 years ago
12 years ago
  1. package storage
  2. import (
  3. proto "code.google.com/p/goprotobuf/proto"
  4. "code.google.com/p/weed-fs/go/glog"
  5. "code.google.com/p/weed-fs/go/operation"
  6. "code.google.com/p/weed-fs/go/util"
  7. "encoding/json"
  8. "errors"
  9. "fmt"
  10. "io/ioutil"
  11. "math/rand"
  12. "strconv"
  13. "strings"
  14. )
  15. type DiskLocation struct {
  16. Directory string
  17. MaxVolumeCount int
  18. volumes map[VolumeId]*Volume
  19. }
  20. func (mn *DiskLocation) reset() {
  21. }
  22. type MasterNodes struct {
  23. nodes []string
  24. lastNode int
  25. }
  26. func NewMasterNodes(bootstrapNode string) (mn *MasterNodes) {
  27. mn = &MasterNodes{nodes: []string{bootstrapNode}, lastNode: -1}
  28. return
  29. }
  30. func (mn *MasterNodes) reset() {
  31. if len(mn.nodes) > 1 && mn.lastNode > 0 {
  32. mn.lastNode = -mn.lastNode
  33. }
  34. }
  35. func (mn *MasterNodes) findMaster() (string, error) {
  36. if len(mn.nodes) == 0 {
  37. return "", errors.New("No master node found!")
  38. }
  39. if mn.lastNode < 0 {
  40. for _, m := range mn.nodes {
  41. if masters, e := operation.ListMasters(m); e == nil {
  42. if len(masters) == 0 {
  43. continue
  44. }
  45. mn.nodes = masters
  46. mn.lastNode = rand.Intn(len(mn.nodes))
  47. glog.V(2).Info("current master node is :", mn.nodes[mn.lastNode])
  48. break
  49. }
  50. }
  51. }
  52. if mn.lastNode < 0 {
  53. return "", errors.New("No master node avalable!")
  54. }
  55. return mn.nodes[mn.lastNode], nil
  56. }
  57. type Store struct {
  58. Port int
  59. Ip string
  60. PublicUrl string
  61. Locations []*DiskLocation
  62. dataCenter string //optional informaton, overwriting master setting if exists
  63. rack string //optional information, overwriting master setting if exists
  64. connected bool
  65. volumeSizeLimit uint64 //read from the master
  66. masterNodes *MasterNodes
  67. }
  68. func NewStore(port int, ip, publicUrl string, dirnames []string, maxVolumeCounts []int) (s *Store) {
  69. s = &Store{Port: port, Ip: ip, PublicUrl: publicUrl}
  70. s.Locations = make([]*DiskLocation, 0)
  71. for i := 0; i < len(dirnames); i++ {
  72. location := &DiskLocation{Directory: dirnames[i], MaxVolumeCount: maxVolumeCounts[i]}
  73. location.volumes = make(map[VolumeId]*Volume)
  74. location.loadExistingVolumes()
  75. s.Locations = append(s.Locations, location)
  76. }
  77. return
  78. }
  79. func (s *Store) AddVolume(volumeListString string, collection string, replicaPlacement string) error {
  80. rt, e := NewReplicaPlacementFromString(replicaPlacement)
  81. if e != nil {
  82. return e
  83. }
  84. for _, range_string := range strings.Split(volumeListString, ",") {
  85. if strings.Index(range_string, "-") < 0 {
  86. id_string := range_string
  87. id, err := NewVolumeId(id_string)
  88. if err != nil {
  89. return fmt.Errorf("Volume Id %s is not a valid unsigned integer!", id_string)
  90. }
  91. e = s.addVolume(VolumeId(id), collection, rt)
  92. } else {
  93. pair := strings.Split(range_string, "-")
  94. start, start_err := strconv.ParseUint(pair[0], 10, 64)
  95. if start_err != nil {
  96. return fmt.Errorf("Volume Start Id %s is not a valid unsigned integer!", pair[0])
  97. }
  98. end, end_err := strconv.ParseUint(pair[1], 10, 64)
  99. if end_err != nil {
  100. return fmt.Errorf("Volume End Id %s is not a valid unsigned integer!", pair[1])
  101. }
  102. for id := start; id <= end; id++ {
  103. if err := s.addVolume(VolumeId(id), collection, rt); err != nil {
  104. e = err
  105. }
  106. }
  107. }
  108. }
  109. return e
  110. }
  111. func (s *Store) DeleteCollection(collection string) (e error) {
  112. for _, location := range s.Locations {
  113. for k, v := range location.volumes {
  114. if v.Collection == collection {
  115. e = v.Destroy()
  116. if e != nil {
  117. return
  118. }
  119. delete(location.volumes, k)
  120. }
  121. }
  122. }
  123. return
  124. }
  125. func (s *Store) findVolume(vid VolumeId) *Volume {
  126. for _, location := range s.Locations {
  127. if v, found := location.volumes[vid]; found {
  128. return v
  129. }
  130. }
  131. return nil
  132. }
  133. func (s *Store) findFreeLocation() (ret *DiskLocation) {
  134. max := 0
  135. for _, location := range s.Locations {
  136. currentFreeCount := location.MaxVolumeCount - len(location.volumes)
  137. if currentFreeCount > max {
  138. max = currentFreeCount
  139. ret = location
  140. }
  141. }
  142. return ret
  143. }
  144. func (s *Store) addVolume(vid VolumeId, collection string, replicaPlacement *ReplicaPlacement) error {
  145. if s.findVolume(vid) != nil {
  146. return fmt.Errorf("Volume Id %d already exists!", vid)
  147. }
  148. if location := s.findFreeLocation(); location != nil {
  149. glog.V(0).Infoln("In dir", location.Directory, "adds volume =", vid, ", collection =", collection, ", replicaPlacement =", replicaPlacement)
  150. if volume, err := NewVolume(location.Directory, collection, vid, replicaPlacement); err == nil {
  151. location.volumes[vid] = volume
  152. return nil
  153. } else {
  154. return err
  155. }
  156. }
  157. return fmt.Errorf("No more free space left")
  158. }
  159. func (s *Store) FreezeVolume(volumeIdString string) error {
  160. vid, err := NewVolumeId(volumeIdString)
  161. if err != nil {
  162. return fmt.Errorf("Volume Id %s is not a valid unsigned integer!", volumeIdString)
  163. }
  164. if v := s.findVolume(vid); v != nil {
  165. if v.readOnly {
  166. return fmt.Errorf("Volume %s is already read-only", volumeIdString)
  167. }
  168. return v.freeze()
  169. }
  170. return fmt.Errorf("volume id %d is not found during freeze!", vid)
  171. }
  172. func (l *DiskLocation) loadExistingVolumes() {
  173. if dirs, err := ioutil.ReadDir(l.Directory); err == nil {
  174. for _, dir := range dirs {
  175. name := dir.Name()
  176. if !dir.IsDir() && strings.HasSuffix(name, ".dat") {
  177. collection := ""
  178. base := name[:len(name)-len(".dat")]
  179. i := strings.Index(base, "_")
  180. if i > 0 {
  181. collection, base = base[0:i], base[i+1:]
  182. }
  183. if vid, err := NewVolumeId(base); err == nil {
  184. if l.volumes[vid] == nil {
  185. if v, e := NewVolume(l.Directory, collection, vid, nil); e == nil {
  186. l.volumes[vid] = v
  187. glog.V(0).Infoln("data file", l.Directory+"/"+name, "replicaPlacement =", v.ReplicaPlacement, "version =", v.Version(), "size =", v.Size())
  188. }
  189. }
  190. }
  191. }
  192. }
  193. }
  194. glog.V(0).Infoln("Store started on dir:", l.Directory, "with", len(l.volumes), "volumes", "max", l.MaxVolumeCount)
  195. }
  196. func (s *Store) Status() []*VolumeInfo {
  197. var stats []*VolumeInfo
  198. for _, location := range s.Locations {
  199. for k, v := range location.volumes {
  200. s := &VolumeInfo{Id: VolumeId(k), Size: v.ContentSize(),
  201. Collection: v.Collection,
  202. ReplicaPlacement: v.ReplicaPlacement,
  203. Version: v.Version(),
  204. FileCount: v.nm.FileCount(),
  205. DeleteCount: v.nm.DeletedCount(),
  206. DeletedByteCount: v.nm.DeletedSize(),
  207. ReadOnly: v.readOnly}
  208. stats = append(stats, s)
  209. }
  210. }
  211. return stats
  212. }
  213. func (s *Store) SetDataCenter(dataCenter string) {
  214. s.dataCenter = dataCenter
  215. }
  216. func (s *Store) SetRack(rack string) {
  217. s.rack = rack
  218. }
  219. func (s *Store) SetBootstrapMaster(bootstrapMaster string) {
  220. s.masterNodes = NewMasterNodes(bootstrapMaster)
  221. }
  222. func (s *Store) Join() (masterNode string, e error) {
  223. masterNode, e = s.masterNodes.findMaster()
  224. if e != nil {
  225. return
  226. }
  227. var volumeMessages []*operation.VolumeInformationMessage
  228. maxVolumeCount := 0
  229. var maxFileKey uint64
  230. for _, location := range s.Locations {
  231. maxVolumeCount = maxVolumeCount + location.MaxVolumeCount
  232. for k, v := range location.volumes {
  233. volumeMessage := &operation.VolumeInformationMessage{
  234. Id: proto.Uint32(uint32(k)),
  235. Size: proto.Uint64(uint64(v.Size())),
  236. Collection: proto.String(v.Collection),
  237. FileCount: proto.Uint64(uint64(v.nm.FileCount())),
  238. DeleteCount: proto.Uint64(uint64(v.nm.DeletedCount())),
  239. DeletedByteCount: proto.Uint64(v.nm.DeletedSize()),
  240. ReadOnly: proto.Bool(v.readOnly),
  241. ReplicaPlacement: proto.Uint32(uint32(v.ReplicaPlacement.Byte())),
  242. Version: proto.Uint32(uint32(v.Version())),
  243. }
  244. volumeMessages = append(volumeMessages, volumeMessage)
  245. if maxFileKey < v.nm.MaxFileKey() {
  246. maxFileKey = v.nm.MaxFileKey()
  247. }
  248. }
  249. }
  250. joinMessage := &operation.JoinMessage{
  251. IsInit: proto.Bool(!s.connected),
  252. Ip: proto.String(s.Ip),
  253. Port: proto.Uint32(uint32(s.Port)),
  254. PublicUrl: proto.String(s.PublicUrl),
  255. MaxVolumeCount: proto.Uint32(uint32(maxVolumeCount)),
  256. MaxFileKey: proto.Uint64(maxFileKey),
  257. DataCenter: proto.String(s.dataCenter),
  258. Rack: proto.String(s.rack),
  259. Volumes: volumeMessages,
  260. }
  261. data, err := proto.Marshal(joinMessage)
  262. if err != nil {
  263. return "", err
  264. }
  265. jsonBlob, err := util.PostBytes("http://"+masterNode+"/dir/join", data)
  266. if err != nil {
  267. s.masterNodes.reset()
  268. return "", err
  269. }
  270. var ret operation.JoinResult
  271. if err := json.Unmarshal(jsonBlob, &ret); err != nil {
  272. return masterNode, err
  273. }
  274. if ret.Error != "" {
  275. return masterNode, errors.New(ret.Error)
  276. }
  277. s.volumeSizeLimit = ret.VolumeSizeLimit
  278. s.connected = true
  279. return
  280. }
  281. func (s *Store) Close() {
  282. for _, location := range s.Locations {
  283. for _, v := range location.volumes {
  284. v.Close()
  285. }
  286. }
  287. }
  288. func (s *Store) Write(i VolumeId, n *Needle) (size uint32, err error) {
  289. if v := s.findVolume(i); v != nil {
  290. if v.readOnly {
  291. err = fmt.Errorf("Volume %d is read only!", i)
  292. return
  293. } else {
  294. if MaxPossibleVolumeSize >= v.ContentSize()+uint64(size) {
  295. size, err = v.write(n)
  296. } else {
  297. err = fmt.Errorf("Volume Size Limit %d Exceeded! Current size is %d", s.volumeSizeLimit, v.ContentSize())
  298. }
  299. if s.volumeSizeLimit < v.ContentSize()+3*uint64(size) {
  300. glog.V(0).Infoln("volume", i, "size", v.ContentSize(), "will exceed limit", s.volumeSizeLimit)
  301. if _, e := s.Join(); e != nil {
  302. glog.V(0).Infoln("error when reporting size:", e)
  303. }
  304. }
  305. }
  306. return
  307. }
  308. glog.V(0).Infoln("volume", i, "not found!")
  309. err = fmt.Errorf("Volume %d not found!", i)
  310. return
  311. }
  312. func (s *Store) Delete(i VolumeId, n *Needle) (uint32, error) {
  313. if v := s.findVolume(i); v != nil && !v.readOnly {
  314. return v.delete(n)
  315. }
  316. return 0, nil
  317. }
  318. func (s *Store) Read(i VolumeId, n *Needle) (int, error) {
  319. if v := s.findVolume(i); v != nil {
  320. return v.read(n)
  321. }
  322. return 0, fmt.Errorf("Volume %v not found!", i)
  323. }
  324. func (s *Store) GetVolume(i VolumeId) *Volume {
  325. return s.findVolume(i)
  326. }
  327. func (s *Store) HasVolume(i VolumeId) bool {
  328. v := s.findVolume(i)
  329. return v != nil
  330. }