Exemple #1
0
def get_page():
    # First we look for the user sid
    # so we bail out if it's a false one
    user = app.get_user_auth()

    if not user:
        redirect("/user/login")
    

    all_imp_impacts = app.datamgr.get_services()#important_elements()
    #all_imp_impacts.sort(hst_srv_sort)

    impacts = []
    for imp in all_imp_impacts:
        safe_print("FIND A BAD SERVICE IN IMPACTS", imp.get_dbg_name())
        d = {'name' : imp.get_full_name().encode('utf8', 'ignore'),
             "title": "My Image 3", "thumb": "/static/images/state_flapping.png", "zoom": "/static/images/state_flapping.png",
             "html" : get_div(imp)}
        impacts.append(d)
    
    # Got in json format
    #j_impacts = json.dumps(impacts)
#    print "Return impact in json", j_impacts

    return {'app' : app, 'user' : user, 'impacts' : impacts}
Exemple #2
0
def problems():
    # First we look for the user sid
    # so we bail out if it's a false one
    user = app.get_user_auth()

    if not user:
        redirect("/mobile/")
        return

    # We want to limit the number of elements
    start = int(app.request.GET.get('start', '0'))
    end = int(app.request.GET.get('end', '5'))

    all_pbs = app.datamgr.get_all_problems()

    # Now sort it!
    all_pbs.sort(hst_srv_sort)

    total = len(all_pbs)
    # If we overflow, came back as normal
    if start > total:
        start = 0
        end = 5

    navi = app.helper.get_navi(total, start, step=5)
    all_pbs = all_pbs[start:end]

    return {'app' : app, 'user' : user,  'navi' : navi, 'problems' : all_pbs, 'menu_part' : '/problems'}
Exemple #3
0
def get_launch():
    user = app.get_user_auth()

    if not user:
        redirect("/user/login")

    print "Got forms in /newhosts/launch page"
    names = app.request.forms.get('names', '')

    runners = []
    for (k,v) in app.request.forms.iteritems():
        print "DUMP OF K, V FOR LAUNCH", k, v
        print k.startswith('enable-runner-')
        if k.startswith('enable-runner-'):
            r_name = k[len('enable-runner-'):]
            print "NAME", r_name, v, to_bool(v)
            if to_bool(v):
                runners.append(r_name)

    print "Selected runners", runners
    print "Got in request form"
    print names

    # We are putting a ask ask in the database
    i = random.randint(1, 65535)
    scan_ask = {'_id': i, 'names': names, 'runners': runners, 'state': 'pending', 'creation': int(time.time())}
    print "Saving", scan_ask, "in", app.db.scans
    r = app.db.scans.save(scan_ask)
    # We just want the id as string, not the object
    print "We create the scan", i
    app.ask_new_scan(i)

    return {'app': app, 'user': user}
Exemple #4
0
def get_graphs_widget():
    
    user = app.get_user_auth()
    if not user:
        redirect("/user/login")

    search = app.request.GET.get('search', '')

    if not search:
        search = 'localhost'

    # Look for an host or a service?
    elt = None
    if not '/' in search:
        elt = app.datamgr.get_host(search)
    else:
        parts = search.split('/', 1)
        elt = app.datamgr.get_service(parts[0], parts[1])
    
    wid = app.request.GET.get('wid', 'widget_graphs_'+str(int(time.time())))
    collapsed = (app.request.GET.get('collapsed', 'False') == 'True')

    options = {'search' : {'value' : search, 'type' : 'hst_srv', 'label' : 'Element name'},}

    title = 'Element graphs for %s' % search

    return {'app' : app, 'elt' : elt, 'user' : user, 
            'wid' : wid, 'collapsed' : collapsed, 'options' : options, 'base_url' : '/widget/graphs', 'title' : title,
            }
Exemple #5
0
def checkauth():
    user = app.get_user_auth()

    if not user:
        redirect("/user/login")
    else:
        return user
Exemple #6
0
def impacts():
    # First we look for the user sid
    # so we bail out if it's a false one
    user = app.get_user_auth()

    if not user:
        redirect("/mobile/")
        return
	
    # We want to limit the number of elements
    start = int(app.request.GET.get('start', '0'))
    end = int(app.request.GET.get('end', '5'))

    all_imp_impacts = app.datamgr.get_important_elements()
    all_imp_impacts.sort(worse_first)

    total = len(all_imp_impacts)
    # If we overflow, came back as normal
    if start > total:
        start = 0
        end = 5

    navi = app.helper.get_navi(total, start, step=5)
    all_imp_impacts = all_imp_impacts[start:end]
    
    
    return {'app' : app, 'user' : user, 'navi' : navi, 'impacts' : all_imp_impacts}
Exemple #7
0
def get_last_errors_widget():

    user = app.get_user_auth()
    if not user:
        redirect("/user/login")

    # We want to limit the number of elements, The user will be able to increase it
    nb_elements = max(0, int(app.request.GET.get('nb_elements', '10')))

    pbs = app.datamgr.get_problems_time_sorted()

    # Filter with the user interests
    pbs = only_related_to(pbs, user)

    # Keep only nb_elements
    pbs = pbs[:nb_elements]

    wid = app.request.GET.get('wid', 'widget_last_problems_' + str(int(time.time())))
    collapsed = (app.request.GET.get('collapsed', 'False') == 'True')

    options = {'nb_elements': {'value': nb_elements, 'type': 'int', 'label': 'Max number of elements to show'},
               }

    title = 'Last IT problems'

    return {'app': app, 'pbs': pbs, 'user': user, 'page': 'problems',
            'wid': wid, 'collapsed': collapsed, 'options': options, 'base_url': '/widget/last_problems', 'title': title,
            }
Exemple #8
0
def get_page():
    
    # First we look for the user sid
    # so we bail out if it's a false one
#    sid = app.request.get_cookie("sid")
    

    user = app.get_user_auth()

    if not user:
        redirect("/user/login")
#        return {'app' : app, 'pbs' : [], 'valid_user' : False, 'user' : None, 'navi' : None}
 
    #We want to limit the number of elements
    start = int(app.request.GET.get('start', '0'))
    end = int(app.request.GET.get('end', '30'))

    search = app.request.GET.get('search', '')

    pbs = app.datamgr.get_all_problems()
    
    # Filter with the user interests
    pbs = only_related_to(pbs, user)

    # Ok, if need, appli the search filter
    if search:
        print "SEARCHING FOR", search
        print "Before filtering", len(pbs)
        # We compile the patern
        pat = re.compile(search, re.IGNORECASE)
        new_pbs = []
        for p in pbs:
            if pat.search(p.get_full_name()):
                new_pbs.append(p)
                continue
            to_add = False
            for imp in p.impacts:
                if pat.search(imp.get_full_name()):
                    to_add = True
            for src in p.source_problems:
                if pat.search(src.get_full_name()):
                    to_add = True
            if to_add:
                new_pbs.append(p)

        pbs = new_pbs
        print "After filtering", len(pbs)

    total = len(pbs)
    # If we overflow, came back as normal
    if start > total:
        start = 0
        end = 30
    navi = app.helper.get_navi(total, start, step=30)
    pbs = pbs[start:end]

#    print "get all problems:", pbs
#    for pb in pbs :
#        print pb.get_name()
    return {'app' : app, 'pbs' : pbs, 'valid_user' : True, 'user' : user, 'navi' : navi, 'search' : search, 'page' : 'problems'}
Exemple #9
0
def elements_generic(cls, show_tpls=False):
    # First we look for the user sid
    # so we bail out if it's a false one
    user = app.get_user_auth()
    if not user:
        redirect("/user/login")

    # Get all entries from db
    #t = getattr(app.db, cls.my_type+'s')
    #cur = t.find({})
    #elts = [cls(i) for i in cur]
    print "GENERIC", cls.my_type
    t = cls.my_type + 's'
    key = keys[t]
    #if cls.my_type == 'host':
    #    print "HOOK HOSTS"

    elts = [cls(i) for i in app.datamgr.get_generics(t, key)]
    print "GOT elements", elts

    # Look for removing or keeping templates
    if not show_tpls:
        print "REMOVING TEMPLATES"
        elts = [e for e in elts if not e.is_tpl()]

    return {'app': app, 'user': user, 'elts': elts, 'elt_type': cls.my_type}
Exemple #10
0
def get_page():
    # First we look for the user sid
    # so we bail out if it's a false one
    user = app.get_user_auth()
    if not user:
        redirect("/user/login")
        return

    # We are looking for hosts that got valid GPS coordinates,
    # and we just give them to the template to print them.
    all_hosts = app.datamgr.get_hosts()
    valid_hosts = []
    for h in all_hosts:
        _lat = h.customs.get('_LAT', None)
        _long = h.customs.get('_LONG', None)

        try:
            print "Host", h.get_name(), _lat, _long, h.customs
        except:
            pass
        if _lat and _long:
            try:
                _lat = float(_lat)
                _long = float(_long)
            # Maybe the customs are set, but with invalid float?
            except ValueError:
                continue
            # Look for good range, lat/long must be between -180/180
            if -180 <= _lat <= 180 and -180 <= _long <= 180:
                print "GOOD VALUES FOR HOST", h.get_name()
                valid_hosts.append(h)

    # So now we can just send the valid hosts to the template
    return {'app': app, 'user': user, 'hosts' : valid_hosts}
Exemple #11
0
def do_register():
    username = app.request.forms.get("username")
    email = app.request.forms.get("email")
    password = app.request.forms.get("password")
    password_hash = hashlib.sha512(password).hexdigest()
    cli_mode = app.request.forms.get("cli_mode", "0")

    print "Get a new user %s with email %s and hash %s" % (username, email, password_hash)
    if not app.is_name_available(username):
        if cli_mode == "1":
            app.response.content_type = "application/json"
            return json.dumps({"state": 400, "text": "Sorry, this username is not available"})
        redirect("/register?error=Sorry, this username is not available")

    app.register_user(username, password_hash, email)
    if cli_mode == "1":
        app.response.content_type = "application/json"
        return json.dumps(
            {
                "state": 200,
                "text": "Registering success, please look at your email and click in the link in it to validate your account",
            }
        )
    redirect(
        "/register?success=Registering success, please look at your email and click in the link in it to validate your account"
    )
Exemple #12
0
def eue_widget():
    user = app.get_user_auth()

    if not user:
        redirect("/user/login")

    wid = app.request.GET.get('wid', 'widget_system_' + str(int(time.time())))
    collapsed = (app.request.GET.get('collapsed', 'False') == 'True')

    got_childs = (app.request.GET.get('got_childs', 'False') == 'True')
    key = app.request.GET.get('key', 1)

    options = {}

    problems = {}

    message,db = getdb('shinken')
    if not db:
        return {
            'app': app, 'user': user, 'wid': wid,
            'collapsed': collapsed, 'options': options,
            'base_url': '/widget/eue', 'title': 'Eue problems',
            'problems':problems        
        }


    return {'app': app, 'user': user, 'wid': wid,
            'collapsed': collapsed, 'options': options,
            'base_url': '/widget/eue', 'title': 'Eue problems',
            'problems':problems
    }
Exemple #13
0
def get_page():
    # First we look for the user sid
    # so we bail out if it's a false one
    user = app.get_user_auth()

    if not user:
        redirect("/user/login")

    all_imp_impacts = app.datamgr.get_important_elements()
    all_imp_impacts.sort(hst_srv_sort)
    # all_imp_impacts.sort(hst_srv_sort)

    # all_imp_impacts = app.datamgr.get_services()#important_elements()

    impacts = all_imp_impacts
    #    for imp in all_imp_impacts:
    #        safe_print("FIND A BAD SERVICE IN IMPACTS", imp.get_dbg_name())
    #        d = {'name' : imp.get_full_name().encode('utf8', 'ignore'),
    #             "title": "My Image 3", "thumb": "/static/images/state_flapping.png", "zoom": "/static/images/state_flapping.png",
    #             "html" : get_div(imp)}
    #        impacts.append(d)

    # Got in json format
    # j_impacts = json.dumps(impacts)
    #    print "Return impact in json", j_impacts
    all_pbs = app.datamgr.get_all_problems()
    now = time.time()
    # Get only the last 10min errors
    all_pbs = [pb for pb in all_pbs if pb.last_state_change > now - 600]
    # And sort it
    all_pbs.sort(hst_srv_sort)  # sort_by_last_state_change)

    return {"app": app, "user": user, "impacts": impacts, "problems": all_pbs}
Exemple #14
0
def post_user():
    # First we look for the user sid
    # so we bail out if it's a false one
    user = app.get_user_auth()

    if not user:
        redirect("/user/login")
        return

    # Take the user that send the post and not the
    # form value for secutiry reason of course :)
    username = user.get('username')
    email = app.request.forms.get('email')
    password = app.request.forms.get('password')
    password2 = app.request.forms.get('password2')
    password_hash = None
    if password:
        password_hash = hashlib.sha512(password).hexdigest()
    if password != password2:
        abort(400, 'Wrong password')

    print "Get a user %s update with email %s and hash %s" % (username, email, password_hash)

    app.update_user(username, password_hash, email)
    return
Exemple #15
0
def get_page(username):
    # First we look for the user sid
    # so we bail out if it's a false one
    user = app.get_user_auth()

    if not user:
        redirect("/user/login")
        return

    #uname = user.get('username')
    view_user = app.get_user_by_name(username)
    cur = app.db.packs.find({'user': username, 'state': 'ok'})
    validated_packs = [p for p in cur]

    # Only show pending and refused packs if YOU are the user
    pending_packs = []
    refused_packs = []
    if user == view_user:
        cur = app.db.packs.find({'user': username, 'state': 'pending'})
        pending_packs = [p for p in cur]

        cur = app.db.packs.find({'user': username, 'state': 'refused'})
        refused_packs = [p for p in cur]

    return {'app': app, 'user': user, 'view_user': view_user, 'validated_packs': validated_packs, 'pending_packs': pending_packs,
            'refused_packs': refused_packs}
Exemple #16
0
def get_last_errors_widget():

    user = app.get_user_auth()
    if not user:
        redirect("/user/login")

    # We want to limit the number of elements, The user will be able to increase it
    nb_elements = max(0, int(app.request.GET.get("nb_elements", "10")))

    pbs = app.datamgr.get_problems_time_sorted()

    # Filter with the user interests
    pbs = only_related_to(pbs, user)

    # Keep only nb_elements
    pbs = pbs[:nb_elements]

    wid = app.request.GET.get("wid", "widget_last_problems_" + str(int(time.time())))
    collapsed = app.request.GET.get("collapsed", "False") == "True"

    options = {"nb_elements": {"value": nb_elements, "type": "int", "label": "Max number of elements to show"}}

    title = "Last IT problems"

    return {
        "app": app,
        "pbs": pbs,
        "user": user,
        "page": "problems",
        "wid": wid,
        "collapsed": collapsed,
        "options": options,
        "base_url": "/widget/last_problems",
        "title": title,
    }
Exemple #17
0
def show_service(hname, desc):

    # First we look for the user sid
    # so we bail out if it's a false one
    user = app.get_user_auth()

    if not user:
        redirect("/user/login")
#        return {'app': app, 'elt': None, 'valid_user': False, 'user': user}


    # Ok we are in a detail page but the user ask for a specific search
    search = app.request.GET.get('global_search', None)
    if search:
        new_h = app.datamgr.get_host(search)
        if new_h:
            redirect("/host/" + search)

    # Get graph data. By default, show last 4 hours
    now = int(time.time())
    graphstart = int(app.request.GET.get('graphstart', str(now - 4*3600)))
    graphend = int(app.request.GET.get('graphend', str(now)))

    # Ok, we can lookup it :)
    s = app.datamgr.get_service(hname, desc)
    return {'app': app, 'elt': s, 'valid_user': True, 'user': user, 'graphstart': graphstart,
            'graphend': graphend}
Exemple #18
0
def system_widget():
    user = app.get_user_auth()

    if not user:
        redirect("/user/login")

    schedulers = app.datamgr.get_schedulers()
    brokers = app.datamgr.get_brokers()
    reactionners = app.datamgr.get_reactionners()
    receivers = app.datamgr.get_receivers()
    pollers = app.datamgr.get_pollers()

    wid = app.request.GET.get('wid', 'widget_system_' + str(int(time.time())))
    collapsed = (app.request.GET.get('collapsed', 'False') == 'True')
    print "SYSTEM COLLAPSED?", collapsed, type(collapsed)

    got_childs = (app.request.GET.get('got_childs', 'False') == 'True')
    key = app.request.GET.get('key', 1)

    options = {}

    return {'app': app, 'user': user, 'wid': wid,
            'collapsed': collapsed, 'options': options,
            'base_url': '/widget/system', 'title': 'System Information',
            'schedulers': schedulers,
            'brokers': brokers, 'reactionners': reactionners,
            'receivers': receivers, 'pollers': pollers,
            }
Exemple #19
0
def post_validatehost():
    user = app.get_user_auth()

    if not user:
        redirect("/user/login")

    print "Got forms in /newhosts/validatehost call"
    _id = app.request.forms.get('_id', 'unknown-host')
    use = app.request.forms.get('use', '')
    host_name = app.request.forms.get('host_name', None)

    print "DUMP FORMS", app.request.forms.__dict__
    print "Got in request form", _id, host_name, use
    if not host_name:
        print "BAD HOST NAME for post_validatehost bail out"
        return None

    host = {'_id': _id, 'host_name': host_name, 'use': use}
    # If there is no such host in db.hosts, just add it.
    r = app.db.hosts.find_one({'_id': _id})
    print "Already got host?", r
    if not r:
        print "Saving", host, "in", app.db.hosts
        r = app.db.hosts.save(host)
        print "Insert result", r

    # Set this host as added in the discovered_hosts as _discovery_state='added'
    r = app.db.discovered_hosts.update({'_id': _id}, {'$set': {'_discovery_state': 'added'}})
    print "result of update", r

    return None
Exemple #20
0
def get_launch():
    user = app.get_user_auth()

    if not user:
        redirect("/user/login")

    print "Got forms in /newhosts/launch page"
    names = app.request.forms.get('names', '')
    use_nmap = to_bool(app.request.forms.get('use_nmap', '0'))
    use_vmware = to_bool(app.request.forms.get('use_vmware', '0'))

    print "Got in request form"
    print names
    print 'nmap?', use_nmap
    print 'vmware?', use_vmware

    # We are putting a ask ask in the database
    i = random.randint(1, 65535)
    scan_ask = {'_id': i, 'names': names, 'use_nmap': use_nmap, 'use_vmware': use_vmware, 'state': 'pending', 'creation': int(time.time())}
    print "Saving", scan_ask, "in", app.db.scans
    r = app.db.scans.save(scan_ask)
    # We just want the id as string, not the object
    print "We create the scan", i
    app.ask_new_scan(i)

    return {'app': app, 'user': user}
Exemple #21
0
def get_scans():
    user = app.get_user_auth()

    if not user:
        redirect("/user/login")

    print "Got scans"
    return {'app': app, 'user': user}
Exemple #22
0
def tag_unmanaged(hname):
    user = app.get_user_auth()

    if not user:
        redirect("/user/login")

    print "Look for infinite delete for", hname
    r = app.db.discovered_hosts.update({'_id': hname}, {'$set': {'_discovery_state': 'disabled'}})
Exemple #23
0
def delete_host(hname):
    user = app.get_user_auth()

    if not user:
        redirect("/user/login")

    print "Look for simple deleting of an host", hname
    app.db.discovered_hosts.remove({'_id': hname})
Exemple #24
0
def get_pbs_widget():

    user = app.get_user_auth()
    if not user:
        redirect("/user/login")

    # We want to limit the number of elements, The user will be able to increase it
    nb_elements = max(0, int(app.request.GET.get('nb_elements', '10')))
    search = app.request.GET.get('search', '')

    pbs = app.datamgr.get_all_problems(to_sort=False)

    # Filter with the user interests
    pbs = only_related_to(pbs, user)

    # Sort it now
    pbs.sort(hst_srv_sort)

    # Ok, if need, appli the search filter
    if search:
        print "SEARCHING FOR", search
        print "Before filtering", len(pbs)
        # We compile the patern
        pat = re.compile(search, re.IGNORECASE)
        new_pbs = []
        for p in pbs:
            if pat.search(p.get_full_name()):
                new_pbs.append(p)
                continue
            to_add = False
            for imp in p.impacts:
                if pat.search(imp.get_full_name()):
                    to_add = True
            for src in p.source_problems:
                if pat.search(src.get_full_name()):
                    to_add = True
            if to_add:
                new_pbs.append(p)

        pbs = new_pbs[:nb_elements]
        print "After filtering", len(pbs)

    pbs = pbs[:nb_elements]

    wid = app.request.GET.get('wid', 'widget_problems_' + str(int(time.time())))
    collapsed = (app.request.GET.get('collapsed', 'False') == 'True')

    options = {'search': {'value': search, 'type': 'text', 'label': 'Filter by name'},
               'nb_elements': {'value': nb_elements, 'type': 'int', 'label': 'Max number of elements to show'},
               }

    title = 'IT problems'
    if search:
        title = 'IT problems (%s)' % search

    return {'app': app, 'pbs': pbs, 'user': user, 'search': search, 'page': 'problems',
            'wid': wid, 'collapsed': collapsed, 'options': options, 'base_url': '/widget/problems', 'title': title,
            }
Exemple #25
0
def form_comment_delete(name):
    print "Want comment for", name
    user = app.get_user_auth()

    if not user:
        redirect("/user/login")
        return

    return {'app': app, 'user': user, 'name': name}
Exemple #26
0
def get_currently():

    user = app.get_user_auth()

    if not user:
        redirect("/user/login")
        return

    return {"app": app, "user": user}
Exemple #27
0
def form_downtime(name):
    print "Want downtime for", name
    user = app.get_user_auth()

    if not user:
        redirect("/user/login")
        return

    return {'app': app, 'user': user, 'name': name}
Exemple #28
0
def user_logout():
    # To delete it, send the same, with different date
    user_name = app.request.get_cookie("user", secret=app.auth_secret)
    if user_name:
        app.response.set_cookie('user', False, secret=app.auth_secret, path='/')
    else:
        app.response.set_cookie('user', '', secret=app.auth_secret, path='/')
    redirect("/user/login")
    return {}
Exemple #29
0
def user_login():
    user = app.get_user_auth()
    if user:
        redirect("/main")

    err = app.request.GET.get('error', None)
    login_text = app.login_text

    return {'error': err, 'login_text': login_text}
Exemple #30
0
def elements_timeperiod(name):
    user = app.get_user_auth()
    if not user:
        redirect("/user/login")

    elt = app.datamgr.get_timeperiod(name)
    if not elt:
        elt = {}
    return {'app': app, 'user': user, 'elt': elt, 'helper': Helper(app)}
Exemple #31
0
def get_page(arg1='nothing'):
    # First we look for the user sid
    # so we bail out if it's a false one
    user = app.get_user_auth()

    if not user:
        redirect("/user/login")
        return

    # Here we can call app.datamgr beause when the webui "loaded" us, it
    # populated app with it's own value.
    my_host = app.datamgr.get_host(arg1)

    # we return values for the template (view). But beware, theses values are the
    # only one the tempalte will have, so we must give it an app link and the
    # user we are loggued with (it's a contact object in fact)
    return {'app': app, 'user': user, 'host': my_host}
Exemple #32
0
def get_new_packs():
    # First we look for the user sid
    # so we bail out if it's a false one
    user = app.get_user_auth()
    if not user:
        redirect("/user/login")
        return

    # We need an api_key to launc hthe query
    api_key = app.get_api_key()

    categories = ''
    error = ''
    api_error = ''
    status_code = 500

    # Get the categories
    c = pycurl.Curl()
    c.setopt(c.POST, 1)
    c.setopt(c.CONNECTTIMEOUT, 5)
    c.setopt(c.TIMEOUT, 8)
    if app.http_proxy:
        c.setopt(c.PROXY, app.http_proxy)
    c.setopt(c.URL, app.community_uri + "/categories")
    c.setopt(c.HTTPPOST, [("root", '/'), ('api_key', api_key)])
    c.setopt(c.VERBOSE, 1)
    response = StringIO()
    c.setopt(c.WRITEFUNCTION, response.write)
    try:
        r = c.perform()
        response.seek(0)
        status_code = c.getinfo(pycurl.HTTP_CODE)

        # We only parse the json if we got
        if status_code == 200:
            categories = json.loads(response.read().replace('\\/', '/'))
        else:
            api_error = response.read()

        print "status code: %s" % status_code
        c.close()
        print "Json loaded", categories
    except Exception, exp:
        api_error = str(exp)
Exemple #33
0
def main():
    # First we look for the user sid
    # so we bail out if it's a false one
    user = app.get_user_auth()

    if not user:
        redirect("/mobile/")
        return

    all_imp_impacts = app.datamgr.get_important_elements()

    all_pbs = app.datamgr.get_all_problems()

    return {
        'app': app,
        'user': user,
        'impacts': all_imp_impacts,
        'problems': all_pbs
    }
Exemple #34
0
def get_graphs_widget():

    user = app.get_user_auth()
    if not user:
        redirect("/user/login")

    search = app.request.GET.get('search', '')

    if not search:
        search = 'localhost'

    # Look for an host or a service?
    elt = None
    if not '/' in search:
        elt = app.datamgr.get_host(search)
    else:
        parts = search.split('/', 1)
        elt = app.datamgr.get_service(parts[0], parts[1])

    wid = app.request.GET.get('wid', 'widget_graphs_' + str(int(time.time())))
    collapsed = (app.request.GET.get('collapsed', 'False') == 'True')

    options = {
        'search': {
            'value': search,
            'type': 'hst_srv',
            'label': 'Element name'
        },
    }

    title = 'Element graphs for %s' % search

    return {
        'app': app,
        'elt': elt,
        'user': user,
        'wid': wid,
        'collapsed': collapsed,
        'options': options,
        'base_url': '/widget/graphs',
        'title': title,
    }
Exemple #35
0
def get_last_errors_widget():

    user = app.get_user_auth()
    if not user:
        redirect("/user/login")

    # We want to limit the number of elements, The user will be able to increase it
    nb_elements = max(0, int(app.request.GET.get('nb_elements', '10')))

    pbs = app.datamgr.get_problems_time_sorted()

    # Filter with the user interests
    pbs = only_related_to(pbs, user)

    # Keep only nb_elements
    pbs = pbs[:nb_elements]

    wid = app.request.GET.get('wid',
                              'widget_last_problems_' + str(int(time.time())))
    collapsed = (app.request.GET.get('collapsed', 'False') == 'True')

    options = {
        'nb_elements': {
            'value': nb_elements,
            'type': 'int',
            'label': 'Max number of elements to show'
        },
    }

    title = 'Last IT problems'

    return {
        'app': app,
        'pbs': pbs,
        'user': user,
        'page': 'problems',
        'wid': wid,
        'collapsed': collapsed,
        'options': options,
        'base_url': '/widget/last_problems',
        'title': title,
    }
Exemple #36
0
def wall():
    # First we look for the user sid
    # so we bail out if it's a false one
    user = app.get_user_auth()

    if not user:
        redirect("/mobile/")

    all_imp_impacts = app.datamgr.get_important_elements()
    all_imp_impacts.sort(hst_srv_sort)

    impacts = all_imp_impacts
    all_pbs = app.datamgr.get_all_problems()
    now = time.time()
    # Get only the last 10min errors
    all_pbs = [pb for pb in all_pbs if pb.last_state_change > now - 600]
    # And sort it
    all_pbs.sort(hst_srv_sort)  # sort_by_last_state_change)

    return {'app': app, 'user': user, 'impacts': impacts, 'problems': all_pbs}
Exemple #37
0
def depgraph_srv(hname, desc):
    # First we look for the user sid
    # so we bail out if it's a false one
    user = app.get_user_auth()

    if not user:
        return {'app': app, 'elt': None, 'valid_user': False}

    loop = bool(int(app.request.GET.get('loop', '0')))
    loop_time = int(app.request.GET.get('loop_time', '10'))

    # Ok we are in a detail page but the user ask for a specific search
    search = app.request.GET.get('global_search', None)
    if search:
        new_h = app.datamgr.get_host(search)
        if new_h:
            redirect("/depgraph/" + search)

    s = app.datamgr.get_service(hname, desc)
    return {'app': app, 'elt': s, 'user': user, 'valid_user': True, 'loop' : loop, 'loop_time' : loop_time}
Exemple #38
0
def show_impacts():
    # First we look for the user sid
    # so we bail out if it's a false one
    user = app.get_user_auth()

    if not user:
        redirect("/user/login")
        #return {'app': app, 'impacts': {}, 'valid_user': False, 'user': user}

    all_imp_impacts = app.datamgr.get_important_elements()
    all_imp_impacts.sort(hst_srv_sort)

    impacts = {}

    imp_id = 0
    for imp in all_imp_impacts:
        #safe_print("FIND A BAD SERVICE IN IMPACTS", imp.get_dbg_name())
        imp_id += 1
        impacts[imp_id] = imp

    return {'app': app, 'impacts': impacts, 'valid_user': True, 'user': user}
Exemple #39
0
def show_log():
    user = app.get_user_auth()

    if not user:
        redirect("/user/login")

    schedulers = app.datamgr.get_schedulers()
    brokers = app.datamgr.get_brokers()
    reactionners = app.datamgr.get_reactionners()
    receivers = app.datamgr.get_receivers()
    pollers = app.datamgr.get_pollers()

    return {
        'app': app,
        'user': user,
        'schedulers': schedulers,
        'brokers': brokers,
        'reactionners': reactionners,
        'receivers': receivers,
        'pollers': pollers,
    }
Exemple #40
0
def system_page():
    user = app.get_user_auth()

    if not user:
        redirect("/mobile/")

    schedulers = app.datamgr.get_schedulers()
    brokers = app.datamgr.get_brokers()
    reactionners = app.datamgr.get_reactionners()
    receivers = app.datamgr.get_receivers()
    pollers = app.datamgr.get_pollers()

    return {
        'app': app,
        'user': user,
        'schedulers': schedulers,
        'brokers': brokers,
        'reactionners': reactionners,
        'receivers': receivers,
        'pollers': pollers,
    }
Exemple #41
0
def get_results():
    user = app.get_user_auth()

    if not user:
        redirect("/user/login")

    print "Looking for hosts in discovered state"
    now = int(time.time())
    yesterday = now - 86400
    # Search all new discovery elements that are not disabled or already added
    cur = app.db.discovered_hosts.find({'_discovery_state': 'discovered'})
    pending_hosts = [h for h in cur]

    print "And in progress scans"

    cur = app.db.scans.find({'creation': {'$gte': yesterday}})
    scans = [s for s in cur]
    for s in scans:
        print "SCAN", s

    return {'app': app, 'user': user, 'pending_hosts': pending_hosts, 'scans': scans}
Exemple #42
0
def save_common_pref():
    user = app.get_user_auth()

    if not user:
        redirect("/user/login")
        return

    key = app.request.forms.get('key', None)
    value = app.request.forms.get('value', None)

    if key is None or value is None:
        return

    s = json.dumps('{%s: %s}' % (key, value))

    print "We will save common pref ", key, ':', value
    print "As %s" % s

    if user.is_admin:
        app.set_common_preference( key, value)

    return
Exemple #43
0
def get_page():
    # First we look for the user sid
    # so we bail out if it's a false one
    user = app.get_user_auth()

    if not user:
        redirect("/user/login")
        return

    api_key = app.get_api_key()
    print "API KEY IS", api_key, type(api_key)
    api_error = ''
    results = ''
    if api_key:
        (results, api_error) = check_api_server(api_key)
    else:
        api_error = "You don't have configured your API KEY"

    # we return values for the template (view). But beware, theses values are the
    # only one the template will have, so we must give it an app link and the
    # user we are logged with (it's a contact object in fact)
    return {'app': app, 'user': user, 'results': results, 'api_error': api_error}
Exemple #44
0
def eue_widget():
    user = app.get_user_auth()

    if not user:
        redirect("/user/login")

    wid = app.request.GET.get('wid', 'widget_system_' + str(int(time.time())))
    collapsed = (app.request.GET.get('collapsed', 'False') == 'True')

    got_childs = (app.request.GET.get('got_childs', 'False') == 'True')
    key = app.request.GET.get('key', 1)

    options = {}

    problems = {}

    message, db = getdb('shinken')
    if not db:
        return {
            'app': app,
            'user': user,
            'wid': wid,
            'collapsed': collapsed,
            'options': options,
            'base_url': '/widget/eue',
            'title': 'Eue problems',
            'problems': problems
        }

    return {
        'app': app,
        'user': user,
        'wid': wid,
        'collapsed': collapsed,
        'options': options,
        'base_url': '/widget/eue',
        'title': 'Eue problems',
        'problems': problems
    }
Exemple #45
0
def save_pref():
    # First we look for the user sid
    # so we bail out if it's a false one
    user = app.get_user_auth()

    if not user:
        redirect("/user/login")
        return

    key = app.request.forms.get('key', None)
    value = app.request.forms.get('value', None)

    if key is None or value is None:
        return

    s = json.dumps('{%s: %s}' % (key, value))

    print "We will save for the user", user.get_name(), key, ':', value
    print "As %s" % s

    app.set_user_preference(user, key, value)

    return
Exemple #46
0
def get_page():
    # First we look for the user sid
    # so we bail out if it's a false one
    user = app.get_user_auth()

    if not user:
        redirect("/user/login")

    all_imp_impacts = app.datamgr.get_important_elements()
    all_imp_impacts.sort(hst_srv_sort)
    #all_imp_impacts.sort(hst_srv_sort)

    #all_imp_impacts = app.datamgr.get_services() #important_elements()

    impacts = []
    for imp in all_imp_impacts:
        safe_print("FIND A BAD SERVICE IN IMPACTS", imp.get_dbg_name())
        d = {
            'name': imp.get_full_name().encode('utf8', 'ignore'),
            "title": "My Image 3",
            "thumb": "/static/images/state_flapping.png",
            "zoom": "/static/images/state_flapping.png",
            "html": get_div(imp)
        }
        impacts.append(d)

    # Got in json format
    #j_impacts = json.dumps(impacts)
    #print "Return impact in json", j_impacts
    all_pbs = app.datamgr.get_all_problems()
    now = time.time()
    # Get only the last 10min errors
    all_pbs = [pb for pb in all_pbs if pb.last_state_change > now - 600]
    # And sort it
    all_pbs.sort(hst_srv_sort)  # sort_by_last_state_change)

    return {'app': app, 'user': user, 'impacts': impacts, 'problems': all_pbs}
Exemple #47
0
def show_host(name):
    # First we look for the user sid
    # so we bail out if it's a false one
    user = app.get_user_auth()

    if not user:
        redirect("/mobile/")

    # Ok we are in a detail page but the user ask for a specific search
    search = app.request.GET.get('global_search', None)
    if search:
        new_h = app.datamgr.get_host(search)
        if new_h:
            redirect("/host/" + search)

    # Get graph data. By default, show last 4 hours
    now = int(time.time())
    graphstart = int(app.request.GET.get('graphstart', str(now - 4*3600)))
    graphend = int(app.request.GET.get('graphend', str(now)))

    # Ok, we can lookup it
    h = app.datamgr.get_host(name)
    return {'app': app, 'elt': h, 'valid_user': True, 'user': user, 'graphstart': graphstart,
            'graphend': graphend}
Exemple #48
0
def get_root():
    user = app.request.get_cookie("user", secret=app.auth_secret)
    print "USER IS FOUND", user
    if user:
        redirect("/main")
    elif app.remote_user_variable in app.request.headers and app.remote_user_enable == '1':
        user_name = app.request.headers[app.remote_user_variable]
        c = app.datamgr.get_contact(user_name)
        print "Got", c
        if not c:
            print "Warning: You need to have a contact having the same name as your user %s" % user_name
            redirect("/user/login")
        else:
            app.response.set_cookie('user', user_name, secret=app.auth_secret, path='/')
            redirect("/main")
    else:
        redirect("/main")
Exemple #49
0
def user_auth():
    print "Got forms"
    login = app.request.forms.get('login', '')
    password = app.request.forms.get('password', '')
    is_mobile = app.request.forms.get('is_mobile', '0')
    is_auth = app.check_auth(login, password)

    is_activated = app.is_actitaved(login)
    if not is_activated:
        redirect("/user/login?error=Invalid user or Password, or your account is not validated.")

    if is_auth:
        app.response.set_cookie('user', login, secret=app.auth_secret, path='/')
        if is_mobile == '1':
            redirect("/mobile/main")
        else:
            redirect("/main")
    else:
        redirect("/user/login?error=Invalid user or Password")

    return {'app': app, 'is_auth': is_auth}
Exemple #50
0
def user_auth():
    print "Got forms"
    login = app.request.forms.get('login', '')
    password = app.request.forms.get('password', '')
    is_mobile = app.request.forms.get('is_mobile', '0')
    is_auth = app.check_auth(login, password)

    if is_auth:
        app.response.set_cookie('user',
                                login,
                                secret=app.auth_secret,
                                path='/')
        if is_mobile == '1':
            redirect("/mobile/main")
        else:
            redirect("/problems")
    else:
        redirect("/user/login?error=Invalid user or Password")

    return {'app': app, 'is_auth': is_auth}
Exemple #51
0
def get_json():
    app.response.content_type = 'application/json'

    user = app.get_user_auth()
    if not user:
        redirect("/user/login")
        return

    d = {
        "paris": {
            "comments": [],
            "h_equal": [],
            "h_match": ["srv-.*"],
            "hg_equal": ["REALM_PARIS"],
            "hg_match": [],
            "hosts": {
                "down": [{
                    "host_groups": "",
                    "host_name": "srv-emc-clariion",
                    "last_hard_state_change": "1363775109",
                    "state": "1"
                }, {
                    "host_groups": "",
                    "host_name": "srv-esx",
                    "last_hard_state_change": "1363775057",
                    "state": "1"
                }],
                "up": [{
                    "host_groups": "",
                    "host_name": "srv-checkways",
                    "last_hard_state_change": "1363774995",
                    "state": "0"
                }, {
                    "host_groups": "",
                    "host_name": "srv-exchange",
                    "last_hard_state_change": "1363775080",
                    "state": "0"
                }, {
                    "host_groups": "",
                    "host_name": "srv-exchange2",
                    "last_hard_state_change": "1363774975",
                    "state": "0"
                }]
            },
            "position": {
                "latitude": "39.044036",
                "longitude": "-77.48709"
            },
            "services": {
                "critical": [{
                    "comments_with_info": "",
                    "description": "Disks",
                    "host_comments_with_info": "",
                    "host_groups": "",
                    "host_name": "srv-emc-clariion",
                    "last_hard_state_change": "1363775192",
                    "plugin_output": "[Errno 2] No such file or directory",
                    "state": "2"
                }, {
                    "comments_with_info": "",
                    "description": "FC-ports",
                    "host_comments_with_info": "",
                    "host_groups": "",
                    "host_name": "srv-emc-clariion",
                    "last_hard_state_change": "1363775154",
                    "plugin_output": "[Errno 2] No such file or directory",
                    "state": "2"
                }],
                "ok": [{
                    "comments_with_info": "",
                    "description": "Cpu",
                    "host_comments_with_info": "",
                    "host_groups": "",
                    "host_name": "srv-exchange",
                    "last_hard_state_change": "1363775099",
                    "plugin_output":
                    "OK (Sample Period 301 sec) - Average CPU Utilisation 1.13%",
                    "state": "0"
                }, {
                    "comments_with_info": "",
                    "description": "Disks",
                    "host_comments_with_info": "",
                    "host_groups": "",
                    "host_name": "srv-exchange",
                    "last_hard_state_change": "1363775043",
                    "plugin_output":
                    "OK - C: Total=838.23GB, Used=72.59GB (8.7%), Free=765.64GB (91.3%)",
                    "state": "0"
                }],
                "unknown": [{
                    "comments_with_info": "",
                    "description": "BigProcesses",
                    "host_comments_with_info": "",
                    "host_groups": "",
                    "host_name": "srv-exchange-cas",
                    "last_hard_state_change": "0.0",
                    "plugin_output":
                    "INIFILE and/or INIDIR are set but there were no ini file(s) or an error occurred trying to read them.",
                    "state": "3"
                }, {
                    "comments_with_info": "",
                    "description": "Cpu",
                    "host_comments_with_info": "",
                    "host_groups": "",
                    "host_name": "srv-exchange-cas",
                    "last_hard_state_change": "0.0",
                    "plugin_output":
                    "UNKNOWN - The WMI query had problems. The error text from wmic is: [librpc/rpc/dcerpc_connect.c:329:dcerpc_pipe_connect_ncacn_ip_tcp_recv()] failed NT status (c0000017) in dcerpc_pipe_connect_ncacn_ip_tcp_recv",
                    "state": "3"
                }],
                "warning": [{
                    "comments_with_info": "",
                    "description": "BigProcessesWarn",
                    "host_comments_with_info": "",
                    "host_groups": "",
                    "host_name": "srv-exchange-cas",
                    "last_hard_state_change": "0.0",
                    "plugin_output":
                    "INIFILE and/or INIDIR are set but there were no ini file(s) or an error occurred trying to read them.",
                    "state": "3"
                }, {
                    "comments_with_info": "",
                    "description": "CpuWarn",
                    "host_comments_with_info": "",
                    "host_groups": "",
                    "host_name": "srv-exchange-cas",
                    "last_hard_state_change": "0.0",
                    "plugin_output":
                    "UNKNOWN - The WMI query had problems. The error text from wmic is: [librpc/rpc/dcerpc_connect.c:329:dcerpc_pipe_connect_ncacn_ip_tcp_recv()] failed NT status (c0000017) in dcerpc_pipe_connect_ncacn_ip_tcp_recv",
                    "state": "3"
                }]
            }
        }
    }

    return json.dumps(d)
Exemple #52
0
def new_object():
    user = app.get_user_auth()
    if not user:
        redirect("/user/login")

    return {'app': app, 'user': user, 'elt': {}, 'helper': Helper(app)}
Exemple #53
0
def get_view(page):

    user = app.get_user_auth()
    if not user:
        redirect("/user/login")

    print 'DUMP COMMON GET', app.request.GET.__dict__

    # Look for the toolbar pref
    tool_pref = app.get_user_preference(user, 'toolbar')
    # If void, create an empty one
    if not tool_pref:
        app.set_user_preference(user, 'toolbar', 'show')
        tool_pref = 'show'
    toolbar = app.request.GET.get('toolbar', '')
    print "Toolbar", tool_pref, toolbar
    if toolbar != tool_pref and len(toolbar) > 0:
        print "Need to change user prefs for Toolbar",
        app.set_user_preference(user, 'toolbar', toolbar)
    tool_pref = app.get_user_preference(user, 'toolbar')

    # We want to limit the number of elements
    start = int(app.request.GET.get('start', '0'))
    end = int(app.request.GET.get('end', '30'))

    # We will keep a trace of our filters
    filters = {}
    ts = ['hst_srv', 'hg', 'realm', 'htag', 'ack', 'downtime', 'crit']
    for t in ts:
        filters[t] = []

    search = app.request.GET.getall('search')
    if search == []:
        search = app.request.GET.get('global_search', '')

    # Most of the case, search will be a simple string, if so
    # make it a list of this string
    if isinstance(search, basestring):
        search = [search]

    search_str = '&'.join(search)
    print 'Search str=', search_str
    print 'And search', search

    # Load the bookmarks
    bookmarks_r = app.get_user_preference(user, 'bookmarks')
    if not bookmarks_r:
        app.set_user_preference(user, 'bookmarks', '[]')
        bookmarks_r = '[]'
    bookmarks = json.loads(bookmarks_r)
    bookmarks_ro = app.get_common_preference('bookmarks')
    if not bookmarks_ro:
        bookmarks_ro = '[]'

    bookmarksro = json.loads(bookmarks_ro)
    bookmarks = json.loads(bookmarks_r)

    items = []
    if page == 'problems':
        items = app.datamgr.get_all_problems(to_sort=False,
                                             get_acknowledged=True)
    elif page == 'all':
        items = app.datamgr.get_all_hosts_and_services()
    else:  # WTF?!?
        redirect("/problems")

    # Filter with the user interests
    items = only_related_to(items, user)

    # Ok, if need, appli the search filter
    for s in search:
        s = s.strip()
        if not s:
            continue

        print "SEARCHING FOR", s
        print "Before filtering", len(items)

        elts = s.split(':', 1)
        t = 'hst_srv'
        if len(elts) > 1:
            t = elts[0]
            s = elts[1]

        print 'Search for type %s and pattern %s' % (t, s)
        if not t in filters:
            filters[t] = []
        filters[t].append(s)

        if t == 'hst_srv':
            # We compile the pattern
            pat = re.compile(s, re.IGNORECASE)
            new_items = []
            for i in items:
                if pat.search(i.get_full_name()):
                    new_items.append(i)
                    continue
                to_add = False
                for imp in i.impacts:
                    if pat.search(imp.get_full_name()):
                        to_add = True
                for src in i.source_problems:
                    if pat.search(src.get_full_name()):
                        to_add = True
                if to_add:
                    new_items.append(i)

            items = new_items

        if t == 'hg':
            hg = app.datamgr.get_hostgroup(s)
            print 'And a valid hg filtering for', s
            items = [i for i in items if hg in i.get_hostgroups()]

        if t == 'realm':
            r = app.datamgr.get_realm(s)
            print 'Add a realm filter', r
            items = [i for i in items if i.get_realm() == r]

        if t == 'htag':
            print 'Add a htag filter', s
            items = [i for i in items if s in i.get_host_tags()]

        if t == 'ack':
            print "Got an ack filter", s
            if s == 'false':
                # First look for hosts, so ok for services, but remove problem_has_been_acknowledged elements
                items = [
                    i for i in items if i.__class__.my_type == 'service'
                    or not i.problem_has_been_acknowledged
                ]
                # Now ok for hosts, but look for services, and service hosts
                items = [
                    i for i in items if i.__class__.my_type == 'host' or (
                        not i.problem_has_been_acknowledged
                        and not i.host.problem_has_been_acknowledged)
                ]
            if s == 'true':
                # First look for hosts, so ok for services, but remove problem_has_been_acknowledged elements
                items = [
                    i for i in items if i.__class__.my_type == 'service'
                    or i.problem_has_been_acknowledged
                ]
                # Now ok for hosts, but look for services, and service hosts
                items = [
                    i for i in items if i.__class__.my_type == 'host' or (
                        i.problem_has_been_acknowledged
                        or i.host.problem_has_been_acknowledged)
                ]

        if t == 'downtime':
            print "Got an downtime filter", s
            if s == 'false':
                # First look for hosts, so ok for services, but remove problem_has_been_acknowledged elements
                items = [
                    i for i in items if i.__class__.my_type == 'service'
                    or not i.in_scheduled_downtime
                ]
                # Now ok for hosts, but look for services, and service hosts
                items = [
                    i for i in items if i.__class__.my_type == 'host' or (
                        not i.in_scheduled_downtime
                        and not i.host.in_scheduled_downtime)
                ]
            if s == 'true':
                # First look for hosts, so ok for services, but remove problem_has_been_acknowledged elements
                items = [
                    i for i in items if i.__class__.my_type == 'service'
                    or i.in_scheduled_downtime
                ]
                # Now ok for hosts, but look for services, and service hosts
                items = [
                    i for i in items if i.__class__.my_type == 'host' or
                    (i.in_scheduled_downtime or i.host.in_scheduled_downtime)
                ]

        if t == 'crit':
            print "Add a criticity filter", s
            items = [
                i for i in items
                if (i.__class__.my_type == 'service' and i.state_id == 2) or (
                    i.__class__.my_type == 'host' and i.state_id == 1)
            ]

        print "After filtering for", t, s, 'we got', len(items)

    # If we are in the /problems and we do not have an ack filter
    # we apply by default the ack:false one
    print "Late problem filtering?", page == 'problems', len(
        filters['ack']) == 0
    if page == 'problems' and len(filters['ack']) == 0:
        # First look for hosts, so ok for services, but remove problem_has_been_acknowledged elements
        items = [
            i for i in items if i.__class__.my_type == 'service'
            or not i.problem_has_been_acknowledged
        ]
        # Now ok for hosts, but look for services, and service hosts
        items = [
            i for i in items if i.__class__.my_type == 'host' or (
                not i.problem_has_been_acknowledged
                and not i.host.problem_has_been_acknowledged)
        ]

    # If we are in the /problems and we do not have an ack filter
    # we apply by default the ack:false one
    print "Late problem filtering?", page == 'problems', len(
        filters['downtime']) == 0
    if page == 'problems' and len(filters['downtime']) == 0:
        # First look for hosts, so ok for services, but remove problem_has_been_acknowledged elements
        items = [
            i for i in items
            if i.__class__.my_type == 'service' or not i.in_scheduled_downtime
        ]
        # Now ok for hosts, but look for services, and service hosts
        items = [
            i for i in items if i.__class__.my_type == 'host' or
            (not i.in_scheduled_downtime and not i.host.in_scheduled_downtime)
        ]

    # Now sort it!
    items.sort(hst_srv_sort)

    total = len(items)
    # If we overflow, came back as normal
    if start > total:
        start = 0
        end = 30

    navi = app.helper.get_navi(total, start, step=30)
    items = items[start:end]

    ## print "get all problems:", pbs
    ## for pb in pbs:
    ##     print pb.get_name()
    print 'Give filters', filters
    return {
        'app': app,
        'pbs': items,
        'user': user,
        'navi': navi,
        'search': search_str,
        'page': page,
        'filters': filters,
        'bookmarks': bookmarks,
        'bookmarksro': bookmarksro,
        'toolbar': tool_pref
    }
Exemple #54
0
def user_login_redirect():
    redirect("/user/login")
    return {}
Exemple #55
0
def get_pbs_widget():

    user = app.get_user_auth()
    if not user:
        redirect("/user/login")

    # We want to limit the number of elements, The user will be able to increase it
    nb_elements = max(0, int(app.request.GET.get('nb_elements', '10')))
    search = app.request.GET.get('search', '')

    pbs = app.datamgr.get_all_problems(to_sort=False)

    # Filter with the user interests
    pbs = only_related_to(pbs, user)

    # Sort it now
    pbs.sort(hst_srv_sort)

    # Ok, if need, appli the search filter
    if search:
        print "SEARCHING FOR", search
        print "Before filtering", len(pbs)
        # We compile the pattern
        pat = re.compile(search, re.IGNORECASE)
        new_pbs = []
        for p in pbs:
            if pat.search(p.get_full_name()):
                new_pbs.append(p)
                continue
            to_add = False
            for imp in p.impacts:
                if pat.search(imp.get_full_name()):
                    to_add = True
            for src in p.source_problems:
                if pat.search(src.get_full_name()):
                    to_add = True
            if to_add:
                new_pbs.append(p)

        pbs = new_pbs[:nb_elements]
        print "After filtering", len(pbs)

    pbs = pbs[:nb_elements]

    wid = app.request.GET.get('wid',
                              'widget_problems_' + str(int(time.time())))
    collapsed = (app.request.GET.get('collapsed', 'False') == 'True')

    options = {
        'search': {
            'value': search,
            'type': 'text',
            'label': 'Filter by name'
        },
        'nb_elements': {
            'value': nb_elements,
            'type': 'int',
            'label': 'Max number of elements to show'
        },
    }

    title = 'IT problems'
    if search:
        title = 'IT problems (%s)' % search

    return {
        'app': app,
        'pbs': pbs,
        'user': user,
        'search': search,
        'page': 'problems',
        'wid': wid,
        'collapsed': collapsed,
        'options': options,
        'base_url': '/widget/problems',
        'title': title,
    }