3 # - script to sync a group of files on alien with a local cache
4 # downloads only new and updated files
5 # - by default it mirrors the directory structure in a specified local location
6 # (the local chache location and paths can be manipulated.)
7 # - needs a configured config file (by default alienSync.config)
8 # and a working alien environment (token and at least $ALIEN_DIR or $ALIEN_ROOT set)
10 # origin: Mikolaj Krzewicki, mikolaj.krzewicki@cern.ch
14 if [[ $# -lt 1 ]]; then
15 echo "Usage: ${0##*/} configFile=/path/to/config"
16 echo "expert: ${0##*/} alienFindCommand=\"alien_find /some/path/ file\" [opt=value]"
17 echo " ${0##*/} alienFindCommand=\"alien_find /some/path/ file\" localPathPrefix=\${PWD}"
19 echo "by default files are downloaded to current dir, or \${alienSync_localPathPrefix} if set."
20 echo "At least specify alienFindCommand, either on command line or in the configFile."
24 # try to load the config file
25 #[[ ! -f $1 ]] && echo "config file $1 not found, exiting..." | tee -a $logFile && exit 1
26 if ! parseConfig "$@"; then return 1; fi
28 [[ -z ${alienFindCommand} ]] && echo "alienFindCommand not defined!" && return 1
30 #if not set, use the default group
31 [[ -z ${alienSyncFilesGroupOwnership} ]] && alienSyncFilesGroupOwnership=$(id -gn)
34 [[ ! -d $logOutputPath ]] && echo "logOutputPath not available, creating..." && sg ${alienSyncFilesGroupOwnership} "mkdir -p $logOutputPath"
35 [[ ! -d $logOutputPath ]] && echo "could not create log dir, exiting..." && exit 1
36 dateString=$(date +%Y-%m-%d-%H-%M)
37 logFile=$logOutputPath/alienSync-$dateString.log
38 echo "$0 $@"|tee -a $logFile
39 echo ""|tee -a $logFile
42 #be nice and allow group members access as well (002 will create dirs with 775 and files with 664)
46 lockFile=$logOutputPath/runningNow.lock
47 [[ -f $lockFile ]] && echo "locked. Another process running? ($lockFile)" | tee -a $logFile && exit 1
49 [[ ! -f $lockFile ]] && echo "unable to create lock. exiting..." | tee -a $logFile && exit 1
51 #redirect all output to a log
52 if [[ $allOutputToLog -eq 1 ]]; then
57 newFilesList=$logOutputPath/"newFiles.list"
60 redoneFilesList=$logOutputPath/"redoneFiles.list"
61 rm -f $redoneFilesList
62 touch $redoneFilesList
63 updatedFilesList="${logOutputPath}/updatedFiles.list"
66 [[ -z $alienFindCommand ]] && echo "alienFindCommand not defined, exiting..." && exitScript 1
67 [[ -z ${localPathPrefix} ]] && echo "localPathPrefix not defined, exiting..." && exitScript 1
68 [[ -z $logOutputPath ]] && echo "logOutputPath not defined, exiting..." && exitScript 1
69 [[ -z $secondsToSuicide ]] && echo "setting default secondsToSuicide of 10 hrs..." && secondsToSuicide=$(( 10*3600 ))
72 [[ -z $ALIEN_ROOT && -n $ALIEN_DIR ]] && ALIEN_ROOT=$ALIEN_DIR
73 #if ! haveAlienToken; then
74 # $ALIEN_ROOT/api/bin/alien-token-destroy
75 $ALIEN_ROOT/api/bin/alien-token-init $alienUserName
77 #if ! haveAlienToken; then
78 # if [[ $allOutputToLog -eq 1 ]]; then
81 # echo "problems getting token! exiting..." | tee -a $logFile
84 #ls -ltr /tmp/gclient_env_$UID
85 #cat /tmp/gclient_env_$UID
86 source /tmp/gclient_env_$UID
88 #set a default timeout for grid access
89 [[ -z $copyTimeout ]] && copyTimeout=600
90 export GCLIENT_COMMAND_MAXWAIT=$copyTimeout
92 localAlienDatabase=$logOutputPath/localAlienDatabase.list
93 localFileList=$logOutputPath/localFile.list
95 alienFileListCurrent=$logOutputPath/alienFileDatabase.list
96 [[ ! -f $localFileList ]] && touch $localFileList
97 candidateLocalFileDatabase=$logOutputPath/candidateLocalFileDatabase.list
99 #here we produce the current alien file list
100 if [[ -n ${useExistingAlienFileDatabase} && -f ${localAlienDatabase} ]]; then
102 echo "using ${localAlienDatabase} instead of full alien search"
103 echo cp -f ${localAlienDatabase} ${alienFileListCurrent}
104 cp -f ${localAlienDatabase} ${alienFileListCurrent}
107 echo "eval $alienFindCommand > $alienFileListCurrent"
108 eval "$alienFindCommand" > $alienFileListCurrent
111 echo "number of files in the collection: $(wc -l $alienFileListCurrent)"
112 #create a list of candidate destination locations
113 #this is in case there are more files on alien trying to get to the same local destination
114 #in which case we take the one with the youngest ctime (later in code)
115 if [[ -n ${destinationModifyCommand} ]]; then
116 echo eval "cat $alienFileListCurrent | ${destinationModifyCommand} | sed \"s,^,${localPathPrefix},\" > ${candidateLocalFileDatabase}"
117 eval "cat $alienFileListCurrent | ${destinationModifyCommand} | sed \"s,^,${localPathPrefix},\" > ${candidateLocalFileDatabase}"
120 #logic is: if file list is missing we force the md5 recalculation
121 [[ ! -f $localAlienDatabase ]] && forceLocalMD5recalculation=1 && echo "forcing local MD5 sum recalculation" && cp -f $alienFileListCurrent $localAlienDatabase
123 #since we grep through the files frequently, copy some stuff to tmpfs for fast access
124 tmp=$(mktemp -d 2>/dev/null)
125 if [[ -d $tmp ]]; then
126 cp $localAlienDatabase $tmp
127 cp $localFileList $tmp
128 cp $alienFileListCurrent $tmp
129 [[ -f ${candidateLocalFileDatabase} ]] && cp ${candidateLocalFileDatabase} ${tmp}
134 echo "starting downloading:"
138 downloadedFileCounter=0
139 while read -r alienFile md5alien timestamp size
143 #sometimes the md5 turns out empty and is then stored as a "." to avoid problems parsing
144 [[ "$md5alien" =~ "." ]] && md5alien=""
146 [[ -n $timeStampInLog ]] && date
147 [[ $SECONDS -ge $secondsToSuicide ]] && echo "$SECONDS seconds passed, exiting by suicide..." && break
148 [[ "$alienFile" != "/"*"/"?* ]] && echo "WARNING: read line not path-like: $alienFile" && continue
149 ((alienFileCounter++))
150 destination=${localPathPrefix}/${alienFile}
151 destination=${destination//\/\///} #remove double slashes
152 [[ -n ${destinationModifyCommand} ]] && destination=$( eval "echo ${destination} | ${destinationModifyCommand}" )
153 destinationdir=${destination%/*}
154 [[ -n $softLinkName ]] && softlinktodestination=${destinationdir}/${softLinkName}
155 tmpdestination="${destination}.aliensyncTMP"
157 if [[ -n ${destinationModifyCommand} ]]; then
158 #find the candidate in the database, in case there are more files trying to go to the same
159 #place due to $destinationModifyCommand which alters the final path, find the one
160 #with the largest ctime (3rd field in the database list) and check if that is the current one
162 #echo grep -n ${destination} $candidateLocalFileDatabase | sed "s/:/ /" | sort -rk4
163 #grep -n ${destination} $candidateLocalFileDatabase| sed "s/:/ /" | sort -rk4
164 #this guy contains: index of the original entry, local file name, md5, ctime
165 candidateDBrecord=($(grep -n ${destination} $tmp/${candidateLocalFileDatabase##*/}| sed "s/:/ /" | sort -rk4|head -n1 ))
166 originalEntryIndex=${candidateDBrecord[0]}
167 [[ $lineNumber -ne $originalEntryIndex ]] && continue
171 if [[ -f ${destination} ]]; then
172 #soft link the downloaded file (maybe to provide a consistent link to the latest version)
173 if [[ -n $softlinktodestination ]]; then
174 echo ln -sf ${destination} ${softlinktodestination}
175 ln -sf ${destination} ${softlinktodestination}
177 ((localFileCounter++))
179 localDBrecord=($(grep $alienFile $tmp/${localAlienDatabase##*/}))
180 md5local=${localDBrecord[1]}
182 #sometimes the md5 turns out empty and is then stored as a "." to avoid problems parsing
183 [[ "$md5local" =~ "." ]] && md5local=""
185 if [[ $forceLocalMD5recalculation -eq 1 || -z $md5local ]]; then
186 tmparrayMD5=($(md5sum ${destination}))
187 md5recalculated=${tmparrayMD5[0]}
188 [[ "$md5local" != "$md5recalculated" ]] && echo "WARNING: local copy change ${destination}"
189 md5local=${md5recalculated}
191 if [[ "$md5local" == "$md5alien" && -n $md5alien ]]; then
192 echo "OK ${destination} $md5alien"
193 if ! grep -q ${destination} $tmp/${localFileList##*/}; then
194 echo ${destination} >> $localFileList
198 if [[ -z $md5alien ]]; then
199 if ! grep -q ${destination} $tmp/${localFileList##*/}; then
200 echo ${destination} >> $localFileList
202 echo "WARNING: missing alien md5, leaving the local file as it is"
205 echo "WARNING: md5 mismatch ${destination}"
206 echo " $md5local $md5alien"
210 [[ -f $tmpdestination ]] && echo "WARNING: stale $tmpdestination, removing" && rm $tmpdestination
212 sg ${alienSyncFilesGroupOwnership} "mkdir -p ${destinationdir}"
213 [[ ! -d $destinationdir ]] && echo cannot access $destinationdir && continue
216 #if ! haveAlienToken; then
217 # $ALIEN_ROOT/api/bin/alien-token-init $alienUserName
218 # #source /tmp/gclient_env_$UID
224 export copyTimeoutHard
225 echo copyFromAlien "$alienFile" "$tmpdestination"
226 [[ $pretend -eq 1 ]] && continue
227 copyFromAlien $alienFile $tmpdestination
228 chgrp ${alienSyncFilesGroupOwnership} $tmpdestination
230 # if we didn't download remove the destination in case we tried to redownload
232 [[ ! -f $tmpdestination ]] && echo "file not downloaded" && rm -f ${destination} && continue
235 #verify the downloaded md5 if available, validate otherwise...
236 if [[ -n $md5alien ]]; then
237 if (echo "$md5alien $tmpdestination"|md5sum -c --status -); then
238 echo "OK md5 after download"
241 echo "failed verifying md5 $md5alien of $tmpdestination"
247 #handle zip files - check the checksums
248 if [[ $alienFile =~ '.zip' && $downloadOK -eq 1 ]]; then
249 echo "checking integrity of zip archive $tmpdestination"
250 if unzip -t $tmpdestination; then
257 if [[ $downloadOK -eq 1 ]]; then
258 echo mv $tmpdestination ${destination}
259 mv $tmpdestination ${destination}
260 chgrp ${alienSyncFilesGroupOwnership} ${destination}
261 ((downloadedFileCounter++))
262 if [[ -n $softlinktodestination ]]; then
263 echo ln -s ${destination} $softlinktodestination
264 ln -s ${destination} $softlinktodestination
266 [[ -z $redownloading ]] && echo ${destination} >> $newFilesList
267 [[ -n $redownloading ]] && echo ${destination} >> $redoneFilesList
268 if ! grep -q ${destination} $tmp/${localFileList##*/}; then
269 echo ${destination} >> $localFileList
271 [[ -n ${postCommand} ]] && ( cd ${destinationdir}; eval "${postCommand}" )
273 echo "download not validated, NOT moving to ${destination}..."
274 echo "removing $tmpdestination"
275 rm -f $tmpdestination
279 if [[ $unzipFiles -eq 1 ]]; then
280 echo unzip $tmpdestination -d $destinationdir
281 unzip $tmpdestination -d $destinationdir
285 done < ${alienFileListCurrent}
287 [[ $alienFileCounter -gt 0 ]] && mv -f $alienFileListCurrent $localAlienDatabase
291 if [[ $allOutputToLog -eq 1 ]]; then
295 cat ${newFilesList} ${redoneFilesList} > ${updatedFilesList}
298 echo alienFindCommand:
299 echo " $alienFindCommand"
301 echo "files on alien: $alienFileCounter"
302 echo "local files before: $localFileCounter"
303 echo "files downloaded: $downloadedFileCounter"
313 [[ -n $MAILTO ]] && echo $logFile | mail -s "alienSync $alienFindCommand done" $MAILTO
321 echo removing $lockFile
330 # like a regular alien_find command
331 # output is a list with md5sums and ctimes
332 executable="$ALIEN_ROOT/api/bin/gbbox find"
333 [[ ! -x ${executable% *} ]] && echo "### error, no $executable..." && return 1
334 [[ -z $logOutputPath ]] && logOutputPath="./"
336 maxCollectionLength=10000
338 export GCLIENT_COMMAND_MAXWAIT=600
339 export GCLIENT_COMMAND_RETRY=20
340 export GCLIENT_SERVER_RESELECT=4
341 export GCLIENT_SERVER_RECONNECT=2
342 export GCLIENT_RETRY_DAMPING=1.2
343 export GCLIENT_RETRY_SLEEPTIME=2
346 numberOfFiles=$maxCollectionLength
347 rm -f $logOutputPath/alien_find.err
348 while [[ $numberOfFiles -ge $maxCollectionLength && $iterationNumber -lt 100 ]]; do
350 offset=$((maxCollectionLength*iterationNumber-1));
351 [[ $offset -lt 0 ]] && offset=0;
352 $executable -x coll -l ${maxCollectionLength} -o ${offset} "$@" 2>>$logOutputPath/alien_find.err \
353 | while read -a fields;
355 nfields=${#fields[*]}
360 for ((x=1;x<=${nfields};x++)); do
361 field=${fields[${x}]}
362 if [[ "${field}" == "md5="* ]]; then
365 if [[ "${field}" == "turl="* ]]; then
368 if [[ "${field}" == "ctime="* ]]; then
369 eval ${field}" "${fields[((x+1))]}
371 if [[ "${field}" == "size="* ]]; then
372 eval ${field}" "${fields[((x+1))]}
375 ctime=$( date -d "${ctime}" +%s 2>/dev/null)
376 [[ -z $md5 ]] && md5="."
377 [[ -n "$turl" ]] && echo "${turl//"alien://"/} ${md5} ${ctime} ${size}" && ((numberOfFiles++))
379 ((iterationNumber++))
386 #split the search in sub searches in the subdirectories of the base path
389 subPathSelection=${3}
390 [[ -z ${subPathSelection} ]] && subPathSelection=".*"
391 gbbox ls ${basePath} 2>/dev/null | \
392 while read subPath; do
393 [[ ! ${subPath} =~ ${subPathSelection} ]] && continue
394 alien_find ${basePath}/${subPath} ${searchTerm}
398 listCollectionContents()
400 #find the xml collections and print the list of filenames and hashes
401 while read -a fields; do
402 nfields=${#fields[*]}
406 for ((x=1;x<=${nfields};x++)); do
407 field=${fields[${x}]}
408 if [[ "${field}" == "md5="* ]]; then
411 if [[ "${field}" == "turl="* ]]; then
414 if [[ "${field}" == "ctime="* ]]; then
415 eval "${field} ${fields[((x+1))]}"
418 ctime=$( date -d "${ctime}" +%s 2>/dev/null)
419 [[ -n "$turl" ]] && echo "${turl//"alien://"/} ${md5} ${ctime}"
420 done < <(catCollections $1 $2 2>/dev/null)
425 #print the contents of collection(s)
426 if [[ $# -eq 2 ]]; then
427 while read collection; do
428 [[ $collection != "/"*"/"?* ]] && continue
429 gbbox cat $collection
430 done < <(alien_find $1 $2)
431 elif [[ $# -eq 1 ]]; then
438 #only get a new token if the old one expires soon
440 [[ -z $maxExpireTime ]] && maxExpireTime=4000
441 [[ -z $ALIEN_ROOT ]] && echo "no ALIEN_ROOT!" && return 1
443 tokenExpirationTime=$($ALIEN_ROOT/api/bin/alien-token-info|grep Expires)
444 tokenExpirationTime=$(date -d "${tokenExpirationTime#*:}" "+%s")
445 secondsToExpire=$(( tokenExpirationTime-now ))
446 if [[ $secondsToExpire -lt $maxExpireTime ]]; then
449 echo "token valid for another $secondsToExpire seconds"
456 #copy the file $1 to $2 using a specified method
457 #uses the "timeout" command to make sure the
458 #download processes will not hang forever.
460 [[ -z $copyTimeout ]] && copyTimeout=600
461 [[ -z $copyTimeoutHard ]] && copyTimeoutHard=1200
462 src=${1//"alien://"/}
465 if [[ "$copyMethod" == "tfilecp" ]]; then
466 echo timeout $copyTimeout root -b -q "$copyScript(\"$src\",\"$dst\")"
467 timeout $copyTimeout root -b -q "$copyScript(\"$src\",\"$dst\")"
469 echo timeout $copyTimeout $ALIEN_ROOT/api/bin/alien_cp $src $dst
470 timeout $copyTimeout $ALIEN_ROOT/api/bin/alien_cp $src $dst
479 secondsToSuicide=$(( 10*3600 ))
480 localPathPrefix="${PWD}"
481 #define alienSync_localPathPrefix in your env to have a default central location
482 [[ -n ${alienSync_localPathPrefix} ]] && localPathPrefix=${alienSync_localPathPrefix}
483 logOutputPath="${localPathPrefix}/alienSyncLogs"
489 #first, check if the config file is configured
490 #is yes - source it so that other options can override it
492 for opt in "${args[@]}"; do
493 if [[ ${opt} =~ configFile=.* ]]; then
495 [[ ! -f ${configFile} ]] && echo "configFile ${configFile} not found, exiting..." && return 1
496 echo "using config file: ${configFile}"
497 source "${configFile}"
502 #then, parse the options as they override the options from file
503 for opt in "${args[@]}"; do
504 if [[ ! "${opt}" =~ .*=.* ]]; then
505 echo "badly formatted option ${var}, should be: option=value, stopping..."
508 local var="${opt%%=*}"
509 local value="${opt#*=}"
510 echo "${var} = ${value}"
511 export ${var}="${value}"