设为首页 收藏本站
查看: 802|回复: 0

[经验分享] 初探oVirt-体验sdk-python

[复制链接]

尚未签到

发表于 2018-8-11 11:47:43 | 显示全部楼层 |阅读模式
  
一、说明
  
使用sdk-python
  
通过pip安装 ovirt-engine-sdk-python
  
# pip install ovirt-engine-sdk-python
  

  
注:本文是从ovirt-engine-sdk-python的3.5.4更新到3.6.0.3,关于版本的差异有一个主要区别是新增了这个选项:
  
use_cloud_init=True
  

  
二、示例
  
[root@n86 bin]# cat ovirt_sdk.py
  
#!/bin/env python
  
# -*- coding:utf-8 -*-
  
# for ovirt-engine-sdk-python-3.6.0.3
  
# 2015/12/8
  

  
from __future__ import print_function
  
from time import sleep
  

  
from ovirtsdk.api import API
  
from ovirtsdk.xml import params
  

  
__version__ = '0.2.8'
  

  
OE_URL = 'https://e01.test/api'
  
OE_USERNAME = 'admin@internal'
  
OE_PASSWORD = 'TestVM'
  
# curl -k https://e01.test/ca.crt -o ca.crt
  
OE_CA_FILE = 'ca.crt'  # ca.crt 在当前目录下
  

  

  
def vm_list(oe_api):
  
    """
  
        List VM
  
    """
  
    try:
  
        print('[I] List vms: ')
  
        for vm_online in oe_api.vms.list():
  
            print('{0}'.format(vm_online.name))
  
    except Exception as err:
  
        print('[E] List VM: {0}'.format(str(err)))
  

  

  
def vm_start(oe_api, vm_name):
  
    """
  
        start vm by name
  
    """
  
    try:
  
        if vm_name not in [vm_online.name for vm_online in oe_api.vms.list()]:
  
            print("[E] VM not found: {0}".format(vm_name))
  
            return 1
  
        if oe_api.vms.get(vm_name).status.state != 'up':
  
            print('[I] Starting VM.')
  
            oe_api.vms.get(vm_name).start()
  
            print('[I] Waiting for VM to reach Up status... ', end='')
  
            while oe_api.vms.get(vm_name).status.state != 'up':
  
                print('.', end='')
  
                sleep(1)
  
            print('VM {0} is up!'.format(vm_name))
  
        else:
  
            print('[E] VM already up.')
  
    except Exception as err:
  
        print('[E] Failed to Start VM: {0}'.format(str(err)))
  

  

  
def vm_stop(oe_api, vm_name):
  
    """
  
        stop vm by name
  
    """
  
    try:
  
        if vm_name not in [vm_online.name for vm_online in oe_api.vms.list()]:
  
            print("[E] VM not found: {0}".format(vm_name))
  
            return 1
  
        if oe_api.vms.get(vm_name).status.state != 'down':
  
            print('[I] Stop VM.')
  
            oe_api.vms.get(vm_name).stop()
  
            print('[I] Waiting for VM to reach Down status... ', end='')
  
            while oe_api.vms.get(vm_name).status.state != 'down':
  
                print('.', end='')
  
                sleep(1)
  
            print('VM {0} is down!'.format(vm_name))
  
        else:
  
            print('[E] VM already down: {0}'.format(vm_name))
  
    except Exception as err:
  
        print('[E] Stop VM: {0}'.format(str(err)))
  

  

  
def vm_delete(oe_api, vm_name):
  
    """
  
        delete vm by name
  
    """
  
    try:
  
        if vm_name not in [vm_online.name for vm_online in oe_api.vms.list()]:
  
            print("[E] VM not found: {0}".format(vm_name))
  
            return 1
  
        oe_api.vms.get(vm_name).delete()
  
        print('[I] Waiting for VM to be deleted... ', end='')
  
        while vm_name in [vm_online.name for vm_online in oe_api.vms.list()]:
  
            print('.', end='')
  
            sleep(1)
  
        print('VM was removed successfully.')
  
    except Exception as err:
  
        print('[E] Failed to remove VM: {0}'.format(str(err)))
  

  

  
def vm_run_once(oe_api, vm_name, vm_password, vm_nic_info):
  
    """
  
        vm run once with cloud-init
  
    """
  
    try:
  
        if vm_name not in [vm_online.name for vm_online in oe_api.vms.list()]:
  
            print("[E] VM not found: {0}".format(vm_name))
  
            return 1
  
        elif vm_nic_info is None:
  
            print('[E] VM nic info is needed: "name_of_nic, ip_address, net_mask, gateway"')
  
            return 2
  
        elif oe_api.vms.get(vm_name).status.state == 'down':
  
            print('[I] Starting VM with cloud-init.')
  
            p_host = params.Host(address="{0}".format(vm_name))
  
            p_users = params.Users(user=[params.User(user_name="root",
  
                                                     password=vm_password)])
  
            vm_nic = [nic for nic in vm_nic_info.split(', ')]
  
            if len(vm_nic) != 4:
  
                print('[E] VM nic info need 4 args: "name_of_nic, ip_address, net_mask, gateway"')
  
                return 3
  
            p_nic = params.Nics(nic=[params.NIC(name=vm_nic[0],
  
                                                boot_protocol="STATIC",
  
                                                on_boot=True,
  
                                                network=params.Network(ip=params.IP(address=vm_nic[1],
  
                                                                                    netmask=vm_nic[2],
  
                                                                                    gateway=vm_nic[3])))])
  
            p_network = params.NetworkConfiguration(nics=p_nic)
  
            p_cloud_init = params.CloudInit(host=p_host,
  
                                            users=p_users,
  
                                            regenerate_ssh_keys=True,
  
                                            network_configuration=p_network)
  
            p_initialization = params.Initialization(cloud_init=p_cloud_init)
  
            vm_params = params.VM(initialization=p_initialization)
  
            vm_action = params.Action(vm=vm_params, use_cloud_init=True)
  
            oe_api.vms.get(vm_name).start(vm_action)
  

  
            print('[I] Waiting for VM to reach Up status... ', end='')
  
            while oe_api.vms.get(vm_name).status.state != 'up':
  
                print('.', end='')
  
                sleep(1)
  
            print('VM {0} is up!'.format(vm_name))
  
        else:
  
            print('[E] VM already up.')
  

  
    except Exception as err:
  
        print('[E] Failed to Start VM with cloud-init: {0}'.format(str(err)))
  

  

  
def vm_create_from_tpl(oe_api, vm_name, tpl_name, cluster_name):
  
    """
  
        create vm from template.
  
        notice: not (Clone/Independent), but (Thin/Dependent)
  
    """
  
    try:
  
        vm_params = params.VM(name=vm_name,
  
                              template=oe_api.templates.get(tpl_name),
  
                              cluster=oe_api.clusters.get(cluster_name))
  
        oe_api.vms.add(vm_params)
  
        print('[I] VM was created from Template successfully.\nWaiting for VM to reach Down status... ', end='')
  
        while oe_api.vms.get(vm_name).status.state != 'down':
  
            print('.', end='')
  
            sleep(1)
  
        print('VM {0} is down!'.format(vm_name))
  
    except Exception as err:
  
        print('[E] Failed to create VM from template: {0}'.format(str(err)))
  

  

  
if __name__ == '__main__':
  
    import optparse
  
    p = optparse.OptionParser()
  
    p.add_option("-a", "--action", action="store", type="string", dest="action",
  
                 help="list|init|start|stop|delete|create[-list]")
  
    p.add_option("-n", "--vm-name", action="store", type="string", dest="vm_name",
  
                 help="provide the name of vm. eg: -a create -n vm01")
  
    p.add_option("-c", "--vm-cluster", action="store", type="string", dest="vm_cluster",
  
                 help="provide cluster name")
  
    p.add_option("-t", "--vm-template", action="store", type="string", dest="vm_template",
  
                 help="provide template name. eg: -a create -n vm01 -t tpl01 -c cluster01")
  
    p.add_option("-p", "--vm-password", action="store", type="string", dest="vm_password",
  
                 help="-a init -p password_of_vm -i vm_nic_info")
  
    p.add_option("-i", "--vm-nic-info", action="store", type="string", dest="vm_nic_info",
  
                 help='nic info: "name_of_nic, ip_address, net_mask, gateway". '
  
                      'eg: -a init -n vm01 -p 123456 -i "eth0, 10.0.100.101, 255.255.255.0, 10.0.100.1"')
  
    p.add_option("-L", "--vm-list", action="store", type="string", dest="vm_list",
  
                 help='a list of vms. eg: -a stop-list -L "vm01, vm02, vm03"')
  
    p.set_defaults(action='list',
  
                   vm_cluster='C01',
  
                   vm_template='tpl-m1')
  
    opt, args = p.parse_args()
  
    oe_conn = None
  
    try:
  
        oe_conn = API(url=OE_URL, username=OE_USERNAME, password=OE_PASSWORD, ca_file=OE_CA_FILE)
  
        if opt.action == 'list':
  
            vm_list(oe_conn)
  
        elif opt.action == 'start':
  
            vm_start(oe_conn, opt.vm_name)
  
        elif opt.action == 'stop':
  
            vm_stop(oe_conn, opt.vm_name)
  
        elif opt.action == 'delete':
  
            vm_delete(oe_conn, opt.vm_name)
  
        elif opt.action == 'create':
  
            vm_create_from_tpl(oe_conn, opt.vm_name, opt.vm_template, opt.vm_cluster)
  
        elif opt.action == 'init':
  
            vm_run_once(oe_conn, opt.vm_name, opt.vm_password, opt.vm_nic_info)
  
        elif opt.action == 'start-list':
  
            for vm in opt.vm_list.replace(' ', '').split(','):
  
                print('[I] try to start vm: {0}'.format(vm))
  
                vm_start(oe_conn, vm)
  
        elif opt.action == 'stop-list':
  
            for vm in opt.vm_list.replace(' ', '').split(','):
  
                print('[I] try to stop vm: {0}'.format(vm))
  
                vm_stop(oe_conn, vm)
  
        elif opt.action == 'delete-list':
  
            for vm in opt.vm_list.replace(' ', '').split(','):
  
                print('[I] try to delete: {0}'.format(vm))
  
                vm_delete(oe_conn, vm)
  
        elif opt.action == 'create-list':
  
            for vm in opt.vm_list.replace(' ', '').split(','):
  
                print('[I] try to create: {0}'.format(vm))
  
                vm_create_from_tpl(oe_conn, vm, opt.vm_template, opt.vm_cluster)
  
    except Exception as e:
  
        print('[E] Failed to init API: {0}'.format(str(e)))
  
    finally:
  
        if oe_conn is not None:
  
            oe_conn.disconnect()
  

  

  

  

  

  

  
ZYXW、参考
  
1、docs
  
http://www.ovirt.org/Python-sdk
  
http://www.ovirt.org/Testing/PythonApi
  
http://www.ovirt.org/Features/Cloud-Init_Integration
  
https://access.redhat.com/documentation/zh-CN/Red_Hat_Enterprise_Virtualization/3.5/html-single/Technical_Guide/index.html#chap-REST_API_Quick_Start_Example

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-550108-1-1.html 上篇帖子: 【python】编程语言入门经典100例--1 下篇帖子: python 插入mysql数据库数据
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表