elastic_store.go 9.2 KB

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