def __init__(self, profileFile=None):
        """ """
        self.profileFile = profileFile
        self.profileType = ''
        self.name = ''
        self.email = ''
        self.phoneNumber = ''
        self.icon = None
        self.publicId = str(GUID())
        self.location = ''
        self.venueClientURL = ''
        self.homeVenue = ''
        self.privateId = ''
        self.distinguishedName = ''
        self.techSupportInfo = ''
        self.connectionId = ''
        if time.daylight:
            self.gmtoffset = time.altzone
        else:
            self.gmtoffset = time.timezone
        self.beacon = 0
        self.video = self.audio = self.display = 0
        self.lat = self.long = 0

        if profileFile != None and os.path.exists(profileFile):
            self.Load(self.profileFile)
        else:
            self.profile = ClientProfile.defaultProfile.copy()
            self.profile['ClientProfile.id'] = self.publicId
            self._SetFromConfig()  # Get the values from the config
Beispiel #2
0
    def AddMimeType(self, name, extension, mimeType, startable="1"):
        """
        returns a tuple of (int, string). Success is (1, mimeType),
        failure is (0, reason)
        """

        # Ensure that we're in synch with the on-disk appdb
        self._Synch()

        namekey = self._GetPrivName(name)
        if namekey == None:
            namekey = str(GUID())

        privName = self.defaultSeparator.join(["priv_names", namekey])
        nameStr = self.defaultSeparator.join(["name", namekey])
        extStr = self.defaultSeparator.join(["extension", extension])
        mimeStr = self.defaultSeparator.join([mimeType, "None"])
        startableStr = self.defaultSeparator.join(["startable", mimeType])

        self.AppDb[privName] = name
        self.AppDb[nameStr] = mimeType
        self.AppDb[extStr] = mimeType
        self.AppDb[mimeStr] = None
        self.AppDb[startableStr] = startable

        self._Flush()

        return (1, mimeType)
    def __init__(self, name, description, version, mimeType, extension):
        '''
        Initiate the class.

        ** Arguments **

        * name * name of the service.
        * description * description of the service.
        * version * service version.
        '''
        self.name = name
        self.description = description
        self.version = version
        self.mimeType = mimeType
        self.extension = extension
        self.visible = 1
        self.id = GUID()
                
        # Defined in Start.
        self.venueProxies = {}
        self.url = None 
        self.log = None 
        self.app = None

        # Standard AG initialization for console apps.
        self.app = CmdlineApplication.instance()
        self.app.AddCmdLineOption(Option("-v", "--venueUrl",
                                         dest="venueUrl",
                                         help="Register with venue located at this url."))
        
        self.app.AddCmdLineOption(Option("-s", "--venueServerUrl",
                                         dest="venueServerUrl",
                                         help="Register with all venues at server located at this url."))
                                         
        self.capabilities = []
Beispiel #4
0
    def __init__(self):
        AGService.__init__(self)
        self.log.debug("DebugService.__init__: Init Service")
        self.id = str(GUID())

        # Set capabilities
        self.capabilities = [
            Capability(Capability.CONSUMER, Capability.AUDIO),
            Capability(Capability.CONSUMER, Capability.VIDEO),
            Capability(Capability.PRODUCER, "debug")
        ]
        # Set executable
        self.executable = None

        # Set configuration parameters
        self.param1 = OptionSetParameter("Configuration Parameter 1: ", "On",
                                         ["On", "Off"])
        self.param2 = RangeParameter("Configuration Parameter 2: ", 0, 0, 100)
        self.param3 = TextParameter("Configuration Parameter 3: ",
                                    "DebugService")
        self.param4 = ValueParameter("Configuration Parameter 4: ", 25)

        # Append parameters to the configuration list
        self.configuration.append(self.param1)
        self.configuration.append(self.param2)
        self.configuration.append(self.param3)
        self.configuration.append(self.param4)
Beispiel #5
0
    def __init__( self ):
        if self.__class__ == AGService:
            raise Exception("Can't instantiate abstract class AGService")


        self.name = str(self.__class__).split('.')[-1]
        self.uri = 0
        self.serviceManagerUri = ''

        self.resource = None
        self.executable = ""
        self.streamDescription = None
        self.startPriority = "5"
        
        self.capabilities = []
        self.startPriorityOption = OptionSetParameter("Start Priority", self.startPriority, 
        						self.START_PRIORITY_OPTIONS)
        self.configuration = [ self.startPriorityOption ]
        self.started = 1
        self.enabled = 1
        self.running = 1
        self.packageFile = ""
        self.id = GUID()
        # Variable used by new service with AG3.1 interface to indicate when the server has first been configured
        # Afterwards relies on streamDescription comparision as with older AG3.0.x services.
        self.isConfigured = False  
        
        self.processManager = ProcessManager()
        
        app = GetDefaultApplication()
        if not app: 
            app = Service.instance()
        self.log = app.GetLog()
    def __AddInlineService(self, servicePackage):
        log.info("Importing inline service class %s",
                 servicePackage.inlineClass)

        # import the service class
        if '.' not in sys.path:
            sys.path.insert(0, '.')
        mod = __import__(servicePackage.name)

        # instantiate the service object
        serviceClass = getattr(mod, servicePackage.name)
        serviceObj = serviceClass()

        # instantiate the interface object
        serviceObjI = AGServiceI(serviceObj)
        serviceObjI.impl = serviceObj
        serviceObjI.auth_method_name = None

        # register the interface object
        pid = str(GUID())
        path = '/Services/' + servicePackage.name + '.' + pid
        self.server.RegisterObject(serviceObjI, path=path)
        serviceUrl = self.server.FindURLForObject(serviceObj)

        serviceObj.SetUri(serviceUrl)

        log.info("Service registered at url %s", serviceUrl)

        # Get the description from the service
        serviceDescription = serviceObj.GetDescription()
        serviceDescription.SetObject(serviceObj)
        serviceDescription.packageFile = servicePackage.packageFile

        return serviceObj, pid
    def _remove_plugin(self, name):
        namekey = self._get_priv_name(name)
        if namekey == None:
            namekey = str(GUID())

        privName = self.defaultSeparator.join(['priv_names', namekey])
        nameStr = self.defaultSeparator.join(['name', namekey])
        desckey = self.defaultSeparator.join(['priv_desc', namekey])
        cmdkey = self.defaultSeparator.join(['priv_cmds', namekey])
        modulekey = self.defaultSeparator.join(['priv_modules', namekey])
        iconkey = self.defaultSeparator.join(['priv_icons', namekey])

        #
        # The ,None prevents an exception being thrown that we don't
        # care about, ie KeyError
        #
        self.PluginDb.pop(privName, None)
        self.PluginDb.pop(desckey, None)
        self.PluginDb.pop(cmdkey, None)
        self.PluginDb.pop(modulekey, None)
        self.PluginDb.pop(iconkey, None)

        self.Save()

        return True
 def connectionMade(self, connection):
     # Setup a connection id for each connection
     connection.connectionId = GUID()
     # add connection to list, but it has no group yet
     self.connections[connection.connectionId] = (connection, None)
     log.info("connectionMade %s:%s",
              connection.getPeer().host,
              connection.getPeer().port)
Beispiel #9
0
 def JoinBridge(self, multicastNetworkLocation):
     mnl = multicastNetworkLocation
     log.info("Bridge request: mcast %s %s" %
              (mnl["host"], str(mnl["port"])))
     uaddr = SystemConfig.instance().GetHostname()
     retBridge = self.bridgeFactory.CreateBridge(id=mnl["id"],
                                                 maddr=mnl["host"],
                                                 mport=mnl["port"],
                                                 mttl=mnl["ttl"],
                                                 uaddr=uaddr,
                                                 uport=None)
     networkLocation = UnicastNetworkLocation(host=retBridge.uaddr,
                                              port=retBridge.uport)
     networkLocation.profile = self.providerProfile
     networkLocation.id = GUID()
     networkLocation.privateId = GUID()
     return networkLocation
 def __init__(self, parent):
     '''Starts event service'''
     self.uniqueId = str(GUID())
     self.eventList = parent.eventsOut
     self.eventService = EventService((parent.host, int(parent.port)))
     self.eventService.start()
     self.eventService.AddChannel(self.uniqueId)
     self.lock = parent.sendLock
     self.nrOfEvent = parent.nrOfEvent
Beispiel #11
0
    def testRegisterAndLookupBridges(self):
        from AccessGrid.Registry.RegistryClient import RegistryClient
        from AccessGrid.Descriptions import BridgeDescription, QUICKBRIDGE_TYPE, UMTP_TYPE
        from AccessGrid.GUID import GUID
        rc = RegistryClient(url=GetRegistryUrl())

        guid1 = GUID()
        name1 = "name1"
        host1 = "host1"
        listenPort1 = 20001
        serverType1 = QUICKBRIDGE_TYPE
        desc1 = "description1"
        bridgeDesc1 = BridgeDescription(guid=guid1,
                                        name=name1,
                                        host=host1,
                                        port=listenPort1,
                                        serverType=serverType1,
                                        description=desc1)
        validSecs1 = rc.RegisterBridge(bridgeDesc1)

        guid2 = GUID()
        name2 = "name2"
        host2 = "host2"
        listenPort2 = 20002
        serverType2 = UMTP_TYPE
        desc2 = "description2"
        bridgeDesc2 = BridgeDescription(guid=guid2,
                                        name=name2,
                                        host=host2,
                                        port=listenPort2,
                                        serverType=serverType2,
                                        description=desc2)
        validSecs2 = rc.RegisterBridge(bridgeDesc2)

        results = rc.LookupBridge(5)
        found1 = False
        found2 = False
        for result in results:
            if self._bridgeDescriptionsMatch(result, bridgeDesc1):
                found1 = True
            if self._bridgeDescriptionsMatch(result, bridgeDesc2):
                found2 = True
        assert found1
        assert found2
 def AddNetworkLocation(self, networkLocation):
     """
    Add the specified network location to the list
    
    Note: This method overwrites the network location id 
          in the incoming network location
    """
     networkLocation.id = str(GUID())
     self.networkLocations.append(networkLocation)
     return networkLocation.id
   def __init__(self):
      self.id = str(GUID())
      self.location = None
      self.displayWidth = -1
      self.displayHeight = -1
      self.displayDepth = -1
      self.windowList = list()
      self.regionList = list()

      self._Initialize()
    def __ExecuteService(self, servicePackage):
        log.debug("Executing service %s", servicePackage.name)
        #
        # Start the service process
        #
        options = []

        #
        # Determine executable
        #
        servicePath = self.__GetServicePath(servicePackage)
        exeFile = os.path.join(servicePath, servicePackage.executable)
        options.append(exeFile)

        # Set options for service
        # - port
        port = self.allocator.AllocatePort()
        options.append('--port')
        options.append(port)

        # - url of service manager to register with
        options.append('--serviceManagerUri')
        options.append(self.uri)

        # - a token that the service will pass when registering
        token = str(GUID())
        options.append('--token')
        options.append(token)

        # - if service manager is insecure, services will be too
        if self.app.GetOption('secure'):
            options.append('--secure')

        log.info("Running Service; options: %s", str(options))

        # Execute the service process
        pid = self.processManager.StartProcess(sys.executable, options)

        # Wait for service to register with me
        self.registeringServices[token] = None
        self.registerFlag.clear()
        self.registerFlag.wait(10)

        if self.registerFlag.isSet():
            serviceUrl = self.registeringServices[token]
            log.info("Service registered: %s %s", serviceUrl, token)
        else:
            log.info("Service failed to register: %s", token)
            raise Exception("Service failed to become reachable")

        # Remove service from registration list
        del self.registeringServices[token]

        return serviceUrl, pid
    def __init__(self, name=None, description=None, uri=None, oid=None):

        # Catch annoying None case
        if oid != None:
            self.id = oid
        else:
            self.id = str(GUID())

        self.name = name
        self.description = description
        self.uri = uri
Beispiel #16
0
    def __init__(self, host, port):
        '''
        Starts text service

        **Arguments**
        *host* host where text service is running
        *port* port that text service is using
        '''
        self.uniqueId = str(GUID())
        self.textService = TextService((host, int(port)))
        self.textService.start()
        self.textService.AddChannel(self.uniqueId)
 def __init__(self, parent):
     '''
     Starts EventServiceSender
     '''
     self.privateId = str(GUID())
     self.eventOutList = parent.eventsOut
     self.eventReceivedList = []
     self.lock = parent.sendLock
     self.nrOfEvent = parent.nrOfEvent
     self.parent = parent
     self.name = parent.index
     parent.index = parent.index + 1
Beispiel #18
0
def ping(host, port, count):
    try:
        # Create the text client
        profile = ClientProfile()
        textClient = TextClient(profile, (host, port))

        # Connect and send
        privId = str(GUID())
        textClient.Connect(channel, privId)
        #         pubId = profile.GetPublicId()
        #         for i in range(count):
        #             textClient.Input("%s -- %d" % (pubId, i))
        queue.put(0)
    except TextClientConnectException, e:
        print "EXCEPTION in text", sys.exc_type, sys.exc_value
        queue.put(2)
def RunClient(*args, **kw):
    m2threading.init()
    id = kw['id']
    venueUri = kw['url']
    app = kw['app']
    iter = app.GetOption("rt")
    verbose = kw['verbose']

    profile = ClientProfile()
    profile.name = "Test Client %s" % id
    profile.publicId = str(GUID())

    client = MyVenueClient(profile, app)
    
    for i in range(iter):
        try:
            if verbose:
                print "Entering Venue: %s" % venueUri
            ret = client.EnterVenue(venueUri)
            if ret:
                print '** EnterVenue ret = ', ret
            print "Client %d Entered %s %d times" % (id, venueUri,i)
        except:
            print traceback.print_exc()
            continue
        
        if verbose:
            client.PrintVenueState()

        # Pick next one
        if client.venueState is not None:
            exits = client.venueState.connections.values()
            if len(exits):
                next_index = random.randint(0, len(exits)-1)
                venueUri = exits[next_index].uri

        try:
            time.sleep(1)
            client.ExitVenue()
            if verbose:
                print "Exited venue !"
        except:
            print traceback.print_exc()

    client.Shutdown()
    m2threading.cleanup()
def ping(host, port, count):
    try:
        privId = str(GUID())
        eventClient = EventClient(privId, (host, port), channel)
        eventClient.Start()
        eventClient.Send(ConnectEvent(channel, privId))

        for i in range(1, count):
            eventClient.Send(HeartbeatEvent(channel, "%s -- %d" % (privId, i)))
        queue.put(0)
    except EventClientConnectionException:
        print sys.exc_type, sys.exc_value
        queue.put(2)
    except:
        print sys.exc_type, sys.exc_value
        queue.put(3)
    done.set()
Beispiel #21
0
    def __init__(self, parent):
        '''
        Starts TextServiceSender

        **Arguments**
        *eventList* buffer where to insert sent events
        *lock* lock for eventList (also used by EventServiceController)
        *nrOfEvents* how many events of each type should get sent
        '''
        self.parent = parent
        self.privateId = str(GUID())
        self.eventList = parent.eventsOut
        self.receiveList = []
        self.lock = parent.sendLock
        self.nrOfEvent = parent.nrOfMessages
        self.profile = ClientProfile()
        self.profile.name = "client" + str(self.parent.index)
        self.parent.index = self.parent.index + 1
    def stringReceived(self, data):
        #print "lineReceived", data
        connection = self.transport

        sentOk = self.factory.sendGroupMessage(connection, data)
        if sentOk == False:
            if not self.factory.connectionHasGroup(connection):
                # Client is not in any group; treat data as connect string
                # parse connection string:  grouplen,groupid,connectionlen,connectionid

                try:
                    if len(data) == 32:
                        # do beta1 compatibility handling
                        groupId = data
                        connectionId = GUID()
                        log.info('beta1 compat: group=%s  conn=%s' %
                                 (groupId, connectionId))
                    else:
                        grouplen = int(data[:2])
                        groupId = data[2:grouplen + 2]
                        connectionlen = int(data[grouplen + 2:grouplen + 4])
                        connectionId = data[grouplen + 4:grouplen + 4 +
                                            connectionlen]
                        log.info('beta2+: groupid=%s; connectionid=%s' %
                                 (groupId, connectionId))
                    self.factory.addConnection(connection, groupId,
                                               connectionId)
                except GroupDoesNotExistException:
                    self.sendError(ERROR.NO_SUCH_GROUP)
                    self.transport.loseConnection()
                except:
                    log.exception('Exception in group msg service connect')
                    self.sendError(ERROR.UNKNOWN)
                    self.transport.loseConnection()

                self.sendConnectResponse(connectionId=connection.connectionId)
                #print "Wrote version 1 response ack"
                #assert True==self.factory.connectionHasGroup(connection)
            else:
                # Existing connection.  Unable to send for unspecified reason.
                log.debug('Client in group, but send failed')
                self.sendError(ERROR.SERVER_UNABLE_TO_SEND)
                self.transport.loseConnection()
Beispiel #23
0
 def __init__(self,
              name=None,
              auth_type=None,
              auth_data=None,
              id=str(GUID())):
     """
     @param name: the name of the subject
     @param auth_type: the type of authentication used for the subject
     @param auth_data: opaque authentication specific data
     @param id: a globally unique identifier for this object
     @type name: string
     @type auth_type: string
     @type auth_data: string
     @type id: a string containing a globally unique identifier
     """
     self.name = name
     self.auth_type = auth_type
     self.auth_data = auth_data
     self.id = id
Beispiel #24
0
    def __init__(self):
        self.dataPort = 9988
        self.dataStoreClientList = []
        self.uniqueId = GUID()

        # Start transfer service
        self.dataTransferServer = GSIHTTPTransferServer(
            ('', int(self.dataPort)), numThreads=4, sslCompat=0)
        self.dataTransferServer.run()

        self.CreateDataStore()

        # Basic test
        d = DataStoreClient(self.dataStore, 0)
        d.StartDataOperations()

        # Thread test
        #self.StartDataStoreClients()

        self.ShutDown()
    def __init__(self):
        """
        The constructor, initializes itself.
        """
        self.id = str(GUID())
        self.roles = list()
        self.actions = list()
        self.defaultRoles = list()
        self.defaultRoles.append(Everybody)
        self.parent = None
        self.rolesRequired = list()

        # Yeah, I know
        self.profileCachePrefix = "serverProfileCache"
        userConfig = UserConfig.instance()
        self.profileCachePath = os.path.join(userConfig.GetConfigDir(),
                                             self.profileCachePrefix)
        self.profileCache = ClientProfileCache(self.profileCachePath)

        self.identificationRequired = 0
Beispiel #26
0
    def AddCommand(self, mimeType, cmdName, cmdString):
        """
        returns a tuple (int, string). Success is (1, cmdName),
        failure is (0, reason).
        """

        # Ensure that we're in synch with the on-disk appdb
        self._Synch()

        pCmd = self._GetPrivVerb(cmdName, mimeType)
        if pCmd == None:
            pCmd = str(GUID())
        cmdkey = self.defaultSeparator.join([mimeType, pCmd])
        pcmdkey = self.defaultSeparator.join(["priv_cmds", pCmd])

        self.AppDb[cmdkey] = cmdString
        self.AppDb[pcmdkey] = cmdName

        self._Flush()

        return (1, cmdName)
    def _add_plugin(self, name, description, command, module, icon):

        namekey = self._get_priv_name(name)
        if namekey == None:
            namekey = str(GUID())

        privName = self.defaultSeparator.join(['priv_names', namekey])
        nameStr = self.defaultSeparator.join(['name', namekey])
        desckey = self.defaultSeparator.join(['priv_desc', namekey])
        cmdkey = self.defaultSeparator.join(['priv_cmds', namekey])
        modulekey = self.defaultSeparator.join(['priv_modules', namekey])
        iconkey = self.defaultSeparator.join(['priv_icons', namekey])

        self.PluginDb[privName] = name
        self.PluginDb[desckey] = description
        self.PluginDb[cmdkey] = command
        self.PluginDb[modulekey] = module
        self.PluginDb[iconkey] = icon

        self.Save()

        return True
Beispiel #28
0
 def __init__(self,
              name,
              location,
              listenPort,
              qbexec,
              registryUrlList,
              portRange=None):
     if not os.path.exists(qbexec):
         raise Exception(
             "QuickBridge executable does not exist at this location:",
             qbexec)
     self.bridgeFactory = BridgeFactory(qbexec=qbexec,
                                        portRange=portRange,
                                        logger=log)
     self.providerProfile = ProviderProfile(name, location)
     self.listenPort = listenPort
     self.listeningServer = AsyncAGXMLRPCServerThreaded(
         ("", listenPort),
         intervalSecs=1,
         callback=self.MaintenanceCallback,
         logRequests=0)
     self._RegisterRemoteFunctions()
     self.registryClients = []
     for registryUrl in registryUrlList:
         self.registryClients.append(RegistryClient(url=registryUrl))
     hostname = SystemConfig.instance().GetHostname()
     self.bridgeDescription = BridgeDescription(
         guid=GUID(),
         name=name,
         host=hostname,
         port=self.listenPort,
         serverType=QUICKBRIDGE_TYPE,
         description="",
         portMin=self.bridgeFactory.GetPortMin(),
         portMax=self.bridgeFactory.GetPortMax())
     self._RegisterWithRegistry()
     self.running = False
Beispiel #29
0
    def __init__(self,vncserverexe,displayID,geometry="1024x768",depth=24):
        
            
        # Initialize the vncserver executable
        self.vncserverexe = vncserverexe

        # Initialize the contact string, construct it from the hostname and the
        # display ID
        hostname=Toolkit.CmdlineApplication.instance().GetHostname()
        if IsWindows():
            self.contactString="%s"%(hostname,)
        elif IsOSX():
            self.contactString="%s"%(hostname,)
        elif IsLinux() or IsFreeBSD():
            self.contactString="%s%s"%(hostname,displayID)
            
        self.displayID=displayID
        
        # Initialize internal representation of the desired geometry
        self.geometry={}
        (tmpWidth,tmpHeight)=geometry.split('x')
        self.geometry["Width"]=eval(tmpWidth)
        self.geometry["Height"]=eval(tmpHeight)

        # And depth
        self.depth=depth

        # Initialize other random bits, mostly path/file names
        self.guid=str(GUID())
        self.passwdFilename = None
        
        # Initialize the password file.
        self.genPassword()
        
        self.processManager = ProcessManager()
        
        self.running = 0
Beispiel #30
0
            s.settimeout(2)
            s.bind(('', desc.GetPort()))
            s.sendto('qwe', (desc.host, desc.port))
            fdList = select.select([s.fileno()], [], [], timeout)
            if fdList[0] and s.fileno() in fdList[0]:
                data, src_addr = s.recvfrom(MSGSIZE)
                ret = 1
        except Exception, e:
            log.exception("Error testing bridge")
        if s:
            s.close()

        return ret

    def PingBridge(self):
        raise Exception("Not yet implemented")


if __name__ == '__main__':
    bc = UMTPClient(host="milton.mcs.anl.gov", port=52000)
    multicastNetworkLocation = MulticastNetworkLocation(host="224.2.224.15",
                                                        port=20002,
                                                        ttl=1)
    multicastNetworkLocation.id = GUID()
    multicastNetworkLocation.privateId = GUID()
    multicastNetworkLocation.profile = ("", "")
    print dir(multicastNetworkLocation)
    print multicastNetworkLocation.__dict__
    print "Multicast location: ", multicastNetworkLocation
    print "Test: ", bc.TestBridge(multicastNetworkLocation)