Repository: chef/automate
Pull request #8822: Get the aliases for all the indexes eligible
Author: login: SahithiMy
Created: 2025-03-20T08:53:19Z | Merged: 2025-03-24T05:23:23Z

### :nut_and_bolt: Description: What code changed, and why?
Added GetAliases method to get aliases for indexes.
<!-- /!\ Please ensure that you are NOT disclosing any customer information without their consent /!\ -->

### :chains: Related Resources
https://progresssoftware.atlassian.net/browse/CHEF-19077
### :+1: Definition of Done

### :athletic_shoe: How to Build and Test the Change
`build components/ingest service`
`build components/automate-deployment/`
`build components/automate-cli`
Run `chef-automate reindex start`
### :white_check_mark: Checklist

**All PRs** must tick these:

- [ ] I have read the [CONTRIBUTING document](https://github.com/chef/automate/blob/master/CONTRIBUTING.md).
- [ ] All commits signed-off for the [Developer Certification of Origin](https://github.com/chef/chef/blob/master/CONTRIBUTING.md#developer-certification-of-origin-dco).

With occasional exceptions, all PRs **from Progress employees** must tick these:

- [ ] Is the code clear? *(complicated code or lots of comments--subdivide and use well-named methods, meaningful variable names, etc.)*
- [ ] Consistency checked? *(user notifications, user prompts, visual patterns, code patterns, variable names)*
- [ ] Repeated code blocks eliminated? *(adapt and reuse existing components, blocks, functions, etc.)*
- [ ] Spelling, grammar, typos checked? *(at a minimum use `make spell` in any component directory)*
- [ ] Code well-formatted? *(indents, line breaks, etc. improve rather than hinder readability)*

All PRs **from Progress employees** should tick these if appropriate:

- [ ] Tests added/updated? (all new code needs new tests)
- [ ] Docs added/updated? (all customer-facing changes)

*Please add a note next to any checkbox above if you are NOT ticking it.*

### :camera: Screenshots, if applicable
<img width="1416" alt="Screenshot 2025-03-21 at 1 27 25 PM" src="https://github.com/user-attachments/assets/b5de43c0-426a-4cb2-8ed2-1d746907ed86" />



Diff:
diff --git a/components/ingest-service/backend/client.go b/components/ingest-service/backend/client.go
index f60a6a39bb..6a80179dd7 100644
--- a/components/ingest-service/backend/client.go
+++ b/components/ingest-service/backend/client.go
@@ -94,9 +94,9 @@ type Client interface {
 	ReindexNodeStateToLatest(context.Context, string) (string, error)
 	GetActions(string, int, time.Time, string, bool) ([]InternalChefAction, int64, error)
 	DeleteAllIndexesWithPrefix(string, context.Context) error
-
 	GetIndices(ctx context.Context) ([]Index, error)
 	GetIndexVersionSettings(index string) (*IndexSettingsVersion, error)
 
 	TriggerReindex(index string) error
+	GetAliases(context.Context, string) ([]string, bool, error)
 }
diff --git a/components/ingest-service/backend/elastic/migration.go b/components/ingest-service/backend/elastic/migration.go
index e04388d870..ae36aafecf 100644
--- a/components/ingest-service/backend/elastic/migration.go
+++ b/components/ingest-service/backend/elastic/migration.go
@@ -537,3 +537,23 @@ func (es *Backend) GetIndexVersionSettings(index string) (*backend.IndexSettings
 func (es *Backend) TriggerReindex(index string) error {
 	return nil
 }
+
+func (es *Backend) GetAliases(ctx context.Context, index string) ([]string, bool, error) {
+
+	aliasesResult, err := es.client.Aliases().Index(index).Do(ctx)
+	if err != nil {
+		return nil, false, err
+	}
+
+	// Extract aliases from the result
+	var aliases []string
+
+	if indexAliases, ok := aliasesResult.Indices[index]; ok {
+		for _, alias := range indexAliases.Aliases {
+			aliases = append(aliases, alias.AliasName)
+		}
+	}
+
+	hasAliases := len(aliases) > 0
+	return aliases, hasAliases, nil
+}
diff --git a/components/ingest-service/server/chef.go b/components/ingest-service/server/chef.go
index 88e669d1e5..bd834407d1 100644
--- a/components/ingest-service/server/chef.go
+++ b/components/ingest-service/server/chef.go
@@ -282,7 +282,6 @@ OuterLoop:
 
 func (s *ChefIngestServer) StartReindex(ctx context.Context, req *ingest.StartReindexRequest) (*ingest.StartReindexResponse, error) {
 	log.Info("Received request to start reindexing")
-
 	indices, err := s.GetIndicesEligableForReindexing(ctx)
 	if err != nil {
 		return nil, status.Errorf(codes.Internal, "failed to fetch indices: %s", err)
@@ -315,8 +314,10 @@ func (s *ChefIngestServer) StartReindex(ctx context.Context, req *ingest.StartRe
 			return nil, status.Errorf(codes.Internal, "failed to add reindex request: %s", err)
 		}
 	}
-
-	log.Info("Reindexing started successfully")
+	err = s.GetAliases(ctx, indices, requestID)
+	if err != nil {
+		return nil, status.Errorf(codes.Internal, "failed to get aliases for indices: %s", err)
+	}
 	return &ingest.StartReindexResponse{
 		Message: "Reindexing started successfully",
 	}, nil
@@ -374,3 +375,22 @@ func (s *ChefIngestServer) GetVersion(ctx context.Context, empty *ingest.Version
 		Sha:     version.GitSHA,
 	}, nil
 }
+
+// Get aliases for indexes
+func (s *ChefIngestServer) GetAliases(ctx context.Context, indexes map[string]backend.IndexSettingsVersion, requestID int) error {
+	log.Info("Fetching aliases for indexes")
+	for index := range indexes {
+		log.Info("Fetching aliases for index: ", index)
+		alias, hasAlias, err := s.client.GetAliases(ctx, index)
+		if err != nil {
+			log.Info("Failed to fetch aliases for index: ", index)
+			return err
+		}
+		err = s.db.UpdateAliasesForIndex(index, hasAlias, alias, requestID, time.Now())
+		if err != nil {
+			log.Info("Failed to update aliases for index: ", index)
+			return err
+		}
+	}
+	return nil
+}
diff --git a/components/ingest-service/storage/db.go b/components/ingest-service/storage/db.go
index 20542a292a..4c5690099b 100644
--- a/components/ingest-service/storage/db.go
+++ b/components/ingest-service/storage/db.go
@@ -4,6 +4,7 @@ import (
 	"database/sql"
 	"encoding/json"
 	"sort"
+	"strings"
 	"time"
 
 	"github.com/chef/automate/components/ingest-service/config"
@@ -256,6 +257,16 @@ func (db *DB) GetLatestReindexRequestID() (int, error) {
 	return requestID, nil
 }
 
+func (db *DB) UpdateAliasesForIndex(index string, hasAlias bool, alias []string, requestID int, currentTime time.Time) error {
+	if hasAlias {
+		aliasString := strings.Join(alias, ",")
+		_, err := db.Exec(updateReindexRequestDetailed, hasAlias, aliasString, currentTime, requestID, index)
+		return err
+	}
+
+	return nil
+}
+
 // SQL Queries
 const insertReindexRequest = `
 INSERT INTO reindex_requests(status, created_at, last_updated)
@@ -287,3 +298,6 @@ DELETE FROM reindex_requests WHERE id = $1;`
 
 const deleteReindexRequestDetail = `
 DELETE FROM reindex_request_detailed WHERE id = $1;`
+
+const updateReindexRequestDetailed = `
+UPDATE reindex_request_detailed SET having_alias = $1, alias_list = $2, updated_at = $3 WHERE request_id = $4 AND index = $5;`
diff --git a/components/ingest-service/storage/db_test.go b/components/ingest-service/storage/db_test.go
index 5650a062aa..f08f172231 100644
--- a/components/ingest-service/storage/db_test.go
+++ b/components/ingest-service/storage/db_test.go
@@ -329,3 +329,53 @@ func TestGetReindexStatusNoDetails(t *testing.T) {
 	expectedJSON := `{"request_id":1,"status":"completed","indexes":[]}`
 	assert.JSONEq(t, expectedJSON, string(statusJSON))
 }
+
+func TestUpdateAliasesForIndex(t *testing.T) {
+	dbConn, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual))
+	assert.NoError(t, err)
+	defer dbConn.Close()
+
+	db := &storage.DB{
+		DbMap: &gorp.DbMap{Db: dbConn, Dialect: gorp.PostgresDialect{}},
+	}
+	time := time.Now()
+	query := `UPDATE reindex_request_detailed SET having_alias = $1, alias_list = $2, updated_at = $3 WHERE request_id = $4 AND index = $5;`
+	mock.ExpectExec(query).WithArgs(true, "test,test2", time, 1, "reindexing").WillReturnError(fmt.Errorf("update error"))
+
+	err = db.UpdateAliasesForIndex("reindexing", true, []string{"test", "test2"}, 1, time)
+	assert.EqualError(t, err, "update error")
+}
+
+func TestUpdateAliasesForIndexSuccess(t *testing.T) {
+	dbConn, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual))
+	assert.NoError(t, err)
+	defer dbConn.Close()
+
+	db := &storage.DB{
+		DbMap: &gorp.DbMap{Db: dbConn, Dialect: gorp.PostgresDialect{}},
+	}
+	time := time.Now()
+
+	query := `UPDATE reindex_request_detailed SET having_alias = $1, alias_list = $2, updated_at = $3 WHERE request_id = $4 AND index = $5;`
+	mock.ExpectExec(query).WithArgs(true, "test1,test2", time, 1, "reindexing").WillReturnResult(sqlmock.NewResult(1, 1))
+
+	err = db.UpdateAliasesForIndex("reindexing", true, []string{"test1", "test2"}, 1, time)
+	assert.NoError(t, err)
+}
+
+func TestUpdateAliasesForIndexNoAliases(t *testing.T) {
+	dbConn, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual))
+	assert.NoError(t, err)
+	defer dbConn.Close()
+
+	db := &storage.DB{
+		DbMap: &gorp.DbMap{Db: dbConn, Dialect: gorp.PostgresDialect{}},
+	}
+	time := time.Now()
+
+	query := `UPDATE reindex_request_detailed SET having_alias = $1, alias_list = $2, updated_at = $3 WHERE request_id = $4 AND index = $5;`
+	mock.ExpectExec(query).WithArgs(false, "", time, 1, "reindexing").WillReturnResult(sqlmock.NewResult(1, 1))
+
+	err = db.UpdateAliasesForIndex("reindexing", false, []string{""}, 1, time)
+	assert.NoError(t, err)
+}


Reviews:
user: login: Dmaddu
state: CHANGES_REQUESTED
author_association: COLLABORATOR
submitted_at: 2025-03-21T09:12:14Z
user: login: Dmaddu
state: APPROVED
author_association: COLLABORATOR
submitted_at: 2025-03-21T10:11:35Z
user: login: Dmaddu
body: The unit tests are failing for ingest service here
https://buildkite.com/chef-oss/chef-automate-main-verify/builds/35694#0195b80a-f257-48e7-8bf7-a220561d1b66
plz fix them
state: CHANGES_REQUESTED
author_association: COLLABORATOR
submitted_at: 2025-03-21T10:14:05Z
user: login: Dmaddu
state: APPROVED
author_association: COLLABORATOR
submitted_at: 2025-03-24T05:23:13Z

Review comments:
diff_hunk: @@ -329,3 +329,35 @@ func TestGetReindexStatusNoDetails(t *testing.T) {
 	expectedJSON := `{"request_id":1,"status":"completed","indexes":[]}`
 	assert.JSONEq(t, expectedJSON, string(statusJSON))
 }
+
+func TestUpdateAliasesForIndex(t *testing.T) {
path: components/ingest-service/storage/db_test.go
user: login: Dmaddu
body: plz, add the scenario of having no alias for the index.
created_at: 2025-03-21T09:10:43Z
author_association: COLLABORATOR
diff_hunk: @@ -287,3 +298,6 @@ DELETE FROM reindex_requests WHERE id = $1;`
 
 const deleteReindexRequestDetail = `
 DELETE FROM reindex_request_detailed WHERE id = $1;`
+
+const updateReindexRequestDetailed = `
path: components/ingest-service/storage/db.go
user: login: Dmaddu
body: you need to update the last_updated column as well with this update
created_at: 2025-03-21T09:11:16Z
author_association: COLLABORATOR

PR comments:
user: login: netlify[bot]
created_at: 2025-03-20T08:53:36Z
body: ### <span aria-hidden="true">👷</span> Deploy Preview for *chef-automate* processing.


|  Name | Link |
|:-:|------------------------|
|<span aria-hidden="true">🔨</span> Latest commit | fe18bdaf51f68c05da60b5c2a14e1e99e42cfdf6 |
|<span aria-hidden="true">🔍</span> Latest deploy log | https://app.netlify.com/sites/chef-automate/deploys/67dd3e310c7f210008f17d38 |
author_association: NONE
user: login: sonarqube-for-infrastructure-prod[bot]
created_at: 2025-03-21T08:35:26Z
body: ## [![Quality Gate failed](https://raw.githubusercontent.com/SonarSource/sonarqube-static-resources/master/v104/checks/QualityGateBadge/failed-16px.png 'Quality Gate failed')](https://sonar.progress.com/dashboard?id=chef_automate_AYeOVEbqJ4YHsO5MtKWC&pullRequest=8822) **Quality Gate failed**  
Failed conditions  
[![](https://raw.githubusercontent.com/SonarSource/sonarqube-static-resources/master/v104/common/failed-16px.png '')](https://sonar.progress.com/component_measures?id=chef_automate_AYeOVEbqJ4YHsO5MtKWC&pullRequest=8822&metric=new_coverage&view=list) [13.8% Coverage on New Code](https://sonar.progress.com/component_measures?id=chef_automate_AYeOVEbqJ4YHsO5MtKWC&pullRequest=8822&metric=new_coverage&view=list) (required ≥ 80%)  
  
[See analysis details on SonarQube](https://sonar.progress.com/dashboard?id=chef_automate_AYeOVEbqJ4YHsO5MtKWC&pullRequest=8822)


author_association: NONE