Exemplo n.º 1
0
def checkMsg(msg, typeCheck=None):
    """Checks if the return is an error, if it is, it will handle it. If not 
    then it will check it against the provided type. If is not the valid type 
    it will print it right then and there. If it IS the valid type it will 
    return it.
    """
    msg = strToMessage(msg)
    if msg is None: 
        print("ERROR: Is the Daemon running?")
        sys.exit(1)
    
    if msg.getType() == ERROR_MSG_TYPE:
        print("ERROR:",msg.getValue())
        sys.exit(1)
    elif typeCheck is None or typeCheck is type(msg.getValue()):
        return msg.getValue()
    else:
        print(msg.getValue())
Exemplo n.º 2
0
 def receiver(self):
     """ Runs the receiving portion of the interface. """
     from empbase.comm.messages import strToMessage
     
     #LATER: Add security to this portion. Adjust message handling for privilege level?
 
     logging.debug("starting interface comm")
     self._socket.setblocking(True)
     try:
         while 1:
             msg = self._socket.recv()
             if not msg: break
             else: self.router.sendMsg(strToMessage(msg))
     except Exception as e: 
         logging.error("interface died because: %s"%e)
     finally:
         logging.debug("ending interface comm")
         self.router.rmInterface(self.ID)
         self.close()
Exemplo n.º 3
0
 def startRouter(self, triggermethod=lambda:False):
     """ This is the thread that runs and pushes messages everywhere. """
     
     logging.debug("ComRouter thread has started")
     while triggermethod():
         try:
             if self._msg_queue.empty():raise queue.Empty
             msg = self._msg_queue.get() #remove and return a message
             
             if isinstance(msg, str): 
                 msg = strToMessage(msg)
             elif msg is None or not isinstance(msg, Message): 
                 continue
             
             logging.debug("destination: %s"%msg.getDestination())
             
             # if the destination is not "registered" but its a known type
             if msg.getDestination() == "" or msg.getDestination() == None:
                 # Check if the message type is an alert, if it is, then send it
                 # to all interfaces and alerters. We keep this functionality for
                 # possible use in Chat programs or quick universal relays. But
                 # actual "Alerts" are now called Events and are managed by the
                 # EventManager.
                 if msg.getType() == ALERT_MSG_TYPE:
                     for id in list( self._routees.keys()):
                         logging.debug("sending alert to %s: %s"% (id, msg))
                         _,ref = self._routees.get(id)
                         if isinstance(ref, Interface):
                             Thread(target=ref.handle_msg, args=(msg,)).start()
                         # Notice, alarms don't get the message.
                         
                 # if not send it to the daemon to handle.
                 else:
                     self.__sendToDaemon(msg)
                         
             
             elif self.isRegistered(msg.getDestination()):
                 if msg.getDestination() == "daemon" or msg.getDestination() == None:
                     self.__sendToDaemon(msg)
                     continue
                 # if its registered, it could be a routee or an attachment.
                 if msg.getType() == COMMAND_MSG_TYPE:
                     cmds = self._attachments.getCommands(msg.getDestination())
                     if cmds is not None:#we can run the command and send the result.
                         found = False
                         for cmd in cmds:
                             if cmd == msg.getValue():
                                 found = True
                                 Thread(target=self._cmdrun, args=msg.get("args"),
                                        kwargs={"cmd":cmd, "dest":msg.getSource(),
                                                "source":msg.getDestination()}).start()
                         if not found:
                             self.sendMsg(makeErrorMsg("Command does not exist.",msg.getDestination(), msg.getSource() ))
                         continue   
                         
                 #ok to send since its been registered, but is a routee
                 ref = self._routees.get(msg.getDestination(),None)
                 if ref is not None:
                     logging.debug("sending message: %s" % msg)
                     Thread(target=ref.handle_msg, args=(msg,)).start()
                 else: #send to daemon.
                     self.__sendToDaemon(msg)
             
             # if we don't know how to handle the message, log and discard it. oh well.
             else:
                 logging.warning("I don't know who %s is, msg=%s" % 
                                 (msg.getDestination(), str(msg.getValue())))
                 
         except queue.Empty: pass
         except Exception as e:
             logging.exception(e)
 
         ## then we sleep for a while. This is randomized because we don't really know
         ## the speed at which messages are being sent. We could write a method to adapt
         ## to the internal rate, later. But currently randomizing provides a better 
         ## compensation than a constant time factor.
         if not self._msg_queue.empty(): continue
         try: time.sleep(random.random())
         except: pass
         
     #when closing, it doesn't need to clean anything, just die and 
     #log about it
     logging.debug("ComRouter thread has died")
     
 
 
     
Exemplo n.º 4
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.
Exemplo n.º 5
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