Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 0 additions & 4 deletions central/image/datastore/singleton.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
pgStoreV2 "github.com/stackrox/rox/central/image/datastore/store/v2/postgres"
"github.com/stackrox/rox/central/ranking"
riskDS "github.com/stackrox/rox/central/risk/datastore"
"github.com/stackrox/rox/pkg/features"
"github.com/stackrox/rox/pkg/sync"
)

Expand All @@ -23,9 +22,6 @@ func initialize() {

// Singleton provides the interface for non-service external interaction.
func Singleton() DataStore {
if features.FlattenImageData.Enabled() {
return nil
}
once.Do(initialize)
return ad
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
//go:build sql_integration

package m223tom224

import (
"context"
"fmt"
"testing"

"github.com/stackrox/rox/migrator/migrations/m_223_to_m_224_populate_deployment_containers_imageidv2/schema"
pghelper "github.com/stackrox/rox/migrator/migrations/postgreshelper"
"github.com/stackrox/rox/migrator/types"
"github.com/stackrox/rox/pkg/postgres/pgutils"
"github.com/stackrox/rox/pkg/sac"
"github.com/stackrox/rox/pkg/uuid"
)

func BenchmarkMigration(b *testing.B) {
ctx := sac.WithAllAccess(context.Background())
db := pghelper.ForT(b, false)
pgutils.CreateTableFromModel(ctx, db.GetGormDB(), schema.CreateTableDeploymentsStmt)

const numDeployments = 100
const containersPerDeployment = 5
totalContainers := numDeployments * containersPerDeployment

// Insert deployments and containers.
for i := 0; i < numDeployments; i++ {
depID := uuid.NewV4().String()
err := insertIntoDeployments(ctx, db, &schema.Deployments{
ID: depID,
Name: fmt.Sprintf("dep-%d", i),
Type: "Deployment",
Namespace: "default",
})
if err != nil {
b.Fatal(err)
}
for j := 0; j < containersPerDeployment; j++ {
sql := "INSERT INTO deployments_containers (image_name_fullname, image_id, deployments_id, idx) VALUES ($1, $2, $3, $4)"
fullName := fmt.Sprintf("registry.example.com/image-%d:%d@sha256:%064x", i, j, i*containersPerDeployment+j)
imageID := fmt.Sprintf("sha256:%064x", i*containersPerDeployment+j)
_, err := db.Exec(ctx, sql, fullName, imageID, depID, j)
if err != nil {
b.Fatal(err)
}
}
}

b.ResetTimer()
for n := 0; n < b.N; n++ {
// Reset image_idv2 so the migration has work to do each iteration.
_, err := db.Exec(ctx, "UPDATE deployments_containers SET image_idv2 = ''")
if err != nil {
b.Fatal(err)
}

batchSize = 5000
dbs := &types.Databases{
GormDB: db.GetGormDB(),
PostgresDB: db.DB,
DBCtx: ctx,
}
if err := migrate(dbs); err != nil {
b.Fatal(err)
}
}
b.StopTimer()

// Verify all rows were populated.
var count int
err := db.QueryRow(ctx, "SELECT COUNT(*) FROM deployments_containers WHERE image_idv2 != '' AND image_idv2 IS NOT NULL").Scan(&count)
if err != nil {
b.Fatal(err)
}
if count != totalContainers {
b.Fatalf("expected %d containers with image_idv2, got %d", totalContainers, count)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package m223tom224

import (
"github.com/hashicorp/go-multierror"
"github.com/jackc/pgx/v5"
"github.com/stackrox/rox/migrator/migrations/m_223_to_m_224_populate_deployment_containers_imageidv2/schema"
"github.com/stackrox/rox/migrator/types"
"github.com/stackrox/rox/pkg/logging"
"github.com/stackrox/rox/pkg/postgres"
"github.com/stackrox/rox/pkg/postgres/pgutils"
"github.com/stackrox/rox/pkg/uuid"
)

var (
log = logging.LoggerForModule()
batchSize = 5000
)

func migrate(database *types.Databases) error {
// Use databases.DBCtx to take advantage of the transaction wrapping present in the migration initiator
pgutils.CreateTableFromModel(database.DBCtx, database.GormDB, schema.CreateTableDeploymentsStmt)
log.Infof("Batch size is %d", batchSize)

db := database.PostgresDB

conn, err := db.Acquire(database.DBCtx)
defer conn.Release()
if err != nil {
return err
}
updatedRows := 0
for {
batch := pgx.Batch{}
// This will continue looping through the containers until there are no more containers that need to have their
// image_idv2 field populated, in batches up to batchSize
getStmt := `SELECT image_name_fullname, image_id FROM deployments_containers WHERE image_id is not null AND image_id != '' AND image_name_fullname is not null AND image_name_fullname != '' AND (image_idv2 is null OR image_idv2 = '') LIMIT $1`
rows, err := db.Query(database.DBCtx, getStmt, batchSize)
if err != nil {
return err
}
defer rows.Close()

containers, err := readRows(rows)
if err != nil {
return err
}
for _, container := range containers {
updateStmt := `UPDATE deployments_containers SET image_idv2 = $1 WHERE image_name_fullname = $2 AND image_id = $3`
imageIdV2 := uuid.NewV5FromNonUUIDs(container.ImageNameFullName, container.ImageID).String()
batch.Queue(updateStmt, imageIdV2, container.ImageNameFullName, container.ImageID)
}
batchResults := conn.SendBatch(database.DBCtx, &batch)
var result *multierror.Error
for i := 0; i < batch.Len(); i++ {
_, err = batchResults.Exec()
result = multierror.Append(result, err)
if err == nil {
updatedRows += 1
}
}
if err = batchResults.Close(); err != nil {
return err
}
if err = result.ErrorOrNil(); err != nil {
return err
}
if len(containers) != batchSize {
log.Infof("Populated the image_idv2 field in deployment containers. %d rows updated.", updatedRows)
return nil
}
}
}

func readRows(rows *postgres.Rows) ([]*schema.DeploymentsContainers, error) {
var containers []*schema.DeploymentsContainers

for rows.Next() {
var imageName string
var imageId string

if err := rows.Scan(&imageName, &imageId); err != nil {
log.Errorf("Error scanning row: %v", err)
}

container := &schema.DeploymentsContainers{
ImageID: imageId,
ImageNameFullName: imageName,
}
containers = append(containers, container)
}

log.Debugf("Read returned %d containers", len(containers))
return containers, rows.Err()
}
Comment on lines +77 to +94
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Scan errors are silently swallowed — risk of infinite loop and data corruption.

rows.Scan errors are logged but not returned, and the (now empty) container is still appended on line 89. Two consequences:

  1. A container with empty ImageNameFullName/ImageID gets a bogus UPDATE queued that matches nothing (the SELECT filter excludes empty values), so the row is silently skipped.
  2. Because len(containers) == batchSize still holds (we kept appending), the outer loop re-queries the same rows, scan-fails again, and loops forever.

Return the scan error immediately, or at least continue without appending.

🛡️ Proposed fix
 		if err := rows.Scan(&imageName, &imageId); err != nil {
-			log.Errorf("Error scanning row: %v", err)
+			return nil, err
 		}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
for rows.Next() {
var imageName string
var imageId string
if err := rows.Scan(&imageName, &imageId); err != nil {
log.Errorf("Error scanning row: %v", err)
}
container := &schema.DeploymentsContainers{
ImageID: imageId,
ImageNameFullName: imageName,
}
containers = append(containers, container)
}
log.Debugf("Read returned %d containers", len(containers))
return containers, rows.Err()
}
for rows.Next() {
var imageName string
var imageId string
if err := rows.Scan(&imageName, &imageId); err != nil {
return nil, err
}
container := &schema.DeploymentsContainers{
ImageID: imageId,
ImageNameFullName: imageName,
}
containers = append(containers, container)
}
log.Debugf("Read returned %d containers", len(containers))
return containers, rows.Err()
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@migrator/migrations/m_223_to_m_224_populate_deployment_containers_imageidv2/migration_impl.go`
around lines 77 - 94, The loop is appending a zeroed
schema.DeploymentsContainers even when rows.Scan returns an error, causing bad
updates and potential infinite re-querying; change the error handling in the for
rows.Next() loop so that when rows.Scan(&imageName, &imageId) returns an error
you do NOT append the container and instead return that error immediately (or at
minimum skip appending and continue), and make sure the function (the reader
that builds the containers slice) propagates the scan error rather than only
logging it; update the log message to include the scan error and remove the
append(containers, container) path when err != nil so containers only contains
successfully scanned items.

Loading
Loading