Example #1
0
 def addInstanceInterface(self,instance,brName):
     netk = self.getNetwork(brName)
     if netk:
         xml = netk.XMLDesc(0)
         tree = ElementTree.fromstring(xml)
         try:
             mode = tree.find('virtualport').get('type')  
         except:
             mode = 'brct'         
         interXml = Const.CreateNetcard(nkt_br=brName, ntk_name=brName +'-'+CommTools.radString(length=4), mode=mode)
         try:
             return instance.attachDeviceFlags(interXml,3)#如果是关闭状态则标记flags为3,保证添加的硬盘重启不会丢失 
         except Exception,e:
             return e
Example #2
0
 def addInstanceDisk(self,instance,volPath):
     diskSn = 'vda'
     diskList = ['vd'+chr(i) for i in range(97,123)]
     domXml = instance.XMLDesc(0)
     tree = ElementTree.fromstring(domXml)
     for ds in tree.findall('devices/disk'):
         device = ds.get('device')
         vdisk = ds.find('target').get('dev')
         if device == 'disk' and vdisk in diskList:diskSn = diskList[diskList.index(vdisk) + 1]
     diskXml = Const.CreateDisk(volume_path=volPath, diskSn=diskSn)
     try:
         result = instance.attachDeviceFlags(diskXml,3)#如果是关闭状态则标记flags为3,保证添加的硬盘重启不会丢失 
     except:
         return False
     if result == 0:return True
     else:return False
Example #3
0
def addInstance(request):
    if request.method == "GET":
        try:
            vMserverId = request.GET.get('id')
            vmServer = VMServer.selectOneHost(id=vMserverId)
            userList = User.objects.all()
            tempList = TempInstance.listVmTemp()
            VMS = LibvirtManage(vmServer.uri)
            SERVER = VMS.genre(model='server')
            NETWORK = VMS.genre(model='network')
            if SERVER: vStorage = SERVER.getVmStorageInfo()
            else:
                return render_to_response(
                    '404.html', context_instance=RequestContext(request))
        except:
            vStorage = None
        vMImages = SERVER.getVmIsoList()
        netkList = NETWORK.listNetwork()
        VMS.close()
        return render_to_response('vmInstance/add_instance.html', {
            "user":
            request.user,
            "localtion": [{
                "name": "首页",
                "url": '/'
            }, {
                "name": "虚拟机实例",
                "url": '#'
            }, {
                "name": "添加虚拟机",
                "url": "/addInstance"
            }],
            "vmServer":
            vmServer,
            "vStorage":
            vStorage,
            "vMImages":
            vMImages,
            "netkList":
            netkList,
            "tempList":
            tempList,
            "userList":
            userList
        },
                                  context_instance=RequestContext(request))
    elif request.method == "POST":
        op = request.POST.get('op')
        if op in [
                'custom', 'xml', 'template'
        ] and request.user.has_perm('VManagePlatform.add_vmserverinstance'):
            try:
                vMserver = VMServer.selectOneHost(
                    id=request.POST.get('server_id'))
                VMS = LibvirtManage(uri=vMserver.uri)
                INSTANCE = VMS.genre(model='instance')
                SERVER = VMS.genre(model='server')
                STORAGE = VMS.genre(model='storage')
                NETWORK = VMS.genre(model='network')
            except Exception, e:
                return JsonResponse({
                    "code": 500,
                    "msg": "虚拟服务器连接失败,请注意连通性。",
                    "data": e
                })
            if SERVER:
                if op == 'custom':
                    netks = [
                        str(i) for i in request.POST.get('netk').split(',')
                    ]
                    if INSTANCE:
                        instance = INSTANCE.queryInstance(
                            name=str(request.POST.get('vm_name')))
                        if instance:
                            return JsonResponse({
                                "code": 500,
                                "msg": "虚拟机已经存在",
                                "data": None
                            })
                        else:
                            networkXml = ''
                            radStr = CommTools.radString(4)
                            for nt in netks:
                                netkType = NETWORK.getNetworkType(nt)
                                netXml = Const.CreateNetcard(nkt_br=nt,
                                                             ntk_name=nt +
                                                             '-' + radStr,
                                                             mode=netkType)
                                networkXml = netXml + networkXml
                            pool = STORAGE.getStoragePool(
                                pool_name=request.POST.get('storage'))
                            volume_name = request.POST.get('vm_name') + '.img'
                            if pool:
                                volume = STORAGE.createVolumes(
                                    pool,
                                    volume_name=volume_name,
                                    volume_capacity=request.POST.get('disk'))
                                if volume:
                                    disk_path = volume.path()
                                    volume_name = volume.name()
                                    disk_xml = Const.CreateDisk(
                                        volume_path=disk_path)
                                else:
                                    return JsonResponse({
                                        "code": 500,
                                        "msg": "添加虚拟机失败,存储池里面以存在以主机名命名的磁盘",
                                        "data": None
                                    })
                            else:
                                return JsonResponse({
                                    "code": 500,
                                    "msg": "添加虚拟机失败,存储池已经被删除掉",
                                    "data": None
                                })
                            dom_xml = Const.CreateIntanceConfig(
                                dom_name=request.POST.get('vm_name'),
                                maxMem=int(SERVER.getServerInfo().get('mem')),
                                mem=int(request.POST.get('mem')),
                                cpu=request.POST.get('cpu'),
                                disk=disk_xml,
                                iso_path=request.POST.get('system'),
                                network=networkXml)
                            dom = SERVER.createInstance(dom_xml)
                            recordLogs.delay(
                                user=request.user,
                                action=op,
                                status=dom,
                                vm_name=request.POST.get('vm_name'))
                            if dom == 0:
                                VMS.close()
                                VmInstance.insertInstance(
                                    dict(
                                        server=vMserver,
                                        name=request.POST.get('vm_name'),
                                        cpu=request.POST.get('cpu'),
                                        mem=request.POST.get('mem'),
                                        owner=request.POST.get('owner'),
                                        status=1,
                                    ))
                                return JsonResponse({
                                    "code": 200,
                                    "data": None,
                                    "msg": "虚拟主机添加成功。"
                                })
                            else:
                                STORAGE.deleteVolume(pool, volume_name)
                                VMS.close()
                                return JsonResponse({
                                    "code": 500,
                                    "data": None,
                                    "msg": "虚拟主机添加失败。"
                                })
                elif op == 'xml':
                    domXml = request.POST.get('xml')
                    dom = SERVER.defineXML(xml=domXml)
                    VMS.close()
                    recordLogs.delay(user=request.user,
                                     action=op,
                                     status=dom,
                                     vm_name=request.POST.get('vm_name'))
                    if dom:
                        return JsonResponse({
                            "code": 200,
                            "data": None,
                            "msg": "虚拟主机添加成功。"
                        })
                    else:
                        return JsonResponse({
                            "code": 500,
                            "data": None,
                            "msg": "虚拟主机添加失败。"
                        })
                elif op == 'template':
                    try:
                        temp = TempInstance.selectVmTemp(
                            id=request.POST.get('temp'))
                        if INSTANCE:
                            instance = INSTANCE.queryInstance(
                                name=str(request.POST.get('vm_name')))
                        if instance:
                            return JsonResponse({
                                "code": 500,
                                "msg": "虚拟机已经存在",
                                "data": None
                            })
                        else:
                            pool = STORAGE.getStoragePool(
                                pool_name=request.POST.get('storage'))
                            volume_name = request.POST.get('vm_name') + '.img'
                            if pool:
                                volume = STORAGE.createVolumes(
                                    pool,
                                    volume_name=volume_name,
                                    volume_capacity=temp.disk)
                                if volume:
                                    disk_path = volume.path()
                                    volume_name = volume.name()
                                    disk_xml = Const.CreateDisk(
                                        volume_path=disk_path)
                                else:
                                    return JsonResponse({
                                        "code": 500,
                                        "msg": "添加虚拟机失败,存储池里面以存在以主机名命名的磁盘",
                                        "data": None
                                    })
                            else:
                                return JsonResponse({
                                    "code": 500,
                                    "msg": "添加虚拟机失败,存储池已经被删除掉",
                                    "data": None
                                })
                            dom_xml = Const.CreateIntanceConfig(
                                dom_name=request.POST.get('vm_name'),
                                maxMem=int(SERVER.getServerInfo().get('mem')),
                                mem=temp.mem,
                                cpu=temp.cpu,
                                disk=disk_xml,
                                iso_path=request.POST.get('system'),
                                network=None)
                            dom = SERVER.createInstance(dom_xml)
                            recordLogs.delay(
                                user=request.user,
                                action=op,
                                status=dom,
                                vm_name=request.POST.get('vm_name'))
                            if dom == 0:
                                VMS.close()
                                return JsonResponse({
                                    "code": 200,
                                    "data": None,
                                    "msg": "虚拟主机添加成功。"
                                })
                            else:
                                STORAGE.deleteVolume(pool, volume_name)
                                VMS.close()
                                return JsonResponse({
                                    "code": 500,
                                    "data": None,
                                    "msg": "虚拟主机添加失败。"
                                })
                    except:
                        return JsonResponse({
                            "code": 500,
                            "data": None,
                            "msg": "虚拟主机添加失败。"
                        })

            else:
                return JsonResponse({
                    "code": 500,
                    "data": None,
                    "msg": "虚拟服务器连接失败,请注意连通性。"
                })
        else:
            return JsonResponse({
                "code": 500,
                "data": None,
                "msg": "不支持的操作或者您没有权限添加虚拟机"
            })
Example #4
0
def addInstance(request,id):
    try:
        vmServer = VmServer.objects.get(id=id)
    except:
        return render_to_response('404.html',context_instance=RequestContext(request))

    if request.method == "GET":
        userList = User.objects.all()
        tempList = VmInstance_Template.objects.all()
        VMS = LibvirtManage(vmServer.server_ip,vmServer.username, vmServer.passwd,vmServer.vm_type)    
        SERVER = VMS.genre(model='server') 
        NETWORK = VMS.genre(model='network')       
        if SERVER:
            vStorage = SERVER.getVmStorageInfo()
        vMImages =SERVER.getVmIsoList()  #.iso文件
        netkList = NETWORK.listNetwork()
        VMS.close()

        return render_to_response('vmInstance/add_instance.html',
                                  {"user":request.user,"localtion":[{"name":"首页","url":'/'},{"name":"宿主机","url":'/viewServer/'+str(vmServer.id)},
                                                                    {"name":"创建虚拟机","url":"/addInstance/"+str(vmServer.id)}],
                                    "vmServer":vmServer,"vStorage":vStorage,"vMImages":vMImages,"netkList":netkList,
                                    "tempList":tempList,"userList":userList},
                                  context_instance=RequestContext(request))

    elif request.method == "POST":
        op = request.POST.get('op')
        if op in ['custom','xml','template'] and request.user.has_perm('VManagePlatform.add_vmserverinstance'):
            VMS = LibvirtManage(vmServer.server_ip,vmServer.username, vmServer.passwd,vmServer.vm_type)  
            INSTANCE = VMS.genre(model='instance')
            SERVER = VMS.genre(model='server')
            STORAGE = VMS.genre(model='storage')
            NETWORK = VMS.genre(model='network')

            #自定义配置创建虚拟机
            if op == 'custom':
                netks = [ str(i) for i in request.POST.get('netk').split(',')]
                if INSTANCE:
                    instance =  INSTANCE.queryInstance(name=str(request.POST.get('vm_name'))) 
                    if instance:
                        return  JsonResponse({"code":500,"msg":"虚拟机已经存在","data":None})
                    else:
                        networkXml = ''
                        radStr = CommTools.radString(4)
                        for nt in netks:
                            netkType = NETWORK.getNetworkType(nt)
                            netXml = Const.CreateNetcard(nkt_br=nt,ntk_name=nt+'-'+radStr,data=netkType)                             
                            networkXml = netXml +  networkXml

                        pool = STORAGE.getStoragePool(pool_name=request.POST.get('storage')) 
                        volume_name = request.POST.get('vm_name')+'.img'
                        if not pool:
                            return  JsonResponse({"code":500,"msg":"创建虚拟机失败,存储池已经被删除掉","data":None})

                        if request.POST.get('storagetype') == 'new':   #创建新磁盘
                            volume = STORAGE.createVolumes(pool, volume_name=volume_name, volume_capacity=request.POST.get('disk'))
                            if isinstance(volume, str):
                                return JsonResponse({"code":500,"msg":volume,"data":None})
                            disk_path = volume.path()
                            volume_name = volume.name()
                            disk_xml = Const.CreateDisk(volume_path=disk_path)
                        else:           #使用现有磁盘
                            volume = STORAGE.getStorageVolume(pool, request.POST.get('vol'))
                            if isinstance(volume, str):
                                return JsonResponse({"code":500,"msg":volume,"data":None})
                            disk_path = volume.path()
                            volume_name = volume.name()
                            disk_xml = Const.CreateDisk(volume_path=disk_path)

                        iso_path = request.POST.get('system')
                        if not iso_path:
                            iso_path = ""

                        dom_xml = Const.CreateIntanceConfig(dom_name=request.POST.get('vm_name'),maxMem=int(SERVER.getServerInfo().get('mem')),
                                                      mem=int(request.POST.get('mem')),cpu=request.POST.get('cpu'),disk=disk_xml,
                                                      iso_path=iso_path,network=networkXml)
                        dom = SERVER.createInstance(dom_xml)                          
                        if dom==0:    
                            instance = INSTANCE.queryInstance(name=str(request.POST.get('vm_name')))
                            VMS.close()

                            #生成VmServerInstance表记录
                            try:
                                VmServerInstance.objects.create(server=vmServer,name=request.POST.get('vm_name'),mem=int(request.POST.get('mem')),status=1,
                                                                cpu=request.POST.get('cpu'),token=INSTANCE.getInsUUID(instance))
                            except Exception,e: 
                                return  JsonResponse({"code":500,"data":None,"msg":e})

                            #生成日志
                            recordLogs.delay(server_id=vmServer.id,vm_name=request.POST.get('vm_name'),
                                             content="创建虚拟机{name}".format(name=request.POST.get('vm_name')),
                                             user=str(request.user),status=dom) 
                            return JsonResponse({"code":200,"data":None,"msg":"虚拟主机添加成功。"}) 
                        else:
                            if request.POST.get('storagetype') == 'new':
                                #创建虚拟机失败时,删除创建的磁盘文件
                                STORAGE.deleteVolume(pool, volume_name)

                            VMS.close() 
                            recordLogs.delay(server_id=vmServer.id,vm_name=request.POST.get('vm_name'),
                                             content="创建虚拟机{name}".format(name=request.POST.get('vm_name')),
                                             user=str(request.user),status=1,result=dom)                            
                            return JsonResponse({"code":500,"data":None,"msg":dom})

            elif op == 'xml':
                domXml = request.POST.get('xml')
                dom = SERVER.defineXML(xml=domXml)
                VMS.close() 
                if isinstance(dom,int):
                    recordLogs.delay(server_id=vmServer.id,vm_name=request.POST.get('vm_name'),
                                             content="通过XML创建虚拟机{name}".format(name=request.POST.get('vm_name')),
                                             user=str(request.user),status=dom) 
                    return  JsonResponse({"code":200,"data":None,"msg":"虚拟主机添加成功。"})
                else:
                    recordLogs.delay(server_id=vmServer.id,vm_name=request.POST.get('vm_name'),
                                             content="通过XML创建虚拟机{name}".format(name=request.POST.get('vm_name')),
                                             user=str(request.user),status=1,result=dom) 
                    return JsonResponse({"code":500,"data":None,"msg":dom})

            elif op=='template':
                try:
                    temp = VmInstance_Template.objects.get(id=request.POST.get('temp'))
                    if INSTANCE:
                        instance =  INSTANCE.queryInstance(name=str(request.POST.get('vm_name')))
                    if instance:
                        return  JsonResponse({"code":500,"msg":"虚拟机已经存在","data":None})
                    else:
                        pool = STORAGE.getStoragePool(pool_name=request.POST.get('storage')) 
                        volume_name = request.POST.get('vm_name')+'.img'
                        if pool:
                            volume = STORAGE.createVolumes(pool, volume_name=volume_name, volume_capacity=temp.disk)
                            if volume:
                                disk_path = volume.path()
                                volume_name = volume.name()
                                disk_xml = Const.CreateDisk(volume_path=disk_path)  
                            else:
                                return JsonResponse({"code":500,"msg":"创建虚拟机失败,存储池里面以存在以主机名命名的磁盘","data":None})
                        else:
                            return  JsonResponse({"code":500,"msg":"创建虚拟机失败,存储池已经被删除掉","data":None})
                        dom_xml = Const.CreateIntanceConfig(dom_name=request.POST.get('vm_name'),maxMem=int(SERVER.getServerInfo().get('mem')),
                                                      mem=temp.mem,cpu=temp.cpu,disk=disk_xml,
                                                      iso_path=request.POST.get('system'),network=None)
                        dom = SERVER.createInstance(dom_xml)
                        if dom==0:    
                            VMS.close()        
                            recordLogs.delay(server_id=vmServer.id,vm_name=request.POST.get('vm_name'),
                                             content="通过模板创建虚拟机{name}".format(name=request.POST.get('vm_name')),
                                             user=str(request.user),status=dom) 
                            return JsonResponse({"code":200,"data":None,"msg":"虚拟主机添加成功。"}) 
                        else:
                            STORAGE.deleteVolume(pool, volume_name)
                            VMS.close() 
                            recordLogs.delay(server_id=vmServer.id,vm_name=request.POST.get('vm_name'),
                                             content="通过模板创建虚拟机{name}".format(name=request.POST.get('vm_name')),
                                             user=str(request.user),status=1,result=dom)                            
                            return JsonResponse({"code":500,"data":None,"msg":dom}) 
                except:
                    return JsonResponse({"code":500,"data":None,"msg":"虚拟主机添加失败。"})