def _ping(self, host):
        '''
        Invoke system ping command to host

        @param host: machine to ping
        @type host: string
        @return: average time for ping command  
        @rtype: string
        '''

        if IsOSX() or IsLinux() or IsFreeBSD():
            # osx and linux ping command have the
            # same output format

            # time out after 10 sec
            if IsOSX() or IsFreeBSD():
                cmd = 'ping -o -t 1 %s' % (host)
            else:
                cmd = 'ping -c 1 -w 1 %s' % (host)

            ret = self._execCmd(cmd)

            if ret.find('unknown host') > -1:
                self.log.info("Ping: Host %s not found" % (host))
                raise Exception, "Ping: Host %s not found" % (host)

            if ret.find('100%') > -1:
                self.log.info("Ping: Host %s timed out" % (host))
                raise Exception, "Ping: Host %s timed out" % (host)

            # Find average round trip time
            i = ret.find('time')
            ret = ret[i:]
            ret = ret.split('=')[1]
            ret = ret.split()[0]
            val = float(ret) / 1000

        if IsWindows():
            cmd = 'ping -n 1 %s' % (host)
            ret = self._execCmd(cmd)

            if ret.find('could not find') > -1:
                self.log.info("Ping: Host %s not found" % (host))
                raise Exception, "Ping: Host %s not found" % (host)

            # windows times out automatically
            if ret.find('timed out') > -1:
                self.log.info("Ping: Host %s timed out" % (host))
                raise Exception, "Ping: Host %s timed out" % (host)

            # Find average round trip time
            a = ret.find('Average')
            ret = ret[a:]
            val = ret.split('=')[1]
            val = filter(lambda x: x.isdigit(), val)
            val = float(val)

        return val
def SetIcon(app):
    icon = None
    if IsWindows() or IsLinux() or IsFreeBSD():
        icon = icons.getAGIconIcon()
        app.SetIcon(icon)
    elif IsOSX():
        icon = icons.getAGIcon128Icon()
        t = wx.TaskBarIcon()
        t.SetIcon(icon, "VenueClient")
Пример #3
0
 def ForceStop(self):
     """
     Forcefully stop the service
     """
     if IsWindows():
        # windows : do nothing special to force stop; it's forced anyway
        AGService.Stop(self)
     elif IsLinux() or IsOSX() or IsFreeBSD():
        # linux : kill, instead of terminating
        self.started = 0
        self.processManager.KillAllProcesses()
    def __SetRTPDefaults(self, profile):
        """
        Set values used by rat for identification
        
        Note:  OpenMash sets rtpName/rtpEmail in ~/.mash/prefs
        """
        if profile == None:
            self.log.exception("Invalid profile (None)")
            raise Exception, "Can't set RTP Defaults without a valid profile."

        if IsLinux():
            try:
                rtpDefaultsFile = os.path.join(os.environ["HOME"],
                                               ".RTPdefaults")
                rtpDefaultsText = "*rtpName: %s\n*rtpEmail: %s\n*rtpLoc: %s\n*rtpPhone: \
                                 %s\n*rtpNote: %s\n"

                rtpDefaultsFH = open(rtpDefaultsFile, "w")
                rtpDefaultsFH.write(
                    rtpDefaultsText %
                    (profile.name, profile.email, profile.location,
                     profile.phoneNumber, profile.publicId))
                rtpDefaultsFH.close()
            except:
                self.log.exception("Error writing RTP defaults file: %s",
                                   rtpDefaultsFile)

        elif IsWindows():
            try:
                #
                # Set RTP defaults according to the profile
                #
                k = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER,
                                      r"Software\Mbone Applications\common")

                # Vic reads these values (with '*')
                _winreg.SetValueEx(k, "*rtpName", 0, _winreg.REG_SZ,
                                   profile.name)
                _winreg.SetValueEx(k, "*rtpEmail", 0, _winreg.REG_SZ,
                                   profile.email)
                _winreg.SetValueEx(k, "*rtpPhone", 0, _winreg.REG_SZ,
                                   profile.phoneNumber)
                _winreg.SetValueEx(k, "*rtpLoc", 0, _winreg.REG_SZ,
                                   profile.location)
                _winreg.SetValueEx(k, "*rtpNote", 0, _winreg.REG_SZ,
                                   str(profile.publicId))
                _winreg.CloseKey(k)
            except:
                self.log.exception("Error writing RTP defaults to registry")
        else:
            self.log.error("No support for platform: %s", sys.platform)
Пример #5
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
Пример #6
0
#-----------------------------------------------------------------------------
# Name:        Config.py
# Purpose:     Configuration objects for applications using the toolkit.
#              there are config objects for various sub-parts of the system.
# Created:     2003/05/06
# RCS-ID:      $Id: Config.py,v 1.6 2006-05-10 01:30:04 willing Exp $
# Copyright:   (c) 2002
# Licence:     See COPYING.TXT
#-----------------------------------------------------------------------------
"""
"""
__revision__ = "$Id: Config.py,v 1.6 2006-05-10 01:30:04 willing Exp $"

import sys
from AccessGrid.Platform import IsWindows, IsLinux, IsOSX, IsFreeBSD

if IsWindows():
    from AccessGrid.Platform.win32.Config import *
elif IsLinux() or IsOSX() or IsFreeBSD():
    from AccessGrid.Platform.unix.Config import *
else:
    print "No support for Platform %s" % sys.platform
Пример #7
0
    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 **
        #self.privateId=self.appProxy.Join(ClientProfile('./profile'))

        #
        # Retrieve the channel id
        #
        (self.channelId, address, port ) = self.appProxy.GetDataChannel(self.privateId)

        # 
        # Subscribe to the event channel
        #
        #self.eventClient = EventClient.EventClient(eventServiceLocation, self.channelId)
        #self.eventClient.start()
        #self.eventClient.Send(Events.ConnectEvent(self.channelId))

        #
        # Register the 'view' event callback
        #
        # The callback function is invoked with one argument, the data from the call.
        #self.eventClient.RegisterCallback("view", self.ViewCallback )

        # Get the connection state and print it
        self.vncContact = self.appProxy.GetData(self.privateId, "VNC_Contact");
        self.vncGeometry = self.appProxy.GetData(self.privateId, "VNC_Geometry");
        self.vncDepth = self.appProxy.GetData(self.privateId, "VNC_Depth");
        # Read password from app object
        encoded_pwd = self.appProxy.GetData(self.privateId, "VNC_Pwd")

        print "VNC Server at %s (%s, %s-bits):"%(self.vncContact,self.vncGeometry,self.vncDepth);
        self.passwdFilename=os.path.join(UserConfig.instance().GetTempDir(), ("passwd-" + str(GUID()) + ".vnc"))
        # Write password to file so it can be passed to vnc.
        pwd_file = file(self.passwdFilename, 'wb')
        pwd_file.write(base64.decodestring(encoded_pwd))
        pwd_file.close()


        # Change to the location of the application before running, since helper executables are located here.
        print "Running from directory", os.getcwd()

        execString = ""
        if IsWindows():
            width=eval(self.vncGeometry.split('x')[0]);
            if width >= 5120:
                execString='vncviewer -shared -scale 1/4 -passwd %s %s'%(self.passwdFilename,self.vncContact)
            elif width >= 4096:
                execString='vncviewer -shared -scale 1/3 -passwd %s %s'%(self.passwdFilename,self.vncContact)
            elif width >= 3072:
                execString='vncviewer -shared -scale 1/2 -passwd %s %s'%(self.passwdFilename,self.vncContact)
            else:
                execString='vncviewer -shared -passwd %s %s'%(self.passwdFilename,self.vncContact)                
        elif IsLinux():
            if os.path.exists("/usr/local/bin/vncviewer") or os.path.exists("/usr/bin/vncviewer"):
		execString='vncviewer -shared -passwd %s %s'%(self.passwdFilename,self.vncContact)
            else:
		execString='chmod +x ./vncviewer; ./vncviewer -shared -passwd %s %s'%(self.passwdFilename,self.vncContact)
        elif IsFreeBSD():
            if os.path.exists("/usr/local/bin/vncviewer") or os.path.exists("/usr/X11R6/bin/vncviewer"):
		execString='vncviewer -shared -passwd %s %s'%(self.passwdFilename,self.vncContact)
            else:
		execString='chmod +x ./vncviewer; ./vncviewer -shared -passwd %s %s'%(self.passwdFilename,self.vncContact)
        elif IsOSX():
            vncviewer='/Applications/Chicken\ of\ the\ VNC.app/Contents/MacOS/Chicken\ of\ the\ VNC'
            execString='%s --PasswordFile %s %s' % (vncviewer,self.passwdFilename,self.vncContact)
        else:
            raise Exception("Unsupported platform")
        print "About the execute: %s"%(execString)
        log.info("Starting vnc client: %s", execString)
        os.system(execString);
        os.unlink(self.passwdFilename);
Пример #8
0
    def start(self):
        log.debug('vncServer.start')
        if self.isRunning():
            raise VNCServerException("Start attempted while already running")
        try:
            if IsWindows():
                # Convert the password to hex for windows command line
                password = ''
                for ch in self.password:
                    password += '%x' % (ord(ch),)
                args = [
                        'Password='******'AlwaysShared=1',
                        ]

                log.info("starting vnc server: %s %s" % (self.vncserverexe,args))
                p = self.processManager.StartProcess(self.vncserverexe,args)
                log.debug("  pid = %s" % (p,))
            elif IsOSX():
                self.writePasswordFile()
                args = [
                        '-rfbauth',
                        self.passwdFilename,
                        '-alwaysshared',
                        ]
                log.info("starting vnc server: %s %s" % (self.vncserverexe,args))
                p = self.processManager.StartProcess(self.vncserverexe,args)
                log.debug("  pid = %s" % (p,))

            elif IsLinux() or IsFreeBSD():
                # Add entry in the xauthority file similar to the way
                #     vncserver does.
                cookie = commands.getoutput("/usr/bin/mcookie")
                hostname = commands.getoutput("uname -n")
                command = "xauth add %s%s . %s" % (hostname, self.displayID, cookie)
                os.system(command)
                command = "xauth add %s/unix%s . %s" %(hostname, self.displayID, cookie)
                os.system(command)

                self.writePasswordFile()
                args = [
                        self.displayID,
                        '-geometry', '%dx%d' % (self.geometry['Width'],self.geometry['Height']),
                        '-depth', self.depth,
                        '-rfbauth', self.passwdFilename,
                        '-alwaysshared'
                        ]
                log.info("starting vnc server: %s %s" % (self.vncserverexe,args))
                p = self.processManager.StartProcess(self.vncserverexe,args)
                log.debug("  pid = %s" % (p,))
                
                # Wait, then run xstartup
                time.sleep(2)
                # set paths to find config files
                venuevnc_path = os.path.join(os.environ["HOME"], ".venuevnc")
                xstartup = os.path.join(venuevnc_path, "xstartup")
                # if xstartup file does not exist, create one.
                if not os.path.exists(xstartup):
                    log.info("Creating xstartup file")
                    if not os.path.exists(venuevnc_path):
                        os.mkdir(venuevnc_path)
                    f = file(xstartup, "w+")
                    # default is the same as tight vnc's default, but use mwm
                    # instead of twm if it is available 
                    windowmanager = "twm"
                    if os.path.exists("/usr/X11R6/bin/mwm") or os.path.exists("/usr/bin/mwm"):
                        windowmanager = "mwm -xrm 'Mwm*usePager: false' -xrm 'Mwm*edgeScrollX:0' -xrm 'Mwm*edgeScrollY:0' " 
                    defaultStartup= "#!/bin/sh\n\n" +     \
                        "#xrdb $HOME/.Xresources\n" +     \
                        "xsetroot -solid grey\n" +        \
                        "xterm -geometry 80x24+10+10 -ls -title \"VenueVNC Desktop\" &\n" +    \
                        windowmanager + " &\n"
                    f.write(defaultStartup)
                    f.close()
                    os.chmod(xstartup,0755)
                else:
                    log.info("Using existing xstartup file")

                os.environ["DISPLAY"] = self.displayID
                if os.path.exists(xstartup):
                    log.info("Running x startup script %s" % ( xstartup,))
                    self.processManager.StartProcess(xstartup,[])
                else:
                    log.info("Running MWM")
                    self.processManager.StartProcess('mwm',[])
                    
                    
                self.running = 1
        except:
            log.exception("Failed to start vncServer")
            raise
Пример #9
0
from AccessGrid import Events
from AccessGrid import Toolkit
from AccessGrid.Platform.Config import UserConfig, SystemConfig
from AccessGrid.Platform import IsWindows, IsLinux, IsOSX, IsFreeBSD
from AccessGrid import DataStore
from AccessGrid.GUID import GUID
from AccessGrid.DataStoreClient import GetVenueDataStore
from AccessGrid.Toolkit import CmdlineApplication
from AccessGrid.Platform.ProcessManager import ProcessManager
from AccessGrid.Venue import VenueIW
from AccessGrid.SharedApplication import SharedApplicationIW

from AccessGrid.ClientProfile import ClientProfile

if IsLinux() or IsFreeBSD():
    import commands

log = None

# Generic exception to indicate failure.  More precision should come later.
class VNCServerException(Exception):
    pass

class VNCAppServerException(Exception):
    pass
    
class vncServer:
    def __init__(self,vncserverexe,displayID,geometry="1024x768",depth=24):
        
            
    def Start(self):
        """Start service"""
        try:
            # Enable firewall
            self.sysConf.AppFirewallConfig(self.executable, 1)

            # Resolve assigned resource to a device understood by vic
            print "self.resource = ", type(self.resource), self.resource
            print "res = ", self.resource.resource
            if self.resource == "None":
                vicDevice = "None"
            else:
                vicDevice = self.resource.resource
                if IsLinux() and vicDevice.startswith('/dev/video'):
                    # Translate vic device name to a name understood
                    # by openmash (linux only)
                    vicDeviceNum = vicDevice[-1]
                    vicDevice = 'VideoCapture/V4l' + vicDeviceNum
                vicDevice = vicDevice.replace("[", "\[")
                vicDevice = vicDevice.replace("]", "\]")

            if IsWindows():
                try:
                    self.MapWinDevice(self.resource.resource)
                except:
                    self.log.exception("Exception mapping device")

            #
            # Write vic startup file
            #
            startupfile = os.path.join(
                UserConfig.instance().GetTempDir(),
                'VideoProducerService_%d.vic' % (os.getpid()))

            if self.port.value == '':
                portstr = "None"
            else:
                portstr = self.port.value

            name = email = "Participant"
            if self.profile:
                name = self.profile.name
                email = self.profile.email
            else:
                # Error case
                name = email = Toolkit.GetDefaultSubject().GetCN()
                self.log.error("Starting service without profile set")

            # Replace double backslashes in the startupfile name with single
            #  forward slashes (vic will crash otherwise)
            if IsWindows():
                startupfile = startupfile.replace("\\", "/")

            #
            # Start the service; in this case, store command line args in a list and let
            # the superclass _Start the service
            options = []
            options.append("headlessVideo.mash")
            #options.append( "-u" )
            #options.append( startupfile )
            #options.append( "-C" )
            #options.append( '"' + self.streamname.value + '"'  )
            if self.streamDescription.encryptionFlag != 0:
                options.append("-K")
                options.append(self.streamDescription.encryptionKey)

            # Check whether the network location has a "type" attribute
            # Note: this condition is only to maintain compatibility between
            # older venue servers creating network locations without this attribute
            # and newer services relying on the attribute; it should be removed
            # when the incompatibility is gone
            if self.streamDescription.location.__dict__.has_key("type"):
                # use TTL from multicast locations only
                if self.streamDescription.location.type == MulticastNetworkLocation.TYPE:
                    options.append("-t")
                    options.append('%d' %
                                   (self.streamDescription.location.ttl))
            options.append('-F')
            options.append(self.framerate.value)
            options.append('-bps')
            options.append(self.bandwidth.value)
            options.append('-q')
            options.append(self.quality.value)
            options.append('-f')
            options.append(self.encoding.value)
            #options.append(' '); options.append(self.standard.value)
            #options.append('-D'); options.append(vicDevice)
            options.append('-D')
            options.append('VideoCapture/Test')
            options.append('-p')
            options.append('blue_passion')
            #options.append('-p'); options.append(portstr)
            options.append('-name')
            options.append("%s(%s)" % (name, self.streamname.value))
            options.append('-email')
            options.append(email)
            options.append('-omft')
            options.append(self.standard.value)

            # Address/port is last option
            options.append('%s/%d' % (self.streamDescription.location.host,
                                      self.streamDescription.location.port))

            self.log.info("Starting VideoProducerService")
            self.log.info(" executable = %s" % self.executable)
            self.log.info(" options = %s" % options)
            self._Start(options)
            #os.remove(startupfile)
        except:
            self.log.exception("Exception in VideoProducerService.Start")
            raise Exception("Failed to start service")