Ejemplo n.º 1
0
def r_migrate(uuids, destination_host):

    args_rules = [
        Rules.UUIDS.value,
        Rules.DESTINATION_HOST.value
    ]

    try:
        ji.Check.previewing(args_rules, {'uuids': uuids, 'destination_host': destination_host})

        ret = dict()
        ret['state'] = ji.Common.exchange_state(20000)

        # 取全部活着的 hosts
        available_hosts = Host.get_available_hosts(nonrandom=None)

        if available_hosts.__len__() == 0:
            ret['state'] = ji.Common.exchange_state(50351)
            return ret

        available_hosts_mapping_by_node_id = dict()

        for host in available_hosts:
            if host['node_id'] not in available_hosts_mapping_by_node_id:
                available_hosts_mapping_by_node_id[host['node_id']] = host

        guest = Guest()
        for uuid in uuids.split(','):
            guest.uuid = uuid
            guest.get_by('uuid')

        config = Config()
        config.id = 1
        config.get()

        for uuid in uuids.split(','):
            guest.uuid = uuid
            guest.get_by('uuid')

            # 忽略宕机计算节点 上面的 虚拟机 迁移请求
            # 忽略目标计算节点 等于 当前所在 计算节点 的虚拟机 迁移请求
            if guest.node_id not in available_hosts_mapping_by_node_id or \
                    available_hosts_mapping_by_node_id[guest.node_id]['hostname'] == destination_host:
                continue

            message = {
                '_object': 'guest',
                'action': 'migrate',
                'uuid': uuid,
                'node_id': guest.node_id,
                'storage_mode': config.storage_mode,
                'duri': 'qemu+ssh://' + destination_host + '/system'
            }

            Utils.emit_instruction(message=json.dumps(message))

        return ret

    except ji.PreviewingError, e:
        return json.loads(e.message)
    def verify(customer_id, secret_key, queueit_token):
        diagnostics = ConnectorDiagnostics()
        q_params = QueueUrlParams.extractQueueParams(queueit_token)

        if q_params is None:
            return diagnostics

        if q_params.redirectType is None:
            return diagnostics

        if q_params.redirectType != "debug":
            return diagnostics

        if Utils.isNilOrEmpty(customer_id) or Utils.isNilOrEmpty(secret_key):
            diagnostics.__setStateWithSetupError()
            return diagnostics

        expected_hash = QueueitHelpers.hmacSha256Encode(
            q_params.queueITTokenWithoutHash, secret_key)
        if q_params.hashCode != expected_hash:
            diagnostics.__setStateWithTokenError(customer_id, "hash")
            return diagnostics

        if q_params.timeStamp < QueueitHelpers.getCurrentTime():
            diagnostics.__setStateWithTokenError(customer_id, "timestamp")
            return diagnostics

        diagnostics.isEnabled = True
        return diagnostics
Ejemplo n.º 3
0
def r_resume(uuids):

    args_rules = [Rules.UUIDS.value]

    try:
        ji.Check.previewing(args_rules, {'uuids': uuids})

        guest = Guest()
        for uuid in uuids.split(','):
            guest.uuid = uuid
            guest.get_by('uuid')

        for uuid in uuids.split(','):
            guest.uuid = uuid
            guest.get_by('uuid')

            message = {
                '_object': 'guest',
                'action': 'resume',
                'uuid': uuid,
                'node_id': guest.node_id
            }

            Utils.emit_instruction(message=json.dumps(message))

        ret = dict()
        ret['state'] = ji.Common.exchange_state(20000)
        return ret

    except ji.PreviewingError, e:
        return json.loads(e.message)
Ejemplo n.º 4
0
def r_force_reboot(uuids):

    args_rules = [Rules.UUIDS.value]

    try:
        ji.Check.previewing(args_rules, {'uuids': uuids})

        guest = Guest()
        for uuid in uuids.split(','):
            guest.uuid = uuid
            guest.get_by('uuid')

        for uuid in uuids.split(','):
            guest.uuid = uuid
            guest.get_by('uuid')
            disks, _ = Disk.get_by_filter(
                filter_str=':'.join(['guest_uuid', 'eq', guest.uuid]))

            message = {
                '_object': 'guest',
                'action': 'force_reboot',
                'uuid': uuid,
                'node_id': guest.node_id,
                'disks': disks
            }

            Utils.emit_instruction(message=json.dumps(message))

        ret = dict()
        ret['state'] = ji.Common.exchange_state(20000)
        return ret

    except ji.PreviewingError, e:
        return json.loads(e.message)
Ejemplo n.º 5
0
 def worker(self, args):
     is_initialized = Repo(Utils.get_backend(self.backup)).is_initialized()
     if self.edit:
         if not is_initialized:
             return False
     else:
         Repo(Utils.get_backend(self.backup)).init(
             self.backup.password.encode())
     return True
Ejemplo n.º 6
0
def r_delete(ids):
    ret = dict()
    ret['state'] = ji.Common.exchange_state(20000)

    config = Config()
    config.id = 1
    config.get()

    # 取全部活着的 hosts
    available_hosts = Host.get_available_hosts(nonrandom=None)

    if available_hosts.__len__() == 0:
        ret['state'] = ji.Common.exchange_state(50351)
        return ret

    chosen_host = available_hosts[0]
    node_id = chosen_host['node_id']

    os_template_image = OSTemplateImage()

    # TODO: 加入对,是否有被 Guest 引用的判断
    for _id in ids.split(','):
        os_template_image.id = _id
        os_template_image.get()

    for _id in ids.split(','):
        os_template_image.id = _id
        os_template_image.get()

        # 暂时不支持从计算节点上,删除公共镜像
        if os_template_image.kind == OSTemplateImageKind.public.value:
            os_template_image.delete()
            continue

        elif os_template_image.kind == OSTemplateImageKind.custom.value:
            os_template_image.progress = 254

            message = {
                '_object': 'os_template_image',
                'action': 'delete',
                'storage_mode': config.storage_mode,
                'dfs_volume': config.dfs_volume,
                'template_path': os_template_image.path,
                # uuid 这里没有实际意义,仅仅是为了迁就 JimV-C 的个命令格式
                'uuid': None,
                'node_id': node_id,
                'os_template_image_id': os_template_image.id,
                'passback_parameters': {
                    'id': os_template_image.id
                }
            }

            Utils.emit_instruction(message=json.dumps(message))

            os_template_image.update()

    return ret
Ejemplo n.º 7
0
def r_resize(uuid, size):

    args_rules = [
        Rules.UUID.value,
        Rules.DISK_SIZE_STR.value
    ]

    try:
        ji.Check.previewing(args_rules, {'uuid': uuid, 'size': size})

        disk = Disk()
        disk.uuid = uuid
        disk.get_by('uuid')

        ret = dict()
        ret['state'] = ji.Common.exchange_state(20000)

        if disk.size >= int(size):
            ret['state'] = ji.Common.exchange_state(41257)
            return ret

        config = Config()
        config.id = 1
        config.get()

        disk.size = int(size)
        disk.quota(config=config)
        # 将在事件返回层(models/event_processor.py:224 附近),更新数据库中 disk 对象

        message = {
            '_object': 'disk',
            'action': 'resize',
            'uuid': disk.uuid,
            'guest_uuid': disk.guest_uuid,
            'storage_mode': config.storage_mode,
            'size': disk.size,
            'dfs_volume': config.dfs_volume,
            'node_id': disk.node_id,
            'image_path': disk.path,
            'disks': [disk.__dict__],
            'passback_parameters': {'size': disk.size}
        }

        if config.storage_mode in [StorageMode.shared_mount.value, StorageMode.ceph.value,
                                   StorageMode.glusterfs.value]:
            message['node_id'] = Host.get_lightest_host()['node_id']

        if disk.guest_uuid.__len__() == 36:
            message['device_node'] = dev_table[disk.sequence]

        Utils.emit_instruction(message=json.dumps(message, ensure_ascii=False))

        return ret

    except ji.PreviewingError, e:
        return json.loads(e.message)
Ejemplo n.º 8
0
def update_ssh_key(uuid):

    guest = Guest()
    guest.uuid = uuid
    guest.get_by('uuid')

    # 不支持更新离线虚拟机的 SSH-KEY
    if guest.status != GuestState.running.value:
        return

    os_template_image = OSTemplateImage()
    os_template_profile = OSTemplateProfile()

    os_template_image.id = guest.os_template_image_id
    os_template_image.get()

    os_template_profile.id = os_template_image.os_template_profile_id
    os_template_profile.get()

    # 不支持更新 Windows 虚拟机的 SSH-KEY
    if os_template_profile.os_type == 'windows':
        return

    rows, _ = SSHKeyGuestMapping.get_by_filter(
        filter_str=':'.join(['guest_uuid', 'eq', uuid]))

    ssh_keys_id = list()
    for row in rows:
        ssh_keys_id.append(row['ssh_key_id'].__str__())

    ssh_keys = list()

    if ssh_keys_id.__len__() > 0:
        rows, _ = SSHKey.get_by_filter(
            filter_str=':'.join(['id', 'in', ','.join(ssh_keys_id)]))
        for row in rows:
            ssh_keys.append(row['public_key'])

    else:
        ssh_keys.append('')

    message = {
        '_object': 'guest',
        'uuid': uuid,
        'node_id': guest.node_id,
        'action': 'update_ssh_key',
        'ssh_keys': ssh_keys,
        'os_type': os_template_profile.os_type,
        'passback_parameters': {
            'uuid': uuid,
            'ssh_keys': ssh_keys,
            'os_type': os_template_profile.os_type
        }
    }

    Utils.emit_instruction(message=json.dumps(message, ensure_ascii=False))
Ejemplo n.º 9
0
def r_detach_disk(disk_uuid):

    args_rules = [Rules.DISK_UUID.value]

    try:
        ji.Check.previewing(args_rules, {'disk_uuid': disk_uuid})

        disk = Disk()
        disk.uuid = disk_uuid
        disk.get_by('uuid')

        ret = dict()
        ret['state'] = ji.Common.exchange_state(20000)

        if disk.state != DiskState.mounted.value or disk.sequence == 0:
            # 表示未被任何实例使用,已被分离
            # 序列为 0 的表示实例系统盘,系统盘不可以被分离
            # TODO: 系统盘单独范围其它状态
            return ret

        guest = Guest()
        guest.uuid = disk.guest_uuid
        guest.get_by('uuid')

        # 判断 Guest 是否处于可用状态
        if guest.status in (status.GuestState.no_state.value,
                            status.GuestState.dirty.value):
            ret['state'] = ji.Common.exchange_state(41259)
            return ret

        config = Config()
        config.id = 1
        config.get()

        guest_xml = GuestXML(guest=guest, disk=disk, config=config)

        message = {
            '_object': 'guest',
            'action': 'detach_disk',
            'uuid': disk.guest_uuid,
            'node_id': guest.node_id,
            'xml': guest_xml.get_disk(),
            'passback_parameters': {
                'disk_uuid': disk.uuid
            }
        }

        Utils.emit_instruction(message=json.dumps(message))

        disk.state = DiskState.unloading.value
        disk.update()

        return ret

    except ji.PreviewingError, e:
        return json.loads(e.message)
Ejemplo n.º 10
0
def r_adjust_ability(uuids, cpu, memory):
    args_rules = [
        Rules.UUIDS.value,
        Rules.CPU.value,
        Rules.MEMORY.value,
    ]

    try:
        ret = dict()
        ret['state'] = ji.Common.exchange_state(20000)

        cpu = int(cpu)
        memory = int(memory)

        ji.Check.previewing(args_rules, {'uuids': uuids, 'cpu': cpu, 'memory': memory})

        not_ready_yet_of_guests = list()

        guest = Guest()

        # 检测所指定的 UUDIs 实例都存在。且状态都为可以操作状态(即关闭状态)。
        for uuid in uuids.split(','):
            guest.uuid = uuid
            guest.get_by('uuid')

            if guest.status != status.GuestState.shutoff.value:
                not_ready_yet_of_guests.append(guest.__dict__)

        if not_ready_yet_of_guests.__len__() > 0:
            ret['state'] = ji.Common.exchange_state(41261)
            ret['data'] = not_ready_yet_of_guests
            return ret

        for uuid in uuids.split(','):
            guest.uuid = uuid
            guest.get_by('uuid')
            guest.cpu = cpu
            guest.memory = memory

            message = {
                '_object': 'guest',
                'action': 'adjust_ability',
                'uuid': guest.uuid,
                'node_id': guest.node_id,
                'cpu': guest.cpu,
                'memory': guest.memory,
                'passback_parameters': {'cpu': guest.cpu, 'memory': guest.memory}
            }

            Utils.emit_instruction(message=json.dumps(message, ensure_ascii=False))

        return ret

    except ji.PreviewingError, e:
        return json.loads(e.message)
Ejemplo n.º 11
0
    def __resolveQueueRequestByLocalConfig(target_url, queueit_token,
                                           queue_config, customer_id,
                                           secret_key, http_context_provider,
                                           debug_entries, is_debug):
        if is_debug:
            debug_entries["SdkVersion"] = UserInQueueService.SDK_VERSION
            debug_entries["Connector"] = http_context_provider.getProviderName(
            )
            debug_entries["Runtime"] = KnownUser.__getRunTime()
            debug_entries["TargetUrl"] = target_url
            debug_entries["QueueitToken"] = queueit_token
            debug_entries[
                "OriginalUrl"] = http_context_provider.getOriginalRequestUrl()
            if queue_config is None:
                debug_entries["QueueConfig"] = "NULL"
            else:
                debug_entries["QueueConfig"] = queue_config.toString()
            KnownUser.__logMoreRequestDetails(debug_entries,
                                              http_context_provider)

        if Utils.isNilOrEmpty(customer_id):
            raise KnownUserError("customerId can not be none or empty.")

        if Utils.isNilOrEmpty(secret_key):
            raise KnownUserError("secretKey can not be none or empty.")

        if queue_config is None:
            raise KnownUserError("queueConfig can not be none.")

        if Utils.isNilOrEmpty(queue_config.eventId):
            raise KnownUserError(
                "queueConfig.eventId can not be none or empty.")

        if Utils.isNilOrEmpty(queue_config.queueDomain):
            raise KnownUserError(
                "queueConfig.queueDomain can not be none or empty.")

        minutes = QueueitHelpers.convertToInt(
            queue_config.cookieValidityMinute)
        if minutes <= 0:
            raise KnownUserError(
                "queueConfig.cookieValidityMinute should be integer greater than 0."
            )

        if not isinstance(queue_config.extendCookieValidity, bool):
            raise KnownUserError(
                "queueConfig.extendCookieValidity should be valid boolean.")

        user_in_queue_service = KnownUser.__getUserInQueueService(
            http_context_provider)
        result = user_in_queue_service.validateQueueRequest(
            target_url, queueit_token, queue_config, customer_id, secret_key)
        result.isAjaxResult = KnownUser.__isQueueAjaxCall(
            http_context_provider)
        return result
Ejemplo n.º 12
0
def r_reset_password(uuids, password):

    args_rules = [
        Rules.UUIDS.value,
        Rules.PASSWORD.value
    ]

    try:
        ji.Check.previewing(args_rules, {'uuids': uuids, 'password': password})

        guest = Guest()
        os_template_image = OSTemplateImage()
        os_template_profile = OSTemplateProfile()

        # 检测所指定的 UUDIs 实例都存在
        for uuid in uuids.split(','):
            guest.uuid = uuid
            guest.get_by('uuid')

        for uuid in uuids.split(','):
            guest.uuid = uuid
            guest.get_by('uuid')

            os_template_image.id = guest.os_template_image_id
            os_template_image.get()

            os_template_profile.id = os_template_image.os_template_profile_id
            os_template_profile.get()

            user = '******'

            if os_template_profile.os_type == 'windows':
                user = '******'

            # guest.password 由 guest 事件处理机更新。参见 @models/event_processory.py:189 附近。

            message = {
                '_object': 'guest',
                'action': 'reset_password',
                'uuid': guest.uuid,
                'node_id': guest.node_id,
                'os_type': os_template_profile.os_type,
                'user': user,
                'password': password,
                'passback_parameters': {'password': password}
            }

            Utils.emit_instruction(message=json.dumps(message, ensure_ascii=False))

        ret = dict()
        ret['state'] = ji.Common.exchange_state(20000)
        return ret

    except ji.PreviewingError, e:
        return json.loads(e.message)
Ejemplo n.º 13
0
def r_delete(snapshots_id):

    args_rules = [
        Rules.SNAPSHOTS_ID.value
    ]

    try:
        ji.Check.previewing(args_rules, {'snapshots_id': snapshots_id})

        snapshot = Snapshot()
        guest = Guest()

        # 检测所指定的 快照 都存在
        for snapshot_id in snapshots_id.split(','):
            snapshot.snapshot_id = snapshot_id
            snapshot.get_by('snapshot_id')

            guest.uuid = snapshot.guest_uuid
            guest.get_by('uuid')

        # 执行删除操作
        for snapshot_id in snapshots_id.split(','):
            snapshot.snapshot_id = snapshot_id
            snapshot.get_by('snapshot_id')

            guest.uuid = snapshot.guest_uuid
            guest.get_by('uuid')

            message = {
                '_object': 'snapshot',
                'action': 'delete',
                'uuid': snapshot.guest_uuid,
                'snapshot_id': snapshot.snapshot_id,
                'node_id': guest.node_id,
                'passback_parameters': {'id': snapshot.id}
            }

            Utils.emit_instruction(message=json.dumps(message))

            # 删除创建失败的 快照
            if snapshot.progress == 255:
                SnapshotDiskMapping.delete_by_filter(filter_str=':'.join(['snapshot_id', 'eq', snapshot.snapshot_id]))
                snapshot.delete()

            else:
                snapshot.progress = 254
                snapshot.update()

        ret = dict()
        ret['state'] = ji.Common.exchange_state(20000)
        return ret

    except ji.PreviewingError, e:
        return json.loads(e.message)
Ejemplo n.º 14
0
def r_delete(uuids):

    args_rules = [
        Rules.UUIDS.value
    ]

    # TODO: 加入是否删除使用的数据磁盘开关,如果为True,则顺便删除使用的磁盘。否则解除该磁盘被使用的状态。
    try:
        ji.Check.previewing(args_rules, {'uuids': uuids})

        guest = Guest()
        # 检测所指定的 UUDIs 实例都存在
        for uuid in uuids.split(','):
            guest.uuid = uuid
            guest.get_by('uuid')

        config = Config()
        config.id = 1
        config.get()

        # 执行删除操作
        for uuid in uuids.split(','):
            guest.uuid = uuid
            guest.get_by('uuid')

            message = {
                '_object': 'guest',
                'action': 'delete',
                'uuid': uuid,
                'storage_mode': config.storage_mode,
                'dfs_volume': config.dfs_volume,
                'node_id': guest.node_id
            }

            Utils.emit_instruction(message=json.dumps(message))

            # 删除创建失败的 Guest
            if guest.status == status.GuestState.dirty.value:
                disk = Disk()
                disk.uuid = guest.uuid
                disk.get_by('uuid')

                if disk.state == status.DiskState.pending.value:
                    disk.delete()
                    guest.delete()
                    SSHKeyGuestMapping.delete_by_filter(filter_str=':'.join(['guest_uuid', 'eq', guest.uuid]))

        ret = dict()
        ret['state'] = ji.Common.exchange_state(20000)
        return ret

    except ji.PreviewingError, e:
        return json.loads(e.message)
Ejemplo n.º 15
0
def r_delete(uuids):

    args_rules = [
        Rules.UUIDS.value
    ]

    try:
        ji.Check.previewing(args_rules, {'uuids': uuids})

        ret = dict()
        ret['state'] = ji.Common.exchange_state(20000)

        disk = Disk()

        # 检测所指定的 UUDIs 磁盘都存在
        for uuid in uuids.split(','):
            disk.uuid = uuid
            disk.get_by('uuid')

            # 判断磁盘是否与虚拟机处于离状态
            if disk.state not in [DiskState.idle.value, DiskState.dirty.value]:
                ret['state'] = ji.Common.exchange_state(41256)
                return ret

        config = Config()
        config.id = 1
        config.get()

        # 执行删除操作
        for uuid in uuids.split(','):
            disk.uuid = uuid
            disk.get_by('uuid')

            message = {
                '_object': 'disk',
                'action': 'delete',
                'uuid': disk.uuid,
                'storage_mode': config.storage_mode,
                'dfs_volume': config.dfs_volume,
                'node_id': disk.node_id,
                'image_path': disk.path
            }

            if config.storage_mode in [StorageMode.shared_mount.value, StorageMode.ceph.value,
                                       StorageMode.glusterfs.value]:
                message['node_id'] = Host.get_lightest_host()['node_id']

            Utils.emit_instruction(message=json.dumps(message, ensure_ascii=False))

        return ret

    except ji.PreviewingError, e:
        return json.loads(e.message)
    def __createCookieValue(eventId, queueId, fixedCookieValidityMinutes,
                            redirectType, secretKey):
        issueTime = Utils.toString(QueueitHelpers.getCurrentTime())
        hashValue = UserInQueueStateCookieRepository.__generateHash(
            eventId, queueId, fixedCookieValidityMinutes, redirectType,
            issueTime, secretKey)

        fixedCookieValidityMinutesPart = ""
        if (not Utils.isNilOrEmpty(fixedCookieValidityMinutes)):
            fixedCookieValidityMinutesPart = "&FixedValidityMins=" + fixedCookieValidityMinutes

        cookieValue = "EventId=" + eventId + "&QueueId=" + queueId + fixedCookieValidityMinutesPart + "&RedirectType=" + redirectType + "&IssueTime=" + issueTime + "&Hash=" + hashValue
        return cookieValue
Ejemplo n.º 17
0
    def __cancelRequestByLocalConfig(target_url, queueit_token, cancel_config,
                                     customer_id, secret_key,
                                     http_context_provider, debug_entries,
                                     is_debug):
        target_url = KnownUser.__generateTargetUrl(target_url,
                                                   http_context_provider)

        if is_debug:
            debug_entries["SdkVersion"] = UserInQueueService.SDK_VERSION
            debug_entries["Connector"] = http_context_provider.getProviderName(
            )
            debug_entries["Runtime"] = KnownUser.__getRunTime()
            debug_entries["TargetUrl"] = target_url
            debug_entries["QueueitToken"] = queueit_token
            debug_entries[
                "OriginalUrl"] = http_context_provider.getOriginalRequestUrl()
            if cancel_config is None:
                debug_entries["CancelConfig"] = "NULL"
            else:
                debug_entries["CancelConfig"] = cancel_config.toString()
            KnownUser.__logMoreRequestDetails(debug_entries,
                                              http_context_provider)

        if Utils.isNilOrEmpty(target_url):
            raise KnownUserError("targetUrl can not be none or empty.")

        if Utils.isNilOrEmpty(customer_id):
            raise KnownUserError("customerId can not be none or empty.")

        if Utils.isNilOrEmpty(secret_key):
            raise KnownUserError("secretKey can not be none or empty.")

        if cancel_config is None:
            raise KnownUserError("cancelConfig can not be none.")

        if Utils.isNilOrEmpty(cancel_config.eventId):
            raise KnownUserError(
                "cancelConfig.eventId can not be none or empty.")

        if Utils.isNilOrEmpty(cancel_config.queueDomain):
            raise KnownUserError(
                "cancelConfig.queueDomain can not be none or empty.")

        user_in_queue_service = KnownUser.__getUserInQueueService(
            http_context_provider)
        result = user_in_queue_service.validateCancelRequest(
            target_url, cancel_config, customer_id, secret_key)
        result.isAjaxResult = KnownUser.__isQueueAjaxCall(
            http_context_provider)

        return result
Ejemplo n.º 18
0
    def __resolveQueueRequestByLocalConfig(targetUrl, queueitToken,
                                           queueConfig, customerId, secretKey,
                                           httpContextProvider, debugEntries):
        isDebug = KnownUser.__getIsDebug(queueitToken, secretKey)
        if (isDebug):
            debugEntries["TargetUrl"] = targetUrl
            debugEntries["QueueitToken"] = queueitToken
            debugEntries[
                "OriginalUrl"] = httpContextProvider.getOriginalRequestUrl()
            if (queueConfig == None):
                debugEntries["QueueConfig"] = "NULL"
            else:
                debugEntries["QueueConfig"] = queueConfig.toString()
            KnownUser.__logMoreRequestDetails(debugEntries,
                                              httpContextProvider)

        if (Utils.isNilOrEmpty(customerId)):
            raise KnownUserError("customerId can not be none or empty.")

        if (Utils.isNilOrEmpty(secretKey)):
            raise KnownUserError("secretKey can not be none or empty.")

        if (queueConfig == None):
            raise KnownUserError("queueConfig can not be none.")

        if (Utils.isNilOrEmpty(queueConfig.eventId)):
            raise KnownUserError(
                "queueConfig.eventId can not be none or empty.")

        if (Utils.isNilOrEmpty(queueConfig.queueDomain)):
            raise KnownUserError(
                "queueConfig.queueDomain can not be none or empty.")

        minutes = QueueitHelpers.convertToInt(queueConfig.cookieValidityMinute)
        if (minutes <= 0):
            raise KnownUserError(
                "queueConfig.cookieValidityMinute should be integer greater than 0."
            )

        if (queueConfig.extendCookieValidity != True
                and queueConfig.extendCookieValidity != False):
            raise KnownUserError(
                "queueConfig.extendCookieValidity should be valid boolean.")

        userInQueueService = KnownUser.__getUserInQueueService(
            httpContextProvider)
        result = userInQueueService.validateQueueRequest(
            targetUrl, queueitToken, queueConfig, customerId, secretKey)
        result.isAjaxResult = KnownUser.__isQueueAjaxCall(httpContextProvider)
        return result
Ejemplo n.º 19
0
def r_before_request():
    try:
        g.ts = ji.Common.ts()
        if not is_not_need_to_auth(request.endpoint) and request.blueprint is not None and request.method != 'OPTIONS':
            g.config = Config()
            g.config.id = 1
            g.config.get()

            token = session.get('token', '')
            g.token = Utils.verify_token(token)

            user = User()
            user.id = g.token['uid']

            try:
                user.get()
            except ji.PreviewingError, e:
                # 如果该用户获取失败,则清除该用户对应的session。因为该用户可能已经被删除。
                for key in session.keys():
                    session.pop(key=key)
                return json.loads(e.message)

    except ji.JITError, e:
        ret = json.loads(e.message)

        if ret['state']['code'] == '404':
            return redirect(location=url_for('v_config.create'), Response=Response)

        if ret['state']['sub']['code'] in ['41208']:
            return redirect(location=url_for('v_misc.login'), Response=Response)

        return ret
 def run(self):
     snapshot = Repo(
         Utils.get_backend(self.backup),
         thread_count=self.backup.thread_count,
         compression_level=self.backup.compression_level).get_snapshot_obj(
             self.backup.password.encode(), self.snapshot_id)
     self.downloaded.emit(snapshot)
    def __getQueueITTokenValidationResult(self, targetUrl, eventId, config,
                                          queueParams, customerId, secretKey):
        calculatedHash = QueueitHelpers.hmacSha256Encode(
            queueParams.queueITTokenWithoutHash, secretKey)

        if (calculatedHash.upper() != queueParams.hashCode.upper()):
            return self.__getVaidationErrorResult(customerId, targetUrl,
                                                  config, queueParams, "hash")

        if (queueParams.eventId.upper() != eventId.upper()):
            return self.__getVaidationErrorResult(
                customerId, targetUrl, config, queueParams, "eventid")

        if (queueParams.timeStamp <
                QueueitHelpers.getCurrentTime()):
            return self.__getVaidationErrorResult(
                customerId, targetUrl, config, queueParams, "timestamp")

        cookieDomain = ""
        if (not Utils.isNilOrEmpty(config.cookieDomain)):
            cookieDomain = config.cookieDomain

        self.userInQueueStateRepository.store(
            config.eventId, queueParams.queueId,
            queueParams.cookieValidityMinutes, cookieDomain,
            queueParams.redirectType, secretKey)
        return RequestValidationResult(ActionTypes.QUEUE, config.eventId,
                                       queueParams.queueId, None,
                                       queueParams.redirectType)
    def validateCancelRequest(self, targetUrl, cancelConfig, customerId,
                              secretKey):
        state = self.userInQueueStateRepository.getState(
            cancelConfig.eventId, -1, secretKey, False)
        if (state.isValid):
            self.userInQueueStateRepository.cancelQueueCookie(
                cancelConfig.eventId, cancelConfig.cookieDomain)

            targetUrlParam = ""
            if (not Utils.isNilOrEmpty(targetUrl)):
                targetUrlParam = "&r=" + QueueitHelpers.urlEncode(
                    targetUrl)

            query = self.__getQueryString(customerId, cancelConfig.eventId,
                                          cancelConfig.version, None,
                                          None) + targetUrlParam

            domainAlias = cancelConfig.queueDomain
            if (not domainAlias.endswith("/")):
                domainAlias = domainAlias + "/"

            redirectUrl = "https://" + domainAlias + "cancel/" + customerId + "/" + cancelConfig.eventId + "/?" + query
            return RequestValidationResult(ActionTypes.CANCEL,
                                           cancelConfig.eventId, state.queueId,
                                           redirectUrl, state.redirectType)
        else:
            return RequestValidationResult(
                ActionTypes.CANCEL, cancelConfig.eventId, None, None, None)
Ejemplo n.º 23
0
def r_after_request(response):
    try:
        # https://developer.mozilla.org/en/HTTP_access_control
        # (中文版) https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS#Access-Control-Allow-Credentials
        # http://www.w3.org/TR/cors/
        # 由于浏览器同源策略,凡是发送请求url的协议、域名、端口三者之间任意一与当前页面地址不同即为跨域。

        if request.referrer is None:
            # 跑测试脚本时,用该规则。
            response.headers['Access-Control-Allow-Origin'] = '*'
        else:
            # 生产环境中,如果前后端分离。那么请指定具体的前端域名地址,不要用如下在开发环境中的便捷方式。
            # -- Access-Control-Allow-Credentials为true,携带cookie时,不允许Access-Control-Allow-Origin为通配符,是浏览器对用户的一种安全保护。
            # -- 至少能避免登录山寨网站,骗取用户相关信息。
            response.headers['Access-Control-Allow-Origin'] = '/'.join(request.referrer.split('/')[:3])

        response.headers['Access-Control-Allow-Credentials'] = 'true'
        response.headers['Access-Control-Allow-Methods'] = 'HEAD, GET, POST, DELETE, OPTIONS, PATCH, PUT'
        response.headers['Access-Control-Allow-Headers'] = 'X-Request-With, Content-Type'
        response.headers['Access-Control-Expose-Headers'] = 'Set-Cookie'

        # 少于session生命周期一半时,自动对其续期
        if not is_not_need_to_auth(request.endpoint) and hasattr(g, 'token') and \
                        g.token['exp'] < (ji.Common.ts() + (app.config['token_ttl'] / 2)):
            token = Utils.generate_token(g.token['uid'])
            # 清除原有session,由新session代替
            for key in session.keys():
                session.pop(key=key)
            session['token'] = token
        return response
    except ji.JITError, e:
        return json.loads(e.message)
Ejemplo n.º 24
0
 def test_get_backend__azure(self):
     backup = Backup()
     backup.location = "Microsoft Azure"
     backup.azure_conn_str = environ["BLOBBACKUP_AZURE_CONN_STR"]
     backup.azure_container = environ["BLOBBACKUP_AZURE_CONTAINER"]
     backup.cloud_prefix = "tmp"
     self._verify_backend(Utils.get_backend(backup), AzureBackend)
Ejemplo n.º 25
0
def r_sign_in():

    args_rules = [
        Rules.LOGIN_NAME.value,
        Rules.PASSWORD.value
    ]

    user = User()
    user.login_name = request.json.get('login_name')
    user.password = request.json.get('password')

    try:
        ji.Check.previewing(args_rules, user.__dict__)
        plain_password = user.password
        user.get_by('login_name')

        if not ji.Security.ji_pbkdf2_check(password=plain_password, password_hash=user.password):
            ret = dict()
            ret['state'] = ji.Common.exchange_state(40101)
            ret['state']['sub']['zh-cn'] = ''.join([ret['state']['sub']['zh-cn'], u': 鉴权失败'])
            raise ji.PreviewingError(json.dumps(ret, ensure_ascii=False))

        token = Utils.generate_token(user.id)
        session['token'] = token
        rep = make_response()
        rep.data = json.dumps({'state': ji.Common.exchange_state(20000)}, ensure_ascii=False)
        return rep

    except ji.PreviewingError, e:
        return json.loads(e.message)
Ejemplo n.º 26
0
def r_reset_password(token):

    args_rules = [
        Rules.TOKEN.value
    ]

    try:
        ji.Check.previewing(args_rules, {'token': token})

        token = Utils.verify_token(token, audience='r_reset_password')

        user = User()
        user.id = token['uid']
        user.get()

        args_rules = [
            Rules.PASSWORD.value
        ]

        user.password = request.json.get('password')

        ji.Check.previewing(args_rules, user.__dict__)
        user.password = ji.Security.ji_pbkdf2(user.password)
        user.update()
    except (ji.PreviewingError, ji.JITError), e:
        return json.loads(e.message)
Ejemplo n.º 27
0
 def validate_backend(backup):
     try:
         if not Utils.get_backend(backup).check_connection():
             return False, f"Cannot connect to {backup.location} backend"
     except:
         return False, f"Cannot connect to {backup.location} backend"
     return True, None
Ejemplo n.º 28
0
def r_create():

    args_rules = [
        Rules.GUEST_UUID.value
    ]

    if 'label' in request.json:
        args_rules.append(
            Rules.LABEL.value,
        )

    try:
        ret = dict()
        ret['state'] = ji.Common.exchange_state(20000)

        ji.Check.previewing(args_rules, request.json)

        snapshot = Snapshot()
        guest = Guest()
        guest.uuid = request.json.get('guest_uuid')
        guest.get_by('uuid')

        snapshot.label = request.json.get('label', '')
        snapshot.status = guest.status
        snapshot.guest_uuid = guest.uuid
        snapshot.snapshot_id = '_'.join(['tmp', ji.Common.generate_random_code(length=8)])
        snapshot.parent_id = '-'
        snapshot.progress = 0

        snapshot.create()
        snapshot.get_by('snapshot_id')

        message = {
            '_object': 'snapshot',
            'action': 'create',
            'uuid': guest.uuid,
            'node_id': guest.node_id,
            'passback_parameters': {'id': snapshot.id}
        }

        Utils.emit_instruction(message=json.dumps(message, ensure_ascii=False))

        ret['data'] = snapshot.__dict__
        return ret

    except ji.PreviewingError, e:
        return json.loads(e.message)
Ejemplo n.º 29
0
 def test_get_backend__b2(self):
     backup = Backup()
     backup.location = "Backblaze B2"
     backup.b2_key_id = environ["BLOBBACKUP_B2_KEY_ID"]
     backup.b2_key = environ["BLOBBACKUP_B2_KEY"]
     backup.b2_bucket = environ["BLOBBACKUP_B2_BUCKET"]
     backup.cloud_prefix = "tmp"
     self._verify_backend(Utils.get_backend(backup), B2Backend)
Ejemplo n.º 30
0
 def test_get_backend__gcp(self):
     backup = Backup()
     backup.location = "Google Cloud"
     backup.gcp_cred_file = environ["BLOBBACKUP_GCP_CRED_FILE"]
     backup.gcp_project = environ["BLOBBACKUP_GCP_PROJECT"]
     backup.gcp_bucket = environ["BLOBBACKUP_GCP_BUCKET"]
     backup.cloud_prefix = "tmp"
     self._verify_backend(Utils.get_backend(backup), GcpBackend)
Ejemplo n.º 31
0
 def post(self):
     try:
         action = self.request.POST[u'action'].strip()
         
         if not action:
             raise Exception(u'Hey! feed atleast one valentine pick.')
         
         if action == "update_matches":
             Utils.update_matches_all()
         
         if action == "notify_matches":
             Utils.notify_matches_all()
         
         
         
     except Exception, e:
         self.set_message(type=u'error',
             content=u'Unknown error occured. (' + unicode(e) + u')')