validator.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package componentstatus
  14. import (
  15. "crypto/tls"
  16. "sync"
  17. "time"
  18. utilnet "k8s.io/apimachinery/pkg/util/net"
  19. "k8s.io/kubernetes/pkg/probe"
  20. httpprober "k8s.io/kubernetes/pkg/probe/http"
  21. )
  22. const (
  23. probeTimeOut = 20 * time.Second
  24. )
  25. type ValidatorFn func([]byte) error
  26. type Server struct {
  27. Addr string
  28. Port int
  29. Path string
  30. EnableHTTPS bool
  31. TLSConfig *tls.Config
  32. Validate ValidatorFn
  33. Prober httpprober.Prober
  34. Once sync.Once
  35. }
  36. type ServerStatus struct {
  37. // +optional
  38. Component string `json:"component,omitempty"`
  39. // +optional
  40. Health string `json:"health,omitempty"`
  41. // +optional
  42. HealthCode probe.Result `json:"healthCode,omitempty"`
  43. // +optional
  44. Msg string `json:"msg,omitempty"`
  45. // +optional
  46. Err string `json:"err,omitempty"`
  47. }
  48. func (server *Server) DoServerCheck() (probe.Result, string, error) {
  49. // setup the prober
  50. server.Once.Do(func() {
  51. if server.Prober != nil {
  52. return
  53. }
  54. const followNonLocalRedirects = true
  55. server.Prober = httpprober.NewWithTLSConfig(server.TLSConfig, followNonLocalRedirects)
  56. })
  57. scheme := "http"
  58. if server.EnableHTTPS {
  59. scheme = "https"
  60. }
  61. url := utilnet.FormatURL(scheme, server.Addr, server.Port, server.Path)
  62. result, data, err := server.Prober.Probe(url, nil, probeTimeOut)
  63. if err != nil {
  64. return probe.Unknown, "", err
  65. }
  66. if result == probe.Failure {
  67. return probe.Failure, string(data), err
  68. }
  69. if server.Validate != nil {
  70. if err := server.Validate([]byte(data)); err != nil {
  71. return probe.Failure, string(data), err
  72. }
  73. }
  74. return result, string(data), nil
  75. }