Esempio n. 1
0
def HandleLoginRequest(request):
    is_post, bad_response = POST_req_checker(request)

    if not is_post:
        return bad_response

    body_unicode = request.body.decode('utf-8')
    body = json.loads(body_unicode)

    username = body['Username']
    password = body['Password']

    account_object = authenticate(username=username, password=password)
    response = HttpResponse()

    if account_object is not None:
        token = Token.objects.create(user=account_object)

        response['Content-Type'] = 'application/text'
        response.status_code = 200
        response.reason_phrase = 'Login Successful'
        response.content = token.key
    else:
        response['Content-Type'] = 'application/text'
        response.status_code = 401
        response.reason_phrase = 'Login Failed'

    return response
Esempio n. 2
0
    def add_disk(self, disks):
        print('disks:', disks)
        disks = json.loads(disks)

        controller = vim.vm.device.ParaVirtualSCSIController()
        controller.sharedBus = vim.vm.device.VirtualSCSIController.Sharing.noSharing
        virtual_device_spec = vim.vm.device.VirtualDeviceSpec()
        virtual_device_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
        virtual_device_spec.device = controller
        config_spec = vim.vm.ConfigSpec()
        config_spec.deviceChange = [virtual_device_spec]
        task = self.vm.ReconfigVM_Task(config_spec)
        wait_for_tasks(self.si, [task])

        for disk in disks:
            print('disk:', disk)
            disk_size = disk.get('size')
            disk_type = disk.get('type')
            if not all([disk_size, disk_type]):
                raise Exception('parameter error')

            spec = vim.vm.ConfigSpec()
            # get all disks on a VM, set unit_number to the next available
            unit_number = 0
            for dev in self.vm.config.hardware.device:
                if hasattr(dev.backing, 'fileName'):
                    unit_number = int(dev.unitNumber) + 1
                    # unit_number 7 reserved for scsi controller
                    if unit_number == 7:
                        unit_number += 1
                    if unit_number >= 16:
                        print "we don't support this many disks"
                        raise Exception("we don't support this many disks")
                if isinstance(dev, vim.vm.device.VirtualSCSIController):
                    controller = dev

            # add disk here
            dev_changes = []
            new_disk_kb = int(disk_size) * 1024 * 1024
            disk_spec = vim.vm.device.VirtualDeviceSpec()
            disk_spec.fileOperation = "create"
            disk_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
            disk_spec.device = vim.vm.device.VirtualDisk()
            disk_spec.device.backing = \
                vim.vm.device.VirtualDisk.FlatVer2BackingInfo()

            if disk_type == 'thin':
                disk_spec.device.backing.thinProvisioned = True

            disk_spec.device.backing.diskMode = 'persistent'
            disk_spec.device.unitNumber = unit_number
            disk_spec.device.capacityInKB = new_disk_kb
            disk_spec.device.controllerKey = controller.key
            dev_changes.append(disk_spec)
            spec.deviceChange = dev_changes
            task = self.vm.ReconfigVM_Task(spec=spec)
            wait_for_tasks(self.si, [task])

        sync_disk(self.platform_id, self.vm)
Esempio n. 3
0
    def add_network(self, networks):

        networks = json.loads(networks)

        devs = self.vm.config.hardware.device

        # nic_prefix_label = 'Network adapter '

        for network in networks:

            # 获取网络设备信息
            local_network_port_group = network_port_group_manage.get_network_by_id(
                network)

            # 开始添加网卡信息
            spec = vim.vm.ConfigSpec()
            nic_changes = []

            nic_spec = vim.vm.device.VirtualDeviceSpec()
            nic_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
            nic_spec.device = vim.vm.device.VirtualE1000()
            nic_spec.device.deviceInfo = vim.Description()
            nic_spec.device.deviceInfo.summary = 'vCenter API test'

            # content = self.si.RetrieveContent()

            network = get_obj(self.content, [vim.Network],
                              local_network_port_group.name)
            if isinstance(network, vim.OpaqueNetwork):

                nic_spec.device.backing = \
                    vim.vm.device.VirtualEthernetCard.OpaqueNetworkBackingInfo()
                nic_spec.device.backing.opaqueNetworkType = \
                    network.summary.opaqueNetworkType
                nic_spec.device.backing.opaqueNetworkId = \
                    network.summary.opaqueNetworkId
            else:

                nic_spec.device.backing = \
                    vim.vm.device.VirtualEthernetCard.NetworkBackingInfo()
                nic_spec.device.backing.useAutoDetect = False
                nic_spec.device.backing.deviceName = network.name

            nic_spec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo(
            )
            nic_spec.device.connectable.startConnected = True
            nic_spec.device.connectable.allowGuestControl = True
            nic_spec.device.connectable.connected = False
            nic_spec.device.connectable.status = 'untried'
            nic_spec.device.wakeOnLanEnabled = True
            nic_spec.device.addressType = 'assigned'

            nic_changes.append(nic_spec)
            spec.deviceChange = nic_changes
            task = self.vm.ReconfigVM_Task(spec=spec)
            wait_for_tasks(self.si, [task])
        # 同步云主机网卡信息
        sync_network_device(self.platform_id, self.vm)
Esempio n. 4
0
    def __init__(self,
                 platform_id,
                 uuid=None,
                 si=None,
                 content=None,
                 network_port_group=None,
                 network_device=None):
        # print('platform_id:', platform_id)
        self.platform_id = platform_id
        self.si = si
        self.content = content
        self.uuid = uuid

        if not si:
            try:
                si, content, platform = get_connect(platform_id)
                self.si = si
                self.content = content
                self.platform = platform
            except Exception as e:
                raise Exception('connect vcenter failed')
        else:
            self.platform = None
        if network_port_group:
            self.network_port_group = json.loads(network_port_group)
        else:
            self.network_port_group = None
        if network_device:
            self.network_device = json.loads(network_device)
        else:
            self.network_device = None

        if uuid:

            local_vm = db.instances.list_by_uuid(self.platform_id, self.uuid)
            vm = get_obj(self.content, [vim.VirtualMachine], local_vm.vm_name)

            self.local_vm = local_vm
            self.vm = vm
        else:
            self.local_vm = None
            self.vm = None
Esempio n. 5
0
    def decrypt_keystr(self, keystr):
        '''解密keystr'''
        global aes_key, aes_iv
        licdata = dict()

        try:
            obj = AES.new(aes_key, AES.MODE_CBC, aes_iv)
            keydata = base64.b64decode(keystr)
            lictxt = obj.decrypt(keydata)
            padpos = lictxt.find('}0') + 1
            if padpos == 0:
                jsdata = json.loads(lictxt)
            else:
                jsdata = json.loads(lictxt[:padpos])
            if jsdata != None:
                for (k, v) in jsdata.items():
                    licdata[k] = v
        except Exception as err:
            print(str(err))

        return licdata
Esempio n. 6
0
def HandleRateRequest(request):
    # TODO make sure the prof is in the module instance
    is_post, bad_response = POST_req_checker(request)

    if not is_post:
        return bad_response

    response = HttpResponse()
    response['Content-Type'] = 'application/text'
    if not Token.objects.get(key=request.headers['Authorization']):
        response.status_code = 401
        response.reason_phrase = 'Not Logged in'
        return response

    body_unicode = request.body.decode('utf-8')
    body = json.loads(body_unicode)

    rating = body["rating"]
    professor = body["professor"]
    module = body["module"]
    year = body["year"]
    semester = body["semester"]

    try:
        prof_object = Professor.objects.get(professor_code=professor)
        module_object = Module.objects.get(module_code=module)

        module_instance_object = ModuleInstance.objects.get(
            module=module_object, academic_year=year, module_semester=semester)
        response.content = '3'

        rat = Rating.objects.create(rating=rating,
                                    module=module_instance_object,
                                    professor_code=prof_object)
        rat.save()

        response.status_code = 200
        response.reason_phrase = 'OK'
    except Exception as e:
        e = str(e)
        response.status_code = 404
        response.reason_phrase = 'Records not found'

    return response
Esempio n. 7
0
def HandleRegisterRequest(request):
    body_unicode = request.body.decode('utf-8')
    body = json.loads(body_unicode)

    username = body['Username']
    email = body['Email']
    password = body['Password']

    response = HttpResponse()
    response['Content-Type'] = 'application/text'

    try:
        user = User.objects.create_user(username=username,
                                        email=email,
                                        password=password)
        user.save()
        response.status_code = 200
        response.reason_phrase = 'User Created Successfully'
    except IntegrityError:
        response.status_code = 409
        response.reason_phrase = 'User Creation Failed'

    return response
Esempio n. 8
0
    def del_network(self, networks):
        try:
            networks = json.loads(networks)

            devs = self.vm.config.hardware.device

            # 获取network device label
            for device_id in networks:

                # 根据id 获取 network device
                device = network_device_manage.device_list_by_id(
                    self.platform_id, self.uuid, device_id)

                if device:
                    for dev in devs:
                        virtual_nic_device = None
                        if isinstance(dev, vim.vm.device.VirtualEthernetCard) \
                                and device.label == dev.deviceInfo.label:
                            virtual_nic_device = dev

                        if virtual_nic_device:
                            virtual_nic_spec = vim.vm.device.VirtualDeviceSpec(
                            )
                            virtual_nic_spec.operation = \
                                vim.vm.device.VirtualDeviceSpec.Operation.remove
                            virtual_nic_spec.device = virtual_nic_device

                            spec = vim.vm.ConfigSpec()
                            spec.deviceChange = [virtual_nic_spec]
                            task = self.vm.ReconfigVM_Task(spec=spec)
                            wait_for_tasks(self.si, [task])
                else:
                    raise Exception('unable find vm network device')
            # 同步云主机网卡信息
            sync_network_device(self.platform_id, self.vm)
        except Exception as e:
            Exception('vm network delete failed')
Esempio n. 9
0
    def boot(self, new_cpu, new_memory, dc_id, ds_id, vm_name, networks, disks,
             image_id):

        try:
            if disks:
                new_disks = json.loads(disks)
                for disk in new_disks:
                    if not disk.get('type'):
                        raise Exception(
                            'The disk information format is incorrect.')
                    if not disk.get('size'):
                        raise Exception(
                            'The disk information format is incorrect.')
        except Exception as e:
            raise Exception('The disk information format is incorrect.')

        try:

            dc_info = db.vcenter.vcenter_tree_by_id(dc_id)
            dc = get_obj(self.content, [vim.Datacenter], dc_info.name)
        except Exception as e:
            raise Exception('dc get failed')

        vm_folder = dc.vmFolder
        hosts = dc.hostFolder.childEntity
        resource_pool = hosts[0].resourcePool

        # ds = content.viewManager.CreateContainerView(dc, [vim.Datastore], True)

        ds = get_obj(self.content, [vim.Datastore], 'datastore1')

        # datastore_path = '[' + ds + '] ' + vm_name
        datastore_path = '[datastore1] ' + vm_name
        print datastore_path
        vmx_file = vim.vm.FileInfo(logDirectory=None,
                                   snapshotDirectory=None,
                                   suspendDirectory=None,
                                   vmPathName=datastore_path)

        config = vim.vm.ConfigSpec(name=vm_name,
                                   memoryMB=int(new_memory),
                                   numCPUs=int(new_cpu),
                                   files=vmx_file,
                                   guestId='rhel6_64Guest',
                                   version='vmx-09')
        try:
            task = vm_folder.CreateVM_Task(config=config, pool=resource_pool)
            wait_for_tasks(self.si, [task])
            vm = get_obj(self.content, [vim.VirtualMachine], vm_name)
            self.vm = vm
            self.update_vm_local()
        except Exception as e:
            raise Exception('task to create failed')
        try:
            # 获取vm 并为vm 添加network

            if networks:
                self.add_network(networks)
        except Exception as e:
            raise Exception('vm network attach failed')
        try:
            if disks:
                self.add_disk(disks)
        except Exception as e:
            raise Exception('vm disk attach failed')
        try:
            if image_id:
                self.add_image(image_id)
            # vm_add_network(self.platform_id, vm.summary.config.uuid, networks, vm)
        except Exception as e:
            raise Exception('vm image attach failed')