15 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
16 "git.curoverse.com/arvados.git/sdk/go/streamer"
19 // Function used to emit debug messages. The easiest way to enable
20 // keepclient debug messages in your application is to assign
21 // log.Printf to DebugPrintf.
22 var DebugPrintf = func(string, ...interface{}) {}
25 if arvadosclient.StringBool(os.Getenv("ARVADOS_DEBUG")) {
26 DebugPrintf = log.Printf
30 type keepService struct {
31 Uuid string `json:"uuid"`
32 Hostname string `json:"service_host"`
33 Port int `json:"service_port"`
34 SSL bool `json:"service_ssl_flag"`
35 SvcType string `json:"service_type"`
36 ReadOnly bool `json:"read_only"`
39 // Md5String returns md5 hash for the bytes in the given string
40 func Md5String(s string) string {
41 return fmt.Sprintf("%x", md5.Sum([]byte(s)))
45 Items []keepService `json:"items"`
48 type uploadStatus struct {
56 func (this *KeepClient) uploadToKeepServer(host string, hash string, body io.ReadCloser,
57 upload_status chan<- uploadStatus, expectedLength int64, requestID int32) {
61 var url = fmt.Sprintf("%s/%s", host, hash)
62 if req, err = http.NewRequest("PUT", url, nil); err != nil {
63 DebugPrintf("DEBUG: [%08x] Error creating request PUT %v error: %v", requestID, url, err.Error())
64 upload_status <- uploadStatus{err, url, 0, 0, ""}
69 req.ContentLength = expectedLength
70 if expectedLength > 0 {
71 // Do() will close the body ReadCloser when it is done
75 // "For client requests, a value of 0 means unknown if Body is
76 // not nil." In this case we do want the body to be empty, so
77 // don't set req.Body. However, we still need to close the
82 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", this.Arvados.ApiToken))
83 req.Header.Add("Content-Type", "application/octet-stream")
84 req.Header.Add(X_Keep_Desired_Replicas, fmt.Sprint(this.Want_replicas))
86 var resp *http.Response
87 if resp, err = this.httpClient().Do(req); err != nil {
88 DebugPrintf("DEBUG: [%08x] Upload failed %v error: %v", requestID, url, err.Error())
89 upload_status <- uploadStatus{err, url, 0, 0, ""}
94 if xr := resp.Header.Get(X_Keep_Replicas_Stored); xr != "" {
95 fmt.Sscanf(xr, "%d", &rep)
98 defer resp.Body.Close()
99 defer io.Copy(ioutil.Discard, resp.Body)
101 respbody, err2 := ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 4096})
102 response := strings.TrimSpace(string(respbody))
103 if err2 != nil && err2 != io.EOF {
104 DebugPrintf("DEBUG: [%08x] Upload %v error: %v response: %v", requestID, url, err2.Error(), response)
105 upload_status <- uploadStatus{err2, url, resp.StatusCode, rep, response}
106 } else if resp.StatusCode == http.StatusOK {
107 DebugPrintf("DEBUG: [%08x] Upload %v success", requestID, url)
108 upload_status <- uploadStatus{nil, url, resp.StatusCode, rep, response}
110 if resp.StatusCode >= 300 && response == "" {
111 response = resp.Status
113 DebugPrintf("DEBUG: [%08x] Upload %v error: %v response: %v", requestID, url, resp.StatusCode, response)
114 upload_status <- uploadStatus{errors.New(resp.Status), url, resp.StatusCode, rep, response}
118 func (this *KeepClient) putReplicas(
120 tr *streamer.AsyncStream,
121 expectedLength int64) (locator string, replicas int, err error) {
123 // Generate an arbitrary ID to identify this specific
124 // transaction in debug logs.
125 requestID := rand.Int31()
127 // Calculate the ordering for uploading to servers
128 sv := NewRootSorter(this.WritableLocalRoots(), hash).GetSortedRoots()
130 // The next server to try contacting
133 // The number of active writers
136 // Used to communicate status from the upload goroutines
137 upload_status := make(chan uploadStatus)
139 // Wait for any abandoned uploads (e.g., we started
140 // two uploads and the first replied with replicas=2)
141 // to finish before closing the status channel.
151 replicasTodo := this.Want_replicas
153 replicasPerThread := this.replicasPerService
154 if replicasPerThread < 1 {
155 // unlimited or unknown
156 replicasPerThread = replicasTodo
159 retriesRemaining := 1 + this.Retries
160 var retryServers []string
162 lastError := make(map[string]string)
164 for retriesRemaining > 0 {
165 retriesRemaining -= 1
167 retryServers = []string{}
168 for replicasTodo > 0 {
169 for active*replicasPerThread < replicasTodo {
170 // Start some upload requests
171 if next_server < len(sv) {
172 DebugPrintf("DEBUG: [%08x] Begin upload %s to %s", requestID, hash, sv[next_server])
173 go this.uploadToKeepServer(sv[next_server], hash, tr.MakeStreamReader(), upload_status, expectedLength, requestID)
177 if active == 0 && retriesRemaining == 0 {
178 msg := "Could not write sufficient replicas: "
179 for _, resp := range lastError {
182 msg = msg[:len(msg)-2]
183 return locator, replicasDone, InsufficientReplicasError(errors.New(msg))
189 DebugPrintf("DEBUG: [%08x] Replicas remaining to write: %v active uploads: %v",
190 requestID, replicasTodo, active)
192 // Now wait for something to happen.
194 status := <-upload_status
197 if status.statusCode == 200 {
199 replicasDone += status.replicas_stored
200 replicasTodo -= status.replicas_stored
201 locator = status.response
202 delete(lastError, status.url)
204 msg := fmt.Sprintf("[%d] %s", status.statusCode, status.response)
208 lastError[status.url] = msg
211 if status.statusCode == 0 || status.statusCode == 408 || status.statusCode == 429 ||
212 (status.statusCode >= 500 && status.statusCode != 503) {
213 // Timeout, too many requests, or other server side failure
214 // Do not retry when status code is 503, which means the keep server is full
215 retryServers = append(retryServers, status.url[0:strings.LastIndex(status.url, "/")])
225 return locator, replicasDone, nil