Ejemplo n.º 1
0
    def clone(self, instance, clone_data):
        '''克隆实例'''
        clone_dev_path = []
        xml = self.getInsXMLDesc(instance, flag=1)
        tree = ElementTree.fromstring(xml)
        name = tree.find('name')
        name.text = clone_data['name']
        uuid = tree.find('uuid')
        tree.remove(uuid)
        for num, net in enumerate(tree.findall('devices/interface')):
            elm = net.find('mac')
            inter = net.find('target')
            brName = net.find('source').get('bridge')
            inter.set('dev', brName + '-' + CommTools.radString(4))
            elm.set('address', vMUtil.randomMAC())

        for disk in tree.findall('devices/disk'):
            if disk.get('device') == 'disk':
                elm = disk.find('target')
                device_name = elm.get('dev')
                if device_name:
                    target_file = clone_data['disk']
                    try:
                        meta_prealloc = clone_data['meta']
                    except:
                        meta_prealloc = False
                    elm.set('dev', device_name)
                elm = disk.find('source')
                source_file = elm.get('file')
                if source_file:
                    clone_dev_path.append(source_file)
                    clone_path = os.path.join(os.path.dirname(source_file),
                                              target_file)
                    elm.set('file', clone_path)
                    vol = self.getVolumeByPath(source_file)
                    vol_format = vMUtil.get_xml_path(
                        vol.XMLDesc(0), "/volume/target/format/@type")
                    if vol_format == 'qcow2' and meta_prealloc:
                        meta_prealloc = True
                    vol_clone_xml = """
                                    <volume>
                                        <name>%s</name>
                                        <capacity>0</capacity>
                                        <allocation>0</allocation>
                                        <target>
                                            <format type='%s'/>
                                        </target>
                                    </volume>""" % (target_file, vol_format)
                    stg = vol.storagePoolLookupByVolume()
                    stg.createXMLFrom(vol_clone_xml, vol, meta_prealloc)
        if self.defineXML(ElementTree.tostring(tree)): return 0
Ejemplo n.º 2
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
Ejemplo n.º 3
0
def modfInstance(request):
    if request.method == "POST":
        if CommTools.argsCkeck(args=['op', 'server_id', 'vm_name'],
                               data=request.POST) and request.user.has_perm(
                                   'VManagePlatform.change_vmserverinstance'):
            vMserver = VMServer.selectOneHost(id=request.POST.get('server_id'))
            LIBMG = LibvirtManage(uri=vMserver.uri)
            SERVER = LIBMG.genre(model='server')
            STROAGE = LIBMG.genre(model='storage')
            INSTANCE = LIBMG.genre(model='instance')
            NETWORK = LIBMG.genre(model='network')
            if SERVER:
                instance = INSTANCE.queryInstance(
                    name=str(request.POST.get('vm_name')))
                if instance is False:
                    LIBMG.close()
                    return JsonResponse({
                        "code": 404,
                        "data": None,
                        "msg": "虚拟机不存在,或者已经被删除。"
                    })
            else:
                return JsonResponse({
                    "code": 500,
                    "data": None,
                    "msg": "虚拟主机链接失败。"
                })
            #调整磁盘
            if request.POST.get('device') == 'disk':
                if request.POST.get('op') == 'attach':
                    if instance.state()[0] == 5:
                        return JsonResponse({
                            "code": 500,
                            "data": None,
                            "msg": "请先启动虚拟机。"
                        })
                    storage = STROAGE.getStoragePool(
                        pool_name=request.POST.get('pool_name'))
                    if storage:
                        volume = STROAGE.createVolumes(
                            pool=storage,
                            volume_name=request.POST.get('vol_name'),
                            drive=request.POST.get('vol_drive'),
                            volume_capacity=request.POST.get('vol_size'))
                        if volume:
                            volPath = volume.path()
                            volume_name = volume.name()
                        else:
                            LIBMG.close()
                            return JsonResponse({
                                "code": 500,
                                "data": None,
                                "msg": "卷已经存在。"
                            })
                        status = INSTANCE.addInstanceDisk(instance, volPath)
                        LIBMG.close()
                        if status:
                            recordLogs.delay(
                                user=request.user,
                                action='attach_disk',
                                status=0,
                                vm_name=request.POST.get('vm_name'))
                            return JsonResponse({
                                "code": 200,
                                "data": None,
                                "msg": "操作成功。"
                            })
                        else:
                            STROAGE.deleteVolume(storage, volume_name)
                            recordLogs.delay(
                                user=request.user,
                                action='attach_disk',
                                status=1,
                                vm_name=request.POST.get('vm_name'))
                            return JsonResponse({
                                "code": 500,
                                "data": None,
                                "msg": "操作失败。"
                            })
                    else:
                        LIBMG.close()
                        return JsonResponse({
                            "code": 404,
                            "data": None,
                            "msg": "存储池不存在,或者已经被删除。"
                        })
                elif request.POST.get('op') == 'detach':
                    status = INSTANCE.delInstanceDisk(
                        instance, volPath=request.POST.get('disk'))
                    LIBMG.close()
                    recordLogs.delay(user=request.user,
                                     action='detach_disk',
                                     status=status,
                                     vm_name=request.POST.get('vm_name'))
                    if status == 0:
                        return JsonResponse({
                            "code": 200,
                            "data": None,
                            "msg": "操作成功。"
                        })
                    else:
                        LIBMG.close()
                        return JsonResponse({
                            "code": 500,
                            "data": status,
                            "msg": "操作失败。"
                        })
            #调整网卡
            elif request.POST.get('device') == 'netk':
                if request.POST.get('op') == 'attach':
                    result = INSTANCE.addInstanceInterface(
                        instance, brName=request.POST.get('netk_name'))
                    recordLogs.delay(user=request.user,
                                     action='attach_netk',
                                     status=result,
                                     vm_name=request.POST.get('vm_name'))
                    if result == 0:
                        return JsonResponse({
                            "code": 200,
                            "data": None,
                            "msg": "操作成功。"
                        })
                    else:
                        return JsonResponse({
                            "code": 500,
                            "data": status,
                            "msg": "添加失败。"
                        })
                elif request.POST.get('op') == 'detach':
                    result = INSTANCE.delInstanceInterface(
                        instance, interName=request.POST.get('netk_name'))
                    recordLogs.delay(user=request.user,
                                     action='detach_netk',
                                     status=result,
                                     vm_name=request.POST.get('vm_name'))
                    if result == 0:
                        return JsonResponse({
                            "code": 200,
                            "data": None,
                            "msg": "操作成功。"
                        })
                    else:
                        return JsonResponse({
                            "code": 500,
                            "data": status,
                            "msg": "添加失败。"
                        })
            #调整内存大小
            elif request.POST.get('device') == 'mem':
                if request.POST.get('op') == 'attach':
                    result = INSTANCE.setMem(instance,
                                             mem=int(request.POST.get('mem')))
                    recordLogs.delay(user=request.user,
                                     action='attach_mem',
                                     status=result,
                                     vm_name=request.POST.get('vm_name'))
                    if result == 0:
                        return JsonResponse({
                            "code": 200,
                            "data": None,
                            "msg": "操作成功。"
                        })
                    else:
                        return JsonResponse({
                            "code": 500,
                            "data": None,
                            "msg": "不能设置虚拟机内存超过宿主机机器的物理内存"
                        })
            #调整cpu个数
            elif request.POST.get('device') == 'cpu':
                if request.POST.get('op') == 'attach':
                    result = INSTANCE.setVcpu(instance,
                                              cpu=int(request.POST.get('cpu')))
                    LIBMG.close()
                    recordLogs.delay(user=request.user,
                                     action='attach_cpu',
                                     status=result,
                                     vm_name=request.POST.get('vm_name'))
                    if result == 0:
                        return JsonResponse({
                            "code": 200,
                            "data": None,
                            "msg": "操作成功。"
                        })
                    else:
                        return JsonResponse({
                            "code": 500,
                            "data": None,
                            "msg": "不能设置虚拟机CPU超过宿主机机器的物理CPU个数"
                        })
            #调整带宽
            elif request.POST.get('device') == 'bandwidth':
                SSH = BRManage(hostname=vMserver.server_ip, port=22)
                OVS = SSH.genre(model='ovs')
                BRCTL = SSH.genre(model='brctl')
                mode = INSTANCE.getInterFace(instance,
                                             request.POST.get('netk_name'))
                if request.POST.get('op') == 'attach':
                    if mode.get('type') == 'openvswitch':
                        if int(request.POST.get('bandwidth')) == 0:
                            result = OVS.ovsCleanBandwidth(
                                port=request.POST.get('netk_name'))
                        else:
                            result = OVS.ovsConfBandwidth(
                                port=request.POST.get('netk_name'),
                                bandwidth=request.POST.get('bandwidth'))
                    else:
                        if int(request.POST.get('bandwidth')) == 0:
                            result = INSTANCE.cleanInterfaceBandwidth(
                                instance, request.POST.get('netk_name'))
                        result = INSTANCE.setInterfaceBandwidth(
                            instance,
                            port=request.POST.get('netk_name'),
                            bandwidth=request.POST.get('bandwidth'))
                    SSH.close()
                    LIBMG.close()
                    if result.get('status') == 'success':
                        return JsonResponse({
                            "code": 200,
                            "data": None,
                            "msg": "操作成功。"
                        })
                    else:
                        return JsonResponse({
                            "code": 500,
                            "data": None,
                            "msg": "未设置带宽,不需要清除"
                        })

            LIBMG.close()
        else:
            return JsonResponse({
                "code": 500,
                "data": None,
                "msg": "暂时不支持的操作或者您没有权限操作操作此项。"
            })
Ejemplo n.º 4
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": "不支持的操作或者您没有权限添加虚拟机"
            })
Ejemplo n.º 5
0
        else:
            return JsonResponse({
                "code": 500,
                "data": None,
                "msg": "不支持的操作或者您没有权限添加虚拟机"
            })


@login_required
def modfInstance(request, id):
    try:
        vServer = VmServer.objects.get(id=id)
    except Exception, e:
        return JsonResponse({"code": 500, "msg": "找不到主机资源", "data": e})
    if request.method == "POST":
        if CommTools.argsCkeck(args=['op', 'server_id', 'vm_name'],
                               data=request.POST) and request.user.has_perm(
                                   'VManagePlatform.change_vmserverinstance'):
            LIBMG = LibvirtManage(vServer.server_ip, vServer.username,
                                  vServer.passwd, vServer.vm_type)
            SERVER = LIBMG.genre(model='server')
            STROAGE = LIBMG.genre(model='storage')
            INSTANCE = LIBMG.genre(model='instance')
            if SERVER:
                instance = INSTANCE.queryInstance(
                    name=str(request.POST.get('vm_name')))
                if instance is False:
                    LIBMG.close()
                    return JsonResponse({
                        "code": 404,
                        "data": None,
                        "msg": "虚拟机不存在,或者已经被删除。"
Ejemplo n.º 6
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":"虚拟主机添加失败。"})
Ejemplo n.º 7
0
                            return JsonResponse({"code":500,"data":None,"msg":dom}) 
                except:
                    return JsonResponse({"code":500,"data":None,"msg":"虚拟主机添加失败。"})
                    
        else:
            return JsonResponse({"code":500,"data":None,"msg":"不支持的操作或者您没有权限创建虚拟机"})

@login_required
def modfInstance(request,id):      
    try:
        vServer = VmServer.objects.get(id=id)
    except Exception,e:
        return JsonResponse({"code":500,"msg":"找不到主机资源","data":e})

    if request.method == "POST":
        if CommTools.argsCkeck(args=['op','server_id','vm_name'], data=request.POST) and request.user.has_perm('VManagePlatform.change_vmserverinstance'):
            LIBMG = LibvirtManage(vServer.server_ip,vServer.username, vServer.passwd,vServer.vm_type)  
            SERVER = LIBMG.genre(model='server')
            STORAGE = LIBMG.genre(model='storage')
            INSTANCE = LIBMG.genre(model='instance')

            if SERVER:
                instance = INSTANCE.queryInstance(name=str(request.POST.get('vm_name')))  
                if instance is False:
                    LIBMG.close()
                    return  JsonResponse({"code":404,"data":None,"msg":"虚拟机不存在,或者已经被删除。"})     
            else:return  JsonResponse({"code":500,"data":None,"msg":"虚拟主机链接失败。"})

            #调整磁盘            
            if request.POST.get('device') == 'disk':   
                if request.POST.get('op') == 'attach':