7 "git.curoverse.com/arvados.git/sdk/go/streamer"
17 // Function used to emit debug messages. The easiest way to enable
18 // keepclient debug messages in your application is to assign
19 // log.Printf to DebugPrintf.
20 var DebugPrintf = func(string, ...interface{}) {}
22 type keepService struct {
23 Uuid string `json:"uuid"`
24 Hostname string `json:"service_host"`
25 Port int `json:"service_port"`
26 SSL bool `json:"service_ssl_flag"`
27 SvcType string `json:"service_type"`
28 ReadOnly bool `json:"read_only"`
31 // Md5String returns md5 hash for the bytes in the given string
32 func Md5String(s string) string {
33 return fmt.Sprintf("%x", md5.Sum([]byte(s)))
36 // Set timeouts applicable when connecting to non-disk services
37 // (assumed to be over the Internet).
38 func (this *KeepClient) setClientSettingsNonDisk() {
39 if this.Client.Timeout == 0 {
40 // Maximum time to wait for a complete response
41 this.Client.Timeout = 300 * time.Second
43 // TCP and TLS connection settings
44 this.Client.Transport = &http.Transport{
46 // The maximum time to wait to set up
47 // the initial TCP connection.
48 Timeout: 30 * time.Second,
50 // The TCP keep alive heartbeat
52 KeepAlive: 120 * time.Second,
55 TLSHandshakeTimeout: 10 * time.Second,
60 // Set timeouts applicable when connecting to keepstore services directly
61 // (assumed to be on the local network).
62 func (this *KeepClient) setClientSettingsDisk() {
63 if this.Client.Timeout == 0 {
64 // Maximum time to wait for a complete response
65 this.Client.Timeout = 20 * time.Second
67 // TCP and TLS connection timeouts
68 this.Client.Transport = &http.Transport{
70 // The maximum time to wait to set up
71 // the initial TCP connection.
72 Timeout: 2 * time.Second,
74 // The TCP keep alive heartbeat
76 KeepAlive: 180 * time.Second,
79 TLSHandshakeTimeout: 4 * time.Second,
85 Items []keepService `json:"items"`
88 type uploadStatus struct {
96 func (this *KeepClient) uploadToKeepServer(host string, hash string, body io.ReadCloser,
97 upload_status chan<- uploadStatus, expectedLength int64, requestID int32) {
101 var url = fmt.Sprintf("%s/%s", host, hash)
102 if req, err = http.NewRequest("PUT", url, nil); err != nil {
103 DebugPrintf("DEBUG: [%08x] Error creating request PUT %v error: %v", requestID, url, err.Error())
104 upload_status <- uploadStatus{err, url, 0, 0, ""}
109 req.ContentLength = expectedLength
110 if expectedLength > 0 {
111 // http.Client.Do will close the body ReadCloser when it is
115 // "For client requests, a value of 0 means unknown if Body is
116 // not nil." In this case we do want the body to be empty, so
117 // don't set req.Body. However, we still need to close the
122 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", this.Arvados.ApiToken))
123 req.Header.Add("Content-Type", "application/octet-stream")
124 req.Header.Add(X_Keep_Desired_Replicas, fmt.Sprint(this.Want_replicas))
126 var resp *http.Response
127 if resp, err = this.Client.Do(req); err != nil {
128 DebugPrintf("DEBUG: [%08x] Upload failed %v error: %v", requestID, url, err.Error())
129 upload_status <- uploadStatus{err, url, 0, 0, ""}
134 if xr := resp.Header.Get(X_Keep_Replicas_Stored); xr != "" {
135 fmt.Sscanf(xr, "%d", &rep)
138 defer resp.Body.Close()
139 defer io.Copy(ioutil.Discard, resp.Body)
141 respbody, err2 := ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 4096})
142 response := strings.TrimSpace(string(respbody))
143 if err2 != nil && err2 != io.EOF {
144 DebugPrintf("DEBUG: [%08x] Upload %v error: %v response: %v", requestID, url, err2.Error(), response)
145 upload_status <- uploadStatus{err2, url, resp.StatusCode, rep, response}
146 } else if resp.StatusCode == http.StatusOK {
147 DebugPrintf("DEBUG: [%08x] Upload %v success", requestID, url)
148 upload_status <- uploadStatus{nil, url, resp.StatusCode, rep, response}
150 DebugPrintf("DEBUG: [%08x] Upload %v error: %v response: %v", requestID, url, resp.StatusCode, response)
151 upload_status <- uploadStatus{errors.New(resp.Status), url, resp.StatusCode, rep, response}
155 func (this *KeepClient) putReplicas(
157 tr *streamer.AsyncStream,
158 expectedLength int64) (locator string, replicas int, err error) {
160 // Generate an arbitrary ID to identify this specific
161 // transaction in debug logs.
162 requestID := rand.Int31()
164 // Calculate the ordering for uploading to servers
165 sv := NewRootSorter(this.WritableLocalRoots(), hash).GetSortedRoots()
167 // The next server to try contacting
170 // The number of active writers
173 // Used to communicate status from the upload goroutines
174 upload_status := make(chan uploadStatus)
176 // Wait for any abandoned uploads (e.g., we started
177 // two uploads and the first replied with replicas=2)
178 // to finish before closing the status channel.
188 replicasTodo := this.Want_replicas
190 replicasPerThread := this.replicasPerService
191 if replicasPerThread < 1 {
192 // unlimited or unknown
193 replicasPerThread = replicasTodo
196 retriesRemaining := 1 + this.Retries
197 var retryServers []string
199 for retriesRemaining > 0 {
200 retriesRemaining -= 1
202 retryServers = []string{}
203 for replicasTodo > 0 {
204 for active*replicasPerThread < replicasTodo {
205 // Start some upload requests
206 if next_server < len(sv) {
207 DebugPrintf("DEBUG: [%08x] Begin upload %s to %s", requestID, hash, sv[next_server])
208 go this.uploadToKeepServer(sv[next_server], hash, tr.MakeStreamReader(), upload_status, expectedLength, requestID)
212 if active == 0 && retriesRemaining == 0 {
213 return locator, replicasDone, InsufficientReplicasError
219 DebugPrintf("DEBUG: [%08x] Replicas remaining to write: %v active uploads: %v",
220 requestID, replicasTodo, active)
222 // Now wait for something to happen.
224 status := <-upload_status
227 if status.statusCode == 200 {
229 replicasDone += status.replicas_stored
230 replicasTodo -= status.replicas_stored
231 locator = status.response
232 } else if status.statusCode == 0 || status.statusCode == 408 || status.statusCode == 429 ||
233 (status.statusCode >= 500 && status.statusCode != 503) {
234 // Timeout, too many requests, or other server side failure
235 // Do not retry when status code is 503, which means the keep server is full
236 retryServers = append(retryServers, status.url[0:strings.LastIndex(status.url, "/")])
246 return locator, replicasDone, nil