Skip to content

Commit

Permalink
karmadactl support apply command
Browse files Browse the repository at this point in the history
Signed-off-by: carlory <baofa.fan@daocloud.io>
  • Loading branch information
carlory committed Jun 17, 2022
1 parent 5c3336e commit aec6042
Show file tree
Hide file tree
Showing 30 changed files with 5,716 additions and 0 deletions.
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ require (
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/imdario/mergo v0.3.12 // indirect
github.com/inconshreveable/mousetrap v1.0.0 // indirect
github.com/jonboulle/clockwork v0.2.2 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/kr/text v0.2.0 // indirect
Expand Down
190 changes: 190 additions & 0 deletions pkg/karmadactl/apply.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
package karmadactl

import (
"fmt"

"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/cli-runtime/pkg/resource"
restclient "k8s.io/client-go/rest"
"k8s.io/kubectl/pkg/cmd/apply"
kcmdutil "k8s.io/kubectl/pkg/cmd/util"
"k8s.io/kubectl/pkg/util/i18n"
"k8s.io/kubectl/pkg/util/templates"

policyv1alpha1 "github.com/karmada-io/karmada/pkg/apis/policy/v1alpha1"
"github.com/karmada-io/karmada/pkg/karmadactl/options"
"github.com/karmada-io/karmada/pkg/util/names"
)

var metadataAccessor = meta.NewAccessor()

// CommandApplyOptions contains the input to the apply command.
type CommandApplyOptions struct {
// global flags
options.GlobalCommandOptions
}

var (
applyLong = templates.LongDesc(i18n.T(`
Apply a configuration to a resource by file name or stdin.
The resource name must be specified. This resource will be created if it doesn't exist yet.
To use 'apply', always create the resource initially with either 'apply' or 'create --save-config'.
JSON and YAML formats are accepted.
Alpha Disclaimer: the --prune functionality is not yet complete. Do not use unless you are aware of what the current state is. See https://issues.k8s.io/34274.`))

applyExample = templates.Examples(i18n.T(`
# Apply the configuration in pod.json to a pod
%[1]s apply -f ./pod.json
# Apply resources from a directory containing kustomization.yaml - e.g. dir/kustomization.yaml
%[1]s apply -k dir/
# Apply the JSON passed into stdin to a pod
cat pod.json | %[1]s apply -f -
# Note: --prune is still in Alpha
# Apply the configuration in manifest.yaml that matches label app=nginx and delete all other resources that are not in the file and match label app=nginx
%[1]s apply --prune -f manifest.yaml -l app=nginx
# Apply the configuration in manifest.yaml and delete all the other config maps that are not in the file
%[1]s apply --prune -f manifest.yaml --all --prune-whitelist=core/v1/ConfigMap`))
)

// NewCmdApply creates the `apply` command
// TODO(@carlory): use kcmdutil.factory as an input argument instead of the karmada config,
// in order to make it act like the kubectl apply command.
func NewCmdApply(karmadaConfig KarmadaConfig, parentCommand string) *cobra.Command {
o := &CommandApplyOptions{}
ioStreams := genericclioptions.IOStreams{In: getIn, Out: getOut, ErrOut: getErr}
flags := apply.NewApplyFlags(nil, ioStreams)
kubeConfigFlags := NewConfigFlags(true).WithDeprecatedPasswordFlag()
cmd := &cobra.Command{
Use: "apply (-f FILENAME | -k DIRECTORY)",
DisableFlagsInUseLine: true,
Short: i18n.T("Apply a configuration to a resource by file name or stdin"),
Long: applyLong,
Example: fmt.Sprintf(applyExample, parentCommand),
PreRunE: func(cmd *cobra.Command, args []string) error {
// factory must be initialized before the command runs
restConfig, err := karmadaConfig.GetRestConfig(o.KarmadaContext, o.KubeConfig)
if err != nil {
return err
}
kubeConfigFlags.WrapConfigFn = func(config *restclient.Config) *restclient.Config { return restConfig }
flags.Factory = kcmdutil.NewFactory(kubeConfigFlags)
return nil
},
Run: func(cmd *cobra.Command, args []string) {
// coverts flags to the kubectl apply options
o, err := flags.ToOptions(cmd, parentCommand, args)
kcmdutil.CheckErr(err)
// generate and inject policies
o.PreProcessorFn = func() error {
return generateAndInjectPolices(flags.Factory, o)
}
kcmdutil.CheckErr(o.Validate(cmd, args))
kcmdutil.CheckErr(o.Run())
},
}
flags.AddFlags(cmd)
cmd.Flags().StringVar(&o.KubeConfig, "kubeconfig", "", "Path to the control plane kubeconfig file.")
cmd.Flags().StringVar(&o.KarmadaContext, "karmada-context", "", "Name of the cluster context in control plane kubeconfig file.")
// Fixme(carlory): kubectl uses kubeConfigFlags as global command-line options (applies to all commands).
cmd.Flags().StringVarP(kubeConfigFlags.Namespace, flagNamespace, "n", *kubeConfigFlags.Namespace, "If present, the namespace scope for this CLI request")
return cmd
}

// generateAndInjectPolices generates and injects policies to the given resources.
// It returns an error if any of the policies cannot be generated.
func generateAndInjectPolices(f kcmdutil.Factory, o *apply.ApplyOptions) error {
// load the resources
infos, err := o.GetObjects()
if err != nil {
return err
}

// generate policies and append them to the resources
var results []*resource.Info
for _, info := range infos {
results = append(results, info)
obj := generatePropagationObject(info)
gvk := obj.GetObjectKind().GroupVersionKind()
mapping, err := o.Mapper.RESTMapping(gvk.GroupKind(), gvk.Version)
if err != nil {
return fmt.Errorf("unable to recognize resource: %v", err)
}
client, err := f.ClientForMapping(mapping)
if err != nil {
return fmt.Errorf("unable to connect to a server to handle %q: %v", mapping.Resource, err)
}
policyName, _ := metadataAccessor.Name(obj)
ret := &resource.Info{
Namespace: info.Namespace,
Name: policyName,
Object: obj,
Mapping: mapping,
Client: client,
}
results = append(results, ret)
}

// store the results object to be sequentially applied
o.SetObjects(results)
return nil
}

// generatePropagationObject generates a propagation object for the given resource info.
// It takes the resource namespace, name and GVK as input to generate policy name.
// TODO(carlory): allow users to select clusters to propagate resources. default to all clusters.
func generatePropagationObject(info *resource.Info) runtime.Object {
gvk := info.Mapping.GroupVersionKind
policyName := names.GeneratePolicyName(info.Namespace, info.Name, gvk.String())
spec := policyv1alpha1.PropagationSpec{
ResourceSelectors: []policyv1alpha1.ResourceSelector{
{
APIVersion: gvk.GroupVersion().String(),
Kind: gvk.Kind,
Name: info.Name,
Namespace: info.Namespace,
},
},
Placement: policyv1alpha1.Placement{
ClusterAffinity: &policyv1alpha1.ClusterAffinity{},
},
}

// for a namespaced-scope resource, we need to generate a PropagationPolicy object.
// for a cluster-scope resource, we need to generate a ClusterPropagationPolicy object.
var obj runtime.Object
if info.Namespaced() {
obj = &policyv1alpha1.PropagationPolicy{
TypeMeta: metav1.TypeMeta{
APIVersion: "policy.karmada.io/v1alpha1",
Kind: "PropagationPolicy",
},
ObjectMeta: metav1.ObjectMeta{
Name: policyName,
Namespace: info.Namespace,
},
Spec: spec,
}
} else {
obj = &policyv1alpha1.ClusterPropagationPolicy{
TypeMeta: metav1.TypeMeta{
APIVersion: "policy.karmada.io/v1alpha1",
Kind: "ClusterPropagationPolicy",
},
ObjectMeta: metav1.ObjectMeta{
Name: policyName,
},
Spec: spec,
}
}
return obj
}
1 change: 1 addition & 0 deletions pkg/karmadactl/karmadactl.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ func NewKarmadaCtlCommand(cmdUse, parentCommand string) *cobra.Command {
rootCmd.AddCommand(NewCmdCordon(karmadaConfig, parentCommand))
rootCmd.AddCommand(NewCmdUncordon(karmadaConfig, parentCommand))
rootCmd.AddCommand(NewCmdGet(karmadaConfig, parentCommand))
rootCmd.AddCommand(NewCmdApply(karmadaConfig, parentCommand))
rootCmd.AddCommand(NewCmdTaint(karmadaConfig, parentCommand))
rootCmd.AddCommand(NewCmdPromote(karmadaConfig, parentCommand))
rootCmd.AddCommand(NewCmdLogs(karmadaConfig, parentCommand))
Expand Down
12 changes: 12 additions & 0 deletions vendor/github.com/jonboulle/clockwork/.editorconfig

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

27 changes: 27 additions & 0 deletions vendor/github.com/jonboulle/clockwork/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit aec6042

Please sign in to comment.