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")
Exemple #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
        """
        if profile == None:
            self.log.exception("Invalid profile (None)")
            raise Exception, "Can't set RTP Defaults without a valid profile."

        if IsLinux() or IsOSX() or IsFreeBSD():
            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)
Exemple #5
0
    def GetInstallDir(self):
        try:
            self.installDir = os.environ[AGTK_LOCATION]
        except:
            if IsFreeBSD():
                self.installDir = "/usr/local"
            else:
                self.installDir = "/usr"

        # Check dir and make it if needed.
        if self.initIfNeeded:
            if self.installDir is not None and \
                   not os.path.exists(self.installDir):
                os.mkdir(self.installDir)

        # Check the installation
        if self.installDir is not None and not os.path.exists(self.installDir):
            raise Exception, "AGTkConfig: install dir does not exist."

        return self.installDir
Exemple #6
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
#-----------------------------------------------------------------------------
# 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
Exemple #8
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);
Exemple #9
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
Exemple #10
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):
        
            
Exemple #11
0
class AGTkConfig(Config.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.

    """
    if IsFreeBSD():
        AGTkBasePath = "/usr/local/etc/AccessGrid3"
    else:
        AGTkBasePath = "/etc/AccessGrid3"

    def instance(initIfNeeded=0):
        if Config.AGTkConfig.theAGTkConfigInstance == None:
            AGTkConfig(initIfNeeded)

        return Config.AGTkConfig.theAGTkConfigInstance

    instance = staticmethod(instance)

    def GetBaseDir(self):
        if self.installBase == None:
            try:
                self.installBase = os.environ[AGTK_LOCATION]
            except:
                self.installBase = self.AGTkBasePath

        # remove trailing "\bin" if it's there
        if self.installBase.endswith("bin"):
            self.installBase = os.path.join(
                os.path.split(self.installBase)[:-1])[0]

        # Check the installation
        if not os.path.exists(self.installBase):
            raise Exception, "AGTkConfig: installation base does not exist (%s)" % self.installBase

        return self.installBase

    def GetInstallDir(self):
        try:
            self.installDir = os.environ[AGTK_LOCATION]
        except:
            if IsFreeBSD():
                self.installDir = "/usr/local"
            else:
                self.installDir = "/usr"

        # Check dir and make it if needed.
        if self.initIfNeeded:
            if self.installDir is not None and \
                   not os.path.exists(self.installDir):
                os.mkdir(self.installDir)

        # Check the installation
        if self.installDir is not None and not os.path.exists(self.installDir):
            raise Exception, "AGTkConfig: install dir does not exist."

        return self.installDir

    def GetBinDir(self):
        binDir = os.path.join(self.GetInstallDir(), "bin")
        return binDir

    def GetDocDir(self):
        if sys.platform == 'darwin':
            self.docDir = os.path.join(self.GetInstallDir(), "doc")
        else:
            self.docDir = os.path.join(self.GetInstallDir(), "share", "doc",
                                       "AccessGrid-" + str(GetVersion()))

    #    # Check dir and make it if needed.
    #    if self.initIfNeeded:
    #        if self.docDir is not None and \
    #               not os.path.exists(self.docDir):
    #            if os.path.exists(self.GetBaseDir()):
    #                os.makedirs(self.docDir)

    #    # Check the installation
    #    #if self.docDir is not None and not os.path.exists(self.docDir):
    #    #    raise Exception, "AGTkConfig: doc dir does not exist."
    #
        return self.docDir