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. Ttl: v.Ttl}
  236. stats = append(stats, s)
  237. }
  238. }
  239. return stats
  240. }
  241. func (s *Store) SetDataCenter(dataCenter string) {
  242. s.dataCenter = dataCenter
  243. }
  244. func (s *Store) SetRack(rack string) {
  245. s.rack = rack
  246. }
  247. func (s *Store) SetBootstrapMaster(bootstrapMaster string) {
  248. s.masterNodes = NewMasterNodes(bootstrapMaster)
  249. }
  250. func (s *Store) Join() (masterNode string, secretKey security.Secret, e error) {
  251. masterNode, e = s.masterNodes.findMaster()
  252. if e != nil {
  253. return
  254. }
  255. var volumeMessages []*operation.VolumeInformationMessage
  256. maxVolumeCount := 0
  257. var maxFileKey uint64
  258. for _, location := range s.Locations {
  259. maxVolumeCount = maxVolumeCount + location.MaxVolumeCount
  260. for k, v := range location.volumes {
  261. if maxFileKey < v.nm.MaxFileKey() {
  262. maxFileKey = v.nm.MaxFileKey()
  263. }
  264. if !v.expired(s.volumeSizeLimit) {
  265. volumeMessage := &operation.VolumeInformationMessage{
  266. Id: proto.Uint32(uint32(k)),
  267. Size: proto.Uint64(uint64(v.Size())),
  268. Collection: proto.String(v.Collection),
  269. FileCount: proto.Uint64(uint64(v.nm.FileCount())),
  270. DeleteCount: proto.Uint64(uint64(v.nm.DeletedCount())),
  271. DeletedByteCount: proto.Uint64(v.nm.DeletedSize()),
  272. ReadOnly: proto.Bool(v.readOnly),
  273. ReplicaPlacement: proto.Uint32(uint32(v.ReplicaPlacement.Byte())),
  274. Version: proto.Uint32(uint32(v.Version())),
  275. Ttl: proto.Uint32(v.Ttl.ToUint32()),
  276. }
  277. volumeMessages = append(volumeMessages, volumeMessage)
  278. } else {
  279. if v.exiredLongEnough(MAX_TTL_VOLUME_REMOVAL_DELAY) {
  280. s.DeleteVolume(location.volumes, v)
  281. glog.V(0).Infoln("volume", v.Id, "is deleted.")
  282. } else {
  283. glog.V(0).Infoln("volume", v.Id, "is expired.")
  284. }
  285. }
  286. }
  287. }
  288. joinMessage := &operation.JoinMessage{
  289. IsInit: proto.Bool(!s.connected),
  290. Ip: proto.String(s.Ip),
  291. Port: proto.Uint32(uint32(s.Port)),
  292. PublicUrl: proto.String(s.PublicUrl),
  293. MaxVolumeCount: proto.Uint32(uint32(maxVolumeCount)),
  294. MaxFileKey: proto.Uint64(maxFileKey),
  295. DataCenter: proto.String(s.dataCenter),
  296. Rack: proto.String(s.rack),
  297. Volumes: volumeMessages,
  298. }
  299. data, err := proto.Marshal(joinMessage)
  300. if err != nil {
  301. return "", "", err
  302. }
  303. jsonBlob, err := util.PostBytes("http://"+masterNode+"/dir/join", data)
  304. if err != nil {
  305. s.masterNodes.reset()
  306. return "", "", err
  307. }
  308. var ret operation.JoinResult
  309. if err := json.Unmarshal(jsonBlob, &ret); err != nil {
  310. return masterNode, "", err
  311. }
  312. if ret.Error != "" {
  313. return masterNode, "", errors.New(ret.Error)
  314. }
  315. s.volumeSizeLimit = ret.VolumeSizeLimit
  316. secretKey = security.Secret(ret.SecretKey)
  317. s.connected = true
  318. return
  319. }
  320. func (s *Store) Close() {
  321. for _, location := range s.Locations {
  322. for _, v := range location.volumes {
  323. v.Close()
  324. }
  325. }
  326. }
  327. func (s *Store) Write(i VolumeId, n *Needle) (size uint32, err error) {
  328. if v := s.findVolume(i); v != nil {
  329. if v.readOnly {
  330. err = fmt.Errorf("Volume %d is read only", i)
  331. return
  332. }
  333. if MaxPossibleVolumeSize >= v.ContentSize()+uint64(size) {
  334. size, err = v.write(n)
  335. } else {
  336. err = fmt.Errorf("Volume Size Limit %d Exceeded! Current size is %d", s.volumeSizeLimit, v.ContentSize())
  337. }
  338. if s.volumeSizeLimit < v.ContentSize()+3*uint64(size) {
  339. glog.V(0).Infoln("volume", i, "size", v.ContentSize(), "will exceed limit", s.volumeSizeLimit)
  340. if _, _, e := s.Join(); e != nil {
  341. glog.V(0).Infoln("error when reporting size:", e)
  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. }