SDK使用规范

ZStack ZSphere提供Java SDK和Python SDK。您可以通过SDK调用ZStack ZSphere API,实现对应功能。

本章介绍SDK兼容版本以及Java SDK和Python SDK的使用方法。

SDK概述与兼容性

ZStack ZSphere支持以下SDK和运行环境:

  • Java SDK:Java 8
  • Python SDK:Python 2.7

具体API的SDK调用示例请参见对应API正文。

Java SDK

环境准备

使用Java SDK前,需准备以下软件和文件:

  • Java 8
  • Java开发工具,例如IntelliJ IDEA或Eclipse
  • ZStack ZSphere安装包中的sdk-5.1.0.jar
  • SDK依赖的第三方JAR

SDK使用

  1. 新建Java Maven项目。
  2. 将SDK JAR添加到项目Libraries,并在项目中添加SDK依赖的第三方JAR。
  3. 参考具体API正文中的Java SDK示例编写代码。
  4. 编译并运行项目。

查询虚拟机示例

以下示例使用Java SDK登录ZStack ZSphere并查询虚拟机:

import org.zstack.sdk.*;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.UnsupportedEncodingException;
import java.util.List;

public class ZSphereSDKDemo {
    public static void main(String[] args) {
        String serverHostname = "MANAGEMENT_NODE_IP";
        String accountName = "ACCOUNT_NAME";
        String password = "ACCOUNT_PASSWORD";

        ZSClient.configure(
                new ZSConfig.Builder()
                        .setHostname(serverHostname)
                        .setPort(8080)
                        .setContextPath("zstack")
                        .build()
        );

        String sessionId = getSessionByLoginAccount(accountName, password);

        QueryVmInstanceAction action = new QueryVmInstanceAction();
        action.sessionId = sessionId;
        QueryVmInstanceAction.Result result = action.call();
        result.throwExceptionIfError();

        List<VmInstanceInventory> vmList = result.value.getInventories();
        System.out.println("查询到的虚拟机数量:" +
                (vmList != null ? vmList.size() : 0));
    }

    private static String getSessionByLoginAccount(
            String accountName, String password) {
        LogInByAccountAction action = new LogInByAccountAction();
        action.accountName = accountName;
        action.password = encryptToSHA512(password);

        LogInByAccountAction.Result result = action.call();
        result.throwExceptionIfError();
        return result.value.getInventory().getUuid();
    }

    private static String encryptToSHA512(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-512");
            md.update(input.getBytes("utf8"));
            BigInteger number = new BigInteger(1, md.digest());
            return String.format("%0128x", number);
        } catch (NoSuchAlgorithmException |
                 UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}

将示例中的管理节点IP地址、账户和密码替换为实际信息后,编译并运行代码。

Python SDK

环境准备

Python SDK兼容Python 2.7。可在管理节点执行以下命令,启用ZStack-ZSphere CLI使用的Python虚拟环境:

source /var/lib/zstack/virtualenv/zstackcli/bin/activate

若在其他主机使用,可将管理节点的/var/lib/zstack/virtualenv/zstackcli目录复制到该主机。该主机需安装Python 2并与管理节点网络互通。

执行以下命令指定管理节点IP地址:

export ZS_SERVER_IP=MANAGEMENT_NODE_IP

SDK使用

启用Python虚拟环境并指定管理节点IP地址后,可参考具体API正文中的Python SDK示例编写代码。

查询虚拟机示例

以下示例使用Python SDK登录ZStack ZSphere并查询虚拟机:

import hashlib
import os

from apibinding import api
import apibinding.api_actions as api_actions

server_ip = os.environ['ZS_SERVER_IP']
account_name = 'ACCOUNT_NAME'
password = 'ACCOUNT_PASSWORD'


def sync_call(action, session_uuid):
    api_instance = api.Api(host=server_ip, port='8080')
    if session_uuid:
        api_instance.set_session_to_api_message(action, session_uuid)
    name, reply = api_instance.sync_call(action)
    if not reply.success:
        raise api.ApiError(api.error_code_to_string(reply.error))
    return reply


def async_call(action, session_uuid):
    api_instance = api.Api(host=server_ip, port='8080')
    if session_uuid:
        api_instance.set_session_to_api_message(action, session_uuid)
    name, event = api_instance.async_call_wait_for_complete(action)
    if not event.success:
        raise api.ApiError(api.error_code_to_string(event.error))
    return event


login = api_actions.LogInByAccountAction()
login.accountName = account_name
login.password = hashlib.sha512(password).hexdigest()
session_uuid = async_call(login, None).inventory.uuid

query = api_actions.QueryVmInstanceAction()
query.conditions = []
vm_list = sync_call(query, session_uuid).inventories
for vm in vm_list:
    print '查询到虚拟机[uuid:%s]' % vm.uuid

logout = api_actions.LogOutAction()
logout.sessionUuid = session_uuid
async_call(logout, session_uuid)

将示例中的账户和密码替换为实际信息后,执行Python脚本。

开发手册 | ZStack ZSphere · ZVF | ZStack 资源中心