diff --git a/contrib/completions/bash/kubectl b/contrib/completions/bash/kubectl index 238b289c036..f7bc2ac465b 100644 --- a/contrib/completions/bash/kubectl +++ b/contrib/completions/bash/kubectl @@ -242,6 +242,7 @@ _kubectl_get() must_have_one_flag=() must_have_one_noun=() + must_have_one_noun+=("componentstatus") must_have_one_noun+=("endpoints") must_have_one_noun+=("event") must_have_one_noun+=("limitrange") diff --git a/pkg/api/meta/restmapper.go b/pkg/api/meta/restmapper.go index 249752a276c..615749b44fa 100644 --- a/pkg/api/meta/restmapper.go +++ b/pkg/api/meta/restmapper.go @@ -138,13 +138,17 @@ func kindToResource(kind string, mixedCase bool) (plural, singular string) { } else { singular = strings.ToLower(kind) } - switch string(singular[len(singular)-1]) { - case "s": - plural = singular - case "y": - plural = strings.TrimSuffix(singular, "y") + "ies" - default: - plural = singular + "s" + if strings.HasSuffix(singular, "status") { + plural = strings.TrimSuffix(singular, "status") + "statuses" + } else { + switch string(singular[len(singular)-1]) { + case "s": + plural = singular + case "y": + plural = strings.TrimSuffix(singular, "y") + "ies" + default: + plural = singular + "s" + } } return } @@ -215,7 +219,7 @@ func (m *DefaultRESTMapper) RESTMapping(kind string, versions ...string) (*RESTM return nil, fmt.Errorf("the provided version %q has no relevant versions", version) } - return &RESTMapping{ + retVal := &RESTMapping{ Resource: resource, APIVersion: version, Kind: kind, @@ -224,7 +228,9 @@ func (m *DefaultRESTMapper) RESTMapping(kind string, versions ...string) (*RESTM Codec: interfaces.Codec, ObjectConvertor: interfaces.ObjectConvertor, MetadataAccessor: interfaces.MetadataAccessor, - }, nil + } + + return retVal, nil } // aliasToResource is used for mapping aliases to resources diff --git a/pkg/api/register.go b/pkg/api/register.go index 4a352961990..83fc40e23af 100644 --- a/pkg/api/register.go +++ b/pkg/api/register.go @@ -60,6 +60,8 @@ func init() { &PodLogOptions{}, &PodExecOptions{}, &PodProxyOptions{}, + &ComponentStatus{}, + &ComponentStatusList{}, ) // Legacy names are supported Scheme.AddKnownTypeWithName("", "Minion", &Node{}) @@ -101,3 +103,5 @@ func (*ListOptions) IsAnAPIObject() {} func (*PodLogOptions) IsAnAPIObject() {} func (*PodExecOptions) IsAnAPIObject() {} func (*PodProxyOptions) IsAnAPIObject() {} +func (*ComponentStatus) IsAnAPIObject() {} +func (*ComponentStatusList) IsAnAPIObject() {} diff --git a/pkg/api/types.go b/pkg/api/types.go index 5868517c84c..9c8d108f2ac 100644 --- a/pkg/api/types.go +++ b/pkg/api/types.go @@ -1827,3 +1827,34 @@ func AddToNodeAddresses(addresses *[]NodeAddress, addAddresses ...NodeAddress) { } } } + +// Type and constants for component health validation. +type ComponentConditionType string + +// These are the valid conditions for the component. +const ( + ComponentHealthy ComponentConditionType = "Healthy" +) + +type ComponentCondition struct { + Type ComponentConditionType `json:"type" description:"the type of condition"` + Status ConditionStatus `json:"status" description:"the status of this condition"` + Message string `json:"message,omitempty" description:"health check message received from the component"` + Error string `json:"error,omitempty" description:"error code from health check attempt (if any)"` +} + +// ComponentStatus (and ComponentStatusList) holds the cluster validation info. +type ComponentStatus struct { + TypeMeta `json:",inline"` + ObjectMeta `json:"metadata,omitempty"` + + Name string `json:"name,omitempty" description:"name of the component"` + Conditions []ComponentCondition `json:"conditions,omitempty" description:"list of component condition objects"` +} + +type ComponentStatusList struct { + TypeMeta `json:",inline"` + ListMeta `json:"metadata,omitempty"` + + Items []ComponentStatus `json:"items" description:"items is a list of component status objects"` +} diff --git a/pkg/api/v1beta1/register.go b/pkg/api/v1beta1/register.go index f2a137292e7..3947ac26f9a 100644 --- a/pkg/api/v1beta1/register.go +++ b/pkg/api/v1beta1/register.go @@ -68,6 +68,8 @@ func init() { &PodLogOptions{}, &PodExecOptions{}, &PodProxyOptions{}, + &ComponentStatus{}, + &ComponentStatusList{}, ) // Future names are supported api.Scheme.AddKnownTypeWithName("v1beta1", "Node", &Minion{}) @@ -110,3 +112,5 @@ func (*ListOptions) IsAnAPIObject() {} func (*PodLogOptions) IsAnAPIObject() {} func (*PodExecOptions) IsAnAPIObject() {} func (*PodProxyOptions) IsAnAPIObject() {} +func (*ComponentStatus) IsAnAPIObject() {} +func (*ComponentStatusList) IsAnAPIObject() {} diff --git a/pkg/api/v1beta1/types.go b/pkg/api/v1beta1/types.go index 57d41de70ef..a05fde07adc 100644 --- a/pkg/api/v1beta1/types.go +++ b/pkg/api/v1beta1/types.go @@ -1592,3 +1592,32 @@ type GlusterfsVolumeSource struct { // the Glusterfs volume to be mounted with read-only permissions ReadOnly bool `json:"readOnly,omitempty" description:"Glusterfs volume to be mounted with read-only permissions"` } + +// Type and constants for component health validation. +type ComponentConditionType string + +// These are the valid conditions for the component. +const ( + ComponentHealthy ComponentConditionType = "Healthy" +) + +type ComponentCondition struct { + Type ComponentConditionType `json:"type"` + Status ConditionStatus `json:"status"` + Message string `json:"message,omitempty" description:"health check message received from the component"` + Error string `json:"error,omitempty" description:"error code from health check attempt (if any)"` +} + +// ComponentStatus (and ComponentStatusList) holds the cluster validation info. +type ComponentStatus struct { + TypeMeta `json:",inline"` + + Name string `json:"name,omitempty" description:"name of the component"` + Conditions []ComponentCondition `json:"conditions,omitempty"` +} + +type ComponentStatusList struct { + TypeMeta `json:",inline"` + + Items []ComponentStatus `json:"items" description:"items is a list of component status objects"` +} diff --git a/pkg/api/v1beta2/register.go b/pkg/api/v1beta2/register.go index 3cc2bc7d54a..75393fd89c4 100644 --- a/pkg/api/v1beta2/register.go +++ b/pkg/api/v1beta2/register.go @@ -68,6 +68,8 @@ func init() { &PodLogOptions{}, &PodExecOptions{}, &PodProxyOptions{}, + &ComponentStatus{}, + &ComponentStatusList{}, ) // Future names are supported api.Scheme.AddKnownTypeWithName("v1beta2", "Node", &Minion{}) @@ -110,3 +112,5 @@ func (*ListOptions) IsAnAPIObject() {} func (*PodLogOptions) IsAnAPIObject() {} func (*PodExecOptions) IsAnAPIObject() {} func (*PodProxyOptions) IsAnAPIObject() {} +func (*ComponentStatus) IsAnAPIObject() {} +func (*ComponentStatusList) IsAnAPIObject() {} diff --git a/pkg/api/v1beta2/types.go b/pkg/api/v1beta2/types.go index 52e1fc720c8..31f6b674cae 100644 --- a/pkg/api/v1beta2/types.go +++ b/pkg/api/v1beta2/types.go @@ -1655,3 +1655,32 @@ type SecretList struct { Items []Secret `json:"items" description:"items is a list of secret objects"` } + +// Type and constants for component health validation. +type ComponentConditionType string + +// These are the valid conditions for the component. +const ( + ComponentHealthy ComponentConditionType = "Healthy" +) + +type ComponentCondition struct { + Type ComponentConditionType `json:"type"` + Status ConditionStatus `json:"status"` + Message string `json:"message,omitempty" description:"health check message received from the component"` + Error string `json:"error,omitempty" description:"error code from health check attempt (if any)"` +} + +// ComponentStatus (and ComponentStatusList) holds the cluster validation info. +type ComponentStatus struct { + TypeMeta `json:",inline"` + + Name string `json:"name,omitempty" description:"name of the component"` + Conditions []ComponentCondition `json:"conditions,omitempty"` +} + +type ComponentStatusList struct { + TypeMeta `json:",inline"` + + Items []ComponentStatus `json:"items" description:"items is a list of component status objects"` +} diff --git a/pkg/api/v1beta3/register.go b/pkg/api/v1beta3/register.go index 538ea5a9ac9..ea168aaf83a 100644 --- a/pkg/api/v1beta3/register.go +++ b/pkg/api/v1beta3/register.go @@ -61,6 +61,8 @@ func init() { &PodLogOptions{}, &PodExecOptions{}, &PodProxyOptions{}, + &ComponentStatus{}, + &ComponentStatusList{}, ) // Legacy names are supported api.Scheme.AddKnownTypeWithName("v1beta3", "Minion", &Node{}) @@ -102,3 +104,5 @@ func (*ListOptions) IsAnAPIObject() {} func (*PodLogOptions) IsAnAPIObject() {} func (*PodExecOptions) IsAnAPIObject() {} func (*PodProxyOptions) IsAnAPIObject() {} +func (*ComponentStatus) IsAnAPIObject() {} +func (*ComponentStatusList) IsAnAPIObject() {} diff --git a/pkg/api/v1beta3/types.go b/pkg/api/v1beta3/types.go index a70316c06d9..0f4a7b1a7d5 100644 --- a/pkg/api/v1beta3/types.go +++ b/pkg/api/v1beta3/types.go @@ -1672,3 +1672,34 @@ type SecretList struct { Items []Secret `json:"items" description:"items is a list of secret objects"` } + +// Type and constants for component health validation. +type ComponentConditionType string + +// These are the valid conditions for the component. +const ( + ComponentHealthy ComponentConditionType = "Healthy" +) + +type ComponentCondition struct { + Type ComponentConditionType `json:"type"` + Status ConditionStatus `json:"status"` + Message string `json:"message,omitempty" description:"health check message received from the component"` + Error string `json:"error,omitempty" description:"error code from health check attempt (if any)"` +} + +// ComponentStatus (and ComponentStatusList) holds the cluster validation info. +type ComponentStatus struct { + TypeMeta `json:",inline"` + ObjectMeta `json:"metadata,omitempty"` + + Name string `json:"name,omitempty" description:"name of the component"` + Conditions []ComponentCondition `json:"conditions,omitempty"` +} + +type ComponentStatusList struct { + TypeMeta `json:",inline"` + ListMeta `json:"metadata,omitempty"` + + Items []ComponentStatus `json:"items" description:"items is a list of component status objects"` +} diff --git a/pkg/apiserver/apiserver.go b/pkg/apiserver/apiserver.go index 693ac3013cf..924165eafa8 100644 --- a/pkg/apiserver/apiserver.go +++ b/pkg/apiserver/apiserver.go @@ -140,7 +140,8 @@ func (g *APIGroupVersion) InstallREST(container *restful.Container) error { return errors.NewAggregate(registrationErrors) } -// TODO: Convert to go-restful +// TODO: This endpoint is deprecated and should be removed at some point. +// Use "componentstatus" API instead. func InstallValidator(mux Mux, servers func() map[string]Server) { mux.Handle("/validate", NewValidator(servers)) } diff --git a/pkg/apiserver/validator.go b/pkg/apiserver/validator.go index 368ea66d67f..1db5e64b5c2 100644 --- a/pkg/apiserver/validator.go +++ b/pkg/apiserver/validator.go @@ -48,13 +48,39 @@ type validator struct { rt http.RoundTripper } +type ServerStatus struct { + Component string `json:"component,omitempty"` + Health string `json:"health,omitempty"` + HealthCode probe.Result `json:"healthCode,omitempty"` + Msg string `json:"msg,omitempty"` + Err string `json:"err,omitempty"` +} + // TODO: can this use pkg/probe/http -func (s *Server) check(client httpGet) (probe.Result, string, error) { +func (server *Server) DoServerCheck(rt http.RoundTripper) (probe.Result, string, error) { + var client *http.Client scheme := "http://" - if s.EnableHTTPS { + if server.EnableHTTPS { + // TODO(roberthbailey): The servers that use HTTPS are currently the + // kubelets, and we should be using a standard kubelet client library + // to talk to them rather than a separate http client. + transport := &http.Transport{ + Proxy: http.ProxyFromEnvironment, + Dial: (&net.Dialer{ + Timeout: 30 * time.Second, + KeepAlive: 30 * time.Second, + }).Dial, + TLSHandshakeTimeout: 10 * time.Second, + TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, + } + + client = &http.Client{Transport: transport} scheme = "https://" + } else { + client = &http.Client{Transport: rt} } - resp, err := client.Get(scheme + net.JoinHostPort(s.Addr, strconv.Itoa(s.Port)) + s.Path) + + resp, err := client.Get(scheme + net.JoinHostPort(server.Addr, strconv.Itoa(server.Port)) + server.Path) if err != nil { return probe.Unknown, "", err } @@ -70,14 +96,6 @@ func (s *Server) check(client httpGet) (probe.Result, string, error) { return probe.Success, string(data), nil } -type ServerStatus struct { - Component string `json:"component,omitempty"` - Health string `json:"health,omitempty"` - HealthCode probe.Result `json:"healthCode,omitempty"` - Msg string `json:"msg,omitempty"` - Err string `json:"err,omitempty"` -} - func (v *validator) ServeHTTP(w http.ResponseWriter, r *http.Request) { verb := "get" apiResource := "" @@ -88,21 +106,7 @@ func (v *validator) ServeHTTP(w http.ResponseWriter, r *http.Request) { reply := []ServerStatus{} for name, server := range v.servers() { transport := v.rt - if server.EnableHTTPS { - // TODO(roberthbailey): The servers that use HTTPS are currently the - // kubelets, and we should be using a standard kubelet client library - // to talk to them rather than a separate http client. - transport = &http.Transport{ - Proxy: http.ProxyFromEnvironment, - Dial: (&net.Dialer{ - Timeout: 30 * time.Second, - KeepAlive: 30 * time.Second, - }).Dial, - TLSHandshakeTimeout: 10 * time.Second, - TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, - } - } - status, msg, err := server.check(&http.Client{Transport: transport}) + status, msg, err := server.DoServerCheck(transport) var errorMsg string if err != nil { errorMsg = err.Error() diff --git a/pkg/apiserver/validator_test.go b/pkg/apiserver/validator_test.go index 6d0c3a2a0e0..1a840cb3c4e 100644 --- a/pkg/apiserver/validator_test.go +++ b/pkg/apiserver/validator_test.go @@ -65,8 +65,8 @@ func TestValidate(t *testing.T) { StatusCode: test.code, }, } - fake := &http.Client{Transport: fakeRT} - status, data, err := s.check(fake) + // fake := &http.Client{Transport: fakeRT} + status, data, err := s.DoServerCheck(fakeRT) expect := fmt.Sprintf("http://%s:%d/healthz", s.Addr, s.Port) if fakeRT.url != expect { t.Errorf("expected %s, got %s", expect, fakeRT.url) diff --git a/pkg/client/client.go b/pkg/client/client.go index 3903e4324cf..cf99707cb5c 100644 --- a/pkg/client/client.go +++ b/pkg/client/client.go @@ -43,6 +43,7 @@ type Interface interface { NamespacesInterface PersistentVolumesInterface PersistentVolumeClaimsNamespacer + ComponentStatusesInterface } func (c *Client) ReplicationControllers(namespace string) ReplicationControllerInterface { @@ -92,6 +93,10 @@ func (c *Client) PersistentVolumeClaims(namespace string) PersistentVolumeClaimI return newPersistentVolumeClaims(c, namespace) } +func (c *Client) ComponentStatuses() ComponentStatusInterface { + return newComponentStatuses(c) +} + // VersionInterface has a method to retrieve the server version. type VersionInterface interface { ServerVersion() (*version.Info, error) @@ -137,6 +142,25 @@ func (c *Client) ServerAPIVersions() (*api.APIVersions, error) { return &v, nil } +type ComponentValidatorInterface interface { + ValidateComponents() (*api.ComponentStatusList, error) +} + +// ValidateComponents retrieves and parses the master's self-monitored cluster state. +// TODO: This should hit the versioned endpoint when that is implemented. +func (c *Client) ValidateComponents() (*api.ComponentStatusList, error) { + body, err := c.Get().AbsPath("/validate").DoRaw() + if err != nil { + return nil, err + } + + statuses := []api.ComponentStatus{} + if err := json.Unmarshal(body, &statuses); err != nil { + return nil, fmt.Errorf("got '%s': %v", string(body), err) + } + return &api.ComponentStatusList{Items: statuses}, nil +} + // IsTimeout tests if this is a timeout error in the underlying transport. // This is unbelievably ugly. // See: http://stackoverflow.com/questions/23494950/specifically-check-for-timeout-error for details diff --git a/pkg/client/componentstatuses.go b/pkg/client/componentstatuses.go new file mode 100644 index 00000000000..133aae05c3f --- /dev/null +++ b/pkg/client/componentstatuses.go @@ -0,0 +1,63 @@ +/* +Copyright 2015 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 client + +import ( + "github.com/GoogleCloudPlatform/kubernetes/pkg/api" + "github.com/GoogleCloudPlatform/kubernetes/pkg/fields" + "github.com/GoogleCloudPlatform/kubernetes/pkg/labels" +) + +type ComponentStatusesInterface interface { + ComponentStatuses() ComponentStatusInterface +} + +// ComponentStatusInterface contains methods to retrieve ComponentStatus +type ComponentStatusInterface interface { + List(label labels.Selector, field fields.Selector) (*api.ComponentStatusList, error) + Get(name string) (*api.ComponentStatus, error) + + // TODO: It'd be nice to have watch support at some point + //Watch(label labels.Selector, field fields.Selector, resourceVersion string) (watch.Interface, error) +} + +// componentStatuses implements ComponentStatusesInterface +type componentStatuses struct { + client *Client +} + +func newComponentStatuses(c *Client) *componentStatuses { + return &componentStatuses{c} +} + +func (c *componentStatuses) List(label labels.Selector, field fields.Selector) (result *api.ComponentStatusList, err error) { + result = &api.ComponentStatusList{} + err = c.client.Get(). + Resource("componentStatuses"). + LabelsSelectorParam(label). + FieldsSelectorParam(field). + Do(). + Into(result) + + return result, err +} + +func (c *componentStatuses) Get(name string) (result *api.ComponentStatus, err error) { + result = &api.ComponentStatus{} + err = c.client.Get().Resource("componentStatuses").Name(name).Do().Into(result) + return +} diff --git a/pkg/client/testclient/fake_componentstatuses.go b/pkg/client/testclient/fake_componentstatuses.go new file mode 100644 index 00000000000..b14150f63af --- /dev/null +++ b/pkg/client/testclient/fake_componentstatuses.go @@ -0,0 +1,47 @@ +/* +Copyright 2015 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 testclient + +import ( + "github.com/GoogleCloudPlatform/kubernetes/pkg/api" + "github.com/GoogleCloudPlatform/kubernetes/pkg/fields" + "github.com/GoogleCloudPlatform/kubernetes/pkg/labels" +) + +// Fake implements ComponentStatusInterface. +type FakeComponentStatuses struct { + Fake *Fake +} + +func (c *FakeComponentStatuses) List(label labels.Selector, field fields.Selector) (result *api.ComponentStatusList, err error) { + obj, err := c.Fake.Invokes(FakeAction{Action: "list-componentstatuses"}, &api.ComponentStatusList{}) + return obj.(*api.ComponentStatusList), err +} + +func (c *FakeComponentStatuses) Get(name string) (*api.ComponentStatus, error) { + obj, err := c.Fake.Invokes(FakeAction{Action: "get-componentstatus", Value: name}, &api.ComponentStatus{}) + // c.Actions = append(c.Actions, FakeAction{Action: "get-componentstatuses", Value: nil}) + // testStatus := &api.ComponentStatus{ + // Name: "test", + // Health: "ok", + // HealthCode: int(probe.Success), + // Message: "ok", + // Error: "", + // } + // return &api.ComponentStatusList{Items: []api.ComponentStatus{*testStatus}}, nil + return obj.(*api.ComponentStatus), err +} diff --git a/pkg/client/testclient/testclient.go b/pkg/client/testclient/testclient.go index 02799596629..41ec014b153 100644 --- a/pkg/client/testclient/testclient.go +++ b/pkg/client/testclient/testclient.go @@ -125,3 +125,7 @@ func (c *Fake) ServerAPIVersions() (*api.APIVersions, error) { c.Actions = append(c.Actions, FakeAction{Action: "get-apiversions", Value: nil}) return &api.APIVersions{Versions: []string{"v1beta1", "v1beta2"}}, nil } + +func (c *Fake) ComponentStatuses() client.ComponentStatusInterface { + return &FakeComponentStatuses{Fake: c} +} diff --git a/pkg/kubectl/cmd/cmd_test.go b/pkg/kubectl/cmd/cmd_test.go index 3a767b0d684..3ca8aeadc82 100644 --- a/pkg/kubectl/cmd/cmd_test.go +++ b/pkg/kubectl/cmd/cmd_test.go @@ -150,6 +150,13 @@ func NewAPIFactory() (*cmdutil.Factory, *testFactory, runtime.Codec) { Object: func() (meta.RESTMapper, runtime.ObjectTyper) { return latest.RESTMapper, api.Scheme }, + Client: func() (*client.Client, error) { + // Swap out the HTTP client out of the client with the fake's version. + fakeClient := t.Client.(*client.FakeRESTClient) + c := client.NewOrDie(t.ClientConfig) + c.Client = fakeClient.Client + return c, t.Err + }, RESTClient: func(*meta.RESTMapping) (resource.RESTClient, error) { return t.Client, t.Err }, diff --git a/pkg/kubectl/cmd/get.go b/pkg/kubectl/cmd/get.go index 72519966eb4..24c9fc9f97b 100644 --- a/pkg/kubectl/cmd/get.go +++ b/pkg/kubectl/cmd/get.go @@ -34,7 +34,7 @@ const ( get_long = `Display one or many resources. Possible resources include pods (po), replication controllers (rc), services -(svc), minions (mi), or events (ev). +(svc), minions (mi), events (ev), or component statuses (cs). By specifying the output as 'template' and providing a Go template as the value of the --template flag, you can filter the attributes of the fetched resource(s).` diff --git a/pkg/kubectl/cmd/get_test.go b/pkg/kubectl/cmd/get_test.go index a432872bd8c..7ba7177cc8a 100644 --- a/pkg/kubectl/cmd/get_test.go +++ b/pkg/kubectl/cmd/get_test.go @@ -87,6 +87,31 @@ func testData() (*api.PodList, *api.ServiceList, *api.ReplicationControllerList) return pods, svc, rc } +func testComponentStatusData() *api.ComponentStatusList { + good := &api.ComponentStatus{ + Name: "servergood", + Conditions: []api.ComponentCondition{ + {Type: api.ComponentHealthy, Status: api.ConditionTrue, Message: "ok", Error: "nil"}, + }, + } + bad := &api.ComponentStatus{ + Name: "serverbad", + Conditions: []api.ComponentCondition{ + {Type: api.ComponentHealthy, Status: api.ConditionFalse, Message: "", Error: "bad status: 500"}, + }, + } + unknown := &api.ComponentStatus{ + Name: "serverunknown", + Conditions: []api.ComponentCondition{ + {Type: api.ComponentHealthy, Status: api.ConditionUnknown, Message: "", Error: "fizzbuzz error"}, + }, + } + + return &api.ComponentStatusList{ + Items: []api.ComponentStatus{*good, *bad, *unknown}, + } +} + // Verifies that schemas that are not in the master tree of Kubernetes can be retrieved via Get. func TestGetUnknownSchemaObject(t *testing.T) { f, tf, codec := NewTestFactory() @@ -188,6 +213,32 @@ func TestGetListObjects(t *testing.T) { } } +func TestGetListComponentStatus(t *testing.T) { + statuses := testComponentStatusData() + + f, tf, codec := NewAPIFactory() + tf.Printer = &testPrinter{} + tf.Client = &client.FakeRESTClient{ + Codec: codec, + Resp: &http.Response{StatusCode: 200, Body: objBody(codec, statuses)}, + } + tf.Namespace = "test" + buf := bytes.NewBuffer([]byte{}) + + cmd := NewCmdGet(f, buf) + cmd.SetOutput(buf) + cmd.Run(cmd, []string{"componentstatuses"}) + + expected := []runtime.Object{statuses} + actual := tf.Printer.(*testPrinter).Objects + if !reflect.DeepEqual(expected, actual) { + t.Errorf("unexpected object: %#v %#v", expected, actual) + } + if len(buf.String()) == 0 { + t.Errorf("unexpected empty output") + } +} + func TestGetMultipleTypeObjects(t *testing.T) { pods, svc, _ := testData() diff --git a/pkg/kubectl/kubectl.go b/pkg/kubectl/kubectl.go index 51c24ea95a0..301f8599a2c 100644 --- a/pkg/kubectl/kubectl.go +++ b/pkg/kubectl/kubectl.go @@ -96,17 +96,19 @@ func (e ShortcutExpander) VersionAndKindForResource(resource string) (defaultVer // indeed a shortcut. Otherwise, will return resource unmodified. func expandResourceShortcut(resource string) string { shortForms := map[string]string{ - "po": "pods", - "rc": "replicationcontrollers", - // DEPRECATED: will be removed before 1.0 - "se": "services", - "svc": "services", - "mi": "minions", + // Please keep this alphabetized + "cs": "componentstatus", "ev": "events", "limits": "limitRanges", - "quota": "resourceQuotas", + "mi": "minions", + "po": "pods", "pv": "persistentVolumes", "pvc": "persistentVolumeClaims", + "quota": "resourceQuotas", + "rc": "replicationcontrollers", + // DEPRECATED: will be removed before 1.0 + "se": "services", + "svc": "services", } if expanded, ok := shortForms[resource]; ok { return expanded diff --git a/pkg/kubectl/resource_printer.go b/pkg/kubectl/resource_printer.go index e3f393c241d..71e52ac2355 100644 --- a/pkg/kubectl/resource_printer.go +++ b/pkg/kubectl/resource_printer.go @@ -256,6 +256,7 @@ var namespaceColumns = []string{"NAME", "LABELS", "STATUS"} var secretColumns = []string{"NAME", "DATA"} var persistentVolumeColumns = []string{"NAME", "LABELS", "CAPACITY", "ACCESSMODES", "STATUS", "CLAIM"} var persistentVolumeClaimColumns = []string{"NAME", "LABELS", "STATUS", "VOLUME"} +var componentStatusColumns = []string{"NAME", "STATUS", "MESSAGE", "ERROR"} // addDefaultHandlers adds print handlers for default Kubernetes types. func (h *HumanReadablePrinter) addDefaultHandlers() { @@ -284,6 +285,8 @@ func (h *HumanReadablePrinter) addDefaultHandlers() { h.Handler(persistentVolumeClaimColumns, printPersistentVolumeClaimList) h.Handler(persistentVolumeColumns, printPersistentVolume) h.Handler(persistentVolumeColumns, printPersistentVolumeList) + h.Handler(componentStatusColumns, printComponentStatus) + h.Handler(componentStatusColumns, printComponentStatusList) } func (h *HumanReadablePrinter) unknown(data []byte, w io.Writer) error { @@ -647,6 +650,36 @@ func printResourceQuotaList(list *api.ResourceQuotaList, w io.Writer) error { return nil } +func printComponentStatus(item *api.ComponentStatus, w io.Writer) error { + status := "Unknown" + message := "" + error := "" + for _, condition := range item.Conditions { + if condition.Type == api.ComponentHealthy { + if condition.Status == api.ConditionTrue { + status = "Healthy" + } else { + status = "Unhealthy" + } + message = condition.Message + error = condition.Error + break + } + } + _, err := fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", item.Name, status, message, error) + return err +} + +func printComponentStatusList(list *api.ComponentStatusList, w io.Writer) error { + for _, item := range list.Items { + if err := printComponentStatus(&item, w); err != nil { + return err + } + } + + return nil +} + // PrintObj prints the obj in a human-friendly format according to the type of the obj. func (h *HumanReadablePrinter) PrintObj(obj runtime.Object, output io.Writer) error { w := tabwriter.NewWriter(output, 10, 4, 3, ' ', 0) diff --git a/pkg/master/master.go b/pkg/master/master.go index a310bd17668..0b4c582f978 100644 --- a/pkg/master/master.go +++ b/pkg/master/master.go @@ -43,6 +43,7 @@ import ( "github.com/GoogleCloudPlatform/kubernetes/pkg/fields" "github.com/GoogleCloudPlatform/kubernetes/pkg/labels" "github.com/GoogleCloudPlatform/kubernetes/pkg/master/ports" + "github.com/GoogleCloudPlatform/kubernetes/pkg/registry/componentstatus" controlleretcd "github.com/GoogleCloudPlatform/kubernetes/pkg/registry/controller/etcd" "github.com/GoogleCloudPlatform/kubernetes/pkg/registry/endpoint" endpointsetcd "github.com/GoogleCloudPlatform/kubernetes/pkg/registry/endpoint/etcd" @@ -416,6 +417,8 @@ func (m *Master) init(c *Config) { "persistentVolumes/status": persistentVolumeStatusStorage, "persistentVolumeClaims": persistentVolumeClaimStorage, "persistentVolumeClaims/status": persistentVolumeClaimStatusStorage, + + "componentStatuses": componentstatus.NewStorage(func() map[string]apiserver.Server { return m.getServersToValidate(c) }), } apiVersions := []string{"v1beta1", "v1beta2"} diff --git a/pkg/registry/componentstatus/doc.go b/pkg/registry/componentstatus/doc.go new file mode 100644 index 00000000000..ac9f8457305 --- /dev/null +++ b/pkg/registry/componentstatus/doc.go @@ -0,0 +1,19 @@ +/* +Copyright 2015 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 componentstatus provides interfaces and implementation for retrieving cluster +// component status. +package componentstatus diff --git a/pkg/registry/componentstatus/rest.go b/pkg/registry/componentstatus/rest.go new file mode 100644 index 00000000000..6d7b1f6c0c9 --- /dev/null +++ b/pkg/registry/componentstatus/rest.go @@ -0,0 +1,110 @@ +/* +Copyright 2015 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 componentstatus + +import ( + "fmt" + "net/http" + + "github.com/GoogleCloudPlatform/kubernetes/pkg/api" + "github.com/GoogleCloudPlatform/kubernetes/pkg/apiserver" + "github.com/GoogleCloudPlatform/kubernetes/pkg/fields" + "github.com/GoogleCloudPlatform/kubernetes/pkg/labels" + "github.com/GoogleCloudPlatform/kubernetes/pkg/probe" + "github.com/GoogleCloudPlatform/kubernetes/pkg/runtime" +) + +type REST struct { + GetServersToValidate func() map[string]apiserver.Server + rt http.RoundTripper +} + +// NewStorage returns a new REST. +func NewStorage(serverRetriever func() map[string]apiserver.Server) *REST { + return &REST{ + GetServersToValidate: serverRetriever, + rt: http.DefaultTransport, + } +} + +func (rs *REST) New() runtime.Object { + return &api.ComponentStatus{} +} + +func (rs *REST) NewList() runtime.Object { + return &api.ComponentStatusList{} +} + +// Returns the list of component status. Note that the label and field are both ignored. +// Note that this call doesn't support labels or selectors. +func (rs *REST) List(ctx api.Context, label labels.Selector, field fields.Selector) (runtime.Object, error) { + servers := rs.GetServersToValidate() + + // TODO: This should be parallelized. + reply := []api.ComponentStatus{} + for name, server := range servers { + status := rs.getComponentStatus(name, server) + reply = append(reply, *status) + } + return &api.ComponentStatusList{Items: reply}, nil +} + +func (rs *REST) Get(ctx api.Context, name string) (runtime.Object, error) { + servers := rs.GetServersToValidate() + + if server, ok := servers[name]; !ok { + return nil, fmt.Errorf("Component not found: %s", name) + } else { + return rs.getComponentStatus(name, server), nil + } +} + +func ToConditionStatus(s probe.Result) api.ConditionStatus { + switch s { + case probe.Success: + return api.ConditionTrue + case probe.Failure: + return api.ConditionFalse + default: + return api.ConditionUnknown + } +} + +func (rs *REST) getComponentStatus(name string, server apiserver.Server) *api.ComponentStatus { + transport := rs.rt + status, msg, err := server.DoServerCheck(transport) + var errorMsg string + if err != nil { + errorMsg = err.Error() + } else { + errorMsg = "nil" + } + + c := &api.ComponentCondition{ + Type: api.ComponentHealthy, + Status: ToConditionStatus(status), + Message: msg, + Error: errorMsg, + } + + retVal := &api.ComponentStatus{ + Name: name, + Conditions: []api.ComponentCondition{*c}, + } + + return retVal +} diff --git a/pkg/registry/componentstatus/rest_test.go b/pkg/registry/componentstatus/rest_test.go new file mode 100644 index 00000000000..bd7431313eb --- /dev/null +++ b/pkg/registry/componentstatus/rest_test.go @@ -0,0 +1,143 @@ +/* +Copyright 2015 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 componentstatus + +import ( + "bytes" + "fmt" + "io/ioutil" + "net/http" + "reflect" + "strings" + "testing" + + "github.com/GoogleCloudPlatform/kubernetes/pkg/api" + "github.com/GoogleCloudPlatform/kubernetes/pkg/apiserver" + "github.com/GoogleCloudPlatform/kubernetes/pkg/fields" + "github.com/GoogleCloudPlatform/kubernetes/pkg/labels" + "github.com/GoogleCloudPlatform/kubernetes/pkg/util" +) + +type fakeRoundTripper struct { + err error + resp *http.Response + url string +} + +func (f *fakeRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { + f.url = req.URL.String() + return f.resp, f.err +} + +type testResponse struct { + code int + data string + err error +} + +func NewTestREST(resp testResponse) *REST { + return &REST{ + GetServersToValidate: func() map[string]apiserver.Server { + return map[string]apiserver.Server{ + "test1": {Addr: "testserver1", Port: 8000, Path: "/healthz"}, + } + }, + rt: &fakeRoundTripper{ + err: resp.err, + resp: &http.Response{ + Body: ioutil.NopCloser(bytes.NewBufferString(resp.data)), + StatusCode: resp.code, + }, + }, + } +} + +func createTestStatus(name string, status api.ConditionStatus, msg string, err string) *api.ComponentStatus { + return &api.ComponentStatus{ + Name: name, + Conditions: []api.ComponentCondition{ + {Type: api.ComponentHealthy, Status: status, Message: msg, Error: err}, + }, + } +} + +func TestList_NoError(t *testing.T) { + r := NewTestREST(testResponse{code: 200, data: "ok"}) + got, err := r.List(api.NewContext(), labels.Everything(), fields.Everything()) + if err != nil { + t.Fatalf("Unexpected error: %v", err) + } + expect := &api.ComponentStatusList{ + Items: []api.ComponentStatus{*(createTestStatus("test1", api.ConditionTrue, "ok", "nil"))}, + } + if e, a := expect, got; !reflect.DeepEqual(e, a) { + t.Errorf("Got unexpected object. Diff: %s", util.ObjectDiff(e, a)) + } +} + +func TestList_FailedCheck(t *testing.T) { + r := NewTestREST(testResponse{code: 500, data: ""}) + got, err := r.List(api.NewContext(), labels.Everything(), fields.Everything()) + if err != nil { + t.Fatalf("Unexpected error: %v", err) + } + expect := &api.ComponentStatusList{ + Items: []api.ComponentStatus{ + *(createTestStatus("test1", api.ConditionFalse, "", "unhealthy http status code: 500 ()"))}, + } + if e, a := expect, got; !reflect.DeepEqual(e, a) { + t.Errorf("Got unexpected object. Diff: %s", util.ObjectDiff(e, a)) + } +} + +func TestList_UnknownError(t *testing.T) { + r := NewTestREST(testResponse{code: 500, data: "", err: fmt.Errorf("fizzbuzz error")}) + got, err := r.List(api.NewContext(), labels.Everything(), fields.Everything()) + if err != nil { + t.Fatalf("Unexpected error: %v", err) + } + expect := &api.ComponentStatusList{ + Items: []api.ComponentStatus{ + *(createTestStatus("test1", api.ConditionUnknown, "", "Get http://testserver1:8000/healthz: fizzbuzz error"))}, + } + if e, a := expect, got; !reflect.DeepEqual(e, a) { + t.Errorf("Got unexpected object. Diff: %s", util.ObjectDiff(e, a)) + } +} + +func TestGet_NoError(t *testing.T) { + r := NewTestREST(testResponse{code: 200, data: "ok"}) + got, err := r.Get(api.NewContext(), "test1") + if err != nil { + t.Fatalf("Unexpected error: %v", err) + } + expect := createTestStatus("test1", api.ConditionTrue, "ok", "nil") + if e, a := expect, got; !reflect.DeepEqual(e, a) { + t.Errorf("Got unexpected object. Diff: %s", util.ObjectDiff(e, a)) + } +} + +func TestGet_BadName(t *testing.T) { + r := NewTestREST(testResponse{code: 200, data: "ok"}) + _, err := r.Get(api.NewContext(), "invalidname") + if err == nil { + t.Fatalf("Expected error, but did not get one") + } + if !strings.Contains(err.Error(), "Component not found: invalidname") { + t.Fatalf("Got unexpected error: %v", err) + } +}