11557: Merge branch 'master' into 11557-acr-output-col-perms
[arvados.git] / tools / keep-rsync / keep-rsync.go
1 package main
2
3 import (
4         "bufio"
5         "crypto/tls"
6         "errors"
7         "flag"
8         "fmt"
9         "io/ioutil"
10         "log"
11         "net/http"
12         "os"
13         "strings"
14         "time"
15
16         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
17         "git.curoverse.com/arvados.git/sdk/go/keepclient"
18 )
19
20 func main() {
21         err := doMain()
22         if err != nil {
23                 log.Fatalf("%v", err)
24         }
25 }
26
27 func doMain() error {
28         flags := flag.NewFlagSet("keep-rsync", flag.ExitOnError)
29
30         srcConfigFile := flags.String(
31                 "src",
32                 "",
33                 "Source 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.")
34
35         dstConfigFile := flags.String(
36                 "dst",
37                 "",
38                 "Destination 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, and ARVADOS_API_HOST_INSECURE for the destination.")
39
40         srcKeepServicesJSON := flags.String(
41                 "src-keep-services-json",
42                 "",
43                 "An optional list of available source keepservices. "+
44                         "If not provided, this list is obtained from api server configured in src-config-file.")
45
46         dstKeepServicesJSON := flags.String(
47                 "dst-keep-services-json",
48                 "",
49                 "An optional list of available destination keepservices. "+
50                         "If not provided, this list is obtained from api server configured in dst-config-file.")
51
52         replications := flags.Int(
53                 "replications",
54                 0,
55                 "Number of replications to write to the destination. If replications not specified, "+
56                         "default replication level configured on destination server will be used.")
57
58         prefix := flags.String(
59                 "prefix",
60                 "",
61                 "Index prefix")
62
63         srcBlobSignatureTTLFlag := flags.Duration(
64                 "src-blob-signature-ttl",
65                 0,
66                 "Lifetime of blob permission signatures on source keepservers. If not provided, this will be retrieved from the API server's discovery document.")
67
68         // Parse args; omit the first arg which is the command name
69         flags.Parse(os.Args[1:])
70
71         srcConfig, srcBlobSigningKey, err := loadConfig(*srcConfigFile)
72         if err != nil {
73                 return fmt.Errorf("Error loading src configuration from file: %s", err.Error())
74         }
75
76         dstConfig, _, err := loadConfig(*dstConfigFile)
77         if err != nil {
78                 return fmt.Errorf("Error loading dst configuration from file: %s", err.Error())
79         }
80
81         // setup src and dst keepclients
82         kcSrc, srcBlobSignatureTTL, err := setupKeepClient(srcConfig, *srcKeepServicesJSON, false, 0, *srcBlobSignatureTTLFlag)
83         if err != nil {
84                 return fmt.Errorf("Error configuring src keepclient: %s", err.Error())
85         }
86
87         kcDst, _, err := setupKeepClient(dstConfig, *dstKeepServicesJSON, true, *replications, 0)
88         if err != nil {
89                 return fmt.Errorf("Error configuring dst keepclient: %s", err.Error())
90         }
91
92         // Copy blocks not found in dst from src
93         err = performKeepRsync(kcSrc, kcDst, srcBlobSignatureTTL, srcBlobSigningKey, *prefix)
94         if err != nil {
95                 return fmt.Errorf("Error while syncing data: %s", err.Error())
96         }
97
98         return nil
99 }
100
101 type apiConfig struct {
102         APIToken        string
103         APIHost         string
104         APIHostInsecure bool
105         ExternalClient  bool
106 }
107
108 // Load src and dst config from given files
109 func loadConfig(configFile string) (config apiConfig, blobSigningKey string, err error) {
110         if configFile == "" {
111                 return config, blobSigningKey, errors.New("config file not specified")
112         }
113
114         config, blobSigningKey, err = readConfigFromFile(configFile)
115         if err != nil {
116                 return config, blobSigningKey, fmt.Errorf("Error reading config file: %v", err)
117         }
118
119         return
120 }
121
122 // Read config from file
123 func readConfigFromFile(filename string) (config apiConfig, blobSigningKey string, err error) {
124         if !strings.Contains(filename, "/") {
125                 filename = os.Getenv("HOME") + "/.config/arvados/" + filename + ".conf"
126         }
127
128         content, err := ioutil.ReadFile(filename)
129
130         if err != nil {
131                 return config, "", err
132         }
133
134         lines := strings.Split(string(content), "\n")
135         for _, line := range lines {
136                 if line == "" {
137                         continue
138                 }
139
140                 kv := strings.SplitN(line, "=", 2)
141                 key := strings.TrimSpace(kv[0])
142                 value := strings.TrimSpace(kv[1])
143
144                 switch key {
145                 case "ARVADOS_API_TOKEN":
146                         config.APIToken = value
147                 case "ARVADOS_API_HOST":
148                         config.APIHost = value
149                 case "ARVADOS_API_HOST_INSECURE":
150                         config.APIHostInsecure = arvadosclient.StringBool(value)
151                 case "ARVADOS_EXTERNAL_CLIENT":
152                         config.ExternalClient = arvadosclient.StringBool(value)
153                 case "ARVADOS_BLOB_SIGNING_KEY":
154                         blobSigningKey = value
155                 }
156         }
157         return
158 }
159
160 // setup keepclient using the config provided
161 func setupKeepClient(config apiConfig, keepServicesJSON string, isDst bool, replications int, srcBlobSignatureTTL time.Duration) (kc *keepclient.KeepClient, blobSignatureTTL time.Duration, err error) {
162         arv := arvadosclient.ArvadosClient{
163                 ApiToken:    config.APIToken,
164                 ApiServer:   config.APIHost,
165                 ApiInsecure: config.APIHostInsecure,
166                 Client: &http.Client{Transport: &http.Transport{
167                         TLSClientConfig: &tls.Config{InsecureSkipVerify: config.APIHostInsecure}}},
168                 External: config.ExternalClient,
169         }
170
171         // If keepServicesJSON is provided, use it instead of service discovery
172         if keepServicesJSON == "" {
173                 kc, err = keepclient.MakeKeepClient(&arv)
174                 if err != nil {
175                         return nil, 0, err
176                 }
177         } else {
178                 kc = keepclient.New(&arv)
179                 err = kc.LoadKeepServicesFromJSON(keepServicesJSON)
180                 if err != nil {
181                         return kc, 0, err
182                 }
183         }
184
185         if isDst {
186                 // Get default replications value from destination, if it is not already provided
187                 if replications == 0 {
188                         value, err := arv.Discovery("defaultCollectionReplication")
189                         if err == nil {
190                                 replications = int(value.(float64))
191                         } else {
192                                 return nil, 0, err
193                         }
194                 }
195
196                 kc.Want_replicas = replications
197         }
198
199         // If srcBlobSignatureTTL is not provided, get it from API server discovery doc
200         blobSignatureTTL = srcBlobSignatureTTL
201         if !isDst && srcBlobSignatureTTL == 0 {
202                 value, err := arv.Discovery("blobSignatureTtl")
203                 if err == nil {
204                         blobSignatureTTL = time.Duration(int(value.(float64))) * time.Second
205                 } else {
206                         return nil, 0, err
207                 }
208         }
209
210         return kc, blobSignatureTTL, nil
211 }
212
213 // Get unique block locators from src and dst
214 // Copy any blocks missing in dst
215 func performKeepRsync(kcSrc, kcDst *keepclient.KeepClient, srcBlobSignatureTTL time.Duration, blobSigningKey, prefix string) error {
216         // Get unique locators from src
217         srcIndex, err := getUniqueLocators(kcSrc, prefix)
218         if err != nil {
219                 return err
220         }
221
222         // Get unique locators from dst
223         dstIndex, err := getUniqueLocators(kcDst, prefix)
224         if err != nil {
225                 return err
226         }
227
228         // Get list of locators found in src, but missing in dst
229         toBeCopied := getMissingLocators(srcIndex, dstIndex)
230
231         // Copy each missing block to dst
232         log.Printf("Before keep-rsync, there are %d blocks in src and %d blocks in dst. Start copying %d blocks from src not found in dst.",
233                 len(srcIndex), len(dstIndex), len(toBeCopied))
234
235         err = copyBlocksToDst(toBeCopied, kcSrc, kcDst, srcBlobSignatureTTL, blobSigningKey)
236
237         return err
238 }
239
240 // Get list of unique locators from the specified cluster
241 func getUniqueLocators(kc *keepclient.KeepClient, prefix string) (map[string]bool, error) {
242         uniqueLocators := map[string]bool{}
243
244         // Get index and dedup
245         for uuid := range kc.LocalRoots() {
246                 reader, err := kc.GetIndex(uuid, prefix)
247                 if err != nil {
248                         return uniqueLocators, err
249                 }
250                 scanner := bufio.NewScanner(reader)
251                 for scanner.Scan() {
252                         uniqueLocators[strings.Split(scanner.Text(), " ")[0]] = true
253                 }
254         }
255
256         return uniqueLocators, nil
257 }
258
259 // Get list of locators that are in src but not in dst
260 func getMissingLocators(srcLocators, dstLocators map[string]bool) []string {
261         var missingLocators []string
262         for locator := range srcLocators {
263                 if _, ok := dstLocators[locator]; !ok {
264                         missingLocators = append(missingLocators, locator)
265                 }
266         }
267         return missingLocators
268 }
269
270 // Copy blocks from src to dst; only those that are missing in dst are copied
271 func copyBlocksToDst(toBeCopied []string, kcSrc, kcDst *keepclient.KeepClient, srcBlobSignatureTTL time.Duration, blobSigningKey string) error {
272         total := len(toBeCopied)
273
274         startedAt := time.Now()
275         for done, locator := range toBeCopied {
276                 if done == 0 {
277                         log.Printf("Copying data block %d of %d (%.2f%% done): %v", done+1, total,
278                                 float64(done)/float64(total)*100, locator)
279                 } else {
280                         timePerBlock := time.Since(startedAt) / time.Duration(done)
281                         log.Printf("Copying data block %d of %d (%.2f%% done, %v est. time remaining): %v", done+1, total,
282                                 float64(done)/float64(total)*100, timePerBlock*time.Duration(total-done), locator)
283                 }
284
285                 getLocator := locator
286                 expiresAt := time.Now().AddDate(0, 0, 1)
287                 if blobSigningKey != "" {
288                         getLocator = keepclient.SignLocator(getLocator, kcSrc.Arvados.ApiToken, expiresAt, srcBlobSignatureTTL, []byte(blobSigningKey))
289                 }
290
291                 reader, len, _, err := kcSrc.Get(getLocator)
292                 if err != nil {
293                         return fmt.Errorf("Error getting block: %v %v", locator, err)
294                 }
295
296                 _, _, err = kcDst.PutHR(getLocator[:32], reader, len)
297                 if err != nil {
298                         return fmt.Errorf("Error copying data block: %v %v", locator, err)
299                 }
300         }
301
302         log.Printf("Successfully copied to destination %d blocks.", total)
303         return nil
304 }