def profile(request):
    if request.method == "POST":
        data = request.POST
        password = data.get('password',None)
        email = data.get('email',None)
        cell_phone = data.get('cell_phone',None)
        
        if password and email and cell_phone:
            try:
                user = Account.objects.get(username=request.session.get('username'))
            except Account.DoesNotExist:
                return render('users/profile.html',{'user_not_exist':True},request)
            else:
                Account.objects.filter(username=request.session.get('username')).update(
                    password=password.strip(),
                    email=email.strip(),
                    cell_phone=cell_phone.strip()
                )
                return render('users/profile.html',{'finished':True},request)
    try:
        user = Account.objects.get(username=request.session.get('username'))
    except Account.DoesNotExist:
        return render('users/profile.html',{'user_not_exist':True},request)
    
    return render('users/profile.html',{'user':user},request)
def owner_job(request):
    """
    list jobs for current user.
    """
    final_dict = dict()
    noti_result_list = Notification_Result.objects.filter(to_user=request.session['username'],op_processed_result=None)
    if not noti_result_list:
        return render('jobs/owner_job.html',{'host_not_exist':True},request)
    for line in noti_result_list:
        final_dict[line.id] = {}
        final_dict[line.id]['notification'] = Notification.objects.get(id=line.notification_id)
        final_dict[line.id]['result'] = line
    generator_dict = [{key:final_dict[key]} for key in sorted(final_dict.keys(),reverse=True)]
    return render('jobs/owner_job.html',{'result_list':generator_dict},request)
def home(request):
    hosts_sql = """
    SELECT COUNT( * ) AS quantity
    FROM nagios_hosts a, nagios_hoststatus b
    WHERE a.host_object_id = b.host_object_id
    AND a.instance_id = b.instance_id
    AND b.current_state !=0
    """
    hosts_cursor = raw_sql(hosts_sql)
    hosts_rows = hosts_cursor.fetchall()
    problem_hosts = int(hosts_rows[0][0])
    
    services_sql = """
    SELECT COUNT( * ) AS quantity
    FROM nagios_services a, nagios_servicestatus b
    WHERE a.service_object_id = b.service_object_id
    AND a.instance_id = b.instance_id
    AND b.current_state !=0
    """
    services_cursor = raw_sql(services_sql)
    services_rows = services_cursor.fetchall()
    problem_services = int(services_rows[0][0])
    
    notifications = Notification.objects.filter(has_processed=None)
    unhandled_notifications = len(notifications)
    
    jobs = Notification_Result.objects.filter(to_user=request.session.get('username',None),op_processed_result=None)
    unhandled_jobs = len(jobs)
    
    return render('users/home.html',{'problem_hosts':problem_hosts,
                                    'problem_services':problem_services,
                                    'unhandled_notifications':unhandled_notifications,
                                    'unhandled_jobs':unhandled_jobs
                                     },request)
def login(request):
    if request.method == "POST":
        data = request.POST
        if not data:
            return render('users/login.html',{},request)
        username = data['username']
        password = data['password']
        try:
            account = Account.objects.get(username=username,password=password)
        except:
            messages.error(request,_('Invalid email or password.'))
            return render('users/login.html',{},request)
            
        if not account.is_valid:
            messages.error(request,_('Your account is locked, please contact to administrator.'))
            return render('users/login.html',{},request)
        
        
        _set_session_data(request,account)
        
        return shortcuts.redirect(reverse('home'))
    
    return render('users/login.html',{},request)
def instances_setting(request,uuid):
    if request.method == "POST":
        data = request.POST
        try:
            arp = data['arp']
        except:
            arp = None
        try:
            ping = data['ping']
        except:
            ping = None
        tcp = data['tcp']
        udp = data['udp']
        name = data['instance_name']
        ip = data['instance_ip']
        moniting_data = dict()
        moniting_data['ping'] = True if ping =='on' else None
        moniting_data['arp'] = True if arp == 'on' else None
        moniting_data['tcp'] = get_portlist(tcp)
        moniting_data['udp'] = get_portlist(udp)
        
        notification_data = dict()
        notification_data['cpu_warnning'] = data['cpu_warnning'] if data['cpu_warnning'] else 0
        notification_data['cpu_critical'] = data['cpu_critical'] if data['cpu_critical'] else 0
        notification_data['disk_usage_warnning'] = data['disk_usage_warnning'] if data['disk_usage_warnning'] else 0
        notification_data['disk_usage_critical'] = data['disk_usage_critical'] if data['disk_usage_critical'] else 0
        notification_data['bandwidth_usage_warnning'] = data['bandwidth_usage_warnning'] if data['bandwidth_usage_warnning'] else 0
        notification_data['bandwidth_usage_critical'] = data['bandwidth_usage_critical'] if data['bandwidth_usage_critical'] else 0
        try:
            ins = Instances_Config.objects.get(uuid=uuid)
        except Exception,e:
            instances = Instances_Config(
                name = name,
                ipaddress = ip,
                uuid = uuid,
                notification_state = notification_data,
                moniting_state = moniting_data
            )
            instances.save()
        else:
            Instances_Config.objects.filter(uuid=uuid).update(
                notification_state = notification_data,
                moniting_state = moniting_data
            )
        return render('instances/notification.html',{'finish_update':True},request)
def show_settings(request):
    """
    main view for display settings page.
    """
    all_ruler = SendRuler.objects.all()
    
    page_size = 6
    after_range_num = 4
    before_range_num = 5
    try:
        page = int(request.GET.get('page',1))
        if page < 1:
            page = 1
    except ValueError:
        page = 1
    paginator = Paginator(all_ruler,page_size)
    try:
        rulers = paginator.page(page)
    except(EmptyPage, InvalidPage, PageNotAnInteger):
        rulers = paginator.page(1)
    if page >= after_range_num:
        page_range = paginator.page_range[page - after_range_num : page + before_range_num]
    else:
        page_range = paginator.page_range[0:int(page) + before_range_num]
    
    final_rulers = list()
    
    for rule in rulers:
        temp = dict()
        temp['id'] = rule.id
        temp['created_time'] = rule.created_time
        temp['host_name'] = eval(rule.host_name)
        temp['host_name_include'] = rule.host_name_include
        temp['state'] = eval(rule.state)
        temp['user_name'] = eval(rule.user_name)
        temp['output'] = rule.output
        final_rulers.append(temp)
    
    return render('system/main.html',{'host_service_list':host_service_list,'users':get_user_list(), \
                                      'page_range':page_range, 'paged_ruler':rulers, 'original_ruler':final_rulers,\
                                        'host_service_list_json':json.dumps(host_service_list)}, request)
def update_settings(request):
    """
    update function used for settings page.
    """
    if request.method == "POST":
        data = request.POST
        host_list = data.getlist('host_list')
        host_list_include = data['host_list_include']
        state = data.getlist('state')
        user_list = data.getlist('user_list')
        output = data['output']
        state = data.getlist('state')
        p = SendRuler(
            host_name = host_list,
            host_name_include = host_list_include,
            user_name = user_list,
            state = state,
            output = output
        )
        p.save()    
        return render('system/main.html',{'updated':True},request)
def host_list(request):
    host_type = request.REQUEST.get('host_type',None)
    if not host_type:
        sql = """
        SELECT
        a.host_object_id,a.display_name,a.address,
        b.current_state,(select now()) as status_update_time,b.last_state_change,b.output
        FROM nagios_hosts a, nagios_hoststatus b
        WHERE a.host_object_id = b.host_object_id AND a.instance_id = b.instance_id
        ORDER by a.display_name ASC
        """
    elif host_type == "unhandled":
        sql = """
        SELECT
        a.host_object_id,a.display_name,a.address,
        b.current_state,(select now()) as status_update_time,b.last_state_change,b.output
        FROM nagios_hosts a, nagios_hoststatus b
        WHERE a.host_object_id = b.host_object_id AND a.instance_id = b.instance_id
        AND b.current_state !=0
        ORDER by a.display_name ASC
        """
    
    cursor = raw_sql(sql)
    rows = cursor.fetchall()
    host_list = list()
    for line in rows:
        temp = dict()
        temp['host_object_id'] = line[0]
        temp['display_name'] = line[1]
        temp['address'] = line[2]
        temp['current_state'] = line[3]
        duration = line[4] - line[5]
        hms = time.gmtime(duration.seconds)
        temp['state_duration'] = str(duration.days) + ' d ' + \
            str(hms.tm_hour) + ' h ' + str(hms.tm_min) +  ' m ' + str(hms.tm_sec) + ' s'
        temp['output'] = line[6]
        host_list.append(temp)
    return render('host_list/main.html',{'host_list':host_list,'services_list':get_hosts_state()},request)
def service_list(request):
    host = request.REQUEST.get('host',None)
    service_type = request.REQUEST.get('service_type',None)
    
    if host:
        sql = """
        SELECT host_object_id
        FROM nagios_hosts
        WHERE display_name =  '%s'
        """ % host
        cursor = raw_sql(sql)
        rows = cursor.fetchall()
        try:
            host_object_id = rows[0][0]
        except:
            return render('service_list/main.html',{'host_not_exist':True},request)
        
        sql = """
        SELECT 
        a.host_object_id, a.service_object_id, a.display_name,
        (select now()) as status_update_time,b.last_state_change,b.current_state,b.output
        FROM nagios_services a, nagios_servicestatus b
        WHERE a.service_object_id = b.service_object_id
        AND a.instance_id = b.instance_id
        AND a.host_object_id = %d
        ORDER BY a.host_object_id,a.display_name ASC
        """ % host_object_id
        cursor = raw_sql(sql)
        rows = cursor.fetchall()
    else:
        if not service_type:
            sql = """
            SELECT
            a.host_object_id, a.service_object_id, a.display_name,
            (select now()) as status_update_time,b.last_state_change,b.current_state,b.output
            FROM nagios_services a, nagios_servicestatus b
            WHERE a.service_object_id = b.service_object_id
            AND a.instance_id = b.instance_id
            ORDER BY a.host_object_id,a.display_name ASC
            """
            cursor = raw_sql(sql)
            rows = cursor.fetchall()
        elif service_type == "unhandled":
            sql = """
            SELECT
            a.host_object_id, a.service_object_id, a.display_name,
            (select now()) as status_update_time,b.last_state_change,b.current_state,b.output
            FROM nagios_services a, nagios_servicestatus b
            WHERE a.service_object_id = b.service_object_id
            AND a.instance_id = b.instance_id
            AND b.current_state !=0
            ORDER BY a.host_object_id,a.display_name ASC
            """
            cursor = raw_sql(sql)
            rows = cursor.fetchall()
            
    ############### get unique host list ################
    sql = """
        SELECT host_object_id,display_name
        FROM nagios_hosts
        """
    cursor = raw_sql(sql)
    rows_temp = cursor.fetchall()
    unique_hostname_list = list()
    for line in rows_temp:
        unique_hostname_list.append({line[0]:line[1]})
    def get_hostname_from_id(host_id):
        for item in unique_hostname_list:
            for k,v in item.items():
                if host_id ==k:
                    return v
    ################## end get unique host list############
    
    service_list = list()
    for line in rows:
        temp = dict()
        temp['hostname'] = get_hostname_from_id(line[0])
        temp['host_object_id'] = line[0]
        temp['service_object_id'] = line[1]
        temp['display_name'] = line[2]
        duration = line[3] - line[4]
        hms = time.gmtime(duration.seconds)
        temp['state_duration'] = str(duration.days) + ' d ' + str(hms.tm_hour) + ' h ' + str(hms.tm_min) +  ' m ' + str(hms.tm_sec) + ' s'
        temp['current_state'] = line[5]
        temp['output'] = line[6]
        service_list.append(temp)
    return render('service_list/main.html',{'hostname_list':unique_hostname_list,'service_list':service_list},request)
def perfdata_host_service(request, host, service):
    if service == "all":
        perfdata_path = os.path.dirname(os.path.abspath(__file__))
        return render('perfdata/main.html', {'show_host_chart':True, 'host_dict':get_rrdfiles_by_host(host)}, request)
    else:
        return render('perfdata/main.html', {'show_service_chart':True, 'host_and_service':{host:service}}, request)
def advanced_search_result(request):
        data = request.GET
    
        keyword = data.get('keyword',None)
        critical = 2 if data.get('critical',None) else 0
        warning = 1 if data.get('warning',None) else 0
        unknown = 3 if data.get('unknown',None) else 0
        starttime = data.get('starttime',None)
        endtime = data.get('endtime',None)
        
        if starttime and endtime:
            start_time = datetime.datetime.strptime(starttime,datetime_format)
            end_time = datetime.datetime.strptime(endtime,datetime_format)
        else:
            start_time = end_time = None
        
        keyword = keyword.strip().lower()

        if start_time and end_time and keyword:
            notifications = Notification.objects.filter(Q(hostname__icontains=keyword) | Q(service_description__icontains=keyword) |
                                                        Q(output__icontains=keyword),
                                                        has_processed=None,
                                                        ).filter(
                                                        Q(created_time__gt=start_time) &
                                                        Q(created_time__lt=end_time)
                                                        )
        elif start_time and end_time:
            notifications = Notification.objects.filter(
                                                        Q(created_time__gt=start_time) &
                                                        Q(created_time__lt=end_time)
                                                        )
        elif keyword:
            notifications = Notification.objects.filter(Q(hostname__icontains=keyword) | Q(service_description__icontains=keyword) |
                                                        Q(output__icontains=keyword),
                                                        has_processed=None,
                                                        )
        else:
            notifications = None
        
        if notifications:
            if critical and not warning and not unknown:
                notifications = notifications.filter(Q(state__iexact=critical))
            elif warning and not critical and not unknown:
                notifications = notifications.filter(Q(state__iexact=warning))
            elif unknown and not critical and not warning:
                notifications = notifications.filter(Q(state__iexact=unknown))
            elif critical and warning and not unknown:
                notifications = notifications.filter(Q(state__iexact=critical) or Q(state__iexact=warning))
            elif critical and unknown and not warning:
                notifications = notifications.filter(Q(state__iexact=critical) or Q(state__iexact=unknown))
            elif warning and unknown and not critical:
                notifications = notifications.filter(Q(state__iexact=warning) or Q(state__iexact=unknown))
            elif critical and warning and unknown:
                notifications = notifications.filter(Q(state__iexact=warning) or Q(state__iexact=unknown) or Q(state__iexact=unknown))
        else:
            notifications = Notification.objects.filter(Q(state__iexact=warning) or Q(state__iexact=unknown) or Q(state__iexact=unknown))
        
        users = Account.objects.all()
        user_list = list()
        for user in users:
            user_list.append(user.username)
        
        page_size = 13
        after_range_num = 4
        before_range_num = 5
        try:
            page = int(request.GET.get('page',1))
            if page < 1:
                page = 1
        except ValueError:
            page = 1
        paginator = Paginator(notifications,page_size)
        try:
            paged_notifications = paginator.page(page)
        except(EmptyPage, InvalidPage, PageNotAnInteger):
            rulers = paginator.page(1)
        if page >= after_range_num:
            page_range = paginator.page_range[page - after_range_num : page + before_range_num]
        else:
            page_range = paginator.page_range[0:int(page) + before_range_num]   
        
        return render('notification/search_result.html',{'notifications':paged_notifications,
                                                         'original_notifications':notifications,
                                                         'user_list':user_list,
                                                         'keyword':keyword,
                                                         'starttime':start_time.strftime(datetime_format) if start_time else '',
                                                         'endtime':end_time.strftime(datetime_format) if end_time else '',
                                                         'critical':'on' if critical==2 else '',
                                                         'warning':'on' if warning==1 else '',
                                                         'unknown':'on' if unknown==3 else '',
                                                         },request)
def advanced_search(request):
    return render('notification/search.html', {}, request)
def show_notification(request):
    """
    view for notification and search form
    """
    keyword = request.REQUEST.get("keyword",None)
    
    users = Account.objects.all()
    user_list = list()
    for user in users:
        user_list.append(user.username)
        
    if keyword:
        keyword = keyword.strip().lower()
        if len(keyword) == 0:
            return render('notification/main.html',{'host_not_exist':True},request)
        
        if keyword.startswith('#'):
            keyword = keyword.split('#')[1]
            notifications = Notification.objects.filter(Q(id__iexact=keyword), has_processed=None)
        else:
            notifications = Notification.objects.filter(Q(hostname__icontains=keyword) | Q(service_description__icontains=keyword) |
                                                        Q(output__icontains=keyword) | Q(id__iexact=keyword), has_processed=None)
        if not notifications:
            return render('notification/main.html',{'host_not_exist':True},request)
        
        page_size = 13
        after_range_num = 4
        before_range_num = 5
        try:
            page = int(request.GET.get('page',1))
            if page < 1:
                page = 1
        except ValueError:
            page = 1
        paginator = Paginator(notifications,page_size)
        try:
            paged_notifications = paginator.page(page)
        except(EmptyPage, InvalidPage, PageNotAnInteger):
            rulers = paginator.page(1)
        if page >= after_range_num:
            page_range = paginator.page_range[page - after_range_num : page + before_range_num]
        else:
            page_range = paginator.page_range[0:int(page) + before_range_num]
        
        return render('notification/main.html',{'notifications':paged_notifications,'original_notifications':notifications, 'user_list':user_list, 'keyword':keyword},request)
    
    elif not keyword and request.REQUEST.get("source")=="form":
        return render('notification/main.html', {'empty_keyword':True}, request)
    
    else:
        notifications = Notification.objects.filter(has_processed=None)
        if not notifications:
            return render('notification/main.html',{'host_not_exist':True},request)
        
        page_size = 13
        after_range_num = 4
        before_range_num = 5
        try:
            page = int(request.GET.get('page',1))
            if page < 1:
                page = 1
        except ValueError:
            page = 1
        paginator = Paginator(notifications,page_size)
        try:
            paged_notifications = paginator.page(page)
        except(EmptyPage, InvalidPage, PageNotAnInteger):
            rulers = paginator.page(1)
        if page >= after_range_num:
            page_range = paginator.page_range[page - after_range_num : page + before_range_num]
        else:
            page_range = paginator.page_range[0:int(page) + before_range_num]
        
        return render('notification/main.html',{'notifications':paged_notifications,'original_notifications':notifications, 'user_list':user_list},request)
def instances_list(request):
    session = Session()
    session.autoflush=True
    ins = session.query(Instances).all()
    final_instances = get_instances_list(ins)
    return render('instances/instance_list.html',{'instances':final_instances},request)
def instances_detail(request):
    session = Session()
    session.autoflush=True
    ins = session.query(Instances).all()
    final_instances = get_instances_detail(ins)
    return render('instances/instance_detail.html',{'instances':simplejson.dumps(final_instances)},request)
                notification_state = notification_data,
                moniting_state = moniting_data
            )
            instances.save()
        else:
            Instances_Config.objects.filter(uuid=uuid).update(
                notification_state = notification_data,
                moniting_state = moniting_data
            )
        return render('instances/notification.html',{'finish_update':True},request)
        
        
    uuid = uuid.strip()
    session = Session()
    instance = session.query(Instances).filter(Instances.uuid==uuid).all()
    final_instance = get_instances_list(instance)
    try:
        instance_config = Instances_Config.objects.get(uuid=uuid)
        final_instance_config = get_instances_config(instance_config)
    except:
        final_instance_config = None
    return render('instances/notification.html',{'instance_info':final_instance[0],'instance_config':final_instance_config},request)


@csrf_exempt
def instances_config(request):
    if request.method == "POST":
        instances_config = Instances_Config.objects.all().values()
        return HttpResponse(str(instances_config))
    return HttpResponse()