Merge branch '6934-pam' refs #6934
[arvados.git] / sdk / go / keepclient / support.go
1 package keepclient
2
3 import (
4         "crypto/md5"
5         "errors"
6         "fmt"
7         "git.curoverse.com/arvados.git/sdk/go/streamer"
8         "io"
9         "io/ioutil"
10         "log"
11         "net"
12         "net/http"
13         "strings"
14         "time"
15 )
16
17 type keepDisk struct {
18         Uuid     string `json:"uuid"`
19         Hostname string `json:"service_host"`
20         Port     int    `json:"service_port"`
21         SSL      bool   `json:"service_ssl_flag"`
22         SvcType  string `json:"service_type"`
23         ReadOnly bool   `json:"read_only"`
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() 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 err
90                 }
91         }
92
93         listed := make(map[string]bool)
94         localRoots := make(map[string]string)
95         gatewayRoots := make(map[string]string)
96         writableLocalRoots := make(map[string]string)
97
98         for _, service := range m.Items {
99                 scheme := "http"
100                 if service.SSL {
101                         scheme = "https"
102                 }
103                 url := fmt.Sprintf("%s://%s:%d", scheme, service.Hostname, service.Port)
104
105                 // Skip duplicates
106                 if listed[url] {
107                         continue
108                 }
109                 listed[url] = true
110
111                 switch service.SvcType {
112                 case "disk":
113                         localRoots[service.Uuid] = url
114                 case "proxy":
115                         localRoots[service.Uuid] = url
116                         this.Using_proxy = true
117                 }
118
119                 if service.ReadOnly == false {
120                         writableLocalRoots[service.Uuid] = url
121                 }
122
123                 // Gateway services are only used when specified by
124                 // UUID, so there's nothing to gain by filtering them
125                 // by service type. Including all accessible services
126                 // (gateway and otherwise) merely accommodates more
127                 // service configurations.
128                 gatewayRoots[service.Uuid] = url
129         }
130
131         if this.Using_proxy {
132                 this.setClientSettingsProxy()
133         } else {
134                 this.setClientSettingsStore()
135         }
136
137         this.SetServiceRoots(localRoots, writableLocalRoots, gatewayRoots)
138         return nil
139 }
140
141 type uploadStatus struct {
142         err             error
143         url             string
144         statusCode      int
145         replicas_stored int
146         response        string
147 }
148
149 func (this KeepClient) uploadToKeepServer(host string, hash string, body io.ReadCloser,
150         upload_status chan<- uploadStatus, expectedLength int64, requestId string) {
151
152         var req *http.Request
153         var err error
154         var url = fmt.Sprintf("%s/%s", host, hash)
155         if req, err = http.NewRequest("PUT", url, nil); err != nil {
156                 log.Printf("[%v] Error creating request PUT %v error: %v", requestId, url, err.Error())
157                 upload_status <- uploadStatus{err, url, 0, 0, ""}
158                 body.Close()
159                 return
160         }
161
162         req.ContentLength = expectedLength
163         if expectedLength > 0 {
164                 // http.Client.Do will close the body ReadCloser when it is
165                 // done with it.
166                 req.Body = body
167         } else {
168                 // "For client requests, a value of 0 means unknown if Body is
169                 // not nil."  In this case we do want the body to be empty, so
170                 // don't set req.Body.  However, we still need to close the
171                 // body ReadCloser.
172                 body.Close()
173         }
174
175         req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", this.Arvados.ApiToken))
176         req.Header.Add("Content-Type", "application/octet-stream")
177
178         if this.Using_proxy {
179                 req.Header.Add(X_Keep_Desired_Replicas, fmt.Sprint(this.Want_replicas))
180         }
181
182         var resp *http.Response
183         if resp, err = this.Client.Do(req); err != nil {
184                 log.Printf("[%v] Upload failed %v error: %v", requestId, url, err.Error())
185                 upload_status <- uploadStatus{err, url, 0, 0, ""}
186                 return
187         }
188
189         rep := 1
190         if xr := resp.Header.Get(X_Keep_Replicas_Stored); xr != "" {
191                 fmt.Sscanf(xr, "%d", &rep)
192         }
193
194         defer resp.Body.Close()
195         defer io.Copy(ioutil.Discard, resp.Body)
196
197         respbody, err2 := ioutil.ReadAll(&io.LimitedReader{resp.Body, 4096})
198         response := strings.TrimSpace(string(respbody))
199         if err2 != nil && err2 != io.EOF {
200                 log.Printf("[%v] Upload %v error: %v response: %v", requestId, url, err2.Error(), response)
201                 upload_status <- uploadStatus{err2, url, resp.StatusCode, rep, response}
202         } else if resp.StatusCode == http.StatusOK {
203                 log.Printf("[%v] Upload %v success", requestId, url)
204                 upload_status <- uploadStatus{nil, url, resp.StatusCode, rep, response}
205         } else {
206                 log.Printf("[%v] Upload %v error: %v response: %v", requestId, url, resp.StatusCode, response)
207                 upload_status <- uploadStatus{errors.New(resp.Status), url, resp.StatusCode, rep, response}
208         }
209 }
210
211 func (this KeepClient) putReplicas(
212         hash string,
213         tr *streamer.AsyncStream,
214         expectedLength int64) (locator string, replicas int, err error) {
215
216         // Take the hash of locator and timestamp in order to identify this
217         // specific transaction in log statements.
218         requestId := fmt.Sprintf("%x", md5.Sum([]byte(locator+time.Now().String())))[0:8]
219
220         // Calculate the ordering for uploading to servers
221         sv := NewRootSorter(this.WritableLocalRoots(), hash).GetSortedRoots()
222
223         // The next server to try contacting
224         next_server := 0
225
226         // The number of active writers
227         active := 0
228
229         // Used to communicate status from the upload goroutines
230         upload_status := make(chan uploadStatus)
231         defer close(upload_status)
232
233         // Desired number of replicas
234         remaining_replicas := this.Want_replicas
235
236         for remaining_replicas > 0 {
237                 for active < remaining_replicas {
238                         // Start some upload requests
239                         if next_server < len(sv) {
240                                 log.Printf("[%v] Begin upload %s to %s", requestId, hash, sv[next_server])
241                                 go this.uploadToKeepServer(sv[next_server], hash, tr.MakeStreamReader(), upload_status, expectedLength, requestId)
242                                 next_server += 1
243                                 active += 1
244                         } else {
245                                 if active == 0 {
246                                         return locator, (this.Want_replicas - remaining_replicas), InsufficientReplicasError
247                                 } else {
248                                         break
249                                 }
250                         }
251                 }
252                 log.Printf("[%v] Replicas remaining to write: %v active uploads: %v",
253                         requestId, remaining_replicas, active)
254
255                 // Now wait for something to happen.
256                 status := <-upload_status
257                 active -= 1
258
259                 if status.statusCode == 200 {
260                         // good news!
261                         remaining_replicas -= status.replicas_stored
262                         locator = status.response
263                 }
264         }
265
266         return locator, this.Want_replicas, nil
267 }