elastic_store.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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, dirPath weed_util.FullPath, startFileName string, includeStartFile bool, limit int64, prefix string, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) {
  88. return lastFileName, filer.ErrUnsupportedListDirectoryPrefixed
  89. }
  90. func (store *ElasticStore) InsertEntry(ctx context.Context, entry *filer.Entry) (err error) {
  91. index := getIndex(entry.FullPath, false)
  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, false)
  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, false)
  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, limit int64) (err error) {
  171. _, err = store.ListDirectoryEntries(ctx, fullpath, "", false, math.MaxInt32, func(entry *filer.Entry) bool {
  172. if err := store.DeleteEntry(ctx, entry.FullPath); err != nil {
  173. glog.Errorf("elastic delete %s: %v.", entry.FullPath, err)
  174. return false
  175. }
  176. return true
  177. })
  178. return
  179. }
  180. func (store *ElasticStore) ListDirectoryEntries(ctx context.Context, dirPath weed_util.FullPath, startFileName string, includeStartFile bool, limit int64, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) {
  181. return store.listDirectoryEntries(ctx, dirPath, startFileName, includeStartFile, limit, eachEntryFunc)
  182. }
  183. func (store *ElasticStore) listDirectoryEntries(
  184. ctx context.Context, fullpath weed_util.FullPath, startFileName string, inclusive bool, limit int64, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) {
  185. first := true
  186. index := getIndex(fullpath, true)
  187. nextStart := ""
  188. parentId := weed_util.Md5String([]byte(fullpath))
  189. if _, err = store.client.Refresh(index).Do(ctx); err != nil {
  190. if elastic.IsNotFound(err) {
  191. store.client.CreateIndex(index).Do(ctx)
  192. return
  193. }
  194. }
  195. for {
  196. result := &elastic.SearchResult{}
  197. if (startFileName == "" && first) || inclusive {
  198. if result, err = store.search(ctx, index, parentId); err != nil {
  199. glog.Errorf("search (%s,%s,%t,%d) %v.", string(fullpath), startFileName, inclusive, limit, err)
  200. return
  201. }
  202. } else {
  203. fullPath := string(fullpath) + "/" + startFileName
  204. if !first {
  205. fullPath = nextStart
  206. }
  207. after := weed_util.Md5String([]byte(fullPath))
  208. if result, err = store.searchAfter(ctx, index, parentId, after); err != nil {
  209. glog.Errorf("searchAfter (%s,%s,%t,%d) %v.", string(fullpath), startFileName, inclusive, limit, err)
  210. return
  211. }
  212. }
  213. first = false
  214. for _, hit := range result.Hits.Hits {
  215. esEntry := &ESEntry{
  216. ParentId: "",
  217. Entry: &filer.Entry{},
  218. }
  219. if err := jsoniter.Unmarshal(hit.Source, esEntry); err == nil {
  220. limit--
  221. if limit < 0 {
  222. return lastFileName, nil
  223. }
  224. nextStart = string(esEntry.Entry.FullPath)
  225. fileName := esEntry.Entry.FullPath.Name()
  226. if fileName == startFileName && !inclusive {
  227. continue
  228. }
  229. if !eachEntryFunc(esEntry.Entry) {
  230. break
  231. }
  232. lastFileName = fileName
  233. }
  234. }
  235. if len(result.Hits.Hits) < store.maxPageSize {
  236. break
  237. }
  238. }
  239. return
  240. }
  241. func (store *ElasticStore) search(ctx context.Context, index, parentId string) (result *elastic.SearchResult, err error) {
  242. if count, err := store.client.Count(index).Do(ctx); err == nil && count == 0 {
  243. return &elastic.SearchResult{
  244. Hits: &elastic.SearchHits{
  245. Hits: make([]*elastic.SearchHit, 0)},
  246. }, nil
  247. }
  248. queryResult, err := store.client.Search().
  249. Index(index).
  250. Query(elastic.NewMatchQuery("ParentId", parentId)).
  251. Size(store.maxPageSize).
  252. Sort("_id", false).
  253. Do(ctx)
  254. return queryResult, err
  255. }
  256. func (store *ElasticStore) searchAfter(ctx context.Context, index, parentId, after string) (result *elastic.SearchResult, err error) {
  257. queryResult, err := store.client.Search().
  258. Index(index).
  259. Query(elastic.NewMatchQuery("ParentId", parentId)).
  260. SearchAfter(after).
  261. Size(store.maxPageSize).
  262. Sort("_id", false).
  263. Do(ctx)
  264. return queryResult, err
  265. }
  266. func (store *ElasticStore) Shutdown() {
  267. store.client.Stop()
  268. }
  269. func getIndex(fullpath weed_util.FullPath, isDirectory bool) string {
  270. path := strings.Split(string(fullpath), "/")
  271. if isDirectory && len(path) >= 2 {
  272. return indexPrefix + strings.ToLower(path[1])
  273. }
  274. if len(path) > 2 {
  275. return indexPrefix + strings.ToLower(path[1])
  276. }
  277. if len(path) == 2 {
  278. return indexPrefix
  279. }
  280. return ""
  281. }