脚本实现通过Python获取数据库信息,并调用OpenStack API从其他机器将镜像文件复制到OpenStack控制节点完成上传镜像操作及删除镜像操作。
#-*- coding:utf-8 -*-
#!/usr/bin/env python
import time
from keystoneauth1 import loading
from keystoneauth1 import session
from novaclient import client
from glanceclient import client as gg
import MySQLdb
import traceback
import re
import os
import paramiko
class openstackapi(object):
"""OpenStack认证"""
def __init__(self):
self.loader = loading.get_plugin_loader('password')
self.auth = self.loader.load_from_options(auth_url = 'http://controller:5000/', username = 'admin', password = 'xxxxxxxxxxxxx', project_id = 'xxxxxxxxxxxxxxxxxxxxxxx')
self.sess = session.Session(auth = self.auth)
self.nova = client.Client(2, session = self.sess)
self.glance = gg.Client(2, session = self.sess)
#连接数据库
def connect_db(self):
try:
self.db = MySQLdb.connect(host = '0.0.0.0', user = 'root', passwd = 'root', db = 'database')
self.db_cur = self.db.cursor()
except:
traceback.print_exc()
#关闭数据库
def close_db(self):
try:
self.db.close()
self.db_cur.close()
except:
traceback.print_exc()
#获取等待上传镜像信息
def getWaiting(self):
try:
dbGetStatus = """select vms_template, path from vms_template where status = 'waiting' limit 1"""
self.db_cur.execute(dbGetStatus)
waiting = self.db_cur.fetchone()
return waiting
except:
traceback.print_exc()
#上传镜像好后远程删除镜像
def delparamiko(self, path):
print 'remote delete template'
scp=paramiko.Transport(('0.0.0.0', 22))
scp.connect(username='root',password='xxxxxxxxx')
sftp=paramiko.SFTPClient.from_transport(scp)
sftp.remove(path)
#远程从其他机器复制镜像到本地
def paramiko(self, path):
print 'Start transferring files'
scp=paramiko.Transport(('0.0.0.0', 22))
scp.connect(username='root',password='xxxxxxxxxx')
sftp=paramiko.SFTPClient.from_transport(scp)
sftp.get(path, path)
print 'The file transfer ends'
#创建镜像
def createImage(self, vms_template, path):
try:
print path
dbSetStatus = """update vms_template set status = 'upload' where path = '%s'"""%(path)
self.db_cur.execute(dbSetStatus)
self.db.commit()
imageFromat = re.split("[.]", path)[-1]
if imageFromat == 'img':
imageFromat = str('raw')
self.paramiko(path)
#创建镜像信息
image = self.glance.images.create(name = vms_template, disk_format = imageFromat, container_format = 'bare')
time.sleep(1)
status = image.status
Id = image.id
print Id
print status
dbSetUuid = """update vms_template set vms_template_uuid = '%s' where path = '%s'"""%(Id, path)
self.db_cur.execute(dbSetUuid)
self.db.commit()
try:
while True:
if image.status == 'queued':
#上传镜像文件
self.glance.images.upload(image.id, open(path, 'r'))
imageStatus = self.glance.images.get(image.id)['status']
while True:
time.sleep(3)
if imageStatus == 'active':
dbSetStatus = """update vms_template set status = 'active' where path = '%s'"""%( path)
self.db_cur.execute(dbSetStatus)
self.db.commit()
print "Succeed creat image: '%s'"%(vms_template)
os.remove(path)
self.delparamiko(path)
break
break
except:
#失败删除镜像信息
dbGetError = """update vms_template set status = 'error' where path = '%s'"""%(path)
self.db_cur.execute(dbGetError)
self.db.commit()
self.glance.images.delete(Id)
os.remove(path)
print 'Create template error: ' + vms_template
traceback.print_exc()
except:
dbGetError = """update vms_template set status = 'error' where path = '%s'"""%(path)
self.db_cur.execute(dbGetError)
self.db.commit()
traceback.print_exc()
#删除镜像数据
def getDelete(self):
dbGetDelete = """select vms_template, vms_template_uuid, path from vms_template where status = 'delete'"""
self.db_cur.execute(dbGetDelete)
getDelete = self.db_cur.fetchone()
return getDelete
#删除镜像
def deleteImage(self, vms_template, Id, path):
print vms_template, Id
self.glance.images.delete(Id)
dbDelDelete = """delete from vms_template where vms_template_uuid = '%s'"""%(Id)
self.db_cur.execute(dbDelDelete)
self.db.commit()
print 'Succeed delete ' + vms_template
def main(self):
try:
self.connect_db()
getWaiting = self.getWaiting()
if getWaiting:
vms_template, path = getWaiting
self.createImage(vms_template, path)
getDelete = self.getDelete()
if getDelete:
vms_template, Id, path = getDelete
self.deleteImage(vms_template, Id, path)
self.close_db()
except:
traceback.print_exc()
if __name__ == '__main__':
print 'Upload Openstack image'
a = openstackapi()
while True:
a.main()
time.sleep(1)