7253: Write a test that "does not" fail when an invalid manifest text is retrieved...
[arvados.git] / services / datamanager / keep / keep.go
1 /* Deals with getting Keep Server blocks from API Server and Keep Servers. */
2
3 package keep
4
5 import (
6         "bufio"
7         "encoding/json"
8         "errors"
9         "fmt"
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"
14         "io"
15         "io/ioutil"
16         "log"
17         "net/http"
18         "strconv"
19         "strings"
20         "time"
21 )
22
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"`
30 }
31
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.
36 }
37
38 // BlockServerInfo is info about a specified block given by a server
39 type BlockServerInfo struct {
40         ServerIndex int
41         Mtime       int64 // TODO(misha): Replace this with a timestamp.
42 }
43
44 // ServerContents struct
45 type ServerContents struct {
46         BlockDigestToInfo map[blockdigest.DigestWithSize]BlockInfo
47 }
48
49 // ServerResponse struct
50 type ServerResponse struct {
51         Address  ServerAddress
52         Contents ServerContents
53         Err      error
54 }
55
56 // ReadServers struct
57 type ReadServers struct {
58         ReadAllServers           bool
59         KeepServerIndexToAddress []ServerAddress
60         KeepServerAddressToIndex map[ServerAddress]int
61         ServerToContents         map[ServerAddress]ServerContents
62         BlockToServers           map[blockdigest.DigestWithSize][]BlockServerInfo
63         BlockReplicationCounts   map[int]int
64 }
65
66 // GetKeepServersParams struct
67 type GetKeepServersParams struct {
68         Client arvadosclient.ArvadosClient
69         Logger *logger.Logger
70         Limit  int
71 }
72
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"`
77 }
78
79 // String
80 // TODO(misha): Change this to include the UUID as well.
81 func (s ServerAddress) String() string {
82         return s.URL()
83 }
84
85 // URL of the keep server
86 func (s ServerAddress) URL() string {
87         if s.SSL {
88                 return fmt.Sprintf("https://%s:%d", s.Host, s.Port)
89         }
90         return fmt.Sprintf("http://%s:%d", s.Host, s.Port)
91 }
92
93 // GetKeepServersAndSummarize gets keep servers from api
94 func GetKeepServersAndSummarize(params GetKeepServersParams) (results ReadServers, err error) {
95         results, err = GetKeepServers(params)
96         if err != nil {
97                 return
98         }
99         log.Printf("Returned %d keep disks", len(results.ServerToContents))
100
101         results.Summarize(params.Logger)
102         log.Printf("Replication level distribution: %v",
103                 results.BlockReplicationCounts)
104
105         return
106 }
107
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"}},
112         }
113         if params.Limit > 0 {
114                 sdkParams["limit"] = params.Limit
115         }
116
117         var sdkResponse ServiceList
118         err = params.Client.List("keep_services", sdkParams, &sdkResponse)
119
120         if err != nil {
121                 return
122         }
123
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)
128                 }
129         }
130
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
137                 })
138         }
139
140         log.Printf("Received keep services list: %+v", sdkResponse)
141
142         if len(sdkResponse.KeepServers) < sdkResponse.ItemsAvailable {
143                 return results, fmt.Errorf("Did not receive all available keep servers: %+v", sdkResponse)
144         }
145
146         results.KeepServerIndexToAddress = sdkResponse.KeepServers
147         results.KeepServerAddressToIndex = make(map[ServerAddress]int)
148         for i, address := range results.KeepServerIndexToAddress {
149                 results.KeepServerAddressToIndex[address] = i
150         }
151
152         log.Printf("Got Server Addresses: %v", results)
153
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,
165                                 keepServer,
166                                 params.Client)
167                 }(keepServer)
168         }
169
170         results.ServerToContents = make(map[ServerAddress]ServerContents)
171         results.BlockToServers = make(map[blockdigest.DigestWithSize][]BlockServerInfo)
172
173         // Read all the responses
174         for i := range sdkResponse.KeepServers {
175                 _ = i // Here to prevent go from complaining.
176                 response := <-responseChan
177
178                 // Check if there were any errors during GetServerContents
179                 if response.Err != nil {
180                         return results, response.Err
181                 }
182
183                 log.Printf("Received channel response from %v containing %d files",
184                         response.Address,
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})
193                 }
194         }
195         return
196 }
197
198 // GetServerContents of the keep server
199 func GetServerContents(arvLogger *logger.Logger,
200         keepServer ServerAddress,
201         arv arvadosclient.ArvadosClient) (response ServerResponse) {
202
203         err := GetServerStatus(arvLogger, keepServer, arv)
204         if err != nil {
205                 response.Err = err
206                 return
207         }
208
209         req, err := CreateIndexRequest(arvLogger, keepServer, arv)
210         if err != nil {
211                 response.Err = err
212                 return
213         }
214
215         resp, err := arv.Client.Do(req)
216         if err != nil {
217                 response.Err = err
218                 return
219         }
220
221         response, err = ReadServerResponse(arvLogger, keepServer, resp)
222         if err != nil {
223                 response.Err = err
224                 return
225         }
226
227         return
228 }
229
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",
235                 keepServer.Host,
236                 keepServer.Port)
237
238         if arvLogger != nil {
239                 now := time.Now()
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
246
247                         keepInfo[keepServer.UUID] = serverInfo
248                 })
249         }
250
251         resp, err := arv.Client.Get(url)
252         if err != nil {
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 "+
256                         "for %s status: %s",
257                         resp.StatusCode, url, resp.Status)
258         }
259
260         var keepStatus map[string]interface{}
261         decoder := json.NewDecoder(resp.Body)
262         decoder.UseNumber()
263         err = decoder.Decode(&keepStatus)
264         if err != nil {
265                 return fmt.Errorf("Error decoding keep status from %s: %v", url, err)
266         }
267
268         if arvLogger != nil {
269                 now := time.Now()
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
275                 })
276         }
277
278         return nil
279 }
280
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)
287
288         if arvLogger != nil {
289                 now := time.Now()
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
294                 })
295         }
296
297         req, err = http.NewRequest("GET", url, nil)
298         if err != nil {
299                 return req, fmt.Errorf("Error building http request for %s: %v", url, err)
300         }
301
302         req.Header.Add("Authorization", "OAuth2 "+arv.ApiToken)
303         return req, err
304 }
305
306 // ReadServerResponse reads reasponse from keep server
307 func ReadServerResponse(arvLogger *logger.Logger,
308         keepServer ServerAddress,
309         resp *http.Response) (response ServerResponse, err error) {
310
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)
314         }
315
316         if arvLogger != nil {
317                 now := time.Now()
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
322                 })
323         }
324
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
330         for {
331                 numLines++
332                 line, err := reader.ReadString('\n')
333                 if err == io.EOF {
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)
339                 }
340                 if line == "\n" {
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)
348                         }
349                         numLines--
350                         break
351                 }
352                 blockInfo, err := parseBlockInfoFromIndexLine(line)
353                 if err != nil {
354                         return response, fmt.Errorf("Error parsing BlockInfo from index line "+
355                                 "received from %s: %v",
356                                 keepServer.String(),
357                                 err)
358                 }
359
360                 if storedBlock, ok := response.Contents.BlockDigestToInfo[blockInfo.Digest]; ok {
361                         // This server returned multiple lines containing the same block digest.
362                         numDuplicates++
363                         // Keep the block that's newer.
364                         if storedBlock.Mtime < blockInfo.Mtime {
365                                 response.Contents.BlockDigestToInfo[blockInfo.Digest] = blockInfo
366                         }
367                 } else {
368                         response.Contents.BlockDigestToInfo[blockInfo.Digest] = blockInfo
369                 }
370         }
371
372         log.Printf("%s index contained %d lines with %d duplicates with "+
373                 "%d size disagreements",
374                 keepServer.String(),
375                 numLines,
376                 numDuplicates,
377                 numSizeDisagreements)
378
379         if arvLogger != nil {
380                 now := time.Now()
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{})
384
385                         serverInfo["processing_finished_at"] = now
386                         serverInfo["lines_received"] = numLines
387                         serverInfo["duplicates_seen"] = numDuplicates
388                         serverInfo["size_disagreements_seen"] = numSizeDisagreements
389                 })
390         }
391         resp.Body.Close()
392         return
393 }
394
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.",
400                         tokens)
401         }
402
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\"",
406                         err, indexLine)
407                 return
408         }
409         if len(locator.Hints) > 0 {
410                 err = fmt.Errorf("Block locator in index line should not contain hints "+
411                         "but it does: %#q",
412                         locator)
413                 return
414         }
415
416         blockInfo.Mtime, err = strconv.ParseInt(tokens[1], 10, 64)
417         if err != nil {
418                 return
419         }
420         blockInfo.Digest =
421                 blockdigest.DigestWithSize{Digest: locator.Digest,
422                         Size: uint32(locator.Size)}
423         return
424 }
425
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]++
432         }
433
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)
438                 })
439         }
440 }
441
442 // TrashRequest struct
443 type TrashRequest struct {
444         Locator    string `json:"locator"`
445         BlockMtime int64  `json:"block_mtime"`
446 }
447
448 // TrashList is an array of TrashRequest objects
449 type TrashList []TrashRequest
450
451 // SendTrashLists to trash queue
452 func SendTrashLists(kc *keepclient.KeepClient, spl map[string]TrashList) (errs []error) {
453         count := 0
454         barrier := make(chan error)
455
456         client := kc.Client
457
458         for url, v := range spl {
459                 count++
460                 log.Printf("Sending trash list to %v", url)
461
462                 go (func(url string, v TrashList) {
463                         pipeReader, pipeWriter := io.Pipe()
464                         go (func() {
465                                 enc := json.NewEncoder(pipeWriter)
466                                 enc.Encode(v)
467                                 pipeWriter.Close()
468                         })()
469
470                         req, err := http.NewRequest("PUT", fmt.Sprintf("%s/trash", url), pipeReader)
471                         if err != nil {
472                                 log.Printf("Error creating trash list request for %v error: %v", url, err.Error())
473                                 barrier <- err
474                                 return
475                         }
476
477                         req.Header.Add("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
478
479                         // Make the request
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())
483                                 barrier <- err
484                                 return
485                         }
486
487                         log.Printf("Sent trash list to %v: response was HTTP %v", url, resp.Status)
488
489                         io.Copy(ioutil.Discard, resp.Body)
490                         resp.Body.Close()
491
492                         if resp.StatusCode != 200 {
493                                 barrier <- errors.New(fmt.Sprintf("Got HTTP code %v", resp.StatusCode))
494                         } else {
495                                 barrier <- nil
496                         }
497                 })(url, v)
498
499         }
500
501         for i := 0; i < count; i++ {
502                 b := <-barrier
503                 if b != nil {
504                         errs = append(errs, b)
505                 }
506         }
507
508         return errs
509 }