Пример #1
0
def saltkey_list(request):
    '''
    @note: 从数据库中删除已经存入的API信息
    '''
    data = []
    [data.append(i.to_json()) for i in SaltKey.objects.all()]

    if request.method == "POST":
        if len(ApiMg.objects.filter(app_name='saltstack')) == 0:
            result = {"result": False, "message": u'请确保api信息已录入!'}
            return render_json(result)
        else:
            try:
                client = SaltApi('saltstack')
                params = {'client': 'wheel', 'fun': 'key.list_all'}
                json_data = dict(
                    json.loads(client.saltCmd(
                        params=params))['return'][0])['data']['return']
                # 已经认证的key入库,并将状态设置为Online
                for key_name in json_data["minions"]:
                    salt_key = SaltKey(key_name=key_name, key_status='Online')
                    salt_key.save()
                # 未认证的key入库,并将状态设置为Offline
                for key_name in json_data["minions_pre"]:
                    salt_key = SaltKey(key_name=key_name, key_status='Offline')
                    salt_key.save()
                result = {'result': True, 'message': u"刷新列表成功."}
            except Exception, e:
                logger.error(u"刷新salt-key列表失败,%s" % e)
                result = {'result': False, 'message': u"刷新列表失败,%s" % e}
            return render_json(result)
Пример #2
0
def online_maintain(request):
    task_name = {
        1: u'全服停服',
        2: u'IOS停服',
        3: u'安卓停服',
        4: u'缓存清理',
        5: u'配置发布',
        6: u'代码拉取',
        7: u'全服开服',
        8: u'IOS开服',
        9: u'安卓开服',
    }
    if request.method == 'POST':

        task_id = request.GET.get('task_id')

        for k, v in task_name.items():

            if int(k) == int(task_id):
                print '你将执行的操作是: ', v
                try:
                    client = SaltApi('saltstack')
                    deploy_parmas = {
                        'client': 'local_async',
                        'fun': 'cmd.run',
                        'tgt': '*',
                        'arg': 'sh /root/a.sh'
                    }
                    jid = dict(
                        json.loads(client.saltCmd(
                            params=deploy_parmas))['return'][0]).values()[0]

                    # 入库
                    mattask = MatTask(mattask_name=v,
                                      mattask_user=request.user,
                                      mattask_jid=jid)
                    mattask.save()

                    result = {
                        'result': True,
                        'message': u'{0} 任务已经下发,后台执行中...'.format(v)
                    }
                    return render_json(result)
                except Exception, e:
                    result = {
                        'result': False,
                        'message': u'{0} 执行失败\n{1}'.format(v, e)
                    }
                    return render_json(result)
Пример #3
0
def salt_minion_test(request):
    '''
    @note: 单台salt-minion测试连通性
    '''
    salt_key = request.GET.get('saltkey')
    try:
        client = SaltApi('saltstack')
        params = {'client': 'local', 'fun': 'test.ping', 'tgt': salt_key}
        json_data = dict(json.loads(
            client.saltCmd(params=params)))['return'][0]
        res = json_data[salt_key]
        if res:
            result = {
                'result': res,
                'message': u"该Salt-minion连接正常\n%s" % str(salt_key)
            }
            return render_json(result)
    except Exception, e:
        logger.error(u"该Salt-minion连接异常\n%s," % e)
        result = {'result': False, 'message': u"该Salt-minion连接异常\n%s," % e}
        return render_json(result)
Пример #4
0
def soft_deploy(request):
    '''
    @note: 应用部署
    '''
    # 获取所有主机
    host_list = Hostinfo.objects.all()
    all_host = []
    [all_host.append(i.to_json()['hostname']) for i in host_list]

    # 定义state
    soft = ["nginx", "zabbix_client", "redis", "Mongodb"]

    if request.method == "POST":
        data = dict(request.POST)
        # 主机列表
        host_list = []
        [
            host_list.append(each_host)
            for each_host in list(data['host_arr'])[0].split(',')
        ]

        # 软件列表
        soft_list = []
        [
            soft_list.append(each_soft)
            for each_soft in list(data['soft_arr'])[0].split(',')
        ]

        deploy_info = []

        sum = 0
        client = SaltApi('saltstack')
        for each_host in host_list:
            for each_soft in soft_list:
                sum += 1
                deploy_parmas = {
                    'client': 'local_async',
                    'fun': 'state.sls',
                    'tgt': each_host,
                    'arg': each_soft
                }
                jid = dict(
                    json.loads(client.saltCmd(
                        params=deploy_parmas))['return'][0]).values()[0]
                deploy_info.append({
                    "msg": "%s ==>> %s" % (each_host, each_soft),
                    "id": sum,
                    "job_id": jid
                })
                # 部署信息入库
                deploy_log = DeployLog(deploy_app=each_soft,
                                       deploy_target=each_host,
                                       deploy_time=int(time.time()),
                                       deploy_user=request.user,
                                       deploy_jid=jid)
                deploy_log.save()
        result = {"result": True, "data": deploy_info}
        #print deploy_info
        return render_json(result)
    return render_mako_context(
        request, '/home_application/opsplatform/soft_deploy.html', {
            "all_host": all_host,
            "soft": soft
        })
Пример #5
0
def salt_cmd(request):
    '''
    @note: 选择一台server只有执行salt命令; 此函数只能针对一台server进行操作
    '''
    hostname = request.GET.get('hostname', '')
    if request.method == 'POST':  # 如何接收ajax post 过来的josn数据...
        data = dict(request.POST)
        # 获取web端输入的命令
        run_cmd = data["cmd"][0]
        cmd = run_cmd.replace(" ", " ")
        # 命令黑名单
        black_cmd = [
            'date', 'echo', 'rm -rf /', 'shutdown', 'poweroff', 'reboot'
        ]
        for s in black_cmd:

            if cmd in s:
                result = {"result": False, "message": u'禁止在此平台运行该命令'}
                return render_json(result)
        # 获取主机名
        hostname = data["hostname"][0]

        cmd_params = {
            'client': 'local',
            'fun': 'cmd.run',
            'tgt': '%s' % hostname,
            'arg': '%s' % cmd
        }
        try:
            client = SaltApi('saltstack')
            t = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
            result_data = dict(
                dict(json.loads(
                    client.saltCmd(cmd_params)))['return'][0]).values()[0]
            #result_data = dict(json.loads(client.saltCmd(cmd_params)))
            print result_data

            for i in check_result():
                if i in result_data:
                    result = {
                        "result": False,
                        "message": u'执行失败,{0}'.format(i)
                    }
                    return render_json(result)
                else:
                    runcmd_log = RuncmdLog(runcmd_target=hostname,
                                           runcmd_cmd=cmd,
                                           runcmd_user=request.user,
                                           runcmd_result=result_data)
                    runcmd_log.save()
                    result = {
                        "result": True,
                        "data": result_data,
                        "run_time": t,
                        "message": u'执行成功'
                    }
                    return render_json(result)
        except Exception, e:
            logger.info('执行失败')
            result = {"result": False, "message": u'执行失败.{0}'.format(e)}
            print e
            return render_json(result)