def main(options, args):
    
    # Make top-level logger.
    logger = ssdlog.make_logger('ut1-utc', options)

    today = time.strftime("%Y%M%d", time.localtime())

    oldfile = os.path.join(dbarea, filename)
    bakfile = os.path.join(dbarea, filename + '.bak')
    newfile = os.path.join(dbarea, filename + '.' + today)

    res = os.system("wget --tries=5 -O %s %s" % (newfile, options.url))
    if res == 0:
        try:
            os.remove(bakfile)
        except OSError:
            pass

        try:
            os.rename(oldfile, bakfile)
            os.rename(newfile, oldfile)

        except Exception, e:
            logger.error("Failed to ftp ut1-utc file: %s" % url)
            logger.error(str(e))
            sys.exit(1)
Exemplo n.º 2
0
def main(options, args):

    logname = 'summit_ups'
    logger = ssdlog.make_logger(logname, options)

    power_off = 'obcpPoff'
    power_off = os.path.join(options.dir, power_off)

    try:
        os.remove(power_off)
    except Exception as e:
        logger.warn('warn: is %s there??  %s' % (power_off, e))

    snmp = SnmpTrap(power_off, logger)

    try:
        transportDispatcher = AsynsockDispatcher()
        transportDispatcher.registerTransport(
            udp.domainName,
            udp.UdpSocketTransport().openServerMode(
                ('%s' % options.mgrhost, 162)))
        transportDispatcher.registerRecvCbFun(snmp.trap_cb)
        transportDispatcher.jobStarted(1)  # this job would never finish
        transportDispatcher.runDispatcher()
    except KeyboardInterrupt:
        logger.info('keyboard interrupting...')
        snmp.ev_quit.set()
    except Exception as e:
        logger.error('error: %s' % e)
        snmp.ev_quit.set()
        logger.error('error: snmp trap terminated..')
Exemplo n.º 3
0
def main(options, args):

    # Create top level logger.
    logger = ssdlog.make_logger('plot', options)

    class AppWindow(QtGui.QMainWindow):
        def __init__(self):
            QtGui.QMainWindow.__init__(self)
            self.setAttribute(QtCore.Qt.WA_DeleteOnClose)

            self.resize(350, 350)

            self.main_widget = QtGui.QWidget()
            l = QtGui.QVBoxLayout(self.main_widget)
            l.setMargin(0)
            l.setSpacing(0)

            #sc = MyStaticMplCanvas(self.main_widget, width=5, height=5, dpi=None)

            if options.mode == 'ag':
                plot = AgPlot(self.main_widget, logger=logger)
                #aplot=AOPlot1(self.main_widget, logger=logger)
            elif options.mode == 'fmos':
                plot = FmosPlot(self.main_widget, logger=logger)
            elif options.mode == 'nsopt' or options.mode == 'hsc':
                plot = TwoGuidingPlot(self.main_widget, logger=logger)
            elif options.mode == 'nsir':
                plot = NsIrPlot(self.main_widget, logger=logger)
            else:
                logger.error('error: mode=%s' % options.mode)
                sys.exit(1)
            #l.addWidget(sc)
            #zoomin = QtGui.QPushButton(QtGui.QIcon.fromTheme('zoom-in'), 'Zoom In')
            l.addWidget(plot)
            ##l.addWidget(aplot)
            ##l.addWidget(zoomin)
            timer = QtCore.QTimer(self)
            QtCore.QObject.connect(timer, QtCore.SIGNAL("timeout()"),
                                   plot.tick)
            timer.start(options.interval)

            self.main_widget.setFocus()
            self.setCentralWidget(self.main_widget)

            self.statusBar().showMessage("%s starting..." % options.mode, 5000)
            #print options

        def closeEvent(self, ce):
            self.close()

    try:
        qApp = QtGui.QApplication(sys.argv)
        aw = AppWindow()
        aw.setWindowTitle("%s" % progname)
        aw.show()
        sys.exit(qApp.exec_())

    except KeyboardInterrupt, e:
        logger.warn('keyboard interruption....')
        sys.exit(0)
def main(options, args):

    logger = ssdlog.make_logger('launcher', options)

    # Create the scanner
    scanner = launcherScanner(logger=logger, debug=0, lextab=lex_tab_module)
    # Create the parser
    parser = launcherParser(scanner,
                            logger=logger,
                            debug=1,
                            tabmodule=yacc_tab_module)

    if len(args) > 0:
        for filename in args:
            try:
                if options.action == 'scan':
                    res = scanner.scan_file(filename)
                    if (res.tokens != None) and options.verbose:
                        printTokens(res.tokens)

                elif options.action == 'parse':
                    res = parser.parse_file(filename)
                    if (res != None) and options.verbose:
                        pprint.pprint(res)

                else:
                    raise ScanError("I don't understand action='%s'" %
                                    (options.action))

            except (ScanError, ParseError), e:
                # Print error message and continue to next file
                logger.error(str(e))
Exemplo n.º 5
0
def main(options, args):
    """Main program.  _options_ is an OptionParser object that holds parsed
    options.  _args_ is a list of the remaining non-option parameters.
    """

    # Create top level logger.
    logger = ssdlog.make_logger('INSintTester', options)

    # Only import and initialize remoteObjects if we are trying to
    # use Gen2 services
    if options.monitor or options.statussvc:
        ro.init()

    # Create app and display
    app = INSintTester(options, logger)
    app.show()

    # TODO: find a better way to keep these dialogs suppressed at
    # startup.
    sw = app.widgets['setup_obcp']
    sw.window.hide()
    sw = app.widgets['dialog_filechooser']
    sw.window.hide()

    # Enter GUI event-processing loop.
    while not app.ev_mainquit.isSet():
        # Process X events
        while gtk.events_pending():
            gtk.main_iteration()

        # Sleep and let other threads run
        time.sleep(0.25)
Exemplo n.º 6
0
def main(options, args):

    # Create top level logger.
    logger = ssdlog.make_logger('bootmgr', options)

    # Create the boot manager
    bootmgr = BootManager(logger,
                          mgrport=options.mgrport,
                          monsvc=options.monitor,
                          confpfx=options.confpfx)

    # Show possible configurations
    # NOTE: this won't work unless a module is loaded
    if options.showconfigs:
        print "Available configurations: %s" % str(bootmgr.getConfigs())
        sys.exit(0)

    if options.configname:
        # Try to load the specified config
        try:
            bootmgr.loadConfig(options.configname)

        except BootError, e:
            print str(e)
            print "Available configurations: %s" % str(bootmgr.getConfigs())
            sys.exit(1)
Exemplo n.º 7
0
def main(options, args):

    # Create top level logger.
    logger = ssdlog.make_logger('hskymon', options)

    ### Start the legacy viewer ###

    # Flags that record what has been started, to effect an orderly
    # shutdown--see quit().  We declare variables here so that quit
    # is closed in their lexical scope.
    viewproc = None

    # This function is called if we receive a signal, terminate the app,
    # etc.
    def quit(exitcode):
        if viewproc:
            logger.info("Stopping hskymon viewer.")
            try:
                viewproc.killpg()

            except Exception, e:
                # If user used a normal exit mechanism from GUI then
                # trying to kill it here raises an error.
                if str(e) != "[Errno 3] No such process":
                    logger.error("Error stopping subprocesses: %s" % str(e))
                    exitcode = 1

        # logger.close() ??
        sys.exit(exitcode)
def main(options, args):

    # Create top level logger.
    logger = ssdlog.make_logger('sk_skcompile', options)

    if options.skdir:
        skdir = options.skdir
    else:
        try:
            skdir = os.path.join(os.environ['PYHOME'], 'SOSS', 'SkPara', 'sk')
        except KeyError:
            print "Please set your PYHOME environment variable"
            print "or specify the --skdir option"
            sys.exit(1)

    sk_bank = sk_interp.skBank(skdir, logger=logger)

    compiler = SkCompiler(sk_bank, logger, append_mode=options.appendmode)

    obe_id = args[0].upper()
    obe_mode = args[1].upper()

    for cmd in args[2:]:
        print compiler.compile_skeleton(obe_id, obe_mode, cmd)
        compiler.append_mode = True

    return 0
Exemplo n.º 9
0
def main(options, args):

    logname = 'star_list'
    # Create top level logger.
    logger = ssdlog.make_logger(logname, options)

    try:
        ra = float(options.ra)
        dec = float(options.dec)
        fov = float(options.fov)
        uppermag = float(options.uppermag)
        lowermag = float(options.lowermag)
    except Exception as e:
        print 'need args.  %s' % str(e)
        sys.exit(1)

    if lowermag >= uppermag:
        print 'upper mag should be greater than lower mag'
        sys.exit(1)

    catalog = options.catalog

    if options.dbhost:
        dbhost = options.dbhost
    else:
        try:
            dbhost = os.environ['DBHOST']
        except KeyError, e:
            dbhost = 'g2db'
Exemplo n.º 10
0
def main(options, args):

    logname = 'sendlog'
    logger = ssdlog.make_logger(logname, options)

    ro.init()
    tm = ro.remoteObjectProxy('taskmgr0')
    tm.loadModule('LOGTask')
    tm.addAllocs(['STARS'])

    today = datetime.date.today()
    one_day = datetime.timedelta(days=1)
    yesterday = today - one_day

    if not options.fromdate:
        obs_time_from = '%s 17:00:00' % (yesterday)
        day_time_from = '%s 08:00:00' % (yesterday)

    else:
        obs_time_from = options.fromdate
        day_time_from = options.fromdate

    if not options.todate:
        obs_time_to = '%s 08:00:00' % (today)
        day_time_to = '%s 17:00:00' % (yesterday)

    else:
        obs_time_to = options.todate
        day_time_to = options.fromdate

    try:
        logdir = os.environ['LOGHOME']
    except KeyError, e:
        logdir = '/gen2/logs'
Exemplo n.º 11
0
def main(options, args):
    """Main program.  Set up the logger, create a dbtool object and invoke
    a method on it.
    """

    # Create top level logger.
    logger = ssdlog.make_logger('dbtool', options)

    if not options.target:
        logger.error("Please specify a --target !")
        return

    dbtools = []
    for target in options.target.split(','):
        try:
            dbtools.append(DbTool(logger, dbhosts[target]))

        except KeyError:
            logger.error("--target must include one or more of %s" % (
                str(dbhosts.keys())))
            return

    try:
        for dbtool in dbtools:
            dispatch(dbtool, options, logger)

    except (Error, SOSSdb.SOSSdbError), e:
        logger.error(str(e))
        sys.exit(1)
def main(options, args):
    # Create top level logger.
    logger = ssdlog.make_logger('jplObjectDBSearch', options)
    
    targetID = jplObjectDBSearch(options.targetName, options.targetID, logger)
    logger.info('targetID %s' % targetID)
    print 'targetID %s' % targetID
Exemplo n.º 13
0
    def setUp(self):
        try:
            pyhome = os.environ['PYHOME']
            cfgDir = os.path.join(pyhome, 'cfg', 'alarm')
        except:
            cfgDir = '.'
        default_alarm_cfg_file = os.path.join(cfgDir, '*.yml')

        from optparse import OptionParser
        usage = "usage: %prog [options]"
        optprs = OptionParser(usage=usage, version=('%%prog'))

        optprs.add_option("-f",
                          "--configfile",
                          dest="configfile",
                          default=default_alarm_cfg_file,
                          help="Specify configuration file")
        ssdlog.addlogopts(optprs)

        (options, args) = optprs.parse_args(sys.argv[1:])

        # Create top level logger.
        logger = ssdlog.make_logger('module_test', options)

        dummyDatafileLock = None

        try:
            self.svConfig = StatusVar.StatusVarConfig(options.configfile,
                                                      dummyDatafileLock,
                                                      logger)
        except Exception, e:
            logger.error('Error opening configuration file(s): %s' % str(e))
def start(options):
    # Create logger 
    logger = ssdlog.make_logger('ltcs-remote', options)

    # Initialize remote objects service, necessary before any
    ro.init()

    svc = LTCSRemoteService(options, logger, usethread=True)
Exemplo n.º 15
0
def main(options, args):

    logger = ssdlog.make_logger('test', options)

    ro.init()

    ev_quit = threading.Event()
    queue = Queue.Queue()

    # make a name for our monitor
    myMonName = options.name

    # monitor channels we are interested in
    channels = options.channels.split(',')

    # Create a local monitor
    mymon = Monitor.Monitor(myMonName, logger, numthreads=20)

    # Make our callback functions
    m = Make_cb(logger=logger,
                monitor=mymon,
                queue=queue,
                monpath=options.monpath,
                watch_execs=options.watch_execs,
                history=options.history)

    # Subscribe our callback functions to the local monitor
    mymon.subscribe_cb(m.anon_arr, channels)

    server_started = False
    try:
        # Startup monitor threadpool
        mymon.start(wait=True)
        # start_server is necessary if we are subscribing, but not if only
        # publishing
        mymon.start_server(wait=True, port=options.port)
        server_started = True

        # subscribe our monitor to the central monitor hub
        mymon.subscribe_remote(options.monitor, channels, ())

        while not ev_quit.isSet():
            try:
                (path, tree, time) = queue.get(block=True, timeout=1.0)

                printTree(path, tree, time)

            except Queue.Empty:
                continue

            except KeyboardInterrupt:
                logger.error("Received keyboard interrupt!")
                ev_quit.set()

    finally:
        if server_started:
            mymon.stop_server(wait=True)
        mymon.stop(wait=True)
Exemplo n.º 16
0
def main(options, args):

    # Create top level logger.
    logger = ssdlog.make_logger('resource', options)

    class AppWindow(QtGui.QMainWindow):
        def __init__(self):
            super(AppWindow, self).__init__()
            self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
            self.w = 450
            self.h = 25
            self.init_ui()

        def init_ui(self):
            self.resize(self.w, self.h)

            self.main_widget = QtGui.QWidget()
            l = QtGui.QVBoxLayout(self.main_widget)
            l.setMargin(0)
            l.setSpacing(0)

            if options.mode == 'water':
                r = WaterStorageDisplay(parent=self.main_widget, logger=logger)
            elif options.mode == 'oil':
                r = OilStorageDisplay(parent=self.main_widget, logger=logger)
            else:
                r = ResourceDisplay(parent=self.main_widget, logger=logger)

            l.addWidget(r)

            timer = QtCore.QTimer(self)
            QtCore.QObject.connect(timer, QtCore.SIGNAL("timeout()"), r.tick)
            timer.start(options.interval)

            self.main_widget.setFocus()
            self.setCentralWidget(self.main_widget)
            self.statusBar().showMessage("%s starting..." % options.mode,
                                         options.interval)

        def closeEvent(self, ce):
            self.close()

    try:
        qApp = QtGui.QApplication(sys.argv)
        aw = AppWindow()
        print 'state'
        #state = State(logger=logger)
        aw.setWindowTitle("%s" % progname)
        aw.show()
        #state.show()
        print 'show'
        sys.exit(qApp.exec_())

    except KeyboardInterrupt, e:
        logger.warn('keyboard interruption....')
        sys.exit(0)
Exemplo n.º 17
0
def main(options, args):

    # Create top level logger.
    logger = ssdlog.make_logger('names', options)

    try:
        myhost = ro.get_myhost()

    except Exception, e:
        raise nameServiceError("Can't get my own hostname: %s" % str(e))
Exemplo n.º 18
0
def main(options, args):
    logger = ssdlog.make_logger('test', options)

    print "mode<%s>" % (options.mode)

    if not options.mode == 'test':

        ro.init()
        # make a name for our monitor

        #myMonName = ('testmon-%d' % os.getpid())
        myMonName = ('testmon')
        # monitor channels we are interested in
        channels = options.channels.split(',')

        # Create a local monitor
        mymon = Monitor.Monitor(myMonName, logger, numthreads=4)

        # Startup monitor threadpool
        mymon.start(wait=True)
        # start_server is necessary if we are subscribing, but not if only
        # publishing
        mymon.start_server(port=options.port, wait=True)
        #mymon.start_server(wait=True)

        # Make our callback functions
        m = Make_cb(logger=logger, monitor=mymon)

        # Subscribe our callback functions to the local monitor
        mymon.subscribe_cb(m.anon_arr, channels)

        try:
            # subscribe our monitor to the central monitor hub
            #monitor = ro.remoteObjectProxy(options.monitor)
            mymon.subscribe_remote(options.monitor, channels, ())
        except:
            logger.error("subscribe to the central monitor faild")

    else:
        feed_test_data()
        mymon = None

    try:

        gtk.gdk.threads_init()
        task_view = TreeView(logger)
        task_view.start_updating()
        gtk.main()
        stop_service(task_view, mymon=mymon)
        print 'GUI END'

    except KeyboardInterrupt:
        #gtk.main_quit()
        stop_service(task_view, mymon=mymon)
Exemplo n.º 19
0
def main(options, args, ui):

    myhost = SOSSrpc.get_myhost(short=False)

    basename = 'g2disp-%s' % (myhost.replace('.', '_'))
    logger = ssdlog.make_logger(basename, options)

    # Make our callback object
    mobj = g2Disp(logger=logger, basename=basename)

    ui.ui(mobj)
Exemplo n.º 20
0
def main(options, args):
    logger = ssdlog.make_logger('test', options)

    if options.mode == 'test':
        print 'test mode'
        feed_test_data()
        mymon = None

    else:

        ro.init()
        # make a name for our monitor

        #myMonName = ('testmon-%d' % os.getpid())
        myMonName = ('testmon')
        # monitor channels we are interested in
        channels = options.channels.split(',')

        # Create a local monitor
        mymon = Monitor.Monitor(myMonName, logger, numthreads=4)

        # Startup monitor threadpool
        mymon.start(wait=True)
        # start_server is necessary if we are subscribing, but not if only
        # publishing
        mymon.start_server(wait=True)

        # Make our callback functions
        m = Make_cb(logger=logger, monitor=mymon)

        # Subscribe our callback functions to the local monitor
        mymon.subscribe_cb(m.anon_arr, channels)

        try:
            # subscribe our monitor to the central monitor hub
            monitor = ro.remoteObjectProxy(options.monitor)
            monitor.subscribe(myMonName, channels, ())
        except:
            logger.error("subscribe to the central monitor faild")

    try:

        app = QtGui.QApplication(sys.argv)
        tv = TreeView()
        tv.start_updating()
        tv.show()
        sys.exit(app.exec_())
        stop_service(tv, mymon=mymon)
        print 'GUI END'

    except KeyboardInterrupt:
        print 'Keyboard'
        #gtk.main_quit()
        stop_service(tv, mymon=mymon)
Exemplo n.º 21
0
def main(options, args):

    logname = 'agsim'
    logger = ssdlog.make_logger(logname, options)

    logger.info('guider sim starting ...')

    app = QApplication(sys.argv)
    gsim = GuiderSim(logger)
    gsim.show()
    app.exec_()
Exemplo n.º 22
0
def main(options, args):

    ro_hosts = options.gen2host.split(',')
    ro.init(ro_hosts)

    svcname = options.svcname
    monname = svcname + '.mon'
    
    # create a real logger if you want logging
    logger = ssdlog.make_logger(svcname, options)

    ev_quit = threading.Event()
    
    # Create a local subscribe object
    myhost = ro.get_myhost(short=True)
    mymon = Monitor.Monitor(monname, logger)

    channels = options.channels.split(',')
    relay = StatusRelay(logger, options.statsvc, options.monitor,
                        mymon, channels)

    # Startup monitor
    mymon.start(wait=True)
    monport = options.monport
    if not monport:
        monport = options.port + 1
    mymon.start_server(wait=True, port=monport)
    threadPool = mymon.get_threadPool()

    svc = ro.remoteObjectServer(svcname=options.svcname,
                                obj=relay, logger=logger,
                                port=options.port,
                                default_auth=None,
                                ev_quit=ev_quit,
                                usethread=False,
                                threadPool=threadPool)
    try:
        relay.update_statusProxy()
        relay.update_monitorFeed()
    
        try:
            print "Press ^C to terminate the server."
            svc.ro_start(wait=True)
            svr_started = True

        except KeyboardInterrupt:
            logger.error("Caught keyboard interrupt!")
            ev_quit.set()
            
    finally:
        logger.info("Shutting down...")
        mymon.unsubscribe_remote('monitor', channels, {})
        mymon.stop_server()
        mymon.stop()
Exemplo n.º 23
0
def main(options, args):

    # Create top level logger.
    logger = ssdlog.make_logger(options.svcname, options)

    # Initialize remote objects subsystem.
    try:
        ro.init()

    except ro.remoteObjectError, e:
        logger.error("Error initializing remote objects subsystem: %s" % str(e))
        sys.exit(1)
Exemplo n.º 24
0
def main(options, args):
    global statusFromGen2, lock

    # Create top level logger.
    logger = ssdlog.make_logger('alarm_monitor', options)

    # Load the status variable configuration
    try:
        svConfig = StatusVar.StatusVarConfig(options.configfile,
                                             persistDatafileLock, logger)
    except Exception, e:
        logger.error('Error opening configuration file(s): %s' % str(e))
        return
Exemplo n.º 25
0
def main(options, args):

    basename = options.svcname
    logger = ssdlog.make_logger(basename, options)

    # Initialize remoteObjects subsystem
    try:
        ro.init()

    except ro.remoteObjectError, e:
        logger.error("Error initializing remote objects subsystem: %s" % \
                     str(e))
        sys.exit(1)
Exemplo n.º 26
0
def main(options, args):

    # Create top level logger.
    logger = ssdlog.make_logger('mgrsvc', options)

    # Get the names of the nodes in this cluster and remove our name.  The
    # result is the list of hosts running name servers that we need to
    # synchronize with.
    try:
        myhost = ro.get_myhost(short=True)

    except Exception, e:
        raise managerSvcError("Can't get my own hostname: %s" % str(e))
Exemplo n.º 27
0
def main(options, args):
    ''' right now, this main is for testing purpose'''

    import starlist
    logname = 'star_selection'
    # Create top level logger.
    logger = ssdlog.make_logger(logname, options)

    sh_keys = {'ra': 10.1, 'dec': 10.0, 'fov': 0.076, 'limitmag': 13.0}
    ag_keys = {
        'ra': 10.0,
        'dec': 20.0,
        'fov': 0.076,
        'probe_ra': 10.0,
        'probe_dec': 20.0,
        'focus': 'CS',
        'ins': 'MOIRCS',
        'probe_r': 0.0,
        'probe_theta': 0.0,
        'probe_x': 0.0,
        'probe_y': 0.0,
        'pa': 0.0,
        'limitmag': 15.0,
        'goodmag': 10.0,
        'fov_pattern': 'STANDARD'
    }

    try:
        catalog = starlist.CatalogSearch(logger)
        starlist = catalog.search_starcatalog(ra=sh_keys['ra'],
                                              dec=sh_keys['dec'],
                                              fov=sh_keys['fov'],
                                              limitmag=sh_keys['limitmag'])

        ss = StarSelection(logger)
        res = ss.select_sh_stars(sh_keys, starlist)

        # for star in res:
        #     print star['name']

        #        starlist=catalog.search_starcatalog(ra=ag_keys['ra'], dec=ag_keys['dec'], fov=ag_keys['fov'], limitmag=ag_keys['limitmag'])
        #        res=ss.select_ag_stars(ag_keys, starlist)

        print 'prefered=%d' % res.get('prefered_num')
        for star in res.get('selected_stars'):
            print star['name'], star['priority']

    except KeyboardInterrupt:
        print 'keyboard interrupting...'
    except Exception as e:
        print 'excpetion %s' % e
Exemplo n.º 28
0
def main(options, args):
    
    svcname = ('ana_menu')

    if not options.logstderr:
        options.logfile='/tmp/ana.log'
        options.loglevel=0

    logger = ssdlog.make_logger(svcname, options)

    try:
        os.chmod(options.logfile,0666)
    except Exception,e:
        logger.warn('warning: changing permission.<%s> ' %(e))
Exemplo n.º 29
0
def main(options,args):
 
    logname = 'email'
    logger = ssdlog.make_logger(logname, options)

    subject='TEST'
    sender='*****@*****.**'
    recipient='*****@*****.**'

    today=datetime.datetime.today()
    msg='%s\nmailing to you...' %today.strftime("%Y-%m-%d %H:%M:%S")

    notify_me(sub=subject, sndr=sender, rcpt=recipient,  msg=msg, logger=logger)
    notify_snmp(msg, logger)
Exemplo n.º 30
0
def main(options, args):

    svcname = options.svcname
    logger = ssdlog.make_logger(svcname, options)
    monchannels = ['statint', 'logs']

    # Initialize remote objects subsystem.
    try:
        ro.init()

    except ro.remoteObjectError, e:
        logger.error("Error initializing remote objects subsystem: %s" %
                     str(e))
        sys.exit(1)