Esempio n. 1
0
def main():
    parser = setupParser()
    args = parser.parse_args()
    #handle the commands given
    if len(sys.argv) == 1:
        print("Usage:",__simple__,"\n\nType 'emp -h' for some help.")
        return
    
    #print(args)
    if args.help: help()
    elif args.i:
        from interface.empcurse import interactiveMode
        interactiveMode()
    else:
        try:
            # we will be communicating with the daemon
            commport = EmpDaemon().getComPort()
            if commport is None: print("Error: Daemon isn't running!");return
            
            daemon = DaemonClientSocket(port=commport)
            daemon.connect()
            msg = strToMessage(daemon.recv())
            if msg is None or msg.getValue() != "proceed": 
                print("Error: Couldn't connect to the daemon.")
                return
            
            myID = msg.getDestination()
                
            #what are we communicating    
            if args.list:
                daemon.send(makeCommandMsg("alarms",myID))
                alerters = checkMsg(daemon.recv())
                daemon.send(makeCommandMsg("plugs",myID))
                plugs = checkMsg(daemon.recv())
            
                #print the list all pretty like:
                print("Attached targets and their temp IDs:") #TODO: make option to make it nopretty?
                print("   Plugs:")
                for k in plugs.keys():
                    print("     %s" % plugs[k][1])
                    print("        Name: %s"%plugs[k][0])
                    print("        ID: %s"%k)
                print("\n   Alarms:")
                for k in alerters.keys():
                    print("     %s" % alerters[k][1])
                    print("        Name: %s"%alerters[k][0])
                    print("        ID: %s"%k)
                print()
                
        
            elif args.all: 
                daemon.send(makeCommandMsg("help",myID, args=["all"]))
                cmds = checkMsg(daemon.recv(), dict)
                for target in cmds.keys():
                    if args.pretty: print("%s"%target)
                    if len(cmds[target].keys()) > 0:
                        if args.pretty:
                            print("Commands:")
                            fancyprint(cmds[target])
                        else: print(str(cmds[target]))
                    else: print("No Commands available!")
                    print()
                    
            else:
                # now we can start parsing targets and figuring out what to do with them
                if args.tcmds:
                    daemon.send(makeCommandMsg("help",myID, args=args.target))
                    cmds = checkMsg(daemon.recv(), dict)
                    if args.pretty: 
                        print("%s Commands: "%args.target[0])
                        fancyprint(cmds)
                    else: print(str(cmds))
                elif args.ask:
                    daemon.send(makeCommandMsg("help",myID, args=args.target))
                    cmds = checkMsg(daemon.recv(), dict)
                    cmdfound = False
                    for cmd in cmds.keys():
                        if args.ask[0] == cmd:
                            if args.pretty: print("  %s  -%s"%(cmd,cmds[cmd]))
                            else: print("{'%s': '%s'}"%(cmd,cmds[cmd]))
                            cmdfound = True
                            break
                            
                    if not cmdfound:
                        if args.pretty: print("The target does not have that command.")
                        else: print("ERROR: No command")
                else:
                    if len(args.command) < 1:
                        print("Usage: ",__usage__)
                        daemon.send(makeCommandMsg("help", myID, args=args.target))
                        cmds = checkMsg(daemon.recv(), dict)
                        print("\n%s Commands: "%args.target[0])
                        fancyprint(cmds)
                    else:
                        daemon.send(makeCommandMsg(args.command[0], myID, dest=args.target[0], args=args.command[1:]))
                        
                        if not args.nowait:
                            result = checkMsg(daemon.recv())
                            # since this is a general case interface, we don't really know 
                            # how to interpret the result of an argument. But this can
                            # be utilized in a script or a higher level interface. if you 
                            # want to call smtg through your program be sure you can 
                            # handle JSON 
                            if args.pretty: fancyprint(result)
                            # No-pretty is the default, but its an argument just to specify 
                            # if the command line is placed in scripts.
                            else: print(result) 
                        else: print("success")
            
            # now lets close the port to indicate that we are finished.
            daemon.close()
        except:
            if not args.nowait: raise
            else: print("error") # scripts can check for this.
Esempio n. 2
0
def main():
    parser = OptionParser( usage=__usage__, 
                           version="Version: empd "+__version__,
                           description=__description__ )
    parser.add_option("--start",action="store_const", const=0, dest="state", 
                      help="start the EMP daemon")
    parser.add_option("--stop", action="store_const", const=1, dest="state",  
                      help="stop a running EMP daemon, may take some time to \
                       close all plug-ins")
    parser.add_option("--restart", action="store_const", const=2, dest="state", 
                      help="restart a running EMP daemon")
    parser.add_option("--status", action="store_const", const=1, dest="status",
                      help="show the status of the currently running EMP \
                      daemon")
    parser.add_option("--startup", action="store_const", const=3, dest="state",
                      help="Use this in your start-up/boot scripts to auto-launch \
                      empd.")    
    ### the special daemonizer token. see Daemon class for more info ###
    parser.add_option("-d", nargs=0, dest="daemonize", help=SUPPRESS_HELP)
    
    # if there are no command line args, then print usage
    if len(sys.argv[1:]) == 0:
        parser.print_usage()
        print("Use '-h' for more help and a list of options.")
        return
    
    ## parse the command line arguments ##
    (options, args) = parser.parse_args()
    if len(args) > 1:
        print("Invalid argument structure. Use '-h' for help.\n")
        return
    

    try: ## find out what the user wants to do. ##
        
        # user wants to run some functions on the daemon.
        # First we have to construct it to talk to it,
        # which of course takes some time.
        if options.state != None: 
            #we want to mess with the daemon, so construct it
            if len(args) == 1: daemon = EmpDaemon(configfile=args[0])
            else: daemon = EmpDaemon()

            # then call functions on it.
            if options.state == 0:
                daemon.start()
            elif options.state == 1:
                daemon.stop()
            elif options.state == 2:
                daemon.restart()
            elif options.state == 3:
                daemon.startup()
            
        

        # all the user wants to do is ask how the daemon is doing
        # so open up a port and ask it for some information.
        elif options.status != None:
            try:
                daemon = EmpDaemon()
                p = daemon.getComPort()
                if p is not None:
                    socket = DaemonClientSocket(port=p)
                    socket.connect()
                    msg = strToMessage(socket.recv())
                    logging.debug("empd got back: %s"%msg)
                    if msg.getValue() == "proceed":# it connected
                        myId= msg.getDestination()
                        socket.send(makeCommandMsg("status", myId))
                        print(strToMessage(socket.recv()).getValue(),"\n")
                        socket.close()
                    else: print("ERROR: Daemon rejected connection attempt.")
                else: print("ERROR: Daemon is not running.")
            except Exception as e:
                print("ERROR: couldn't communicate with daemon:", e)
                
        # The process has been called via a background thread so 
        # it is ok to just run the daemon, we are one!!
        # see smtg.daemon.daemon.Daemon for more information.
        elif options.daemonize != None:
            #we want to mess with the daemon, so construct it
            if len(args) == 1: daemon = EmpDaemon(configfile=args[0])
            else: daemon = EmpDaemon()
            daemon._run()            

    except Exception as e:
        print("ERROR:",e)
        raise e