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.

87 lines
2.2 KiB

  1. package cassandra_store
  2. import (
  3. "fmt"
  4. "github.com/chrislusf/weed-fs/go/glog"
  5. "github.com/gocql/gocql"
  6. )
  7. /*
  8. Basically you need a table just like this:
  9. CREATE TABLE seaweed_files (
  10. path varchar,
  11. fids list<varchar>,
  12. PRIMARY KEY (path)
  13. );
  14. Need to match flat_namespace.FlatNamespaceStore interface
  15. Put(fullFileName string, fid string) (err error)
  16. Get(fullFileName string) (fid string, err error)
  17. Delete(fullFileName string) (fid string, err error)
  18. */
  19. type CassandraStore struct {
  20. cluster *gocql.ClusterConfig
  21. session *gocql.Session
  22. }
  23. func NewCassandraStore(keyspace string, hosts ...string) (c *CassandraStore, err error) {
  24. c = &CassandraStore{}
  25. c.cluster = gocql.NewCluster(hosts...)
  26. c.cluster.Keyspace = keyspace
  27. c.cluster.Consistency = gocql.Quorum
  28. c.session, err = c.cluster.CreateSession()
  29. if err != nil {
  30. glog.V(0).Infof("Failed to open cassandra store, hosts %v, keyspace %s", hosts, keyspace)
  31. }
  32. return
  33. }
  34. func (c *CassandraStore) Put(fullFileName string, fid string) (err error) {
  35. var input []string
  36. input = append(input, fid)
  37. if err := c.session.Query(
  38. `INSERT INTO seaweed_files (path, fids) VALUES (?, ?)`,
  39. fullFileName, input).Exec(); err != nil {
  40. glog.V(0).Infof("Failed to save file %s with id %s: %v", fullFileName, fid, err)
  41. return err
  42. }
  43. return nil
  44. }
  45. func (c *CassandraStore) Get(fullFileName string) (fid string, err error) {
  46. var output []string
  47. if err := c.session.Query(
  48. `select fids FROM seaweed_files WHERE path = ? LIMIT 1`,
  49. fullFileName).Consistency(gocql.One).Scan(&output); err != nil {
  50. if err != gocql.ErrNotFound {
  51. glog.V(0).Infof("Failed to find file %s: %v", fullFileName, fid, err)
  52. }
  53. }
  54. if len(output) == 0 {
  55. return "", fmt.Errorf("No file id found for %s", fullFileName)
  56. }
  57. return output[0], nil
  58. }
  59. // Currently the fid is not returned
  60. func (c *CassandraStore) Delete(fullFileName string) (fid string, err error) {
  61. if err := c.session.Query(
  62. `DELETE FROM seaweed_files WHERE path = ?`,
  63. fullFileName).Exec(); err != nil {
  64. if err != gocql.ErrNotFound {
  65. glog.V(0).Infof("Failed to delete file %s: %v", fullFileName, err)
  66. }
  67. return "", err
  68. }
  69. return "", nil
  70. }
  71. func (c *CassandraStore) Close() {
  72. if c.session != nil {
  73. c.session.Close()
  74. }
  75. }