⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 statussections.py

📁 Network Administration Visualized 网络管理可视化源码
💻 PY
📖 第 1 页 / 共 5 页
字号:
# -*- coding: ISO8859-1 -*-# $Id: StatusSections.py 3792 2007-01-15 15:21:34Z jodal $## Copyright 2003, 2004 Norwegian University of Science and Technology# Copyright 2006 UNINETT AS## This file is part of Network Administration Visualized (NAV)## NAV is free software; you can redistribute it and/or modify# it under the terms of the GNU General Public License as published by# the Free Software Foundation; either version 2 of the License, or# (at your option) any later version.## NAV is distributed in the hope that it will be useful,# but WITHOUT ANY WARRANTY; without even the implied warranty of# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the# GNU General Public License for more details.## You should have received a copy of the GNU General Public License# along with NAV; if not, write to the Free Software# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA### Authors: Hans J鴕gen Hoel <hansjorg@orakel.ntnu.no>#          Stein Magnus Jodal <stein.magnus.jodal@uninett.no>#"""Contains classes representing different sections (netboxes down,services down, etc.) on the status and history page"""################################################### Importsimport nav.db.manage,mx.DateTime,navfrom nav.web import urlbuilder################################################### ConstantsFILTER_ALL_SELECTED = 'all_selected_tkn'BASEPATH = '/status/'INFINITY = mx.DateTime.DateTime(999999,12,31,0,0,0)################################################### Classesclass SectionBox:    " A general section on the status or history page "    controlBaseName = None    title = None    maxHeight = None    urlRoot = None    # ManageGetArgs instance    getArgs = None    # Id for sorting    sortId = None    def __init__(self, controlBaseName, title, getArgs, maxHeight = None,\    urlRoot = 'status'):        self.controlBaseName = controlBaseName        self.sortId = controlBaseName + 'sort'        self.getArgs = getArgs        self.urlRoot = urlRoot        self.maxHeight = maxHeight        self.title = title    def addHeadings(self):        # Add headings with sorting urls        i = 1        for text,sort in self.headingDefs:            url = None            style = None            sortBy = i            if (self.getArgs.getArgs(self.sortId)):                if int(self.getArgs.getArgs(self.sortId)[0]) == sortBy:                    # already sorting by this column, reverse it                    sortBy = -i            args = self.getArgs.addArg(self.sortId,repr(sortBy))            url = '%s?%s#%s' % (self.urlRoot,args,self.controlBaseName)                        self.headings.append((text,url,style,self.controlBaseName))            i+=1    def sort(self):        if self.headingDefs[self.sortBy][1]:            compareFunction = self.headingDefs[self.sortBy][1]            self.rows.sort(compareFunction)                else:            self.rows.sort()        if self.sortReverse:            self.rows.reverse()    # Compare function for sorting lists of ip's    def ipCompare(self,ip1,ip2):        # ip1[0] and ip2[0] are the sort parameter        ip1 = ip1[0].split('.')        ip2 = ip2[0].split('.')        r = 0        try:            for i in range(0,4):                r = cmp(int(ip1[i]),int(ip2[i]))                if r != 0:                    break        except:            r = 0        return r################################################### Sections that inherits from SectionBox        class ServiceSectionBox(SectionBox):    " Section displaying services that are down or in shadow "    # attribs for preferences    name = 'Services down'    typeId = 'service'    prefsOptions = None    defaultSort = 3         # -3, thus sortReverse = True    sortReverse = False     sortBy = defaultSort    def __init__(self, controlBaseName,getArgs,title,filterSettings):        # Sort reverse by column 3 (downtime)        self.headings = []        self.headingDefs = [('Sysname',None),                            ('Handler',None),                            ('Down since',None),                            ('Downtime',None),                            ('',None)]        self.rows = []        self.summary = None        self.historyLink = []        self.historyLink.append((BASEPATH + 'history/?type=services',                                 'history'))        self.historyLink.append(('/browse/service/allMatrix',                                 'service status'))        self.filterSettings = filterSettings        SectionBox.__init__(self, controlBaseName,title,getArgs,None)         self.addHeadings()        return     def fill(self):        filterSettings = self.filterSettings            sql = """SELECT DISTINCT n.sysname, s.handler, ah.start_time,                now() - ah.start_time AS downtime, s.up, s.serviceid, n.netboxid            FROM alerthist AS ah, netbox AS n, service AS s            WHERE ah.netboxid = n.netboxid                AND ah.subid = s.serviceid                AND ah.end_time = 'infinity'                AND ah.eventtypeid = 'serviceState'"""         # parse filter settings        where_clause = ''        if filterSettings:            # orgid            if not filterSettings['orgid'].count(FILTER_ALL_SELECTED):                where_clause += " AND ("                first_line = True                for org in filterSettings['orgid']:                    if not first_line:                        where_clause += " OR "                    where_clause += "n.orgid = '" + org + "'"                    first_line = False                where_clause += ") "            # catid            if not filterSettings['handler'].count(FILTER_ALL_SELECTED):                where_clause += " AND ("                first_line = True                for handler in filterSettings['handler']:                    if not first_line:                        where_clause += " OR "                    where_clause += "s.handler = '" + handler + "'"                    first_line = False                where_clause += ") "            # state            self.listStates = filterSettings['state']            if not filterSettings['state'].count(FILTER_ALL_SELECTED):                where_clause += " AND ("                first_line = True                for state in filterSettings['state']:                    if not first_line:                        where_clause += " OR "                    where_clause += "s.up = '" + state + "'"                    first_line = False                where_clause += ") "            else:               where_clause += " AND (s.up = 'n' OR s.up = 's') "        sql = sql + where_clause + " ORDER BY now()-start_time"         connection = nav.db.getConnection('status', 'manage')        database = connection.cursor()        database.execute(sql)        result = database.fetchall()                  # If components is on maintenance, do not show them        sql = """SELECT n.sysname, s.handler, ah.start_time,                now() - ah.start_time AS downtime, s.up, s.serviceid,                n.netboxid            FROM alerthist AS ah, netbox AS n, service AS s            WHERE ah.netboxid = n.netboxid                AND ah.subid = s.serviceid                AND ah.end_time = 'infinity'                AND ah.eventtypeid = 'maintenanceState'"""        database.execute(sql)        result_maint = database.fetchall()                height = len(result)        if self.maxHeight:            if height > self.maxHeight:                height = self.maxHeight        servicesDown = 0        servicesShadow = 0        servicesMaintenance = 0        SYSNAME = 0        HANDLER = 1        STARTTIME = 2        DOWNTIME = 3        UP = 4        SERVICEID = 5        BOXID = 6        # Create list of components on maintenance        onmaint = {}        for line in result_maint:            onmaint[(line[BOXID], line[SERVICEID])] = True                for line in result:            # If on maintenance, skip this component            if (line[BOXID], line[SERVICEID]) in onmaint:                servicesMaintenance += 1                continue            row = []            style = None            if line[UP] == 's':                servicesShadow += 1                #style = 'shadow'             else:                servicesDown += 1             # Sysname            row.append((line[SYSNAME],                        urlbuilder.createUrl(id=line[BOXID],division='netbox'),                        None,style))            # Handler            row.append((line[HANDLER],urlbuilder.createUrl(id=line[HANDLER],                        division='service'),None,style))             # Start            row.append((line[STARTTIME].strftime('%Y-%m-%d %H:%M'),                        None, None, style))            # Downtime            downTime = str(line[DOWNTIME].absvalues()[0]) + ' d, ' + \                       line[DOWNTIME].strftime('%H') + ' h, ' + \                       line[DOWNTIME].strftime('%M') + ' m'            row.append((downTime,None,None,style))            # History link            row.append((None,                        BASEPATH + 'history/?type=services&id=%s' \                        % (line[SERVICEID],),                        ('/images/status/status-history.png',                        'View history for this service'),                        None))            self.rows.append([line[self.sortBy],row])        self.sort()        servicesDown = str(servicesDown)        servicesShadow = str(servicesShadow)        servicesMaintenance = str(servicesMaintenance)        if servicesDown=='0':            servicesDown = 'No'        if servicesShadow=='0':            servicesShadow = 'No'        if not self.listStates.count('s') and self.listStates.count('n'):            self.summary = servicesDown + ' services down'        elif not self.listStates.count('n') and self.listStates.count('s'):            self.summary = servicesShadow + ' services in shadow'        else:            self.summary = servicesDown + ' services down, ' + \                           servicesShadow.lower() + ' in shadow'    def getFilters(controlBaseName,orgList):        """        Returns the filters that this section box accepts        """        filterHeadings = ['Organisation','Service','State']        filterSelects = []        table = nav.db.manage.Org        # Org        optionsList = [(FILTER_ALL_SELECTED,'All',True)]        # Restrict to orgs where user belongs        #whereOrg = makeWhereList(orgList)        for org in table.getAllIterator(orderBy = 'orgid'):            optionsList.append((org.orgid,org.orgid,False))        filterSelects.append((controlBaseName + '_' + 'orgid',optionsList))        # Handler        # FIXME: The handler list should be dynamic (see editdb.py for example)        optionsList = [(FILTER_ALL_SELECTED,'All')]        filterSelects.append((controlBaseName + '_' + 'handler',\            [(FILTER_ALL_SELECTED, 'All', True),            ('dc', 'dc', False),            ('dns', 'dns', False),            ('dummy', 'dummy', False),            ('ftp', 'ftp', False),            ('http', 'http', False),            ('https', 'https', False),            ('imap', 'imap', False),            ('imaps', 'imaps', False),            ('ldap', 'ldap', False),            ('mysql', 'mysql', False),            ('oracle', 'oracle', False),            ('pop3', 'pop3', False),            ('postgresql', 'postgresql', False),            ('radius', 'radius', False),            ('rpc', 'rpc', False),            ('smb', 'smb', False),            ('smtp', 'smtp', False),            ('ssh', 'ssh', False)]        ))        # State        filterSelects.append((controlBaseName + '_' + 'state',\            [(FILTER_ALL_SELECTED, 'All', True),            ('y', 'Up', False),            ('n', 'Down', False),            ('s', 'Shadow', False)]        ))        return (filterHeadings,filterSelects)    getFilters = staticmethod(getFilters)class ServiceMaintenanceSectionBox(SectionBox):    " Section displaying services that are on maintenance "    name = 'Services on maintenance'    typeId = 'servicemaint'    prefsOptions = None    defaultSort = 3    sortReverse = False     sortBy = defaultSort    def __init__(self, controlBaseName, getArgs, title, filterSettings):

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -