Example #1
0
def restart_service(request):
    task_id = request.POST.get('id')
    server_name = request.POST.get('server_name')
    commands_obj = ServerInfo.objects.filter(id=task_id)
    task_list = Runner.Task(name=server_name,
                            module_name='shell',
                            module_args='/root/test/didid.sh')
    runner = Runner(task_list=task_list,
                    host_list=[commands_obj[0].InnerIpAddress])
    ret_info = runner.run()
    host_ip = []
    host_status = []
    host_msg = []
    host_name = [request.POST.get('host_name')]
    for i in ret_info[1].values():
        print('i#', i)
        for k, v in i.items():
            host_ip.append(k)
            host_status.append(v['status'])
            if host_status[0] == 'ok':
                host_msg = ['successful~']
            else:
                host_msg.append(v['result']['msg'])
    # return render(request, 'cmdb/cmdb_phone.html', locals())
    return JsonResponse({
        'status': host_status,
        'hostname': host_name,
        'message': host_msg
    })
Example #2
0
def run_job(job_id='', account='', run_type=0):
    """
    运行作业多个任务
    :param job_id: 作业ID
    :param account: 执行人
    :param run_type: 执行类型(默认为0 网页执行)。(1 crontab执行)
    :return:
    """
    job = Job.objects.get(id=job_id)
    tasks = job.task_id.split(',')
    job.current_task = tasks[0]
    job.status = 0
    job.save()

    start_time = datetime.datetime.utcnow()
    task_list = []
    try:
        for task in tasks:
            # job.current_task = task
            # job.save()
            print("task", task)
            print("--------------------------------------------")
            task_rs_obj = RunScript.objects.filter(id=task)  # 执行结果为一个列表
            task_ft_obj = FileTransfer.objects.filter(id=task)  # 执行结果为一个列表
            # 如果是执行脚本
            if task_rs_obj:  # 如果列表不为空,则为执行脚本的任务
                task_list.append(gen_runscript_task(task))
            # 如果是分发文件
            if task_ft_obj:  # 如果列表不为空,则为分发文件的任务
                _tmp_task = gen_filetransfer_task(task)
                if isinstance(_tmp_task, list):
                    task_list.extend(_tmp_task)
                else:
                    task_list.append(_tmp_task)
        inv = [
            si.ansible_host
            for si in ServerInfo.objects.filter(id__in=job.server.split(','))
        ]
        runner = Runner(task_list=task_list, host_list=inv)
        code, res = runner.run(callback=FileTransferResultsCollector(
            jobid=job_id))
        end_time = datetime.datetime.utcnow()
        total_time = (end_time - start_time).total_seconds()
        TaskRecord(account=account,
                   task_id=str(job.id),
                   start_time=start_time,
                   end_time=end_time,
                   total_time=total_time,
                   run_type=run_type,
                   task_type='job').save()
        job.current_task = ''
        job.status = 1
        job.save()
    except Exception as e:
        traceback.print_exc()
Example #3
0
def gen_filetransfer_task(task_id):
    """
    生成分发文件的Task列表
    :param task_id: 任务ID
    :return: Runner.Task对象的列表
    """
    ft_obj = FileTransfer.objects.filter(id=task_id)
    f_path = ft_obj[0].files_path
    dest = ft_obj[0].dest_path
    li_f_path = f_path.split('||')
    task_list = []
    for file_path in li_f_path:
        sub_task_name = ft_obj[0].name + ' -> ' + (
            file_path[file_path.rfind('/') +
                      1:] if file_path.rfind('/') >= 0 else file_path)
        task_list.append(
            Runner.Task(name=sub_task_name,
                        module_name='copy',
                        module_args={
                            "src": file_path,
                            "dest": dest
                        },
                        _id=task_id,
                        super_task_name=ft_obj[0].name))
    return task_list
Example #4
0
def gen_runscript_task(task_id):
    """
    生成执行脚本的Task任务
    :param task_id: 任务ID
    :param server_list: 服务器列表
    :return: Runner.Task对象
    """
    commands_obj = RunScript.objects.filter(id=task_id)
    commands_from_mysql = commands_obj[0].script_content
    file_path = save_tmp_script(commands_from_mysql)

    return Runner.Task(name=commands_obj[0].name, module_name='script', module_args=file_path)
Example #5
0
def run_task(inventory, module_name='command', module_args='', pattern='all'):
    """
    运行ansible单个任务
    :param inventory: 主机列表。格式:{'section1':['ip1', 'ip2',...], 'section2':[...]}
    :param pattern: 主机列表名
    :param module_name: 模块名
    :param module_args: 模块参数
    :return: task运行结果
    """
    if not inventory:
        raise Exception("No host selected!")
    task_name = 'default_task'
    task_list = [Runner.Task(task_name, module_name, module_args)]

    # 定义playbook对象
    p2 = Runner.Playbook(task_list=task_list)

    # 执行playbook
    runner = Runner(playbook=p2, host_list=inventory, pattern=pattern)
    # 执行单个任务或多个任务
    code, result = runner.run()
    # print(result)
    return result[task_name]
Example #6
0
def filetransfer(request):
    if request.method == "GET":
        ft_name = create_name('分发文件')
        srv_param = request.GET.get("server", None)
        if srv_param:
            server_ids = srv_param.split(',')
            srvs = ServerInfo.objects.filter(id__in=server_ids)
            servers = [srv.to_dict() for srv in srvs]
        return render(request, 'operating/filetransfer.html', locals())

    tasks = []
    form = FileTransferForm(request.POST)
    if form.is_valid():
        try:
            ft_name = create_name('分发文件')
            data = form.cleaned_data
            print(data)
            srvs = [
                ServerInfo.objects.get(id=i).ansible_host
                for i in data['server_ids']
            ]
            print(srvs)
            ft = FileTransfer(name=ft_name,
                              user=data['user'],
                              files_path='||'.join(data['file_path']),
                              dest_path=data['dest'],
                              server=','.join(data['server_ids']))
            ft.save()
            start_time = datetime.datetime.utcnow()
            tr = TaskRecord(account=request.user.username,
                            start_time=start_time,
                            task_id=ft.id,
                            task_type='filetransfer')
            tr.save()

            task_list = [
                Runner.Task(name='be sure libselinux-python are installed',
                            module_name='yum',
                            module_args={
                                'name': 'libselinux-python',
                                'state': 'present'
                            })
            ]
            for fp in data['file_path']:
                task_list.append(
                    Runner.Task(name='copy file ' + fp,
                                module_name='copy',
                                module_args={
                                    'src': fp,
                                    'dest': data['dest']
                                }))
            # pb = Runner.Playbook(task_list=task_list)
            rc, result = Runner(host_list=srvs, task_list=task_list).run()
            tr.result, flag = analyze_filetransfer_result(result)
            tr.result = json.dumps(tr.result)
            ft.status = 1 if flag else 2
            ft.save()
            tr.end_time = datetime.datetime.utcnow()
            tr.total_time = (tr.end_time - start_time).total_seconds()
            tr.save()
            return JsonResponse({
                'result': True,
                'message': '执行完毕',
                'data': tr.to_dict()
            })
        except Exception as e:
            traceback.print_exc()
            log.error(traceback.format_exc())
    else:
        print("验证失败")
        print(form.errors)