Example #1
0
def init_logging(appName):
    hdlr = Log.StreamHandler()
    hdlr.setLevel(log.DEBUG)
    hdlr.setFormatter(Log.GetFormatter())

    appLogger = Log.GetLogger(appName)
    Log.HandleLoggers(appLogger, Log.GetDefaultLoggers())
Example #2
0
    def InitLogging(self, debug=0, log=None):
        """
        Returns the log file.
        
        **Arguments**
        
        *debug* Not relevant. Note: Use WXGUIApplication.Initialize() in
        application main method instead.

        *log* Not relevant. Note: Use WXGUIApplication.Initialize() in
        application main method instead.
        """

        # We don't really need this method if all shared apps uses
        # WXGUIApplication() in main call. Keep this around for now to
        # maintain interoperability with old shared apps.

        # For this to work, you have to use WXGUIApplication in your
        # application's main call.

        self.log = Log.GetLogger(self.__appName)

        #Log.SetDefaultLevel(self.__appName, Log.DEBUG)

        # Log to file
        #if log == None:
        #    logFile = self.__appName + ".log"
        #else:
        #    logFile = log

        #fileHandler = Log.FileHandler(logFile)
        #fileHandler.setFormatter(Log.GetFormatter())
        #Log.HandleLoggers(fileHandler, Log.GetDefaultLoggers())

        return self.log
Example #3
0
    def ProcessArgsThatUsePreferences(self):
        """
       Process toolkit wide logging arguments. Then return the modified
       argv so the app can choose to parse more if it requires that.
       """

        if self.options.debug or int(
                self.preferences.GetPreference(Preferences.LOG_TO_CMD)):
            self.streamLoggerLevels = Log.HandleLoggers(
                Log.defStreamHandler, Log.GetDefaultLoggers())
            self.streamLoggerLevels.SetLevel(Log.DEBUG)
            self.streamLoggerLevels.SetLevel(Log.CRITICAL, Log.RTPSensor)
            # When in debug mode, we'll make the stream the primary handler.
            self.loggerLevels = self.streamLoggerLevels
        else:
            # If not in debug, we only used the StreamHandler before Logging was initialized.
            #    so we don't have a StreamLoggerLevels.
            self.streamLoggerLevels = None
Example #4
0
 def __init__(self):
     '''
     Initiates the class. Creates a network service matcher and a dictionary
     to keep track of available network services.
     '''
     
     self.__services = dict()
     self.__matcher = NetworkServiceMatcher()
     self.log = Log.GetLogger('NetworkServicesManager')
    def __init__(self, url):
        self.url = url
        self.serverProxy = None
        self.registryPeers = None
        self.bridges = None
        self.bridgeCache = BridgeCache()
        self.log = Log.GetLogger('RegistryClient')

        self.proxyURL = BuildPreferencesProxyURL()
Example #6
0
def GetMemoryHandlers():
    numFound = 0
    for log in Log.GetLoggers():
        for handler in log.handlers:
            for lowhandler in handler.handlers:
                if isinstance(lowhandler, logging.handlers.MemoryHandler):
                    #print "Found memory handler: ", lowhandler
                    numFound += 1
    return numFound
    def __init__(self, args):
        # Initilialize Logging
        self.ntl = Log.handlers.NTEventLogHandler("AG Node Service")
        self.ntl.setLevel(Log.DEBUG)
        self.log = Log.GetLogger(Log.NodeService)
        Log.HandleLoggers(self.ntl, Log.GetDefaultLoggers())

        # Initialize Win32 Service stuff
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

        # Make a node service
        self.nodeService = AGNodeService()

        # Make a hosting environment
        self.server = Server(self._defaultPort)

        # Make a node service service
        self.server.RegisterObject(self.nodeService, path='/NodeService')

        # Tell the world we're here
        self.log.info("Created Node Service.")
Example #8
0
    def __init__(self, args):
        # Initialize Logging
        ntl = Log.handlers.NTEventLogHandler("AG VenueServer")
        ntl.setLevel(Log.DEBUG)
        self.log = Log.GetLogger(Log.VenueServer)
        Log.HandleLoggers(ntl, Log.GetDefaultLoggers())

        # Initialize Win32 Service stuff
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

        # Make a hosting environment
        self.server = Server(self._defaultPort)

        # Make a venue server
        self.venueService = VenueServer(self.server)

        # Make a Service Manager Service
        self.server.RegisterObject(self.venueService, path='/VenueServer')

        # tell the world we are here
        self.log.info("Created VenueServer.")
Example #9
0
def SetLogging():
    debugMode = 1
    logFile = None

    if logFile is None:
        logname = os.path.join(GetUserConfigDir(), "Test.log")
    else:
        logname = logFile

    hdlr = Log.FileHandler(logname)
    hdlr.setFormatter(Log.GetFormatter())
    hdlr.setLevel(Log.WARN)
    Log.HandleLoggers(hdlr, Log.GetDefaultLoggers())

    if debugMode:
        hdlr = Log.StreamHandler()
        hdlr.setFormatter(Log.GetLowDetailFormatter())
        Log.HandleLoggers(hdlr, Log.GetDefaultLoggers())
def SetLogging():
    logFile = None
    debugMode = 1

    if logFile is None:
        logname = os.path.join(UserConfig.instance().GetConfigDir(),
                               "NodeSetupWizard.log")
    else:
        logname = logFile

    hdlr = Log.FileHandler(logname)
    hdlr.setFormatter(Log.GetFormatter())
    Log.HandleLoggers(hdlr, Log.GetDefaultLoggers())

    if debugMode:
        hdlr = Log.StreamHandler()
        hdlr.setFormatter(Log.GetLowDetailFormatter())
        Log.HandleLoggers(hdlr, Log.GetDefaultLoggers())
Example #11
0
    def __SetLogPreference(self):
        """
        Set correct log level for each log category according
        to preferences.
        """
        logFiles = Log.GetCategories()

        for name in logFiles:
            # Get level from preferences.
            logLevel = int(self.preferences.GetPreference(name))
            fLevels = self.GetFileLogLevels()
            sLevels = self.GetStreamLogLevels()

            # Level for files
            if fLevels:
                fLevels.SetLevel(logLevel, name)
            # Level for streams
            if sLevels:
                sLevels.SetLevel(logLevel, name)
Example #12
0
    def __init__(self,
                 qbexec,
                 portRange=None,
                 logger=Log.GetLogger("BridgeFactory")):
        self.qbexec = qbexec
        self.portRange = portRange
        global log
        log = logger

        self.bridges = dict()
        self.processManager = ProcessManager()
        self.processManager.WaitForChildren(self.OnBridgeDeath)

        self.bridgesByPid = {}

        self.addressAllocator = NetworkAddressAllocator()

        # Use the port range if given
        if portRange:
            log.info("Allocator using port range: %s" % (portRange, ))
            self.SetPortMin(portRange[0])
            self.SetPortMax(portRange[1])
Example #13
0
 def __init__(self):
     self.log = Log.GetLogger('NetworkServiceMatcher')
Example #14
0
#-----------------------------------------------------------------------------
# Name:        UMTPClient.py
# Purpose:     Interface for UMTP Servers
# Created:     2006/06/22
# RCS-ID:      $Id: UMTPClient.py,v 1.1 2006/06/26 13:29:30 ngkim Exp $
#-----------------------------------------------------------------------------

from AccessGrid.Preferences import Preferences
from AccessGrid.Registry.RegistryClient import RegistryClient
from AccessGrid.UMTP import UMTPAgent
from AccessGrid.BridgeClient import BridgeClient
from AccessGrid import Log
from AccessGrid.NetworkLocation import MulticastNetworkLocation
from AccessGrid.GUID import GUID

log = Log.GetLogger("UMTPClient")


class UMTPClient(BridgeClient):
    def __init__(self, host=None, port=None, timeout=1):
        BridgeClient.__init__(self, host, port)

        self.host = host
        self.port = port

        self.agent = UMTPAgent(log)

    def SetHostPort(self, host, port):
        self.host = host
        self.port = port
Example #15
0
def RunService(service,serviceInterface,unusedCompatabilityArg=None,app=None):
    import signal, time
    from AccessGrid.hosting import SecureServer, InsecureServer
    from AccessGrid.interfaces.AGServiceManager_client import AGServiceManagerIW
    
    serviceName = service.GetName()

    # Initialize the service
    svc = Service.instance()
    svc.AddCmdLineOption(Option("-p", "--port", type="int", dest="port",
                        default=9999, metavar="PORT",
                        help="Set the port the service should run on."))
    svc.AddCmdLineOption(Option("-s", "--serviceManagerUri", type="string", dest="serviceManagerUri",
                        default=None, metavar="SERVICE_MANAGER_URL",
                        help="URL of ServiceManager to register with"))
    svc.AddCmdLineOption(Option("-t", "--token", type="string", dest="token",
                        default=None, metavar="TOKEN",
                        help="Token to pass to service manager when registering"))
    svc.AddCmdLineOption(Option("--test", action='store_true', dest="test",
                        default=None, metavar="TEST",
                        help="Test service and then exit"))


    svc.Initialize(serviceName)
    log = svc.GetLog()
    Log.SetDefaultLevel(serviceName, Log.DEBUG)   

    # Get options
    port = svc.GetOption("port")
    serviceManagerUri = svc.GetOption('serviceManagerUri')
    test = svc.GetOption('test')
    if test:
        from AccessGrid.NetworkLocation import MulticastNetworkLocation
        stream = StreamDescription('test stream',
                                   MulticastNetworkLocation('224.2.2.2',20000,1))
        stream.capability = service.capabilities
        resources = service.GetResources()
        if len(resources) > 0:
            service.SetResource(resources[0])
        service.SetStream(stream)
        return
    
    # Create the server
    
    if not app:
        app = GetDefaultApplication()
    hostname = app.GetHostname()
    server = None
    if svc.GetOption("secure"):
        server = SecureServer( (hostname, port) )
    else:
        server = InsecureServer( (hostname, port) )
    
    serviceInterface.impl = service
    serviceInterface.auth_method_name = None    


    # Register the service interface with the server
    servicePath = '/Services/%s.%s' % (serviceName, str(GUID()))
    server.RegisterObject(serviceInterface, path = servicePath)
    
    # Start the server
    server.RunInThread()
    url = server.FindURLForObject(service)
    log.info("Starting Service URI: %s", url)
    print "Starting Service URI: %s" % url

    
    # Set service data
    service.SetServiceManagerUrl(serviceManagerUri)
    service.SetUri(url)

    # Register with the calling service manager
    if serviceManagerUri:
        log.debug("Registering with service manager; url=%s", serviceManagerUri)
        token = svc.GetOption('token')
        AGServiceManagerIW(serviceManagerUri).RegisterService(token,url)
    else:
        log.info("Service Manager does not exist for service %s"%(url))

    

    # Register the signal handler so we can shut down cleanly
    # lambda is used to pass the service instance to the 
    # signal handler
    signal.signal(signal.SIGINT, 
                  lambda signum,frame,service=service:
                  SignalHandler(signum,frame,service))
   
    # Loop main thread to catch signals
    while service.IsRunning():
       time.sleep(1)
       
    # Shutdown the server
    server.Stop()
Example #16
0
    def __init__(self):
        """
       The application constructor that enforces the singleton pattern.
       """
        if AppBase.instance():
            raise Exception, "Only one instance of AppBase is allowed; already have instance of %s" % (
                AppBase.instance().__class__, )

        AppBase.set_instance(self)

        self.parser = OptionParser()
        self.parser.add_option("-d",
                               "--debug",
                               action="store_true",
                               dest="debug",
                               default=0,
                               help="Set the debug level of this program.")
        self.parser.add_option("-l",
                               "--logfile",
                               dest="logfilename",
                               metavar="LOGFILE",
                               default=None,
                               help="Specify a log file to output logging to.")
        self.parser.add_option(
            "--numlogfiles",
            dest="numlogfiles",
            metavar="NUMLOGFILES",
            default=1,
            type="int",
            help="Specify the number of log files to retain")
        self.parser.add_option("--logfilesize",
                               dest="logfilesize",
                               metavar="LOGFILESIZE",
                               default=10000000,
                               type="long",
                               help="Specify the size of log files to retain")
        self.parser.add_option(
            "-c",
            "--configfile",
            dest="configfilename",
            metavar="CONFIGFILE",
            default=None,
            help="Specify a configuration file for the program.")
        self.parser.add_option(
            "--version",
            action="store_true",
            dest="version",
            default=0,
            help="Print out what version of the toolkit this is.")
        self.parser.add_option("--secure",
                               type="int",
                               dest="secure",
                               default=0,
                               help="Specify whether the service uses SSL.")
        self.parser.add_option("--cert",
                               dest="cert",
                               metavar="CERTFILE",
                               default=None,
                               help="Specify a certificate file to use.")
        self.parser.add_option("--key",
                               dest="key",
                               metavar="KEYFILE",
                               default=None,
                               help="Specify a certificate key file to use.")
        self.parser.add_option(
            "--cadir",
            dest="cadir",
            metavar="CADIR",
            default=None,
            help="Specify the directory containing CA certificates.")

        self.options = None
        self.userConfig = None
        self.agtkConfig = None
        self.systemConfig = SystemConfig.instance()
        self.log = None
        self.loggerLevels = None
        self.fhLoggerLevels = None

        self._certificateManager = None
        self._certMgrUI = None

        # This initializes logging
        self.log = Log.GetLogger(Log.Toolkit)
        self.log.debug("Initializing AG Toolkit version %s %s", GetVersion(),
                       GetStatus())
        self.log.info("Command and arguments: %s" % sys.argv)

        self.__context = None
        self.__passphrase = None
"""
"""
__revision__ = "$Id: Config.py,v 1.42 2006-10-02 19:10:32 turam Exp $"

import os
import sys
import re
import struct
import time
import select
import socket
import shutil

from AccessGrid import Log
from AccessGrid.Version import GetVersion
log = Log.GetLogger(Log.Toolkit)

class AGTkConfig:
    """
    This class encapsulates a system configuration for the Access Grid
    Toolkit. This object provides primarily read-only access to configuration
    data that is created when the toolkit is installed.

    @type version: string
    @ivar version: The version of this installation.
    @type installDir: string
    @ivar installDir: The directory this toolkit is installed in.
    @type appDir: string
    @ivar appDir: The directory for system installed shared applications
    @type nodeServicesDir: string
    @ivar nodeServicesDir: the directory for system installed node services
import sys
import re
from AccessGrid import Log

hdlr = Log.StreamHandler()
hdlr.setLevel(Log.DEBUG)
Log.HandleLoggers(Log.StreamHandler(), Log.GetDefaultLoggers())

sys.path.append(r"c:\home\olson\ag\dev\AccessGrid")

from AccessGrid import DataStore

defaultURL = "https://localhost:9011/test"

if len(sys.argv) > 1:
    url = sys.argv[1]
else:
    url = defaultURL

files = [
    r"c:\temp\tarfile-0.6.5.zip",
    r"c:\boot.ini",
    r"c:\Program Files\Inno Setup 3\whatsnew.htm",
    #         r"file name with spaces.txt",
    #         r"c:\home\olson\ag\dev\AccessGrid\AccessGrid\put.py",
    #          r"c:\temp\put.py",
    r"c:\home\olson\docs\AG\ag-2-design\datastore-simplified.doc"
]

if re.search("^https:", url):
    x = DataStore.GSIHTTPUploadFiles(url, files, None)
Example #19
0
import os
import sys

from AccessGrid.Plugin import Plugin
from AccessGrid.Descriptions import PluginDescription
from AccessGrid import Log

from AccessGrid.Platform import Config

log = Log.GetLogger("PluginFactory")

def BuildPlugin(pluginDesc):
    if not pluginDesc:
        log.exception("Null plugin description.")
        return None

    if not isinstance(pluginDesc, PluginDescription):
        log.exception("Invalid type, expected PluginDescription.")
        return None

    namenospace = pluginDesc.name.replace(' ', '_')

    sysdir = os.path.join(Config.AGTkConfig.instance().GetPluginDir(),
                          namenospace)
    userdir = os.path.join(Config.UserConfig.instance().GetPluginDir(),
                           namenospace)
    olddir = os.getcwd()
        
    if os.access(userdir, os.R_OK):
        pluginDir = userdir
    elif os.access(sysdir, os.R_OK):
Example #20
0
import shutil
import getpass
import sys
import time

from stat import *

from AccessGrid import Log
from AccessGrid import Utilities
from AccessGrid.Security import CertificateRepository
from AccessGrid.Security import CRSClient
from AccessGrid.Security import ProxyGen
from AccessGrid import Platform
from AccessGrid.Platform.Config import AGTkConfig, UserConfig

log = Log.GetLogger(Log.CertificateManager)


class CertificateManagerError(Exception):
    pass

class NoIdentityCertificateError(CertificateManagerError):
    pass

class NoCertificates(Exception):
    pass

class NoDefaultIdentity(Exception):
    pass

class ProxyExpired(Exception):
Example #21
0
    def Initialize(self, name=None, args=None):
        """
       This method sets up everything for reasonable execution.
       At the first sign of any problems it raises exceptions and exits.
       """
        self.name = name

        # 1. Process Command Line Arguments
        argvResult = self.ProcessArgs(args=args)

        # 2. Load the Toolkit wide configuration.
        try:
            self.agtkConfig = AGTkConfig.instance(0)
        except Exception:
            self.log.exception("Toolkit Initialization failed.")
            sys.exit(-1)

        # 3. Load the user configuration, creating one if necessary.
        try:
            self.userConfig = UserConfig.instance(initIfNeeded=1)
        except Exception:
            self.log.exception("User Initialization failed.")
            sys.exit(-1)

        # Load client preferences
        self.preferences = Preferences()
        self.ProcessArgsThatUsePreferences()

        # 4. Redirect logging to files in the user's directory,
        #    purging memory to file

        fh = Log.defLogHandler

        if self.options.logfilename is not None:
            if not self.options.logfilename.endswith(".log"):
                self.name = self.options.logfilename + ".log"
            else:
                self.name = self.options.logfilename
        elif self.name is not None:
            if not self.name.endswith(".log"):
                self.name = self.name + ".log"

        self.log.info("Logfile Name: %s", self.name)

        if self.name:
            if not self.name.startswith(os.sep) \
                                      and not self.name.startswith("."):
                filename = os.path.join(self.userConfig.GetLogDir(), self.name)
            else:
                filename = self.name

            fh = Log.RotatingFileHandler(filename, "a",
                                         self.options.logfilesize,
                                         self.options.numlogfiles)

            fh.setFormatter(Log.GetFormatter())
            self.fhLoggerLevels = Log.HandleLoggers(fh,
                                                    Log.GetDefaultLoggers())
            self.fhLoggerLevels.SetLevel(Log.DEBUG)
            self.fhLoggerLevels.SetLevel(Log.CRITICAL, Log.RTPSensor)
            self.loggerLevels = self.fhLoggerLevels

            # Send the log in memory to stream (debug) or file handler.
        if self.options.debug or int(
                self.preferences.GetPreference(Preferences.LOG_TO_CMD)):
            Log.mlh.setTarget(Log.defStreamHandler)
        else:
            Log.mlh.setTarget(fh)
        Log.mlh.close()
        Log.RemoveLoggerLevels(Log.memLevels, Log.GetLoggers())

        self.__SetLogPreference()

        self.CheckDependencies()

        # Check if machine clock is synchronized.
        # - Disabled for 3.0: clock-sync is important when using proxy certs, which we're not
        #self.__CheckForInvalidClock()

        self.__context = None

        return argvResult
Example #22
0
import sys
import base64

from AccessGrid import Events
from AccessGrid import Toolkit
from AccessGrid.Platform.Config import UserConfig
from AccessGrid.Platform import IsWindows,IsLinux,IsOSX,IsFreeBSD
from AccessGrid import DataStore
from AccessGrid import Platform
from AccessGrid.GUID import GUID
from AccessGrid.Toolkit import CmdlineApplication
from AccessGrid.ClientProfile import ClientProfile
from AccessGrid.SharedApplication import SharedApplicationIW

from AccessGrid import Log
log = Log.GetLogger("VenueVNCClient")

class vncSharedAppClient:
    """
    """
    def __init__( self, appUrl, clientProfile ):

        self.appUrl = appUrl

        self.appProxy=SharedApplicationIW(self.appUrl)
        print( "Application URL: %s" %(self.appUrl) )
        #print( "Application URL Valid? " + self.appProxy.isValid( ) )
        # Join the application
        #  ** NEW METHOD **
        (self.publicId, self.privateId) = self.appProxy.Join(clientProfile)
        #  ** OLD METHOD **
# Licence:     See COPYING.TXT
#-----------------------------------------------------------------------------

import time
import select
import socket
import xmlrpclib
from AccessGrid.NetworkLocation import MulticastNetworkLocation, UnicastNetworkLocation
from GUID import GUID
from BridgeClient import BridgeClient
from AccessGrid.UrllibTransport import UrllibTransport, TimeoutTransport
from AccessGrid import Utilities
from AccessGrid.Descriptions import BridgeDescription
from AccessGrid import Log

log = Log.GetLogger("QuickBridgeClient")


class ConnectionError(Exception):
    pass


class QuickBridgeClient(BridgeClient):
    def __init__(self, host=None, port=None, timeout=1):
        BridgeClient.__init__(self, host, port)

        transport = None
        self.proxyURL = Utilities.BuildPreferencesProxyURL()
        if self.proxyURL:
            self.transport = UrllibTransport(self.proxyURL, timeout)
        else:
Example #24
0
# Created:     2003/08/02
# RCS-ID:      $Id: ProcessManager.py,v 1.14 2007-04-16 19:39:46 turam Exp $
# Copyright:   (c) 2002-2003
# Licence:     See COPYING.txt
#-----------------------------------------------------------------------------
"""
"""
__revision__ = "$Id: ProcessManager.py,v 1.14 2007-04-16 19:39:46 turam Exp $"

import win32api
import win32con
import win32event
import win32process
from AccessGrid import Log

log = Log.GetLogger(Log.ProcessManager)


class ProcessManager:
    def __init__(self):
        self.processes = []
        self.threadid = dict()

    def WaitForChildren(self, callback):
        log.warn('ProcessManager callback not yet implemented on Windows')

    def StartProcess(self, command, arglist, detached=1, maxWait=20):
        """
        Start a new process.

        @param command : the name of the command to be started. It can
Example #25
0
import time
import string

import os
import os.path
import re
import shutil

import wx

from AccessGrid.UIUtilities import MessageDialog, ErrorDialog, ErrorDialogWithTraceback
from AccessGrid import Log
from AccessGrid import Toolkit

log = Log.GetLogger(Log.CertificateManagerWXGUI)

from AccessGrid.Security import CertificateManager
from AccessGrid.Security import CertificateRepository


def ValidateExportPath(path):
    """
    Validate the path for exporting.

    @param path: Pathname to be validated.
    
    @return: A tuple (success, message).

    Success is 0 for success, 1 for can't write, 2 for file exists. Yes, this
    is a little arbitrary but this isn't a general purpose routine, it's to
Example #26
0
# Standard Python library
import sys
import threading
import urlparse
import urllib
import asyncore

# Medusa
from FTPS import filesys
from FTPS import ftps_server

# M2Crypto
from M2Crypto import Rand, SSL

from AccessGrid import Log
log = Log.GetLogger('FTPSServer')
Log.SetDefaultLevel('FTPSServer', Log.DEBUG)


class authorizer:
    def __init__(self, root='/', authorizecb=None):
        self.root = root
        self.authorizecb = authorizecb

    def authorize(self, channel, username, password):

        channel.read_only = 0
        if self.authorizecb and self.authorizecb(channel, username, password):
            return 1, 'Ok.', filesys.os_filesystem(self.root)
        else:
            return 0, 'Connection rejected.', None
import wx

from AccessGrid import Log
from AccessGrid.Events import Event
from AccessGrid.Platform import IsWindows, Config
from AccessGrid.ClientProfile import ClientProfile
from AccessGrid.Toolkit import WXGUIApplication
from AccessGrid.SharedAppClient import SharedAppClient
from AccessGrid.Platform.Config import UserConfig

import os
import getopt
from time import localtime, strftime

log = Log.GetLogger(Log.AppMonitor)


class AppMonitor:
    '''
    An Application Monitor connects to an Application Service and
    displays current application state such as participants and their status,
    application name, and description. It also includes an event window
    that shows when participants joined, data changed, and so forth.
    '''
    def __init__(self, parent, appUrl):
        '''
        Opens the Application Monitor frame and loads it with
        current application state. Also, register callbacks for
        events that updates the state.
        
        **Arguments**
#-----------------------------------------------------------------------------
"""
"""
__revision__ = "$Id: Descriptions.py,v 1.108 2007/12/20 16:37:23 turam Exp $"
__docformat__ = "restructuredtext en"

import string

from AccessGrid.GUID import GUID
from AccessGrid import Log
from AccessGrid.NetworkLocation import MulticastNetworkLocation
from AccessGrid.NetworkLocation import UnicastNetworkLocation
from AccessGrid.NetworkLocation import ProviderProfile
from AccessGrid.ClientProfile import ClientProfile

log = Log.GetLogger(Log.DataStore)


class ObjectDescription:
    """
    An object description has four parts:
        id : string
        name : string
        description : string
        uri : uri (string)
    """
    def __init__(self, name=None, description=None, uri=None, oid=None):

        # Catch annoying None case
        if oid != None:
            self.id = oid
Example #29
0
import os
import ConfigParser

from AccessGrid import Log
from AccessGrid.Descriptions import ConnectionDescription
log = Log.GetLogger("VenueCache")


class VenueCache:
    def __init__(self, venuesFile, venueServers):
        self.venuesFile = venuesFile
        self.venueServers = venueServers
        self.venues = {}

    def Update(self):
        log.debug("Updating venue cache")
        from AccessGrid.interfaces.VenueServer_client import VenueServerIW

        venueList = []

        for url in self.venueServers:
            try:
                venueList = VenueServerIW(url).GetVenues()
                venueList.sort(cmp=lambda x, y: cmp(x.name, y.name))
                self.venues[url] = VenueCache.VenueList(url, venueList)
                log.debug("Retrieved %d venues from server %s", len(venueList),
                          url)
            except:
                log.exception("Exception retrieving venues from %s", url)

    def GetVenues(self):
def main():
    """
    This is the function that does all the real work.
    """
    app = CmdlineApplication.instance()
    app.Initialize("CreateVenues")

    venueServerUri = "https://localhost:8000/VenueServer"

    if len(sys.argv) > 2:
        venueServerUri = sys.argv[2]

    configFile = sys.argv[1]

    venueServer = VenueServerIW(venueServerUri, tracefile=sys.stdout)
    #venueServer.SetEncryptAllMedia(0)

    config = ConfigParser.ConfigParser()
    config.read(configFile)
    venues = {}

    # Start up the logging
    log = Log.GetLogger("CreateVenues")
    hdlr = Log.StreamHandler()
    hdlr.setLevel(Log.INFO)
    Log.HandleLoggers(hdlr, Log.GetDefaultLoggers())

    # We do this in two iterations because we need valid URLs for connections
    for sec in config.sections():
        # Build Venue Descriptions
        vdesc = VenueDescription3(config.get(sec, 'name'),
                                  config.get(sec, 'description'))
        vdesc.streams = []

        # Static Video
        if config.has_option(sec, 'video'):
            (host, port) = string.split(config.get(sec, 'video'), ':')
            vcap = Capability3(Capability.PRODUCER, Capability.VIDEO)
            vsd = StreamDescription3(
                vdesc.name,
                MulticastNetworkLocation(host.strip(), int(port), 127), vcap,
                0, None, 1)
            vdesc.streams.append(vsd)

        # Static Audio
        if config.has_option(sec, 'audio'):
            (host, port) = string.split(config.get(sec, 'audio'), ':')
            acap = Capability3(Capability3.PRODUCER, Capability3.AUDIO)
            asd = StreamDescription3(
                vdesc.name,
                MulticastNetworkLocation(host.strip(), int(port), 127), acap,
                0, None, 1)
            vdesc.streams.append(asd)

        # Make the venue, then store the resulting URL
        print "VD #%s : %s" % (sec, vdesc.name)
        vdesc.uri = venueServer.AddVenue(vdesc)
        config.set(sec, 'uri', vdesc.uri)

        if config.has_option(sec, 'default'):
            venueServer.SetDefaultVenue(vdesc.id)

        venues[sec] = vdesc

    for sec in config.sections():
        # Build up connections
        exits = string.split(config.get(sec, 'exits'), ', ')
        for vexit in exits:
            if venues.has_key(vexit):
                toVenue = venues[vexit]
                uri = toVenue.uri
                conn = ConnectionDescription(toVenue.name, toVenue.description,
                                             toVenue.uri)
                venues[sec].connections.append(conn)
            else:
                print "Error making connection to venue: ", vexit

        # Set the connections on the given venue
        print "CD #%s/%s: %s" % (sec, venues[sec].name, config.get(
            sec, 'exits'))

        # venue = Client.Handle(venues[sec].uri).GetProxy()
        print "URL: %s" % venues[sec].uri
        venue = VenueIW(venues[sec].uri, tracefile=sys.stdout)
        venue.SetConnections(venues[sec].connections)