def delete_clients():
    """
        Description : View function to delete the clients
    
    """
    url = settings.BASE_URL + "/" 
    form_data = request.json if request.json else request.form
    if form_data.get('clients'):
        for client_id in form_data.get('clients'):
            doc_url = url + client_id
            result = retrive_document_details({
              'url': doc_url,
            })
            print result
            if result.get('response_code') != 200:
                resp_text = "client details not present for {0}".format(client_id)
                response_data = { 'post_response': { 'response_text' : resp_text}}
                resp = make_response(jsonify(response_data), 400)
                return resp
            else:
                document = result.get('document_data')
                # Delete the document
                result = retrive_document_details({
                    'url': doc_url + "?rev=" + document['_rev'],
                    'method': "DELETE",
                })
                if result.get('response_code') != 200:
                    resp_text = "Error Happened while deleting client {0}".format(client_id)
                    response_data = { 'post_response': { 'response_text' : resp_text}}
                    resp = make_response(jsonify(response_data), 400)
                    return resp
    resp_text = "Successfully delete all the clients"
    response_data = { 'post_response': { 'response_text' : resp_text}}
    resp = make_response(jsonify(response_data), 200)
    return resp
def all_clients_details(client_id=None):
    """
        Description : View fucntion to Handle the clients display requests
        
        input_param : client_id - configured host name of the client
        input_type : string
    
    """
    url = settings.BASE_URL   
    if request.method == 'GET':
        if not client_id:
            design = json.loads(settings.DESIGN_DATA)
            url = url + "/" + design['_id'] + "/_view/all_clients"
            result = retrive_document_details({
                   'url': url
            })
            total_clients = result['document_data']['rows']
            for client in total_clients:
                args = json.dumps({
                        'command_to_send' : 'check_alive',
                        'ip': client['value']['ip'],
                        'port': settings.client_port
                })
                p = subprocess.Popen(['python', 'command_sender.py', args])
                p.wait()
                if p.returncode == 0:
                    client['value']['active'] = True
            response_data = {  'form' : render_template('configured_clients.html'),
                           'response_data': {
                                                'clients': total_clients,
                                                'rules': RULES,
                                                'client_filters': CLIENT_DISPLAY_FILTERS
										}
                        }
            resp = make_response(jsonify(response_data), 200)
            return resp
        else:
            url = url + "/" + client_id 
            result = retrive_document_details({
                   'url': url
            })
            response_data = {  'form' : render_template('single_client_details.html'),
                           'response_data': {
                                             'client': result['document_data']
										}
                        }
            resp = make_response(jsonify(response_data), 200)
            return resp
def start_packet_capture():
    """
        Description : View function to start the packet sniffing program in client machines
    
    """
    url = settings.BASE_URL + "/" 
    form_data = request.json if request.json else request.form
    if form_data.get('clients'):
        for client_id in form_data.get('clients'):
            doc_url = url + client_id
            result = retrive_document_details({
              'url': doc_url
            })
            if result.get('response_code') != 200:
                resp_text = "client details not present for {0}".format(client_id)
                response_data = { 'post_response': { 'response_text' : resp_text}}
                resp = make_response(jsonify(response_data), 400)
                return resp
            else:
                document = result.get('document_data')
                rules = document['rules']
                document['status_name'] = 'capture_started'
                document_args = {
                    'url': doc_url,
                    'data' : json.dumps(document),
                    'override_doc' : True
                }
                capture_rules = []
                for rule in rules: 
                    if rule.get('append_type'):
                        capture_rules.extend( [ rule['rule_name'], rule['rule_value'], rule['append_type'] ])
                    else:
                        capture_rules.extend( [ rule['rule_name'], rule['rule_value'] ])
                args = json.dumps({
                        'command_to_send' : 'start_packet_sniffing',
                        'ip': document['ip'],
                        'port': settings.client_port,
                        'capture_rules': capture_rules
                })
                p = subprocess.Popen(['python', 'command_sender.py', args])
                p.wait()
                if p.returncode == 0:
                    # upload the constructed document
                    result = upload_document(document_args)
                # If the document upload is successful
                #if not result.get('status'):
                if not result.get('status') or p.returncode !=0 :
                    resp_text = "Error Happened while starting sniffer for {0}".format(client_id)
                    response_data = { 'post_response': { 'response_text' : resp_text}}
                    resp = make_response(jsonify(response_data), 400)
                    return resp
    resp_text = "Successfully started packet sniffing for all the selected clients"
    response_data = { 'post_response': { 'response_text' : resp_text}}
    resp = make_response(jsonify(response_data), 200)
    return resp
def show_client_statistics():
    """
        Description : View function to show statistics of packets for all the clients
    
    """
    design = json.loads(settings.DESIGN_DATA)
    url = settings.BASE_URL + "/" + design['_id'] + "/_view/all_clients"
    result = retrive_document_details({
              'url': url
    })
    clients = []
    if request.method == 'GET':
        if result.get('response_code') == 200:
            result_data = result.get('document_data', {})
            for client in result_data.get('rows'):
                client = client.get('value')
                client_url = settings.BASE_URL + "/" + client['_id']
                args = json.dumps({
                        'command_to_send' : 'send_packet_stats',
                        'ip': client['ip'],
                        'port': settings.client_port,
                        'url': client_url
                })
                p = subprocess.Popen(['python', 'command_sender.py', args])
                p.wait()
                client_result = retrive_document_details({'url': client_url})
                if client_result.get('response_code') == 200:
                    clients.append( client_result.get('document_data') )
        response_data = {  'form' : render_template('client_stats.html'),
                           'response_data': {
                                                'clients': clients,
                                                'rules': RULES,
                                                'client_filters': CLIENT_DISPLAY_FILTERS
                                        }
                        }
        resp = make_response(jsonify(response_data), 200)
        return resp
def add_client_rule():
    """
        Description : View function to Add the packet sniffing rules of the clients
    
    """
    url = settings.BASE_URL + "/" 
    form_data = request.json if request.json else request.form
    if form_data.get('clients'):
        for client in form_data.get('clients'):
            doc_url = url + client.get('host_name')
            result = retrive_document_details({
              'url': doc_url
            })
            if result.get('response_code') != 200:
                resp_text = "client details not present for {0}".format(client.get('host_name', ''))
                response_data = { 'post_response': { 'response_text' : resp_text}}
                resp = make_response(jsonify(response_data), 400)
                return resp
            else:
                document = result.get('document_data')
                document['rules'] = client.get('rule')
                document['status_name'] = 'rule_configured'
                document_args = {
                    'url': settings.BASE_URL + "/" + document['_id'],
                    'data' : json.dumps(document),
                    'override_doc' : True
                }
                
                # upload the constructed document
                result = upload_document(document_args)
                # If the document upload is successful
                #if not result.get('status'):
                if not result.get('status'):
                    resp_text = "client details rule update failes for {0}".format(rule.get('host_name', ''))
                    response_data = { 'post_response': { 'response_text' : resp_text}}
                    resp = make_response(jsonify(response_data), 400)
                    return resp
    resp_text = "Successfully updated rule for all the selected clients"
    response_data = { 'post_response': { 'response_text' : resp_text}}
    resp = make_response(jsonify(response_data), 200)
    return resp
 response = sender_socket.recv(5)
 if response == 'start':
     data = ""
     while start_count <= max_count:
         data = data + sender_socket.recv(1024)
         try:
            json_data = json.loads(data)
         except ValueError:
            logger.debug("Decode error while decoding json data")
            start_count = start_count + 1
            json_data = None
            continue
         break
     if json_data:
         result = retrive_document_details({
                 'url': arguements['url']
         })
         if result.get('response_code') == 200:
             document = result.get('document_data')
             document['stats'] = json_data
             document_args = {
                 'url': arguements['url'],
                 'data' : json.dumps(document),
                 'override_doc' : True
             }
             upload_document(document_args)
     sender_socket.send("stats received")
     response = sender_socket.recv(3)
     if response == "end":
         logger.debug("Stats are received")
         sender_socket.close()