21700: Install Bundler system-wide in Rails postinst
[arvados.git] / tools / keep-block-check / keep-block-check.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package main
6
7 import (
8         "crypto/tls"
9         "errors"
10         "flag"
11         "fmt"
12         "io"
13         "io/ioutil"
14         "log"
15         "net/http"
16         "os"
17         "strings"
18         "time"
19
20         "git.arvados.org/arvados.git/lib/cmd"
21         "git.arvados.org/arvados.git/sdk/go/arvadosclient"
22         "git.arvados.org/arvados.git/sdk/go/keepclient"
23 )
24
25 var version = "dev"
26
27 func main() {
28         os.Exit(doMain(os.Args[1:], os.Stderr))
29 }
30
31 func doMain(args []string, stderr io.Writer) int {
32         flags := flag.NewFlagSet("keep-block-check", flag.ExitOnError)
33
34         configFile := flags.String(
35                 "config",
36                 "",
37                 "Configuration filename. May be either a pathname to a config file, or (for example) 'foo' as shorthand for $HOME/.config/arvados/foo.conf file. This file is expected to specify the values for ARVADOS_API_TOKEN, ARVADOS_API_HOST, ARVADOS_API_HOST_INSECURE, and ARVADOS_BLOB_SIGNING_KEY for the source.")
38
39         keepServicesJSON := flags.String(
40                 "keep-services-json",
41                 "",
42                 "An optional list of available keepservices. "+
43                         "If not provided, this list is obtained from api server configured in config-file.")
44
45         locatorFile := flags.String(
46                 "block-hash-file",
47                 "",
48                 "Filename containing the block hashes to be checked. This is required. "+
49                         "This file contains the block hashes one per line.")
50
51         prefix := flags.String(
52                 "prefix",
53                 "",
54                 "Block hash prefix. When a prefix is specified, only hashes listed in the file with this prefix will be checked.")
55
56         blobSignatureTTLFlag := flags.Duration(
57                 "blob-signature-ttl",
58                 0,
59                 "Lifetime of blob permission signatures on the keepservers. If not provided, this will be retrieved from the API server's discovery document.")
60
61         verbose := flags.Bool(
62                 "v",
63                 false,
64                 "Log progress of each block verification")
65
66         getVersion := flags.Bool(
67                 "version",
68                 false,
69                 "Print version information and exit.")
70
71         if ok, code := cmd.ParseFlags(flags, os.Args[0], args, "", stderr); !ok {
72                 return code
73         } else if *getVersion {
74                 fmt.Printf("%s %s\n", os.Args[0], version)
75                 return 0
76         }
77
78         config, blobSigningKey, err := loadConfig(*configFile)
79         if err != nil {
80                 fmt.Fprintf(stderr, "Error loading configuration from file: %s\n", err)
81                 return 1
82         }
83
84         // get list of block locators to be checked
85         blockLocators, err := getBlockLocators(*locatorFile, *prefix)
86         if err != nil {
87                 fmt.Fprintf(stderr, "Error reading block hashes to be checked from file: %s\n", err)
88                 return 1
89         }
90
91         // setup keepclient
92         kc, blobSignatureTTL, err := setupKeepClient(config, *keepServicesJSON, *blobSignatureTTLFlag)
93         if err != nil {
94                 fmt.Fprintf(stderr, "Error configuring keepclient: %s\n", err)
95                 return 1
96         }
97
98         err = performKeepBlockCheck(kc, blobSignatureTTL, blobSigningKey, blockLocators, *verbose)
99         if err != nil {
100                 fmt.Fprintln(stderr, err)
101                 return 1
102         }
103
104         return 0
105 }
106
107 type apiConfig struct {
108         APIToken        string
109         APIHost         string
110         APIHostInsecure bool
111 }
112
113 // Load config from given file
114 func loadConfig(configFile string) (config apiConfig, blobSigningKey string, err error) {
115         if configFile == "" {
116                 err = errors.New("Client config file not specified")
117                 return
118         }
119
120         config, blobSigningKey, err = readConfigFromFile(configFile)
121         return
122 }
123
124 // Read config from file
125 func readConfigFromFile(filename string) (config apiConfig, blobSigningKey string, err error) {
126         if !strings.Contains(filename, "/") {
127                 filename = os.Getenv("HOME") + "/.config/arvados/" + filename + ".conf"
128         }
129
130         content, err := ioutil.ReadFile(filename)
131
132         if err != nil {
133                 return
134         }
135
136         lines := strings.Split(string(content), "\n")
137         for _, line := range lines {
138                 if line == "" {
139                         continue
140                 }
141
142                 kv := strings.SplitN(line, "=", 2)
143                 if len(kv) == 2 {
144                         key := strings.TrimSpace(kv[0])
145                         value := strings.TrimSpace(kv[1])
146
147                         switch key {
148                         case "ARVADOS_API_TOKEN":
149                                 config.APIToken = value
150                         case "ARVADOS_API_HOST":
151                                 config.APIHost = value
152                         case "ARVADOS_API_HOST_INSECURE":
153                                 config.APIHostInsecure = arvadosclient.StringBool(value)
154                         case "ARVADOS_BLOB_SIGNING_KEY":
155                                 blobSigningKey = value
156                         }
157                 }
158         }
159
160         return
161 }
162
163 // setup keepclient using the config provided
164 func setupKeepClient(config apiConfig, keepServicesJSON string, blobSignatureTTL time.Duration) (kc *keepclient.KeepClient, ttl time.Duration, err error) {
165         arv := arvadosclient.ArvadosClient{
166                 ApiToken:    config.APIToken,
167                 ApiServer:   config.APIHost,
168                 ApiInsecure: config.APIHostInsecure,
169                 Client: &http.Client{Transport: &http.Transport{
170                         TLSClientConfig: &tls.Config{InsecureSkipVerify: config.APIHostInsecure}}},
171         }
172
173         // If keepServicesJSON is provided, use it instead of service discovery
174         if keepServicesJSON == "" {
175                 kc, err = keepclient.MakeKeepClient(&arv)
176                 if err != nil {
177                         return
178                 }
179         } else {
180                 kc = keepclient.New(&arv)
181                 err = kc.LoadKeepServicesFromJSON(keepServicesJSON)
182                 if err != nil {
183                         return
184                 }
185         }
186
187         // Get if blobSignatureTTL is not provided
188         ttl = blobSignatureTTL
189         if blobSignatureTTL == 0 {
190                 value, err := arv.Discovery("blobSignatureTtl")
191                 if err == nil {
192                         ttl = time.Duration(int(value.(float64))) * time.Second
193                 } else {
194                         return nil, 0, err
195                 }
196         }
197
198         return
199 }
200
201 // Get list of unique block locators from the given file
202 func getBlockLocators(locatorFile, prefix string) (locators []string, err error) {
203         if locatorFile == "" {
204                 err = errors.New("block-hash-file not specified")
205                 return
206         }
207
208         content, err := ioutil.ReadFile(locatorFile)
209         if err != nil {
210                 return
211         }
212
213         locatorMap := make(map[string]bool)
214         for _, line := range strings.Split(string(content), "\n") {
215                 line = strings.TrimSpace(line)
216                 if line == "" || !strings.HasPrefix(line, prefix) || locatorMap[line] {
217                         continue
218                 }
219                 locators = append(locators, line)
220                 locatorMap[line] = true
221         }
222
223         return
224 }
225
226 // Get block headers from keep. Log any errors.
227 func performKeepBlockCheck(kc *keepclient.KeepClient, blobSignatureTTL time.Duration, blobSigningKey string, blockLocators []string, verbose bool) error {
228         totalBlocks := len(blockLocators)
229         notFoundBlocks := 0
230         current := 0
231         for _, locator := range blockLocators {
232                 current++
233                 if verbose {
234                         log.Printf("Verifying block %d of %d: %v", current, totalBlocks, locator)
235                 }
236                 getLocator := locator
237                 if blobSigningKey != "" {
238                         expiresAt := time.Now().AddDate(0, 0, 1)
239                         getLocator = keepclient.SignLocator(locator, kc.Arvados.ApiToken, expiresAt, blobSignatureTTL, []byte(blobSigningKey))
240                 }
241
242                 _, _, err := kc.Ask(getLocator)
243                 if err != nil {
244                         notFoundBlocks++
245                         log.Printf("Error verifying block %v: %v", locator, err)
246                 }
247         }
248
249         log.Printf("Verify block totals: %d attempts, %d successes, %d errors", totalBlocks, totalBlocks-notFoundBlocks, notFoundBlocks)
250
251         if notFoundBlocks > 0 {
252                 return fmt.Errorf("Block verification failed for %d out of %d blocks with matching prefix", notFoundBlocks, totalBlocks)
253         }
254
255         return nil
256 }