8 "git.curoverse.com/arvados.git/sdk/go/streamer"
18 type keepService 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 ReadOnly bool `json:"read_only"`
27 // Md5String returns md5 hash for the bytes in the given string
28 func Md5String(s string) string {
29 return fmt.Sprintf("%x", md5.Sum([]byte(s)))
32 // Set timeouts apply when connecting to keepproxy services (assumed to be over
34 func (this *KeepClient) setClientSettingsProxy() {
35 if this.Client.Timeout == 0 {
36 // Maximum time to wait for a complete response
37 this.Client.Timeout = 300 * time.Second
39 // TCP and TLS connection settings
40 this.Client.Transport = &http.Transport{
42 // The maximum time to wait to set up
43 // the initial TCP connection.
44 Timeout: 30 * time.Second,
46 // The TCP keep alive heartbeat
48 KeepAlive: 120 * time.Second,
51 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) setClientSettingsDisk() {
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,
81 Items []keepService `json:"items"`
84 // DiscoverKeepServers gets list of available keep services from api server
85 func (this *KeepClient) DiscoverKeepServers() error {
88 // Get keep services from api server
89 err := this.Arvados.Call("GET", "keep_services", "", "accessible", nil, &list)
94 return this.loadKeepServers(list)
97 // LoadKeepServicesFromJSON gets list of available keep services from given JSON
98 func (this *KeepClient) LoadKeepServicesFromJSON(services string) error {
101 // Load keep services from given json
102 dec := json.NewDecoder(strings.NewReader(services))
103 if err := dec.Decode(&list); err != nil {
107 return this.loadKeepServers(list)
111 func (this *KeepClient) loadKeepServers(list svcList) error {
112 listed := make(map[string]bool)
113 localRoots := make(map[string]string)
114 gatewayRoots := make(map[string]string)
115 writableLocalRoots := make(map[string]string)
117 // replicasPerService is 1 for disks; unknown or unlimited otherwise
118 this.replicasPerService = 1
119 this.Using_proxy = false
121 for _, service := range list.Items {
126 url := fmt.Sprintf("%s://%s:%d", scheme, service.Hostname, service.Port)
134 localRoots[service.Uuid] = url
135 if service.SvcType == "proxy" {
136 this.Using_proxy = true
139 if service.ReadOnly == false {
140 writableLocalRoots[service.Uuid] = url
141 if service.SvcType != "disk" {
142 this.replicasPerService = 0
146 // Gateway services are only used when specified by
147 // UUID, so there's nothing to gain by filtering them
148 // by service type. Including all accessible services
149 // (gateway and otherwise) merely accommodates more
150 // service configurations.
151 gatewayRoots[service.Uuid] = url
154 if this.Using_proxy {
155 this.setClientSettingsProxy()
157 this.setClientSettingsDisk()
160 this.SetServiceRoots(localRoots, writableLocalRoots, gatewayRoots)
164 type uploadStatus struct {
172 func (this KeepClient) uploadToKeepServer(host string, hash string, body io.ReadCloser,
173 upload_status chan<- uploadStatus, expectedLength int64, requestId string) {
175 var req *http.Request
177 var url = fmt.Sprintf("%s/%s", host, hash)
178 if req, err = http.NewRequest("PUT", url, nil); err != nil {
179 log.Printf("[%v] Error creating request PUT %v error: %v", requestId, url, err.Error())
180 upload_status <- uploadStatus{err, url, 0, 0, ""}
185 req.ContentLength = expectedLength
186 if expectedLength > 0 {
187 // http.Client.Do will close the body ReadCloser when it is
191 // "For client requests, a value of 0 means unknown if Body is
192 // not nil." In this case we do want the body to be empty, so
193 // don't set req.Body. However, we still need to close the
198 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", this.Arvados.ApiToken))
199 req.Header.Add("Content-Type", "application/octet-stream")
200 req.Header.Add(X_Keep_Desired_Replicas, fmt.Sprint(this.Want_replicas))
202 var resp *http.Response
203 if resp, err = this.Client.Do(req); err != nil {
204 log.Printf("[%v] Upload failed %v error: %v", requestId, url, err.Error())
205 upload_status <- uploadStatus{err, url, 0, 0, ""}
210 if xr := resp.Header.Get(X_Keep_Replicas_Stored); xr != "" {
211 fmt.Sscanf(xr, "%d", &rep)
214 defer resp.Body.Close()
215 defer io.Copy(ioutil.Discard, resp.Body)
217 respbody, err2 := ioutil.ReadAll(&io.LimitedReader{resp.Body, 4096})
218 response := strings.TrimSpace(string(respbody))
219 if err2 != nil && err2 != io.EOF {
220 log.Printf("[%v] Upload %v error: %v response: %v", requestId, url, err2.Error(), response)
221 upload_status <- uploadStatus{err2, url, resp.StatusCode, rep, response}
222 } else if resp.StatusCode == http.StatusOK {
223 log.Printf("[%v] Upload %v success", requestId, url)
224 upload_status <- uploadStatus{nil, url, resp.StatusCode, rep, response}
226 log.Printf("[%v] Upload %v error: %v response: %v", requestId, url, resp.StatusCode, response)
227 upload_status <- uploadStatus{errors.New(resp.Status), url, resp.StatusCode, rep, response}
231 func (this KeepClient) putReplicas(
233 tr *streamer.AsyncStream,
234 expectedLength int64) (locator string, replicas int, err error) {
236 // Take the hash of locator and timestamp in order to identify this
237 // specific transaction in log statements.
238 requestId := fmt.Sprintf("%x", md5.Sum([]byte(locator+time.Now().String())))[0:8]
240 // Calculate the ordering for uploading to servers
241 sv := NewRootSorter(this.WritableLocalRoots(), hash).GetSortedRoots()
243 // The next server to try contacting
246 // The number of active writers
249 // Used to communicate status from the upload goroutines
250 upload_status := make(chan uploadStatus)
252 // Wait for any abandoned uploads (e.g., we started
253 // two uploads and the first replied with replicas=2)
254 // to finish before closing the status channel.
263 // Desired number of replicas
264 remaining_replicas := this.Want_replicas
266 replicasPerThread := this.replicasPerService
267 if replicasPerThread < 1 {
268 // unlimited or unknown
269 replicasPerThread = remaining_replicas
272 for remaining_replicas > 0 {
273 for active*replicasPerThread < remaining_replicas {
274 // Start some upload requests
275 if next_server < len(sv) {
276 log.Printf("[%v] Begin upload %s to %s", requestId, hash, sv[next_server])
277 go this.uploadToKeepServer(sv[next_server], hash, tr.MakeStreamReader(), upload_status, expectedLength, requestId)
282 return locator, (this.Want_replicas - remaining_replicas), InsufficientReplicasError
288 log.Printf("[%v] Replicas remaining to write: %v active uploads: %v",
289 requestId, remaining_replicas, active)
291 // Now wait for something to happen.
292 status := <-upload_status
295 if status.statusCode == 200 {
297 remaining_replicas -= status.replicas_stored
298 locator = status.response
302 return locator, this.Want_replicas, nil