...

Source file src/k8s.io/kubernetes/pkg/probe/tcp/tcp.go

Documentation: k8s.io/kubernetes/pkg/probe/tcp

     1  /*
     2  Copyright 2015 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package tcp
    18  
    19  import (
    20  	"net"
    21  	"strconv"
    22  	"time"
    23  
    24  	"k8s.io/kubernetes/pkg/probe"
    25  
    26  	"k8s.io/klog/v2"
    27  )
    28  
    29  // New creates Prober.
    30  func New() Prober {
    31  	return tcpProber{}
    32  }
    33  
    34  // Prober is an interface that defines the Probe function for doing TCP readiness/liveness checks.
    35  type Prober interface {
    36  	Probe(host string, port int, timeout time.Duration) (probe.Result, string, error)
    37  }
    38  
    39  type tcpProber struct{}
    40  
    41  // Probe checks that a TCP connection to the address can be opened.
    42  func (pr tcpProber) Probe(host string, port int, timeout time.Duration) (probe.Result, string, error) {
    43  	return DoTCPProbe(net.JoinHostPort(host, strconv.Itoa(port)), timeout)
    44  }
    45  
    46  // DoTCPProbe checks that a TCP socket to the address can be opened.
    47  // If the socket can be opened, it returns Success
    48  // If the socket fails to open, it returns Failure.
    49  // This is exported because some other packages may want to do direct TCP probes.
    50  func DoTCPProbe(addr string, timeout time.Duration) (probe.Result, string, error) {
    51  	d := probe.ProbeDialer()
    52  	d.Timeout = timeout
    53  	conn, err := d.Dial("tcp", addr)
    54  	if err != nil {
    55  		// Convert errors to failures to handle timeouts.
    56  		return probe.Failure, err.Error(), nil
    57  	}
    58  	err = conn.Close()
    59  	if err != nil {
    60  		klog.Errorf("Unexpected error closing TCP probe socket: %v (%#v)", err, err)
    61  	}
    62  	return probe.Success, "", nil
    63  }
    64  

View as plain text