search
HomeOperation and MaintenanceLinux Operation and MaintenanceHow to use Alibaba Cloud ECS SDK to create and manage preemptible instances reasonably and quickly

The content of this article is about how to use Alibaba Cloud ECS SDK to create and manage preemptible instances reasonably and quickly. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. .

Manage preemptible instances

Preparation

##Before performing the operation, you need:

Learn about the instance specifications and regions that meet your business requirements.

Be familiar with the basic knowledge and calling methods of Alibaba Cloud ECS SDK. For details, please refer to the SDK usage instructions.

Note:

The preemptible instance code requires ECS SDK version 4.2.0 or above. Taking the Java POM dependency as an example, modify and introduce the pom dependency:

<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>aliyun-java-sdk-core</artifactId>
  <version>3.2.8</version>
</dependency>
<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>aliyun-java-sdk-ecs</artifactId>
  <version>4.2.0</version>
</dependency>

Query the region and available instance specifications

Use the OpenAPI DescribeZones query to create The region and available instance specifications of preemptible instances. Sample code is shown below.

OpenApiCaller.java
public class OpenApiCaller {
  IClientProfile profile;
  IAcsClient client;
  public OpenApiCaller() {
      profile = DefaultProfile.getProfile("cn-hangzhou", AKSUtil.accessKeyId, AKSUtil.accessKeySecret);
      client = new DefaultAcsClient(profile);
  }
  public  <T extends AcsResponse> T doAction(AcsRequest<T> var1) {
      try {
          return  client.getAcsResponse(var1);
      } catch (Throwable e) {
          e.printStackTrace();
          return null;
      }
  }
}
DescribeZonesSample.java
public class DescribeZonesSample {
  public static void main(String[] args) {
      OpenApiCaller caller = new OpenApiCaller();
      DescribeZonesRequest request = new DescribeZonesRequest();
      request.setRegionId("cn-zhangjiakou");//可以通过 DescribeRegionsRequest 获取每个地域的 RegionId
      request.setSpotStrategy("SpotWithPriceLimit");//对于查询是否可购买抢占式实例此项必填
      request.setInstanceChargeType("PostPaid");//后付费模式,抢占式实例必须是后付费模式
      DescribeZonesResponse response = caller.doAction(request);
      System.out.println(JSON.toJSONString(response));
  }
}

The following is the output result. You can view the available instance specifications, disk types, network types and other information for each region.

{
  "requestId": "388D6321-E587-470C-8CFA-8985E2963DAE",
  "zones": [
      {
          "localName": "华北 3 可用区 A",
          "zoneId": "cn-zhangjiakou-a",
          "availableDiskCategories": [
              "cloud_ssd",
              "cloud_efficiency"
          ],
          "availableInstanceTypes": [
              "ecs.e4.large",
              "ecs.n4.4xlarge",
              "ecs.sn2.medium",
              "ecs.i1.2xlarge",
              "ecs.se1.2xlarge",
              "ecs.n4.xlarge",
              "ecs.se1ne.2xlarge",
              "ecs.se1.large",
              "ecs.sn2.xlarge",
              "ecs.se1ne.xlarge",
              "ecs.xn4.small",
              "ecs.sn2ne.4xlarge",
              "ecs.se1ne.4xlarge",
              "ecs.sn1.medium",
              "ecs.n4.8xlarge",
              "ecs.mn4.large",
              "ecs.e4.2xlarge",
              "ecs.mn4.2xlarge",
              "ecs.mn4.8xlarge",
              "ecs.n4.2xlarge",
              "ecs.e4.xlarge",
              "ecs.sn2ne.large",
              "ecs.sn2ne.xlarge",
              "ecs.sn1ne.large",
              "ecs.n4.large",
              "ecs.sn1.3xlarge",
              "ecs.e4.4xlarge",
              "ecs.sn1ne.2xlarge",
              "ecs.e4.small",
              "ecs.i1.4xlarge",
              "ecs.se1.4xlarge",
              "ecs.sn2ne.2xlarge",
              "ecs.sn2.3xlarge",
              "ecs.i1.xlarge",
              "ecs.n4.small",
              "ecs.sn1ne.4xlarge",
              "ecs.mn4.4xlarge",
              "ecs.sn1ne.xlarge",
              "ecs.se1ne.large",
              "ecs.sn2.large",
              "ecs.i1-c5d1.4xlarge",
              "ecs.sn1.xlarge",
              "ecs.sn1.large",
              "ecs.mn4.small",
              "ecs.mn4.xlarge",
              "ecs.se1.xlarge"
          ],
          "availableResourceCreation": [
              "VSwitch",
              "IoOptimized",
              "Instance",
              "Disk"
          ],
          "availableResources": [
              {
                  "dataDiskCategories": [
                      "cloud_ssd",
                      "cloud_efficiency"
                  ],
                  "instanceGenerations": [
                      "ecs-3",
                      "ecs-2"
                  ],
                  "instanceTypeFamilies": [
                      "ecs.mn4",
                      "ecs.sn1",
                      "ecs.sn2",
                      "ecs.sn1ne",
                      "ecs.xn4",
                      "ecs.i1",
                      "ecs.se1",
                      "ecs.e4",
                      "ecs.n4",
                      "ecs.se1ne",
                      "ecs.sn2ne"
                  ],
                  "instanceTypes": [
                      "ecs.n4.4xlarge",
                      "ecs.sn2.medium",
                      "ecs.i1.2xlarge",
                      "ecs.se1.2xlarge",
                      "ecs.n4.xlarge",
                      "ecs.se1ne.2xlarge",
                      "ecs.se1.large",
                      "ecs.sn2.xlarge",
                      "ecs.se1ne.xlarge",
                      "ecs.xn4.small",
                      "ecs.sn2ne.4xlarge",
                      "ecs.se1ne.4xlarge",
                      "ecs.sn1.medium",
                      "ecs.n4.8xlarge",
                      "ecs.mn4.large",
                      "ecs.mn4.2xlarge",
                      "ecs.mn4.8xlarge",
                      "ecs.n4.2xlarge",
                      "ecs.sn2ne.large",
                      "ecs.sn2ne.xlarge",
                      "ecs.sn1ne.large",
                      "ecs.n4.large",
                      "ecs.sn1.3xlarge",
                      "ecs.sn1ne.2xlarge",
                      "ecs.e4.small",
                      "ecs.i1.4xlarge",
                      "ecs.se1.4xlarge",
                      "ecs.sn2ne.2xlarge",
                      "ecs.sn2.3xlarge",
                      "ecs.i1.xlarge",
                      "ecs.n4.small",
                      "ecs.sn1ne.4xlarge",
                      "ecs.mn4.4xlarge",
                      "ecs.sn1ne.xlarge",
                      "ecs.se1ne.large",
                      "ecs.sn2.large",
                      "ecs.i1-c5d1.4xlarge",
                      "ecs.sn1.xlarge",
                      "ecs.sn1.large",
                      "ecs.mn4.small",
                      "ecs.mn4.xlarge",
                      "ecs.se1.xlarge"
                  ],
                  "ioOptimized": true,
                  "networkTypes": [
                      "vpc"
                  ],
                  "systemDiskCategories": [
                      "cloud_ssd",
                      "cloud_efficiency"
                  ]
              }
          ],
          "availableVolumeCategories": [
              "san_ssd",
              "san_efficiency"
          ]
      }
  ]
}

Query the historical price of a preemptible instance

Use OpenAPI DescribeSpotPriceHistory to query the price change data of a preemptible instance in the last 30 days. To obtain the region and specification information with the best price/performance ratio, the sample code (DescribeSpotPriceHistorySample.java) is as follows.

public class DescribeSpotPriceHistorySample {
    public static void main(String[] args) {
        OpenApiCaller caller = new OpenApiCaller();
        List<DescribeSpotPriceHistoryResponse.SpotPriceType>
         result = new ArrayList<DescribeSpotPriceHistoryResponse.SpotPriceType>();
        int offset = 0;
        while (true) {
            DescribeSpotPriceHistoryRequest request = new DescribeSpotPriceHistoryRequest();
            request.setRegionId("cn-hangzhou");
            //可以通过 DescribeRegionsRequest 获取可购买的每个地域的 RegionId
            request.setZoneId("cn-hangzhou-b");//可用区必填
            request.setInstanceType("ecs.sn2.medium");//参考 DescribeZones 返回的实例类型,必填
            request.setNetworkType("vpc");//参考 DescribeZones 返回的网络类型,必填
//            request.setIoOptimized("optimized");
                        //是否 I/O 优化类型,DescribeZones 返回的 IoOptimized,选填
//            request.setStartTime("2017-09-20T08:45:08Z");//价格开始时间,选填,默认 3 天内数据
//            request.setEndTime("2017-09-28T08:45:08Z");//价格结束时间,选填
            request.setOffset(offset);
            DescribeSpotPriceHistoryResponse response = caller.doAction(request);
            if (response != null && response.getSpotPrices() != null) {
                result.addAll(response.getSpotPrices());
            }
            if (response.getNextOffset() == null || response.getNextOffset() == 0) {
                break;
            } else {
                offset = response.getNextOffset();
            }
        }
        if (!result.isEmpty()) {
            for (DescribeSpotPriceHistoryResponse.SpotPriceType spotPriceType : result) {
                System.out.println(spotPriceType.getTimestamp() + "---> 
                spotPrice:" + spotPriceType.getSpotPrice() + "---->
                originPrice:" + spotPriceType.getOriginPrice());
            }
            System.out.println(result.size());
        } else {
        }
    }
}

The following are examples of returned results.

2017-09-26T06:28:55Z--->spotPrice:0.24---->originPrice:1.2
2017-09-26T14:00:00Z--->spotPrice:0.36---->originPrice:1.2
2017-09-26T15:00:00Z--->spotPrice:0.24---->originPrice:1.2
2017-09-27T14:00:00Z--->spotPrice:0.36---->originPrice:1.2
2017-09-27T15:00:00Z--->spotPrice:0.24---->originPrice:1.2
2017-09-28T14:00:00Z--->spotPrice:0.36---->originPrice:1.2
2017-09-28T15:00:00Z--->spotPrice:0.24---->originPrice:1.2
2017-09-29T06:28:55Z--->spotPrice:0.24---->originPrice:1.2

Repeat the above steps, and you can determine the price trend and recent price of resources of this specification in the availability zone.

Note:

You can use the average price and maximum price to decide whether you can accept the purchase of the preemptible instance. You can also analyze historical price data through a more reasonable data model and adjust the creation at any time. Resource specifications and availability zones to achieve the best price/performance ratio.

Create a preemptible instance

Before creating a preemptible instance, you need to complete the following work:

If you use To create a preemptible instance from a custom image, you must have created a custom image.

Create a security group in the console, or use OpenAPI CreateSecurityGroup to create a security group and obtain the security group ID (SecurityGroupId).

Create a VPC and switch in the console, or use OpenAPI CreateVpc and CreateVSwitch to create it, and get the switch ID (VSwitchId).

Use OpenAPI CreateInstance to create a preemptible instance. The sample code (CreateInstaneSample.java) is as follows.

public class CreateInstaneSample {
    public static void main(String[] args) {
        OpenApiCaller caller = new OpenApiCaller();
        CreateInstanceRequest request = new CreateInstanceRequest();
        request.setRegionId("cn-hangzhou");//地域 ID
        request.setZoneId("cn-hangzhou-b"); //可用区ID
        request.setSecurityGroupId("sg-bp11nhf94ivkdxwb2gd4");//提前创建的安全组 ID
        request.setImageId("centos_7_03_64_20G_alibase_20170818.vhd");
        //建议选择您自己在该地域准备的自定义镜像
        request.setVSwitchId("vsw-bp164cyonthfudn9kj5br");//VPC 类型需要交换机 ID
        request.setInstanceType("ecs.sn2.medium"); //填入您询价后需要购买的规格
        request.setIoOptimized("optimized");//参考 DescirbeZones 返回参数
        request.setSystemDiskCategory("cloud_ssd");
        //参考 DescirbeZones 返回参数,多选一 cloud_ssd, cloud_efficiency, cloud
        request.setSystemDiskSize(40);
        request.setInstanceChargeType("PostPaid");//抢占式实例必须后付费
        request.setSpotStrategy("SpotWithPriceLimit");
        //SpotWithPriceLimit 出价模式,SpotAsPriceGo 不用出价,最高按量付费价格
        request.setSpotPriceLimit(0.25F);//SpotWithPriceLimit 
        出价模式生效,您能接受的最高价格,单位为元每小时,必须高于当前的市场成交价才能成功
        CreateInstanceResponse response = caller.doAction(request);
        System.out.println(response.getInstanceId());
    }
}

Recycling of preemptible instances

When preemptible instances may be forcibly recycled due to price factors or changes in market supply and demand. At this time, the interrupt of the preemptible instance will be triggered. Before releasing, the preemptible instance will enter the locked state, indicating that the instance will be automatically recycled. You can automate the exit logic for an instance based on its recycling status.

Currently, you can obtain the interrupt lock status of a preemptible instance through any of the following methods:

Get it through instance metadata. Run the following command:

curl &#39;http://100.100.100.200/latest/meta-data/instance/spot/termination-time&#39;

If the return value is empty, the instance can be used continuously. If information in a format similar to 2015-01-05T18:02:00Z (UTC time) is returned, it means that the instance will be released at this time.

Use OpenAPI DescribeInstances to determine whether the instance has entered the pending recycling state based on the returned OperationLocks. The code sample is as follows (DescribeInstancesSample.java).

public class DescribeInstancesSample {
  public static void main(String[] args) throws InterruptedException {
      OpenApiCaller caller = new OpenApiCaller();
      JSONArray allInstances = new JSONArray();
      allInstances.addAll(Arrays.asList("i-bp18hgfai8ekoqwo0y2n", "i-bp1ecbyds24ij63w146c"));
      while (!allInstances.isEmpty()) {
          DescribeInstancesRequest request = new DescribeInstancesRequest();
          request.setRegionId("cn-hangzhou");
          request.setInstanceIds(allInstances.toJSONString());//指定实例 ID,效率最高
          DescribeInstancesResponse response = caller.doAction(request);
          List<DescribeInstancesResponse.Instance> instanceList = response.getInstances();
          if (instanceList != null && !instanceList.isEmpty()) {
              for (DescribeInstancesResponse.Instance instance : instanceList) {
                  System.out.println
               ("result:instance:" + instance.getInstanceId() + ",az:" + instance.getZoneId());
                  if (instance.getOperationLocks() != null) {
            for (DescribeInstancesResponse.Instance.LockReason 
            lockReason : instance.getOperationLocks()) {
   System.out.println("instance:" + instance.getInstanceId() + "-->
   lockReason:" + lockReason.getLockReason() + ",vmStatus:" + instance.getStatus());
          if ("Recycling".equals(lockReason.getLockReason())) {
           //do your action
  System.out.println("spot instance will be recycled immediately, 
  instance id:" + instance.getInstanceId());
        allInstances.remove(instance.getInstanceId());
                          }
                      }
                  }
              }
              System.out.print("try describeInstances again later ...");
              Thread.sleep(2 * 60 * 1000);
          } else {
              break;
          }
      }
  }
}

The output result when recycling is triggered is as follows:

instance:i-bp1ecbyds24ij63w146c-->lockReason:Recycling,vmStatus:Stopped
spot instance will be recycled immediately, instance id:i-bp1ecbyds24ij63w146c


The above is the detailed content of How to use Alibaba Cloud ECS SDK to create and manage preemptible instances reasonably and quickly. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Linux: How to Enter Recovery Mode (and Maintenance)Linux: How to Enter Recovery Mode (and Maintenance)Apr 18, 2025 am 12:05 AM

The steps to enter Linux recovery mode are: 1. Restart the system and press the specific key to enter the GRUB menu; 2. Select the option with (recoverymode); 3. Select the operation in the recovery mode menu, such as fsck or root. Recovery mode allows you to start the system in single-user mode, perform file system checks and repairs, edit configuration files, and other operations to help solve system problems.

Linux's Essential Components: Explained for BeginnersLinux's Essential Components: Explained for BeginnersApr 17, 2025 am 12:08 AM

The core components of Linux include the kernel, file system, shell and common tools. 1. The kernel manages hardware resources and provides basic services. 2. The file system organizes and stores data. 3. Shell is the interface for users to interact with the system. 4. Common tools help complete daily tasks.

Linux: A Look at Its Fundamental StructureLinux: A Look at Its Fundamental StructureApr 16, 2025 am 12:01 AM

The basic structure of Linux includes the kernel, file system, and shell. 1) Kernel management hardware resources and use uname-r to view the version. 2) The EXT4 file system supports large files and logs and is created using mkfs.ext4. 3) Shell provides command line interaction such as Bash, and lists files using ls-l.

Linux Operations: System Administration and MaintenanceLinux Operations: System Administration and MaintenanceApr 15, 2025 am 12:10 AM

The key steps in Linux system management and maintenance include: 1) Master the basic knowledge, such as file system structure and user management; 2) Carry out system monitoring and resource management, use top, htop and other tools; 3) Use system logs to troubleshoot, use journalctl and other tools; 4) Write automated scripts and task scheduling, use cron tools; 5) implement security management and protection, configure firewalls through iptables; 6) Carry out performance optimization and best practices, adjust kernel parameters and develop good habits.

Understanding Linux's Maintenance Mode: The EssentialsUnderstanding Linux's Maintenance Mode: The EssentialsApr 14, 2025 am 12:04 AM

Linux maintenance mode is entered by adding init=/bin/bash or single parameters at startup. 1. Enter maintenance mode: Edit the GRUB menu and add startup parameters. 2. Remount the file system to read and write mode: mount-oremount,rw/. 3. Repair the file system: Use the fsck command, such as fsck/dev/sda1. 4. Back up the data and operate with caution to avoid data loss.

How Debian improves Hadoop data processing speedHow Debian improves Hadoop data processing speedApr 13, 2025 am 11:54 AM

This article discusses how to improve Hadoop data processing efficiency on Debian systems. Optimization strategies cover hardware upgrades, operating system parameter adjustments, Hadoop configuration modifications, and the use of efficient algorithms and tools. 1. Hardware resource strengthening ensures that all nodes have consistent hardware configurations, especially paying attention to CPU, memory and network equipment performance. Choosing high-performance hardware components is essential to improve overall processing speed. 2. Operating system tunes file descriptors and network connections: Modify the /etc/security/limits.conf file to increase the upper limit of file descriptors and network connections allowed to be opened at the same time by the system. JVM parameter adjustment: Adjust in hadoop-env.sh file

How to learn Debian syslogHow to learn Debian syslogApr 13, 2025 am 11:51 AM

This guide will guide you to learn how to use Syslog in Debian systems. Syslog is a key service in Linux systems for logging system and application log messages. It helps administrators monitor and analyze system activity to quickly identify and resolve problems. 1. Basic knowledge of Syslog The core functions of Syslog include: centrally collecting and managing log messages; supporting multiple log output formats and target locations (such as files or networks); providing real-time log viewing and filtering functions. 2. Install and configure Syslog (using Rsyslog) The Debian system uses Rsyslog by default. You can install it with the following command: sudoaptupdatesud

How to choose Hadoop version in DebianHow to choose Hadoop version in DebianApr 13, 2025 am 11:48 AM

When choosing a Hadoop version suitable for Debian system, the following key factors need to be considered: 1. Stability and long-term support: For users who pursue stability and security, it is recommended to choose a Debian stable version, such as Debian11 (Bullseye). This version has been fully tested and has a support cycle of up to five years, which can ensure the stable operation of the system. 2. Package update speed: If you need to use the latest Hadoop features and features, you can consider Debian's unstable version (Sid). However, it should be noted that unstable versions may have compatibility issues and stability risks. 3. Community support and resources: Debian has huge community support, which can provide rich documentation and

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor