Beispiel #1
0
def create_maker_app(creator,
                     app_name,
                     app_url,
                     developer='',
                     app_tag='',
                     introduction='',
                     add_user='',
                     company_code=''):
    """
    @summary: 创建 maker app
    @param creator:创建者英文id
    @param app_name:app名称
    @param app_url:app链接, 请填写绝对地址
    @param developer: 填写开发者英文id列表,请用英文分号";"隔开
                                只有开发者才有操作该maker app的权限
    @param app_tag: 可选	String	轻应用分类
    @param introduction: 可选	String	轻应用描述
    @param add_user: 冗余字段,多版本兼容
    @param company_code: 冗余字段,多版本兼容
    @return: {'result': True, 'message':'', 'data': {'bk_light_app_code': 'xxxxx'}}
    {'result': False, 'message':u"APP Maker 创建出错", 'app_code':''}
    """
    client = get_client_by_user(creator)
    kwargs = {
        'creator': creator,
        'bk_app_code': settings.APP_CODE,
        'bk_light_app_name': app_name,
        'app_url': app_url,
        'developer': developer,
        'app_tag': app_tag,
        'introduction': introduction
    }
    result = client.bk_paas.create_app(kwargs)
    return result
Beispiel #2
0
def cc_get_ip_list_by_biz_and_user(username, biz_cc_id):
    """
    @summary:根据当前用户和业务ID获取IP
    @note: 由于获取了全业务IP,接口会比较慢,需要加缓存
    @note: 由于存在单主机多IP问题,需要取第一个IP作为实际值
    @param-username
    @param-biz_cc_id

    """
    cache_key = "cc_get_ip_list_by_biz_and_user_%s_%s" % (username, biz_cc_id)
    data = cache.get(cache_key)
    if not data:
        client = get_client_by_user(username)
        cc_result = client.cc.get_app_host_list({'app_id': biz_cc_id})
        if cc_result['result']:
            data = cc_result['data']
            # 多IP主机处理,取第一个IP
            for ip in data:
                if ',' in ip['InnerIP']:
                    ip['InnerIP'] = ip['InnerIP'].split(',')[0]
            cache.set(cache_key, data, 60)
        else:
            logger.warning(
                (u"get_app_host_list ERROR###biz_cc_id=%s"
                 u"###cc_result=%s") % (biz_cc_id, json.dumps(cc_result)))
    if not data:
        return []
    return data
Beispiel #3
0
def edit_maker_app(operator, app_maker_code, app_name='', app_url='', developer='', app_tag='', introduction='',
                   add_user='', company_code=''):
    """
    @summary: 修改 maker app
    @param operator:操作者英文id
    @param app_maker_code: maker app编码
    @param app_name:app名称,可选参数,为空则不修改名称
    @param app_url:app链接,可选参数,为空则不修改链接
    @param developer: 填写开发者英文id列表,请用英文分号";"隔开, 可选参数,为空则不修改开发者
                                    需传入修改后的所有开发者信息
    @param app_tag: 可选	String	轻应用分类
    @param introduction: 可选	String	轻应用描述
    @param add_user: 冗余字段,多版本兼容
    @param company_code: 冗余字段,多版本兼容
    @return: {'result': True, 'message':u"APP Maker 修改成功"}
    {'result': False, 'message':u"APP Maker 修改出错"}
    """
    client = get_client_by_user(operator)
    client.set_bk_api_ver('v2')
    kwargs = {
        'operator': operator,
        'bk_light_app_code': app_maker_code,
        'bk_light_app_name': app_name,
        'app_url': app_url,
        'developer': developer,
        'app_tag': app_tag,
        'introduction': introduction
    }
    result = client.bk_paas.edit_app(kwargs)
    return result
Beispiel #4
0
    def execute(self, data, parent_data):
        executor = parent_data.get_one_of_inputs('executor')
        biz_cc_id = parent_data.get_one_of_inputs('biz_cc_id')
        client = get_client_by_user(executor)
        client.set_bk_api_ver('v2')
        if parent_data.get_one_of_inputs('language'):
            setattr(client, 'language',
                    parent_data.get_one_of_inputs('language'))

        # 查询主机id
        ip_list = get_ip_by_regex(data.get_one_of_inputs('cc_host_ip'))
        host_result = cc_get_host_id_by_innerip(executor, biz_cc_id, ip_list)
        if not host_result['result']:
            data.set_outputs('ex_data', host_result['message'])
            return False

        cc_module_select = data.get_one_of_inputs('cc_module_select')
        cc_is_increment = data.get_one_of_inputs('cc_is_increment')

        cc_kwargs = {
            "bk_biz_id": biz_cc_id,
            "bk_host_id": [int(host_id) for host_id in host_result['data']],
            "bk_module_id": cc_module_select,
            "is_increment": cc_is_increment
        }
        cc_result = client.cc.transfer_host_module(cc_kwargs)
        if cc_result['result']:
            return True
        else:
            message = cc_handle_api_error('cc.transfer_host_module', cc_kwargs,
                                          cc_result['message'])
            data.set_outputs('ex_data', message)
            return False
Beispiel #5
0
    def execute(self, data, parent_data):
        executor = parent_data.get_one_of_inputs('executor')
        biz_cc_id = parent_data.get_one_of_inputs('biz_cc_id')
        client = get_client_by_user(executor)
        client.set_bk_api_ver('v2')
        if parent_data.get_one_of_inputs('language'):
            setattr(client, 'language',
                    parent_data.get_one_of_inputs('language'))

        cc_set_select = data.get_one_of_inputs('cc_set_select')
        for set_id in cc_set_select:
            cc_kwargs = {
                "bk_biz_id": biz_cc_id,
                "bk_set_id": set_id,
                "data": {
                    "bk_service_status":
                    data.get_one_of_inputs('cc_set_status')
                }
            }
            cc_result = client.cc.update_set(cc_kwargs)
            if not cc_result['result']:
                message = cc_handle_api_error('cc.update_set', cc_kwargs,
                                              cc_result['message'])
                data.set_outputs('ex_data', message)
                return False
        return True
Beispiel #6
0
    def execute(self, data, parent_data):
        executor = parent_data.get_one_of_inputs('executor')
        biz_cc_id = parent_data.get_one_of_inputs('biz_cc_id')
        client = get_client_by_user(executor)
        client.set_bk_api_ver('v2')
        if parent_data.get_one_of_inputs('language'):
            setattr(client, 'language',
                    parent_data.get_one_of_inputs('language'))
            translation.activate(parent_data.get_one_of_inputs('language'))

        cc_set_select = cc_format_tree_mode_id(
            data.get_one_of_inputs('cc_set_select'))

        cc_set_property = data.get_one_of_inputs('cc_set_property')
        if cc_set_property == "bk_service_status":
            bk_service_status = cc_format_prop_data(
                executor, 'set', 'bk_service_status',
                parent_data.get_one_of_inputs('language'))
            if not bk_service_status['result']:
                data.set_outputs('ex_data', bk_service_status['message'])
                return False

            cc_set_prop_value = bk_service_status['data'].get(
                data.get_one_of_inputs('cc_set_prop_value'))
            if not cc_set_prop_value:
                data.set_outputs('ex_data', _(u"服务状态校验失败,请重试并修改为正确的服务状态"))
                return False

        elif cc_set_property == "bk_set_env":
            bk_set_env = cc_format_prop_data(
                executor, 'set', 'bk_set_env',
                parent_data.get_one_of_inputs('language'))
            if not bk_set_env['result']:
                data.set_outputs('ex_data', bk_set_env['message'])
                return False

            cc_set_prop_value = bk_set_env['data'].get(
                data.get_one_of_inputs('cc_set_prop_value'))
            if not cc_set_prop_value:
                data.set_outputs('ex_data', _(u"环境类型校验失败,请重试并修改为正确的环境类型"))
                return False

        else:
            cc_set_prop_value = data.get_one_of_inputs('cc_set_prop_value')

        for set_id in cc_set_select:
            cc_kwargs = {
                "bk_biz_id": biz_cc_id,
                "bk_set_id": set_id,
                "data": {
                    cc_set_property: cc_set_prop_value
                }
            }
            cc_result = client.cc.update_set(cc_kwargs)
            if not cc_result['result']:
                message = cc_handle_api_error('cc.update_set', cc_kwargs,
                                              cc_result['message'])
                data.set_outputs('ex_data', message)
                return False
        return True
Beispiel #7
0
    def execute(self, data, parent_data):
        executor = parent_data.get_one_of_inputs('executor')
        biz_cc_id = parent_data.get_one_of_inputs('biz_cc_id')
        client = get_client_by_user(executor)
        client.set_bk_api_ver('v2')
        if parent_data.get_one_of_inputs('language'):
            setattr(client, 'language',
                    parent_data.get_one_of_inputs('language'))
            translation.activate(parent_data.get_one_of_inputs('language'))

        cc_set_select = cc_format_tree_mode_id(
            data.get_one_of_inputs('cc_set_select'))

        cc_kwargs = {
            "bk_biz_id": biz_cc_id,
            "delete": {
                "inst_ids": cc_set_select
            }
        }
        cc_result = client.cc.batch_delete_set(cc_kwargs)
        if not cc_result['result']:
            message = cc_handle_api_error('cc.batch_delete_set', cc_kwargs,
                                          cc_result['message'])
            data.set_outputs('ex_data', message)
            return False
        return True
Beispiel #8
0
def get_job_instance_log(request, biz_cc_id):
    client = get_client_by_user(request.user.username)
    client.set_bk_api_ver('v2')
    job_instance_id = request.GET.get('job_instance_id')
    log_kwargs = {"bk_biz_id": biz_cc_id, "job_instance_id": job_instance_id}
    log_result = client.job.get_job_instance_log(log_kwargs)
    return JsonResponse(log_result)
Beispiel #9
0
    def execute(self, data, parent_data):
        executor = parent_data.get_one_of_inputs('executor')
        biz_cc_id = parent_data.get_one_of_inputs('biz_cc_id')
        client = get_client_by_user(executor)
        client.set_bk_api_ver('v2')
        if parent_data.get_one_of_inputs('language'):
            setattr(client, 'language',
                    parent_data.get_one_of_inputs('language'))
            translation.activate(parent_data.get_one_of_inputs('language'))

        cc_set_parent_select = cc_format_tree_mode_id(
            data.get_one_of_inputs('cc_set_parent_select'))
        cc_set_info = data.get_one_of_inputs('cc_set_info')
        cc_kwargs = {'bk_biz_id': biz_cc_id, 'data': {}}

        for parent_id in cc_set_parent_select:
            cc_kwargs['data']['bk_parent_id'] = parent_id
            for set_params in cc_set_info:
                for key, value in set_params.items():
                    if value:
                        if key == "bk_set_env":
                            bk_set_env = cc_format_prop_data(
                                executor, 'set', 'bk_set_env',
                                parent_data.get_one_of_inputs('language'))
                            if not bk_set_env['result']:
                                data.set_outputs('ex_data',
                                                 bk_set_env['message'])
                                return False

                            value = bk_set_env['data'].get(value)
                            if not value:
                                data.set_outputs('ex_data',
                                                 _(u"环境类型校验失败,请重试并修改为正确的环境类型"))
                                return False

                        elif key == "bk_service_status":
                            bk_service_status = cc_format_prop_data(
                                executor, 'set', 'bk_service_status',
                                parent_data.get_one_of_inputs('language'))
                            if not bk_service_status['result']:
                                data.set_outputs('ex_data',
                                                 bk_service_status['message'])
                                return False

                            value = bk_service_status['data'].get(value)
                            if not value:
                                data.set_outputs('ex_data',
                                                 _(u"服务状态校验失败,请重试并修改为正确的服务状态"))
                                return False

                        cc_kwargs['data'][key] = value

                cc_result = client.cc.create_set(cc_kwargs)
                if not cc_result['result']:
                    message = cc_handle_api_error('cc.create_set', cc_kwargs,
                                                  cc_result['message'])
                    data.set_outputs('ex_data', message)
                    return False
        return True
Beispiel #10
0
 def execute(self, data, parent_data):
     executor = parent_data.get_one_of_inputs('executor')
     biz_cc_id = parent_data.get_one_of_inputs('biz_cc_id')
     client = get_client_by_user(executor)
     client.set_bk_api_ver('v2')
     if parent_data.get_one_of_inputs('language'):
         setattr(client, 'language',
                 parent_data.get_one_of_inputs('language'))
Beispiel #11
0
    def execute(self, data, parent_data):
        executor = parent_data.get_one_of_inputs('executor')
        biz_cc_id = parent_data.get_one_of_inputs('biz_cc_id')
        client = get_client_by_user(executor)
        client.set_bk_api_ver('v2')
        if parent_data.get_one_of_inputs('language'):
            setattr(client, 'language',
                    parent_data.get_one_of_inputs('language'))
            translation.activate(parent_data.get_one_of_inputs('language'))

        kwargs = {"bk_biz_id": biz_cc_id}
        tree_data = client.cc.search_biz_inst_topo(kwargs)
        if not tree_data['result']:
            message = cc_handle_api_error('cc.search_biz_inst_topo', kwargs,
                                          tree_data['message'])
            data.set_outputs('ex_data', message)
            return False

        cc_module_select = cc_format_tree_mode_id(
            data.get_one_of_inputs('cc_module_select'))
        cc_module_property = data.get_one_of_inputs('cc_module_property')
        if cc_module_property == "bk_module_type":
            bk_module_type = cc_format_prop_data(
                executor, 'module', 'bk_module_type',
                parent_data.get_one_of_inputs('language'))
            if not bk_module_type['result']:
                data.set_outputs('ex_data', bk_module_type['message'])
                return False

            cc_module_prop_value = bk_module_type['data'].get(
                data.get_one_of_inputs('cc_module_prop_value'))
            if not cc_module_prop_value:
                data.set_outputs('ex_data', _(u"模块类型校验失败,请重试并填写正确的模块类型"))
                return False
        else:
            cc_module_prop_value = data.get_one_of_inputs(
                'cc_module_prop_value')

        for module_id in cc_module_select:
            cc_kwargs = {
                "bk_biz_id": biz_cc_id,
                "bk_set_id": get_module_set_id(tree_data['data'], module_id),
                "bk_module_id": module_id,
                "data": {
                    cc_module_property: cc_module_prop_value
                }
            }
            cc_result = client.cc.update_module(cc_kwargs)
            if not cc_result['result']:
                message = cc_handle_api_error('cc.update_module', cc_kwargs,
                                              cc_result['message'])
                data.set_outputs('ex_data', message)
                return False
        return True
Beispiel #12
0
def cc_get_host_id_by_innerip(executor, bk_biz_id, ip_list):
    """
    获取主机ID
    :param executor:
    :param bk_biz_id:
    :param ip_list:
    :return: [1, 2, 3] id列表
    """
    cc_kwargs = {
        'bk_biz_id':
        bk_biz_id,
        'ip': {
            'data': ip_list,
            'exact': 1,
            'flag': 'bk_host_innerip'
        },
        'condition': [{
            'bk_obj_id': 'host',
            'fields': ['bk_host_id', 'bk_host_innerip']
        }],
    }

    client = get_client_by_user(executor)
    client.set_bk_api_ver('v2')
    cc_result = client.cc.search_host(cc_kwargs)

    if not cc_result['result']:
        message = cc_handle_api_error('cc.search_host', cc_kwargs,
                                      cc_result['message'])
        return {'result': False, 'message': message}

    ip_to_id = {
        item['host']['bk_host_innerip']: str(item['host']['bk_host_id'])
        for item in cc_result['data']['info']
    }
    host_id_list = []
    invalid_ip_list = []
    for ip in ip_list:
        if ip in ip_to_id:
            host_id_list.append(ip_to_id[ip])
        else:
            invalid_ip_list.append(ip)

    if invalid_ip_list:
        result = {
            'result':
            False,
            'message':
            _(u"查询配置平台(CMDB)接口cc.search_host表明,存在不属于当前业务的IP: {ip}").format(
                ip=','.join(invalid_ip_list))
        }
        return result
    return {'result': True, 'data': host_id_list}
Beispiel #13
0
    def execute(self, data, parent_data):
        executor = parent_data.get_one_of_inputs('executor')
        biz_cc_id = parent_data.get_one_of_inputs('biz_cc_id')
        client = get_client_by_user(executor)
        client.set_bk_api_ver('v2')
        if parent_data.get_one_of_inputs('language'):
            setattr(client, 'language',
                    parent_data.get_one_of_inputs('language'))
            translation.activate(parent_data.get_one_of_inputs('language'))

        cc_hosts = data.get_one_of_inputs('cc_host_replace_detail')

        # 克隆属性
        clone_kwargs = {"bk_biz_id": biz_cc_id}
        fault_machine = []
        for item in cc_hosts:
            clone_kwargs.update(
                {"bk_org_ip": "".join(get_ip_by_regex(item['cc_fault_ip']))})
            clone_kwargs.update(
                {"bk_dst_ip": "".join(get_ip_by_regex(item['cc_new_ip']))})
            # 克隆主机属性会自动把主机移动到对应模块
            clone_result = client.cc.clone_host_property(clone_kwargs)
            if not clone_result['result']:
                message = cc_handle_api_error('cc.clone_host_property',
                                              clone_kwargs,
                                              clone_result['message'])
                data.set_outputs('ex_data', message)
                return False

            fault_machine.append("".join(get_ip_by_regex(item['cc_fault_ip'])))

        # 将故障机上交至故障机模块
        host_result = cc_get_host_id_by_innerip(executor, biz_cc_id,
                                                fault_machine)
        if not host_result['result']:
            data.set_outputs('ex_data', host_result['message'])
            return False

        to_fault_module_kwargs = {
            "bk_biz_id": biz_cc_id,
            "bk_host_id": [int(host_id) for host_id in host_result['data']],
        }
        cc_result = client.cc.transfer_host_to_faultmodule(
            to_fault_module_kwargs)
        if cc_result['result']:
            return True
        else:
            message = cc_handle_api_error('cc.transfer_host_to_faultmodule',
                                          to_fault_module_kwargs,
                                          cc_result['message'])
            data.set_outputs('ex_data', message)
            return False
Beispiel #14
0
    def execute(self, data, parent_data):
        executor = parent_data.get_one_of_inputs('executor')
        biz_cc_id = parent_data.get_one_of_inputs('biz_cc_id')
        client = get_client_by_user(executor)
        if parent_data.get_one_of_inputs('language'):
            setattr(self, 'language',
                    parent_data.get_one_of_inputs('language'))

        original_source_files = data.get_one_of_inputs('job_source_files', [])
        file_source = []
        for item in original_source_files:
            ip_info = cc_get_ips_info_by_str(executor, biz_cc_id, item['ip'])
            file_source.append({
                'file':
                item['files'].strip(),
                'ip_list': [{
                    'ip': _ip['InnerIP'],
                    'source': _ip['Source']
                } for _ip in ip_info['ip_result']],
                'account':
                item['account'].strip(),
            })

        original_ip_list = data.get_one_of_inputs('job_ip_list')
        ip_info = cc_get_ips_info_by_str(executor, biz_cc_id, original_ip_list)
        ip_list = [{
            'ip': _ip['InnerIP'],
            'source': _ip['Source']
        } for _ip in ip_info['ip_result']]

        job_kwargs = {
            'app_id': biz_cc_id,
            'file_source': file_source,
            'ip_list': ip_list,
            'account': data.get_one_of_inputs('job_account'),
            'file_target_path': data.get_one_of_inputs('job_target_path'),
        }

        job_result = client.job.fast_push_file(job_kwargs)
        if job_result['result']:
            data.set_outputs('job_inst_id',
                             job_result['data']['taskInstanceId'])
            data.set_outputs('job_inst_name',
                             job_result['data']['taskInstanceName'])
            data.set_outputs('client', client)
            return True
        else:
            data.set_outputs('ex_data', job_result['message'])
            return False
Beispiel #15
0
def del_maker_app(operator, app_maker_code):
    """
    @summary: 删除 maker app
    @param operator:操作者英文id
    @param app_maker_code: maker app编码
    @return: {'result': True, 'message':u"APP Maker 删除成功"}
    {'result': False, 'message':u"APP Maker 删除失败"}
    """
    client = get_client_by_user(operator)
    kwargs = {
        'operator': operator,
        'bk_light_app_code': app_maker_code,
    }
    result = client.bk_paas.del_app(kwargs)
    return result
Beispiel #16
0
    def execute(self, data, parent_data):
        executor = parent_data.get_one_of_inputs('executor')
        biz_cc_id = parent_data.get_one_of_inputs('biz_cc_id')
        client = get_client_by_user(executor)
        client.set_bk_api_ver("v2")
        if parent_data.get_one_of_inputs('language'):
            setattr(client, 'language', parent_data.get_one_of_inputs('language'))
            translation.activate(parent_data.get_one_of_inputs('language'))

        original_ip_list = data.get_one_of_inputs('job_ip_list')
        ip_info = cc_get_ips_info_by_str(executor, biz_cc_id, original_ip_list)
        ip_list = [{'ip': _ip['InnerIP'], 'bk_cloud_id': _ip['Source']}
                   for _ip in ip_info['ip_result']]

        job_kwargs = {
            'bk_biz_id': biz_cc_id,
            'script_timeout': data.get_one_of_inputs('job_script_timeout'),
            'account': data.get_one_of_inputs('job_account'),
            'ip_list': ip_list,
        }

        script_param = data.get_one_of_inputs('job_script_param')
        if script_param:
            job_kwargs.update({
                'script_param': base64.b64encode(script_param.encode('utf-8'))
            })

        script_source = data.get_one_of_inputs('job_script_source')
        if script_source in ["general", "public"]:
            job_kwargs.update({
                "script_id": data.get_one_of_inputs('job_script_list_%s' % script_source)
            })
        else:
            job_kwargs.update({
                'script_type': data.get_one_of_inputs('job_script_type'),
                'script_content': base64.b64encode(data.get_one_of_inputs('job_content').encode('utf-8')),
            })

        job_result = client.job.fast_execute_script(job_kwargs)
        if job_result['result']:
            data.set_outputs('job_inst_id', job_result['data']['job_instance_id'])
            data.set_outputs('job_inst_name', job_result['data']['job_instance_name'])
            data.set_outputs('client', client)
            self.set_outputs_job_url(data, parent_data)
            return True
        else:
            data.set_outputs('ex_data', '%s, invalid ip: %s' % (job_result['message'], ','.join(ip_info['invalid_ip'])))
            return False
Beispiel #17
0
    def execute(self, data, parent_data):
        executor = parent_data.get_one_of_inputs('executor')
        biz_cc_id = parent_data.get_one_of_inputs('biz_cc_id')
        client = get_client_by_user(executor)
        if parent_data.get_one_of_inputs('language'):
            setattr(client, 'language',
                    parent_data.get_one_of_inputs('language'))

        original_global_var = data.get_one_of_inputs('job_global_var')
        global_var = []
        for _value in original_global_var:
            # 1-字符串,2-IP
            if _value['type'] == 2:
                var_ip = cc_get_ips_info_by_str(executor, biz_cc_id,
                                                _value['value'])
                ip_list = [
                    '%s:%s' % (_ip['Source'], _ip['InnerIP'])
                    for _ip in var_ip['ip_result']
                ]
                global_var.append({
                    'id': _value['id'],
                    'name': _value['name'],
                    'ipList': ','.join(ip_list),
                })
            else:
                global_var.append({
                    'id': _value['id'],
                    'name': _value['name'],
                    'value': _value['value'].strip(),
                })

        job_kwargs = {
            'app_id': biz_cc_id,
            'task_id': data.get_one_of_inputs('job_task_id'),
            'global_var': global_var,
        }

        job_result = client.job.execute_task_ext(job_kwargs)
        if job_result['result']:
            data.set_outputs('job_inst_id',
                             job_result['data']['taskInstanceId'])
            data.set_outputs('job_inst_name',
                             job_result['data']['taskInstanceName'])
            data.set_outputs('client', client)
            return True
        else:
            data.set_outputs('ex_data', job_result['message'])
            return False
Beispiel #18
0
def modify_app_logo(operator, app_maker_code, logo):
    """
    @summary: 修改轻应用的 logo
    @param operator:操作者英文id
    @param app_maker_code: maker app编码
    @param logo: maker app编码
    @return: {'result': True, 'message':u"APP LOGO 修改成功"}
    {'result': False, 'message':u"APP LOGO 修改失败"}
    """
    client = get_client_by_user(operator)
    kwargs = {
        'operator': operator,
        'bk_light_app_code': app_maker_code,
        'logo': logo,
    }
    result = client.bk_paas.modify_app_logo(kwargs)
    return result
Beispiel #19
0
def cc_get_ips_by_set_and_module(username, biz_cc_id, set_id_list,
                                 set_name_list, module_name_list):
    """
    @summary: 根据集群名和模块名获取IP
    :param username:
    :param biz_cc_id:
    :param set_name_list:
    :param module_name_list:
    :return:
    """
    client = get_client_by_user(username)

    if not set_id_list and not set_name_list:
        return []
    if not module_name_list:
        return []

    if set_id_list:
        if '0' in set_id_list:
            set_id_list = []
    else:
        if _(u"所有集群(all)") in set_name_list or 'all' in set_name_list:
            set_id_list = []
        else:
            set_id_list = cc_get_set_ids_by_names(username, biz_cc_id,
                                                  set_name_list)
            if not set_id_list:
                return []

    if _(u"所有模块(all)") in module_name_list or 'all' in module_name_list:
        module_name_list = []

    cc_kwargs = {
        'app_id': biz_cc_id,
        'set_id': ','.join(set_id_list),
        'module_name': ','.join(module_name_list),
    }
    cc_result = client.cc.get_hosts_by_property(cc_kwargs)
    result = []
    if cc_result['result']:
        result = cc_result['data']
    else:
        logger.warning(u"client.cc.get_hosts_by_property ERROR###biz_cc_id=%s"
                       u"###cc_result=%s" % (biz_cc_id, json.dumps(cc_result)))
    return result
Beispiel #20
0
    def execute(self, data, parent_data):
        executor = parent_data.get_one_of_inputs('executor')
        biz_cc_id = parent_data.get_one_of_inputs('biz_cc_id')
        client = get_client_by_user(executor)
        client.set_bk_api_ver("v2")
        if parent_data.get_one_of_inputs('language'):
            setattr(client, 'language', parent_data.get_one_of_inputs('language'))
            translation.activate(parent_data.get_one_of_inputs('language'))

        original_global_var = data.get_one_of_inputs('job_global_var')
        global_vars = []
        for _value in original_global_var:
            # 1-字符串,2-IP
            if _value['type'] == 2:
                var_ip = cc_get_ips_info_by_str(
                    executor,
                    biz_cc_id,
                    _value['value'])
                ip_list = [{'ip': _ip['InnerIP'], 'bk_cloud_id': _ip['Source']} for _ip in var_ip['ip_result']]
                global_vars.append({
                    'id': _value['id'],
                    'ip_list': ip_list,
                })
            else:
                global_vars.append({
                    'id': _value['id'],
                    'value': _value['value'].strip(),
                })

        job_kwargs = {
            'bk_biz_id': biz_cc_id,
            'bk_job_id': data.get_one_of_inputs('job_task_id'),
            'global_vars': global_vars,
        }

        job_result = client.job.execute_job(job_kwargs)
        if job_result['result']:
            data.set_outputs('job_inst_id', job_result['data']['job_instance_id'])
            data.set_outputs('job_inst_name', job_result['data']['job_instance_name'])
            data.set_outputs('client', client)
            self.set_outputs_job_url(data, parent_data)
            return True
        else:
            data.set_outputs('ex_data', job_result['message'])
            return False
Beispiel #21
0
    def execute(self, data, parent_data):
        executor = parent_data.get_one_of_inputs('executor')
        biz_cc_id = parent_data.get_one_of_inputs('biz_cc_id')
        client = get_client_by_user(executor)
        if parent_data.get_one_of_inputs('language'):
            setattr(client, 'language',
                    parent_data.get_one_of_inputs('language'))

        original_ip_list = data.get_one_of_inputs('job_ip_list')
        ip_info = cc_get_ips_info_by_str(executor, biz_cc_id, original_ip_list)
        ip_list = [{
            'ip': _ip['InnerIP'],
            'source': _ip['Source']
        } for _ip in ip_info['ip_result']]

        job_kwargs = {
            'app_id':
            biz_cc_id,
            'type':
            data.get_one_of_inputs('job_script_type'),
            'content':
            base64.b64encode(
                data.get_one_of_inputs('job_content').encode('utf-8')),
            'script_param':
            data.get_one_of_inputs('job_script_param'),
            'script_timeout':
            data.get_one_of_inputs('job_script_timeout'),
            'account':
            data.get_one_of_inputs('job_account'),
            'ip_list':
            ip_list,
        }
        job_result = client.job.fast_execute_script(job_kwargs)
        if job_result['result']:
            data.set_outputs('job_inst_id',
                             job_result['data']['taskInstanceId'])
            data.set_outputs('job_inst_name',
                             job_result['data']['taskInstanceName'])
            data.set_outputs('client', client)
            return True
        else:
            data.set_outputs('ex_data', job_result['message'])
            return False
Beispiel #22
0
def cc_get_inner_ip_by_module_id(username, biz_cc_id, module_id_list):
    """
    @summary: 根据模块ID查询主机内网ip
    :param username:
    :param biz_cc_id:
    :param module_id_list:
    :return:
    """
    client = get_client_by_user(username)
    client.set_bk_api_ver('v2')
    cc_kwargs = {
        "bk_biz_id":
        biz_cc_id,
        "condition": [{
            "bk_obj_id": "host",
            "fields": ["bk_host_innerip"],
        }, {
            "bk_obj_id":
            "module",
            "fields": [],
            "condition": [{
                "field": "bk_module_id",
                "operator": "$in",
                "value": module_id_list
            }]
        }, {
            "bk_obj_id": "set",
            "fields": [],
            "condition": []
        }, {
            "bk_obj_id": "biz",
            "fields": [],
            "condition": []
        }]
    }
    cc_result = client.cc.search_host(cc_kwargs)
    result = []
    if cc_result['result']:
        result = cc_result['data']['info']
    else:
        logger.warning(u"client.cc.search_host ERROR###biz_cc_id=%s"
                       u"###cc_result=%s" % (biz_cc_id, json.dumps(cc_result)))
    return result
Beispiel #23
0
def cc_get_set_ids_by_names(username, biz_cc_id, set_names):
    """
    @summary: 根据集群名称查询业务在配置平台的集群ID
    :param username:
    :param biz_cc_id:
    :param set_names:
    :return:
    """
    client = get_client_by_user(username)
    cc_result = client.cc.get_sets_by_property({'app_id': biz_cc_id})
    cc_sets = []
    if cc_result['result']:
        cc_sets = cc_result['data']
    else:
        logger.warning(u"client.cc.get_sets_by_property ERROR###biz_cc_id=%s"
                       u"###cc_result=%s" % (biz_cc_id, json.dumps(cc_result)))
    cc_set_names = [_set['SetName'] for _set in cc_sets]
    # 列表格式
    if isinstance(set_names, list):
        set_ids = []
        for set_name in set_names:
            if set_name in cc_set_names:
                set_ids.append(cc_sets[cc_set_names.index(set_name)]['SetID'])
        if len(set_ids) != len(set_names):
            logger.warning(
                u"cc_get_set_ids_by_names ERROR###error="
                u"return set less than request set###biz_cc_id=%s"
                u"###set_names=%s###cc_result=%s" %
                (biz_cc_id, json.dumps(set_names), json.dumps(cc_result)))
    # 单个集群名称字符串
    else:
        set_ids = ""
        if set_names in cc_set_names:
            set_ids = cc_sets[cc_set_names.index(set_names)]['SetID']
        else:
            logger.warning(
                u"cc_get_set_ids_by_names ERROR###error="
                u"return set less than request set###biz_cc_id=%s"
                u"###set_names=%s###cc_result=%s" %
                (biz_cc_id, json.dumps(set_names), json.dumps(cc_result)))
    return set_ids
Beispiel #24
0
    def execute(self, data, parent_data):
        executor = parent_data.get_one_of_inputs('executor')
        biz_cc_id = parent_data.get_one_of_inputs('biz_cc_id')
        client = get_client_by_user(executor)
        server_ip = data.get_one_of_inputs('server_ip')
        disk = data.get_one_of_inputs('disk')

        LOGGER.info('client: %s' % client.__dict__)
        api_kwargs = {
            'bk_biz_id': biz_cc_id,
            'ip': server_ip,
            'disk': disk
        }
        api_result = client.bkcs.get_host_capacity(api_kwargs)
        LOGGER.info('api_result: {result}, api_kwargs: {kwargs}'.format(result=api_result, kwargs=api_kwargs))

        if api_result['result']:
            data.set_outputs('disk', disk)
            data.set_outputs('capacity', api_result['data']['capacity'])
            data.set_outputs('datatime', api_result['data']['datatime'])
            return True
        else:
            data.set_outputs('ex_data', api_result['message'])
Beispiel #25
0
def cc_format_prop_data(executor, obj_id, prop_id, language):
    ret = {"result": True, "data": {}}
    client = get_client_by_user(executor)
    client.set_bk_api_ver('v2')
    if language:
        setattr(client, 'language', language)
    cc_kwargs = {"bk_obj_id": obj_id}

    cc_result = client.cc.search_object_attribute(cc_kwargs)
    if not cc_result['result']:
        message = cc_handle_api_error('cc.search_object_attribute', cc_kwargs,
                                      cc_result['message'])
        ret['result'] = False
        ret['message'] = message
        return ret

    for prop in cc_result['data']:
        if prop['bk_property_id'] == prop_id:
            for item in prop['option']:
                ret['data'][item['name'].strip()] = item['id']
            else:
                break
    return ret
Beispiel #26
0
def cc_get_role_users(username, biz_cc_id, user_roles, more_users=''):
    """
    @summary: 根据业务和角色获取人员信息
    :param username:
    :param biz_cc_id:
    :param user_roles:
    :param more_users:
    :return:
    """
    client = get_client_by_user(username)
    cc_result = client.cc.get_app_by_id({'app_id': biz_cc_id})
    if not cc_result:
        message = _(u"查询配置平台(CMDB)的业务[app_id=%s]接口cc.get_app_by_id返回失败: %s"
                    ) % (biz_cc_id, cc_result['message'])
        logger.error(message)
        return {'result': False, 'message': message, 'data': []}

    cc_data = cc_result['data'][0]
    for role in user_roles:
        if role in cc_data:
            more_users += ',%s' % cc_data[role]
    users = filter(lambda x: x, re.split(r'\s*[,;\s]\s*', more_users))
    users = list(set(users))
    return {'result': True, 'data': users, 'messgae': ''}
Beispiel #27
0
    def execute(self, data, parent_data):
        executor = parent_data.get_one_of_inputs('executor')
        biz_cc_id = parent_data.get_one_of_inputs('biz_cc_id')
        client = get_client_by_user(executor)
        client.set_bk_api_ver('v2')
        if parent_data.get_one_of_inputs('language'):
            setattr(client, 'language',
                    parent_data.get_one_of_inputs('language'))
        # 查询主机id
        ip_list = get_ip_by_regex(data.get_one_of_inputs('cc_host_ip'))
        host_result = cc_get_host_id_by_innerip(executor, biz_cc_id, ip_list)
        if not host_result['result']:
            data.set_outputs('ex_data', host_result['message'])
            return False

        # 更新主机属性
        cc_host_property = data.get_one_of_inputs('cc_host_property')
        if cc_host_property == "bk_isp_name":
            bk_isp_name = cc_format_prop_data(
                executor, 'host', 'bk_isp_name',
                parent_data.get_one_of_inputs('language'))
            if not bk_isp_name['result']:
                data.set_outputs('ex_data', bk_isp_name['message'])
                return False

            cc_host_prop_value = bk_isp_name['data'].get(
                data.get_one_of_inputs('cc_host_prop_value'))
            if not cc_host_prop_value:
                data.set_outputs('ex_data', _(u'所属运营商校验失败,请重试并修改为正确的所属运营商'))
                return False

        elif cc_host_property == "bk_state_name":
            bk_state_name = cc_format_prop_data(
                executor, 'host', 'bk_state_name',
                parent_data.get_one_of_inputs('language'))
            if not bk_state_name['result']:
                data.set_outputs('ex_data', bk_state_name['message'])
                return False

            cc_host_prop_value = bk_state_name['data'].get(
                data.get_one_of_inputs('cc_host_prop_value'))
            if not cc_host_prop_value:
                data.set_outputs('ex_data', _(u'所在国家校验失败,请重试并修改为正确的所在国家'))
                return False
        elif cc_host_property == "bk_province_name":
            bk_province_name = cc_format_prop_data(
                executor, 'host', 'bk_province_name',
                parent_data.get_one_of_inputs('language'))
            if not bk_province_name['result']:
                data.set_outputs('ex_data', bk_province_name['message'])
                return False
            cc_host_prop_value = bk_province_name['data'].get(
                data.get_one_of_inputs('cc_host_prop_value'))
            if not cc_host_prop_value:
                data.set_outputs('ex_data', _(u'所在省份校验失败,请重试并修改为正确的所在省份'))
                return False
        else:
            cc_host_prop_value = data.get_one_of_inputs('cc_host_prop_value')

        cc_kwargs = {
            "bk_host_id": ",".join(host_result['data']),
            "data": {
                cc_host_property: cc_host_prop_value
            }
        }
        cc_result = client.cc.update_host(cc_kwargs)
        if cc_result['result']:
            return True
        else:
            message = cc_handle_api_error('cc.update_host', cc_kwargs,
                                          cc_result['message'])
            data.set_outputs('ex_data', message)
            return False