Esempio n. 1
0
    def start(self):
        """
        Begins the event loop. After this, the node's Face is set up and it can
        send/receive interests+data
        """
        self.log.info("Starting up")
        self.loop = asyncio.get_event_loop()
        
        if (self.faceTransport == None or self.faceTransport == ''):
            self.face = ThreadsafeFace(self.loop)
        else:
            self.face = ThreadsafeFace(self.loop, self.faceTransport, self.faceConn)
        
        self.face.setCommandSigningInfo(self._keyChain, self.getDefaultCertificateName())
        
        self._keyChain.setFace(self.face)

        self._isStopped = False
        self.beforeLoopStart()
        
        try:
            self.loop.run_forever()
        except Exception as e:
            self.log.exception(exc_info=True)
        finally:
            self.stop()
Esempio n. 2
0
def main():
    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

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

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

    # Try to fetch anything.
    name1 = Name("/")
    dump("Express name ", name1.toUri())
    # These call to exressIinterest is thread safe because face is a ThreadsafeFace.
    face.expressInterest(name1, counter.onData, counter.onTimeout)

    # Try to fetch using a known name.
    name2 = Name("/ndn/edu/ucla/remap/demo/ndn-js-test/hello.txt/%FDU%8D%9DM")
    dump("Express name ", name2.toUri())
    face.expressInterest(name2, counter.onData, counter.onTimeout)

    # Expect this to time out.
    name3 = Name("/test/timeout")
    dump("Express name ", name3.toUri())
    face.expressInterest(name3, counter.onData, counter.onTimeout)

    # Run until the Counter calls stop().
    loop.run_forever()
    face.shutdown()
Esempio n. 3
0
def main():
    loop = asyncio.get_event_loop()
    # Connect to the demo host at memoria.ndn.ucla.edu .
    face = ThreadsafeFace(loop, "128.97.98.8")

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

    # Try to fetch anything.
    name1 = Name("/")
    dump("Express name ", name1.toUri())
    # These call to exressIinterest is thread safe because face is a ThreadsafeFace.
    face.expressInterest(name1, counter.onData, counter.onTimeout)

    # Try to fetch using a known name.
    name2 = Name("/ndn/edu/ucla/remap/demo/ndn-js-test/hello.txt/%FDX%DC5%1F")
    dump("Express name ", name2.toUri())
    face.expressInterest(name2, counter.onData, counter.onTimeout)

    # Expect this to time out.
    name3 = Name("/test/timeout")
    dump("Express name ", name3.toUri())
    face.expressInterest(name3, counter.onData, counter.onTimeout)

    # Run until the Counter calls stop().
    loop.run_forever()
    face.shutdown()
Esempio n. 4
0
 def __init__(self, host):
     self.__name__ = __name__
     self.keyChain = KeyChain()
     self.isDone = False
     self.counter = 0
     loop = asyncio.get_event_loop()
     self.face = ThreadsafeFace(loop, host)
     self.a = {}
     self.methods = {}
def main():
    # Params parsing
    parser = argparse.ArgumentParser(
        description=
        'bms gateway node to Parse or follow Cascade Datahub log and publish to MiniNdn.'
    )
    parser.add_argument('filename', help='datahub log file')
    parser.add_argument('-f',
                        dest='follow',
                        action='store_true',
                        help='follow (tail -f) the log file')
    parser.add_argument('--namespace',
                        default='/ndn/nist/bms',
                        help='root of ndn name, no trailing slash')

    parser.add_argument('--image',
                        dest='image',
                        default='../simulator/res/floor2.jpg',
                        help='the floor plan to publish')
    parser.add_argument('--location',
                        dest='location',
                        default='../simulator/res/locations.txt',
                        help='the floor plan to publish')

    args = parser.parse_args()

    # Setup logging
    logger = Logger()
    logger.prepareLogging()

    # Face, KeyChain, memoryContentCache and asio event loop initialization
    loop = asyncio.get_event_loop()
    face = ThreadsafeFace(loop)

    keyChain = KeyChain(IdentityManager(BasicIdentityStorage()))
    # For the gateway publisher, we create one identity for it to sign nfd command interests
    certificateName = keyChain.createIdentityAndCertificate(
        Name("/ndn/nist/gateway"))
    face.setCommandSigningInfo(keyChain, certificateName)
    cache = MemoryContentCache(face)

    dataPublisher = DataPublisher(face, keyChain, loop, cache, args.namespace,
                                  args.image, args.location)
    cache.registerPrefix(Name(args.namespace), dataPublisher.onRegisterFailed,
                         dataPublisher.onDataNotFound)
    loop.run_until_complete(dataPublisher.publishFloorImage())

    if args.follow:
        #asyncio.async(loop.run_in_executor(executor, followfile, args.filename, args.namespace, cache))
        loop.run_until_complete(dataPublisher.followfile(args.filename))
    else:
        loop.run_until_complete(dataPublisher.readfile(args.filename))

    loop.run_forever()
    face.shutdown()
Esempio n. 6
0
def main():
    # Params parsing
    parser = argparse.ArgumentParser(
        description=
        'bms gateway node to Parse or follow Cascade Datahub log and publish to MiniNdn.'
    )
    parser.add_argument('filename', help='datahub log file')
    parser.add_argument('-f',
                        dest='follow',
                        action='store_true',
                        help='follow (tail -f) the log file')
    parser.add_argument('--namespace',
                        default='/ndn/edu/ucla/remap/bms',
                        help='root of ndn name, no trailing slash')
    args = parser.parse_args()

    # Setup logging
    logger = Logger()
    logger.prepareLogging()

    # Face, KeyChain, memoryContentCache and asio event loop initialization
    loop = asyncio.get_event_loop()
    face = ThreadsafeFace(loop, "128.97.98.7")

    keyChain = KeyChain(
        IdentityManager(BasicIdentityStorage(), FilePrivateKeyStorage()))
    # For the gateway publisher, we create one identity for it to sign nfd command interests
    #certificateName = keyChain.createIdentityAndCertificate(Name("/ndn/bms/gateway-publisher"))
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())
    print "Using certificate name " + keyChain.getDefaultCertificateName(
    ).toUri()
    cache = MemoryContentCache(face)

    dataPublisher = DataPublisher(face, keyChain, loop, cache, args.namespace)
    cache.registerPrefix(Name(args.namespace), dataPublisher.onRegisterFailed,
                         dataPublisher.onDataNotFound)

    # Parse csv to decide the mapping between sensor JSON -> <NDN name, data type>
    dataPublisher.populateSensorNDNDictFromCSV(
        'bms-sensor-data-types-sanitized.csv')

    loop.call_later(dataPublisher._restartInterval, dataPublisher.checkAlive)
    if args.follow:
        #asyncio.async(loop.run_in_executor(executor, followfile, args.filename, args.namespace, cache))
        loop.run_until_complete(dataPublisher.followfile(args.filename))
    else:
        loop.run_until_complete(dataPublisher.readfile(args.filename))

    loop.run_forever()
    face.shutdown()
Esempio n. 7
0
    def startPublishing(self):
        # One-time security setup
        self.prepareLogging()

        privateKeyStorage = FilePrivateKeyStorage()
        identityStorage = BasicIdentityStorage()
        policyManager = ConfigPolicyManager(self._trustSchemaFile)

        self._keyChain = KeyChain(
            IdentityManager(identityStorage, privateKeyStorage), policyManager)
        self._certificateName = self._keyChain.createIdentityAndCertificate(
            self._identityName)

        print("My Identity name: " + self._identityName.toUri())
        print("My certificate name: " + self._certificateName.toUri())
        certificateData = self._keyChain.getIdentityManager(
        )._identityStorage.getCertificate(self._certificateName)
        print("My certificate string: " +
              b64encode(certificateData.wireEncode().toBuffer()))
        # self._keyChain.getIdentityCertificate(self._certificateName).)

        self._loop = asyncio.get_event_loop()
        self._face = ThreadsafeFace(self._loop)
        self._keyChain.setFace(self._face)

        self._face.setCommandSigningInfo(self._keyChain, self._certificateName)
        self._memoryContentCache = MemoryContentCache(self._face)

        # We should only ask for cert to be signed upon the first run of a certain aggregator
        if DO_CERT_SETUP:
            if (KeyLocator.getFromSignature(
                    certificateData.getSignature()).getKeyName().equals(
                        self._certificateName.getPrefix(-1))):
                # Need to configure for mini-ndn; aggregation node runs outside of mini-ndn first so that signed cert get installed and mini-ndn won't ask for this again
                print("certificate " + self._certificateName.toUri() +
                      " asking for signature")
                response = urllib2.urlopen(
                    "http://192.168.56.1:5000/bms-cert-hack?cert=" +
                    b64encode(certificateData.wireEncode().toBuffer()) +
                    "&cert_prefix=" + self._identityName.toUri() +
                    '&subject_name=' + self._identityName.toUri()).read()

                signedCertData = Data()
                signedCertData.wireDecode(Blob(b64decode(response)))

                self._memoryContentCache.add(signedCertData)
                cmdline = ['ndnsec-install-cert', '-']
                p = subprocess.Popen(cmdline,
                                     stdin=subprocess.PIPE,
                                     stdout=subprocess.PIPE)
                # desanitize + sign in GET request
                cert, err = p.communicate(response)
                if p.returncode != 0:
                    raise RuntimeError("ndnsec-install-cert error")
            else:
                self._memoryContentCache.add(certificateData)
        else:
            self._memoryContentCache.add(certificateData)

        dataNode = self.conf.getDataNode()
        childrenNode = self.conf.getChildrenNode()

        self._memoryContentCache.registerPrefix(Name(self._identityName),
                                                self.onRegisterFailed,
                                                self.onDataNotFound)

        # For each type of data, we refresh each type of aggregation according to the interval in the configuration
        for i in range(len(dataNode.subtrees)):
            dataType = dataNode.subtrees.keys()[i]
            aggregationParams = self.conf.getProducingParamsForAggregationType(
                dataNode.subtrees.items()[i][1])

            if childrenNode == None:
                self._dataQueue[dataType] = DataQueue(None, None, None)
                self.generateData(dataType, 2, 0)

            for aggregationType in aggregationParams:
                childrenList = OrderedDict()
                if childrenNode != None:

                    for j in range(len(childrenNode.subtrees)):
                        if dataType in childrenNode.subtrees.items(
                        )[j][1].subtrees['data'].subtrees:
                            if aggregationType in childrenNode.subtrees.items(
                            )[j][1].subtrees['data'].subtrees[
                                    dataType].subtrees:
                                childrenList[childrenNode.subtrees.items()[j][
                                    0]] = self.conf.getProducingParamsForAggregationType(
                                        childrenNode.subtrees.items()[j]
                                        [1].subtrees['data'].subtrees[dataType]
                                    )[aggregationType]

                self.startPublishingAggregation(
                    aggregationParams[aggregationType], childrenList, dataType,
                    aggregationType)
        return
Esempio n. 8
0
]

#set up a keyChain
keyChain = KeyChain()
print("Default identity:", keyChain.getDefaultCertificateName())

#main async event loop
loop = asyncio.get_event_loop()

for hub in hubList:
    url = urlparse(hub['site'])
    if (hub['shortname'] not in ['UCLA', 'LIP6']):
        continue

    print("Registering", hub['shortname'], "hostname:", url.hostname)
    face = ThreadsafeFace(loop, url.hostname)
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())
    facePrefix = Name(PREFIX + hub['shortname'])

    print("Face:", facePrefix)
    #shadowing to replace the default PyNDN function that does not support passing options
    # setOrigin(65) must be included to propagate the prefix to other nodes
    face._node._nfdRegisterPrefix = types.MethodType(nfdRegisterPrefix,
                                                     face._node)
    face.registerPrefix(facePrefix,
                        onInterest,
                        onRegisterFailed,
                        onRegisterSuccess=onRegisterSuccess)
    faces[facePrefix] = face

#schedule pings later, so that prefixes have some time to register and propagate
Esempio n. 9
0
    def _onInterest(self, prefix, interest, *k):
        print >> sys.stderr, "<< PyNDN %s" % interest.name

        content = "PyNDN LINE #%d\n" % self.counter
        self.counter += 1

        data = ndn.Data(interest.getName())

        meta = ndn.MetaInfo()
        meta.setFreshnessPeriod(5000)
        data.setMetaInfo(meta)

        data.setContent(content)

        self.keyChain.sign(data, self.keyChain.getDefaultCertificateName())

        self.face.putData(data)

    def _onRegisterFailed(self, prefix):
        print >> sys.stderr, "<< PyNDN: failed to register prefix"


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    face = ThreadsafeFace(loop, None)
    server = Server(face)

    loop.run_forever()
    face.shutdown()
Esempio n. 10
0
 def __init__(self,localhub_ip):
     self.loop = asyncio.get_event_loop()
     self.face = ThreadsafeFace(self.loop, localhub_ip)
Esempio n. 11
0
 def _setup_face(self, ip):
     """Sets up a face that connects to a remote forwarder."""
     udp_connection_info = UdpTransport.ConnectionInfo(ip, 6363)
     udp_transport = UdpTransport()
     return ThreadsafeFace(self._loop, udp_transport, udp_connection_info)
Esempio n. 12
0
#TODO: Test if DB not initialized, else do
#first_run()
timestamp = int(time.time())
#sys.exit(1)
testbed_json = json.load(open(request.urlretrieve("http://ndndemo.arl.wustl.edu/testbed-nodes.json")[0], "r"))
#Initialize keychain
keychain = KeyChain()
loop = asyncio.get_event_loop()
# loop.call_soon(destroy)
# loop.run_forever()
for hub_name in testbed_json.keys():
    hub = testbed_json[hub_name]
    valid_prefixes = Name(PREFIX + hub["shortname"])

for hub_name in testbed_json.keys():
    hub = testbed_json[hub_name]
    print("Adding faces to hub: {}".format(hub["name"]))
    face_base = hub["site"].strip("http").replace(":80/",":6363")
    for protocol in PROTOCOLS:
        face = ThreadsafeFace(loop, "{}{}".format(protocol, hub))
        face.setCommandSigningInfo(keychain, keychain.getDefaultCertificateName())
        prefix = Name(PREFIX + hub["shortname"])
        options = RegistrationOptions().setOrigin(65)
        face.registerPrefix(prefix, onInterest, onRegisterFailed, onRegisterSuccess=registration, registrationOptions=options)
        time.sleep(2)
        print("Begin ping")
        loop.call_soon(schedulePings, prefix)
        loop.run_forever()
#time.sleep(30)
conn.close()
Esempio n. 13
0
        namespaces = args.namespace.split(',')
    else:
        namespaces = [default_prefix]

    if args.security:
        security_option = args.security
    else:
        security_option = default_security_option

    if args.request:
        request_prefix = args.request
    else:
        request_prefix = default_request_prefix

    loop = asyncio.get_event_loop()
    face = ThreadsafeFace(loop)
    
    bootstrap = Bootstrap(face)
    appName = "flow1"
    
    def startProducers(defaultCertificateName, keyChain):
        if len(addrs) != len(namespaces):
            print "argument length mismatch: addrs(" + str(len(addrs)) + ") and namespaces(" + str(len(namespaces)) + ")"
            return
        for i in range(0, len(addrs)):
            producer = AppProducer(face, defaultCertificateName, keyChain, Name(namespaces[i]))
            producer.start()
            peripheral = BtlePeripheral(addrs[i], producer, loop, receive_uuid, send_uuid, security_option)
            peripheral.start()
        return