示例#1
0
    def Run(self):
        # ~~~~~~~~~~~ start rem app here ~~~~~~~~~~~~~
        try:
            self.wa = wakit(self.execname, port=self.myport,
                       cmdhandler=self.RecvMessage)
            self.wa.StartServer()
            #print('%s is running wakit' % self.execname)
            
            peeraddr, peerport, peername = self.wa.getPeerID()
            #print 'PeerID: addr=%s, port=%d, name=%s' % (
            #       peeraddr, peerport, peername)
            self.mynick = peername # ie. reporting from this peer
            
            appaddr, appport, appname = self.wa.getAppID()
            print('AppID: addr=%s, port=%s, name=%s' % (
                   appaddr, appport, appname))
            
            while self.quit == False:  # can improve this with a queue
                sleep(1.0)

        except:
            print('Exception happened somewhere ...')
            traceback.print_exc()
        
        finally:
            print('%s is quitting ...' % self.execname)
            self.wa.StopServer()
示例#2
0
 def __init__(self, myport):
 #--------------------------------------------------------------------------
    ''' Init the remote service '''
    self.svcname = os.path.basename(sys.argv[0])
    self.svc = FileCopySvc()
    self.wa =wakit(self.svcname, port=myport, cmdhandler=self.svc.RecvMessage)
    self.svc.wa = self.wa   # svc needs some wakit access
示例#3
0
 def __init__(self, port):
    ''' Init the service app '''
    self.svcname = os.path.basename(sys.argv[0])
    self.gol = Conway()
    self.wa = wakit(self.svcname, port=port, cmdhandler=self.gol.RecvMessage)
    #print('golsvc: self.wa.port is %s' % self.wa.myport)  # debug
    #print('%s is now running wakit' % self.svcname)
    self.gol.wa = self.wa
示例#4
0
 def __init__(self, myport=None):
    ''' Init the service '''
    self.svcname = os.path.basename(sys.argv[0])
    self.svc = AudioServices(self.svcname)
    self.sndDict = {}   # a dictionary (mapping) of keywords to audio files
    self.wa = wakit(self.svcname, port=myport,
                     cmdhandler=self.svc.RecvMessage)
    #print('%s is now running wakit' % self.svcname)
    self.svc.wa = self.wa # svc needs this to send messages
示例#5
0
文件: peer.py 项目: rwniessen/msgkit
   def Run(self):
   #--------------------------------------------------------------------------
      ''' This method is the main app of the peer web-app. After assisting in
      peer startup, it lies dormant until it receives a signal to shut down.
      '''
      try:
         #global MYPORT
         #MYPORT = PEERPORT  # declare this web-app to be a peer
         self.wa = wakit(execname=self.execname, port=PEERPORT,
                         cmdhandler=self.RecvMessage)

         # do configurations as peer ...
         # item are: {ipaddr: peername, ...}
         self.iplist = self.wa.CopyPeerList()

         self.portpool = PortPoolMgr(int(PEERPORT)+1, NUMAPPPORTS)

         self.findallpeersparallel(PEERPORT)

         self.wa.StartServer()
         #print('%s is now running wakit' % self.execname)

         self.peeraddr, peerport, self.peername = self.wa.getPeerID()
         print('PeerID: addr=%s, port=%s, name=%s' %    \
               (self.peeraddr, peerport, self.peername))

         # wait for peer shutdown command cmd=quit
         while True:
            dic = self.msgq.get(True, None)
            # shut down the peer
            break

      except:
         print('Exception happened somewhere ...')
         traceback.print_exc()
      finally:
         sleep(0.5)   # let things settle a bit, then quit
         self.wa.StopServer()
示例#6
0
   def Run(self):
      ''' This is the mainline code of the Special Service Launcher app
      '''
      try:
         self.wa = wakit(self.execname, cmdhandler=self.RecvMessage)
            
         self.wa.StartServer()
         #print('%s is running wakit' % self.execname)

         peeraddr, peerport, peername = self.wa.getPeerID()
         print('PeerID: addr=%s, port=%s, name=%s' %  \
               (peeraddr, peerport, peername))
            
         appaddr, appport, appname = self.wa.getAppID()
         print('AppID: addr=%s, port=%s, name=%s' %   \
               (appaddr, appport, appname))
         
         if self.ssvcid[-3:] == '.py':
            lwa = self.wa.LaunchSvc(appaddr, self.ssvcid)
            if lwa[ISOK] == YES:
               port = lwa[PORT]
               print('%s is running on port %s' % (self.ssvcid, port))
            else:
               print('failed to launch %s, error: ...')
               if MSG in lwa:
                  print(self.wa.hex2s(lwa[MSG]))
         else:
            resp = self.wa.LaunchSpecialSvc(self.ssvcid)
            print(resp)
            if MSG in resp:
               print(self.wa.hex2s(resp[MSG]))
            
      except:
         print(traceback.format_exc())
      finally:
         print('%s is quitting ...\n' % self.execname)
         self.wa.StopServer()
示例#7
0
文件: fcopy.py 项目: rwniessen/msgkit
   def Run(self):
      ''' This is the mainline code of the file copy client app
      '''
      try:
         wa = wakit(self.execname, cmdhandler=self.RecvMessage)

         wa.StartServer()
         #print('%s is now running wakit' % self.execname)
           
         peeraddr, peerport, peername = wa.getPeerID()
         appaddr, appport, appname = wa.getAppID()
         print('AppID: addr=%s, port=%s, name=%s' % (
                appaddr, appport, appname))

         # find the supporting peer
         srcip   = ''  # ip addr of source peer (host)
         dstip   = ''  # ip addr of destination peer (host)

         lss = wa.LaunchSpecialSvc(ssvcid)
         if lss[ISOK] == YES:
            # do a quick check on src & dst peers ...
            srcip = wa.GetPeerAddress(self.srcname)
            dstip = wa.GetPeerAddress(self.dstname)
            if srcip == None:
               raise MyException('source peer %s not found' % self.srcname)
            if dstip == None:
               raise MyException('destination peer %s not found' % self.dstname)

            #cmd = self.cmmd+' '+self.srcname+' '+self.dstname+' '+self.fprefix
            #mtype, mbody = wa.SendMessage(lss.svcpeerip, lss.svcappport,
            #                             'apps', cmd)
            dbgON()    # debug
            # send file copy service the command
            cmd = '%s=%s %s=%s %s=%s %s=%s' % (CMD, self.cmmd,
                  SRCHOST, self.srcname, TRGHOST, self.dstname,
                  FPREFIX, self.fprefix)
            dbgPrt('B4 copy-move: %s' % cmd)
            fc = wa.SendMessage(lss[IPADDR], lss[PORT], cmd)
            dbgPrt('Ftr copy-move: %s' % fc)
            if fc[ISOK] == NO:
               print('%s service at %s:%s responded with:\n%s' % (
                     ssvcid, lss[IPADDR], lss[PORT], wa.hex2s(fc[MSG])))
                
            raise MyException('Copy command complete! Forcing exit badly ...')
                    
         else:
            raise MyException(lss.msg)

         # enter running loop
         while True:
            msg = self.msgq.get(True, None)
            if msg == QUIT:
               break
            # more incoming messages here ...
            print('noticing incoming message: |%s|' % msg)

      except MyException as msg:
         print('%s' % msg)
      except:
         print(traceback.format_exc())
      finally:
         print('%s is quitting ...' % self.execname)
         dbgOFF()     # debug
         wa.StopServer()
示例#8
0
文件: gol.py 项目: rwniessen/msgkit
   if svcper[0].lower() == PerHost[0]:
      svcper = PerHost
   elif svcper[0].lower() == PerCore[0]:
      svcper = PerCore
   else:
      print('Invalid service instantiation mode')
      usage()
      sys.exit()

   dt1 = datetime.today()

   gol = Conway()
        
   try:
      wa = wakit(execname=webapp, cmdhandler=gol.RecvMessage)
      #print('%s is now running wakit' % webapp)
      gol.wa = wa  # make wakit available from gol
      gol.firstpatternfile = gen1file
      gol.serviceper = svcper
      gol.graphics = graphics
      gol.nPPC = nPPC
      gol.verbose = verbose
      gol.quietsvc = quietsvc
            
      wa.StartServer()
        
      peeraddr, peerport, peername = wa.getPeerID()
      #print('PeerID: addr=%s, port=%s, name=%s' % (
      #       peeraddr, peerport, peername))
            
示例#9
0
def main():
   # set the default argument variables:
   testp2p = False
   testpeer = False
   testapi = False
   peer1addr = ''

   try:
      # options that require an argument must be followed by a colon
      opts, args = getopt.getopt(sys.argv[1:],'ha:t:')
      srcname = os.path.basename(sys.argv[0])
   except getopt.GetoptError:
      usage()
      sys.exit(0)

   for opt, arg in opts:
      if opt == '-h':
         usage()
         sys.exit(0)
      elif opt == '-a':
         peer1addr = arg
      elif opt == '-t':
         if arg == 'p2p':
            testp2p = True
         elif arg == 'peer':
            testpeer = True
         elif arg == 'api':
            testapi = True
         elif arg == 'all':
            testp2p = True
            testpeer = True
            testapi = True
         else:
            print('%s is an invalid test (-t) argument' % arg)
            usage()
            sys.exit(0)
      else:
         print('Invalid options list')
         sys.exit(1)

   try:
      try:
         wa = wakit(srcname)
         peer = wa.StartServer()

         appaddr, appport, appname = wa.getAppID()
         apppid = os.getpid()
         print('AppID: addr=%s, port=%s, name=%s' % (appaddr, appport, appname))
        
         if peer1addr == '':
            destip = appaddr
         else:
            destip = wa.MakeLocalAddress(peer1addr)
         peeraddr, peerport, peername = wa.getPeerID()
         print('Tests will be run against the peer at %s:%s' % (
                destip, peerport))

         if testp2p == True:
            testp2pmessages(wa, destip, peerport, appname, appaddr, appport)
         if testpeer == True:
            testpeermessages(wa, destip, peerport, appname, appaddr, appport,
                                 apppid)
         if testapi == True:
            testwakitapi(wa, appaddr, destip, peerport)

      except MyException as msg:
         print('%s' % msg)
      except:
         traceback.print_exc()
        
      print('Tests all done, shutting down ....\n')

   except:
      print('Exception happened somewhere ...')
      traceback.print_exc()

   finally:
      wa.StopServer()    # frees my app port and stops my message server
示例#10
0
    def Run(self):
        """
      This is the client application.
      """
        try:
            self.wa = wakit(self.execname, cmdhandler=self.RecvMessage)
            # print('%s is running wakit' % self.execname)

            self.wa.StartServer()

            peeraddr, peerport, peername = self.wa.getPeerID()
            # print 'PeerID: addr=%s, port=%d, name=%s' % (
            #       peeraddr, peerport, peername)

            appaddr, appport, appname = self.wa.getAppID()
            print("AppID: addr=%s, port=%s, name=%s" % (appaddr, appport, appname))

            # build a list of all active peers as a list of triplets
            #     name:ipaddr:port ... name:ipaddr:port
            self.peers = self.wa.GetActivePeerList()
            dbgPrt("here is the active peer list:\n%s" % self.peers)

            # make a list of all infosvc.py by an attempted launch per peer
            svcname = "infosvc.py"
            print("launching all the %s service apps ..." % svcname)
            for peerid in self.peers:
                peername, peerip, x3 = peerid.split(":")
                lma = self.wa.LaunchSvc(peerip, svcname)
                dbgPrt("reply from Launch...\n%s" % lma)
                if lma[ISOK] == YES:
                    port = lma[PORT]
                    self.svcapps.append("%s:%s:%s" % (peername, peerip, port))
                    dbgPrt("%s launched remote svc %s on port %s" % (peerid, svcname, port))
                else:
                    print("%s failed to launch service %s" % (peerid, svcname))
                    dbgPrt("message: %s" % self.wa.hex2s(lma[MSG]))

            # get data from each infosvc.py service
            if len(self.svcapps) == 0:
                raise MyException("unable to launch any %s, exiting" % svcname)

            data = []
            for svcid in self.svcapps:
                peername, ipaddr, port = svcid.split(":")
                dbgPrt("polling host %s at %s port %s" % (peername, ipaddr, port))
                s = "%s=%s" % (CMD, self.infocmmd)
                dbgPrt("be4 infosvc kv list: " + s)
                reply = self.wa.SendMessage(ipaddr, port, s)
                dbgPrt("ret infosvc: %s" % reply)
                if reply[ISOK] == YES:
                    value = self.wa.hex2s(reply[HEXREPLY])
                    triplet = "%s:%s:%s" % (peername, self.infocmmd, value)
                    data.append(triplet)  # accumulate data list for display
                else:
                    if MSG in reply:
                        print("data not returned by %s, msg=%s" % (peername, self.wa.hex2s(reply[MSG])))
                    else:
                        print("data not returned by %s, but msg not returned" % peername)

            if len(data) == 0:
                raise MyException("No data received for display")

            # display the data in columnar format: node command value
            tnode = "Node"
            tcommand = "Command"
            tvalue = "Value"
            titles = [tnode, tcommand, tvalue]
            colwidths = [len(tnode), len(tcommand), len(tvalue)]
            for triplet in data:
                node, cmmd, value = triplet.split(":")
                l = len(node)
                if l > colwidths[0]:
                    colwidths[0] = l
                l = len(cmmd)
                if l > colwidths[1]:
                    colwidths[1] = l
                l = len(value)
                if l > colwidths[2]:
                    colwidths[2] = l
            for k in range(0, len(colwidths)):
                colwidths[k] += 2
            print(
                "%s%s%s"
                % (
                    self.Pad(titles[0], colwidths[0]),
                    self.Pad(titles[1], colwidths[1]),
                    self.Pad(titles[2], colwidths[2]),
                )
            )
            for triplet in data:
                node, cmmd, value = triplet.split(":")
                print(
                    "%s%s%s"
                    % (self.Pad(node, colwidths[0]), self.Pad(cmmd, colwidths[1]), self.Pad(value, colwidths[2]))
                )

                # ~~~~~~~~~~~ end app ~~~~~~~~~~~~~
        except MyException as msg:
            print("%s" % msg)
        except:
            print("Exception happened somewhere ...")
            traceback.print_exc()
        finally:
            # print('%s is shutting down' % self.execname)
            self.wa.StopServer()
示例#11
0
   def Run(self):
      '''
      This is the application.
      '''
      try:
         self.wa=wakit(self.execname, cmdhandler=self.RecvMessage)
         #print('%s is running wakit' % self.execname)
            
         self.wa.StartServer()

         peeraddr, peerport, peername = self.wa.getPeerID()
            
         appaddr, appport, appname = self.wa.getAppID()
         print('AppID: addr=%s, port=%s, name=%s' % (
                appaddr, appport, appname))
            
         # This time delay serves two functions: (1) on small peer
         # networks the bot can arrive at the originating node before the 
         # first infobot.py has completely shut down, (2) to throttle the
         # network traffic loading.
         sleep(1.0)
         botname = 'infobot.py'
         if self.incdata == '':
            # start the distributed bot ...
            # get a list of all active peers as a list of triplets
            #     (name:ipaddr:port, ..., name:ipaddr:port)
            # assumption: an infobot.py is present on each active node
            self.peers = self.wa.GetActivePeerList()
            if len(self.peers) == 0:     # Q: is my own peer in the list?
               print('No peers found, exiting')
               self.wa.Stopserver()
               sys.exit()
            # initialize the data vector with dummy data values
            # make sure that my item is the last in the list
            dbgPrt('peers=%s' % self.peers)
            outstr = ''
            for item in self.peers:
               n,addr,p = item.split(':')
               if appaddr == addr:
                  myitem = item
               else:
                  outstr += '%s:%s:%s:%s%s' % (n,addr,p,EMPTY,SEP)
            n,addr,p = myitem.split(':')
            outstr += '%s:%s:%s:%s' % (n,addr,p,EMPTY)
            dbgPrt('outstr: %s' % outstr)
            # send data to first bot in the list
            nextbot = outstr.split(SEP)
            n,addr,p,v = nextbot[0].split(':')
            dbgPrt('B4 StartNextBot: %s %s %s %s' % (n,addr,p,v))
            self.StartNextBot(addr, botname, self.infocmmd, '0,'+outstr)
         else:
            # run the distributed bot task
            # split data string to index and list
            index, data = self.incdata.split(',')
            index = int(index)
            datalist = self.StringToList(data)
            myname, myaddr, myport, myvalue = datalist[index]
            # a sanity check: my data value should not be valid
            if myvalue == EMPTY:
               # Good, now update my data value
               svcname = 'infosvc.py'
               infovalue = self.RunInfoCommand(appaddr, svcname)
               datalist[index] = (myname, myaddr, myport, infovalue)
               # are there any empty items left?
               # if so, then send the data to that node
               done = True
               for item in datalist:
                  n,addr,p,v = item
                  if v == EMPTY:
                     self.outdata = self.ListToString(datalist)
                     ind = '%d,' % (index+1)
                     self.StartNextBot(addr, botname,
                                   self.infocmmd, ind+self.outdata)
                     done = False
                     break

               if done == True:
                  self.PrintData(datalist, self.infocmmd)
            else:
                print('Ooops ... potential infinite loop !!')
                print('My data value should be empty, but is updated!')
                print('Printing existing data as-is ...')
                self.PrintData(datalist, self.infocmmd)
            # ~~~~~~~~~~~ end app ~~~~~~~~~~~~~
      except:
         print('Exception happened somewhere ...')
         traceback.print_exc()
      finally:
         print('%s is shutting down' % self.execname)
         self.wa.StopServer()
示例#12
0
def main():
   if len(sys.argv) < 2:
      print('The -m message parameter is mandatory')
      usage()
      sys.exit()

   # set the default peer argument variables:
   execname = os.path.basename(sys.argv[0])
   destport = PEERPORT
   destaddr = ''
    
   # set the app defaults
   msgparam = False
   msgbody = ''

   try:
      # options that require an argument must be followed by a colon
      msgopts = sys.argv[1:]
      opts, args = getopt.getopt(msgopts,'ha:p:m:')
   except getopt.GetoptError:
      usage()
      sys.exit()

   for opt, arg in opts:
      if opt == '-h':
         usage()
         sys.exit()
      elif opt == '-p':
         destport = arg
      elif opt == '-a':
         destaddr = arg
      elif opt == '-m':
         msgparam = True
      else:
         print('Invalid options list')
         usage()
         sys.exit()

   msgstr = ''
   if msgparam == True:
      bFound = False
      for item in msgopts:
         if bFound == True:
            msgstr += item+' '
         if item == '-m':
            bFound = True
      msgbody = msgstr.rstrip().split()   # remove trailing whitespace
   else:
      pass

   try:
      wa = wakit(execname)
      peeraddr, _pp, peername = wa.getPeerID()
        
      if destaddr == '':
         destip = wa.nodeaddr  # this is a cheat :)
      else:
         destip = wa.MakeLocalAddress(destaddr)
        

      # ~~~~~~~~~~~ send message(s) to a peer or app ~~~~~~~~~~~~~
      if len(msgbody) > 0:
         dic = KVstr2Dict(msgbody)
         params = urllib.parse.urlencode(dic)
         print('sent: %s' % params)
         data = params.encode('ascii')

         url = 'http://%s:%s' % (destip, destport)
         print('to url: %s' % url)
         response = urllib.request.urlopen(url, data).read().decode('utf-8')
         #with urllib.request.urlopen(url, data) as f:
         #     print(f.read().decode('utf-8'))
         print('reply: '+response)
         dic = KeyValueString2Dict(response)
         if HEXREPLY in dic:
            print('HEXREPLY=%s' % wa.hex2s(dic[HEXREPLY]))
         if MSG in dic:
            print('MSG=%s' % wa.hex2s(dic[MSG]))
      # ~~~~~~~~~~~ end send message(s) to a peer or app ~~~~~~~~~~

   except ValueError as msg:
      print(msg)
   except urllib.error.URLError as msg:
      print(msg)
   except:
      print('Exception happened somewhere ...')
      traceback.print_exc()
   finally:
      pass