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