]> git.uio.no Git - u/mrichter/AliRoot.git/blob - PWGPP/QA/scripts/runQA.sh
add comment
[u/mrichter/AliRoot.git] / PWGPP / QA / scripts / runQA.sh
1 #!/bin/bash
2 # process QA output into plots and trending
3 # run without arguments for examples
4 # origin: Mikolaj Krzewicki, mkrzewic@cern.ch
5 #
6 if [ ${BASH_VERSINFO} -lt 4 ]; then
7   echo "bash version >= 4 needed, you have ${BASH_VERSION}, exiting..."
8   exit 1
9 fi
10
11 main()
12 {
13   if [[ -z $1 ]]; then
14     echo "Usage: "
15     echo "  ${0##*/} option=value [option=value]"
16     echo "  at least inputList should be specified, or configFile containing it:"
17     echo "  ${0##*/} inputList=file.list"
18     echo "  options override config file (if any), e.g.:"
19     echo "  ${0##*/} configFile=runQA.config inputList=file.list outputDirectory=%det"
20     echo "some expert options"
21     echo "  inputListHighPtTrees=file.list - external list of filtered trees, requires inputList to be set"
22     echo "  includeDetectors=TPC,V0,MU - only process those"
23     echo "  excludeDetectors=EVS,TPC - skip processing of those"
24     echo "  - see example config file for more"
25     return 1
26   fi
27
28   if ! parseConfig "$@"; then
29     ${0}
30     return 1
31   fi
32
33   [[ -z $ALICE_ROOT ]] && echo "ALICE_ROOT not defined" && return 1
34
35   ocdbregex='raw://'
36   if [[ ${ocdbStorage} =~ ${ocdbregex} ]]; then
37     alien-token-init ${alienUserName}
38     #this is a hack! alien-token init seems not enough
39     #but the gclient_env script messes up the LD_LIBRARY_PATH
40     while read x; do
41       eval ${x};
42     done < <(grep -v "LD_LIBRARY_PATH" /tmp/gclient_env_${UID})
43   fi
44
45   updateQA "$@"
46   return 0
47 }
48
49 updateQA()
50 {
51   umask 0002
52   parseConfig "$@"
53
54   #be paranoid and make some full paths
55   [[ ! -f ${inputList} ]] && echo "no input list: ${inputList}" && return 1
56   inputList=$(get_realpath ${inputList})
57   mkdir -p ${workingDirectory}
58   #this is a trick to get the full path of workingDirectory
59   #(on a mac 'readlink -f' does not work...)
60   workingDirectory=$(workingDirectory=${workingDirectory%/}; cd ${workingDirectory%/*}; echo "${PWD}/${workingDirectory##*/}")
61   if [[ ! -d ${workingDirectory} ]]; then
62     echo "working dir $workingDirectory does not exist and cannot be created"
63     return 1
64   fi
65   cd ${workingDirectory}
66
67   echo JOB config:
68   echo inputList=$inputList
69   echo outputDirectory=$outputDirectory
70   echo
71
72   dateString=$(date +%Y-%m-%d-%H-%M-%S-%N)
73   echo "Start time QA process: $dateString"
74
75   #logging
76   mkdir -p $logDirectory
77   [[ ! -d $logDirectory ]] && echo "no log dir $logDirectory" && return 1
78   logFile="$logDirectory/${0##*/}.${dateString}.log"
79   touch ${logFile}
80   [[ ! -f ${logFile} ]] && echo "cannot write logfile $logfile" && return 1
81   echo "logFile = $logFile"
82
83   #check lock
84   lockFile=${workingDirectory}/runQA.lock
85   [[ -f ${lockFile} ]] && echo "lock ${lockFile} exists!" | tee ${logFile} && return 1
86   touch ${lockFile}
87   [[ ! -f ${lockFile} ]] && echo "cannot lock $lockFile" | tee ${logFile} && return 1
88   
89   exec &>${logFile}
90
91   ################################################################
92   #ze detector loop
93   for detectorScript in $ALICE_ROOT/PWGPP/QA/detectorQAscripts/*; do
94     echo
95     echo "##############################################"
96     echo $(date)
97     unset planB
98     [[ ! ${detectorScript} =~ .*\.sh$ ]] && continue
99     detector=${detectorScript%.sh}
100     detector=${detector##*/}
101     #by default we expect the container in the QA root file to de named like
102     #the detector
103     detectorQAcontainerName=${detector}
104     
105     #skip if excluded
106     if [[ "${excludeDetectors}" =~ ${detector} ]]; then
107       echo "${detector} is excluded in config, skipping..."
108       continue
109     fi
110
111     #if includeDetectors set, only process thoe detectors specified there
112     if [[ -n ${includeDetectors} && ! "${includeDetectors}" =~ ${detector} ]]; then
113       echo "${detector} not included in includeDetectors, skipping..."
114       continue
115     fi
116
117     logSummary=${logDirectory}/summary-${detector}-${dateString}.log
118     hostInfo >> ${logSummary}
119     outputDir=$(substituteDetectorName ${detector} ${outputDirectory})
120     tmpDetectorRunDir=${workingDirectory}/tmpQAtmpRunDir${detector}-${dateString}
121     if ! mkdir -p ${tmpDetectorRunDir}; then
122       echo "cannot create the temp dir $tmpDetectorRunDir"
123       continue
124     fi
125     cd ${tmpDetectorRunDir}
126
127     tmpPrefix=${tmpDetectorRunDir}/${outputDir}
128     echo "running QA for ${detector}"
129     echo "  outputDir=$outputDir"
130     echo "  tmpPrefix=$tmpPrefix"
131     
132     #source the detector script
133     #unset the detector functions from previous iterations (detectors)
134     unset -f runLevelQA
135     unset -f runLevelQAouter
136     unset -f periodLevelQA
137     unset -f runLevelEventStatQA
138     unset -f runLevelHighPtTreeQA
139     unset -f periodLevelHighPtTreeQA
140     source ${detectorScript}
141
142     #################################################################
143     #produce the QA and trending tree for each file (run)
144     unset arrOfTouchedProductions
145     declare -A arrOfTouchedProductions
146     while read inputFile; do
147       echo
148       echo $(date)
149       
150       #first check if input file exists
151       [[ ! -f ${inputFile%\#*} ]] && echo "file ${inputFile%\#*} not accessible" && continue
152
153       if ! guessRunData ${inputFile}; then
154         echo "could not guess run data from ${inputFile}"
155         continue
156       fi
157       echo "anchorYear for ${originalPeriod} is: ${anchorYear}"
158
159       tmpProductionDir=${tmpPrefix}/${dataType}/${year}/${period}/${pass}
160       tmpRunDir=${tmpProductionDir}/000${runNumber}
161       mkdir -p ${tmpRunDir}
162       cd ${tmpRunDir}
163
164       #check what kind of input file we have, default is a zip archive
165       #set the inputs accordingly
166       qaFile=""
167       qaFileOuter=""
168       highPtTree=""
169       eventStatFile=""
170       #it is possible we get the highPt trees from somewhere else
171       #search the list of high pt trees for the proper run number
172       if [[ -n ${inputListHighPtTrees} ]]; then
173         highPtTree=$(egrep -m1 ${runNumber} ${inputListHighPtTrees})
174         echo "loaded the highPtTree ${highPtTree} from external file ${inputListHighPtTrees}"
175       fi
176       #if we are explicit about the input file this takes precedence 
177       #over earlier additions
178       [[ "${inputFile}" =~ QAresults.root$ ]] && qaFile=${inputFile}
179       [[ "${inputFile}" =~ QAresults_outer.root$ ]] && qaFileOuter=${inputFile}
180       [[ "${inputFile}" =~ FilterEvents_Trees.root$ ]] && highPtTree=${inputFile}
181       [[ "${inputFile}" =~ event_stat.root$ ]] && eventStatFile=${inputFile}
182       if [[ "${inputFile}" =~ \.zip$ ]]; then
183         [[ -z ${qaFile} ]] && qaFile=${inputFile}
184         [[ -z ${qaFileOuter} ]] && qaFileOuter=${inputFile}
185         [[ -z ${highPtTree} ]] && highPtTree=${inputFile}
186         [[ -z ${eventStatFile} ]] && eventStatFile=${inputFile}
187       fi
188
189       #if we have zip archives in the input, extract the proper file name
190       #from the archive and append in a root-like fashion
191       if [[ "$qaFile" =~ .*.zip$ ]]; then
192         if unzip -l ${qaFile} | egrep "QAresults.root" &>/dev/null; then
193           qaFile+="#QAresults.root"
194         elif unzip -l ${qaFile} | egrep "QAresults_barrel.root" &>/dev/null; then
195           qaFile+="#QAresults_barrel.root"
196         else
197           qaFile=""
198         fi
199       fi
200       if [[ "$qaFileOuter" =~ .*.zip$ ]]; then
201         if unzip -l ${qaFileOuter} | egrep "QAresults_outer.root" &>/dev/null; then
202           qaFileOuter+="#QAresults_outer.root"
203         else
204           qaFileOuter=""
205         fi
206       fi
207       if [[ "$highPtTree" =~ .*.zip$ ]]; then
208         if unzip -l ${highPtTree} | egrep "FilterEvents_Trees.root" &>/dev/null; then
209           highPtTree+="#FilterEvents_Trees.root"
210         else
211           highPtTree=""
212         fi
213       fi
214       if [[ "${eventStatFile}" =~ .*.zip$ ]]; then
215         if unzip -l ${eventStatFile} | egrep "event_stat.root" &>/dev/null; then
216           eventStatFile+="#event_stat.root"
217         elif unzip -l ${eventStatFile} | egrep "event_stat_barrel.root" &>/dev/null; then
218           eventStatFile+="#event_stat_barrel.root"
219         else
220           eventStatFile=""
221         fi
222       fi
223      
224       echo qaFile=$qaFile
225       echo qaFileOuter=$qaFileOuter
226       echo highPtTree=$highPtTree
227       echo eventStatFile=$eventStatFile
228       echo ocdbStorage=${ocdbStorage}
229       echo
230
231       #standard QA based on QAresults.root file (and variants)
232       if [[ -n ${qaFile} && $(type -t runLevelQA) =~ "function" ]]; then
233         echo running ${detector} runLevelQA for run ${runNumber} from ${qaFile}
234         ( runLevelQA "${qaFile}" ) &>> runLevelQA.log
235         #cache the touched production + an example file to guarantee consistent run data parsing
236         arrOfTouchedProductions[${tmpProductionDir}]="${inputFile%\#*}"
237       fi
238       #standard QA based on QAresults_outer.root file (there in cpass, with different triggers)
239       if [[ -n ${qaFileOuter} && $(type -t runLevelQAouter) =~ "function" ]]; then
240         echo running ${detector} runLevelQAouter for run ${runNumber} from ${qaFileOuter}
241         ( runLevelQAouter "${qaFileOuter}" ) &>> runLevelQA.log
242         #cache the touched production + an example file to guarantee consistent run data parsing
243         arrOfTouchedProductions[${tmpProductionDir}]="${inputFile%\#*}"
244       fi
245       #expert QA based on high pt trees
246       if [[ -n ${highPtTree} && $(type -t runLevelHighPtTreeQA) =~ "function" ]]; then
247         echo running ${detector} runLevelHighPtTreeQA for run ${runNumber} from ${highPtTree}
248         ( runLevelHighPtTreeQA "${highPtTree}" ) &>> runLevelQA.log
249         #cache the touched production + an example file to guarantee consistent run data parsing
250         arrOfTouchedProductions[${tmpProductionDir}]="${inputFile%\#*}"
251       fi
252       #event stat QA based on event_stat.root file
253       if [[ -n ${eventStatFile} && $(type -t runLevelEventStatQA) =~ "function" ]]; then
254         echo running ${detector} runLevelEventStatQA for run ${runNumber} from ${eventStatFile}
255         ( runLevelEventStatQA "${eventStatFile}" ) &>> runLevelQA.log
256         #cache the touched production + an example file to guarantee consistent run data parsing
257         arrOfTouchedProductions[${tmpProductionDir}]="${inputFile%\#*}"
258       fi
259
260       #perform some default actions:
261       #if trending.root not created, create a default one
262       if [[ ! -f trending.root ]]; then
263         aliroot -b -q -l "$ALICE_ROOT/PWGPP/macros/simpleTrending.C(\"${qaFile}\",${runNumber},\"${detectorQAcontainerName}\",\"trending.root\",\"trending\",\"recreate\")" 2>&1 | tee -a runLevelQA.log
264       fi
265       if [[ ! -f trending.root ]]; then
266         echo "trending.root not created"
267       fi
268
269       cd ${tmpDetectorRunDir}
270     
271     done < ${inputList}
272
273     #################################################################
274     #cache which productions were (re)done
275     echo "list of processed productions:"
276     echo "    ${!arrOfTouchedProductions[@]}"
277     echo
278
279     #################################################################
280     #(re)do the merging/trending 
281     for tmpProductionDir in ${!arrOfTouchedProductions[@]}; do
282       cd ${tmpProductionDir}
283       echo
284       echo "running period level stuff in ${tmpProductionDir}"
285       echo $(date)
286     
287       productionDir=${outputDir}/${tmpProductionDir#${tmpPrefix}}
288       echo productionDir=${outputDir}/${tmpProductionDir#${tmpPrefix}}
289
290       mkdir -p ${productionDir}
291       if [[ ! -d ${productionDir} ]]; then 
292         echo "cannot make productionDir $productionDir" && continue
293       fi
294       
295       #move runs to final destination
296       for dir in ${tmpProductionDir}/000*; do
297         echo 
298         oldRunDir=${outputDir}/${dir#${tmpPrefix}}
299         if ! guessRunData "${arrOfTouchedProductions[${tmpProductionDir}]}"; then
300           echo "could not guess run data from ${arrOfTouchedProductions[${tmpProductionDir}]}"
301           continue
302         fi
303
304         #before moving - VALIDATE!!!
305         if ! validate ${dir}; then 
306           continue
307         fi
308
309         #moving a dir is an atomic operation, no locking necessary
310         if [[ -d ${oldRunDir} ]]; then
311           echo "removing old ${oldRunDir}"
312           rm -rf ${oldRunDir}
313         fi
314         echo "moving new ${runNumber} to ${productionDir}"
315         mv -f ${dir} ${productionDir}
316       done
317    
318       #go to a temp dir to do the period level stuff in a completely clean dir
319       tmpPeriodLevelQAdir="${tmpProductionDir}/periodLevelQA"
320       echo
321       echo tmpPeriodLevelQAdir="${tmpPeriodLevelQAdir}"
322       if ! mkdir -p ${tmpPeriodLevelQAdir}; then continue; fi
323       cd ${tmpPeriodLevelQAdir}
324
325       #link the final list of per-run dirs here, just the dirs
326       #to have a clean working directory
327       unset linkedStuff
328       declare -a linkedStuff
329       for x in ${productionDir}/000*; do [[ -d $x ]] && ln -s $x && linkedStuff+=(${x##*/}); done
330
331       #merge trending files if any
332       if /bin/ls 000*/trending.root &>/dev/null; then
333         hadd trending.root 000*/trending.root &> periodLevelQA.log
334       fi
335       
336       #run the period level trending/QA
337       if [[ -f "trending.root" && $(type -t periodLevelQA) =~ "function" ]]; then
338         echo running ${detector} periodLevelQA for production ${period}/${pass}
339         ( periodLevelQA trending.root ) &>> periodLevelQA.log
340       else 
341         echo "WARNING: not running ${detector} periodLevelQA for production ${period}/${pass}, no trending.root"
342       fi
343
344       if ! validate ${PWD}; then continue; fi
345
346       #here we are validated so move the produced QA to the final place
347       #clean up linked stuff first
348       [[ -n ${linkedStuff[@]} ]] && rm ${linkedStuff[@]}
349       periodLevelLock=${productionDir}/runQA.lock
350       if [[ ! -f ${periodLevelLock} ]]; then
351         #some of the output could be a directory, so handle that
352         #TODO: maybe use rsync?
353         #lock to avoid conflicts:
354         echo "${HOSTNAME} ${dateString}" > ${periodLevelLock}
355         for x in ${tmpPeriodLevelQAdir}/*; do  
356           if [[ -d ${x} ]]; then
357             echo "removing ${productionDir}/${x##*/}"
358             rm -rf ${productionDir}/${x##*/}
359             echo "moving ${x} to ${productionDir}"
360             mv ${x} ${productionDir}
361           fi
362           if [[ -f ${x} ]]; then
363             echo "moving ${x} to ${productionDir}"
364             mv -f ${x} ${productionDir} 
365           fi
366         done
367         rm -f ${periodLevelLock}
368         #remove the temp dir
369         rm -rf ${tmpPeriodLevelQAdir}
370       else
371         echo "ERROR: cannot move to destination"                     >> ${logSummary}
372         echo "production dir ${productionDir} locked!"               >> ${logSummary}
373         echo "check and maybe manually do:"                          >> ${logSummary}
374         echo " rm ${periodLevelLock}"                                >> ${logSummary}
375         echo " rsync -av ${tmpPeriodLevelQAdir}/ ${productionDir}/"  >> ${logSummary}
376         planB=1
377       fi
378
379     done
380
381     cd ${workingDirectory}
382
383     if [[ -z ${planB} ]]; then
384       echo
385       echo removing ${tmpDetectorRunDir}
386       rm -rf ${tmpDetectorRunDir}
387     else
388       executePlanB
389     fi
390   done #end of detector loop
391
392   #remove lock
393   rm -f ${lockFile}
394   return 0
395 }
396
397 executePlanB()
398 {
399   #in case of emergency
400   #first check if we have the email of the detector expert defined,
401   #if yes, append to the mailing list
402   local mailTo=${MAILTO}
403   local detExpertEmailVar="MAILTO_${detector}"
404   [[ -n "${!detExpertEmailVar}" ]] && mailTo+=" ${!detExpertEmailVar}"
405   if [[ -n ${mailTo} ]]; then 
406     echo
407     echo "trouble detected, sending email to ${mailTo}"
408     cat ${logSummary} | mail -s "${detector} QA in need of assistance" ${mailTo}
409   fi
410   return 0
411 }
412
413 validate()
414 {
415   summarizeLogs ${1} >> ${logSummary}
416   logStatus=$?
417   if [[ ${logStatus} -ne 0 ]]; then 
418     echo "WARNING not validated: ${1}"
419     planB=1
420     return 1
421   fi
422   return 0
423 }
424
425 summarizeLogs()
426 {
427   local dir=$1
428   [[ ! -d ${dir} ]] && dir=${PWD}
429
430   #print a summary of logs
431   logFiles=(
432       "*.log"
433       "stdout"
434       "stderr"
435   )
436
437   #check logs
438   local logstatus=0
439   for log in ${dir}/${logFiles[*]}; do
440     [[ ! -f ${log} ]] && continue
441     errorSummary=$(validateLog ${log})
442     validationStatus=$?
443     [[ validationStatus -ne 0 ]] && logstatus=1
444     if [[ ${validationStatus} -eq 0 ]]; then 
445       #in pretend mode randomly report an error in rec.log some cases
446       if [[ -n ${pretend} && "${log}" == "rec.log" ]]; then
447         [[ $(( ${RANDOM}%2 )) -ge 1 ]] && echo "${log} BAD random error" || echo "${log} OK"
448       else
449         echo "${log} OK"
450       fi
451     elif [[ ${validationStatus} -eq 1 ]]; then
452       echo "${log} BAD ${errorSummary}"
453     elif [[ ${validationStatus} -eq 2 ]]; then
454       echo "${log} OK MWAH ${errorSummary}"
455     fi
456   done
457
458   #report core files
459   while read x; do
460     echo ${x}
461     chmod 644 ${x}
462     gdb --batch --quiet -ex "bt" -ex "quit" aliroot ${x} > stacktrace_${x//\//_}.log
463   done < <(/bin/ls ${PWD}/*/core 2>/dev/null; /bin/ls ${PWD}/core 2>/dev/null)
464
465   return ${logstatus}
466 }
467
468 validateLog()
469 {
470   log=${1}
471   errorConditions=(
472             'There was a crash'
473             'floating'
474             'error while loading shared libraries'
475             'std::bad_alloc'
476             's_err_syswatch_'
477             'Thread [0-9]* (Thread'
478             'AliFatal'
479             'core dumped'
480             '\.C.*error:.*\.h: No such file'
481             'segmentation'
482             'Interpreter error recovered'
483   )
484
485   warningConditions=(
486             'This is serious'
487   )
488
489   local logstatus=0
490   local errorSummary=""
491   local warningSummary=""
492
493   for ((i=0; i<${#errorConditions[@]};i++)); do
494     local tmp=$(grep -m1 -e "${errorConditions[${i}]}" ${log})
495     [[ -n ${tmp} ]] && tmp+=" : "
496     errorSummary+=${tmp}
497   done
498
499   for ((i=0; i<${#warningConditions[@]};i++)); do
500     local tmp=$(grep -m1 -e "${warningConditions[${i}]}" ${log})
501     [[ -n ${tmp} ]] && tmp+=" : "
502     warningSummary+=${tmp}
503   done
504
505   if [[ -n ${errorSummary} ]]; then 
506     echo "${errorSummary}"
507     return 1
508   fi
509
510   if [[ -n ${warningSummary} ]]; then
511     echo "${warningSummary}"
512     return 2
513   fi
514
515   return 0
516 }
517
518 parseConfig()
519 {
520   args=("$@")
521
522   #config file
523   configFile=""
524   #where to search for qa files
525   inputList=file.list
526   #working directory
527   workingDirectory="${PWD}"
528   #where to place the final qa plots
529   #outputDirectory="/afs/cern.ch/work/a/aliqa%det/www/"
530   outputDirectory="${workingDirectory}/%DET"
531   #filter out detector option
532   excludeDetectors="EXAMPLE"
533   #logs
534   logDirectory=${workingDirectory}/logs
535   #OCDB storage
536   ocdbStorage="raw://"
537   #email to
538   #MAILTO="fbellini@cern.ch"
539   runMap="
540   2010 108350 139517
541   2011 140441 170593
542   2012 171590 193766
543   2013 194482 197692
544   "
545
546   #first, check if the config file is configured
547   #is yes - source it so that other options can override it
548   #if any
549   for opt in "${args[@]}"; do
550     if [[ ${opt} =~ configFile=.* ]]; then
551       eval "${opt}"
552       [[ ! -f ${configFile} ]] && echo "configFile ${configFile} not found, exiting..." && return 1
553       echo "using config file: ${configFile}"
554       source "${configFile}"
555       break
556     fi
557   done
558
559   #then, parse the options as they override the options from file
560   for opt in "${args[@]}"; do
561     if [[ ! "${opt}" =~ .*=.* ]]; then
562       echo "badly formatted option ${var}, should be: option=value, stopping..."
563       return 1
564     fi
565     local var="${opt%%=*}"
566     local value="${opt#*=}"
567     echo "${var}=${value}"
568     export ${var}="${value}"
569   done
570   return 0
571 }
572
573 guessRunData()
574 {
575   #guess the period from the path, pick the rightmost one
576   period=""
577   runNumber=""
578   year=""
579   pass=""
580   legoTrainRunNumber=""
581   dataType=""
582   originalPass=""
583   originalPeriod=""
584   anchorYear=""
585
586   shortRunNumber=""
587   oldIFS=${IFS}
588   local IFS="/"
589   declare -a path=( $1 )
590   IFS="${oldIFS}"
591   local dirDepth=$(( ${#path[*]}-1 ))
592   i=0
593   for ((x=${dirDepth};x>=0;x--)); do
594
595     [[ $((x-1)) -ge 0 ]] && local fieldPrev=${path[$((x-1))]}
596     local field=${path[${x}]}
597     local fieldNext=${path[$((x+1))]}
598
599     [[ ${field} =~ ^[0-9]*$ && ${fieldNext} =~ (.*\.zip$|.*\.root$) ]] && legoTrainRunNumber=${field}
600     [[ -n ${legoTrainRunNumber} && -z ${pass} ]] && pass=${fieldPrev}
601     [[ ${field} =~ ^LHC[0-9][0-9][a-z].*$ ]] && period=${field%_*} && originalPeriod=${field}
602     [[ ${field} =~ ^000[0-9][0-9][0-9][0-9][0-9][0-9]$ ]] && runNumber=${field#000}
603     [[ ${field} =~ ^[0-9][0-9][0-9][0-9][0-9][0-9]$ ]] && shortRunNumber=${field}
604     [[ ${field} =~ ^20[0-9][0-9]$ ]] && year=${field}
605     [[ ${field} =~ ^(^sim$|^data$) ]] && dataType=${field}
606     (( i++ ))
607   done
608   originalPass=${pass}
609   [[ -n ${shortRunNumber} && "${legoTrainRunNumber}" =~ ${shortRunNumber} ]] && legoTrainRunNumber=""
610   [[ -z ${legoTrainRunNumber} ]] && pass=${path[$((dirDepth-1))]}
611   [[ "${dataType}" =~ ^sim$ ]] && pass="passMC" && runNumber=${shortRunNumber} && originalPass="" #for MC not from lego, the runnumber is identified as lego train number, thus needs to be nulled
612   [[ -n ${legoTrainRunNumber} ]] && pass+="_lego${legoTrainRunNumber}"
613   
614   #modify the OCDB: set the year
615   if [[ ${dataType} =~ sim ]]; then 
616     anchorYear=$(run2year $runNumber)
617     if [[ -z "${anchorYear}" ]]; then
618       echo "WARNING: anchorYear not available for this production: ${originalPeriod}, runNumber: ${runNumber}. Cannot set the OCDB."
619       return 1
620     fi
621     ocdbStorage=$(setYear ${anchorYear} ${ocdbStorage})
622   else
623     ocdbStorage=$(setYear ${year} ${ocdbStorage})
624   fi
625
626   #if [[ -z ${dataType} || -z ${year} || -z ${period} || -z ${runNumber}} || -z ${pass} ]];
627   if [[ -z ${runNumber} ]]
628   then
629     #error condition
630     return 1
631   fi
632   
633   #ALL OK
634   return 0
635 }
636
637 run2year()
638 {
639   #for a given run print the year.
640   #the run-year table is ${runMap} (a string)
641   #defined in the config file
642   #one line per year, format: year runMin runMax
643   local run=$1
644   [[ -z ${run} ]] && return 1
645   local year=""
646   local runMin=""
647   local runMax=""
648   while read year runMin runMax; do
649     [[ -z ${year} || -z ${runMin} || -z ${runMax} ]] && continue
650     [[ ${run} -ge ${runMin} && ${run} -le ${runMax} ]] && echo ${year} && break
651   done < <(echo "${runMap}")
652   return 0
653 }
654
655 substituteDetectorName()
656 {
657   local det=$1
658   local dir=$2
659   [[ ${dir} =~ \%det ]] && det=${det,,} && echo ${dir/\%det/${det}}
660   [[ ${dir} =~ \%DET ]] && det=${det} && echo ${dir/\%DET/${det}}
661   return 0
662 }
663
664 get_realpath() 
665 {
666   if [[ -f "$1" ]]
667   then
668     # file *must* exist
669     if cd "$(echo "${1%/*}")" &>/dev/null
670     then
671       # file *may* not be local
672       # exception is ./file.ext
673       # try 'cd .; cd -;' *works!*
674       local tmppwd="$PWD"
675       cd - &>/dev/null
676     else
677       # file *must* be local
678       local tmppwd="$PWD"
679     fi
680   else
681     # file *cannot* exist
682     return 1 # failure
683   fi
684   # reassemble realpath
685   echo "$tmppwd"/"${1##*/}"
686   return 0 # success
687 }
688
689 setYear()
690 {
691   #set the year
692   #  ${1} - year to be set
693   #  ${2} - where to set the year
694   local year1=$(guessYear ${1})
695   local year2=$(guessYear ${2})
696   local path=${2}
697   [[ ${year1} -ne ${year2} && -n ${year2} && -n ${year1} ]] && path=${2/\/${year2}\//\/${year1}\/}
698   echo ${path}
699   return 0
700 }
701
702 guessYear()
703 {
704   #guess the year from the path, pick the rightmost one
705   local IFS="/"
706   declare -a pathArray=( ${1} )
707   local field
708   local year
709   for field in ${pathArray[@]}; do
710     [[ ${field} =~ ^20[0-9][0-9]$ ]] && year=${field}
711   done
712   echo ${year}
713   return 0
714 }
715
716 hostInfo(){
717 #
718 # Hallo world -  Print AliRoot/Root/Alien system info
719 #
720
721 #
722 # HOST info
723 #
724     echo --------------------------------------
725         echo 
726         echo HOSTINFO
727         echo 
728         echo HOSTINFO HOSTNAME"      "$HOSTNAME
729         echo HOSTINFO DATE"          "`date`
730         echo HOSTINFO gccpath"       "`which gcc` 
731         echo HOSTINFO gcc version"   "`gcc --version | grep gcc`
732         echo --------------------------------------    
733
734 #
735 # ROOT info
736 #
737         echo --------------------------------------
738         echo
739         echo ROOTINFO
740         echo 
741         echo ROOTINFO ROOT"           "`which root`
742         echo ROOTINFO VERSION"        "`root-config --version`
743         echo 
744         echo --------------------------------------
745
746
747 #
748 # ALIROOT info
749 #
750         echo --------------------------------------
751         echo
752         echo ALIROOTINFO
753         echo 
754         echo ALIROOTINFO ALIROOT"        "`which aliroot`
755         echo ALIROOTINFO VERSION"        "`echo $ALICE_LEVEL`
756         echo ALIROOTINFO TARGET"         "`echo $ALICE_TARGET`
757         echo 
758         echo --------------------------------------
759
760 #
761 # Alien info
762 #
763 #echo --------------------------------------
764 #echo
765 #echo ALIENINFO
766 #for a in `alien --printenv`; do echo ALIENINFO $a; done 
767 #echo
768 #echo --------------------------------------
769
770 #
771 # Local Info
772 #
773         echo PWD `pwd`
774         echo Dir 
775         ls -al
776         echo
777         echo
778         echo
779   
780   return 0
781 }
782
783 main "$@"