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.

345 lines
8.8 KiB

  1. package arangodb
  2. import (
  3. "context"
  4. "crypto/md5"
  5. "crypto/tls"
  6. "encoding/binary"
  7. "encoding/hex"
  8. "fmt"
  9. "io"
  10. "time"
  11. "github.com/arangodb/go-driver"
  12. "github.com/arangodb/go-driver/http"
  13. "github.com/chrislusf/seaweedfs/weed/filer"
  14. "github.com/chrislusf/seaweedfs/weed/glog"
  15. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  16. "github.com/chrislusf/seaweedfs/weed/util"
  17. )
  18. func init() {
  19. filer.Stores = append(filer.Stores, &ArangodbStore{})
  20. }
  21. type ArangodbStore struct {
  22. connect driver.Connection
  23. client driver.Client
  24. database driver.Database
  25. collection driver.Collection
  26. }
  27. type Model struct {
  28. Key string `json:"_key"`
  29. Directory string `json:"directory"`
  30. Name string `json:"name"`
  31. Meta []uint64 `json:"meta"`
  32. }
  33. func (store *ArangodbStore) GetName() string {
  34. return "arangodb"
  35. }
  36. func (store *ArangodbStore) Initialize(configuration util.Configuration, prefix string) (err error) {
  37. return store.connection(configuration.GetStringSlice(prefix+"arango_host"),
  38. configuration.GetString(prefix+"arango_user"),
  39. configuration.GetString(prefix+"arango_pass"),
  40. )
  41. }
  42. func (store *ArangodbStore) connection(uris []string, user string, pass string) (err error) {
  43. ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
  44. store.connect, err = http.NewConnection(http.ConnectionConfig{
  45. Endpoints: uris,
  46. TLSConfig: &tls.Config{
  47. InsecureSkipVerify: true,
  48. },
  49. })
  50. if err != nil {
  51. return err
  52. }
  53. store.client, err = driver.NewClient(driver.ClientConfig{
  54. Connection: store.connect,
  55. Authentication: driver.BasicAuthentication(user, pass),
  56. })
  57. if err != nil {
  58. return err
  59. }
  60. db_name := "seaweed-filer"
  61. ok, err := store.client.DatabaseExists(ctx, db_name)
  62. if err != nil {
  63. return err
  64. }
  65. if ok {
  66. store.database, err = store.client.Database(ctx, db_name)
  67. } else {
  68. store.database, err = store.client.CreateDatabase(ctx, db_name, &driver.CreateDatabaseOptions{})
  69. }
  70. if err != nil {
  71. return err
  72. }
  73. coll_name := "files"
  74. ok, err = store.database.CollectionExists(ctx, coll_name)
  75. if err != nil {
  76. return err
  77. }
  78. if ok {
  79. store.collection, err = store.database.Collection(ctx, coll_name)
  80. } else {
  81. store.collection, err = store.database.CreateCollection(ctx, coll_name, &driver.CreateCollectionOptions{})
  82. }
  83. if err != nil {
  84. return err
  85. }
  86. // ensure indices
  87. if _, _, err = store.collection.EnsurePersistentIndex(ctx, []string{"directory", "name"}, &driver.EnsurePersistentIndexOptions{
  88. Name: "directory_name_multi",
  89. Unique: true,
  90. }); err != nil {
  91. return err
  92. }
  93. if _, _, err = store.collection.EnsurePersistentIndex(ctx, []string{"directory"},
  94. &driver.EnsurePersistentIndexOptions{Name: "IDX_directory"}); err != nil {
  95. return err
  96. }
  97. if _, _, err = store.collection.EnsureFullTextIndex(ctx, []string{"directory_fulltext"},
  98. &driver.EnsureFullTextIndexOptions{Name: "IDX_FULLTEXT_directory", MinLength: 1}); err != nil {
  99. return err
  100. }
  101. if _, _, err = store.collection.EnsurePersistentIndex(ctx, []string{"name"}, &driver.EnsurePersistentIndexOptions{
  102. Name: "IDX_name",
  103. }); err != nil {
  104. return err
  105. }
  106. return err
  107. }
  108. type key int
  109. const (
  110. transactionKey key = 0
  111. )
  112. func (store *ArangodbStore) BeginTransaction(ctx context.Context) (context.Context, error) {
  113. txn, err := store.database.BeginTransaction(ctx, driver.TransactionCollections{
  114. Exclusive: []string{"files"},
  115. }, &driver.BeginTransactionOptions{})
  116. if err != nil {
  117. return nil, err
  118. }
  119. return context.WithValue(ctx, transactionKey, txn), nil
  120. }
  121. func (store *ArangodbStore) CommitTransaction(ctx context.Context) error {
  122. val := ctx.Value(transactionKey)
  123. cast, ok := val.(driver.TransactionID)
  124. if !ok {
  125. return fmt.Errorf("txn cast fail %s:", val)
  126. }
  127. err := store.database.CommitTransaction(ctx, cast, &driver.CommitTransactionOptions{})
  128. if err != nil {
  129. return err
  130. }
  131. return nil
  132. }
  133. func (store *ArangodbStore) RollbackTransaction(ctx context.Context) error {
  134. val := ctx.Value(transactionKey)
  135. cast, ok := val.(driver.TransactionID)
  136. if !ok {
  137. return fmt.Errorf("txn cast fail %s:", val)
  138. }
  139. err := store.database.AbortTransaction(ctx, cast, &driver.AbortTransactionOptions{})
  140. if err != nil {
  141. return err
  142. }
  143. return nil
  144. }
  145. func (store *ArangodbStore) InsertEntry(ctx context.Context, entry *filer.Entry) (err error) {
  146. dir, name := entry.FullPath.DirAndName()
  147. meta, err := entry.EncodeAttributesAndChunks()
  148. if err != nil {
  149. return fmt.Errorf("encode %s: %s", entry.FullPath, err)
  150. }
  151. if len(entry.Chunks) > 50 {
  152. meta = util.MaybeGzipData(meta)
  153. }
  154. model := &Model{
  155. Key: hashString(string(entry.FullPath)),
  156. Directory: dir,
  157. Name: name,
  158. Meta: bytesToArray(meta),
  159. }
  160. _, err = store.collection.CreateDocument(ctx, model)
  161. if err != nil {
  162. return fmt.Errorf("UpdateEntry %s: %v", entry.FullPath, err)
  163. }
  164. return nil
  165. }
  166. func (store *ArangodbStore) UpdateEntry(ctx context.Context, entry *filer.Entry) (err error) {
  167. dir, name := entry.FullPath.DirAndName()
  168. meta, err := entry.EncodeAttributesAndChunks()
  169. if err != nil {
  170. return fmt.Errorf("encode %s: %s", entry.FullPath, err)
  171. }
  172. if len(entry.Chunks) > 50 {
  173. meta = util.MaybeGzipData(meta)
  174. }
  175. model := &Model{
  176. Key: hashString(string(entry.FullPath)),
  177. Directory: dir,
  178. Name: name,
  179. Meta: bytesToArray(meta),
  180. }
  181. _, err = store.collection.UpdateDocument(ctx, model.Key, model)
  182. if err != nil {
  183. return fmt.Errorf("UpdateEntry %s: %v", entry.FullPath, err)
  184. }
  185. return nil
  186. }
  187. func (store *ArangodbStore) FindEntry(ctx context.Context, fullpath util.FullPath) (entry *filer.Entry, err error) {
  188. var data Model
  189. _, err = store.collection.ReadDocument(ctx, hashString(string(fullpath)), &data)
  190. if driver.IsNotFound(err) {
  191. return nil, filer_pb.ErrNotFound
  192. }
  193. if err != nil {
  194. glog.Errorf("find %s: %v", fullpath, err)
  195. return nil, filer_pb.ErrNotFound
  196. }
  197. if len(data.Meta) == 0 {
  198. return nil, filer_pb.ErrNotFound
  199. }
  200. entry = &filer.Entry{
  201. FullPath: fullpath,
  202. }
  203. err = entry.DecodeAttributesAndChunks(util.MaybeDecompressData(arrayToBytes(data.Meta)))
  204. if err != nil {
  205. return entry, fmt.Errorf("decode %s : %v", entry.FullPath, err)
  206. }
  207. return entry, nil
  208. }
  209. func (store *ArangodbStore) DeleteEntry(ctx context.Context, fullpath util.FullPath) error {
  210. _, err := store.collection.RemoveDocument(ctx, hashString(string(fullpath)))
  211. if err != nil {
  212. glog.Errorf("find %s: %v", fullpath, err)
  213. return fmt.Errorf("delete %s : %v", fullpath, err)
  214. }
  215. return nil
  216. }
  217. func (store *ArangodbStore) DeleteFolderChildren(ctx context.Context, fullpath util.FullPath) error {
  218. dir, _ := fullpath.DirAndName()
  219. cur, err := store.database.Query(ctx, `
  220. for d in files
  221. filter d.directory == @dir
  222. remove d in files`, map[string]interface{}{"dir": dir})
  223. if err != nil {
  224. return fmt.Errorf("delete %s : %v", fullpath, err)
  225. }
  226. defer cur.Close()
  227. return nil
  228. }
  229. func (store *ArangodbStore) ListDirectoryPrefixedEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, prefix string, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) {
  230. return lastFileName, filer.ErrUnsupportedListDirectoryPrefixed
  231. }
  232. func (store *ArangodbStore) ListDirectoryEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) {
  233. eq := ""
  234. if !includeStartFile {
  235. eq = "filter d.name != \"" + startFileName + "\""
  236. }
  237. fmt.Println(dirPath, startFileName, includeStartFile)
  238. query := fmt.Sprintf(`
  239. for d in files
  240. filter d.directory == "%s"
  241. sort d.name desc
  242. %s
  243. limit %d
  244. return d`, string(dirPath), eq, limit)
  245. cur, err := store.database.Query(ctx, query, nil)
  246. if err != nil {
  247. return lastFileName, fmt.Errorf("failed to list directory entries: find error: %w", err)
  248. }
  249. defer cur.Close()
  250. for cur.HasMore() {
  251. var data Model
  252. _, err = cur.ReadDocument(ctx, &data)
  253. if err != nil {
  254. break
  255. }
  256. entry := &filer.Entry{
  257. FullPath: util.NewFullPath(string(dirPath), data.Name),
  258. }
  259. lastFileName = data.Name
  260. converted := arrayToBytes(data.Meta)
  261. if decodeErr := entry.DecodeAttributesAndChunks(util.MaybeDecompressData(converted)); decodeErr != nil {
  262. err = decodeErr
  263. glog.V(0).Infof("list %s : %v", entry.FullPath, err)
  264. break
  265. }
  266. if !eachEntryFunc(entry) {
  267. break
  268. }
  269. }
  270. return lastFileName, err
  271. }
  272. func (store *ArangodbStore) Shutdown() {
  273. }
  274. func hashString(dir string) string {
  275. h := md5.New()
  276. io.WriteString(h, dir)
  277. b := h.Sum(nil)
  278. return hex.EncodeToString(b)
  279. }
  280. func bytesToArray(bs []byte) []uint64 {
  281. out := make([]uint64, 0, 2+len(bs)/8)
  282. out = append(out, uint64(len(bs)))
  283. for len(bs)%8 != 0 {
  284. bs = append(bs, 0)
  285. }
  286. for i := 0; i < len(bs); i = i + 8 {
  287. out = append(out, binary.BigEndian.Uint64(bs[i:]))
  288. }
  289. return out
  290. }
  291. func arrayToBytes(xs []uint64) []byte {
  292. if len(xs) < 2 {
  293. return []byte{}
  294. }
  295. first := xs[0]
  296. out := make([]byte, len(xs)*8)
  297. for i := 1; i < len(xs); i = i + 1 {
  298. binary.BigEndian.PutUint64(out[((i-1)*8):], xs[i])
  299. }
  300. return out[:first]
  301. }