[pve-devel] [WIP v2 pve-network 06/10] ipam: Add helper methods for DHCP to PVE IPAM

Stefan Lendl s.lendl at proxmox.com
Fri Oct 27 13:51:50 CEST 2023


Stefan Hanreich <s.hanreich at proxmox.com> writes:

> Those methods are used by the DHCP plugins to attain the next free
> IP address for a given DHCP range, as well as delete all entries with
> a certain MAC address.
>
> Signed-off-by: Stefan Hanreich <s.hanreich at proxmox.com>
> ---
>  src/PVE/Network/SDN/Ipams/PVEPlugin.pm | 64 ++++++++++++++++++++++++++
>  1 file changed, 64 insertions(+)
>
> diff --git a/src/PVE/Network/SDN/Ipams/PVEPlugin.pm b/src/PVE/Network/SDN/Ipams/PVEPlugin.pm
> index 3e8ffc5..fcc8282 100644
> --- a/src/PVE/Network/SDN/Ipams/PVEPlugin.pm
> +++ b/src/PVE/Network/SDN/Ipams/PVEPlugin.pm
> @@ -156,6 +156,70 @@ sub add_next_freeip {
>      return "$freeip/$mask";
>  }
>
> +sub add_dhcp_ip {
> +    my ($class, $subnet, $dhcp_range, $data) = @_;
> +
> +    my $cidr = $subnet->{cidr};
> +    my $zone = $subnet->{zone};
> +
> +    cfs_lock_file($ipamdb_file, undef, sub {
> +	my $db = read_db();
> +
> +	my $dbzone = $db->{zones}->{$zone};
> +	die "zone '$zone' doesn't exist in IPAM DB\n" if !$dbzone;
> +
> +	my $dbsubnet = $dbzone->{subnets}->{$cidr};
> +	die "subnet '$cidr' doesn't exist in IPAM DB\n" if !$dbsubnet;
> +
> +	my $ip = new Net::IP ("$dhcp_range->{'start-address'} - $dhcp_range->{'end-address'}")
> +	    or die "Invalid IP address(es) in DHCP Range!\n";
> +
> +	do {
> +	    my $ip_address = $ip->ip();
> +	    if (!$dbsubnet->{ips}->{$ip_address}) {
> +		$dbsubnet->{ips}->{$ip_address} = $data;
> +		write_db($db);
> +
> +		return $ip_address;
> +	    }
> +	} while (++$ip);
> +
> +	die "No free IP left in DHCP Range $dhcp_range->{'start-address'}:$dhcp_range->{'end-address'}}\n";
> +    });
> +}

This duplicates existing functionality to find a new IP.
Regarding the reply from Alexandre, we may not need to implement
dhcp_range feature and solely rely on IPAM generating a new IP.

> +
> +sub del_dhcp_ip {
> +    my ($class, $subnet, $mac) = @_;
> +
> +    my $cidr = $subnet->{cidr};
> +    my $zone = $subnet->{zone};
> +
> +    my $returned_ip = undef;
> +
> +    cfs_lock_file($ipamdb_file, undef, sub {
> +	my $db = read_db();
> +
> +	die "zone $zone don't exist in ipam db" if !$db->{zones}->{$zone};
> +	my $dbzone = $db->{zones}->{$zone};
> +
> +	die "subnet $cidr don't exist in ipam db" if !$dbzone->{subnets}->{$cidr};
> +	my $dbsubnet = $dbzone->{subnets}->{$cidr};
> +
> +	foreach my $ip_address (keys %{$dbsubnet->{ips}}) {
> +	    my $data = $dbsubnet->{ips}->{$ip_address};
> +	    next if !$data->{mac} || $data->{mac} ne $mac;
> +
> +	    delete $dbsubnet->{ips}->{$ip_address};
> +	    write_db($db);
> +
> +	    $returned_ip = $ip_address;
> +	}
> +    });
> +    die "$@" if $@;
> +
> +    return $returned_ip;
> +}
> +
>  sub del_ip {
>      my ($class, $plugin_config, $subnetid, $subnet, $ip) = @_;





More information about the pve-devel mailing list