コード例 #1
0
ファイル: asset_api.py プロジェクト: yunyun1/MagicStack
def update_asset_info(need_update_asset, name, proxy=None):
    """
    更新资产信息
    """
    g_lock = threading.Lock()
    try:
        g_lock.acquire()
        proxy_asset = Asset.objects.filter(proxy__proxy_name=proxy.proxy_name)
        update_proxy_asset = list(set(proxy_asset) & set(need_update_asset))
        host_list = [
            asset.networking.all()[0].ip_address
            for asset in update_proxy_asset
        ]
        if host_list:
            resource = gen_resource(update_proxy_asset)
            data = {
                'mod_name': 'setup',
                'resource': resource,
                'hosts': host_list,
                'mod_args': '',
                'run_action': 'sync',
                'run_type': 'ad-hoc'
            }
            data = json.dumps(data)
            api = APIRequest('{0}/v1.0/module'.format(proxy.url),
                             proxy.username, CRYPTOR.decrypt(proxy.password))
            result, code = api.req_post(data)
            logger.debug(u'更新操作结果result:%s       code:%s' % (result, code))
            if code == 200 and result['messege']['success']:
                asset_ansible_update(update_proxy_asset, result, name)
    except Exception as e:
        raise ServerError(e)
    finally:
        g_lock.release()
コード例 #2
0
ファイル: views.py プロジェクト: AutoOps/MagicStack
def asset_event(request):
    response = {'success': True, 'message':''}
    if request.method == 'GET':
        user_name = request.user.username
        try:
            if asset_task_queue.qsize() > 0:
                tk_event = asset_task_queue.get()
                if tk_event['task_user'] != user_name:
                    asset_task_queue.put(tk_event)
                    response['success'] = False
                else:
                    tk_proxy = Proxy.objects.get(proxy_name=tk_event['task_proxy'])
                    api = APIRequest('{0}/v1.0/event/{1}'.format(tk_proxy.url, tk_event['task_name']), tk_proxy.username, CRYPTOR.decrypt(tk_proxy.password))
                    result, codes = api.req_get()
                    logger.debug(u'事件查询结果result:%s'%result)
                    tk = get_object(Task, task_name=tk_event['task_name'])
                    tk.status = result['status']
                    tk.content = result['event_log']
                    tk.save()
                    response['message'] = result['event_log']
            return HttpResponse(json.dumps(response), content_type='application/json')
        except Exception as e:
            logger.error(e)
            response['success'] = False
            response['message'] = e
            return HttpResponse(json.dumps(response), content_type='application/json')
コード例 #3
0
ファイル: asset_api.py プロジェクト: yunyun1/MagicStack
def asset_operator(asset_list, status, username, proxy=None):
    """
    重启,关机,重装系统
    """
    g_lock = threading.Lock()
    try:
        g_lock.acquire()
        proxy_asset = Asset.objects.filter(proxy__proxy_name=proxy.proxy_name)
        need_delete_asset = set(asset_list) & set(proxy_asset)
        systems = [item.name for item in need_delete_asset]
        profile = asset_list[0].profile
        if status == 'rebuild':
            data = {'rebuild': 'true', 'profile': profile, 'systems': systems}
        else:
            data = {'power': status, 'systems': systems}
        data = json.dumps(data)
        api = APIRequest('{0}/v1.0/system/action'.format(proxy.url),
                         proxy.username, CRYPTOR.decrypt(proxy.password))
        result, codes = api.req_post(data)
        logger.debug(u"操作结果result:%s   codes:%s" % (result, codes))
        task = Task()
        task.task_name = result['task_name']
        task.username = username
        task.status = result['messege']
        task.start_time = datetime.datetime.now()
        task.url = '{0}/v1.0/system/action'.format(proxy.url)
        task.save()
        task_queue.put(
            dict(task_name=result['task_name'],
                 task_user=username,
                 task_proxy=proxy.proxy_name))
    except Exception as e:
        raise ServerError(e)
    finally:
        g_lock.release()
コード例 #4
0
ファイル: views.py プロジェクト: AutoOps/MagicStack
def adv_task_action(request, res, *args, **kwargs):
    if request.method == 'POST':

        task_id = request.POST.get('task_id')
        action = request.POST.get('action')
        task = Task.objects.get(id=task_id)
        try:
            # TODO 先获取记录是否存在,存在的话就是新建

            # 构建参数
            param = {'action': action}

            # 调用proxy接口,
            api = APIRequest('{0}/v1.0/job/{1}/action/'.format(task.task_proxy.url, task.task_uuid),
                             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:
                if action == 'pause':
                    task.task_statu = '01'
                else:
                    task.task_statu = '00'
                task.save()
        except ServerError, e:
            error = e.message
            res['flag'] = False
            res['content'] = error
        except Exception, e:
            res['flag'] = False
            res['content'] = e[1]
コード例 #5
0
    def add_user(self, username, proxy, groups, web_username):
        """
        add a host user.
        username: 系统用户名
        web_username: 网站用户名
        """
        self.run_action = 'async'
        self.run_type = 'ad-hoc'
        if groups.strip():
            module_args = 'name=%s shell=/bin/bash groups=%s' % (username,
                                                                 groups)
        else:
            module_args = 'name=%s shell=/bin/bash' % username

        data = {
            'mod_name': 'user',
            'resource': self.resource,
            'hosts': self.host_list,
            'mod_args': module_args,
            'role_name': username,
            'web_username': web_username,
            'run_action': self.run_action,
            'run_type': self.run_type,  # 标记, 执行ansible ad-hoc命令还是执行playbook
            'isTemplate': self.isTemplate
        }
        data = json.dumps(data)
        api = APIRequest('{0}/v1.0/module'.format(proxy.url), proxy.username,
                         CRYPTOR.decrypt(proxy.password))
        result, code = api.req_post(data)
        return result
コード例 #6
0
ファイル: asset_api.py プロジェクト: AutoOps/MagicStack
def update_asset_info(need_update_asset, name, proxy=None):
    """
    更新资产信息
    """
    g_lock = threading.Lock()
    try:
        g_lock.acquire()
        proxy_asset = Asset.objects.filter(proxy__proxy_name=proxy.proxy_name)
        update_proxy_asset = list(set(proxy_asset) & set(need_update_asset))
        host_list = [asset.networking.all()[0].ip_address for asset in update_proxy_asset]
        if host_list:
            resource = gen_resource(update_proxy_asset)
            data = {'mod_name': 'setup',
                    'resource': resource,
                    'hosts': host_list,
                    'mod_args': '',
                    'run_action': 'sync',
                    'run_type': 'ad-hoc'
                    }
            data = json.dumps(data)
            api = APIRequest('{0}/v1.0/module'.format(proxy.url), proxy.username, CRYPTOR.decrypt(proxy.password))
            result, code = api.req_post(data)
            logger.debug(u'更新操作结果result:%s       code:%s' % (result,code))
            if code == 200 and result['messege']['success']:
                asset_ansible_update(update_proxy_asset, result, name)
    except Exception as e:
        raise ServerError(e)
    finally:
        g_lock.release()
コード例 #7
0
ファイル: views.py プロジェクト: AutoOps/MagicStack
def adv_task_del(request, res, *args, **kwargs):
    if request.method == 'POST':
        task_ids = request.POST.get('task_id')
        res['flag'] = True
        success = []
        fail = []
        # 循环删除
        for task_id in task_ids.split(','):
            task = Task.objects.get(id=task_id)
            try:
                # 调用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_del(json.dumps({}))
                if code != 200:
                    raise ServerError(result['messege'])
                else:
                    task.task_statu = '02'
                    task.save()
            except ServerError, e:
                fail.append(task)
                error = e.message
                res['flag'] = False
                res['content'] = error
            except Exception, e:
                fail.append(task)
                res['flag'] = False
                res['content'] = e[1]
            else:
                success.append(task)
コード例 #8
0
ファイル: views.py プロジェクト: AutoOps/MagicStack
def task_exec_info_v1(request, res, *args, **kwargs):
    """
        获取任务执行信息

        前端使用jquery plugin datatables进行分页
        后端根据前端规则组合数据
    """

    if request.method == 'POST':
        task_id = request.POST.get('task_id')
        page = request.POST.get('page')
        limit = request.POST.get('limit')
        task = Task.objects.get(id=task_id)
        try:
            # 调用proxy接口,
            api = APIRequest('{0}/v1.0/job_task/{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 != 200:
                raise ServerError(result['messege'])
            else:
                tasks = result['result']['tasks']
        except ServerError, e:
            error = e.message
            res['flag'] = False
            res['content'] = error
        except Exception, e:
            res['flag'] = False
            res['content'] = e[1]
コード例 #9
0
ファイル: ansible_api.py プロジェクト: AutoOps/MagicStack
    def add_user(self, username, proxy, groups, web_username):
        """
        add a host user.
        username: 系统用户名
        web_username: 网站用户名
        """
        self.run_action = 'async'
        self.run_type = 'ad-hoc'
        if groups.strip():
            module_args = 'name=%s shell=/bin/bash groups=%s' % (username, groups)
        else:
            module_args = 'name=%s shell=/bin/bash' % username

        data = {'mod_name': 'user',
                'resource': self.resource,
                'hosts': self.host_list,
                'mod_args': module_args,
                'role_name': username,
                'web_username': web_username,
                'run_action': self.run_action,
                'run_type': self.run_type,                    # 标记, 执行ansible ad-hoc命令还是执行playbook
                'isTemplate': self.isTemplate
                }
        data = json.dumps(data)
        api = APIRequest('{0}/v1.0/module'.format(proxy.url), proxy.username, CRYPTOR.decrypt(proxy.password))
        result, code = api.req_post(data)
        return result
コード例 #10
0
ファイル: perm_api.py プロジェクト: AutoOps/MagicStack
def query_event(task_name, username, proxy):
    data = {'task_name': task_name, 'username': username}
    data = json.dumps(data)
    api = APIRequest('{0}/v1.0/permission/event'.format(proxy.url), proxy.username, CRYPTOR.decrypt(proxy.password))
    result, codes = api.req_post(data)
    logger.info('推送用户事件查询结果result:%s'%result)
    return result
コード例 #11
0
ファイル: perm_api.py プロジェクト: yunyun1/MagicStack
def query_event(task_name, username, proxy):
    data = {'task_name': task_name, 'username': username}
    data = json.dumps(data)
    api = APIRequest('{0}/v1.0/permission/event'.format(proxy.url),
                     proxy.username, CRYPTOR.decrypt(proxy.password))
    result, codes = api.req_post(data)
    logger.info('推送用户事件查询结果result:%s' % result)
    return result
コード例 #12
0
ファイル: perm_api.py プロジェクト: AutoOps/MagicStack
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
コード例 #13
0
ファイル: views.py プロジェクト: AutoOps/MagicStack
def task_exec_info(request, res, *args, **kwargs):
    """
        获取任务执行信息

        前端使用jquery plugin datatables进行分页
        后端根据前端规则组合数据
    """

    if request.method == 'POST':
        # 初始化返回结果
        return_obj = {
            "sEcho": request.POST.get('sEcho', 0), # 前端上传原样返回
            "iTotalRecords": 0, # 总记录数
            "iTotalDisplayRecords": 0, # 过滤后总记录数
            "aaData": [] # 返回前端数据,json格式
        }

        # 获取过滤条件
        task_id = request.POST.get('task_id')
        # 前端datatable上传每页显示数据
        limit = request.POST.get('iDisplayLength', 0)
        # 前端datatable上送从第几条开始展示
        offset = request.POST.get('iDisplayStart', 5)
        task = Task.objects.get(id=task_id)

        # 获取数据
        try:
            # 调用proxy接口,
            api = APIRequest(
                '{0}/v1.0/job_task/{1}?limit={2}&offset={3}'.format(task.task_proxy.url, task.task_uuid, limit, offset),
                task.task_proxy.username,
                CRYPTOR.decrypt(task.task_proxy.password))
            result, code = api.req_get()
            if code != 200:
                raise ServerError(result['messege'])
            else:
                tasks = result['result']['tasks']
                total_count = result['result']['total_count']
                display_lsit = []
                for task in tasks:
                    display_lsit.append({
                        'start_time': task.get('start_time'),
                        'end_time': task.get('end_time'),
                        'status': task.get('status'),
                        'id': task.get('id'),
                        'job_id': task.get('job_id')
                    })

                return_obj['aaData'] = display_lsit
                return_obj['iTotalRecords'] = total_count
                return_obj['iTotalDisplayRecords'] = total_count
        except:
            logger.error("GET TASK EXEC INFO ERROR\n {0}".format(traceback.format_exc()))

        return HttpResponse(json.dumps(return_obj))
コード例 #14
0
ファイル: asset_api.py プロジェクト: jinrenlab/MagicStack
def get_profiles():
    profiles = []
    try:
        api = APIRequest('http://172.16.30.69:8100/v1.0/profile', 'test', '123456')
        msg, codes = api.req_get()
        logger.debug("msg:%s"%msg)
        if msg:
            profiles = msg['profiles']
    except Exception as e:
        logger.error(e)
    return profiles
コード例 #15
0
ファイル: perm_api.py プロジェクト: AutoOps/MagicStack
def get_one_or_all(obj_name, proxy, obj_uuid='all'):
    """
    获取所有的对象或者一个id对应的对象
    """
    obj_list = []
    try:
        api = APIRequest('{0}/v1.0/permission/{1}/{2}'.format(proxy.url, obj_name, obj_uuid), proxy.username, CRYPTOR.decrypt(proxy.password))
        result, codes = api.req_get()
        obj_list = result['messege']
    except Exception as e:
        logger.error(e)
    return obj_list
コード例 #16
0
def get_backup_info_from_proxy(backup):
    # 调用proxy接口
    api = APIRequest('{0}/v1.0/job_task/{1}?limit=1'.format(backup.proxy.url, backup.task_uuid),
                     backup.proxy.username,
                     CRYPTOR.decrypt(backup.proxy.password))
    result, code = api.req_get()
    if code != 200:
        # 获取失败,下次继续获取
        result = {}
    else:
        result = result['result']
    return result
コード例 #17
0
ファイル: views.py プロジェクト: AutoOps/MagicStack
def task_action(request, res, *args, **kwargs):
    if request.method == 'POST':

        task_id = request.POST.get('task_id')
        action = request.POST.get('action')
        task = Task.objects.get(id=task_id)
        try:
            # 先从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()

            # 构建参数
            param = {'action': action}
            if code == 200:
                # 调用proxy接口,
                api = APIRequest('{0}/v1.0/job/{1}/action/'.format(task.task_proxy.url, task.task_uuid),
                                 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:
                    if action == 'pause':
                        task.task_statu = '01'
                    else:
                        task.task_statu = '00'
                    task.save()
            elif code == 404:
                logger.info("task [%s] have been deleted" % task.task_uuid)
                # 不存在时,若启用则创建,若禁用则直接修改为禁用
                if action == 'pause':
                    # 停用,直接修改为禁用
                    task.task_statu = '01'
                    task.save()
                elif action == 'resume':
                    res['flag'] = False
                    res['content'] = '触发器已过期,请使用编辑功能编辑触发器'
                    return HttpResponse(json.dumps(res))
        except ServerError, e:
            logger.error("action error %s" % str(e))
            error = e.message
            res['flag'] = False
            res['content'] = error
        except Exception, e:
            logger.error("error %s" % str(e))
            res['flag'] = False
            res['content'] = e[1]
コード例 #18
0
ファイル: perm_api.py プロジェクト: yunyun1/MagicStack
def get_one_or_all(obj_name, proxy, obj_uuid='all'):
    """
    获取所有的对象或者一个id对应的对象
    """
    obj_list = []
    try:
        api = APIRequest(
            '{0}/v1.0/permission/{1}/{2}'.format(proxy.url, obj_name,
                                                 obj_uuid), proxy.username,
            CRYPTOR.decrypt(proxy.password))
        result, codes = api.req_get()
        obj_list = result['messege']
    except Exception as e:
        logger.error(e)
    return obj_list
コード例 #19
0
def download(request):
    if request.method == 'POST':
        # 上传到本地目录
        res = {'result': False}
        try:
            path = request.POST.get('path')
            proxy = request.POST.get('proxy')
            proxy_host = request.POST.get('proxy_host')
            params = {'action': 'download_ansible'}
            # 通过proxy处理文件
            proxy_obj = Proxy.objects.get(id=proxy)
            hosts = []
            if not proxy_host:
                raise RuntimeError("没有可执行主机")
            else:
                hosts.append(Asset.objects.get(id=int(proxy_host)))
            host_list = []
            resource = []
            params['path'] = path
            # 构建inventory 和 构建主机list
            for host in hosts:
                host_list.append(host.networking.all()[0].ip_address)
                tmp_d = dict()
                tmp_d['hostname'] = host.networking.all()[0].ip_address
                tmp_d['port'] = host.port
                tmp_d['username'] = host.username
                tmp_d['password'] = CRYPTOR.decrypt(host.password)
                # 用于前端确定选择的asset
                tmp_d['id'] = host.id
                resource.append(tmp_d)
            params['host_list'] = host_list
            params['resource'] = resource

            api = APIRequest(
                '{0}/v1.0/download'.format(proxy_obj.url), proxy_obj.username,
                CRYPTOR.decrypt(proxy_obj.password))
            result, code = api.req_post(json.dumps(params))
            if code != 200:
                res['message'] = result['message']
            else:
                res['result'] = True
                link = "{0}/v1.0/download?link_id={1}".format(proxy_obj.url, result['link'])
                res['link'] = link
                logger.info("link => {0}".format(res))
        except Exception, e:
            logger.info(traceback.format_exc())
            res['message'] = '失败'
        return HttpResponse(json.dumps(res))
コード例 #20
0
ファイル: ansible_api.py プロジェクト: AutoOps/MagicStack
    def del_key(self, user, key_path, proxy):
        """
        push the ssh authorized key to target.
        """

        module_args = 'user="******" key="{{ lookup("file", "%s") }}" state="absent"' % (user, key_path)
        data = {'mod_name': 'authorized_key',
                'resource': self.resource,
                'hosts': self.host_list,
                'mod_args': module_args,
                'role_name': user
                }
        data = json.dumps(data)
        api = APIRequest('{0}/v1.0/module'.format(proxy.url), proxy.username, CRYPTOR(proxy.password))
        result, code = api.req_post(data)
        return result
コード例 #21
0
ファイル: views.py プロジェクト: AutoOps/MagicStack
def asset_del(request,res, *args):
    """
    del a asset
    删除主机
    """
    response = {'msg': u'删除成功'}
    res['operator'] = res['content'] = u'删除主机'
    asset_id = request.GET.get('id', '')
    if asset_id:
        asset = get_object(Asset, id=int(asset_id))
        if asset:
            proxy = asset.proxy
            param = {'names': [asset.name], 'id_unique': asset.id_unique}
            data = json.dumps(param)
            try:
                api = APIRequest('{0}/v1.0/system'.format(proxy.url), proxy.username, CRYPTOR.decrypt(proxy.password))
                result, code = api.req_del(data)
                logger.debug(u'删除单一资产result:%s'%result)
                if code == 200:
                    asset.delete()
                else:
                    response['msg'] = result['messege']
            except Exception as e:
                logger.error(e)
                res['flag'] = 'false'
                res['content'] = e
                response['msg'] = e

    if request.method == 'POST':
        try:
            asset_id_all = request.POST.get('asset_id_all', '')
            asset_list = []
            for asset_id in asset_id_all.split(','):
                asset = get_object(Asset, id=int(asset_id))
                res['content'] += '%s   ' % asset.name
                if asset:
                    asset_list.append(asset)
            proxy_list = Proxy.objects.all()
            execute_thread_tasks(proxy_list, THREAD_NUMBERS, delete_asset_batch, asset_list)
            response['msg'] = u'批量删除主机成功'
        except Exception as e:
            logger.error(e)
            res['flag'] = 'false'
            res['content'] = e
            response['msg'] = e
        return HttpResponse(json.dumps(response), content_type='application/json')
コード例 #22
0
ファイル: ansible_api.py プロジェクト: AutoOps/MagicStack
 def del_user(self, username, proxy, web_username):
     """
     delete a host user.
     """
     module_args = 'name=%s groups='' state=absent remove=yes move_home=yes force=yes' % username
     data = {'mod_name': 'user',
             'resource': self.resource,
             'hosts': self.host_list,
             'mod_args': module_args,
             'role_name': username,
             'web_username': web_username,
             'run_action': 'sync',                       # run_action参数表示同步还是异步执行
             'run_type': 'ad-hoc'
             }
     data = json.dumps(data)
     api = APIRequest('{0}/v1.0/module'.format(proxy.url), proxy.username, CRYPTOR.decrypt(proxy.password))
     result, code = api.req_post(data)
     return result
コード例 #23
0
ファイル: asset_api.py プロジェクト: AutoOps/MagicStack
def gen_proxy_profiles(proxys):
    """
    获取proxy对应的profiles
    """
    proxy_profiles = {}
    if isinstance(proxys, (list, QuerySet)):
        for item in proxys:
            profiles = []
            try:
                api = APIRequest('{0}/v1.0/profile'.format(item.url), item.username, CRYPTOR.decrypt(item.password))
                msg, codes = api.req_get()
                if msg:
                    profiles = msg['profiles']
            except Exception as e:
                logger.error(e)
            proxy_profiles[item.proxy_name] = profiles
    logger.info("获取proxy对应的profiles:%s"%proxy_profiles)
    return proxy_profiles
コード例 #24
0
ファイル: ansible_api.py プロジェクト: AutoOps/MagicStack
 def del_user_sudo(self, role_uuid, proxy, web_username):
     """
     delete a role sudo item
     """
     filename = 'role-%s'%role_uuid
     module_args = "name=/etc/sudoers.d/%s  state=absent" %filename
     data = {'mod_name': 'file',
             'resource': self.resource,
             'hosts': self.host_list,
             'mod_args': module_args,
             'web_username': web_username,
             'run_action': 'sync',
             'run_type': 'ad-hoc'
             }
     data = json.dumps(data)
     api = APIRequest('{0}/v1.0/module'.format(proxy.url), proxy.username, CRYPTOR.decrypt(proxy.password))
     result, code = api.req_post(data)
     return result
コード例 #25
0
    def del_key(self, user, key_path, proxy):
        """
        push the ssh authorized key to target.
        """

        module_args = 'user="******" key="{{ lookup("file", "%s") }}" state="absent"' % (
            user, key_path)
        data = {
            'mod_name': 'authorized_key',
            'resource': self.resource,
            'hosts': self.host_list,
            'mod_args': module_args,
            'role_name': user
        }
        data = json.dumps(data)
        api = APIRequest('{0}/v1.0/module'.format(proxy.url), proxy.username,
                         CRYPTOR(proxy.password))
        result, code = api.req_post(data)
        return result
コード例 #26
0
ファイル: asset_api.py プロジェクト: yunyun1/MagicStack
def gen_proxy_profiles(proxys):
    """
    获取proxy对应的profiles
    """
    proxy_profiles = {}
    if isinstance(proxys, (list, QuerySet)):
        for item in proxys:
            profiles = []
            try:
                api = APIRequest('{0}/v1.0/profile'.format(item.url),
                                 item.username, CRYPTOR.decrypt(item.password))
                msg, codes = api.req_get()
                if msg:
                    profiles = msg['profiles']
            except Exception as e:
                logger.error(e)
            proxy_profiles[item.proxy_name] = profiles
    logger.info("获取proxy对应的profiles:%s" % proxy_profiles)
    return proxy_profiles
コード例 #27
0
 def del_user(self, username, proxy, web_username):
     """
     delete a host user.
     """
     module_args = 'name=%s groups=' ' state=absent remove=yes move_home=yes force=yes' % username
     data = {
         'mod_name': 'user',
         'resource': self.resource,
         'hosts': self.host_list,
         'mod_args': module_args,
         'role_name': username,
         'web_username': web_username,
         'run_action': 'sync',  # run_action参数表示同步还是异步执行
         'run_type': 'ad-hoc'
     }
     data = json.dumps(data)
     api = APIRequest('{0}/v1.0/module'.format(proxy.url), proxy.username,
                      CRYPTOR.decrypt(proxy.password))
     result, code = api.req_post(data)
     return result
コード例 #28
0
ファイル: asset_api.py プロジェクト: AutoOps/MagicStack
def delete_asset_batch(asset_list, proxy=None):
    g_lock = threading.Lock()
    try:
        g_lock.acquire()
        proxy_asset = Asset.objects.filter(proxy__proxy_name=proxy.proxy_name)
        need_delete_asset = set(asset_list) & set(proxy_asset)
        asset_names = [asset.name for asset in need_delete_asset]
        id_uniques = [asset.id_unique for asset in need_delete_asset]
        param = {'names': asset_names, 'id_unique': id_uniques}
        data = json.dumps(param)
        api = APIRequest('{0}/v1.0/system'.format(proxy.url), proxy.username, CRYPTOR.decrypt(proxy.password))
        result, code = api.req_del(data)
        logger.info(u'删除多个资产result:%s'% result)
        if code == 200:
            for item in need_delete_asset:
                item.delete()
    except Exception as e:
        raise ServerError(e)
    finally:
        g_lock.release()
コード例 #29
0
ファイル: views.py プロジェクト: yunyun1/MagicStack
def exec_commands_log(request):
    log_id = request.POST.get('id', '')
    proxy_id = request.POST.get('proxy_id', '')
    try:
        proxy = Proxy.objects.get(id=int(proxy_id))
        if log_id and proxy:
            api = APIRequest('{0}/v1.0/execute/commands/loginfos/{1}'.format(proxy.url, log_id), proxy.username, CRYPTOR.decrypt(proxy.password))
            result, codes = api.req_get()
            log_info = result['data']
            exec_log = ExecLog()
            exec_log.remote_id = log_id
            exec_log.user = request.user.username
            exec_log.host = log_info['host']
            exec_log.cmd = log_info['cmd']
            exec_log.remote_ip = log_info['remote_ip']
            exec_log.proxy_host = log_info['proxy_host']
            exec_log.result = log_info['result']
            exec_log.save()
    except Exception as e:
        logger.error(e)
コード例 #30
0
ファイル: views.py プロジェクト: yunyun1/MagicStack
def log_history(request):
    """ 命令历史记录 """
    log_id = request.GET.get('id', 0)
    loginfo = Log.objects.get(id=log_id)
    proxy_log_id = loginfo.proxy_log_id
    if loginfo:
        proxy_name = loginfo.proxy_name
        proxy = Proxy.objects.get(proxy_name=proxy_name)
        api = APIRequest('{0}/v1.0/ttylog?log_id={1}'.format(proxy.url, proxy_log_id), proxy.username, CRYPTOR.decrypt(proxy.password))
        result, codes = api.req_get()
        if 'data' in result.keys():
            tty_proxys = result['data']
            tty_logs = sorted(tty_proxys, key=lambda x: x['datetime'])
            if tty_logs:
                content = ''
                for tty_log in tty_logs:
                    content += '%s: %s\n' % (tty_log['datetime'], tty_log['cmd'])
                return HttpResponse(content)

    return HttpResponse('无日志记录!')
コード例 #31
0
 def del_user_sudo(self, role_uuid, proxy, web_username):
     """
     delete a role sudo item
     """
     filename = 'role-%s' % role_uuid
     module_args = "name=/etc/sudoers.d/%s  state=absent" % filename
     data = {
         'mod_name': 'file',
         'resource': self.resource,
         'hosts': self.host_list,
         'mod_args': module_args,
         'web_username': web_username,
         'run_action': 'sync',
         'run_type': 'ad-hoc'
     }
     data = json.dumps(data)
     api = APIRequest('{0}/v1.0/module'.format(proxy.url), proxy.username,
                      CRYPTOR.decrypt(proxy.password))
     result, code = api.req_post(data)
     return result
コード例 #32
0
ファイル: ansible_api.py プロジェクト: AutoOps/MagicStack
 def push_sudo(self, role, sudo_uuids, proxy, web_username):
     """
     use template to render pushed sudoers file
     """
     self.run_action = 'async'
     self.run_type = 'playbook'
     data = {'resource': self.resource,
             'hosts': self.host_list,
             'sudo_uuids': sudo_uuids,
             'role_name': role.name,
             'role_uuid': role.uuid_id,
             'web_username': web_username,
             'run_action': self.run_action,
             'run_type': self.run_type,
             'isTemplate': True
             }
     data = json.dumps(data)
     api = APIRequest('{0}/v1.0/module'.format(proxy.url), proxy.username, CRYPTOR.decrypt(proxy.password))
     result, code = api.req_post(data)
     return result
コード例 #33
0
ファイル: ansible_api.py プロジェクト: AutoOps/MagicStack
 def push_key(self, user, key_path, proxy, web_username):
     """
     push the ssh authorized key to target.
     """
     self.run_action = 'async'
     self.run_type = 'ad-hoc'
     module_args = 'user="******" key="{{ lookup("file", "%s") }}" state=present' % (user, key_path)
     data = {'mod_name': 'authorized_key',
             'resource': self.resource,
             'hosts': self.host_list,
             'mod_args': module_args,
             'role_name': user,
             'web_username': web_username,
             'run_action': self.run_action,
             'run_type': self.run_type,
             'isTemplate': self.isTemplate
             }
     data = json.dumps(data)
     api = APIRequest('{0}/v1.0/module'.format(proxy.url), proxy.username, CRYPTOR.decrypt(proxy.password))
     result, code = api.req_post(data)
     return result
コード例 #34
0
ファイル: perm_api.py プロジェクト: AutoOps/MagicStack
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
コード例 #35
0
ファイル: asset_api.py プロジェクト: yunyun1/MagicStack
def delete_asset_batch(asset_list, proxy=None):
    g_lock = threading.Lock()
    try:
        g_lock.acquire()
        proxy_asset = Asset.objects.filter(proxy__proxy_name=proxy.proxy_name)
        need_delete_asset = set(asset_list) & set(proxy_asset)
        asset_names = [asset.name for asset in need_delete_asset]
        id_uniques = [asset.id_unique for asset in need_delete_asset]
        param = {'names': asset_names, 'id_unique': id_uniques}
        data = json.dumps(param)
        api = APIRequest('{0}/v1.0/system'.format(proxy.url), proxy.username,
                         CRYPTOR.decrypt(proxy.password))
        result, code = api.req_del(data)
        logger.info(u'删除多个资产result:%s' % result)
        if code == 200:
            for item in need_delete_asset:
                item.delete()
    except Exception as e:
        raise ServerError(e)
    finally:
        g_lock.release()
コード例 #36
0
ファイル: views.py プロジェクト: yunyun1/MagicStack
def log_kill(request):
    """ 杀掉connect进程 """
    response = {'success':'true', 'error':''}
    log_id = request.POST.get('log_id')
    log = Log.objects.get(id=log_id)
    if log:
        proxy_name = log.proxy_name
        proxy = Proxy.objects.get(proxy_name=proxy_name)
        proxy_log_id = log.proxy_log_id
        api = APIRequest('{0}/v1.0/ws/terminal/kill/?id={1}'.format(proxy.url, proxy_log_id), proxy.username, CRYPTOR.decrypt(proxy.password))
        result, codes = api.req_get()
        if codes == 200:
            time.sleep(3)
        else:
            log.is_finished = 1
            log.save()
        response['error'] = u'断开[%s]连接成功'%log.host
        return HttpResponse(json.dumps(response), content_type='application/json')
    else:
        response['success'] = 'false'
        response['error'] = '没有此进程'
        return HttpResponseNotFound(u'没有此进程!')
コード例 #37
0
ファイル: views.py プロジェクト: yunyun1/MagicStack
def log_record_save(request):
    response = {'error':'', 'success': 'true'}
    if request.method == 'GET':
        asset_id = request.GET.get('asset_id', '')
        log_id = request.GET.get('log_id', '')
        asset = Asset.objects.get(id_unique=asset_id)
        proxy = asset.proxy
        try:
            api = APIRequest('{0}/v1.0/loginfo/{1}'.format(proxy.url, log_id), proxy.username, CRYPTOR.decrypt(proxy.password))
            result, codes = api.req_get()
            if 'data' in result.keys():
                log_data = result['data']
                username = User.objects.get(id=log_data['user_id']).username
                asset_ip = asset.networking.all()[0].ip_address
                loginfo = Log()
                loginfo.user = username
                loginfo.host = asset_ip
                loginfo.filename = '' if log_data['filename'] is None else log_data['filename']
                loginfo.is_finished = False
                loginfo.log_path = log_data['log_path']
                loginfo.login_type = log_data['login_type']
                loginfo.pid = 0
                loginfo.remote_ip = log_data['remote_ip']
                loginfo.start_time = log_data['start_time']
                loginfo.proxy_log_id = log_id
                loginfo.proxy_name = proxy.proxy_name
                loginfo.asset_id_unique = asset_id
                loginfo.save()
            else:
                response['error'] = u'从proxy获取日志信息失败'
                response['success'] = 'false'
        except Exception as e:
            logger.error(e)
            response['error'] = e
            response['success'] = 'false'
    else:
        time.sleep(3)
        try:
            asset_id = request.POST.get('asset_id', '')
            log_id = request.POST.get('log_id', '')
            asset = Asset.objects.get(id_unique=asset_id)
            proxy = asset.proxy
            api = APIRequest('{0}/v1.0/loginfo/{1}'.format(proxy.url, log_id), proxy.username, CRYPTOR.decrypt(proxy.password))
            result, codes = api.req_get()
            if 'data' in result.keys():
                log_data = result['data']
                loginfo = Log.objects.get(proxy_log_id=int(log_id), proxy_name=proxy.proxy_name)
                loginfo.is_finished = True if log_data['is_finished'] is None else log_data['is_finished']
                loginfo.end_time = log_data['end_time']
                loginfo.filename = '' if log_data['filename'] is None else log_data['filename']
                loginfo.save()
            else:
                response['error'] = u'从proxy获取日志信息失败'
                response['success'] = 'false'
        except Exception as e:
            response['error'] = e
            response['success'] = 'false'
            logger.error(e)
    return HttpResponse(json.dumps(response), content_type='application/json')
コード例 #38
0
 def push_sudo(self, role, sudo_uuids, proxy, web_username):
     """
     use template to render pushed sudoers file
     """
     self.run_action = 'async'
     self.run_type = 'playbook'
     data = {
         'resource': self.resource,
         'hosts': self.host_list,
         'sudo_uuids': sudo_uuids,
         'role_name': role.name,
         'role_uuid': role.uuid_id,
         'web_username': web_username,
         'run_action': self.run_action,
         'run_type': self.run_type,
         'isTemplate': True
     }
     data = json.dumps(data)
     api = APIRequest('{0}/v1.0/module'.format(proxy.url), proxy.username,
                      CRYPTOR.decrypt(proxy.password))
     result, code = api.req_post(data)
     return result
コード例 #39
0
ファイル: asset_api.py プロジェクト: AutoOps/MagicStack
def asset_operator(asset_list, status, username, proxy=None):
    """
    重启,关机,重装系统
    """
    g_lock = threading.Lock()
    try:
        g_lock.acquire()
        proxy_asset = Asset.objects.filter(proxy__proxy_name=proxy.proxy_name)
        need_delete_asset = set(asset_list) & set(proxy_asset)
        systems = [item.name for item in need_delete_asset]
        profile = asset_list[0].profile
        if status == 'rebuild':
            data = {
                'rebuild': 'true',
                'profile': profile,
                'systems': systems
            }
        else:
            data = {
                'power': status,
                'systems': systems
            }
        data = json.dumps(data)
        api = APIRequest('{0}/v1.0/system/action'.format(proxy.url), proxy.username, CRYPTOR.decrypt(proxy.password))
        result, codes = api.req_post(data)
        logger.debug(u"操作结果result:%s   codes:%s"%(result, codes))
        task = Task()
        task.task_name = result['task_name']
        task.username = username
        task.status = result['messege']
        task.start_time = datetime.datetime.now()
        task.url = '{0}/v1.0/system/action'.format(proxy.url)
        task.save()
        task_queue.put(dict(task_name=result['task_name'], task_user=username, task_proxy=proxy.proxy_name))
    except Exception as e:
        raise ServerError(e)
    finally:
        g_lock.release()
コード例 #40
0
ファイル: perm_api.py プロジェクト: yunyun1/MagicStack
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
コード例 #41
0
 def push_key(self, user, key_path, proxy, web_username):
     """
     push the ssh authorized key to target.
     """
     self.run_action = 'async'
     self.run_type = 'ad-hoc'
     module_args = 'user="******" key="{{ lookup("file", "%s") }}" state=present' % (
         user, key_path)
     data = {
         'mod_name': 'authorized_key',
         'resource': self.resource,
         'hosts': self.host_list,
         'mod_args': module_args,
         'role_name': user,
         'web_username': web_username,
         'run_action': self.run_action,
         'run_type': self.run_type,
         'isTemplate': self.isTemplate
     }
     data = json.dumps(data)
     api = APIRequest('{0}/v1.0/module'.format(proxy.url), proxy.username,
                      CRYPTOR.decrypt(proxy.password))
     result, code = api.req_post(data)
     return result
コード例 #42
0
def upload(request):
    if request.method == 'POST':
        # 上传到本地目录
        try:
            path = request.POST.get('path')
            proxy = request.POST.get('proxy')
            proxy_host = request.POST.getlist('proxy_host')
            # 上传到本地
            f = request.FILES['file']
            df = handle_uploaded_file(f)
            files = {'file': (f.name, open(df, 'rb'))}
            params = {'action': 'upload'}
            # 通过proxy处理文件
            proxy_obj = Proxy.objects.get(id=proxy)
            tnow = datetime.datetime.now()

            # 调用proxy接口,上传文件
            api = API('{0}/v1.0/upload'.format(proxy_obj.url), proxy_obj.username,
                      CRYPTOR.decrypt(proxy_obj.password))

            result, code = api.req_post(data=params, files=files)
            if code != 200:
                file = File(path=path, proxy=proxy_obj, create_time=tnow, status='01',
                            result="上传文件失败")
                file.save()
                raise ServerError(result['messege'])
                # 上传文件成功之后,调用proxy接口,进行文件上传任务
            hosts = []
            if not proxy_host:
                hosts = Asset.objects.all().filter(proxy=proxy_obj)
                if not hosts:
                    # 没有可执行主机
                    file = File(path=path, proxy=proxy_obj, create_time=tnow, status='01',
                                result="没有可执行主机")
                    file.save()
                    raise RuntimeError("没有可执行主机")

            else:
                for host_id in proxy_host:
                    hosts.append(Asset.objects.get(id=host_id))

            host_list = []
            resource = []
            params = {}
            trigger_kwargs = {}
            trigger_kwargs['year'] = tnow.year
            trigger_kwargs['month'] = tnow.month
            trigger_kwargs['day'] = tnow.day
            trigger_kwargs['hour'] = tnow.hour
            trigger_kwargs['minute'] = tnow.minute+1
            trigger_kwargs['second'] = tnow.second
            params['trigger_kwargs'] = trigger_kwargs
            params['task_name'] = 'ansible'
            task_kwargs = {}
            task_kwargs['module_name'] = 'copy'
            task_kwargs['module_args'] = 'src={0} dest={1}'.format(result.get('fp'), path)

            # 构建inventory 和 构建主机list
            for host in hosts:
                host_list.append(host.networking.all()[0].ip_address)
                tmp_d = dict()
                tmp_d['hostname'] = host.networking.all()[0].ip_address
                tmp_d['port'] = host.port
                tmp_d['username'] = host.username
                tmp_d['password'] = CRYPTOR.decrypt(host.password)
                # 用于前端确定选择的asset
                tmp_d['id'] = host.id
                resource.append(tmp_d)
            task_kwargs['host_list'] = host_list
            task_kwargs['resource'] = resource
            params['task_kwargs'] = task_kwargs
            # 调用proxy接口,创建任务
            api = APIRequest('{0}/v1.0/job'.format(proxy_obj.url), proxy_obj.username,
                             CRYPTOR.decrypt(proxy_obj.password))
            result, code = api.req_post(json.dumps(params))
            if code != 200:
                file = File(path=path, proxy=proxy_obj, create_time=tnow,
                            status='01', result="上传文件失败")
                file.save()
            else:
                file = File(path=path, proxy=proxy_obj, task_uuid=result['job']['job_id'],
                            create_time=tnow)
                file.save()
        except Exception, e:
            logger.error(traceback.format_exc())
        return HttpResponseRedirect(reverse('file_upload'))
コード例 #43
0
ファイル: views.py プロジェクト: AutoOps/MagicStack
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:
コード例 #44
0
ファイル: perm_api.py プロジェクト: yunyun1/MagicStack
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
コード例 #45
0
ファイル: views.py プロジェクト: AutoOps/MagicStack
def asset_add(request,res, *args):
    """
    Asset add view
    添加资产
    """
    response = {'success': False, 'error': ''}
    res['operator'] = u'添加资产'
    if request.method == 'POST':
        try:
            hostname = request.POST.get('name', '')
            if Asset.objects.filter(name=unicode(hostname)):
                error = u'该主机名 %s 已存在!' % hostname
                raise ServerError(error)

            name = request.POST.get('name')
            port = request.POST.get('port')
            username = request.POST.get('username')
            pwd = request.POST.get('password')
            hostname = request.POST.get('hostname', '')
            power_address = request.POST.get('power_address')
            power_username = request.POST.get('power_username')
            ency_password = request.POST.get('power_password')
            mac_address = request.POST.get('mac_address')
            ip_address = request.POST.get('ip_address')

            if '' in [name, port, username, pwd, hostname, power_address, power_username, ency_password, mac_address, ip_address]:
                raise ServerError(u'必要参数为空')

            timestamp = int(time.time())
            id_unique = name + '_'+ str(timestamp)
            fields = {
                "id_unique": id_unique,
                "name": request.POST.get('name'),
                "hostname": request.POST.get('hostname'),
                "profile": request.POST.get('profile'),
                "gateway": request.POST.get('gateway'),
                "power_type": request.POST.get('power_type'),
                "netboot_enabled": request.POST.get('is_enabled'),
                "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/'.format(pro_url), pro_username, CRYPTOR.decrypt(pro_password))
                result, codes = api.req_post(data)
            except Exception as e:
                res['flag'] = 'false'
                res['content'] = e.message
                response['error'] = e.message
            else:
                if codes == 200:
                    asset_info = Asset()
                    asset_info.id_unique = id_unique
                    asset_info.name = request.POST.get('name', '')
                    asset_info.profile = request.POST.get('profile', '')
                    asset_info.status = request.POST.get('status', '1')
                    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.product_serial = request.POST.get('sn', '')
                    asset_info.comment = request.POST.get('comment', '')
                    asset_info.proxy_id = int(request.POST.get('proxy', '1'))

                    nt_g = NetWorkingGlobal()
                    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()
                    asset_info.networking_g_id = nt_g.id

                    pm = PowerManage()
                    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()
                    asset_info.power_manage_id = pm.id

                    asset_info.proxy_id = int(request.POST.get('proxy', 1))
                    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 = NetWorking()
                    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()
                    asset_info.networking.add(net)

                    group_id = request.POST.getlist('group')
                    for item in group_id:
                        group = AssetGroup.objects.get(id=int(item))
                        asset_info.group.add(group)
                    asset_info.save()
                    res['content'] = u'创建主机成功'
                    response['success'] = True
                    response['error'] = result['messege']
                else:
                    res['flag'] = 'false'
                    res['content'] = u"创建机器失败:%s"%result['messege']
                    response['error'] = u"创建机器失败:%s"%result['messege']
        except ServerError as e:
            res['flag'] = 'false'
            res['content'] = e.message
            response['error'] = e.message

    return HttpResponse(json.dumps(response), content_type='application/json')
コード例 #46
0
ファイル: views.py プロジェクト: AutoOps/MagicStack
def adv_task_add(request, res, *args):
    if request.method == 'POST':
        param = {}
        # 触发器
        trigger_kwargs = request.POST.get('trigger')
        task_name = request.POST.get('task_type')
        task_content = request.POST.get('task_content') # 文件内容
        task_host = request.POST.getlist('task_host[]') # 前端上送list时
        proxy = request.POST.get('proxy')
        comment = request.POST.get('comment')
        try:
            # 构建trigger
            init_trigger = trigger_kwargs = json.loads(trigger_kwargs)
            start_date = trigger_kwargs.pop('start_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
            param['trigger_kwargs'] = trigger_kwargs

            hosts = []
            # 没有选中主机,则认为是全选,取选中proxy下的所有
            proxy_obj = Proxy.objects.get(id=proxy)
            param['task_name'] = task_name
            task_kwargs = {}

            if not task_host:
                hosts = Asset.objects.all().filter(proxy=proxy_obj)
                if not hosts:
                    # 没有可执行主机
                    raise ServerError("no exec host")
            else:
                for host_id in task_host:
                    hosts.append(Asset.objects.get(id=host_id))

            host_list = []
            resource = []
            # 构建inventory 和 构建主机list
            for host in hosts:
                host_list.append(host.networking.all()[0].ip_address)
                tmp_d = dict()
                tmp_d['hostname'] = host.networking.all()[0].ip_address
                tmp_d['port'] = host.port
                tmp_d['username'] = host.username
                tmp_d['password'] = CRYPTOR.decrypt(host.password)
                # 用于前端确定选择的asset
                tmp_d['id'] = host.id
                resource.append(tmp_d)
            task_kwargs['host_list'] = host_list
            task_kwargs['resource'] = resource
            task_kwargs['content'] = task_content
            param['task_kwargs'] = task_kwargs
            # 调用proxy接口,创建任务
            api = APIRequest('{0}/v1.0/job'.format(proxy_obj.url), proxy_obj.username,
                             CRYPTOR.decrypt(proxy_obj.password))
            result, code = api.req_post(json.dumps(param))
            if code != 200:
                raise ServerError(result['messege'])
            else:
                task = Task(task_type=task_name, task_proxy=proxy_obj, task_kwargs=json.dumps(task_kwargs),
                            trigger_kwargs=json.dumps(trigger_kwargs), channal='00', comment=comment,
                            task_uuid=result['job']['job_id'], create_time=datetime.now())
                task.save()
        except ServerError, e:
            error = e.message
            res['flag'] = False
            res['content'] = error
        except Exception, e:
            logger.error(traceback.format_exc())
            res['flag'] = False
            res['content'] = e[1]
コード例 #47
0
ファイル: views.py プロジェクト: AutoOps/MagicStack
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))