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.

348 lines
10 KiB

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