Skip to content

vNIC

The class "vNIC" serves as the implementation of the network interface card in the simulation. It includes a queue specifically designed to store "vPacket" objects and has the capability to establish connections with other "vNIC" instances. The "vNIC" class is equipped with two resources: uplink bandwidth and downlink bandwidth. These resources are allocated to the transmission and reception of "vPacket" objects respectively. The transmission and reception functionalities of "vPacket" are implemented as member functions within the class. Upon receiving a "vPacket", a specialized "vProcess" called PacketHandler is created to simulate the decoding process and the associated processing delay. If there is insufficient uplink or downlink bandwidth available, the "vPacket" will be kept in the queue until the necessary resources become available.

Bases: vHardwareComponent

Source code in PyCloudSim\entity\v_nic.py
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
class vNIC(vHardwareComponent):
    def __init__(
        self,
        host: vHardwareEntity | vGateway,
        label: str | None = None,
        create_at: int
        | float
        | Callable[..., int]
        | Callable[..., float]
        | None = None,
        terminate_at: int
        | float
        | Callable[..., int]
        | Callable[..., float]
        | None = None,
        precursor: Entity | List[Entity] | None = None,
    ) -> None:
        """Create a simulated NIC."""
        super().__init__(label, create_at, terminate_at, precursor)
        self._host = host
        self._ports: List[vPort] = EntityList(label=f"{self} Ports")
        self._packet_queue: List[vPacket] = EntityList(label=f"{self} Packet Queue")

    def on_power_on(self) -> None:
        """Power on the simulated NIC."""
        super().on_power_on()
        for port in self.ports:
            port.power_on(simulation.now)

        @self.continuous_event(
            at=simulation.now,
            interval=simulation.min_time_unit,
            duration=inf,
            label=f"{self} Transmit Packets",
        )
        def _schedule_packets():
            """A continous event to schedule packets in the queue."""
            self.packet_queue.sort(key=lambda packet: packet.priority)
            for packet in self.packet_queue:
                # check if packet is decoded
                if packet.decoded and not packet.in_transmission:
                    logger.debug(f"{simulation.now}:\t{self} is scheduling {packet}.")
                    # find the port to transmit the packet to the next hop
                    try:
                        src_port = [
                            port
                            for port in self.ports
                            if port.endpoint is packet.next_hop
                        ][0]
                    except:
                        raise RuntimeError(
                            f"Can not find a port on {packet.path[0]} to transmit {packet}."
                        )
                    # find the port to receive the packet on the next hop
                    try:
                        dst_port = [
                            port
                            for port in packet.next_hop.NIC.ports
                            if port.endpoint is packet.current_hop
                        ][0]
                    except:
                        raise RuntimeError(
                            f"Can not find a port on {packet.path[1]} to receive {packet}."
                        )
                    logger.debug(
                        f"{simulation.now}:\t{self} found src port {src_port} and dst port {dst_port} for {packet}"
                    )
                    # calculate the available bandwidth and transmission time
                    available_bandwidth = min(
                        src_port.bandwidth.amount, dst_port.bandwidth.amount
                    )
                    logger.debug(
                        f"{simulation.now}:\t{self} found available bandwidth {available_bandwidth} for {packet}"
                    )
                    # check if the packet can be transmitted
                    if available_bandwidth > packet.size:
                        packet.state.append(Constants.INTRANSMISSION)
                        link_speed = min(
                            src_port.bandwidth.capacity, dst_port.bandwidth.capacity
                        )
                        # calculate the transmission time
                        transmission_time = packet.size / link_speed

                        # packet consumes the bandwidth of the src port and returns the bandwidth in future
                        src_port.transmit(packet, transmission_time)

                        # packet consumes the bandwidth of the dst port and returns the bandwidth in future
                        dst_port.receive(packet, transmission_time)

                        logger.info(
                            f"{simulation.now}:\t{packet} in transmission from {src_port.host} to {dst_port.host}"
                        )
                else:
                    # pass packets that have not been decoded
                    pass

    def on_power_off(self) -> None:
        """Power off the simulated NIC."""
        super().on_power_off()
        for event in self.events:
            if event.label == f"{self} Transmit Packets":
                event.cancel()

    def add_port(
        self,
        endpoint: vHardwareEntity | vGateway,
        bandwidth: int | Callable[..., int],
        ip_address: IPv4Address | None,
        at: int | float,
    ):
        """Add a port to this virtual NIC."""

        @self.instant_event(at, label=f"{self} Add Port to {endpoint}")
        def _add_port():
            port = vPort(
                self,
                endpoint,
                bandwidth,
                ip_address=ip_address,
                label=f"{self.label}-{len(self.ports)}",
                create_at=simulation.now,
            )
            self.ports.append(port)

    def remove_port(self, endpoint: vHardwareEntity, at: int | float):
        """Remove a port from this virtual NIC."""

        @self.instant_event(at, label=f"{self} Remove Port to {endpoint}")
        def _remove_port():
            for port in self.ports:
                if port.endpoint is endpoint:
                    port.terminate(simulation.now)

    @property
    def host(self):
        """Return the host of this NIC."""
        return self._host

    @property
    def ports(self):
        """Return the ports of this NIC."""
        return self._ports

    @property
    def packet_queue(self):
        """Return the packet queue of this NIC."""
        return self._packet_queue

    def egress_usage(self, duration: int | float | None = None):
        """Return the egress bandwidth usage of this NIC."""
        return sum([port.usage(duration) for port in self.ports])

    def egress_utilization(self, duration: int | float | None = None):
        """Return the egress bandwidth utilization of this NIC."""
        return sum([port.utilization(duration) for port in self.ports]) / len(
            self.ports
        )

    def ingress_usage(self, duration: int | float | None = None):
        """Return the ingress bandwidth usage of this NIC."""
        connected_nodes = [
            port.endpoint for port in self.ports
        ]
        ingress_usage = 0
        for node in connected_nodes:
            for port in node.NIC.ports:
                if port.endpoint is self.host:
                    ingress_usage += port.usage(duration)
        return ingress_usage

    def ingress_utilization(self, duration: int | float | None = None):
        """Return the ingress bandwidth utilization of this NIC."""
        connected_nodes = [
            port.endpoint for port in self.ports
        ]
        ingress_utilization = 0
        for node in connected_nodes:
            for port in node.NIC.ports:
                if port.endpoint is self.host:
                    ingress_utilization += port.utilization(duration)
        return ingress_utilization / len(connected_nodes)

host property

Return the host of this NIC.

packet_queue property

Return the packet queue of this NIC.

ports property

Return the ports of this NIC.

__init__(host, label=None, create_at=None, terminate_at=None, precursor=None)

Create a simulated NIC.

Source code in PyCloudSim\entity\v_nic.py
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
def __init__(
    self,
    host: vHardwareEntity | vGateway,
    label: str | None = None,
    create_at: int
    | float
    | Callable[..., int]
    | Callable[..., float]
    | None = None,
    terminate_at: int
    | float
    | Callable[..., int]
    | Callable[..., float]
    | None = None,
    precursor: Entity | List[Entity] | None = None,
) -> None:
    """Create a simulated NIC."""
    super().__init__(label, create_at, terminate_at, precursor)
    self._host = host
    self._ports: List[vPort] = EntityList(label=f"{self} Ports")
    self._packet_queue: List[vPacket] = EntityList(label=f"{self} Packet Queue")

add_port(endpoint, bandwidth, ip_address, at)

Add a port to this virtual NIC.

Source code in PyCloudSim\entity\v_nic.py
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
def add_port(
    self,
    endpoint: vHardwareEntity | vGateway,
    bandwidth: int | Callable[..., int],
    ip_address: IPv4Address | None,
    at: int | float,
):
    """Add a port to this virtual NIC."""

    @self.instant_event(at, label=f"{self} Add Port to {endpoint}")
    def _add_port():
        port = vPort(
            self,
            endpoint,
            bandwidth,
            ip_address=ip_address,
            label=f"{self.label}-{len(self.ports)}",
            create_at=simulation.now,
        )
        self.ports.append(port)

egress_usage(duration=None)

Return the egress bandwidth usage of this NIC.

Source code in PyCloudSim\entity\v_nic.py
280
281
282
def egress_usage(self, duration: int | float | None = None):
    """Return the egress bandwidth usage of this NIC."""
    return sum([port.usage(duration) for port in self.ports])

egress_utilization(duration=None)

Return the egress bandwidth utilization of this NIC.

Source code in PyCloudSim\entity\v_nic.py
284
285
286
287
288
def egress_utilization(self, duration: int | float | None = None):
    """Return the egress bandwidth utilization of this NIC."""
    return sum([port.utilization(duration) for port in self.ports]) / len(
        self.ports
    )

ingress_usage(duration=None)

Return the ingress bandwidth usage of this NIC.

Source code in PyCloudSim\entity\v_nic.py
290
291
292
293
294
295
296
297
298
299
300
def ingress_usage(self, duration: int | float | None = None):
    """Return the ingress bandwidth usage of this NIC."""
    connected_nodes = [
        port.endpoint for port in self.ports
    ]
    ingress_usage = 0
    for node in connected_nodes:
        for port in node.NIC.ports:
            if port.endpoint is self.host:
                ingress_usage += port.usage(duration)
    return ingress_usage

ingress_utilization(duration=None)

Return the ingress bandwidth utilization of this NIC.

Source code in PyCloudSim\entity\v_nic.py
302
303
304
305
306
307
308
309
310
311
312
def ingress_utilization(self, duration: int | float | None = None):
    """Return the ingress bandwidth utilization of this NIC."""
    connected_nodes = [
        port.endpoint for port in self.ports
    ]
    ingress_utilization = 0
    for node in connected_nodes:
        for port in node.NIC.ports:
            if port.endpoint is self.host:
                ingress_utilization += port.utilization(duration)
    return ingress_utilization / len(connected_nodes)

on_power_off()

Power off the simulated NIC.

Source code in PyCloudSim\entity\v_nic.py
228
229
230
231
232
233
def on_power_off(self) -> None:
    """Power off the simulated NIC."""
    super().on_power_off()
    for event in self.events:
        if event.label == f"{self} Transmit Packets":
            event.cancel()

on_power_on()

Power on the simulated NIC.

Source code in PyCloudSim\entity\v_nic.py
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
def on_power_on(self) -> None:
    """Power on the simulated NIC."""
    super().on_power_on()
    for port in self.ports:
        port.power_on(simulation.now)

    @self.continuous_event(
        at=simulation.now,
        interval=simulation.min_time_unit,
        duration=inf,
        label=f"{self} Transmit Packets",
    )
    def _schedule_packets():
        """A continous event to schedule packets in the queue."""
        self.packet_queue.sort(key=lambda packet: packet.priority)
        for packet in self.packet_queue:
            # check if packet is decoded
            if packet.decoded and not packet.in_transmission:
                logger.debug(f"{simulation.now}:\t{self} is scheduling {packet}.")
                # find the port to transmit the packet to the next hop
                try:
                    src_port = [
                        port
                        for port in self.ports
                        if port.endpoint is packet.next_hop
                    ][0]
                except:
                    raise RuntimeError(
                        f"Can not find a port on {packet.path[0]} to transmit {packet}."
                    )
                # find the port to receive the packet on the next hop
                try:
                    dst_port = [
                        port
                        for port in packet.next_hop.NIC.ports
                        if port.endpoint is packet.current_hop
                    ][0]
                except:
                    raise RuntimeError(
                        f"Can not find a port on {packet.path[1]} to receive {packet}."
                    )
                logger.debug(
                    f"{simulation.now}:\t{self} found src port {src_port} and dst port {dst_port} for {packet}"
                )
                # calculate the available bandwidth and transmission time
                available_bandwidth = min(
                    src_port.bandwidth.amount, dst_port.bandwidth.amount
                )
                logger.debug(
                    f"{simulation.now}:\t{self} found available bandwidth {available_bandwidth} for {packet}"
                )
                # check if the packet can be transmitted
                if available_bandwidth > packet.size:
                    packet.state.append(Constants.INTRANSMISSION)
                    link_speed = min(
                        src_port.bandwidth.capacity, dst_port.bandwidth.capacity
                    )
                    # calculate the transmission time
                    transmission_time = packet.size / link_speed

                    # packet consumes the bandwidth of the src port and returns the bandwidth in future
                    src_port.transmit(packet, transmission_time)

                    # packet consumes the bandwidth of the dst port and returns the bandwidth in future
                    dst_port.receive(packet, transmission_time)

                    logger.info(
                        f"{simulation.now}:\t{packet} in transmission from {src_port.host} to {dst_port.host}"
                    )
            else:
                # pass packets that have not been decoded
                pass

remove_port(endpoint, at)

Remove a port from this virtual NIC.

Source code in PyCloudSim\entity\v_nic.py
256
257
258
259
260
261
262
263
def remove_port(self, endpoint: vHardwareEntity, at: int | float):
    """Remove a port from this virtual NIC."""

    @self.instant_event(at, label=f"{self} Remove Port to {endpoint}")
    def _remove_port():
        for port in self.ports:
            if port.endpoint is endpoint:
                port.terminate(simulation.now)