def main():
    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

    interest = Interest()
    interest.wireDecode(TlvInterest)

    # Use a hard-wired secret for testing. In a real application the signer
    # ensures that the verifier knows the shared key and its keyName.
    key = Blob(
        bytearray([
            0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
            19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31
        ]))

    if KeyChain.verifyInterestWithHmacWithSha256(interest, key):
        dump("Hard-coded interest signature verification: VERIFIED")
    else:
        dump("Hard-coded interest signature verification: FAILED")

    freshInterest = Interest(Name("/ndn/abc"))
    freshInterest.setMustBeFresh(False)
    keyName = Name("key1")
    dump("Signing fresh interest", freshInterest.getName().toUri())
    KeyChain.signWithHmacWithSha256(freshInterest, key, keyName)

    if KeyChain.verifyInterestWithHmacWithSha256(freshInterest, key):
        dump("Freshly-signed interest signature verification: VERIFIED")
    else:
        dump("Freshly-signed interest signature verification: FAILED")
예제 #2
0
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)
예제 #3
0
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()
예제 #4
0
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)
예제 #5
0
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()
예제 #6
0
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)
예제 #7
0
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)
예제 #8
0
def main():
    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

    loop = asyncio.get_event_loop()
    face = ThreadsafeFace(loop, "memoria.ndn.ucla.edu")

    # Counter will stop the ioService after callbacks for all expressInterest.
    counter = Counter(loop, 3)

    # Try to fetch anything.
    name1 = Name("/")
    dump("Express name ", name1.toUri())
    # These call to exressIinterest is thread safe because face is a ThreadsafeFace.
    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)

    # Run until the Counter calls stop().
    loop.run_forever()
    face.shutdown()
def main():
    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

    interest = Interest()
    interest.wireDecode(TlvInterest)

    # Use a hard-wired secret for testing. In a real application the signer
    # ensures that the verifier knows the shared key and its keyName.
    key = Blob(bytearray([
       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15,
      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31
    ]))

    if KeyChain.verifyInterestWithHmacWithSha256(interest, key):
      dump("Hard-coded interest signature verification: VERIFIED")
    else:
      dump("Hard-coded interest signature verification: FAILED")

    freshInterest = Interest(Name("/ndn/abc"))
    freshInterest.setMustBeFresh(False)
    keyName = Name("key1")
    dump("Signing fresh interest", freshInterest.getName().toUri())
    KeyChain.signWithHmacWithSha256(freshInterest, key, keyName)

    if KeyChain.verifyInterestWithHmacWithSha256(freshInterest, key):
      dump("Freshly-signed interest signature verification: VERIFIED")
    else:
      dump("Freshly-signed interest signature verification: FAILED")
예제 #10
0
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()
예제 #11
0
    def __init__(self, name, face):
        Interest.setDefaultCanBePrefix(True)

        self.name = Name(name)
        self.face = face
        self._callbackCount = 0
        self.value = None
        self.last = None
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"))
예제 #13
0
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"))
예제 #14
0
    def __init__(self, engine, measured_instrument):
        Interest.setDefaultCanBePrefix(True)

        self.engine = engine
        self.measured_instrument = measured_instrument
        self.name = Name(measured_instrument.getName())
        self.face = Face()
        self._callbackCount = 0
        self._callbackTimeout = 0
        self.value = None
        self.last = None
        self.time_start = time.time()
예제 #15
0
파일: test_sync.py 프로젝트: danome/PyCNL
def main():
    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

    if sys.version_info[0] <= 2:
        userName = raw_input("Enter your user name (e.g. \"a\" or \"b\"): ")
    else:
        userName = input("Enter your user name (e.g. \"a\" or \"b\"): ")
    if userName == "":
        dump("You must enter a user name")
        return

    # 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.
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    applicationPrefix = Namespace(Name("/test/app"), keyChain)
    applicationPrefix.setFace(face,
      lambda prefix: dump("Register failed for prefix", prefix))
    applicationPrefix.enableSync()

    userPrefix = applicationPrefix[Name.Component(userName)]

    def onStateChanged(nameSpace, changedNamespace, state, callbackId):
        if (state == NamespaceState.NAME_EXISTS and
             not userPrefix.name.isPrefixOf(changedNamespace.name)):
            dump("Received", changedNamespace.name.toUri())

    applicationPrefix.addOnStateChanged(onStateChanged)

    publishIntervalMs = 1000.0
    component = Name("/%00").get(0)

    # Loop, producing a new name every publishIntervalMs milliseconds (and also
    # calling processEvents()).
    previousPublishMs = 0.0
    while True:
        now = Common.getNowMilliseconds()
        if now >= previousPublishMs + publishIntervalMs:
            # If userName is "a", this makes /test/app/a/%00, /test/app/a/%01, etc.
            newNamespace = userPrefix[component]
            dump("Publish", newNamespace.name.toUri())
            component = component.getSuccessor()

            previousPublishMs = now

        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
예제 #16
0
def main():
    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

    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, 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)
예제 #17
0
def main():
    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

    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 onSegmentedObject(objectNamespace):
        dump("Got segmented object size", objectNamespace.obj.size())
        enabled[0] = False
    SegmentedObjectHandler(page, onSegmentedObject).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)
예제 #18
0
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()

    stream = Namespace("/ndn/eb/stream/run/28/annotations")
    stream.setFace(face)

    def onNewObject(sequenceNumber, contentMetaInfo, objectNamespace):
        dump("Got generalized object, sequenceNumber", sequenceNumber,
             ", content-type", contentMetaInfo.contentType, ":",
             str(objectNamespace.obj))

    pipelineSize = 10
    GeneralizedObjectStreamHandler(stream, pipelineSize,
                                   onNewObject).objectNeeded()

    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)
예제 #19
0
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()

    objectPrefix = Namespace("/ndn/eb/run/28/description")
    objectPrefix.setFace(face)

    enabled = [True]

    def onGeneralizedObject(contentMetaInfo, objectNamespace):
        dump("Got generalized object, content-type",
             contentMetaInfo.contentType, ":", str(objectNamespace.obj))
        enabled[0] = False

    GeneralizedObjectHandler(objectPrefix, onGeneralizedObject).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)
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)
예제 #21
0
    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()
예제 #22
0
def main():
    # Uncomment these lines to print ChronoSync debug messages.
    # logging.getLogger('').addHandler(logging.StreamHandler(sys.stdout))
    # logging.getLogger('').setLevel(logging.INFO)

    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

    screenName = promptAndInput("Enter your chat username: "******"ndn/edu/ucla/remap"
    hubPrefix = promptAndInput("Enter your hub prefix [" + defaultHubPrefix +
                               "]: ")
    if hubPrefix == "":
        hubPrefix = defaultHubPrefix

    defaultChatRoom = "ndnchat"
    chatRoom = promptAndInput("Enter the chatroom name [" + defaultChatRoom +
                              "]: ")
    if chatRoom == "":
        chatRoom = defaultChatRoom

    host = "localhost"
    print("Connecting to " + host + ", Chatroom: " + chatRoom +
          ", Username: "******"")

    face = Face(host)

    # Set up the key chain.
    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())

    chat = Chat(screenName, chatRoom, Name(hubPrefix), face, keyChain,
                keyChain.getDefaultCertificateName())

    # The main loop to process Chat while checking stdin to send a message.
    print("Enter your chat message. To quit, enter \"leave\" or \"exit\".")
    while True:
        # Set timeout to 0 for an immediate check.
        isReady, _, _ = select.select([sys.stdin], [], [], 0)
        if len(isReady) != 0:
            input = promptAndInput("")
            if input == "leave" or input == "exit":
                # We will send the leave message below.
                break

            chat.sendMessage(input)

        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)

    # The user entered the command to leave.
    chat.leave()
    # Wait a little bit to allow other applications to fetch the leave message.
    startTime = Chat.getNowMilliseconds()
    while True:
        if Chat.getNowMilliseconds() - startTime >= 1000.0:
            break

        face.processEvents()
        time.sleep(0.01)
예제 #23
0
def main():
    """Runs a consumer with the specified properties."""

    # silence the warning from interest wire encode
    Interest.setDefaultCanBePrefix(True)

    # handle and specify arguments
    parser = argparse.ArgumentParser()

    parser.add_argument("-p",
                        "--prefix",
                        help="the prefix to request data from",
                        action="append",
                        default=["/ndn/external/test"])
    parser.add_argument("-c",
                        "--count",
                        help="the number of interests to send",
                        type=int,
                        default=10)
    parser.add_argument("-i",
                        "--ipaddress",
                        help="the ip address to tunnel to",
                        default="10.10.1.1")
    parser.add_argument("-v",
                        "--verbosity",
                        help="increase output verbosity",
                        choices=[0, 1, 2],
                        type=int,
                        default=0)
    # TODO: add rate functionality back in if needed
    #  parser.add_argument("-r", "--rate", help="the rate at which interests are sent", type=rate_parser, default="0.00001")
    parser.add_argument("-r",
                        "--repeat",
                        help="the number of interest bursts to send",
                        type=int,
                        default=1)
    parser.add_argument("-f",
                        "--filename",
                        help="the output file to store data to (in CSV form)")

    args = parser.parse_args()

    # clean up prefix argument
    if len(args.prefix) > 1:
        args.prefix.pop(0)

    # create a list of dictionaries to store data in
    data = []

    # send interest burst a specified number of times
    for i in range(0, args.repeat):

        # create a consumer and send interests with it for each prefix provided
        for namespace in args.prefix:
            consumer = Consumer(args.ipaddress, verbose=args.verbosity)
            #  TODO: add rate functionality back in if needed
            data.append(consumer.send_interests(namespace, args.count))

        time.sleep(0.25)

    # create dataframe from list of dictionaries
    df = pd.DataFrame(data)

    # store output to file if filename option is enabled
    if args.filename is not None:
        df.to_csv(args.filename)

    print(df)
예제 #24
0
 def ndnInit(self): 
     Interest.setDefaultCanBePrefix(True)
     # TODO: Bug? Does not auto retry TCP if unix socket fails as says in docs. 
     # self.face = Face("localhost", 6363)
     self.face = Face()
     self.primary_prefix = "/ndn"
예제 #25
0
def main():
    # Uncomment these lines to print ChronoSync debug messages.
    # logging.getLogger('').addHandler(logging.StreamHandler(sys.stdout))
    # logging.getLogger('').setLevel(logging.INFO)

    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

    screenName = promptAndInput("Enter your chat username: "******"ndn/edu/ucla/remap"
    hubPrefix = promptAndInput("Enter your hub prefix [" + defaultHubPrefix + "]: ")
    if hubPrefix == "":
        hubPrefix = defaultHubPrefix

    defaultChatRoom = "ndnchat"
    chatRoom = promptAndInput("Enter the chatroom name [" + defaultChatRoom + "]: ")
    if chatRoom == "":
        chatRoom = defaultChatRoom

    host = "localhost"
    print("Connecting to " + host + ", Chatroom: " + chatRoom + ", Username: "******"")

    face = Face(host)

    # Set up the key chain.
    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())

    chat = Chat(
      screenName, chatRoom, Name(hubPrefix), face, keyChain,
      keyChain.getDefaultCertificateName())

    # The main loop to process Chat while checking stdin to send a message.
    print("Enter your chat message. To quit, enter \"leave\" or \"exit\".")
    while True:
        # Set timeout to 0 for an immediate check.
        isReady, _, _ = select.select([sys.stdin], [], [], 0)
        if len(isReady) != 0:
            input = promptAndInput("")
            if input == "leave" or input == "exit":
                # We will send the leave message below.
                break

            chat.sendMessage(input)

        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)

    # The user entered the command to leave.
    chat.leave()
    # Wait a little bit to allow other applications to fetch the leave message.
    startTime = Chat.getNowMilliseconds()
    while True:
        if Chat.getNowMilliseconds() - startTime >= 1000.0:
            break

        face.processEvents()
        time.sleep(0.01)
예제 #26
0
async def run(cmd: str):
    async def face_loop():
        nonlocal face, running
        while running:
            face.processEvents()
            await asyncio.sleep(0.01)

    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())
    Interest.setDefaultCanBePrefix(True)

    if cmd == "track-repo":
        if len(sys.argv) < 3:
            print("Usage:", sys.argv[0], "track-repo <repo>", file=sys.stderr)
        else:
            repo = sys.argv[2]
            interest = Interest(
                Name(LOCAL_CMD_PREFIX).append("track-repo").append(repo))
            data = await fetch_data_packet(face, interest)
            if isinstance(data, Data):
                result = struct.unpack("i", data.content.toBytes())[0]
                if result == 1:
                    print("OK")
                elif result == 2:
                    print("FAILED")
                else:
                    print("PENDING")
            else:
                print("error: Couldn't connect to",
                      interest.name.toUri(),
                      file=sys.stderr)
    elif cmd == "create-branch":
        if len(sys.argv) < 4:
            print("Usage:",
                  sys.argv[0],
                  "create-branch <repo> <branch>",
                  file=sys.stderr)
        else:
            repo = sys.argv[2]
            branch = sys.argv[3]
            interest = Interest(
                Name(LOCAL_CMD_PREFIX).append("create-branch").append(
                    repo).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("OK")
                elif result == 2:
                    print("FAILED")
                else:
                    print("PENDING")
            else:
                print("error: Couldn't connect to",
                      interest.name.toUri(),
                      file=sys.stderr)
    elif cmd == "mount":
        if len(sys.argv) < 4:
            print("Usage:",
                  sys.argv[0],
                  "mount <repo> <branch>",
                  file=sys.stderr)
        else:
            repo = sys.argv[2]
            branch = sys.argv[3]
            interest = Interest(
                Name(LOCAL_CMD_PREFIX).append("mount").append(repo).append(
                    branch))
            data = await fetch_data_packet(face, interest)
            if isinstance(data, Data):
                content = data.content.toBytes()
                ret_code = struct.unpack("i", content[:4])[0]
                if ret_code == 1:
                    print(content[4:].decode())
                else:
                    print("Failed")
            else:
                print("error: Couldn't connect to",
                      interest.name.toUri(),
                      file=sys.stderr)
    elif cmd == "update":
        if len(sys.argv) < 4:
            print("Usage:",
                  sys.argv[0],
                  "update <repo> <branch>",
                  file=sys.stderr)
        else:
            repo = sys.argv[2]
            branch = sys.argv[3]
            interest = Interest(
                Name(LOCAL_CMD_PREFIX).append("clone").append(repo).append(
                    branch))
            data = await fetch_data_packet(face, interest)
            if isinstance(data, Data):
                content = data.content.toBytes()
                ret_code = struct.unpack("i", content[:4])[0]
                if ret_code == 1:
                    print(content[4:].decode())
                else:
                    print("Failed")
            else:
                print("error: Couldn't connect to",
                      interest.name.toUri(),
                      file=sys.stderr)
    elif cmd == "unmount":
        if len(sys.argv) < 4:
            print("Usage:",
                  sys.argv[0],
                  "unmount <repo> <branch>",
                  file=sys.stderr)
        else:
            repo = sys.argv[2]
            branch = sys.argv[3]
            interest = Interest(
                Name(LOCAL_CMD_PREFIX).append("unmount").append(repo).append(
                    branch))
            data = await fetch_data_packet(face, interest)
            if isinstance(data, Data):
                print("Finished.")
            else:
                print("error: Couldn't connect to",
                      interest.name.toUri(),
                      file=sys.stderr)
    elif cmd == "commit":
        if len(sys.argv) < 6:
            print("Usage:",
                  sys.argv[0],
                  "commit <repo> <dest-branch> <path> <message>",
                  file=sys.stderr)
        else:
            repo = sys.argv[2]
            dest_branch = sys.argv[3]
            path = sys.argv[4]
            commit_msg = sys.argv[5]
            interest = Interest(Name(LOCAL_CMD_PREFIX).append("commit"))
            interest.applicationParameters = b'\x00'.join([
                repo.encode(),
                dest_branch.encode(),
                path.encode(),
                commit_msg.encode()
            ])
            interest.appendParametersDigestToName()
            data = await fetch_data_packet(face, interest)
            if isinstance(data, Data):
                print("Finished.")
            else:
                print("error: Couldn't connect to",
                      interest.name.toUri(),
                      file=sys.stderr)
    else:
        print("Unrecognized command:", cmd, file=sys.stderr)

    running = False
    await face_task
예제 #27
0
def main():
    """Runs a consumer with the specified properties."""

    # silence the warning from interest wire encode
    Interest.setDefaultCanBePrefix(True)

    # handle and specify arguments
    parser = argparse.ArgumentParser()

    parser.add_argument("-p",
                        "--prefix",
                        help="the prefix to request data from",
                        action="append",
                        default=["/ndn/external/test"])
    parser.add_argument("-t",
                        "--time",
                        help="the number of seconds to run each stream for",
                        type=int,
                        default=10)
    parser.add_argument("-f",
                        "--filename",
                        help="the output file to store data to (in CSV form)")
    parser.add_argument("-i",
                        "--ipaddress",
                        help="the ip address to tunnel to",
                        default="10.10.1.1")
    #  parser.add_argument("-r", "--rate", help="the rate at which interests are sent", type=rate_parser, default="0.00001")
    parser.add_argument("-v",
                        "--verbosity",
                        help="increase output verbosity",
                        choices=[0, 1, 2],
                        type=int,
                        default=0)
    parser.add_argument("-d",
                        "--demo",
                        help="enable demo mode (more intuitive printouts)",
                        action="store_true")

    args = parser.parse_args()

    # clean up prefix argument
    if len(args.prefix) > 1:
        args.prefix.pop(0)

    # create a list for storing dataframes
    final_data = []

    # run experiment once for provided prefix
    for namespace in args.prefix:
        consumer = Consumer(args.ipaddress, verbose=args.verbosity)
        #  TODO: add rate functionality back in if needed

        # run consumer and put output into dataframe
        final_data.append(consumer.run(namespace, args.time))

    # store output to file if filename option is enabled
    if args.filename is not None:
        i = 0
        for dataframe in final_data:
            dataframe.to_csv(args.filename + args.prefix[i].replace('/', '-') +
                             '.csv',
                             index=False)
            i += 1

    # print results to stdout
    if not args.demo:
        for dataframe in final_data:
            print(dataframe)

    # print modified results for demo
    if args.demo:
        for dataframe in final_data:
            print(dataframe[[
                'timestamp', 'packet_loss_percent',
                'total_data_goodput_kilobytes', 'bitrate_kbps', 'latency'
            ]])
            #  print(f"Average bitrate: {dataframe.bitrate_kbps.sum() / len(dataframe.index)} kbps")
            #  print(len(dataframe.index))
            #  print(f"Time to first byte: {dataframe.loc[0, 'time_to_first_byte_ms']} ms")

            # compute average bitrate
            total = num = 0
            for bitrate in dataframe['bitrate_kbps'].tolist():
                if bitrate != 0:
                    total += bitrate
                    num += 1
            print(f"Average bitrate: {total / num} kbps")

            # compute average latency
            total = num = 0
            for latency in dataframe['latency'].tolist():
                if latency != 0:
                    total += latency
                    num += 1
            print(f"Average latency: {total / num} ms")