def get_mpd_ndn(url): """ Module to download the MPD from the URL and save it to file""" print 'Entered get mpd ndn' face = Face("server.simpleNDN.ch-geni-net.geni.case.edu") counter = Counter() s = time.clock() try: name = Name(url) face.expressInterest(name, counter.onData, counter.onTimeout) while counter._callbackCount < 1: face.processEvents() # Try to fetch using a known name. name = Name(url + Version) dump("Express name ", name.toUri()) interest = Interest(name) interest.setInterestLifetimeMilliseconds(1000) SegmentFetcher.fetch(face, interest, None, counter.onComplete, counter.onError) except: config_dash.LOG.error("Unable to download MPD file NDN error") return None while counter._callbackCount < 2: face.processEvents() print("time taken to copy all segments:" + str(time.clock() - s)) mpd_data = Content mpd_file = url.split('/')[-1] mpd_file_handle = open(mpd_file, 'w') print mpd_file_handle mpd_file_handle.write(mpd_data) mpd_file_handle.close() config_dash.LOG.info("Downloaded the MPD file {}".format(mpd_file)) return mpd_file
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(): # silence the warning from interest wire encode Interest.setDefaultCanBePrefix(True) # set up a face that connects to the remote forwarder udp_connection_info = UdpTransport.ConnectionInfo("10.10.1.1", 6363) udp_transport = UdpTransport() face = Face(udp_transport, udp_connection_info) counter = Counter() # try to fetch from provided name name_text = input("Enter a name to request content from: ") name = Name(name_text) dump("Express name", name.toUri()) interest = Interest(name) interest.setMustBeFresh(False) face.expressInterest(interest, counter.onData, counter.onTimeout, counter.onNetworkNack) while counter._callbackCount < 1: face.processEvents() # 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()
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
def main(): face = Face() current_nbr = 1 max_nbr = 10 PGI = 5 f = open('measurements/app_measurments.txt','a') f.seek(0) f.truncate() cow = 0 v = 0 counter = Counter(f, face) while current_nbr <= max_nbr: name = Name("farm1/cows") name.append("1") name.append("mvmnt") name.appendSegment(v) interest = Interest(name) counter._callbackCount = 0 f.write('\n'+str(datetime.now().strftime('%X.%f'))) face.expressInterest(interest, counter.onData, counter.onTimeout) while counter._callbackCount < 1 : face.processEvents() time.sleep(0.01) time.sleep(PGI) current_nbr+=1 v+=1 face.shutdown() f.close()
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 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 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()
def main(): # 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 video name: ") #else: # word = input("Enter a video name: ") name = Name("/kebapp/video/video") #name.append(word) dump("Express name ", name.toUri()) interest = Interest(name) #interest.setInterestLifeTimeMilliseconds(30000) interest.setInterestLifetimeMilliseconds(30000) face.expressInterest(interest, counter.onData, counter.onTimeout) #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()
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
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
class FaceModMsg(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,facemod_suffix): try: self._sendFaceModInterest(facemod_suffix) 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 _sendFaceModInterest(self,facemod_suffix): interest = self.ofmsg.create_facemod_msg_interest(facemod_suffix) uri = interest.getName().toUri() self.face.expressInterest(interest, self._onData, self._onTimeout) print("--------Sent <<<FaceMod>>> Msg for \n %s" % uri) def _onData(self, interest, data): pass def _onTimeout(self, interest): pass
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
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
class Consumer(object): '''Register chat prefix to gateway router to advertise''' 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") def run(self): try: self._sendNextInterest(self.host) 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.prefixesToSend) 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 Chat Prefixes to host " + str(self.host) def _onData(self, interest, data): payload = data.getContent() name = data.getName() print str(self.host) + " recieved prefixes" del self.outstanding[name.toUri()] os.system("nfdc cs erase " + str(name)) 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
class HelloReq(object): '''Hello ''' 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, hello_version_number): try: self._sendHelloInterest(hello_version_number) while not self.isDone: self.face.processEvents() time.sleep(0.01) except RuntimeError as e: print("ERROR: %s" % e) return self.isDone def _sendHelloInterest(self, hello_version_number=100001): interest = self.ofmsg.create_hello_req_interest( self.nodeid, hello_version_number) uri = interest.getName().toUri() if uri not in self.outstanding: self.outstanding[uri] = 1 self.face.expressInterest(interest, self._onData, self._onTimeout) print("--------Sent <<<Helloreq>>> Interest -------- \n {0} \n".format( uri)) def _onData(self, interest, data): payload = data.getContent() name = data.getName() print("--------Received <<<HelloRes>>> Data -------- \n {0} \n".format( 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._sendHelloInterest() else: self.isDone = True
class Consumer(object): def __init__(self, prefix): self.prefix = Name(prefix) self.outstanding = dict() self.isDone = False self.face = Face() #event loop, running forever in this application def run(self): try: self._sendNextInterest( self.prefix.append(pyndn.Name.Component.fromSequenceNumber(1))) # 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 * 100) 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: ", 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(): 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(): face = Face() keychain = KeyChain() face.setCommandSigningInfo(keychain, keychain.getDefaultCertificateName()) running = True # The following line doesn't work sometimes # interest = Interest("/icear-server/calc") interest = Interest(Name("/icear-server/calc")) param_msg = SegmentParameterMessage() param_msg.segment_parameter.name.component.append( bytes("example-data", "utf-8")) param_msg.segment_parameter.start_frame = 2 param_msg.segment_parameter.end_frame = 3 op = param_msg.segment_parameter.operations.components.add() op.model = bytes("deeplab", "utf-8") op.flags = 0 op = param_msg.segment_parameter.operations.components.add() op.model = bytes("la_muse", "utf-8") op.flags = 0 interest.name.append(ProtobufTlv.encode(param_msg)) interest.mustBeFresh = True interest.interestLifetimeMilliseconds = 4000.0 interest.setCanBePrefix(True) def on_data(_, data): # type: (Interest, Data) -> None nonlocal running print(data.name.toUri()) print(data.content.toBytes()) running = False def on_timeout(_): nonlocal running print("Timeout") running = False def on_nack(_, nack): # type: (Interest, NetworkNack) -> None nonlocal running print("NACK") print(nack.getReason()) running = False face.expressInterest(interest, on_data, on_timeout, on_nack) while running: face.processEvents() time.sleep(0.01) face.shutdown()
class ErrorMsg(object): '''Error report message is an interest for report error to controller''' 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="h1--0x0004--0x0000--faceid255-down"): try: self._sendErrorMsgInterest(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 _sendErrorMsgInterest(self, error_prefix): interest = self.ofmsg.create_error_msg_interest(error_prefix) uri = interest.getName().toUri() if uri not in self.outstanding: self.outstanding[uri] = 1 self.face.expressInterest(interest, self._onData, self._onTimeout) print("--------Sent <<<Error Msg>>> Interest for \n %s" % uri) def _onData(self, interest, data): payload = data.getContent() name = data.getName() print("Received <<<<Error Msg ACK>>>>from Controller ") 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.run() else: self.isDone = True
def getKey(): face = Face("129.241.208.115", 6363) # Use the system default key chain and certificate name to sign commands. keyChain = KeyChain() face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName()) # util.dump(keyChain.getDefaultCertificateName()) # Also use the default certificate name to sign data packets. face.expressInterest("/ndn/no/ntnu/KEY", onData, onTimeout) 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(): face = Face("localhost") counter = Counter() ignored, name = argv name = "/ndn/ucla.edu/bms/" + name name1 = Name(name) dump("Express name ", name1.toUri()) face.expressInterest(name1, 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(): seg = 0 if len(sys.argv) < 3: print("argv error: please input capture or capture with #seg") exit(1) elif len(sys.argv) == 2: cmd = sys.argv[1] else: cmd = sys.argv[1] seg = sys.argv[2] 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. import time r = time.time() name1 = Name("/home/security/camera/0/"+cmd) name1.appendTimestamp(int(r)) name1.appendSegment(int(seg)) interest = Interest(name1) interest.setInterestLifetimeMilliseconds(3000) 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(): #Interest.setDefaultCanBePrefix(True) with open("shared/system-info.json") as f: user_data = json.load(f) face = Face() counter = Counter() name = Name("/test") """ req_name = "/example/test" sym_key = base64.b64decode(user_data['austin']['sym_key']) iv,ct,tag = sym_encrypt(sym_key,req_name) enc_req_name = base64.b64encode(iv).decode('ascii') name.append(enc_req_name) enc_req_name = base64.b64encode(ct).decode('ascii') name.append(enc_req_name) enc_req_name = base64.b64encode(tag).decode('ascii') name.append(enc_req_name) priv_key = user_data['austin']['priv_key'] priv_key = base64.b64decode(priv_key) priv_key = load_priv_key(priv_key) #sig = base64.b64encode(priv_key.sign(bytes(enc_req_name,'utf-8'))) sig =\ base64.b64encode(priv_key.sign(bytes("austin",'utf-8'))).decode('ascii') name.append(sig) sig = base64.b64decode(sig) """ print(name) face.expressInterest(name,counter.onData,counter.onTimeout) while counter.rec == 1: face.processEvents() time.sleep(0.1)
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 download_segment_ndn(segment_url, dash_folder): """ Module to download the segment """ print 'Entered download segment ndn' face = Face("server.simpleNDN.ch-geni-net.geni.case.edu") counter = Counter() try: name = Name(segment_url) dump("Express name ", name.toUri()) face.expressInterest(name, counter.onData, counter.onTimeout) while counter._callbackCount < 1: face.processEvents() # Try to fetch using a known name. name = Name(segment_url + Version) dump("Express name ", name.toUri()) interest = Interest(name) interest.setInterestLifetimeMilliseconds(1000) SegmentFetcher.fetch(face, interest, None, counter.onComplete, counter.onError) except: config_dash.LOG.error("Unable to download MPD file NDN error") return None while counter._callbackCount < 2: face.processEvents() parsed_uri = urlparse.urlparse(segment_url) segment_path = '{uri.path}'.format(uri=parsed_uri) while segment_path.startswith('/'): segment_path = segment_path[1:] segment_filename = os.path.join(dash_folder, os.path.basename(segment_path)) make_sure_path_exists(os.path.dirname(segment_filename)) segment_file_handle = open(segment_filename, 'wb') segment_size = 0 while True: segment_data = Content segment_size += len(segment_data) segment_file_handle.write(segment_data) if len(segment_data) < DOWNLOAD_CHUNK: break segment_file_handle.close() return segment_size, segment_filename
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(): # Connect to the demo host at memoria.ndn.ucla.edu . face = Face("128.97.98.8") counter = Counter() # Try to fetch anything. name1 = Name("/") dump("Express name ", name1.toUri()) face.expressInterest(name1, counter.onData, counter.onTimeout) # Try to fetch using a known name. name2 = Name("/ndn/edu/ucla/remap/demo/ndn-js-test/hello.txt/%FDX%DC5%1F") dump("Express name ", name2.toUri()) face.expressInterest(name2, counter.onData, counter.onTimeout) # Expect this to time out. name3 = Name("/test/timeout") dump("Express name ", name3.toUri()) face.expressInterest(name3, counter.onData, counter.onTimeout) while counter._callbackCount < 3: 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) face = Face("memoria.ndn.ucla.edu") counter = Counter() # Try to fetch anything. name1 = Name("/") dump("Express name ", name1.toUri()) face.expressInterest(name1, counter.onData, counter.onTimeout) # Try to fetch using a known name. name2 = Name("/ndn/edu/ucla/remap/demo/ndn-js-test/hello.txt/%FDU%8D%9DM") dump("Express name ", name2.toUri()) face.expressInterest(name2, counter.onData, counter.onTimeout) # Expect this to time out. name3 = Name("/test/timeout") dump("Express name ", name3.toUri()) face.expressInterest(name3, counter.onData, counter.onTimeout) while counter._callbackCount < 3: 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("aleph.ndn.ucla.edu") counter = Counter() # Try to fetch anything. name1 = Name("/") dump("Express name ", name1.toUri()) face.expressInterest(name1, counter.onData, counter.onTimeout) # Try to fetch using a known name. name2 = Name("/ndn/edu/ucla/remap/demo/ndn-js-test/hello.txt/%FDU%8D%9DM") dump("Express name ", name2.toUri()) face.expressInterest(name2, counter.onData, counter.onTimeout) # Expect this to time out. name3 = Name("/test/timeout") dump("Express name ", name3.toUri()) face.expressInterest(name3, counter.onData, counter.onTimeout) while counter._callbackCount < 3: 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
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 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() face.expressInterest(interest, on_data, on_timeout, on_network_nack) await done.wait() return result
def deviceListRequest(): 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) while True: username = raw_input('Login username: '******'t be blank") continue else: break while True: password = raw_input("Login password: "******"Username can't be blank") continue else: break userHMACKey = HMACKey(0,0,password,"userHMACKey") interestName = Name("/home/controller/deviceList/user/"+username) interest = Interest(interestName) a = AccessControlManager() a.signInterestWithHMACKey(interest,userHMACKey) dump("Express interst :",interest.toUri()) face.expressInterest(interest,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 run_reqs(self, request): # silence the warning from interest wire encode Interest.setDefaultCanBePrefix(True) # set up a face that connects to the remote forwarder #udp_connection_info = UdpTransport.ConnectionInfo("10.10.1.1", 6363) #udp_connection_info = UdpTransport.ConnectionInfo("10.10.2.1", 6363) #udp_connection_info = UdpTransport.ConnectionInfo("10.10.3.1", 6363) #udp_connection_info = UdpTransport.ConnectionInfo("10.10.4.1", 6363) #udp_connection_info = UdpTransport.ConnectionInfo("10.10.5.1", 6363) udp_transport = UdpTransport() face = Face(udp_transport, udp_connection_info) counter = Counter() # try to fetch from provided name name = Name(request) dump("Express name", name.toUri()) interest = Interest(name) interest.setMustBeFresh(False) date = datetime.now() face.expressInterest(interest, counter.onData, counter.onTimeout, counter.onNetworkNack) dump(f">>{date}>>") with open('data_collection/out.dat', 'a') as outfile: outfile.write(f"{date}\n") while counter._callbackCount < 1: face.processEvents() # don't use 100% of the CPU time.sleep(0.01) face.shutdown()
def main(): if len(sys.argv) < 2: print("usage: python3 client-app.py {good/bad}") quit() #Interest.setDefaultCanBePrefix(True) with open("shared/system-info.json") as f: user_data = json.load(f) face = Face() counter = Counter() name = Name("/ndn-ss/austin") req_name = "/example/test" sym_key = base64.b64decode(user_data['austin']['sym_key']) iv, ct, tag = sym_encrypt(sym_key, req_name) enc_req_name = base64.b64encode(iv).decode('ascii') name.append(enc_req_name) enc_req_name = base64.b64encode(ct).decode('ascii') name.append(enc_req_name) enc_req_name = base64.b64encode(tag).decode('ascii') name.append(enc_req_name) priv_key = user_data['austin']['priv_key'] priv_key = base64.b64decode(priv_key) priv_key = load_priv_key(priv_key) sig =\ base64.b64encode(priv_key.sign(bytes("austin",'utf-8'))).decode('ascii') bad_sig =\ base64.b64encode(priv_key.sign(bytes("abstin",'utf-8'))).decode('ascii') i = Interest() i.setMustBeFresh(True) i.setInterestLifetimeMilliseconds(0) #face.expressInterest(name,counter.onData,counter.onTimeout) if sys.argv[1] == "good": name.append(sig) face.expressInterest(name, i, counter.onData, counter.onTimeout) elif sys.argv[1] == "bad": name.append(bad_sig) face.expressInterest(name, i, counter.onData, counter.onTimeout) else: print("c") while counter.rec == 1: face.processEvents() time.sleep(0.1) face.expressInterest(name, i, counter.onData, counter.onTimeout)
class TestFaceInterestMethods(ut.TestCase): def setUp(self): self.face = Face("aleph.ndn.ucla.edu") def tearDown(self): self.face.shutdown() def run_express_name_test(self, interestName, timeout=12): # returns the dataCallback and timeoutCallback mock objects so we can test timeout behavior # as well as a bool for if we timed out without timeoutCallback being called name = Name(interestName) dataCallback = Mock() timeoutCallback = Mock() self.face.expressInterest(name, dataCallback, timeoutCallback) def waitForCallbacks(): while 1: self.face.processEvents() gevent.sleep() if (dataCallback.call_count > 0 or timeoutCallback.call_count > 0): break task = gevent.spawn(waitForCallbacks) task.join(timeout=10) return dataCallback, timeoutCallback def test_any_interest(self): uri = "/" (dataCallback, timeoutCallback) = self.run_express_name_test(uri) self.assertTrue(timeoutCallback.call_count == 0, 'Timeout on expressed interest') # check that the callback was correct self.assertEqual( dataCallback.call_count, 1, 'Expected 1 onData callback, got ' + str(dataCallback.call_count)) onDataArgs = dataCallback.call_args[ 0] # the args are returned as ([ordered arguments], [keyword arguments]) #just check that the interest was returned correctly? callbackInterest = onDataArgs[0] self.assertTrue(callbackInterest.getName().equals(Name(uri)), 'Interest returned on callback had different name') def test_specific_interest(self): uri = "/ndn/edu/ucla/remap/ndn-js-test/howdy.txt/%FD%052%A1%DF%5E%A4" (dataCallback, timeoutCallback) = self.run_express_name_test(uri) self.assertTrue(timeoutCallback.call_count == 0, 'Unexpected timeout on expressed interest') # check that the callback was correct self.assertEqual( dataCallback.call_count, 1, 'Expected 1 onData callback, got ' + str(dataCallback.call_count)) onDataArgs = dataCallback.call_args[ 0] # the args are returned as ([ordered arguments], [keyword arguments]) #just check that the interest was returned correctly? callbackInterest = onDataArgs[0] self.assertTrue(callbackInterest.getName().equals(Name(uri)), 'Interest returned on callback had different name') def test_timeout(self): uri = "/test/timeout" (dataCallback, timeoutCallback) = self.run_express_name_test(uri) # we're expecting a timeout callback, and only 1 self.assertTrue(dataCallback.call_count == 0, 'Data callback called for invalid interest') self.assertTrue( timeoutCallback.call_count == 1, 'Expected 1 timeout call, got ' + str(timeoutCallback.call_count)) #check that the interest was returned correctly onTimeoutArgs = timeoutCallback.call_args[ 0] # the args are returned as ([ordered arguments], [keyword arguments]) #just check that the interest was returned correctly? callbackInterest = onTimeoutArgs[0] self.assertTrue(callbackInterest.getName().equals(Name(uri)), 'Interest returned on callback had different name') def test_remove_pending(self): name = Name("/ndn/edu/ucla/remap/") dataCallback = Mock() timeoutCallback = Mock() interestID = self.face.expressInterest(name, dataCallback, timeoutCallback) def removeInterestAndWait(): self.face.removePendingInterest(interestID) while 1: self.face.processEvents() gevent.sleep() currentTime = time.clock() if (dataCallback.call_count > 0 or timeoutCallback.call_count > 0): break task = gevent.spawn(removeInterestAndWait) task.join(timeout=10) self.assertEqual( dataCallback.call_count, 0, 'Should not have called data callback after interest was removed') self.assertEqual( timeoutCallback.call_count, 0, 'Should not have called timeout callback after interest was removed' )
class TestFaceRegisterMethods(ut.TestCase): def setUp(self): self.face_in = Face() self.face_out = Face() self.keyChain = KeyChain() def tearDown(self): self.face_in.shutdown() self.face_out.shutdown() def onInterestEffect(self, prefix, interest, transport, prefixID): data = Data(interest.getName()) data.setContent("SUCCESS") self.keyChain.sign(data, self.keyChain.getDefaultCertificateName()) encodedData = data.wireEncode() transport.send(encodedData.toBuffer()) def test_register_prefix_response(self): # gotta sign it (WAT) prefixName = Name("/unittest") self.face_in.setCommandSigningInfo( self.keyChain, self.keyChain.getDefaultCertificateName()) failedCallback = Mock() interestCallback = Mock(side_effect=self.onInterestEffect) self.face_in.registerPrefix(prefixName, interestCallback, failedCallback) server = gevent.spawn(self.face_process_events, self.face_in, [interestCallback, failedCallback], 'h') gevent.sleep(1) # give the 'server' time to register the interest # express an interest on another face dataCallback = Mock() timeoutCallback = Mock() # now express an interest on this new face, and see if onInterest is called interestName = prefixName.append("hello") self.face_out.expressInterest(interestName, dataCallback, timeoutCallback) client = gevent.spawn(self.face_process_events, self.face_out, [dataCallback, timeoutCallback], 'c') gevent.joinall([server, client], timeout=10) self.assertEqual(failedCallback.call_count, 0, 'Failed to register prefix at all') self.assertEqual( interestCallback.call_count, 1, 'Expected 1 onInterest callback, got ' + str(interestCallback.call_count)) self.assertEqual( dataCallback.call_count, 1, 'Expected 1 onData callback, got ' + str(dataCallback.call_count)) onDataArgs = dataCallback.call_args[0] # check the message content data = onDataArgs[1] expectedBlob = Blob(bytearray("SUCCESS")) self.assertTrue( expectedBlob.equals(data.getContent()), 'Data received on face does not match expected format') def face_process_events(self, face, callbacks, name=None): # implemented as a 'greenlet': something like a thread, but semi-synchronous # callbacks should be a list done = False while not done: face.processEvents() gevent.sleep() for c in callbacks: if (c.call_count > 0): done = True
class trigger(object): def __init__(self): 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.Datamessage_size = 8000 #8kB --> Max Size from NDN standard self.prefix_DE = "/picasso/start_de/" # Default configuration of NDN self.outstanding = dict() self.isDone = False self.keyChain = KeyChain() self.face = Face("127.0.0.1") self.face.setCommandSigningInfo(self.keyChain, \ self.keyChain.getDefaultCertificateName()) #self.face.registerPrefix(self.prefix_deployment_pull, self.onInterest_PullService, self.onRegisterFailed) #print "Registering prefix : " + self.prefix_deployment_pull.toUri() def run(self): try: # send Interest message to retrieve data #self.sendNextInterest(self.prefix_serviceMigration) print 'Available services' print ' (1) cloudsuite_webserver_PI.tar --- 495 MB' print ' (2) cloudsuite_db_server_PI.tar --- 430 MB' print ' (3) cloudsuite_memcached_PI.tar --- 366 MB' print ' (4) armbuild_debian.tar --- 145 MB' print ' (5) alpine_armhf_nginx.tar --- 14.95 MB' print ' (6) armhf_alpine.tar --- 3.85 MB' print ' (7) rpi_busybox_httpd.tar --- 2.2 MB' print ' (8) rpi_nano_httpd.tar --- 110 kB' input_service = raw_input( 'Choose service to be deployed (type number, e.g., 1): ') input_node = raw_input( 'Select node to migrate service (e.g., SEG_1): ') if input_service == '1': print 'Start deploy cloudsuite web server' service_name = 'cloudsuite_webserver_PI.tar' elif input_service == '2': print 'Start deploy cloudsuite db server' service_name = 'cloudsuite_db_server_PI.tar' elif input_service == '3': print 'Start deploy Start deploy cloudsuite memcached server' service_name = 'cloudsuite_memcached_PI.tar' elif input_service == '4': print 'Start deploy debian' service_name = 'armbuild_debian.tar' elif input_service == '5': print 'Start deploy nginx' service_name = 'alpine_armhf_nginx.tar' elif input_service == '6': print 'Start deploy alpine linux' service_name = 'armhf_alpine.tar' elif input_service == '7': print 'Start deploy busybox-httpd' service_name = 'rpi_busybox_httpd.tar' elif input_service == '8': print 'Start deploy nano-httpd' service_name = 'rpi_nano_httpd.tar' else: print 'Chosen service is not available' name_prefix = self.prefix_DE + service_name + '/' + input_node print 'name prefix: %s' % name_prefix self.sendInterest_to_DE(Name(name_prefix)) except RuntimeError as e: print "ERROR: %s" % e def sendInterest_to_DE(self, name): interest = Interest(name) interestName = interest.getName() interest.setInterestLifetimeMilliseconds(4000) interest.setMustBeFresh(True) #if uri not in self.outstanding: #self.outstanding[uri] = 1 # self.face.expressInterest(interest, self.onData, self._onTimeout) self.face.expressInterest( interest, None, None ) ## set None --> sent out only, don't wait for Data and Timeout print "Sent Push-Interest for %s" % interestName
fullName = Name(data_prefix).append(Name(data_part)) # currently we need to provide the version ourselves when we # poke the repo ts = int(time.time()*1000) fullName.appendVersion(int(ts)) command = createInsertInterest(fullName) versionStr = fullName.get(-1).toEscapedString() logger.debug('inserting: ' + versionStr) repo_face.makeCommandInterest(command) lastFailCount = failure.call_count lastSuccessCount = success.call_count repo_face.expressInterest(command, success, failure) insertTable.append({'version':versionStr, 'insert_request':time.time()}) while success.call_count == lastSuccessCount and failure.call_count == lastFailCount: repo_face.processEvents() time.sleep(0.1) # only expecting to insert one segment (<1k) for each request # check on the insert status # TODO: kick off a greenlet instead of setting global variable? if success.call_count > lastSuccessCount and current_insertion >= 0: lastFailCount = failure.call_count lastSuccessCount = success.call_count info = getInfoForVersion(versionStr) logger.debug("Checking on: " + str(current_insertion)) if current_status == 100:
rp.setStartBlockId(0) interest = Interest(Name("/example/repo/1").append("insert").append(rp.wireEncode())) 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(interest) callbacks = Callbacks() print interest.getName().toUri() face.expressInterest(interest, callbacks.onData, callbacks.onTimeout) face.registerPrefix(dataPrefix, callbacks.onInterest, callbacks.onRegisterFailed) while True: face.processEvents() time.sleep(0.1)
class TestFaceInterestMethods(ut.TestCase): def setUp(self): self.face = Face("aleph.ndn.ucla.edu") def tearDown(self): self.face.shutdown() def run_express_name_test(self, interestName, timeout=12): # returns the dataCallback and timeoutCallback mock objects so we can test timeout behavior # as well as a bool for if we timed out without timeoutCallback being called name = Name(interestName) dataCallback = Mock() timeoutCallback = Mock() self.face.expressInterest(name, dataCallback, timeoutCallback) def waitForCallbacks(): while 1: self.face.processEvents() gevent.sleep() if (dataCallback.call_count > 0 or timeoutCallback.call_count > 0): break task = gevent.spawn(waitForCallbacks) task.join(timeout=10) return dataCallback, timeoutCallback def test_any_interest(self): uri = "/" (dataCallback, timeoutCallback) = self.run_express_name_test(uri) self.assertTrue(timeoutCallback.call_count == 0 , 'Timeout on expressed interest') # check that the callback was correct self.assertEqual(dataCallback.call_count, 1, 'Expected 1 onData callback, got '+str(dataCallback.call_count)) onDataArgs = dataCallback.call_args[0] # the args are returned as ([ordered arguments], [keyword arguments]) #just check that the interest was returned correctly? callbackInterest = onDataArgs[0] self.assertTrue(callbackInterest.getName().equals(Name(uri)), 'Interest returned on callback had different name') # TODO: Replace this with a test that connects to a Face on localhost #def test_specific_interest(self): # uri = "/ndn/edu/ucla/remap/ndn-js-test/howdy.txt/%FD%052%A1%DF%5E%A4" # (dataCallback, timeoutCallback) = self.run_express_name_test(uri) # self.assertTrue(timeoutCallback.call_count == 0, 'Unexpected timeout on expressed interest') # # # check that the callback was correct # self.assertEqual(dataCallback.call_count, 1, 'Expected 1 onData callback, got '+str(dataCallback.call_count)) # onDataArgs = dataCallback.call_args[0] # the args are returned as ([ordered arguments], [keyword arguments]) # #just check that the interest was returned correctly? # callbackInterest = onDataArgs[0] # self.assertTrue(callbackInterest.getName().equals(Name(uri)), 'Interest returned on callback had different name') def test_timeout(self): uri = "/test/timeout" (dataCallback, timeoutCallback) = self.run_express_name_test(uri) # we're expecting a timeout callback, and only 1 self.assertTrue(dataCallback.call_count == 0, 'Data callback called for invalid interest') self.assertTrue(timeoutCallback.call_count == 1, 'Expected 1 timeout call, got ' + str(timeoutCallback.call_count)) #check that the interest was returned correctly onTimeoutArgs = timeoutCallback.call_args[0] # the args are returned as ([ordered arguments], [keyword arguments]) #just check that the interest was returned correctly? callbackInterest = onTimeoutArgs[0] self.assertTrue(callbackInterest.getName().equals(Name(uri)), 'Interest returned on callback had different name') def test_remove_pending(self): name = Name("/ndn/edu/ucla/remap/") dataCallback = Mock() timeoutCallback = Mock() interestID = self.face.expressInterest(name, dataCallback, timeoutCallback) def removeInterestAndWait(): self.face.removePendingInterest(interestID) while 1: self.face.processEvents() gevent.sleep() currentTime = time.clock() if (dataCallback.call_count > 0 or timeoutCallback.call_count > 0): break task = gevent.spawn(removeInterestAndWait) task.join(timeout=10) self.assertEqual(dataCallback.call_count, 0, 'Should not have called data callback after interest was removed') self.assertEqual(timeoutCallback.call_count, 0, 'Should not have called timeout callback after interest was removed')
class TestFaceRegisterMethods(ut.TestCase): def setUp(self): self.face_in = Face() self.face_out = Face() self.keyChain = KeyChain() def tearDown(self): self.face_in.shutdown() self.face_out.shutdown() def test_register_prefix_response(self): prefixName = Name("/test") self.face_in.setCommandSigningInfo(self.keyChain, self.keyChain.getDefaultCertificateName()) interestCallbackCount = [0] def onInterest(prefix, interest, transport, prefixID): interestCallbackCount[0] += 1 data = Data(interest.getName()) data.setContent("SUCCESS") self.keyChain.sign(data, self.keyChain.getDefaultCertificateName()) encodedData = data.wireEncode() transport.send(encodedData.toBuffer()) failedCallback = Mock() self.face_in.registerPrefix(prefixName, onInterest, failedCallback) # Give the 'server' time to register the interest. time.sleep(1) # express an interest on another face dataCallback = Mock() timeoutCallback = Mock() # now express an interest on this new face, and see if onInterest is called # Add the timestamp so it is unique and we don't get a cached response. interestName = prefixName.append("hello" + repr(time.time())) self.face_out.expressInterest(interestName, dataCallback, timeoutCallback) # Process events for the in and out faces. timeout = 10000 startTime = getNowMilliseconds() while True: if getNowMilliseconds() - startTime >= timeout: break self.face_in.processEvents() self.face_out.processEvents() done = True if interestCallbackCount[0] == 0 and failedCallback.call_count == 0: # Still processing face_in. done = False if dataCallback.call_count == 0 and timeoutCallback.call_count == 0: # Still processing face_out. done = False if done: break time.sleep(0.01) self.assertEqual(failedCallback.call_count, 0, 'Failed to register prefix at all') self.assertEqual(interestCallbackCount[0], 1, 'Expected 1 onInterest callback, got '+str(interestCallbackCount[0])) self.assertEqual(dataCallback.call_count, 1, 'Expected 1 onData callback, got '+str(dataCallback.call_count)) onDataArgs = dataCallback.call_args[0] # check the message content data = onDataArgs[1] expectedBlob = Blob("SUCCESS") self.assertTrue(expectedBlob == data.getContent(), 'Data received on face does not match expected format')
class TestFaceInterestMethods(ut.TestCase): def setUp(self): self.face = Face("localhost") def tearDown(self): self.face.shutdown() def run_express_name_test(self, interestName, timeout=12): # returns the dataCallback and timeoutCallback mock objects so we can test timeout behavior # as well as a bool for if we timed out without timeoutCallback being called name = Name(interestName) dataCallback = Mock() timeoutCallback = Mock() self.face.expressInterest(name, dataCallback, timeoutCallback) while True: self.face.processEvents() time.sleep(0.01) if (dataCallback.call_count > 0 or timeoutCallback.call_count > 0): break return dataCallback, timeoutCallback def test_any_interest(self): uri = "/" (dataCallback, timeoutCallback) = self.run_express_name_test(uri) self.assertTrue(timeoutCallback.call_count == 0 , 'Timeout on expressed interest') # check that the callback was correct self.assertEqual(dataCallback.call_count, 1, 'Expected 1 onData callback, got '+str(dataCallback.call_count)) onDataArgs = dataCallback.call_args[0] # the args are returned as ([ordered arguments], [keyword arguments]) #just check that the interest was returned correctly? callbackInterest = onDataArgs[0] self.assertTrue(callbackInterest.getName() == (Name(uri)), 'Interest returned on callback had different name') # TODO: Replace this with a test that connects to a Face on localhost #def test_specific_interest(self): # uri = "/ndn/edu/ucla/remap/ndn-js-test/howdy.txt/%FD%052%A1%DF%5E%A4" # (dataCallback, timeoutCallback) = self.run_express_name_test(uri) # self.assertTrue(timeoutCallback.call_count == 0, 'Unexpected timeout on expressed interest') # # # check that the callback was correct # self.assertEqual(dataCallback.call_count, 1, 'Expected 1 onData callback, got '+str(dataCallback.call_count)) # onDataArgs = dataCallback.call_args[0] # the args are returned as ([ordered arguments], [keyword arguments]) # #just check that the interest was returned correctly? # callbackInterest = onDataArgs[0] # self.assertTrue(callbackInterest.getName() == Name(uri), 'Interest returned on callback had different name') def test_timeout(self): uri = "/test/timeout" (dataCallback, timeoutCallback) = self.run_express_name_test(uri) # we're expecting a timeout callback, and only 1 self.assertTrue(dataCallback.call_count == 0, 'Data callback called for invalid interest') self.assertTrue(timeoutCallback.call_count == 1, 'Expected 1 timeout call, got ' + str(timeoutCallback.call_count)) #check that the interest was returned correctly onTimeoutArgs = timeoutCallback.call_args[0] # the args are returned as ([ordered arguments], [keyword arguments]) #just check that the interest was returned correctly? callbackInterest = onTimeoutArgs[0] self.assertTrue(callbackInterest.getName() == (Name(uri)), 'Interest returned on callback had different name') def test_remove_pending(self): name = Name("/ndn/edu/ucla/remap/") dataCallback = Mock() timeoutCallback = Mock() interestID = self.face.expressInterest(name, dataCallback, timeoutCallback) self.face.removePendingInterest(interestID) timeout = 10000 startTime = getNowMilliseconds() while True: self.face.processEvents() time.sleep(0.01) if getNowMilliseconds() - startTime >= timeout: break if (dataCallback.call_count > 0 or timeoutCallback.call_count > 0): break self.assertEqual(dataCallback.call_count, 0, 'Should not have called data callback after interest was removed') self.assertEqual(timeoutCallback.call_count, 0, 'Should not have called timeout callback after interest was removed') 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())
class TestFaceRegisterMethods(ut.TestCase): def setUp(self): self.face_in = Face() self.face_out = Face() self.keyChain = KeyChain() def tearDown(self): self.face_in.shutdown() self.face_out.shutdown() def onInterestEffect(self, prefix, interest, transport, prefixID): data = Data(interest.getName()) data.setContent("SUCCESS") self.keyChain.sign(data, self.keyChain.getDefaultCertificateName()) encodedData = data.wireEncode() transport.send(encodedData.toBuffer()) def test_register_prefix_response(self): # gotta sign it (WAT) prefixName = Name("/test") self.face_in.setCommandSigningInfo(self.keyChain, self.keyChain.getDefaultCertificateName()) failedCallback = Mock() interestCallback = Mock(side_effect=self.onInterestEffect) self.face_in.registerPrefix(prefixName, interestCallback, failedCallback) server = gevent.spawn(self.face_process_events, self.face_in, [interestCallback, failedCallback], 'h') time.sleep(1) # give the 'server' time to register the interest # express an interest on another face dataCallback = Mock() timeoutCallback = Mock() # now express an interest on this new face, and see if onInterest is called interestName = prefixName.append("hello") self.face_out.expressInterest(interestName, dataCallback, timeoutCallback) client = gevent.spawn(self.face_process_events, self.face_out, [dataCallback, timeoutCallback], 'c') gevent.joinall([server, client], timeout=10) self.assertEqual(failedCallback.call_count, 0, 'Failed to register prefix at all') self.assertEqual(interestCallback.call_count, 1, 'Expected 1 onInterest callback, got '+str(interestCallback.call_count)) self.assertEqual(dataCallback.call_count, 1, 'Expected 1 onData callback, got '+str(dataCallback.call_count)) onDataArgs = dataCallback.call_args[0] # check the message content data = onDataArgs[1] expectedBlob = Blob(bytearray("SUCCESS")) self.assertTrue(expectedBlob == data.getContent(), 'Data received on face does not match expected format') def face_process_events(self, face, callbacks, name=None): # implemented as a 'greenlet': something like a thread, but semi-synchronous # callbacks should be a list done = False while not done: face.processEvents() gevent.sleep() for c in callbacks: if (c.call_count > 0): done = True
class Consumer(object): '''Sends Interest, listens for data''' 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 run(self): try: while self.nextSegment < self.pipeline: self._sendNextInterest(self.prefix) self.nextSegment += 1 while not self.isDone: self.face.processEvents() time.sleep(0.01) 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() del self.outstanding[name.toUri()] if self.count == self.nextSegment or data.getMetaInfo().getFinalBlockID() == data.getName()[-1]: self.isDone = True else: self._sendNextInterest(self.prefix) self.nextSegment += 1 def _sendNextInterest(self, name): self._sendNextInterestWithSegment(Name(name).appendSegment(self.nextSegment)) def _sendNextInterestWithSegment(self, name): interest = Interest(name) uri = name.toUri() interest.setInterestLifetimeMilliseconds(4000) interest.setMustBeFresh(True) if name.toUri() not in self.outstanding: self.outstanding[name.toUri()] = 1 self.face.expressInterest(interest, self._onData, self._onTimeout) print "Sent Interest for %s" % uri def _onTimeout(self, interest): name = interest.getName() uri = name.toUri() print "TIMEOUT #%d: segment #%s" % (self.outstanding[uri], name[-1].toNumber()) self.outstanding[uri] += 1 if self.outstanding[uri] <= 3: self._sendNextInterestWithSegment(name) else: self.isDone = True