tcp.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. Copyright 2015 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 tcp
  14. import (
  15. "net"
  16. "strconv"
  17. "time"
  18. "k8s.io/kubernetes/pkg/probe"
  19. "k8s.io/klog"
  20. )
  21. // New creates Prober.
  22. func New() Prober {
  23. return tcpProber{}
  24. }
  25. // Prober is an interface that defines the Probe function for doing TCP readiness/liveness checks.
  26. type Prober interface {
  27. Probe(host string, port int, timeout time.Duration) (probe.Result, string, error)
  28. }
  29. type tcpProber struct{}
  30. // Probe returns a ProbeRunner capable of running an TCP check.
  31. func (pr tcpProber) Probe(host string, port int, timeout time.Duration) (probe.Result, string, error) {
  32. return DoTCPProbe(net.JoinHostPort(host, strconv.Itoa(port)), timeout)
  33. }
  34. // DoTCPProbe checks that a TCP socket to the address can be opened.
  35. // If the socket can be opened, it returns Success
  36. // If the socket fails to open, it returns Failure.
  37. // This is exported because some other packages may want to do direct TCP probes.
  38. func DoTCPProbe(addr string, timeout time.Duration) (probe.Result, string, error) {
  39. conn, err := net.DialTimeout("tcp", addr, timeout)
  40. if err != nil {
  41. // Convert errors to failures to handle timeouts.
  42. return probe.Failure, err.Error(), nil
  43. }
  44. err = conn.Close()
  45. if err != nil {
  46. klog.Errorf("Unexpected error closing TCP probe socket: %v (%#v)", err, err)
  47. }
  48. return probe.Success, "", nil
  49. }