github.com/npaton/distribution@v2.3.1-rc.0+incompatible/health/checks/checks.go (about)

     1  package checks
     2  
     3  import (
     4  	"errors"
     5  	"net"
     6  	"net/http"
     7  	"os"
     8  	"strconv"
     9  	"time"
    10  
    11  	"github.com/docker/distribution/health"
    12  )
    13  
    14  // FileChecker checks the existence of a file and returns an error
    15  // if the file exists.
    16  func FileChecker(f string) health.Checker {
    17  	return health.CheckFunc(func() error {
    18  		if _, err := os.Stat(f); err == nil {
    19  			return errors.New("file exists")
    20  		}
    21  		return nil
    22  	})
    23  }
    24  
    25  // HTTPChecker does a HEAD request and verifies that the HTTP status code
    26  // returned matches statusCode.
    27  func HTTPChecker(r string, statusCode int, timeout time.Duration, headers http.Header) health.Checker {
    28  	return health.CheckFunc(func() error {
    29  		client := http.Client{
    30  			Timeout: timeout,
    31  		}
    32  		req, err := http.NewRequest("HEAD", r, nil)
    33  		if err != nil {
    34  			return errors.New("error creating request: " + r)
    35  		}
    36  		for headerName, headerValues := range headers {
    37  			for _, headerValue := range headerValues {
    38  				req.Header.Add(headerName, headerValue)
    39  			}
    40  		}
    41  		response, err := client.Do(req)
    42  		if err != nil {
    43  			return errors.New("error while checking: " + r)
    44  		}
    45  		if response.StatusCode != statusCode {
    46  			return errors.New("downstream service returned unexpected status: " + strconv.Itoa(response.StatusCode))
    47  		}
    48  		return nil
    49  	})
    50  }
    51  
    52  // TCPChecker attempts to open a TCP connection.
    53  func TCPChecker(addr string, timeout time.Duration) health.Checker {
    54  	return health.CheckFunc(func() error {
    55  		conn, err := net.DialTimeout("tcp", addr, timeout)
    56  		if err != nil {
    57  			return errors.New("connection to " + addr + " failed")
    58  		}
    59  		conn.Close()
    60  		return nil
    61  	})
    62  }