tcp.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. "github.com/golang/glog"
  20. )
  21. func New() TCPProber {
  22. return tcpProber{}
  23. }
  24. type TCPProber interface {
  25. Probe(host string, port int, timeout time.Duration) (probe.Result, string, error)
  26. }
  27. type tcpProber struct{}
  28. func (pr tcpProber) Probe(host string, port int, timeout time.Duration) (probe.Result, string, error) {
  29. return DoTCPProbe(net.JoinHostPort(host, strconv.Itoa(port)), timeout)
  30. }
  31. // DoTCPProbe checks that a TCP socket to the address can be opened.
  32. // If the socket can be opened, it returns Success
  33. // If the socket fails to open, it returns Failure.
  34. // This is exported because some other packages may want to do direct TCP probes.
  35. func DoTCPProbe(addr string, timeout time.Duration) (probe.Result, string, error) {
  36. conn, err := net.DialTimeout("tcp", addr, timeout)
  37. if err != nil {
  38. // Convert errors to failures to handle timeouts.
  39. return probe.Failure, err.Error(), nil
  40. }
  41. err = conn.Close()
  42. if err != nil {
  43. glog.Errorf("Unexpected error closing TCP probe socket: %v (%#v)", err, err)
  44. }
  45. return probe.Success, "", nil
  46. }