code.gitea.io/gitea@v1.22.3/modules/indexer/internal/elasticsearch/util.go (about) 1 // Copyright 2023 The Gitea Authors. All rights reserved. 2 // SPDX-License-Identifier: MIT 3 4 package elasticsearch 5 6 import ( 7 "context" 8 "fmt" 9 "time" 10 11 "code.gitea.io/gitea/modules/log" 12 13 "github.com/olivere/elastic/v7" 14 ) 15 16 // VersionedIndexName returns the full index name with version 17 func (i *Indexer) VersionedIndexName() string { 18 return versionedIndexName(i.indexName, i.version) 19 } 20 21 func versionedIndexName(indexName string, version int) string { 22 if version == 0 { 23 // Old index name without version 24 return indexName 25 } 26 return fmt.Sprintf("%s.v%d", indexName, version) 27 } 28 29 func (i *Indexer) createIndex(ctx context.Context) error { 30 createIndex, err := i.Client.CreateIndex(i.VersionedIndexName()).BodyString(i.mapping).Do(ctx) 31 if err != nil { 32 return err 33 } 34 if !createIndex.Acknowledged { 35 return fmt.Errorf("create index %s with %s failed", i.VersionedIndexName(), i.mapping) 36 } 37 38 i.checkOldIndexes(ctx) 39 40 return nil 41 } 42 43 func (i *Indexer) initClient() (*elastic.Client, error) { 44 opts := []elastic.ClientOptionFunc{ 45 elastic.SetURL(i.url), 46 elastic.SetSniff(false), 47 elastic.SetHealthcheckInterval(10 * time.Second), 48 elastic.SetGzip(false), 49 } 50 51 logger := log.GetLogger(log.DEFAULT) 52 53 opts = append(opts, elastic.SetTraceLog(&log.PrintfLogger{Logf: logger.Trace})) 54 opts = append(opts, elastic.SetInfoLog(&log.PrintfLogger{Logf: logger.Info})) 55 opts = append(opts, elastic.SetErrorLog(&log.PrintfLogger{Logf: logger.Error})) 56 57 return elastic.NewClient(opts...) 58 } 59 60 func (i *Indexer) checkOldIndexes(ctx context.Context) { 61 for v := 0; v < i.version; v++ { 62 indexName := versionedIndexName(i.indexName, v) 63 exists, err := i.Client.IndexExists(indexName).Do(ctx) 64 if err == nil && exists { 65 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) 66 } 67 } 68 }