Merge branch 'master' into 4426-search-documentation
[arvados.git] / sdk / go / keepclient / support.go
1 /* Internal methods to support keepclient.go */
2 package keepclient
3
4 import (
5         "crypto/md5"
6         "errors"
7         "fmt"
8         "git.curoverse.com/arvados.git/sdk/go/streamer"
9         "io"
10         "io/ioutil"
11         "log"
12         "net"
13         "net/http"
14         "strings"
15         "time"
16 )
17
18 type keepDisk struct {
19         Uuid     string `json:"uuid"`
20         Hostname string `json:"service_host"`
21         Port     int    `json:"service_port"`
22         SSL      bool   `json:"service_ssl_flag"`
23         SvcType  string `json:"service_type"`
24 }
25
26 func Md5String(s string) string {
27         return fmt.Sprintf("%x", md5.Sum([]byte(s)))
28 }
29
30 // Set timeouts apply when connecting to keepproxy services (assumed to be over
31 // the Internet).
32 func (this *KeepClient) setClientSettingsProxy() {
33         if this.Client.Timeout == 0 {
34                 // Maximum time to wait for a complete response
35                 this.Client.Timeout = 300 * time.Second
36
37                 // TCP and TLS connection settings
38                 this.Client.Transport = &http.Transport{
39                         Dial: (&net.Dialer{
40                                 // The maximum time to wait to set up
41                                 // the initial TCP connection.
42                                 Timeout: 30 * time.Second,
43
44                                 // The TCP keep alive heartbeat
45                                 // interval.
46                                 KeepAlive: 120 * time.Second,
47                         }).Dial,
48
49                         TLSHandshakeTimeout: 10 * time.Second,
50                 }
51         }
52
53 }
54
55 // Set timeouts apply when connecting to keepstore services directly (assumed
56 // to be on the local network).
57 func (this *KeepClient) setClientSettingsStore() {
58         if this.Client.Timeout == 0 {
59                 // Maximum time to wait for a complete response
60                 this.Client.Timeout = 20 * time.Second
61
62                 // TCP and TLS connection timeouts
63                 this.Client.Transport = &http.Transport{
64                         Dial: (&net.Dialer{
65                                 // The maximum time to wait to set up
66                                 // the initial TCP connection.
67                                 Timeout: 2 * time.Second,
68
69                                 // The TCP keep alive heartbeat
70                                 // interval.
71                                 KeepAlive: 180 * time.Second,
72                         }).Dial,
73
74                         TLSHandshakeTimeout: 4 * time.Second,
75                 }
76         }
77 }
78
79 func (this *KeepClient) DiscoverKeepServers() (map[string]string, error) {
80         type svcList struct {
81                 Items []keepDisk `json:"items"`
82         }
83         var m svcList
84
85         err := this.Arvados.Call("GET", "keep_services", "", "accessible", nil, &m)
86
87         if err != nil {
88                 if err := this.Arvados.List("keep_disks", nil, &m); err != nil {
89                         return nil, err
90                 }
91         }
92
93         listed := make(map[string]bool)
94         service_roots := make(map[string]string)
95
96         for _, element := range m.Items {
97                 n := ""
98
99                 if element.SSL {
100                         n = "s"
101                 }
102
103                 // Construct server URL
104                 url := fmt.Sprintf("http%s://%s:%d", n, element.Hostname, element.Port)
105
106                 // Skip duplicates
107                 if !listed[url] {
108                         listed[url] = true
109                         service_roots[element.Uuid] = url
110                 }
111                 if element.SvcType == "proxy" {
112                         this.Using_proxy = true
113                 }
114         }
115
116         if this.Using_proxy {
117                 this.setClientSettingsProxy()
118         } else {
119                 this.setClientSettingsStore()
120         }
121
122         this.SetServiceRoots(service_roots)
123
124         return service_roots, nil
125 }
126
127 type uploadStatus struct {
128         err             error
129         url             string
130         statusCode      int
131         replicas_stored int
132         response        string
133 }
134
135 func (this KeepClient) uploadToKeepServer(host string, hash string, body io.ReadCloser,
136         upload_status chan<- uploadStatus, expectedLength int64, requestId string) {
137
138         var req *http.Request
139         var err error
140         var url = fmt.Sprintf("%s/%s", host, hash)
141         if req, err = http.NewRequest("PUT", url, nil); err != nil {
142                 log.Printf("[%v] Error creating request PUT %v error: %v", requestId, url, err.Error())
143                 upload_status <- uploadStatus{err, url, 0, 0, ""}
144                 body.Close()
145                 return
146         }
147
148         req.ContentLength = expectedLength
149         if expectedLength > 0 {
150                 // http.Client.Do will close the body ReadCloser when it is
151                 // done with it.
152                 req.Body = body
153         } else {
154                 // "For client requests, a value of 0 means unknown if Body is
155                 // not nil."  In this case we do want the body to be empty, so
156                 // don't set req.Body.  However, we still need to close the
157                 // body ReadCloser.
158                 body.Close()
159         }
160
161         req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", this.Arvados.ApiToken))
162         req.Header.Add("Content-Type", "application/octet-stream")
163
164         if this.Using_proxy {
165                 req.Header.Add(X_Keep_Desired_Replicas, fmt.Sprint(this.Want_replicas))
166         }
167
168         var resp *http.Response
169         if resp, err = this.Client.Do(req); err != nil {
170                 log.Printf("[%v] Upload failed %v error: %v", requestId, url, err.Error())
171                 upload_status <- uploadStatus{err, url, 0, 0, ""}
172                 return
173         }
174
175         rep := 1
176         if xr := resp.Header.Get(X_Keep_Replicas_Stored); xr != "" {
177                 fmt.Sscanf(xr, "%d", &rep)
178         }
179
180         defer resp.Body.Close()
181         defer io.Copy(ioutil.Discard, resp.Body)
182
183         respbody, err2 := ioutil.ReadAll(&io.LimitedReader{resp.Body, 4096})
184         response := strings.TrimSpace(string(respbody))
185         if err2 != nil && err2 != io.EOF {
186                 log.Printf("[%v] Upload %v error: %v response: %v", requestId, url, err2.Error(), response)
187                 upload_status <- uploadStatus{err2, url, resp.StatusCode, rep, response}
188         } else if resp.StatusCode == http.StatusOK {
189                 log.Printf("[%v] Upload %v success", requestId, url)
190                 upload_status <- uploadStatus{nil, url, resp.StatusCode, rep, response}
191         } else {
192                 log.Printf("[%v] Upload %v error: %v response: %v", requestId, url, resp.StatusCode, response)
193                 upload_status <- uploadStatus{errors.New(resp.Status), url, resp.StatusCode, rep, response}
194         }
195 }
196
197 func (this KeepClient) putReplicas(
198         hash string,
199         tr *streamer.AsyncStream,
200         expectedLength int64) (locator string, replicas int, err error) {
201
202         // Take the hash of locator and timestamp in order to identify this
203         // specific transaction in log statements.
204         requestId := fmt.Sprintf("%x", md5.Sum([]byte(locator+time.Now().String())))[0:8]
205
206         // Calculate the ordering for uploading to servers
207         sv := NewRootSorter(this.ServiceRoots(), hash).GetSortedRoots()
208
209         // The next server to try contacting
210         next_server := 0
211
212         // The number of active writers
213         active := 0
214
215         // Used to communicate status from the upload goroutines
216         upload_status := make(chan uploadStatus)
217         defer close(upload_status)
218
219         // Desired number of replicas
220         remaining_replicas := this.Want_replicas
221
222         for remaining_replicas > 0 {
223                 for active < remaining_replicas {
224                         // Start some upload requests
225                         if next_server < len(sv) {
226                                 log.Printf("[%v] Begin upload %s to %s", requestId, hash, sv[next_server])
227                                 go this.uploadToKeepServer(sv[next_server], hash, tr.MakeStreamReader(), upload_status, expectedLength, requestId)
228                                 next_server += 1
229                                 active += 1
230                         } else {
231                                 if active == 0 {
232                                         return locator, (this.Want_replicas - remaining_replicas), InsufficientReplicasError
233                                 } else {
234                                         break
235                                 }
236                         }
237                 }
238                 log.Printf("[%v] Replicas remaining to write: %v active uploads: %v",
239                         requestId, remaining_replicas, active)
240
241                 // Now wait for something to happen.
242                 status := <-upload_status
243                 active -= 1
244
245                 if status.statusCode == 200 {
246                         // good news!
247                         remaining_replicas -= status.replicas_stored
248                         locator = status.response
249                 }
250         }
251
252         return locator, this.Want_replicas, nil
253 }