-
Notifications
You must be signed in to change notification settings - Fork 821
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: carlory <baofa.fan@daocloud.io>
- Loading branch information
Showing
30 changed files
with
5,716 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Oops, something went wrong.