Files
kubevela/references/cli/exec.go
Somefive 7103f8ff52 Feat: merge master into apiserver (#2660)
* Feat(rollout): fill rolloutBatches if empty when scale up/down (#2569)

* Feat: fill rolloutBatches if empty

* Fix: fix unit-test

* Test: add more test

Fix: lint

Fix: fix lint

* Update release.yml (#2537)

* Feat: add registry, merge registry and cap center (#2528)

* Feat: add registry command

* Refactor: comp/trait command combine with registry

* Feat: refactor `vela comp/trait`

* Fix: import

* Fix: fix if type is autodetects.core.oam.dev

* Fix: fix list from url

* Fix: test

* Feat: add test

* Fix: remove dup test

* Fix: test

* Fix: test

* Fix: fix label filter

* Fix: reviewable

* Fix test

* fix personal repo in test

* Fix test

* Fix test

* add some boundary check

* reviewable

* Fix: fix nocalhost trait (#2577)

* fix incorrect addon status (#2576)

* Fix(cli): client-side throttling in vela CLI (#2581)

* fix cli throttling

* fix import

* set to a lower value

* remove addon with no defs (#2574)

* Feat: vela logs support multicluster (#2593)

* Feat: add basic multiple cluster logs

* fix context

* Fix select style

* Fix select style

* remove useless env

* fix naming

* Feat: vela cluster support use ocm to join/list/detach cluster (#2599)

* Feat: add render component and apply component remaining (#2587)

* Feat: add render component and apply component remaining

* fix ut

* fix e2e

* allow import package in custom status cue template (#2585)

Co-authored-by: chwetion <chwetion@foxmail.com>

* Fix: abnormal aux name (#2612)

* Feat: store workflow step def properties in cm (#2592)

* Fix: fix notification def

* Feat: store workflow step def properties in cm

* fix ci

* fix data race

* Fix: change Initializer to Application for addon Observability (#2615)

In this doc, updated the Observability implementation from initializer
to Application. I also store definitions as it's not well stored in
vela-templates/addons/observability

* Fix: fix backport param (#2611)

* Fix: add owner reference in workflow context cm (#2573)

* Fix: add owner reference in workflow context cm

* fix ci

* delete useless test case

* Fix: op.delete bugs (#2622)

* Fix: op.delete some bugs

* Fix: app status update error

Fix: make reviewable

* Fix: show reconcile error log (#2626)

* Feat: add reconcile timeout configuration for vela-core (#2630)

* Fix: patch status retry while conflict happens (#2629)

* Fix: allow definition schema cm can be same name in different definition type (#2618)

* Fix: fix definition schema cm name

* fix ut

* fix ut

* fix show

* add switch default case

* Feat: remove envbinding policy into workflow (#2556)

Fix: add more test

* Feat: add vela prob to test cluster (#2635)

* Fix: upgrade stern lib to avoid panic for vela logs (#2650)

* Fix: filter loggable workload in vela logs (#2651)

* Fix: filter loggable workload in vela logs

* reviewable

* Feat: add vela exec for multi cluster (#2299)

fix

support vela exec

* Fix: health check will check for multiclusters (#2645)

* Fix: minor fix for vela cli printing (#2655)

* Fix: minor fix for vela cli printing

* add dockerfile go mod cache

* Feat: support apiserver-related multicluster features (#2625)

* Feat: remove envbinding policy into workflow

Feat: add support for env change (env gc)

Fix: fix rollout timeout setting bug

* Feat: support disable trait and env without workflow

* Fix: add hint for replaced value

Co-authored-by: wyike <wangyike_wyk@163.com>
Co-authored-by: basefas <basefas@hotmail.com>
Co-authored-by: qiaozp <47812250+chivalryq@users.noreply.github.com>
Co-authored-by: Tianxin Dong <dongtianxin.tx@alibaba-inc.com>
Co-authored-by: yangsoon <yangsoonlx@gmail.com>
Co-authored-by: Chwetion <137953601@qq.com>
Co-authored-by: chwetion <chwetion@foxmail.com>
Co-authored-by: Jian.Li <74582607+leejanee@users.noreply.github.com>
Co-authored-by: Zheng Xi Zhou <zzxwill@gmail.com>
Co-authored-by: Jianbo Sun <jianbo.sjb@alibaba-inc.com>
2021-11-09 13:06:55 +08:00

214 lines
5.9 KiB
Go

/*
Copyright 2021 The KubeVela 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 cli
import (
"context"
"fmt"
"strings"
"time"
"github.com/pkg/errors"
"github.com/spf13/cobra"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/client-go/kubernetes"
cmdexec "k8s.io/kubectl/pkg/cmd/exec"
k8scmdutil "k8s.io/kubectl/pkg/cmd/util"
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/multicluster"
"github.com/oam-dev/kubevela/pkg/utils/common"
"github.com/oam-dev/kubevela/pkg/utils/util"
"github.com/oam-dev/kubevela/references/appfile"
)
const (
podRunningTimeoutFlag = "pod-running-timeout"
defaultPodExecTimeout = 60 * time.Second
defaultStdin = true
defaultTTY = true
)
// VelaExecOptions creates options for `exec` command
type VelaExecOptions struct {
Cmd *cobra.Command
Args []string
Stdin bool
TTY bool
Ctx context.Context
VelaC common.Args
Env *types.EnvMeta
App *v1beta1.Application
resourceName string
resourceNamespace string
f k8scmdutil.Factory
kcExecOptions *cmdexec.ExecOptions
ClientSet kubernetes.Interface
}
// NewExecCommand creates `exec` command
func NewExecCommand(c common.Args, ioStreams util.IOStreams) *cobra.Command {
o := &VelaExecOptions{
kcExecOptions: &cmdexec.ExecOptions{
StreamOptions: cmdexec.StreamOptions{
IOStreams: genericclioptions.IOStreams{
In: ioStreams.In,
Out: ioStreams.Out,
ErrOut: ioStreams.ErrOut,
},
},
Executor: &cmdexec.DefaultRemoteExecutor{},
},
}
cmd := &cobra.Command{
Use: "exec [flags] APP_NAME -- COMMAND [args...]",
Short: "Execute command in a container",
Long: "Execute command in a container",
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
if c.Config == nil {
if err := c.SetConfig(); err != nil {
return errors.Wrapf(err, "failed to set config for k8s client")
}
}
o.VelaC = c
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) < 1 {
ioStreams.Error("Please specify an application name.")
return nil
}
if len(args) == 1 {
ioStreams.Error("Please specify at least one command for the container.")
return nil
}
argsLenAtDash := cmd.ArgsLenAtDash()
if argsLenAtDash != 1 {
ioStreams.Error("vela exec APP_NAME COMMAND is not supported. Use vela exec APP_NAME -- COMMAND instead.")
return nil
}
if err := o.Init(context.Background(), cmd, args); err != nil {
return err
}
if err := o.Complete(); err != nil {
return err
}
if err := o.Run(); err != nil {
return err
}
return nil
},
Annotations: map[string]string{
types.TagCommandType: types.TypeApp,
},
Example: `
# Get output from running 'date' command from app pod, using the first container by default
vela exec my-app -- date
# Switch to raw terminal mode, sends stdin to 'bash' in containers of application my-app
# and sends stdout/stderr from 'bash' back to the client
kubectl exec my-app -i -t -- bash -il
`,
}
cmd.Flags().BoolVarP(&o.Stdin, "stdin", "i", defaultStdin, "Pass stdin to the container")
cmd.Flags().BoolVarP(&o.TTY, "tty", "t", defaultTTY, "Stdin is a TTY")
cmd.Flags().Duration(podRunningTimeoutFlag, defaultPodExecTimeout,
"The length of time (like 5s, 2m, or 3h, higher than zero) to wait until at least one pod is running",
)
return cmd
}
// Init prepares the arguments accepted by the Exec command
func (o *VelaExecOptions) Init(ctx context.Context, c *cobra.Command, argsIn []string) error {
o.Cmd = c
o.Args = argsIn
env, err := GetFlagEnvOrCurrent(o.Cmd, o.VelaC)
if err != nil {
return err
}
o.Env = env
app, err := appfile.LoadApplication(env.Namespace, o.Args[0], o.VelaC)
if err != nil {
return err
}
o.App = app
targetResource, err := common.AskToChooseOneEnvResource(o.App)
if err != nil {
return err
}
cf := genericclioptions.NewConfigFlags(true)
cf.Namespace = &targetResource.Namespace
o.f = k8scmdutil.NewFactory(k8scmdutil.NewMatchVersionFlags(cf))
o.resourceName = targetResource.Name
o.Ctx = multicluster.ContextWithClusterName(ctx, targetResource.Cluster)
o.resourceNamespace = targetResource.Namespace
k8sClient, err := kubernetes.NewForConfig(o.VelaC.Config)
if err != nil {
return err
}
o.ClientSet = k8sClient
return nil
}
// Complete loads data from the command environment
func (o *VelaExecOptions) Complete() error {
podName, err := o.getPodName(o.resourceName)
if err != nil {
return err
}
o.kcExecOptions.StreamOptions.Stdin = o.Stdin
o.kcExecOptions.StreamOptions.TTY = o.TTY
args := make([]string, len(o.Args))
copy(args, o.Args)
// args for kcExecOptions MUST be in such format:
// [podName, COMMAND...]
args[0] = podName
return o.kcExecOptions.Complete(o.f, o.Cmd, args, 1)
}
func (o *VelaExecOptions) getPodName(resourceName string) (string, error) {
podList, err := o.ClientSet.CoreV1().Pods(o.resourceNamespace).List(o.Ctx, v1.ListOptions{})
if err != nil {
return "", err
}
var pods []string
for _, p := range podList.Items {
if strings.HasPrefix(p.Name, resourceName) {
pods = append(pods, p.Name)
}
}
if len(pods) < 1 {
return "", fmt.Errorf("no pods found created by resource %s", resourceName)
}
return common.AskToChooseOnePods(pods)
}
// Run executes a validated remote execution against a pod
func (o *VelaExecOptions) Run() error {
return o.kcExecOptions.Run()
}