async def face_event(self): last_seq = -1 retry_time = 3000 retry_count_limit = 60000 // retry_time retry_count = 0 while self.running and self.face: name = Name("/localhost/nfd/faces/events") face_interest = Interest() if last_seq >= 0: name.appendSequenceNumber(last_seq + 1) face_interest.canBePrefix = False else: face_interest.mustBeFresh = True face_interest.canBePrefix = True logging.info("Face event notification stream %s", name.toUri()) face_interest.name = name # face_interest.interestLifetimeMilliseconds = 60000 face_interest.interestLifetimeMilliseconds = retry_time ret = await fetch_data_packet(self.face, face_interest) timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") if isinstance(ret, Data): retry_count = 0 last_seq = ret.name[-1].toSequenceNumber() face_event = FaceEventNotificationMessage() try: ProtobufTlv.decode(face_event, ret.content) dic = self.face_event_to_dict(face_event.face_event_notification) dic['seq'] = str(last_seq) dic['time'] = timestamp self.emit('face event', dic) self.event_list.append(dic) except RuntimeError as exc: logging.fatal('Decode failed %s', exc) last_seq = -1 elif ret is None: if retry_count >= retry_count_limit: logging.info("No response: face event") last_seq = -1 retry_count = 0 else: retry_count += 1 else: logging.info("NFD is not running: start reconnection") self.start_reconnection() return await asyncio.sleep(0.1)
def general_status(): def convert_time(timestamp): ret = datetime.fromtimestamp(float(timestamp) / 1000.0) return str(ret) interest = Interest("/localhost/nfd/status/general") interest.mustBeFresh = True interest.canBePrefix = True ret = run_until_complete(fetch_data_packet(server.face, interest)) if isinstance(ret, Data): name = ret.name.toUri() msg = GeneralStatus() try: ProtobufTlv.decode(msg, ret.content) except RuntimeError as exc: logging.fatal("Decoding Error %s", exc) return "Decoding Error" status = decode_dict(msg) status['start_timestamp'] = convert_time(status['start_timestamp']) status['current_timestamp'] = convert_time( status['current_timestamp']) return render_template('general-status.html', refer_name='/general-status', name=name, status=status) else: logging.info("No response: general status") return redirect('/')
def strategy_list(): def decode_strategy(msg): return [{ "name": decode_name(item.name), "strategy": decode_name(item.strategy.name), } for item in msg] interest = Interest("/localhost/nfd/strategy-choice/list") interest.mustBeFresh = True interest.canBePrefix = True ret = run_until_complete(fetch_data_packet(server.face, interest)) if isinstance(ret, Data): msg = StrategyChoiceMessage() try: ProtobufTlv.decode(msg, ret.content) except RuntimeError as exc: logging.info("Decoding Error %s", exc) return "Decoding Error" strategy_list = decode_strategy(msg.strategy_choice) return render_template('strategy-list.html', refer_name='/strategy-list', strategy_list=strategy_list, **request.args.to_dict()) else: logging.info("No response: strategy-list") return redirect('/')
def route_list(): def decode_route_list(msg): ret = [] for item in msg: name = decode_name(item.name) routes = decode_list(item.route) ret.append((name, routes)) return ret interest = Interest("/localhost/nfd/rib/list") interest.mustBeFresh = True interest.canBePrefix = True ret = run_until_complete(fetch_data_packet(server.face, interest)) if isinstance(ret, Data): name = ret.name.toUri() msg = RibStatusMessage() try: ProtobufTlv.decode(msg, ret.content) except RuntimeError as exc: logging.fatal("Decoding Error %s", exc) return "Decoding Error" rib_list = decode_route_list(msg.rib_entry) return render_template('route-list.html', refer_name='/route-list', rib_list=rib_list, **request.args.to_dict()) else: logging.info("No response: route-list") return redirect('/')
def face_list(): interest = Interest("/localhost/nfd/faces/list") interest.mustBeFresh = True interest.canBePrefix = True ret = run_until_complete(fetch_data_packet(server.face, interest)) if isinstance(ret, Data): name = ret.name.toUri() msg = FaceStatusMessage() try: ProtobufTlv.decode(msg, ret.content) except RuntimeError as exc: logging.fatal("Decoding Error %s", exc) return "Decoding Error" face_list = decode_list(msg.face_status) fields = list(face_list[0].keys()) fields_collapse = [ field for field in set(fields) - {'face_id', 'uri'} ] return render_template('face-list.html', refer_name='/face-list', face_list=face_list, fields_collapse=fields_collapse, **request.args.to_dict()) else: logging.info("No response: face-list") return redirect('/')
def make_command(self, module, verb, **kwargs): name = Name('/localhost/nfd').append(module).append(verb) # Command Parameters cmd_param = ControlCommandMessage() if 'name' in kwargs: name_param = kwargs['name'] for compo in name_param: cmd_param.control_parameters.name.component.append(compo.getValue().toBytes()) if 'strategy' in kwargs: name_param = kwargs['strategy'] for compo in name_param: cmd_param.control_parameters.strategy.name.component.append(compo.getValue().toBytes()) for key in ['uri', 'local_uri']: if key in kwargs: setattr(cmd_param.control_parameters, key, kwargs[key].encode('utf-8')) for key in ['face_id', 'origin', 'cost', 'capacity', 'count', 'base_cong_mark', 'def_cong_thres', 'mtu', 'flags', 'mask', 'exp_period']: if key in kwargs: setattr(cmd_param.control_parameters, key, kwargs[key]) param_blob = ProtobufTlv.encode(cmd_param) name.append(Name.Component(param_blob)) # Command Interest Components ret = Interest(name) ret.canBePrefix = True self.face.makeCommandInterest(ret) return ret
async def send_cmd_interest(self): event_loop = asyncio.get_event_loop() face_task = event_loop.create_task(self.face_loop()) parameter = RepoCommandParameterMessage() for compo in self.prefix: parameter.repo_command_parameter.name.component.append(compo.getValue().toBytes()) parameter.repo_command_parameter.start_block_id = self.latest_tp parameter.repo_command_parameter.end_block_id = parameter.repo_command_parameter.start_block_id param_blob = ProtobufTlv.encode(parameter) # Prepare cmd interest name = Name(self.repo_name).append("insert").append(Name.Component(param_blob)) interest = Interest(name) interest.canBePrefix = True self.face.makeCommandInterest(interest) logging.info("Express interest: {}".format(interest.getName())) ret = await fetch_data_packet(self.face, interest) if not isinstance(ret, Data): logging.warning("Insertion failed") else: # Parse response response = RepoCommandResponseMessage() try: ProtobufTlv.decode(response, ret.content) logging.info('Insertion command accepted: status code {}' .format(response.repo_command_response.status_code)) except RuntimeError as exc: logging.warning('Response decoding failed', exc)
async def _check(self, method: str, repo_name: str, process_id: int) -> RepoCommandResponseMessage: """ Return parsed insert check response message. """ parameter = RepoCommandParameterMessage() parameter.repo_command_parameter.process_id = process_id param_blob = ProtobufTlv.encode(parameter) name = Name(repo_name).append(method + ' check').append(Name.Component(param_blob)) interest = Interest(name) interest.canBePrefix = True interest.setInterestLifetimeMilliseconds(1000) self.face.makeCommandInterest(interest) logging.info('Send ' + method + 'check interest') ret = await fetch_data_packet(self.face, interest) if not isinstance(ret, Data): logging.warning('Check error') return None try: response = self.decode_cmd_response_blob(ret) except RuntimeError as exc: logging.warning('Response blob decoding failed') return None return response
def connection_test(self): interest = Interest("/localhost/nfd/faces/events") interest.mustBeFresh = True interest.canBePrefix = True interest.interestLifetimeMilliseconds = 1000 try: def empty(*_args, **_kwargs): pass self.face.expressInterest(interest, empty, empty, empty) return True except (ConnectionRefusedError, BrokenPipeError, OSError): return False
async def query_face_id(self, uri): query_filter = FaceQueryFilterMessage() query_filter.face_query_filter.uri = uri.encode('utf-8') query_filter_msg = ProtobufTlv.encode(query_filter) name = Name("/localhost/nfd/faces/query").append(Name.Component(query_filter_msg)) interest = Interest(name) interest.mustBeFresh = True interest.canBePrefix = True ret = await fetch_data_packet(self.face, interest) if not isinstance(ret, Data): return None msg = FaceStatusMessage() try: ProtobufTlv.decode(msg, ret.content) except RuntimeError as exc: logging.fatal("Decoding Error %s", exc) return None if len(msg.face_status) <= 0: return None return msg.face_status[0].face_id
async def run(): async def face_loop(): nonlocal face, running while running: face.processEvents() await asyncio.sleep(0.01) running = True face = Face() event_loop = asyncio.get_event_loop() face_task = event_loop.create_task(face_loop()) interest = Interest(Name("/localhost/gitsync/notif/temprepo/master")) interest.mustBeFresh = True interest.canBePrefix = True interest.interestLifetimeMilliseconds = 60000 data = await fetch_data_packet(face, interest) if isinstance(data, Data): print("Notif", data.content.toBytes().decode()) else: print("Failed") running = False await face_task
def exec_ndn_ping(): nonlocal last_ping_data name = request.form['name'] can_be_prefix = request.form['can_be_prefix'] == 'true' must_be_fresh = request.form['must_be_fresh'] == 'true' try: interest_lifetime = float( request.form['interest_lifetime']) * 1000.0 except ValueError: interest_lifetime = 4000.0 interest = Interest(name) interest.canBePrefix = can_be_prefix interest.mustBeFresh = must_be_fresh interest.interestLifetimeMilliseconds = interest_lifetime st_time = time.time() ret = run_until_complete(fetch_data_packet(server.face, interest)) ed_time = time.time() response_time = '{:.3f}s'.format(ed_time - st_time) if isinstance(ret, Data): response_type = 'Data' name = ret.name.toUri() if ret.metaInfo.type is not None: content_type = decode_content_type(ret.metaInfo.type) else: content_type = "None" if ret.metaInfo.freshnessPeriod is not None: freshness_period = "{:.3f}s".format( ret.metaInfo.freshnessPeriod / 1000.0) else: freshness_period = "None" if ret.metaInfo.finalBlockId is not None: final_block_id = ret.metaInfo.finalBlockId.toEscapedString() else: final_block_id = "None" signature_type = type(ret.signature).__name__ last_ping_data = ret.content.toBytes() return redirect( url_for('ndn_ping', response_time=response_time, response_type=response_type, name=name, content_type=content_type, freshness_period=freshness_period, final_block_id=final_block_id, signature_type=signature_type, download='/download/ping-data')) elif isinstance(ret, NetworkNack): response_type = 'NetworkNack' reason = decode_nack_reason(ret.getReason()) return redirect( url_for('ndn_ping', response_time=response_time, response_type=response_type, name=name, reason=reason)) elif ret is None: response_type = 'Timeout' return redirect( url_for('ndn_ping', response_time=response_time, response_type=response_type, name=name)) else: logging.info("No response: ndn-ping") return redirect('/')