1 /* Internal methods to support keepclient.go */
8 "git.curoverse.com/arvados.git/sdk/go/streamer"
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"`
27 func Md5String(s string) string {
28 return fmt.Sprintf("%x", md5.Sum([]byte(s)))
31 // Set timeouts apply when connecting to keepproxy services (assumed to be over
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
38 // TCP and TLS connection settings
39 this.Client.Transport = &http.Transport{
41 // The maximum time to wait to set up
42 // the initial TCP connection.
43 Timeout: 30 * time.Second,
45 // The TCP keep alive heartbeat
47 KeepAlive: 120 * time.Second,
50 TLSHandshakeTimeout: 10 * time.Second,
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
63 // TCP and TLS connection timeouts
64 this.Client.Transport = &http.Transport{
66 // The maximum time to wait to set up
67 // the initial TCP connection.
68 Timeout: 2 * time.Second,
70 // The TCP keep alive heartbeat
72 KeepAlive: 180 * time.Second,
75 TLSHandshakeTimeout: 4 * time.Second,
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()
90 Items []keepDisk `json:"items"`
94 err := this.Arvados.Call("GET", "keep_services", "", "accessible", nil, &m)
97 if err := this.Arvados.List("keep_disks", nil, &m); err != nil {
102 listed := make(map[string]bool)
103 service_roots := make(map[string]string)
105 for _, element := range m.Items {
112 // Construct server URL
113 url := fmt.Sprintf("http%s://%s:%d", n, element.Hostname, element.Port)
118 service_roots[element.Uuid] = url
120 if element.SvcType == "proxy" {
121 this.Using_proxy = true
125 if this.Using_proxy {
126 this.setClientSettingsProxy()
128 this.setClientSettingsStore()
131 this.SetServiceRoots(service_roots)
136 type uploadStatus struct {
144 func (this KeepClient) uploadToKeepServer(host string, hash string, body io.ReadCloser,
145 upload_status chan<- uploadStatus, expectedLength int64, requestId string) {
147 var req *http.Request
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, ""}
157 req.ContentLength = expectedLength
158 if expectedLength > 0 {
159 // http.Client.Do will close the body ReadCloser when it is
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
170 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", this.Arvados.ApiToken))
171 req.Header.Add("Content-Type", "application/octet-stream")
173 if this.Using_proxy {
174 req.Header.Add(X_Keep_Desired_Replicas, fmt.Sprint(this.Want_replicas))
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, ""}
185 if xr := resp.Header.Get(X_Keep_Replicas_Stored); xr != "" {
186 fmt.Sscanf(xr, "%d", &rep)
189 defer resp.Body.Close()
190 defer io.Copy(ioutil.Discard, resp.Body)
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}
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}
206 func (this KeepClient) putReplicas(
208 tr *streamer.AsyncStream,
209 expectedLength int64) (locator string, replicas int, err error) {
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]
215 // Calculate the ordering for uploading to servers
216 sv := NewRootSorter(this.ServiceRoots(), hash).GetSortedRoots()
218 // The next server to try contacting
221 // The number of active writers
224 // Used to communicate status from the upload goroutines
225 upload_status := make(chan uploadStatus)
226 defer close(upload_status)
228 // Desired number of replicas
229 remaining_replicas := this.Want_replicas
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)
241 return locator, (this.Want_replicas - remaining_replicas), InsufficientReplicasError
247 log.Printf("[%v] Replicas remaining to write: %v active uploads: %v",
248 requestId, remaining_replicas, active)
250 // Now wait for something to happen.
251 status := <-upload_status
254 if status.statusCode == 200 {
256 remaining_replicas -= status.replicas_stored
257 locator = status.response
261 return locator, this.Want_replicas, nil