Skip to content

Commit

Permalink
Update hyperv.py
Browse files Browse the repository at this point in the history
  • Loading branch information
SRIKKANTH committed Jan 29, 2025
1 parent 5f5fc73 commit 4a04377
Showing 1 changed file with 13 additions and 19 deletions.
32 changes: 13 additions & 19 deletions lisa/tools/hyperv.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import time
from dataclasses import dataclass
from enum import Enum
from typing import Dict, Optional, Set
from typing import Any, Dict, Optional, Set

from assertpy import assert_that
from dataclasses_json import dataclass_json
Expand Down Expand Up @@ -308,8 +308,8 @@ def create_nat(self, name: str, ip_range: str) -> None:

def add_nat_mapping(self, nat_name: str, internal_ip: str) -> int:
external_port = self._get_next_available_nat_port()
# delete NAT mapping if the port is already in use
self.delete_nat_mapping(external_port=external_port)
if self.get_nat_mapping_id(external_port):
raise LisaException(f"Mapping for port {external_port} already exists")

# create a new NAT
self.node.tools[PowerShell].run_cmdlet(
Expand All @@ -320,32 +320,26 @@ def add_nat_mapping(self, nat_name: str, internal_ip: str) -> int:
)
return external_port

def get_nat_mapping_id(self, external_port: int) -> Any:
return self.node.tools[PowerShell].run_cmdlet(
f"Get-NetNatStaticMapping | "
f"Where-Object {{$_.ExternalPort -eq {external_port}}}"
f" | Select-Object -ExpandProperty StaticMappingID",
force_run=True,
)

# delete NAT mapping for a port or internal IP
def delete_nat_mapping(
self, external_port: Optional[int] = None, internal_ip: Optional[str] = None
) -> None:
mapping_id = None
if external_port is not None:
# get the NAT mapping id for the port
mapping_id = self.node.tools[PowerShell].run_cmdlet(
f"Get-NetNatStaticMapping | "
f"Where-Object {{$_.ExternalPort -eq {external_port}}}"
f" | Select-Object -ExpandProperty StaticMappingID",
force_run=True,
)
elif internal_ip is not None:
mapping_id = self.node.tools[PowerShell].run_cmdlet(
f"Get-NetNatStaticMapping | "
f"Where-Object {{$_.InternalIPAddress -eq '{internal_ip}'}}"
f" | Select-Object -ExpandProperty StaticMappingID",
force_run=True,
)
if external_port is None:
external_port = self.node.tools[PowerShell].run_cmdlet(
f"Get-NetNatStaticMapping | "
f"Where-Object {{$_.InternalIPAddress -eq '{internal_ip}'}}"
f" | Select-Object -ExpandProperty ExternalPort",
force_run=True,
)
mapping_id = self.get_nat_mapping_id(external_port)
if mapping_id:
# delete the NAT mapping if it exists
self.node.tools[PowerShell].run_cmdlet(
Expand Down

0 comments on commit 4a04377

Please sign in to comment.