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.

393 lines
10 KiB

3 years ago
  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. // fulltext index not required since no prefix search
  98. // user should just make one themselves if they intend on using it
  99. // if _, _, err = store.collection.EnsureFullTextIndex(ctx, []string{"directory"},
  100. // &driver.EnsureFullTextIndexOptions{Name: "IDX_FULLTEXT_directory", MinLength: 1}); err != nil {
  101. // return err
  102. // }
  103. if _, _, err = store.collection.EnsurePersistentIndex(ctx, []string{"name"}, &driver.EnsurePersistentIndexOptions{
  104. Name: "IDX_name",
  105. }); err != nil {
  106. return err
  107. }
  108. return err
  109. }
  110. type key int
  111. const (
  112. transactionKey key = 0
  113. )
  114. func (store *ArangodbStore) BeginTransaction(ctx context.Context) (context.Context, error) {
  115. txn, err := store.database.BeginTransaction(ctx, driver.TransactionCollections{
  116. Exclusive: []string{"files"},
  117. }, &driver.BeginTransactionOptions{})
  118. if err != nil {
  119. return nil, err
  120. }
  121. return context.WithValue(ctx, transactionKey, txn), nil
  122. }
  123. func (store *ArangodbStore) CommitTransaction(ctx context.Context) error {
  124. val := ctx.Value(transactionKey)
  125. cast, ok := val.(driver.TransactionID)
  126. if !ok {
  127. return fmt.Errorf("txn cast fail %s:", val)
  128. }
  129. err := store.database.CommitTransaction(ctx, cast, &driver.CommitTransactionOptions{})
  130. if err != nil {
  131. return err
  132. }
  133. return nil
  134. }
  135. func (store *ArangodbStore) RollbackTransaction(ctx context.Context) error {
  136. val := ctx.Value(transactionKey)
  137. cast, ok := val.(driver.TransactionID)
  138. if !ok {
  139. return fmt.Errorf("txn cast fail %s:", val)
  140. }
  141. err := store.database.AbortTransaction(ctx, cast, &driver.AbortTransactionOptions{})
  142. if err != nil {
  143. return err
  144. }
  145. return nil
  146. }
  147. func (store *ArangodbStore) InsertEntry(ctx context.Context, entry *filer.Entry) (err error) {
  148. dir, name := entry.FullPath.DirAndName()
  149. meta, err := entry.EncodeAttributesAndChunks()
  150. if err != nil {
  151. return fmt.Errorf("encode %s: %s", entry.FullPath, err)
  152. }
  153. if len(entry.Chunks) > 50 {
  154. meta = util.MaybeGzipData(meta)
  155. }
  156. model := &Model{
  157. Key: hashString(string(entry.FullPath)),
  158. Directory: dir,
  159. Name: name,
  160. Meta: bytesToArray(meta),
  161. }
  162. _, err = store.collection.CreateDocument(ctx, model)
  163. if err != nil {
  164. return fmt.Errorf("UpdateEntry %s: %v", entry.FullPath, err)
  165. }
  166. return nil
  167. }
  168. func (store *ArangodbStore) UpdateEntry(ctx context.Context, entry *filer.Entry) (err error) {
  169. dir, name := entry.FullPath.DirAndName()
  170. meta, err := entry.EncodeAttributesAndChunks()
  171. if err != nil {
  172. return fmt.Errorf("encode %s: %s", entry.FullPath, err)
  173. }
  174. if len(entry.Chunks) > 50 {
  175. meta = util.MaybeGzipData(meta)
  176. }
  177. model := &Model{
  178. Key: hashString(string(entry.FullPath)),
  179. Directory: dir,
  180. Name: name,
  181. Meta: bytesToArray(meta),
  182. }
  183. _, err = store.collection.UpdateDocument(ctx, model.Key, model)
  184. if err != nil {
  185. return fmt.Errorf("UpdateEntry %s: %v", entry.FullPath, err)
  186. }
  187. return nil
  188. }
  189. func (store *ArangodbStore) FindEntry(ctx context.Context, fullpath util.FullPath) (entry *filer.Entry, err error) {
  190. var data Model
  191. _, err = store.collection.ReadDocument(ctx, hashString(string(fullpath)), &data)
  192. if driver.IsNotFound(err) {
  193. return nil, filer_pb.ErrNotFound
  194. }
  195. if err != nil {
  196. glog.Errorf("find %s: %v", fullpath, err)
  197. return nil, filer_pb.ErrNotFound
  198. }
  199. if len(data.Meta) == 0 {
  200. return nil, filer_pb.ErrNotFound
  201. }
  202. entry = &filer.Entry{
  203. FullPath: fullpath,
  204. }
  205. err = entry.DecodeAttributesAndChunks(util.MaybeDecompressData(arrayToBytes(data.Meta)))
  206. if err != nil {
  207. return entry, fmt.Errorf("decode %s : %v", entry.FullPath, err)
  208. }
  209. return entry, nil
  210. }
  211. func (store *ArangodbStore) DeleteEntry(ctx context.Context, fullpath util.FullPath) error {
  212. _, err := store.collection.RemoveDocument(ctx, hashString(string(fullpath)))
  213. if err != nil {
  214. glog.Errorf("find %s: %v", fullpath, err)
  215. return fmt.Errorf("delete %s : %v", fullpath, err)
  216. }
  217. return nil
  218. }
  219. func (store *ArangodbStore) DeleteFolderChildren(ctx context.Context, fullpath util.FullPath) error {
  220. dir, _ := fullpath.DirAndName()
  221. cur, err := store.database.Query(ctx, `
  222. for d in files
  223. filter d.directory == @dir
  224. remove d in files`, map[string]interface{}{"dir": dir})
  225. if err != nil {
  226. return fmt.Errorf("delete %s : %v", fullpath, err)
  227. }
  228. defer cur.Close()
  229. return nil
  230. }
  231. 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) {
  232. return lastFileName, filer.ErrUnsupportedListDirectoryPrefixed
  233. }
  234. //TODO: i must be misunderstanding what this function is supposed to do
  235. //so figure it out is the todo, i guess lol - aaaaa
  236. //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) {
  237. // eq := ""
  238. // if includeStartFile {
  239. // eq = "filter d.name >= \"" + startFileName + "\""
  240. // } else {
  241. // eq = "filter d.name > \"" + startFileName + "\""
  242. // }
  243. // query := fmt.Sprintf(`
  244. //for d in fulltext(files,"directory","prefix:%s")
  245. //sort d.name desc
  246. //%s
  247. //limit %d
  248. //return d`, string(dirPath), eq, limit)
  249. // cur, err := store.database.Query(ctx, query, nil)
  250. // if err != nil {
  251. // return lastFileName, fmt.Errorf("failed to list directory entries: find error: %w", err)
  252. // }
  253. // defer cur.Close()
  254. // for cur.HasMore() {
  255. // var data Model
  256. // _, err = cur.ReadDocument(ctx, &data)
  257. // if err != nil {
  258. // break
  259. // }
  260. // entry := &filer.Entry{
  261. // FullPath: util.NewFullPath(data.Directory, data.Name),
  262. // }
  263. // lastFileName = data.Name
  264. // converted := arrayToBytes(data.Meta)
  265. // if decodeErr := entry.DecodeAttributesAndChunks(util.MaybeDecompressData(converted)); decodeErr != nil {
  266. // err = decodeErr
  267. // glog.V(0).Infof("list %s : %v", entry.FullPath, err)
  268. // break
  269. // }
  270. //
  271. // if !eachEntryFunc(entry) {
  272. // break
  273. // }
  274. //
  275. // }
  276. // return lastFileName, err
  277. //}
  278. func (store *ArangodbStore) ListDirectoryEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) {
  279. eq := ""
  280. if includeStartFile {
  281. eq = "filter d.name >= \"" + startFileName + "\""
  282. } else {
  283. eq = "filter d.name > \"" + startFileName + "\""
  284. }
  285. query := fmt.Sprintf(`
  286. for d in files
  287. filter d.directory == "%s"
  288. sort d.name desc
  289. %s
  290. limit %d
  291. return d`, string(dirPath), eq, limit)
  292. cur, err := store.database.Query(ctx, query, nil)
  293. if err != nil {
  294. return lastFileName, fmt.Errorf("failed to list directory entries: find error: %w", err)
  295. }
  296. defer cur.Close()
  297. for cur.HasMore() {
  298. var data Model
  299. _, err = cur.ReadDocument(ctx, &data)
  300. if err != nil {
  301. break
  302. }
  303. entry := &filer.Entry{
  304. FullPath: util.NewFullPath(string(dirPath), data.Name),
  305. }
  306. lastFileName = data.Name
  307. converted := arrayToBytes(data.Meta)
  308. if decodeErr := entry.DecodeAttributesAndChunks(util.MaybeDecompressData(converted)); decodeErr != nil {
  309. err = decodeErr
  310. glog.V(0).Infof("list %s : %v", entry.FullPath, err)
  311. break
  312. }
  313. if !eachEntryFunc(entry) {
  314. break
  315. }
  316. }
  317. return lastFileName, err
  318. }
  319. func (store *ArangodbStore) Shutdown() {
  320. }
  321. //convert a string into arango-key safe hex bytes hash
  322. func hashString(dir string) string {
  323. h := md5.New()
  324. io.WriteString(h, dir)
  325. b := h.Sum(nil)
  326. return hex.EncodeToString(b)
  327. }
  328. func bytesToArray(bs []byte) []uint64 {
  329. out := make([]uint64, 0, 2+len(bs)/8)
  330. out = append(out, uint64(len(bs)))
  331. for len(bs)%8 != 0 {
  332. bs = append(bs, 0)
  333. }
  334. for i := 0; i < len(bs); i = i + 8 {
  335. out = append(out, binary.BigEndian.Uint64(bs[i:]))
  336. }
  337. return out
  338. }
  339. func arrayToBytes(xs []uint64) []byte {
  340. if len(xs) < 2 {
  341. return []byte{}
  342. }
  343. first := xs[0]
  344. out := make([]byte, len(xs)*8)
  345. for i := 1; i < len(xs); i = i + 1 {
  346. binary.BigEndian.PutUint64(out[((i-1)*8):], xs[i])
  347. }
  348. return out[:first]
  349. }