Beispiel #1
0
class TestRegistrationCallbacks(ut.TestCase):
    def setUp(self):
        self.face = Face()
        keyChain = KeyChain()
        self.face.setCommandSigningInfo(
          keyChain, keyChain.getDefaultCertificateName())

    def tearDown(self):
        self.face.shutdown()

    def test_registration_callbacks(self):
        onRegisterFailed = Mock()
        onRegisterSuccess = Mock()

        self.face.registerPrefix(
          Name("/test/register/callbacks"), None, onRegisterFailed,
          onRegisterSuccess)

        while True:
            self.face.processEvents()
            time.sleep(0.01)
            if (onRegisterSuccess.call_count > 0 or onRegisterFailed.call_count > 0):
                break

        self.assertEqual(
          onRegisterSuccess.call_count, 1,
          "Expected 1 onRegisterSuccess callback, got " +
            str(onRegisterSuccess.call_count))
def 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()
Beispiel #3
0
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()
def main():
    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    counter = Counter()

    if sys.version_info[0] <= 2:
        word = raw_input("Enter a word to echo: ")
    else:
        word = input("Enter a word to echo: ")

    name = Name("/testecho")
    name.append(word)
    dump("Express name ", name.toUri())
    face.expressInterest(name, counter.onData, counter.onTimeout)

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

    face.shutdown()
def main():
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    keyChain = KeyChain(
      IdentityManager(identityStorage, privateKeyStorage), None)
    keyChain.setFace(face)

    # Initialize the storage.
    keyName = Name("/testname/DSK-123")
    certificateName = keyName.getSubName(0, keyName.size() - 1).append(
      "KEY").append(keyName[-1]).append("ID-CERT").append("0")
    identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER))
    privateKeyStorage.setKeyPairForKeyName(
      keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER)

    echo = Echo(keyChain, certificateName)
    prefix = Name("/testecho")
    dump("Register prefix", prefix.toUri())
    face.registerPrefix(prefix, echo.onInterest, echo.onRegisterFailed)

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

    face.shutdown()
Beispiel #6
0
def main():
    face = Face("localhost")

    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    keyChain = KeyChain(
      IdentityManager(identityStorage, privateKeyStorage), None)
    keyChain.setFace(face)

    # Initialize the storage.
    keyName = Name("/testname/DSK-reposerver")
    certificateName = keyName.getSubName(0, keyName.size() - 1).append(
      "KEY").append(keyName[-1]).append("ID-CERT").append("0")
    identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_PUBLIC_KEY_DER))
    privateKeyStorage.setKeyPairForKeyName(
      keyName, DEFAULT_PUBLIC_KEY_DER, DEFAULT_PRIVATE_KEY_DER)

    echo = RepoServer(keyChain, certificateName)
    prefix = Name("/ndn/ucla.edu/bms")
    dump("Register prefix", prefix.toUri())
    face.registerPrefix(prefix, echo.onInterest, echo.onRegisterFailed)

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

    face.shutdown()
Beispiel #7
0
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()
Beispiel #8
0
def main():
    """
    Call requestInsert and register a prefix so that ProduceSegments will answer
    interests from the repo to send the data packets. This assumes that repo-ng
    is already running (e.g. `sudo ndn-repo-ng`).
    """
    repoCommandPrefix = Name("/example/repo/1")
    repoDataPrefix = Name("/example/data/1")

    nowMilliseconds = int(time.time() * 1000.0)
    fetchPrefix = Name(repoDataPrefix).append("testinsert").appendVersion(nowMilliseconds)

    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()
    # Use the system default key chain and certificate name to sign commands.
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    # Register the prefix and send the repo insert command at the same time.
    startBlockId = 0
    endBlockId = 1
    enabled = [True]
    def onFinished():
        dump("All data was inserted.")
        enabled[0] = False
    produceSegments = ProduceSegments(
      keyChain, keyChain.getDefaultCertificateName(), startBlockId, endBlockId,
      onFinished)
    dump("Register prefix", fetchPrefix.toUri())
    def onRegisterFailed(prefix):
        dump("Register failed for prefix", prefix.toUri())
        enabled[0] = False
    face.registerPrefix(
      fetchPrefix, produceSegments.onInterest, onRegisterFailed)

    def onInsertStarted():
        dump("Insert started for", fetchPrefix.toUri())
    def onFailed():
        enabled[0] = False
    requestInsert(
      face, repoCommandPrefix, fetchPrefix, onInsertStarted, onFailed,
      startBlockId, endBlockId)

    # Run until all the data is sent.
    while enabled[0]:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)

    face.shutdown()
Beispiel #9
0
def main():
    """
    Call startRepoWatch and register a prefix so that SendSegments will answer
    interests from the repo to send data packets for the watched prefix.  When
    all the data is sent (or an error), call stopRepoWatch. This assumes that
    repo-ng is already running (e.g. `sudo ndn-repo-ng`).
    """
    repoCommandPrefix = Name("/example/repo/1")
    repoDataPrefix = Name("/example/data/1")

    nowMilliseconds = int(time.time() * 1000.0)
    watchPrefix = Name(repoDataPrefix).append("testwatch").appendVersion(
      nowMilliseconds)

    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()
    # Use the system default key chain and certificate name to sign commands.
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    # Register the prefix and start the repo watch at the same time.
    enabled = [True]
    def onFinishedSending():
        stopRepoWatchAndQuit(face, repoCommandPrefix, watchPrefix, enabled)
    sendSegments = SendSegments(
      keyChain, keyChain.getDefaultCertificateName(), onFinishedSending)
    def onRegisterFailed(prefix):
        dump("Register failed for prefix", prefix.toUri())
        enabled[0] = False
    dump("Register prefix", watchPrefix.toUri())
    face.registerPrefix(watchPrefix, sendSegments.onInterest, onRegisterFailed)

    def onRepoWatchStarted():
        dump("Watch started for", watchPrefix.toUri())
    def onStartFailed():
        dump("startRepoWatch failed.")
        stopRepoWatchAndQuit(face, repoCommandPrefix, watchPrefix, enabled)
    startRepoWatch(
      face, repoCommandPrefix, watchPrefix, onRepoWatchStarted, onStartFailed)

    # Run until someone sets enabled[0] = False.
    enabled[0] = True
    while enabled[0]:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)

    face.shutdown()
Beispiel #10
0
def main():
    face = Face()

    # Use the system default key chain and certificate name to sign commands.
    keyChain = KeyChain()
    certificateName = keyChain.getDefaultCertificateName()
    face.setCommandSigningInfo(keyChain, certificateName)
    test = DiscoveryTest(face, keyChain, certificateName)
    test.start()

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

    face.shutdown()
Beispiel #11
0
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()
Beispiel #12
0
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():
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    # Use the system default key chain and certificate name to sign commands.
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    # Also use the default certificate name to sign data packets.
    echo = Echo(keyChain, keyChain.getDefaultCertificateName())
    prefix = Name("/testecho")
    dump("Register prefix", prefix.toUri())
    face.registerPrefix(prefix, echo.onInterest, echo.onRegisterFailed)

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

    face.shutdown()
Beispiel #14
0
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 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 startPKG():
    global EXIT
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    pkg = PublicKeyGenerator(face, "/ndn/no/ntnu")

    while not EXIT:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
        isReady, _, _ = select.select([sys.stdin], [], [], 0)
        if len(isReady) != 0:
            input = promptAndInput("")
            if input == "r":
                sensorPull.requestData()
            if input == "leave" or input == "exit":
                EXIT = True
                break
    face.shutdown()
Beispiel #16
0
def main():
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    # Use the system default key chain and certificate name to sign commands.
    print("key1")
    keyChain = KeyChain()
    print("key2")
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    # Also use the default certificate name to sign data packets.
    echo = Echo(keyChain, keyChain.getDefaultCertificateName())
    prefix = Name("/testecho")
    dump("Register prefix", prefix.toUri())
    face.registerPrefix(prefix, echo.onInterest, echo.onRegisterFailed)

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

    face.shutdown()
Beispiel #17
0
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 startSensorPull():
    global EXIT
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    presharedKey = "gAJVrjM6R1RYT09MeE1XZXMxVzJiYWRuTXppaHIyamttRjNwdXJhTC9abnFKQTUrRU5DM1Z1eHB1YnpST1VBVTlVN2dvclZlT0ZmUDNPUkR1UkJaVldjNUh0dDVEOXcwNVJOUmFNV1YxeVFqTlUvNmo1Rk9LbU5RUmkrZWxORlNoRkxYbWtZZjdxS3ZWUlNGUU1najBoNkt1YW1IN1J4WWNYZ09wMlR4MUx4RnBXYlBFPXEALg=="
    sensorPull = Device(face, "/ndn/no/ntnu", "device1", presharedKey)
    sensorPull.requestIdentityBasedPrivateKey()
    while not EXIT:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
        isReady, _, _ = select.select([sys.stdin], [], [], 0)
        if len(isReady) != 0:
            input = promptAndInput("")
            if input == "r":
                sensorPull.requestData()
            if input == "leave" or input == "exit":
                EXIT = True
                break

    face.shutdown()
def startSensorData():
    global EXIT
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    presharedKey = "gAJVrjM6RjFCMGE3Y0VRaFh2RTdqSUZPT3R2ZFZEWFVubDVVRVlXMmlmbWVXczR3K0JTdG9TTlUxREk3TGQ1K1p0UkpkL0NVUG55c1M4ZzhXdDdKT2lKOWx4cUh3UVRtNDVWemlGWVdaQlV2cHMwZkpQWUNMc0RyeTFqUldMOEQ4YTcyaTZCTlhueXo3bitIa0ZFdm1wVzhFbE00UEtRc21KdTlTWmkybVRlVlZFaTNRPXEALg=="
    sensorData = Device(face, "/ndn/no/ntnu", "device2", presharedKey)
    sensorData.requestIdentityBasedPrivateKey()
    sensorData.registerPrefix()
    while not EXIT:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
        isReady, _, _ = select.select([sys.stdin], [], [], 0)
        if len(isReady) != 0:
            input = promptAndInput("")
            if input == "r":
                sensorPull.requestData()
            if input == "leave" or input == "exit":
                EXIT = True
                break
    face.shutdown()
Beispiel #20
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()
Beispiel #21
0
class Producer():
    """Hosts data under a certain namespace"""

    def __init__(self, data_size, verbose=False):
        # create a KeyChain for signing data packets
        self._key_chain = KeyChain()
        self._is_done = False
        self._num_interests = 0
        #  self._keyChain.createIdentityV2(Name("/ndn/identity"))

        # host data at the local forwarder
        self._face = Face()

        # immutable byte array to use as data
        self._byte_array = bytes(data_size)

        # the number of bytes contained in each data packet
        self._data_size = data_size

        # the verbosity of diagnostic information
        self._verbose = verbose

        # keep track of if the first interest has been recieved (for timing)
        self._is_first_interst = True

        # keep track of various performance metrics:
        self._interests_satisfied = 0
        self._interests_recieved = 0
        self._data_sent = 0
        self._elapsed_time = {}
        self._initial_time = {}
        self._final_time = {}

        print("Producer instance created.")


    def run(self, namespace):
        """Starts listening for interest packets in the given namespace."""

        prefix = Name(namespace)

        # Use the system default key chain and certificate name to sign commands.
        self._face.setCommandSigningInfo(self._key_chain, self._key_chain.getDefaultCertificateName())

        # Also use the default certificate name to sign Data packets.
        self._face.registerPrefix(prefix, self.onInterest, self.onRegisterFailed)

        dump("Registering prefix", prefix.toUri())

        print(f"Listening for interests under {namespace}...")

        # Run the event loop forever. Use a short sleep to
        # prevent the Producer from using 100% of the CPU.
        while not self._is_done:
            self._face.processEvents()
            time.sleep(0.01)

        # shutdown this face - TODO: figure out why this can't be done in the self.shutdown() method
        self._face.shutdown()


    def onInterest(self, prefix, interest, transport, registeredPrefixId):
        """Called when an interest for the specified name is recieved"""

        # keep track of when first interest was recieved
        self._initial_time['download_time'] = time.time()

        # set data to a byte array of a specified size
        interestName = interest.getName()
        data = Data(interestName)
        data.setContent(self._byte_array)

        # sign and send data
        data.getMetaInfo().setFreshnessPeriod(3600 * 1000)
        self._key_chain.sign(data, self._key_chain.getDefaultCertificateName())
        transport.send(data.wireEncode().toBuffer())

        # print additional information if verobse flag is set
        if self._verbose:
            dump("Replied to:", interestName.toUri())

        # increment appropriate variables
        self._interests_recieved += 1
        self._interests_satisfied += 1
        self._num_interests += 1


    def onRegisterFailed(self, prefix):
        """Called when forwarder can't register prefix."""
        dump("Register failed for prefix", prefix.toUri())
        self.shutdown()


    def shutdown(self):
        self._final_time['download_time'] = time.time()
        self._is_done = True
        self.print_status_report()


    def print_status_report(self):
        """Prints performance metrics for this producer."""

        # compute total data sent (in bytes)
        self._data_sent = self._interests_satisfied * self._data_size

        # compute timing
        for key, value in self._initial_time.items():
            self._elapsed_time[key] = self._final_time[key] - self._initial_time[key]

        # calculate bitrate of interests sent
        download_kbps = ((self._data_sent * 8) / 1000) / self._elapsed_time['download_time']


        print("\n----------------------------------")
        print(f"Number of interests recieved: {self._interests_recieved}")
        print(f"Number of interests satisfied: {self._interests_satisfied}")
        print("----------------------------------")
        # this probably isn't a useful metric, as the output interface will throttle this
        #  print(f"{self._data_sent / 1000} kilobytes sent for a bitrate of {download_kbps} kbps")
        print(f"{self._data_size * self._interests_satisfied} bytes of data sent.")
        print("----------------------------------\n")
Beispiel #22
0
        dump("Time out for interest", interest.getName().toUri())


if __name__ == "__main__":
    import sys
    arg = 1

    filename = sys.argv[1]

    try:
        name = sys.argv[2]
    except:
        name = "/endless/testchunks"

    name += "/chunked/"

    face = Face()
    chunks = Chunks(face, filename)

    # Try to fetch.
    name1 = Name(name).appendSegment(0)
    dump("Express name:", name1.toUri())
    face.expressInterest(name1, chunks.onData, chunks.onTimeout)

    while chunks._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()
Beispiel #23
0
class LightController():
    shouldSign = False
    COLORS_PER_LIGHT = 3
    STRAND_SIZE = 50
    def __init__(self, nStrands=1, myIP="192.168.1.1", lightIP="192.168.1.50", prefix="/testlight"):
        self.log = logging.getLogger("LightController")
        self.log.setLevel(logging.DEBUG)
        sh = logging.StreamHandler()
        sh.setLevel(logging.WARNING)
        self.log.addHandler(sh)
        fh = logging.FileHandler("LightController.log")
        fh.setLevel(logging.INFO)
        self.log.addHandler(fh)

        self.payloadBuffer = [[0]*self.STRAND_SIZE*self.COLORS_PER_LIGHT for n in range(nStrands)]

        self.kinetsender = KinetSender(myIP, lightIP, nStrands, self.STRAND_SIZE*self.COLORS_PER_LIGHT)
        self.registerFailed = False
        self.done = False
        self.prefix = Name(prefix)
        self.keychain = KeyChain()
        self.certificateName = self.keychain.getDefaultCertificateName()

    # XXX: we should get a thread for this or something!
    def start(self):
        self.face = Face()
        self.face.setCommandSigningInfo(self.keychain, self.certificateName)
        self.face.registerPrefix(self.prefix, self.onLightingCommand, self.onRegisterFailed)
        while self.face is not None:
            self.face.processEvents()
            if self.registerFailed:
                self.stop()
                break
            #time.sleep(0.001)


    def stop(self):
        self.kinetsender.stop = True
        self.kinetsender.complete.wait()         
        self.face.shutdown()
        self.face = None

    def signData(self, data):
        if LightController.shouldSign:
            self.keychain.sign(data, self.certificateName)
        else:
            data.setSignature(Sha256WithRsaSignature())

    def setPayloadColor(self, strand, color):
        # will expand this to allow the repeats, etc
        self.payloadBuffer[strand] = [int(color.r)&0xff, int(color.g)&0xff, int(color.b)&0xff]*self.STRAND_SIZE

    def onLightingCommand(self, prefix, interest, transport, prefixId):
        interestName = Name(interest.getName())
        #d = Data(interest.getName().getPrefix(prefix.size()+1))
        d = Data(interest.getName())
        # get the command parameters from the name
        try:
            commandComponent = interest.getName().get(prefix.size())
            commandParams = interest.getName().get(prefix.size()+1)

            lightingCommand = LightCommandMessage()
            ProtobufTlv.decode(lightingCommand, commandParams.getValue())
            self.log.info("Command: " + commandComponent.toEscapedString())
            requestedColor = lightingCommand.command.pattern.colors[0] 
            colorStr = str((requestedColor.r, requestedColor.g, requestedColor.b))
            self.log.info("Requested color: " + colorStr)
            self.setPayloadColor(0, requestedColor)
            self.sendLightPayload(1)
            d.setContent("Gotcha: " + colorStr+ "\n")
        except Exception as e:
            print e
            d.setContent("Bad command\n")
        finally:
            d.getMetaInfo().setFinalBlockID(0)
            self.signData(d)

        encodedData = d.wireEncode()
        transport.send(encodedData.toBuffer())

    def onRegisterFailed(self, prefix):
        self.log.error("Could not register " + prefix.toUri())
        print "Register failed!"
        self.registerFailed = True

    def sendLightPayload(self, port):
        self.kinetsender.setPayload(port, self.payloadBuffer[port-1])
Beispiel #24
0
class Server:
    def __init__(self, deeplab_manager, fst_manager, _root_path, storage):
        # type: (DeepLab, Fst, str, IStorage) -> None
        self.face = None
        self.keychain = KeyChain()
        # self.namespace = Namespace(Name(SERVER_PREFIX).append(RESULT_PREFIX), self.keychain)
        # self.namespace.addOnObjectNeeded(self.on_result_interest)
        self.segment_size = Face.getMaxNdnPacketSize() // 2

        self.running = False
        self._restart = False

        self.deeplab_manager = deeplab_manager
        self.fst_manager = fst_manager
        self.storage = storage
        deeplab_manager.on_finished = self.on_process_finished
        fst_manager.on_finished = self.on_process_finished

        self.fetcher = Fetcher(self.keychain, self.on_payload, self.storage, self.on_fetch_fail)

        self.command_filter_id = 0
        self.result_filter_id = 0

        self.operations_set = self.fst_manager.get_models() | {"deeplab"}
        # Status set, one item per frame
        # TODO: Start with unfinished tasks
        # self.status_set = {}

    def save_status(self, name, status):
        # type: (Name, ResultStatus) -> None
        """Save status to database"""
        self.storage.put(Name(STATUS_PREFIX).append(name), status.to_bytes())

    def load_status(self, name):
        """Load status from database"""
        # Get exact prefix to data
        if name[-1] == Name.Component("_meta") or name[-1].isSegment():
            name = name[:-1]
        ret = self.storage.get(Name(STATUS_PREFIX).append(name))
        if ret is not None:
            return ResultStatus.from_bytes(ret)
        else:
            return None

    async def _run(self):
        self.running = True
        while self.running:
            self.face = Face()
            self._restart = False
            try:
                self._network_start()
                logging.info("Starting...")
                while self.running and not self._restart:
                    self.face.processEvents()
                    await asyncio.sleep(0.01)
            except ConnectionRefusedError:
                logging.warning("Connection refused. Retry in %ss.", DISCONN_RETRY_TIME)
            finally:
                self.face.shutdown()
                self._network_stop()
            if self.running:
                time.sleep(DISCONN_RETRY_TIME)

    def run(self):
        event_loop = asyncio.get_event_loop()
        try:
            event_loop.run_until_complete(self._run())
        finally:
            event_loop.close()

    def stop(self):
        self.running = False

    def _network_start(self):
        self.face.setCommandSigningInfo(self.keychain, self.keychain.getDefaultCertificateName())
        # self.namespace.setFace(self.face, lambda prefix: print("Register failed for"))

        self.face.registerPrefix(Name(SERVER_PREFIX), None, self.on_register_failed)
        self.command_filter_id = self.face.setInterestFilter(
            Name(SERVER_PREFIX).append(COMMAND_PREFIX), self.on_command)
        self.result_filter_id = self.face.setInterestFilter(
            Name(SERVER_PREFIX).append(RESULT_PREFIX), self.on_result_interest)
        self.fetcher.network_start(self.face)

    def _network_stop(self):
        self.fetcher.network_stop()
        self.face.unsetInterestFilter(self.result_filter_id)
        self.face.unsetInterestFilter(self.command_filter_id)

    def on_register_failed(self, prefix):
        # type: (Name) -> None
        logging.error("Register failed for prefix: %s", prefix.toUri())
        self._restart = True

    def on_command(self, _prefix, interest, _face, _interest_filter_id, _filter_obj):
        # type: (Name, Interest, Face, int, InterestFilter) -> None
        parameter_msg = SegmentParameterMessage()
        try:
            ProtobufTlv.decode(parameter_msg, interest.name[-1].getValue())
        except ValueError:
            self.nodata_reply(interest.name, RET_MALFORMED_COMMAND)
            return

        parameter = parameter_msg.segment_parameter
        prefix = Name()
        for compo in parameter.name.component:
            prefix.append(compo.decode("utf-8"))

        # Check operations
        for op in parameter.operations.components:
            model_name = op.model.decode("utf-8")
            if model_name not in self.operations_set:
                self.nodata_reply(interest.name, RET_NOT_SUPPORTED)
                return

        # Fetch frames
        for frame_id in range(parameter.start_frame, parameter.end_frame + 1):
            frame_name = Name(prefix).append(str(frame_id))
            for op in parameter.operations.components:
                model_name = op.model.decode("utf-8")
                data_name = Name(frame_name).append(model_name)
                logging.info("Request processed: %s", data_name)
                status = ResultStatus(prefix.toUri(), model_name, Common.getNowMilliseconds())
                status.status = STATUS_FETCHING
                status.estimated_time = status.proecess_start_time + 10.0
                self.save_status(data_name, status)

        # Check data existence and trigger fetching process
        for frame_id in range(parameter.start_frame, parameter.end_frame + 1):
            frame_name = Name(prefix).append(str(frame_id))
            if self.storage.exists(frame_name):
                self.on_payload(frame_name)
            else:
                self.fetcher.fetch_data(frame_name)

        self.nodata_reply(interest.name, RET_OK, 10.0)

    # def on_result_interest(self, _namespace, needed_obj, _id):
    #     # type: (Namespace, Namespace, int) -> bool
    def on_result_interest(self, _prefix, interest, face, _interest_filter_id, _filter_obj):
        # type: (Name, Interest, Face, int, InterestFilter) -> bool
        prefix = Name(SERVER_PREFIX).append(RESULT_PREFIX)
        if not prefix.isPrefixOf(interest.name):
            # Wrong prefix
            return False

        data_name = interest.name[prefix.size():]
        logging.info("On result interest: %s", data_name.toUri())
        # key, stat = self._result_set_prefix_match(data_name)
        status = self.load_status(data_name)
        if status is None:
            # No such request
            self.nodata_reply(interest.name, RET_NO_REQUEST)
            return True

        if data_name[-1].isSegment():
            # Segment no suffix
            seg_no = data_name[-1].toSegment()
            result = self.storage.get(data_name.getPrefix(-1))
        elif data_name[-1] == Name("_meta")[0]:
            # MetaInfo suffix
            seg_no = -1
            result = self.storage.get(data_name.getPrefix(-1))
        else:
            # No suffix
            seg_no = None
            result = self.storage.get(data_name)

        if result is not None:
            # There are data
            segment_cnt = (len(result) + self.segment_size - 1) // self.segment_size
            # Note: I don't understand why namespace keep all data in memory
            metainfo = MetaInfo()
            # metainfo.setFinalBlockId(segment_cnt - 1) # WHY this doesn't work?
            metainfo.setFinalBlockId(Name().appendSegment(segment_cnt - 1)[0])
            if segment_cnt > 1 and seg_no is None:
                # Fetch segmented data with no suffix will get only first segment
                seg_no = 0
                data_name.appendSequenceNumber(seg_no)

            data = Data(Name(prefix).append(data_name))
            data.setMetaInfo(metainfo)
            if seg_no == -1:
                # _meta
                data.content = self.storage.get(data_name)
            else:
                # data
                if segment_cnt > 1:
                    # Segmented
                    if seg_no < segment_cnt:
                        start_offset = seg_no * self.segment_size
                        end_offset = start_offset + self.segment_size
                        data.content = Blob(bytearray(result[start_offset:end_offset]))
                    else:
                        data.content = None
                else:
                    # No segmentation
                    data.content = Blob(bytearray(result))

            self.keychain.sign(data)
            face.putData(data)
            return True
        else:
            # Data are not ready
            if status.status == STATUS_NO_INPUT:
                self.nodata_reply(interest.name, RET_NO_INPUT)
            elif status.status == STATUS_FAILED:
                self.nodata_reply(interest.name, RET_EXECUTION_FAILED)
            else:
                self.nodata_reply(interest.name, RET_RETRY_AFTER, status.estimated_time - Common.getNowMilliseconds())
            return True

    def nodata_reply(self, name, code, retry_after=0.0):
        # type: (Name, int, float) -> None
        logging.info("Reply with code: %s", code)
        data = Data(name)
        metainfo = MetaInfo()
        msg = ServerResponseMessage()
        msg.server_response.ret_code = code

        if code != RET_OK:
            metainfo.type = ContentType.NACK
        else:
            metainfo.type = ContentType.BLOB
        if retry_after > 0.1:
            metainfo.freshnessPeriod = int(retry_after / 10)
            msg.server_response.retry_after = int(retry_after)
        else:
            metainfo.freshnessPeriod = 600

        data.setMetaInfo(metainfo)
        data.setContent(ProtobufTlv.encode(msg))

        self.keychain.sign(data)
        self.face.putData(data)

    def on_payload(self, frame_name):
        # type: (Name) -> None
        for model in self.operations_set:
            data_name = Name(frame_name).append(model)
            status = self.load_status(data_name)
            if status is None:
                continue
            if self.storage.exists(data_name):
                logging.info("Result exists: %s", data_name.toUri())
                continue
            logging.info("Ready to produce: %s", data_name.toUri())
            status.proecess_start_time = Common.getNowMilliseconds()

            if model == "deeplab":
                ret = self.deeplab_manager.send(DeepLabRequest(frame_name.toUri()[1:],
                                                               frame_name.toUri(),
                                                               data_name))
            else:
                ret = self.fst_manager.send(FstRequest(frame_name.toUri()[1:],
                                                       model,
                                                       frame_name.toUri(),
                                                       data_name))
            status.status = STATUS_PROCESSING if ret else STATUS_FAILED
            self.save_status(data_name, status)

    def on_process_finished(self, name_str, model_name):
        # type: (str, str) -> None
        data_name = Name(name_str).append(model_name)
        logging.info("Process finished: %s", data_name.toUri())
        status = self.load_status(data_name)
        if status is None:
            logging.fatal("Database broken.")
            raise RuntimeError()
        status.end_time = Common.getNowMilliseconds()
        status.status = STATUS_SUCCEED

        meta_name = Name(data_name).append("_meta")
        content_metainfo = ContentMetaInfo()
        content_metainfo.setContentType("png")
        content_metainfo.setTimestamp(status.end_time)
        content_metainfo.setHasSegments(True)
        self.storage.put(meta_name, content_metainfo.wireEncode().toBytes())

    def on_fetch_fail(self, frame_name):
        logging.error("Fail to fetch: {}".format(frame_name))
        for model in self.operations_set:
            data_name = Name(frame_name).append(model)
            status = self.load_status(data_name)
            if status is None:
                continue
            status.status = STATUS_NO_INPUT
            self.save_status(data_name, status)
            if shouldCollectStats:
                insertTable.append({'version':versionStr, 'insert_request':time.time()})
            data = generateData(fullName)
            dataCache.add(data)

            if shouldCollectStats:
                info = getInfoForVersion(versionStr)
                if info is not None:
                    info['insert_complete'] = time.time()
            time.sleep(0.1)
            print '.',
            sys.stdout.flush()
    except Exception as e:
        print e
        tb = traceback.format_exc()
    except KeyboardInterrupt:
        pass
    else:
        pass
    finally:
        done = True
        time.sleep(0.5)
        if tb is not None:
            print tb
        if shouldCollectStats:
            collectStats(insertTable)
        publisher_face.shutdown()
    
    
class TestConfigPolicyManager(ut.TestCase):
    def setUp(self):
        testCertDirectory = 'policy_config/certs'
        self.testCertFile = os.path.join(testCertDirectory, 'test.cert')

        self.identityStorage = MemoryIdentityStorage()
        self.privateKeyStorage = MemoryPrivateKeyStorage()
        self.identityManager = IdentityManager(self.identityStorage,
                self.privateKeyStorage)
        self.policyManager = ConfigPolicyManager('policy_config/simple_rules.conf')

        self.identityName = Name('/TestConfigPolicyManager/temp')
        # to match the anchor cert
        keyName = Name(self.identityName).append('ksk-1416010123')
        self.privateKeyStorage.setKeyPairForKeyName(
          keyName, KeyType.RSA, TEST_RSA_PUBLIC_KEY_DER, TEST_RSA_PRIVATE_KEY_DER)
        self.identityStorage.addKey(
          keyName, KeyType.RSA, Blob(TEST_RSA_PUBLIC_KEY_DER))

        cert = self.identityManager.selfSign(keyName)
        self.identityStorage.setDefaultKeyNameForIdentity(keyName)
        self.identityManager.addCertificateAsDefault(cert)

        self.keyChain = KeyChain(self.identityManager, self.policyManager)
        self.keyName = keyName

        self.face = Face()

    def tearDown(self):
        self.privateKeyStorage.deleteKeyPair(self.keyName)
        self.face.shutdown()
        try:
            os.remove(self.testCertFile)
        except OSError:
            pass

    def test_no_verify(self):
        policyManager = NoVerifyPolicyManager()
        identityName = Name('TestValidator/Null').appendVersion(int(time.time()))

        keyChain = KeyChain(self.identityManager, policyManager)
        keyChain.createIdentityAndCertificate(identityName)
        data = Data(Name(identityName).append('data'))
        keyChain.signByIdentity(data, identityName)

        vr = doVerify(policyManager, data)

        self.assertFalse(vr.hasFurtherSteps,
                "NoVerifyPolicyManager returned a ValidationRequest")

        self.assertEqual(vr.failureCount, 0,
            "Verification failed with NoVerifyPolicyManager")
        self.assertEqual(vr.successCount, 1,
            "Verification success called {} times instead of 1".format(
            vr.successCount))

    def test_self_verification(self):
        policyManager = SelfVerifyPolicyManager(self.identityStorage)
        keyChain = KeyChain(self.identityManager, policyManager)

        identityName  = Name('TestValidator/RsaSignatureVerification')
        keyChain.createIdentityAndCertificate(identityName)

        data = Data(Name('/TestData/1'))
        keyChain.signByIdentity(data, identityName)

        vr = doVerify(policyManager, data)

        self.assertFalse(vr.hasFurtherSteps,
                "SelfVerifyPolicyManager returned a ValidationRequest")
        self.assertEqual(vr.failureCount, 0,
            "Verification of identity-signed data failed")
        self.assertEqual(vr.successCount, 1,
            "Verification success called {} times instead of 1".format(
            vr.successCount))

        data2 = Data(Name('/TestData/2'))

        vr = doVerify(policyManager,
                data2)

        self.assertFalse(vr.hasFurtherSteps,
                "SelfVerifyPolicyManager returned a ValidationRequest")
        self.assertEqual(vr.successCount, 0,
            "Verification of unsigned data succeeded")
        self.assertEqual(vr.failureCount, 1,
            "Verification failure callback called {} times instead of 1".format(
            vr.failureCount))

    def test_interest_timestamp(self):
        interestName = Name('/ndn/ucla/edu/something')
        certName = self.identityManager.getDefaultCertificateNameForIdentity(
                self.identityName)
        self.face.setCommandSigningInfo(self.keyChain, certName)

        oldInterest = Interest(interestName)
        self.face.makeCommandInterest(oldInterest)

        time.sleep(0.1) # make sure timestamps are different
        newInterest = Interest(interestName)
        self.face.makeCommandInterest(newInterest)

        vr  = doVerify(self.policyManager,
                newInterest)

        self.assertFalse(vr.hasFurtherSteps,
                "ConfigPolicyManager returned ValidationRequest but certificate is known")
        self.assertEqual(vr.failureCount, 0,
                "Verification of valid interest failed")
        self.assertEqual(vr.successCount, 1,
                "Verification success called {} times instead of 1".format(
                      vr.successCount))

        vr  = doVerify(self.policyManager,
                oldInterest)

        self.assertFalse(vr.hasFurtherSteps,
                "ConfigPolicyManager returned ValidationRequest but certificate is known")
        self.assertEqual(vr.successCount, 0,
                "Verification of stale interest succeeded")
        self.assertEqual(vr.failureCount, 1,
                "Failure callback called {} times instead of 1".format(
                      vr.failureCount))

    def _removeFile(self, filename):
        try:
            os.remove(filename)
        except OSError:
            # no such file
            pass

    def test_refresh_10s(self):
        with open('policy_config/testData', 'r') as dataFile:
            encodedData = dataFile.read()
            data = Data()
            dataBlob = Blob(b64decode(encodedData))
            data.wireDecode(dataBlob)

        # needed, since the KeyChain will express interests in unknown
        # certificates
        vr = doVerify(self.policyManager, data)

        self.assertTrue(vr.hasFurtherSteps,
                "ConfigPolicyManager did not create ValidationRequest for unknown certificate")
        self.assertEqual(vr.successCount, 0,
                "ConfigPolicyManager called success callback with pending ValidationRequest")
        self.assertEqual(vr.failureCount, 0,
                "ConfigPolicyManager called failure callback with pending ValidationRequest")

        # now save the cert data to our anchor directory, and wait
        # we have to sign it with the current identity or the
        # policy manager will create an interest for the signing certificate

        with open(self.testCertFile, 'w') as certFile:
            cert = IdentityCertificate()
            certData = b64decode(CERT_DUMP)
            cert.wireDecode(Blob(certData, False))
            self.keyChain.signByIdentity(cert, self.identityName)
            encodedCert = b64encode(cert.wireEncode().toBytes())
            certFile.write(Blob(encodedCert, False).toRawStr())

        # still too early for refresh to pick it up
        vr = doVerify(self.policyManager, data)

        self.assertTrue(vr.hasFurtherSteps,
                "ConfigPolicyManager refresh occured sooner than specified")
        self.assertEqual(vr.successCount, 0,
                "ConfigPolicyManager called success callback with pending ValidationRequest")
        self.assertEqual(vr.failureCount, 0,
                "ConfigPolicyManager called failure callback with pending ValidationRequest")
        time.sleep(6)

        # now we should find it
        vr  = doVerify(self.policyManager, data)

        self.assertFalse(vr.hasFurtherSteps,
                "ConfigPolicyManager did not refresh certificate store")
        self.assertEqual(vr.successCount, 1,
                "Verification success called {} times instead of 1".format(
                    vr.successCount))
        self.assertEqual(vr.failureCount, 0,
                "ConfigPolicyManager did not verify valid signed data")
Beispiel #27
0
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, face, interestFilterId, filter):
            interestCallbackCount[0] += 1
            data = Data(interest.getName())
            data.setContent("SUCCESS")
            self.keyChain.sign(data, self.keyChain.getDefaultCertificateName())
            face.putData(data)

        failedCallback = Mock()

        self.face_in.registerPrefix(prefixName, onInterest, failedCallback)
        # Give the 'server' time to register the interest.
        timeout = 1000
        startTime = getNowMilliseconds()
        while True:
            if getNowMilliseconds() - startTime >= timeout:
                break
            self.face_in.processEvents()
            time.sleep(0.01)

        # 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')
Beispiel #28
0
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')
Beispiel #29
0
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
Beispiel #30
0
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())
Beispiel #31
0
class TestFaceInterestMethods(ut.TestCase):
    def setUp(self):
        self.face = Face("localhost")

    def tearDown(self):
        self.face.shutdown()

    def run_express_name_test(self, interestName, useOnNack = False):
        # 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()
        onNackCallback = Mock()

        if useOnNack:
            self.face.expressInterest(
              name, dataCallback, timeoutCallback, onNackCallback)
        else:
            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 or
                onNackCallback.call_count > 0):
                break

        return dataCallback, timeoutCallback, onNackCallback

    def test_any_interest(self):
        uri = "/"
        (dataCallback, timeoutCallback, onNackCallback) = 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, onNackCallback) = 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, onNackCallback) = 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:
            if getNowMilliseconds() - startTime >= timeout:
                break
            self.face.processEvents()
            if (dataCallback.call_count > 0 or timeoutCallback.call_count > 0):
                break
            time.sleep(0.01)

        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())

    def test_network_nack(self):
        uri = "/noroute" + str(getNowMilliseconds())
        (dataCallback, timeoutCallback, onNackCallback) = self.run_express_name_test(
          uri, True)

        # We're expecting a network Nack callback, and only 1.
        self.assertEqual(dataCallback.call_count, 0,
          "Data callback called for unroutable interest")
        self.assertEqual(timeoutCallback.call_count, 0,
          "Timeout callback called for unroutable interest")
        self.assertEqual(onNackCallback.call_count, 1,
          "Expected 1 network Nack call")

        # The args are returned as ([ordered arguments], [keyword arguments])
        onNetworkNackArgs = onNackCallback.call_args[0]

        callbackNetworkNack = onNetworkNackArgs[1]
        self.assertEqual(callbackNetworkNack.getReason(), NetworkNack.Reason.NO_ROUTE,
          "Network Nack has unexpected reason")
Beispiel #32
0
class TestConfigPolicyManager(ut.TestCase):
    def setUp(self):
        testCertDirectory = 'policy_config/certs'
        self.testCertFile = os.path.join(testCertDirectory, 'test.cert')

        # Reuse the policy_config subdirectory for the temporary SQLite file.
        self.databaseFilePath = "policy_config/test-public-info.db"
        try:
            os.remove(self.databaseFilePath)
        except OSError:
            # no such file
            pass

        self.identityStorage = BasicIdentityStorage(self.databaseFilePath)
        self.privateKeyStorage = MemoryPrivateKeyStorage()
        self.identityManager = IdentityManager(self.identityStorage,
                self.privateKeyStorage)
        self.policyManager = ConfigPolicyManager('policy_config/simple_rules.conf')

        self.identityName = Name('/TestConfigPolicyManager/temp')
        # to match the anchor cert
        keyName = Name(self.identityName).append('ksk-1416010123')
        self.privateKeyStorage.setKeyPairForKeyName(
          keyName, KeyType.RSA, TEST_RSA_PUBLIC_KEY_DER, TEST_RSA_PRIVATE_KEY_DER)
        self.identityStorage.addKey(
          keyName, KeyType.RSA, Blob(TEST_RSA_PUBLIC_KEY_DER))

        cert = self.identityManager.selfSign(keyName)
        self.identityStorage.setDefaultKeyNameForIdentity(keyName)
        self.identityManager.addCertificateAsDefault(cert)

        self.keyChain = KeyChain(self.identityManager, self.policyManager)
        self.keyName = keyName

        self.face = Face()

    def tearDown(self):
        try:
            os.remove(self.databaseFilePath)
        except OSError:
            pass
        self.privateKeyStorage.deleteKeyPair(self.keyName)
        self.face.shutdown()
        try:
            os.remove(self.testCertFile)
        except OSError:
            pass

    def test_no_verify(self):
        policyManager = NoVerifyPolicyManager()
        identityName = Name('TestValidator/Null').appendVersion(int(time.time()))

        keyChain = KeyChain(self.identityManager, policyManager)
        keyChain.createIdentityAndCertificate(identityName)
        data = Data(Name(identityName).append('data'))
        keyChain.signByIdentity(data, identityName)

        vr = doVerify(policyManager, data)

        self.assertFalse(vr.hasFurtherSteps,
                "NoVerifyPolicyManager returned a ValidationRequest")

        self.assertEqual(vr.failureCount, 0,
            "Verification failed with NoVerifyPolicyManager")
        self.assertEqual(vr.successCount, 1,
            "Verification success called {} times instead of 1".format(
            vr.successCount))

    def test_self_verification(self):
        policyManager = SelfVerifyPolicyManager(self.identityStorage)
        keyChain = KeyChain(self.identityManager, policyManager)

        identityName  = Name('TestValidator/RsaSignatureVerification')
        keyChain.createIdentityAndCertificate(identityName)

        data = Data(Name('/TestData/1'))
        keyChain.signByIdentity(data, identityName)

        vr = doVerify(policyManager, data)

        self.assertFalse(vr.hasFurtherSteps,
                "SelfVerifyPolicyManager returned a ValidationRequest")
        self.assertEqual(vr.failureCount, 0,
            "Verification of identity-signed data failed")
        self.assertEqual(vr.successCount, 1,
            "Verification success called {} times instead of 1".format(
            vr.successCount))

        data2 = Data(Name('/TestData/2'))

        vr = doVerify(policyManager,
                data2)

        self.assertFalse(vr.hasFurtherSteps,
                "SelfVerifyPolicyManager returned a ValidationRequest")
        self.assertEqual(vr.successCount, 0,
            "Verification of unsigned data succeeded")
        self.assertEqual(vr.failureCount, 1,
            "Verification failure callback called {} times instead of 1".format(
            vr.failureCount))

    def test_interest_timestamp(self):
        interestName = Name('/ndn/ucla/edu/something')
        certName = self.identityManager.getDefaultCertificateNameForIdentity(
                self.identityName)
        self.face.setCommandSigningInfo(self.keyChain, certName)

        oldInterest = Interest(interestName)
        self.face.makeCommandInterest(oldInterest)

        time.sleep(0.1) # make sure timestamps are different
        newInterest = Interest(interestName)
        self.face.makeCommandInterest(newInterest)

        vr  = doVerify(self.policyManager,
                newInterest)

        self.assertFalse(vr.hasFurtherSteps,
                "ConfigPolicyManager returned ValidationRequest but certificate is known")
        self.assertEqual(vr.failureCount, 0,
                "Verification of valid interest failed")
        self.assertEqual(vr.successCount, 1,
                "Verification success called {} times instead of 1".format(
                      vr.successCount))

        vr  = doVerify(self.policyManager,
                oldInterest)

        self.assertFalse(vr.hasFurtherSteps,
                "ConfigPolicyManager returned ValidationRequest but certificate is known")
        self.assertEqual(vr.successCount, 0,
                "Verification of stale interest succeeded")
        self.assertEqual(vr.failureCount, 1,
                "Failure callback called {} times instead of 1".format(
                      vr.failureCount))

    def _removeFile(self, filename):
        try:
            os.remove(filename)
        except OSError:
            # no such file
            pass

    def test_refresh_10s(self):
        with open('policy_config/testData', 'r') as dataFile:
            encodedData = dataFile.read()
            data = Data()
            dataBlob = Blob(b64decode(encodedData))
            data.wireDecode(dataBlob)

        # needed, since the KeyChain will express interests in unknown
        # certificates
        vr = doVerify(self.policyManager, data)

        self.assertTrue(vr.hasFurtherSteps,
                "ConfigPolicyManager did not create ValidationRequest for unknown certificate")
        self.assertEqual(vr.successCount, 0,
                "ConfigPolicyManager called success callback with pending ValidationRequest")
        self.assertEqual(vr.failureCount, 0,
                "ConfigPolicyManager called failure callback with pending ValidationRequest")

        # now save the cert data to our anchor directory, and wait
        # we have to sign it with the current identity or the
        # policy manager will create an interest for the signing certificate

        with open(self.testCertFile, 'w') as certFile:
            cert = IdentityCertificate()
            certData = b64decode(CERT_DUMP)
            cert.wireDecode(Blob(certData, False))
            self.keyChain.signByIdentity(cert, self.identityName)
            encodedCert = b64encode(cert.wireEncode().toBuffer())
            certFile.write(Blob(encodedCert, False).toRawStr())

        # still too early for refresh to pick it up
        vr = doVerify(self.policyManager, data)

        self.assertTrue(vr.hasFurtherSteps,
                "ConfigPolicyManager refresh occured sooner than specified")
        self.assertEqual(vr.successCount, 0,
                "ConfigPolicyManager called success callback with pending ValidationRequest")
        self.assertEqual(vr.failureCount, 0,
                "ConfigPolicyManager called failure callback with pending ValidationRequest")
        time.sleep(6)

        # now we should find it
        vr  = doVerify(self.policyManager, data)

        self.assertFalse(vr.hasFurtherSteps,
                "ConfigPolicyManager did not refresh certificate store")
        self.assertEqual(vr.successCount, 1,
                "Verification success called {} times instead of 1".format(
                    vr.successCount))
        self.assertEqual(vr.failureCount, 0,
                "ConfigPolicyManager did not verify valid signed data")
Beispiel #33
0
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')
Beispiel #34
0
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
Beispiel #35
0
    else:
        timing.append(done-start)


if __name__ == '__main__':
    face = Face()
    if shouldSign:
        face.setCommandSigningInfo(keychain, certName)
    input = None
    N = 0
    try:
        while True:
            byteVal = (N)&0xff
            color = (0,0,0)
            selector = (N/256)%0x3
            if selector == 1:
                color = (byteVal, 0, 0)
            elif selector == 2:
                color = (0, byteVal, 0)
            elif selector == 0:
                color = (0, 0, byteVal)

            interest = createCommandInterest(color=color)
            waitForResponse(face, interest, None)
            N += 10
    except KeyboardInterrupt:
        pass
    face.shutdown()
    print "Response time: {:3.2f}/{:3.2f}/{:3.2f}s min/mean/max".format(min(timing), mean(timing), max(timing))
    print str(timeouts) + " timeouts"
Beispiel #36
0
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'
        )
Beispiel #37
0
def main():
    """
    Call startRepoWatch and register a prefix so that SendSegments will answer
    interests from the repo to send data packets for the watched prefix.  When
    all the data is sent (or an error), call startRepoWatch.
    """
    repoCommandPrefix = Name("/ndn/edu/ucla/remap/bms-repo/1")
    repoDataPrefix = Name("/ndn/edu/ucla/remap/bms")

    nowMilliseconds = int(time.time() * 1000.0)
    watchPrefix = Name(repoDataPrefix).append("testwatch").appendVersion(
        nowMilliseconds)

    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()
    # Use the system default key chain and certificate name to sign commands.
    from pyndn.security.identity import IdentityManager, FilePrivateKeyStorage, BasicIdentityStorage

    keyChain = KeyChain(
        IdentityManager(BasicIdentityStorage(), FilePrivateKeyStorage()))
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    # Register the prefix and start the repo watch at the same time.
    enabled = [True]
    sendSegments = SendSegments(keyChain, keyChain.getDefaultCertificateName(),
                                enabled)
    dump("Register prefix", watchPrefix.toUri())
    face.registerPrefix(watchPrefix, sendSegments.onInterest,
                        sendSegments.onRegisterFailed)
    print("Here")

    def onRepoWatchStarted():
        dump("Watch started for", watchPrefix.toUri())

    def onFailed():
        enabled[0] = False

    startRepoWatch(face, repoCommandPrefix, watchPrefix, onRepoWatchStarted,
                   onFailed)

    # Run until all the data is sent.
    while enabled[0]:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)

    def onRepoWatchStopped():
        dump("Watch stopped for", watchPrefix.toUri())
        enabled[0] = False

    stopRepoWatch(face, repoCommandPrefix, watchPrefix, onRepoWatchStopped,
                  onFailed)

    # Run until stopRepoWatch finishes.
    enabled[0] = True
    while enabled[0]:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)

    face.shutdown()