1 /* Internal methods to support keepclient.go */
16 type keepDisk struct {
17 Hostname string `json:"service_host"`
18 Port int `json:"service_port"`
19 SSL bool `json:"service_ssl_flag"`
20 SvcType string `json:"service_type"`
23 func (this *KeepClient) DiscoverKeepServers() error {
24 if prx := os.Getenv("ARVADOS_KEEP_PROXY"); prx != "" {
25 this.SetServiceRoots([]string{prx})
26 this.Using_proxy = true
30 // Construct request of keep disk list
34 if req, err = http.NewRequest("GET", fmt.Sprintf("https://%s/arvados/v1/keep_services/accessible?format=json", this.ApiServer), nil); err != nil {
38 // Add api token header
39 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", this.ApiToken))
41 req.Header.Add("X-External-Client", "1")
45 var resp *http.Response
46 if resp, err = this.Client.Do(req); err != nil {
50 if resp.StatusCode != http.StatusOK {
51 // fall back on keep disks
52 if req, err = http.NewRequest("GET", fmt.Sprintf("https://%s/arvados/v1/keep_disks", this.ApiServer), nil); err != nil {
55 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", this.ApiToken))
56 if resp, err = this.Client.Do(req); err != nil {
59 if resp.StatusCode != http.StatusOK {
60 return errors.New(resp.Status)
65 Items []keepDisk `json:"items"`
69 dec := json.NewDecoder(resp.Body)
71 if err := dec.Decode(&m); err != nil {
75 listed := make(map[string]bool)
76 service_roots := make([]string, 0, len(m.Items))
78 for _, element := range m.Items {
85 // Construct server URL
86 url := fmt.Sprintf("http%s://%s:%d", n, element.Hostname, element.Port)
91 service_roots = append(service_roots, url)
93 if element.SvcType == "proxy" {
94 this.Using_proxy = true
98 this.SetServiceRoots(service_roots)
103 func (this KeepClient) shuffledServiceRoots(hash string) (pseq []string) {
104 // Build an ordering with which to query the Keep servers based on the
105 // contents of the hash. "hash" is a hex-encoded number at least 8
106 // digits (32 bits) long
108 // seed used to calculate the next keep server from 'pool' to be added
112 // Keep servers still to be added to the ordering
113 service_roots := this.ServiceRoots()
114 pool := make([]string, len(service_roots))
115 copy(pool, service_roots)
117 // output probe sequence
118 pseq = make([]string, 0, len(service_roots))
120 // iterate while there are servers left to be assigned
124 // ran out of digits in the seed
125 if len(pseq) < (len(hash) / 4) {
126 // the number of servers added to the probe
127 // sequence is less than the number of 4-digit
128 // slices in 'hash' so refill the seed with the
130 seed = hash[len(hash)-4:]
135 // Take the next 8 digits (32 bytes) and interpret as an integer,
136 // then modulus with the size of the remaining pool to get the next
138 probe, _ := strconv.ParseUint(seed[0:8], 16, 32)
139 probe %= uint64(len(pool))
141 // Append the selected server to the probe sequence and remove it
143 pseq = append(pseq, pool[probe])
144 pool = append(pool[:probe], pool[probe+1:]...)
146 // Remove the digits just used from the seed
152 type uploadStatus struct {
159 func (this KeepClient) uploadToKeepServer(host string, hash string, body io.ReadCloser,
160 upload_status chan<- uploadStatus, expectedLength int64) {
162 log.Printf("Uploading %s to %s", hash, host)
164 var req *http.Request
166 var url = fmt.Sprintf("%s/%s", host, hash)
167 if req, err = http.NewRequest("PUT", url, nil); err != nil {
168 upload_status <- uploadStatus{err, url, 0, 0}
173 if expectedLength > 0 {
174 req.ContentLength = expectedLength
177 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", this.ApiToken))
178 req.Header.Add("Content-Type", "application/octet-stream")
180 if this.Using_proxy {
181 req.Header.Add(X_Keep_Desired_Replicas, fmt.Sprint(this.Want_replicas))
186 var resp *http.Response
187 if resp, err = this.Client.Do(req); err != nil {
188 upload_status <- uploadStatus{err, url, 0, 0}
194 if xr := resp.Header.Get(X_Keep_Replicas_Stored); xr != "" {
195 fmt.Sscanf(xr, "%d", &rep)
198 if resp.StatusCode == http.StatusOK {
199 upload_status <- uploadStatus{nil, url, resp.StatusCode, rep}
201 upload_status <- uploadStatus{errors.New(resp.Status), url, resp.StatusCode, rep}
205 func (this KeepClient) putReplicas(
207 tr *streamer.AsyncStream,
208 expectedLength int64) (replicas int, err error) {
210 // Calculate the ordering for uploading to servers
211 sv := this.shuffledServiceRoots(hash)
213 // The next server to try contacting
216 // The number of active writers
219 // Used to communicate status from the upload goroutines
220 upload_status := make(chan uploadStatus)
221 defer close(upload_status)
223 // Desired number of replicas
225 remaining_replicas := this.Want_replicas
227 for remaining_replicas > 0 {
228 for active < remaining_replicas {
229 // Start some upload requests
230 if next_server < len(sv) {
231 go this.uploadToKeepServer(sv[next_server], hash, tr.MakeStreamReader(), upload_status, expectedLength)
236 return (this.Want_replicas - remaining_replicas), InsufficientReplicasError
243 // Now wait for something to happen.
244 status := <-upload_status
245 if status.statusCode == 200 {
247 remaining_replicas -= status.replicas_stored
249 // writing to keep server failed for some reason
250 log.Printf("Keep server put to %v failed with '%v'",
251 status.url, status.err)
254 log.Printf("Upload to %v status code: %v remaining replicas: %v active: %v", status.url, status.statusCode, remaining_replicas, active)
257 return this.Want_replicas, nil