Exemple #1
0
def execute_action_form(request, agent, action, filters, dialog_name, response_container, xhr=None):
    if request.method == "POST":
        inputs = get_action_inputs(agent, action)
        logger.debug("Recreating form")
        form_type = create_action_form(inputs)
        form = form_type(request.POST)

        #Check if the <xhr> var had something passed to it.
        if xhr == "xhr":
            # Yup, this is an Ajax request.
            # Validate the form:
            clean = form.is_valid()
            # Make some dicts to get passed back to the browser
            rdict = {'bad':'false', 'agent':agent, 'action':action, 'dialog_name':dialog_name, 'response_container':response_container, 'filters':filters }
            if not clean:
                rdict.update({'bad':'true'})
                d = {}
                # This was painful, but I can't find a better way to extract the error messages:
                for e in form.errors.iteritems():
                    d.update({e[0]:unicode(e[1])}) # e[0] is the id, unicode(e[1]) is the error HTML.
                # Bung all that into the dict
                rdict.update({'errs': d })
                # Make a json whatsit to send back.
                json_data = json.dumps(rdict, ensure_ascii=False)
            else:
                logger.debug("Parameters check: OK.")
                logger.debug("Creating args")
                arguments=None
                for input in inputs:
                    if form.cleaned_data[input['name']]:
                        if arguments:
                            arguments = arguments + ';'
                        else:
                            arguments = ''
                        arguments = arguments + input['name'] + '=' + form.cleaned_data[input['name']] 
                
                logger.debug("Arguments for MCollective call %s" % arguments)
                wait_for_response = False
                response, content = callRestServer(request.user, filters, agent, action, arguments, wait_for_response)
                #Leave wait for response check it to support both two in the future (read wait_for_response from config file)
                if wait_for_response:
                    if response.getStatus() == 200:
                        json_data = render_agent_template(request, rdict, content, form.cleaned_data, agent, action)
                        return HttpResponse(json_data, mimetype='application/javascript')
                    else:
                        rdict.update({"result": "KO", "message": "Error communicating with server. <br> %s"%content})
                else: 
                    logger.debug("Returning request UUID")
                    update_url = reverse('get_progress', kwargs={'taskname':content, 'taskid':response.task_id})
                    rdict.update({"UUID": response.task_id, "taskname": content, 'update_url': update_url})
             
            return HttpResponse(json.dumps(rdict, ensure_ascii=False), mimetype='application/javascript')
        else:
            if form.is_valid():
                logger.error("Trying to execute a NON Ajax call. Rejected and redirected to DashBoard.")
                return HttpResponseRedirect(settings.BASE_URL)
    else:
        # It's not post so make a new form
        logger.warn("Cannot access this page using GET")
        raise Http404
Exemple #2
0
def execute_action_form(request, agent, action, filters, dialog_name, response_container, xhr=None):
    if request.method == "POST":
        inputs = get_action_inputs(agent, action)
        logger.debug("Recreating form")
        form_type = create_action_form(inputs)
        form = form_type(request.POST)

        #Check if the <xhr> var had something passed to it.
        if xhr == "xhr":
            # Yup, this is an Ajax request.
            # Validate the form:
            clean = form.is_valid()
            # Make some dicts to get passed back to the browser
            rdict = {'bad':'false', 'agent':agent, 'action':action, 'dialog_name':dialog_name, 'response_container':response_container, 'filters':filters }
            if not clean:
                rdict.update({'bad':'true'})
                d = {}
                # This was painful, but I can't find a better way to extract the error messages:
                for e in form.errors.iteritems():
                    d.update({e[0]:unicode(e[1])}) # e[0] is the id, unicode(e[1]) is the error HTML.
                # Bung all that into the dict
                rdict.update({'errs': d })
                # Make a json whatsit to send back.
                json_data = json.dumps(rdict, ensure_ascii=False)
            else:
                logger.debug("Parameters check: OK.")
                logger.debug("Creating args")
                arguments=None
                for input in inputs:
                    if form.cleaned_data[input['name']]:
                        if arguments:
                            arguments = arguments + ';'
                        else:
                            arguments = ''
                        arguments = arguments + input['name'] + '=' + form.cleaned_data[input['name']] 
                
                logger.debug("Arguments for MCollective call %s" % arguments)
                wait_for_response = False
                response, content = callRestServer(request.user, filters, agent, action, arguments, wait_for_response)
                #Leave wait for response check it to support both two in the future (read wait_for_response from config file)
                if wait_for_response:
                    if response.status == 200:
                        json_data = render_agent_template(request, rdict, content, form.cleaned_data, agent, action)
                        return HttpResponse(json_data, mimetype='application/javascript')
                    else:
                        rdict.update({"result": "KO", "message": "Error communicating with server. <br> %s"%content})
                else: 
                    logger.debug("Returning request UUID")
                    update_url = reverse('get_progress', kwargs={'taskname':content, 'taskid':response.task_id})
                    rdict.update({"UUID": response.task_id, "taskname": content, 'update_url': update_url})
             
            return HttpResponse(json.dumps(rdict, ensure_ascii=False), mimetype='application/javascript')
        else:
            if form.is_valid():
                logger.error("Trying to execute a NON Ajax call. Rejected and redirected to DashBoard.")
                return HttpResponseRedirect(settings.BASE_URL)
    else:
        # It's not post so make a new form
        logger.warn("Cannot access this page using GET")
        raise Http404
Exemple #3
0
def get_progress(request, taskname, taskid):
    logger.info("Requesting taskid: %s"%taskid)
    result = AsyncResult(taskid, backend=None, task_name=taskname)
    logger.info("TASKID: %s"%result.task_id)
    
    dict = {}
    if (result.state == 'PENDING'):
        dict['state'] = 'Waiting for worker to execute task...'
    elif (result.state == 'PROGRESS'):
        dict['state'] = 'Operation in progress..'
    else:
        dict['state'] = result.state
    if result.result:
        if isinstance(result.result, tuple):
            response,content,agent,action=result.result
            if response.status == 200:
                json_data = render_agent_template(request, {}, content, {}, agent, action)
                return HttpResponse(json_data, mimetype="application/json")
            elif response.status == 408:
                dict['state'] = 'FAILURE'
                dict['message'] = 'TIMEOUT'
        else:
            if "current" in result.result and "total" in result.result:
                value = float(1.0*result.result['current']/result.result['total'])*100
                dict['value'] = value
            else:
                dict.update({"responsecontent": result.result})
    else: 
        dict['value'] = 0
    json_data = json.dumps(dict)
    return HttpResponse(json_data, mimetype="application/json")
Exemple #4
0
def get(request, wait_for_response=False):
    if request.method != "POST":
        return HttpResponseForbidden()

    agent = request.POST["agent"]
    action = request.POST["action"]
    filters = request.POST["filters"]
    if request.POST["parameters"]:
        args = request.POST["parameters"]
        
    #Fix for unicode wait_for_response variable (actually used in url only for Virtualization Platform)
    if wait_for_response == "false" or wait_for_response == "False":
        wait_for_response = False
    elif wait_for_response == "true" or wait_for_response == "True":
        wait_for_response = True
        
    if verify_agent_acl(request.user, agent) and verify_action_acl(request.user, agent, action):
        response, content = callRestServer(request.user, filters, agent, action, args, wait_for_response)
        if wait_for_response:
            if response.getStatus() == 200:
                json_data = render_agent_template(request, {}, content, {}, agent, action)
                return HttpResponse(json_data, mimetype="application/json")
        else:
            logger.debug("Returning request UUID")
            update_url = reverse('get_progress', kwargs={'taskname':content, 'taskid':response.task_id})
            json_data = json.dumps({"UUID": response.task_id, "taskname": content, 'update_url': update_url})
            return HttpResponse(json_data, mimetype="application/json")
    else:
        return HttpResponseForbidden()
Exemple #5
0
def get(request, filters, agent, action, args=None):
    if verify_agent_acl(request.user, agent) and verify_action_acl(request.user, agent, action):
        response, content = callRestServer(request.user, filters, agent, action, args)
        if response.status == 200:
            json_data = render_agent_template(request, {}, content, {}, agent, action)
            return HttpResponse(json_data, mimetype="application/json")
        return response
    else:
        return HttpResponseForbidden()
Exemple #6
0
def get(request, filters, agent, action, args=None):
    if verify_agent_acl(request.user, agent) and verify_action_acl(
            request.user, agent, action):
        response, content = callRestServer(request.user, filters, agent,
                                           action, args)
        if response.status == 200:
            json_data = render_agent_template(request, {}, content, {}, agent,
                                              action)
            return HttpResponse(json_data, mimetype="application/json")
        return response
    else:
        return HttpResponseForbidden()
Exemple #7
0
def execute_action_form(request, agent, action, filters, dialog_name, response_container, xhr=None):
    if request.method == "POST":
        inputs = get_action_inputs(agent, action)
        logger.debug("Recreating form")
        form_type = create_action_form(inputs)
        form = form_type(request.POST)

        #Check if the <xhr> var had something passed to it.
        if xhr == "xhr":
            # Yup, this is an Ajax request.
            # Validate the form:
            clean = form.is_valid()
            # Make some dicts to get passed back to the browser
            rdict = {'bad':'false', 'agent':agent, 'action':action, 'dialog_name':dialog_name, 'response_container':response_container, 'filters':filters }
            if not clean:
                rdict.update({'bad':'true'})
                d = {}
                # This was painful, but I can't find a better way to extract the error messages:
                for e in form.errors.iteritems():
                    d.update({e[0]:unicode(e[1])}) # e[0] is the id, unicode(e[1]) is the error HTML.
                # Bung all that into the dict
                rdict.update({'errs': d })
                # Make a json whatsit to send back.
                json_data = json.dumps(rdict, ensure_ascii=False)
            else:
                logger.debug("Parameters check: OK.")
                logger.debug("Creating args")
                arguments=None
                for input in inputs:
                    if form.cleaned_data[input['name']]:
                        if arguments:
                            arguments = arguments + ';'
                        else:
                            arguments = ''
                        arguments = arguments + input['name'] + '=' + form.cleaned_data[input['name']] 
                
                logger.debug("Arguments for MCollective call " + arguments)
                response, content = callRestServer(request.user, filters, agent, action, arguments)
                if response.status == 200:
                    json_data = render_agent_template(request, rdict, content, form.cleaned_data, agent, action)
             
            # And send it off.
            return HttpResponse(json_data, mimetype='application/javascript')
        # It's a normal submit - non ajax.
        else:
            if form.is_valid():
                # We don't accept non-ajax requests for the moment
                return HttpResponseRedirect("/")
    else:
        # It's not post so make a new form
        logger.warn("Cannot access this page using GET")
        raise Http404
Exemple #8
0
def get(request, filters, agent, action, args=None, wait_for_response=False):
    if verify_agent_acl(request.user, agent) and verify_action_acl(request.user, agent, action):
        response, content = callRestServer(request.user, filters, agent, action, args, wait_for_response)
        if wait_for_response:
            if response.status == 200:
                json_data = render_agent_template(request, {}, content, {}, agent, action)
                return HttpResponse(json_data, mimetype="application/json")
        else:
            logger.debug("Returning request UUID")
            update_url = reverse('get_progress', kwargs={'taskname':content, 'taskid':response.task_id})
            json_data = json.dumps({"UUID": response.task_id, "taskname": content, 'update_url': update_url})
            return HttpResponse(json_data, mimetype="application/json")
    else:
        return HttpResponseForbidden()
Exemple #9
0
def get(request, wait_for_response=False):
    if request.method != "POST":
        return HttpResponseForbidden()

    agent = request.POST["agent"]
    action = request.POST["action"]
    filters = request.POST["filters"]
    if request.POST["parameters"]:
        args = request.POST["parameters"]

    #Fix for unicode wait_for_response variable (actually used in url only for Virtualization Platform)
    if wait_for_response == "false" or wait_for_response == "False":
        wait_for_response = False
    elif wait_for_response == "true" or wait_for_response == "True":
        wait_for_response = True

    if verify_agent_acl(request.user, agent) and verify_action_acl(
            request.user, agent, action):
        response, content = callRestServer(request.user, filters, agent,
                                           action, args, wait_for_response)
        if wait_for_response:
            if response.getStatus() == 200:
                json_data = render_agent_template(request, {}, content, {},
                                                  agent, action)
                return HttpResponse(json_data, mimetype="application/json")
        else:
            logger.debug("Returning request UUID")
            update_url = reverse('get_progress',
                                 kwargs={
                                     'taskname': content,
                                     'taskid': response.task_id
                                 })
            json_data = json.dumps({
                "UUID": response.task_id,
                "taskname": content,
                'update_url': update_url
            })
            return HttpResponse(json_data, mimetype="application/json")
    else:
        return HttpResponseForbidden()
Exemple #10
0
def execute_action_form(request, xhr=None):
    if request.method == "POST":
        agent=request.POST['agent']
        action=request.POST['action']
        filters=request.POST['filters']
        dialog_name=request.POST['execution_dialog_name']
        response_container=request.POST['response_container_name']
        inputs = get_inputs(agent, action, with_filters=(filters!=None and filters!='null'))
        logger.debug("Recreating form")
        form_type = create_action_form(inputs)
        form = form_type(request.POST)

        #Check if the <xhr> var had something passed to it.
        if xhr == "xhr":
            # Yup, this is an Ajax request.
            # Validate the form:
            clean = form.is_valid()
            # Make some dicts to get passed back to the browser
            rdict = {'bad':'false', 'agent':agent, 'action':action, 'dialog_name':dialog_name, 'response_container':response_container, 'filters':filters }
            if not clean:
                rdict.update({'bad':'true'})
                d = {}
                # This was painful, but I can't find a better way to extract the error messages:
                for e in form.errors.iteritems():
                    d.update({e[0]:unicode(e[1])}) # e[0] is the id, unicode(e[1]) is the error HTML.
                # Bung all that into the dict
                rdict.update({'errs': d })
                # Make a json whatsit to send back.
                json_data = json.dumps(rdict, ensure_ascii=False)
            else:
                logger.debug("Parameters check: OK.")
                logger.debug("Creating args")
                arguments=None
                action_inputs = get_action_inputs(agent, action)
                if action_inputs:
                    for input_data in action_inputs:
                        if form.cleaned_data[input_data['name']]:
                            if arguments:
                                arguments = "%;" % arguments
                            else:
                                arguments = ''
                            arguments = "%s%s=%s" % (arguments, input_data['name'], form.cleaned_data[input_data['name']]) 
                            
                if "identityfilter" in form.cleaned_data and form.cleaned_data["identityfilter"]:
                    logger.debug("Applying identity filter")
                    if filters and filters != "null":
                        filters = "%s;" % filters
                    else:
                        filters = ""
                    
                    id_filts = form.cleaned_data["identityfilter"].split(';')
                    for filt in id_filts:
                        if filters:
                            filters = "%s;" % filters
                        filters = "%sidentity=%s" % (filters, filt)
                        
                if "classfilter" in form.cleaned_data and form.cleaned_data["classfilter"]:
                    logger.debug("Applying class filter")
                    if filters and filters != "null":
                        filters = "%s;" % filters
                    else:
                        filters = ""
                    
                    id_filts = form.cleaned_data["classfilter"].split(';')
                    for filt in id_filts:
                        if filters:
                            filters = "%s;" % filters
                        filters = "%sclass=%s" % (filters, filt)
                
                if "compoundfilter" in form.cleaned_data and form.cleaned_data["compoundfilter"]:
                    logger.debug("Applying compound filter")
                    if filters and filters != "null":
                        filters = "%s;" % filters
                    else:
                        filters = ""
                    
                    filters = "%scompound=%s" % (filters, form.cleaned_data["compoundfilter"])
                
                if "limit" in form.cleaned_data and form.cleaned_data["limit"]:
                    limit = form.cleaned_data["limit"]
                else: 
                    limit = None
                use_backend_scheduler = form.cleaned_data["usesched"]
                    
                logger.debug("Arguments for MCollective call %s" % arguments)
                wait_for_response = False
                response, content = callRestServer(request.user, filters, agent, action, arguments, wait_for_response, use_backend_scheduler=use_backend_scheduler, limit=limit)
                #Leave wait for response check it to support both two in the future (read wait_for_response from config file)
                if wait_for_response:
                    if response.getStatus() == 200:
                        json_data = render_agent_template(request, rdict, content, form.cleaned_data, agent, action)
                        return HttpResponse(json_data, mimetype='application/javascript')
                    else:
                        rdict.update({"result": "KO", "message": "Error communicating with server. <br> %s"%content})
                else: 
                    logger.debug("Returning request UUID")
                    update_url = reverse('get_progress', kwargs={'taskname':content, 'taskid':response.task_id})
                    rdict.update({"UUID": response.task_id, "taskname": content, 'update_url': update_url})
             
            return HttpResponse(json.dumps(rdict, ensure_ascii=False), mimetype='application/javascript')
        else:
            if form.is_valid():
                logger.error("Trying to execute a NON Ajax call. Rejected and redirected to DashBoard.")
                return HttpResponseRedirect(settings.BASE_URL)
    else:
        # It's not post so make a new form
        logger.warn("Cannot access this page using GET")
        raise Http404