示例#1
0
class CnCRun(BaseRun):
    def __init__(self, showCmd=False, showCmdOutput=False, dbType=None):
        self.__showCmd = showCmd
        self.__showCmdOutput = showCmdOutput

        self.__cnc = None
        self.__reconnect(False)

        self.__runNumFile = \
            os.path.join(os.environ["HOME"], ".i3live-run")

        super(CnCRun, self).__init__(showCmd, showCmdOutput, dbType)

        self.__runSetId = None
        self.__runCfg = None
        self.__runNum = None

    def __reconnect(self, abortOnFail=True):
        self.__cnc = RPCClient("localhost", DAQPort.CNCSERVER)
        try:
            self.__cnc.rpc_ping()
        except socket.error, err:
            if err[0] == 61 or err[0] == 111:
                self.__cnc = None
            else:
                raise

        if self.__cnc is None and abortOnFail:
            raise RunException("Cannot connect to CnCServer")
示例#2
0
 def __reconnect(self, abortOnFail=True):
     self.__cnc = RPCClient("localhost", DAQPort.CNCSERVER)
     try:
         self.__cnc.rpc_ping()
     except socket.error, err:
         if err[0] == 61 or err[0] == 111:
             self.__cnc = None
         else:
             raise
示例#3
0
    def __init__(self, daqhost="localhost", daqport=8081):
        "Constructor - instantiate an RPC connection to DAQRun.py"

        # Find install location via $PDAQ_HOME, otherwise use locate_pdaq.py
        if environ.has_key("PDAQ_HOME"):
            self.__home = environ["PDAQ_HOME"]
        else:
            from locate_pdaq import find_pdaq_trunk
            self.__home = find_pdaq_trunk()

        self.__rpc = RPCClient(daqhost, int(daqport))
        self.__id = self.__rpc.rpc_ping()
示例#4
0
    def __init__(self, compName, host, port):
        self.__compName = compName
        self.__client = RPCClient(host, port)

        self.__beanFields = {}
        self.__beanList = self.__client.mbean.listMBeans()
        for bean in self.__beanList:
            self.__beanFields[bean] = self.__client.mbean.listGetters(bean)
示例#5
0
class DAQRunIface(object):
    START_TRANSITION_SECONDS = 300
    STOP_TRANSITION_SECONDS = 300
    RECOVERY_TRANSITION_SECONDS = 300
    RELEASE_TRANSITION_SECONDS = 300

    def __init__(self, daqhost="localhost", daqport=8081):
        "Constructor - instantiate an RPC connection to DAQRun.py"

        # Find install location via $PDAQ_HOME, otherwise use locate_pdaq.py
        if environ.has_key("PDAQ_HOME"):
            self.__home = environ["PDAQ_HOME"]
        else:
            from locate_pdaq import find_pdaq_trunk
            self.__home = find_pdaq_trunk()

        self.__rpc = RPCClient(daqhost, int(daqport))
        self.__id = self.__rpc.rpc_ping()

    def start(self, r, config, logInfo=()):
        "Tell DAQRun to start a run"
        config = sub('\.xml$', '', config)
        self.__rpc.rpc_start_run(r, 0, config, logInfo)
        return DAQRunIface.START_TRANSITION_SECONDS

    def stop(self):
        "Tell DAQRun to stop a run"
        self.__rpc.rpc_stop_run()
        return DAQRunIface.STOP_TRANSITION_SECONDS

    def recover(self):
        "Tell DAQRun to recover from an error and go to STOPPED state"
        self.__rpc.rpc_recover()
        return DAQRunIface.RECOVERY_TRANSITION_SECONDS

    def getState(self):
        "Get current DAQ state"
        return self.__rpc.rpc_run_state()

    def flasher(self, subRunID, flashingDomsList):
        """
        Tell DAQ to flash DOMs.  subRunID is 0, 1, ....  flashingDomsList is a list of
        tuples in the form (domid,       brightness, window, delay, mask, rate)
        or                 (dom_name,    "                                   ")
        or                 (string, pos, "                                   ")
        or a list of dictionaries, one per DOM, whose keys are
            'stringHub','domPosition','brightness','window','delay','mask','rate'
            and whose values are strings.
            (THIS OPTION WILL RAISE A KEYERROR IF YOU DON'T PASS THE CORRECT ARGS)
        Return value is 1 if the operation succeeded (subrun successfully started),
        else 0 (in which case, check the pDAQ logs for diagnostic information).
        
        """
        if flashingDomsList == []: pass  # Nothing to do except stop the subrun
        elif type(flashingDomsList[0]
                  ) == DictType:  # Check for dictionary list signature
            l = []
            # Throws exception if dictionary is messed up:
            try:
                for dom in flashingDomsList:
                    if dom.has_key('stringHub') and dom.has_key('domPosition'):
                        l.append(
                            (int(dom['stringHub']), int(dom['domPosition']),
                             int(dom['brightness']), int(dom['window']),
                             int(dom['delay']), int(dom['mask'],
                                                    16), int(dom['rate'])))
                    elif dom.has_key('MBID'):
                        l.append((str(dom['MBID']), int(dom['brightness']),
                                  int(dom['window']), int(dom['delay']),
                                  int(dom['mask'], 16), int(dom['rate'])))
                    else:
                        raise MalformedFlasherInput('Hash error on input')
            except Exception, e:
                m = 'Input was: ' + str(flashingDomsList)
                if not e.args: e.args = [
                        m,
                ]
                else:
                    e.args = (e.args[0], m) + e.args[1:]
                raise

            flashingDomsList = l

        #print "Subrun %d: DOMs to flash: %s" % (subRunID, str(flashingDomsList))
        return self.__rpc.rpc_flash(subRunID, flashingDomsList)
示例#6
0
class Dash(cmd.Cmd):
    CMD_BEAN = "bean"
    CMD_HELP = "help"
    CMD_LS = "ls"

    CMDS = {
        CMD_BEAN: "get bean data",
        CMD_HELP: "print this message",
        CMD_LS: "list component info",
    }

    def __init__(self):
        self.__cnc = RPCClient("localhost", DAQPort.CNCSERVER)

        cmd.Cmd.__init__(self)

        self.prompt = "> "

    @staticmethod
    def __findComponentId(compDict, compName):
        if not compDict.has_key(compName):
            if compName.endswith("#0") or compName.endswith("-0"):
                compName = compName[:-2]
            elif compName.find("-") > 0:
                flds = compName.split("-")
                if len(flds) > 1:
                    compName = "#".join(flds)

        if compDict.has_key(compName):
            return compDict[compName]

        raise ValueError("Unknown component \"%s\"" % compName)

    def __listAll(self):
        ids = self.__cnc.rpc_runset_list_ids()
        compDict = self.__cnc.rpc_component_list()
        comps = self.__cnc.rpc_component_list_dicts(compDict.values())

        if len(comps) > 0:
            print "Components:"
            self.__printComponents(comps, "  ")
            if len(ids) > 0:
                print

        if len(ids) > 0:
            numIds = len(ids)
            for i in range(numIds):
                rsid = ids[i]
                if i > 0: print
                state = self.__cnc.rpc_runset_state(rsid)
                print "Runset #%d: %s" % (rsid, state)

                rs = self.__cnc.rpc_runset_list(rsid)
                self.__printComponents(rs, "  ")

    def __printComponentDetails(self, idList=None):
        if idList is None:
            info = self.__cnc.rpc_component_connector_info()
        else:
            info = self.__cnc.rpc_component_connector_info(idList)
        print "Details:"
        for cdict in info:
            print "  #%s: %s#%d" % (cdict["id"], cdict["compName"],
                                    cdict["compNum"])
            if cdict.has_key("conn"):
                for conn in cdict["conn"]:
                    print "    %s *%d %s" % (conn["type"], conn["numChan"],
                                             conn["state"])
            elif cdict.has_key("error"):
                print "    %s" % cdict["error"]
            else:
                print "    Unknown error"

    def __printComponents(self, comps, indent):
        for cdict in comps:
            print "%s#%d: %s#%d (%s)" % \
                  (indent, cdict["id"], cdict["compName"],
                   cdict["compNum"], cdict["state"])

    def __runCmdBean(self, args):
        "Get bean data"
        if len(args) == 0:
            print >> sys.stderr, "Please specify a component.bean.field"
            return

        compDict = self.__cnc.rpc_component_list()

        for c in args:
            bflds = c.split(".")

            if compDict.has_key(bflds[0]):
                compName = bflds[0]
                compId = compDict[compName]
            else:
                try:
                    compId = int(bflds[0])
                except ValueError:
                    compId = None

                compName = None
                if compId is not None:
                    for c in compDict.keys():
                        if compDict[c] == compId:
                            compName = c
                            break

                if compName is None:
                    print >> sys.stderr, "Unknown component \"%s\"" % bflds[0]

            if len(bflds) == 1:
                beanList = self.__cnc.rpc_component_list_beans(compId)

                print "%s beans:" % compName
                for b in beanList:
                    print "    " + b

                return

            beanName = bflds[1]
            if len(bflds) == 2:
                fldList = \
                    self.__cnc.rpc_component_list_bean_fields(compId, beanName)

                print "%s bean %s fields:" % (compName, beanName)
                for f in fldList:
                    print "    " + f

                return

            fldName = bflds[2]
            if len(bflds) == 3:
                val = self.__cnc.rpc_component_get_bean_field(
                    compId, beanName, fldName)
                print "%s bean %s field %s: %s" % \
                    (compName, beanName, fldName, val)

                return

            print >> sys.stderr, "Bad component.bean.field \"%s\"" % c

    def __runCmdList(self, args):
        "List component info"
        if len(args) == 0:
            self.__listAll()
            return

        compDict = None
        idList = []
        for cstr in args:
            if cstr == "*":
                idList = None
                break

            try:
                id = int(cstr)
            except ValueError:
                if compDict is None:
                    compDict = self.__cnc.rpc_component_list()

                try:
                    id = self.__findComponentId(compDict, cstr)
                except ValueError:
                    print >> sys.stderr, "Unknown component \"%s\"" % cstr
                    continue

            idList.append(id)

        self.__printComponentDetails(idList)

    def do_bean(self, line):
        "Get bean data"
        try:
            self.__runCmdBean(line.split())
        except:
            traceback.print_exc()

    def do_EOF(self, line):
        print
        return True

    def do_list(self, line):
        "List component info"
        try:
            self.__runCmdList(line.split())
        except:
            traceback.print_exc()

    def do_ls(self, args):
        "List component info"
        return self.do_list(args)
示例#7
0
    def __init__(self):
        self.__cnc = RPCClient("localhost", DAQPort.CNCSERVER)

        cmd.Cmd.__init__(self)

        self.prompt = "> "
示例#8
0
        print '%s  #%d %s#%d at %s:%d M#%d %s' % \
            (indent, c[0], c[1], c[2], c[3], c[4], c[5], c[6])


if __name__ == "__main__":
    ver_info = "%(filename)s %(revision)s %(date)s %(time)s %(author)s " \
               "%(release)s %(repo_rev)s" % get_version_info(SVN_ID)
    usage = "%prog [options]\nversion: " + ver_info
    p = optparse.OptionParser(usage=usage, version=ver_info)

    p.add_option("-v", "--verbose", action="store_true", dest="verbose")
    p.set_defaults(verbose=False)

    opt, args = p.parse_args()

    cncrpc = RPCClient("localhost", DAQPort.CNCSERVER)

    try:
        nc = cncrpc.rpc_get_num_components()
        lc = cncrpc.rpc_list_components()
        ns = int(cncrpc.rpc_num_sets())
        ids = cncrpc.rpc_runset_listIDs()
    except:
        nc = 0
        lc = []
        ns = 0
        ids = []

    print "CNC %s:%d" % ("localhost", DAQPort.CNCSERVER)

    print "-----------------------"
示例#9
0
 def getRPCClient(self, addr, port):
     return RPCClient(addr, port)
示例#10
0
 def createClient(self, host, port):
     return RPCClient(host, port)
示例#11
0
                 action="store_true", default=False,
                 help="just kill everything with extreme (-9) prejudice")
    opt, args = p.parse_args()

    if opt.quiet and opt.verbose:
        print >>sys.stderr, "Cannot specify both -q(uiet) and -v(erbose)"
        raise SystemExit

    configDir = join(metaDir, 'config')
    logDir    = join(' ', 'mnt', 'data', 'pdaq', 'log').strip()
    logDirFallBack = join(metaDir, 'log')
    dashDir   = join(metaDir, 'dash')

    if not opt.force:
        # connect to CnCServer
        cnc = RPCClient('localhost', DAQPort.CNCSERVER)

        # Get the number of active runsets from CnCServer
        try:
            numSets = int(cnc.rpc_runset_count())
        except:
            numSets = None

        if numSets is not None and numSets > 0:
            inactiveStates = (RunSetState.READY, RunSetState.IDLE,
                              RunSetState.DESTROYED, RunSetState.ERROR)

            active = 0
            runsets = {}
            for id in cnc.rpc_runset_list_ids():
                runsets[id] = cnc.rpc_runset_state(id)
示例#12
0
if __name__ == "__main__":
    ver_info = "%(filename)s %(revision)s %(date)s %(time)s %(author)s " \
               "%(release)s %(repo_rev)s" % get_version_info(SVN_ID)
    usage = "%prog [options]\nversion: " + ver_info
    p = optparse.OptionParser(usage=usage, version=ver_info)

    p.add_option("-n", "--numeric", dest="numeric",
                 action="store_true", default=False,
                 help="Verbose listing uses IP addresses instead of hostnames")
    p.add_option("-v", "--verbose", dest="verbose",
                 action="store_true", default=False,
                 help="Print detailed list")

    opt, args = p.parse_args()

    cncrpc = RPCClient("localhost", DAQPort.CNCSERVER)

    try:
        nc = cncrpc.rpc_component_count()
        lc = cncrpc.rpc_component_list_dicts([], False)
        ns = cncrpc.rpc_runset_count()
        ids = cncrpc.rpc_runset_list_ids()
        versInfo = cncrpc.rpc_version()
        vers = " (%s:%s)" % (versInfo["release"], versInfo["repo_rev"])
    except:
        nc = 0
        lc = []
        ns = 0
        ids = []
        vers = ""
示例#13
0
    if not exists(logDir):
        if not opt.dryRun:
            try:
                mkdir(logDir)
            except OSError, (errno, strerror):
                if opt.verbose:
                    print "Problem making log dir: '%s' (%s)" % (logDir, strerror)
                    print "Using fallback for logDir: %s" % (logDirFallBack)
                logDir = logDirFallBack
                if not exists(logDir): mkdir(logDir)
    else:
        system('rm -f %s' % join(logDir, 'catchall.log'))

    if not opt.force:
        # connect to CnCServer
        cncrpc = RPCClient('localhost', DAQPort.CNCSERVER)

        # Get the number of active runsets from CnCServer
        try:
            numSets = int(cncrpc.rpc_num_sets())
        except:
            numSets = None

        if numSets is not None and numSets > 0:
            daqrpc = RPCClient("localhost", DAQPort.DAQRUN)
            try:
                state  = daqrpc.rpc_run_state()
            except:
                state = "DEAD"

            deadStates = ("DEAD", "ERROR", "STOPPED")
示例#14
0
    op.add_option("-l",
                  "--list",
                  dest="list",
                  action="store_true",
                  default=False,
                  help="List active runset IDs")
    op.add_option("-L",
                  "--list-flags",
                  dest="listFlags",
                  action="store_true",
                  default=False,
                  help="List debugging flags")

    opt, args = op.parse_args()

    rpc = RPCClient("localhost", DAQPort.CNCSERVER)

    if opt.list:
        try:
            idList = rpc.rpc_runset_list_ids()
            print "Run set IDs:"
            for i in idList:
                print "  %d" % i
        except socket.error, err:
            print >> sys.stderr, "Cannot connect to CnCServer"

    if opt.listFlags:
        keys = RunSetDebug.NAME_MAP.keys()
        keys.sort()
        print "Debugging flags:"
        for k in keys: