Skip to content

Commit

Permalink
[UDT] add create resource type command (#8104)
Browse files Browse the repository at this point in the history
# Description

add rad resource-type create 

## Type of change

- This pull request adds or changes features of Radius and has an
approved issue (issue link required).

Partially Fixes: #issue_number

## Contributor checklist
Please verify that the PR meets the following requirements, where
applicable:

- [ NA] An overview of proposed schema changes is included in a linked
GitHub issue.
- [ NA] A design document PR is created in the [design-notes
repository](https://github.com/radius-project/design-notes/), if new
APIs are being introduced.
- [NA ] If applicable, design document has been reviewed and approved by
Radius maintainers/approvers.
- [NA ] A PR for the [samples
repository](https://github.com/radius-project/samples) is created, if
existing samples are affected by the changes in this PR.
- [ NA] A PR for the [documentation
repository](https://github.com/radius-project/docs) is created, if the
changes in this PR affect the documentation or any user facing updates
are made.
- [ NA] A PR for the [recipes
repository](https://github.com/radius-project/recipes) is created, if
existing recipes are affected by the changes in this PR.
  • Loading branch information
nithyatsu authored Jan 8, 2025
1 parent 3c28b26 commit 73ed52d
Show file tree
Hide file tree
Showing 10 changed files with 574 additions and 28 deletions.
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 {
// 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

0 comments on commit 73ed52d

Please sign in to comment.