ZStack - 全流程代码

/ 代码 /

# -*- coding: UTF-8 -*-
import requests
import json
import hashlib

user_name = 'admin'
user_password = 'password'
host = 'http://localhost:8080/'


# 登录
def login():
    sha512 = hashlib.sha512()
    sha512.update(user_password)
    password = sha512.hexdigest()
    content = {
        "logInByAccount": {
            "password": password,
            "accountName": user_name}
    }
    data = json.dumps(content)
    url = host + 'zstack/v1/accounts/login'
    headers = {"Content-Type": "application/json"}
    response = requests.put(url, data, headers=headers)
    text = response.text
    rsp = json.loads(text)
    if rsp:
        return rsp['inventory']['uuid']


# 创建区域
def create_zone(session_uuid):
    content = {
        "params":
            {"name": "Zone",
             "description": "zone"}
    }
    data = json.dumps(content)
    url = host + 'zstack/v1/zones'
    headers = {"Content-Type": "application/json", "Authorization": "OAuth " + session_uuid}
    response = requests.post(url, data, headers=headers)
    zone_uuid = deal_response(response, True)
    if zone_uuid:
        return zone_uuid


# 创建集群
def create_clusters(session_uuid, zone_uuid):
    content = {
        "params":
            {"zoneUuid": zone_uuid,
             "name": "cluster",
             "description": "cluster",
             "hypervisorType": "KVM"}
    }
    data = json.dumps(content)
    url = host + 'zstack/v1/clusters'
    headers = {"Content-Type": "application/json", "Authorization": "OAuth " + session_uuid}
    response = requests.post(url, data, headers=headers)
    cluster_uuid = deal_response(response, True)
    if cluster_uuid:
        return cluster_uuid


# 创建物理机
def create_host(cluster_uuid, session_uuid):
    print('cluster_uuid : %s' % cluster_uuid)
    content = {
        "params": {
            "username": "root",
            "password": "password",
            "name": "Host",
            "sshPort": 22,
            "managementIp": "192.168.0.101",
            "clusterUuid": cluster_uuid,
            "hostType": "kvm",
            "description": "host_des"
        }
    }
    data = json.dumps(content)
    url = host + 'zstack/v1/hosts/kvm'
    headers = {"Content-Type": "application/json", "Authorization": "OAuth " + session_uuid}
    response = requests.post(url, data, headers=headers)
    host_uuid = deal_response(response, True)
    if host_uuid:
        return host_uuid


# 添加镜像仓库
def create_image_store(session_uuid):
    data = json.dumps({
        "params":
            {"hostname": "192.168.0.100",
             "username": "root",
             "password": "pssword",
             "sshPort": 22,
             "url": "/zs_image",
             "name": "ImageStore",
             "type": "image-store",
             "description": "image_des"
             }})
    url = host + 'zstack/v1/backup-storage/image-store'
    headers = {"Content-Type": "application/json", "Authorization": "OAuth " + session_uuid}
    response = requests.post(url, data, headers=headers)
    store_uuid = deal_response(response, True)
    if store_uuid:
        return store_uuid


# 挂载镜像服务器到区域
def attach_image_store_to_zone(zone_uuid, store_uuid, session_uuid):
    url = host + 'zstack/v1/zones/' + zone_uuid + '/backup-storage/' + store_uuid
    headers = {"Content-Type": "application/json", "Authorization": "OAuth " + session_uuid}
    response = requests.post(url, headers=headers)
    deal_response(response, False)


# 添加主存储
def create_local_storage(zone_uuid, session_uuid):
    data = json.dumps({
        "params":
            {"url": "/zstack_ps",
             "name": "PS1",
             "zoneUuid": zone_uuid}})
    url = host + 'zstack/v1/primary-storage/local-storage'
    headers = {"Content-Type": "application/json", "Authorization": "OAuth " + session_uuid}
    response = requests.post(url, data, headers=headers)
    deal_response(response, False)


# 创建计算规格
def create_instance_offerings(session_uuid):
    data = json.dumps({
        "params": {
            "name": "instanceOffering",
            "cpuNum": 2.0,
            "memorySize": 104857600.0,
            "sortKey": 0.0, }})
    url = host + 'zstack/v1/instance-offerings'
    headers = {"Content-Type": "application/json", "Authorization": "OAuth " + session_uuid}
    response = requests.post(url, data, headers=headers)
    offer_uuid = deal_response(response, True)
    if offer_uuid:
        return offer_uuid


# 添加镜像
def create_images(store_uuid, session_uuid):
    data = json.dumps({
        "params": {
            "name": "Linux",
            "url": "http://localhost:8081/iso/centos7.iso",
            "mediaType": "RootVolumeTemplate",
            "system": "false",
            "format": "qcow2",
            "platform": "Linux",
            "backupStorageUuids": [store_uuid]}})
    url = host + 'zstack/v1/images'
    headers = {"Content-Type": "application/json", "Authorization": "OAuth " + session_uuid}
    response = requests.post(url, data, headers=headers)
    image_uuid = deal_response(response, False)
    if image_uuid :
        return image_uuid


# 创建网络
def create_networks(zone_uuid, cluster_uuid, session_uuid):
    # 创建2层网络
    l2_uuid = create_l2_networks(zone_uuid, session_uuid)
    if l2_uuid:
        print('CreateL2Network successfully!')
        headers = {"Content-Type": "application/json", "Authorization": "OAuth " + session_uuid}
        # 挂载2层网络到集群AttachL2NetworkToCluster
        url = host + 'zstack/v1/l2-networks/' + l2_uuid + '/clusters/' + cluster_uuid
        response = requests.post(url, None, headers=headers)
        rsp = json.loads(response.text)
        if rsp:
            if query_until_done(rsp):
                print('AttachL2NetworkToCluster successfully!')
                # 创建3层网络CreateL3Network
                data = json.dumps({
                    "params": {
                        "name": "L3Network",
                        "type": "L3BasicNetwork",
                        "l2NetworkUuid": l2_uuid,
                        "category": 'Private',
                        "system": "false"}})
                url = host + 'zstack/v1/l3-networks'
                response = requests.post(url, data, headers=headers)
                rsp = json.loads(response.text)
                if rsp:
                    json_str = query_until_done(rsp)
                    l3_uuid = json_str['inventory']['uuid']
                    if l3_uuid:
                        print('CreateL3Network successfully!')
                        # 添加DNSAddDnsToL3Network
                        data = json.dumps({
                            "params": {
                                "dns": "8.8.8.8"}})
                        url = host + 'zstack/v1/l3-networks/' + l3_uuid + '/dns'
                        response = requests.post(url, data, headers=headers)
                        rsp = json.loads(response.text)
                        if rsp:
                            if query_until_done(rsp):
                                print('AddDnsToL3Network successfully!')
                                # 添加IP地址范围AddIpRange
                                data = json.dumps({
                                    "params": {
                                        "name": "ip-range",
                                        "startIp": "192.168.100.10",
                                        "endIp": "192.168.100.250",
                                        "netmask": "255.255.255.0",
                                        "gateway": "192.168.100.1"}})
                                url = host + 'zstack/v1/l3-networks/' + l3_uuid + '/ip-ranges'
                                response = requests.post(url, data, headers=headers)
                                rsp = json.loads(response.text)
                                if rsp:
                                    if query_until_done(rsp):
                                        print('AddIpRange successfully!')
                                        # 查询网络服务模块QueryNetworkServiceProvider
                                        url = host + 'zstack/v1/network-services/providers'
                                        response = requests.get(url, data, headers=headers)
                                        rsp = json.loads(response.text)
                                        if rsp:
                                            inventories_dict = {}
                                            inventories_list = rsp['inventories']
                                            for index in range(len(inventories_list)):
                                                item = inventories_list[index]
                                                inventories_dict[item['uuid']] = item['networkServiceTypes']
                                            # 添加网络服务到3层网络AttachNetworkServiceToL3Network
                                            if inventories_dict:
                                                print('QueryNetworkServiceProvider successfully!')
                                                data = json.dumps({
                                                    "params": {
                                                        "networkServices": inventories_dict}})
                                                url = host + 'zstack/v1/l3-networks/' + l3_uuid + '/network-services'
                                                response = requests.post(url, data, headers=headers)
                                                if response:
                                                    print('Network created successfully!')
                                                    return l3_uuid


# 创建二层网络
def create_l2_networks(zone_uuid, session_uuid):
    data = json.dumps({
        "params": {
            "name": "L2Network",
            "description": "Test",
            "zoneUuid": zone_uuid,
            "physicalInterface": "ens33"}})
    url = host + 'zstack/v1/l2-networks/no-vlan'
    headers = {"Content-Type": "application/json", "Authorization": "OAuth " + session_uuid}
    response = requests.post(url, data, headers=headers)
    l2_uuid = deal_response(response, True)
    if l2_uuid:
        return l2_uuid


# 创建云主机
def create_vm(session_uuid, instance_uuid, image_uuid, l3_uuid_arr, host_uuid, storage_uuid):
    # 创建云盘规格CreateDiskOffering
    data = json.dumps({
        "params": {
            "name": "diskOffering",
            "diskSize": '1073741824'}})
    url = host + 'zstack/v1/disk-offerings'
    headers = {"Content-Type": "application/json", "Authorization": "OAuth " + session_uuid}
    response = requests.post(url, data, headers=headers)
    offer_uuid = deal_response(response, True)
    if offer_uuid:
        print('CreateDiskOffering successfully!')
        # 创建云主机
        data = json.dumps({
            "params": {
                "name": "vm",
                "description": "this is a vm",
                "instanceOfferingUuid": instance_uuid,
                "imageUuid": image_uuid,
                "l3NetworkUuids": l3_uuid_arr,
                "dataVolumeSystemTags": [],
                "rootVolumeSystemTags": [],
                "rootDiskOfferingUuid": offer_uuid,
                "hostUuid": host_uuid
            }})
        print(data)
        url = host + 'zstack/v1/vm-instances'
        response = requests.post(url, data, headers=headers)
        vm_uuid = deal_response(response, True)
        if vm_uuid:
            print('CreateVmInstance successfully!')
            # 创建云盘CreateDataVolume
            data = json.dumps({
                "params": {
                    "name": "vm",
                    "description": "this is a vm",
                    "diskOfferingUuid": offer_uuid,
                    "primaryStorageUuid": storage_uuid,
                },
                "systemTags": [
                    "localStorage::hostUuid::" + host_uuid
                ],
            })
            print(data)
            url = host + 'zstack/v1/volumes/data'
            response = requests.post(url, data, headers=headers)
            data_uuid = deal_response(response, True)
            if data_uuid:
                print('CreateDataVolume successfully!')
                # 挂载云盘到VM
                print(data)
                url = host + 'zstack/v1/volumes/' + data_uuid + '/vm-instances/' + vm_uuid
                response = requests.post(url, None, headers=headers)
                deal_response(response, False)
                print('Virtual machine created successfully!')


# 处理返回数据
def deal_response(response, is_return):
    if response:
        rsp = json.loads(response.text)
        if rsp:
            print('rsp : {%s}' % rsp)
            json_str = query_until_done(rsp)
            if json_str:
                if not json_str.has_key('error'):
                    if is_return:
                        return json_str['inventory']['uuid']
                    else:
                        return True
    return False


# 轮询查询API结果
def query_until_done(rsp):
    if rsp.has_key('location'):
        location = rsp['location']
        job_uuid = location.split('/')[-1]
        if job_uuid:
            while True:
                url = host + "zstack/v1/api-jobs/" + location.split('/')[-1]
                response = requests.get(url)
                text = response.text
                if text != '{}':
                    print(text)
                    return json.loads(text)


if __name__ == '__main__':
    session_uuid = login()
    instance_uuid = ''
    image_uuid = ''
    l3_uuid_arr = []
    host_uuid = ''
    storage_uuid = ''
    if session_uuid:
        # 创建区域
        zone_uuid = create_zone(session_uuid)
        if zone_uuid:
            # 创建集群
            cluster_uuid = create_clusters(session_uuid, zone_uuid)
            if cluster_uuid:
                # 创建物理机
                host_uuid = create_host(cluster_uuid, session_uuid)
                # 创建网络
                l3_uuid = create_networks(zone_uuid, cluster_uuid, session_uuid)
                l3_uuid_arr.append(l3_uuid)
            # 创建本地存储
            storage_uuid = create_local_storage(zone_uuid, session_uuid)
            # 创建镜像服务器
            store_uuid = create_image_store(session_uuid)
            # 挂载镜像服务器到区域
            if store_uuid:
                attach_image_store_to_zone(zone_uuid, store_uuid, session_uuid)
                # 添加镜像
                image_uuid = create_images(store_uuid, session_uuid)
        # 创建计算规格
        instance_uuid = create_instance_offerings(session_uuid)
        # 创建云主机
        create_vm(session_uuid=session_uuid, instance_uuid=instance_uuid, image_uuid=image_uuid,
                  l3_uuid_arr=l3_uuid_arr, host_uuid=host_uuid,
                  storage_uuid=storage_uuid)

/ ZStack全流程相关博文链接 /

ZStack - 登录

ZStack - 创建区域、集群

ZStack - 创建物理机

ZStack - 创建主存储

ZStack - 创建2层3层网络

ZStack - 创建云主机计算规格

ZStack - 创建镜像

ZStack - 创建云主机计算规格

ZStack - 创建云主机

ZStack - 全流程代码

原创文章 42 获赞 51 访问量 1万+

猜你喜欢

转载自blog.csdn.net/F1004145107/article/details/106086603