ZStack - 全流程代码

本文详细介绍使用ZStack云平台进行全流程部署的过程,包括登录、创建区域、集群、物理机、网络、镜像服务器、计算规格及云主机等关键步骤。通过Python脚本实现自动化部署,涵盖从基础设施搭建到云资源创建的各个环节。

/ 代码 /

# -*- 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 - 全流程代码

ZStack 是全新的开源 IaaS 软件,它的诞生是为了解决困绕 IaaS 软件的几大难题:复杂度、稳定性、可伸缩性和灵活性。作为这个领域的新项目,ZStack 从前辈身上学习到了很多经验,并且针对各种云的问题重头设计了整套架构。 ZStack 已经提供了大部分IaaS的基本功能,包括:虚拟机管理,存储卷管理,存储卷快照,各种网络服务(DHCP、DNS、SNAT、EIP、PortForward以及Security Group)。请访问官网网站以获取完整的功能列表:http://zstack.org/documentation/features-matrix.html ZStack非常容易安装。在快速安装说明(http://zstack.org/installation/)里,记录了如何通过两条命令,5分钟时间,完成在一台Linux机器上部署单机演示环境。或者阅读多控制节点安装手册(http://zstack.org/installation/multi-node.html),在30分钟内搭建一个可以负责管理成百上千台服务器的服务集群。 ZStack的相关公开介绍: ZStack 架构设计  为什么我们创造ZStack而不是选择OpenStack http://zstack.org/cn_blog/why-zstack.html  浅谈 CloudStackZStack 架构与性能  http://www.csdn.net/article/2015-08-24/2825516  _[CSDN]ZStack深度试用:部署、架构与网络及其与OpenStack的对比 http://www.csdn.net/article/2015-05-18/2824690 [CSDN]直戳OpenStack痛处?IaaS开源新兵ZStack架构设计全解析 http://www.csdn.net/article/2015-04-10/2824443  [Infoq]私有云之殇:公有云这座大山(上)http://www.infoq.com/cn/articles/ZStack-PartI  [Infoq]为私有云结庐而做“隆中对”(下)http://www.infoq.com/cn/articles/ZStack-PartII  [英文媒体Newstacks]ZStack, an Infrastructure Software with an In-Process Microservices Architecture http://thenewstack.io/zstack-an-infrastructure-software-with-an-in-process-microservices-architecture/  标签:ZStack
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值