1 /* Deals with getting Keep Server blocks from API Server and Keep Servers. */
10 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
11 "git.curoverse.com/arvados.git/sdk/go/blockdigest"
12 "git.curoverse.com/arvados.git/sdk/go/keepclient"
13 "git.curoverse.com/arvados.git/sdk/go/logger"
23 // ServerAddress struct
24 type ServerAddress struct {
25 SSL bool `json:"service_ssl_flag"`
26 Host string `json:"service_host"`
27 Port int `json:"service_port"`
28 UUID string `json:"uuid"`
29 ServiceType string `json:"service_type"`
32 // BlockInfo is info about a particular block returned by the server
33 type BlockInfo struct {
34 Digest blockdigest.DigestWithSize
35 Mtime int64 // TODO(misha): Replace this with a timestamp.
38 // BlockServerInfo is info about a specified block given by a server
39 type BlockServerInfo struct {
41 Mtime int64 // TODO(misha): Replace this with a timestamp.
44 // ServerContents struct
45 type ServerContents struct {
46 BlockDigestToInfo map[blockdigest.DigestWithSize]BlockInfo
49 // ServerResponse struct
50 type ServerResponse struct {
52 Contents ServerContents
57 type ReadServers struct {
59 KeepServerIndexToAddress []ServerAddress
60 KeepServerAddressToIndex map[ServerAddress]int
61 ServerToContents map[ServerAddress]ServerContents
62 BlockToServers map[blockdigest.DigestWithSize][]BlockServerInfo
63 BlockReplicationCounts map[int]int
66 // GetKeepServersParams struct
67 type GetKeepServersParams struct {
68 Client arvadosclient.ArvadosClient
73 // ServiceList consists of the addresses of all the available kee servers
74 type ServiceList struct {
75 ItemsAvailable int `json:"items_available"`
76 KeepServers []ServerAddress `json:"items"`
80 // TODO(misha): Change this to include the UUID as well.
81 func (s ServerAddress) String() string {
85 // URL of the keep server
86 func (s ServerAddress) URL() string {
88 return fmt.Sprintf("https://%s:%d", s.Host, s.Port)
90 return fmt.Sprintf("http://%s:%d", s.Host, s.Port)
93 // GetKeepServersAndSummarize gets keep servers from api
94 func GetKeepServersAndSummarize(params GetKeepServersParams) (results ReadServers, err error) {
95 results, err = GetKeepServers(params)
99 log.Printf("Returned %d keep disks", len(results.ServerToContents))
101 results.Summarize(params.Logger)
102 log.Printf("Replication level distribution: %v",
103 results.BlockReplicationCounts)
108 // GetKeepServers from api server
109 func GetKeepServers(params GetKeepServersParams) (results ReadServers, err error) {
110 sdkParams := arvadosclient.Dict{
111 "filters": [][]string{[]string{"service_type", "!=", "proxy"}},
113 if params.Limit > 0 {
114 sdkParams["limit"] = params.Limit
117 var sdkResponse ServiceList
118 err = params.Client.List("keep_services", sdkParams, &sdkResponse)
124 // Currently, only "disk" types are supported. Stop if any other service types are found.
125 for _, server := range sdkResponse.KeepServers {
126 if server.ServiceType != "disk" {
127 return results, fmt.Errorf("Unsupported service type %q found for: %v", server.ServiceType, server)
131 if params.Logger != nil {
132 params.Logger.Update(func(p map[string]interface{}, e map[string]interface{}) {
133 keepInfo := logger.GetOrCreateMap(p, "keep_info")
134 keepInfo["num_keep_servers_available"] = sdkResponse.ItemsAvailable
135 keepInfo["num_keep_servers_received"] = len(sdkResponse.KeepServers)
136 keepInfo["keep_servers"] = sdkResponse.KeepServers
140 log.Printf("Received keep services list: %+v", sdkResponse)
142 if len(sdkResponse.KeepServers) < sdkResponse.ItemsAvailable {
143 return results, fmt.Errorf("Did not receive all available keep servers: %+v", sdkResponse)
146 results.KeepServerIndexToAddress = sdkResponse.KeepServers
147 results.KeepServerAddressToIndex = make(map[ServerAddress]int)
148 for i, address := range results.KeepServerIndexToAddress {
149 results.KeepServerAddressToIndex[address] = i
152 log.Printf("Got Server Addresses: %v", results)
154 // Send off all the index requests concurrently
155 responseChan := make(chan ServerResponse)
156 for _, keepServer := range sdkResponse.KeepServers {
157 // The above keepsServer variable is reused for each iteration, so
158 // it would be shared across all goroutines. This would result in
159 // us querying one server n times instead of n different servers
160 // as we intended. To avoid this we add it as an explicit
161 // parameter which gets copied. This bug and solution is described
162 // in https://golang.org/doc/effective_go.html#channels
163 go func(keepServer ServerAddress) {
164 responseChan <- GetServerContents(params.Logger,
170 results.ServerToContents = make(map[ServerAddress]ServerContents)
171 results.BlockToServers = make(map[blockdigest.DigestWithSize][]BlockServerInfo)
173 // Read all the responses
174 for i := range sdkResponse.KeepServers {
175 _ = i // Here to prevent go from complaining.
176 response := <-responseChan
178 // Check if there were any errors during GetServerContents
179 if response.Err != nil {
180 return results, response.Err
183 log.Printf("Received channel response from %v containing %d files",
185 len(response.Contents.BlockDigestToInfo))
186 results.ServerToContents[response.Address] = response.Contents
187 serverIndex := results.KeepServerAddressToIndex[response.Address]
188 for _, blockInfo := range response.Contents.BlockDigestToInfo {
189 results.BlockToServers[blockInfo.Digest] = append(
190 results.BlockToServers[blockInfo.Digest],
191 BlockServerInfo{ServerIndex: serverIndex,
192 Mtime: blockInfo.Mtime})
198 // GetServerContents of the keep server
199 func GetServerContents(arvLogger *logger.Logger,
200 keepServer ServerAddress,
201 arv arvadosclient.ArvadosClient) (response ServerResponse) {
203 err := GetServerStatus(arvLogger, keepServer, arv)
209 req, err := CreateIndexRequest(arvLogger, keepServer, arv)
215 resp, err := arv.Client.Do(req)
221 response, err = ReadServerResponse(arvLogger, keepServer, resp)
230 // GetServerStatus get keep server status by invoking /status.json
231 func GetServerStatus(arvLogger *logger.Logger,
232 keepServer ServerAddress,
233 arv arvadosclient.ArvadosClient) error {
234 url := fmt.Sprintf("http://%s:%d/status.json",
238 if arvLogger != nil {
240 arvLogger.Update(func(p map[string]interface{}, e map[string]interface{}) {
241 keepInfo := logger.GetOrCreateMap(p, "keep_info")
242 serverInfo := make(map[string]interface{})
243 serverInfo["status_request_sent_at"] = now
244 serverInfo["host"] = keepServer.Host
245 serverInfo["port"] = keepServer.Port
247 keepInfo[keepServer.UUID] = serverInfo
251 resp, err := arv.Client.Get(url)
253 return fmt.Errorf("Error getting keep status from %s: %v", url, err)
254 } else if resp.StatusCode != 200 {
255 return fmt.Errorf("Received error code %d in response to request "+
257 resp.StatusCode, url, resp.Status)
260 var keepStatus map[string]interface{}
261 decoder := json.NewDecoder(resp.Body)
263 err = decoder.Decode(&keepStatus)
265 return fmt.Errorf("Error decoding keep status from %s: %v", url, err)
268 if arvLogger != nil {
270 arvLogger.Update(func(p map[string]interface{}, e map[string]interface{}) {
271 keepInfo := logger.GetOrCreateMap(p, "keep_info")
272 serverInfo := keepInfo[keepServer.UUID].(map[string]interface{})
273 serverInfo["status_response_processed_at"] = now
274 serverInfo["status"] = keepStatus
281 // CreateIndexRequest to the keep server
282 func CreateIndexRequest(arvLogger *logger.Logger,
283 keepServer ServerAddress,
284 arv arvadosclient.ArvadosClient) (req *http.Request, err error) {
285 url := fmt.Sprintf("http://%s:%d/index", keepServer.Host, keepServer.Port)
286 log.Println("About to fetch keep server contents from " + url)
288 if arvLogger != nil {
290 arvLogger.Update(func(p map[string]interface{}, e map[string]interface{}) {
291 keepInfo := logger.GetOrCreateMap(p, "keep_info")
292 serverInfo := keepInfo[keepServer.UUID].(map[string]interface{})
293 serverInfo["index_request_sent_at"] = now
297 req, err = http.NewRequest("GET", url, nil)
299 return req, fmt.Errorf("Error building http request for %s: %v", url, err)
302 req.Header.Add("Authorization", "OAuth2 "+arv.ApiToken)
306 // ReadServerResponse reads reasponse from keep server
307 func ReadServerResponse(arvLogger *logger.Logger,
308 keepServer ServerAddress,
309 resp *http.Response) (response ServerResponse, err error) {
311 if resp.StatusCode != 200 {
312 return response, fmt.Errorf("Received error code %d in response to index request for %s: %s",
313 resp.StatusCode, keepServer.String(), resp.Status)
316 if arvLogger != nil {
318 arvLogger.Update(func(p map[string]interface{}, e map[string]interface{}) {
319 keepInfo := logger.GetOrCreateMap(p, "keep_info")
320 serverInfo := keepInfo[keepServer.UUID].(map[string]interface{})
321 serverInfo["index_response_received_at"] = now
325 response.Address = keepServer
326 response.Contents.BlockDigestToInfo =
327 make(map[blockdigest.DigestWithSize]BlockInfo)
328 reader := bufio.NewReader(resp.Body)
329 numLines, numDuplicates, numSizeDisagreements := 0, 0, 0
332 line, err := reader.ReadString('\n')
334 return response, fmt.Errorf("Index from %s truncated at line %d",
335 keepServer.String(), numLines)
336 } else if err != nil {
337 return response, fmt.Errorf("Error reading index response from %s at line %d: %v",
338 keepServer.String(), numLines, err)
341 if _, err := reader.Peek(1); err == nil {
342 extra, _ := reader.ReadString('\n')
343 return response, fmt.Errorf("Index from %s had trailing data at line %d after EOF marker: %s",
344 keepServer.String(), numLines+1, extra)
345 } else if err != io.EOF {
346 return response, fmt.Errorf("Index from %s had read error after EOF marker at line %d: %v",
347 keepServer.String(), numLines, err)
352 blockInfo, err := parseBlockInfoFromIndexLine(line)
354 return response, fmt.Errorf("Error parsing BlockInfo from index line "+
355 "received from %s: %v",
360 if storedBlock, ok := response.Contents.BlockDigestToInfo[blockInfo.Digest]; ok {
361 // This server returned multiple lines containing the same block digest.
363 // Keep the block that's newer.
364 if storedBlock.Mtime < blockInfo.Mtime {
365 response.Contents.BlockDigestToInfo[blockInfo.Digest] = blockInfo
368 response.Contents.BlockDigestToInfo[blockInfo.Digest] = blockInfo
372 log.Printf("%s index contained %d lines with %d duplicates with "+
373 "%d size disagreements",
377 numSizeDisagreements)
379 if arvLogger != nil {
381 arvLogger.Update(func(p map[string]interface{}, e map[string]interface{}) {
382 keepInfo := logger.GetOrCreateMap(p, "keep_info")
383 serverInfo := keepInfo[keepServer.UUID].(map[string]interface{})
385 serverInfo["processing_finished_at"] = now
386 serverInfo["lines_received"] = numLines
387 serverInfo["duplicates_seen"] = numDuplicates
388 serverInfo["size_disagreements_seen"] = numSizeDisagreements
395 func parseBlockInfoFromIndexLine(indexLine string) (blockInfo BlockInfo, err error) {
396 tokens := strings.Fields(indexLine)
397 if len(tokens) != 2 {
398 err = fmt.Errorf("Expected 2 tokens per line but received a "+
399 "line containing %#q instead.",
403 var locator blockdigest.BlockLocator
404 if locator, err = blockdigest.ParseBlockLocator(tokens[0]); err != nil {
405 err = fmt.Errorf("%v Received error while parsing line \"%#q\"",
409 if len(locator.Hints) > 0 {
410 err = fmt.Errorf("Block locator in index line should not contain hints "+
416 blockInfo.Mtime, err = strconv.ParseInt(tokens[1], 10, 64)
421 blockdigest.DigestWithSize{Digest: locator.Digest,
422 Size: uint32(locator.Size)}
426 // Summarize results from keep server
427 func (readServers *ReadServers) Summarize(arvLogger *logger.Logger) {
428 readServers.BlockReplicationCounts = make(map[int]int)
429 for _, infos := range readServers.BlockToServers {
430 replication := len(infos)
431 readServers.BlockReplicationCounts[replication]++
434 if arvLogger != nil {
435 arvLogger.Update(func(p map[string]interface{}, e map[string]interface{}) {
436 keepInfo := logger.GetOrCreateMap(p, "keep_info")
437 keepInfo["distinct_blocks_stored"] = len(readServers.BlockToServers)
442 // TrashRequest struct
443 type TrashRequest struct {
444 Locator string `json:"locator"`
445 BlockMtime int64 `json:"block_mtime"`
448 // TrashList is an array of TrashRequest objects
449 type TrashList []TrashRequest
451 // SendTrashLists to trash queue
452 func SendTrashLists(kc *keepclient.KeepClient, spl map[string]TrashList) (errs []error) {
454 barrier := make(chan error)
458 for url, v := range spl {
460 log.Printf("Sending trash list to %v", url)
462 go (func(url string, v TrashList) {
463 pipeReader, pipeWriter := io.Pipe()
465 enc := json.NewEncoder(pipeWriter)
470 req, err := http.NewRequest("PUT", fmt.Sprintf("%s/trash", url), pipeReader)
472 log.Printf("Error creating trash list request for %v error: %v", url, err.Error())
477 req.Header.Add("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
480 var resp *http.Response
481 if resp, err = client.Do(req); err != nil {
482 log.Printf("Error sending trash list to %v error: %v", url, err.Error())
487 log.Printf("Sent trash list to %v: response was HTTP %v", url, resp.Status)
489 io.Copy(ioutil.Discard, resp.Body)
492 if resp.StatusCode != 200 {
493 barrier <- errors.New(fmt.Sprintf("Got HTTP code %v", resp.StatusCode))
501 for i := 0; i < count; i++ {
504 errs = append(errs, b)