Merge branch 'master' into 4523-search-index
[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/http"
13         "os"
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 func (this *KeepClient) DiscoverKeepServers() error {
31         if prx := os.Getenv("ARVADOS_KEEP_PROXY"); prx != "" {
32                 sr := map[string]string{"proxy": prx}
33                 this.SetServiceRoots(sr)
34                 this.Using_proxy = true
35                 if this.Client.Timeout == 0 {
36                         this.Client.Timeout = 10 * time.Minute
37                 }
38                 return nil
39         }
40
41         if this.Client.Timeout == 0 {
42                 this.Client.Timeout = 15 * time.Second
43         }
44
45         type svcList struct {
46                 Items []keepDisk `json:"items"`
47         }
48         var m svcList
49
50         err := this.Arvados.Call("GET", "keep_services", "", "accessible", nil, &m)
51
52         if err != nil {
53                 if err := this.Arvados.List("keep_disks", nil, &m); err != nil {
54                         return err
55                 }
56         }
57
58         listed := make(map[string]bool)
59         service_roots := make(map[string]string)
60
61         for _, element := range m.Items {
62                 n := ""
63
64                 if element.SSL {
65                         n = "s"
66                 }
67
68                 // Construct server URL
69                 url := fmt.Sprintf("http%s://%s:%d", n, element.Hostname, element.Port)
70
71                 // Skip duplicates
72                 if !listed[url] {
73                         listed[url] = true
74                         service_roots[element.Uuid] = url
75                 }
76                 if element.SvcType == "proxy" {
77                         this.Using_proxy = true
78                 }
79         }
80
81         this.SetServiceRoots(service_roots)
82
83         return nil
84 }
85
86 type uploadStatus struct {
87         err             error
88         url             string
89         statusCode      int
90         replicas_stored int
91         response        string
92 }
93
94 func (this KeepClient) uploadToKeepServer(host string, hash string, body io.ReadCloser,
95         upload_status chan<- uploadStatus, expectedLength int64, requestId string) {
96
97         var req *http.Request
98         var err error
99         var url = fmt.Sprintf("%s/%s", host, hash)
100         if req, err = http.NewRequest("PUT", url, nil); err != nil {
101                 log.Printf("[%v] Error creating request PUT %v error: %v", requestId, url, err.Error())
102                 upload_status <- uploadStatus{err, url, 0, 0, ""}
103                 body.Close()
104                 return
105         }
106
107         req.ContentLength = expectedLength
108         if expectedLength > 0 {
109                 // http.Client.Do will close the body ReadCloser when it is
110                 // done with it.
111                 req.Body = body
112         } else {
113                 // "For client requests, a value of 0 means unknown if Body is
114                 // not nil."  In this case we do want the body to be empty, so
115                 // don't set req.Body.  However, we still need to close the
116                 // body ReadCloser.
117                 body.Close()
118         }
119
120         req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", this.Arvados.ApiToken))
121         req.Header.Add("Content-Type", "application/octet-stream")
122
123         if this.Using_proxy {
124                 req.Header.Add(X_Keep_Desired_Replicas, fmt.Sprint(this.Want_replicas))
125         }
126
127         var resp *http.Response
128         if resp, err = this.Client.Do(req); err != nil {
129                 log.Printf("[%v] Upload failed %v error: %v", requestId, url, err.Error())
130                 upload_status <- uploadStatus{err, url, 0, 0, ""}
131                 return
132         }
133
134         rep := 1
135         if xr := resp.Header.Get(X_Keep_Replicas_Stored); xr != "" {
136                 fmt.Sscanf(xr, "%d", &rep)
137         }
138
139         defer resp.Body.Close()
140         defer io.Copy(ioutil.Discard, resp.Body)
141
142         respbody, err2 := ioutil.ReadAll(&io.LimitedReader{resp.Body, 4096})
143         response := strings.TrimSpace(string(respbody))
144         if err2 != nil && err2 != io.EOF {
145                 log.Printf("[%v] Upload %v error: %v response: %v", requestId, url, err2.Error(), response)
146                 upload_status <- uploadStatus{err2, url, resp.StatusCode, rep, response}
147         } else if resp.StatusCode == http.StatusOK {
148                 log.Printf("[%v] Upload %v success", requestId, url)
149                 upload_status <- uploadStatus{nil, url, resp.StatusCode, rep, response}
150         } else {
151                 log.Printf("[%v] Upload %v error: %v response: %v", requestId, url, resp.StatusCode, response)
152                 upload_status <- uploadStatus{errors.New(resp.Status), url, resp.StatusCode, rep, response}
153         }
154 }
155
156 func (this KeepClient) putReplicas(
157         hash string,
158         tr *streamer.AsyncStream,
159         expectedLength int64) (locator string, replicas int, err error) {
160
161         // Take the hash of locator and timestamp in order to identify this
162         // specific transaction in log statements.
163         requestId := fmt.Sprintf("%x", md5.Sum([]byte(locator+time.Now().String())))[0:8]
164
165         // Calculate the ordering for uploading to servers
166         sv := NewRootSorter(this.ServiceRoots(), hash).GetSortedRoots()
167
168         // The next server to try contacting
169         next_server := 0
170
171         // The number of active writers
172         active := 0
173
174         // Used to communicate status from the upload goroutines
175         upload_status := make(chan uploadStatus)
176         defer close(upload_status)
177
178         // Desired number of replicas
179         remaining_replicas := this.Want_replicas
180
181         for remaining_replicas > 0 {
182                 for active < remaining_replicas {
183                         // Start some upload requests
184                         if next_server < len(sv) {
185                                 log.Printf("[%v] Begin upload %s to %s", requestId, hash, sv[next_server])
186                                 go this.uploadToKeepServer(sv[next_server], hash, tr.MakeStreamReader(), upload_status, expectedLength, requestId)
187                                 next_server += 1
188                                 active += 1
189                         } else {
190                                 if active == 0 {
191                                         return locator, (this.Want_replicas - remaining_replicas), InsufficientReplicasError
192                                 } else {
193                                         break
194                                 }
195                         }
196                 }
197                 log.Printf("[%v] Replicas remaining to write: %v active uploads: %v",
198                         requestId, remaining_replicas, active)
199
200                 // Now wait for something to happen.
201                 status := <-upload_status
202                 active -= 1
203
204                 if status.statusCode == 200 {
205                         // good news!
206                         remaining_replicas -= status.replicas_stored
207                         locator = status.response
208                 }
209         }
210
211         return locator, this.Want_replicas, nil
212 }