Esempio n. 1
0
    def _setup_mobile_nodes(self):
        """configure the mobile nodes"""

        for node in self._mobile_nodes:
            node.forwarder = ICNForwarder(
                0,
                encoder=SimpleStringEncoder(),
                routing=True,
                interfaces=[
                    self._simulation_bus.add_interface(f"car{node.node_id}")
                ])
            node.fetch = Fetch(
                f"car{node.node_id}",
                None,
                255,
                SimpleStringEncoder(),
                interfaces=[
                    self._simulation_bus.add_interface(f"ftcar{node.node_id}")
                ])
            node.mgmt_tool = MgmtClient(
                node.forwarder.mgmt.mgmt_sock.getsockname()[1])

            for stationary_node in self._stationary_nodes:
                car_face_id = node.forwarder.linklayer.faceidtable.get_or_create_faceid(
                    AddressInfo(f"rsu{stationary_node.node_id}", 0))
                self.to_rsu_faces[stationary_node.node_id][
                    node.node_id] = car_face_id

                rsu_face_id = node.forwarder.linklayer.faceidtable.get_or_create_faceid(
                    AddressInfo(f"car{stationary_node.node_id}", 0))
                self.to_car_faces[stationary_node.node_id][
                    node.node_id] = rsu_face_id
Esempio n. 2
0
    def _setup_stationary_nodes(self):
        """configure the NFN com. stack at the stationary nodes"""

        for node in self._stationary_nodes:
            # install the NFN forwarder and the mgmt client tool at the stationary node
            if self._forwarder == "NFNForwarder":
                node.nfn_forwarder = NFNForwarder(
                    0,
                    encoder=SimpleStringEncoder(),
                    interfaces=[
                        self._simulation_bus.add_interface(
                            f"rsu{node.node_id}")
                    ],
                    ageing_interval=10)
            elif self._forwarder == "NFNForwarderData":
                node.nfn_forwarder = NFNForwarderData(
                    0,
                    encoder=SimpleStringEncoder(),
                    interfaces=[
                        self._simulation_bus.add_interface(
                            f"rsu{node.node_id}")
                    ],
                    chunk_size=self._chunk_size,
                    num_of_forwards=1,
                    ageing_interval=10)
            else:
                self.logger.error(
                    "Forwarder: " + self._forwarder +
                    " is not supported! Use 'NFNForwarder' or 'NFNForwarderData'!"
                )

            # install the optimizer
            if self._optimizer == "ToDataFirstOptimizer":
                node.nfn_forwarder.nfnlayer.optimizer = ToDataFirstOptimizer(
                    node.nfn_forwarder.icnlayer.cs,
                    node.nfn_forwarder.icnlayer.fib,
                    node.nfn_forwarder.icnlayer.pit,
                    node.nfn_forwarder.linklayer.faceidtable)
            elif self._optimizer == "EdgeComputingOptimizer":
                node.nfn_forwarder.nfnlayer.optimizer = EdgeComputingOptimizer(
                    node.nfn_forwarder.icnlayer.cs,
                    node.nfn_forwarder.icnlayer.fib,
                    node.nfn_forwarder.icnlayer.pit,
                    node.nfn_forwarder.linklayer.faceidtable)
            # install the mgmt client tool at the node
            node.mgmt_tool = MgmtClient(
                node.nfn_forwarder.mgmt.mgmt_sock.getsockname()[1])
            node.nfn_forwarder.icnlayer.cs.set_cs_timeout(60)
Esempio n. 3
0
    def __init__(self):
        """define the configuration"""
        self.number_of_rsus = 4
        self.number_of_cars = 5
        self.to_car_faces = [[0] * self.number_of_cars for i in range(self.number_of_rsus)] #rsu, car -> faceid
        self.to_rsu_faces = [[0] * self.number_of_cars for i in range(self.number_of_rsus)] #rsu, car -> faceid
        self.car_speed = [60, 60, 60, 60, 60] #in km/h
        self.car_direction = [1, 1 ,1 ,1 ,1] # 1 or -1, consider starting rsu by choosing direction.

        self.starting_rsu = [0, 0, 0, 0, 0]

        self.rsu_distance = 0.5 #in km, range is identical here

        self.computations = self.get_computations() #Store computations in here, car will randomly choose one
        self.named_functions ={"/rsu/func/f1": "PYTHON\nf\ndef f(a, b, c):\n return a+b+c",
                             "/rsu/func/f2": "PYTHON\nf\ndef f(a, b, c):\n return a*b*c"} #named functions stored on the
        self.chunk_size = 8192

        self.optimizer = EdgeComputingOptimizer #NFN resolution strategy optimizer
        self.encoder_type = SimpleStringEncoder()
        self.simulation_bus = SimulationBus(packetencoder=self.encoder_type)

        self.rsu_name = Name("/rsu")

        self.car_to_computation = [0,0,0,0,0] #index which car issues which computation

        self._compute_rsu_connection_time()
        self.setup_network()
Esempio n. 4
0
File: Fetch.py Progetto: tairun/PiCN
def main(args):
    name_str = args.name
    name = None
    if 'NFN' in name_str and '_' not in name_str:
        name = parse_nfn_str(name_str)

    if name is None:
        if '[' in name_str and ']' in name_str:
            name = unescape_str_to_Name(args.name)
        else:
            name = Name(args.name)
            name = unescape_name(name)
    name.format = args.format
    log_level = 255

    encoder = NdnTlvEncoder(
    ) if args.format == 'ndntlv' else SimpleStringEncoder()
    fetchTool = Fetch(ip=args.ip,
                      port=args.port,
                      log_level=log_level,
                      encoder=encoder,
                      autoconfig=args.autoconfig)

    content = fetchTool.fetch_data(name, timeout=10)
    print(content)

    fetchTool.stop_fetch()
Esempio n. 5
0
 def __init__(self,
              packetencoder: BasicEncoder = SimpleStringEncoder(),
              print_keep_alive=True,
              log_level=logging.DEBUG):
     super().__init__("SimulationBus", log_level)
     self.interfacetable: Dict[str, SimulationInterface] = {}
     self.packetencoder = packetencoder
     self.print_keep_alive = print_keep_alive
Esempio n. 6
0
    def setUp(self):
        self.encoder_type = SimpleStringEncoder()
        self.simulation_bus = SimulationBus(packetencoder=self.encoder_type)
        chunk_size = 8192
        self.chunkifyer = SimpleContentChunkifyer(chunk_size)

        # Initialize two cars
        self.cars = []
        self.fetch_tool_cars = []
        self.mgmt_client_cars = []
        for i in range(2):
            self.cars.append(
                ICNForwarder(
                    0,
                    encoder=self.encoder_type,
                    routing=True,
                    interfaces=[self.simulation_bus.add_interface(f"car{i}")]))
            self.fetch_tool_cars.append(
                Fetch(f"car{i}",
                      None,
                      255,
                      self.encoder_type,
                      interfaces=[
                          self.simulation_bus.add_interface(f"ftcar{i}")
                      ]))
            self.mgmt_client_cars.append(
                MgmtClient(self.cars[i].mgmt.mgmt_sock.getsockname()[1]))
            self.cars[i].icnlayer.cs.set_cs_timeout(40)

        # Initialize RSUs
        self.rsus = []
        self.fetch_tools = []
        self.mgmt_clients = []
        for i in range(3):
            self.rsus.append(
                NFNForwarderData(
                    0,
                    encoder=self.encoder_type,
                    interfaces=[self.simulation_bus.add_interface(f"rsu{i}")],
                    chunk_size=chunk_size,
                    num_of_forwards=1,
                    ageing_interval=10))
            self.fetch_tools.append(
                Fetch(f"rsu{i}",
                      None,
                      255,
                      self.encoder_type,
                      interfaces=[self.simulation_bus.add_interface(f"ft{i}")
                                  ]))
            self.rsus[i].nfnlayer.optimizer = EdgeComputingOptimizer(
                self.rsus[i].icnlayer.cs, self.rsus[i].icnlayer.fib,
                self.rsus[i].icnlayer.pit, self.rsus[i].linklayer.faceidtable)
            self.mgmt_clients.append(
                MgmtClient(self.rsus[i].mgmt.mgmt_sock.getsockname()[1]))
            self.fetch_tools[i].timeoutpreventionlayer.timeout_interval = 40
            self.rsus[i].icnlayer.cs.set_cs_timeout(60)
Esempio n. 7
0
def main(args):

    # Log Level
    if args.logging == 'error':
        log_level = logging.ERROR
    elif args.logging == 'warning':
        log_level = logging.WARNING
    elif args.logging == 'info':
        log_level = logging.INFO
    elif args.logging == 'debug':
        log_level = logging.DEBUG
    else:
        log_level = 255
    logger = Logger("NFNForwarder", log_level)

    # Info
    logger.info("Starting a NFN Forwarder...")
    logger.info("UDP Port:       " + str(args.port))
    logger.info("Log Level:      " + args.logging)
    logger.info("Packet Format:  " + args.format)

    # Packet encoder
    encoder = NdnTlvEncoder(
        log_level) if args.format == 'ndntlv' else SimpleStringEncoder(
            log_level)

    if args.optimizer == "Edge":
        forwarder = PiCN.ProgramLibs.NFNForwarder.NFNForwarder(
            args.port, log_level, encoder, ageing_interval=1)
        logger.info("Edge Computing Node")
        forwarder.icnlayer.pit.set_pit_timeout(2)
        forwarder.icnlayer.cs.set_cs_timeout(30)
        forwarder.nfnlayer.optimizer = EdgeComputingOptimizer(
            forwarder.icnlayer.cs, forwarder.icnlayer.fib,
            forwarder.icnlayer.pit, forwarder.linklayer.faceidtable)
    elif args.optimizer == "MapReduce":
        forwarder = PiCN.ProgramLibs.NFNForwarder.NFNForwarder(
            args.port, log_level, encoder)
        logger.info("Using MapReduce Optimizer")
        forwarder.nfnlayer.optimizer = MapReduceOptimizer(
            forwarder.icnlayer.cs, forwarder.icnlayer.fib,
            forwarder.icnlayer.pit, forwarder.linklayer.faceidtable)
    elif args.optimizer == "Thunks":
        forwarder = PiCN.ProgramLibs.NFNForwarder.NFNForwarder(args.port,
                                                               log_level,
                                                               encoder,
                                                               use_thunks=True)
        logger.info("Using Thunks for Planning and Optimizing")
    else:
        forwarder = PiCN.ProgramLibs.NFNForwarder.NFNForwarder(
            args.port, log_level, encoder)

    forwarder.start_forwarder()

    forwarder.linklayer.process.join()
Esempio n. 8
0
File: Fetch.py Progetto: s3lph/PiCN
    def __init__(self,
                 ip: str,
                 port: int,
                 log_level=255,
                 encoder: BasicEncoder = None,
                 autoconfig: bool = False,
                 interfaces=None):

        # create encoder and chunkifyer
        if encoder is None:
            self.encoder = SimpleStringEncoder(log_level=log_level)
        else:
            encoder.set_log_level(log_level)
            self.encoder = encoder
        self.chunkifyer = SimpleContentChunkifyer()

        # initialize layers
        synced_data_struct_factory = PiCNSyncDataStructFactory()
        synced_data_struct_factory.register("faceidtable", FaceIDDict)
        synced_data_struct_factory.create_manager()
        faceidtable = synced_data_struct_factory.manager.faceidtable()

        if interfaces is None:
            interfaces = [UDP4Interface(0)]
        else:
            interfaces = interfaces

        # create layers
        self.linklayer = BasicLinkLayer(interfaces,
                                        faceidtable,
                                        log_level=log_level)
        self.packetencodinglayer = BasicPacketEncodingLayer(
            self.encoder, log_level=log_level)
        self.chunklayer = BasicChunkLayer(self.chunkifyer, log_level=log_level)

        self.lstack: LayerStack = LayerStack(
            [self.chunklayer, self.packetencodinglayer, self.linklayer])

        self.autoconfig = autoconfig
        if autoconfig:
            self.autoconfiglayer: AutoconfigClientLayer = AutoconfigClientLayer(
                self.linklayer)
            self.lstack.insert(self.autoconfiglayer,
                               on_top_of=self.packetencodinglayer)

        # setup communication
        if port is None:
            self.fid = self.linklayer.faceidtable.get_or_create_faceid(
                AddressInfo(ip, 0))
        else:
            self.fid = self.linklayer.faceidtable.get_or_create_faceid(
                AddressInfo((ip, port), 0))

        # send packet
        self.lstack.start_all()
Esempio n. 9
0
    def setUp(self):
        self.encoder_type = SimpleStringEncoder()
        self.simulation_bus = SimulationBus(packetencoder=self.encoder_type)
        chunk_size = 4
        self.chunkifyer = SimpleContentChunkifyer(chunk_size)

        self.car = ICNForwarder(
            0,
            encoder=self.encoder_type,
            routing=True,
            interfaces=[self.simulation_bus.add_interface("car")])
        self.fetch_tool_car = Fetch(
            "car",
            None,
            255,
            self.encoder_type,
            interfaces=[self.simulation_bus.add_interface("ftcar")])
        self.mgmt_client_car = MgmtClient(
            self.car.mgmt.mgmt_sock.getsockname()[1])

        self.rsus = []
        self.fetch_tools = []
        self.mgmt_clients = []

        for i in range(4):
            self.rsus.append(
                NFNForwarderData(
                    0,
                    encoder=self.encoder_type,
                    interfaces=[self.simulation_bus.add_interface(f"rsu{i}")],
                    chunk_size=chunk_size,
                    num_of_forwards=0))
            self.fetch_tools.append(
                Fetch(f"rsu{i}",
                      None,
                      255,
                      self.encoder_type,
                      interfaces=[self.simulation_bus.add_interface(f"ft{i}")
                                  ]))
            self.rsus[i].nfnlayer.optimizer = EdgeComputingOptimizer(
                self.rsus[i].icnlayer.cs, self.rsus[i].icnlayer.fib,
                self.rsus[i].icnlayer.pit, self.rsus[i].linklayer.faceidtable)
            self.mgmt_clients.append(
                MgmtClient(self.rsus[i].mgmt.mgmt_sock.getsockname()[1]))
            self.fetch_tools[i].timeoutpreventionlayer.timeout_interval = 30
Esempio n. 10
0
    def __init__(self, database_path, port=9000, log_level=255, encoder: BasicEncoder = None, flush_database=False):
        # debug level
        logger = Logger("PushRepo", log_level)

        # packet encoder
        if encoder is None:
            self.encoder = SimpleStringEncoder(log_level=log_level)
        else:
            encoder.set_log_level(log_level=log_level)
            self.encoder = encoder

        # setup data structures
        synced_data_struct_factory = PiCNSyncDataStructFactory()
        synced_data_struct_factory.register("cs", ContentStorePersistentExact)
        synced_data_struct_factory.register("faceidtable", FaceIDDict)
        synced_data_struct_factory.create_manager()

        cs = synced_data_struct_factory.manager.cs(db_path=database_path + "/pushrepo.db")
        if flush_database:
            cs.delete_all()
        faceidtable = synced_data_struct_factory.manager.faceidtable()

        # default interface
        interfaces = [UDP4Interface(port)]
        mgmt_port = interfaces[0].get_port()

        # initialize layers
        self.linklayer = BasicLinkLayer(interfaces, faceidtable, log_level=log_level)
        self.packetencodinglayer = BasicPacketEncodingLayer(self.encoder, log_level=log_level)
        self.repolayer = PushRepositoryLayer(log_level=log_level)

        self.lstack: LayerStack = LayerStack([
            self.repolayer,
            self.packetencodinglayer,
            self.linklayer
        ])

        self.repolayer.cs = cs

        # mgmt
        self.mgmt = Mgmt(cs, None, None, self.linklayer, mgmt_port, self.stop_forwarder,
                         log_level=log_level)
Esempio n. 11
0
def main(args):

    prefix = Name(args.icnprefix)

    log_level = logging.DEBUG

    if args.format == "ndntlv":
        encoder = NdnTlvEncoder()
    else:
        encoder = SimpleStringEncoder(log_level=log_level)

    repo = ICNDataRepository(args.datapath,
                             prefix,
                             args.port,
                             log_level,
                             encoder=encoder,
                             autoconfig=args.autoconfig)
    repo.start_repo()

    repo.linklayer.process.join()
Esempio n. 12
0
File: Peek.py Progetto: tairun/PiCN
def main(args):

    # Packet encoder
    encoder = NdnTlvEncoder(
    ) if args.format == 'ndntlv' else SimpleStringEncoder()

    # Generate interest packet
    interest: Interest = Interest(args.name)
    encoded_interest = encoder.encode(interest)

    # Send interest packet
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.settimeout(args.timeout)
    sock.bind(("0.0.0.0", 0))
    try:
        resolved_hostname = socket.gethostbyname(args.ip)
    except:
        print("Resolution of hostname failed.")
        sys.exit(-2)
    sock.sendto(encoded_interest, (resolved_hostname, args.port))

    # Receive content object
    try:
        wire_packet, addr = sock.recvfrom(8192)
    except:
        print("Timeout.")
        sys.exit(-1)

    # Print
    if args.plain is False:
        printer = NdnTlvPrinter(wire_packet)
        printer.formatted_print()
    else:
        encoder = NdnTlvEncoder()
        if encoder.is_content(wire_packet):
            sys.stdout.buffer.write(encoder.decode_data(wire_packet)[1])
        else:
            sys.exit(-2)
Esempio n. 13
0
 def __init__(self, packetencoder: BasicEncoder = SimpleStringEncoder()):
     self.interfacetable: Dict[SimulationInterface] = {}
     self.packetencoder = packetencoder
Esempio n. 14
0
 def setUp(self):
     self.encoder1 = SimpleStringEncoder()
Esempio n. 15
0
 def get_encoder(self):
     return SimpleStringEncoder()
Esempio n. 16
0
class test_SimpleStringEncoder(unittest.TestCase):
    """Test the SimpleStringEncoder"""
    def setUp(self):
        self.encoder1 = SimpleStringEncoder()

    def tearDown(self):
        pass

    def test_Encoder_encode_interest_equal(self):
        """Test the interest encoding of Encoder: equal"""
        i = Interest("/test/data")
        ei = self.encoder1.encode(i)
        self.assertEqual(ei.decode(), "I:/test/data:")

    def test_Encoder_encode_interest_not_equal(self):
        """Test the interest encoding of Encoder: not equal"""
        i = Interest("/data/test")
        ei = self.encoder1.encode(i)
        self.assertNotEqual(ei.decode(), "I:/test/data:")

    def test_Encoder_decode_interest_equal(self):
        """Test the interest decoding of Encoder: equal"""
        data = "I:/test/data:".encode()
        di = self.encoder1.decode(data)
        cmp_interest = Interest("/test/data")
        self.assertTrue(di == cmp_interest)

    def test_Encoder_decode_interest_equal(self):
        """Test the interest decoding of Encoder: not equal"""
        data = "I:/data/test:".encode()
        di = self.encoder1.decode(data)
        cmp_interest = Interest("/test/data")
        self.assertFalse(di == cmp_interest)

    def test_Encoder_encode_decode_interest(self):
        """Test the interest decoding of Encoder: equal"""
        i = Interest("/data/test")
        ei = self.encoder1.encode(i)
        di = self.encoder1.decode(ei)
        self.assertTrue(i == di)

    def test_Encoder_decode_content_equal(self):
        """Test the Content decoding of Encoder: equal"""
        data = "C:/data/test::HelloWorld".encode()
        dc = self.encoder1.decode(data)
        cmp_interest = Content("/data/test", "HelloWorld")
        self.assertTrue(dc == cmp_interest)

    def test_Encoder_decode_content_not_equal(self):
        """Test the Content decoding of Encoder: not equal"""
        data = "C:/data/test::HelloWorld2".encode()
        dc = self.encoder1.decode(data)
        cmp_interest = Content("/data/test", "HelloWorld")
        self.assertFalse(dc == cmp_interest)

    def test_Encoder_encode_decode_content(self):
        """Test the content decoding of Encoder"""
        c = Content("/data/test", "HelloWorld")
        ec = self.encoder1.encode(c)
        dc = self.encoder1.decode(ec)
        self.assertTrue(c == dc)

    def test_Encoder_encode_decode_nack(self):
        """Test the nack decoding of Encoder"""
        interest = Interest("/data/test")
        n = Nack("/data/test", NackReason.NO_CONTENT, interest=interest)
        en = self.encoder1.encode(n)
        dn = self.encoder1.decode(en)
        self.assertTrue(n == dn)
Esempio n. 17
0
    def __init__(self,
                 port=9000,
                 log_level=255,
                 encoder: BasicEncoder = None,
                 interfaces: List[BaseInterface] = None,
                 executors: BaseNFNExecutor = None,
                 ageing_interval: int = 3,
                 use_thunks=False):
        # debug level
        logger = Logger("NFNForwarder", log_level)
        logger.info("Start PiCN NFN Forwarder on port " + str(port))

        # packet encoder
        if encoder is None:
            self.encoder = SimpleStringEncoder(log_level=log_level)
        else:
            encoder.set_log_level(log_level)
            self.encoder = encoder

    # setup data structures
        synced_data_struct_factory = PiCNSyncDataStructFactory()
        synced_data_struct_factory.register("cs", ContentStoreMemoryExact)
        synced_data_struct_factory.register(
            "fib", ForwardingInformationBaseMemoryPrefix)
        synced_data_struct_factory.register("pit",
                                            PendingInterstTableMemoryExact)
        synced_data_struct_factory.register("faceidtable", FaceIDDict)

        synced_data_struct_factory.register("computation_table",
                                            NFNComputationList)
        synced_data_struct_factory.register("timeoutprevention_dict",
                                            TimeoutPreventionMessageDict)
        if use_thunks:
            synced_data_struct_factory.register("thunktable", ThunkList)
            synced_data_struct_factory.register("plantable", PlanTable)

        synced_data_struct_factory.create_manager()

        cs = synced_data_struct_factory.manager.cs()
        fib = synced_data_struct_factory.manager.fib()
        pit = synced_data_struct_factory.manager.pit()
        faceidtable = synced_data_struct_factory.manager.faceidtable()

        self.parser = DefaultNFNParser()
        if use_thunks:
            thunktable = synced_data_struct_factory.manager.thunktable()
            plantable = synced_data_struct_factory.manager.plantable(
                self.parser)

        #setup chunkifier
        self.chunkifier = SimpleContentChunkifyer()

        # default interface
        if interfaces is not None:
            self.interfaces = interfaces
            mgmt_port = port
        else:
            interfaces = [UDP4Interface(port)]
            mgmt_port = interfaces[0].get_port()

        # initialize layers
        self.linklayer = BasicLinkLayer(interfaces,
                                        faceidtable,
                                        log_level=log_level)
        self.packetencodinglayer = BasicPacketEncodingLayer(
            self.encoder, log_level=log_level)
        self.icnlayer = BasicICNLayer(log_level=log_level,
                                      ageing_interval=ageing_interval)
        self.chunklayer = BasicChunkLayer(self.chunkifier, log_level=log_level)

        # setup nfn
        self.icnlayer._interest_to_app = True
        if executors is None:
            self.executors = {"PYTHON": NFNPythonExecutor()}
        else:
            self.executors = executors
        self.r2cclient = TimeoutR2CHandler()
        comp_table = synced_data_struct_factory.manager.computation_table(
            self.r2cclient, self.parser)
        self.nfnlayer = BasicNFNLayer(cs,
                                      fib,
                                      pit,
                                      faceidtable,
                                      comp_table,
                                      self.executors,
                                      self.parser,
                                      self.r2cclient,
                                      log_level=log_level)
        if use_thunks:
            self.thunk_layer = BasicThunkLayer(cs,
                                               fib,
                                               pit,
                                               faceidtable,
                                               thunktable,
                                               plantable,
                                               self.parser,
                                               log_level=log_level)
            self.nfnlayer.optimizer = ThunkPlanExecutor(
                cs, fib, pit, faceidtable, plantable)

        timeoutprevention_dict = synced_data_struct_factory.manager.timeoutprevention_dict(
        )
        self.timeoutpreventionlayer = BasicTimeoutPreventionLayer(
            timeoutprevention_dict, comp_table, pit=pit, log_level=log_level)

        if use_thunks:
            self.lstack: LayerStack = LayerStack([
                self.nfnlayer, self.chunklayer, self.timeoutpreventionlayer,
                self.thunk_layer, self.icnlayer, self.packetencodinglayer,
                self.linklayer
            ])
        else:
            self.lstack: LayerStack = LayerStack([
                self.nfnlayer, self.chunklayer, self.timeoutpreventionlayer,
                self.icnlayer, self.packetencodinglayer, self.linklayer
            ])

        self.icnlayer.cs = cs
        self.icnlayer.fib = fib
        self.icnlayer.pit = pit

        # mgmt
        self.mgmt = Mgmt(self.icnlayer.cs,
                         self.icnlayer.fib,
                         self.icnlayer.pit,
                         self.linklayer,
                         mgmt_port,
                         self.stop_forwarder,
                         log_level=log_level)
Esempio n. 18
0
 def __init__(self,
              packetencoder: BasicEncoder = SimpleStringEncoder(),
              print_keep_alive=True):
     self.interfacetable: Dict[str, SimulationInterface] = {}
     self.packetencoder = packetencoder
     self.print_keep_alive = print_keep_alive
Esempio n. 19
0
    def __init__(self,
                 run_id: int,
                 mobile_nodes: List[MobileNode],
                 stationary_nodes: List[StationaryNode],
                 stationary_node_distance: float,
                 named_functions: dict,
                 function_names: list,
                 forwarder: str = "NFNForwarder",
                 optimizer: str = "ToDataFirstOptimizer",
                 use_distribution_helper: bool = False,
                 log_level=logging.DEBUG):
        """
        Configuration of the mobility simulation

        :param run_id the identifier of the simulation run
        :param mobile_nodes a list of mobile nodes part of the simulation
        :param stationary_nodes a list of stationary nodes forming the infrastructure
        :param stationary_node_distance the distance between the stationary nodes
        :param named_functions a dictionary of named function definitions used to be executed
        :param function_names a list of function names to be assigned to the mobile nodes
        :param forwarder the NFN forwarder to be used
        :param optimizer the NFN resolution strategy optimizer to be used in the simulation
        :param use_distribution_helper A flag indicating if the default distribution helper (ZipfMandelbrotDistribution)
        shall be used or not; default = False
        :param log_level the log level of the logger to be used; default: logging.DEBUG
        """
        self._run_id = run_id
        self._forwarder = forwarder
        self._optimizer = optimizer
        self._mobile_nodes = mobile_nodes
        self._stationary_nodes = stationary_nodes
        self._stationary_node_distance = stationary_node_distance
        self.logger = Logger("MobilitySimulation", log_level)
        self.to_car_faces = [[0] * len(self._mobile_nodes)
                             for i in range(len(self._stationary_nodes))
                             ]  # rsu, car -> faceid
        self.to_rsu_faces = [[0] * len(self._mobile_nodes)
                             for i in range(len(self._stationary_nodes))
                             ]  # rsu, car -> faceid
        self._velocities = []
        self._heading_directions = []
        self._starting_points = []
        for node in self._mobile_nodes:
            self._velocities.append(node.speed)
            self._heading_directions.append(node.direction)
            self._starting_points.append(node.spawn_point)

        self._is_running = False  # flag indicating if the simulation is running or not
        self._function_names = function_names  # list of function names to be invoked by the nodes
        self._named_functions = named_functions  # a dict of function definitions to be invoked
        self._chunk_size = 8192

        self._simulation_bus = SimulationBus(
            packetencoder=SimpleStringEncoder())

        self._stationary_node_name_prefix = Name("/rsu")
        self._mobile_node_to_computation = [0] * len(
            mobile_nodes)  # index which mobile node issues which computation
        if use_distribution_helper:
            # TODO in the future support more distribution types, e.g., uniform, gaussian, etc.
            dist_array = ZipfMandelbrotDistribution.create_zipf_mandelbrot_distribution(
                len(self._function_names), 0.7, 0.7)
            for i in range(0, len(mobile_nodes)):
                self._mobile_node_to_computation[i] = ZipfMandelbrotDistribution.\
                    get_next_zipfmandelbrot_random_number(dist_array, len(self._function_names)) - 1
                # get_next_zipfmandelbrot_random_number(dist_array, len(self._function_names), run_id) - 1

        self._compute_rsu_connection_time()
        self._setup_simulation_network()
Esempio n. 20
0
    def __init__(self, foldername: Optional[str], prefix: Name,
                 port=9000, log_level=255, encoder: BasicEncoder = None,
                 autoconfig: bool = False, autoconfig_routed: bool = False, interfaces: List[BaseInterface] = None,
                 use_thunks=False):
        """
        :param foldername: If None, use an in-memory repository. Else, use a file system repository.
        """

        logger = Logger("ICNRepoSession", log_level)
        logger.info("Start PiCN Data Repository with Sessions")

        # packet encoder
        if encoder is None:
            self.encoder = SimpleStringEncoder(log_level=log_level)
        else:
            encoder.set_log_level(log_level)
            self.encoder = encoder

        # chunkifyer
        self.chunkifyer = SimpleContentChunkifyer()

        # repo
        manager = multiprocessing.Manager()

        if foldername is None:
            self.repo: BaseRepository = SimpleMemoryRepository(prefix, manager, logger)
        else:
            self.repo: BaseRepository = SimpleFileSystemRepository(foldername, prefix, manager, logger)

        # initialize layers
        synced_data_struct_factory = PiCNSyncDataStructFactory()
        synced_data_struct_factory.register("faceidtable", FaceIDDict)

        if use_thunks:
            synced_data_struct_factory.register("thunktable", ThunkList)
            synced_data_struct_factory.register("plantable", PlanTable)
        synced_data_struct_factory.create_manager()
        faceidtable = synced_data_struct_factory.manager.faceidtable()

        if use_thunks:
            self.parser = DefaultNFNParser()
            thunktable = synced_data_struct_factory.manager.thunktable()
            plantable = synced_data_struct_factory.manager.plantable(self.parser)

        if interfaces is not None:
            self.interfaces = interfaces
            mgmt_port = port
        else:
            interfaces = [UDP4Interface(port)]
            mgmt_port = interfaces[0].get_port()

        self.linklayer = BasicLinkLayer(interfaces, faceidtable, log_level=log_level)
        self.packetencodinglayer = BasicPacketEncodingLayer(self.encoder, log_level=log_level)
        self.chunklayer = BasicChunkLayer(self.chunkifyer, log_level=log_level)
        self.repolayer = SessionRepositoryLayer(self.repo, log_level=log_level)

        if use_thunks:
            self.thunklayer = BasicThunkLayer(None, None, None, faceidtable, thunktable, plantable, self.parser, self.repo, log_level=log_level)
            logger.info("Using Thunks")

        if use_thunks:
            self.lstack: LayerStack = LayerStack([
                self.repolayer,
                self.chunklayer,
                self.thunklayer,
                self.packetencodinglayer,
                self.linklayer
            ])
        else:
            self.lstack: LayerStack = LayerStack([
                self.repolayer,
                self.chunklayer,
                self.packetencodinglayer,
                self.linklayer
            ])

        if autoconfig:
            self.autoconfiglayer = AutoconfigRepoLayer(name=prefix.string_components[-1],
                                                       addr='127.0.0.1',
                                                       linklayer=self.linklayer, repo=self.repo,
                                                       register_global=autoconfig_routed, log_level=log_level)
            self.lstack.insert(self.autoconfiglayer, below_of=self.chunklayer)

        # mgmt
        self.mgmt = Mgmt(None, None, None, self.linklayer, mgmt_port,
                         self.start_repo, repo_path=foldername,
                         repo_prfx=prefix, log_level=log_level)
Esempio n. 21
0
    def __init__(self,
                 port=9000,
                 log_level=255,
                 encoder: BasicEncoder = None,
                 routing: bool = False,
                 peers=None,
                 autoconfig: bool = False,
                 interfaces: List[BaseInterface] = None,
                 ageing_interval: int = 3,
                 node_name: str = None):
        # debug level
        logger = Logger("ICNForwarder",
                        log_level)  # FIXME: Why isn't this self.logger???
        self._node_name = node_name
        # packet encoder
        if encoder is None:
            self.encoder = SimpleStringEncoder(log_level=log_level)
        else:
            encoder.set_log_level(log_level=log_level)
            self.encoder = encoder

        # setup data structures
        synced_data_struct_factory = PiCNSyncDataStructFactory()
        synced_data_struct_factory.register("cs", ContentStoreMemoryExact)
        synced_data_struct_factory.register(
            "fib", ForwardingInformationBaseMemoryPrefix)
        synced_data_struct_factory.register("pit",
                                            PendingInterestTableMemoryExact)
        synced_data_struct_factory.register("rib", TreeRoutingInformationBase)
        synced_data_struct_factory.register("faceidtable", FaceIDDict)
        synced_data_struct_factory.create_manager()

        cs = synced_data_struct_factory.manager.cs()
        fib = synced_data_struct_factory.manager.fib()
        pit = synced_data_struct_factory.manager.pit()

        rib = None
        if routing:
            rib = synced_data_struct_factory.manager.rib()
        faceidtable = synced_data_struct_factory.manager.faceidtable()

        # default interface
        if interfaces is not None:
            self.interfaces = interfaces
            mgmt_port = port
        else:
            interfaces = [UDP4Interface(port)]
            mgmt_port = interfaces[0].get_port()

        # initialize layers
        self.linklayer = BasicLinkLayer(interfaces,
                                        faceidtable,
                                        log_level=log_level)
        self.packetencodinglayer = BasicPacketEncodingLayer(
            self.encoder, log_level=log_level)
        self.icnlayer = BasicICNLayer(log_level=log_level,
                                      ageing_interval=ageing_interval)

        self.lstack: LayerStack = LayerStack(
            [self.icnlayer, self.packetencodinglayer, self.linklayer])

        if autoconfig:
            self.autoconfiglayer: AutoconfigServerLayer = AutoconfigServerLayer(
                linklayer=self.linklayer,
                address='127.0.0.1',
                registration_prefixes=[(Name('/testnetwork/repos'), True)],
                log_level=log_level)
            self.lstack.insert(self.autoconfiglayer, below_of=self.icnlayer)

        if routing:
            self.routinglayer = BasicRoutingLayer(self.linklayer,
                                                  peers=peers,
                                                  log_level=log_level)
            self.lstack.insert(self.routinglayer, below_of=self.icnlayer)

        self.icnlayer.cs = cs
        self.icnlayer.fib = fib
        # ----- by Luc # FIXME: How to pass these parameters to __init__
        self.icnlayer.fib.logger = logger
        self.icnlayer.fib.node_name = self._node_name
        # ----- by Luc # FIXME: How to pass these parameters to __init__
        self.icnlayer.pit = pit
        self.icnlayer.pit.logger = logger
        self.icnlayer.pit.node_name = self._node_name
        # -----

        if autoconfig:
            self.autoconfiglayer.fib = fib
        if routing:
            self.routinglayer.rib = rib
            self.routinglayer.fib = fib

        # mgmt
        self.mgmt = Mgmt(cs,
                         fib,
                         pit,
                         self.linklayer,
                         mgmt_port,
                         self.stop_forwarder,
                         log_level=log_level)
Esempio n. 22
0
def main(args):
    logger = Logger(
        "ICNPushRepo",
        logging.DEBUG)  # note: set later according to cli/config arguments
    logger.info("Starting a Push Repository...")

    # Parse Configuration file
    conf = None
    if args.config != "none":
        try:
            conf = ConfigParser(args.config)
            logger.info("Successfully parsed configuration file.")
        except CouldNotOpenConfigError:
            conf = None
            logger.warning(
                "Could not open configuration file. Proceed with command line arguments or default values."
            )
        except CouldNotParseError:
            logger.warning(
                "Could not parse configuration file. Proceed with command line arguments or default values."
            )
        except MalformedConfigurationError as e:
            logger.warning(
                "Invalid configuration file. Proceed with command line arguments or default values. Hint: "
                + str(e))

    # Choose command line arguments before config file arguments before default values
    if not args.port:
        if conf and conf.udp_port:
            args.port = conf.udp_port
        else:
            args.port = default_port

    if not args.format:
        if conf and conf.format:
            args.format = conf.format
        else:
            args.format = default_format

    if not args.logging:
        if conf and conf.logging:
            args.logging = conf.logging
        else:
            args.logging = default_logging

    # Log Level
    if args.logging == 'error':
        log_level = logging.ERROR
    elif args.logging == 'warning':
        log_level = logging.WARNING
    elif args.logging == 'info':
        log_level = logging.INFO
    elif args.logging == 'debug':
        log_level = logging.DEBUG
    else:
        log_level = 255
    logger.setLevel(log_level)

    # Info
    logger.info("UDP Port:       " + str(args.port))
    logger.info("Log Level:      " + args.logging)
    logger.info("Packet Format:  " + args.format)
    logger.info("Database:       " + args.database_path)
    logger.info("Flush DB:       " + str(args.flush_database))

    # Packet encoder
    encoder = NdnTlvEncoder(
        log_level) if args.format == 'ndntlv' else SimpleStringEncoder(
            log_level)

    # Start
    forwarder = PiCN.ProgramLibs.ICNPushRepository.ICNPushRepository(
        args.database_path, args.port, log_level, encoder, args.flush_database)
    forwarder.start_forwarder()
    forwarder.linklayer.process.join()