Merge branch 'master' into 5538-arvadosclient-retry
[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         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
10         "git.curoverse.com/arvados.git/sdk/go/keepclient"
11         "io/ioutil"
12         "log"
13         "net/http"
14         "os"
15         "regexp"
16         "strings"
17         "time"
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         // Parse args; omit the first arg which is the command name
64         flags.Parse(os.Args[1:])
65
66         srcConfig, srcBlobSigningKey, err := loadConfig(*srcConfigFile)
67         if err != nil {
68                 return fmt.Errorf("Error loading src configuration from file: %s", err.Error())
69         }
70
71         dstConfig, _, err := loadConfig(*dstConfigFile)
72         if err != nil {
73                 return fmt.Errorf("Error loading dst configuration from file: %s", err.Error())
74         }
75
76         // setup src and dst keepclients
77         kcSrc, err := setupKeepClient(srcConfig, *srcKeepServicesJSON, false, 0)
78         if err != nil {
79                 return fmt.Errorf("Error configuring src keepclient: %s", err.Error())
80         }
81
82         kcDst, err := setupKeepClient(dstConfig, *dstKeepServicesJSON, true, *replications)
83         if err != nil {
84                 return fmt.Errorf("Error configuring dst keepclient: %s", err.Error())
85         }
86
87         // Copy blocks not found in dst from src
88         err = performKeepRsync(kcSrc, kcDst, srcBlobSigningKey, *prefix)
89         if err != nil {
90                 return fmt.Errorf("Error while syncing data: %s", err.Error())
91         }
92
93         return nil
94 }
95
96 type apiConfig struct {
97         APIToken        string
98         APIHost         string
99         APIHostInsecure bool
100         ExternalClient  bool
101 }
102
103 // Load src and dst config from given files
104 func loadConfig(configFile string) (config apiConfig, blobSigningKey string, err error) {
105         if configFile == "" {
106                 return config, blobSigningKey, errors.New("config file not specified")
107         }
108
109         config, blobSigningKey, err = readConfigFromFile(configFile)
110         if err != nil {
111                 return config, blobSigningKey, fmt.Errorf("Error reading config file: %v", err)
112         }
113
114         return
115 }
116
117 var matchTrue = regexp.MustCompile("^(?i:1|yes|true)$")
118
119 // Read config from file
120 func readConfigFromFile(filename string) (config apiConfig, blobSigningKey string, err error) {
121         if !strings.Contains(filename, "/") {
122                 filename = os.Getenv("HOME") + "/.config/arvados/" + filename + ".conf"
123         }
124
125         content, err := ioutil.ReadFile(filename)
126
127         if err != nil {
128                 return config, "", err
129         }
130
131         lines := strings.Split(string(content), "\n")
132         for _, line := range lines {
133                 if line == "" {
134                         continue
135                 }
136
137                 kv := strings.SplitN(line, "=", 2)
138                 key := strings.TrimSpace(kv[0])
139                 value := strings.TrimSpace(kv[1])
140
141                 switch key {
142                 case "ARVADOS_API_TOKEN":
143                         config.APIToken = value
144                 case "ARVADOS_API_HOST":
145                         config.APIHost = value
146                 case "ARVADOS_API_HOST_INSECURE":
147                         config.APIHostInsecure = matchTrue.MatchString(value)
148                 case "ARVADOS_EXTERNAL_CLIENT":
149                         config.ExternalClient = matchTrue.MatchString(value)
150                 case "ARVADOS_BLOB_SIGNING_KEY":
151                         blobSigningKey = value
152                 }
153         }
154         return
155 }
156
157 // setup keepclient using the config provided
158 func setupKeepClient(config apiConfig, keepServicesJSON string, isDst bool, replications int) (kc *keepclient.KeepClient, err error) {
159         arv := arvadosclient.ArvadosClient{
160                 ApiToken:    config.APIToken,
161                 ApiServer:   config.APIHost,
162                 ApiInsecure: config.APIHostInsecure,
163                 Client: &http.Client{Transport: &http.Transport{
164                         TLSClientConfig: &tls.Config{InsecureSkipVerify: config.APIHostInsecure}}},
165                 External: config.ExternalClient,
166         }
167
168         // if keepServicesJSON is provided, use it to load services; else, use DiscoverKeepServers
169         if keepServicesJSON == "" {
170                 kc, err = keepclient.MakeKeepClient(&arv)
171                 if err != nil {
172                         return nil, err
173                 }
174         } else {
175                 kc = keepclient.New(&arv)
176                 err = kc.LoadKeepServicesFromJSON(keepServicesJSON)
177                 if err != nil {
178                         return kc, err
179                 }
180         }
181
182         if isDst {
183                 // Get default replications value from destination, if it is not already provided
184                 if replications == 0 {
185                         value, err := arv.Discovery("defaultCollectionReplication")
186                         if err == nil {
187                                 replications = int(value.(float64))
188                         } else {
189                                 return nil, err
190                         }
191                 }
192
193                 kc.Want_replicas = replications
194         }
195
196         return kc, nil
197 }
198
199 // Get unique block locators from src and dst
200 // Copy any blocks missing in dst
201 func performKeepRsync(kcSrc, kcDst *keepclient.KeepClient, blobSigningKey, prefix string) error {
202         // Get unique locators from src
203         srcIndex, err := getUniqueLocators(kcSrc, prefix)
204         if err != nil {
205                 return err
206         }
207
208         // Get unique locators from dst
209         dstIndex, err := getUniqueLocators(kcDst, prefix)
210         if err != nil {
211                 return err
212         }
213
214         // Get list of locators found in src, but missing in dst
215         toBeCopied := getMissingLocators(srcIndex, dstIndex)
216
217         // Copy each missing block to dst
218         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.",
219                 len(srcIndex), len(dstIndex), len(toBeCopied))
220
221         err = copyBlocksToDst(toBeCopied, kcSrc, kcDst, blobSigningKey)
222
223         return err
224 }
225
226 // Get list of unique locators from the specified cluster
227 func getUniqueLocators(kc *keepclient.KeepClient, prefix string) (map[string]bool, error) {
228         uniqueLocators := map[string]bool{}
229
230         // Get index and dedup
231         for uuid := range kc.LocalRoots() {
232                 reader, err := kc.GetIndex(uuid, prefix)
233                 if err != nil {
234                         return uniqueLocators, err
235                 }
236                 scanner := bufio.NewScanner(reader)
237                 for scanner.Scan() {
238                         uniqueLocators[strings.Split(scanner.Text(), " ")[0]] = true
239                 }
240         }
241
242         return uniqueLocators, nil
243 }
244
245 // Get list of locators that are in src but not in dst
246 func getMissingLocators(srcLocators, dstLocators map[string]bool) []string {
247         var missingLocators []string
248         for locator := range srcLocators {
249                 if _, ok := dstLocators[locator]; !ok {
250                         missingLocators = append(missingLocators, locator)
251                 }
252         }
253         return missingLocators
254 }
255
256 // Copy blocks from src to dst; only those that are missing in dst are copied
257 func copyBlocksToDst(toBeCopied []string, kcSrc, kcDst *keepclient.KeepClient, blobSigningKey string) error {
258         total := len(toBeCopied)
259
260         startedAt := time.Now()
261         for done, locator := range toBeCopied {
262                 if done == 0 {
263                         log.Printf("Copying data block %d of %d (%.2f%% done): %v", done+1, total,
264                                 float64(done)/float64(total)*100, locator)
265                 } else {
266                         timePerBlock := time.Since(startedAt) / time.Duration(done)
267                         log.Printf("Copying data block %d of %d (%.2f%% done, %v est. time remaining): %v", done+1, total,
268                                 float64(done)/float64(total)*100, timePerBlock*time.Duration(total-done), locator)
269                 }
270
271                 getLocator := locator
272                 expiresAt := time.Now().AddDate(0, 0, 1)
273                 if blobSigningKey != "" {
274                         getLocator = keepclient.SignLocator(getLocator, kcSrc.Arvados.ApiToken, expiresAt, []byte(blobSigningKey))
275                 }
276
277                 reader, len, _, err := kcSrc.Get(getLocator)
278                 if err != nil {
279                         return fmt.Errorf("Error getting block: %v %v", locator, err)
280                 }
281
282                 _, _, err = kcDst.PutHR(getLocator[:32], reader, len)
283                 if err != nil {
284                         return fmt.Errorf("Error copying data block: %v %v", locator, err)
285                 }
286         }
287
288         log.Printf("Successfully copied to destination %d blocks.", total)
289         return nil
290 }