checks.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. // Copyright 2020 by the contributors.
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package healthcheck
  15. import (
  16. "context"
  17. "database/sql"
  18. "fmt"
  19. "net"
  20. "net/http"
  21. "runtime"
  22. "time"
  23. )
  24. // TCPDialCheck returns a Check that checks TCP connectivity to the provided
  25. // endpoint.
  26. func TCPDialCheck(addr string, timeout time.Duration) Check {
  27. return func() error {
  28. conn, err := net.DialTimeout("tcp", addr, timeout)
  29. if err != nil {
  30. return err
  31. }
  32. return conn.Close()
  33. }
  34. }
  35. // HTTPGetCheck returns a Check that performs an HTTP GET request against the
  36. // specified URL. The check fails if the response times out or returns a non-200
  37. // status code.
  38. func HTTPGetCheck(url string, timeout time.Duration) Check {
  39. return func() error {
  40. return HTTPCheck(url, http.MethodGet, http.StatusOK, timeout)()
  41. }
  42. }
  43. // HTTPCheck returns a Check that performs a HTTP request against the specified URL.
  44. // The Check fails if the response times out or returns an unexpected status code.
  45. func HTTPCheck(url string, method string, status int, timeout time.Duration) Check {
  46. client := &http.Client{
  47. Timeout: timeout,
  48. CheckRedirect: func(*http.Request, []*http.Request) error {
  49. return http.ErrUseLastResponse
  50. },
  51. }
  52. return HTTPCheckClient(client, url, method, status, timeout)
  53. }
  54. // HTTPCheckClient returns a Check that performs a HTTP request against the specified URL.
  55. // The Check fails if the response times out or returns an unexpected status code.
  56. // On top of that it uses a custom client specified by the caller.
  57. func HTTPCheckClient(client *http.Client, url string, method string, status int, timeout time.Duration) Check {
  58. return func() error {
  59. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  60. defer cancel()
  61. req, err := http.NewRequest(method, url, nil)
  62. if err != nil {
  63. return err
  64. }
  65. req = req.WithContext(ctx)
  66. resp, err := client.Do(req)
  67. if err != nil {
  68. return err
  69. }
  70. defer resp.Body.Close()
  71. if resp.StatusCode != status {
  72. return fmt.Errorf("returned status %d, expected %d", resp.StatusCode, status)
  73. }
  74. return nil
  75. }
  76. }
  77. // DatabasePingCheck returns a Check that validates connectivity to a
  78. // database/sql.DB using Ping().
  79. func DatabasePingCheck(database *sql.DB, timeout time.Duration) Check {
  80. return func() error {
  81. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  82. defer cancel()
  83. if database == nil {
  84. return fmt.Errorf("database is nil")
  85. }
  86. return database.PingContext(ctx)
  87. }
  88. }
  89. // DNSResolveCheck returns a Check that makes sure the provided host can resolve
  90. // to at least one IP address within the specified timeout.
  91. func DNSResolveCheck(host string, timeout time.Duration) Check {
  92. resolver := net.Resolver{}
  93. return func() error {
  94. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  95. defer cancel()
  96. addrs, err := resolver.LookupHost(ctx, host)
  97. if err != nil {
  98. return err
  99. }
  100. if len(addrs) < 1 {
  101. return fmt.Errorf("could not resolve host")
  102. }
  103. return nil
  104. }
  105. }
  106. // GoroutineCountCheck returns a Check that fails if too many goroutines are
  107. // running (which could indicate a resource leak).
  108. func GoroutineCountCheck(threshold int) Check {
  109. return func() error {
  110. count := runtime.NumGoroutine()
  111. if count > threshold {
  112. return fmt.Errorf("too many goroutines (%d > %d)", count, threshold)
  113. }
  114. return nil
  115. }
  116. }