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.

338 lines
9.8 KiB

  1. package elastic
  2. import (
  3. "context"
  4. "fmt"
  5. "math"
  6. "strings"
  7. "github.com/chrislusf/seaweedfs/weed/filer"
  8. "github.com/chrislusf/seaweedfs/weed/glog"
  9. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  10. weed_util "github.com/chrislusf/seaweedfs/weed/util"
  11. jsoniter "github.com/json-iterator/go"
  12. elastic "github.com/olivere/elastic/v7"
  13. )
  14. var (
  15. indexType = "_doc"
  16. indexPrefix = ".seaweedfs_"
  17. indexKV = ".seaweedfs_kv_entries"
  18. kvMappings = ` {
  19. "mappings": {
  20. "enabled": false,
  21. "properties": {
  22. "Value":{
  23. "type": "binary"
  24. }
  25. }
  26. }
  27. }`
  28. )
  29. type ESEntry struct {
  30. ParentId string `json:"ParentId"`
  31. Entry *filer.Entry
  32. }
  33. type ESKVEntry struct {
  34. Value []byte `json:"Value"`
  35. }
  36. func init() {
  37. filer.Stores = append(filer.Stores, &ElasticStore{})
  38. }
  39. type ElasticStore struct {
  40. client *elastic.Client
  41. maxPageSize int
  42. }
  43. func (store *ElasticStore) GetName() string {
  44. return "elastic7"
  45. }
  46. func (store *ElasticStore) Initialize(configuration weed_util.Configuration, prefix string) (err error) {
  47. options := []elastic.ClientOptionFunc{}
  48. servers := configuration.GetStringSlice(prefix + "servers")
  49. options = append(options, elastic.SetURL(servers...))
  50. username := configuration.GetString(prefix + "username")
  51. password := configuration.GetString(prefix + "password")
  52. if username != "" && password != "" {
  53. options = append(options, elastic.SetBasicAuth(username, password))
  54. }
  55. options = append(options, elastic.SetSniff(configuration.GetBool(prefix+"sniff_enabled")))
  56. options = append(options, elastic.SetHealthcheck(configuration.GetBool(prefix+"healthcheck_enabled")))
  57. store.maxPageSize = configuration.GetInt(prefix + "index.max_result_window")
  58. if store.maxPageSize <= 0 {
  59. store.maxPageSize = 10000
  60. }
  61. glog.Infof("filer store elastic endpoints: %v.", servers)
  62. return store.initialize(options)
  63. }
  64. func (store *ElasticStore) initialize(options []elastic.ClientOptionFunc) (err error) {
  65. ctx := context.Background()
  66. store.client, err = elastic.NewClient(options...)
  67. if err != nil {
  68. return fmt.Errorf("init elastic %v.", err)
  69. }
  70. if ok, err := store.client.IndexExists(indexKV).Do(ctx); err == nil && !ok {
  71. _, err = store.client.CreateIndex(indexKV).Body(kvMappings).Do(ctx)
  72. if err != nil {
  73. return fmt.Errorf("create index(%s) %v.", indexKV, err)
  74. }
  75. }
  76. return nil
  77. }
  78. func (store *ElasticStore) BeginTransaction(ctx context.Context) (context.Context, error) {
  79. return ctx, nil
  80. }
  81. func (store *ElasticStore) CommitTransaction(ctx context.Context) error {
  82. return nil
  83. }
  84. func (store *ElasticStore) RollbackTransaction(ctx context.Context) error {
  85. return nil
  86. }
  87. func (store *ElasticStore) ListDirectoryPrefixedEntries(ctx context.Context, fullpath weed_util.FullPath, startFileName string, inclusive bool, limit int, prefix string) (entries []*filer.Entry, err error) {
  88. return nil, filer.ErrUnsupportedListDirectoryPrefixed
  89. }
  90. func (store *ElasticStore) InsertEntry(ctx context.Context, entry *filer.Entry) (err error) {
  91. index := getIndex(entry.FullPath)
  92. dir, _ := entry.FullPath.DirAndName()
  93. id := weed_util.Md5String([]byte(entry.FullPath))
  94. esEntry := &ESEntry{
  95. ParentId: weed_util.Md5String([]byte(dir)),
  96. Entry: entry,
  97. }
  98. value, err := jsoniter.Marshal(esEntry)
  99. if err != nil {
  100. glog.Errorf("insert entry(%s) %v.", string(entry.FullPath), err)
  101. return fmt.Errorf("insert entry %v.", err)
  102. }
  103. _, err = store.client.Index().
  104. Index(index).
  105. Type(indexType).
  106. Id(id).
  107. BodyJson(string(value)).
  108. Do(ctx)
  109. if err != nil {
  110. glog.Errorf("insert entry(%s) %v.", string(entry.FullPath), err)
  111. return fmt.Errorf("insert entry %v.", err)
  112. }
  113. return nil
  114. }
  115. func (store *ElasticStore) UpdateEntry(ctx context.Context, entry *filer.Entry) (err error) {
  116. return store.InsertEntry(ctx, entry)
  117. }
  118. func (store *ElasticStore) FindEntry(ctx context.Context, fullpath weed_util.FullPath) (entry *filer.Entry, err error) {
  119. index := getIndex(fullpath)
  120. id := weed_util.Md5String([]byte(fullpath))
  121. searchResult, err := store.client.Get().
  122. Index(index).
  123. Type(indexType).
  124. Id(id).
  125. Do(ctx)
  126. if elastic.IsNotFound(err) {
  127. return nil, filer_pb.ErrNotFound
  128. }
  129. if searchResult != nil && searchResult.Found {
  130. esEntry := &ESEntry{
  131. ParentId: "",
  132. Entry: &filer.Entry{},
  133. }
  134. err := jsoniter.Unmarshal(searchResult.Source, esEntry)
  135. return esEntry.Entry, err
  136. }
  137. glog.Errorf("find entry(%s),%v.", string(fullpath), err)
  138. return nil, filer_pb.ErrNotFound
  139. }
  140. func (store *ElasticStore) DeleteEntry(ctx context.Context, fullpath weed_util.FullPath) (err error) {
  141. index := getIndex(fullpath)
  142. id := weed_util.Md5String([]byte(fullpath))
  143. if strings.Count(string(fullpath), "/") == 1 {
  144. return store.deleteIndex(ctx, index)
  145. }
  146. return store.deleteEntry(ctx, index, id)
  147. }
  148. func (store *ElasticStore) deleteIndex(ctx context.Context, index string) (err error) {
  149. deleteResult, err := store.client.DeleteIndex(index).Do(ctx)
  150. if elastic.IsNotFound(err) || (err == nil && deleteResult.Acknowledged) {
  151. return nil
  152. }
  153. glog.Errorf("delete index(%s) %v.", index, err)
  154. return err
  155. }
  156. func (store *ElasticStore) deleteEntry(ctx context.Context, index, id string) (err error) {
  157. deleteResult, err := store.client.Delete().
  158. Index(index).
  159. Type(indexType).
  160. Id(id).
  161. Do(ctx)
  162. if err == nil {
  163. if deleteResult.Result == "deleted" || deleteResult.Result == "not_found" {
  164. return nil
  165. }
  166. }
  167. glog.Errorf("delete entry(index:%s,_id:%s) %v.", index, id, err)
  168. return fmt.Errorf("delete entry %v.", err)
  169. }
  170. func (store *ElasticStore) DeleteFolderChildren(ctx context.Context, fullpath weed_util.FullPath) (err error) {
  171. if entries, err := store.ListDirectoryEntries(ctx, fullpath, "", false, math.MaxInt32); err == nil {
  172. for _, entry := range entries {
  173. store.DeleteEntry(ctx, entry.FullPath)
  174. }
  175. }
  176. return nil
  177. }
  178. func (store *ElasticStore) ListDirectoryEntries(
  179. ctx context.Context, fullpath weed_util.FullPath, startFileName string, inclusive bool, limit int,
  180. ) (entries []*filer.Entry, err error) {
  181. if string(fullpath) == "/" {
  182. return store.listRootDirectoryEntries(ctx, startFileName, inclusive, limit)
  183. }
  184. return store.listDirectoryEntries(ctx, fullpath, startFileName, inclusive, limit)
  185. }
  186. func (store *ElasticStore) listRootDirectoryEntries(ctx context.Context, startFileName string, inclusive bool, limit int) (entries []*filer.Entry, err error) {
  187. indexResult, err := store.client.CatIndices().Do(ctx)
  188. if err != nil {
  189. glog.Errorf("list indices %v.", err)
  190. return entries, err
  191. }
  192. for _, index := range indexResult {
  193. if index.Index == indexKV {
  194. continue
  195. }
  196. if strings.HasPrefix(index.Index, indexPrefix) {
  197. if entry, err := store.FindEntry(ctx,
  198. weed_util.FullPath("/"+strings.Replace(index.Index, indexPrefix, "", 1))); err == nil {
  199. fileName := getFileName(entry.FullPath)
  200. if fileName == startFileName && !inclusive {
  201. continue
  202. }
  203. limit--
  204. if limit < 0 {
  205. break
  206. }
  207. entries = append(entries, entry)
  208. }
  209. }
  210. }
  211. return entries, nil
  212. }
  213. func (store *ElasticStore) listDirectoryEntries(
  214. ctx context.Context, fullpath weed_util.FullPath, startFileName string, inclusive bool, limit int,
  215. ) (entries []*filer.Entry, err error) {
  216. first := true
  217. index := getIndex(fullpath)
  218. nextStart := ""
  219. parentId := weed_util.Md5String([]byte(fullpath))
  220. if _, err := store.client.Refresh(index).Do(ctx); err != nil {
  221. if elastic.IsNotFound(err) {
  222. store.client.CreateIndex(index).Do(ctx)
  223. return entries, nil
  224. }
  225. }
  226. for {
  227. result := &elastic.SearchResult{}
  228. if (startFileName == "" && first) || inclusive {
  229. if result, err = store.search(ctx, index, parentId); err != nil {
  230. glog.Errorf("search (%s,%s,%t,%d) %v.", string(fullpath), startFileName, inclusive, limit, err)
  231. return entries, err
  232. }
  233. } else {
  234. fullPath := string(fullpath) + "/" + startFileName
  235. if !first {
  236. fullPath = nextStart
  237. }
  238. after := weed_util.Md5String([]byte(fullPath))
  239. if result, err = store.searchAfter(ctx, index, parentId, after); err != nil {
  240. glog.Errorf("searchAfter (%s,%s,%t,%d) %v.", string(fullpath), startFileName, inclusive, limit, err)
  241. return entries, err
  242. }
  243. }
  244. first = false
  245. for _, hit := range result.Hits.Hits {
  246. esEntry := &ESEntry{
  247. ParentId: "",
  248. Entry: &filer.Entry{},
  249. }
  250. if err := jsoniter.Unmarshal(hit.Source, esEntry); err == nil {
  251. limit--
  252. if limit < 0 {
  253. return entries, nil
  254. }
  255. nextStart = string(esEntry.Entry.FullPath)
  256. fileName := getFileName(esEntry.Entry.FullPath)
  257. if fileName == startFileName && !inclusive {
  258. continue
  259. }
  260. entries = append(entries, esEntry.Entry)
  261. }
  262. }
  263. if len(result.Hits.Hits) < store.maxPageSize {
  264. break
  265. }
  266. }
  267. return entries, nil
  268. }
  269. func (store *ElasticStore) search(ctx context.Context, index, parentId string) (result *elastic.SearchResult, err error) {
  270. if count, err := store.client.Count(index).Do(ctx); err == nil && count == 0 {
  271. return &elastic.SearchResult{
  272. Hits: &elastic.SearchHits{
  273. Hits: make([]*elastic.SearchHit, 0)},
  274. }, nil
  275. }
  276. queryResult, err := store.client.Search().
  277. Index(index).
  278. Query(elastic.NewMatchQuery("ParentId", parentId)).
  279. Size(store.maxPageSize).
  280. Sort("_id", false).
  281. Do(ctx)
  282. return queryResult, err
  283. }
  284. func (store *ElasticStore) searchAfter(ctx context.Context, index, parentId, after string) (result *elastic.SearchResult, err error) {
  285. queryResult, err := store.client.Search().
  286. Index(index).
  287. Query(elastic.NewMatchQuery("ParentId", parentId)).
  288. SearchAfter(after).
  289. Size(store.maxPageSize).
  290. Sort("_id", false).
  291. Do(ctx)
  292. return queryResult, err
  293. }
  294. func (store *ElasticStore) Shutdown() {
  295. store.client.Stop()
  296. }
  297. func getIndex(fullpath weed_util.FullPath) string {
  298. path := strings.Split(string(fullpath), "/")
  299. if len(path) > 1 {
  300. return indexPrefix + path[1]
  301. }
  302. return ""
  303. }
  304. func getFileName(fullpath weed_util.FullPath) string {
  305. path := strings.Split(string(fullpath), "/")
  306. if len(path) > 1 {
  307. return path[len(path)-1]
  308. }
  309. return ""
  310. }