func main() {
	// use os.Args instead of "flags" because "flags" will mess up the man pages!
	path := "docs/man/man1"
	if len(os.Args) == 2 {
		path = os.Args[1]
	} else if len(os.Args) > 2 {
		fmt.Fprintf(os.Stderr, "usage: %s [output directory]\n", os.Args[0])
		os.Exit(1)
	}

	outDir, err := genutils.OutDir(path)
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to get output directory: %v\n", err)
		os.Exit(1)
	}

	// Set environment variables used by kubectl so the output is consistent,
	// regardless of where we run.
	os.Setenv("HOME", "/home/username")
	//TODO os.Stdin should really be something like ioutil.Discard, but a Reader
	kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
	genMarkdown(kubectl, "", outDir)
	for _, c := range kubectl.Commands() {
		genMarkdown(c, "kubectl", outDir)
	}
}
func TestKubectlCompatibility(t *testing.T) {
	f := clientcmd.New(pflag.NewFlagSet("name", pflag.ContinueOnError))

	oc := NewCommandCLI("oc", "oc", &bytes.Buffer{}, ioutil.Discard, ioutil.Discard)
	kubectl := kcmd.NewKubectlCommand(f.Factory, nil, ioutil.Discard, ioutil.Discard)

kubectlLoop:
	for _, kubecmd := range kubectl.Commands() {
		for _, occmd := range oc.Commands() {
			if kubecmd.Name() == occmd.Name() {
				if MissingCommands.Has(kubecmd.Name()) {
					t.Errorf("%s was supposed to be missing", kubecmd.Name())
					continue
				}
				if WhitelistedCommands.Has(kubecmd.Name()) {
					t.Errorf("%s was supposed to be whitelisted", kubecmd.Name())
					continue
				}
				continue kubectlLoop
			}
		}
		if MissingCommands.Has(kubecmd.Name()) || WhitelistedCommands.Has(kubecmd.Name()) {
			continue
		}

		t.Errorf("missing %q in oc", kubecmd.Name())
	}

}
Example #3
0
/*
WARNING: this logic is duplicated, with minor changes, in cmd/hyperkube/kubectl.go
Any salient changes here will need to be manually reflected in that file.
*/
func Run() error {
	logs.InitLogs()
	defer logs.FlushLogs()

	cmd := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, os.Stdout, os.Stderr)
	return cmd.Execute()
}
Example #4
0
func AddFlags(fs *pflag.FlagSet, kubectlSubCmd string) {
	cmd := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, os.Stdout, os.Stderr)
	fs.AddFlagSet(cmd.LocalFlags())
	if kubectlSubCmd == "" {
		return
	}
	for _, child := range cmd.Commands() {
		if child.Name() == kubectlSubCmd {
			fs.AddFlagSet(child.LocalFlags())
			return
		}
	}
}
Example #5
0
func NewKubectlServer() *Server {
	cmd := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, os.Stdout, os.Stderr)
	localFlags := cmd.LocalFlags()
	localFlags.SetInterspersed(false)

	return &Server{
		name:        "kubectl",
		SimpleUsage: "Kubernetes command line client",
		Long:        "Kubernetes command line client",
		Run: func(s *Server, args []string) error {
			cmd.SetArgs(args)
			return cmd.Execute()
		},
		flags: localFlags,
	}
}
func main() {
	errors := []error{}

	kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
	result := cmdsanity.CheckCmdTree(kubectl, cmdsanity.AllCmdChecks, []string{})
	errors = append(errors, result...)

	if len(errors) > 0 {
		for i, err := range errors {
			fmt.Fprintf(os.Stderr, "%d. %s\n\n", i+1, err)
		}
		os.Exit(1)
	}

	fmt.Fprintln(os.Stdout, "Congrats, CLI looks good!")
}
Example #7
0
func main() {
	flag.Parse()

	if len(*outputFile) < 1 {
		fmt.Printf("Must specify --output.\n")
		os.Exit(1)
	}

	// Initialize a kubectl command that we can use to get the help documentation
	kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)

	// Create the structural representation
	spec := NewKubectlSpec(kubectl)

	// Write the spec to a file as yaml
	WriteFile(spec)
}
Example #8
0
func NewKubectlServer() *Server {
	// need to use term.StdStreams to get the right IO refs on Windows
	stdin, stdout, stderr := term.StdStreams()
	cmd := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), stdin, stdout, stderr)
	localFlags := cmd.LocalFlags()
	localFlags.SetInterspersed(false)

	return &Server{
		name:        "kubectl",
		SimpleUsage: "Kubernetes command line client",
		Long:        "Kubernetes command line client",
		Run: func(s *Server, args []string) error {
			cmd.SetArgs(args)
			return cmd.Execute()
		},
		flags: localFlags,
	}
}
Example #9
0
File: cli.go Project: kcbabo/origin
// NewCmdKubectl provides exactly the functionality from Kubernetes,
// but with support for OpenShift resources
func NewCmdKubectl(name string, out io.Writer) *cobra.Command {
	flags := pflag.NewFlagSet("", pflag.ContinueOnError)
	f := clientcmd.New(flags)
	cmds := kubecmd.NewKubectlCommand(f.Factory, os.Stdin, out, os.Stderr)
	cmds.Aliases = []string{"kubectl"}
	cmds.Use = name
	cmds.Short = "Kubernetes cluster management via kubectl"
	flags.VisitAll(func(flag *pflag.Flag) {
		if f := cmds.PersistentFlags().Lookup(flag.Name); f == nil {
			cmds.PersistentFlags().AddFlag(flag)
		} else {
			glog.V(5).Infof("already registered flag %s", flag.Name)
		}
	})
	cmds.PersistentFlags().Var(flags.Lookup("config").Value, "kubeconfig", "Specify a kubeconfig file to define the configuration")
	templates.ActsAsRootCommand(cmds)
	cmds.AddCommand(cmd.NewCmdOptions(out))
	return cmds
}
func main() {
	// use os.Args instead of "flags" because "flags" will mess up the man pages!
	path := "contrib/completions/bash/"
	if len(os.Args) == 2 {
		path = os.Args[1]
	} else if len(os.Args) > 2 {
		fmt.Fprintf(os.Stderr, "usage: %s [output directory]\n", os.Args[0])
		os.Exit(1)
	}

	outDir, err := genutils.OutDir(path)
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to get output directory: %v\n", err)
		os.Exit(1)
	}
	outFile := outDir + "kubectl"

	//TODO os.Stdin should really be something like ioutil.Discard, but a Reader
	kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
	kubectl.GenBashCompletionFile(outFile)
}
Example #11
0
// NewCmdKubectl provides exactly the functionality from Kubernetes,
// but with support for OpenShift resources
func NewCmdKubectl(name string, out io.Writer) *cobra.Command {
	flags := pflag.NewFlagSet("", pflag.ContinueOnError)
	f := clientcmd.New(flags)
	cmds := kubecmd.NewKubectlCommand(f.Factory, os.Stdin, out, os.Stderr)
	cmds.Aliases = []string{"kubectl"}
	cmds.Use = name
	cmds.Short = "Kubernetes cluster management via kubectl"
	cmds.Long = cmds.Long + `

This command exposes the exact semantics of the Kubernetes command line client with additional
support for application lifecycles.`
	flags.VisitAll(func(flag *pflag.Flag) {
		if f := cmds.PersistentFlags().Lookup(flag.Name); f == nil {
			cmds.PersistentFlags().AddFlag(flag)
		} else {
			glog.V(5).Infof("already registered flag %s", flag.Name)
		}
	})
	templates.ActsAsRootCommand(cmds)
	cmds.AddCommand(cmd.NewCmdOptions(out))
	return cmds
}
Example #12
0
// this only checks one level deep for nested commands, but it does ensure that we've gotten several
// --validate flags.  Based on that we can reasonably assume we got them in the kube commands since they
// all share the same registration.
func TestValidateDisabled(t *testing.T) {
	f := clientcmd.New(pflag.NewFlagSet("name", pflag.ContinueOnError))

	oc := NewCommandCLI("oc", "oc", &bytes.Buffer{}, ioutil.Discard, ioutil.Discard)
	kubectl := kcmd.NewKubectlCommand(f.Factory, nil, ioutil.Discard, ioutil.Discard)

	for _, kubecmd := range kubectl.Commands() {
		for _, occmd := range oc.Commands() {
			if kubecmd.Name() == occmd.Name() {
				ocValidateFlag := occmd.Flags().Lookup("validate")
				if ocValidateFlag == nil {
					continue
				}

				if ocValidateFlag.Value.String() != "false" {
					t.Errorf("%s --validate is not defaulting to false", occmd.Name())
				}
			}
		}
	}

}
Example #13
0
/*
WARNING: this logic is duplicated, with minor changes, in cmd/hyperkube/kubectl.go
Any salient changes here will need to be manually reflected in that file.
*/
func Run() error {
	cmd := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, os.Stdout, os.Stderr)
	return cmd.Execute()
}
Example #14
0
func main() {
	// embed kubectl
	if filepath.Base(os.Args[0]) == "kubectl" {
		cmd := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, os.Stdout, os.Stderr)
		if err := cmd.Execute(); err != nil {
			os.Exit(1)
		}
		return
	}

	usr, err := user.Current()
	if err != nil {
		log.Fatal(err)
	}

	mfs := pflag.NewFlagSet("main", pflag.ExitOnError)
	nodes := mfs.StringSlice("nodes", []string{}, "list of nodes to make part of cluster")
	sshKeyfile := mfs.String("ssh-keyfile", usr.HomeDir+"/.vagrant.d/insecure_private_key", "private ssh key to use for tunnels")
	sshUser := mfs.String("ssh-user", "core", "ssh user to use for tunnels")
	clusterIPRange := mfs.String("service-cluster-ip-range", "10.1.30.0/24", "A CIDR notation IP range from which to assign service cluster IPs. This must not overlap with any IP ranges assigned to nodes for pods.")
	mfs.Parse(os.Args)

	config := &ssh.ClientConfig{
		User: *sshUser,
		Auth: []ssh.AuthMethod{
			PublicKeyFile(*sshKeyfile),
		},
	}
	for _, remoteHost := range *nodes {
		// Dial your ssh server.
		go func(host string) {
			// Serve HTTP with your SSH server acting as a reverse proxy.
			go func() {
				b := &backoff.Backoff{
					//These are the defaults
					Min:    100 * time.Millisecond,
					Max:    10 * time.Second,
					Factor: 2,
					Jitter: false,
				}
				for {
					conn, err := ssh.Dial("tcp", host, config)
					if err != nil {
						log.Println("unable to connect, retrying:", err)
						time.Sleep(b.Duration())
						continue
					}
					defer conn.Close()

					// Request the remote side to open port 8080 on all interfaces.
					l, err := conn.Listen("tcp", remoteListen)
					if err != nil {
						log.Println("unable to register tcp forward, retrying:", err)
						time.Sleep(b.Duration())
						continue
					}
					defer l.Close()
					fwd, _ := forward.New()
					http.Serve(l, http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
						req.URL = testutils.ParseURI("http://localhost:8080")
						fwd.ServeHTTP(resp, req)
					}))
					log.Println("proxy connection broken, reconnecting....")
					time.Sleep(b.Duration())
				}
			}()
			go func() {
				// this will block, and the kubelet will stop once the connection is broken
				// loop for reconnection
				b := &backoff.Backoff{
					//These are the defaults
					Min:    100 * time.Millisecond,
					Max:    10 * time.Second,
					Factor: 2,
					Jitter: false,
				}

				for {
					ip, _, err := net.SplitHostPort(host)
					if err != nil {
						log.Fatalf("unable split host port: %v", err)
						return
					}
					cmd := fmt.Sprintf("sudo /usr/bin/kubelet --hostname-override=%s --api-servers=http://localhost:8080", ip)
					_, err = executeCmd(cmd, host, config)
					if err != nil {
						log.Println("unable to execute kubelet, retrying:", err)
					}
					// if we got here something went wrong
					dur := b.Duration()
					log.Println("kubelet connection broken, reconnecting in", dur)
					time.Sleep(dur)

				}
			}()
			<-make(chan interface{})
		}(remoteHost)
	}

	go func() {
		// etcd reads os.Args so we have to use mess with them
		os.Args = []string{"etcd"}
		etcdmain.Main()
	}()

	go func() {
		s := kubeapiserver.NewAPIServer()
		fs := pflag.NewFlagSet("apiserver", pflag.ContinueOnError)
		s.AddFlags(fs)
		fs.Parse([]string{
			"--service-cluster-ip-range=" + *clusterIPRange,
			"--etcd-servers=http://127.0.0.1:2379",
			"--ssh-keyfile=" + *sshKeyfile,
			"--ssh-user="******"controller", pflag.ContinueOnError)
		s.AddFlags(fs)
		fs.Parse([]string{})
		s.Run([]string{})
	}()

	go func() {
		s := scheduler.NewSchedulerServer()
		fs := pflag.NewFlagSet("scheduler", pflag.ContinueOnError)
		s.AddFlags(fs)
		fs.Parse([]string{})
		s.Run([]string{})
	}()
	<-make(chan interface{})
}
Example #15
0
/*
WARNING: this logic is duplicated, with minor changes, in cmd/hyperkube/kubectl.go
Any salient changes here will need to be manually reflected in that file.
*/
func Run() error {
	// need to use term.StdStreams to get the right IO refs on Windows
	stdin, stdout, stderr := term.StdStreams()
	cmd := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), stdin, stdout, stderr)
	return cmd.Execute()
}
Example #16
0
func main() {
	// use os.Args instead of "flags" because "flags" will mess up the man pages!
	path := "docs/man/man1"
	module := ""
	if len(os.Args) == 3 {
		path = os.Args[1]
		module = os.Args[2]
	} else {
		fmt.Fprintf(os.Stderr, "usage: %s [output directory] [module] \n", os.Args[0])
		os.Exit(1)
	}

	outDir, err := genutils.OutDir(path)
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to get output directory: %v\n", err)
		os.Exit(1)
	}

	// Set environment variables used by command so the output is consistent,
	// regardless of where we run.
	os.Setenv("HOME", "/home/username")

	switch module {
	case "kube-apiserver":
		// generate manpage for kube-apiserver
		apiserver := apiservapp.NewAPIServerCommand()
		genMarkdown(apiserver, "", outDir)
		for _, c := range apiserver.Commands() {
			genMarkdown(c, "kube-apiserver", outDir)
		}
	case "kube-controller-manager":
		// generate manpage for kube-controller-manager
		controllermanager := cmapp.NewControllerManagerCommand()
		genMarkdown(controllermanager, "", outDir)
		for _, c := range controllermanager.Commands() {
			genMarkdown(c, "kube-controller-manager", outDir)
		}
	case "kube-proxy":
		// generate manpage for kube-proxy
		proxy := proxyapp.NewProxyCommand()
		genMarkdown(proxy, "", outDir)
		for _, c := range proxy.Commands() {
			genMarkdown(c, "kube-proxy", outDir)
		}
	case "kube-scheduler":
		// generate manpage for kube-scheduler
		scheduler := schapp.NewSchedulerCommand()
		genMarkdown(scheduler, "", outDir)
		for _, c := range scheduler.Commands() {
			genMarkdown(c, "kube-scheduler", outDir)
		}
	case "kubelet":
		// generate manpage for kubelet
		kubelet := kubeletapp.NewKubeletCommand()
		genMarkdown(kubelet, "", outDir)
		for _, c := range kubelet.Commands() {
			genMarkdown(c, "kubelet", outDir)
		}
	case "kubectl":
		// generate manpage for kubectl
		// TODO os.Stdin should really be something like ioutil.Discard, but a Reader
		kubectl := kubectlcmd.NewKubectlCommand(kubectlcmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
		genMarkdown(kubectl, "", outDir)
		for _, c := range kubectl.Commands() {
			genMarkdown(c, "kubectl", outDir)
		}
	default:
		fmt.Fprintf(os.Stderr, "Module %s is not supported", module)
		os.Exit(1)
	}
}