Merge branch 'thehyve/fix-crunch-documentation' Fix a typo in Crunch Dispatch install...
[arvados.git] / sdk / go / keepclient / support.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: Apache-2.0
4
5 package keepclient
6
7 import (
8         "crypto/md5"
9         "errors"
10         "fmt"
11         "io"
12         "io/ioutil"
13         "log"
14         "net/http"
15         "os"
16         "strings"
17
18         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
19 )
20
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{}) {}
25
26 func init() {
27         if arvadosclient.StringBool(os.Getenv("ARVADOS_DEBUG")) {
28                 DebugPrintf = log.Printf
29         }
30 }
31
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"`
39 }
40
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)))
44 }
45
46 type svcList struct {
47         Items []keepService `json:"items"`
48 }
49
50 type uploadStatus struct {
51         err             error
52         url             string
53         statusCode      int
54         replicas_stored int
55         response        string
56 }
57
58 func (this *KeepClient) uploadToKeepServer(host string, hash string, body io.Reader,
59         upload_status chan<- uploadStatus, expectedLength int64, reqid string) {
60
61         var req *http.Request
62         var err error
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, ""}
67                 return
68         }
69
70         req.ContentLength = expectedLength
71         if expectedLength > 0 {
72                 req.Body = ioutil.NopCloser(body)
73         } else {
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.
77         }
78
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
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, ""}
88                 return
89         }
90
91         rep := 1
92         if xr := resp.Header.Get(X_Keep_Replicas_Stored); xr != "" {
93                 fmt.Sscanf(xr, "%d", &rep)
94         }
95
96         defer resp.Body.Close()
97         defer io.Copy(ioutil.Discard, resp.Body)
98
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}
107         } else {
108                 if resp.StatusCode >= 300 && response == "" {
109                         response = resp.Status
110                 }
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}
113         }
114 }
115
116 func (this *KeepClient) putReplicas(
117         hash string,
118         getReader func() io.Reader,
119         expectedLength int64) (locator string, replicas int, err error) {
120
121         reqid := this.getRequestID()
122
123         // Calculate the ordering for uploading to servers
124         sv := NewRootSorter(this.WritableLocalRoots(), hash).GetSortedRoots()
125
126         // The next server to try contacting
127         next_server := 0
128
129         // The number of active writers
130         active := 0
131
132         // Used to communicate status from the upload goroutines
133         upload_status := make(chan uploadStatus)
134         defer func() {
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.
138                 go func() {
139                         for active > 0 {
140                                 <-upload_status
141                         }
142                         close(upload_status)
143                 }()
144         }()
145
146         replicasDone := 0
147         replicasTodo := this.Want_replicas
148
149         replicasPerThread := this.replicasPerService
150         if replicasPerThread < 1 {
151                 // unlimited or unknown
152                 replicasPerThread = replicasTodo
153         }
154
155         retriesRemaining := 1 + this.Retries
156         var retryServers []string
157
158         lastError := make(map[string]string)
159
160         for retriesRemaining > 0 {
161                 retriesRemaining -= 1
162                 next_server = 0
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)
170                                         next_server += 1
171                                         active += 1
172                                 } else {
173                                         if active == 0 && retriesRemaining == 0 {
174                                                 msg := "Could not write sufficient replicas: "
175                                                 for _, resp := range lastError {
176                                                         msg += resp + "; "
177                                                 }
178                                                 msg = msg[:len(msg)-2]
179                                                 return locator, replicasDone, InsufficientReplicasError(errors.New(msg))
180                                         } else {
181                                                 break
182                                         }
183                                 }
184                         }
185                         DebugPrintf("DEBUG: [%s] Replicas remaining to write: %v active uploads: %v",
186                                 reqid, replicasTodo, active)
187
188                         // Now wait for something to happen.
189                         if active > 0 {
190                                 status := <-upload_status
191                                 active -= 1
192
193                                 if status.statusCode == 200 {
194                                         // good news!
195                                         replicasDone += status.replicas_stored
196                                         replicasTodo -= status.replicas_stored
197                                         locator = status.response
198                                         delete(lastError, status.url)
199                                 } else {
200                                         msg := fmt.Sprintf("[%d] %s", status.statusCode, status.response)
201                                         if len(msg) > 100 {
202                                                 msg = msg[:100]
203                                         }
204                                         lastError[status.url] = msg
205                                 }
206
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, "/")])
212                                 }
213                         } else {
214                                 break
215                         }
216                 }
217
218                 sv = retryServers
219         }
220
221         return locator, replicasDone, nil
222 }