2020-01-31 09:29:31 -05:00
/ *
Copyright 2020 The Kubernetes 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 debug
import (
"context"
2021-04-14 12:40:42 -04:00
"encoding/json"
2020-01-31 09:29:31 -05:00
"fmt"
2023-09-01 04:46:01 -04:00
"os"
2020-01-31 09:29:31 -05:00
"time"
2023-08-31 10:48:53 -04:00
"github.com/distribution/reference"
2020-01-31 09:29:31 -05:00
"github.com/spf13/cobra"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
2021-04-14 12:40:42 -04:00
"k8s.io/apimachinery/pkg/types"
2020-01-31 09:29:31 -05:00
utilrand "k8s.io/apimachinery/pkg/util/rand"
2021-04-14 12:40:42 -04:00
"k8s.io/apimachinery/pkg/util/strategicpatch"
2020-01-31 09:29:31 -05:00
"k8s.io/apimachinery/pkg/watch"
"k8s.io/cli-runtime/pkg/genericclioptions"
2023-04-05 07:07:46 -04:00
"k8s.io/cli-runtime/pkg/genericiooptions"
2022-02-18 07:33:38 -05:00
"k8s.io/cli-runtime/pkg/printers"
2020-01-31 09:29:31 -05:00
"k8s.io/cli-runtime/pkg/resource"
2023-02-13 05:03:50 -05:00
"k8s.io/client-go/kubernetes"
2020-01-31 09:29:31 -05:00
corev1client "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/tools/cache"
watchtools "k8s.io/client-go/tools/watch"
2024-05-20 16:14:54 -04:00
"k8s.io/klog/v2"
2020-01-31 09:29:31 -05:00
"k8s.io/kubectl/pkg/cmd/attach"
"k8s.io/kubectl/pkg/cmd/exec"
"k8s.io/kubectl/pkg/cmd/logs"
cmdutil "k8s.io/kubectl/pkg/cmd/util"
"k8s.io/kubectl/pkg/polymorphichelpers"
"k8s.io/kubectl/pkg/scheme"
"k8s.io/kubectl/pkg/util/i18n"
"k8s.io/kubectl/pkg/util/interrupt"
"k8s.io/kubectl/pkg/util/templates"
2024-05-20 16:14:54 -04:00
"k8s.io/utils/ptr"
2024-06-04 08:06:45 -04:00
"sigs.k8s.io/yaml"
2020-01-31 09:29:31 -05:00
)
var (
2020-04-03 12:36:32 -04:00
debugLong = templates . LongDesc ( i18n . T ( `
Debug cluster resources using interactive debugging containers .
' debug ' provides automation for common debugging tasks for cluster objects identified by
2020-10-30 13:23:34 -04:00
resource and name . Pods will be used by default if no resource is specified .
2020-04-03 12:36:32 -04:00
The action taken by ' debug ' varies depending on what resource is specified . Supported
actions include :
* Workload : Create a copy of an existing pod with certain attributes changed ,
for example changing the image tag to a new version .
* Workload : Add an ephemeral container to an already running pod , for example to add
debugging utilities without restarting the pod .
* Node : Create a new pod that runs in the node ' s host namespaces and can access
the node ' s filesystem .
2025-03-19 03:50:30 -04:00
2025-05-15 06:32:06 -04:00
Note : When a non - root user is configured for the entire target Pod , some capabilities granted
2025-03-19 03:50:30 -04:00
by debug profile may not work .
2020-10-30 13:23:34 -04:00
` ) )
2020-01-31 09:29:31 -05:00
debugExample = templates . Examples ( i18n . T ( `
# Create an interactive debugging session in pod mypod and immediately attach to it .
2020-11-04 10:30:49 -05:00
kubectl debug mypod - it -- image = busybox
2020-01-31 09:29:31 -05:00
2023-02-10 02:21:15 -05:00
# Create an interactive debugging session for the pod in the file pod . yaml and immediately attach to it .
# ( requires the EphemeralContainers feature to be enabled in the cluster )
kubectl debug - f pod . yaml - it -- image = busybox
2020-01-31 09:29:31 -05:00
# Create a debug container named debugger using a custom automated debugging image .
2020-11-04 10:30:49 -05:00
kubectl debug -- image = myproj / debug - tools - c debugger mypod
2020-04-12 13:58:36 -04:00
2020-10-30 13:23:34 -04:00
# Create a copy of mypod adding a debug container and attach to it
2020-11-04 10:30:49 -05:00
kubectl debug mypod - it -- image = busybox -- copy - to = my - debugger
2020-04-12 13:58:36 -04:00
2020-10-30 13:23:34 -04:00
# Create a copy of mypod changing the command of mycontainer
2020-11-04 10:30:49 -05:00
kubectl debug mypod - it -- copy - to = my - debugger -- container = mycontainer -- sh
2020-10-30 13:23:34 -04:00
# Create a copy of mypod changing all container images to busybox
2020-11-04 10:30:49 -05:00
kubectl debug mypod -- copy - to = my - debugger -- set - image = *= busybox
2020-10-30 13:23:34 -04:00
# Create a copy of mypod adding a debug container and changing container images
2020-11-04 10:30:49 -05:00
kubectl debug mypod - it -- copy - to = my - debugger -- image = debian -- set - image = app = app : debug , sidecar = sidecar : debug
2020-04-03 12:36:32 -04:00
# Create an interactive debugging session on a node and immediately attach to it .
# The container will run in the host namespaces and the host ' s filesystem will be mounted at / host
2020-11-04 10:30:49 -05:00
kubectl debug node / mynode - it -- image = busybox
2020-04-12 13:58:36 -04:00
` ) )
2020-01-31 09:29:31 -05:00
)
var nameSuffixFunc = utilrand . String
2023-09-01 04:46:01 -04:00
type DebugAttachFunc func ( ctx context . Context , restClientGetter genericclioptions . RESTClientGetter , cmdPath string , ns , podName , containerName string ) error
2020-01-31 09:29:31 -05:00
// DebugOptions holds the options for an invocation of kubectl debug.
type DebugOptions struct {
2024-02-06 02:19:23 -05:00
Args [ ] string
ArgsOnly bool
Attach bool
AttachFunc DebugAttachFunc
Container string
CopyTo string
Replace bool
Env [ ] corev1 . EnvVar
Image string
Interactive bool
KeepLabels bool
KeepAnnotations bool
KeepLiveness bool
KeepReadiness bool
KeepStartup bool
KeepInitContainers bool
Namespace string
TargetNames [ ] string
PullPolicy corev1 . PullPolicy
Quiet bool
SameNode bool
SetImages map [ string ] string
ShareProcesses bool
TargetContainer string
TTY bool
Profile string
CustomProfileFile string
CustomProfile * corev1 . Container
Applier ProfileApplier
2020-04-12 13:58:36 -04:00
2023-02-10 02:21:15 -05:00
explicitNamespace bool
2020-11-05 07:40:11 -05:00
attachChanged bool
2020-04-12 13:58:36 -04:00
shareProcessedChanged bool
2020-01-31 09:29:31 -05:00
2021-06-28 12:19:50 -04:00
podClient corev1client . CoreV1Interface
2020-01-31 09:29:31 -05:00
2023-02-13 05:03:50 -05:00
Builder * resource . Builder
2023-04-05 07:07:46 -04:00
genericiooptions . IOStreams
2023-01-09 20:14:16 -05:00
WarningPrinter * printers . WarningPrinter
2023-02-10 02:21:15 -05:00
resource . FilenameOptions
2020-01-31 09:29:31 -05:00
}
// NewDebugOptions returns a DebugOptions initialized with default values.
2023-04-05 07:07:46 -04:00
func NewDebugOptions ( streams genericiooptions . IOStreams ) * DebugOptions {
2020-01-31 09:29:31 -05:00
return & DebugOptions {
2024-02-06 02:19:23 -05:00
Args : [ ] string { } ,
IOStreams : streams ,
KeepInitContainers : true ,
TargetNames : [ ] string { } ,
ShareProcesses : true ,
2020-01-31 09:29:31 -05:00
}
}
// NewCmdDebug returns a cobra command that runs kubectl debug.
2023-04-05 07:07:46 -04:00
func NewCmdDebug ( restClientGetter genericclioptions . RESTClientGetter , streams genericiooptions . IOStreams ) * cobra . Command {
2020-01-31 09:29:31 -05:00
o := NewDebugOptions ( streams )
cmd := & cobra . Command {
2020-10-30 13:23:34 -04:00
Use : "debug (POD | TYPE[[.VERSION].GROUP]/NAME) [ -- COMMAND [args...] ]" ,
2020-01-31 09:29:31 -05:00
DisableFlagsInUseLine : true ,
2020-10-30 13:23:34 -04:00
Short : i18n . T ( "Create debugging sessions for troubleshooting workloads and nodes" ) ,
2020-01-31 09:29:31 -05:00
Long : debugLong ,
Example : debugExample ,
Run : func ( cmd * cobra . Command , args [ ] string ) {
2023-02-13 05:16:35 -05:00
cmdutil . CheckErr ( o . Complete ( restClientGetter , cmd , args ) )
2022-05-17 04:38:20 -04:00
cmdutil . CheckErr ( o . Validate ( ) )
2023-02-13 05:16:35 -05:00
cmdutil . CheckErr ( o . Run ( restClientGetter , cmd ) )
2020-01-31 09:29:31 -05:00
} ,
}
2023-02-13 04:36:18 -05:00
o . AddFlags ( cmd )
2020-01-31 09:29:31 -05:00
return cmd
}
2023-02-13 04:36:18 -05:00
func ( o * DebugOptions ) AddFlags ( cmd * cobra . Command ) {
cmdutil . AddJsonFilenameFlag ( cmd . Flags ( ) , & o . FilenameOptions . Filenames , "identifying the resource to debug" )
cmd . Flags ( ) . BoolVar ( & o . ArgsOnly , "arguments-only" , o . ArgsOnly , i18n . T ( "If specified, everything after -- will be passed to the new container as Args instead of Command." ) )
cmd . Flags ( ) . BoolVar ( & o . Attach , "attach" , o . Attach , i18n . T ( "If true, wait for the container to start running, and then attach as if 'kubectl attach ...' were called. Default false, unless '-i/--stdin' is set, in which case the default is true." ) )
cmd . Flags ( ) . StringVarP ( & o . Container , "container" , "c" , o . Container , i18n . T ( "Container name to use for debug container." ) )
cmd . Flags ( ) . StringVar ( & o . CopyTo , "copy-to" , o . CopyTo , i18n . T ( "Create a copy of the target Pod with this name." ) )
cmd . Flags ( ) . BoolVar ( & o . Replace , "replace" , o . Replace , i18n . T ( "When used with '--copy-to', delete the original Pod." ) )
2020-01-31 09:29:31 -05:00
cmd . Flags ( ) . StringToString ( "env" , nil , i18n . T ( "Environment variables to set in the container." ) )
2023-02-13 04:36:18 -05:00
cmd . Flags ( ) . StringVar ( & o . Image , "image" , o . Image , i18n . T ( "Container image to use for debug container." ) )
2024-02-06 02:19:23 -05:00
cmd . Flags ( ) . BoolVar ( & o . KeepLabels , "keep-labels" , o . KeepLabels , i18n . T ( "If true, keep the original pod labels.(This flag only works when used with '--copy-to')" ) )
cmd . Flags ( ) . BoolVar ( & o . KeepAnnotations , "keep-annotations" , o . KeepAnnotations , i18n . T ( "If true, keep the original pod annotations.(This flag only works when used with '--copy-to')" ) )
cmd . Flags ( ) . BoolVar ( & o . KeepLiveness , "keep-liveness" , o . KeepLiveness , i18n . T ( "If true, keep the original pod liveness probes.(This flag only works when used with '--copy-to')" ) )
cmd . Flags ( ) . BoolVar ( & o . KeepReadiness , "keep-readiness" , o . KeepReadiness , i18n . T ( "If true, keep the original pod readiness probes.(This flag only works when used with '--copy-to')" ) )
cmd . Flags ( ) . BoolVar ( & o . KeepStartup , "keep-startup" , o . KeepStartup , i18n . T ( "If true, keep the original startup probes.(This flag only works when used with '--copy-to')" ) )
cmd . Flags ( ) . BoolVar ( & o . KeepInitContainers , "keep-init-containers" , o . KeepInitContainers , i18n . T ( "Run the init containers for the pod. Defaults to true.(This flag only works when used with '--copy-to')" ) )
2023-02-13 04:36:18 -05:00
cmd . Flags ( ) . StringToStringVar ( & o . SetImages , "set-image" , o . SetImages , i18n . T ( "When used with '--copy-to', a list of name=image pairs for changing container images, similar to how 'kubectl set image' works." ) )
2020-10-30 13:23:34 -04:00
cmd . Flags ( ) . String ( "image-pull-policy" , "" , i18n . T ( "The image pull policy for the container. If left empty, this value will not be specified by the client and defaulted by the server." ) )
2023-02-13 04:36:18 -05:00
cmd . Flags ( ) . BoolVarP ( & o . Interactive , "stdin" , "i" , o . Interactive , i18n . T ( "Keep stdin open on the container(s) in the pod, even if nothing is attached." ) )
cmd . Flags ( ) . BoolVarP ( & o . Quiet , "quiet" , "q" , o . Quiet , i18n . T ( "If true, suppress informational messages." ) )
cmd . Flags ( ) . BoolVar ( & o . SameNode , "same-node" , o . SameNode , i18n . T ( "When used with '--copy-to', schedule the copy of target Pod on the same node." ) )
cmd . Flags ( ) . BoolVar ( & o . ShareProcesses , "share-processes" , o . ShareProcesses , i18n . T ( "When used with '--copy-to', enable process namespace sharing in the copy." ) )
cmd . Flags ( ) . StringVar ( & o . TargetContainer , "target" , "" , i18n . T ( "When using an ephemeral container, target processes in this container name." ) )
cmd . Flags ( ) . BoolVarP ( & o . TTY , "tty" , "t" , o . TTY , i18n . T ( "Allocate a TTY for the debugging container." ) )
2026-01-16 09:45:12 -05:00
cmd . Flags ( ) . StringVar ( & o . Profile , "profile" , ProfileGeneral , i18n . T ( ` Options are "general", "baseline", "restricted", "netadmin" or "sysadmin". Defaults to "general" ` ) )
2024-10-22 14:48:59 -04:00
cmd . Flags ( ) . StringVar ( & o . CustomProfileFile , "custom" , o . CustomProfileFile , i18n . T ( "Path to a JSON or YAML file containing a partial container spec to customize built-in debug profiles." ) )
2020-01-31 09:29:31 -05:00
}
// Complete finishes run-time initialization of debug.DebugOptions.
2023-02-13 05:16:35 -05:00
func ( o * DebugOptions ) Complete ( restClientGetter genericclioptions . RESTClientGetter , cmd * cobra . Command , args [ ] string ) error {
2020-01-31 09:29:31 -05:00
var err error
o . PullPolicy = corev1 . PullPolicy ( cmdutil . GetFlagString ( cmd , "image-pull-policy" ) )
// Arguments
argsLen := cmd . ArgsLenAtDash ( )
2020-04-03 08:31:18 -04:00
o . TargetNames = args
2020-01-31 09:29:31 -05:00
// If there is a dash and there are args after the dash, extract the args.
if argsLen >= 0 && len ( args ) > argsLen {
2020-04-03 08:31:18 -04:00
o . TargetNames , o . Args = args [ : argsLen ] , args [ argsLen : ]
2020-01-31 09:29:31 -05:00
}
// Attach
attachFlag := cmd . Flags ( ) . Lookup ( "attach" )
if ! attachFlag . Changed && o . Interactive {
o . Attach = true
2023-12-22 01:50:48 -05:00
}
// Downstream tools may want to use their own customized
// attach function to do extra work or use attach command
// with different flags instead of the static one defined in
// handleAttachPod. But if this function is not set explicitly,
// we fall back to default.
if o . AttachFunc == nil {
o . AttachFunc = o . handleAttachPod
2020-01-31 09:29:31 -05:00
}
// Environment
envStrings , err := cmd . Flags ( ) . GetStringToString ( "env" )
if err != nil {
return fmt . Errorf ( "internal error getting env flag: %v" , err )
}
for k , v := range envStrings {
o . Env = append ( o . Env , corev1 . EnvVar { Name : k , Value : v } )
}
// Namespace
2023-02-13 05:16:35 -05:00
o . Namespace , o . explicitNamespace , err = restClientGetter . ToRawKubeConfigLoader ( ) . Namespace ( )
2020-01-31 09:29:31 -05:00
if err != nil {
return err
}
2020-11-05 07:40:11 -05:00
// Record flags that the user explicitly changed from their defaults
o . attachChanged = cmd . Flags ( ) . Changed ( "attach" )
2020-04-12 13:58:36 -04:00
o . shareProcessedChanged = cmd . Flags ( ) . Changed ( "share-processes" )
2023-01-09 20:14:16 -05:00
// Set default WarningPrinter
if o . WarningPrinter == nil {
2025-12-18 01:35:36 -05:00
o . WarningPrinter = printers . NewWarningPrinter ( o . ErrOut , printers . WarningPrinterOptions { Color : printers . AllowsColorOutput ( o . ErrOut ) } )
2023-01-09 20:14:16 -05:00
}
Implement kubectl debug profiles: general, baseline, and restricted (#114280)
* feat(debug): add more profiles
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
* feat(debug): implment serveral debugging profiles
Including `general`, `baseline` and `restricted`.
I plan to add more profiles afterwards, but I'd like to get early
reviews.
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
* test: add some basic tests
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
* chore: add some helper functions
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
* ensure pod copies always get their probes cleared
not wanting probes to be present is something we want
for all the debug profiles; so an easy place to implement
this is at the time of pod copy generation.
* ensure debug container in pod copy is added before the profile application
The way that the container list modification was defered causes the
debug container to be added after the profile applier runs. We now
make sure to have the container list modification happen before
the profile applier runs.
* make switch over pod copy, ephemeral, or node more clear
* use helper functions
added a helper function to modify a container out of a list that
matches the provided container name.
also added a helper function that adds capabilities to container
security.
* add tests for the debug profiles
* document new debugging profiles in command line help text
* add file header to profiles_test.go
* remove URL to KEP from help text
* move probe removal to the profiles
* remove mustNewProfileApplier in tests
* remove extra whiteline from import block
* remove isPodCopy helper func
* switch baselineProfile to using the modifyEphemeralContainer helper
* rename addCap to addCapability, and don't do deep copy
* fix godoc on modifyEphemeralContainer
* export DebugOptions.Applier for extensibility
* fix unit test
* fix spelling on overriden
* remove debugStyle facilities
* inline setHostNamespace helper func
* remove modifyContainer, modifyEphemeralContainer, and remove probes
their logic have been in-lined at call sites
* remove DebugApplierFunc convenience facility
* fix baseline profile implementation
it shouldn't have SYS_PTRACE base on
https://github.com/kubernetes/enhancements/tree/master/keps/sig-cli/1441-kubectl-debug#profile-baseline
* remove addCapability helper, in-lining at call sites
* address Arda's code review comments
1 use Bool instead of BoolPtr (now deprecated)
2 tweak for loop to continue when container name is not what we expect
3 use our knowledge on how the debug container is generated to simplify
our modification to the security context
4 use our knowledge on how the pod for node debugging is generated to no
longer explicit set pod's HostNework, HostPID and HostIPC fields to
false
* remove tricky defer in generatePodCopyWithDebugContainer
* provide helper functions to make debug profiles more readable
* add note to remind people about updating --profile's help text when adding new profiles
* Implement helper functions with names that improve readability
* add styleUnsupported to replace debugStyle(-1)
* fix godoc on modifyContainer
* drop style prefix from debugStyle values
* put VisitContainers in podutils & use that from debug
* cite source for ContainerType and VisitContainers
* pull in AllContainers ContainerType value
* have VisitContainer take pod spec rather than pod
* in-line modifyContainer
* unexport helper funcs
* put debugStyle at top of file
* merge profile_applier.go into profile.go
* tweak dropCapabilities
* fix allowProcessTracing & add a test for it
* drop mask param from help funcs, since we can already unambiguous identify the container by name
* fix grammar in code comment
---------
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
Co-authored-by: Jian Zeng <anonymousknight96@gmail.com>
Kubernetes-commit: d35da348c60a3c7505419741f2546ff8b0e38454
2023-02-09 12:18:22 -05:00
if o . Applier == nil {
2024-02-06 02:19:23 -05:00
kflags := KeepFlags {
Labels : o . KeepLabels ,
Annotations : o . KeepAnnotations ,
Liveness : o . KeepLiveness ,
Readiness : o . KeepReadiness ,
Startup : o . KeepStartup ,
InitContainers : o . KeepInitContainers ,
}
applier , err := NewProfileApplier ( o . Profile , kflags )
Implement kubectl debug profiles: general, baseline, and restricted (#114280)
* feat(debug): add more profiles
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
* feat(debug): implment serveral debugging profiles
Including `general`, `baseline` and `restricted`.
I plan to add more profiles afterwards, but I'd like to get early
reviews.
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
* test: add some basic tests
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
* chore: add some helper functions
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
* ensure pod copies always get their probes cleared
not wanting probes to be present is something we want
for all the debug profiles; so an easy place to implement
this is at the time of pod copy generation.
* ensure debug container in pod copy is added before the profile application
The way that the container list modification was defered causes the
debug container to be added after the profile applier runs. We now
make sure to have the container list modification happen before
the profile applier runs.
* make switch over pod copy, ephemeral, or node more clear
* use helper functions
added a helper function to modify a container out of a list that
matches the provided container name.
also added a helper function that adds capabilities to container
security.
* add tests for the debug profiles
* document new debugging profiles in command line help text
* add file header to profiles_test.go
* remove URL to KEP from help text
* move probe removal to the profiles
* remove mustNewProfileApplier in tests
* remove extra whiteline from import block
* remove isPodCopy helper func
* switch baselineProfile to using the modifyEphemeralContainer helper
* rename addCap to addCapability, and don't do deep copy
* fix godoc on modifyEphemeralContainer
* export DebugOptions.Applier for extensibility
* fix unit test
* fix spelling on overriden
* remove debugStyle facilities
* inline setHostNamespace helper func
* remove modifyContainer, modifyEphemeralContainer, and remove probes
their logic have been in-lined at call sites
* remove DebugApplierFunc convenience facility
* fix baseline profile implementation
it shouldn't have SYS_PTRACE base on
https://github.com/kubernetes/enhancements/tree/master/keps/sig-cli/1441-kubectl-debug#profile-baseline
* remove addCapability helper, in-lining at call sites
* address Arda's code review comments
1 use Bool instead of BoolPtr (now deprecated)
2 tweak for loop to continue when container name is not what we expect
3 use our knowledge on how the debug container is generated to simplify
our modification to the security context
4 use our knowledge on how the pod for node debugging is generated to no
longer explicit set pod's HostNework, HostPID and HostIPC fields to
false
* remove tricky defer in generatePodCopyWithDebugContainer
* provide helper functions to make debug profiles more readable
* add note to remind people about updating --profile's help text when adding new profiles
* Implement helper functions with names that improve readability
* add styleUnsupported to replace debugStyle(-1)
* fix godoc on modifyContainer
* drop style prefix from debugStyle values
* put VisitContainers in podutils & use that from debug
* cite source for ContainerType and VisitContainers
* pull in AllContainers ContainerType value
* have VisitContainer take pod spec rather than pod
* in-line modifyContainer
* unexport helper funcs
* put debugStyle at top of file
* merge profile_applier.go into profile.go
* tweak dropCapabilities
* fix allowProcessTracing & add a test for it
* drop mask param from help funcs, since we can already unambiguous identify the container by name
* fix grammar in code comment
---------
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
Co-authored-by: Jian Zeng <anonymousknight96@gmail.com>
Kubernetes-commit: d35da348c60a3c7505419741f2546ff8b0e38454
2023-02-09 12:18:22 -05:00
if err != nil {
return err
}
o . Applier = applier
2021-11-11 11:57:02 -05:00
}
2022-02-18 07:33:38 -05:00
2023-09-01 04:46:01 -04:00
if o . CustomProfileFile != "" {
customProfileBytes , err := os . ReadFile ( o . CustomProfileFile )
if err != nil {
return fmt . Errorf ( "must pass a container spec json file for custom profile: %w" , err )
}
err = json . Unmarshal ( customProfileBytes , & o . CustomProfile )
if err != nil {
2024-06-04 08:06:45 -04:00
err = yaml . Unmarshal ( customProfileBytes , & o . CustomProfile )
if err != nil {
return fmt . Errorf ( "%s does not contain a valid container spec: %w" , o . CustomProfileFile , err )
}
2023-09-01 04:46:01 -04:00
}
}
2023-02-13 05:16:35 -05:00
clientConfig , err := restClientGetter . ToRESTConfig ( )
2023-02-13 05:03:50 -05:00
if err != nil {
return err
}
client , err := kubernetes . NewForConfig ( clientConfig )
if err != nil {
return err
}
o . podClient = client . CoreV1 ( )
2023-02-13 05:16:35 -05:00
o . Builder = resource . NewBuilder ( restClientGetter )
2023-02-13 05:03:50 -05:00
2020-01-31 09:29:31 -05:00
return nil
}
// Validate checks that the provided debug options are specified.
2022-05-17 04:38:20 -04:00
func ( o * DebugOptions ) Validate ( ) error {
2020-11-05 07:40:11 -05:00
// Attach
if o . Attach && o . attachChanged && len ( o . Image ) == 0 && len ( o . Container ) == 0 {
return fmt . Errorf ( "you must specify --container or create a new container using --image in order to attach." )
}
2020-10-30 03:54:13 -04:00
// CopyTo
2020-10-30 13:23:34 -04:00
if len ( o . CopyTo ) > 0 {
if len ( o . Image ) == 0 && len ( o . SetImages ) == 0 && len ( o . Args ) == 0 {
return fmt . Errorf ( "you must specify --image, --set-image or command arguments." )
}
if len ( o . Args ) > 0 && len ( o . Container ) == 0 && len ( o . Image ) == 0 {
return fmt . Errorf ( "you must specify an existing container or a new image when specifying args." )
}
} else {
// These flags are exclusive to --copy-to
2020-10-30 03:54:13 -04:00
switch {
case o . Replace :
return fmt . Errorf ( "--replace may only be used with --copy-to." )
case o . SameNode :
return fmt . Errorf ( "--same-node may only be used with --copy-to." )
2020-10-30 13:23:34 -04:00
case len ( o . SetImages ) > 0 :
return fmt . Errorf ( "--set-image may only be used with --copy-to." )
case len ( o . Image ) == 0 :
return fmt . Errorf ( "you must specify --image when not using --copy-to." )
2020-10-30 03:54:13 -04:00
}
}
2020-01-31 09:29:31 -05:00
// Image
2020-10-30 13:23:34 -04:00
if len ( o . Image ) > 0 && ! reference . ReferenceRegexp . MatchString ( o . Image ) {
return fmt . Errorf ( "invalid image name %q: %v" , o . Image , reference . ErrReferenceInvalidFormat )
2020-01-31 09:29:31 -05:00
}
// Name
2023-02-10 02:21:15 -05:00
if len ( o . TargetNames ) == 0 && len ( o . FilenameOptions . Filenames ) == 0 {
return fmt . Errorf ( "NAME or filename is required for debug" )
2020-01-31 09:29:31 -05:00
}
// Pull Policy
switch o . PullPolicy {
case corev1 . PullAlways , corev1 . PullIfNotPresent , corev1 . PullNever , "" :
// continue
default :
return fmt . Errorf ( "invalid image pull policy: %s" , o . PullPolicy )
}
2020-10-30 13:23:34 -04:00
// SetImages
for name , image := range o . SetImages {
if ! reference . ReferenceRegexp . MatchString ( image ) {
return fmt . Errorf ( "invalid image name %q for container %q: %v" , image , name , reference . ErrReferenceInvalidFormat )
}
}
2020-10-30 03:54:13 -04:00
// TargetContainer
2021-04-13 09:50:26 -04:00
if len ( o . TargetContainer ) > 0 {
if len ( o . CopyTo ) > 0 {
return fmt . Errorf ( "--target is incompatible with --copy-to. Use --share-processes instead." )
}
if ! o . Quiet {
fmt . Fprintf ( o . Out , "Targeting container %q. If you don't see processes from this container it may be because the container runtime doesn't support this feature.\n" , o . TargetContainer )
// TODO(verb): Add a list of supported container runtimes to https://kubernetes.io/docs/concepts/workloads/pods/ephemeral-containers/ and then link here.
}
2020-04-03 12:36:32 -04:00
}
2020-01-31 09:29:31 -05:00
// TTY
if o . TTY && ! o . Interactive {
return fmt . Errorf ( "-i/--stdin is required for containers with -t/--tty=true" )
}
2023-01-09 20:14:16 -05:00
// WarningPrinter
if o . WarningPrinter == nil {
return fmt . Errorf ( "WarningPrinter can not be used without initialization" )
2022-02-18 07:33:38 -05:00
}
2023-09-01 04:46:01 -04:00
if o . CustomProfile != nil {
if o . CustomProfile . Name != "" || len ( o . CustomProfile . Command ) > 0 || o . CustomProfile . Image != "" || o . CustomProfile . Lifecycle != nil || len ( o . CustomProfile . VolumeDevices ) > 0 {
return fmt . Errorf ( "name, command, image, lifecycle and volume devices are not modifiable via custom profile" )
}
}
2024-09-19 11:28:38 -04:00
// Warning for legacy profile
if o . Profile == ProfileLegacy {
2025-12-23 10:50:14 -05:00
fmt . Fprintln ( o . ErrOut , ` --profile=legacy is deprecated and planned to be removed in v1.39. It is recommended to specify other profile, for example "--profile=general". ` ) //nolint:errcheck
2024-09-19 11:28:38 -04:00
}
2020-01-31 09:29:31 -05:00
return nil
}
// Run executes a kubectl debug.
2023-02-13 05:16:35 -05:00
func ( o * DebugOptions ) Run ( restClientGetter genericclioptions . RESTClientGetter , cmd * cobra . Command ) error {
2020-04-03 08:31:18 -04:00
ctx := context . Background ( )
2023-02-13 05:03:50 -05:00
r := o . Builder .
2020-01-31 09:29:31 -05:00
WithScheme ( scheme . Scheme , scheme . Scheme . PrioritizedVersionsAllGroups ( ) ... ) .
2023-02-10 02:21:15 -05:00
FilenameParam ( o . explicitNamespace , & o . FilenameOptions ) .
2020-04-03 08:31:18 -04:00
NamespaceParam ( o . Namespace ) . DefaultNamespace ( ) . ResourceNames ( "pods" , o . TargetNames ... ) .
2020-01-31 09:29:31 -05:00
Do ( )
if err := r . Err ( ) ; err != nil {
return err
}
2023-02-13 05:03:50 -05:00
err := r . Visit ( func ( info * resource . Info , err error ) error {
2020-01-31 09:29:31 -05:00
if err != nil {
// TODO(verb): configurable early return
return err
}
2020-04-03 08:31:18 -04:00
var (
debugPod * corev1 . Pod
containerName string
visitErr error
)
switch obj := info . Object . ( type ) {
2020-04-03 12:36:32 -04:00
case * corev1 . Node :
debugPod , containerName , visitErr = o . visitNode ( ctx , obj )
2020-04-03 08:31:18 -04:00
case * corev1 . Pod :
debugPod , containerName , visitErr = o . visitPod ( ctx , obj )
default :
visitErr = fmt . Errorf ( "%q not supported by debug" , info . Mapping . GroupVersionKind )
2020-01-31 09:29:31 -05:00
}
2020-04-03 08:31:18 -04:00
if visitErr != nil {
return visitErr
2020-01-31 09:29:31 -05:00
}
2023-07-24 08:28:21 -04:00
if o . Attach && len ( containerName ) > 0 && o . AttachFunc != nil {
if err := o . AttachFunc ( ctx , restClientGetter , cmd . Parent ( ) . CommandPath ( ) , debugPod . Namespace , debugPod . Name , containerName ) ; err != nil {
2020-01-31 09:29:31 -05:00
return err
}
}
return nil
} )
return err
}
2020-04-03 12:36:32 -04:00
// visitNode handles debugging for node targets by creating a privileged pod running in the host namespaces.
// Returns an already created pod and container name for subsequent attach, if applicable.
func ( o * DebugOptions ) visitNode ( ctx context . Context , node * corev1 . Node ) ( * corev1 . Pod , string , error ) {
pods := o . podClient . Pods ( o . Namespace )
2021-11-11 11:57:02 -05:00
debugPod , err := o . generateNodeDebugPod ( node )
if err != nil {
return nil , "" , err
}
newPod , err := pods . Create ( ctx , debugPod , metav1 . CreateOptions { } )
2020-04-03 12:36:32 -04:00
if err != nil {
return nil , "" , err
}
return newPod , newPod . Spec . Containers [ 0 ] . Name , nil
}
2020-04-03 08:31:18 -04:00
// visitPod handles debugging for pod targets by (depending on options):
2022-07-19 20:54:13 -04:00
// 1. Creating an ephemeral debug container in an existing pod, OR
// 2. Making a copy of pod with certain attributes changed
//
2020-04-03 08:31:18 -04:00
// visitPod returns a pod and debug container name for subsequent attach, if applicable.
func ( o * DebugOptions ) visitPod ( ctx context . Context , pod * corev1 . Pod ) ( * corev1 . Pod , string , error ) {
2020-04-12 13:58:36 -04:00
if len ( o . CopyTo ) > 0 {
return o . debugByCopy ( ctx , pod )
}
return o . debugByEphemeralContainer ( ctx , pod )
}
// debugByEphemeralContainer runs an EphemeralContainer in the target Pod for use as a debug container
func ( o * DebugOptions ) debugByEphemeralContainer ( ctx context . Context , pod * corev1 . Pod ) ( * corev1 . Pod , string , error ) {
2021-04-09 07:53:13 -04:00
klog . V ( 2 ) . Infof ( "existing ephemeral containers: %v" , pod . Spec . EphemeralContainers )
2021-04-14 12:40:42 -04:00
podJS , err := json . Marshal ( pod )
if err != nil {
return nil , "" , fmt . Errorf ( "error creating JSON for pod: %v" , err )
}
2021-04-09 07:53:13 -04:00
2021-11-11 11:57:02 -05:00
debugPod , debugContainer , err := o . generateDebugContainer ( pod )
if err != nil {
return nil , "" , err
}
2021-04-09 07:53:13 -04:00
klog . V ( 2 ) . Infof ( "new ephemeral container: %#v" , debugContainer )
2021-11-11 11:57:02 -05:00
2025-03-19 03:50:30 -04:00
o . displayWarning ( ( * corev1 . Container ) ( & debugContainer . EphemeralContainerCommon ) , pod )
2021-04-14 12:40:42 -04:00
debugJS , err := json . Marshal ( debugPod )
if err != nil {
return nil , "" , fmt . Errorf ( "error creating JSON for debug container: %v" , err )
}
2021-04-09 07:53:13 -04:00
2021-04-14 12:40:42 -04:00
patch , err := strategicpatch . CreateTwoWayMergePatch ( podJS , debugJS , pod )
2020-04-03 08:31:18 -04:00
if err != nil {
2021-04-14 12:40:42 -04:00
return nil , "" , fmt . Errorf ( "error creating patch to add debug container: %v" , err )
}
klog . V ( 2 ) . Infof ( "generated strategic merge patch for debug container: %s" , patch )
pods := o . podClient . Pods ( pod . Namespace )
result , err := pods . Patch ( ctx , pod . Name , types . StrategicMergePatchType , patch , metav1 . PatchOptions { } , "ephemeralcontainers" )
if err != nil {
// The apiserver will return a 404 when the EphemeralContainers feature is disabled because the `/ephemeralcontainers` subresource
// is missing. Unlike the 404 returned by a missing pod, the status details will be empty.
if serr , ok := err . ( * errors . StatusError ) ; ok && serr . Status ( ) . Reason == metav1 . StatusReasonNotFound && serr . ErrStatus . Details . Name == "" {
2022-12-16 10:46:47 -05:00
return nil , "" , fmt . Errorf ( "ephemeral containers are disabled for this cluster (error from server: %q)" , err )
2020-04-03 08:31:18 -04:00
}
2021-06-28 12:19:50 -04:00
2021-04-14 12:40:42 -04:00
return nil , "" , err
2020-04-03 08:31:18 -04:00
}
2021-04-09 07:53:13 -04:00
return result , debugContainer . Name , nil
2020-04-03 08:31:18 -04:00
}
2023-09-01 04:46:01 -04:00
// applyCustomProfile applies given partial container json file on to the profile
// incorporated debug pod.
func ( o * DebugOptions ) applyCustomProfile ( debugPod * corev1 . Pod , containerName string ) error {
o . CustomProfile . Name = containerName
customJS , err := json . Marshal ( o . CustomProfile )
if err != nil {
return fmt . Errorf ( "unable to marshall custom profile: %w" , err )
}
var index int
found := false
for i , val := range debugPod . Spec . Containers {
if val . Name == containerName {
index = i
found = true
break
}
}
if ! found {
return fmt . Errorf ( "unable to find the %s container in the pod %s" , containerName , debugPod . Name )
}
var debugContainerJS [ ] byte
debugContainerJS , err = json . Marshal ( debugPod . Spec . Containers [ index ] )
if err != nil {
return fmt . Errorf ( "unable to marshall container: %w" , err )
}
patchedContainer , err := strategicpatch . StrategicMergePatch ( debugContainerJS , customJS , corev1 . Container { } )
if err != nil {
return fmt . Errorf ( "error creating three way patch to add debug container: %w" , err )
}
err = json . Unmarshal ( patchedContainer , & debugPod . Spec . Containers [ index ] )
if err != nil {
return fmt . Errorf ( "unable to unmarshall patched container to container: %w" , err )
}
return nil
}
// applyCustomProfileEphemeral applies given partial container json file on to the profile
// incorporated ephemeral container of the pod.
func ( o * DebugOptions ) applyCustomProfileEphemeral ( debugPod * corev1 . Pod , containerName string ) error {
o . CustomProfile . Name = containerName
customJS , err := json . Marshal ( o . CustomProfile )
if err != nil {
return fmt . Errorf ( "unable to marshall custom profile: %w" , err )
}
var index int
found := false
for i , val := range debugPod . Spec . EphemeralContainers {
if val . Name == containerName {
index = i
found = true
break
}
}
if ! found {
return fmt . Errorf ( "unable to find the %s ephemeral container in the pod %s" , containerName , debugPod . Name )
}
var debugContainerJS [ ] byte
debugContainerJS , err = json . Marshal ( debugPod . Spec . EphemeralContainers [ index ] )
if err != nil {
return fmt . Errorf ( "unable to marshall ephemeral container:%w" , err )
}
patchedContainer , err := strategicpatch . StrategicMergePatch ( debugContainerJS , customJS , corev1 . Container { } )
if err != nil {
return fmt . Errorf ( "error creating three way patch to add debug container: %w" , err )
}
err = json . Unmarshal ( patchedContainer , & debugPod . Spec . EphemeralContainers [ index ] )
if err != nil {
return fmt . Errorf ( "unable to unmarshall patched container to ephemeral container: %w" , err )
}
return nil
}
2020-04-12 13:58:36 -04:00
// debugByCopy runs a copy of the target Pod with a debug container added or an original container modified
func ( o * DebugOptions ) debugByCopy ( ctx context . Context , pod * corev1 . Pod ) ( * corev1 . Pod , string , error ) {
2020-10-30 13:23:34 -04:00
copied , dc , err := o . generatePodCopyWithDebugContainer ( pod )
if err != nil {
return nil , "" , err
}
2025-03-19 03:50:30 -04:00
var debugContainer * corev1 . Container
for i := range copied . Spec . Containers {
if copied . Spec . Containers [ i ] . Name == dc {
debugContainer = & copied . Spec . Containers [ i ]
break
}
}
o . displayWarning ( debugContainer , copied )
2020-10-30 13:23:34 -04:00
created , err := o . podClient . Pods ( copied . Namespace ) . Create ( ctx , copied , metav1 . CreateOptions { } )
2020-04-12 13:58:36 -04:00
if err != nil {
return nil , "" , err
2020-01-31 09:29:31 -05:00
}
2020-04-12 13:58:36 -04:00
if o . Replace {
err := o . podClient . Pods ( pod . Namespace ) . Delete ( ctx , pod . Name , * metav1 . NewDeleteOptions ( 0 ) )
if err != nil {
return nil , "" , err
}
2020-01-31 09:29:31 -05:00
}
2020-10-30 13:23:34 -04:00
return created , dc , nil
2020-01-31 09:29:31 -05:00
}
2025-03-19 03:50:30 -04:00
// Display warning message if some capabilities are set by profile and non-root user is specified in .Spec.SecurityContext.RunAsUser.(#1650)
func ( o * DebugOptions ) displayWarning ( container * corev1 . Container , pod * corev1 . Pod ) {
if container == nil {
return
}
if pod . Spec . SecurityContext . RunAsUser == nil || * pod . Spec . SecurityContext . RunAsUser == 0 {
return
}
if container . SecurityContext == nil {
return
}
if container . SecurityContext . RunAsUser != nil && * container . SecurityContext . RunAsUser == 0 {
return
}
if ( container . SecurityContext . Privileged == nil || ! * container . SecurityContext . Privileged ) &&
( container . SecurityContext . Capabilities == nil || len ( container . SecurityContext . Capabilities . Add ) == 0 ) {
return
}
_ , _ = fmt . Fprintln ( o . ErrOut , ` Warning: Non-root user is configured for the entire target Pod, and some capabilities granted by debug profile may not work. Please consider using "--custom" with a custom profile that specifies "securityContext.runAsUser: 0". ` )
}
2021-11-11 11:57:02 -05:00
// generateDebugContainer returns a debugging pod and an EphemeralContainer suitable for use as a debug container
2020-01-31 09:29:31 -05:00
// in the given pod.
2021-11-11 11:57:02 -05:00
func ( o * DebugOptions ) generateDebugContainer ( pod * corev1 . Pod ) ( * corev1 . Pod , * corev1 . EphemeralContainer , error ) {
2020-04-12 13:58:36 -04:00
name := o . computeDebugContainerName ( pod )
2020-01-31 09:29:31 -05:00
ec := & corev1 . EphemeralContainer {
EphemeralContainerCommon : corev1 . EphemeralContainerCommon {
Name : name ,
Env : o . Env ,
Image : o . Image ,
ImagePullPolicy : o . PullPolicy ,
Stdin : o . Interactive ,
TerminationMessagePolicy : corev1 . TerminationMessageReadFile ,
TTY : o . TTY ,
} ,
2020-10-30 03:54:13 -04:00
TargetContainerName : o . TargetContainer ,
2020-01-31 09:29:31 -05:00
}
if o . ArgsOnly {
ec . Args = o . Args
} else {
ec . Command = o . Args
}
2021-11-11 11:57:02 -05:00
copied := pod . DeepCopy ( )
copied . Spec . EphemeralContainers = append ( copied . Spec . EphemeralContainers , * ec )
Implement kubectl debug profiles: general, baseline, and restricted (#114280)
* feat(debug): add more profiles
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
* feat(debug): implment serveral debugging profiles
Including `general`, `baseline` and `restricted`.
I plan to add more profiles afterwards, but I'd like to get early
reviews.
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
* test: add some basic tests
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
* chore: add some helper functions
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
* ensure pod copies always get their probes cleared
not wanting probes to be present is something we want
for all the debug profiles; so an easy place to implement
this is at the time of pod copy generation.
* ensure debug container in pod copy is added before the profile application
The way that the container list modification was defered causes the
debug container to be added after the profile applier runs. We now
make sure to have the container list modification happen before
the profile applier runs.
* make switch over pod copy, ephemeral, or node more clear
* use helper functions
added a helper function to modify a container out of a list that
matches the provided container name.
also added a helper function that adds capabilities to container
security.
* add tests for the debug profiles
* document new debugging profiles in command line help text
* add file header to profiles_test.go
* remove URL to KEP from help text
* move probe removal to the profiles
* remove mustNewProfileApplier in tests
* remove extra whiteline from import block
* remove isPodCopy helper func
* switch baselineProfile to using the modifyEphemeralContainer helper
* rename addCap to addCapability, and don't do deep copy
* fix godoc on modifyEphemeralContainer
* export DebugOptions.Applier for extensibility
* fix unit test
* fix spelling on overriden
* remove debugStyle facilities
* inline setHostNamespace helper func
* remove modifyContainer, modifyEphemeralContainer, and remove probes
their logic have been in-lined at call sites
* remove DebugApplierFunc convenience facility
* fix baseline profile implementation
it shouldn't have SYS_PTRACE base on
https://github.com/kubernetes/enhancements/tree/master/keps/sig-cli/1441-kubectl-debug#profile-baseline
* remove addCapability helper, in-lining at call sites
* address Arda's code review comments
1 use Bool instead of BoolPtr (now deprecated)
2 tweak for loop to continue when container name is not what we expect
3 use our knowledge on how the debug container is generated to simplify
our modification to the security context
4 use our knowledge on how the pod for node debugging is generated to no
longer explicit set pod's HostNework, HostPID and HostIPC fields to
false
* remove tricky defer in generatePodCopyWithDebugContainer
* provide helper functions to make debug profiles more readable
* add note to remind people about updating --profile's help text when adding new profiles
* Implement helper functions with names that improve readability
* add styleUnsupported to replace debugStyle(-1)
* fix godoc on modifyContainer
* drop style prefix from debugStyle values
* put VisitContainers in podutils & use that from debug
* cite source for ContainerType and VisitContainers
* pull in AllContainers ContainerType value
* have VisitContainer take pod spec rather than pod
* in-line modifyContainer
* unexport helper funcs
* put debugStyle at top of file
* merge profile_applier.go into profile.go
* tweak dropCapabilities
* fix allowProcessTracing & add a test for it
* drop mask param from help funcs, since we can already unambiguous identify the container by name
* fix grammar in code comment
---------
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
Co-authored-by: Jian Zeng <anonymousknight96@gmail.com>
Kubernetes-commit: d35da348c60a3c7505419741f2546ff8b0e38454
2023-02-09 12:18:22 -05:00
if err := o . Applier . Apply ( copied , name , copied ) ; err != nil {
2021-11-11 11:57:02 -05:00
return nil , nil , err
}
2023-09-01 04:46:01 -04:00
if o . CustomProfile != nil {
err := o . applyCustomProfileEphemeral ( copied , ec . Name )
if err != nil {
return nil , nil , err
}
}
Implement kubectl debug profiles: general, baseline, and restricted (#114280)
* feat(debug): add more profiles
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
* feat(debug): implment serveral debugging profiles
Including `general`, `baseline` and `restricted`.
I plan to add more profiles afterwards, but I'd like to get early
reviews.
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
* test: add some basic tests
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
* chore: add some helper functions
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
* ensure pod copies always get their probes cleared
not wanting probes to be present is something we want
for all the debug profiles; so an easy place to implement
this is at the time of pod copy generation.
* ensure debug container in pod copy is added before the profile application
The way that the container list modification was defered causes the
debug container to be added after the profile applier runs. We now
make sure to have the container list modification happen before
the profile applier runs.
* make switch over pod copy, ephemeral, or node more clear
* use helper functions
added a helper function to modify a container out of a list that
matches the provided container name.
also added a helper function that adds capabilities to container
security.
* add tests for the debug profiles
* document new debugging profiles in command line help text
* add file header to profiles_test.go
* remove URL to KEP from help text
* move probe removal to the profiles
* remove mustNewProfileApplier in tests
* remove extra whiteline from import block
* remove isPodCopy helper func
* switch baselineProfile to using the modifyEphemeralContainer helper
* rename addCap to addCapability, and don't do deep copy
* fix godoc on modifyEphemeralContainer
* export DebugOptions.Applier for extensibility
* fix unit test
* fix spelling on overriden
* remove debugStyle facilities
* inline setHostNamespace helper func
* remove modifyContainer, modifyEphemeralContainer, and remove probes
their logic have been in-lined at call sites
* remove DebugApplierFunc convenience facility
* fix baseline profile implementation
it shouldn't have SYS_PTRACE base on
https://github.com/kubernetes/enhancements/tree/master/keps/sig-cli/1441-kubectl-debug#profile-baseline
* remove addCapability helper, in-lining at call sites
* address Arda's code review comments
1 use Bool instead of BoolPtr (now deprecated)
2 tweak for loop to continue when container name is not what we expect
3 use our knowledge on how the debug container is generated to simplify
our modification to the security context
4 use our knowledge on how the pod for node debugging is generated to no
longer explicit set pod's HostNework, HostPID and HostIPC fields to
false
* remove tricky defer in generatePodCopyWithDebugContainer
* provide helper functions to make debug profiles more readable
* add note to remind people about updating --profile's help text when adding new profiles
* Implement helper functions with names that improve readability
* add styleUnsupported to replace debugStyle(-1)
* fix godoc on modifyContainer
* drop style prefix from debugStyle values
* put VisitContainers in podutils & use that from debug
* cite source for ContainerType and VisitContainers
* pull in AllContainers ContainerType value
* have VisitContainer take pod spec rather than pod
* in-line modifyContainer
* unexport helper funcs
* put debugStyle at top of file
* merge profile_applier.go into profile.go
* tweak dropCapabilities
* fix allowProcessTracing & add a test for it
* drop mask param from help funcs, since we can already unambiguous identify the container by name
* fix grammar in code comment
---------
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
Co-authored-by: Jian Zeng <anonymousknight96@gmail.com>
Kubernetes-commit: d35da348c60a3c7505419741f2546ff8b0e38454
2023-02-09 12:18:22 -05:00
ec = & copied . Spec . EphemeralContainers [ len ( copied . Spec . EphemeralContainers ) - 1 ]
2021-11-11 11:57:02 -05:00
return copied , ec , nil
2020-01-31 09:29:31 -05:00
}
2020-04-03 12:36:32 -04:00
// generateNodeDebugPod generates a debugging pod that schedules on the specified node.
// The generated pod will run in the host PID, Network & IPC namespaces, and it will have the node's filesystem mounted at /host.
2021-11-11 11:57:02 -05:00
func ( o * DebugOptions ) generateNodeDebugPod ( node * corev1 . Node ) ( * corev1 . Pod , error ) {
2020-04-03 12:36:32 -04:00
cn := "debugger"
// Setting a user-specified container name doesn't make much difference when there's only one container,
// but the argument exists for pod debugging so it might be confusing if it didn't work here.
if len ( o . Container ) > 0 {
cn = o . Container
}
// The name of the debugging pod is based on the target node, and it's not configurable to
// limit the number of command line flags. There may be a collision on the name, but this
// should be rare enough that it's not worth the API round trip to check.
2021-01-26 10:36:35 -05:00
pn := fmt . Sprintf ( "node-debugger-%s-%s" , node . Name , nameSuffixFunc ( 5 ) )
2020-04-03 12:36:32 -04:00
if ! o . Quiet {
2021-01-26 10:36:35 -05:00
fmt . Fprintf ( o . Out , "Creating debugging pod %s with container %s on node %s.\n" , pn , cn , node . Name )
2020-04-03 12:36:32 -04:00
}
p := & corev1 . Pod {
ObjectMeta : metav1 . ObjectMeta {
Name : pn ,
2025-05-15 06:32:06 -04:00
Labels : map [ string ] string {
"app.kubernetes.io/managed-by" : "kubectl-debug" ,
} ,
2020-04-03 12:36:32 -04:00
} ,
Spec : corev1 . PodSpec {
Containers : [ ] corev1 . Container {
{
Name : cn ,
Env : o . Env ,
Image : o . Image ,
ImagePullPolicy : o . PullPolicy ,
Stdin : o . Interactive ,
TerminationMessagePolicy : corev1 . TerminationMessageReadFile ,
TTY : o . TTY ,
} ,
} ,
2021-01-26 10:36:35 -05:00
NodeName : node . Name ,
2020-04-03 12:36:32 -04:00
RestartPolicy : corev1 . RestartPolicyNever ,
2021-01-26 10:36:35 -05:00
Tolerations : [ ] corev1 . Toleration {
{
Operator : corev1 . TolerationOpExists ,
} ,
} ,
2020-04-03 12:36:32 -04:00
} ,
}
if o . ArgsOnly {
p . Spec . Containers [ 0 ] . Args = o . Args
} else {
p . Spec . Containers [ 0 ] . Command = o . Args
}
Implement kubectl debug profiles: general, baseline, and restricted (#114280)
* feat(debug): add more profiles
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
* feat(debug): implment serveral debugging profiles
Including `general`, `baseline` and `restricted`.
I plan to add more profiles afterwards, but I'd like to get early
reviews.
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
* test: add some basic tests
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
* chore: add some helper functions
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
* ensure pod copies always get their probes cleared
not wanting probes to be present is something we want
for all the debug profiles; so an easy place to implement
this is at the time of pod copy generation.
* ensure debug container in pod copy is added before the profile application
The way that the container list modification was defered causes the
debug container to be added after the profile applier runs. We now
make sure to have the container list modification happen before
the profile applier runs.
* make switch over pod copy, ephemeral, or node more clear
* use helper functions
added a helper function to modify a container out of a list that
matches the provided container name.
also added a helper function that adds capabilities to container
security.
* add tests for the debug profiles
* document new debugging profiles in command line help text
* add file header to profiles_test.go
* remove URL to KEP from help text
* move probe removal to the profiles
* remove mustNewProfileApplier in tests
* remove extra whiteline from import block
* remove isPodCopy helper func
* switch baselineProfile to using the modifyEphemeralContainer helper
* rename addCap to addCapability, and don't do deep copy
* fix godoc on modifyEphemeralContainer
* export DebugOptions.Applier for extensibility
* fix unit test
* fix spelling on overriden
* remove debugStyle facilities
* inline setHostNamespace helper func
* remove modifyContainer, modifyEphemeralContainer, and remove probes
their logic have been in-lined at call sites
* remove DebugApplierFunc convenience facility
* fix baseline profile implementation
it shouldn't have SYS_PTRACE base on
https://github.com/kubernetes/enhancements/tree/master/keps/sig-cli/1441-kubectl-debug#profile-baseline
* remove addCapability helper, in-lining at call sites
* address Arda's code review comments
1 use Bool instead of BoolPtr (now deprecated)
2 tweak for loop to continue when container name is not what we expect
3 use our knowledge on how the debug container is generated to simplify
our modification to the security context
4 use our knowledge on how the pod for node debugging is generated to no
longer explicit set pod's HostNework, HostPID and HostIPC fields to
false
* remove tricky defer in generatePodCopyWithDebugContainer
* provide helper functions to make debug profiles more readable
* add note to remind people about updating --profile's help text when adding new profiles
* Implement helper functions with names that improve readability
* add styleUnsupported to replace debugStyle(-1)
* fix godoc on modifyContainer
* drop style prefix from debugStyle values
* put VisitContainers in podutils & use that from debug
* cite source for ContainerType and VisitContainers
* pull in AllContainers ContainerType value
* have VisitContainer take pod spec rather than pod
* in-line modifyContainer
* unexport helper funcs
* put debugStyle at top of file
* merge profile_applier.go into profile.go
* tweak dropCapabilities
* fix allowProcessTracing & add a test for it
* drop mask param from help funcs, since we can already unambiguous identify the container by name
* fix grammar in code comment
---------
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
Co-authored-by: Jian Zeng <anonymousknight96@gmail.com>
Kubernetes-commit: d35da348c60a3c7505419741f2546ff8b0e38454
2023-02-09 12:18:22 -05:00
if err := o . Applier . Apply ( p , cn , node ) ; err != nil {
2021-11-11 11:57:02 -05:00
return nil , err
}
2023-09-01 04:46:01 -04:00
if o . CustomProfile != nil {
err := o . applyCustomProfile ( p , cn )
if err != nil {
return nil , err
}
}
2021-11-11 11:57:02 -05:00
return p , nil
2020-04-03 12:36:32 -04:00
}
2020-10-30 13:23:34 -04:00
// generatePodCopyWithDebugContainer takes a Pod and returns a copy and the debug container name of that copy
func ( o * DebugOptions ) generatePodCopyWithDebugContainer ( pod * corev1 . Pod ) ( * corev1 . Pod , string , error ) {
2020-04-12 13:58:36 -04:00
copied := & corev1 . Pod {
ObjectMeta : metav1 . ObjectMeta {
Name : o . CopyTo ,
Namespace : pod . Namespace ,
Annotations : pod . Annotations ,
2024-02-06 02:19:23 -05:00
Labels : pod . Labels ,
2020-04-12 13:58:36 -04:00
} ,
Spec : * pod . Spec . DeepCopy ( ) ,
}
2020-09-06 13:43:21 -04:00
// set EphemeralContainers to nil so that the copy of pod can be created
copied . Spec . EphemeralContainers = nil
2020-04-12 13:58:36 -04:00
// change ShareProcessNamespace configuration only when commanded explicitly
if o . shareProcessedChanged {
2024-05-20 16:14:54 -04:00
copied . Spec . ShareProcessNamespace = ptr . To ( o . ShareProcesses )
2020-04-12 13:58:36 -04:00
}
if ! o . SameNode {
copied . Spec . NodeName = ""
}
2020-10-30 13:23:34 -04:00
// Apply image mutations
for i , c := range copied . Spec . Containers {
override := o . SetImages [ "*" ]
if img , ok := o . SetImages [ c . Name ] ; ok {
override = img
}
if len ( override ) > 0 {
copied . Spec . Containers [ i ] . Image = override
}
}
2020-11-05 07:40:11 -05:00
name , containerByName := o . Container , containerNameToRef ( copied )
2020-10-30 13:23:34 -04:00
c , ok := containerByName [ name ]
if ! ok {
// Adding a new debug container
if len ( o . Image ) == 0 {
2020-11-05 07:40:11 -05:00
if len ( o . SetImages ) > 0 {
// This was a --set-image only invocation
return copied , "" , nil
}
2020-10-30 13:23:34 -04:00
return nil , "" , fmt . Errorf ( "you must specify image when creating new container" )
}
2020-11-05 07:40:11 -05:00
if len ( name ) == 0 {
name = o . computeDebugContainerName ( copied )
}
Implement kubectl debug profiles: general, baseline, and restricted (#114280)
* feat(debug): add more profiles
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
* feat(debug): implment serveral debugging profiles
Including `general`, `baseline` and `restricted`.
I plan to add more profiles afterwards, but I'd like to get early
reviews.
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
* test: add some basic tests
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
* chore: add some helper functions
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
* ensure pod copies always get their probes cleared
not wanting probes to be present is something we want
for all the debug profiles; so an easy place to implement
this is at the time of pod copy generation.
* ensure debug container in pod copy is added before the profile application
The way that the container list modification was defered causes the
debug container to be added after the profile applier runs. We now
make sure to have the container list modification happen before
the profile applier runs.
* make switch over pod copy, ephemeral, or node more clear
* use helper functions
added a helper function to modify a container out of a list that
matches the provided container name.
also added a helper function that adds capabilities to container
security.
* add tests for the debug profiles
* document new debugging profiles in command line help text
* add file header to profiles_test.go
* remove URL to KEP from help text
* move probe removal to the profiles
* remove mustNewProfileApplier in tests
* remove extra whiteline from import block
* remove isPodCopy helper func
* switch baselineProfile to using the modifyEphemeralContainer helper
* rename addCap to addCapability, and don't do deep copy
* fix godoc on modifyEphemeralContainer
* export DebugOptions.Applier for extensibility
* fix unit test
* fix spelling on overriden
* remove debugStyle facilities
* inline setHostNamespace helper func
* remove modifyContainer, modifyEphemeralContainer, and remove probes
their logic have been in-lined at call sites
* remove DebugApplierFunc convenience facility
* fix baseline profile implementation
it shouldn't have SYS_PTRACE base on
https://github.com/kubernetes/enhancements/tree/master/keps/sig-cli/1441-kubectl-debug#profile-baseline
* remove addCapability helper, in-lining at call sites
* address Arda's code review comments
1 use Bool instead of BoolPtr (now deprecated)
2 tweak for loop to continue when container name is not what we expect
3 use our knowledge on how the debug container is generated to simplify
our modification to the security context
4 use our knowledge on how the pod for node debugging is generated to no
longer explicit set pod's HostNework, HostPID and HostIPC fields to
false
* remove tricky defer in generatePodCopyWithDebugContainer
* provide helper functions to make debug profiles more readable
* add note to remind people about updating --profile's help text when adding new profiles
* Implement helper functions with names that improve readability
* add styleUnsupported to replace debugStyle(-1)
* fix godoc on modifyContainer
* drop style prefix from debugStyle values
* put VisitContainers in podutils & use that from debug
* cite source for ContainerType and VisitContainers
* pull in AllContainers ContainerType value
* have VisitContainer take pod spec rather than pod
* in-line modifyContainer
* unexport helper funcs
* put debugStyle at top of file
* merge profile_applier.go into profile.go
* tweak dropCapabilities
* fix allowProcessTracing & add a test for it
* drop mask param from help funcs, since we can already unambiguous identify the container by name
* fix grammar in code comment
---------
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
Co-authored-by: Jian Zeng <anonymousknight96@gmail.com>
Kubernetes-commit: d35da348c60a3c7505419741f2546ff8b0e38454
2023-02-09 12:18:22 -05:00
copied . Spec . Containers = append ( copied . Spec . Containers , corev1 . Container {
2020-10-30 13:23:34 -04:00
Name : name ,
TerminationMessagePolicy : corev1 . TerminationMessageReadFile ,
Implement kubectl debug profiles: general, baseline, and restricted (#114280)
* feat(debug): add more profiles
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
* feat(debug): implment serveral debugging profiles
Including `general`, `baseline` and `restricted`.
I plan to add more profiles afterwards, but I'd like to get early
reviews.
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
* test: add some basic tests
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
* chore: add some helper functions
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
* ensure pod copies always get their probes cleared
not wanting probes to be present is something we want
for all the debug profiles; so an easy place to implement
this is at the time of pod copy generation.
* ensure debug container in pod copy is added before the profile application
The way that the container list modification was defered causes the
debug container to be added after the profile applier runs. We now
make sure to have the container list modification happen before
the profile applier runs.
* make switch over pod copy, ephemeral, or node more clear
* use helper functions
added a helper function to modify a container out of a list that
matches the provided container name.
also added a helper function that adds capabilities to container
security.
* add tests for the debug profiles
* document new debugging profiles in command line help text
* add file header to profiles_test.go
* remove URL to KEP from help text
* move probe removal to the profiles
* remove mustNewProfileApplier in tests
* remove extra whiteline from import block
* remove isPodCopy helper func
* switch baselineProfile to using the modifyEphemeralContainer helper
* rename addCap to addCapability, and don't do deep copy
* fix godoc on modifyEphemeralContainer
* export DebugOptions.Applier for extensibility
* fix unit test
* fix spelling on overriden
* remove debugStyle facilities
* inline setHostNamespace helper func
* remove modifyContainer, modifyEphemeralContainer, and remove probes
their logic have been in-lined at call sites
* remove DebugApplierFunc convenience facility
* fix baseline profile implementation
it shouldn't have SYS_PTRACE base on
https://github.com/kubernetes/enhancements/tree/master/keps/sig-cli/1441-kubectl-debug#profile-baseline
* remove addCapability helper, in-lining at call sites
* address Arda's code review comments
1 use Bool instead of BoolPtr (now deprecated)
2 tweak for loop to continue when container name is not what we expect
3 use our knowledge on how the debug container is generated to simplify
our modification to the security context
4 use our knowledge on how the pod for node debugging is generated to no
longer explicit set pod's HostNework, HostPID and HostIPC fields to
false
* remove tricky defer in generatePodCopyWithDebugContainer
* provide helper functions to make debug profiles more readable
* add note to remind people about updating --profile's help text when adding new profiles
* Implement helper functions with names that improve readability
* add styleUnsupported to replace debugStyle(-1)
* fix godoc on modifyContainer
* drop style prefix from debugStyle values
* put VisitContainers in podutils & use that from debug
* cite source for ContainerType and VisitContainers
* pull in AllContainers ContainerType value
* have VisitContainer take pod spec rather than pod
* in-line modifyContainer
* unexport helper funcs
* put debugStyle at top of file
* merge profile_applier.go into profile.go
* tweak dropCapabilities
* fix allowProcessTracing & add a test for it
* drop mask param from help funcs, since we can already unambiguous identify the container by name
* fix grammar in code comment
---------
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
Co-authored-by: Jian Zeng <anonymousknight96@gmail.com>
Kubernetes-commit: d35da348c60a3c7505419741f2546ff8b0e38454
2023-02-09 12:18:22 -05:00
} )
c = & copied . Spec . Containers [ len ( copied . Spec . Containers ) - 1 ]
2020-10-30 13:23:34 -04:00
}
if len ( o . Args ) > 0 {
if o . ArgsOnly {
c . Args = o . Args
} else {
c . Command = o . Args
c . Args = nil
}
}
if len ( o . Env ) > 0 {
2020-04-12 13:58:36 -04:00
c . Env = o . Env
}
2020-10-30 13:23:34 -04:00
if len ( o . Image ) > 0 {
c . Image = o . Image
2020-04-12 13:58:36 -04:00
}
2020-10-30 13:23:34 -04:00
if len ( o . PullPolicy ) > 0 {
c . ImagePullPolicy = o . PullPolicy
2020-04-12 13:58:36 -04:00
}
2020-10-30 13:23:34 -04:00
c . Stdin = o . Interactive
c . TTY = o . TTY
Implement kubectl debug profiles: general, baseline, and restricted (#114280)
* feat(debug): add more profiles
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
* feat(debug): implment serveral debugging profiles
Including `general`, `baseline` and `restricted`.
I plan to add more profiles afterwards, but I'd like to get early
reviews.
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
* test: add some basic tests
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
* chore: add some helper functions
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
* ensure pod copies always get their probes cleared
not wanting probes to be present is something we want
for all the debug profiles; so an easy place to implement
this is at the time of pod copy generation.
* ensure debug container in pod copy is added before the profile application
The way that the container list modification was defered causes the
debug container to be added after the profile applier runs. We now
make sure to have the container list modification happen before
the profile applier runs.
* make switch over pod copy, ephemeral, or node more clear
* use helper functions
added a helper function to modify a container out of a list that
matches the provided container name.
also added a helper function that adds capabilities to container
security.
* add tests for the debug profiles
* document new debugging profiles in command line help text
* add file header to profiles_test.go
* remove URL to KEP from help text
* move probe removal to the profiles
* remove mustNewProfileApplier in tests
* remove extra whiteline from import block
* remove isPodCopy helper func
* switch baselineProfile to using the modifyEphemeralContainer helper
* rename addCap to addCapability, and don't do deep copy
* fix godoc on modifyEphemeralContainer
* export DebugOptions.Applier for extensibility
* fix unit test
* fix spelling on overriden
* remove debugStyle facilities
* inline setHostNamespace helper func
* remove modifyContainer, modifyEphemeralContainer, and remove probes
their logic have been in-lined at call sites
* remove DebugApplierFunc convenience facility
* fix baseline profile implementation
it shouldn't have SYS_PTRACE base on
https://github.com/kubernetes/enhancements/tree/master/keps/sig-cli/1441-kubectl-debug#profile-baseline
* remove addCapability helper, in-lining at call sites
* address Arda's code review comments
1 use Bool instead of BoolPtr (now deprecated)
2 tweak for loop to continue when container name is not what we expect
3 use our knowledge on how the debug container is generated to simplify
our modification to the security context
4 use our knowledge on how the pod for node debugging is generated to no
longer explicit set pod's HostNework, HostPID and HostIPC fields to
false
* remove tricky defer in generatePodCopyWithDebugContainer
* provide helper functions to make debug profiles more readable
* add note to remind people about updating --profile's help text when adding new profiles
* Implement helper functions with names that improve readability
* add styleUnsupported to replace debugStyle(-1)
* fix godoc on modifyContainer
* drop style prefix from debugStyle values
* put VisitContainers in podutils & use that from debug
* cite source for ContainerType and VisitContainers
* pull in AllContainers ContainerType value
* have VisitContainer take pod spec rather than pod
* in-line modifyContainer
* unexport helper funcs
* put debugStyle at top of file
* merge profile_applier.go into profile.go
* tweak dropCapabilities
* fix allowProcessTracing & add a test for it
* drop mask param from help funcs, since we can already unambiguous identify the container by name
* fix grammar in code comment
---------
Signed-off-by: Jian Zeng <anonymousknight96@gmail.com>
Co-authored-by: Jian Zeng <anonymousknight96@gmail.com>
Kubernetes-commit: d35da348c60a3c7505419741f2546ff8b0e38454
2023-02-09 12:18:22 -05:00
err := o . Applier . Apply ( copied , c . Name , pod )
2021-11-11 11:57:02 -05:00
if err != nil {
return nil , "" , err
}
2023-09-01 04:46:01 -04:00
if o . CustomProfile != nil {
err = o . applyCustomProfile ( copied , name )
if err != nil {
return nil , "" , err
}
}
2020-10-30 13:23:34 -04:00
return copied , name , nil
2020-04-12 13:58:36 -04:00
}
func ( o * DebugOptions ) computeDebugContainerName ( pod * corev1 . Pod ) string {
if len ( o . Container ) > 0 {
return o . Container
}
2023-02-10 02:21:15 -05:00
cn , containerByName := "" , containerNameToRef ( pod )
for len ( cn ) == 0 || ( containerByName [ cn ] != nil ) {
cn = fmt . Sprintf ( "debugger-%s" , nameSuffixFunc ( 5 ) )
}
if ! o . Quiet {
fmt . Fprintf ( o . Out , "Defaulting debug container name to %s.\n" , cn )
2020-04-12 13:58:36 -04:00
}
2023-02-10 02:21:15 -05:00
return cn
2020-04-12 13:58:36 -04:00
}
func containerNameToRef ( pod * corev1 . Pod ) map [ string ] * corev1 . Container {
names := map [ string ] * corev1 . Container { }
for i := range pod . Spec . Containers {
ref := & pod . Spec . Containers [ i ]
names [ ref . Name ] = ref
}
for i := range pod . Spec . InitContainers {
2020-09-06 13:43:21 -04:00
ref := & pod . Spec . InitContainers [ i ]
2020-04-12 13:58:36 -04:00
names [ ref . Name ] = ref
}
for i := range pod . Spec . EphemeralContainers {
2020-09-06 13:43:21 -04:00
ref := ( * corev1 . Container ) ( & pod . Spec . EphemeralContainers [ i ] . EphemeralContainerCommon )
2020-04-12 13:58:36 -04:00
names [ ref . Name ] = ref
}
return names
}
// waitForContainer watches the given pod until the container is running
2022-03-09 20:51:35 -05:00
func ( o * DebugOptions ) waitForContainer ( ctx context . Context , ns , podName , containerName string ) ( * corev1 . Pod , error ) {
2020-01-31 09:29:31 -05:00
// TODO: expose the timeout
ctx , cancel := watchtools . ContextWithOptionalTimeout ( ctx , 0 * time . Second )
defer cancel ( )
fieldSelector := fields . OneTermEqualSelector ( "metadata.name" , podName ) . String ( )
lw := & cache . ListWatch {
ListFunc : func ( options metav1 . ListOptions ) ( runtime . Object , error ) {
options . FieldSelector = fieldSelector
2022-03-09 20:51:35 -05:00
return o . podClient . Pods ( ns ) . List ( ctx , options )
2020-01-31 09:29:31 -05:00
} ,
WatchFunc : func ( options metav1 . ListOptions ) ( watch . Interface , error ) {
options . FieldSelector = fieldSelector
2022-03-09 20:51:35 -05:00
return o . podClient . Pods ( ns ) . Watch ( ctx , options )
2020-01-31 09:29:31 -05:00
} ,
}
intr := interrupt . New ( nil , cancel )
var result * corev1 . Pod
err := intr . Run ( func ( ) error {
2020-04-23 16:05:55 -04:00
ev , err := watchtools . UntilWithSync ( ctx , lw , & corev1 . Pod { } , nil , func ( ev watch . Event ) ( bool , error ) {
2022-03-09 20:51:35 -05:00
klog . V ( 2 ) . Infof ( "watch received event %q with object %T" , ev . Type , ev . Object )
2020-01-31 09:29:31 -05:00
switch ev . Type {
case watch . Deleted :
return false , errors . NewNotFound ( schema . GroupResource { Resource : "pods" } , "" )
}
p , ok := ev . Object . ( * corev1 . Pod )
if ! ok {
return false , fmt . Errorf ( "watch did not return a pod: %v" , ev . Object )
}
2020-04-12 13:58:36 -04:00
s := getContainerStatusByName ( p , containerName )
if s == nil {
return false , nil
}
klog . V ( 2 ) . Infof ( "debug container status is %v" , s )
if s . State . Running != nil || s . State . Terminated != nil {
return true , nil
2020-01-31 09:29:31 -05:00
}
2022-03-09 20:51:35 -05:00
if ! o . Quiet && s . State . Waiting != nil && s . State . Waiting . Message != "" {
2023-01-09 20:14:16 -05:00
o . WarningPrinter . Print ( fmt . Sprintf ( "container %s: %s" , containerName , s . State . Waiting . Message ) )
2022-03-09 20:51:35 -05:00
}
2020-01-31 09:29:31 -05:00
return false , nil
} )
if ev != nil {
result = ev . Object . ( * corev1 . Pod )
}
return err
} )
return result , err
}
2023-07-24 08:28:21 -04:00
func ( o * DebugOptions ) handleAttachPod ( ctx context . Context , restClientGetter genericclioptions . RESTClientGetter , cmdPath string , ns , podName , containerName string ) error {
opts := & attach . AttachOptions {
StreamOptions : exec . StreamOptions {
IOStreams : o . IOStreams ,
Stdin : o . Interactive ,
TTY : o . TTY ,
Quiet : o . Quiet ,
} ,
CommandName : cmdPath + " attach" ,
Attach : & attach . DefaultRemoteAttach { } ,
}
config , err := restClientGetter . ToRESTConfig ( )
if err != nil {
return err
}
opts . Config = config
opts . AttachFunc = attach . DefaultAttachFunc
2022-03-09 20:51:35 -05:00
pod , err := o . waitForContainer ( ctx , ns , podName , containerName )
2020-01-31 09:29:31 -05:00
if err != nil {
return err
}
opts . Namespace = ns
opts . Pod = pod
opts . PodName = podName
2020-04-12 13:58:36 -04:00
opts . ContainerName = containerName
2020-01-31 09:29:31 -05:00
if opts . AttachFunc == nil {
opts . AttachFunc = attach . DefaultAttachFunc
}
2020-04-12 13:58:36 -04:00
status := getContainerStatusByName ( pod , containerName )
if status == nil {
// impossible path
2020-10-30 13:23:34 -04:00
return fmt . Errorf ( "error getting container status of container name %q: %+v" , containerName , err )
2020-01-31 09:29:31 -05:00
}
if status . State . Terminated != nil {
klog . V ( 1 ) . Info ( "Ephemeral container terminated, falling back to logs" )
2024-10-22 14:49:06 -04:00
return logOpts ( ctx , restClientGetter , pod , opts )
2020-01-31 09:29:31 -05:00
}
if err := opts . Run ( ) ; err != nil {
2022-06-24 03:07:44 -04:00
fmt . Fprintf ( opts . ErrOut , "warning: couldn't attach to pod/%s, falling back to streaming logs: %v\n" , podName , err )
2024-10-22 14:49:06 -04:00
return logOpts ( ctx , restClientGetter , pod , opts )
2020-01-31 09:29:31 -05:00
}
return nil
}
2020-04-12 13:58:36 -04:00
func getContainerStatusByName ( pod * corev1 . Pod , containerName string ) * corev1 . ContainerStatus {
allContainerStatus := [ ] [ ] corev1 . ContainerStatus { pod . Status . InitContainerStatuses , pod . Status . ContainerStatuses , pod . Status . EphemeralContainerStatuses }
for _ , statusSlice := range allContainerStatus {
for i := range statusSlice {
if statusSlice [ i ] . Name == containerName {
return & statusSlice [ i ]
}
}
}
return nil
}
2020-01-31 09:29:31 -05:00
// logOpts logs output from opts to the pods log.
2024-10-22 14:49:06 -04:00
func logOpts ( ctx context . Context , restClientGetter genericclioptions . RESTClientGetter , pod * corev1 . Pod , opts * attach . AttachOptions ) error {
2020-01-31 09:29:31 -05:00
ctrName , err := opts . GetContainerName ( pod )
if err != nil {
return err
}
requests , err := polymorphichelpers . LogsForObjectFn ( restClientGetter , pod , & corev1 . PodLogOptions { Container : ctrName } , opts . GetPodTimeout , false )
if err != nil {
return err
}
for _ , request := range requests {
2024-10-22 14:49:06 -04:00
if err := logs . DefaultConsumeRequest ( ctx , request , opts . Out ) ; err != nil {
2020-01-31 09:29:31 -05:00
return err
}
}
return nil
}