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.

util.go 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2023 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package elasticsearch
  4. import (
  5. "context"
  6. "fmt"
  7. "time"
  8. "code.gitea.io/gitea/modules/log"
  9. "github.com/olivere/elastic/v7"
  10. )
  11. // VersionedIndexName returns the full index name with version
  12. func (i *Indexer) VersionedIndexName() string {
  13. return versionedIndexName(i.indexName, i.version)
  14. }
  15. func versionedIndexName(indexName string, version int) string {
  16. if version == 0 {
  17. // Old index name without version
  18. return indexName
  19. }
  20. return fmt.Sprintf("%s.v%d", indexName, version)
  21. }
  22. func (i *Indexer) createIndex(ctx context.Context) error {
  23. createIndex, err := i.Client.CreateIndex(i.VersionedIndexName()).BodyString(i.mapping).Do(ctx)
  24. if err != nil {
  25. return err
  26. }
  27. if !createIndex.Acknowledged {
  28. return fmt.Errorf("create index %s with %s failed", i.VersionedIndexName(), i.mapping)
  29. }
  30. i.checkOldIndexes(ctx)
  31. return nil
  32. }
  33. func (i *Indexer) initClient() (*elastic.Client, error) {
  34. opts := []elastic.ClientOptionFunc{
  35. elastic.SetURL(i.url),
  36. elastic.SetSniff(false),
  37. elastic.SetHealthcheckInterval(10 * time.Second),
  38. elastic.SetGzip(false),
  39. }
  40. logger := log.GetLogger(log.DEFAULT)
  41. opts = append(opts, elastic.SetTraceLog(&log.PrintfLogger{Logf: logger.Trace}))
  42. opts = append(opts, elastic.SetInfoLog(&log.PrintfLogger{Logf: logger.Info}))
  43. opts = append(opts, elastic.SetErrorLog(&log.PrintfLogger{Logf: logger.Error}))
  44. return elastic.NewClient(opts...)
  45. }
  46. func (i *Indexer) checkOldIndexes(ctx context.Context) {
  47. for v := 0; v < i.version; v++ {
  48. indexName := versionedIndexName(i.indexName, v)
  49. exists, err := i.Client.IndexExists(indexName).Do(ctx)
  50. if err == nil && exists {
  51. log.Warn("Found older elasticsearch index named %q, Gitea will keep the old NOT DELETED. You can delete the old version after the upgrade succeed.", indexName)
  52. }
  53. }
  54. }