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.

386 lines
11 KiB

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