Skip to content
Merged
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
17 changes: 11 additions & 6 deletions pkg/db/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,21 +110,26 @@ func (c *Client) NeedsUpdate(ctx context.Context, cliVersion string, skip bool)
meta = metadata.Metadata{Version: db.SchemaVersion}
}

// We can't use the DB if either `trivy.db` or `metadata.json` is missing.
// In that case, we need to download the DB.
if noRequiredFiles {
if skip {
log.ErrorContext(ctx, "The first run cannot skip downloading DB")
return false, xerrors.New("--skip-db-update cannot be specified on the first run")
}
return true, nil
}

// There are 3 cases when DownloadAt field is zero:
// - metadata file was not created yet. This is the first run of Trivy.
// - trivy-db was downloaded with `oras`. In this case user can use `--skip-db-update` (like for air-gapped) or re-download trivy-db.
// - trivy-db was corrupted while copying from tmp directory to cache directory. We should update this trivy-db.
// We can't detect these cases, so we will show warning for users who use oras + air-gapped.
if !noRequiredFiles && meta.DownloadedAt.IsZero() && !skip {
if meta.DownloadedAt.IsZero() && !skip {
log.WarnContext(ctx, "Trivy DB may be corrupted and will be re-downloaded. If you manually downloaded DB - use the `--skip-db-update` flag to skip updating DB.")
return true, nil
}

if skip && noRequiredFiles {
log.ErrorContext(ctx, "The first run cannot skip downloading DB")
return false, xerrors.New("--skip-db-update cannot be specified on the first run")
}

if db.SchemaVersion < meta.Version {
log.ErrorContext(ctx, "Trivy version is old. Update to the latest version.", log.String("version", cliVersion))
return false, xerrors.Errorf("the version of DB schema doesn't match. Local DB: %d, Expected: %d",
Expand Down
13 changes: 13 additions & 0 deletions pkg/db/db_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,19 @@ func TestClient_NeedsUpdate(t *testing.T) {
"The local DB has an old schema version which is not supported by the current version of Trivy CLI. DB needs to be updated.",
},
},
{
name: "trivy.db is missing but metadata with recent DownloadedAt",
dbFileExists: false,
metadata: metadata.Metadata{
Version: db.SchemaVersion,
NextUpdate: timeNextUpdateDay1,
DownloadedAt: time.Date(2019, 9, 30, 23, 30, 0, 0, time.UTC),
},
want: true,
wantLogs: []string{
"There is no db file",
},
},
}

for _, tt := range tests {
Expand Down
Loading