Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: check subnet remains ip before allocation #43

Merged
merged 1 commit into from
Nov 13, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions pkg/ipamd/uapi.go
Original file line number Diff line number Diff line change
@@ -140,6 +140,11 @@ func (s *ipamServer) uapiAllocateSecondaryIP(number int) (ips []*vpc.IpInfo, err
req.SubnetId = ucloud.String(s.uapi.SubnetID())

for i := 0; i < number; i++ {
err = s.uapiCheckSubnetRemainsIP()
if err != nil {
return nil, err
}

resp, err := cli.AllocateSecondaryIp(req)
if err != nil {
if resp != nil && resp.GetRetCode() == UAPIErrorSubnetNotEnough {
@@ -155,6 +160,38 @@ func (s *ipamServer) uapiAllocateSecondaryIP(number int) (ips []*vpc.IpInfo, err
return
}

// Describe Subnet, check if it still has remain IP(s) to allocate
// If there is no remain IP, returns `ErrOutOfIP`
func (s *ipamServer) uapiCheckSubnetRemainsIP() error {
cli, err := s.uapi.VPCClient()
if err != nil {
return err
}

req := cli.NewDescribeSubnetRequest()
req.ShowAvailableIPs = ucloud.Bool(true)
req.SubnetId = ucloud.String(s.uapi.SubnetID())
req.VPCId = ucloud.String(s.uapi.VPCID())

resp, err := cli.DescribeSubnet(req)
if err != nil {
return err
}

if len(resp.DataSet) == 0 {
return fmt.Errorf("subnet %s not found", s.uapi.SubnetID())
}

subnet := resp.DataSet[0]
ulog.Infof("Subnet remains %d ip to allocate", subnet.AvailableIPs)
if subnet.AvailableIPs <= 0 {
ulog.Warnf("No enough ip in subnet %s to allocate", s.uapi.SubnetID())
return ErrOutOfIP
}

return nil
}

func (s *ipamServer) uapiEnsureSecondaryIP(ip string) (*vpc.IpInfo, error) {
cli, err := s.uapi.VPCClient()
if err != nil {