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.

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