|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "fmt" |
| 6 | + "os" |
| 7 | + "time" |
| 8 | + |
| 9 | + "github.com/microsoft/retina/internal/buildinfo" |
| 10 | + "github.com/microsoft/retina/shell" |
| 11 | + "github.com/spf13/cobra" |
| 12 | + v1 "k8s.io/api/core/v1" |
| 13 | + "k8s.io/cli-runtime/pkg/genericclioptions" |
| 14 | + "k8s.io/cli-runtime/pkg/resource" |
| 15 | + cmdutil "k8s.io/kubectl/pkg/cmd/util" |
| 16 | + "k8s.io/kubectl/pkg/scheme" |
| 17 | + "k8s.io/kubectl/pkg/util/templates" |
| 18 | +) |
| 19 | + |
| 20 | +var ( |
| 21 | + configFlags *genericclioptions.ConfigFlags |
| 22 | + matchVersionFlags *cmdutil.MatchVersionFlags |
| 23 | + retinaShellImageRepo string |
| 24 | + retinaShellImageVersion string |
| 25 | + mountHostFilesystem bool |
| 26 | + allowHostFilesystemWrite bool |
| 27 | + hostPID bool |
| 28 | + capabilities []string |
| 29 | + timeout time.Duration |
| 30 | +) |
| 31 | + |
| 32 | +var ( |
| 33 | + // AKS requires clusters to allow access to MCR, so use this repository by default. |
| 34 | + defaultRetinaShellImageRepo = "mcr.microsoft.com/containernetworking/retina-shell" |
| 35 | + |
| 36 | + // Default version is the same as CLI version, set at link time. |
| 37 | + defaultRetinaShellImageVersion = buildinfo.Version |
| 38 | + |
| 39 | + defaultTimeout = 30 * time.Second |
| 40 | + |
| 41 | + errMissingRequiredRetinaShellImageVersionArg = errors.New("missing required --retina-shell-image-version") |
| 42 | + errUnsupportedResourceType = errors.New("unsupported resource type") |
| 43 | +) |
| 44 | + |
| 45 | +var shellCmd = &cobra.Command{ |
| 46 | + Use: "shell (NODE | TYPE[[.VERSION].GROUP]/NAME)", |
| 47 | + Short: "[EXPERIMENTAL] Interactively debug a node or pod", |
| 48 | + Long: templates.LongDesc(` |
| 49 | + [EXPERIMENTAL] This is an experimental command. The flags and behavior may change in the future. |
| 50 | +
|
| 51 | + Start a shell with networking tools in a node or pod for adhoc debugging. |
| 52 | +
|
| 53 | + * For nodes, this creates a pod on the node in the root network namespace. |
| 54 | + * For pods, this creates an ephemeral container inside the pod's network namespace. |
| 55 | +
|
| 56 | + You can override the default image used for the shell container with either |
| 57 | + CLI flags (--retina-shell-image-repo and --retina-shell-image-version) or |
| 58 | + environment variables (RETINA_SHELL_IMAGE_REPO and RETINA_SHELL_IMAGE_VERSION). |
| 59 | + CLI flags take precedence over env vars. |
| 60 | +`), |
| 61 | + |
| 62 | + Example: templates.Examples(` |
| 63 | + # start a shell in a node |
| 64 | + kubectl retina shell node0001 |
| 65 | +
|
| 66 | + # start a shell in a node, with debug pod in kube-system namespace |
| 67 | + kubectl retina shell -n kube-system node0001 |
| 68 | +
|
| 69 | + # start a shell as an ephemeral container inside an existing pod |
| 70 | + kubectl retina shell -n kube-system pod/coredns-d459997b4-7cpzx |
| 71 | +
|
| 72 | + # start a shell in a node, mounting the host filesystem to /host with ability to chroot |
| 73 | + kubectl retina shell node001 --mount-host-filesystem --capabilities SYS_CHROOT |
| 74 | +
|
| 75 | + # start a shell in a node, with NET_RAW and NET_ADMIN capabilities |
| 76 | + # (required for iptables and tcpdump) |
| 77 | + kubectl retina shell node001 --capabilities NET_RAW,NET_ADMIN |
| 78 | +`), |
| 79 | + Args: cobra.ExactArgs(1), |
| 80 | + RunE: func(_ *cobra.Command, args []string) error { |
| 81 | + // retinaShellImageVersion defaults to the CLI version, but that might not be set if the CLI is built without -ldflags. |
| 82 | + if retinaShellImageVersion == "" { |
| 83 | + return errMissingRequiredRetinaShellImageVersionArg |
| 84 | + } |
| 85 | + |
| 86 | + namespace, explicitNamespace, err := matchVersionFlags.ToRawKubeConfigLoader().Namespace() |
| 87 | + if err != nil { |
| 88 | + return fmt.Errorf("error retrieving namespace arg: %w", err) |
| 89 | + } |
| 90 | + |
| 91 | + // This interprets the first arg as either a node or pod (same as kubectl): |
| 92 | + // "node001" -> node |
| 93 | + // "node/node001" -> node |
| 94 | + // "pod/example-7cpzx" -> pod |
| 95 | + r := resource.NewBuilder(configFlags). |
| 96 | + WithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...). |
| 97 | + FilenameParam(explicitNamespace, &resource.FilenameOptions{}). |
| 98 | + NamespaceParam(namespace).DefaultNamespace().ResourceNames("nodes", args[0]). |
| 99 | + Do() |
| 100 | + if rerr := r.Err(); rerr != nil { |
| 101 | + return fmt.Errorf("error constructing resource builder: %w", rerr) |
| 102 | + } |
| 103 | + |
| 104 | + restConfig, err := matchVersionFlags.ToRESTConfig() |
| 105 | + if err != nil { |
| 106 | + return fmt.Errorf("error constructing REST config: %w", err) |
| 107 | + } |
| 108 | + |
| 109 | + config := shell.Config{ |
| 110 | + RestConfig: restConfig, |
| 111 | + RetinaShellImage: fmt.Sprintf("%s:%s", retinaShellImageRepo, retinaShellImageVersion), |
| 112 | + MountHostFilesystem: mountHostFilesystem, |
| 113 | + AllowHostFilesystemWrite: allowHostFilesystemWrite, |
| 114 | + HostPID: hostPID, |
| 115 | + Capabilities: capabilities, |
| 116 | + Timeout: timeout, |
| 117 | + } |
| 118 | + |
| 119 | + return r.Visit(func(info *resource.Info, err error) error { |
| 120 | + if err != nil { |
| 121 | + return err |
| 122 | + } |
| 123 | + |
| 124 | + switch obj := info.Object.(type) { |
| 125 | + case *v1.Node: |
| 126 | + podDebugNamespace := namespace |
| 127 | + nodeName := obj.Name |
| 128 | + return shell.RunInNode(config, nodeName, podDebugNamespace) |
| 129 | + case *v1.Pod: |
| 130 | + return shell.RunInPod(config, obj.Namespace, obj.Name) |
| 131 | + default: |
| 132 | + gvk := obj.GetObjectKind().GroupVersionKind() |
| 133 | + return fmt.Errorf("unsupported resource %s/%s: %w", gvk.GroupVersion(), gvk.Kind, errUnsupportedResourceType) |
| 134 | + } |
| 135 | + }) |
| 136 | + }, |
| 137 | +} |
| 138 | + |
| 139 | +func init() { |
| 140 | + Retina.AddCommand(shellCmd) |
| 141 | + shellCmd.PersistentPreRun = func(cmd *cobra.Command, _ []string) { |
| 142 | + // Avoid printing full usage message if the command exits with an error. |
| 143 | + cmd.SilenceUsage = true |
| 144 | + cmd.SilenceErrors = true |
| 145 | + |
| 146 | + // Allow setting image repo and version via environment variables (CLI flags still take precedence). |
| 147 | + if !cmd.Flags().Changed("retina-shell-image-repo") { |
| 148 | + if envRepo := os.Getenv("RETINA_SHELL_IMAGE_REPO"); envRepo != "" { |
| 149 | + retinaShellImageRepo = envRepo |
| 150 | + } |
| 151 | + } |
| 152 | + if !cmd.Flags().Changed("retina-shell-image-version") { |
| 153 | + if envVersion := os.Getenv("RETINA_SHELL_IMAGE_VERSION"); envVersion != "" { |
| 154 | + retinaShellImageVersion = envVersion |
| 155 | + } |
| 156 | + } |
| 157 | + } |
| 158 | + shellCmd.Flags().StringVar(&retinaShellImageRepo, "retina-shell-image-repo", defaultRetinaShellImageRepo, "The container registry repository for the image to use for the shell container") |
| 159 | + shellCmd.Flags().StringVar(&retinaShellImageVersion, "retina-shell-image-version", defaultRetinaShellImageVersion, "The version (tag) of the image to use for the shell container") |
| 160 | + shellCmd.Flags().BoolVarP(&mountHostFilesystem, "mount-host-filesystem", "m", false, "Mount the host filesystem to /host. Applies only to nodes, not pods.") |
| 161 | + shellCmd.Flags().BoolVarP(&allowHostFilesystemWrite, "allow-host-filesystem-write", "w", false, |
| 162 | + "Allow write access to the host filesystem. Implies --mount-host-filesystem. Applies only to nodes, not pods.") |
| 163 | + shellCmd.Flags().BoolVar(&hostPID, "host-pid", false, "Set HostPID on the shell container. Applies only to nodes, not pods.") |
| 164 | + shellCmd.Flags().StringSliceVarP(&capabilities, "capabilities", "c", []string{}, "Add capabilities to the shell container") |
| 165 | + shellCmd.Flags().DurationVar(&timeout, "timeout", defaultTimeout, "The maximum time to wait for the shell container to start") |
| 166 | + |
| 167 | + // configFlags and matchVersion flags are used to load kubeconfig. |
| 168 | + // This uses the same mechanism as `kubectl debug` to connect to apiserver and attach to containers. |
| 169 | + configFlags = genericclioptions.NewConfigFlags(true) |
| 170 | + configFlags.AddFlags(shellCmd.PersistentFlags()) |
| 171 | + matchVersionFlags = cmdutil.NewMatchVersionFlags(configFlags) |
| 172 | + matchVersionFlags.AddFlags(shellCmd.PersistentFlags()) |
| 173 | +} |
0 commit comments