1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
18 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
21 // Function used to emit debug messages. The easiest way to enable
22 // keepclient debug messages in your application is to assign
23 // log.Printf to DebugPrintf.
24 var DebugPrintf = func(string, ...interface{}) {}
27 if arvadosclient.StringBool(os.Getenv("ARVADOS_DEBUG")) {
28 DebugPrintf = log.Printf
32 type keepService struct {
33 Uuid string `json:"uuid"`
34 Hostname string `json:"service_host"`
35 Port int `json:"service_port"`
36 SSL bool `json:"service_ssl_flag"`
37 SvcType string `json:"service_type"`
38 ReadOnly bool `json:"read_only"`
41 // Md5String returns md5 hash for the bytes in the given string
42 func Md5String(s string) string {
43 return fmt.Sprintf("%x", md5.Sum([]byte(s)))
47 Items []keepService `json:"items"`
50 type uploadStatus struct {
58 func (this *KeepClient) uploadToKeepServer(host string, hash string, body io.Reader,
59 upload_status chan<- uploadStatus, expectedLength int64, reqid string) {
63 var url = fmt.Sprintf("%s/%s", host, hash)
64 if req, err = http.NewRequest("PUT", url, nil); err != nil {
65 DebugPrintf("DEBUG: [%s] Error creating request PUT %v error: %v", reqid, url, err.Error())
66 upload_status <- uploadStatus{err, url, 0, 0, ""}
70 req.ContentLength = expectedLength
71 if expectedLength > 0 {
72 req.Body = ioutil.NopCloser(body)
74 // "For client requests, a value of 0 means unknown if
75 // Body is not nil." In this case we do want the body
76 // to be empty, so don't set req.Body.
79 req.Header.Add("X-Request-Id", reqid)
80 req.Header.Add("Authorization", "OAuth2 "+this.Arvados.ApiToken)
81 req.Header.Add("Content-Type", "application/octet-stream")
82 req.Header.Add(X_Keep_Desired_Replicas, fmt.Sprint(this.Want_replicas))
83 if len(this.StorageClasses) > 0 {
84 req.Header.Add("X-Keep-Storage-Classes", strings.Join(this.StorageClasses, ", "))
87 var resp *http.Response
88 if resp, err = this.httpClient().Do(req); err != nil {
89 DebugPrintf("DEBUG: [%s] Upload failed %v error: %v", reqid, url, err.Error())
90 upload_status <- uploadStatus{err, url, 0, 0, ""}
95 if xr := resp.Header.Get(X_Keep_Replicas_Stored); xr != "" {
96 fmt.Sscanf(xr, "%d", &rep)
99 defer resp.Body.Close()
100 defer io.Copy(ioutil.Discard, resp.Body)
102 respbody, err2 := ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 4096})
103 response := strings.TrimSpace(string(respbody))
104 if err2 != nil && err2 != io.EOF {
105 DebugPrintf("DEBUG: [%s] Upload %v error: %v response: %v", reqid, url, err2.Error(), response)
106 upload_status <- uploadStatus{err2, url, resp.StatusCode, rep, response}
107 } else if resp.StatusCode == http.StatusOK {
108 DebugPrintf("DEBUG: [%s] Upload %v success", reqid, url)
109 upload_status <- uploadStatus{nil, url, resp.StatusCode, rep, response}
111 if resp.StatusCode >= 300 && response == "" {
112 response = resp.Status
114 DebugPrintf("DEBUG: [%s] Upload %v error: %v response: %v", reqid, url, resp.StatusCode, response)
115 upload_status <- uploadStatus{errors.New(resp.Status), url, resp.StatusCode, rep, response}
119 func (this *KeepClient) putReplicas(
121 getReader func() io.Reader,
122 expectedLength int64) (locator string, replicas int, err error) {
124 reqid := this.getRequestID()
126 // Calculate the ordering for uploading to servers
127 sv := NewRootSorter(this.WritableLocalRoots(), hash).GetSortedRoots()
129 // The next server to try contacting
132 // The number of active writers
135 // Used to communicate status from the upload goroutines
136 upload_status := make(chan uploadStatus)
138 // Wait for any abandoned uploads (e.g., we started
139 // two uploads and the first replied with replicas=2)
140 // to finish before closing the status channel.
150 replicasTodo := this.Want_replicas
152 replicasPerThread := this.replicasPerService
153 if replicasPerThread < 1 {
154 // unlimited or unknown
155 replicasPerThread = replicasTodo
158 retriesRemaining := 1 + this.Retries
159 var retryServers []string
161 lastError := make(map[string]string)
163 for retriesRemaining > 0 {
164 retriesRemaining -= 1
166 retryServers = []string{}
167 for replicasTodo > 0 {
168 for active*replicasPerThread < replicasTodo {
169 // Start some upload requests
170 if next_server < len(sv) {
171 DebugPrintf("DEBUG: [%s] Begin upload %s to %s", reqid, hash, sv[next_server])
172 go this.uploadToKeepServer(sv[next_server], hash, getReader(), upload_status, expectedLength, reqid)
176 if active == 0 && retriesRemaining == 0 {
177 msg := "Could not write sufficient replicas: "
178 for _, resp := range lastError {
181 msg = msg[:len(msg)-2]
182 return locator, replicasDone, InsufficientReplicasError(errors.New(msg))
188 DebugPrintf("DEBUG: [%s] Replicas remaining to write: %v active uploads: %v",
189 reqid, replicasTodo, active)
191 // Now wait for something to happen.
193 status := <-upload_status
196 if status.statusCode == 200 {
198 replicasDone += status.replicas_stored
199 replicasTodo -= status.replicas_stored
200 locator = status.response
201 delete(lastError, status.url)
203 msg := fmt.Sprintf("[%d] %s", status.statusCode, status.response)
207 lastError[status.url] = msg
210 if status.statusCode == 0 || status.statusCode == 408 || status.statusCode == 429 ||
211 (status.statusCode >= 500 && status.statusCode != 503) {
212 // Timeout, too many requests, or other server side failure
213 // Do not retry when status code is 503, which means the keep server is full
214 retryServers = append(retryServers, status.url[0:strings.LastIndex(status.url, "/")])
224 return locator, replicasDone, nil