| 1 |
package stressClient |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"fmt" |
| 6 |
"io" |
| 7 |
"io/ioutil" |
| 8 |
"net/http" |
| 9 |
"time" |
| 10 |
) |
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
func (sc *stressClient) spinOffWritePackage(p Package, serv int) { |
| 18 |
sc.Add(1) |
| 19 |
sc.wc.Increment() |
| 20 |
go func() { |
| 21 |
sc.retry(p, time.Duration(time.Nanosecond), serv) |
| 22 |
sc.Done() |
| 23 |
sc.wc.Decrement() |
| 24 |
}() |
| 25 |
} |
| 26 |
|
| 27 |
|
| 28 |
func (sc *stressClient) retry(p Package, backoff time.Duration, serv int) { |
| 29 |
|
| 30 |
|
| 31 |
backoffInterval := time.Duration(500 * time.Millisecond) |
| 32 |
|
| 33 |
|
| 34 |
bo := backoff + backoffInterval |
| 35 |
|
| 36 |
|
| 37 |
resp, elapsed, err := sc.prepareWrite(p.Body, serv) |
| 38 |
|
| 39 |
|
| 40 |
numBackoffs := int(bo/backoffInterval) - 1 |
| 41 |
|
| 42 |
|
| 43 |
var statusCode int |
| 44 |
|
| 45 |
if resp == nil { |
| 46 |
statusCode = 500 |
| 47 |
} else { |
| 48 |
statusCode = resp.StatusCode |
| 49 |
} |
| 50 |
|
| 51 |
|
| 52 |
point := sc.writePoint(numBackoffs, p.StatementID, statusCode, elapsed, p.Tracer.Tags, len(p.Body)) |
| 53 |
|
| 54 |
|
| 55 |
sc.responseChan <- NewResponse(point, p.Tracer) |
| 56 |
|
| 57 |
|
| 58 |
bi, _ := time.ParseDuration(sc.wdelay) |
| 59 |
time.Sleep(bi) |
| 60 |
|
| 61 |
|
| 62 |
if !(statusCode == 204) || err != nil { |
| 63 |
|
| 64 |
p.Tracer.Add(1) |
| 65 |
|
| 66 |
fmt.Println(err) |
| 67 |
|
| 68 |
time.Sleep(bo) |
| 69 |
sc.retry(p, bo, serv) |
| 70 |
} |
| 71 |
|
| 72 |
} |
| 73 |
|
| 74 |
|
| 75 |
func (sc *stressClient) prepareWrite(points []byte, serv int) (*http.Response, time.Duration, error) { |
| 76 |
|
| 77 |
|
| 78 |
var writeTemplate string |
| 79 |
if sc.ssl { |
| 80 |
writeTemplate = "https://%v/write?db=%v&precision=%v&u=%v&p=%v" |
| 81 |
} else { |
| 82 |
writeTemplate = "http://%v/write?db=%v&precision=%v&u=%v&p=%v" |
| 83 |
} |
| 84 |
address := fmt.Sprintf(writeTemplate, sc.addresses[serv], sc.database, sc.precision, sc.username, sc.password) |
| 85 |
|
| 86 |
|
| 87 |
t := time.Now() |
| 88 |
resp, err := makePost(address, bytes.NewBuffer(points)) |
| 89 |
elapsed := time.Since(t) |
| 90 |
|
| 91 |
return resp, elapsed, err |
| 92 |
} |
| 93 |
|
| 94 |
|
| 95 |
func makePost(url string, points io.Reader) (*http.Response, error) { |
| 96 |
|
| 97 |
resp, err := http.Post(url, "text/plain", points) |
| 98 |
|
| 99 |
if err != nil { |
| 100 |
return resp, fmt.Errorf("Error making write POST request\n error: %v\n url: %v\n", err, url) |
| 101 |
} |
| 102 |
|
| 103 |
body, _ := ioutil.ReadAll(resp.Body) |
| 104 |
|
| 105 |
if resp.StatusCode != 204 { |
| 106 |
return resp, fmt.Errorf("Write returned non-204 status code\n StatusCode: %v\n InfluxDB Error: %v\n", resp.StatusCode, string(body)) |
| 107 |
} |
| 108 |
|
| 109 |
resp.Body.Close() |
| 110 |
|
| 111 |
return resp, nil |
| 112 |
} |