def train(trainer, runset, callbackRecv=None): """A callback receiver can optionally be specified""" # ICE functionality to enable bidirectional connection for callback adapter = ic.createObjectAdapter("") cbID = Ice.Identity() cbID.name = Ice.generateUUID() cbID.category = "" if not callbackRecv: callbackRecv = TrainerCallbackReceiverI() adapter.add(callbackRecv, cbID) adapter.activate() trainer.ice_getConnection().setAdapter(adapter) # connect to trainer, initialize with a verbosity value, and train trainer.initialize(3) if type(runset) is dict: runset = runset["runset"] trainer.process(cbID, runset) # check results if not callbackRecv.detectorData: raise RuntimeError("no DetectorData received from trainer") if callbackRecv.detectorData.type == cvac.DetectorDataType.BYTES: raise RuntimeError("detectorData as BYTES has not been tested yet") elif callbackRecv.detectorData.type == cvac.DetectorDataType.PROVIDER: raise RuntimeError("detectorData as PROVIDER has not been tested yet") return callbackRecv.detectorData
def createLocalMirror(corpusServer, corpus): """Call the corpusServer to create the local mirror for the specified corpus. Provide a simple callback for tracking.""" # ICE functionality to enable bidirectional connection for callback adapter = ic.createObjectAdapter("") cbID = Ice.Identity() cbID.name = Ice.generateUUID() cbID.category = "" callbackRecv = CorpusCallbackI() adapter.add(callbackRecv, cbID) adapter.activate() corpusServer.ice_getConnection().setAdapter(adapter) # this call should block corpusServer.createLocalMirror(corpus, cbID) if not callbackRecv.corpus: raise RuntimeError("could not create local mirror")
def getTable(self, file_obj, factory, current=None): """ Create and/or register a table servant. """ # Will throw an exception if not allowed. file_id = None if file_obj is not None and file_obj.id is not None: file_id = file_obj.id.val self.logger.info("getTable: %s %s", file_id, current.ctx) file_path = self.repo_mgr.getFilePath(file_obj) p = path(file_path).dirname() if not p.exists(): p.makedirs() storage = self._storage_factory.getOrCreate(file_path, self.read_only) id = Ice.Identity() id.name = Ice.generateUUID() table = TableI(self.ctx, file_obj, factory, storage, uuid=id.name, call_context=current.ctx) self.resources.add(table) prx = current.adapter.add(table, id) return self._table_cast(prx)
def getTable(self, file_obj, factory, current = None): """ Create and/or register a table servant. """ # Will throw an exception if not allowed. file_id = None if file_obj is not None and file_obj.id is not None: file_id = file_obj.id.val self.logger.info("getTable: %s %s", file_id, current.ctx) file_path = self.repo_mgr.getFilePath(file_obj) p = path(file_path).dirname() if not p.exists(): p.makedirs() storage = HDFLIST.getOrCreate(file_path) id = Ice.Identity() id.name = Ice.generateUUID() table = TableI(self.ctx, file_obj, factory, storage, uuid = id.name, \ call_context=current.ctx) self.resources.add(table) prx = current.adapter.add(table, id) return self._table_cast(prx)
def __init__(self, adapterId=None, catchSignals=True, icemgr=None, logLevel=logging.WARNING, defaultTimeout=500, auto_shutdown=False): """ adapterID will be the Ice name of the adapter catchSginal will catch ctrl-C, this should only be done once per process. """ self.auto_shutdown = auto_shutdown if not adapterId: adapterId = Ice.generateUUID() self.logger = logging.getLogger(self.__class__.__name__ + "::" + adapterId) if len(logging.root.handlers) == 0: #dirty hack logging.basicConfig() self.logger.setLevel(logLevel) self._agents = [] self._lock = Lock() if not icemgr: self.icemgr = icehms.IceManager(adapterId=adapterId, defaultTimeout=defaultTimeout, logLevel=logLevel) self.icemgr.init() else: self.icemgr = icemgr if catchSignals: #Handle Ctrl-C on windows and linux signal.signal(signal.SIGINT, self.shutdown) signal.signal(signal.SIGTERM, self.shutdown)
def __init__(self): super(Client, self).__init__() self._session_prx = None self.agent_receiver_ice_ident = Ice.Identity() self.agent_receiver_ice_ident.category = "RPCChannel" self.agent_receiver_ice_ident.name = Ice.generateUUID() self.agent_receiver_adapter = None self.agent_receiver = AgentReceiverI(self)
def run(self, argv): rtFile = self.communicator().getProperties().getPropertyWithDefault( "RoutingTable", "RTABLE") self.router.getRoutingTable().load(rtFile) self.router.pox = pox.PacketInjectorPrx.checkedCast( self.communicator().propertyToProxy( "SimpleRouter.Proxy").ice_twoway()) if not self.router.pox: log.error( "ERROR: Cannot connect to POX controller or invalid configuration of the controller" ) return -1 ifFile = self.communicator().getProperties().getPropertyWithDefault( "Ifconfig", "IP_CONFIG") self.router.loadIfconfig(ifFile) adapter = self.communicator().createObjectAdapter("") ident = Ice.Identity() ident.name = Ice.generateUUID() ident.category = "" adapter.add(PacketHandler(self.router), ident) adapter.activate() self.router.pox.ice_getConnection().setAdapter(adapter) self.router.pox.addPacketHandler(ident) ifaces = self.router.pox.getIfaces() self.router.reset(ifaces) def poxPinger(self): while not self.shouldStop: time.sleep(1) try: self.router.pox.ice_ping() except: print("Connection to POX service broken, exiting...", file=sys.stderr) self.communicator().shutdown() self.shouldStop = False checkThread = threading.Thread(target=poxPinger, args=(self, )) checkThread.start() testAdapter = self.communicator().createObjectAdapterWithEndpoints( "Tester", "tcp -p 65500") testAdapter.add(Tester(self.router), self.communicator().stringToIdentity("Tester")) testAdapter.activate() self.communicator().waitForShutdown() self.shouldStop = True self.router.arpCache.stop() checkThread.join() return 0
def __init__(self, communicator, name, parent): self._name = name self._parent = parent self.lines = [] assert(self._parent != None) # Create an identity # self._id = Ice.Identity() self._id.name = Ice.generateUUID()
def __init__(self, communicator, name, parent): self._name = name self._parent = parent self.lines = [] assert (self._parent != None) # Create an identity # self._id = Ice.Identity() self._id.name = Ice.generateUUID()
def detect( detector, detectorData, runset, callbackRecv=None ): ''' Synchronously run detection with the specified detector, trained model, and optional callback receiver. The detectorData can be either a cvac.DetectorData object or simply a filename of a pre-trained model. Naturally, the model has to be compatible with the detector. The runset can be either a cvac.RunSet object or anything that createRunSet can turn into a RunSet. If a callback receiver is specified, this function returns nothing, otherwise, the obtained results are returned. ''' # create a cvac.DetectorData object out of a filename if type(detectorData) is str: ddpath = getCvacPath( detectorData ); detectorData = cvac.DetectorData( cvac.DetectorDataType.FILE, None, ddpath, None ) elif not type(detectorData) is cvac.DetectorData: raise RuntimeError("detectorData must be either filename or cvac.DetectorData") # if not given an actual cvac.RunSet, try to create a RunSet if isinstance(runset, cvac.RunSet): pass elif type(runset) is dict and not runset['runset'] is None\ and isinstance(runset['runset'], cvac.RunSet): #classmap = runset['classmap'] runset = runset['runset'] else: res = createRunSet( runset ) #classmap = res['classmap'] runset = res['runset'] # ICE functionality to enable bidirectional connection for callback adapter = ic.createObjectAdapter("") cbID = Ice.Identity() cbID.name = Ice.generateUUID() cbID.category = "" ourRecv = False # will we use our own simple callback receiver? if not callbackRecv: ourRecv = True callbackRecv = DetectorCallbackReceiverI(); callbackRecv.allResults = [] adapter.add( callbackRecv, cbID ) adapter.activate() detector.ice_getConnection().setAdapter(adapter) # connect to detector, initialize with a verbosity value # and the trained model, and run the detection on the runset detector.initialize( 3, detectorData ) detector.process( cbID, runset ) if ourRecv: return callbackRecv.allResults
def __init__(self, communicator, name, parent): self._name = name self._parent = parent self._contents = [] # Create an identity. The root directory has the fixed identity "RootDir" # self._id = Ice.Identity() if self._parent: self._id.name = Ice.generateUUID() else: self._id.name = "RootDir"
def activate(self, a): # # Create an identity. The root directory has the fixed identity "RootDir" # id = Ice.Identity() if self._parent: id.name = Ice.generateUUID() else: id.name = "RootDir" thisNode = Filesystem.NodePrx.uncheckedCast(a.add(self, id)) if self._parent: self._parent.addChild(thisNode)
def createObjectAdapter(self, timeout, close, heartbeat, current=None): com = current.adapter.getCommunicator() properties = com.getProperties() protocol = properties.getPropertyWithDefault("Ice.Default.Protocol", "tcp"); name = Ice.generateUUID() if timeout >= 0: properties.setProperty(name + ".ACM.Timeout", str(timeout)) if close >= 0: properties.setProperty(name + ".ACM.Close", str(close)) if heartbeat >= 0: properties.setProperty(name + ".ACM.Heartbeat", str(heartbeat)) properties.setProperty(name + ".ThreadPool.Size", "2") adapter = com.createObjectAdapterWithEndpoints(name, protocol + " -h 127.0.0.1") return Test.RemoteObjectAdapterPrx.uncheckedCast(current.adapter.addWithUUID(RemoteObjectAdapterI(adapter)))
def _init_Ice(self): import Ice props = Ice.createProperties() props.setProperty("Ice.ThreadPool.Server.SizeMax", "16") # props.setProperty("Ice.ThreadPool.SizeMax", "16") props.setProperty("Ice.MessageSizeMax", "0") # props.setProperty("Ice.Trace.ThreadPool", "1") # props.setProperty("Ice.Trace.Network", "1") # props.setProperty("Ice.Trace.Protocol", "1") data = Ice.InitializationData() data.properties = props self._ice_ic = ic = Ice.initialize(data=data) self._ice_adapter = adapter = ic.createObjectAdapter("") self._ice_ident = ident = Ice.Identity() ident.name = Ice.generateUUID() adapter.add(self, ident) adapter.activate()
def run(self, argv): broker = self.communicator() servant = PrinterI() identity = Ice.Identity(Ice.generateUUID()) adapter = broker.createObjectAdapter("") adapter.add(servant, identity) adapter.activate() proxy = broker.stringToProxy(argv[1]) server = Example.CallbackPrx.checkedCast(proxy) server.ice_getConnection().setAdapter(adapter) server.attach(identity) self.communicator().waitForShutdown() return 0
def detect(detector, detectorData, runset, callbackRecv=None): """Synchronously run detection with the specified detector, trained model, and optional callback receiver. The detectorData can be either a cvac.DetectorData object or simply a filename of a pre-trained model. Naturally, the model has to be compatible with the detector. The runset can be either a cvac.RunSet object, filename to a single file that is to be tested, or a directory path. If a callback receiver is specified, this function returns nothing, otherwise, the obtained results are returned.""" # create a cvac.DetectorData object out of a filename if type(detectorData) is str: ddpath = getCvacPath(detectorData) detectorData = cvac.DetectorData(cvac.DetectorDataType.FILE, None, ddpath, None) elif not type(detectorData) is cvac.DetectorData: raise RuntimeException("detectorData must be either filename or cvac.DetectorData") # create a RunSet out of a filename or directory path if type(runset) is str: res = createRunSet(runset) runset = res["runset"] classmap = res["classmap"] elif not type(runset) is cvac.RunSet: raise RuntimeException("runset must either be a filename, directory, or cvac.RunSet") # ICE functionality to enable bidirectional connection for callback adapter = ic.createObjectAdapter("") cbID = Ice.Identity() cbID.name = Ice.generateUUID() cbID.category = "" ourRecv = False # will we use our own simple callback receiver? if not callbackRecv: ourRecv = True callbackRecv = DetectorCallbackReceiverI() adapter.add(callbackRecv, cbID) adapter.activate() detector.ice_getConnection().setAdapter(adapter) # connect to detector, initialize with a verbosity value # and the trained model, and run the detection on the runset detector.initialize(3, detectorData) detector.process(cbID, runset) if ourRecv: return callbackRecv.allResults
def xxx(): print "create session" ic = Ice.initialize(sys.argv) base = ic.stringToProxy("SimpleEntry:tcp -p 10000") entry = LabrestAPI.EntryPrx.checkedCast(base) if not entry: raise RuntimeError('Invalid proxy') session.write(entry.login('guest','guest')) adapter = ic.createObjectAdapter("") ident = Ice.Identity() ident.name = Ice.generateUUID() ident.category = "" print ident.name cb = LabrestAPI.CallbackI() adapter.add(cb, ident) adapter.activate(); session.read().ice_getConnection().setAdapter(adapter) session.read().getCallbackManager().registerCallback(ident)
def run(self, args): if len(args) > 1: print(self.appName() + ": too many arguments") return 1 server = Demo.CallbackSenderPrx.checkedCast(self.communicator().propertyToProxy('CallbackSender.Proxy')) if not server: print(self.appName() + ": invalid proxy") return 1 adapter = self.communicator().createObjectAdapter("") ident = Ice.Identity() ident.name = Ice.generateUUID() ident.category = "" adapter.add(CallbackReceiverI(), ident) adapter.activate() server.ice_getConnection().setAdapter(adapter) server.addClient(ident) self.communicator().waitForShutdown() return 0
def run (self, argv): """Ejecuci�n del c�digo asociado al renderAgent""" self.shutdownOnInterrupt() # Conexión con Glacier2. router = Glacier2.RouterPrx.checkedCast(self.communicator().getDefaultRouter()) session = router.createSession('david', 'david') self.obtainServiceRoot() self.getBasicServices() self.addRenderService('render', TYPEOFSERVICE) # Subscripci�n al DirectoryFacilitator. self.subscribeDF() ### ACCIONES ESPECÍFICAS. self.obtainProxies() # Informar del tiempo de ejecuci�n del benchmark. self.notifyBenchmarkValue() ### FIN ACCIONES ESPECÍFICAS. # Subscripci�n al Master. oa = self.communicator().createObjectAdapter('MyAdapter') ident = Ice.Identity() ident.name = Ice.generateUUID() ident.category = router.getServerProxy().ice_getIdentity().category prx = MASYRO.RenderAgentPrx.uncheckedCast(oa.add(self, ident)) self.subscribeMaster(prx) self.communicator().waitForShutdown() # Baja del DirectoryFacilitator y del AMS. self.deregister() self.unsubscribeDF() # Eliminaci�n de la subscripci�n al Master. self.unsubscribeMaster() # Limpieza de recursos. self.clear() return 0
def run(self, args): if len(args) > 1: print self.appName() + ": too many arguments" return 1 import Glacier2 ## Copied from demopy/Glacier2/callback/Client.py defaultRouter = self.communicator().getDefaultRouter() if not defaultRouter: print self.appName() + ": no default router set" return 1 router = Glacier2.RouterPrx.checkedCast(defaultRouter) if not router: print self.appName() + ": configured router is not a Glacier2 router" return 1 ## End copied session = router.createSession("", "") server = Demo.CallbackSenderPrx.checkedCast(session) if not server: print self.appName() + ": invalid proxy" return 1 adapter = self.communicator().createObjectAdapterWithRouter("Callback.Client", router) adapter.activate() ident = Ice.Identity() ident.name = Ice.generateUUID() ident.category = router.getCategoryForClient() prx = adapter.add(CallbackReceiverI(), ident) prx = Demo.CallbackReceiverPrx.uncheckedCast(prx) server.addClientObj(prx) self.communicator().waitForShutdown() print "here" return 0
def addWithUUID(self, servant): return objectAdapter().add(servant, createCallbackIdentity(Ice.generateUUID()))
def run(self, mappings, testSuiteIds): if isinstance(platform, Darwin): # # On macOS, we set the trust settings on the certificate to prevent # the Web browsers from prompting the user about the untrusted # certificate. Some browsers such as Chrome don't provide the # option to set this trust settings. # serverCert = os.path.join(toplevel, "certs", "server.pem") if self.clean: if os.system("security verify-cert -c " + serverCert + " >& /dev/null") == 0: sys.stdout.write("removing trust settings for the HTTP server certificate... ") sys.stdout.flush() if os.system("security remove-trusted-cert " + serverCert) != 0: print("\nerror: couldn't remove trust settings for the HTTP server certificate") else: print("ok") else: print("trust settings already removed") return else: if os.system("security verify-cert -c " + serverCert + " >& /dev/null") != 0: sys.stdout.write("adding trust settings for the HTTP server certificate... ") sys.stdout.flush() if os.system("security add-trusted-cert -r trustAsRoot " + serverCert) != 0: print("error: couldn't add trust settings for the HTTP server certificate") print("ok") print("run " + sys.argv[0] + " --clean to remove the trust setting") self.initCommunicator() import Ice Ice.loadSlice(os.path.join(toplevel, "scripts", "Controller.ice")) import Test class TestCaseI(Test.Common.TestCase): def __init__(self, driver, current): self.driver = driver self.current = current self.serverSideRunning = False def startServerSide(self, config, c): self.updateCurrent(config) try: self.serverSideRunning = True return self.current.serverTestCase._startServerSide(self.current) except Exception as ex: self.serverSideRunning = False raise Test.Common.TestCaseFailedException(self.current.result.getOutput() + "\n" + traceback.format_exc()) def stopServerSide(self, success, c): if self.serverSideRunning: try: self.current.serverTestCase._stopServerSide(self.current, success) return self.current.result.getOutput() except Exception as ex: raise Test.Common.TestCaseFailedException(self.current.result.getOutput() + "\n" + str(ex)) def runClientSide(self, host, config, c): self.updateCurrent(config) try: self.current.clientTestCase._runClientSide(self.current, host) return self.current.result.getOutput() except Exception as ex: raise Test.Common.TestCaseFailedException(self.current.result.getOutput() + "\n" + str(ex)) def destroy(self, c): if self.serverSideRunning: try: self.current.serverTestCase._stopServerSide(self.current, False) except: pass c.adapter.remove(c.id) def updateCurrent(self, config): attrs = ["protocol", "mx", "serialize", "compress", "ipv6", "cprops", "sprops"] for a in attrs: v = getattr(config, a) if v is not Ice.Unset: if a not in self.current.config.parsedOptions: self.current.config.parsedOptions.append(a) setattr(self.current.config, a, v) class ControllerI(Test.Common.Controller): def __init__(self, driver): self.driver = driver self.testcase = None def runTestCase(self, mapping, testsuite, testcase, cross, c): if self.testcase: try: self.testcase.destroy() except: pass self.testcase = None current = self.driver.getCurrent(mapping, testsuite, testcase, cross) prx = c.adapter.addWithUUID(TestCaseI(self.driver, current)) self.testcase = Test.Common.TestCasePrx.uncheckedCast(c.adapter.createDirectProxy(prx.ice_getIdentity())) return self.testcase def getTestSuites(self, mapping, c): mapping = Mapping.getByName(mapping) config = self.driver.configs[mapping] return [str(t) for t in mapping.getTestSuites() if not mapping.filterTestSuite(t.getId(), config)] def getOptionOverrides(self, c): return Test.Common.OptionOverrides(ipv6=([False] if not self.driver.hostIPv6 else [False, True])) self.initCommunicator() self.communicator.getProperties().setProperty("ControllerAdapter.Endpoints", self.endpoints) self.communicator.getProperties().setProperty("ControllerAdapter.AdapterId", Ice.generateUUID()) adapter = self.communicator.createObjectAdapter("ControllerAdapter") adapter.add(ControllerI(self), self.communicator.stringToIdentity(self.id)) adapter.activate() self.communicator.waitForShutdown()
def run(communicator): try: opts, args = getopt.getopt(sys.argv[1:], '', [ 'datagram', 'twoway', 'oneway', 'ordered', 'batch', 'retryCount=', 'id=' ]) except getopt.GetoptError: usage() sys.exit(1) batch = False option = "None" topicName = "time" id = "" retryCount = "" for o, a in opts: oldoption = option if o == "--datagram": option = "Datagram" elif o == "--twoway": option = "Twoway" elif o == "--ordered": option = "Ordered" elif o == "--oneway": option = "Oneway" elif o == "--batch": batch = True elif o == "--id": id = a elif o == "--retryCount": retryCount = a if oldoption != option and oldoption != "None": usage() sys.exit(1) if len(args) > 1: usage() sys.exit(1) if len(args) > 0: topicName = args[0] if len(retryCount) > 0: if option == "None": option = "Twoway" elif option != "Twoway" and option != "Ordered": print(sys.argv[0] + ": retryCount requires a twoway proxy") sys.exit(1) if batch and (option in ("Twoway", "Ordered")): print(sys.argv[0] + ": batch can only be set with oneway or datagram") sys.exit(1) manager = IceStorm.TopicManagerPrx.checkedCast( communicator.propertyToProxy('TopicManager.Proxy')) if not manager: print(args[0] + ": invalid proxy") sys.exit(1) # # Retrieve the topic. # try: topic = manager.retrieve(topicName) except IceStorm.NoSuchTopic as e: try: topic = manager.create(topicName) except IceStorm.TopicExists as ex: print(sys.argv[0] + ": temporary error. try again") sys.exit(1) adapter = communicator.createObjectAdapter("Clock.Subscriber") # # Add a servant for the Ice object. If --id is used the identity # comes from the command line, otherwise a UUID is used. # # id is not directly altered since it is used below to detect # whether subscribeAndGetPublisher can raise AlreadySubscribed. # subId = Ice.Identity() subId.name = id if len(subId.name) == 0: subId.name = Ice.generateUUID() subscriber = adapter.add(ClockI(), subId) # # Activate the object adapter before subscribing. # adapter.activate() qos = {} if len(retryCount) > 0: qos["retryCount"] = retryCount # # Set up the proxy. # if option == "Datagram": if batch: subscriber = subscriber.ice_batchDatagram() else: subscriber = subscriber.ice_datagram() elif option == "Twoway": # Do nothing to the subscriber proxy. Its already twoway. pass elif option == "Ordered": # Do nothing to the subscriber proxy. Its already twoway. qos["reliability"] = "ordered" elif option == "Oneway" or option == "None": if batch: subscriber = subscriber.ice_batchOneway() else: subscriber = subscriber.ice_oneway() try: topic.subscribeAndGetPublisher(qos, subscriber) except IceStorm.AlreadySubscribed as ex: # If we're manually setting the subscriber id ignore. if len(id) == 0: raise print("reactivating persistent subscriber") communicator.waitForShutdown() # # Unsubscribe all subscribed objects. # topic.unsubscribe(subscriber)
def run(self, args): try: opts, args = getopt.getopt(args[1:], '', ['datagram', 'twoway', 'oneway', 'ordered', 'batch', 'retryCount=', 'id=']) except getopt.GetoptError: self.usage() return 1 batch = False option = "None" topicName = "time" id = "" retryCount = "" for o, a in opts: oldoption = option if o == "--datagram": option = "Datagram" elif o =="--twoway": option = "Twoway" elif o =="--ordered": option = "Ordered" elif o =="--oneway": option = "Oneway" elif o =="--batch": batch = True elif o == "--id": id = a elif o == "--retryCount": retryCount = a if oldoption != option and oldoption != "None": self.usage() return 1 if len(args) > 1: self.usage() return 1 if len(args) > 0: topicName = args[0] if len(retryCount) > 0: if option == "None": option = "Twoway" elif option != "Twoway" and option != "Ordered": print(self.appName() + ": retryCount requires a twoway proxy") return 1 if batch and (option in ("Twoway", "Ordered")): print(self.appName() + ": batch can only be set with oneway or datagram") return 1 manager = IceStorm.TopicManagerPrx.checkedCast(self.communicator().propertyToProxy('TopicManager.Proxy')) if not manager: print(args[0] + ": invalid proxy") return 1 # # Retrieve the topic. # try: topic = manager.retrieve(topicName) except IceStorm.NoSuchTopic as e: try: topic = manager.create(topicName) except IceStorm.TopicExists as ex: print(self.appName() + ": temporary error. try again") return 1 adapter = self.communicator().createObjectAdapter("Clock.Subscriber") # # Add a servant for the Ice object. If --id is used the identity # comes from the command line, otherwise a UUID is used. # # id is not directly altered since it is used below to detect # whether subscribeAndGetPublisher can raise AlreadySubscribed. # subId = Ice.Identity() subId.name = id if len(subId.name) == 0: subId.name = Ice.generateUUID() subscriber = adapter.add(ClockI(), subId) # # Activate the object adapter before subscribing. # adapter.activate() qos = {} if len(retryCount) > 0: qos["retryCount"] = retryCount # # Set up the proxy. # if option == "Datagram": if batch: subscriber = subscriber.ice_batchDatagram() else: subscriber = subscriber.ice_datagram() elif option == "Twoway": # Do nothing to the subscriber proxy. Its already twoway. pass elif option == "Ordered": # Do nothing to the subscriber proxy. Its already twoway. qos["reliability"] = "ordered" elif option == "Oneway" or option == "None": if batch: subscriber = subscriber.ice_batchOneway() else: subscriber = subscriber.ice_oneway() try: topic.subscribeAndGetPublisher(qos, subscriber) except IceStorm.AlreadySubscribed as ex: # If we're manually setting the subscriber id ignore. if len(id) == 0: raise print("reactivating persistent subscriber") self.shutdownOnInterrupt() self.communicator().waitForShutdown() # # Unsubscribe all subscribed objects. # topic.unsubscribe(subscriber) return 0
def register(self, obj, class_): uuid = self._ic.stringToIdentity(Ice.generateUUID()) proxy = self._adapter.add(obj, uuid) self._connections.append(uuid) return class_.uncheckedCast(proxy)
def allTests(communicator, ref): manager = Test.ServerManagerPrx.checkedCast(communicator.stringToProxy(ref)) locator = communicator.getDefaultLocator() test(manager) registry = Test.TestLocatorRegistryPrx.checkedCast(locator.getRegistry()); test(registry); sys.stdout.write("testing stringToProxy... ") sys.stdout.flush() base = communicator.stringToProxy("test @ TestAdapter") base2 = communicator.stringToProxy("test @ TestAdapter") base3 = communicator.stringToProxy("test") base4 = communicator.stringToProxy("ServerManager") base5 = communicator.stringToProxy("test2") print("ok") sys.stdout.write("testing ice_locator and ice_getLocator... ") sys.stdout.flush() test(Ice.proxyIdentityEqual(base.ice_getLocator(), communicator.getDefaultLocator())); anotherLocator = Ice.LocatorPrx.uncheckedCast(communicator.stringToProxy("anotherLocator")); base = base.ice_locator(anotherLocator); test(Ice.proxyIdentityEqual(base.ice_getLocator(), anotherLocator)); communicator.setDefaultLocator(None); base = communicator.stringToProxy("test @ TestAdapter"); test(not base.ice_getLocator()); base = base.ice_locator(anotherLocator); test(Ice.proxyIdentityEqual(base.ice_getLocator(), anotherLocator)); communicator.setDefaultLocator(locator); base = communicator.stringToProxy("test @ TestAdapter"); test(Ice.proxyIdentityEqual(base.ice_getLocator(), communicator.getDefaultLocator())); # # We also test ice_router/ice_getRouter (perhaps we should add a # test/Ice/router test?) # test(not base.ice_getRouter()); anotherRouter = Ice.RouterPrx.uncheckedCast(communicator.stringToProxy("anotherRouter")); base = base.ice_router(anotherRouter); test(Ice.proxyIdentityEqual(base.ice_getRouter(), anotherRouter)); router = Ice.RouterPrx.uncheckedCast(communicator.stringToProxy("dummyrouter")); communicator.setDefaultRouter(router); base = communicator.stringToProxy("test @ TestAdapter"); test(Ice.proxyIdentityEqual(base.ice_getRouter(), communicator.getDefaultRouter())); communicator.setDefaultRouter(None); base = communicator.stringToProxy("test @ TestAdapter"); test(not base.ice_getRouter()); print("ok") sys.stdout.write("starting server... ") sys.stdout.flush() manager.startServer() print("ok") sys.stdout.write("testing checked cast... ") sys.stdout.flush() obj = Test.TestIntfPrx.checkedCast(base) obj = Test.TestIntfPrx.checkedCast(communicator.stringToProxy("test@TestAdapter")) obj = Test.TestIntfPrx.checkedCast(communicator.stringToProxy("test @TestAdapter")) obj = Test.TestIntfPrx.checkedCast(communicator.stringToProxy("test@ TestAdapter")) test(obj) obj2 = Test.TestIntfPrx.checkedCast(base2) test(obj2) obj3 = Test.TestIntfPrx.checkedCast(base3) test(obj3) obj4 = Test.ServerManagerPrx.checkedCast(base4) test(obj4) obj5 = Test.TestIntfPrx.checkedCast(base5) test(obj5) print("ok") sys.stdout.write("testing id@AdapterId indirect proxy... ") sys.stdout.flush() obj.shutdown() manager.startServer() try: obj2 = Test.TestIntfPrx.checkedCast(base2) obj2.ice_ping() except Ice.LocalException: test(False) print("ok") sys.stdout.write("testing identity indirect proxy... ") sys.stdout.flush() obj.shutdown() manager.startServer() try: obj3 = Test.TestIntfPrx.checkedCast(base3) obj3.ice_ping() except Ice.LocalException as ex: print(ex) test(False) try: obj2 = Test.TestIntfPrx.checkedCast(base2) obj2.ice_ping() except Ice.LocalException as ex: print(ex) test(False) obj.shutdown() manager.startServer() try: obj2 = Test.TestIntfPrx.checkedCast(base2) obj2.ice_ping() except Ice.LocalException as ex: print(ex) test(False) try: obj3 = Test.TestIntfPrx.checkedCast(base3) obj3.ice_ping() except Ice.LocalException as ex: print(ex) test(False) obj.shutdown() manager.startServer() try: obj2 = Test.TestIntfPrx.checkedCast(base2) obj2.ice_ping() except Ice.LocalException: test(False) obj.shutdown() manager.startServer() try: obj3 = Test.TestIntfPrx.checkedCast(base3) obj3.ice_ping() except Ice.LocalException: test(False) obj.shutdown() manager.startServer() try: obj2 = Test.TestIntfPrx.checkedCast(base2) obj2.ice_ping() except Ice.LocalException: test(False) obj.shutdown() manager.startServer() try: obj5 = Test.TestIntfPrx.checkedCast(base5) obj5.ice_ping() except Ice.LocalException: test(False) print("ok") sys.stdout.write("testing reference with unknown identity... ") sys.stdout.flush() try: base = communicator.stringToProxy("unknown/unknown") base.ice_ping() test(False) except Ice.NotRegisteredException as ex: test(ex.kindOfObject == "object") test(ex.id == "unknown/unknown") print("ok") sys.stdout.write("testing reference with unknown adapter... ") sys.stdout.flush() try: base = communicator.stringToProxy("test @ TestAdapterUnknown") base.ice_ping() test(False) except Ice.NotRegisteredException as ex: test(ex.kindOfObject == "object adapter") test(ex.id == "TestAdapterUnknown") print("ok") sys.stdout.write("testing object reference from server... ") sys.stdout.flush() hello = obj.getHello() hello.sayHello() print("ok") sys.stdout.write("testing object reference from server after shutdown... ") sys.stdout.flush() obj.shutdown() manager.startServer() hello.sayHello() print("ok") sys.stdout.write("testing object migration... ") sys.stdout.flush() hello = Test.HelloPrx.checkedCast(communicator.stringToProxy("hello")) obj.migrateHello() hello.ice_getConnection().close(False); hello.sayHello() obj.migrateHello() hello.sayHello() obj.migrateHello() hello.sayHello() print("ok") sys.stdout.write("shutdown server... ") sys.stdout.flush() obj.shutdown() print("ok") sys.stdout.write("testing whether server is gone... ") sys.stdout.flush() try: obj2.ice_ping() test(False) except Ice.LocalException: pass try: obj3.ice_ping() test(False) except Ice.LocalException: pass try: obj5.ice_ping() test(False) except Ice.LocalException: pass print("ok") # # Set up test for calling a collocated object through an indirect, adapterless reference. # sys.stdout.write("testing indirect references to collocated objects... ") sys.stdout.flush() properties = communicator.getProperties(); properties.setProperty("Ice.PrintAdapterReady", "0"); adapter = communicator.createObjectAdapterWithEndpoints("Hello", "default"); adapter.setLocator(locator); assert(adapter.getLocator() == locator) id = Ice.Identity(); id.name = Ice.generateUUID(); registry.addObject(adapter.add(HelloI(), id)); adapter.activate(); helloPrx = Test.HelloPrx.checkedCast(communicator.stringToProxy(communicator.identityToString(id))); test(not helloPrx.ice_getConnection()); adapter.deactivate(); print("ok") sys.stdout.write("shutdown server manager... ") sys.stdout.flush() manager.shutdown() print("ok")
def run(self, mappings): if isinstance(platform, Darwin): # # On OS X, we set the trust settings on the certificate to prevent # the Web browsers from prompting the user about the unstrusted # certificate. Some browsers such as Chrome don't provide the # option to set this trust settings. # serverCert = os.path.join(toplevel, "certs", "server.pem") if self.clean: if os.system("security verify-cert -c " + serverCert + " >& /dev/null") == 0: sys.stdout.write("removing trust settings for the HTTP server certificate... ") sys.stdout.flush() if os.system("security remove-trusted-cert " + serverCert) != 0: print("\nerror: couldn't remove trust settings for the HTTP server certificate") else: print("ok") else: print("trust settings already removed") return else: if os.system("security verify-cert -c " + serverCert + " >& /dev/null") != 0: sys.stdout.write("adding trust settings for the HTTP server certificate... ") sys.stdout.flush() if os.system("security add-trusted-cert -r trustAsRoot " + serverCert) != 0: print("error: couldn't add trust settings for the HTTP server certificate") print("ok") print("run " + sys.argv[0] + " --clean to remove the trust setting") import Ice Ice.loadSlice(os.path.join(toplevel, "scripts", "Controller.ice")) import Test class ServerI(Test.Common.Server): def __init__(self, driver, current): self.driver = driver self.current = current def waitForServer(self, c): if not self.current: raise Test.Common.ServerFailedException("couldn't find test suite") try: self.current.serverTestCase._startServerSide(self.current) except Exception as ex: raise Test.Common.ServerFailedException(str(ex)) def waitTestSuccess(self, c): c.adapter.remove(c.id) if self.current: self.current.serverTestCase._stopServerSide(self.current, True) def terminate(self, c): c.adapter.remove(c.id) if self.current: self.current.serverTestCase._stopServerSide(self.current, False) class TestCaseI(Test.Common.TestCase): def __init__(self, driver, current): self.driver = driver self.current = current self.serverSideRunning = False def startServerSide(self, config, c): self.updateCurrent(config) # Depending on the configuration, either use an IPv4, IPv6 or BT address for Ice.Default.Host if self.current.config.ipv6: if not self.driver.hostIPv6: raise Test.Common.TestCaseFailedException("no IPv6 address set with --host-ipv6") self.current.host = self.driver.hostIPv6 elif self.current.config.protocol == "bt": if not self.driver.hostBT: raise Test.Common.TestCaseFailedException("no Bluetooth address set with --host-bt") self.current.host = self.driver.hostBT else: self.current.host = self.driver.host if self.driver.host else self.driver.interface try: self.current.serverTestCase._startServerSide(self.current) self.serverSideRunning = True return self.current.host except Exception as ex: raise Test.Common.TestCaseFailedException(self.current.result.getOutput() + "\n" + str(ex)) def stopServerSide(self, success, c): if self.serverSideRunning: try: self.current.serverTestCase._stopServerSide(self.current, success) return self.current.result.getOutput() except Exception as ex: raise Test.Common.TestCaseFailedException(self.current.result.getOutput() + "\n" + str(ex)) def runClientSide(self, host, config, c): self.updateCurrent(config) if host: current.host = host try: self.current.clientTestCase._runClientSide(self.current) return self.current.result.getOutput() except Exception as ex: raise Test.Common.TestCaseFailedException(self.current.result.getOutput() + "\n" + str(ex)) def destroy(self, c): if self.serverSideRunning: try: self.current.serverTestCase._stopServerSide(self.current, False) except: pass c.adapter.remove(c.id) def updateCurrent(self, config): attrs = ["protocol", "mx", "serialize", "compress", "ipv6"] for a in attrs: v = getattr(config, a) if v is not Ice.Unset: setattr(self.current.config, a, v) class ControllerI(Test.Common.Controller): def __init__(self, driver): self.driver = driver self.server = None self.testcase = None def runServer(self, mapping, testsuite, protocol, host, winrt, testcase, args, c): self.terminate() try: current = self.driver.getCurrent(mapping, testsuite, testcase, "", protocol, host, args) except Test.Common.TestCaseNotExistException: current = None self.server = Test.Common.ServerPrx.uncheckedCast(c.adapter.addWithUUID(ServerI(self.driver, current))) return self.server def runTestCase(self, mapping, testsuite, testcase, cross, c): self.terminate() current = self.driver.getCurrent(mapping, testsuite, testcase, cross) self.testcase = Test.Common.TestCasePrx.uncheckedCast(c.adapter.addWithUUID(TestCaseI(self.driver, current))) return self.testcase def getOptionOverrides(self, c): return Test.Common.OptionOverrides(ipv6=([False] if not self.driver.hostIPv6 else [False, True])) def terminate(self): if self.server: try: self.server.terminate() except: pass self.server = None if self.testcase: try: self.testcase.destroy() except: pass self.testcase = None initData = Ice.InitializationData() initData.properties = Ice.createProperties(); initData.properties.setProperty("Ice.Plugin.IceSSL", "IceSSL:createIceSSL") initData.properties.setProperty("IceSSL.DefaultDir", os.path.join(toplevel, "certs")) initData.properties.setProperty("IceSSL.CertFile", "server.p12") initData.properties.setProperty("IceSSL.Password", "password") initData.properties.setProperty("IceSSL.Keychain", "test.keychain") initData.properties.setProperty("IceSSL.KeychainPassword", "password") initData.properties.setProperty("IceSSL.VerifyPeer", "0"); initData.properties.setProperty("Ice.ThreadPool.Server.SizeMax", "10") initData.properties.setProperty("Ice.Plugin.IceDiscovery", "IceDiscovery:createIceDiscovery") initData.properties.setProperty("IceDiscovery.DomainId", "TestController") if self.interface: initData.properties.setProperty("IceDiscovery.Interface", self.interface) initData.properties.setProperty("Ice.Default.Host", self.interface) #initData.properties.setProperty("Ice.Trace.Network", "3") #initData.properties.setProperty("Ice.Trace.Protocol", "1") initData.properties.setProperty("ControllerAdapter.Endpoints", self.endpoints) initData.properties.setProperty("ControllerAdapter.AdapterId", Ice.generateUUID()) communicator = Ice.initialize(initData) try: adapter = communicator.createObjectAdapter("ControllerAdapter") adapter.add(ControllerI(self), communicator.stringToIdentity(self.id)) adapter.activate() communicator.waitForShutdown() finally: communicator.destroy()
def allTests(helper, communicator): ref = "ServerManager:{0}".format(helper.getTestEndpoint()) manager = Test.ServerManagerPrx.checkedCast(communicator.stringToProxy(ref)) locator = communicator.getDefaultLocator() test(manager) registry = Test.TestLocatorRegistryPrx.checkedCast(locator.getRegistry()) test(registry) sys.stdout.write("testing stringToProxy... ") sys.stdout.flush() base = communicator.stringToProxy("test @ TestAdapter") base2 = communicator.stringToProxy("test @ TestAdapter") base3 = communicator.stringToProxy("test") base4 = communicator.stringToProxy("ServerManager") base5 = communicator.stringToProxy("test2") print("ok") sys.stdout.write("testing ice_locator and ice_getLocator... ") sys.stdout.flush() test(Ice.proxyIdentityEqual(base.ice_getLocator(), communicator.getDefaultLocator())) anotherLocator = Ice.LocatorPrx.uncheckedCast(communicator.stringToProxy("anotherLocator")) base = base.ice_locator(anotherLocator) test(Ice.proxyIdentityEqual(base.ice_getLocator(), anotherLocator)) communicator.setDefaultLocator(None) base = communicator.stringToProxy("test @ TestAdapter") test(not base.ice_getLocator()) base = base.ice_locator(anotherLocator) test(Ice.proxyIdentityEqual(base.ice_getLocator(), anotherLocator)) communicator.setDefaultLocator(locator) base = communicator.stringToProxy("test @ TestAdapter") test(Ice.proxyIdentityEqual(base.ice_getLocator(), communicator.getDefaultLocator())) # # We also test ice_router/ice_getRouter (perhaps we should add a # test/Ice/router test?) # test(not base.ice_getRouter()) anotherRouter = Ice.RouterPrx.uncheckedCast(communicator.stringToProxy("anotherRouter")) base = base.ice_router(anotherRouter) test(Ice.proxyIdentityEqual(base.ice_getRouter(), anotherRouter)) router = Ice.RouterPrx.uncheckedCast(communicator.stringToProxy("dummyrouter")) communicator.setDefaultRouter(router) base = communicator.stringToProxy("test @ TestAdapter") test(Ice.proxyIdentityEqual(base.ice_getRouter(), communicator.getDefaultRouter())) communicator.setDefaultRouter(None) base = communicator.stringToProxy("test @ TestAdapter") test(not base.ice_getRouter()) print("ok") sys.stdout.write("starting server... ") sys.stdout.flush() manager.startServer() print("ok") sys.stdout.write("testing checked cast... ") sys.stdout.flush() obj = Test.TestIntfPrx.checkedCast(base) obj = Test.TestIntfPrx.checkedCast(communicator.stringToProxy("test@TestAdapter")) obj = Test.TestIntfPrx.checkedCast(communicator.stringToProxy("test @TestAdapter")) obj = Test.TestIntfPrx.checkedCast(communicator.stringToProxy("test@ TestAdapter")) test(obj) obj2 = Test.TestIntfPrx.checkedCast(base2) test(obj2) obj3 = Test.TestIntfPrx.checkedCast(base3) test(obj3) obj4 = Test.ServerManagerPrx.checkedCast(base4) test(obj4) obj5 = Test.TestIntfPrx.checkedCast(base5) test(obj5) print("ok") sys.stdout.write("testing id@AdapterId indirect proxy... ") sys.stdout.flush() obj.shutdown() manager.startServer() try: obj2 = Test.TestIntfPrx.checkedCast(base2) obj2.ice_ping() except Ice.LocalException: test(False) print("ok") sys.stdout.write("testing identity indirect proxy... ") sys.stdout.flush() obj.shutdown() manager.startServer() try: obj3 = Test.TestIntfPrx.checkedCast(base3) obj3.ice_ping() except Ice.LocalException as ex: print(ex) test(False) try: obj2 = Test.TestIntfPrx.checkedCast(base2) obj2.ice_ping() except Ice.LocalException as ex: print(ex) test(False) obj.shutdown() manager.startServer() try: obj2 = Test.TestIntfPrx.checkedCast(base2) obj2.ice_ping() except Ice.LocalException as ex: print(ex) test(False) try: obj3 = Test.TestIntfPrx.checkedCast(base3) obj3.ice_ping() except Ice.LocalException as ex: print(ex) test(False) obj.shutdown() manager.startServer() try: obj2 = Test.TestIntfPrx.checkedCast(base2) obj2.ice_ping() except Ice.LocalException: test(False) obj.shutdown() manager.startServer() try: obj3 = Test.TestIntfPrx.checkedCast(base3) obj3.ice_ping() except Ice.LocalException: test(False) obj.shutdown() manager.startServer() try: obj2 = Test.TestIntfPrx.checkedCast(base2) obj2.ice_ping() except Ice.LocalException: test(False) obj.shutdown() manager.startServer() try: obj5 = Test.TestIntfPrx.checkedCast(base5) obj5.ice_ping() except Ice.LocalException: test(False) print("ok") sys.stdout.write("testing reference with unknown identity... ") sys.stdout.flush() try: base = communicator.stringToProxy("unknown/unknown") base.ice_ping() test(False) except Ice.NotRegisteredException as ex: test(ex.kindOfObject == "object") test(ex.id == "unknown/unknown") print("ok") sys.stdout.write("testing reference with unknown adapter... ") sys.stdout.flush() try: base = communicator.stringToProxy("test @ TestAdapterUnknown") base.ice_ping() test(False) except Ice.NotRegisteredException as ex: test(ex.kindOfObject == "object adapter") test(ex.id == "TestAdapterUnknown") print("ok") sys.stdout.write("testing object reference from server... ") sys.stdout.flush() hello = obj.getHello() hello.sayHello() print("ok") sys.stdout.write("testing object reference from server after shutdown... ") sys.stdout.flush() obj.shutdown() manager.startServer() hello.sayHello() print("ok") sys.stdout.write("testing object migration... ") sys.stdout.flush() hello = Test.HelloPrx.checkedCast(communicator.stringToProxy("hello")) obj.migrateHello() hello.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait) hello.sayHello() obj.migrateHello() hello.sayHello() obj.migrateHello() hello.sayHello() print("ok") sys.stdout.write("shutdown server... ") sys.stdout.flush() obj.shutdown() print("ok") sys.stdout.write("testing whether server is gone... ") sys.stdout.flush() try: obj2.ice_ping() test(False) except Ice.LocalException: pass try: obj3.ice_ping() test(False) except Ice.LocalException: pass try: obj5.ice_ping() test(False) except Ice.LocalException: pass print("ok") sys.stdout.write("testing indirect references to collocated objects... ") sys.stdout.flush() communicator.getProperties().setProperty("Hello.AdapterId", Ice.generateUUID()) adapter = communicator.createObjectAdapterWithEndpoints("Hello", "default") id = Ice.Identity() id.name = Ice.generateUUID() adapter.add(HelloI(), id) helloPrx = Test.HelloPrx.checkedCast(communicator.stringToProxy(Ice.identityToString(id))) test(not helloPrx.ice_getConnection()) helloPrx = Test.HelloPrx.checkedCast(adapter.createIndirectProxy(id)) test(not helloPrx.ice_getConnection()) helloPrx = Test.HelloPrx.checkedCast(adapter.createDirectProxy(id)) test(not helloPrx.ice_getConnection()) print("ok") sys.stdout.write("shutdown server manager... ") sys.stdout.flush() manager.shutdown() print("ok")
def run(communicator): batch = False option = "Twoway" topicName = "mp3App" id = "1" retryCount = "1" if batch and (option in ("Twoway", "Ordered")): print("batch can only be set with oneway or datagram") sys.exit(1) manager = IceStorm.TopicManagerPrx.checkedCast( communicator.propertyToProxy('TopicManager.Proxy')) if not manager: print(" invalid proxy") sys.exit(1) # # Retrieve the topic. # try: topic = manager.retrieve(topicName) except IceStorm.NoSuchTopic as e: try: topic = manager.create(topicName) except IceStorm.TopicExists as ex: print("temporary error. try again") sys.exit(1) adapter = communicator.createObjectAdapter("mp3App.Subscriber") # # Add a servant for the Ice object. If --id is used the identity # comes from the command line, otherwise a UUID is used. # # id is not directly altered since it is used below to detect # whether subscribeAndGetPublisher can raise AlreadySubscribed. # subId = Ice.Identity() subId.name = id if len(subId.name) == 0: subId.name = Ice.generateUUID() subscriber = adapter.add(ServerI(), subId) # # Activate the object adapter before subscribing. # adapter.activate() qos = {} if len(retryCount) > 0: qos["retryCount"] = retryCount try: topic.subscribeAndGetPublisher(qos, subscriber) except IceStorm.AlreadySubscribed as ex: # If we're manually setting the subscriber id ignore. if len(id) == 0: raise print("reactivating persistent subscriber") communicator.waitForShutdown() # # Unsubscribe all subscribed objects. # topic.unsubscribe(subscriber)
session.read().getCallbackManager().registerCallback(ident) LabrestAPI.CallbackI = CallbackI try: ic = Ice.initialize(sys.argv) base = ic.stringToProxy("SimpleEntry:tcp -p 10000") entry = LabrestAPI.EntryPrx.checkedCast(base) if not entry: raise RuntimeError('Invalid proxy') session.write(entry.login('guest','guest')) t=Thread(target=do_refresh) t.start() adapter = ic.createObjectAdapter("") ident = Ice.Identity() ident.name = Ice.generateUUID() ident.category = "" print ident.name cb = LabrestAPI.CallbackI() adapter.add(cb, ident) adapter.activate(); session.read().ice_getConnection().setAdapter(adapter) session.read().getCallbackManager().registerCallback(ident) cbThread = Thread(target = call2skype) cbThread.start() ic.waitForShutdown() except Ice.ConnectionRefusedException: print "connection refused" except: traceback.print_exc() status = 1
def __init__(self, host, port, topic_manager_name, ice_topic_name, adapter_name, metadata_endpoint, control_endpoint): logging.info("initializing") super(IceMetadataSourceService, self).__init__(self.IDLE_STATE) self.metadata_endpoint = metadata_endpoint self.control_endpoint = control_endpoint self.buffer = Queue.Queue() # Set up ICE properties ice_properties = Ice.createProperties() ice_properties.setProperty( "Ice.Default.Locator", "IceGrid/Locator:tcp -h %s -p %s" % (host, port)) # No tracing ice_properties.setProperty("Ice.Trace.Network", "0") ice_properties.setProperty("Ice.Trace.Protocol", "0") # Increase maximum message size from 1MB to 128MB ice_properties.setProperty("Ice.MessageSizeMax", "131072") # Disable IPv6. As of Ice 3.5 it is enabled by default ice_properties.setProperty("Ice.IPv6", "0") # Set the hostname for which clients will initiate a connection # to in order to send messages. By default the Ice server will publish # all ip addresses and clients will round-robin between them for # the puroses of load-balancing. This forces it to only publish # a single ip address. ice_properties.setProperty("Ice.Default.Host", node()) ice_properties.setProperty("%s.Endpoints" % adapter_name, "tcp") logging.debug("Ice properties are: %s" % str(ice_properties)) init_data = Ice.InitializationData() init_data.properties = ice_properties # create the Ice communator logging.debug("Creating communicator") self.communicator = Ice.initialize(init_data) # instantiate a topic manager logging.debug("Instantiating topic manager") topic_manager = self.communicator.stringToProxy(topic_manager_name) topic_manager = IceStorm.TopicManagerPrx.checkedCast(topic_manager) # create an adapter logging.debug("Creating adapter") adapter = self.communicator.createObjectAdapter(adapter_name) # create identity identity = Ice.Identity() uuid = Ice.generateUUID() identity.name = uuid # create subscriber logging.debug("Creating subscriber") subscriber = adapter.add( IceMetadataSourceService._IcePublisher(self.buffer), identity) subscriber = subscriber.ice_twoway() logging.debug("Retrieving topic") try: topic = topic_manager.retrieve(ice_topic_name) except IceStorm.NoSuchTopic: try: topic = topic_manager.create(ice_topic_name) except IceStorm.TopicExists: topic = topic_manager.retrieve(ice_topic_name) logging.debug("Subscribing") qos = {} qos["reliability"] = "ordered" topic.subscribeAndGetPublisher(qos, subscriber) logging.debug("Activating adapter") adapter.activate()
def run(self, args): if len(args) > 1: print(self.appName() + ": too many arguments") return 1 manager = IceStorm.TopicManagerPrx.checkedCast(self.communicator().propertyToProxy('TopicManager.Proxy')) if not manager: print('Invalid topic manager proxy') return 1 print('Topic list:') topic_dict = manager.retrieveAll() for topic_name, topic_prx in topic_dict.items(): print(topic_name) link_info_seq = topic_prx.getLinkInfoSeq() print(' linked topics:') for link_info in link_info_seq: print(' {0} cost {1}'.format(link_info.name, link_info.cost)) # Retrieve the topic. topic_name = platform.node() try: topic = manager.retrieve(topic_name) except IceStorm.NoSuchTopic as e: print('Topic {0} not found'.format(topic_name)) return 1 adapter = self.communicator().createObjectAdapter("Syslog.Subscriber") # Add a servant for the Ice object. # Id is not directly altered since it is used below to detect # whether subscribeAndGetPublisher can raise AlreadySubscribed. subId = Ice.Identity() subId.name = Ice.generateUUID() subscriber = adapter.add(SensorObserverI(), subId) # Activate the object adapter before subscribing. adapter.activate() qos = {} #qos["retryCount"] = retryCount # Set up the proxy. #if option == "Datagram": # if batch: # subscriber = subscriber.ice_batchDatagram() # else: # subscriber = subscriber.ice_datagram() #elif option == "Twoway": # # Do nothing to the subscriber proxy. Its already twoway. # pass #elif option == "Ordered": # # Do nothing to the subscriber proxy. Its already twoway. # qos["reliability"] = "ordered" #elif option == "Oneway" or option == "None": # if batch: # subscriber = subscriber.ice_batchOneway() # else: # subscriber = subscriber.ice_oneway() subscriber = subscriber.ice_batchDatagram() try: topic.subscribeAndGetPublisher(qos, subscriber) except IceStorm.AlreadySubscribed as ex: raise self.shutdownOnInterrupt() self.communicator().waitForShutdown() # Unsubscribe all subscribed objects. topic.unsubscribe(subscriber) return 0
def allTests(communicator, ref): manager = Test.ServerManagerPrx.checkedCast(communicator.stringToProxy(ref)) locator = communicator.getDefaultLocator() test(manager) registry = Test.TestLocatorRegistryPrx.checkedCast(locator.getRegistry()); test(registry); sys.stdout.write("testing stringToProxy... ") sys.stdout.flush() base = communicator.stringToProxy("test @ TestAdapter") base2 = communicator.stringToProxy("test @ TestAdapter") base3 = communicator.stringToProxy("test") base4 = communicator.stringToProxy("ServerManager") base5 = communicator.stringToProxy("test2") print("ok") sys.stdout.write("testing ice_locator and ice_getLocator... ") sys.stdout.flush() test(Ice.proxyIdentityEqual(base.ice_getLocator(), communicator.getDefaultLocator())); anotherLocator = Ice.LocatorPrx.uncheckedCast(communicator.stringToProxy("anotherLocator")); base = base.ice_locator(anotherLocator); test(Ice.proxyIdentityEqual(base.ice_getLocator(), anotherLocator)); communicator.setDefaultLocator(None); base = communicator.stringToProxy("test @ TestAdapter"); test(not base.ice_getLocator()); base = base.ice_locator(anotherLocator); test(Ice.proxyIdentityEqual(base.ice_getLocator(), anotherLocator)); communicator.setDefaultLocator(locator); base = communicator.stringToProxy("test @ TestAdapter"); test(Ice.proxyIdentityEqual(base.ice_getLocator(), communicator.getDefaultLocator())); # # We also test ice_router/ice_getRouter (perhaps we should add a # test/Ice/router test?) # test(not base.ice_getRouter()); anotherRouter = Ice.RouterPrx.uncheckedCast(communicator.stringToProxy("anotherRouter")); base = base.ice_router(anotherRouter); test(Ice.proxyIdentityEqual(base.ice_getRouter(), anotherRouter)); router = Ice.RouterPrx.uncheckedCast(communicator.stringToProxy("dummyrouter")); communicator.setDefaultRouter(router); base = communicator.stringToProxy("test @ TestAdapter"); test(Ice.proxyIdentityEqual(base.ice_getRouter(), communicator.getDefaultRouter())); communicator.setDefaultRouter(None); base = communicator.stringToProxy("test @ TestAdapter"); test(not base.ice_getRouter()); print("ok") sys.stdout.write("starting server... ") sys.stdout.flush() manager.startServer() print("ok") sys.stdout.write("testing checked cast... ") sys.stdout.flush() obj = Test.TestIntfPrx.checkedCast(base) obj = Test.TestIntfPrx.checkedCast(communicator.stringToProxy("test@TestAdapter")) obj = Test.TestIntfPrx.checkedCast(communicator.stringToProxy("test @TestAdapter")) obj = Test.TestIntfPrx.checkedCast(communicator.stringToProxy("test@ TestAdapter")) test(obj) obj2 = Test.TestIntfPrx.checkedCast(base2) test(obj2) obj3 = Test.TestIntfPrx.checkedCast(base3) test(obj3) obj4 = Test.ServerManagerPrx.checkedCast(base4) test(obj4) obj5 = Test.TestIntfPrx.checkedCast(base5) test(obj5) print("ok") sys.stdout.write("testing id@AdapterId indirect proxy... ") sys.stdout.flush() obj.shutdown() manager.startServer() try: obj2 = Test.TestIntfPrx.checkedCast(base2) obj2.ice_ping() except Ice.LocalException: test(False) print("ok") sys.stdout.write("testing identity indirect proxy... ") sys.stdout.flush() obj.shutdown() manager.startServer() try: obj3 = Test.TestIntfPrx.checkedCast(base3) obj3.ice_ping() except Ice.LocalException: test(False) try: obj2 = Test.TestIntfPrx.checkedCast(base2) obj2.ice_ping() except Ice.LocalException: test(False) obj.shutdown() manager.startServer() try: obj2 = Test.TestIntfPrx.checkedCast(base2) obj2.ice_ping() except Ice.LocalException: test(False) try: obj3 = Test.TestIntfPrx.checkedCast(base3) obj3.ice_ping() except Ice.LocalException: test(False) obj.shutdown() manager.startServer() try: obj2 = Test.TestIntfPrx.checkedCast(base2) obj2.ice_ping() except Ice.LocalException: test(False) obj.shutdown() manager.startServer() try: obj3 = Test.TestIntfPrx.checkedCast(base3) obj3.ice_ping() except Ice.LocalException: test(False) obj.shutdown() manager.startServer() try: obj2 = Test.TestIntfPrx.checkedCast(base2) obj2.ice_ping() except Ice.LocalException: test(False) obj.shutdown() manager.startServer() try: obj5 = Test.TestIntfPrx.checkedCast(base5) obj5.ice_ping() except Ice.LocalException: test(False) print("ok") sys.stdout.write("testing reference with unknown identity... ") sys.stdout.flush() try: base = communicator.stringToProxy("unknown/unknown") base.ice_ping() test(False) except Ice.NotRegisteredException as ex: test(ex.kindOfObject == "object") test(ex.id == "unknown/unknown") print("ok") sys.stdout.write("testing reference with unknown adapter... ") sys.stdout.flush() try: base = communicator.stringToProxy("test @ TestAdapterUnknown") base.ice_ping() test(False) except Ice.NotRegisteredException as ex: test(ex.kindOfObject == "object adapter") test(ex.id == "TestAdapterUnknown") print("ok") sys.stdout.write("testing object reference from server... ") sys.stdout.flush() hello = obj.getHello() hello.sayHello() print("ok") sys.stdout.write("testing object reference from server after shutdown... ") sys.stdout.flush() obj.shutdown() manager.startServer() hello.sayHello() print("ok") sys.stdout.write("testing object migration... ") sys.stdout.flush() hello = Test.HelloPrx.checkedCast(communicator.stringToProxy("hello")) obj.migrateHello() hello.ice_getConnection().close(False); hello.sayHello() obj.migrateHello() hello.sayHello() obj.migrateHello() hello.sayHello() print("ok") sys.stdout.write("shutdown server... ") sys.stdout.flush() obj.shutdown() print("ok") sys.stdout.write("testing whether server is gone... ") sys.stdout.flush() try: obj2.ice_ping() test(False) except Ice.LocalException: pass try: obj3.ice_ping() test(False) except Ice.LocalException: pass try: obj5.ice_ping() test(False) except Ice.LocalException: pass print("ok") # # Set up test for calling a collocated object through an indirect, adapterless reference. # sys.stdout.write("testing indirect references to collocated objects... ") sys.stdout.flush() properties = communicator.getProperties(); properties.setProperty("Ice.PrintAdapterReady", "0"); adapter = communicator.createObjectAdapterWithEndpoints("Hello", "default"); adapter.setLocator(locator); assert(adapter.getLocator() == locator) id = Ice.Identity(); id.name = Ice.generateUUID(); registry.addObject(adapter.add(HelloI(), id)); adapter.activate(); helloPrx = Test.HelloPrx.checkedCast(communicator.stringToProxy(communicator.identityToString(id))); test(not helloPrx.ice_getConnection()); adapter.deactivate(); print("ok") sys.stdout.write("shutdown server manager... ") sys.stdout.flush() manager.shutdown() print("ok")
def add_with_uuid(self, servant): return self.object_adapter.add( servant, self.create_callback_identity(Ice.generateUUID()))
def __init__(self, url, text, rating=None): self._id = Ice.Identity() self._id.name = Ice.generateUUID() self._url = url self._text = text self._rating = rating
#trainer_base = ic.stringToProxy("BOW_Trainer:default -p 10003") trainer = cvac.DetectorTrainerPrx.checkedCast(trainer_base) if not trainer: raise RuntimeError("Invalid DetectorTrainer proxy") # this will get called once the training is done class TrainerCallbackReceiverI(cvac.TrainerCallbackHandler): detectorData = None def createdDetector(self, detData, current=None): self.detectorData = detData print("Finished training, obtained DetectorData of type", self.detectorData.type) # ICE functionality to enable bidirectional connection for callback adapter = ic.createObjectAdapter("") callback = Ice.Identity() callback.name = Ice.generateUUID() callback.category = "" tcbrec = TrainerCallbackReceiverI() adapter.add( tcbrec, callback) adapter.activate() trainer.ice_getConnection().setAdapter(adapter) # connect to trainer, initialize with a verbosity value, and train trainer.initialize( 3 ) trainer.process( callback, runset ) if tcbrec.detectorData.type == cvac.DetectorDataType.FILE: print("received file: {0}/{1}".format(tcbrec.detectorData.file.directory.relativePath, tcbrec.detectorData.file.filename)) elif tcbrec.detectorData.type == cvac.DetectorDataType.BYTES: print("received bytes")
def run(self, mappings, testSuiteIds): if isinstance(platform, Darwin): # # On macOS, we set the trust settings on the certificate to prevent # the Web browsers from prompting the user about the untrusted # certificate. Some browsers such as Chrome don't provide the # option to set this trust settings. # serverCert = os.path.join(toplevel, "certs", "server.pem") if self.clean: if os.system("security verify-cert -c " + serverCert + " >& /dev/null") == 0: sys.stdout.write("removing trust settings for the HTTP server certificate... ") sys.stdout.flush() if os.system("security remove-trusted-cert " + serverCert) != 0: print("\nerror: couldn't remove trust settings for the HTTP server certificate") else: print("ok") else: print("trust settings already removed") return else: if os.system("security verify-cert -c " + serverCert + " >& /dev/null") != 0: sys.stdout.write("adding trust settings for the HTTP server certificate... ") sys.stdout.flush() if os.system("security add-trusted-cert -r trustAsRoot " + serverCert) != 0: print("error: couldn't add trust settings for the HTTP server certificate") print("ok") print("run " + sys.argv[0] + " --clean to remove the trust setting") self.initCommunicator() import Ice Ice.loadSlice(os.path.join(toplevel, "scripts", "Controller.ice")) import Test class TestCaseI(Test.Common.TestCase): def __init__(self, driver, current): self.driver = driver self.current = current self.serverSideRunning = False def startServerSide(self, config, c): self.updateCurrent(config) try: self.serverSideRunning = True return self.current.serverTestCase._startServerSide(self.current) except Exception as ex: self.serverSideRunning = False raise Test.Common.TestCaseFailedException(self.current.result.getOutput() + "\n" + traceback.format_exc()) def stopServerSide(self, success, c): if self.serverSideRunning: try: self.current.serverTestCase._stopServerSide(self.current, success) return self.current.result.getOutput() except Exception as ex: raise Test.Common.TestCaseFailedException(self.current.result.getOutput() + "\n" + str(ex)) def runClientSide(self, host, config, c): self.updateCurrent(config) try: self.current.clientTestCase._runClientSide(self.current, host) return self.current.result.getOutput() except Exception as ex: raise Test.Common.TestCaseFailedException(self.current.result.getOutput() + "\n" + str(ex)) def destroy(self, c): if self.serverSideRunning: try: self.current.serverTestCase._stopServerSide(self.current, False) except: pass c.adapter.remove(c.id) def updateCurrent(self, config): attrs = ["protocol", "mx", "serialize", "compress", "ipv6", "cprops", "sprops"] for a in attrs: v = getattr(config, a) if v is not Ice.Unset: if a not in self.current.config.parsedOptions: self.current.config.parsedOptions.append(a) setattr(self.current.config, a, v) class ControllerI(Test.Common.Controller): def __init__(self, driver): self.driver = driver self.testcase = None def runTestCase(self, mapping, testsuite, testcase, cross, c): if self.testcase: try: self.testcase.destroy() except: pass self.testcase = None current = self.driver.getCurrent(mapping, testsuite, testcase, cross) self.testcase = Test.Common.TestCasePrx.uncheckedCast(c.adapter.addWithUUID(TestCaseI(self.driver, current))) return self.testcase def getTestSuites(self, mapping, c): mapping = Mapping.getByName(mapping) config = self.driver.configs[mapping] return [str(t) for t in mapping.getTestSuites() if not mapping.filterTestSuite(t.getId(), config)] def getOptionOverrides(self, c): return Test.Common.OptionOverrides(ipv6=([False] if not self.driver.hostIPv6 else [False, True])) self.initCommunicator() self.communicator.getProperties().setProperty("ControllerAdapter.Endpoints", self.endpoints) self.communicator.getProperties().setProperty("ControllerAdapter.AdapterId", Ice.generateUUID()) adapter = self.communicator.createObjectAdapter("ControllerAdapter") adapter.add(ControllerI(self), self.communicator.stringToIdentity(self.id)) adapter.activate() self.communicator.waitForShutdown()
def run(self, args): if len(args) > 1: print(self.appName() + ": too many arguments") return 1 manager = IceStorm.TopicManagerPrx.checkedCast(self.communicator().propertyToProxy('TopicManager.Proxy')) if not manager: print('Invalid topic manager proxy') return 1 print('Topic list:') topic_dict = manager.retrieveAll() for topic_name, topic_prx in topic_dict.items(): print(topic_name) link_info_seq = topic_prx.getLinkInfoSeq() print(' linked topics:') for link_info in link_info_seq: print(' {0} cost {1}'.format(link_info.name, link_info.cost)) # Retrieve the topic. topic_name = platform.node() try: topic = manager.retrieve(topic_name) except IceStorm.NoSuchTopic as e: print('Topic {0} not found'.format(topic_name)) return 1 adapter = self.communicator().createObjectAdapter("Syslog.Subscriber") observer_interest_dict = {} for c in self.component_list: interest_list = c.get_supported_sensor_types() for interest in interest_list: if interest in observer_interest_dict: observer_interest_dict[t].append(c) else: observer_interest_dict[interest] = [c] sensor_observer = SensorObserverI(observer_interest_dict) # Add a servant for the Ice object. # Id is not directly altered since it is used below to detect # whether subscribeAndGetPublisher can raise AlreadySubscribed. subId = Ice.Identity() subId.name = Ice.generateUUID() subscriber = adapter.add(sensor_observer, subId) # Activate the object adapter before subscribing. adapter.activate() qos = {} #qos["retryCount"] = retryCount # Set up the proxy. #if option == "Datagram": # if batch: # subscriber = subscriber.ice_batchDatagram() # else: # subscriber = subscriber.ice_datagram() #elif option == "Twoway": # # Do nothing to the subscriber proxy. Its already twoway. # pass #elif option == "Ordered": # # Do nothing to the subscriber proxy. Its already twoway. # qos["reliability"] = "ordered" #elif option == "Oneway" or option == "None": # if batch: # subscriber = subscriber.ice_batchOneway() # else: # subscriber = subscriber.ice_oneway() subscriber = subscriber.ice_batchDatagram() try: topic.subscribeAndGetPublisher(qos, subscriber) except IceStorm.AlreadySubscribed as ex: raise self.shutdownOnInterrupt() while True: # main game loop try: new_events = pygame.event.get() # Retrieve new events self.display_surf.fill((0, 0, 0)) # black background # Let each component update visual representation for c in self.component_list: c.process_events(new_events) c.update_visuals() pygame.display.update() # Check if we should quit for event in new_events: if event.type == QUIT: pygame.quit() return 0 self.main_clock.tick(FPS) except Ice.Exception as ex: print(ex) break # Unsubscribe all subscribed objects. topic.unsubscribe(subscriber) return 0
return 1 adapter = self.communicator().createObjectAdapter("Clock.Subscriber") # # Add a servant for the Ice object. If --id is used the identity # comes from the command line, otherwise a UUID is used. # # id is not directly altered since it is used below to detect # whether subscribeAndGetPublisher can raise AlreadySubscribed. # subId = Ice.Identity() subId.name = id if len(subId.name) == 0: subId.name = Ice.generateUUID() subscriber = adapter.add(ClockI(), subId) qos = {} if len(retryCount) > 0: qos["retryCount"] = retryCount # # Set up the proxy. # if option == "Datagram": if batch: subscriber = subscriber.ice_batchDatagram() else: subscriber = subscriber.ice_datagram() elif option == "Twoway":