def test_150_SetIdentity(self): global nodeService profile = ClientProfile(UserConfig.instance().GetProfile()) nodeService.SetIdentity(profile)
def test_200_StoreConfiguration(self): global nodeService, server, smurl global NumSavedServiceManagers, NumSavedServices global ConfigName svcList = nodeService.GetServices() NumSavedServices = len(svcList) smList = nodeService.GetServiceManagers() NumSavedServiceManagers = len(smList) # Store the configuration as a new name print "Testing store of new node configuration" nodeConfigDir = os.path.join(UserConfig.instance().GetConfigDir(), "nodeConfig") files = os.listdir(nodeConfigDir) if ConfigName in files: os.remove(os.path.join(nodeConfigDir,ConfigName)) nodeService.StoreConfiguration(ConfigName) # Try to overwrite the configuration by writing # it a second time print "Testing store of existing node configuration" nodeService.StoreConfiguration(ConfigName)
def test_200_StoreConfiguration(self): global nodeService, server, smurl global NumSavedServiceManagers, NumSavedServices global ConfigName svcList = nodeService.GetServices() NumSavedServices = len(svcList) smList = nodeService.GetServiceManagers() NumSavedServiceManagers = len(smList) # Store the configuration as a new name print "Testing store of new node configuration" nodeConfigDir = os.path.join(UserConfig.instance().GetConfigDir(), "nodeConfig") files = os.listdir(nodeConfigDir) if ConfigName in files: os.remove(os.path.join(nodeConfigDir, ConfigName)) nodeService.StoreConfiguration(ConfigName) # Try to overwrite the configuration by writing # it a second time print "Testing store of existing node configuration" nodeService.StoreConfiguration(ConfigName)
def testUserConfigDir(self): configDir = UserConfig.instance().GetConfigDir() #print "User config dir (using temp name): ", configDir assert configDir != "" and configDir is not None, 'empty config dir' expectedDir = os.path.join(self.userdir, "Config") assert configDir == expectedDir, 'User config dir %s != UserConfig...GetConfigDir() %s' % ( configDir, expectedDir)
def test_100_Setup(self): global nodeService, server, log, smurl, serviceManager # initialize toolkit and environment app = Toolkit.Service.instance() app.Initialize("Node_test", sys.argv[:1]) log = app.GetLog() # Create a hosting environment server = Server(('localhost', 4000)) # Create a Node Service nodeService = AGNodeService() # Create the Node Service Service nsurl = server.RegisterObject(AGNodeServiceI(nodeService), path="/NodeService") print "NS URL: %s" % nsurl # Tell the world where to find the service log.info("Started node service; URI: %s", nsurl) # Create a Service Manager serviceManager = AGServiceManager(server) # Create the Service Manager Service smurl = server.RegisterObject(AGServiceManagerI(serviceManager), path="/ServiceManager") print "SM URL: %s" % smurl serviceManager = AGServiceManagerIW(smurl) # Tell the world where to find the service log.info("Started service manager; URI: %s", smurl) # Run the service server.RunInThread() # Remove some service packages from the local services # dir, to force the service manager to retrieve some packages # from the node service servicesDir = os.path.join(UserConfig.instance().GetConfigDir(), 'local_services') serviceFileList = os.listdir(servicesDir) halfTheServices = len(serviceFileList) / 2 for i in range(halfTheServices): print "Removing service dir ", serviceFileList[i] dir = os.path.join(servicesDir,serviceFileList[i]) if os.path.isdir(dir): dirFiles = os.listdir(dir) # remove files in the dir map( lambda f: os.remove(os.path.join(dir,f)), dirFiles) # remove the dir os.rmdir(dir)
def test_100_Setup(self): global nodeService, server, log, smurl, serviceManager # initialize toolkit and environment app = Toolkit.Service.instance() app.Initialize("Node_test", sys.argv[:1]) log = app.GetLog() # Create a hosting environment server = Server(('localhost', 4000)) # Create a Node Service nodeService = AGNodeService() # Create the Node Service Service nsurl = server.RegisterObject(AGNodeServiceI(nodeService), path="/NodeService") print "NS URL: %s" % nsurl # Tell the world where to find the service log.info("Started node service; URI: %s", nsurl) # Create a Service Manager serviceManager = AGServiceManager(server) # Create the Service Manager Service smurl = server.RegisterObject(AGServiceManagerI(serviceManager), path="/ServiceManager") print "SM URL: %s" % smurl serviceManager = AGServiceManagerIW(smurl) # Tell the world where to find the service log.info("Started service manager; URI: %s", smurl) # Run the service server.RunInThread() # Remove some service packages from the local services # dir, to force the service manager to retrieve some packages # from the node service servicesDir = os.path.join(UserConfig.instance().GetConfigDir(), 'local_services') serviceFileList = os.listdir(servicesDir) halfTheServices = len(serviceFileList) / 2 for i in range(halfTheServices): print "Removing service dir ", serviceFileList[i] dir = os.path.join(servicesDir, serviceFileList[i]) if os.path.isdir(dir): dirFiles = os.listdir(dir) # remove files in the dir map(lambda f: os.remove(os.path.join(dir, f)), dirFiles) # remove the dir os.rmdir(dir)
def writePasswordFile(self): # Create the password filename self.passwdFilename=os.path.join(UserConfig.instance().GetTempDir(),"passwd-%s.vnc"%(self.guid)) # Write password file f = file(self.passwdFilename,'wb') f.write(self.password) f.close()
def __init__(self, cachePath=""): if len(cachePath): self.cachePath = cachePath else: userConfig = UserConfig.instance() self.cachePath = os.path.join(userConfig.GetConfigDir(), "profileCache") if not os.path.exists( self.cachePath ): os.mkdir (self.cachePath)
def GetProxyPath(self): """ Determine the path into which the proxy should be installed. If identity is not None, it should be a CertificateDescriptor for the identity we're creating a proxy (future support for multiple active identities). """ return UserConfig.instance().GetProxyFile()
def __init__(self, cachePath=""): if len(cachePath): self.cachePath = cachePath else: userConfig = UserConfig.instance() self.cachePath = os.path.join(userConfig.GetConfigDir(), "profileCache") if not os.path.exists(self.cachePath): os.mkdir(self.cachePath)
def setUp(self): # only way to clear the config seems to be to # set the instance to None. Config.AGTkConfig.theAGTkConfigInstance = None Config.UserConfig.theUserConfigInstance = None self.userdir = tempfile.mkdtemp() self.sysdir = tempfile.mkdtemp() self.foodir = os.path.join(self.sysdir, "foo") os.mkdir(self.foodir) try: self.origSysDir = os.environ[Platform.AGTK_LOCATION] except: self.origSysDir = None try: self.origUserDir = os.environ[Platform.AGTK_USER] except: self.origUserDir = None os.environ[Platform.AGTK_LOCATION] = self.sysdir os.environ[Platform.AGTK_USER] = self.userdir UserConfig.instance(initIfNeeded=1)
def __init__(self, appUrl, name, size=None): ''' Creates the shared application client, used for application service interaction, and opens a web browser for UI display. ''' wx.App.__init__(self, False) reactor.interleave(wx.CallAfter) # Create shared application client self.sharedAppClient = SharedAppClient(name) self.log = self.sharedAppClient.InitLogging() # Get client profile try: clientProfileFile = os.path.join( UserConfig.instance().GetConfigDir(), "profile") clientProfile = ClientProfile(clientProfileFile) except: self.log.info( "SharedAppClient.Connect: Could not load client profile, set clientProfile = None" ) clientProfile = None # Join the application session. self.sharedAppClient.Join(appUrl, clientProfile) # Register browse event callback self.sharedAppClient.RegisterEventCallback("browse", self.BrowseCallback) # Create Browser Window self.frame = wx.Frame(None, -1, "SharedBrowser", size=size) if sys.platform != Platform.WIN: self.frame.CreateStatusBar() self.browser = WebBrowser(self.frame, -1, self.log, self.frame) # Add callback for local browsing self.browser.add_navigation_callback(self.IBrowsedCallback) # Browse to the current url, if exists currentUrl = self.sharedAppClient.GetData("url") if currentUrl and len(currentUrl) > 0: self.browser.navigate(currentUrl) try: self.sharedAppClient.SetParticipantStatus(currentUrl) except: self.log.exception( "SharedBrowser:__init__: Failed to set participant status") self.frame.SetIcon(icons.getAGIconIcon()) self.frame.Show(1) self.SetTopWindow(self.frame)
def __init__(self, parent, name, appUrl, venueUrl, connectionId): wx.Panel.__init__(self, parent, -1) reactor.interleave(wx.CallAfter) # Create ActiveX interface to adobe acrobate reader self.pdf = PDFWindow(self) # Do UI layout self.__Layout() # Create UI events EVT_BUTTON(self, self.openButton.GetId(), self.OnOpenButton) EVT_BUTTON(self, self.prevButton.GetId(), self.OnPrevPageButton) EVT_BUTTON(self, self.nextButton.GetId(), self.OnNextPageButton) EVT_WINDOW_DESTROY(self, self.OnExit) # Create shared application client self.sharedAppClient = SharedAppClient(name) self.log = self.sharedAppClient.InitLogging() self.log.debug("PdfViewer.__init__: Start pdf viewer, venueUrl: %s, appUrl: %s"%(venueUrl, appUrl)) # Get client profile clientProfile = ClientProfile(UserConfig.instance().GetProfile()) # Join the application session. self.sharedAppClient.Join(appUrl, clientProfile) self.id = self.sharedAppClient.GetPublicId() # Register callbacks for external events self.sharedAppClient.RegisterEventCallback("openFile", self.OpenCallback) self.sharedAppClient.RegisterEventCallback("changePage", self.ChangePageCallback) # Create data store interface self.dataStoreClient = GetVenueDataStore(venueUrl, connectionId) self.file = None self.pageNr = 1 # Get current state self.file = str(self.sharedAppClient.GetData("file")) self.pageNr = int(self.sharedAppClient.GetData("page")) if not self.pageNr: self.pageNr = 1 if self.file: try: self.dataStoreClient.Download(self.file, "tmp") self.pdf.LoadFile("tmp") self.pdf.setCurrentPage( int(self.pageNr)) except: self.log.exception("PdfViewer.__init__: Download failed %s"%(self.file))
def __init__(self, appUrl, name, size=None): """ Creates the shared application client, used for application service interaction, and opens a web browser for UI display. """ wx.App.__init__(self, False) reactor.interleave(wx.CallAfter) # Create shared application client self.sharedAppClient = SharedAppClient(name) self.log = self.sharedAppClient.InitLogging() # Get client profile try: clientProfileFile = os.path.join(UserConfig.instance().GetConfigDir(), "profile") clientProfile = ClientProfile(clientProfileFile) except: self.log.info("SharedAppClient.Connect: Could not load client profile, set clientProfile = None") clientProfile = None # Join the application session. self.sharedAppClient.Join(appUrl, clientProfile) # Register browse event callback self.sharedAppClient.RegisterEventCallback("browse", self.BrowseCallback) # Create Browser Window self.frame = wx.Frame(None, -1, "SharedBrowser", size=size) if sys.platform != Platform.WIN: self.frame.CreateStatusBar() self.browser = WebBrowser(self.frame, -1, self.log, self.frame) # Add callback for local browsing self.browser.add_navigation_callback(self.IBrowsedCallback) # Browse to the current url, if exists currentUrl = self.sharedAppClient.GetData("url") if currentUrl and len(currentUrl) > 0: self.browser.navigate(currentUrl) try: self.sharedAppClient.SetParticipantStatus(currentUrl) except: self.log.exception("SharedBrowser:__init__: Failed to set participant status") self.frame.SetIcon(icons.getAGIconIcon()) self.frame.Show(1) self.SetTopWindow(self.frame)
def UnregisterPlugin(self, name): noSpaceName = '_'.join(name.split(' ')) dstPath = os.path.join(UserConfig.instance().GetPluginDir(), noSpaceName) if os.path.exists(dstPath): try: shutil.rmtree(dstPath) print "Unregistration of application %s complete" % (name) except: print "App directory error -- can't remove (%s)." % dstPath else: print "Application %s not found; skipping" % (name) return 0 return self._remove_plugin(name)
def OnImportCertificate(self, event): if self.selectedItem is None: return item = self.reqList[self.selectedItem] status = self.certStatus[self.selectedItem] cert = status[1] # # Write the cert out to a tempfile, then import. # hash = NewMd5Hash(cert).hexdigest() tempfile = os.path.join(UserConfig.instance().GetTempDir(), "%s.pem" % (hash)) try: try: fh = open(tempfile, "w") fh.write(cert) fh.close() certMgr = Toolkit.Application.instance().GetCertificateManager() impCert = certMgr.ImportRequestedCertificate(tempfile) MessageDialog(self, "Successfully imported certificate for\n" + str(impCert.GetSubject()), "Import Successful") self.AddCertificates() except RepoInvalidCertificate, e: log.exception("Invalid certificate") msg = e[0] ErrorDialog(self, "The import of your approved certificate failed:\n"+ msg, "Import Failed") except: log.exception("Import of requested cert failed") ErrorDialog(self, "The import of your approved certificate failed.", "Import Failed")
def __init__(self, path=None, filename="PluginDatabase"): self.PluginDb = dict() if path is None: self.path = UserConfig.instance().GetConfigDir() else: self.path = path self.fileName = os.path.join(self.path, filename) if not os.path.exists(self.fileName): try: file(self.fileName, 'w').close() except: log.exception('Couldn\'t create app db file %s', self.fileName) self.Load(self.fileName)
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())
def __init__( self, appUrl, name): ''' Creates the shared application client, used for application service interaction, and opens the audience/moderatorView for UI display. ''' Model.__init__(self) self.allQuestions = [] # Create shared application client self.sharedAppClient = SharedAppClient(name) self.log = self.sharedAppClient.InitLogging() self.log.debug("SharedQuestionTool.__init__:Started shared question tool appUrl %s" %(appUrl)) # Get client profile try: clientProfileFile = os.path.join(UserConfig.instance().GetConfigDir(), "profile") self.clientProfile = ClientProfile(clientProfileFile) except: self.log.info("SharedQuestionTool.__init__: Could not load client profile, set clientProfile = None") self.clientProfile = None # Join the application session self.sharedAppClient.Join(appUrl, self.clientProfile) self.publicId = self.sharedAppClient.GetPublicId() # Register event callback self.sharedAppClient.RegisterEventCallback(self.SEND_QUESTION, self.SendQuestionCb) self.sharedAppClient.RegisterEventCallback(self.REMOVE_QUESTION, self.RemoveQuestionCb) # Get all questions currently stored in the application service clients = self.sharedAppClient.GetDataKeys() if clients: for clientId in clients: try: list = self.sharedAppClient.GetData(clientId) if len(list) > 0: qlist = self.__FromXML(list) for question in qlist: self.allQuestions.append(question) except: self.log.exception("SharedQuestionTool.__init__: Failed to get questions")
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
def FindConfigFile(self, configFile): """ Locate given file in configuration directories: first check user dir, then system dir; return None if not found """ if self.userConfig is None: self.userConfig = UserConfig.instance() pathToFile = os.path.join(self.userConfig.GetConfigDir(), configFile) self.log.debug("Looking for: %s", pathToFile) if os.path.exists(pathToFile): return pathToFile pathToFile = os.path.join(self.agtkConfig.GetConfigDir(), configFile) self.log.debug("Looking for: %s", pathToFile) if os.path.exists(pathToFile): return pathToFile raise Exception, "File Not Found"
def FindConfigFile(self, configFile): """ Locate given file in configuration directories: first check user dir, then system dir; return None if not found """ if self.userConfig is None: self.userConfig = UserConfig.instance() pathToFile = os.path.join(self.userConfig.GetConfigDir(), configFile) self.log.debug("Looking for: %s", pathToFile) if os.path.exists( pathToFile ): return pathToFile pathToFile = os.path.join(self.agtkConfig.GetConfigDir(), configFile) self.log.debug("Looking for: %s", pathToFile) if os.path.exists( pathToFile ): return pathToFile raise Exception, "File Not Found"
def __init__(self, path=None, filename="ApplicationDatabase"): """ The constructor for the AppDb, it uses a file for persistent storage. """ self.AppDb = dict() if path is None: self.path = UserConfig.instance().GetConfigDir() else: self.path = path self.fileName = os.path.join(self.path, filename) # Create the file if it doesn't exist if not os.path.exists(self.fileName): try: file(self.fileName, 'w').close() except: log.exception("Couldn't create app db file %s", self.fileName) self.Load(self.fileName)
def registerApp(fileNames): import AccessGrid.Toolkit as Toolkit #app = Toolkit.GetApplication() #if app == None: #app = Toolkit.CmdlineApplication() app = Toolkit.CmdlineApplication.instance() appdb = AppDb() fn_list = [] for f in fileNames: fn_list.append(os.path.basename(f)) exeCmd = sys.executable + " " + fn_list[0] + " -v %(venueUrl)s -a %(appUrl)s" # Call the registration method on the applications database appdb.RegisterApplication("Shared Presentation", "application/x-ag-shared-presentation", "sharedpresentation", {"Open" : exeCmd }, fn_list, os.getcwd(), UserConfig.instance().GetSharedAppDir())
def __init__(self, path=None, filename="ApplicationDatabase"): """ The constructor for the AppDb, it uses a file for persistent storage. """ self.AppDb = dict() if path is None: self.path = UserConfig.instance().GetConfigDir() else: self.path = path self.fileName = os.path.join(self.path, filename) # Create the file if it doesn't exist if not os.path.exists(self.fileName): try: file(self.fileName,'w').close() except: log.exception("Couldn't create app db file %s", self.fileName) self.Load(self.fileName)
def registerApp(fileNames): import AccessGrid.Toolkit as Toolkit #app = Toolkit.GetApplication() #if app == None: #app = Toolkit.CmdlineApplication() app = Toolkit.CmdlineApplication.instance() appdb = AppDb() fn_list = [] for f in fileNames: fn_list.append(os.path.basename(f)) exeCmd = sys.executable + " " + fn_list[ 0] + " -v %(venueUrl)s -a %(appUrl)s" # Call the registration method on the applications database appdb.RegisterApplication("Shared Presentation", "application/x-ag-shared-presentation", "sharedpresentation", {"Open": exeCmd}, fn_list, os.getcwd(), UserConfig.instance().GetSharedAppDir())
def UnregisterApplication(self, name=None, mimeType=None, extension=None): """ Encapsulate all the actions required to unregister an application. returns 0 on failure, 1 on success """ noSpaceName = '_'.join(name.split(' ')) dstPath = os.path.join(UserConfig.instance().GetSharedAppDir(), noSpaceName) if os.path.exists(dstPath): try: shutil.rmtree(dstPath) print "Unregistration of application %s complete" % (name) except: print "App directory error -- can't remove (%s)." % dstPath else: print "Application %s not found; skipping" % (name) return 0 if mimeType == None: mimeType = self.GetMimeType(name, extension) if mimeType == None: print "MimeType: %s not found." % mimeType return 0 cmdList = self.GetCommandNames(mimeType) (ret, retStr) = self.RemoveMimeType(name, extension, mimeType) if ret: for cmdName in cmdList: (result, resultString) = self.RemoveCommand(mimeType, cmdName) if not result: print "Error removing verb, continuing." return 1
def __init__(self, dsc, name): """ Create a new venue file writer. dsc is the datastore client, name is the name of the file in the venue. """ self.dsc = dsc self.name = name self.open = 0 # # create a temporary directory for this file so # we can write it with the correct filename. # self.tempdir = os.path.join(UserConfig.instance().GetTempDir(), "DSClientTemp-%s" % (os.getpid())) os.mkdir(self.tempdir) self.localFile = os.path.join(self.tempdir, name) print "Creating local file ", self.localFile self.fh = open(self.localFile, "w") self.open = 1
def testUserConfigDir(self): configDir = UserConfig.instance().GetConfigDir() #print "User config dir (using temp name): ", configDir assert configDir != "" and configDir is not None, 'empty config dir' expectedDir = os.path.join(self.userdir, "Config") assert configDir == expectedDir, 'User config dir %s != UserConfig...GetConfigDir() %s' % (configDir, expectedDir)
def testGetServicesDir(self): servicesDir = UserConfig.instance().GetServicesDir() assert servicesDir != "" and servicesDir is not None, 'invalid services dir' assert os.path.isdir(servicesDir)
def testGetSharedAppDir(self): appDir = UserConfig.instance().GetSharedAppDir() assert appDir != "" and appDir is not None, 'empty user app dir' assert os.path.isdir(appDir)
def testGetLogDir(self): logDir = UserConfig.instance().GetLogDir() assert logDir != "" and logDir is not None, 'invalid log dir' assert os.path.isdir(logDir)
def Start(self): """Start service""" try: # Set processor affinity (windows only) if IsWindows(): try: if self.processorUsage.value == 'All': self.log.info( 'Setting processor affinity to all processors') SystemConfig.instance().SetProcessorAffinity( self.allProcsMask) else: val = 2**(int(self.processorUsage.value) - 1) self.log.info( 'Ssetting processor affinity : use processor %s', self.processorUsage.value) SystemConfig.instance().SetProcessorAffinity( int(self.processorUsage.value)) except: self.log.exception("Exception setting processor affinity") # Enable firewall self.sysConf.AppFirewallConfig(self.executable, 1) # Resolve assigned resource to a device understood by vic if self.resource == "None": vicDevice = "None" else: vicDevice = self.resource[0] vicDevice = vicDevice.replace("[", "\[") vicDevice = vicDevice.replace("]", "\]") if IsWindows(): try: self.MapWinDevice(self.resource[0]) except: self.log.exception("Exception mapping device") # # Write vic startup file # startupfile = os.path.join(UserConfig.instance().GetTempDir(), 'VideoProducerService_%s.vic' % self.id) f = open(startupfile, "w") 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") f.write(vicstartup % ( self.bandwidth.value, self.framerate.value, self.quality.value, self.encoding.value, self.standard.value, vicDevice, "%s(%s)" % (name, self.streamname.value), email, email, portstr, portstr)) f.close() # Open permissions on vic startupfile os.chmod(startupfile, 0777) # 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("-u") options.append(startupfile) options.append("-C") options.append(str(self.streamname.value)) if IsOSX(): options.append("-X") options.append("transmitOnStartup=1") if self.streamDescription.encryptionFlag != 0: options.append("-K") options.append(self.streamDescription.encryptionKey) if self.profile: options.append("-X") options.append("site=%s" % self.profile.publicId) options.append('-X') options.append('noMulticastBind=true') # 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('%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")
def Start( self ): """ Start service """ try: # Set processor affinity (windows only) if IsWindows(): try: if self.processorUsage.value == 'All': self.log.info('Setting processor affinity to all processors') SystemConfig.instance().SetProcessorAffinity(self.allProcsMask) else: val = 2**(int(self.processorUsage.value)-1) self.log.info('Ssetting processor affinity : use processor %s', self.processorUsage.value) SystemConfig.instance().SetProcessorAffinity(int(self.processorUsage.value)) except: self.log.exception("Exception setting processor affinity") # Enable firewall self.sysConf.AppFirewallConfig(self.executable, 1) # Resolve assigned resource to a device understood by vic if self.resource == "None": vicDevice = "None" else: vicDevice = self.resource[0] vicDevice = vicDevice.replace("[","\[") vicDevice = vicDevice.replace("]","\]") if IsWindows(): try: self.MapWinDevice(self.resource[0]) except: self.log.exception("Exception mapping device") # # Write vic startup file # startupfile = os.path.join(UserConfig.instance().GetTempDir(), 'VideoServiceH264_%s.vic' % self.id ) f = open(startupfile,"w") if self.port.value == '': portstr = "None" else: portstr = self.port.value if self.standard.value == '': standardstr = "None" else: standardstr = self.standard.value if self.muteSources.value == "On": # streams are muted, so disable autoplace disableAutoplace = "true" else: # streams are not muted, so don't disable autoplace # (flags should not be negative!) disableAutoplace = "false" if self.inputsize.value == "Small": inputsize = 4 elif self.inputsize.value == "Large" and self.encoding.value != "h261": inputsize = 1 else: inputsize = 2 if self.resolution != None: resolution = self.resolution.value else: resolution = "none" 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") f.write( vicstartup % ( disableAutoplace, OnOff(self.muteSources.value), self.bandwidth.value, self.framerate.value, self.quality.value, self.encoding.value, standardstr, vicDevice, "%s(%s)" % (name,self.streamname.value), email, OnOff(self.encodingDeinterlacer.value), resolution, email, OnOff(self.transmitOnStart.value), portstr, portstr, inputsize) ) f.close() # Open permissions on vic startupfile os.chmod(startupfile,0777) # 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( "-u" ) options.append( startupfile ) options.append( "-C" ) options.append( str(self.streamDescription.name) ) if IsOSX(): if self.transmitOnStart.value: options.append( "-X") options.append( "transmitOnStartup=1") if self.streamDescription.encryptionFlag != 0: options.append( "-K" ) options.append( self.streamDescription.encryptionKey ) # Set drop time to something reasonable options.append('-XsiteDropTime=5') if not self.positionWindow.value == 'Off': # - set vic window geometry try: if not self.windowGeometry: h = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_Y) w_sys = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_X) try: w = GetScreenWidth(w_sys,h) except ValueError: self.log.debug('Error computing screen width; using system screen width %d', w_sys) w = w_sys window_width = w-300 window_height = 300 window_x = 300 window_y = h-375 border_w = wx.SystemSettings_GetMetric(wx.SYS_FRAMESIZE_X) if border_w > 0: window_width -= 4*border_w window_x += 2*border_w self.windowGeometry = (window_width,window_height,window_x,window_y) if self.positionWindow.value == 'Justify Left': options.append('-Xgeometry=%dx%d+%d+%d' % self.windowGeometry) else: options.append('-Xgeometry=%dx%d-%d+%d' % self.windowGeometry) except: self.log.exception('Error calculating window placement') if self.profile: options.append("-X") options.append("site=%s" % self.profile.publicId) # Set number of columns to use for thumbnail display options.append("-Xtile=%s" % self.tiles.value) # 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( '%s/%d' % ( self.streamDescription.location.host, self.streamDescription.location.port) ) self.log.info("Starting VideoServiceH264") self.log.info(" executable = %s" % self.executable) self.log.info(" options = %s" % options) os.chdir(self.thepath) self._Start( options ) #os.remove(startupfile) except: self.log.exception("Exception in VideoServiceH264.Start") raise Exception("Failed to start service")
def Start(self): """ Start service """ try: # Set processor affinity (windows only) if IsWindows(): try: if self.processorUsage.value == 'All': self.log.info( 'Setting processor affinity to all processors') SystemConfig.instance().SetProcessorAffinity( self.allProcsMask) else: val = 2**(int(self.processorUsage.value) - 1) self.log.info( 'Ssetting processor affinity : use processor %s', self.processorUsage.value) SystemConfig.instance().SetProcessorAffinity( int(self.processorUsage.value)) except: self.log.exception("Exception setting processor affinity") # Enable firewall self.sysConf.AppFirewallConfig(self.executable, 1) # Resolve assigned resource to a device understood by vic if self.resource == "None": vicDevice = "None" else: vicDevice = self.resource[0] vicDevice = vicDevice.replace("[", "\[") vicDevice = vicDevice.replace("]", "\]") if IsWindows(): try: self.MapWinDevice(self.resource[0]) except: self.log.exception("Exception mapping device") # # Write vic startup file # startupfile = os.path.join(UserConfig.instance().GetTempDir(), 'VideoServiceH264_%s.vic' % self.id) f = open(startupfile, "w") if self.port.value == '': portstr = "None" else: portstr = self.port.value if self.standard.value == '': standardstr = "None" else: standardstr = self.standard.value if self.muteSources.value == "On": # streams are muted, so disable autoplace disableAutoplace = "true" else: # streams are not muted, so don't disable autoplace # (flags should not be negative!) disableAutoplace = "false" if self.inputsize.value == "Small": inputsize = 4 elif self.inputsize.value == "Large" and self.encoding.value != "h261": inputsize = 1 else: inputsize = 2 if self.resolution != None: resolution = self.resolution.value else: resolution = "none" 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") f.write( vicstartup % (disableAutoplace, OnOff(self.muteSources.value), self.bandwidth.value, self.framerate.value, self.quality.value, self.encoding.value, standardstr, vicDevice, "%s(%s)" % (name, self.streamname.value), email, OnOff(self.encodingDeinterlacer.value), resolution, email, OnOff( self.transmitOnStart.value), portstr, portstr, inputsize)) f.close() # Open permissions on vic startupfile os.chmod(startupfile, 0777) # 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("-u") options.append(startupfile) options.append("-C") options.append(str(self.streamDescription.name)) if IsOSX(): if self.transmitOnStart.value: options.append("-X") options.append("transmitOnStartup=1") if self.streamDescription.encryptionFlag != 0: options.append("-K") options.append(self.streamDescription.encryptionKey) # Set drop time to something reasonable options.append('-XsiteDropTime=5') if not self.positionWindow.value == 'Off': # - set vic window geometry try: if not self.windowGeometry: h = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_Y) w_sys = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_X) try: w = GetScreenWidth(w_sys, h) except ValueError: self.log.debug( 'Error computing screen width; using system screen width %d', w_sys) w = w_sys window_width = w - 300 window_height = 300 window_x = 300 window_y = h - 375 border_w = wx.SystemSettings_GetMetric( wx.SYS_FRAMESIZE_X) if border_w > 0: window_width -= 4 * border_w window_x += 2 * border_w self.windowGeometry = (window_width, window_height, window_x, window_y) if self.positionWindow.value == 'Justify Left': options.append('-Xgeometry=%dx%d+%d+%d' % self.windowGeometry) else: options.append('-Xgeometry=%dx%d-%d+%d' % self.windowGeometry) except: self.log.exception('Error calculating window placement') if self.profile: options.append("-X") options.append("site=%s" % self.profile.publicId) # Set number of columns to use for thumbnail display options.append("-Xtile=%s" % self.tiles.value) # 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('%s/%d' % (self.streamDescription.location.host, self.streamDescription.location.port)) self.log.info("Starting VideoServiceH264") self.log.info(" executable = %s" % self.executable) self.log.info(" options = %s" % options) os.chdir(self.thepath) self._Start(options) #os.remove(startupfile) except: self.log.exception("Exception in VideoServiceH264.Start") raise Exception("Failed to start service")
def __init__(self): self.bridges = [] self.config = UserConfig.instance(initIfNeeded=0) self.configPath = self.config.GetBridges()
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);
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); if __name__ == "__main__": app = CmdlineApplication.instance() app.Initialize("VenueVNCClient") log = app.GetLog() if len(sys.argv) < 2: print "Usage: %s <appObjectUrl>" % sys.argv[0] sys.exit(1) appUrl = sys.argv[1] clientProfileFile = os.path.join(UserConfig.instance().GetConfigDir(), "profile") clientProfile = ClientProfile(clientProfileFile) sb = vncSharedAppClient( appUrl, clientProfile )
def WriteNodeConfig(configName, config): """ Writes the given node config to the given node config name A 'config' is a dictionary keys: service manager urls values: [ [servicename, resource name, serviceconfig], ... ] serviceconfig should be a list of name,value pairs """ userNodeConfigDir = UserConfig.instance().GetNodeConfigDir() fileName = os.path.join(userNodeConfigDir, configName) hostname = SystemConfig.instance().GetHostname() # Catch inability to write config file if ((not os.path.exists(userNodeConfigDir)) or (not os.access(userNodeConfigDir, os.W_OK)) or (os.path.exists(fileName) and not os.access(fileName, os.W_OK))): log.exception("Can't write config file %s" % (fileName)) raise IOError(errno.EACCES, "Can't write config file %s" % (fileName)) numServiceManagers = 0 numServices = 0 node_servicemanagers = '' configParser = ConfigParser.ConfigParser() configParser.optionxform = str for key in config.keys(): builtin = 0 url = key name = url servicemanager_services = '' # # Create Service Manager section # serviceManagerSection = 'servicemanager%d' % numServiceManagers configParser.add_section(serviceManagerSection) node_servicemanagers += serviceManagerSection + " " if url.find(hostname) >= 0: builtin = 1 else: builtin = 0 configParser.set(serviceManagerSection, 'builtin', builtin) if builtin: configParser.set(serviceManagerSection, "name", '') configParser.set(serviceManagerSection, "url", '') else: configParser.set(serviceManagerSection, "name", name) configParser.set(serviceManagerSection, "url", url) services = config[key] if not services: services = [] for service in services: serviceName, resourceName, serviceConfig = service serviceSection = 'service%d' % numServices configParser.add_section(serviceSection) # # Create Resource section # if resourceName: log.debug('Storing resource: %s', resourceName) resourceSection = 'resource%d' % numServices configParser.add_section(resourceSection) configParser.set(resourceSection, "name", resourceName) configParser.set(serviceSection, "resource", resourceSection) else: log.debug('No resource specified') # # Create Service Config section # if serviceConfig: serviceConfigSection = 'serviceconfig%d' % numServices configParser.set(serviceSection, "serviceConfig", serviceConfigSection) configParser.add_section(serviceConfigSection) for k, v in serviceConfig: configParser.set(serviceConfigSection, k, v) # # Create Service section # servicemanager_services += serviceSection + " " configParser.set(serviceSection, "packageName", serviceName) numServices += 1 configParser.set(serviceManagerSection, "services", servicemanager_services) numServiceManagers += 1 configParser.add_section('node') configParser.set('node', "servicemanagers", node_servicemanagers) # # Write config file # fp = open(fileName, "w") fp.write("# AGTk %s node configuration\n" % (Version.GetVersion())) configParser.write(fp) fp.close()
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
def testGetProfile(self): profile = UserConfig.instance().GetProfile() assert profile != None
def __init__(self, parent, id, title, appUrl): wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(800, 600)) #wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(800, 600), wx.DEFAULT_FRAME_STYLE^(wx.RESIZE_BORDER | wx.MINIMIZE_BOX |wx.MAXIMIZE_BOX)) #self.SetIcon(wx.Icon('ico/sharedpaint.ico', wx.BITMAP_TYPE_ICO)) self.appUrl = appUrl # <AGtk code> reactor.interleave(wx.CallAfter) # Create shared application client self.sharedAppClient = SharedAppClient("SharedPaint") self.log = self.sharedAppClient.InitLogging() self.log.debug("GroupPaint.__init__: Started Group Paint") # Get client profile try: self.clientProfileFile = os.path.join( UserConfig.instance().GetConfigDir(), "profile") self.clientProfile = ClientProfile(self.clientProfileFile) except: self.log.info( "SharedQuestionTool.__init__: Could not load client profile, set clientProfile = None" ) self.clientProfile = None # Join the application session self.sharedAppClient.Join(self.appUrl, self.clientProfile) self.publicId = self.sharedAppClient.GetPublicId() self.user = self.clientProfile.GetName() self.id = self.sharedAppClient.GetPublicId() # Register event callback self.sharedAppClient.RegisterEventCallback(events.CONSOLE_EVENT, self.GetConsoleEventData) self.sharedAppClient.RegisterEventCallback(events.CLEAR_EVENT, self.GetClearEvent) #self.sharedAppClient.RegisterEventCallback(events.SET_BG_EVENT, self.GetSetBGEvent) # </AGtk code> """ Setting status bar """ self.CreateStatusBar() workspace = wx.BoxSizer(wx.VERTICAL) imagePanel = wx.Panel(self, -1, style=wx.SIMPLE_BORDER) """ Painter """ self.painter = DoodleWindow(imagePanel, -1, self.clientProfile, self.sharedAppClient) imageBox = wx.BoxSizer(wx.VERTICAL) imageBox.Add(self.painter, 1, wx.EXPAND | wx.ALL, 1) imagePanel.SetSizer(imageBox) """ Console settings """ consolePanel = wx.Panel(self, -1, style=wx.SIMPLE_BORDER) self.console = wx.TextCtrl(consolePanel, -1, style=wx.TE_MULTILINE) self.console.SetEditable(0) consoleBox = wx.BoxSizer(wx.VERTICAL) consoleBox.Add(self.console, 1, wx.EXPAND | wx.ALL, 1) consolePanel.SetSizer(consoleBox) workspace.Add(imagePanel, 4, wx.EXPAND | wx.ALL, 1) workspace.Add(consolePanel, 1, wx.EXPAND | wx.ALL, 1) self.SetSizer(workspace)
def testGetBaseDir(self): baseDir = UserConfig.instance().GetBaseDir() assert baseDir == self.userdir , 'incorrect base dir' assert os.path.isdir(baseDir)
def testGetConfigDir(self): configDir = UserConfig.instance().GetConfigDir() assert configDir != "" and configDir is not None, 'empty user config dir' expectedDir = os.path.join(self.userdir, "Config") assert configDir == expectedDir, 'AGTkConfig config dir %s != AGTkConfig...GetConfigDir() %s' % (configDir, expectedDir)
def testGetTempDir(self): tempDir = UserConfig.instance().GetTempDir() assert tempDir != "" and tempDir is not None, 'empty temp dir' assert os.path.isdir(tempDir), 'temp dir does not exist'
def InitAppAndProcessArgs(app): doc = """ By default this program registers/installs a shared application or node service with the users environment. Using the -u argument applications can be unregistered/uninstalled. To unregister node services, use the '--unregister-service' argument. """ tkConf = AGTkConfig.instance() app.AddCmdLineOption( Option("-u", "--unregister", action="store_true", dest="unregister", default=0, help="Unregister the application, instead of registering it. \ Specify application with '-n'")) app.AddCmdLineOption( Option("--unregister-service", action="store_true", dest="unregisterservice", default=0, help="Unregister the service, instead of registering it. \ Specify service with '-n'. (Requires administrative access)")) app.AddCmdLineOption( Option("--unregister-plugin", action="store_true", dest="unregisterplugin", default=0, help="Unregister the plugin, instead of registering it. \ Specify plugin with '-n'.")) app.AddCmdLineOption( Option( "-n", "--name", dest="appname", help="specify a name other than the default on from the .app file." )) app.AddCmdLineOption( Option("-v", "--verbose", action="store_true", dest="verbose", default=0, help="Be verbose during app processing.")) app.AddCmdLineOption( Option("-f", "--file", dest="appfile", help="The name of a .app file to install.")) # Remove conflicting options and readd without the shorter option. app.parser.remove_option("-d") # remove debug option app.parser.remove_option("-l") # remove logfile option # Unnecessary options app.parser.remove_option("--cert") app.parser.remove_option("--key") app.parser.remove_option("--cadir") app.parser.remove_option("--secure") # Readd debug option without the shorter -d. app.parser.add_option("--debug", action="store_true", dest="debug", default=0, help="Set the debug level of this program.") # Readd logfile option without the shorter -l. app.parser.add_option("--logfile", dest="logfilename", metavar="LOGFILE", default=None, help="Specify a log file to output logging to.") app.AddCmdLineOption( Option("-d", "--dir", dest="appdir", help="The name of a directory containing a .app file.")) app.AddCmdLineOption( Option("-z", "--zip", dest="appzip", help="The name of a .zip file containing a .app or .svc file.\ (Requires administrative access to install services)" )) app.AddCmdLineOption( Option("-p", "--package", dest="apppkg", help="The name of an agpkg file containing a .app or .svc \ file. (Requires administrative access to install services)" )) app.AddCmdLineOption( Option("-l", "--list-apps", action="store_true", dest="listapps", help="List installed shared apps.")) app.AddCmdLineOption( Option("--list-services", action="store_true", dest="listservices", help="List installed node services.")) app.AddCmdLineOption( Option("--list-plugins", action="store_true", dest="listplugins", help="List installed plugins.")) app.AddCmdLineOption( Option("-s", "--system", action="store_true", dest="sys_install", default=0, help="Install the package for all users. \ (This requires administrative access)")) app.AddCmdLineOption( Option("--post-install", action="store_true", dest="post_install", default=0, help="Do a post-installation run, which will install \ all apps distributed with the toolkit in the system \ if possible. (This requires administrative access)")) app.AddCmdLineOption( Option("--wait-for-input", action="store_true", dest="wait_for_input", default=0, help="After completing wait for the user to confirm by\ pressing a key.")) app.AddCmdLineOption( Option( "--gui", action="store_true", dest="useGui", help="Show if the installation was successful with a GUI dialog.")) args = app.Initialize("agpm") if True == app.GetOption("useGui"): global gUseGui gUseGui = True # Validate arguments if not ( # these args imply an action app.options.appzip or app.options.apppkg or app.options.appfile or app.options.appdir # these are explicit actions or app.options.post_install or app.options.listservices or app.options.listapps or app.options.listplugins or app.options.unregister or app.options.unregisterservice or app.options.unregisterplugin): app.parser.print_help() ShowResult("Error: no action specified") sys.exit(1) if app.options.sys_install or app.options.post_install: appdb = AppDb(path=tkConf.GetConfigDir()) plugindb = PluginDb(path=tkConf.GetConfigDir()) appdest = tkConf.GetSharedAppDir() plugindest = tkConf.GetPluginDir() else: appdb = AppDb() plugindb = PluginDb() appdest = UserConfig.instance().GetSharedAppDir() plugindest = UserConfig.instance().GetPluginDir() return app.options, appdb, plugindb, appdest, plugindest
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")