class PacketIn(object): '''PacketIn message is an interest for inquiring unknown prefix ''' def __init__(self): self.keyChain = KeyChain() self.isDone = False self.ofmsg = OFMSG() self.outstanding = dict() #a dictionary to keep track of outstanding Interests and retransmissions. #self.face = Face("127.0.0.1") self.face = Face() self.nodeid = OSCommand.getnodeid() def run(self, unknown_prefix="/abcd/dfgh/tcd"): try: self._sendPacketinInterest(unknown_prefix) while not self.isDone: self.face.processEvents() time.sleep(0.01) except RuntimeError as e: print("ERROR: %s" % e) return self.isDone def _sendPacketinInterest(self,unknown_prefix): interest = self.ofmsg.create_packetin_msg_interest(unknown_prefix, self.nodeid) uri = interest.getName().toUri() if uri not in self.outstanding: self.outstanding[uri] = 1 self.face.expressInterest(interest, self._onData, self._onTimeout) print("######### Sent <<<PacketIn>>> Interest #########\n {0} \n".format(uri)) def _onData(self, interest, data): payload = data.getContent() name = data.getName() print("Received <<<<FlowMod data>>>>from Controller ") self.nodeid = OSCommand.getnodeid() # add this item to flow table. FlowModDataList = NdnFlowTable.parse_FlowMod_Data(payload) # print(FlowModDataList) NdnFlowTable.updatendnflowtable(FlowModDataList,self.nodeid) print(NdnFlowTable) del self.outstanding[name.toUri()] self.isDone = True def _onTimeout(self, interest): name = interest.getName() uri = name.toUri() print("TIMEOUT #%d: %s" % (self.outstanding[uri], uri)) self.outstanding[uri] += 1 self.isDone = True
def __init__(self, producerName, namePrefix): self.configPrefix = Name(namePrefix) prefix_pullService = "/picasso/pull_Service/" self.prefix_pullService = Name(prefix_pullService) self.Datamessage_size = 19990000 #20MB --> Max Size from modified NDN self.window = 5 self.producerName = producerName self.outstanding = dict() self.isDone = False self.keyChain = KeyChain() self.face = Face("127.0.0.1") self.script_path = os.path.abspath( __file__) # i.e. /path/to/dir/foobar.py self.script_dir = os.path.split( self.script_path)[0] #i.e. /path/to/dir/ self.interestLifetime = 800000 self.num_deployedContainer = 0 self.lastChunk_window = 0 self.lastChunk_sent = 0 folder_name = "SEG_repository/" self.repo_path = os.path.join(self.script_dir, folder_name) if not os.path.exists(self.repo_path): os.makedirs(self.repo_path) folder_name = "Migration_cost/" self.timestamp_path = os.path.join(self.script_dir, folder_name) if not os.path.exists(self.timestamp_path): os.makedirs(self.timestamp_path)
def __init__(self, data_size, verbose=False): # create a KeyChain for signing data packets self._key_chain = KeyChain() self._is_done = False self._num_interests = 0 # self._keyChain.createIdentityV2(Name("/ndn/identity")) # the number of interests to satisfy before shutdown of server self._max_interests = 0 # host data at the local forwarder self._face = Face() # immutable byte array to use as data self._byte_array = bytes(data_size) # the number of bytes contained in each data packet self._data_size = data_size # the verbosity of diagnostic information self._verbose = verbose # keep track of if the first interest has been recieved (for timing) self._is_first_interst = True # keep track of various performance metrics: self._interests_satisfied = 0 self._interests_recieved = 0 self._data_sent = 0 self._elapsed_time = {} self._initial_time = {} self._final_time = {} print("Producer instance created.")
class FlowRemovedMsg(object): '''FlowRemoved message is an interest send once, no need response ''' def __init__(self): self.keyChain = KeyChain() self.ofmsg = OFMSG() self.face = Face() def run(self,removed_prefix): try: self._sendFlowRemovedInterest(removed_prefix) n=0 while n<200: self.face.processEvents() time.sleep(0.01) n+=1 except RuntimeError as e: print("ERROR: %s" % e) return True def _sendFlowRemovedInterest(self,removed_prefix): interest = self.ofmsg.create_flowremoved_msg_interest(removed_prefix) uri = interest.getName().toUri() self.face.expressInterest(interest, self._onData, self._onTimeout) print("--------Sent <<<FlowRemoved>>> Msg for %s" % uri) def _onData(self, interest, data): pass def _onTimeout(self, interest): pass
def main(): # The default Face connects to the local NFD. face = Face() interest = Interest(Name("/localhost/nfd/rib/list")) interest.setInterestLifetimeMilliseconds(4000) dump("Express interest", interest.getName().toUri()) enabled = [True] def onComplete(content): enabled[0] = False printRibEntries(content) def onError(errorCode, message): enabled[0] = False dump(message) SegmentFetcher.fetch( face, interest, SegmentFetcher.DontVerifySegment, onComplete, onError) # Loop calling processEvents until a callback sets enabled[0] = False. while enabled[0]: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01)
def main(): # Silence the warning from Interest wire encode. Interest.setDefaultCanBePrefix(True) # The default Face connects to the local NFD. face = Face() interest = Interest(Name("/localhost/nfd/faces/list")) interest.setInterestLifetimeMilliseconds(4000) dump("Express interest", interest.getName().toUri()) enabled = [True] def onComplete(content): enabled[0] = False printFaceStatuses(content) def onError(errorCode, message): enabled[0] = False dump(message) SegmentFetcher.fetch(face, interest, None, onComplete, onError) # Loop calling processEvents until a callback sets enabled[0] = False. while enabled[0]: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01)
def main(): if len(sys.argv) < 2: print("Usage:", sys.argv[0], "command-prefix", file=sys.stderr) return -1 else: command_prefix = sys.argv[1] logging.basicConfig(format='[%(asctime)s]%(levelname)s:%(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO) event_loop = asyncio.get_event_loop() face = Face() keychain = KeyChain() face.setCommandSigningInfo(keychain, keychain.getDefaultCertificateName()) server = Server(face, command_prefix) async def face_loop(): nonlocal face, server while server.running: face.processEvents() await asyncio.sleep(0.01) try: event_loop.run_until_complete(face_loop()) finally: event_loop.close()
async def fetch_data_packet(face: Face, interest: Interest) -> Union[Data, NetworkNack, None]: done = asyncio.Event() result = None def on_data(_interest, data: Data): nonlocal done, result logging.info('on data') result = data done.set() def on_timeout(_interest): nonlocal done logging.info('timeout') done.set() def on_network_nack(_interest, network_nack: NetworkNack): nonlocal done, result logging.info('nack') result = network_nack done.set() try: face.expressInterest(interest, on_data, on_timeout, on_network_nack) await done.wait() return result except (ConnectionRefusedError, BrokenPipeError) as error: return error
def __init__(self): self.outstanding = dict() self.isDone = False self.keyChain = KeyChain() self.face = Face("127.0.0.1") self.nameInput = '/umobile/pull'
def init_network(self, prefix): self.prefix = prefix self.face = Face() self.keychain = KeyChain() self.face.setCommandSigningInfo( self.keychain, self.keychain.getDefaultCertificateName()) self.face.registerPrefix(self.prefix, None, self.on_register_failed)
def main(): # The default Face connects to the local NFD. face = Face() interest = Interest(Name("/localhost/nfd/rib/list")) interest.setInterestLifetimeMilliseconds(4000) dump("Express interest", interest.getName().toUri()) enabled = [True] def onComplete(content): enabled[0] = False printRibEntries(content) def onError(errorCode, message): enabled[0] = False dump(message) SegmentFetcher.fetch(face, interest, SegmentFetcher.DontVerifySegment, onComplete, onError) # Loop calling processEvents until a callback sets enabled[0] = False. while enabled[0]: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01)
def setUp(self): testCertDirectory = 'policy_config/certs' self.testCertFile = os.path.join(testCertDirectory, 'test.cert') self.identityStorage = MemoryIdentityStorage() self.privateKeyStorage = MemoryPrivateKeyStorage() self.identityManager = IdentityManager(self.identityStorage, self.privateKeyStorage) self.policyManager = ConfigPolicyManager('policy_config/simple_rules.conf') self.identityName = Name('/TestConfigPolicyManager/temp') # to match the anchor cert keyName = Name(self.identityName).append('ksk-1416010123') self.privateKeyStorage.setKeyPairForKeyName( keyName, KeyType.RSA, TEST_RSA_PUBLIC_KEY_DER, TEST_RSA_PRIVATE_KEY_DER) self.identityStorage.addKey( keyName, KeyType.RSA, Blob(TEST_RSA_PUBLIC_KEY_DER)) cert = self.identityManager.selfSign(keyName) self.identityStorage.setDefaultKeyNameForIdentity(keyName) self.identityManager.addCertificateAsDefault(cert) self.keyChain = KeyChain(self.identityManager, self.policyManager) self.keyName = keyName self.face = Face()
def main(): # Silence the warning from Interest wire encode. Interest.setDefaultCanBePrefix(True) # The default Face will connect using a Unix socket, or to "localhost". face = Face() prefix = Namespace("/ndn/test/status") prefix.setFace(face) enabled = [True] # This is called to print the content after it is re-assembled from segments. def onGeneralizedObject(contentMetaInfo, objectNamespace): dump("Got generalized object", objectNamespace.name, ", content-type", contentMetaInfo.contentType, ":", str(objectNamespace.obj)) enabled[0] = False handler = GeneralizedObjectHandler(prefix, onGeneralizedObject) # Allow one component after the prefix for the <version>. handler.setNComponentsAfterObjectNamespace(1) # In objectNeeded, set mustBeFresh == true so we avoid expired cached data. prefix.objectNeeded(True) # Loop calling processEvents until a callback sets enabled[0] = False. while enabled[0]: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01)
def main(): async def face_loop(): nonlocal face, repo while repo.running: face.processEvents() await asyncio.sleep(0.001) config = get_yaml() logging.info(config) face = Face() keychain = KeyChain() face.setCommandSigningInfo(keychain, keychain.getDefaultCertificateName()) # storage = LevelDBStorage(config['db_config']['leveldb']['dir']) storage = MongoDBStorage(config['db_config']['mongodb']['db'], config['db_config']['mongodb']['collection']) read_handle = ReadHandle(face, keychain, storage) write_handle = WriteCommandHandle(face, keychain, storage, read_handle) delete_handle = DeleteCommandHandle(face, keychain, storage) tcp_bulk_insert_handle = TcpBulkInsertHandle( storage, read_handle, config['tcp_bulk_insert']['addr'], config['tcp_bulk_insert']['port']) repo = Repo(Name(config['repo_config']['repo_name']), face, storage, read_handle, write_handle, delete_handle, tcp_bulk_insert_handle) repo.listen() # my nfd is broken... event_loop = asyncio.get_event_loop() try: event_loop.run_until_complete(face_loop()) finally: event_loop.close()
def __init__(self, prefix): self.prefix = Name(prefix) self.outstanding = dict() self.isDone = False self.face = Face("127.0.0.1") self.start_time = 0 start_time = time.time()
def start(self, osDur, startingColors): self.loop = asyncio.get_event_loop() self.lightFace = Face(self.lightAddress) self.lightFace.setCommandSigningInfo(self.keychain, self.certificateName) asyncio.Task(self.issueLightingCommand(osDur, startingColors))
def __init__(self, HostName, prefixesToSend): self.host = Name(HostName) self.outstanding = dict() self.prefixesToSend = prefixesToSend self.isDone = False self.face = Face("127.0.0.1")
class Consumer(object): '''Hello World consumer''' def __init__(self, gatewayprefix, newprefix, chatroom): self.gatewayprefix = Name(gatewayprefix) self.newprefix = str(Name(newprefix)) self.chatroom = str(Name(chatroom)) self.parameter = self.newprefix + "|" + self.chatroom self.outstanding = dict() self.isDone = False self.face = Face("127.0.0.1") def run(self): os.system("nlsrc advertise " + self.newprefix) os.system("nlsrc advertise " + self.chatroom) try: self._sendNextInterest(self.gatewayprefix) while not self.isDone: self.face.processEvents() time.sleep(0.01) except RuntimeError as e: print "ERROR: %s" % e def _sendNextInterest(self, name): interest = Interest(name) uri = name.toUri() interest.setApplicationParameters(self.parameter) interest.setInterestLifetimeMilliseconds(4000) interest.setMustBeFresh(True) if uri not in self.outstanding: self.outstanding[uri] = 1 self.face.expressInterest(interest, self._onData, self._onTimeout) print "Sent Interest for %s" % uri print interest def _onData(self, interest, data): payload = data.getContent() name = data.getName() print "Received response from gateway: ", payload.toRawStr() del self.outstanding[name.toUri()] self.isDone = True def _onTimeout(self, interest): name = interest.getName() uri = name.toUri() print "TIMEOUT #%d: %s" % (self.outstanding[uri], uri) self.outstanding[uri] += 1 if self.outstanding[uri] <= 1000: self._sendNextInterest(name) else: self.isDone = True
def main(): # The default Face will connect using a Unix socket, or to "localhost". face = Face() prefix = Name("/icear-server/result/example-data/2/deeplab") prefixNamespace = Namespace(prefix) prefixNamespace.setFace(face) enabled = [True] img = [None] def onGeneralizedObject(contentMetaInfo, obj): data = obj.toBytes() dump("Got generalized object, content-type", contentMetaInfo.getContentType(), ":", repr(data)) print(len(data)) enabled[0] = False img[0] = data goh = GeneralizedObjectHandler(onGeneralizedObject) prefixNamespace.setHandler(goh).objectNeeded() # Loop calling processEvents until a callback sets enabled[0] = False. while enabled[0]: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01) image = Image.open(io.BytesIO(img[0])) image.show()
def main(): face = Face() keychain = KeyChain() face.setCommandSigningInfo(keychain, keychain.getDefaultCertificateName()) async def face_loop(): nonlocal face while True: face.processEvents() await asyncio.sleep(0.001) parser = argparse.ArgumentParser(description='segmented insert client') parser.add_argument('-r', '--repo_name', required=True, help='Name of repo') parser.add_argument('-p', '--process_id', required=True, help="Process ID") args = parser.parse_args() logging.basicConfig(format='[%(asctime)s]%(levelname)s:%(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO) client = CommandChecker(face, keychain) event_loop = asyncio.get_event_loop() event_loop.create_task(face_loop()) event_loop.run_until_complete(client.check_delete(args.repo_name, int(args.process_id)))
def __init__(self, namePrefix): self.outstanding = dict() self.isDone = False self.keyChain = KeyChain() self.face = Face("127.0.0.1") self.configPrefix = Name(namePrefix) self.script_path = os.path.abspath(__file__) # i.e. /path/to/dir/foobar.py self.script_dir = os.path.split(self.script_path)[0] #i.e. /path/to/dir/ self.interestLifetime = 12000 folder_name = "SC_repository/" rel_path = os.path.join(self.script_dir, folder_name) prefix_startDE = "/picasso/start_de/" self.prefix_startDE = Name(prefix_startDE) self.prefix_deployService = '/picasso/service_deployment_push/' self.json_server_Spec_default= { # This is only an skeleton 'par':{ # service parameters 'serviceName': 'nameOfService', 'imageName': 'NameOfImageToIstantiateService', 'imageSize': 'sizeOfImage', 'maxConReq': 'maxNumConcurrentRequestsThatAnIntanceCanHandle', 'startUpTime': 'timeToInstatiateService' }, 'QoS':{ #QoS parameters expected from the service 'responseTime': 'resposeTimeExpectedFromService', 'availability': 'availabilityExpectedFromService', 'numConReq': 'numConcurrentRequestsToBeHandledByService' } } if not os.path.exists(rel_path): os.makedirs(rel_path)
def main(): # The default Face will connect using a Unix socket, or to "localhost". face = Face() # Use the system default key chain and certificate name to sign commands. #print("key1") #keyChain = KeyChain() #print("key2") identityStorage = MemoryIdentityStorage() privateKeyStorage = MemoryPrivateKeyStorage() keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage), NoVerifyPolicyManager()) identityName = Name("UbiCDN") certificateName = keyChain.createIdentityAndCertificate(identityName) keyChain.getIdentityManager().setDefaultIdentity(identityName) face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName()) # Also use the default certificate name to sign data packets. echo = UbiCDN(keyChain, certificateName) prefix = Name("/ubicdn/video") dump("Register prefix", prefix.toUri()) face.registerPrefix(prefix, echo.onInterest, echo.onRegisterFailed) while echo._responseCount < 1: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01) face.shutdown()
def main(): face = Face() keychain = KeyChain() face.setCommandSigningInfo(keychain, keychain.getDefaultCertificateName()) running = True img = None interest = Interest(Name("/icear-server/result/example-data/2/deeplab")) interest.mustBeFresh = True def on_data(_, data): # type: (Interest, Data) -> None nonlocal running, img print(data.name.toUri()) print(data.content.toBytes()) running = False if data.metaInfo.type == ContentType.NACK: print("NACK") else: img = data.content.toBytes() face.expressInterest(interest, on_data) while running: face.processEvents() time.sleep(0.01) face.shutdown() if img: image = Image.open(io.BytesIO(img)) image.show()
def main(): # Silence the warning from Interest wire encode. Interest.setDefaultCanBePrefix(True) # The default Face will connect using a Unix socket, or to "localhost". face = Face() memberName = Name("/first/user") memberKeyName = Name(memberName).append(Name("/KEY/%0C%87%EB%E6U%27B%D6")) memberKeyChain = KeyChain("pib-memory:", "tpm-memory:") memberKeyChain.importSafeBag(SafeBag (memberKeyName, Blob(MEMBER_PRIVATE_KEY, False), Blob(MEMBER_PUBLIC_KEY, False))) # TODO: Use a real Validator. decryptor = DecryptorV2( memberKeyChain.getPib().getIdentity(memberName).getDefaultKey(), ValidatorNull(), memberKeyChain, face) contentPrefix = Name("/testname/content") contentNamespace = Namespace(contentPrefix) contentNamespace.setFace(face) contentNamespace.setDecryptor(decryptor) enabled = [True] def onSegmentedObject(objectNamespace): dump("Got segmented content", objectNamespace.obj.toRawStr()) enabled[0] = False SegmentedObjectHandler(contentNamespace, onSegmentedObject).objectNeeded() while enabled[0]: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01)
class Consumer(object): '''Hello World consumer''' def __init__(self, prefix): self.prefix = Name(prefix) self.outstanding = dict() self.isDone = False self.face = Face("127.0.0.1") self.start_time = 0 start_time = time.time() def run(self): try: self._sendNextInterest(self.prefix) while not self.isDone: self.face.processEvents() time.sleep(0.01) except RuntimeError as e: print "ERROR: %s" % e def _sendNextInterest(self, name): self.start_time = time.time() interest = Interest(name) uri = name.toUri() interest.setInterestLifetimeMilliseconds(9000) interest.setMustBeFresh(False) if uri not in self.outstanding: self.outstanding[uri] = 1 self.face.expressInterest(interest, self._onData, self._onTimeout) # print "Sent Interest for %s" % uri def _onData(self, interest, data): payload = data.getContent() name = data.getName() # print "Received data: ", len(payload.toRawStr()) # print "Processing data: " time.sleep(2) del self.outstanding[name.toUri()] self.isDone = True elapsed_time = time.time() - self.start_time print elapsed_time def _onTimeout(self, interest): name = interest.getName() uri = name.toUri() print "TIMEOUT #%d: %s" % (self.outstanding[uri], uri) self.outstanding[uri] += 1 if self.outstanding[uri] <= 3: self._sendNextInterest(name) else: self.isDone = True
async def fetch_data_packet( face: Face, interest: Interest) -> Union[Data, NetworkNack, None]: done = threading.Event() result = None def on_data(_interest, data: Data): nonlocal done, result result = data done.set() def on_timeout(_interest): nonlocal done done.set() def on_network_nack(_interest, network_nack: NetworkNack): nonlocal done, result result = network_nack done.set() async def wait_for_event(): ret = False while not ret: ret = done.wait(0.01) await asyncio.sleep(0.01) try: face.expressInterest(interest, on_data, on_timeout, on_network_nack) await wait_for_event() return result except (ConnectionRefusedError, BrokenPipeError) as error: return error
class Consumer(object): def __init__(self): self.outstanding = dict() self.isDone = False self.keyChain = KeyChain() self.face = Face("127.0.0.1") self.nameInput = '/umobile/pull' def run(self): try: self._sendNextInterest(Name(self.nameInput)) while not self.isDone: self.face.processEvents() time.sleep(0.01) except RuntimeError as e: print "ERROR: %s" % e def _sendNextInterest(self, name): interest = Interest(name) uri = name.toUri() interest.setInterestLifetimeMilliseconds(4000) interest.setMustBeFresh(True) if uri not in self.outstanding: self.outstanding[uri] = 1 self.face.expressInterest(interest, self._onData, self._onTimeout) print "Sent Interest for %s" % uri def _onData(self, interest, data): payload = data.getContent() dataName = data.getName() dataName_size = dataName.size() print "Received data name: ", dataName.toUri() print "Received data: ", payload.toRawStr() self.isDone = True def _onTimeout(self, interest): name = interest.getName() uri = name.toUri() print "TIMEOUT #%d: %s" % (self.outstanding[uri], uri) self.outstanding[uri] += 1 if self.outstanding[uri] <= 3: self._sendNextInterest(name) else: self.isDone = True def onRegisterFailed(self, prefix): print "Register failed for prefix", prefix.toUri() self.isDone = True
def main(): interest = Interest() interest.wireDecode(TlvInterest) dump("Interest:") dumpInterest(interest) # Set the name again to clear the cached encoding so we encode again. interest.setName(interest.getName()) encoding = interest.wireEncode() dump("") dump("Re-encoded interest", encoding.toHex()) reDecodedInterest = Interest() reDecodedInterest.wireDecode(encoding) dump("Re-decoded Interest:") dumpInterest(reDecodedInterest) freshInterest = Interest(Name("/ndn/abc")) freshInterest.setMustBeFresh(False) dump(freshInterest.toUri()) freshInterest.setMinSuffixComponents(4) freshInterest.setMaxSuffixComponents(6) freshInterest.getKeyLocator().setType(KeyLocatorType.KEY_LOCATOR_DIGEST) freshInterest.getKeyLocator().setKeyData(bytearray( [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F])) freshInterest.getExclude().appendComponent(Name("abc")[0]).appendAny() freshInterest.setInterestLifetimeMilliseconds(30000) freshInterest.setChildSelector(1) freshInterest.setMustBeFresh(True); freshInterest.setScope(2) identityStorage = MemoryIdentityStorage() privateKeyStorage = MemoryPrivateKeyStorage() keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage), SelfVerifyPolicyManager(identityStorage)) # Initialize the storage. keyName = Name("/testname/DSK-123") certificateName = keyName.getSubName(0, keyName.size() - 1).append( "KEY").append(keyName[-1]).append("ID-CERT").append("0") identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER)) privateKeyStorage.setKeyPairForKeyName( keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER) # Make a Face just so that we can sign the interest. face = Face("localhost") face.setCommandSigningInfo(keyChain, certificateName) face.makeCommandInterest(freshInterest) reDecodedFreshInterest = Interest() reDecodedFreshInterest.wireDecode(freshInterest.wireEncode()) dump("") dump("Re-decoded fresh Interest:") dumpInterest(reDecodedFreshInterest) keyChain.verifyInterest( reDecodedFreshInterest, makeOnVerified("Freshly-signed Interest"), makeOnVerifyFailed("Freshly-signed Interest"))
def cert_server_thread(): face = Face() CertServer(face) while True: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01)
def __init__(self, prefix): # Create a connection to the local forwarder and # initialize outstanding Interest state keeping self.prefix = Name(prefix) self.outstanding = dict() self.isDone = False self.face = Face("127.0.0.1") pass
def __init__(self, prefix, pipeline): self.prefix = Name(prefix) self.pipeline = pipeline self.nextSegment = 0 self.outstanding = dict() self.isDone = False self.face = Face("127.0.0.1")
def __init__(self): self.outstanding = dict() self.isDone = False self.keyChain = KeyChain() self.face = Face("127.0.0.1") self.nameInput = '/umobile/push_PulblishData/publish' self.configPrefix = Name(self.nameInput)
class Consumer(object): '''Hello World consumer''' def __init__(self, prefix): self.prefix = Name(prefix) self.outstanding = dict() self.isDone = False self.face = Face("127.0.0.1") def run(self): try: self._sendNextInterest(self.prefix) while not self.isDone: self.face.processEvents() time.sleep(0.01) except RuntimeError as e: print "ERROR: %s" % e def _sendNextInterest(self, name): interest = Interest(name) uri = name.toUri() interest.setInterestLifetimeMilliseconds(4000) interest.setMustBeFresh(True) if uri not in self.outstanding: self.outstanding[uri] = 1 self.face.expressInterest(interest, self._onData, self._onTimeout) print "Sent Interest for %s" % uri def _onData(self, interest, data): payload = data.getContent() name = data.getName() print "Received data: ", payload.toRawStr() del self.outstanding[name.toUri()] self.isDone = True def _onTimeout(self, interest): name = interest.getName() uri = name.toUri() print "TIMEOUT #%d: %s" % (self.outstanding[uri], uri) self.outstanding[uri] += 1 if self.outstanding[uri] <= 3: self._sendNextInterest(name) else: self.isDone = True
def main(): # Silence the warning from Interest wire encode. Interest.setDefaultCanBePrefix(True) interest = Interest() interest.wireDecode(TlvInterest) dump("Interest:") dumpInterest(interest) # Set the name again to clear the cached encoding so we encode again. interest.setName(interest.getName()) encoding = interest.wireEncode() dump("") dump("Re-encoded interest", encoding.toHex()) reDecodedInterest = Interest() reDecodedInterest.wireDecode(encoding) dump("Re-decoded Interest:") dumpInterest(reDecodedInterest) freshInterest = (Interest(Name("/ndn/abc")) .setMustBeFresh(False) .setMinSuffixComponents(4) .setMaxSuffixComponents(6) .setInterestLifetimeMilliseconds(30000) .setChildSelector(1) .setMustBeFresh(True)) freshInterest.getKeyLocator().setType(KeyLocatorType.KEY_LOCATOR_DIGEST) freshInterest.getKeyLocator().setKeyData(bytearray( [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F])) freshInterest.getExclude().appendComponent(Name("abc")[0]).appendAny() freshInterest.getForwardingHint().add(1, Name("/A")) dump(freshInterest.toUri()) # Set up the KeyChain. keyChain = KeyChain("pib-memory:", "tpm-memory:") keyChain.importSafeBag(SafeBag (Name("/testname/KEY/123"), Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False), Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False))) validator = Validator(ValidationPolicyFromPib(keyChain.getPib())) # Make a Face just so that we can sign the interest. face = Face("localhost") face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName()) face.makeCommandInterest(freshInterest) reDecodedFreshInterest = Interest() reDecodedFreshInterest.wireDecode(freshInterest.wireEncode()) dump("") dump("Re-decoded fresh Interest:") dumpInterest(reDecodedFreshInterest) validator.validate( reDecodedFreshInterest, makeSuccessCallback("Freshly-signed Interest"), makeFailureCallback("Freshly-signed Interest"))
def main(): # The default Face will connect using a Unix socket, or to "localhost". face = Face() keyChain = KeyChain() face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName()) dataPrefix = "/home/test1/data" repoDataPrefix = "/home/test1/data" # Set up repo-ng, register prefix for repo-ng's fetch prefix # Per configuration file in /usr/local/etc/ndn/repo-ng.conf # memCache is not used for now; repo is hoping that the piece of data in question is still being held at nfd #memCache = MemoryContentCache(face, 100000) #memCache.registerPrefix(Name(repoDataPrefix), onRegisterFailed, onDataNotFound) counter = Counter(face, repoDataPrefix) interest = Interest(Name(dataPrefix)) interest.setChildSelector(1) interest.setInterestLifetimeMilliseconds(defaultInterestLifetime) face.expressInterest(interest, counter.onData, counter.onTimeout) while True: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(1) face.shutdown()
class TestRegistrationCallbacks(ut.TestCase): def setUp(self): self.face = Face() keyChain = KeyChain() self.face.setCommandSigningInfo( keyChain, keyChain.getDefaultCertificateName()) def tearDown(self): self.face.shutdown() def test_registration_callbacks(self): onRegisterFailed = Mock() onRegisterSuccess = Mock() self.face.registerPrefix( Name("/test/register/callbacks"), None, onRegisterFailed, onRegisterSuccess) while True: self.face.processEvents() time.sleep(0.01) if (onRegisterSuccess.call_count > 0 or onRegisterFailed.call_count > 0): break self.assertEqual( onRegisterSuccess.call_count, 1, "Expected 1 onRegisterSuccess callback, got " + str(onRegisterSuccess.call_count))
def setUp(self): testCertDirectory = 'policy_config/certs' self.testCertFile = os.path.join(testCertDirectory, 'test.cert') # Reuse the policy_config subdirectory for the temporary SQLite file. self.databaseFilePath = "policy_config/test-public-info.db" try: os.remove(self.databaseFilePath) except OSError: # no such file pass self.identityStorage = BasicIdentityStorage(self.databaseFilePath) self.privateKeyStorage = MemoryPrivateKeyStorage() self.identityManager = IdentityManager(self.identityStorage, self.privateKeyStorage) self.policyManager = ConfigPolicyManager('policy_config/simple_rules.conf') self.identityName = Name('/TestConfigPolicyManager/temp') # to match the anchor cert keyName = Name(self.identityName).append('ksk-1416010123') self.privateKeyStorage.setKeyPairForKeyName( keyName, KeyType.RSA, TEST_RSA_PUBLIC_KEY_DER, TEST_RSA_PRIVATE_KEY_DER) self.identityStorage.addKey( keyName, KeyType.RSA, Blob(TEST_RSA_PUBLIC_KEY_DER)) cert = self.identityManager.selfSign(keyName) self.identityStorage.setDefaultKeyNameForIdentity(keyName) self.identityManager.addCertificateAsDefault(cert) self.keyChain = KeyChain(self.identityManager, self.policyManager) self.keyName = keyName self.face = Face()
def __init__(self, bld_root, keychain, cert_name, symkey, timestamp): Thread.__init__(self) self.bld_root = bld_root self.keychain = keychain self.cert_name = cert_name self.symkey = binascii.hexlify(symkey) self.timestamp = timestamp self.face = Face("localhost")
def test_interest_timestamp(self): interestName = Name('/ndn/ucla/edu/something') certName = self.keyChain.getPib().getIdentity(self.identityName).getKey( self.keyName).getDefaultCertificate().getName() face = Face("localhost") face.setCommandSigningInfo(self.keyChain, certName) oldInterest = Interest(interestName) face.makeCommandInterest(oldInterest) time.sleep(0.1) # make sure timestamps are different newInterest = Interest(interestName) face.makeCommandInterest(newInterest) vr = doVerify(self.policyManager, newInterest) self.assertFalse(vr.hasFurtherSteps, "ConfigPolicyManager returned ValidationRequest but certificate is known") self.assertEqual(vr.failureCount, 0, "Verification of valid interest failed") self.assertEqual(vr.successCount, 1, "Verification success called {} times instead of 1".format( vr.successCount)) vr = doVerify(self.policyManager, oldInterest) self.assertFalse(vr.hasFurtherSteps, "ConfigPolicyManager returned ValidationRequest but certificate is known") self.assertEqual(vr.successCount, 0, "Verification of stale interest succeeded") self.assertEqual(vr.failureCount, 1, "Failure callback called {} times instead of 1".format( vr.failureCount))
def main(): # Silence the warning from Interest wire encode. Interest.setDefaultCanBePrefix(True) # The default Face will connect using a Unix socket, or to "localhost". face = Face() counter = Counter() if sys.version_info[0] <= 2: word = raw_input("Enter a word to echo: ") else: word = input("Enter a word to echo: ") name = Name("/testecho") name.append(word) dump("Express name ", name.toUri()) face.expressInterest(name, counter.onData, counter.onTimeout) while counter._callbackCount < 1: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01) face.shutdown()
def main(): # The default Face will connect using a Unix socket, or to "localhost". face = Face() identityStorage = MemoryIdentityStorage() privateKeyStorage = MemoryPrivateKeyStorage() keyChain = KeyChain( IdentityManager(identityStorage, privateKeyStorage), None) keyChain.setFace(face) # Initialize the storage. keyName = Name("/testname/DSK-123") certificateName = keyName.getSubName(0, keyName.size() - 1).append( "KEY").append(keyName[-1]).append("ID-CERT").append("0") identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER)) privateKeyStorage.setKeyPairForKeyName( keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER) echo = Echo(keyChain, certificateName) prefix = Name("/testecho") dump("Register prefix", prefix.toUri()) face.registerPrefix(prefix, echo.onInterest, echo.onRegisterFailed) while echo._responseCount < 1: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01) face.shutdown()
def main(): face = Face("localhost") identityStorage = MemoryIdentityStorage() privateKeyStorage = MemoryPrivateKeyStorage() keyChain = KeyChain( IdentityManager(identityStorage, privateKeyStorage), None) keyChain.setFace(face) # Initialize the storage. keyName = Name("/testname/DSK-reposerver") certificateName = keyName.getSubName(0, keyName.size() - 1).append( "KEY").append(keyName[-1]).append("ID-CERT").append("0") identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_PUBLIC_KEY_DER)) privateKeyStorage.setKeyPairForKeyName( keyName, DEFAULT_PUBLIC_KEY_DER, DEFAULT_PRIVATE_KEY_DER) echo = RepoServer(keyChain, certificateName) prefix = Name("/ndn/ucla.edu/bms") dump("Register prefix", prefix.toUri()) face.registerPrefix(prefix, echo.onInterest, echo.onRegisterFailed) while True: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01) face.shutdown()
def main(): """ Call requestInsert and register a prefix so that ProduceSegments will answer interests from the repo to send the data packets. This assumes that repo-ng is already running (e.g. `sudo ndn-repo-ng`). """ repoCommandPrefix = Name("/example/repo/1") repoDataPrefix = Name("/example/data/1") nowMilliseconds = int(time.time() * 1000.0) fetchPrefix = Name(repoDataPrefix).append("testinsert").appendVersion(nowMilliseconds) # The default Face will connect using a Unix socket, or to "localhost". face = Face() # Use the system default key chain and certificate name to sign commands. keyChain = KeyChain() face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName()) # Register the prefix and send the repo insert command at the same time. startBlockId = 0 endBlockId = 1 enabled = [True] def onFinished(): dump("All data was inserted.") enabled[0] = False produceSegments = ProduceSegments( keyChain, keyChain.getDefaultCertificateName(), startBlockId, endBlockId, onFinished) dump("Register prefix", fetchPrefix.toUri()) def onRegisterFailed(prefix): dump("Register failed for prefix", prefix.toUri()) enabled[0] = False face.registerPrefix( fetchPrefix, produceSegments.onInterest, onRegisterFailed) def onInsertStarted(): dump("Insert started for", fetchPrefix.toUri()) def onFailed(): enabled[0] = False requestInsert( face, repoCommandPrefix, fetchPrefix, onInsertStarted, onFailed, startBlockId, endBlockId) # Run until all the data is sent. while enabled[0]: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01) face.shutdown()
def start(self): self.face = Face() self.face.setCommandSigningInfo(self.keychain, self.certificateName) self.face.registerPrefix(self.prefix, self.onLightingCommand, self.onRegisterFailed) while self.face is not None: self.face.processEvents() if self.registerFailed: self.stop() break
def __init__(self, prefix, pipeline, count): self.prefix = prefix self.pipeline = pipeline self.count = count self.nextSegment = 0 self.outstanding = dict() self.isDone = False self.face = Face("127.0.0.1")
def main(): """ Call startRepoWatch and register a prefix so that SendSegments will answer interests from the repo to send data packets for the watched prefix. When all the data is sent (or an error), call stopRepoWatch. This assumes that repo-ng is already running (e.g. `sudo ndn-repo-ng`). """ repoCommandPrefix = Name("/example/repo/1") repoDataPrefix = Name("/example/data/1") nowMilliseconds = int(time.time() * 1000.0) watchPrefix = Name(repoDataPrefix).append("testwatch").appendVersion( nowMilliseconds) # The default Face will connect using a Unix socket, or to "localhost". face = Face() # Use the system default key chain and certificate name to sign commands. keyChain = KeyChain() face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName()) # Register the prefix and start the repo watch at the same time. enabled = [True] def onFinishedSending(): stopRepoWatchAndQuit(face, repoCommandPrefix, watchPrefix, enabled) sendSegments = SendSegments( keyChain, keyChain.getDefaultCertificateName(), onFinishedSending) def onRegisterFailed(prefix): dump("Register failed for prefix", prefix.toUri()) enabled[0] = False dump("Register prefix", watchPrefix.toUri()) face.registerPrefix(watchPrefix, sendSegments.onInterest, onRegisterFailed) def onRepoWatchStarted(): dump("Watch started for", watchPrefix.toUri()) def onStartFailed(): dump("startRepoWatch failed.") stopRepoWatchAndQuit(face, repoCommandPrefix, watchPrefix, enabled) startRepoWatch( face, repoCommandPrefix, watchPrefix, onRepoWatchStarted, onStartFailed) # Run until someone sets enabled[0] = False. enabled[0] = True while enabled[0]: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01) face.shutdown()
class Consumer(object): '''Sends Interest, listens for data''' def __init__(self, name): self.name = Name(name) self.face = Face() self.isDone = False def run(self): try: interest = Interest(self.name) uri = self.name.toUri() interest.setInterestLifetimeMilliseconds(4000) interest.setMustBeFresh(True) self.face.expressInterest(interest, self._onData, self._onTimeout) while not self.isDone: self.face.processEvents() time.sleep(0.01) print "Sent Interest for %s" % uri except RuntimeError as e: print "ERROR: %s" % e def _onData(self, interest, data): payload = data.getContent() name = data.getName() print "Received data: %s\n" % payload.toRawStr() self.isDone = True def _onTimeout(self, interest): name = interest.getName() uri = name.toUri() print "TIMEOUT ", uri self.isDone = True
def main(): prefix = Name("/nfd/edu/ucla/remap/test") # Route to aleph.ndn.ucla.edu. Have to use the canonical name with an IP # address and port. uri = "udp4://128.97.98.7:6363" # The default Face connects to the local NFD. face = Face() # Use the system default key chain and certificate name to sign commands. keyChain = KeyChain() face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName()) # Create the /localhost/nfd/faces/query command interest, including the # FaceQueryFilter. Construct the FaceQueryFilter using the structure in # face_query_filter_pb2 which was produced by protoc. message = face_query_filter_pb2.FaceQueryFilterMessage() filter = message.face_query_filter.add() filter.uri = uri encodedFilter = ProtobufTlv.encode(message) interest = Interest(Name("/localhost/nfd/faces/query")) interest.getName().append(encodedFilter) enabled = [True] def onComplete(content): processFaceStatus(content, prefix, uri, face, enabled) def onError(errorCode, message): enabled[0] = False dump(message) SegmentFetcher.fetch( face, interest, SegmentFetcher.DontVerifySegment, onComplete, onError) # Loop calling processEvents until a callback sets enabled[0] = False. while enabled[0]: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01)
def main(): # The default Face will connect using a Unix socket, or to "localhost". face = Face() groupName = Name("/Prefix/READ") userName = Name("/U") userKeyName = Name("/U/Key") contentPrefix = Name("/Prefix/SAMPLE") contentName = Name(contentPrefix).append("Content") keyChain = createVerifyKeyChain() # Imitate test_consumer from the PyNDN integration tests. databaseFilePath = "test.db" try: os.remove(databaseFilePath) except OSError: pass namespace = Namespace(contentName) namespace.setFace(face) handler = NacConsumerHandler( namespace, keyChain, groupName, userName, Sqlite3ConsumerDb(databaseFilePath)) fixtureUserDKeyBlob = Blob(FIXTURE_USER_D_KEY) handler.addDecryptionKey(userKeyName, fixtureUserDKeyBlob) enabled = [True] def onContentSet(namespace, contentNamespace, callbackId): if contentNamespace == namespace: dump("Got segmented content", contentNamespace.content.toRawStr()) enabled[0] = False namespace.addOnContentSet(onContentSet) segmentStream = SegmentStream(namespace) SegmentedContent(segmentStream) segmentStream.start() while enabled[0]: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01)
def main(): face = Face("memoria.ndn.ucla.edu") page = Namespace("/ndn/edu/ucla/remap/demo/ndn-js-test/named-data.net/project/ndn-ar2011.html/%FDT%F7n%9E") page.setFace(face) enabled = [True] def onContentSet(namespace, contentNamespace, callbackId): if contentNamespace == namespace: dump("Got segmented content size", contentNamespace.content.size()) enabled[0] = False page.addOnContentSet(onContentSet) segmentStream = SegmentStream(page) SegmentedContent(segmentStream) segmentStream.start() # Loop calling processEvents until a callback sets enabled[0] = False. while enabled[0]: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01)
class KDSPublisher(Thread): def __init__(self, bld_root, keychain, cert_name, symkey, timestamp): Thread.__init__(self) self.bld_root = bld_root self.keychain = keychain self.cert_name = cert_name self.symkey = binascii.hexlify(symkey) self.timestamp = timestamp self.face = Face("localhost") def run(self): print 'KDS start' closure = Closure(self.bld_root, self.keychain, self.cert_name, self.symkey, self.timestamp) self.face.expressInterest(user_name, closure.onData, closure.onTimeout) while(closure.flag_terminate == 0): self.face.processEvents() time.sleep(0.01) print 'KDS stop'
def main(): if len(sys.argv) < 2: print("argv error: please input turnOn, turnOff or status") exit(1) else: cmd = sys.argv[1] loop = asyncio.get_event_loop() #face = ThreadsafeFace(loop, "localhost") face = Face("localhost") # Counter will stop the ioService after callbacks for all expressInterest. counter = Counter(loop, 3) seed = HMACKey(0,0,"seed","seedName") # Try to fetch anything. name1 = Name("/home/sensor/LED/0/"+cmd+"/0/0") commandTokenName = '/home/sensor/LED/0/'+cmd+'/token/0' commandTokenKey = hmac.new(seed.getKey(), commandTokenName, sha256).digest() accessTokenName = '/home/sensor/LED/0/'+cmd+'/token/0/user/Tom/token/0' accessTokenKey = hmac.new(commandTokenKey, accessTokenName, sha256).digest() accessToken = HMACKey(0,0,accessTokenKey,accessTokenName) dump("seed.getKey() :",seed.getKey()) dump("commandTokenName :",commandTokenName) dump("commandTokenKey :",base64.b64encode(commandTokenKey)) dump("accessTokenName :",accessTokenName) dump("accessTokenKey :",base64.b64encode(accessTokenKey)) interest = Interest(name1) interest.setInterestLifetimeMilliseconds(3000) a = AccessControlManager() a.signInterestWithHMACKey(interest,accessToken) dump("Express name ", interest.toUri()) face.expressInterest(interest, counter.onData, counter.onTimeout) """ name2 = Name("/home/sensor/LED/T0829374723/turnOff") dump("Express name ", name2.toUri()) face.expressInterest(name2, counter.onData, counter.onTimeout) """ while counter._callbackCount < 1: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(2) face.shutdown()
def main(): # The default Face will connect using a Unix socket, or to "localhost". face = Face() # Use the system default key chain and certificate name to sign commands. keyChain = KeyChain() face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName()) # Also use the default certificate name to sign data packets. echo = Echo(keyChain, keyChain.getDefaultCertificateName()) prefix = Name("/testecho") dump("Register prefix", prefix.toUri()) face.registerPrefix(prefix, echo.onInterest, echo.onRegisterFailed) while echo._responseCount < 1: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01) face.shutdown()
def main(): # Silence the warning from Interest wire encode. Interest.setDefaultCanBePrefix(True) if sys.version_info[0] <= 2: userPrefixUri = raw_input("Enter your user prefix (e.g. /a): ") else: userPrefixUri = input("Enter your user prefix (e.g. /a): ") if userPrefixUri == "": dump("You must enter a user prefix") return syncPrefixUri = "/sync" nUserPrefixes = 2 maxPublishedSequenceNo = 3 # The default Face will connect using a Unix socket, or to "localhost". face = Face() # Set up the KeyChain. keyChain = KeyChain("pib-memory:", "tpm-memory:") keyChain.importSafeBag(SafeBag (Name("/testname/KEY/123"), Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False), Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False))) face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName()) producer = Producer( face, keyChain, Name(syncPrefixUri), userPrefixUri, nUserPrefixes, maxPublishedSequenceNo) # The main event loop. while True: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01)
def run(self): face = Face() # Use the system default key chain and certificate name to sign commands. face.setCommandSigningInfo(self.keyChain, self.keyChain.getDefaultCertificateName()) # Also use the default certificate name to sign data packets. face.registerPrefix(self.prefix, self.onInterest, self.onRegisterFailed) print "Registering prefix %s" % self.prefix.toUri() while not self.isDone: face.processEvents() time.sleep(0.01)
def main(): face = Face() # Use the system default key chain and certificate name to sign commands. keyChain = KeyChain() certificateName = keyChain.getDefaultCertificateName() face.setCommandSigningInfo(keyChain, certificateName) test = DiscoveryTest(face, keyChain, certificateName) test.start() while True: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01) face.shutdown()
def test_max_ndn_packet_size(self): # Construct an interest whose encoding is one byte larger than getMaxNdnPacketSize. targetSize = Face.getMaxNdnPacketSize() + 1 # Start with an interest which is almost the right size. interest = Interest() interest.getName().append(bytearray(targetSize)) initialSize = interest.wireEncode().size() # Now replace the component with the desired size which trims off the extra encoding. interest.setName( (Name().append(bytearray(targetSize - (initialSize - targetSize))))) interestSize = interest.wireEncode().size() self.assertEqual(targetSize, interestSize, "Wrong interest size for MaxNdnPacketSize") with self.assertRaises(RuntimeError): # If no error is raised, then expressInterest didn't throw an # exception when the interest size exceeds getMaxNdnPacketSize() self.face.expressInterest(interest, Mock(), Mock())