1 /* Deals with getting Keep Server blocks from API Server and Keep Servers. */
11 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
12 "git.curoverse.com/arvados.git/sdk/go/blockdigest"
13 "git.curoverse.com/arvados.git/sdk/go/keepclient"
14 "git.curoverse.com/arvados.git/sdk/go/logger"
24 // ServerAddress struct
25 type ServerAddress struct {
26 SSL bool `json:"service_ssl_flag"`
27 Host string `json:"service_host"`
28 Port int `json:"service_port"`
29 UUID string `json:"uuid"`
30 ServiceType string `json:"service_type"`
33 // BlockInfo is info about a particular block returned by the server
34 type BlockInfo struct {
35 Digest blockdigest.DigestWithSize
36 Mtime int64 // TODO(misha): Replace this with a timestamp.
39 // BlockServerInfo is info about a specified block given by a server
40 type BlockServerInfo struct {
42 Mtime int64 // TODO(misha): Replace this with a timestamp.
45 // ServerContents struct
46 type ServerContents struct {
47 BlockDigestToInfo map[blockdigest.DigestWithSize]BlockInfo
50 // ServerResponse struct
51 type ServerResponse struct {
53 Contents ServerContents
58 type ReadServers struct {
60 KeepServerIndexToAddress []ServerAddress
61 KeepServerAddressToIndex map[ServerAddress]int
62 ServerToContents map[ServerAddress]ServerContents
63 BlockToServers map[blockdigest.DigestWithSize][]BlockServerInfo
64 BlockReplicationCounts map[int]int
67 // GetKeepServersParams struct
68 type GetKeepServersParams struct {
69 Client arvadosclient.ArvadosClient
74 // ServiceList consists of the addresses of all the available kee servers
75 type ServiceList struct {
76 ItemsAvailable int `json:"items_available"`
77 KeepServers []ServerAddress `json:"items"`
80 var serviceType string
83 flag.StringVar(&serviceType,
86 "Operate only on keep_services with the specified service_type, ignoring all others.")
90 // TODO(misha): Change this to include the UUID as well.
91 func (s ServerAddress) String() string {
95 // URL of the keep server
96 func (s ServerAddress) URL() string {
98 return fmt.Sprintf("https://%s:%d", s.Host, s.Port)
100 return fmt.Sprintf("http://%s:%d", s.Host, s.Port)
103 // GetKeepServersAndSummarize gets keep servers from api
104 func GetKeepServersAndSummarize(params GetKeepServersParams) (results ReadServers, err error) {
105 results, err = GetKeepServers(params)
109 log.Printf("Returned %d keep disks", len(results.ServerToContents))
111 results.Summarize(params.Logger)
112 log.Printf("Replication level distribution: %v",
113 results.BlockReplicationCounts)
118 // GetKeepServers from api server
119 func GetKeepServers(params GetKeepServersParams) (results ReadServers, err error) {
120 sdkParams := arvadosclient.Dict{
121 "filters": [][]string{[]string{"service_type", "!=", "proxy"}},
123 if params.Limit > 0 {
124 sdkParams["limit"] = params.Limit
127 var sdkResponse ServiceList
128 err = params.Client.List("keep_services", sdkParams, &sdkResponse)
134 var keepServers []ServerAddress
135 for _, server := range sdkResponse.KeepServers {
136 if server.ServiceType == serviceType {
137 keepServers = append(keepServers, server)
139 log.Printf("Skipping keep_service %q because its service_type %q does not match -service-type=%q", server, server.ServiceType, serviceType)
143 if len(keepServers) == 0 {
144 return results, fmt.Errorf("Found no keepservices with the service type %v", serviceType)
147 if params.Logger != nil {
148 params.Logger.Update(func(p map[string]interface{}, e map[string]interface{}) {
149 keepInfo := logger.GetOrCreateMap(p, "keep_info")
150 keepInfo["num_keep_servers_available"] = sdkResponse.ItemsAvailable
151 keepInfo["num_keep_servers_received"] = len(sdkResponse.KeepServers)
152 keepInfo["keep_servers"] = sdkResponse.KeepServers
153 keepInfo["indexable_keep_servers"] = keepServers
157 log.Printf("Received keep services list: %+v", sdkResponse)
159 if len(sdkResponse.KeepServers) < sdkResponse.ItemsAvailable {
160 return results, fmt.Errorf("Did not receive all available keep servers: %+v", sdkResponse)
163 results.KeepServerIndexToAddress = keepServers
164 results.KeepServerAddressToIndex = make(map[ServerAddress]int)
165 for i, address := range results.KeepServerIndexToAddress {
166 results.KeepServerAddressToIndex[address] = i
169 log.Printf("Got Server Addresses: %v", results)
171 // Send off all the index requests concurrently
172 responseChan := make(chan ServerResponse)
173 for _, keepServer := range results.KeepServerIndexToAddress {
174 // The above keepsServer variable is reused for each iteration, so
175 // it would be shared across all goroutines. This would result in
176 // us querying one server n times instead of n different servers
177 // as we intended. To avoid this we add it as an explicit
178 // parameter which gets copied. This bug and solution is described
179 // in https://golang.org/doc/effective_go.html#channels
180 go func(keepServer ServerAddress) {
181 responseChan <- GetServerContents(params.Logger,
187 results.ServerToContents = make(map[ServerAddress]ServerContents)
188 results.BlockToServers = make(map[blockdigest.DigestWithSize][]BlockServerInfo)
190 // Read all the responses
191 for i := range results.KeepServerIndexToAddress {
192 _ = i // Here to prevent go from complaining.
193 response := <-responseChan
195 // Check if there were any errors during GetServerContents
196 if response.Err != nil {
197 return results, response.Err
200 log.Printf("Received channel response from %v containing %d files",
202 len(response.Contents.BlockDigestToInfo))
203 results.ServerToContents[response.Address] = response.Contents
204 serverIndex := results.KeepServerAddressToIndex[response.Address]
205 for _, blockInfo := range response.Contents.BlockDigestToInfo {
206 results.BlockToServers[blockInfo.Digest] = append(
207 results.BlockToServers[blockInfo.Digest],
208 BlockServerInfo{ServerIndex: serverIndex,
209 Mtime: blockInfo.Mtime})
215 // GetServerContents of the keep server
216 func GetServerContents(arvLogger *logger.Logger,
217 keepServer ServerAddress,
218 arv arvadosclient.ArvadosClient) (response ServerResponse) {
220 err := GetServerStatus(arvLogger, keepServer, arv)
226 req, err := CreateIndexRequest(arvLogger, keepServer, arv)
232 resp, err := arv.Client.Do(req)
238 response, err = ReadServerResponse(arvLogger, keepServer, resp)
247 // GetServerStatus get keep server status by invoking /status.json
248 func GetServerStatus(arvLogger *logger.Logger,
249 keepServer ServerAddress,
250 arv arvadosclient.ArvadosClient) error {
251 url := fmt.Sprintf("http://%s:%d/status.json",
255 if arvLogger != nil {
257 arvLogger.Update(func(p map[string]interface{}, e map[string]interface{}) {
258 keepInfo := logger.GetOrCreateMap(p, "keep_info")
259 serverInfo := make(map[string]interface{})
260 serverInfo["status_request_sent_at"] = now
261 serverInfo["host"] = keepServer.Host
262 serverInfo["port"] = keepServer.Port
264 keepInfo[keepServer.UUID] = serverInfo
268 resp, err := arv.Client.Get(url)
270 return fmt.Errorf("Error getting keep status from %s: %v", url, err)
271 } else if resp.StatusCode != 200 {
272 return fmt.Errorf("Received error code %d in response to request "+
274 resp.StatusCode, url, resp.Status)
277 var keepStatus map[string]interface{}
278 decoder := json.NewDecoder(resp.Body)
280 err = decoder.Decode(&keepStatus)
282 return fmt.Errorf("Error decoding keep status from %s: %v", url, err)
285 if arvLogger != nil {
287 arvLogger.Update(func(p map[string]interface{}, e map[string]interface{}) {
288 keepInfo := logger.GetOrCreateMap(p, "keep_info")
289 serverInfo := keepInfo[keepServer.UUID].(map[string]interface{})
290 serverInfo["status_response_processed_at"] = now
291 serverInfo["status"] = keepStatus
298 // CreateIndexRequest to the keep server
299 func CreateIndexRequest(arvLogger *logger.Logger,
300 keepServer ServerAddress,
301 arv arvadosclient.ArvadosClient) (req *http.Request, err error) {
302 url := fmt.Sprintf("http://%s:%d/index", keepServer.Host, keepServer.Port)
303 log.Println("About to fetch keep server contents from " + url)
305 if arvLogger != nil {
307 arvLogger.Update(func(p map[string]interface{}, e map[string]interface{}) {
308 keepInfo := logger.GetOrCreateMap(p, "keep_info")
309 serverInfo := keepInfo[keepServer.UUID].(map[string]interface{})
310 serverInfo["index_request_sent_at"] = now
314 req, err = http.NewRequest("GET", url, nil)
316 return req, fmt.Errorf("Error building http request for %s: %v", url, err)
319 req.Header.Add("Authorization", "OAuth2 "+arv.ApiToken)
323 // ReadServerResponse reads reasponse from keep server
324 func ReadServerResponse(arvLogger *logger.Logger,
325 keepServer ServerAddress,
326 resp *http.Response) (response ServerResponse, err error) {
328 if resp.StatusCode != 200 {
329 return response, fmt.Errorf("Received error code %d in response to index request for %s: %s",
330 resp.StatusCode, keepServer.String(), resp.Status)
333 if arvLogger != nil {
335 arvLogger.Update(func(p map[string]interface{}, e map[string]interface{}) {
336 keepInfo := logger.GetOrCreateMap(p, "keep_info")
337 serverInfo := keepInfo[keepServer.UUID].(map[string]interface{})
338 serverInfo["index_response_received_at"] = now
342 response.Address = keepServer
343 response.Contents.BlockDigestToInfo =
344 make(map[blockdigest.DigestWithSize]BlockInfo)
345 reader := bufio.NewReader(resp.Body)
346 numLines, numDuplicates, numSizeDisagreements := 0, 0, 0
349 line, err := reader.ReadString('\n')
351 return response, fmt.Errorf("Index from %s truncated at line %d",
352 keepServer.String(), numLines)
353 } else if err != nil {
354 return response, fmt.Errorf("Error reading index response from %s at line %d: %v",
355 keepServer.String(), numLines, err)
358 if _, err := reader.Peek(1); err == nil {
359 extra, _ := reader.ReadString('\n')
360 return response, fmt.Errorf("Index from %s had trailing data at line %d after EOF marker: %s",
361 keepServer.String(), numLines+1, extra)
362 } else if err != io.EOF {
363 return response, fmt.Errorf("Index from %s had read error after EOF marker at line %d: %v",
364 keepServer.String(), numLines, err)
369 blockInfo, err := parseBlockInfoFromIndexLine(line)
371 return response, fmt.Errorf("Error parsing BlockInfo from index line "+
372 "received from %s: %v",
377 if storedBlock, ok := response.Contents.BlockDigestToInfo[blockInfo.Digest]; ok {
378 // This server returned multiple lines containing the same block digest.
380 // Keep the block that's newer.
381 if storedBlock.Mtime < blockInfo.Mtime {
382 response.Contents.BlockDigestToInfo[blockInfo.Digest] = blockInfo
385 response.Contents.BlockDigestToInfo[blockInfo.Digest] = blockInfo
389 log.Printf("%s index contained %d lines with %d duplicates with "+
390 "%d size disagreements",
394 numSizeDisagreements)
396 if arvLogger != nil {
398 arvLogger.Update(func(p map[string]interface{}, e map[string]interface{}) {
399 keepInfo := logger.GetOrCreateMap(p, "keep_info")
400 serverInfo := keepInfo[keepServer.UUID].(map[string]interface{})
402 serverInfo["processing_finished_at"] = now
403 serverInfo["lines_received"] = numLines
404 serverInfo["duplicates_seen"] = numDuplicates
405 serverInfo["size_disagreements_seen"] = numSizeDisagreements
412 func parseBlockInfoFromIndexLine(indexLine string) (blockInfo BlockInfo, err error) {
413 tokens := strings.Fields(indexLine)
414 if len(tokens) != 2 {
415 err = fmt.Errorf("Expected 2 tokens per line but received a "+
416 "line containing %#q instead.",
420 var locator blockdigest.BlockLocator
421 if locator, err = blockdigest.ParseBlockLocator(tokens[0]); err != nil {
422 err = fmt.Errorf("%v Received error while parsing line \"%#q\"",
426 if len(locator.Hints) > 0 {
427 err = fmt.Errorf("Block locator in index line should not contain hints "+
433 blockInfo.Mtime, err = strconv.ParseInt(tokens[1], 10, 64)
438 blockdigest.DigestWithSize{Digest: locator.Digest,
439 Size: uint32(locator.Size)}
443 // Summarize results from keep server
444 func (readServers *ReadServers) Summarize(arvLogger *logger.Logger) {
445 readServers.BlockReplicationCounts = make(map[int]int)
446 for _, infos := range readServers.BlockToServers {
447 replication := len(infos)
448 readServers.BlockReplicationCounts[replication]++
451 if arvLogger != nil {
452 arvLogger.Update(func(p map[string]interface{}, e map[string]interface{}) {
453 keepInfo := logger.GetOrCreateMap(p, "keep_info")
454 keepInfo["distinct_blocks_stored"] = len(readServers.BlockToServers)
459 // TrashRequest struct
460 type TrashRequest struct {
461 Locator string `json:"locator"`
462 BlockMtime int64 `json:"block_mtime"`
465 // TrashList is an array of TrashRequest objects
466 type TrashList []TrashRequest
468 // SendTrashLists to trash queue
469 func SendTrashLists(arvLogger *logger.Logger, kc *keepclient.KeepClient, spl map[string]TrashList, dryRun bool) (errs []error) {
471 barrier := make(chan error)
475 for url, v := range spl {
476 if arvLogger != nil {
477 // We need a local variable because Update doesn't call our mutator func until later,
478 // when our list variable might have been reused by the next loop iteration.
481 arvLogger.Update(func(p map[string]interface{}, e map[string]interface{}) {
482 trashListInfo := logger.GetOrCreateMap(p, "trash_list_len")
483 trashListInfo[url] = trashLen
488 log.Printf("dry run, not sending trash list to service %s with %d blocks", url, len(v))
493 log.Printf("Sending trash list to %v", url)
495 go (func(url string, v TrashList) {
496 pipeReader, pipeWriter := io.Pipe()
498 enc := json.NewEncoder(pipeWriter)
503 req, err := http.NewRequest("PUT", fmt.Sprintf("%s/trash", url), pipeReader)
505 log.Printf("Error creating trash list request for %v error: %v", url, err.Error())
510 req.Header.Add("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
513 var resp *http.Response
514 if resp, err = client.Do(req); err != nil {
515 log.Printf("Error sending trash list to %v error: %v", url, err.Error())
520 log.Printf("Sent trash list to %v: response was HTTP %v", url, resp.Status)
522 io.Copy(ioutil.Discard, resp.Body)
525 if resp.StatusCode != 200 {
526 barrier <- errors.New(fmt.Sprintf("Got HTTP code %v", resp.StatusCode))
533 for i := 0; i < count; i++ {
536 errs = append(errs, b)