def v2_playbook_on_stats(self, stats):
        hosts = sorted(stats.processed.keys())
        summary = {}
        info = []
        for h in hosts:
            s = stats.summarize(h)
            summary[h] = s
        for i in summary:
            ok = "ok=%s".encode('utf-8') % (summary.get(i).get('ok'))
            changed = "changed=%s" % (summary.get(i).get("changed"))
            unreachable = "unreachable=%s" % (
                summary.get(i).get("unreachable"))
            failed = "failed=%s" % (summary.get(i).get("failures"))
            skipped = "skipped=%s" % (summary.get(i).get('skipped'))
            info.append([i, ok, changed, unreachable, failed, skipped])

        logger('运行结果:', logging.INFO)

        for infos in info:
            rabbit_producer("%s" % infos)
            logger("%s" % infos, logging.INFO)
        rabbit_producer('Error info')
        logger('错误信息', logging.INFO)

        for infos in self.fails:
            if infos in self.fails:
                rabbit_producer("%s" % infos)
                logger(LOG_INFO='%s' % infos, LOG_LEVEL=logging.INFO)
            else:
                logger("没有错误信息", logging.INFO)
        rabbit_producer("quit")
        save_db.save_logs_to_db()
 def v2_playbook_on_play_start(self, play):
     #记录正在执行的playbook
     self.playbook_on_play_start(play.name)
     self.playbook = play.name
     logger(LOG_INFO='Run Model :%s' % self.playbook,
            LOG_LEVEL=logging.INFO)
     rabbit_producer('Run Model :%s' % self.playbook)
Beispiel #3
0
def deploy(request,no_render=False):
    logger(request,logging.INFO)
    save_db.save_logs_to_db("User:%s Access deploy page" % request.user)
    page_name = "DeployMent"
    admin_class = admin_func().get('files')
    deployfunc = admin_func().get('deploylist').model.objects.values('id', 'name')
    model_name = admin_class.model._meta.verbose_name
    form = forms.create_dynamic_modelform(admin_class.model)
    if request.method == "POST":  # admin action
        action_func_name = request.POST.get('admin_action')
        action_func = getattr(admin_class, action_func_name)
        selected_obj_ids = request.POST.getlist("_selected_obj")
        selected_objs = admin_class.model.objects.filter(id__in=selected_obj_ids)
        action_res = action_func(request, selected_objs)
        if action_res:
            return action_res
        return redirect(request.path)
    else:
        form_obj = form()
        querysets, filter_conditions = get_filter_objs(request, admin_class)
        querysets, q_val = get_search_objs(request, querysets, admin_class)
        querysets, new_order_key, order_column, last_orderby_key = get_orderby_objs(request, querysets)
        paginator = Paginator(querysets, admin_class.list_per_page)  # Show 25 contacts per page
        page = request.GET.get('_page')
        try:
            querysets = paginator.page(page)
        except PageNotAnInteger:
            querysets = paginator.page(1)
        except EmptyPage:
            querysets = paginator.page(paginator.num_pages)

    if no_render:
        return locals()
    else:
        return render(request, 'cluster/deploy/deploy.html', locals())
 def v2_runner_on_ok(self, result):
     host = result._host.get_name()
     self.runner_on_ok(host, result._result)
     data = json.dumps({host: result._result}, indent=4)
     self.ok = data
     logger(LOG_INFO="ok %s" % host, LOG_LEVEL=logging.INFO)
     rabbit_producer("ok %s" % host)
Beispiel #5
0
def echo_logs(request):
    logger(request, logging.INFO)
    msg = request.websocket.wait()
    if msg == 'quit':
        run_mq = Rabbit_Consumer()
        run_mq.rabbit_close()
        request.websocket.close()
    elif msg == 'file':
        logs_name = request.GET.get('LogName')
        file = open(logs_name, 'r')
        for content in file.readlines():
            request.websocket.send(content.encode('utf-8'))
        file.close()
        request.websocket.close()
    elif msg == 'logs':
        admin_class = admin_func().get('deploylist')
        log_name = admin_class.model.objects.all().values('name').order_by('-id')[0]['name']
        file = open(log_name,'r')
        for content in file.readlines():
            request.websocket.send(content.encode('utf-8'))
        file.close()
        request.websocket.close()

    else:
        run_mq = Rabbit_Consumer()
        run_mq.rabbit_consumer(request)
Beispiel #6
0
def deploy_delfile(request):
    admin_class = admin_func().get('deploylist')
    if request.method == 'GET':
        for get_id in request.GET.get('idAll').split(','):
            obj = admin_class.model.objects.get(id=get_id)
            filefunc = admin_class.model.objects.values('file_name', 'file_path', 'create_date').get(id=get_id)
            file_name = "%s%s-%s" % (filefunc['file_path'],
                                     filefunc['file_name'], filefunc['create_date'].strftime("%Y-%m-%d_%H:%M:%S"))

            delete_file(file_name)
            obj.delete()
            save_db.save_logs_to_db("User:%s Delete file:%s" % (request.user, file_name))
            logger('用户删除文件:%s' % (file_name), logging.INFO)
        return redirect('/deployment/')
    elif request.method == 'POST':
        try:
            for get_id in request.GET.get('idAll').split(','):
                obj = admin_class.model.objects.get(id=get_id)
                filefunc = admin_class.model.objects.values('name').get(id=get_id)
                file_name = "%s" % (filefunc['name'])
                delete_file(file_name)
                obj.delete()
                save_db.save_logs_to_db("User:%s Delete file:%s" % (request.user, file_name))
            return HttpResponse(json.dumps({"status": 'true'}))
        except ValueError:
            pass
        return HttpResponse(json.dumps({"status": 'true'}))
 def v2_runner_on_failed(self, result, ignore_errors=False):
     #执行失败的playbook日志
     host = result._host.get_name()
     self.runner_on_failed(host, result._result, ignore_errors)
     data = json.dumps({host: result._result}, indent=4)
     self.fail = data
     logger(LOG_INFO='Run Fails:%s' % host, LOG_LEVEL=logging.ERROR)
     self.fails.append(['Run Fails:%s' % data])
 def v2_runner_on_unreachable(self, result):
     #未能连接到playbook的日志
     host = result._host.get_name()
     self.runner_on_unreachable(host, result._result)
     data = json.dumps({host: result._result}, indent=4)
     self.unreachable = data
     self.fails.append('Connect to host fails: %s' % self.unreachable)
     logger(LOG_INFO='Connect to host fails: %s' % self.unreachable,
            LOG_LEVEL=logging.INFO)
     rabbit_producer('Connect to host fails: %s' % self.unreachable)
Beispiel #9
0
def template_delete(request):
    logger(request, logging.INFO)
    admin_class = admin_func().get('filetype')
    for get_id in request.GET.get('idAll').split(','):
        obj = admin_class.model.objects.get(id=get_id)
        name = get_db.get_field(admin_class=admin_class, id=get_id)
        obj.delete()
        logger('删除成功', logging.INFO)
        save_db.save_logs_to_db("User:%s Delete template_type:%s success" % (request.user, name))
    return redirect('/deployment/file_types/')
Beispiel #10
0
def del_settings(request):
    logger('%s' % request, logging.INFO)
    ret = {'status': 'true', 'error': 'false'}
    try:
        if request.method == 'POST':
            admin_class = admin_func().get('settings')
            for get_id in request.GET.get('idAll').split(','):
                obj = admin_class.model.objects.get(id=get_id)
                obj.delete()
                save_db.save_logs_to_db("User:%s Delete system config" % (request.user))
                logger('删除成功', logging.INFO)
            return HttpResponse(json.dumps(ret))
    except ValueError:
        pass
    return HttpResponse(json.dumps(ret))
Beispiel #11
0
def template_del(request):
    logger('%s' %request, logging.INFO)
    ret = {'status': 'true', 'error': 'false'}
    try:
        if request.method =='POST':
            admin_class = admin_func().get('filetype')
            for get_id in request.GET.get('idAll').split(','):
                obj = admin_class.model.objects.get(id=get_id)
                name = get_db.get_field(admin_class=admin_class,id=get_id)
                obj.delete()
                save_db.save_logs_to_db("User:%s Delete template_type:%s success" % (request.user, name))
                logger('删除成功', logging.INFO)
            return HttpResponse(json.dumps(ret))
    except ValueError:
        pass
    return HttpResponse(json.dumps(ret))
Beispiel #12
0
def upload(request):
    logger('%s' % (request), logging.INFO)
    ret = {'status':'true'}
    if request.method == 'POST':
        filename = request.FILES.get('filename')
        filetype = request.GET.get('file_type')
        logger('用户上传文件:%s' %filename, logging.INFO)
        logger('用户上传文件类型:%s' %filetype, logging.INFO)
        if save_file(filename=filename,filetype=filetype):
            logger('保存成功', logging.INFO)
            save_db.save_logs_to_db("User:%s Upload file:%s success" % (request.user, filename))
            return HttpResponse(json.dumps(ret))
        save_db.save_logs_to_db("User:%s Upload file:%s faild,Reason use GET request" % (request.user, filename))
        logger('保存失败', logging.INFO)
        ret.update({'status':'false','error': 'true'})
        return HttpResponse(json.dumps(ret))
Beispiel #13
0
def template(request,no_render=False):
    save_db.save_logs_to_db("User:%s Access template page" % (request.user))
    logger(request, logging.INFO)
    admin_class = admin_func().get('filetype')
    model_name = admin_class.model._meta.verbose_name
    form = forms.create_dynamic_modelform(admin_class.model)
    if request.method == 'POST':
        form_obj = form(data=request.POST)
        logger('用户增加文件类型:%s' %form_obj, logging.INFO)
        if form_obj.is_valid():
            logger('保存成功', logging.INFO)
            save_db.save_logs_to_db("User:%s Add new templay_type:%s success" % (request.user, request.POST.get('name')))
            form_obj.save()
            return redirect('/deployment/file_types/' ,locals())
    else:
        form_obj = form()
        querysets, filter_conditions = get_filter_objs(request, admin_class)
        querysets, q_val = get_search_objs(request, querysets, admin_class)
        querysets, new_order_key, order_column, last_orderby_key = get_orderby_objs(request, querysets)
        paginator = Paginator(querysets, admin_class.list_per_page)  # Show 25 contacts per page
        page = request.GET.get('_page')
        try:
            querysets = paginator.page(page)
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            querysets = paginator.page(1)
        except EmptyPage:
            # If page is out of range (e.g. 9999), deliver last page of results.
            querysets = paginator.page(paginator.num_pages)

    if no_render:  # 被其它函数调用,只返回数据
        return locals()
    else:
        return render(request, 'cluster/deploy/template.html', locals())
 def exec_playbook(self, playbooks):
     if not os.path.exists(playbooks[0]):
         code = 1000
         complex = {
             "playbook": playbooks,
             'msg': playbooks + "playbook does not exist",
             'flag': False
         }
         simple = 'playbook does not exist about' + playbooks
         return code, complex, simple
     results_callback = AnsibleTaskResultCallback()
     playbook = PlaybookExecutor(playbooks=playbooks,
                                 inventory=self.inventory,
                                 variable_manager=self.variable_manager,
                                 loader=self.loader,
                                 options=self.options,
                                 passwords=self.passwords)
     setattr(getattr(playbook, '_tqm'), '_stdout_callback',
             results_callback)
     try:
         playbook.run()
     except AnsibleParserError as e:
         logger(LOG_INFO='Error: %s' % e, LOG_LEVEL=logging.ERROR)
         rabbit_producer('Error: %s' % e)
    def v2_playbook_on_task_start(self, task, is_conditional):

        logger(LOG_INFO=task, LOG_LEVEL=logging.INFO)
        rabbit_producer("%s" % task)
 def v2_playbook_on_no_hosts_matched(self):
     #未能匹配到任何playbook, 不执行任何操作
     self.playbook_on_no_hosts_matched()
     self.no_host = True
     logger(LOG_INFO="No_Host:%s" % self.no_host, LOG_LEVEL=logging.WARNING)