func RunProxy(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command) error { port := cmdutil.GetFlagInt(cmd, "port") fmt.Fprintf(out, "Starting to serve on localhost:%d", port) clientConfig, err := f.ClientConfig() if err != nil { return err } staticPrefix := cmdutil.GetFlagString(cmd, "www-prefix") if !strings.HasSuffix(staticPrefix, "/") { staticPrefix += "/" } apiProxyPrefix := cmdutil.GetFlagString(cmd, "api-prefix") if !strings.HasSuffix(apiProxyPrefix, "/") { apiProxyPrefix += "/" } server, err := kubectl.NewProxyServer(cmdutil.GetFlagString(cmd, "www"), apiProxyPrefix, staticPrefix, clientConfig) if err != nil { return err } glog.Fatal(server.Serve(port)) return nil }
// Complete verifies command line arguments and loads data from the command environment func (p *AttachOptions) Complete(f *cmdutil.Factory, cmd *cobra.Command, argsIn []string) error { if len(argsIn) == 0 { return cmdutil.UsageError(cmd, "POD is required for attach") } if len(argsIn) > 1 { return cmdutil.UsageError(cmd, fmt.Sprintf("expected a single argument: POD, saw %d: %s", len(argsIn), argsIn)) } p.PodName = argsIn[0] namespace, _, err := f.DefaultNamespace() if err != nil { return err } p.Namespace = namespace config, err := f.ClientConfig() if err != nil { return err } p.Config = config client, err := f.Client() if err != nil { return err } p.Client = client return nil }
func RunPortForward(f *cmdutil.Factory, cmd *cobra.Command, args []string) error { podName := cmdutil.GetFlagString(cmd, "pod") if len(podName) == 0 { return cmdutil.UsageError(cmd, "POD is required for exec") } if len(args) < 1 { return cmdutil.UsageError(cmd, "at least 1 PORT is required for port-forward") } namespace, err := f.DefaultNamespace() if err != nil { return err } client, err := f.Client() if err != nil { return err } pod, err := client.Pods(namespace).Get(podName) if err != nil { return err } if pod.Status.Phase != api.PodRunning { glog.Fatalf("Unable to execute command because pod is not running. Current status=%v", pod.Status.Phase) } config, err := f.ClientConfig() if err != nil { return err } signals := make(chan os.Signal, 1) signal.Notify(signals, os.Interrupt) defer signal.Stop(signals) stopCh := make(chan struct{}, 1) go func() { <-signals close(stopCh) }() req := client.RESTClient.Get(). Prefix("proxy"). Resource("nodes"). Name(pod.Spec.Host). Suffix("portForward", namespace, podName) pf, err := portforward.New(req, config, args, stopCh) if err != nil { return err } return pf.ForwardPorts() }
func RunClusterInfo(factory *cmdutil.Factory, out io.Writer, cmd *cobra.Command) error { if os.Args[1] == "clusterinfo" { printDeprecationWarning("cluster-info", "clusterinfo") } client, err := factory.ClientConfig() if err != nil { return err } printService(out, "Kubernetes master", client.Host) mapper, typer := factory.Object() cmdNamespace := cmdutil.GetFlagString(cmd, "namespace") if cmdNamespace == "" { cmdNamespace = api.NamespaceSystem } // TODO use generalized labels once they are implemented (#341) b := resource.NewBuilder(mapper, typer, factory.ClientMapperForCommand()). NamespaceParam(cmdNamespace).DefaultNamespace(). SelectorParam("kubernetes.io/cluster-service=true"). ResourceTypeOrNameArgs(false, []string{"services"}...). Latest() b.Do().Visit(func(r *resource.Info) error { services := r.Object.(*api.ServiceList).Items for _, service := range services { var link string if len(service.Status.LoadBalancer.Ingress) > 0 { ingress := service.Status.LoadBalancer.Ingress[0] ip := ingress.IP if ip == "" { ip = ingress.Hostname } for _, port := range service.Spec.Ports { link += "http://" + ip + ":" + strconv.Itoa(port.Port) + " " } } else { link = client.Host + "/api/" + client.Version + "/proxy/namespaces/" + service.ObjectMeta.Namespace + "/services/" + service.ObjectMeta.Name } name := service.ObjectMeta.Labels["kubernetes.io/name"] if len(name) == 0 { name = service.ObjectMeta.Name } printService(out, name, link) } return nil }) return nil // TODO consider printing more information about cluster }
func RunProxy(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command) error { port := cmdutil.GetFlagInt(cmd, "port") clientConfig, err := f.ClientConfig() if err != nil { return err } staticPrefix := cmdutil.GetFlagString(cmd, "www-prefix") if !strings.HasSuffix(staticPrefix, "/") { staticPrefix += "/" } apiProxyPrefix := cmdutil.GetFlagString(cmd, "api-prefix") if !strings.HasSuffix(apiProxyPrefix, "/") { apiProxyPrefix += "/" } filter := &kubectl.FilterServer{ AcceptPaths: kubectl.MakeRegexpArrayOrDie(cmdutil.GetFlagString(cmd, "accept-paths")), RejectPaths: kubectl.MakeRegexpArrayOrDie(cmdutil.GetFlagString(cmd, "reject-paths")), AcceptHosts: kubectl.MakeRegexpArrayOrDie(cmdutil.GetFlagString(cmd, "accept-hosts")), } if cmdutil.GetFlagBool(cmd, "disable-filter") { glog.Warning("Request filter disabled, your proxy is vulnerable to XSRF attacks, please be cautious") filter = nil } server, err := kubectl.NewProxyServer(port, cmdutil.GetFlagString(cmd, "www"), apiProxyPrefix, staticPrefix, filter, clientConfig) if err != nil { return err } // Separate listening from serving so we can report the bound port // when it is chosen by os (port == 0) l, err := server.Listen() if err != nil { glog.Fatal(err) } fmt.Fprintf(out, "Starting to serve on %s", l.Addr().String()) glog.Fatal(server.ServeOnListener(l)) return nil }
func RunClusterInfo(factory *cmdutil.Factory, out io.Writer, cmd *cobra.Command) error { if os.Args[1] == "clusterinfo" { printDeprecationWarning("cluster-info", "clusterinfo") } client, err := factory.ClientConfig() if err != nil { return err } printService(out, "Kubernetes master", client.Host, false) mapper, typer := factory.Object() cmdNamespace, err := factory.DefaultNamespace() if err != nil { return err } // TODO use generalized labels once they are implemented (#341) b := resource.NewBuilder(mapper, typer, factory.ClientMapperForCommand()). NamespaceParam(cmdNamespace).DefaultNamespace(). SelectorParam("kubernetes.io/cluster-service=true"). ResourceTypeOrNameArgs(false, []string{"services"}...). Latest() b.Do().Visit(func(r *resource.Info) error { services := r.Object.(*api.ServiceList).Items for _, service := range services { splittedLink := strings.Split(strings.Split(service.ObjectMeta.SelfLink, "?")[0], "/") // insert "proxy" into the link splittedLink = append(splittedLink, "") copy(splittedLink[4:], splittedLink[3:]) splittedLink[3] = "proxy" link := client.Host + strings.Join(splittedLink, "/") + "/" printService(out, service.ObjectMeta.Labels["name"], link, true) } return nil }) return nil // TODO consider printing more information about cluster }
// Complete verifies command line arguments and loads data from the command environment func (p *ExecOptions) Complete(f *cmdutil.Factory, cmd *cobra.Command, argsIn []string) error { if len(p.PodName) == 0 && len(argsIn) == 0 { return cmdutil.UsageError(cmd, "POD is required for exec") } if len(p.PodName) != 0 { printDeprecationWarning("exec POD", "-p POD") if len(argsIn) < 1 { return cmdutil.UsageError(cmd, "COMMAND is required for exec") } p.Command = argsIn } else { p.PodName = argsIn[0] p.Command = argsIn[1:] if len(p.Command) < 1 { return cmdutil.UsageError(cmd, "COMMAND is required for exec") } } namespace, _, err := f.DefaultNamespace() if err != nil { return err } p.Namespace = namespace config, err := f.ClientConfig() if err != nil { return err } p.Config = config client, err := f.Client() if err != nil { return err } p.Client = client return nil }
func RunProxy(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command) error { port := cmdutil.GetFlagInt(cmd, "port") fmt.Fprintf(out, "Starting to serve on localhost:%d", port) clientConfig, err := f.ClientConfig() if err != nil { return err } staticPrefix := cmdutil.GetFlagString(cmd, "www-prefix") if !strings.HasSuffix(staticPrefix, "/") { staticPrefix += "/" } apiProxyPrefix := cmdutil.GetFlagString(cmd, "api-prefix") if !strings.HasSuffix(apiProxyPrefix, "/") { apiProxyPrefix += "/" } filter := &kubectl.FilterServer{ AcceptPaths: kubectl.MakeRegexpArrayOrDie(cmdutil.GetFlagString(cmd, "accept-paths")), RejectPaths: kubectl.MakeRegexpArrayOrDie(cmdutil.GetFlagString(cmd, "reject-paths")), AcceptHosts: kubectl.MakeRegexpArrayOrDie(cmdutil.GetFlagString(cmd, "accept-hosts")), } if cmdutil.GetFlagBool(cmd, "disable-filter") { glog.Warning("Request filter disabled, your proxy is vulnerable to XSRF attacks, please be cautious") filter = nil } server, err := kubectl.NewProxyServer(cmdutil.GetFlagString(cmd, "www"), apiProxyPrefix, staticPrefix, filter, clientConfig) if err != nil { return err } glog.Fatal(server.Serve(port)) return nil }
func RunExec(f *cmdutil.Factory, cmd *cobra.Command, cmdIn io.Reader, cmdOut, cmdErr io.Writer, p *execParams, args []string, re remoteExecutor) error { if len(p.podName) == 0 { return cmdutil.UsageError(cmd, "POD is required for exec") } if len(args) < 1 { return cmdutil.UsageError(cmd, "COMMAND is required for exec") } namespace, err := f.DefaultNamespace() if err != nil { return err } client, err := f.Client() if err != nil { return err } pod, err := client.Pods(namespace).Get(p.podName) if err != nil { return err } if pod.Status.Phase != api.PodRunning { glog.Fatalf("Unable to execute command because pod is not running. Current status=%v", pod.Status.Phase) } containerName := p.containerName if len(containerName) == 0 { containerName = pod.Spec.Containers[0].Name } var stdin io.Reader tty := p.tty if p.stdin { stdin = cmdIn if tty { if file, ok := cmdIn.(*os.File); ok { inFd := file.Fd() if term.IsTerminal(inFd) { oldState, err := term.SetRawTerminal(inFd) if err != nil { glog.Fatal(err) } // this handles a clean exit, where the command finished defer term.RestoreTerminal(inFd, oldState) // SIGINT is handled by term.SetRawTerminal (it runs a goroutine that listens // for SIGINT and restores the terminal before exiting) // this handles SIGTERM sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, syscall.SIGTERM) go func() { <-sigChan term.RestoreTerminal(inFd, oldState) os.Exit(0) }() } else { glog.Warning("Stdin is not a terminal") } } else { tty = false glog.Warning("Unable to use a TTY") } } } config, err := f.ClientConfig() if err != nil { return err } req := client.RESTClient.Get(). Resource("pods"). Name(pod.Name). Namespace(namespace). SubResource("exec"). Param("container", containerName) return re.Execute(req, config, args, stdin, cmdOut, cmdErr, tty) }
func RunPortForward(f *cmdutil.Factory, cmd *cobra.Command, args []string, fw portForwarder) error { podName := cmdutil.GetFlagString(cmd, "pod") if len(podName) == 0 { return cmdutil.UsageError(cmd, "POD is required for exec") } if len(args) < 1 { return cmdutil.UsageError(cmd, "at least 1 PORT is required for port-forward") } namespace, _, err := f.DefaultNamespace() if err != nil { return err } client, err := f.Client() if err != nil { return err } pod, err := client.Pods(namespace).Get(podName) if err != nil { return err } if pod.Status.Phase != api.PodRunning { glog.Fatalf("Unable to execute command because pod is not running. Current status=%v", pod.Status.Phase) } config, err := f.ClientConfig() if err != nil { return err } signals := make(chan os.Signal, 1) signal.Notify(signals, os.Interrupt) defer signal.Stop(signals) stopCh := make(chan struct{}, 1) go func() { <-signals close(stopCh) }() req := client.RESTClient.Post(). Resource("pods"). Namespace(namespace). Name(pod.Name). SubResource("portforward") postErr := fw.ForwardPorts(req, config, args, stopCh) // if we don't have an error, return. If we did get an error, try a GET because v3.0.0 shipped with port-forward running as a GET. if postErr == nil { return nil } // only try the get if the error is either a forbidden or method not supported, otherwise trying with a GET probably won't help if !apierrors.IsForbidden(postErr) && !apierrors.IsMethodNotSupported(postErr) { return postErr } getReq := client.RESTClient.Get(). Resource("pods"). Namespace(namespace). Name(pod.Name). SubResource("portforward") getErr := fw.ForwardPorts(getReq, config, args, stopCh) if getErr == nil { return nil } // if we got a getErr, return the postErr because it's more likely to be correct. GET is legacy return postErr }
// RunGet implements the generic Get command // TODO: convert all direct flag accessors to a struct and pass that instead of cmd func RunGet(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) error { selector := cmdutil.GetFlagString(cmd, "selector") allNamespaces := cmdutil.GetFlagBool(cmd, "all-namespaces") mapper, typer := f.Object() cmdNamespace, _, err := f.DefaultNamespace() if err != nil { return err } if len(args) == 0 { fmt.Fprint(out, ` You must specify the type of resource to get. Valid resource types include: * pods (aka 'po') * replicationcontrollers (aka 'rc') * services * nodes (aka 'no') * events (aka 'ev') * secrets * limits * persistentVolumes (aka 'pv') * persistentVolumeClaims (aka 'pvc') * quota `) return errors.New("Required resource not specified.") } // handle watch separately since we cannot watch multiple resource types isWatch, isWatchOnly := cmdutil.GetFlagBool(cmd, "watch"), cmdutil.GetFlagBool(cmd, "watch-only") if isWatch || isWatchOnly { r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()). NamespaceParam(cmdNamespace).DefaultNamespace().AllNamespaces(allNamespaces). SelectorParam(selector). ResourceTypeOrNameArgs(true, args...). SingleResourceType(). Do() if err != nil { return err } mapping, err := r.ResourceMapping() if err != nil { return err } printer, err := f.PrinterForMapping(cmd, mapping, allNamespaces) if err != nil { return err } obj, err := r.Object() if err != nil { return err } rv, err := mapping.MetadataAccessor.ResourceVersion(obj) if err != nil { return err } // print the current object if !isWatchOnly { if err := printer.PrintObj(obj, out); err != nil { return fmt.Errorf("unable to output the provided object: %v", err) } } // print watched changes w, err := r.Watch(rv) if err != nil { return err } kubectl.WatchLoop(w, func(e watch.Event) error { return printer.PrintObj(e.Object, out) }) return nil } b := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()). NamespaceParam(cmdNamespace).DefaultNamespace().AllNamespaces(allNamespaces). SelectorParam(selector). ResourceTypeOrNameArgs(true, args...). ContinueOnError(). Latest() printer, generic, err := cmdutil.PrinterForCommand(cmd) if err != nil { return err } if generic { clientConfig, err := f.ClientConfig() if err != nil { return err } defaultVersion := clientConfig.Version singular := false r := b.Flatten().Do() infos, err := r.IntoSingular(&singular).Infos() if err != nil { return err } // the outermost object will be converted to the output-version, but inner // objects can use their mappings version := cmdutil.OutputVersion(cmd, defaultVersion) obj, err := resource.AsVersionedObject(infos, !singular, version) if err != nil { return err } return printer.PrintObj(obj, out) } // use the default printer for each object return b.Do().Visit(func(r *resource.Info) error { printer, err := f.PrinterForMapping(cmd, r.Mapping, allNamespaces) if err != nil { return err } return printer.PrintObj(r.Object, out) }) }
func RunExec(f *cmdutil.Factory, cmd *cobra.Command, cmdIn io.Reader, cmdOut, cmdErr io.Writer, p *execParams, argsIn []string, re remoteExecutor) error { podName, containerName, args, err := extractPodAndContainer(cmd, argsIn, p) namespace, _, err := f.DefaultNamespace() if err != nil { return err } client, err := f.Client() if err != nil { return err } pod, err := client.Pods(namespace).Get(podName) if err != nil { return err } if pod.Status.Phase != api.PodRunning { glog.Fatalf("Unable to execute command because pod %s is not running. Current status=%v", podName, pod.Status.Phase) } if len(containerName) == 0 { glog.V(4).Infof("defaulting container name to %s", pod.Spec.Containers[0].Name) containerName = pod.Spec.Containers[0].Name } var stdin io.Reader tty := p.tty if p.stdin { stdin = cmdIn if tty { if file, ok := cmdIn.(*os.File); ok { inFd := file.Fd() if term.IsTerminal(inFd) { oldState, err := term.SetRawTerminal(inFd) if err != nil { glog.Fatal(err) } // this handles a clean exit, where the command finished defer term.RestoreTerminal(inFd, oldState) // SIGINT is handled by term.SetRawTerminal (it runs a goroutine that listens // for SIGINT and restores the terminal before exiting) // this handles SIGTERM sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, syscall.SIGTERM) go func() { <-sigChan term.RestoreTerminal(inFd, oldState) os.Exit(0) }() } else { glog.Warning("Stdin is not a terminal") } } else { tty = false glog.Warning("Unable to use a TTY") } } } config, err := f.ClientConfig() if err != nil { return err } req := client.RESTClient.Post(). Resource("pods"). Name(pod.Name). Namespace(namespace). SubResource("exec"). Param("container", containerName) postErr := re.Execute(req, config, args, stdin, cmdOut, cmdErr, tty) // if we don't have an error, return. If we did get an error, try a GET because v3.0.0 shipped with exec running as a GET. if postErr == nil { return nil } // only try the get if the error is either a forbidden or method not supported, otherwise trying with a GET probably won't help if !apierrors.IsForbidden(postErr) && !apierrors.IsMethodNotSupported(postErr) { return postErr } getReq := client.RESTClient.Get(). Resource("pods"). Name(pod.Name). Namespace(namespace). SubResource("exec"). Param("container", containerName) getErr := re.Execute(getReq, config, args, stdin, cmdOut, cmdErr, tty) if getErr == nil { return nil } // if we got a getErr, return the postErr because it's more likely to be correct. GET is legacy return postErr }
// RunGet implements the generic Get command // TODO: convert all direct flag accessors to a struct and pass that instead of cmd func RunGet(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) error { selector := cmdutil.GetFlagString(cmd, "selector") mapper, typer := f.Object() cmdNamespace, err := f.DefaultNamespace() if err != nil { return err } // handle watch separately since we cannot watch multiple resource types isWatch, isWatchOnly := cmdutil.GetFlagBool(cmd, "watch"), cmdutil.GetFlagBool(cmd, "watch-only") if isWatch || isWatchOnly { r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()). NamespaceParam(cmdNamespace).DefaultNamespace(). SelectorParam(selector). ResourceTypeOrNameArgs(true, args...). SingleResourceType(). Do() if err != nil { return err } mapping, err := r.ResourceMapping() if err != nil { return err } printer, err := f.PrinterForMapping(cmd, mapping) if err != nil { return err } obj, err := r.Object() if err != nil { return err } rv, err := mapping.MetadataAccessor.ResourceVersion(obj) if err != nil { return err } // print the current object if !isWatchOnly { if err := printer.PrintObj(obj, out); err != nil { return fmt.Errorf("unable to output the provided object: %v", err) } } // print watched changes w, err := r.Watch(rv) if err != nil { return err } kubectl.WatchLoop(w, func(e watch.Event) error { return printer.PrintObj(e.Object, out) }) return nil } b := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()). NamespaceParam(cmdNamespace).DefaultNamespace(). SelectorParam(selector). ResourceTypeOrNameArgs(true, args...). ContinueOnError(). Latest() printer, generic, err := cmdutil.PrinterForCommand(cmd) if err != nil { return err } if generic { clientConfig, err := f.ClientConfig() if err != nil { return err } defaultVersion := clientConfig.Version singular := false r := b.Flatten().Do() infos, err := r.IntoSingular(&singular).Infos() if err != nil { return err } // the outermost object will be converted to the output-version, but inner // objects can use their mappings version := cmdutil.OutputVersion(cmd, defaultVersion) obj, err := resource.AsVersionedObject(infos, !singular, version) if err != nil { return err } return printer.PrintObj(obj, out) } // use the default printer for each object return b.Do().Visit(func(r *resource.Info) error { printer, err := f.PrinterForMapping(cmd, r.Mapping) if err != nil { return err } return printer.PrintObj(r.Object, out) }) }