1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
19 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
20 "git.curoverse.com/arvados.git/sdk/go/streamer"
23 // Function used to emit debug messages. The easiest way to enable
24 // keepclient debug messages in your application is to assign
25 // log.Printf to DebugPrintf.
26 var DebugPrintf = func(string, ...interface{}) {}
29 if arvadosclient.StringBool(os.Getenv("ARVADOS_DEBUG")) {
30 DebugPrintf = log.Printf
34 type keepService struct {
35 Uuid string `json:"uuid"`
36 Hostname string `json:"service_host"`
37 Port int `json:"service_port"`
38 SSL bool `json:"service_ssl_flag"`
39 SvcType string `json:"service_type"`
40 ReadOnly bool `json:"read_only"`
43 // Md5String returns md5 hash for the bytes in the given string
44 func Md5String(s string) string {
45 return fmt.Sprintf("%x", md5.Sum([]byte(s)))
49 Items []keepService `json:"items"`
52 type uploadStatus struct {
60 func (this *KeepClient) uploadToKeepServer(host string, hash string, body io.ReadCloser,
61 upload_status chan<- uploadStatus, expectedLength int64, requestID int32) {
65 var url = fmt.Sprintf("%s/%s", host, hash)
66 if req, err = http.NewRequest("PUT", url, nil); err != nil {
67 DebugPrintf("DEBUG: [%08x] Error creating request PUT %v error: %v", requestID, url, err.Error())
68 upload_status <- uploadStatus{err, url, 0, 0, ""}
73 req.ContentLength = expectedLength
74 if expectedLength > 0 {
75 // Do() will close the body ReadCloser when it is done
79 // "For client requests, a value of 0 means unknown if Body is
80 // not nil." In this case we do want the body to be empty, so
81 // don't set req.Body. However, we still need to close the
86 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", this.Arvados.ApiToken))
87 req.Header.Add("Content-Type", "application/octet-stream")
88 req.Header.Add(X_Keep_Desired_Replicas, fmt.Sprint(this.Want_replicas))
90 var resp *http.Response
91 if resp, err = this.httpClient().Do(req); err != nil {
92 DebugPrintf("DEBUG: [%08x] Upload failed %v error: %v", requestID, url, err.Error())
93 upload_status <- uploadStatus{err, url, 0, 0, ""}
98 if xr := resp.Header.Get(X_Keep_Replicas_Stored); xr != "" {
99 fmt.Sscanf(xr, "%d", &rep)
102 defer resp.Body.Close()
103 defer io.Copy(ioutil.Discard, resp.Body)
105 respbody, err2 := ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 4096})
106 response := strings.TrimSpace(string(respbody))
107 if err2 != nil && err2 != io.EOF {
108 DebugPrintf("DEBUG: [%08x] Upload %v error: %v response: %v", requestID, url, err2.Error(), response)
109 upload_status <- uploadStatus{err2, url, resp.StatusCode, rep, response}
110 } else if resp.StatusCode == http.StatusOK {
111 DebugPrintf("DEBUG: [%08x] Upload %v success", requestID, url)
112 upload_status <- uploadStatus{nil, url, resp.StatusCode, rep, response}
114 if resp.StatusCode >= 300 && response == "" {
115 response = resp.Status
117 DebugPrintf("DEBUG: [%08x] Upload %v error: %v response: %v", requestID, url, resp.StatusCode, response)
118 upload_status <- uploadStatus{errors.New(resp.Status), url, resp.StatusCode, rep, response}
122 func (this *KeepClient) putReplicas(
124 tr *streamer.AsyncStream,
125 expectedLength int64) (locator string, replicas int, err error) {
127 // Generate an arbitrary ID to identify this specific
128 // transaction in debug logs.
129 requestID := rand.Int31()
131 // Calculate the ordering for uploading to servers
132 sv := NewRootSorter(this.WritableLocalRoots(), hash).GetSortedRoots()
134 // The next server to try contacting
137 // The number of active writers
140 // Used to communicate status from the upload goroutines
141 upload_status := make(chan uploadStatus)
143 // Wait for any abandoned uploads (e.g., we started
144 // two uploads and the first replied with replicas=2)
145 // to finish before closing the status channel.
155 replicasTodo := this.Want_replicas
157 replicasPerThread := this.replicasPerService
158 if replicasPerThread < 1 {
159 // unlimited or unknown
160 replicasPerThread = replicasTodo
163 retriesRemaining := 1 + this.Retries
164 var retryServers []string
166 lastError := make(map[string]string)
168 for retriesRemaining > 0 {
169 retriesRemaining -= 1
171 retryServers = []string{}
172 for replicasTodo > 0 {
173 for active*replicasPerThread < replicasTodo {
174 // Start some upload requests
175 if next_server < len(sv) {
176 DebugPrintf("DEBUG: [%08x] Begin upload %s to %s", requestID, hash, sv[next_server])
177 go this.uploadToKeepServer(sv[next_server], hash, tr.MakeStreamReader(), upload_status, expectedLength, requestID)
181 if active == 0 && retriesRemaining == 0 {
182 msg := "Could not write sufficient replicas: "
183 for _, resp := range lastError {
186 msg = msg[:len(msg)-2]
187 return locator, replicasDone, InsufficientReplicasError(errors.New(msg))
193 DebugPrintf("DEBUG: [%08x] Replicas remaining to write: %v active uploads: %v",
194 requestID, replicasTodo, active)
196 // Now wait for something to happen.
198 status := <-upload_status
201 if status.statusCode == 200 {
203 replicasDone += status.replicas_stored
204 replicasTodo -= status.replicas_stored
205 locator = status.response
206 delete(lastError, status.url)
208 msg := fmt.Sprintf("[%d] %s", status.statusCode, status.response)
212 lastError[status.url] = msg
215 if status.statusCode == 0 || status.statusCode == 408 || status.statusCode == 429 ||
216 (status.statusCode >= 500 && status.statusCode != 503) {
217 // Timeout, too many requests, or other server side failure
218 // Do not retry when status code is 503, which means the keep server is full
219 retryServers = append(retryServers, status.url[0:strings.LastIndex(status.url, "/")])
229 return locator, replicasDone, nil