9 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
10 "git.curoverse.com/arvados.git/sdk/go/keepclient"
21 var srcConfigFile, dstConfigFile, srcKeepServicesJSON, dstKeepServicesJSON, prefix string
23 var srcBlobSigningKey string
29 "Source configuration filename. May be either a pathname to a config file, or (for example) 'foo' as shorthand for $HOME/.config/arvados/foo.conf")
35 "Destination configuration filename. May be either a pathname to a config file, or (for example) 'foo' as shorthand for $HOME/.config/arvados/foo.conf")
39 "src-keep-services-json",
41 "An optional list of available source keepservices. "+
42 "If not provided, this list is obtained from api server configured in src-config-file.")
46 "dst-keep-services-json",
48 "An optional list of available destination keepservices. "+
49 "If not provided, this list is obtained from api server configured in dst-config-file.")
55 "Number of replications to write to the destination. If replications not specified, "+
56 "default replication level configured on destination server will be used.")
66 srcConfig, srcBlobSigningKey, err := loadConfig(srcConfigFile)
68 log.Fatalf("Error loading src configuration from file: %s", err.Error())
71 dstConfig, _, err := loadConfig(dstConfigFile)
73 log.Fatalf("Error loading dst configuration from file: %s", err.Error())
76 // setup src and dst keepclients
77 kcSrc, err := setupKeepClient(srcConfig, srcKeepServicesJSON, false, 0)
79 log.Fatalf("Error configuring src keepclient: %s", err.Error())
82 kcDst, err := setupKeepClient(dstConfig, dstKeepServicesJSON, true, replications)
84 log.Fatalf("Error configuring dst keepclient: %s", err.Error())
87 // Copy blocks not found in dst from src
88 err = performKeepRsync(kcSrc, kcDst, srcBlobSigningKey, prefix)
90 log.Fatalf("Error while syncing data: %s", err.Error())
94 type apiConfig struct {
101 // Load src and dst config from given files
102 func loadConfig(configFile string) (config apiConfig, blobSigningKey string, err error) {
103 if configFile == "" {
104 return config, blobSigningKey, errors.New("config file not specified")
107 config, blobSigningKey, err = readConfigFromFile(configFile)
109 return config, blobSigningKey, fmt.Errorf("Error reading config file: %v", err)
115 var matchTrue = regexp.MustCompile("^(?i:1|yes|true)$")
117 // Read config from file
118 func readConfigFromFile(filename string) (config apiConfig, blobSigningKey string, err error) {
119 if !strings.Contains(filename, "/") {
120 filename = os.Getenv("HOME") + "/.config/arvados/" + filename + ".conf"
123 content, err := ioutil.ReadFile(filename)
126 return config, "", err
129 lines := strings.Split(string(content), "\n")
130 for _, line := range lines {
135 kv := strings.SplitN(line, "=", 2)
136 key := strings.TrimSpace(kv[0])
137 value := strings.TrimSpace(kv[1])
140 case "ARVADOS_API_TOKEN":
141 config.APIToken = value
142 case "ARVADOS_API_HOST":
143 config.APIHost = value
144 case "ARVADOS_API_HOST_INSECURE":
145 config.APIHostInsecure = matchTrue.MatchString(value)
146 case "ARVADOS_EXTERNAL_CLIENT":
147 config.ExternalClient = matchTrue.MatchString(value)
148 case "ARVADOS_BLOB_SIGNING_KEY":
149 blobSigningKey = value
155 // setup keepclient using the config provided
156 func setupKeepClient(config apiConfig, keepServicesJSON string, isDst bool, replications int) (kc *keepclient.KeepClient, err error) {
157 arv := arvadosclient.ArvadosClient{
158 ApiToken: config.APIToken,
159 ApiServer: config.APIHost,
160 ApiInsecure: config.APIHostInsecure,
161 Client: &http.Client{Transport: &http.Transport{
162 TLSClientConfig: &tls.Config{InsecureSkipVerify: config.APIHostInsecure}}},
163 External: config.ExternalClient,
166 // if keepServicesJSON is provided, use it to load services; else, use DiscoverKeepServers
167 if keepServicesJSON == "" {
168 kc, err = keepclient.MakeKeepClient(&arv)
173 kc = keepclient.New(&arv)
174 err = kc.LoadKeepServicesFromJSON(keepServicesJSON)
181 // Get default replications value from destination, if it is not already provided
182 if replications == 0 {
183 value, err := arv.Discovery("defaultCollectionReplication")
185 replications = int(value.(float64))
191 kc.Want_replicas = replications
197 // Get unique block locators from src and dst
198 // Copy any blocks missing in dst
199 func performKeepRsync(kcSrc, kcDst *keepclient.KeepClient, blobSigningKey, prefix string) error {
200 // Get unique locators from src
201 srcIndex, err := getUniqueLocators(kcSrc, prefix)
206 // Get unique locators from dst
207 dstIndex, err := getUniqueLocators(kcDst, prefix)
212 // Get list of locators found in src, but missing in dst
213 toBeCopied := getMissingLocators(srcIndex, dstIndex)
215 // Copy each missing block to dst
216 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.",
217 len(srcIndex), len(dstIndex), len(toBeCopied))
219 err = copyBlocksToDst(toBeCopied, kcSrc, kcDst, blobSigningKey)
224 // Get list of unique locators from the specified cluster
225 func getUniqueLocators(kc *keepclient.KeepClient, prefix string) (map[string]bool, error) {
226 uniqueLocators := map[string]bool{}
228 // Get index and dedup
229 for uuid := range kc.LocalRoots() {
230 reader, err := kc.GetIndex(uuid, prefix)
232 return uniqueLocators, err
234 scanner := bufio.NewScanner(reader)
236 uniqueLocators[strings.Split(scanner.Text(), " ")[0]] = true
240 return uniqueLocators, nil
243 // Get list of locators that are in src but not in dst
244 func getMissingLocators(srcLocators, dstLocators map[string]bool) []string {
245 var missingLocators []string
246 for locator := range srcLocators {
247 if _, ok := dstLocators[locator]; !ok {
248 missingLocators = append(missingLocators, locator)
251 return missingLocators
254 // Copy blocks from src to dst; only those that are missing in dst are copied
255 func copyBlocksToDst(toBeCopied []string, kcSrc, kcDst *keepclient.KeepClient, blobSigningKey string) error {
256 total := len(toBeCopied)
258 startedAt := time.Now()
259 for done, locator := range toBeCopied {
261 log.Printf("Copying data block %d of %d (%.2f%% done): %v", done+1, total,
262 float64(done)/float64(total)*100, locator)
264 timePerBlock := time.Since(startedAt) / time.Duration(done)
265 log.Printf("Copying data block %d of %d (%.2f%% done, ETA %v): %v", done+1, total,
266 float64(done)/float64(total)*100, timePerBlock*time.Duration(total-done), locator)
269 getLocator := locator
270 expiresAt := time.Now().AddDate(0, 0, 1)
271 if blobSigningKey != "" {
272 getLocator = keepclient.SignLocator(getLocator, kcSrc.Arvados.ApiToken, expiresAt, []byte(blobSigningKey))
275 reader, len, _, err := kcSrc.Get(getLocator)
277 return fmt.Errorf("Error getting block: %v %v", locator, err)
280 _, _, err = kcDst.PutHR(getLocator[:32], reader, len)
282 return fmt.Errorf("Error copying data block: %v %v", locator, err)
286 log.Printf("Successfully copied to destination %d blocks.", total)