Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(cli): commands for creating asset and asset scan #500

Merged
10 commits merged into from
Jul 31, 2023
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
151 changes: 151 additions & 0 deletions cmd/vmclarity-cli/asset/asset_create.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
// Copyright © 2023 Cisco Systems, Inc. and its affiliates.
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package asset

import (
"context"
"errors"
"fmt"
"os"
"time"

"github.com/spf13/cobra"

"github.com/openclarity/vmclarity/cmd/vmclarity-cli/root"
cliutils "github.com/openclarity/vmclarity/pkg/cli/utils"

"github.com/openclarity/vmclarity/api/models"
"github.com/openclarity/vmclarity/pkg/shared/backendclient"
)

// assetCreateCmd represents the standalone command.
var assetCreateCmd = &cobra.Command{
Use: "asset-create",
Short: "Create asset",
Long: `It creates asset. It's useful in the CI/CD mode without VMClarity orchestration`,
Run: func(cmd *cobra.Command, args []string) {
root.Logger.Infof("Creating asset...")
filename, err := cmd.Flags().GetString("file")
if err != nil {
root.Logger.Fatalf("Unable to get asset json file name: %v", err)
}
server, err := cmd.Flags().GetString("server")
if err != nil {
root.Logger.Fatalf("Unable to get VMClarity server address: %v", err)
}
assetType, err := getAssetFromJSONFile(filename)
if err != nil {
root.Logger.Fatalf("Failed to get asset from json file: %v", err)
}
updateIfExists, err := cmd.Flags().GetBool("update-if-exists")
if err != nil {
root.Logger.Fatalf("Unable to get update-if-exists flag vaule: %v", err)
}
jsonPath, err := cmd.Flags().GetString("jsonpath")
if err != nil {
root.Logger.Fatalf("Unable to get jsonpath: %v", err)
}

_, err = assetType.ValueByDiscriminator()
if err != nil {
root.Logger.Fatalf("Failed to determine asset type: %v", err)
}

asset, err := createAsset(context.TODO(), assetType, server, updateIfExists)
if err != nil {
root.Logger.Fatalf("Failed to create asset: %v", err)
}

if err := cliutils.PrintJSONData(asset, jsonPath); err != nil {
root.Logger.Fatalf("Failed to print jsonpath: %v", err)
}
},
}

func init() {
root.RootCmd.AddCommand(assetCreateCmd)

assetCreateCmd.Flags().String("file", "", "asset json filename")
assetCreateCmd.Flags().String("server", "", "VMClarity server to create asset to, for example: http://localhost:9999/api")
assetCreateCmd.Flags().Bool("update-if-exists", false, "the asset will be updated the asset if it exists")
assetCreateCmd.Flags().String("jsonpath", "", "print selected value of asset")
if err := assetCreateCmd.MarkFlagRequired("file"); err != nil {
root.Logger.Fatalf("Failed to mark file flag as required: %v", err)
}
if err := assetCreateCmd.MarkFlagRequired("server"); err != nil {
root.Logger.Fatalf("Failed to mark server flag as required: %v", err)
}
}

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)
}
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)
}

// 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)
}

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

return assetType, nil
}

func createAsset(ctx context.Context, assetType *models.AssetType, server string, updateIfExists bool) (*models.Asset, error) {
client, err := backendclient.Create(server)
if err != nil {
return nil, fmt.Errorf("failed to create VMClarity API client: %w", err)
}

creationTime := time.Now()
assetData := models.Asset{
AssetInfo: assetType,
LastSeen: &creationTime,
FirstSeen: &creationTime,
}
asset, err := client.PostAsset(ctx, assetData)
if err == nil {
return asset, nil
}
var conflictError backendclient.AssetConflictError
// As we got a conflict it means there is an existing asset
// 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)
}
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 conflictError.ConflictingAsset, nil
}
114 changes: 114 additions & 0 deletions cmd/vmclarity-cli/asset/asset_scan_create.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
// Copyright © 2023 Cisco Systems, Inc. and its affiliates.
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package asset

import (
"context"
"errors"
"fmt"

"github.com/spf13/cobra"

"github.com/openclarity/vmclarity/cmd/vmclarity-cli/root"
cliutils "github.com/openclarity/vmclarity/pkg/cli/utils"

"github.com/openclarity/vmclarity/api/models"
"github.com/openclarity/vmclarity/pkg/shared/backendclient"
"github.com/openclarity/vmclarity/pkg/shared/utils"
)

// assetScanCreateCmd represents the standalone command.
var assetScanCreateCmd = &cobra.Command{
Use: "asset-scan-create",
Short: "Create asset scan",
Long: `It creates asset scan. It's useful in the CI/CD mode without VMClarity orchestration`,
Run: func(cmd *cobra.Command, args []string) {
root.Logger.Infof("asset-scan-create called")
assetID, err := cmd.Flags().GetString("asset-id")
if err != nil {
root.Logger.Fatalf("Unable to get asset id: %v", err)
}
server, err := cmd.Flags().GetString("server")
if err != nil {
root.Logger.Fatalf("Unable to get VMClarity server address: %v", err)
}
jsonPath, err := cmd.Flags().GetString("jsonpath")
if err != nil {
root.Logger.Fatalf("Unable to get jsonpath: %v", err)
}

assetScan, err := createAssetScan(context.TODO(), server, assetID)
if err != nil {
root.Logger.Fatalf("Failed to create asset scan: %v", err)
}

if err := cliutils.PrintJSONData(assetScan, jsonPath); err != nil {
root.Logger.Fatalf("Failed to print jsonpath: %v", err)
}
},
}

func init() {
root.RootCmd.AddCommand(assetScanCreateCmd)
assetScanCreateCmd.Flags().String("server", "", "VMClarity server to create asset to, for example: http://localhost:9999/api")
assetScanCreateCmd.Flags().String("asset-id", "", "Asset ID for asset scan")
assetScanCreateCmd.Flags().String("jsonpath", "", "print selected value of asset scan")
if err := assetScanCreateCmd.MarkFlagRequired("server"); err != nil {
root.Logger.Fatalf("Failed to mark server flag as required: %v", err)
}
if err := assetScanCreateCmd.MarkFlagRequired("asset-id"); err != nil {
root.Logger.Fatalf("Failed to mark asset-id flag as required: %v", err)
}
}

func createAssetScan(ctx context.Context, server, assetID string) (*models.AssetScan, error) {
client, err := backendclient.Create(server)
if err != nil {
return nil, fmt.Errorf("failed to create VMClarity API client: %w", err)
}

asset, err := client.GetAsset(ctx, assetID, models.GetAssetsAssetIDParams{})
if err != nil {
return nil, fmt.Errorf("failed to get asset %s: %w", assetID, err)
}
assetScanData := createEmptyAssetScanForAsset(asset)

assetScan, err := client.PostAssetScan(ctx, assetScanData)
if err != nil {
var conErr backendclient.AssetScanConflictError
if errors.As(err, &conErr) {
assetScanID := *conErr.ConflictingAssetScan.Id
root.Logger.WithField("AssetScanID", assetScanID).Debug("AssetScan already exist.")
return conErr.ConflictingAssetScan, nil
}
return nil, fmt.Errorf("failed to post AssetScan to backend API: %w", err)
}

return assetScan, nil
}

func createEmptyAssetScanForAsset(asset models.Asset) models.AssetScan {
return models.AssetScan{
Asset: &models.AssetRelationship{
Id: *asset.Id,
},
Status: &models.AssetScanStatus{
General: &models.AssetScanState{
State: utils.PointerTo(models.AssetScanStateStateReadyToScan),
},
},
}
}
Loading
Loading