Skip to content

Commit

Permalink
Use %w verb for fmt.Errorf error wrappings (#668)
Browse files Browse the repository at this point in the history
* Configrue linter to enable fmt.Errorf error wrapping check

* Replace %v with %w verb for fmt.Errorf error wrapping
  • Loading branch information
panyuenlau committed Sep 10, 2023
1 parent 799b5c9 commit 5d1ede7
Show file tree
Hide file tree
Showing 47 changed files with 160 additions and 160 deletions.
2 changes: 1 addition & 1 deletion .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ linters-settings:
local-prefixes: github.com/openclarity/vmclarity
errorlint:
# Check whether fmt.Errorf uses the %w verb for formatting errors. See the readme for caveats
errorf: false
errorf: true
gomoddirectives:
# Allow local `replace` directives. Default is false.
replace-local: true
Expand Down
12 changes: 6 additions & 6 deletions cmd/vmclarity-cli/asset/asset_create.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,26 +91,26 @@ func init() {
func getAssetFromJSONFile(filename string) (*models.AssetType, error) {
file, err := os.Open(filename)
if err != nil {
return nil, fmt.Errorf("failed to open file: %v", err)
return nil, fmt.Errorf("failed to open file: %w", err)
}
defer file.Close()

// get the file size
stat, err := file.Stat()
if err != nil {
return nil, fmt.Errorf("failed to get file stat: %v", err)
return nil, fmt.Errorf("failed to get file stat: %w", err)
}

// read the file
bs := make([]byte, stat.Size())
_, err = file.Read(bs)
if err != nil {
return nil, fmt.Errorf("failed to read file: %v", err)
return nil, fmt.Errorf("failed to read file: %w", err)
}

assetType := &models.AssetType{}
if err := assetType.UnmarshalJSON(bs); err != nil {
return nil, fmt.Errorf("failed to unmarshal asset into AssetType %v", err)
return nil, fmt.Errorf("failed to unmarshal asset into AssetType %w", err)
}

return assetType, nil
Expand All @@ -137,12 +137,12 @@ func createAsset(ctx context.Context, assetType *models.AssetType, server string
// which matches the unique properties of this asset, in this
// case if the update-if-exists flag is set we'll patch the just AssetInfo and FirstSeen instead.
if !errors.As(err, &conflictError) || !updateIfExists {
return nil, fmt.Errorf("failed to post asset: %v", err)
return nil, fmt.Errorf("failed to post asset: %w", err)
}
assetData.FirstSeen = nil
err = client.PatchAsset(ctx, assetData, *conflictError.ConflictingAsset.Id)
if err != nil {
return nil, fmt.Errorf("failed to patch asset: %v", err)
return nil, fmt.Errorf("failed to patch asset: %w", err)
}

return conflictError.ConflictingAsset, nil
Expand Down
2 changes: 1 addition & 1 deletion pkg/apiserver/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ func LoadConfig() (*Config, error) {
if err == nil {
log.Infof("\n\nconfig=%s\n\n", configB)
} else {
return nil, fmt.Errorf("failed to marshal config: %v", err)
return nil, fmt.Errorf("failed to marshal config: %w", err)
}

return config, nil
Expand Down
2 changes: 1 addition & 1 deletion pkg/apiserver/database/gorm/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ func initPostgres(config types.DBConfig, dbLogger logger.Interface) (*gorm.DB, e
Logger: dbLogger,
})
if err != nil {
return nil, fmt.Errorf("failed to open %s db: %v", config.DBName, err)
return nil, fmt.Errorf("failed to open %s db: %w", config.DBName, err)
}

return db, nil
Expand Down
2 changes: 1 addition & 1 deletion pkg/apiserver/database/gorm/scan_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ func validateRuntimeScheduleScanConfig(scheduled *models.RuntimeScheduleScanConf
// validate cron expression
expr, err := cronexpr.Parse(*scheduled.CronLine)
if err != nil {
return fmt.Errorf("malformed cron expression: %v", err)
return fmt.Errorf("malformed cron expression: %w", err)
}

// set operation time if missing
Expand Down
4 changes: 2 additions & 2 deletions pkg/apiserver/database/odatasql/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -694,14 +694,14 @@ func buildWhereFromLambda(sqlVariant jsonsql.Variant, schemaMetas map[string]Sch
newIdentifier := fmt.Sprintf("%sFilterOptions", identifier)
subquery, err := buildWhereFromFilter(sqlVariant, schemaMetas, newFieldMetas[0], newIdentifier, fmt.Sprintf("%s.value", identifier), lambda.Children[1], fmt.Sprintf("%s.", lambda.Children[0].Token.Value))
if err != nil {
return "", fmt.Errorf("unable to build query inside lambda: %v", err)
return "", fmt.Errorf("unable to build query inside lambda: %w", err)
}
return fmt.Sprintf("EXISTS (SELECT 1 FROM %s AS %s WHERE %s)", sqlVariant.JSONEach(sqlVariant.JSONExtract(fieldSource, sourcePath)), identifier, subquery), nil
case "all":
newIdentifier := fmt.Sprintf("%sFilterOptions", identifier)
subquery, err := buildWhereFromFilter(sqlVariant, schemaMetas, newFieldMetas[0], newIdentifier, fmt.Sprintf("%s.value", identifier), lambda.Children[1], fmt.Sprintf("%s.", lambda.Children[0].Token.Value))
if err != nil {
return "", fmt.Errorf("unable to build query inside lambda: %v", err)
return "", fmt.Errorf("unable to build query inside lambda: %w", err)
}
return fmt.Sprintf("NOT EXISTS (SELECT 1 FROM %s AS %s WHERE NOT (%s))", sqlVariant.JSONEach(sqlVariant.JSONExtract(fieldSource, sourcePath)), identifier, subquery), nil
default:
Expand Down
2 changes: 1 addition & 1 deletion pkg/apiserver/rest/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func sendResponse(ctx echo.Context, code int, object interface{}) error {
func (s *ServerImpl) GetOpenAPISpec(ctx echo.Context) error {
swagger, err := server.GetSwagger()
if err != nil {
return fmt.Errorf("failed to load swagger spec: %v", err)
return fmt.Errorf("failed to load swagger spec: %w", err)
}

// Use the X-Forwarded-* headers to populate the OpenAPI spec with the
Expand Down
4 changes: 2 additions & 2 deletions pkg/apiserver/rest/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ type Server struct {
func CreateRESTServer(port int, dbHandler databaseTypes.Database) (*Server, error) {
e, err := createEchoServer(dbHandler)
if err != nil {
return nil, fmt.Errorf("failed to create rest server: %v", err)
return nil, fmt.Errorf("failed to create rest server: %w", err)
}
return &Server{
port: port,
Expand All @@ -57,7 +57,7 @@ func CreateRESTServer(port int, dbHandler databaseTypes.Database) (*Server, erro
func createEchoServer(dbHandler databaseTypes.Database) (*echo.Echo, error) {
swagger, err := server.GetSwagger()
if err != nil {
return nil, fmt.Errorf("failed to load swagger spec: %v", err)
return nil, fmt.Errorf("failed to load swagger spec: %w", err)
}

e := echo.New()
Expand Down
6 changes: 3 additions & 3 deletions pkg/cli/utils/json_helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,18 +28,18 @@ func PrintJSONData(data interface{}, fields string) error {
if fields == "" {
dataB, err := json.Marshal(data)
if err != nil {
return fmt.Errorf("failed to marshal data: %v", err)
return fmt.Errorf("failed to marshal data: %w", err)
}
fmt.Println(string(dataB))
return nil
}
j := jsonpath.New("parser")
if err := j.Parse(fields); err != nil {
return fmt.Errorf("failed to parse jsonpath: %v", err)
return fmt.Errorf("failed to parse jsonpath: %w", err)
}
err := j.Execute(os.Stdout, data)
if err != nil {
return fmt.Errorf("failed to execute jsonpath: %v", err)
return fmt.Errorf("failed to execute jsonpath: %w", err)
}
return nil
}
4 changes: 2 additions & 2 deletions pkg/orchestrator/assetscanprocessor/exploits.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func (asp *AssetScanProcessor) reconcileResultExploitsToFindings(ctx context.Con

newerFound, newerTime, err := asp.newerExistingFindingTime(ctx, assetScan.Asset.Id, "Exploit", *completedTime)
if err != nil {
return fmt.Errorf("failed to check for newer existing exploits findings: %v", err)
return fmt.Errorf("failed to check for newer existing exploits findings: %w", err)
}

// Build a map of existing findings for this scan to prevent us
Expand Down Expand Up @@ -131,7 +131,7 @@ func (asp *AssetScanProcessor) reconcileResultExploitsToFindings(ctx context.Con
// an asset scan older than this asset scan.
err = asp.invalidateOlderFindingsByType(ctx, "Exploit", assetScan.Asset.Id, *completedTime)
if err != nil {
return fmt.Errorf("failed to invalidate older exploit finding: %v", err)
return fmt.Errorf("failed to invalidate older exploit finding: %w", err)
}

// Get all findings which aren't invalidated, and then update the asset's summary
Expand Down
4 changes: 2 additions & 2 deletions pkg/orchestrator/assetscanprocessor/infofinder.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func (asp *AssetScanProcessor) reconcileResultInfoFindersToFindings(ctx context.

newerFound, newerTime, err := asp.newerExistingFindingTime(ctx, assetScan.Asset.Id, "InfoFinder", *completedTime)
if err != nil {
return fmt.Errorf("failed to check for newer existing InfoFinder findings: %v", err)
return fmt.Errorf("failed to check for newer existing InfoFinder findings: %w", err)
}

// Build a map of existing findings for this scan to prevent us
Expand Down Expand Up @@ -129,7 +129,7 @@ func (asp *AssetScanProcessor) reconcileResultInfoFindersToFindings(ctx context.
// an asset scan older than this asset scan.
err = asp.invalidateOlderFindingsByType(ctx, "InfoFinder", assetScan.Asset.Id, *completedTime)
if err != nil {
return fmt.Errorf("failed to invalidate older InfoFinder finding: %v", err)
return fmt.Errorf("failed to invalidate older InfoFinder finding: %w", err)
}

// Get all findings which aren't invalidated, and then update the asset's summary
Expand Down
4 changes: 2 additions & 2 deletions pkg/orchestrator/assetscanprocessor/malware.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func (asp *AssetScanProcessor) reconcileResultMalwareToFindings(ctx context.Cont

newerFound, newerTime, err := asp.newerExistingFindingTime(ctx, assetScan.Asset.Id, "Malware", *completedTime)
if err != nil {
return fmt.Errorf("failed to check for newer existing malware findings: %v", err)
return fmt.Errorf("failed to check for newer existing malware findings: %w", err)
}

// Build a map of existing findings for this scan to prevent us
Expand Down Expand Up @@ -128,7 +128,7 @@ func (asp *AssetScanProcessor) reconcileResultMalwareToFindings(ctx context.Cont
// an asset scan older than this asset scan.
err = asp.invalidateOlderFindingsByType(ctx, "Malware", assetScan.Asset.Id, *completedTime)
if err != nil {
return fmt.Errorf("failed to invalidate older malware finding: %v", err)
return fmt.Errorf("failed to invalidate older malware finding: %w", err)
}

// Get all findings which aren't invalidated, and then update the asset's summary
Expand Down
4 changes: 2 additions & 2 deletions pkg/orchestrator/assetscanprocessor/misconfigurations.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func (asp *AssetScanProcessor) reconcileResultMisconfigurationsToFindings(ctx co

newerFound, newerTime, err := asp.newerExistingFindingTime(ctx, assetScan.Asset.Id, "Misconfiguration", *completedTime)
if err != nil {
return fmt.Errorf("failed to check for newer existing misconfiguration findings: %v", err)
return fmt.Errorf("failed to check for newer existing misconfiguration findings: %w", err)
}

// Build a map of existing findings for this scan to prevent us
Expand Down Expand Up @@ -133,7 +133,7 @@ func (asp *AssetScanProcessor) reconcileResultMisconfigurationsToFindings(ctx co
// an asset scan older than this asset scan.
err = asp.invalidateOlderFindingsByType(ctx, "Misconfiguration", assetScan.Asset.Id, *completedTime)
if err != nil {
return fmt.Errorf("failed to invalidate older misconfiguration finding: %v", err)
return fmt.Errorf("failed to invalidate older misconfiguration finding: %w", err)
}

// Get all findings which aren't invalidated, and then update the asset's summary
Expand Down
4 changes: 2 additions & 2 deletions pkg/orchestrator/assetscanprocessor/packages.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func (asp *AssetScanProcessor) reconcileResultPackagesToFindings(ctx context.Con

newerFound, newerTime, err := asp.newerExistingFindingTime(ctx, assetScan.Asset.Id, "Package", *completedTime)
if err != nil {
return fmt.Errorf("failed to check for newer existing package findings: %v", err)
return fmt.Errorf("failed to check for newer existing package findings: %w", err)
}

// Build a map of existing findings for this scan to prevent us
Expand Down Expand Up @@ -132,7 +132,7 @@ func (asp *AssetScanProcessor) reconcileResultPackagesToFindings(ctx context.Con
// an asset scan older than this asset scan.
err = asp.invalidateOlderFindingsByType(ctx, "Package", assetScan.Asset.Id, *completedTime)
if err != nil {
return fmt.Errorf("failed to invalidate older package finding: %v", err)
return fmt.Errorf("failed to invalidate older package finding: %w", err)
}

// Get all findings which aren't invalidated, and then update the asset's summary
Expand Down
4 changes: 2 additions & 2 deletions pkg/orchestrator/assetscanprocessor/rootkits.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func (asp *AssetScanProcessor) reconcileResultRootkitsToFindings(ctx context.Con

newerFound, newerTime, err := asp.newerExistingFindingTime(ctx, assetScan.Asset.Id, "Rootkit", *completedTime)
if err != nil {
return fmt.Errorf("failed to check for newer existing rootkit findings: %v", err)
return fmt.Errorf("failed to check for newer existing rootkit findings: %w", err)
}

// Build a map of existing findings for this scan to prevent us
Expand Down Expand Up @@ -128,7 +128,7 @@ func (asp *AssetScanProcessor) reconcileResultRootkitsToFindings(ctx context.Con
// an asset scan older than this asset scan.
err = asp.invalidateOlderFindingsByType(ctx, "Rootkit", assetScan.Asset.Id, *completedTime)
if err != nil {
return fmt.Errorf("failed to invalidate older rootkit finding: %v", err)
return fmt.Errorf("failed to invalidate older rootkit finding: %w", err)
}

// Get all findings which aren't invalidated, and then update the asset's summary
Expand Down
4 changes: 2 additions & 2 deletions pkg/orchestrator/assetscanprocessor/secrets.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func (asp *AssetScanProcessor) reconcileResultSecretsToFindings(ctx context.Cont

newerFound, newerTime, err := asp.newerExistingFindingTime(ctx, assetScan.Asset.Id, "Secret", *completedTime)
if err != nil {
return fmt.Errorf("failed to check for newer existing secret findings: %v", err)
return fmt.Errorf("failed to check for newer existing secret findings: %w", err)
}

// Build a map of existing findings for this scan to prevent us
Expand Down Expand Up @@ -132,7 +132,7 @@ func (asp *AssetScanProcessor) reconcileResultSecretsToFindings(ctx context.Cont
// an asset scan older than this asset scan.
err = asp.invalidateOlderFindingsByType(ctx, "Secret", assetScan.Asset.Id, *completedTime)
if err != nil {
return fmt.Errorf("failed to invalidate older secret finding: %v", err)
return fmt.Errorf("failed to invalidate older secret finding: %w", err)
}

// Get all findings which aren't invalidated, and then update the asset's summary
Expand Down
4 changes: 2 additions & 2 deletions pkg/orchestrator/assetscanprocessor/vulnerabilities.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func (asp *AssetScanProcessor) reconcileResultVulnerabilitiesToFindings(ctx cont

newerFound, newerTime, err := asp.newerExistingFindingTime(ctx, assetScan.Asset.Id, "Vulnerability", *completedTime)
if err != nil {
return fmt.Errorf("failed to check for newer existing vulnerability findings: %v", err)
return fmt.Errorf("failed to check for newer existing vulnerability findings: %w", err)
}

existingFilter := fmt.Sprintf("findingInfo/objectType eq 'Vulnerability' and foundBy/id eq '%s'", *assetScan.Id)
Expand Down Expand Up @@ -121,7 +121,7 @@ func (asp *AssetScanProcessor) reconcileResultVulnerabilitiesToFindings(ctx cont
// an asset scan older than this asset scan.
err = asp.invalidateOlderFindingsByType(ctx, "Vulnerability", assetScan.Asset.Id, *completedTime)
if err != nil {
return fmt.Errorf("failed to invalidate older vulnerability finding: %v", err)
return fmt.Errorf("failed to invalidate older vulnerability finding: %w", err)
}

// Get all findings which aren't invalidated, and then update the asset's summary
Expand Down
2 changes: 1 addition & 1 deletion pkg/orchestrator/discovery/discoverer.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ func (d *Discoverer) DiscoverAndCreateAssets(ctx context.Context) error {
}

if err := discoverer.Err(); err != nil {
return fmt.Errorf("failed to discover assets: %v", err)
return fmt.Errorf("failed to discover assets: %w", err)
}

// Find all assets which are not already terminatedOn and were not
Expand Down
4 changes: 2 additions & 2 deletions pkg/orchestrator/provider/aws/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -794,7 +794,7 @@ func (c *Client) GetInstances(ctx context.Context, filters []ec2types.Filter, re
options.Region = regionID
})
if err != nil {
return nil, fmt.Errorf("failed to describe instances: %v", err)
return nil, fmt.Errorf("failed to describe instances: %w", err)
}
ret = append(ret, c.getInstancesFromDescribeInstancesOutput(ctx, out, regionID)...)

Expand All @@ -813,7 +813,7 @@ func (c *Client) GetInstances(ctx context.Context, filters []ec2types.Filter, re
options.Region = regionID
})
if err != nil {
return nil, fmt.Errorf("failed to describe instances: %v", err)
return nil, fmt.Errorf("failed to describe instances: %w", err)
}
ret = append(ret, c.getInstancesFromDescribeInstancesOutput(ctx, out, regionID)...)
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/orchestrator/provider/aws/instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ func (i *Instance) Delete(ctx context.Context) error {
options.Region = i.Region
})
if err != nil {
return fmt.Errorf("failed to terminate instances: %v", err)
return fmt.Errorf("failed to terminate instances: %w", err)
}

return nil
Expand Down
2 changes: 1 addition & 1 deletion pkg/orchestrator/provider/aws/snapshot.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ func (s *Snapshot) Delete(ctx context.Context) error {
options.Region = s.Region
})
if err != nil {
return fmt.Errorf("failed to delete snapshot: %v", err)
return fmt.Errorf("failed to delete snapshot: %w", err)
}

return nil
Expand Down
2 changes: 1 addition & 1 deletion pkg/orchestrator/provider/azure/scannerVm.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ func (c *Client) ensureScannerVirtualMachine(ctx context.Context, config *provid

userData, err := cloudinit.New(config)
if err != nil {
return armcompute.VirtualMachine{}, fmt.Errorf("failed to generate cloud-init: %v", err)
return armcompute.VirtualMachine{}, fmt.Errorf("failed to generate cloud-init: %w", err)
}
userDataBase64 := base64.StdEncoding.EncodeToString([]byte(userData))

Expand Down
12 changes: 6 additions & 6 deletions pkg/orchestrator/provider/external/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ func New(_ context.Context) (*Client, error) {

conn, err := grpc.Dial(config.ProviderPluginAddress, opts...)
if err != nil {
return nil, fmt.Errorf("failed to dial grpc. address=%v: %v", config.ProviderPluginAddress, err)
return nil, fmt.Errorf("failed to dial grpc. address=%v: %w", config.ProviderPluginAddress, err)
}
client.conn = conn
client.providerClient = provider_service.NewProviderClient(conn)
Expand All @@ -79,15 +79,15 @@ func (c *Client) DiscoverAssets(ctx context.Context) provider.AssetDiscoverer {

res, err := c.providerClient.DiscoverAssets(ctx, &provider_service.DiscoverAssetsParams{})
if err != nil {
assetDiscoverer.Error = fmt.Errorf("failed to discover assets: %v", err)
assetDiscoverer.Error = fmt.Errorf("failed to discover assets: %w", err)
return
}

assets := res.GetAssets()
for _, asset := range assets {
modelsAsset, err := convertAssetToModels(asset)
if err != nil {
assetDiscoverer.Error = fmt.Errorf("failed to convert asset to models asset: %v", err)
assetDiscoverer.Error = fmt.Errorf("failed to convert asset to models asset: %w", err)
return
}

Expand All @@ -106,7 +106,7 @@ func (c *Client) DiscoverAssets(ctx context.Context) provider.AssetDiscoverer {
func (c *Client) RunAssetScan(ctx context.Context, config *provider.ScanJobConfig) error {
scanJobConfig, err := convertScanJobConfig(config)
if err != nil {
return fmt.Errorf("failed to convert scan job config: %v", err)
return fmt.Errorf("failed to convert scan job config: %w", err)
}

res, err := c.providerClient.RunAssetScan(ctx, &provider_service.RunAssetScanParams{
Expand Down Expand Up @@ -137,14 +137,14 @@ func (c *Client) RunAssetScan(ctx context.Context, config *provider.ScanJobConfi
func (c *Client) RemoveAssetScan(ctx context.Context, config *provider.ScanJobConfig) error {
scanJobConfig, err := convertScanJobConfig(config)
if err != nil {
return fmt.Errorf("failed to convert scan job config: %v", err)
return fmt.Errorf("failed to convert scan job config: %w", err)
}

_, err = c.providerClient.RemoveAssetScan(ctx, &provider_service.RemoveAssetScanParams{
ScanJobConfig: scanJobConfig,
})
if err != nil {
return fmt.Errorf("failed to remove asset scan: %v", err)
return fmt.Errorf("failed to remove asset scan: %w", err)
}
return nil
}
Loading

0 comments on commit 5d1ede7

Please sign in to comment.