4 from multiprocessing.pool 
import Pool
 
    6 import logging; log = logging.getLogger(
"DCSCalculator2.main")
 
    8 from DQUtils.db 
import fetch_iovs
 
    9 from DQUtils.iov_arrangement 
import inverse_lblb, run_iovs_from_lblb
 
   10 from DQUtils.general 
import timer
 
   11 from DQUtils.utils 
import pprint_objects
 
   12 from DQUtils.logger 
import init_logger
 
   13 from DQUtils.sugar 
import RunLumi, IOVSet
 
   15 from DQDefects 
import DefectsDB
 
   17 from DCSCalculator2.subdetectors 
import ALL_SYSTEMS, SYSTEM_MAP
 
   18 from DCSCalculator2.variable 
import DefectIOV, DefectIOVFull
 
   20 import DCSCalculator2.config 
as config
 
   22 from contextlib 
import nullcontext
 
   29     hours   = seconds / 3600; seconds %= 3600
 
   30     minutes = seconds / 60;   seconds %= 60
 
   31     return "%ih%im%is" % (hours, minutes, seconds)
 
   35         log.info(
"Empty Result.")
 
   47         with timer(
"Run DCS calculator 2 for %s" % system):
 
   48             return system.run(lbtime, run_iovs)
 
   50         log.warning(
"DCS Calculator failed to run for %s.", system)
 
   51         if config.opts.dont_ignore_system_exceptions:
 
   53         log.exception(
"Continuing. Use -e -X commandline to investigate")
 
   54         if config.opts.email_on_failure:
 
   55             from DataQualityUtils.panic 
import panic
 
   56             from traceback 
import format_exc
 
   57             runnum = lbtime[0].Run 
if len(lbtime)>0 
else '??????' 
   58             panicmsg = 
"DCS Calculator failed to execute in run %s for system %s.\n\n%s" % (runnum, system, format_exc())
 
   61     except (KeyboardInterrupt, SystemExit):
 
   65     pool = Pool(N 
if N > 0 
else len(systems))
 
   67     for system 
in systems:
 
   68         result = pool.apply_async(run_one, (system, lbtime, run_iovs))
 
   69         results.append(result)
 
   71     all_results = IOVSet()
 
   72     for system, result 
in zip(systems, map(
lambda x: x.get(), results)):
 
   73         log.info(
" -- result for %s", system)
 
   76             all_results.extend(result)
 
   81     result_iovs = IOVSet()
 
   83     for system 
in systems:
 
   84         log.info(
" -- running for %s", system)
 
   85         system_result = 
run_one(system, lbtime, run_iovs)
 
   88             result_iovs.extend(system_result)
 
   92 def go(iov, systems, db, indb, timewise=False, use_flask=False):
 
   94     Run the DCS calculator for `run` on the `systems` specified, saving the  
   95     result to the `database`. 
   99     with timer(
"Read LBLB"):
 
  101         lblb = 
fetch_iovs(
"LBLB", since, until, with_channel=
False, database=(indb 
if indb.startswith(
'sqlite') 
else 'COOLONL_TRIGGER/%s' % indb))
 
  102         assert lblb, 
"No luminosity blocks for desired range. [%s, %s)" % (since, until)
 
  113     log.debug(
"Will process %i LBs over %i runs", len(lblb), len(run_iovs))
 
  115     log.info(
"DCSC2 will run over range: %r %s", tuple(run_iovs.range_iov), 
"(%i lbs)" % len(lblb))
 
  119     systems = [system() 
for system 
in systems 
 
  120                if not getattr(system, 
"__DISABLED__", 
False)]
 
  129     if log.isEnabledFor(logging.DEBUG):
 
  132     log.info(
"Calculation complete")
 
  136             with timer(
"write result (%i iovs)" % len(result_iovs)):
 
  137                 log.debug(
"Writing result (%i iovs)", len(result_iovs))
 
  138                 defect_iovs = 
list(
filter(
lambda iov: isinstance(iov, DefectIOV), result_iovs))  
 
  139                 defect_iovs_full = [
DefectIOVFull(recoverable=
False, user=
'sys:defectcalculator', **_._asdict()) 
 
  140                                     for _ 
in defect_iovs]
 
  141                 defect_iovs_full.append(
DefectIOVFull(recoverable=
False, user=
'sys:defectcalculator', 
 
  142                                                       channel=
'GLOBAL_DCS_UNCHECKED', present=
False,
 
  143                                                       comment=
'Calculator did run',
 
  144                                                       since=since, until=until))
 
  145                 if len(defect_iovs) > 0:
 
  146                     log.warning(f
'db {db}, read_only {not use_flask}')
 
  147                     ddb = DefectsDB(db, read_only=use_flask, create=
not use_flask)
 
  148                     defect_names = 
set(i.channel 
for i 
in defect_iovs_full)
 
  149                     for defect 
in defect_names:
 
  150                         if defect 
in ddb.defect_id_map:
 
  152                         ddb.create_defect(defect, 
"Created by DCSCalculator2")
 
  153                     with ddb.storage_buffer 
if not use_flask 
else nullcontext():
 
  157                             secret_path = os.environ.get(
'COOLFLASK_SECRET', 
'/afs/cern.ch/user/a/atlasdqm/private/coolflask_secret/coolflask_secret.json')
 
  158                             auth = json.loads(
open(secret_path).
read())
 
  161                         ddb.insert_multiple(defect_iovs_full, use_flask=use_flask, flask_auth=auth)
 
  163             log.warning(
"DCS Calculator failed to upload defects to DB")
 
  164             if config.opts.email_on_failure:
 
  165                 from DataQualityUtils.panic 
import panic
 
  166                 from traceback 
import format_exc
 
  167                 runnum = lbtime[0].Run 
if len(lbtime)>0 
else '??????' 
  168                 panicmsg = 
"DCS Calculator failed to upload defects to database for run %s\n\n%s" % (runnum, format_exc())
 
  173     args = len(result_iovs), 
hash(result_iovs)
 
  174     log.info(
"Success. Calculated %i iovs. Result hash: 0x%0x8.", *args)
 
  178     optp, opts, args = config.parse_options(argv)
 
  182     log.debug(
"Commandline arguments: %s", argv)
 
  183     log.debug(
"Current configuration: %s", (opts))
 
  185     if opts.shell_on_exception: 
 
  187         from IPython.core 
import ultratb
 
  188         sys.excepthook = ultratb.FormattedTB(call_pdb=
True)
 
  192     if opts.systems 
is None:
 
  193         systems = ALL_SYSTEMS
 
  198         for system 
in opts.systems:
 
  199             if system 
not in SYSTEM_MAP:
 
  200                 invalid_systems.append(system)
 
  202                 systems.append(SYSTEM_MAP[system])
 
  205             optp.error(
"Invalid system(s) specified: {0}. " 
  206                        "Available systems: {1}".
format(invalid_systems, SYSTEM_MAP.keys()))
 
  209     if (opts.run 
and opts.range) 
or (
not opts.run 
and not opts.range):
 
  210         optp.error(
"Specify either -r or -R")
 
  212         since, until = opts.run, opts.run
 
  214         since, until = map(int, opts.range.split(
"-"))
 
  218             optp.error(
"--lbs and --range are incompatible. " 
  219                        "Use --lbs with --run")
 
  220         sincelb, untillb = map(int, opts.lbs.split(
"-"))
 
  225     go(iov, systems, opts.output_database, opts.input_database, opts.timewise, opts.flask)