Ejemplo n.º 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)
Ejemplo n.º 2
0
def get_server_info(request):
    '''
    @note: 通过saltapi获取所有minion主机的服务器信息,填入写入数据库中
    '''
    # 获取所有server的hostname
    if request.method == "POST":
        client = SaltApi()
        params = {'client': 'local', 'fun': 'test.ping', 'tgt': '*'}
        json_data = client.get_allhostname(params)
        data = dict(json.loads(json_data)['return'][0])
        hostname_list = []
        [ hostname_list.append(i) for i in data.keys() ]
        
        # 获取所有server的hostname
        for host in hostname_list:

            all_host_info = dict(client.get_minions(host).items())
        
            try:
                host_record = Hostinfo(
                            hostname=all_host_info['hostname'],
                            private_ip=all_host_info['private_ip'],
                            public_ip=all_host_info['public_ip'],
                            mem_total=all_host_info['mem_total'],
                            cpu_type=all_host_info['cpu_type'],
                            num_cpus=all_host_info['num_cpus'],
                            os_release=all_host_info['os_release'],
                            kernelrelease=all_host_info['kernelrelease']
                            )
                host_record.save()
                print u'导入主机 %s 成功!' % all_host_info['hostname']
            except Exception,e:
                print e
Ejemplo n.º 3
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)
Ejemplo n.º 4
0
def get_jid_result(request):
    '''
    @note: 获取salt任务的执行结果
    '''
    job_id = request.GET.get('jid', '')

    client = SaltApi('saltstack')
    result = client.get_jid_result(job_id)

    fail_list = ['command not found', 'error']

    for i in fail_list:
        if i in result:

            #result = dict(json.loads(client.get_jid_result(job_id)))['info']  # salt_2016.11.1 新版本使用该语句
            # result = json.loads(client.get_jobs(JID))['return'][0]['data'] # salt_2015.5.10 老版本使用该语句
            return HttpResponse("执行失败!")
Ejemplo n.º 5
0
def salt_jid_result(request):
    '''
    @note: 获取salt任务的执行结果
    '''
    job_id = request.GET.get('jid', '')

    try:
        client = SaltApi('saltstack')
        result_data = dict(
            json.loads(client.get_jid_result(job_id))['info'][0])['Result']
        result = simplejson.dumps(result_data, sort_keys=True, indent='    ')
        return render_mako_context(
            request, '/home_application/opsplatform/salt_jid_result.html',
            {"result": result})
    except Exception, e:
        result = e
        return render_mako_context(
            request, '/home_application/opsplatform/salt_jid_result.html',
            {"result": result})
Ejemplo n.º 6
0
def get_server_info(request):
    '''
    @note: 通过saltapi获取所有minion主机的服务器信息,填入写入数据库中
    '''
    # 获取所有server的hostname
    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': 'local', 'fun': 'test.ping', 'tgt': '*'}
                json_data = client.get_allhostname(params)

                data = dict(json.loads(json_data)['return'][0])

                hostname_list = []

                [hostname_list.append(i) for i in data.keys()]

                for host in hostname_list:
                    if not Hostinfo.objects.filter(hostname=host):

                        all_host_info = dict(client.get_minions(host).items())
                        host_record = Hostinfo(
                            hostname=all_host_info['hostname'],
                            private_ip=all_host_info['private_ip'],
                            public_ip=all_host_info['public_ip'],
                            mem_total=all_host_info['mem_total'],
                            cpu_type=all_host_info['cpu_type'],
                            num_cpus=all_host_info['num_cpus'],
                            os_release=all_host_info['os_release'],
                            kernelrelease=all_host_info['kernelrelease'])

                        host_record.save()

                result = {"result": True, "message": u'刷新完毕!'}
                return render_json(result)

            except Exception, e:
                result = {"result": False, "message": u'刷新出错!'}
                return render_json(result)
Ejemplo n.º 7
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)
Ejemplo n.º 8
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
        })
Ejemplo n.º 9
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)