1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
20 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
21 "git.curoverse.com/arvados.git/sdk/go/keepclient"
32 flags := flag.NewFlagSet("keep-rsync", flag.ExitOnError)
34 srcConfigFile := flags.String(
37 "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.")
39 dstConfigFile := flags.String(
42 "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.")
44 srcKeepServicesJSON := flags.String(
45 "src-keep-services-json",
47 "An optional list of available source keepservices. "+
48 "If not provided, this list is obtained from api server configured in src-config-file.")
50 dstKeepServicesJSON := flags.String(
51 "dst-keep-services-json",
53 "An optional list of available destination keepservices. "+
54 "If not provided, this list is obtained from api server configured in dst-config-file.")
56 replications := flags.Int(
59 "Number of replications to write to the destination. If replications not specified, "+
60 "default replication level configured on destination server will be used.")
62 prefix := flags.String(
67 srcBlobSignatureTTLFlag := flags.Duration(
68 "src-blob-signature-ttl",
70 "Lifetime of blob permission signatures on source keepservers. If not provided, this will be retrieved from the API server's discovery document.")
72 // Parse args; omit the first arg which is the command name
73 flags.Parse(os.Args[1:])
75 srcConfig, srcBlobSigningKey, err := loadConfig(*srcConfigFile)
77 return fmt.Errorf("Error loading src configuration from file: %s", err.Error())
80 dstConfig, _, err := loadConfig(*dstConfigFile)
82 return fmt.Errorf("Error loading dst configuration from file: %s", err.Error())
85 // setup src and dst keepclients
86 kcSrc, srcBlobSignatureTTL, err := setupKeepClient(srcConfig, *srcKeepServicesJSON, false, 0, *srcBlobSignatureTTLFlag)
88 return fmt.Errorf("Error configuring src keepclient: %s", err.Error())
91 kcDst, _, err := setupKeepClient(dstConfig, *dstKeepServicesJSON, true, *replications, 0)
93 return fmt.Errorf("Error configuring dst keepclient: %s", err.Error())
96 // Copy blocks not found in dst from src
97 err = performKeepRsync(kcSrc, kcDst, srcBlobSignatureTTL, srcBlobSigningKey, *prefix)
99 return fmt.Errorf("Error while syncing data: %s", err.Error())
105 type apiConfig struct {
112 // Load src and dst config from given files
113 func loadConfig(configFile string) (config apiConfig, blobSigningKey string, err error) {
114 if configFile == "" {
115 return config, blobSigningKey, errors.New("config file not specified")
118 config, blobSigningKey, err = readConfigFromFile(configFile)
120 return config, blobSigningKey, fmt.Errorf("Error reading config file: %v", err)
126 // Read config from file
127 func readConfigFromFile(filename string) (config apiConfig, blobSigningKey string, err error) {
128 if !strings.Contains(filename, "/") {
129 filename = os.Getenv("HOME") + "/.config/arvados/" + filename + ".conf"
132 content, err := ioutil.ReadFile(filename)
135 return config, "", err
138 lines := strings.Split(string(content), "\n")
139 for _, line := range lines {
144 kv := strings.SplitN(line, "=", 2)
145 key := strings.TrimSpace(kv[0])
146 value := strings.TrimSpace(kv[1])
149 case "ARVADOS_API_TOKEN":
150 config.APIToken = value
151 case "ARVADOS_API_HOST":
152 config.APIHost = value
153 case "ARVADOS_API_HOST_INSECURE":
154 config.APIHostInsecure = arvadosclient.StringBool(value)
155 case "ARVADOS_EXTERNAL_CLIENT":
156 config.ExternalClient = arvadosclient.StringBool(value)
157 case "ARVADOS_BLOB_SIGNING_KEY":
158 blobSigningKey = value
164 // setup keepclient using the config provided
165 func setupKeepClient(config apiConfig, keepServicesJSON string, isDst bool, replications int, srcBlobSignatureTTL time.Duration) (kc *keepclient.KeepClient, blobSignatureTTL time.Duration, err error) {
166 arv := arvadosclient.ArvadosClient{
167 ApiToken: config.APIToken,
168 ApiServer: config.APIHost,
169 ApiInsecure: config.APIHostInsecure,
170 Client: &http.Client{Transport: &http.Transport{
171 TLSClientConfig: &tls.Config{InsecureSkipVerify: config.APIHostInsecure}}},
172 External: config.ExternalClient,
175 // If keepServicesJSON is provided, use it instead of service discovery
176 if keepServicesJSON == "" {
177 kc, err = keepclient.MakeKeepClient(&arv)
182 kc = keepclient.New(&arv)
183 err = kc.LoadKeepServicesFromJSON(keepServicesJSON)
190 // Get default replications value from destination, if it is not already provided
191 if replications == 0 {
192 value, err := arv.Discovery("defaultCollectionReplication")
194 replications = int(value.(float64))
200 kc.Want_replicas = replications
203 // If srcBlobSignatureTTL is not provided, get it from API server discovery doc
204 blobSignatureTTL = srcBlobSignatureTTL
205 if !isDst && srcBlobSignatureTTL == 0 {
206 value, err := arv.Discovery("blobSignatureTtl")
208 blobSignatureTTL = time.Duration(int(value.(float64))) * time.Second
214 return kc, blobSignatureTTL, nil
217 // Get unique block locators from src and dst
218 // Copy any blocks missing in dst
219 func performKeepRsync(kcSrc, kcDst *keepclient.KeepClient, srcBlobSignatureTTL time.Duration, blobSigningKey, prefix string) error {
220 // Get unique locators from src
221 srcIndex, err := getUniqueLocators(kcSrc, prefix)
226 // Get unique locators from dst
227 dstIndex, err := getUniqueLocators(kcDst, prefix)
232 // Get list of locators found in src, but missing in dst
233 toBeCopied := getMissingLocators(srcIndex, dstIndex)
235 // Copy each missing block to dst
236 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.",
237 len(srcIndex), len(dstIndex), len(toBeCopied))
239 err = copyBlocksToDst(toBeCopied, kcSrc, kcDst, srcBlobSignatureTTL, blobSigningKey)
244 // Get list of unique locators from the specified cluster
245 func getUniqueLocators(kc *keepclient.KeepClient, prefix string) (map[string]bool, error) {
246 uniqueLocators := map[string]bool{}
248 // Get index and dedup
249 for uuid := range kc.LocalRoots() {
250 reader, err := kc.GetIndex(uuid, prefix)
252 return uniqueLocators, err
254 scanner := bufio.NewScanner(reader)
256 uniqueLocators[strings.Split(scanner.Text(), " ")[0]] = true
260 return uniqueLocators, nil
263 // Get list of locators that are in src but not in dst
264 func getMissingLocators(srcLocators, dstLocators map[string]bool) []string {
265 var missingLocators []string
266 for locator := range srcLocators {
267 if _, ok := dstLocators[locator]; !ok {
268 missingLocators = append(missingLocators, locator)
271 return missingLocators
274 // Copy blocks from src to dst; only those that are missing in dst are copied
275 func copyBlocksToDst(toBeCopied []string, kcSrc, kcDst *keepclient.KeepClient, srcBlobSignatureTTL time.Duration, blobSigningKey string) error {
276 total := len(toBeCopied)
278 startedAt := time.Now()
279 for done, locator := range toBeCopied {
281 log.Printf("Copying data block %d of %d (%.2f%% done): %v", done+1, total,
282 float64(done)/float64(total)*100, locator)
284 timePerBlock := time.Since(startedAt) / time.Duration(done)
285 log.Printf("Copying data block %d of %d (%.2f%% done, %v est. time remaining): %v", done+1, total,
286 float64(done)/float64(total)*100, timePerBlock*time.Duration(total-done), locator)
289 getLocator := locator
290 expiresAt := time.Now().AddDate(0, 0, 1)
291 if blobSigningKey != "" {
292 getLocator = keepclient.SignLocator(getLocator, kcSrc.Arvados.ApiToken, expiresAt, srcBlobSignatureTTL, []byte(blobSigningKey))
295 reader, len, _, err := kcSrc.Get(getLocator)
297 return fmt.Errorf("Error getting block: %v %v", locator, err)
300 _, _, err = kcDst.PutHR(getLocator[:32], reader, len)
302 return fmt.Errorf("Error copying data block: %v %v", locator, err)
306 log.Printf("Successfully copied to destination %d blocks.", total)