github.com/coreos/mantle@v0.13.0/network/retrydialer.go (about) 1 // Copyright 2015 CoreOS, Inc. 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 15 package network 16 17 import ( 18 "net" 19 "time" 20 ) 21 22 const ( 23 // DefaultTimeout sets the default timeout for RetryDialer. 24 DefaultTimeout = 5 * time.Second 25 26 // DefaultKeepAlive sets the default keepalive for RetryDialer. 27 DefaultKeepAlive = 30 * time.Second 28 29 // DefaultRetries sets the default number of retries for RetryDialer. 30 DefaultRetries = 7 31 ) 32 33 // RetryDialer is intended to timeout quickly and retry connecting instead 34 // of just failing. Particularly useful for waiting on a booting machine. 35 type RetryDialer struct { 36 net.Dialer 37 Retries int 38 } 39 40 // NewRetryDialer initializes a RetryDialer with reasonable default settings. 41 func NewRetryDialer() *RetryDialer { 42 return &RetryDialer{ 43 Dialer: net.Dialer{ 44 Timeout: DefaultTimeout, 45 KeepAlive: DefaultKeepAlive, 46 }, 47 Retries: DefaultRetries, 48 } 49 } 50 51 // Dial connects to a remote address, retrying on failure. 52 func (d *RetryDialer) Dial(network, address string) (c net.Conn, err error) { 53 for i := 0; i < d.Retries; i++ { 54 c, err = d.Dialer.Dial(network, address) 55 if err == nil { 56 return 57 } 58 } 59 return 60 }