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.

360 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. glog.V(3).Infoln(vid, "garbage level is", v.garbageLevel())
  165. return nil, garbageThreshold < v.garbageLevel()
  166. }
  167. return fmt.Errorf("volume id %s is not found during check compact!", vid), false
  168. }
  169. func (s *Store) CompactVolume(volumeIdString string) error {
  170. vid, err := NewVolumeId(volumeIdString)
  171. if err != nil {
  172. return fmt.Errorf("Volume Id %s is not a valid unsigned integer!", volumeIdString)
  173. }
  174. if v := s.findVolume(vid); v != nil {
  175. return v.Compact()
  176. }
  177. return fmt.Errorf("volume id %s is not found during compact!", vid)
  178. }
  179. func (s *Store) CommitCompactVolume(volumeIdString string) error {
  180. vid, err := NewVolumeId(volumeIdString)
  181. if err != nil {
  182. return fmt.Errorf("Volume Id %s is not a valid unsigned integer!", volumeIdString)
  183. }
  184. if v := s.findVolume(vid); v != nil {
  185. return v.commitCompact()
  186. }
  187. return fmt.Errorf("volume id %s is not found during commit compact!", vid)
  188. }
  189. func (s *Store) FreezeVolume(volumeIdString string) error {
  190. vid, err := NewVolumeId(volumeIdString)
  191. if err != nil {
  192. return fmt.Errorf("Volume Id %s is not a valid unsigned integer!", volumeIdString)
  193. }
  194. if v := s.findVolume(vid); v != nil {
  195. if v.readOnly {
  196. return fmt.Errorf("Volume %s is already read-only", volumeIdString)
  197. }
  198. return v.freeze()
  199. }
  200. return fmt.Errorf("volume id %s is not found during freeze!", vid)
  201. }
  202. func (l *DiskLocation) loadExistingVolumes() {
  203. if dirs, err := ioutil.ReadDir(l.directory); err == nil {
  204. for _, dir := range dirs {
  205. name := dir.Name()
  206. if !dir.IsDir() && strings.HasSuffix(name, ".dat") {
  207. collection := ""
  208. base := name[:len(name)-len(".dat")]
  209. i := strings.Index(base, "_")
  210. if i > 0 {
  211. collection, base = base[0:i], base[i+1:]
  212. }
  213. if vid, err := NewVolumeId(base); err == nil {
  214. if l.volumes[vid] == nil {
  215. if v, e := NewVolume(l.directory, collection, vid, nil); e == nil {
  216. l.volumes[vid] = v
  217. glog.V(0).Infoln("data file", l.directory+"/"+name, "replicaPlacement =", v.ReplicaPlacement, "version =", v.Version(), "size =", v.Size())
  218. }
  219. }
  220. }
  221. }
  222. }
  223. }
  224. glog.V(0).Infoln("Store started on dir:", l.directory, "with", len(l.volumes), "volumes", "max", l.maxVolumeCount)
  225. }
  226. func (s *Store) Status() []*VolumeInfo {
  227. var stats []*VolumeInfo
  228. for _, location := range s.locations {
  229. for k, v := range location.volumes {
  230. s := &VolumeInfo{Id: VolumeId(k), Size: v.ContentSize(),
  231. Collection: v.Collection,
  232. ReplicaPlacement: v.ReplicaPlacement,
  233. Version: v.Version(),
  234. FileCount: v.nm.FileCount(),
  235. DeleteCount: v.nm.DeletedCount(),
  236. DeletedByteCount: v.nm.DeletedSize(),
  237. ReadOnly: v.readOnly}
  238. stats = append(stats, s)
  239. }
  240. }
  241. return stats
  242. }
  243. type JoinResult struct {
  244. VolumeSizeLimit uint64
  245. }
  246. func (s *Store) SetDataCenter(dataCenter string) {
  247. s.dataCenter = dataCenter
  248. }
  249. func (s *Store) SetRack(rack string) {
  250. s.rack = rack
  251. }
  252. func (s *Store) SetBootstrapMaster(bootstrapMaster string) {
  253. s.masterNodes = NewMasterNodes(bootstrapMaster)
  254. }
  255. func (s *Store) Join() error {
  256. masterNode, e := s.masterNodes.findMaster()
  257. if e != nil {
  258. return e
  259. }
  260. stats := new([]*VolumeInfo)
  261. maxVolumeCount := 0
  262. for _, location := range s.locations {
  263. maxVolumeCount = maxVolumeCount + location.maxVolumeCount
  264. for k, v := range location.volumes {
  265. s := &VolumeInfo{Id: VolumeId(k), Size: uint64(v.Size()),
  266. Collection: v.Collection,
  267. ReplicaPlacement: v.ReplicaPlacement,
  268. Version: v.Version(),
  269. FileCount: v.nm.FileCount(),
  270. DeleteCount: v.nm.DeletedCount(),
  271. DeletedByteCount: v.nm.DeletedSize(),
  272. ReadOnly: v.readOnly}
  273. *stats = append(*stats, s)
  274. }
  275. }
  276. bytes, _ := json.Marshal(stats)
  277. values := make(url.Values)
  278. if !s.connected {
  279. values.Add("init", "true")
  280. }
  281. values.Add("port", strconv.Itoa(s.Port))
  282. values.Add("ip", s.Ip)
  283. values.Add("publicUrl", s.PublicUrl)
  284. values.Add("volumes", string(bytes))
  285. values.Add("maxVolumeCount", strconv.Itoa(maxVolumeCount))
  286. values.Add("dataCenter", s.dataCenter)
  287. values.Add("rack", s.rack)
  288. jsonBlob, err := util.Post("http://"+masterNode+"/dir/join", values)
  289. if err != nil {
  290. s.masterNodes.reset()
  291. return err
  292. }
  293. var ret JoinResult
  294. if err := json.Unmarshal(jsonBlob, &ret); err != nil {
  295. return err
  296. }
  297. s.volumeSizeLimit = ret.VolumeSizeLimit
  298. s.connected = true
  299. return nil
  300. }
  301. func (s *Store) Close() {
  302. for _, location := range s.locations {
  303. for _, v := range location.volumes {
  304. v.Close()
  305. }
  306. }
  307. }
  308. func (s *Store) Write(i VolumeId, n *Needle) (size uint32, err error) {
  309. if v := s.findVolume(i); v != nil {
  310. if v.readOnly {
  311. err = fmt.Errorf("Volume %s is read only!", i)
  312. return
  313. } else {
  314. if MaxPossibleVolumeSize >= v.ContentSize()+uint64(size) {
  315. size, err = v.write(n)
  316. } else {
  317. err = fmt.Errorf("Volume Size Limit %d Exceeded! Current size is %d", s.volumeSizeLimit, v.ContentSize())
  318. }
  319. if s.volumeSizeLimit < v.ContentSize()+3*uint64(size) {
  320. glog.V(0).Infoln("volume", i, "size", v.ContentSize(), "will exceed limit", s.volumeSizeLimit)
  321. if e := s.Join(); e != nil {
  322. glog.V(0).Infoln("error when reporting size:", e)
  323. }
  324. }
  325. }
  326. return
  327. }
  328. glog.V(0).Infoln("volume", i, "not found!")
  329. err = fmt.Errorf("Volume %s not found!", i)
  330. return
  331. }
  332. func (s *Store) Delete(i VolumeId, n *Needle) (uint32, error) {
  333. if v := s.findVolume(i); v != nil && !v.readOnly {
  334. return v.delete(n)
  335. }
  336. return 0, nil
  337. }
  338. func (s *Store) Read(i VolumeId, n *Needle) (int, error) {
  339. if v := s.findVolume(i); v != nil {
  340. return v.read(n)
  341. }
  342. return 0, fmt.Errorf("Volume %s not found!", i)
  343. }
  344. func (s *Store) GetVolume(i VolumeId) *Volume {
  345. return s.findVolume(i)
  346. }
  347. func (s *Store) HasVolume(i VolumeId) bool {
  348. v := s.findVolume(i)
  349. return v != nil
  350. }