예제 #1
0
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()
예제 #2
0
    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
예제 #3
0
    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)
예제 #4
0
    async def send_temp_interest(self):
        """
        Send a temperature interest to the producer
        """
        interest_name = Name(self.prefix).append(str(int(time.time()) - 1))
        interest = Interest(interest_name)
        interest.interestLifetimeMilliseconds = 4000

        logging.info('Fetching {}'.format(str(interest.getName())))
        print('Fetching {}'.format(str(interest.getName())))

        data = await fetch_data_packet(self.face, interest)
        if isinstance(data, Data):
            self.process_temp_data(data)
        else:
            logging.info('Failed to fetch {}'.format(str(interest.getName())))
예제 #5
0
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
예제 #6
0
    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('/')
예제 #7
0
async def run(local_repo_path: str, repo_prefix: str):
    async def face_loop():
        nonlocal face, running
        while running:
            face.processEvents()
            await asyncio.sleep(0.01)

    options = {'cloning': False}
    running = True
    face = Face()
    keychain = KeyChain()
    face.setCommandSigningInfo(keychain, keychain.getDefaultCertificateName())
    event_loop = asyncio.get_event_loop()
    face_task = event_loop.create_task(face_loop())
    storage = FileStorage(local_repo_path)
    producer = GitProducer(face, Name(repo_prefix).append("objects"), storage)
    refs = []

    empty_cnt = 0
    while empty_cnt < 2 and running:
        cmd = sys.stdin.readline().rstrip("\n\r")
        # print("<<", cmd, file=sys.stderr)
        if cmd == "capabilities":
            print("push")
            print("fetch")
            print("option")
            print("")
            sys.stdout.flush()
        elif cmd.startswith("option"):
            opt_name, opt_val = cmd.split()[1:]
            if opt_name == "cloning":
                options['cloning'] = (opt_val == 'true')
                print("ok")
            else:
                print("unsupported")
            sys.stdout.flush()
        elif cmd == "list" or cmd == "list for-push":
            interest = Interest(Name(repo_prefix).append("ref-list"))
            data = await fetch_data_packet(face, interest)
            if isinstance(data, Data):
                reflist = data.content.toBytes().decode("utf-8")
                print(reflist)

                if reflist.strip() == "":
                    refs = {}
                else:
                    refs = [
                        item.split(" ")[1]
                        for item in reflist.strip().split("\n")
                    ]
                    refs = {name.split("/")[-1] for name in refs}
            else:
                print("error: Couldn't connect to",
                      repo_prefix,
                      file=sys.stderr)
                running = False
                print("")
            sys.stdout.flush()
        elif cmd.startswith("fetch"):
            fetcher = GitFetcher(face,
                                 Name(repo_prefix).append("objects"), storage)
            while True:
                # Fetch files
                hash_name, ref_name = cmd.split()[1:]
                fetcher.fetch(hash_name, "commit")
                await fetcher.wait_until_finish()
                # Set refs file
                ref_file_path = os.path.join(local_repo_path, ref_name)
                with open(ref_file_path, 'w') as f:
                    f.write(hash_name)
                # Read commands for next fetch
                cmd = sys.stdin.readline().rstrip("\n\r")
                if not cmd.startswith("fetch"):
                    break
            print("")
            sys.stdout.flush()
        elif cmd.startswith("push"):
            while True:
                # Push commands
                # TODO: DELETE ALL HARDCODED THINGS
                # TODO: MAKE DATA AND INTEREST REAL
                branch, commit, _ = parse_push(cmd, local_repo_path)
                repo_name = repo_prefix.split("/")[-1]

                # Create Branch if not exist
                if branch not in refs:
                    print("Non-existing branch. Try to create...",
                          file=sys.stderr)
                    interest = Interest(
                        Name(LOCAL_CMD_PREFIX).append("create-branch").append(
                            repo_name).append(branch))
                    data = await fetch_data_packet(face, interest)
                    if isinstance(data, Data):
                        result = struct.unpack("i", data.content.toBytes())[0]
                        if result == 1:
                            print("Creation succeeded", file=sys.stderr)
                        elif result == 2:
                            print("Creation is FAILED", file=sys.stderr)
                            print("error refs/heads/{} FAILED".format(branch))
                            break
                        else:
                            print("Creation is PENDING", file=sys.stderr)
                            print("error refs/heads/{} PENDING".format(branch))
                            break
                    else:
                        print("error: Couldn't connect to",
                              interest.name.toUri(),
                              file=sys.stderr)
                        break

                # BranchInfo Interest
                interest = Interest(
                    Name(repo_prefix).append("branch-info").append(branch))
                data = await fetch_data_packet(face, interest)
                branchinfo = None
                if isinstance(data, Data):
                    branchinfo = pickle.loads(data.content.toBytes())
                if branchinfo is None or 'custodian' not in branchinfo.__dict__:
                    print("ERROR Interest got no response: ",
                          interest.name,
                          file=sys.stderr)
                    print("error refs/heads/{} DISCONNECTED".format(branch))
                    break

                # Push Interest
                interest = Interest(
                    Name(branchinfo.custodian).append("push").append(
                        repo_name).append(branch))
                interest.applicationParameters = commit.encode("utf-8")
                interest.appendParametersDigestToName()
                interest.interestLifetimeMilliseconds = 20000
                interest.mustBeFresh = True
                data = await fetch_data_packet(face, interest)
                if isinstance(data, Data):
                    result = struct.unpack("i", data.content.toBytes())[0]
                    if result == 1:
                        print("OK push succeeded",
                              interest.name,
                              file=sys.stderr)
                        print("ok refs/heads/{}".format(branch))
                    elif result == 2:
                        print("ERROR push failed",
                              interest.name,
                              file=sys.stderr)
                        print("error refs/heads/{} FAILED".format(branch))
                    else:
                        print("PROCESSING push is not finished yet",
                              interest.name,
                              file=sys.stderr)
                        print("error refs/heads/{} PENDING".format(branch))
                else:
                    print("ERROR Interest got no response: ",
                          interest.name,
                          file=sys.stderr)
                    print("error refs/heads/{} DISCONNECTED".format(branch))
                    break

                # Read commands for next fetch
                cmd = sys.stdin.readline().rstrip("\n\r")
                if not cmd.startswith("push"):
                    break

            print("")
            sys.stdout.flush()
        elif cmd == "":
            empty_cnt += 1
        else:
            pass

    producer.cancel()
    running = False
    await face_task