8784: Fix test for latest firefox.
[arvados.git] / sdk / go / keepclient / support.go
1 package keepclient
2
3 import (
4         "crypto/md5"
5         "errors"
6         "fmt"
7         "io"
8         "io/ioutil"
9         "log"
10         "math/rand"
11         "net/http"
12         "os"
13         "strings"
14
15         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
16         "git.curoverse.com/arvados.git/sdk/go/streamer"
17 )
18
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{}) {}
23
24 func init() {
25         if arvadosclient.StringBool(os.Getenv("ARVADOS_DEBUG")) {
26                 DebugPrintf = log.Printf
27         }
28 }
29
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"`
37 }
38
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)))
42 }
43
44 type svcList struct {
45         Items []keepService `json:"items"`
46 }
47
48 type uploadStatus struct {
49         err             error
50         url             string
51         statusCode      int
52         replicas_stored int
53         response        string
54 }
55
56 func (this *KeepClient) uploadToKeepServer(host string, hash string, body io.ReadCloser,
57         upload_status chan<- uploadStatus, expectedLength int64, requestID int32) {
58
59         var req *http.Request
60         var err error
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, ""}
65                 body.Close()
66                 return
67         }
68
69         req.ContentLength = expectedLength
70         if expectedLength > 0 {
71                 // Do() will close the body ReadCloser when it is done
72                 // with it.
73                 req.Body = body
74         } else {
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
78                 // body ReadCloser.
79                 body.Close()
80         }
81
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))
85
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, ""}
90                 return
91         }
92
93         rep := 1
94         if xr := resp.Header.Get(X_Keep_Replicas_Stored); xr != "" {
95                 fmt.Sscanf(xr, "%d", &rep)
96         }
97
98         defer resp.Body.Close()
99         defer io.Copy(ioutil.Discard, resp.Body)
100
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}
109         } else {
110                 if resp.StatusCode >= 300 && response == "" {
111                         response = resp.Status
112                 }
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}
115         }
116 }
117
118 func (this *KeepClient) putReplicas(
119         hash string,
120         tr *streamer.AsyncStream,
121         expectedLength int64) (locator string, replicas int, err error) {
122
123         // Generate an arbitrary ID to identify this specific
124         // transaction in debug logs.
125         requestID := rand.Int31()
126
127         // Calculate the ordering for uploading to servers
128         sv := NewRootSorter(this.WritableLocalRoots(), hash).GetSortedRoots()
129
130         // The next server to try contacting
131         next_server := 0
132
133         // The number of active writers
134         active := 0
135
136         // Used to communicate status from the upload goroutines
137         upload_status := make(chan uploadStatus)
138         defer func() {
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.
142                 go func() {
143                         for active > 0 {
144                                 <-upload_status
145                         }
146                         close(upload_status)
147                 }()
148         }()
149
150         replicasDone := 0
151         replicasTodo := this.Want_replicas
152
153         replicasPerThread := this.replicasPerService
154         if replicasPerThread < 1 {
155                 // unlimited or unknown
156                 replicasPerThread = replicasTodo
157         }
158
159         retriesRemaining := 1 + this.Retries
160         var retryServers []string
161
162         lastError := make(map[string]string)
163
164         for retriesRemaining > 0 {
165                 retriesRemaining -= 1
166                 next_server = 0
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)
174                                         next_server += 1
175                                         active += 1
176                                 } else {
177                                         if active == 0 && retriesRemaining == 0 {
178                                                 msg := "Could not write sufficient replicas: "
179                                                 for _, resp := range lastError {
180                                                         msg += resp + "; "
181                                                 }
182                                                 msg = msg[:len(msg)-2]
183                                                 return locator, replicasDone, InsufficientReplicasError(errors.New(msg))
184                                         } else {
185                                                 break
186                                         }
187                                 }
188                         }
189                         DebugPrintf("DEBUG: [%08x] Replicas remaining to write: %v active uploads: %v",
190                                 requestID, replicasTodo, active)
191
192                         // Now wait for something to happen.
193                         if active > 0 {
194                                 status := <-upload_status
195                                 active -= 1
196
197                                 if status.statusCode == 200 {
198                                         // good news!
199                                         replicasDone += status.replicas_stored
200                                         replicasTodo -= status.replicas_stored
201                                         locator = status.response
202                                         delete(lastError, status.url)
203                                 } else {
204                                         msg := fmt.Sprintf("[%d] %s", status.statusCode, status.response)
205                                         if len(msg) > 100 {
206                                                 msg = msg[:100]
207                                         }
208                                         lastError[status.url] = msg
209                                 }
210
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, "/")])
216                                 }
217                         } else {
218                                 break
219                         }
220                 }
221
222                 sv = retryServers
223         }
224
225         return locator, replicasDone, nil
226 }