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

[UDT] add create resource type command #8104

Merged
merged 10 commits into from
Jan 8, 2025
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
4 changes: 4 additions & 0 deletions cmd/rad/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ import (
resourceprovider_delete "github.com/radius-project/radius/pkg/cli/cmd/resourceprovider/delete"
resourceprovider_list "github.com/radius-project/radius/pkg/cli/cmd/resourceprovider/list"
resourceprovider_show "github.com/radius-project/radius/pkg/cli/cmd/resourceprovider/show"
resourcetype_create "github.com/radius-project/radius/pkg/cli/cmd/resourcetype/create"
resourcetype_delete "github.com/radius-project/radius/pkg/cli/cmd/resourcetype/delete"
resourcetype_list "github.com/radius-project/radius/pkg/cli/cmd/resourcetype/list"
resourcetype_show "github.com/radius-project/radius/pkg/cli/cmd/resourcetype/show"
Expand Down Expand Up @@ -273,6 +274,9 @@ func initSubCommands() {
resourceTypeDeleteCmd, _ := resourcetype_delete.NewCommand(framework)
resourceTypeCmd.AddCommand(resourceTypeDeleteCmd)

resourceTypeCreateCmd, _ := resourcetype_create.NewCommand(framework)
resourceTypeCmd.AddCommand(resourceTypeCreateCmd)

listRecipeCmd, _ := recipe_list.NewCommand(framework)
recipeCmd.AddCommand(listRecipeCmd)

Expand Down
25 changes: 25 additions & 0 deletions pkg/cli/clivalidation.go
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,31 @@ func ReadResourceGroupNameArgs(cmd *cobra.Command, args []string) (string, error
return name, err
}

// RequireResourceTypeNameArgs is used by commands that require specifying a type name using positional args.
//

// RequireResourceTypeNameArgs reads the resource type name from the command line arguments and returns an error if the name
// is not provided or is empty. It also handles any errors that may occur while reading the resource type name.
func RequireResourceTypeNameArgs(cmd *cobra.Command, args []string) (string, error) {
resourceType, err := ReadResourceTypeNameArgs(cmd, args)
if err != nil {
return "", err
}
if resourceType == "" {
return "", fmt.Errorf("resource type name is not provided or is empty")
}

return resourceType, nil
}

// ReadResourceTypeNameArgs is used to get the resource type name that is supplied as the first argument
func ReadResourceTypeNameArgs(cmd *cobra.Command, args []string) (string, error) {
if len(args) < 1 {
return "", errors.New("resource type name is not provided")
}
return args[0], nil
}

// RequireWorkspaceArgs is used by commands that require an existing workspace either set as the default,
// or specified as a positional arg, or specified using the 'workspace' flag.
//
Expand Down
1 change: 0 additions & 1 deletion pkg/cli/cmd/resourceprovider/create/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,6 @@ func (r *Runner) Run(ctx context.Context) error {
return err
}

// Add a blank line before printing the result.
r.Output.LogInfo("")

err = r.Output.WriteFormatted(r.Format, response, common.GetResourceProviderTableFormat())
Expand Down
2 changes: 1 addition & 1 deletion pkg/cli/cmd/resourceprovider/create/create_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ func Test_Run(t *testing.T) {
expectedResourceType := "testResources"
expectedAPIVersion := "2025-01-01-preview"

clientFactory, err := manifest.NewTestClientFactory()
clientFactory, err := manifest.NewTestClientFactory(manifest.WithResourceProviderServerNoError)
require.NoError(t, err)

var logBuffer bytes.Buffer
Expand Down
188 changes: 188 additions & 0 deletions pkg/cli/cmd/resourcetype/create/create.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
/*
Copyright 2023 The Radius Authors.

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 create

import (
"context"
"strings"

"github.com/radius-project/radius/pkg/cli"
"github.com/radius-project/radius/pkg/cli/clients"
"github.com/radius-project/radius/pkg/cli/clierrors"
"github.com/radius-project/radius/pkg/cli/cmd/commonflags"
"github.com/radius-project/radius/pkg/cli/cmd/resourcetype/common"
"github.com/radius-project/radius/pkg/cli/framework"
"github.com/radius-project/radius/pkg/cli/manifest"
"github.com/radius-project/radius/pkg/cli/output"
"github.com/radius-project/radius/pkg/cli/workspaces"
"github.com/radius-project/radius/pkg/sdk"
"github.com/radius-project/radius/pkg/ucp/api/v20231001preview"
"github.com/spf13/cobra"

aztoken "github.com/radius-project/radius/pkg/azure/tokencredentials"
)

const (
fakeServerResourceProviderNotFoundResponse = "unexpected status code 404. acceptable values are http.StatusOK"
)

// NewCommand creates an instance of the `rad resource-type create` command and runner.
func NewCommand(factory framework.Factory) (*cobra.Command, framework.Runner) {
runner := NewRunner(factory)

cmd := &cobra.Command{
Use: "create [input]",
Short: "Create or update a resource type",
Long: `Create or update a resource type from a resource provider manifest.

Resource types are user defined types such as 'Mycompany.Messaging/plaid'.

Creating a resource type defines a new type that can be used in applications.

Input can be passed in using a JSON or YAML file using the --from-file option.
`,
Example: `
# Create a resource type from YAML file
rad resource-type create myType --from-file /path/to/input.yaml

# Create a resource type from JSON file
rad resource-type create myType --from-file /path/to/input.json
`,
Args: cobra.ExactArgs(1),
RunE: framework.RunCommand(runner),
}

commonflags.AddOutputFlag(cmd)
commonflags.AddWorkspaceFlag(cmd)
commonflags.AddFromFileFlagVar(cmd, &runner.ResourceProviderManifestFilePath)

return cmd, runner
}

// Runner is the Runner implementation for the `rad resource-type create` command.
type Runner struct {
UCPClientFactory *v20231001preview.ClientFactory
ConfigHolder *framework.ConfigHolder
Output output.Interface
Format string
Workspace *workspaces.Workspace

ResourceProviderManifestFilePath string
ResourceProvider *manifest.ResourceProvider
ResourceTypeName string
Logger func(format string, args ...any)
}

// NewRunner creates an instance of the runner for the `rad resource-type create` command.
func NewRunner(factory framework.Factory) *Runner {
return &Runner{
ConfigHolder: factory.GetConfigHolder(),
Output: factory.GetOutput(),
Logger: func(format string, args ...any) {
output.LogInfo(format, args...)
},
}
}

// Validate runs validation for the `rad resource-type create` command.
func (r *Runner) Validate(cmd *cobra.Command, args []string) error {
resourceTypeName, err := cli.RequireResourceTypeNameArgs(cmd, args)
if err != nil {
return err
}
r.ResourceTypeName = resourceTypeName

workspace, err := cli.RequireWorkspace(cmd, r.ConfigHolder.Config, r.ConfigHolder.DirectoryConfig)
if err != nil {
return err
}
r.Workspace = workspace

format, err := cli.RequireOutput(cmd)
if err != nil {
return err
}
r.Format = format

r.ResourceProvider, err = manifest.ReadFile(r.ResourceProviderManifestFilePath)
if err != nil {
return err
}

resourcesTypes := r.ResourceProvider.Types
if _, ok := resourcesTypes[r.ResourceTypeName]; !ok {
return clierrors.Message("Resource type %q not found in the manifest", r.ResourceTypeName)
}

return nil
}

// Run runs the `rad resource-type create` command.
func (r *Runner) Run(ctx context.Context) error {
// Initialize the client factory if it hasn't been set externally.
// This allows for flexibility where a test UCPClientFactory can be set externally during testing.
if r.UCPClientFactory == nil {
err := r.initializeClientFactory(ctx, r.Workspace)
if err != nil {
return err
}
}

response, err := r.UCPClientFactory.NewResourceProvidersClient().Get(ctx, "local", r.ResourceProvider.Name, nil)
if err != nil {
Copy link
Contributor

Choose a reason for hiding this comment

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

The error can also be something other than Resource Provider not Found, right?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

yes. Currently, if there are errors, approach is to recreate. @rynowak do you see any problems with this approach?

Copy link
Contributor

Choose a reason for hiding this comment

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

I think we should only create if the error is 404 and fail if it is something else.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Added changes to return error if it is not 404.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I think we should only create if the error is 404 and fail if it is something else.

Added changes to return error if it is not 404.

// The second clause is required for testing purpose since fake server returns a different type of error.
if clients.Is404Error(err) || strings.Contains(err.Error(), fakeServerResourceProviderNotFoundResponse) {
r.Output.LogInfo("Resource provider %q not found.", r.ResourceProvider.Name)
if registerErr := manifest.RegisterFile(ctx, r.UCPClientFactory, "local", r.ResourceProviderManifestFilePath, r.Logger); err != nil {
return registerErr
}
} else {
return err
}
} else {
r.Output.LogInfo("Resource provider %q found. Registering resource type %q.", r.ResourceProvider.Name, r.ResourceTypeName)
if registerErr := manifest.RegisterType(ctx, r.UCPClientFactory, "local", r.ResourceProviderManifestFilePath, r.ResourceTypeName, r.Logger); err != nil {
return registerErr
}
}

r.Output.LogInfo("")

err = r.Output.WriteFormatted(r.Format, response, common.GetResourceTypeTableFormat())
if err != nil {
return err
}

return nil
}

func (r *Runner) initializeClientFactory(ctx context.Context, workspace *workspaces.Workspace) error {
connection, err := workspace.Connect(ctx)
if err != nil {
return err
}

clientOptions := sdk.NewClientOptions(connection)

clientFactory, err := v20231001preview.NewClientFactory(&aztoken.AnonymousCredential{}, clientOptions)
if err != nil {
return err
}

r.UCPClientFactory = clientFactory
return nil
}
Loading
Loading