]> git.uio.no Git - u/mrichter/AliRoot.git/blob - PWGPP/QA/scripts/runQA.sh
when running with local OCDB - change the year according to the input data
[u/mrichter/AliRoot.git] / PWGPP / QA / scripts / runQA.sh
1 #!/bin/bash
2 main()
3 {
4   if [[ -z $1 ]]; then
5     echo "Usage: "
6     echo "  ${0##*/} option=value [option=value]"
7     echo "  at least inputList should be specified, or configFile containing it:"
8     echo "  ${0##*/} inputList=file.list"
9     echo "  options override config file (if any), e.g.:"
10     echo "  ${0##*/} configFile=runQA.config inputList=file.list outputDirectory=%det"
11     return 1
12   fi
13  
14   if ! parseConfig "$@"; then
15     ${0}
16     return 1
17   fi
18
19   [[ -z $ALICE_ROOT ]] && echo "ALICE_ROOT not defined" && return 1
20
21   ocdbregex='raw://'
22   if [[ ${ocdbStorage} =~ ${ocdbregex} ]]; then
23     alien-token-init ${alienUserName}
24     #this is a hack! alien-token init seems not enough
25     #but the gclient_env script messes up the LD_LIBRARY_PATH
26     while read x; do
27       eval ${x};
28     done < <(grep -v "LD_LIBRARY_PATH" /tmp/gclient_env_${UID})
29   fi
30
31   updateQA "$@"
32 }
33
34 updateQA()
35 {
36   umask 0002
37   parseConfig "$@"
38
39   #be paranoid and make some full paths
40   [[ ! -f ${inputList} ]] && echo "no input list: ${inputList}" && return 1
41   inputList=$(get_realpath ${inputList})
42   mkdir -p ${workingDirectory}
43   workingDirectory=$(workingDirectory=${workingDirectory%/}; cd ${workingDirectory%/*}; echo "${PWD}/${workingDirectory##*/}")
44   if [[ ! -d ${workingDirectory} ]]; then
45     echo "working dir $workingDirectory does not exist and cannot be created"
46     return 1
47   fi
48   cd ${workingDirectory}
49
50   echo JOB config:
51   echo inputList=$inputList
52   echo outputDirectory=$outputDirectory
53   echo
54
55   dateString=$(date +%Y-%m-%d-%H-%M)
56   echo "Start time QA process: $dateString"
57
58   #logging
59   mkdir -p $logDirectory
60   [[ ! -d $logDirectory ]] && echo "no log dir $logDirectory" && return 1
61   logFile="$logDirectory/${0##*/}.${dateString}.log"
62   touch ${logFile}
63   [[ ! -f ${logFile} ]] && echo "cannot write logfile $logfile" && return 1
64   echo "logFile = $logFile"
65
66   #check lock
67   lockFile=${logDirectory}/runQA.lock
68   [[ -f ${lockFile} ]] && echo "lock ${lockFile} exists!" | tee ${logFile} && return 1
69   touch ${lockFile}
70   [[ ! -f ${lockFile} ]] && echo "cannot lock $lockFile" | tee ${logFile} && return 1
71   
72   exec &>${logFile}
73
74   ################################################################
75   #ze detector loop
76   for detectorScript in $ALICE_ROOT/PWGPP/QA/detectorQAscripts/*; do
77     echo
78     echo "##############################################"
79     echo $(date)
80     unset planB
81     [[ ! ${detectorScript} =~ .*\.sh$ ]] && continue
82     detector=${detectorScript%.sh}
83     detector=${detector##*/}
84     
85     #skip if excluded
86     if [[ "${excludeDetectors}" =~ ${detector} ]]; then
87       echo "${detector} is excluded in config, skipping..."
88       continue
89     fi
90
91     #if includeDetectors set, only process thoe detectors specified there
92     if [[ -n ${includeDetectors} && ! "${includeDetectors}" =~ ${detector} ]]; then
93       echo "${detector} not included in includeDetectors, skipping..."
94       continue
95     fi
96
97     logSummary=${logDirectory}/summary-${detector}-${dateString}.log
98     outputDir=$(substituteDetectorName ${detector} ${outputDirectory})
99     tmpDetectorRunDir=${workingDirectory}/tmpQAtmpRunDir${detector}-${dateString}
100     if ! mkdir -p ${tmpDetectorRunDir}; then
101       echo "cannot create the temp dir $tmpDetectorRunDir"
102       continue
103     fi
104     cd ${tmpDetectorRunDir}
105
106     tmpPrefix=${tmpDetectorRunDir}/${outputDir}
107     echo "running QA for ${detector}"
108     echo "  outputDir=$outputDir"
109     echo "  tmpPrefix=$tmpPrefix"
110     
111     #unset the detector functions from previous iterations (detectors)
112     unset -f runLevelQA
113     unset -f periodLevelQA
114     unset -f runLevelHighPtTreeQA
115     unset -f periodLevelHighPtTreeQA
116     source ${detectorScript}
117
118     #################################################################
119     #produce the QA and trending tree for each file (run)
120     unset arrOfTouchedProductions
121     declare -A arrOfTouchedProductions
122     while read qaFile; do
123       echo
124       echo $(date)
125       
126       #first check if input file exists
127       [[ ! -f ${qaFile%\#*} ]] && echo "file ${qaFile%\#*} not accessible" && continue
128
129       if ! guessRunData ${qaFile}; then
130         echo "could not guess run data from ${qaFile}"
131         continue
132       fi
133
134       tmpProductionDir=${tmpPrefix}/${dataType}/${year}/${period}/${pass}
135       tmpRunDir=${tmpProductionDir}/000${runNumber}
136       mkdir -p ${tmpRunDir}
137       cd ${tmpRunDir}
138
139       #by default we expect to have everything in the same archive
140       highPtTree=${qaFile}
141
142       #maybe the input is not an archive, but a file
143       [[ "${qaFile}" =~ QAresults.root$ ]] && highPtTree=""
144       [[ "${qaFile}" =~ FilterEvents_Trees.root$ ]] && qaFile=""
145
146       #it is possible we get the highPt trees from somewhere else
147       #search the list of high pt trees for the proper run number
148       if [[ -n ${inputListHighPtTrees} ]]; then
149         highPtTree=$(egrep -m1 ${runNumber} ${inputListHighPtTrees})
150         echo "loaded the highPtTree ${highPtTree} from external file ${inputListHighPtTrees}"
151       fi
152       
153       echo qaFile=$qaFile
154       echo highPtTree=$highPtTree
155       echo ocdbStorage=${ocdbStorage}
156       echo
157
158       #what if we have a zip archive?
159       if [[ "$qaFile" =~ .*.zip$ ]]; then
160         if unzip -l ${qaFile} | egrep "QAresults.root" &>/dev/null; then
161           qaFile="${qaFile}#QAresults.root"
162         else
163           qaFile=""
164         fi
165       fi
166       if [[ "$highPtTree" =~ .*.zip$ ]]; then
167         if unzip -l ${highPtTree} | egrep "FilterEvents_Trees.root" &>/dev/null; then
168           highPtTree="${highPtTree}#FilterEvents_Trees.root"
169         else
170           highPtTree=""
171         fi
172       fi
173      
174       if [[ -n ${qaFile} && $(type -t runLevelQA) =~ "function" ]]; then
175         echo running ${detector} runLevelQA for run ${runNumber} from ${qaFile}
176         runLevelQA "${qaFile}" &> runLevelQA.log
177         #perform some default actions:
178         #if trending.root not created, create a default one
179         if [[ ! -f trending.root ]]; then
180           aliroot -b -q -l "$ALICE_ROOT/PWGPP/macros/simpleTrending.C(\"${qaFile}\",${runNumber},\"${detector}\",\"trending.root\",\"trending\",\"recreate\")" 2>&1 | tee -a runLevelQA.log
181         fi
182         if [[ -f trending.root ]]; then
183           arrOfTouchedProductions[${tmpProductionDir}]=1
184         else
185           echo "trending.root not created"
186         fi
187       fi
188       #expert QA based on high pt trees
189       if [[ -n ${highPtTree} && $(type -t runLevelHighPtTreeQA) =~ "function" ]]; then
190         echo running ${detector} runLevelHighPtTreeQA for run ${runNumber} from ${highPtTree}
191         runLevelHighPtTreeQA "${highPtTree}" &> runLevelHighPtTreeQA.log
192         arrOfTouchedProductions[${tmpProductionDir}]=1
193       fi
194
195       cd ${tmpDetectorRunDir}
196     
197     done < ${inputList}
198
199     #################################################################
200     #cache which productions were (re)done
201     echo "list of processed productions:"
202     echo "    ${!arrOfTouchedProductions[@]}"
203     echo
204
205     #################################################################
206     #(re)do the merging/trending 
207     for tmpProductionDir in ${!arrOfTouchedProductions[@]}; do
208       cd ${tmpProductionDir}
209       echo
210       echo "running period level stuff in ${tmpProductionDir}"
211       echo $(date)
212     
213       productionDir=${outputDir}/${tmpProductionDir#${tmpPrefix}}
214       echo productionDir=${outputDir}/${tmpProductionDir#${tmpPrefix}}
215
216       mkdir -p ${productionDir}
217       if [[ ! -d ${productionDir} ]]; then 
218         echo "cannot make productionDir $productionDir" && continue
219       fi
220       
221       #move runs to final destination
222       for dir in ${tmpProductionDir}/000*; do
223         echo 
224         oldRunDir=${outputDir}/${dir#${tmpPrefix}}
225         if ! guessRunData "${dir}/dummyName"; then
226           echo "could not guess run data from ${dir}"
227           continue
228         fi
229
230         #before moving - VALIDATE!!!
231         if ! validate ${dir}; then 
232           continue
233         fi
234
235         #moving a dir is an atomic operation, no locking necessary
236         if [[ -d ${oldRunDir} ]]; then
237           echo "removing old ${oldRunDir}"
238           rm -rf ${oldRunDir}
239         fi
240         echo "moving new ${runNumber} to ${productionDir}"
241         mv -f ${dir} ${productionDir}
242       done
243    
244       #go to a temp dir to do the period level stuff in a completely clean dir
245       tmpPeriodLevelQAdir="${tmpProductionDir}/periodLevelQA"
246       echo
247       echo tmpPeriodLevelQAdir="${tmpProductionDir}/periodLevelQA"
248       if ! mkdir -p ${tmpPeriodLevelQAdir}; then continue; fi
249       cd ${tmpPeriodLevelQAdir}
250
251       #link the final list of per-run dirs here, just the dirs
252       #to have a clean working directory
253       unset linkedStuff
254       declare -a linkedStuff
255       for x in ${productionDir}/000*; do [[ -d $x ]] && ln -s $x && linkedStuff+=(${x##*/}); done
256
257       #merge trending files if any
258       if /bin/ls 000*/trending.root &>/dev/null; then
259         hadd trending.root 000*/trending.root &> periodLevelQA.log
260       fi
261       
262       #run the period level trending/QA
263       if [[ -f "trending.root" && $(type -t periodLevelQA) =~ "function" ]]; then
264         echo running ${detector} periodLevelQA for production ${period}/${pass}
265         periodLevelQA trending.root &>> periodLevelQA.log
266       else 
267         echo "WARNING: not running ${detector} periodLevelQA for production ${period}/${pass}, no trending.root"
268       fi
269
270       if ! validate ${PWD}; then continue; fi
271
272       #here we are validated so move the produced QA to the final place
273       #clean up linked stuff first
274       [[ -n ${linkedStuff[@]} ]] && rm ${linkedStuff[@]}
275       periodLevelLock=${productionDir}/runQA.lock
276       if [[ ! -f ${periodLevelLock} ]]; then
277         #some of the output could be a directory, so handle that
278         #TODO: maybe use rsync?
279         #lock to avoid conflicts:
280         echo "${HOSTNAME} ${dateString}" > ${periodLevelLock}
281         for x in ${tmpPeriodLevelQAdir}/*; do  
282           if [[ -d ${x} ]]; then
283             echo "removing ${productionDir}/${x##*/}"
284             rm -rf ${productionDir}/${x##*/}
285             echo "moving ${x} to ${productionDir}"
286             mv ${x} ${productionDir}
287           fi
288           if [[ -f ${x} ]]; then
289             echo "moving ${x} to ${productionDir}"
290             mv -f ${x} ${productionDir} 
291           fi
292         done
293         rm -f ${periodLevelLock}
294         #remove the temp dir
295         rm -rf ${tmpPeriodLevelQAdir}
296       else
297         echo "locked! cannot move to destination"
298         echo "check and maybe manually do:"
299         echo " rm ${periodLevelLock}"
300         echo " rsync -av ${tmpPeriodLevelQAdir}/ ${productionDir}/" >> ${logSummary}
301         planB=1
302       fi
303
304     done
305
306     cd ${workingDirectory}
307
308     if [[ -z ${planB} ]]; then
309       echo
310       echo removing ${tmpDetectorRunDir}
311       rm -rf ${tmpDetectorRunDir}
312     else
313       executePlanB
314     fi
315   done #end of detector loop
316
317   #remove lock
318   rm -f ${lockFile}
319 }
320
321 executePlanB()
322 {
323   #in case of emergency
324   if [[ -n ${MAILTO} ]]; then 
325     echo
326     echo "trouble detected, sending email to ${MAILTO}"
327
328     grep BAD ${logSummary} | mail -s "qa in need of assistance" ${MAILTO}
329   fi
330 }
331
332 validate()
333 {
334   summarizeLogs ${1} >> ${logSummary}
335   logStatus=$?
336   if [[ ${logStatus} -ne 0 ]]; then 
337     echo "WARNING not validated: ${1}"
338     planB=1
339     return 1
340   fi
341   return 0
342 }
343
344 summarizeLogs()
345 {
346   local dir=$1
347   [[ ! -d ${dir} ]] && dir=${PWD}
348
349   #print a summary of logs
350   logFiles=(
351       "*.log"
352       "stdout"
353       "stderr"
354   )
355
356   #check logs
357   local logstatus=0
358   for log in ${dir}/${logFiles[*]}; do
359     finallog=${PWD%/}/${log}
360     [[ ! -f ${log} ]] && continue
361     errorSummary=$(validateLog ${log})
362     validationStatus=$?
363     [[ validationStatus -ne 0 ]] && logstatus=1
364     if [[ ${validationStatus} -eq 0 ]]; then 
365       #in pretend mode randomly report an error in rec.log some cases
366       if [[ -n ${pretend} && "${log}" == "rec.log" ]]; then
367         [[ $(( ${RANDOM}%2 )) -ge 1 ]] && echo "${finallog} BAD random error" || echo "${finallog} OK"
368       else
369         echo "${finallog} OK"
370       fi
371     elif [[ ${validationStatus} -eq 1 ]]; then
372       echo "${finallog} BAD ${errorSummary}"
373     elif [[ ${validationStatus} -eq 2 ]]; then
374       echo "${finallog} OK MWAH ${errorSummary}"
375     fi
376   done
377
378   #report core files
379   while read x; do
380     echo ${x}
381     chmod 644 ${x}
382     gdb --batch --quiet -ex "bt" -ex "quit" aliroot ${x} > stacktrace_${x//\//_}.log
383   done < <(/bin/ls ${PWD}/*/core 2>/dev/null; /bin/ls ${PWD}/core 2>/dev/null)
384
385   return ${logstatus}
386 }
387
388 validateLog()
389 {
390   log=${1}
391   errorConditions=(
392             'There was a crash'
393             'floating'
394             'error while loading shared libraries'
395             'std::bad_alloc'
396             's_err_syswatch_'
397             'Thread [0-9]* (Thread'
398             'AliFatal'
399             'core dumped'
400             '\.C.*error:.*\.h: No such file'
401             'segmentation'
402             'Interpreter error recovered'
403   )
404
405   warningConditions=(
406             'This is serious'
407   )
408
409   local logstatus=0
410   local errorSummary=""
411   local warningSummary=""
412
413   for ((i=0; i<${#errorConditions[@]};i++)); do
414     local tmp=$(grep -m1 -e "${errorConditions[${i}]}" ${log})
415     [[ -n ${tmp} ]] && tmp+=" : "
416     errorSummary+=${tmp}
417   done
418
419   for ((i=0; i<${#warningConditions[@]};i++)); do
420     local tmp=$(grep -m1 -e "${warningConditions[${i}]}" ${log})
421     [[ -n ${tmp} ]] && tmp+=" : "
422     warningSummary+=${tmp}
423   done
424
425   if [[ -n ${errorSummary} ]]; then 
426     echo "${errorSummary}"
427     return 1
428   fi
429
430   if [[ -n ${warningSummary} ]]; then
431     echo "${warningSummary}"
432     return 2
433   fi
434
435   return 0
436 }
437
438 parseConfig()
439 {
440   args=("$@")
441
442   #config file
443   configFile=""
444   #where to search for qa files
445   inputList=file.list
446   #working directory
447   workingDirectory="${PWD}"
448   #where to place the final qa plots
449   #outputDirectory="/afs/cern.ch/work/a/aliqa%det/www/"
450   outputDirectory="${workingDirectory}/%DET"
451   #filter out detector option
452   excludeDetectors="EXAMPLE"
453   #logs
454   logDirectory=${workingDirectory}/logs
455   #OCDB storage
456   ocdbStorage="raw://"
457   #email to
458   #MAILTO="fbellini@cern.ch"
459
460   #first, check if the config file is configured
461   #is yes - source it so that other options can override it
462   #if any
463   for opt in "${args[@]}"; do
464     if [[ ${opt} =~ configFile=.* ]]; then
465       eval "${opt}"
466       [[ ! -f ${configFile} ]] && echo "configFile ${configFile} not found, exiting..." && return 1
467       echo "using config file: ${configFile}"
468       source "${configFile}"
469       break
470     fi
471   done
472
473   #then, parse the options as they override the options from file
474   for opt in "${args[@]}"; do
475     if [[ ! "${opt}" =~ .*=.* ]]; then
476       echo "badly formatted option ${var}, should be: option=value, stopping..."
477       return 1
478     fi
479     local var="${opt%%=*}"
480     local value="${opt#*=}"
481     echo "${var}=${value}"
482     export ${var}="${value}"
483   done
484 }
485
486 guessRunData()
487 {
488   #guess the period from the path, pick the rightmost one
489   period=""
490   runNumber=""
491   year=""
492   pass=""
493   legoTrainRunNumber=""
494   dataType=""
495
496   local shortRunNumber=""
497   oldIFS=${IFS}
498   local IFS="/"
499   declare -a path=( $1 )
500   IFS="${oldIFS}"
501   local dirDepth=$(( ${#path[*]}-1 ))
502   i=0
503   for ((x=${dirDepth};x>=0;x--)); do
504
505     [[ $((x-1)) -ge 0 ]] && local fieldPrev=${path[$((x-1))]}
506     local field=${path[${x}]}
507     local fieldNext=${path[$((x+1))]}
508
509     [[ ${field} =~ ^[0-9]*$ && ${fieldNext} =~ (.*\.zip$|.*\.root$) ]] && legoTrainRunNumber=${field}
510     [[ -n ${legoTrainRunNumber} && -z ${pass} ]] && pass=${fieldPrev}
511     [[ ${field} =~ ^LHC[0-9][0-9][a-z].*$ ]] && period=${field%_*}
512     [[ ${field} =~ ^000[0-9][0-9][0-9][0-9][0-9][0-9]$ ]] && runNumber=${field#000}
513     [[ ${field} =~ ^[0-9][0-9][0-9][0-9][0-9][0-9]$ ]] && shortRunNumber=${field}
514     [[ ${field} =~ ^20[0-9][0-9]$ ]] && year=${field}
515     [[ ${field} =~ ^(^sim$|^data$) ]] && dataType=${field}
516     (( i++ ))
517   done
518   [[ -z ${legoTrainRunNumber} ]] && pass=${path[$((dirDepth-1))]}
519   [[ "${dataType}" =~ ^sim$ ]] && pass="passMC" && runNumber=${shortRunNumber}
520   
521   #modify the OCDB: set the year
522   ocdbStorage=$(setYear ${year} ${ocdbStorage})
523
524   #if [[ -z ${dataType} || -z ${year} || -z ${period} || -z ${runNumber}} || -z ${pass} ]];
525   if [[ -z ${runNumber}} ]]
526   then
527     #error condition
528     return 1
529   else
530     #ALL OK
531     return 0
532   fi
533 }
534
535 substituteDetectorName()
536 {
537   local det=$1
538   local dir=$2
539   [[ ${dir} =~ \%det ]] && det=${det,,} && echo ${dir/\%det/${det}}
540   [[ ${dir} =~ \%DET ]] && det=${det} && echo ${dir/\%DET/${det}}
541 }
542
543 get_realpath() 
544 {
545   if [[ -f "$1" ]]
546   then
547     # file *must* exist
548     if cd "$(echo "${1%/*}")" &>/dev/null
549     then
550       # file *may* not be local
551       # exception is ./file.ext
552       # try 'cd .; cd -;' *works!*
553       local tmppwd="$PWD"
554       cd - &>/dev/null
555     else
556       # file *must* be local
557       local tmppwd="$PWD"
558     fi
559   else
560     # file *cannot* exist
561     return 1 # failure
562   fi
563   # reassemble realpath
564   echo "$tmppwd"/"${1##*/}"
565   return 0 # success
566 }
567
568 setYear()
569 {
570   #set the year
571   #  ${1} - year to be set
572   #  ${2} - where to set the year
573   local year1=$(guessYear ${1})
574   local year2=$(guessYear ${2})
575   local path=${2}
576   [[ ${year1} -ne ${year2} && -n ${year2} && -n ${year1} ]] && path=${2/\/${year2}\//\/${year1}\/}
577   echo ${path}
578   return 0
579 }
580
581 guessYear()
582 {
583   #guess the year from the path, pick the rightmost one
584   local IFS="/"
585   declare -a pathArray=( ${1} )
586   local field
587   local year
588   for field in ${pathArray[@]}; do
589     [[ ${field} =~ ^20[0-9][0-9]$ ]] && year=${field}
590   done
591   echo ${year}
592   return 0
593 }
594
595 main "$@"