示例#1
0
def role_proxy_operator(user_name, obj_name, data, proxy=None, obj_uuid='all', action='add'):
    """
    保存,更新, 删除数据,并把操作结果保存到Task表中
    obj_name: PermRole, PermSudo
    """
    result = res_info = msg_name = ''
    g_lock = threading.Lock()  # 线程锁
    if obj_name == 'PermRole':
        msg_name = u'系统用户'
    elif obj_name == 'PermSudo':
        msg_name = u'SUDO别名'
    g_url = '{0}/v1.0/permission/{1}/{2}'.format(proxy.url, obj_name, obj_uuid)
    try:
        g_lock.acquire()
        # 在每个proxy上(add/update/delete) role/sudo,并返回结果
        api = APIRequest(g_url, proxy.username, CRYPTOR.decrypt(proxy.password))
        if action == 'add':
            result, codes = api.req_post(data)
            pdata = json.loads(data)
            res_info = u'添加{0}{1} {2}'.format(msg_name, pdata['name'], result['messege'])
        elif action == 'update':
            result, codes = api.req_put(data)
            pdata = json.loads(data)
            res_info = u'编辑{0}{1} {2}'.format(msg_name, pdata['name'], result['messege'])
        elif action == 'delete':
            result, codes = api.req_del(data)
            pdata = json.loads(data)
            res_info = u'删除{0}{1} {2}'.format(msg_name, pdata['name'], result['messege'])
        logger.info('role_proxy_%s:%s'%(action, result['messege']))

        # 生成唯一的事件名称,用于从数据库中查询执行结果
        if 'name' not in json.dumps(data):
            raise ValueError('role_proxy_operator: data["name"]不存在')
        task_name = json.loads(data)['name'] + '_' + uuid.uuid4().hex
        # 将事件添加到消息队列中
        task_queue.put({'server': task_name, 'username': user_name})

        # 将执行结果保存到数据库中
        role_task = Task()
        role_task.task_name = task_name
        role_task.proxy_name = proxy.proxy_name
        role_task.role_name = json.loads(data)['name']
        role_task.username = user_name
        role_task.status = 'complete'
        role_task.content = res_info
        role_task.url = g_url
        role_task.start_time = datetime.datetime.now()
        role_task.action = action
        role_task.role_uuid = obj_uuid
        role_task.role_data = data
        role_task.result = result['messege']
        role_task.save()
    except Exception as e:
        logger.error("[role_proxy_operator] %s"%e)
    finally:
        g_lock.release()
    return result
示例#2
0
def save_or_delete(obj_name, data, proxy, obj_uuid=None, action='add'):
    """
    保存,更新, 删除数据
    obj_name: 'PermRole'
    obj_uuid: role.uuid_id
    """
    info = ''
    try:
        api = APIRequest('{0}/v1.0/permission/{1}/{2}'.format(proxy.url, obj_name, obj_uuid), proxy.username, CRYPTOR.decrypt(proxy.password))
        if action == 'add':
            result, codes = api.req_post(data)
        elif action == 'update':
            result, codes = api.req_put(data)
        elif action == 'delete':
            result, codes = api.req_del(data)
        if result is not None:
            info = result['messege']
    except Exception as e:
        info = 'error'
        logger.error("[save_or_delete]    %s"%e)
    return info
示例#3
0
def save_or_delete(obj_name, data, proxy, obj_uuid=None, action='add'):
    """
    保存,更新, 删除数据
    obj_name: 'PermRole'
    obj_uuid: role.uuid_id
    """
    info = ''
    try:
        api = APIRequest(
            '{0}/v1.0/permission/{1}/{2}'.format(proxy.url, obj_name,
                                                 obj_uuid), proxy.username,
            CRYPTOR.decrypt(proxy.password))
        if action == 'add':
            result, codes = api.req_post(data)
        elif action == 'update':
            result, codes = api.req_put(data)
        elif action == 'delete':
            result, codes = api.req_del(data)
        if result is not None:
            info = result['messege']
    except Exception as e:
        info = 'error'
        logger.error("[save_or_delete]    %s" % e)
    return info
示例#4
0
def asset_edit(request, res, *args):
    """
    edit a asset
    修改主机
    """
    res['operator'] = u'编辑资产'
    if request.method == 'GET':
        rest = {}
        asset_id = request.GET.get('id', '')
        asset_obj = get_object(Asset, id=int(asset_id))
        pm = asset_obj.power_manage
        net = asset_obj.networking.all()[0]

        rest['Id'] = asset_obj.id
        rest['name'] = asset_obj.name
        rest['port'] = asset_obj.port
        rest['username'] = asset_obj.username
        rest['password'] = CRYPTOR.decrypt(asset_obj.password)
        rest['proxy_id'] = str(asset_obj.proxy.id)
        rest['profile'] = asset_obj.profile
        rest['kickstart'] = asset_obj.kickstart
        rest['netboot_enabled'] = asset_obj.netboot_enabled
        rest['group'] = ','.join([str(item.id) for item in asset_obj.group.all()])
        rest['idc'] = str(asset_obj.idc.id) if asset_obj.idc else ''
        rest['cabinet'] = asset_obj.cabinet
        rest['number'] = asset_obj.number
        rest['machine_status'] = str(asset_obj.machine_status)
        rest['asset_type'] = str(asset_obj.asset_type)
        rest['is_active'] = asset_obj.is_active
        rest['comment'] = asset_obj.comment
        rest['hostname'] = asset_obj.networking_g.hostname
        rest['gateway'] = asset_obj.networking_g.gateway
        rest['name_servers'] = asset_obj.networking_g.name_servers
        rest['net_name'] = net.net_name
        rest['mac_address'] = net.mac_address
        rest['mtu'] = net.mtu
        rest['ip_address'] = net.ip_address
        rest['static'] = net.static
        rest['subnet_mask'] = net.subnet_mask
        rest['per_gateway'] = net.per_gateway
        rest['dns_name'] = net.dns_name
        rest['static_routes'] = net.static_routes
        rest['power_type'] = pm.power_type
        rest['power_address'] = pm.power_address
        rest['power_username'] = pm.power_username
        rest['power_password'] = pm.power_password
        return HttpResponse(json.dumps(rest), content_type='application/json')
    else:
        response = {'success': False, 'error': ''}
        try:
            asset_id = request.GET.get('id', '')
            asset_info = get_object(Asset, id=asset_id)
            id_unique = asset_info.id_unique
            asset_info.name = request.POST.get('name', '')
            asset_info.profile = request.POST.get('profile', '')
            asset_info.kickstart = request.POST.get('kickstart', '')
            asset_info.port = int(request.POST.get('port',22))
            asset_info.username = request.POST.get('username', 'root')
            pwd = request.POST.get('password', '')
            asset_info.password = CRYPTOR.encrypt(pwd)
            asset_info.idc_id = int(request.POST.get('idc', '1'))
            asset_info.cabinet = request.POST.get('cabinet', '')
            asset_info.number = request.POST.get('number', '')
            asset_info.machine_status = int(request.POST.get('machine_status', 1))
            asset_info.asset_type = int(request.POST.get('asset_type', 1))
            asset_info.comment = request.POST.get('comment', '')
            asset_info.proxy_id = int(request.POST.get('proxy', '1'))

            nt_g = asset_info.networking_g
            nt_g.hostname = request.POST.get('hostname', '')
            nt_g.gateway = request.POST.get('gateway', '')
            nt_g.name_servers = request.POST.get('name_servers', '')
            nt_g.save()

            pm = asset_info.power_manage
            pm.power_type = request.POST.get('power_type')
            pm.power_address = request.POST.get('power_address')
            pm.power_username = request.POST.get('power_username')
            ency_password = CRYPTOR.encrypt(request.POST.get('power_password', ''))
            pm.power_password = ency_password
            pm.save()

            is_active = True if request.POST.get('is_active', '1') == '1' else False
            is_enabled = True if request.POST.get('is_enabled', '1') == '1' else False
            asset_info.netboot_enabled = is_enabled
            asset_info.is_active = is_active
            asset_info.save()

            net = asset_info.networking.all()[0]
            net.net_name = request.POST.get('net_name', 'eth0')
            net.mac_address = request.POST.get('mac_address', '')
            net.ip_address = request.POST.get('ip_address','')
            net.dns_name = request.POST.get('dns_name', '')
            net.mtu = request.POST.get('mtu', '')
            net.per_gateway = request.POST.get('per_gateway', '')
            net.static = request.POST.get('static', '')
            net.static_routes = request.POST.get('static_routes', '')
            net.subnet_mask = request.POST.get('subnet_mask', '')
            net.save()

            # 修改资产组
            new_group = []
            group_id = request.POST.getlist('group')
            for item in group_id:
                group = AssetGroup.objects.get(id=int(item))
                new_group.append(group)
            asset_info.group = new_group

        except Exception as e:
            res['flag'] = 'false'
            res['content'] = e.message
            res['error'] = e.message
        else:
            name = request.POST.get('name')
            fields = {
                'id_unique': id_unique,
                "hostname": request.POST.get('hostname'),
                "profile": request.POST.get('profile'),
                "gateway": request.POST.get('gateway'),
                "netboot_enabled": request.POST.get('is_enabled'),
                "power_type": request.POST.get('power_type'),
                "power_address": request.POST.get('power_address'),
                "power_user": request.POST.get('power_username'),
                "power_pass": request.POST.get('power_password'),
                "interfaces": {
                    "{0}".format(request.POST.get('net_name', 'eth0')): {
                        "mac_address": request.POST.get('mac_address'),
                        "ip_address": request.POST.get('ip_address'),
                        "if_gateway": request.POST.get('per_gateway'),
                        "mtu": request.POST.get('mtu'),
                        "netmask": request.POST.get('subnet_mask'),
                        "static": 1,
                    },
                }
            }
            data = json.dumps(fields)
            select_proxy = get_object(Proxy, id=int(request.POST.get('proxy')))
            pro_username = select_proxy.username
            pro_password = select_proxy.password
            pro_url = select_proxy.url
            try:
                api = APIRequest('{0}/v1.0/system/{1}'.format(pro_url, name), pro_username, CRYPTOR.decrypt(pro_password))
                result, code = api.req_put(data)
            except Exception, e:
                    logger.error(e)
                    res['flag'] = 'false'
                    res['content'] = e.message
                    response['error'] = u'编辑资产失败:%s'%e.message
            else:
示例#5
0
def adv_task_edit(request, res, *args, **kwargs):
    if request.method == 'POST':
        param = {}
        # 触发器
        trigger_kwargs = request.POST.get('trigger')
        comment = request.POST.get('comment')
        task_id = int(request.POST.get('task_id'))
        try:
            task = Task.objects.get(id=task_id)
            # 构建trigger
            trigger_kwargs = json.loads(trigger_kwargs)
            start_date = trigger_kwargs.pop('start_date')
            end_date = trigger_kwargs.get('end_date')
            if end_date:
                trigger_kwargs.pop('end_date')

            if not trigger_kwargs:
                start_date_2_date = datetime.strptime(start_date, '%Y-%m-%d %H:%M:%S')
                trigger_kwargs['year'] = start_date_2_date.year
                trigger_kwargs['month'] = start_date_2_date.month
                trigger_kwargs['day'] = start_date_2_date.day
                trigger_kwargs['hour'] = start_date_2_date.hour
                trigger_kwargs['minute'] = start_date_2_date.minute
                trigger_kwargs['second'] = start_date_2_date.second
            trigger_kwargs['start_date'] = start_date
            if end_date:
                trigger_kwargs['end_date'] = end_date
            param['trigger_kwargs'] = trigger_kwargs

            # 先从Proxy获取是否存在,若不存在则新建
            api = APIRequest('{0}/v1.0/job/{1}'.format(task.task_proxy.url, task.task_uuid),
                             task.task_proxy.username,
                             CRYPTOR.decrypt(task.task_proxy.password))
            result, code = api.req_get()

            if code == 404:
                param['job_id'] = task.task_uuid
                param['task_name'] = task.task_type
                param['task_kwargs'] = json.loads(task.task_kwargs)
                # 任务已经完全结束,再次编辑时,proxy端需要重新创建
                api = APIRequest('{0}/v1.0/job'.format(task.task_proxy.url), task.task_proxy.username,
                                 CRYPTOR.decrypt(task.task_proxy.password))
                result, code = api.req_post(json.dumps(param))
                if code != 200:
                    raise ServerError(result['messege'])
                else:
                    task.trigger_kwargs = json.dumps(trigger_kwargs)
                    task.comment = comment
                    task.is_get_last = '00'
                    task.task_statu = '00'
                    task.save()
            elif code == 200:
                api = APIRequest('{0}/v1.0/job/{1}'.format(task.task_proxy.url, task.task_uuid),
                                 task.task_proxy.username,
                                 CRYPTOR.decrypt(task.task_proxy.password))
                result, code = api.req_put(json.dumps(param))
                if code != 200:
                    raise ServerError(result['messege'])
                else:
                    task.trigger_kwargs = json.dumps(trigger_kwargs)
                    task.comment = comment
                    task.save()
        except:
            logger.error(traceback.format_exc())
            res['flag'] = False
            res['content'] = "update error"
        else:
            res['flag'] = True
        return HttpResponse(json.dumps(res))
    elif request.method == "GET":
        task_id = request.GET.get('task_id')
        task = Task.objects.get(id=task_id).to_dict()
        proxy_list = [proxy.to_dict() for proxy in Proxy.objects.all().order_by('create_time')]
        task['task_proxy'] = task['task_proxy'].to_dict()
        res['task'] = task
        res['proxys'] = proxy_list
        res['task_types'] = Task.TYPES[1:]
        return HttpResponse(json.dumps(res))
示例#6
0
def role_proxy_operator(user_name,
                        obj_name,
                        data,
                        proxy=None,
                        obj_uuid='all',
                        action='add'):
    """
    保存,更新, 删除数据,并把操作结果保存到Task表中
    obj_name: PermRole, PermSudo
    """
    result = res_info = msg_name = ''
    g_lock = threading.Lock()  # 线程锁
    if obj_name == 'PermRole':
        msg_name = u'系统用户'
    elif obj_name == 'PermSudo':
        msg_name = u'SUDO别名'
    g_url = '{0}/v1.0/permission/{1}/{2}'.format(proxy.url, obj_name, obj_uuid)
    try:
        g_lock.acquire()
        # 在每个proxy上(add/update/delete) role/sudo,并返回结果
        api = APIRequest(g_url, proxy.username,
                         CRYPTOR.decrypt(proxy.password))
        if action == 'add':
            result, codes = api.req_post(data)
            pdata = json.loads(data)
            res_info = u'添加{0}{1} {2}'.format(msg_name, pdata['name'],
                                              result['messege'])
        elif action == 'update':
            result, codes = api.req_put(data)
            pdata = json.loads(data)
            res_info = u'编辑{0}{1} {2}'.format(msg_name, pdata['name'],
                                              result['messege'])
        elif action == 'delete':
            result, codes = api.req_del(data)
            pdata = json.loads(data)
            res_info = u'删除{0}{1} {2}'.format(msg_name, pdata['name'],
                                              result['messege'])
        logger.info('role_proxy_%s:%s' % (action, result['messege']))

        # 生成唯一的事件名称,用于从数据库中查询执行结果
        if 'name' not in json.dumps(data):
            raise ValueError('role_proxy_operator: data["name"]不存在')
        task_name = json.loads(data)['name'] + '_' + uuid.uuid4().hex
        # 将事件添加到消息队列中
        task_queue.put({'server': task_name, 'username': user_name})

        # 将执行结果保存到数据库中
        role_task = Task()
        role_task.task_name = task_name
        role_task.proxy_name = proxy.proxy_name
        role_task.role_name = json.loads(data)['name']
        role_task.username = user_name
        role_task.status = 'complete'
        role_task.content = res_info
        role_task.url = g_url
        role_task.start_time = datetime.datetime.now()
        role_task.action = action
        role_task.role_uuid = obj_uuid
        role_task.role_data = data
        role_task.result = result['messege']
        role_task.save()
    except Exception as e:
        logger.error("[role_proxy_operator] %s" % e)
    finally:
        g_lock.release()
    return result