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))
84 var resp *http.Response
85 if resp, err = this.httpClient().Do(req); err != nil {
86 DebugPrintf("DEBUG: [%s] Upload failed %v error: %v", reqid, url, err.Error())
87 upload_status <- uploadStatus{err, url, 0, 0, ""}
92 if xr := resp.Header.Get(X_Keep_Replicas_Stored); xr != "" {
93 fmt.Sscanf(xr, "%d", &rep)
96 defer resp.Body.Close()
97 defer io.Copy(ioutil.Discard, resp.Body)
99 respbody, err2 := ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 4096})
100 response := strings.TrimSpace(string(respbody))
101 if err2 != nil && err2 != io.EOF {
102 DebugPrintf("DEBUG: [%s] Upload %v error: %v response: %v", reqid, url, err2.Error(), response)
103 upload_status <- uploadStatus{err2, url, resp.StatusCode, rep, response}
104 } else if resp.StatusCode == http.StatusOK {
105 DebugPrintf("DEBUG: [%s] Upload %v success", reqid, url)
106 upload_status <- uploadStatus{nil, url, resp.StatusCode, rep, response}
108 if resp.StatusCode >= 300 && response == "" {
109 response = resp.Status
111 DebugPrintf("DEBUG: [%s] Upload %v error: %v response: %v", reqid, url, resp.StatusCode, response)
112 upload_status <- uploadStatus{errors.New(resp.Status), url, resp.StatusCode, rep, response}
116 func (this *KeepClient) putReplicas(
118 getReader func() io.Reader,
119 expectedLength int64) (locator string, replicas int, err error) {
121 reqid := this.getRequestID()
123 // Calculate the ordering for uploading to servers
124 sv := NewRootSorter(this.WritableLocalRoots(), hash).GetSortedRoots()
126 // The next server to try contacting
129 // The number of active writers
132 // Used to communicate status from the upload goroutines
133 upload_status := make(chan uploadStatus)
135 // Wait for any abandoned uploads (e.g., we started
136 // two uploads and the first replied with replicas=2)
137 // to finish before closing the status channel.
147 replicasTodo := this.Want_replicas
149 replicasPerThread := this.replicasPerService
150 if replicasPerThread < 1 {
151 // unlimited or unknown
152 replicasPerThread = replicasTodo
155 retriesRemaining := 1 + this.Retries
156 var retryServers []string
158 lastError := make(map[string]string)
160 for retriesRemaining > 0 {
161 retriesRemaining -= 1
163 retryServers = []string{}
164 for replicasTodo > 0 {
165 for active*replicasPerThread < replicasTodo {
166 // Start some upload requests
167 if next_server < len(sv) {
168 DebugPrintf("DEBUG: [%s] Begin upload %s to %s", reqid, hash, sv[next_server])
169 go this.uploadToKeepServer(sv[next_server], hash, getReader(), upload_status, expectedLength, reqid)
173 if active == 0 && retriesRemaining == 0 {
174 msg := "Could not write sufficient replicas: "
175 for _, resp := range lastError {
178 msg = msg[:len(msg)-2]
179 return locator, replicasDone, InsufficientReplicasError(errors.New(msg))
185 DebugPrintf("DEBUG: [%s] Replicas remaining to write: %v active uploads: %v",
186 reqid, replicasTodo, active)
188 // Now wait for something to happen.
190 status := <-upload_status
193 if status.statusCode == 200 {
195 replicasDone += status.replicas_stored
196 replicasTodo -= status.replicas_stored
197 locator = status.response
198 delete(lastError, status.url)
200 msg := fmt.Sprintf("[%d] %s", status.statusCode, status.response)
204 lastError[status.url] = msg
207 if status.statusCode == 0 || status.statusCode == 408 || status.statusCode == 429 ||
208 (status.statusCode >= 500 && status.statusCode != 503) {
209 // Timeout, too many requests, or other server side failure
210 // Do not retry when status code is 503, which means the keep server is full
211 retryServers = append(retryServers, status.url[0:strings.LastIndex(status.url, "/")])
221 return locator, replicasDone, nil