kubectl: kubecfg rewrite for better modularity and improved UX

This commit is contained in:
Sam Ghods
2014-10-05 18:24:19 -07:00
parent 0b79438237
commit 4b220f8b0a
22 changed files with 2052 additions and 13 deletions

255
pkg/kubectl/cmd/cmd.go Normal file
View File

@@ -0,0 +1,255 @@
/*
Copyright 2014 Google Inc. All rights reserved.
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 cmd
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"strconv"
"strings"
"github.com/GoogleCloudPlatform/kubernetes/pkg/api/latest"
"github.com/GoogleCloudPlatform/kubernetes/pkg/client"
"github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl"
"github.com/golang/glog"
"github.com/spf13/cobra"
)
func RunKubectl(out io.Writer) {
// Parent command to which all subcommands are added.
cmds := &cobra.Command{
Use: "kubectl",
Short: "kubectl controls the Kubernetes cluster manager",
Long: `kubectl controls the Kubernetes cluster manager.
Find more information at https://github.com/GoogleCloudPlatform/kubernetes.`,
Run: runHelp,
}
// Globally persistent flags across all subcommands.
// TODO Change flag names to consts to allow safer lookup from subcommands.
// TODO Add a verbose flag that turns on glog logging. Probably need a way
// to do that automatically for every subcommand.
cmds.PersistentFlags().StringP("server", "s", "", "Kubernetes apiserver to connect to")
cmds.PersistentFlags().StringP("auth-path", "a", os.Getenv("HOME")+"/.kubernetes_auth", "Path to the auth info file. If missing, prompt the user. Only used if using https.")
cmds.PersistentFlags().Bool("match-server-version", false, "Require server version to match client version")
cmds.PersistentFlags().String("api-version", latest.Version, "The version of the API to use against the server (used for viewing resources only)")
cmds.PersistentFlags().String("certificate-authority", "", "Path to a certificate file for the certificate authority")
cmds.PersistentFlags().String("client-certificate", "", "Path to a client certificate for TLS.")
cmds.PersistentFlags().String("client-key", "", "Path to a client key file for TLS.")
cmds.PersistentFlags().Bool("insecure-skip-tls-verify", false, "If true, the server's certificate will not be checked for validity. This will make your HTTPS connections insecure.")
cmds.AddCommand(NewCmdVersion(out))
cmds.AddCommand(NewCmdProxy(out))
cmds.AddCommand(NewCmdGet(out))
cmds.AddCommand(NewCmdDescribe(out))
cmds.AddCommand(NewCmdCreate(out))
cmds.AddCommand(NewCmdUpdate(out))
cmds.AddCommand(NewCmdDelete(out))
if err := cmds.Execute(); err != nil {
os.Exit(1)
}
}
func checkErr(err error) {
if err != nil {
glog.Fatalf("%v", err)
}
}
func usageError(cmd *cobra.Command, format string, args ...interface{}) {
glog.Errorf(format, args...)
glog.Errorf("See '%s -h' for help.", cmd.CommandPath())
os.Exit(1)
}
func runHelp(cmd *cobra.Command, args []string) {
cmd.Help()
}
func getFlagString(cmd *cobra.Command, flag string) string {
f := cmd.Flags().Lookup(flag)
if f == nil {
glog.Fatalf("Flag accessed but not defined for command %s: %s", cmd.Name(), flag)
}
return f.Value.String()
}
func getFlagBool(cmd *cobra.Command, flag string) bool {
f := cmd.Flags().Lookup(flag)
if f == nil {
glog.Fatalf("Flag accessed but not defined for command %s: %s", cmd.Name(), flag)
}
// Caseless compare.
if strings.ToLower(f.Value.String()) == "true" {
return true
}
return false
}
// Returns nil if the flag wasn't set.
func getFlagBoolPtr(cmd *cobra.Command, flag string) *bool {
f := cmd.Flags().Lookup(flag)
if f == nil {
glog.Fatalf("Flag accessed but not defined for command %s: %s", cmd.Name(), flag)
}
// Check if flag was not set at all.
if !f.Changed && f.DefValue == f.Value.String() {
return nil
}
var ret bool
// Caseless compare.
if strings.ToLower(f.Value.String()) == "true" {
ret = true
} else {
ret = false
}
return &ret
}
// Assumes the flag has a default value.
func getFlagInt(cmd *cobra.Command, flag string) int {
f := cmd.Flags().Lookup(flag)
if f == nil {
glog.Fatalf("Flag accessed but not defined for command %s: %s", cmd.Name(), flag)
}
v, err := strconv.Atoi(f.Value.String())
// This is likely not a sufficiently friendly error message, but cobra
// should prevent non-integer values from reaching here.
checkErr(err)
return v
}
func getKubeClient(cmd *cobra.Command) *client.Client {
config := &client.Config{}
var host string
if hostFlag := getFlagString(cmd, "server"); len(hostFlag) > 0 {
host = hostFlag
glog.V(2).Infof("Using server from -s flag: %s", host)
} else if len(os.Getenv("KUBERNETES_MASTER")) > 0 {
host = os.Getenv("KUBERNETES_MASTER")
glog.V(2).Infof("Using server from env var KUBERNETES_MASTER: %s", host)
} else {
// TODO: eventually apiserver should start on 443 and be secure by default
host = "http://localhost:8080"
glog.V(2).Infof("No server found in flag or env var, using default: %s", host)
}
config.Host = host
if client.IsConfigTransportSecure(config) {
// Get the values from the file on disk (or from the user at the
// command line). Override them with the command line parameters, if
// provided.
authPath := getFlagString(cmd, "auth-path")
authInfo, err := kubectl.LoadAuthInfo(authPath, os.Stdin)
if err != nil {
glog.Fatalf("Error loading auth: %v", err)
}
config.Username = authInfo.User
config.Password = authInfo.Password
// First priority is flag, then file.
config.CAFile = firstNonEmptyString(getFlagString(cmd, "certificate-authority"), authInfo.CAFile)
config.CertFile = firstNonEmptyString(getFlagString(cmd, "client-certificate"), authInfo.CertFile)
config.KeyFile = firstNonEmptyString(getFlagString(cmd, "client-key"), authInfo.KeyFile)
// For config.Insecure, the command line ALWAYS overrides the authInfo
// file, regardless of its setting.
if insecureFlag := getFlagBoolPtr(cmd, "insecure-skip-tls-verify"); insecureFlag != nil {
config.Insecure = *insecureFlag
} else if authInfo.Insecure != nil {
config.Insecure = *authInfo.Insecure
}
}
// The API version (e.g. v1beta1), not the binary version.
config.Version = getFlagString(cmd, "api-version")
// The binary version.
matchVersion := getFlagBool(cmd, "match-server-version")
c, err := kubectl.GetKubeClient(config, matchVersion)
if err != nil {
glog.Fatalf("Error creating kubernetes client: %v", err)
}
return c
}
// Returns the first non-empty string out of the ones provided. If all
// strings are empty, returns an empty string.
func firstNonEmptyString(args ...string) string {
for _, s := range args {
if len(s) > 0 {
return s
}
}
return ""
}
// readConfigData reads the bytes from the specified filesytem or network
// location or from stdin if location == "-".
func readConfigData(location string) ([]byte, error) {
if len(location) == 0 {
return nil, fmt.Errorf("Location given but empty")
}
if location == "-" {
// Read from stdin.
data, err := ioutil.ReadAll(os.Stdin)
if err != nil {
return nil, err
}
if len(data) == 0 {
return nil, fmt.Errorf(`Read from stdin specified ("-") but no data found`)
}
return data, nil
}
// Use the location as a file path or URL.
return readConfigDataFromLocation(location)
}
func readConfigDataFromLocation(location string) ([]byte, error) {
// we look for http:// or https:// to determine if valid URL, otherwise do normal file IO
if strings.Index(location, "http://") == 0 || strings.Index(location, "https://") == 0 {
resp, err := http.Get(location)
if err != nil {
return nil, fmt.Errorf("Unable to access URL %s: %v\n", location, err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, fmt.Errorf("Unable to read URL, server reported %d %s", resp.StatusCode, resp.Status)
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("Unable to read URL %s: %v\n", location, err)
}
return data, nil
} else {
data, err := ioutil.ReadFile(location)
if err != nil {
return nil, fmt.Errorf("Unable to read %s: %v\n", location, err)
}
return data, nil
}
}

54
pkg/kubectl/cmd/create.go Normal file
View File

@@ -0,0 +1,54 @@
/*
Copyright 2014 Google Inc. All rights reserved.
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 cmd
import (
"io"
"github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl"
"github.com/spf13/cobra"
)
func NewCmdCreate(out io.Writer) *cobra.Command {
cmd := &cobra.Command{
Use: "create -f filename",
Short: "Create a resource by filename or stdin",
Long: `Create a resource by filename or stdin.
JSON and YAML formats are accepted.
Examples:
$ kubectl create -f pod.json
<create a pod using the data in pod.json>
$ cat pod.json | kubectl create -f -
<create a pod based on the json passed into stdin>`,
Run: func(cmd *cobra.Command, args []string) {
filename := getFlagString(cmd, "filename")
if len(filename) == 0 {
usageError(cmd, "Must pass a filename to update")
}
data, err := readConfigData(filename)
checkErr(err)
err = kubectl.Modify(out, getKubeClient(cmd).RESTClient, kubectl.ModifyCreate, data)
checkErr(err)
},
}
cmd.Flags().StringP("filename", "f", "", "Filename or URL to file to use to create the resource")
return cmd
}

80
pkg/kubectl/cmd/delete.go Normal file
View File

@@ -0,0 +1,80 @@
/*
Copyright 2014 Google Inc. All rights reserved.
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 cmd
import (
"io"
"github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl"
"github.com/spf13/cobra"
)
func NewCmdDelete(out io.Writer) *cobra.Command {
cmd := &cobra.Command{
Use: "delete ([-f filename] | (<resource> <id>))",
Short: "Delete a resource by filename, stdin or resource and id",
Long: `Delete a resource by filename, stdin or resource and id.
JSON and YAML formats are accepted.
If both a filename and command line arguments are passed, the command line
arguments are used and the filename is ignored.
Note that the delete command does NOT do resource version checks, so if someone
submits an update to a resource right when you submit a delete, their update
will be lost along with the rest of the resource.
Examples:
$ kubectl delete -f pod.json
<delete a pod using the type and id pod.json>
$ cat pod.json | kubectl delete -f -
<delete a pod based on the type and id in the json passed into stdin>
$ kubectl delete pod 1234-56-7890-234234-456456
<delete a pod with ID 1234-56-7890-234234-456456>`,
Run: func(cmd *cobra.Command, args []string) {
// If command line args are passed in, use those preferentially.
if len(args) > 0 && len(args) != 2 {
usageError(cmd, "If passing in command line parameters, must be resource and id")
}
var data []byte
var err error
if len(args) == 2 {
data, err = kubectl.CreateResource(args[0], args[1])
} else {
filename := getFlagString(cmd, "filename")
if len(filename) > 0 {
data, err = readConfigData(getFlagString(cmd, "filename"))
}
}
checkErr(err)
if len(data) == 0 {
usageError(cmd, "Must specify filename or command line params")
}
// TODO Add ability to require a resource-version check for delete.
err = kubectl.Modify(out, getKubeClient(cmd).RESTClient, kubectl.ModifyDelete, data)
checkErr(err)
},
}
cmd.Flags().StringP("filename", "f", "", "Filename or URL to file to use to delete the resource")
return cmd
}

View File

@@ -0,0 +1,45 @@
/*
Copyright 2014 Google Inc. All rights reserved.
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 cmd
import (
"io"
"github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl"
"github.com/spf13/cobra"
)
func NewCmdDescribe(out io.Writer) *cobra.Command {
cmd := &cobra.Command{
Use: "describe <resource> <id>",
Short: "Show details of a specific resource",
Long: `Show details of a specific resource.
This command joins many API calls together to form a detailed description of a
given resource.`,
Run: func(cmd *cobra.Command, args []string) {
if len(args) < 2 {
usageError(cmd, "Need to supply a resource and an ID")
}
resource := args[0]
id := args[1]
err := kubectl.Describe(out, getKubeClient(cmd), resource, id)
checkErr(err)
},
}
return cmd
}

70
pkg/kubectl/cmd/get.go Normal file
View File

@@ -0,0 +1,70 @@
/*
Copyright 2014 Google Inc. All rights reserved.
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 cmd
import (
"io"
"github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl"
"github.com/spf13/cobra"
)
func NewCmdGet(out io.Writer) *cobra.Command {
cmd := &cobra.Command{
Use: "get [(-o|--output=)table|json|yaml|template] [-t <file>|--template=<file>] <resource> [<id>]",
Short: "Display one or many resources",
Long: `Display one or many resources.
Possible resources include pods (po), replication controllers (rc), services
(se) or minions (mi).
If you specify a Go template, you can use any field defined in pkg/api/types.go.
Examples:
$ kubectl get pods
<list all pods in ps output format>
$ kubectl get replicationController 1234-56-7890-234234-456456
<list single repliaction controller in ps output format>
$ kubectl get -f json pod 1234-56-7890-234234-456456
<list single pod in json output format>`,
Run: func(cmd *cobra.Command, args []string) {
var resource, id string
if len(args) == 0 {
usageError(cmd, "Need to supply a resource.")
}
if len(args) >= 1 {
resource = args[0]
}
if len(args) >= 2 {
id = args[1]
}
outputFormat := getFlagString(cmd, "output")
templateFile := getFlagString(cmd, "template")
selector := getFlagString(cmd, "selector")
err := kubectl.Get(out, getKubeClient(cmd).RESTClient, resource, id, selector, outputFormat, templateFile)
checkErr(err)
},
}
// TODO Add an --output-version lock which can ensure that regardless of the
// server version, the client output stays the same.
cmd.Flags().StringP("output", "o", "console", "Output format: console|json|yaml|template")
cmd.Flags().StringP("template", "t", "", "Path to template file to use when --output=template")
cmd.Flags().StringP("selector", "l", "", "Selector (label query) to filter on")
return cmd
}

42
pkg/kubectl/cmd/proxy.go Normal file
View File

@@ -0,0 +1,42 @@
/*
Copyright 2014 Google Inc. All rights reserved.
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 cmd
import (
"io"
"github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl"
"github.com/golang/glog"
"github.com/spf13/cobra"
)
func NewCmdProxy(out io.Writer) *cobra.Command {
cmd := &cobra.Command{
Use: "proxy",
Short: "Run a proxy to the Kubernetes API server",
Long: `Run a proxy to the Kubernetes API server.`,
Run: func(cmd *cobra.Command, args []string) {
port := getFlagInt(cmd, "port")
glog.Infof("Starting to serve on localhost:%d", port)
server := kubectl.NewProxyServer(getFlagString(cmd, "www"), getKubeClient(cmd), port)
glog.Fatal(server.Serve())
},
}
cmd.Flags().StringP("www", "w", "", "Also serve static files from the given directory under the prefix /static")
cmd.Flags().IntP("port", "p", 8001, "The port on which to run the proxy")
return cmd
}

55
pkg/kubectl/cmd/update.go Normal file
View File

@@ -0,0 +1,55 @@
/*
Copyright 2014 Google Inc. All rights reserved.
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 cmd
import (
"io"
"github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl"
"github.com/spf13/cobra"
)
func NewCmdUpdate(out io.Writer) *cobra.Command {
cmd := &cobra.Command{
Use: "update -f filename",
Short: "Update a resource by filename or stdin",
Long: `Update a resource by filename or stdin.
JSON and YAML formats are accepted.
Examples:
$ kubectl update -f pod.json
<update a pod using the data in pod.json>
$ cat pod.json | kubectl update -f -
<update a pod based on the json passed into stdin>`,
Run: func(cmd *cobra.Command, args []string) {
filename := getFlagString(cmd, "filename")
if len(filename) == 0 {
usageError(cmd, "Must pass a filename to update")
}
data, err := readConfigData(filename)
checkErr(err)
err = kubectl.Modify(out, getKubeClient(cmd).RESTClient, kubectl.ModifyUpdate, data)
checkErr(err)
},
}
cmd.Flags().StringP("filename", "f", "", "Filename or URL to file to use to update the resource")
return cmd
}

View File

@@ -0,0 +1,40 @@
/*
Copyright 2014 Google Inc. All rights reserved.
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 cmd
import (
"io"
"github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl"
"github.com/spf13/cobra"
)
func NewCmdVersion(out io.Writer) *cobra.Command {
cmd := &cobra.Command{
Use: "version",
Short: "Print version of client and server",
Run: func(cmd *cobra.Command, args []string) {
if getFlagBool(cmd, "client") {
kubectl.GetClientVersion(out)
} else {
kubectl.GetVersion(out, getKubeClient(cmd))
}
},
}
cmd.Flags().BoolP("client", "c", false, "Client version only (no server required)")
return cmd
}