portforward.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package portforward
  14. import (
  15. "fmt"
  16. "net/http"
  17. "net/url"
  18. "os"
  19. "os/signal"
  20. "strconv"
  21. "strings"
  22. "time"
  23. "github.com/spf13/cobra"
  24. corev1 "k8s.io/api/core/v1"
  25. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  26. "k8s.io/cli-runtime/pkg/genericclioptions"
  27. "k8s.io/client-go/kubernetes/scheme"
  28. corev1client "k8s.io/client-go/kubernetes/typed/core/v1"
  29. restclient "k8s.io/client-go/rest"
  30. "k8s.io/client-go/tools/portforward"
  31. "k8s.io/client-go/transport/spdy"
  32. cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
  33. "k8s.io/kubernetes/pkg/kubectl/polymorphichelpers"
  34. "k8s.io/kubernetes/pkg/kubectl/util"
  35. "k8s.io/kubernetes/pkg/kubectl/util/i18n"
  36. "k8s.io/kubernetes/pkg/kubectl/util/templates"
  37. )
  38. // PortForwardOptions contains all the options for running the port-forward cli command.
  39. type PortForwardOptions struct {
  40. Namespace string
  41. PodName string
  42. RESTClient *restclient.RESTClient
  43. Config *restclient.Config
  44. PodClient corev1client.PodsGetter
  45. Address []string
  46. Ports []string
  47. PortForwarder portForwarder
  48. StopChannel chan struct{}
  49. ReadyChannel chan struct{}
  50. }
  51. var (
  52. portforwardLong = templates.LongDesc(i18n.T(`
  53. Forward one or more local ports to a pod. This command requires the node to have 'socat' installed.
  54. Use resource type/name such as deployment/mydeployment to select a pod. Resource type defaults to 'pod' if omitted.
  55. If there are multiple pods matching the criteria, a pod will be selected automatically. The
  56. forwarding session ends when the selected pod terminates, and rerun of the command is needed
  57. to resume forwarding.`))
  58. portforwardExample = templates.Examples(i18n.T(`
  59. # Listen on ports 5000 and 6000 locally, forwarding data to/from ports 5000 and 6000 in the pod
  60. kubectl port-forward pod/mypod 5000 6000
  61. # Listen on ports 5000 and 6000 locally, forwarding data to/from ports 5000 and 6000 in a pod selected by the deployment
  62. kubectl port-forward deployment/mydeployment 5000 6000
  63. # Listen on ports 5000 and 6000 locally, forwarding data to/from ports 5000 and 6000 in a pod selected by the service
  64. kubectl port-forward service/myservice 5000 6000
  65. # Listen on port 8888 locally, forwarding to 5000 in the pod
  66. kubectl port-forward pod/mypod 8888:5000
  67. # Listen on port 8888 on all addresses, forwarding to 5000 in the pod
  68. kubectl port-forward --address 0.0.0.0 pod/mypod 8888:5000
  69. # Listen on port 8888 on localhost and selected IP, forwarding to 5000 in the pod
  70. kubectl port-forward --address localhost,10.19.21.23 pod/mypod 8888:5000
  71. # Listen on a random port locally, forwarding to 5000 in the pod
  72. kubectl port-forward pod/mypod :5000`))
  73. )
  74. const (
  75. // Amount of time to wait until at least one pod is running
  76. defaultPodPortForwardWaitTimeout = 60 * time.Second
  77. )
  78. func NewCmdPortForward(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {
  79. opts := &PortForwardOptions{
  80. PortForwarder: &defaultPortForwarder{
  81. IOStreams: streams,
  82. },
  83. }
  84. cmd := &cobra.Command{
  85. Use: "port-forward TYPE/NAME [options] [LOCAL_PORT:]REMOTE_PORT [...[LOCAL_PORT_N:]REMOTE_PORT_N]",
  86. DisableFlagsInUseLine: true,
  87. Short: i18n.T("Forward one or more local ports to a pod"),
  88. Long: portforwardLong,
  89. Example: portforwardExample,
  90. Run: func(cmd *cobra.Command, args []string) {
  91. if err := opts.Complete(f, cmd, args); err != nil {
  92. cmdutil.CheckErr(err)
  93. }
  94. if err := opts.Validate(); err != nil {
  95. cmdutil.CheckErr(cmdutil.UsageErrorf(cmd, "%v", err.Error()))
  96. }
  97. if err := opts.RunPortForward(); err != nil {
  98. cmdutil.CheckErr(err)
  99. }
  100. },
  101. }
  102. cmdutil.AddPodRunningTimeoutFlag(cmd, defaultPodPortForwardWaitTimeout)
  103. cmd.Flags().StringSliceVar(&opts.Address, "address", []string{"localhost"}, "Addresses to listen on (comma separated). Only accepts IP addresses or localhost as a value. When localhost is supplied, kubectl will try to bind on both 127.0.0.1 and ::1 and will fail if neither of these addresses are available to bind.")
  104. // TODO support UID
  105. return cmd
  106. }
  107. type portForwarder interface {
  108. ForwardPorts(method string, url *url.URL, opts PortForwardOptions) error
  109. }
  110. type defaultPortForwarder struct {
  111. genericclioptions.IOStreams
  112. }
  113. func (f *defaultPortForwarder) ForwardPorts(method string, url *url.URL, opts PortForwardOptions) error {
  114. transport, upgrader, err := spdy.RoundTripperFor(opts.Config)
  115. if err != nil {
  116. return err
  117. }
  118. dialer := spdy.NewDialer(upgrader, &http.Client{Transport: transport}, method, url)
  119. fw, err := portforward.NewOnAddresses(dialer, opts.Address, opts.Ports, opts.StopChannel, opts.ReadyChannel, f.Out, f.ErrOut)
  120. if err != nil {
  121. return err
  122. }
  123. return fw.ForwardPorts()
  124. }
  125. // splitPort splits port string which is in form of [LOCAL PORT]:REMOTE PORT
  126. // and returns local and remote ports separately
  127. func splitPort(port string) (local, remote string) {
  128. parts := strings.Split(port, ":")
  129. if len(parts) == 2 {
  130. return parts[0], parts[1]
  131. }
  132. return parts[0], parts[0]
  133. }
  134. // Translates service port to target port
  135. // It rewrites ports as needed if the Service port declares targetPort.
  136. // It returns an error when a named targetPort can't find a match in the pod, or the Service did not declare
  137. // the port.
  138. func translateServicePortToTargetPort(ports []string, svc corev1.Service, pod corev1.Pod) ([]string, error) {
  139. var translated []string
  140. for _, port := range ports {
  141. localPort, remotePort := splitPort(port)
  142. portnum, err := strconv.Atoi(remotePort)
  143. if err != nil {
  144. svcPort, err := util.LookupServicePortNumberByName(svc, remotePort)
  145. if err != nil {
  146. return nil, err
  147. }
  148. portnum = int(svcPort)
  149. if localPort == remotePort {
  150. localPort = strconv.Itoa(portnum)
  151. }
  152. }
  153. containerPort, err := util.LookupContainerPortNumberByServicePort(svc, pod, int32(portnum))
  154. if err != nil {
  155. // can't resolve a named port, or Service did not declare this port, return an error
  156. return nil, err
  157. }
  158. if int32(portnum) != containerPort {
  159. translated = append(translated, fmt.Sprintf("%s:%d", localPort, containerPort))
  160. } else {
  161. translated = append(translated, port)
  162. }
  163. }
  164. return translated, nil
  165. }
  166. // convertPodNamedPortToNumber converts named ports into port numbers
  167. // It returns an error when a named port can't be found in the pod containers
  168. func convertPodNamedPortToNumber(ports []string, pod corev1.Pod) ([]string, error) {
  169. var converted []string
  170. for _, port := range ports {
  171. localPort, remotePort := splitPort(port)
  172. containerPortStr := remotePort
  173. _, err := strconv.Atoi(remotePort)
  174. if err != nil {
  175. containerPort, err := util.LookupContainerPortNumberByName(pod, remotePort)
  176. if err != nil {
  177. return nil, err
  178. }
  179. containerPortStr = strconv.Itoa(int(containerPort))
  180. }
  181. if localPort != remotePort {
  182. converted = append(converted, fmt.Sprintf("%s:%s", localPort, containerPortStr))
  183. } else {
  184. converted = append(converted, containerPortStr)
  185. }
  186. }
  187. return converted, nil
  188. }
  189. // Complete completes all the required options for port-forward cmd.
  190. func (o *PortForwardOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {
  191. var err error
  192. if len(args) < 2 {
  193. return cmdutil.UsageErrorf(cmd, "TYPE/NAME and list of ports are required for port-forward")
  194. }
  195. o.Namespace, _, err = f.ToRawKubeConfigLoader().Namespace()
  196. if err != nil {
  197. return err
  198. }
  199. builder := f.NewBuilder().
  200. WithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).
  201. ContinueOnError().
  202. NamespaceParam(o.Namespace).DefaultNamespace()
  203. getPodTimeout, err := cmdutil.GetPodRunningTimeoutFlag(cmd)
  204. if err != nil {
  205. return cmdutil.UsageErrorf(cmd, err.Error())
  206. }
  207. resourceName := args[0]
  208. builder.ResourceNames("pods", resourceName)
  209. obj, err := builder.Do().Object()
  210. if err != nil {
  211. return err
  212. }
  213. forwardablePod, err := polymorphichelpers.AttachablePodForObjectFn(f, obj, getPodTimeout)
  214. if err != nil {
  215. return err
  216. }
  217. o.PodName = forwardablePod.Name
  218. // handle service port mapping to target port if needed
  219. switch t := obj.(type) {
  220. case *corev1.Service:
  221. o.Ports, err = translateServicePortToTargetPort(args[1:], *t, *forwardablePod)
  222. if err != nil {
  223. return err
  224. }
  225. default:
  226. o.Ports, err = convertPodNamedPortToNumber(args[1:], *forwardablePod)
  227. if err != nil {
  228. return err
  229. }
  230. }
  231. clientset, err := f.KubernetesClientSet()
  232. if err != nil {
  233. return err
  234. }
  235. o.PodClient = clientset.CoreV1()
  236. o.Config, err = f.ToRESTConfig()
  237. if err != nil {
  238. return err
  239. }
  240. o.RESTClient, err = f.RESTClient()
  241. if err != nil {
  242. return err
  243. }
  244. o.StopChannel = make(chan struct{}, 1)
  245. o.ReadyChannel = make(chan struct{})
  246. return nil
  247. }
  248. // Validate validates all the required options for port-forward cmd.
  249. func (o PortForwardOptions) Validate() error {
  250. if len(o.PodName) == 0 {
  251. return fmt.Errorf("pod name or resource type/name must be specified")
  252. }
  253. if len(o.Ports) < 1 {
  254. return fmt.Errorf("at least 1 PORT is required for port-forward")
  255. }
  256. if o.PortForwarder == nil || o.PodClient == nil || o.RESTClient == nil || o.Config == nil {
  257. return fmt.Errorf("client, client config, restClient, and portforwarder must be provided")
  258. }
  259. return nil
  260. }
  261. // RunPortForward implements all the necessary functionality for port-forward cmd.
  262. func (o PortForwardOptions) RunPortForward() error {
  263. pod, err := o.PodClient.Pods(o.Namespace).Get(o.PodName, metav1.GetOptions{})
  264. if err != nil {
  265. return err
  266. }
  267. if pod.Status.Phase != corev1.PodRunning {
  268. return fmt.Errorf("unable to forward port because pod is not running. Current status=%v", pod.Status.Phase)
  269. }
  270. signals := make(chan os.Signal, 1)
  271. signal.Notify(signals, os.Interrupt)
  272. defer signal.Stop(signals)
  273. go func() {
  274. <-signals
  275. if o.StopChannel != nil {
  276. close(o.StopChannel)
  277. }
  278. }()
  279. req := o.RESTClient.Post().
  280. Resource("pods").
  281. Namespace(o.Namespace).
  282. Name(pod.Name).
  283. SubResource("portforward")
  284. return o.PortForwarder.ForwardPorts("POST", req.URL(), o)
  285. }