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.

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