def registerApp(fileName): import AccessGrid.Toolkit as Toolkit app = Toolkit.CmdlineApplication() appdb = app.GetAppDatabase() fn = os.path.basename(fileName) exeCmd = sys.executable + " " + fn + " -a %(appUrl)s" # Call the registration method on the applications database #appdb.RegisterApplication("Shared Covise", # "application/x-ag-shared-covise", # "sharedcovise", # {"Open" : exeCmd }, # [fn], os.getcwd()) # old init have to be changed soon uad = Platform.GetUserAppPath() src = os.path.abspath(fn) dest = os.path.join(uad, fn) exeCmd = sys.executable + " \"" + dest + "\" -a %(appUrl)s" print("hallo" + src + " to " + dest) try: shutil.copyfile(src, dest) except IOError: print "could not copy app into place" sys.exit(1) # Call the registration method on the applications database appdb.RegisterApplication("Shared Covise", "application/x-ag-covise", "sharedcovise", {"Open": exeCmd})
def ImportPEMIdentityCertificate(certMgr, certFile, keyFile): """ Import a PEM-formatted X509 identity certificate. @param certFile: File containing the certificate. @param keyFile: File containing the private key. """ try: print "Import PEM, looking for cb" cb = Toolkit.GetDefaultApplication().GetCertificateManagerUI( ).GetPassphraseCallback("Private key passphrase", "Enter the passphrase to your private key.") impCert = certMgr.ImportIdentityCertificatePEM( certMgr.GetCertificateRepository(), certFile, keyFile, cb) log.debug("Imported identity %s", str(impCert.GetSubject())) except CertificateRepository.RepoInvalidCertificate, ex: why = ex.args[0] log.exception("Import fails: %s. cert file %s keyfile %s", why, certFile, keyFile) dlg = wx.MessageDialog(None, "Error occurred during certificate import:\n" + why, "Error on import", style=wx.OK | wx.ICON_ERROR) dlg.ShowModal() dlg.Destroy() return
def OnSetDefault(self, event): cert = self.GetSelectedCertificate() if cert is None: return self.certMgr.SetDefaultIdentity(cert) Toolkit.GetDefaultApplication().GetCertificateManagerUI().InitEnvironment() self.Load()
def GetPassphrase(self,verifyFlag=0, prompt1="Enter the passphrase to your private key.", prompt2='Verify passphrase:'): # note: verifyFlag is unused from AccessGrid import Toolkit cb = Toolkit.GetDefaultApplication().GetCertificateManagerUI().GetPassphraseCallback(prompt1, prompt2) p1 = cb(0) passphrase = ''.join(p1) return passphrase
def registerApp(fileName): import AccessGrid.Toolkit as Toolkit app = Toolkit.CmdlineApplication() appdb = app.GetAppDatabase() fn = os.path.basename(fileName) exeCmd = sys.executable + " " + fn + " -a %(appUrl)s" # Call the registration method on the applications database appdb.RegisterApplication("Shared Covise", "application/x-ag-shared-covise", "sharedcovise", {"Open": exeCmd}, [fn], os.getcwd())
def test_100_Setup(self): global venueServer, processManager, venue, venueUrl # initialize toolkit and environment app = Toolkit.Service().instance() app.Initialize("Node_test", sys.argv[:1]) log = app.GetLog() # Start process manager processManager = ProcessManager() # Find venue server exe bin = AGTkConfig.instance().GetBinDir() venueserverexe = os.path.join(bin, 'VenueServer.py') # Start the venue server exe = sys.executable opts = [ venueserverexe, '-p', str(venueserverport), ] processManager.StartProcess(exe, opts) # Create proxy to the venue server venueServer = VenueServerIW('https://localhost:%d/VenueServer' % (venueserverport, )) # Wait for server to become reachable print "Wait for venue server..." up = 0 while not up: try: up = venueServer.IsValid() print "up = ", up continue except: print "waiting for venue server..." pass time.sleep(1) venueUrl = venueServer.GetDefaultVenue() venue = VenueIW(venueUrl)
def RemoveSubject(self, subject): """ This method removes the specified subject from the role. @param subject: the subject to be removed. @type subject: AccessGrid.Security.Subject object @raises InvalidSubject: when the subject passed in not a subclass of the AccessGrid.Security.Subject base class. """ if not isinstance(subject, Subject): raise InvalidSubject if Toolkit.GetDefaultSubject() == subject and self.requireDefaultId: raise DefaultIdentityNotRemovable(subject) if subject not in self.subjects: raise InvalidSubject("Subject %s does not exist in role %s" % (subject.name, self.name)) self.subjects.remove(subject)
def OnDelete(self, event): cert = self.GetSelectedCertificate() if cert is None: return dlg = DeleteCertificateDialog(self, "Deleting a certificate is an irreversible operation.\n" + "Really delete certificate for identity " + cert.GetShortSubject() + "?") ret = dlg.ShowModal() retain = dlg.GetRetainPrivateKey() dlg.Destroy() if ret == wx.ID_NO: return self.certMgr.GetCertificateRepository().RemoveCertificate(cert, dlg.GetRetainPrivateKey()) Toolkit.GetDefaultApplication().GetCertificateManagerUI().InitEnvironment() self.Load()
def OnDelete(self, event): cert = self.GetSelectedCertificate() if cert is None: return dlg = wx.MessageDialog( self, "Deleting a certificate is an irreversible operation.\n" + "Really delete certificate for identity " + cert.GetShortSubject() + "?", "Really delete?", style=wx.YES_NO | wx.NO_DEFAULT) ret = dlg.ShowModal() dlg.Destroy() if ret == wx.ID_NO: return self.certMgr.GetCertificateRepository().RemoveCertificate(cert) Toolkit.GetDefaultApplication().GetCertificateManagerUI( ).InitEnvironment() self.Load()
def ImportRequestedCertificate(self, userCert): repo = self.GetCertificateRepository() impCert = repo.ImportRequestedCertificate(userCert) log.debug("imported requested cert %s", impCert.GetSubject()) impCert.SetMetadata("AG.CertificateManager.certType", "identity") try: defID = self.GetDefaultIdentity() except NoCertificates: defID = None if defID is None: from AccessGrid import Toolkit self.SetDefaultIdentity(impCert) certMgrUI = Toolkit.GetDefaultApplication().GetCertificateManagerUI() certMgrUI.InitEnvironment() repo.NotifyObservers() return impCert
def ImportCACertificates(self): sysConfDir = AGTkConfig.instance().GetConfigDir() caDir = os.path.join(sysConfDir,'CAcertificates') log.debug("Initializing from %s", caDir) # # Now handle the CA certs. # if caDir is not None: try: files = os.listdir(caDir) except: from AccessGrid import Toolkit certMgrUI = Toolkit.GetDefaultApplication().GetCertificateManagerUI() certMgrUI.ReportError("Error reading CA certificate directory\n" + caDir + "\n" + "You will have to import trusted CA certificates later.") files = [] # # Extract the files from the caDir that match OpenSSL's # 8-character dot index format. # regexp = re.compile(r"^[\da-fA-F]{8}\.\d$") possibleCertFiles = filter(lambda f, r = regexp: r.search(f), files) for f in possibleCertFiles: path = os.path.join(caDir, f); log.info("%s might be a cert" % (path)) # Check for existence of signing policy certbasename = f.split('.')[0] signingPolicyFile = '%s.signing_policy' % (certbasename,) signingPath = os.path.join(caDir,signingPolicyFile) if not os.path.isfile(signingPath): log.info("Not importing CA cert %s; couldn't find signing policy file %s", f,signingPath) continue try: # Import the certificate desc = self.ImportCACertificatePEM(self.certRepo, path) except: log.exception('import of ca cert failed') try: # # Copy the signing policy file # shutil.copyfile(signingPath, desc.GetFilePath("signing_policy")) log.info("Imported cert as %s.0", desc.GetSubject().get_hash()) except: # print "Failure to import ", path log.exception("failure importing %s", path)
return 0 if __name__ == "__main__": h = Log.StreamHandler() h.setFormatter(Log.GetFormatter()) Log.HandleLoggers(h, Log.GetDefaultLoggers()) os.mkdir("foo") log.debug("foo") try: cm = CertificateManager("foo") ui = CertificateManagerUserInterface(cm) x = cm.ImportIdentityCertificatePEM(cm.certRepo, r"v\venueServer_cert.pem", r"v\venueServer_key.pem", None) if 0: certMgrUI = Toolkit.GetDefaultApplication().GetCertificateManagerUI() passphraseCB = certMgrUI.GetPassphraseCallback("DOE cert", "") x = cm.ImportIdentityCertificatePEM(cm.certRepo, r"\temp\doe.pem", r"\temp\doe.pem", passphraseCB) cm.InitEnvironment() except Exception, e: print e os.removedirs("foo")
del arg try: pass # sock = self.active_sockets[handle] # conn = ConnectionHandler(sock, self) # conn.registerForRead() # self.connectionMap[conn.GetId()] = None # del self.active_sockets[handle] except: log.exception("Accept failed to find socket for handle.") try: self.registerForListen() except: log.exception("acceptCallback failed") if __name__ == "__main__": from AccessGrid import Toolkit Toolkit.CmdlineApplication().Initialize("Asynch_test", sys.argv[:1]) port = 6500 print "Creating new EventService at %d." % port eventService = EventService(('', port)) evtThread = threading.Thread(target=eventService.start) evtThread.start() evtThread.join()
path = dlg.GetPath() dlg.Destroy() try: profile.Export(path) except: log.exception("Failure exporting profile to %s", path) ErrorDialog(self, "Cannot export service profile", "Cannot export service profile") else: dlg.Destroy() def OnPageShow(self): if self.certInfo.GetType() == "service": self.ExportProfileButton.Enable(1) else: self.ExportProfileButton.Enable(0) if __name__ == "__main__": pp = wx.PySimpleApp() from AccessGrid import Toolkit app = Toolkit.WXGUIApplication() app.Initialize() # Show certificate request wizard certReq = CertificateRequestTool(None) # certReq = CertificateRequestTool(None, certificateType = "SERVICE") certReq.Destroy()
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: # 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")
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")
# 0 - success # 1 - timed out # 2 - connection failure # 3 - unknown failure (the exception prints) import sys, os, time, threading from Queue import Queue from optparse import Option from AccessGrid import Toolkit from AccessGrid.GUID import GUID from AccessGrid.EventClient import EventClient from AccessGrid.EventClient import EventClientConnectionException from AccessGrid.Events import ConnectEvent, HeartbeatEvent app = Toolkit.CmdlineApplication() hostOption = Option("--host", dest="host", metavar="HOST", default="localhost", help="hostanme the event service.") app.AddCmdLineOption(hostOption) portOption = Option("--port", dest="port", metavar="PORT", type="int", default=8002, help="port of the event service.") app.AddCmdLineOption(portOption) channelOption = Option("--channel",
print " Initialization Error: Missing Dependency: ", e sys.exit(-1) except Exception, e: print "Toolkit Initialization failed, exiting." print " Initialization Error: ", e sys.exit(-1) log = app.GetLog() Log.SetDefaultLevel(Log.ServiceManager, Log.DEBUG) port = app.GetOption("port") # Create the hosting environment hostname = app.GetHostname() if app.GetOption("secure"): context = Toolkit.GetDefaultApplication().GetContext() server = SecureServer((hostname, port), context) else: server = InsecureServer((hostname, port)) # Create the Service Manager gServiceManager = AGServiceManager(server) # Create the Service Manager Service smi = AGServiceManagerI(impl=gServiceManager, auth_method_name=None) server.RegisterObject(smi, path="/ServiceManager") url = server.FindURLForObject(gServiceManager) gServiceManager.SetName('%s:%d' % (hostname, port)) gServiceManager.SetUri(url) if app.GetOption("nodeService") is not None:
def OnCreate(self, event): #self.certMgr.CreateProxyCertificate() Toolkit.GetDefaultApplication().GetCertificateManagerUI().CreateProxy() self.Load()
OK = 0 WARN = 1 CRITICAL = 2 privateId = None retval = -1 retstring = "" enteredFlag = threading.Event() enteredFlag.clear() warnFlag = threading.Event() warnFlag.clear() runningFlag = threading.Event() runningFlag.clear() # initialize app app = Toolkit.Service() app.AddCmdLineOption( Option("-v", "--venueUrl", type="string", dest="venueUrl", default="https://localhost:8000/Venues/default", metavar="VENUE_URL", help="Set the url of the venue to enter")) app.AddCmdLineOption( Option("-t", "--timeout", type="int", dest="timeout", default=10,