文档

管理IP前缀

更新时间:

本文展示了如何通过调用阿里云ECS Java SDK来管理弹性网卡的IP前缀,包括分配IP前缀和回收IP前缀。

注意事项

调用分配IP前缀接口时,请注意:

  • 分配IP前缀为同步操作,您可以从请求返回结果中获取分配成功的IP前缀。

  • 只支持可用(Available)或者已附加(InUse)状态下的弹性网卡。

  • 操作主网卡时,网卡附加的实例必须处于运行中(Running)或已停止(Stopped)状态。

  • 您分配的IP前缀必须位于交换机预留段内。更多信息,请参见为交换机添加预留网段

  • 网卡处于可用(Available)状态时,最多可以分配50个辅助私网IP地址。一旦挂载到实例上,网卡能分配的辅助私网IP地址数将受到实例规格的限制。更多信息,请参见实例规格族

  • 分配IPv4前缀时,您不能同时指定Ipv4Prefix.N和Ipv4PrefixCount。分配IPv6前缀时,您不能同时指定Ipv6Prefix.N和Ipv6PrefixCount。

  • 当您选择手动分配前缀时,指定的IPv4前缀掩码必须为/28,指定的IPv6前缀掩码为/80。同时指定的IP前缀必须为标准CIDR。

调用回收IP前缀接口时,请注意:

  • 回收IP前缀为异步操作,获得返回结果仅代表回收IP前缀请求发送成功,回收弹性网卡的IP前缀是否成功需要通过查询网卡详情判断。当查询网卡获得IP前缀结果中不包含希望回收的IP前缀时,说明回收成功;反之,说明回收失败,您可以再次尝试回收IP前缀。

  • 只支持可用(Available)或者已附加(InUse)状态下的弹性网卡。

  • 操作主网卡时,网卡附加的实例必须处于运行中(Running)或已停止(Stopped)状态。

示例代码

以下示例适用于管理弹性网卡的IPv4前缀。

import com.aliyun.ecs20140526.Client;
import com.aliyun.ecs20140526.models.AssignPrivateIpAddressesRequest;
import com.aliyun.ecs20140526.models.DescribeNetworkInterfaceAttributeRequest;
import com.aliyun.ecs20140526.models.DescribeNetworkInterfaceAttributeResponse;
import com.aliyun.ecs20140526.models.DescribeNetworkInterfaceAttributeResponseBody;
import com.aliyun.ecs20140526.models.UnassignPrivateIpAddressesRequest;
import com.aliyun.ecs20140526.models.UnassignPrivateIpAddressesResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.ecs20140526.models.AssignPrivateIpAddressesResponse;
import com.google.gson.Gson;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


public class ManageIpPrefixExample {
    private static final long DESC_INTERVAL_MS = 1000;
    
    /**
     * 使用AK&SK初始化账号Client。
     *
     * 本示例通过从环境变量中读取AccessKey,来实现API访问的身份验证。请根据你的生产环境要求适当调整。
     * 避免AK&SK等关键信息在代码中明文存储是云上安全红线!
     */
    public static Client createClient() throws Exception {
        Config config = new Config()
           .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
           .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // 访问的域名
        config.endpoint = "<yourEcsEndPoint>";
        return new Client(config);
    }

    /**
     * sync assign ipv4 prefix
     * @param ecsClient
     * @param regionId
     * @param eniId
     * @param ipPrefixes
     * @param prefixCount
     * @return
     */
    public static AssignPrivateIpAddressesResponse assignPrivateIpAddresses(Client ecsClient, String regionId,
                                                                            String eniId, List<String> ipPrefixes,
                                                                            Integer prefixCount)  {
        AssignPrivateIpAddressesRequest request = new AssignPrivateIpAddressesRequest();
        request.setRegionId(regionId);
        request.setNetworkInterfaceId(eniId);
        if (CollectionUtils.isNotEmpty(ipPrefixes)) {
            request.setIpv4Prefix(ipPrefixes);
        } else if (null != prefixCount && prefixCount > 0) {
            request.setIpv4PrefixCount(prefixCount);
        }
        AssignPrivateIpAddressesResponse response = null;
        try {
            response = ecsClient.assignPrivateIpAddresses(request);
            System.out.println(new Gson().toJson(response));
        } catch (TeaException te) {
            System.out.println("ErrCode:" + te.getCode());
            System.out.println("ErrMsg:" + te.getMessage());
            System.out.println("RequestId:" + te.getData().get("RequestId"));
        } catch (Exception e) {
            System.out.println("ErrCode:" + e.getMessage());
        }
        return response;
    }


    /**
     * async unassing ipv4 prefix
     * @param ecsClient
     * @param regionId
     * @param eniId
     * @param ipPrefixes
     * @return
     */
    public static UnassignPrivateIpAddressesResponse unassignPrivateIpAddresses(Client ecsClient, String regionId,
                                                                                String eniId, List<String> ipPrefixes) {
        UnassignPrivateIpAddressesRequest request = new UnassignPrivateIpAddressesRequest();
        request.setRegionId(regionId);
        request.setNetworkInterfaceId(eniId);
        if (CollectionUtils.isNotEmpty(ipPrefixes)) {
            request.setIpv4Prefix(ipPrefixes);
        }
        UnassignPrivateIpAddressesResponse response = null;
        try {
            response = ecsClient.unassignPrivateIpAddresses(request);
            System.out.println(new Gson().toJson(response));
        } catch (TeaException te) {
            System.out.println("ErrCode:" + te.getCode());
            System.out.println("ErrMsg:" + te.getMessage());
            System.out.println("RequestId:" + te.getData().get("RequestId"));
        } catch (Exception e) {
            System.out.println("ErrCode:" + e.getMessage());
        }
        return response;
    }

    /**
     * describe network interface attribute
     * @param ecsClient
     * @param regionId
     * @param eniId
     * @return
     */
    public static DescribeNetworkInterfaceAttributeResponse describeNetworkInterfaceAttribute(Client ecsClient, String regionId,
                                                                                              String eniId) {
        DescribeNetworkInterfaceAttributeRequest request = new DescribeNetworkInterfaceAttributeRequest();
        request.setRegionId(regionId);
        request.setNetworkInterfaceId(eniId);
        DescribeNetworkInterfaceAttributeResponse response = null;

        try {
            response = ecsClient.describeNetworkInterfaceAttribute(request);
            System.out.println(new Gson().toJson(response));
        } catch (TeaException te) {
            System.out.println("ErrCode:" + te.getCode());
            System.out.println("ErrMsg:" + te.getMessage());
            System.out.println("RequestId:" + te.getData().get("RequestId"));
        } catch (Exception e) {
            System.out.println("ErrCode:" + e.getMessage());
        }
        return response;
    }

    /**
     * check whether eni successfully unassign ipv4 prefixes with max retry count
     * @param ecsClient
     * @param regionId
     * @param eniId
     * @param ipv4PrefixList
     * @param maxDescTimes
     * @return
     */
    public static boolean isUnassignIpv4PrefixSuccess(Client ecsClient, String regionId, String eniId,
                                                List<String> ipv4PrefixList, int maxDescTimes) {
        if (CollectionUtils.isEmpty(ipv4PrefixList)) {
            return Boolean.TRUE;
        }
        for (int i = 0; i < maxDescTimes; i++) {
            DescribeNetworkInterfaceAttributeResponse response = describeNetworkInterfaceAttribute(ecsClient, regionId, eniId);
            if (Objects.isNull(response.getBody())) {
                System.out.println("DescribeNetworkInterfaces return null, please check your input.");
                break;
            }

            List<DescribeNetworkInterfaceAttributeResponseBody
                    .DescribeNetworkInterfaceAttributeResponseBodyIpv4PrefixSetsIpv4PrefixSet> assignedIpv4PrefixDOList =
                    response.getBody().getIpv4PrefixSets().getIpv4PrefixSet();
            if (CollectionUtils.isEmpty(assignedIpv4PrefixDOList)) {
                return Boolean.TRUE;
            }

            List<String> assignedIpv4PrefixList = assignedIpv4PrefixDOList.stream()
                    .map(DescribeNetworkInterfaceAttributeResponseBody
                            .DescribeNetworkInterfaceAttributeResponseBodyIpv4PrefixSetsIpv4PrefixSet::getIpv4Prefix)
                    .collect(Collectors.toList());

            for (String ipv4Prefix : ipv4PrefixList) {
                if (assignedIpv4PrefixList.contains(ipv4Prefix)) {
                    System.out.printf("This is the %s times describe networkInterface, eni id %s is still unassigning ipv4 prefix %s.%n",
                            i + 1, eniId, ipv4Prefix);
                    break;
                } else {
                    ipv4PrefixList.remove(ipv4Prefix);
                }
            }

            if (CollectionUtils.isEmpty(ipv4PrefixList)) {
                return Boolean.TRUE;
            }
            interval(DESC_INTERVAL_MS);
        }
        return CollectionUtils.isEmpty(ipv4PrefixList);
    }

    public static void interval(long intervalMs) {
        try {
            Thread.sleep(intervalMs);
        } catch (InterruptedException ignored) {

        }
    }

    public static void main(String[] args) throws Exception {
        String regionId = "<regionId>";
        String eniId = "<yourEniId>";
        int maxRetryCnt = 3;
        List<String> ipPrefixList = new ArrayList<>();
        String ipv4Prefix1 = "192.168.10.0/24";
        String ipv4Prefix2 = "192.168.11.0/24";
        ipPrefixList.add(ipv4Prefix1);
        ipPrefixList.add(ipv4Prefix2);

        Client ecsClient = createClient();

        // assign with specify ipv4 prefixes
        AssignPrivateIpAddressesResponse assignResponse = assignPrivateIpAddresses(ecsClient, regionId, eniId, null, 1);
        List<String> assignedIpv4PrefixList = assignResponse.getBody().getAssignedPrivateIpAddressesSet().getIpv4PrefixSet().getIpv4Prefixes();
        if (CollectionUtils.isNotEmpty(assignedIpv4PrefixList)) {
            System.out.printf(
                    "Sync assign network interface %s ipv4 prefix success. Ipv4 prefixes are %s.",
                    eniId, StringUtils.join(assignedIpv4PrefixList, ","));
        } else {
            System.out.println("Sync assign network interface %s ipv4 prefix fail. Please retry.");
        }

        // unassign ipv4 perfix with max retry
        unassignPrivateIpAddresses(ecsClient, regionId, eniId, assignedIpv4PrefixList);
        if (isUnassignIpv4PrefixSuccess(ecsClient, regionId, eniId, assignedIpv4PrefixList, maxRetryCnt)) {
            System.out.printf(
                    "Async unassign network interface %s ipv4 prefix success. Ipv4 prefixes are %s.",
                    eniId, StringUtils.join(assignedIpv4PrefixList, ","));
        } else {
            System.out.println("Async unassign network interface %s ipv4 prefix fail. Please retry.");
        }

        // assign with specify ipv4 prefixes
        assignResponse = assignPrivateIpAddresses(ecsClient, regionId, eniId, ipPrefixList, 0);
        assignedIpv4PrefixList = assignResponse.getBody().getAssignedPrivateIpAddressesSet().getIpv4PrefixSet().getIpv4Prefixes();
        if (assignedIpv4PrefixList.contains(ipv4Prefix1) && assignedIpv4PrefixList.contains(ipv4Prefix2)) {
            System.out.printf(
                    "Sync assign network interface %s ipv4 prefix success. Ipv4 prefixes are %s.",
                    eniId, StringUtils.join(assignedIpv4PrefixList, ","));
        } else {
            System.out.println("Sync assign network interface %s ipv4 prefix fail. Please retry.");
        }

        // unassign ipv4 perfix with max retry
        unassignPrivateIpAddresses(ecsClient, regionId, eniId, assignedIpv4PrefixList);
        if (isUnassignIpv4PrefixSuccess(ecsClient, regionId, eniId, assignedIpv4PrefixList, maxRetryCnt)) {
            System.out.printf(
                    "Async unassign network interface %s ipv4 prefix success. Ipv4 prefixes are %s.",
                    eniId, StringUtils.join(assignedIpv4PrefixList, ","));
        } else {
            System.out.println("Async unassign network interface %s ipv4 prefix fail. Please retry.");
        }

    }

}
  • 本页导读 (1)
文档反馈