Skip to content

Instantly share code, notes, and snippets.

@albertogaona
Created February 8, 2017 15:34
Show Gist options
  • Save albertogaona/795252c4db20119845435e23999127af to your computer and use it in GitHub Desktop.
Save albertogaona/795252c4db20119845435e23999127af to your computer and use it in GitHub Desktop.
Navegar las rutas de un dipositivo zenoss
"""Navega la estructura de un device y obtiene todas las graficas correspondientes al mismo"""
import logging
import os
import sys
import string
import xml.dom.minidom
from xml.dom.minidom import Document
#from Products.ZenModel.ConfigurationError import ConfigurationError
#from Products.ZenModel.DataRoot import DataRoot
import urllib
from zExceptions import NotFound
# Find the best implementation available on this platform
try:
from cStringIO import StringIO
except:
from StringIO import StringIO
import csv
try:
import zen
except Exception, ex:
print "excepcion tratando de importar zen: " + ex
class IndicadorTemporal:
epoch = ''
valor = 'nan'
class DefaultPeriod:
start = 0
end = 0
class DeviceInfo:
devicePath = ''
devicePathDecoded = ''
ipAddress = ''
graficas = []
interfaces = []
class InterfaceInfo:
name = ''
ipAddress = ''
graficas = []
class GraficaInfo:
id = ''
template = ''
units = ''
series = []
class SerieInfo:
id = ''
color = ''
description = ''
rrdFile = ''
valores = []
class ValorInfo:
epoch = None
value = None
import traceback
def formatExceptionInfo(maxTBlevel=5):
cla, exc, trbk = sys.exc_info()
excName = cla.__name__
try:
excArgs = exc.__dict__['args']
except KeyError:
excArgs = '<no args>'
excTb = traceback.format_tb(trbk, maxTBlevel)
return (excName, excArgs, excTb)
class InspectorDevice:
"""Crea un documento XML a partir de un device definido en el Zenoss"""
def __init__(self, loggingLevel=logging.NOTSET):
self.log = logging.getLogger('dmx.InspectorDevice')
self.log.setLevel(loggingLevel)
self.loggingLevel = loggingLevel
self.log.info("#################################################################")
self.log.info("INICIA GENERACION DEL LOG")
self.log.info("#################################################################")
#general fields
zenossDevice = None
devicePath = None
#xml nodes fields
doc = None
dataSources = None
interfaceList = None
# Obtener el home de zenoss
ZENHOME = os.environ.get('ZENHOME', '/opt/zenoss')
if ZENHOME.endswith(os.sep):
ZENHOME = os.path.dirname(ZENHOME)
def getZenHome(self):
return self.ZENHOME
def generaXml(self, devicePath, start, end):
"""Escribe la estructura principal XML del device cuando este existe"""
if not devicePath:
self.traceWarn("generaXml(): devicePath es nulo")
return None
self.traceInfo('generaXml(): devicePath=' + devicePath)
self.traceInfo('generaXml(): start=' + start)
self.traceInfo('generaXml(): end=' + end)
try:
start = string.atoi(start)
end = string.atoi(end)
except:
self.traceError('generaXml(): Formato incorrecto de start/end. Deben ser numericos')
raise # Exception('Formato incorrecto de start/end. Deben ser numericos')
self.devicePath = devicePath
# try:
# import zen
# except IOError:
# self.traceError("generaXml(): devicePath = " + devicePath)
# self.traceError("generaXml(): excepcion tratando de importar zen")
z = zen.Zen()
self.zenossDevice = z.zenFindByPath(devicePath)
self.doc = Document()
#por salud mental creamos una referencia:
doc = self.doc
device = doc.createElement("device")
doc.appendChild(device)
ipAddress = doc.createElement("ipAddress")
device.appendChild(ipAddress)
ipAddressValue = doc.createTextNode(self.zenossDevice.getManageIp())
ipAddress.appendChild(ipAddressValue)
tag = doc.createElement("tag")
device.appendChild(tag)
tagValue = doc.createTextNode("")
tag.appendChild(tagValue)
graficas = doc.createElement("graficas")
device.appendChild(graficas)
interfaceList = doc.createElement("interfaceList")
device.appendChild(interfaceList)
self.traceDebug('generaXml(): DeviceName=' + self.zenossDevice.id)
monitoredComponents = self.zenossDevice.getDeviceComponents()
for component in monitoredComponents:
self.traceDebug('generaXml(): monitoredComponent.name=' + component.name())
try:
nombreInterface = component.getInterfaceName()
if component.monitor:
tieneGraficas = self.tieneGraficasInterface(z, devicePath, nombreInterface, start, end);
msg = 'generaXml(): monitoredComponent.name=' , component.name(), ' tieneGraficas: ' , tieneGraficas
self.traceDebug(msg)
if tieneGraficas:
interface = doc.createElement('interface')
interface.setAttribute('name', component.getInterfaceName().__str__())
interface.setAttribute('operStatus', component.operStatus.__str__())
interface.setAttribute('ipAddress', component.getIpAddress().__str__())
interface.setAttribute('speed', component.niceSpeed().__str__())
interface.setAttribute('mac', component.getInterfaceMacaddress().__str__())
interface.setAttribute('network', component.getNetworkName().__str__())
interfaceList.appendChild(interface)
except:
self.traceDebug('generaXml(): (no es interface)')
for template in self.zenossDevice.getRRDTemplates() :
self.traceDebug('generaXml(): Template=' + template.id)
for graphDef in template.getGraphDefs():
self.traceDebug('generaXml(): -GraphDef=' + graphDef.id)
grafica = doc.createElement('grafica')
grafica.setAttribute('name', graphDef.id)
grafica.setAttribute('unidades', graphDef.units)
tieneDataPoints = False
for graphPoint in graphDef.getGraphPoints():
self.traceDebug('generaXml(): --graphPoint.id=' + graphPoint.id)
self.traceDebug('generaXml(): --graphPoint.descripcion=' + graphPoint.getDescription())
target = "perf/Devices/" + self.zenossDevice.id + "/" + graphPoint.escapeForRRD(graphPoint.getDescription()) + '.rrd';
target = os.path.join(self.getZenHome(), target)
self.traceDebug('generaXml(): target=' + target)
xmlGraphPoint = doc.createElement('graphPoint')
xmlGraphPoint.setAttribute('name', graphPoint.id)
xmlGraphPoint.setAttribute('color', graphPoint.color)
grafica.appendChild(xmlGraphPoint)
xmlDataPoints = doc.createElement('dataPoints')
xmlGraphPoint.appendChild(xmlDataPoints)
if graphPoint.getType() <> 'Threshold':
xmlGraphPoint.setAttribute('rpn', graphPoint.rpn)
self.traceDebug('generaXml(): rpn=' + graphPoint.rpn)
indicadores = self.obtenValoresDataSource(target, graphPoint.rpn, start, end)
if indicadores <> None:
for indicadorTemporal in indicadores:
xmlDataPoint = doc.createElement('dataPoint')
xmlDataPoint.setAttribute('time', indicadorTemporal.epoch)
xmlDataPoint.setAttribute('value', indicadorTemporal.valor)
xmlDataPoints.appendChild(xmlDataPoint)
tieneDataPoints = True
self.traceDebug('generaXml(): epoch =' + indicadorTemporal.epoch + '; indicador=' + indicadorTemporal.valor)
if tieneDataPoints:
graficas.appendChild(grafica)
result = self.doc.toprettyxml(indent=" ")
self.traceDebug(result)
self.traceDebug("generaXml(): done !")
return result
def generaGraficasInterfaceXml(self, devicePath, start, end, nombreInterface):
"""Genera los valores en formato Xml de los indicadores desempeno para todos los templates de una interface"""
nombreInterfaceHomologado = nombreInterface.__str__().replace("/", "_").replace(":", "_").replace("%20", " ").replace(";", "_")
self.traceDebug("generaGraficasInterfaceXml(): nombreInterface =" + nombreInterface)
self.traceDebug("generaGraficasInterfaceXml(): nombreInterfaceHomologado=" + nombreInterfaceHomologado)
if not devicePath:
self.traceWarn("generaGraficasInterfaceXml: devicePath es nulo")
return None
self.traceDebug('generaGraficasInterfaceXml(): start=' + start)
self.traceDebug('generaGraficasInterfaceXml(): end=' + end)
try:
start = string.atoi(start)
end = string.atoi(end)
except:
self.traceError('generaGraficasInterfaceXml(): Formato incorrecto de start/end. Deben ser numericos')
raise # Exception('Formato incorrecto de start/end. Deben ser numericos')
self.devicePath = devicePath
# try:
# import zen
# except IOError:
# self.traceError("generaGraficasInterfaceXml(): devicePath = " % devicePath)
# self.traceError("generaGraficasInterfaceXml(): excepcion tratando de importar zen")
z = zen.Zen()
nombreCompletoInterface = devicePath + "/os/interfaces/" + nombreInterfaceHomologado
#primero buscamos el device para saber su id en el filesystem y ayudar en la busqueda de los RRD: i
self.zenossDevice = z.zenFindByPath(devicePath)
nombreDispositivoFilesystem = self.zenossDevice.id
self.zenossDevice = z.zenFindByPath(nombreCompletoInterface)
self.doc = Document()
#por salud mental creamos una referencia:
doc = self.doc
interface = doc.createElement("interface")
doc.appendChild(interface)
graficas = doc.createElement("graficas")
interface.appendChild(graficas)
#-----------------------------------------------------------------------------
for template in self.zenossDevice.getRRDTemplates():
#print 'Template=' + template.id
for graphDef in template.getGraphDefs():
#print '-GraphDef=' + graphDef.id
grafica = doc.createElement('grafica')
grafica.setAttribute('name', graphDef.id)
grafica.setAttribute('unidades', graphDef.units)
tieneDataPoints = False
for graphPoint in graphDef.getGraphPoints():
self.traceDebug('generaGraficasInterfaceXml(): --graphPoint=' + graphPoint.id)
#self.traceDebug('generaCsv(): ---graphPoint.descripcion=' + graphPoint.getDescription())
target = "perf/Devices/" + nombreDispositivoFilesystem + "/os/interfaces/" + nombreInterfaceHomologado + "/" + graphPoint.escapeForRRD(graphPoint.getDescription()) + '.rrd';
target = os.path.join(self.getZenHome(), target)
self.traceDebug('generaGraficasInterfaceXml(): target=' + target)
xmlGraphPoint = doc.createElement('graphPoint')
xmlGraphPoint.setAttribute('name', graphPoint.id)
xmlGraphPoint.setAttribute('color', graphPoint.color)
xmlGraphPoint.setAttribute('rpn', '')
grafica.appendChild(xmlGraphPoint)
xmlDataPoints = doc.createElement('dataPoints')
xmlGraphPoint.appendChild(xmlDataPoints)
if graphPoint.getType() <> 'Threshold':
xmlGraphPoint.setAttribute('rpn', graphPoint.rpn)
self.traceDebug('generaGraficasInterfaceXml(): rpn=' + graphPoint.rpn)
indicadores = self.obtenValoresDataSource(target, graphPoint.rpn, start, end)
if indicadores == None or indicadores.__len__() == 0:
xmlDataPoint = doc.createElement('dataPoint')
xmlDataPoint.setAttribute('time', '0')
xmlDataPoint.setAttribute('value', '0')
xmlDataPoints.appendChild(xmlDataPoint)
tieneDataPoints = True
else:
for indicadorTemporal in indicadores:
xmlDataPoint = doc.createElement('dataPoint')
xmlDataPoint.setAttribute('time', indicadorTemporal.epoch)
xmlDataPoint.setAttribute('value', indicadorTemporal.valor)
xmlDataPoints.appendChild(xmlDataPoint)
tieneDataPoints = True
else:
xmlDataPoint = doc.createElement('dataPoint')
xmlDataPoint.setAttribute('time', '0')
xmlDataPoint.setAttribute('value', '0')
xmlDataPoints.appendChild(xmlDataPoint)
tieneDataPoints = True
if tieneDataPoints:
graficas.appendChild(grafica)
result = self.doc.toprettyxml(indent=" ")
self.traceDebug(result)
self.traceDebug("generaGraficasInterfaceXml(): done !")
return result
def generaLinksXml(self, devicePath):
"""Devuelve los links para las graficas del device especificado"""
if not devicePath:
self.traceWarn("generaLinksXml(): devicePath es nulo")
return None
self.traceDebug('generaLinksXml(): devicePath=' + devicePath)
self.devicePath = devicePath
# try:
# import zen
# except IOError:
# self.traceError("writeBackBone( self, devicePath ) ")
# self.traceError("writeBackBone: devicePath = " % devicePath)
# self.traceError("writeBackBone: excepcion tratando de importar zen")
z = zen.Zen()
self.zenossDevice = z.zenFindByPath(devicePath)
self.doc = Document()
#por salud mental creamos una referencia:
doc = self.doc
device = doc.createElement("device")
doc.appendChild(device)
ipAddress = doc.createElement("ipAddress")
device.appendChild(ipAddress)
ipAddressValue = doc.createTextNode(self.zenossDevice.getManageIp())
ipAddress.appendChild(ipAddressValue)
tag = doc.createElement("tag")
device.appendChild(tag)
tagValue = doc.createTextNode("")
tag.appendChild(tagValue)
graficas = doc.createElement("graficas")
device.appendChild(graficas)
interfaceList = doc.createElement("interfaceList")
device.appendChild(interfaceList)
self.traceDebug('generaLinksXml(): DeviceName=' + self.zenossDevice.id)
monitoredComponents = self.zenossDevice.getDeviceComponents()
for component in monitoredComponents:
self.traceDebug('generaLinksXml(): monitoredComponent.name=' + component.name())
try:
nombreInterface = component.getInterfaceName()
except:
self.traceDebug('generaLinksXml(): (no es interface)')
continue
try:
if component.monitor:
tieneGraficas = self.tieneGraficasInterface(z, devicePath, nombreInterface);
msg = 'generaLinksXml(): monitoredComponent.name=' , component.name(), ' tieneGraficas: ' , tieneGraficas
self.traceDebug(msg)
if tieneGraficas:
interface = doc.createElement('interface')
interface.setAttribute('name', component.getInterfaceName().__str__())
interface.setAttribute('operStatus', component.operStatus.__str__())
interface.setAttribute('ipAddress', component.getIpAddress().__str__())
interface.setAttribute('speed', component.niceSpeed().__str__())
interface.setAttribute('mac', component.getInterfaceMacaddress().__str__())
interface.setAttribute('network', component.getNetworkName().__str__())
interfaceList.appendChild(interface)
except Exception:
self.traceError('generaLinksXml(): error al analizar la interfaz: ' + nombreInterface)
exceptionInfo = formatExceptionInfo(10).__str__()
print exceptionInfo
self.traceError('generaLinksXml(): ' + exceptionInfo)
drange = 129600
#drange = DataRoot.defaultDateRange
for template in self.zenossDevice.getRRDTemplates() :
self.traceDebug('generaLinksXml(): Template=' + template.id)
for graphDef in template.getGraphDefs():
self.traceDebug('generaLinksXml(): -GraphDef=' + graphDef.id)
grafica = doc.createElement('grafica')
grafica.setAttribute('name', graphDef.id)
grafica.setAttribute('unidades', graphDef.units)
url = self.zenossDevice.getGraphDefUrl(graphDef, drange, template)
self.traceDebug('generaLinksXml(): -url=' + url)
grafica.appendChild(doc.createCDATASection(url))
#graficas.appendChild(grafica)
tieneDataPoints = False
for graphPoint in graphDef.getGraphPoints():
self.traceDebug('generaLinksXml(): --graphPoint.id=' + graphPoint.id)
self.traceDebug('generaLinksXml(): --graphPoint.descripcion=' + graphPoint.getDescription())
target = "perf/Devices/" + self.zenossDevice.id + "/" + graphPoint.escapeForRRD(graphPoint.getDescription()) + '.rrd';
target = os.path.join(self.getZenHome(), target)
self.traceDebug('generaLinksXml(): target=' + target)
if graphPoint.getType() <> 'Threshold':
self.traceDebug('generaLinksXml(): rpn=' + graphPoint.rpn)
# obtener el periodo por default
defaultPeriod = self.getDefaultPeriod(target, None, None)
if not defaultPeriod:
self.traceDebug("generaLinksXml(): no tiene archivo, revisar siguiente 'graphPoint'")
continue
start = defaultPeriod.start
end = defaultPeriod.end
indicadores = self.obtenValoresDataSource(target, graphPoint.rpn, start, end)
if indicadores <> None:
tieneDataPoints = indicadores.__len__() > 0
break
if tieneDataPoints:
graficas.appendChild(grafica)
result = self.doc.toprettyxml(indent=" ")
self.traceDebug(result)
self.traceDebug("generaLinksXml(): done !")
return result
def generaLinksGraficasInterfaceXml(self, devicePath, nombreInterface):
"""Genera los valores en formato Xml de los indicadores desempeno para todos los templates de una interface"""
nombreInterfaceHomologado = nombreInterface.__str__().replace("/", "_").replace(":", "_").replace("%20", " ").replace(";", "_")
self.traceDebug("generaLinksGraficasInterfaceXml(): nombreInterface =" + nombreInterface)
self.traceDebug("generaLinksGraficasInterfaceXml(): nombreInterfaceHomologado=" + nombreInterfaceHomologado)
if not devicePath:
self.traceWarn("generaLinksGraficasInterfaceXml(): devicePath es nulo")
return None
self.devicePath = devicePath
# try:
# import zen
# except IOError:
# self.traceError("generaLinksGraficasInterfaceXml: devicePath = " % devicePath)
# self.traceError("generaLinksGraficasInterfaceXml: excepcion tratando de importar zen")
z = zen.Zen()
nombreCompletoInterface = devicePath + "/os/interfaces/" + nombreInterfaceHomologado
self.traceDebug("generaLinksGraficasInterfaceXml(): nombreCompletoInterface=" + nombreCompletoInterface)
#primero buscamos el device para obtener su id en el filesystem y ayudar en la busqueda de los RRD: i
self.zenossDevice = z.zenFindByPath(devicePath)
nombreDispositivoFilesystem = self.zenossDevice.id
self.zenossDevice = z.zenFindByPath(nombreCompletoInterface)
self.doc = Document()
#por salud mental creamos una referencia:
doc = self.doc
interface = doc.createElement("interface")
doc.appendChild(interface)
graficas = doc.createElement("graficas")
interface.appendChild(graficas)
drange = 129600
#drange = DataRoot.defaultDateRange
#-----------------------------------------------------------------------------
for template in self.zenossDevice.getRRDTemplates() :
self.traceDebug('generaLinksGraficasInterfaceXml(): Template=' + template.id)
for graphDef in template.getGraphDefs():
self.traceDebug('generaLinksGraficasInterfaceXml(): -GraphDef=' + graphDef.id)
grafica = doc.createElement('grafica')
grafica.setAttribute('name', graphDef.id)
grafica.setAttribute('unidades', graphDef.units)
url = self.zenossDevice.getGraphDefUrl(graphDef, drange, template)
self.traceDebug('generaLinksGraficasInterfaceXml(): -url=' + url)
grafica.appendChild(doc.createCDATASection(url))
graficas.appendChild(grafica)
result = self.doc.toprettyxml(indent=" ")
self.traceDebug(result)
return result
def obtenValoresDataSource(self, pathRRD, rpn, start, end):
if not os.path.isfile(pathRRD):
#raise Exception('Archivo ' + pathRRD + ' no existe')
self.traceDebug('obtenValoresDataSource(): Archivo ' + pathRRD + ' no existe')
return None
command = "rrdtool fetch '" + pathRRD + "' AVERAGE --start %d --end %d" \
% (start, end)
self.traceDebug('obtenValoresDataSource(): *****command2=\n' + command)
process = os.popen(command)
if process:
self.traceDebug('obtenValoresDataSource(): command 2 ejecutado con exito')
process.readline() # dropping ds0
process.readline() # dropping null line
resultado = []
while True:
line = process.readline()
if line == "": break
temp = line.split(": ")
if temp.__len__() >= 2:
#print ' temp=' + temp[0] + ',' + temp[1]
indicador = temp[1]
indicadorTemporal = IndicadorTemporal()
indicadorTemporal.epoch = temp[0]
indicadorTemporal.valor = indicador
resultado.append(indicadorTemporal)
if resultado.__len__() == 0:
return None
return resultado
else:
self.traceError("obtenValoresDataSource(): Fallo comando de obtencion de indicadores " + command)
raise Exception("obtenValoresDataSource(): Fallo comando de obtencion de indicadores " + command)
def obtenValorNumericoDeCadenaComoCadena(self, indicador):
if indicador == 'nan':
return indicador
resultado = float(indicador).__str__()
#print 'obtenValorNumericoDeCadenaComoCadena.resultado=' + resultado
return resultado
def evaluaExpresionRpn(self, indicador, rpn):
if rpn == '':
return indicador
valorCadena = self.obtenValorNumericoDeCadenaComoCadena(indicador)
if valorCadena == 'nan':
return 'nan'
valor = float(valorCadena)
operandos = rpn.split(',')
if len(operandos) <> 2:
raise Exception('solo estan soportadas expresiones rpn de dos elementos (p.e. 512,*')
reductor = float(operandos[0])
operador = operandos[1]
if operador == '*':
resultado = valor * reductor
elif operador == '/':
if reductor == 0:
raise Exception('Operacion RPN causaria division entre cero')
resultado = valor / reductor
elif operador == '+':
resultado = valor + reductor
elif operador == '-':
resultado = valor - reductor
else:
raise Exception('Operador ' + operador + ' no soportado en evaluacion de RPN')
return resultado.__str__()
def tieneGraficasInterface(self, zen, devicePath, nombreInterface, start=None, end=None):
"""Genera los valores en formato Xml de los indicadores desempeno para todos los templates de una interface"""
nombreInterfaceHomologado = nombreInterface.__str__().replace("/", "_").replace(":", "_").replace("%20", " ").replace(";", "_")
self.traceDebug("tieneGraficasInterface(): nombreInterface =" + nombreInterface)
self.traceDebug("tieneGraficasInterface(): nombreInterfaceHomologado=" + nombreInterfaceHomologado)
if not devicePath:
self.traceWarn("tieneGraficasInterface(): devicePath es nulo")
return False
#primero buscamos el device para saber su id en el filesystem y ayudar en la busqueda de los RRD: i
nombreCompletoInterface = devicePath + "/os/interfaces/" + nombreInterfaceHomologado
nombreDispositivoFilesystem = self.zenossDevice.id
zenossInterface = zen.zenFindByPath(nombreCompletoInterface)
#-----------------------------------------------------------------------------
for template in zenossInterface.getRRDTemplates():
#print 'Template=' + template.id
for graphDef in template.getGraphDefs():
#print '-GraphDef=' + graphDef.id
for graphPoint in graphDef.getGraphPoints():
self.traceDebug('tieneGraficasInterface(): --graphPoint=' + graphPoint.id)
target = "perf/Devices/" + nombreDispositivoFilesystem + "/os/interfaces/" + nombreInterfaceHomologado + "/" + graphPoint.escapeForRRD(graphPoint.getDescription()) + '.rrd';
target = os.path.join(self.getZenHome(), target)
self.traceDebug('tieneGraficasInterface(): target=' + target)
if graphPoint.getType() <> 'Threshold':
#print 'rpn=' + graphPoint.rpn
if not start or not end:
defaultPeriod = self.getDefaultPeriod(target, start, end)
if not defaultPeriod:
self.traceDebug("tieneGraficasInterface(): no tiene archivo, revisar siguiente 'graphPoint'")
continue
start = defaultPeriod.start
end = defaultPeriod.end
indicadores = self.obtenValoresDataSource(target, graphPoint.rpn, start, end)
if indicadores <> None:
return True
#-----------------------------------------------------------------------------
return False
def getDefaultPeriod(self, target=None, start=None, end=None):
"""Returns a default period if 'start' or 'end' parameters are none"""
if not target:
self.traceWarn("getDefaultPeriod(): target es nulo")
return None
if not os.path.isfile(target):
self.traceDebug("getDefaultPeriod(): target not found as a file: " + target)
return None
filtro1 = str.replace(target, " ", "\ ")
filtro2 = str.replace(filtro1, "(", "\(")
filtro3 = str.replace(filtro2, ")", "\)")
command = "rrdtool info %s" % filtro3
process = os.popen(command)
if not process:
self.traceWarn("getDefaultPeriod(): process es nulo")
return None
process.readline() #dropping filename
process.readline() #dropping version
tempStep = process.readline() #getting step
temp = tempStep.split("=")
try:
step = int(temp[1])
except ValueError:
self.traceWarn("getDefaultPeriod(): exception trying to cast step from string to int !")
self.traceWarn("getDefaultPeriod(): " + tempStep)
self.traceWarn("getDefaultPeriod(): assuming default step = 300")
step = 300
tempLastUpdate = process.readline() #getting lastUpdate
temp = tempLastUpdate.split("=")
try:
if not end:
end = int(temp[1])
except ValueError:
self.traceError("getDefaultPeriod(): exception trying to cast lastUpdate from string to int !")
self.traceError("getDefaultPeriod(): " + tempLastUpdate)
return None
if not start:
start = end - (step * 300)
result = DefaultPeriod()
result.start = start
result.end = end
return result
def generaListaDeGraficasXml(self, deviceList):
if deviceList == None:
self.traceWarn("generaListaDeGraficasXml(): deviceList es nulo, se devuelve XML vacio")
doc = Document()
graficasNode = doc.createElement("graficas")
graficasNode.setAttribute("countGraficasDevices", "0")
graficasNode.setAttribute("countGraficasInterfaces", "0")
doc.appendChild(graficasNode)
return doc.toprettyxml(indent=" ")
# try:
# import zen
# except IOError:
# self.traceError("generaListaDeGraficasXml: excepcion IOError tratando de importar zen")
# return
zenConnection = zen.Zen()
# Escanear cada device para obtener las graficas de cada uno
listaDeGraficasDevicesGlobal = {}
listaDeGraficasInterfacesGlobal = {}
for devicePath in deviceList:
[listaDeGraficas, listaDeGraficasInterfaces] = self.obtenListaDeGraficas(zenConnection, devicePath)
# Hacer el acumulado de las URLs de cada grafica
if listaDeGraficas:
for name in listaDeGraficas:
url = listaDeGraficas.get(name)
if not listaDeGraficasDevicesGlobal.has_key(name):
listaDeGraficasDevicesGlobal[name] = []
listaDeUrls = listaDeGraficasDevicesGlobal.get(name)
listaDeUrls.append(url)
# Hacer el acumulado de las URLs de cada grafica
if listaDeGraficasInterfaces:
for name in listaDeGraficasInterfaces:
listaDeUrlsLocal = listaDeGraficasInterfaces.get(name)
if not listaDeGraficasInterfacesGlobal.has_key(name):
listaDeGraficasInterfacesGlobal[name] = []
listaDeUrlsGlobal = listaDeGraficasInterfacesGlobal.get(name)
for url in listaDeUrlsLocal:
listaDeUrlsGlobal.append(url)
# Armar el XML de salida
doc = Document()
graficasNode = doc.createElement("graficas")
graficasNode.setAttribute("countGraficasDevices", listaDeGraficasDevicesGlobal.__len__().__str__())
graficasNode.setAttribute("countGraficasInterfaces", listaDeGraficasInterfacesGlobal.__len__().__str__())
for graficaDevice in listaDeGraficasDevicesGlobal:
graficaNode = doc.createElement("grafica")
graficaNode.setAttribute("name", graficaDevice)
graficaNode.setAttribute("source", "device")
listaDeUrls = listaDeGraficasDevicesGlobal[graficaDevice]
graficaNode.setAttribute("count", listaDeUrls.__len__().__str__())
for url in listaDeUrls:
urlNode = doc.createElement("url")
urlNode.setAttribute("devicePath", url[1]) #el path del device
urlNode.appendChild(doc.createCDATASection(url[0])) #el URL para la grafica de este device
graficaNode.appendChild(urlNode)
graficasNode.appendChild(graficaNode)
for graficaDevice in listaDeGraficasInterfacesGlobal:
graficaNode = doc.createElement("grafica")
graficaNode.setAttribute("name", graficaDevice)
graficaNode.setAttribute("source", "interface")
listaDeUrls = listaDeGraficasInterfacesGlobal[graficaDevice]
graficaNode.setAttribute("count", listaDeUrls.__len__().__str__())
for url in listaDeUrls:
urlNode = doc.createElement("url")
urlNode.setAttribute("interfaceName", url[2]) #el nombre de la interface
urlNode.setAttribute("devicePath", url[1]) #el path del device
urlNode.appendChild(doc.createCDATASection(url[0])) #el URL para la grafica de este device
graficaNode.appendChild(urlNode)
graficasNode.appendChild(graficaNode)
doc.appendChild(graficasNode)
result = doc.toprettyxml(indent=" ")
self.traceDebug(result)
return result
def obtenListaDeGraficas(self, zenConnection, devicePath):
"""Devuelve la lista de las graficas del device especificado"""
if not devicePath:
self.traceWarn("obtenListaDeGraficas(): devicePath es nulo")
return [None, None]
self.traceDebug('obtenListaDeGraficas(): devicePath=' + devicePath)
devicePathDecoded = devicePath.__str__().replace('%20', ' ')
self.traceDebug('obtenListaDeGraficas(): devicePathDecoded=' + devicePathDecoded)
try:
zenossDevice = zenConnection.zenFindByPath(devicePathDecoded)
except NotFound:
self.traceError("obtenListaDeGraficas: excepcion NotFound tratando de obtener el device: " + devicePathDecoded)
return [None, None]
if zenossDevice == None:
self.traceWarn("obtenListaDeGraficas(): zenossDevice es nulo")
return [None, None]
self.traceDebug('obtenListaDeGraficas(): zenossDevice.getManageIp()=' + zenossDevice.getManageIp())
self.traceDebug('obtenListaDeGraficas(): zenossDevice.id=' + zenossDevice.id)
drange = 129600
graficasInterfaces = {}
monitoredComponents = zenossDevice.getDeviceComponents()
for component in monitoredComponents:
self.traceDebug('obtenListaDeGraficas(): monitoredComponent.name=' + component.name())
try:
nombreInterface = component.getInterfaceName()
if component.monitor:
# decodificar el nombre de la interface
nombreInterfaceHomologado = nombreInterface.__str__().replace("/", "_").replace(":", "_").replace("%20", " ").replace(";", "_")
self.traceDebug("obtenListaDeGraficas(): nombreInterfaceHomologado=" + nombreInterfaceHomologado)
#primero buscamos el device para saber su id en el filesystem y ayudar en la busqueda de los RRD: i
nombreCompletoInterface = devicePath + "/os/interfaces/" + nombreInterfaceHomologado
nombreDispositivoFilesystem = zenossDevice.id
zenossInterface = zenConnection.zenFindByPath(nombreCompletoInterface)
# recorrer los templates para sacar las graficas que contiene
for template in zenossInterface.getRRDTemplates():
self.traceDebug('obtenListaDeGraficas(): Template=' + template.id)
for graphDef in template.getGraphDefs():
self.traceDebug('obtenListaDeGraficas(): -GraphDef=' + graphDef.id)
url = zenossInterface.getGraphDefUrl(graphDef, drange, template)
self.traceDebug('obtenListaDeGraficas(): -url=' + url)
#graficasInterfaces[graphDef.id] = [url, devicePath, nombreInterface]
if not graficasInterfaces.has_key(graphDef.id):
graficasInterfaces[graphDef.id] = []
listaDeUrls = graficasInterfaces.get(graphDef.id)
listaDeUrls.append([url, devicePath, nombreInterface])
except:
self.traceDebug('obtenListaDeGraficas(): (no es interface)')
graficasDevices = {}
for template in zenossDevice.getRRDTemplates():
self.traceDebug('obtenListaDeGraficas(): Template=' + template.id)
for graphDef in template.getGraphDefs():
self.traceDebug('obtenListaDeGraficas(): -GraphDef=' + graphDef.id)
url = zenossDevice.getGraphDefUrl(graphDef, drange, template)
self.traceDebug('obtenListaDeGraficas(): -url=' + url)
tieneDataPoints = False
for graphPoint in graphDef.getGraphPoints():
self.traceDebug('obtenListaDeGraficas(): --graphPoint.id=' + graphPoint.id)
self.traceDebug('obtenListaDeGraficas(): --graphPoint.descripcion=' + graphPoint.getDescription())
target = "perf/Devices/" + zenossDevice.id + "/" + graphPoint.escapeForRRD(graphPoint.getDescription()) + '.rrd';
target = os.path.join(self.getZenHome(), target)
self.traceDebug('obtenListaDeGraficas(): target=' + target)
if graphPoint.getType() <> 'Threshold':
self.traceDebug('obtenListaDeGraficas(): rpn=' + graphPoint.rpn)
# obtener el periodo por default
defaultPeriod = self.getDefaultPeriod(target, None, None)
if not defaultPeriod:
msg = "no existe archivo '%s' - revisar siguiente 'graphPoint'" % target
self.traceDebug(msg)
continue
start = defaultPeriod.start
end = defaultPeriod.end
indicadores = self.obtenValoresDataSource(target, graphPoint.rpn, start, end)
if indicadores <> None:
tieneDataPoints = indicadores.__len__() > 0
break
if tieneDataPoints:
graficasDevices[graphDef.id] = [url, devicePath]
return [graficasDevices, graficasInterfaces]
def diagnosticaDeviceListXml(self, deviceList):
if deviceList == None:
self.traceWarn("diagnosticaDeviceListXml(): deviceList es nulo, se devuelve XML vacio")
doc = Document()
diagnosticosNode = doc.createElement("results")
diagnosticosNode.setAttribute("countOfDevicesOk", "0")
diagnosticosNode.setAttribute("countOfDevicesError", "0")
doc.appendChild(diagnosticosNode)
return doc.toprettyxml(indent=" ")
# try:
# import zen
# except IOError:
# self.traceError("diagnosticaDeviceListXml(): excepcion IOError tratando de importar zen")
# return
zenConnection = zen.Zen()
# Validar la existencia de cada device
# deviceListOk = []
deviceListError = []
for devicePath in deviceList:
if not self.validaDevicePath(zenConnection, devicePath):
deviceListError.append(devicePath)
# else:
# deviceListOk.append(devicePath)
# Armar el XML de salida
doc = Document()
diagnosticosNode = doc.createElement("results")
# diagnosticosNode.setAttribute("countOfDevicesOk", deviceListOk.__len__().__str__())
diagnosticosNode.setAttribute("countOfDevicesError", deviceListError.__len__().__str__())
# # Agregar resultados del diagnostico al XML de salida
# for device in deviceListOk:
#
# deviceNode = doc.createElement("deviceOk")
# deviceNode.setAttribute("name", device)
# diagnosticosNode.appendChild(deviceNode)
# Agregar resultados del diagnostico al XML de salida
for device in deviceListError:
deviceNode = doc.createElement("deviceError")
deviceNode.setAttribute("name", device)
diagnosticosNode.appendChild(deviceNode)
doc.appendChild(diagnosticosNode)
#return doc.toprettyxml(indent=" ")
result = doc.toprettyxml(indent=" ")
self.traceDebug(result)
return result
def validaDevicePath(self, zenConnection, devicePath):
"""Valida la existencia del device especificado"""
if not devicePath:
self.traceWarn("validaDevicePath(): devicePath es nulo")
return False
self.traceDebug('validaDevicePath(): devicePath=' + devicePath)
devicePathDecoded = devicePath.__str__().replace('%20', ' ')
self.traceDebug('validaDevicePath(): devicePathDecoded=' + devicePathDecoded)
try:
zenossDevice = zenConnection.zenFindByPath(devicePathDecoded)
except NotFound:
self.traceDebug("validaDevicePath(): validaDevicePath: excepcion NotFound tratando de obtener el device: " + devicePathDecoded)
return False
if zenossDevice == None:
return False
self.traceDebug('validaDevicePath(): zenossDevice.getManageIp()=' + zenossDevice.getManageIp())
self.traceDebug('validaDevicePath(): zenossDevice.id=' + zenossDevice.id)
return True
def traceDebug(self, message):
#self.log.setLevel(self.loggingLevel)
self.log.debug(message)
# if self.loggingLevel >= logging.DEBUG:
# print message
def traceInfo(self, message):
#self.log.setLevel(self.loggingLevel)
self.log.info(message)
# if self.loggingLevel >= logging.INFO:
# print message
def traceWarn(self, message):
#self.log.setLevel(self.loggingLevel)
self.log.warning(message)
# if self.loggingLevel >= logging.WARNING:
# print message
def traceError(self, message):
#self.log.setLevel(self.loggingLevel)
self.log.error(message)
# if self.loggingLevel >= logging.ERROR:
# print message
def generaCsv(self, deviceList, start, end):
"""Escribe la estructura principal en formato CVS (comma separated values) de una lista de devices"""
self.traceInfo("generaCsv(): Inicia generacion del archivo CVS")
if deviceList == None:
self.traceWarn("generaCsv(): deviceList es nulo, se devuelve CVS vacio")
return
try:
start = string.atoi(start)
end = string.atoi(end)
except:
self.traceError('generaCsv(): Formato incorrecto de start/end. Deben ser numericos')
raise # Exception('Formato incorrecto de start/end. Deben ser numericos')
# Crear el CVS de salida
buffer = StringIO()
# writer = csv.writer(
# buffer,
# dialect=csv.excel,
# quoting=csv.QUOTE_MINIMAL
# )
writer = csv.writer(
buffer,
dialect=csv.excel,
quoting=csv.QUOTE_MINIMAL,
delimiter='|'
)
self.traceDebug("generaCsv(): abriendo conexion con Zen")
zenConnection = zen.Zen()
# Validar la existencia de cada device
self.traceDebug("generaCsv(): Validar la existencia de cada device")
deviceListOk = []
for devicePath in deviceList:
if self.validaDevicePath(zenConnection, devicePath):
deviceListOk.append(devicePath)
else:
self.traceInfo("generaCsv(): devicePath no existente: " + devicePath)
# Procesar solamente los correctos
writer.writerow(['RowType', 'DeviceName', 'InterfaceName', 'IpAddress', 'GraphID', 'Units', 'Template', 'SerieID', 'Color', 'Time', 'Value'])
for devicePath in deviceListOk:
deviceInfo = self.obtenDetalleDeGraficas(zenConnection, devicePath, start, end)
if deviceInfo <> None:
self.traceDebug("generaCsv(): deviceInfo.devicePath: " + deviceInfo.devicePath)
for graficaInfo in deviceInfo.graficas:
#graficaInfo = GraficaInfo()
self.traceDebug("generaCsv(): graficaInfo.id: " + graficaInfo.id)
for serieInfo in graficaInfo.series:
#serieInfo = SerieInfo()
for valorInfo in serieInfo.valores:
#valorInfo = ValorInfo()
writer.writerow([
'DeviceInfo',
deviceInfo.devicePath,
'',
deviceInfo.ipAddress,
graficaInfo.id,
graficaInfo.units,
graficaInfo.template,
serieInfo.id,
serieInfo.color,
valorInfo.epoch,
valorInfo.value
])
for interfaceInfo in deviceInfo.interfaces:
#interfaceInfo = InterfaceInfo()
self.traceDebug("generaCsv(): interfaceInfo.name: " + interfaceInfo.name)
for graficaInfo in deviceInfo.graficas:
#graficaInfo = GraficaInfo()
self.traceDebug("generaCsv(): graficaInfo.id: " + graficaInfo.id)
for serieInfo in graficaInfo.series:
#serieInfo = SerieInfo()
for valorInfo in serieInfo.valores:
#valorInfo = ValorInfo()
writer.writerow([
'InterfaceInfo',
deviceInfo.devicePath,
interfaceInfo.name,
deviceInfo.ipAddress,
graficaInfo.id,
graficaInfo.units,
graficaInfo.template,
serieInfo.id,
serieInfo.color,
valorInfo.epoch,
valorInfo.value
])
result = buffer.getvalue()
self.traceDebug(result)
return result
def obtenDetalleDeGraficas(self, zenConnection, devicePath, start, end):
"""Devuelve la lista de las graficas del device especificado"""
if not devicePath:
self.traceWarn("obtenDetalleDeGraficas(): devicePath es nulo")
return None
self.traceDebug('obtenDetalleDeGraficas(): devicePath=' + devicePath)
devicePathDecoded = devicePath.__str__().replace('%20', ' ')
self.traceDebug('obtenDetalleDeGraficas(): devicePathDecoded=' + devicePathDecoded)
zenossDevice = None
try:
zenossDevice = zenConnection.zenFindByPath(devicePathDecoded)
except NotFound:
self.traceError("obtenDetalleDeGraficas(): excepcion NotFound tratando de obtener el device: " + devicePathDecoded)
return None
if zenossDevice == None:
self.traceWarn("obtenDetalleDeGraficas(): zenossDevice es nulo")
return None
self.traceDebug('obtenDetalleDeGraficas(): zenossDevice.getManageIp()=' + zenossDevice.getManageIp())
self.traceDebug('obtenDetalleDeGraficas(): zenossDevice.id=' + zenossDevice.id)
drange = 129600
deviceInfo = DeviceInfo()
deviceInfo.devicePath = devicePath
deviceInfo.devicePathDecoded = devicePathDecoded
deviceInfo.ipAddress = zenossDevice.getManageIp()
deviceInfo.graficas = []
deviceInfo.interfaces = []
for template in zenossDevice.getRRDTemplates():
self.traceDebug('obtenDetalleDeGraficas(): template.id=' + template.id)
for graphDef in template.getGraphDefs():
self.traceDebug('obtenDetalleDeGraficas(): graphDef.id=' + graphDef.id)
graficaInfo = GraficaInfo()
graficaInfo.id = graphDef.id
graficaInfo.template = template.id
graficaInfo.units = graphDef.units
graficaInfo.series = []
for graphPoint in graphDef.getGraphPoints():
self.traceDebug('obtenDetalleDeGraficas(): graphPoint.id=' + graphPoint.id)
self.traceDebug('obtenDetalleDeGraficas(): graphPoint.descripcion=' + graphPoint.getDescription())
rrdFile = "perf/Devices/" + zenossDevice.id + "/" + graphPoint.escapeForRRD(graphPoint.getDescription()) + '.rrd';
rrdFile = os.path.join(self.getZenHome(), rrdFile)
self.traceDebug('obtenDetalleDeGraficas(): rrdFile=' + rrdFile)
serieInfo = SerieInfo()
serieInfo.id = graphPoint.id
serieInfo.color = graphPoint.color
serieInfo.description = graphPoint.getDescription()
serieInfo.rrdFile = rrdFile
serieInfo.valores = []
if graphPoint.getType() <> 'Threshold':
if graphPoint.rpn <> None:
self.traceDebug('obtenDetalleDeGraficas(): rpn=' + graphPoint.rpn)
if start == None or end == None:
# obtener el periodo por default
defaultPeriod = self.getDefaultPeriod(rrdFile, None, None)
if not defaultPeriod:
msg = "no existe archivo '%s' - revisar siguiente 'graphPoint'" % rrdFile
self.traceDebug(msg)
continue
start = defaultPeriod.start
end = defaultPeriod.end
indicadores = self.obtenValoresDataSource(rrdFile, graphPoint.rpn, start, end)
if indicadores <> None:
for indicadorTemporal in indicadores:
self.traceDebug('obtenDetalleDeGraficas(): epoch =' + indicadorTemporal.epoch + '; value=' + indicadorTemporal.valor)
valor = ValorInfo()
valor.epoch = indicadorTemporal.epoch
valor.value = indicadorTemporal.valor.__str__().replace('\n', '')
serieInfo.valores.append(valor)
if serieInfo.valores.__len__() > 0:
graficaInfo.series.append(serieInfo)
if graficaInfo.series.__len__() > 0:
deviceInfo.graficas.append(graficaInfo)
monitoredComponents = zenossDevice.getDeviceComponents()
for component in monitoredComponents:
self.traceDebug('obtenDetalleDeGraficas(): monitoredComponent.name=' + component.name())
try:
nombreInterface = component.getInterfaceName()
except:
self.traceDebug('obtenDetalleDeGraficas(): (no es interface)')
continue
if component.monitor and nombreInterface.__str__().lower().find('serial')>= 0:
# decodificar el nombre de la interface
nombreInterfaceHomologado = nombreInterface.__str__().replace("/", "_").replace(":", "_").replace("%20", " ").replace(";", "_")
self.traceDebug("obtenDetalleDeGraficas(): nombreInterface =" + nombreInterface)
self.traceDebug("obtenDetalleDeGraficas(): nombreInterfaceHomologado=" + nombreInterfaceHomologado)
#primero buscamos el device para saber su id en el filesystem y ayudar en la busqueda de los RRD: i
nombreCompletoInterface = devicePath + "/os/interfaces/" + nombreInterfaceHomologado
nombreDispositivoFilesystem = zenossDevice.id
zenossInterface = zenConnection.zenFindByPath(nombreCompletoInterface)
interfaceInfo = InterfaceInfo()
interfaceInfo.name = nombreInterface
interfaceInfo.ipAddress = zenossInterface.getManageIp()
interfaceInfo.graficas = []
# recorrer los templates para sacar las graficas que contiene
for template in zenossInterface.getRRDTemplates():
self.traceDebug('obtenDetalleDeGraficas(): template.id=' + template.id)
for graphDef in template.getGraphDefs():
self.traceDebug('obtenDetalleDeGraficas(): graphDef.id=' + graphDef.id)
graficaInfo = GraficaInfo()
graficaInfo.id = graphDef.id
graficaInfo.template = template.id
graficaInfo.units = graphDef.units
graficaInfo.series = []
for graphPoint in graphDef.getGraphPoints():
self.traceDebug('obtenDetalleDeGraficas(): graphPoint.id=' + graphPoint.id)
self.traceDebug('obtenDetalleDeGraficas(): graphPoint.descripcion=' + graphPoint.getDescription())
rrdFile = "perf/Devices/" + zenossDevice.id + "/os/interfaces/" + nombreInterfaceHomologado + "/" + graphPoint.escapeForRRD(graphPoint.getDescription()) + '.rrd';
rrdFile = os.path.join(self.getZenHome(), rrdFile)
self.traceDebug('obtenDetalleDeGraficas(): rrdFile=' + rrdFile)
serieInfo = SerieInfo()
serieInfo.id = graphPoint.id
serieInfo.color = graphPoint.color
serieInfo.description = graphPoint.getDescription()
serieInfo.rrdFile = rrdFile
serieInfo.valores = []
if graphPoint.getType() <> 'Threshold':
if graphPoint.rpn <> None:
self.traceDebug('obtenDetalleDeGraficas(): rpn=' + graphPoint.rpn)
if start == None or end == None:
# obtener el periodo por default
defaultPeriod = self.getDefaultPeriod(rrdFile, None, None)
if not defaultPeriod:
msg = "no existe archivo '%s' - revisar siguiente 'graphPoint'" % rrdFile
self.traceDebug(msg)
continue
start = defaultPeriod.start
end = defaultPeriod.end
indicadores = self.obtenValoresDataSource(rrdFile, graphPoint.rpn, start, end)
if indicadores == None or indicadores.__len__() == 0:
valor = ValorInfo()
valor.epoch = '0'
valor.value = '0'
serieInfo.valores.append(valor)
else:
for indicadorTemporal in indicadores:
self.traceDebug('obtenDetalleDeGraficas(): epoch =' + indicadorTemporal.epoch + '; value=' + indicadorTemporal.valor)
valor = ValorInfo()
valor.epoch = indicadorTemporal.epoch
valor.value = indicadorTemporal.valor.__str__().replace('\n', '')
serieInfo.valores.append(valor)
else:
valor = ValorInfo()
valor.epoch = '0'
valor.value = '0'
serieInfo.valores.append(valor)
if serieInfo.valores.__len__() > 0:
graficaInfo.series.append(serieInfo)
if graficaInfo.series.__len__() > 0:
interfaceInfo.graficas.append(graficaInfo)
if interfaceInfo.graficas.__len__() > 0:
deviceInfo.interfaces.append(interfaceInfo)
self.traceDebug(deviceInfo)
return deviceInfo
class InspectorDeviceTester:
def __init__(self, logginLevel):
self.test = InspectorDevice(logginLevel)
def generaXml(self, devicePath, start, end):
print "Generando grafica..."
xml = self.test.generaXml(devicePath, start, end)
print 'Terminado'
def generaGraficasInterfaceXml(self, devicePath, interface, start, end):
print "Generando grafica (interface)..."
xml = self.test.generaGraficasInterfaceXml(devicePath, start, end, interface)
print 'Terminado'
def generaLinksXml(self, devicePath):
print "Generando links de grafica..."
xml = self.test.generaLinksXml(devicePath)
print 'Terminado'
def generaLinksGraficasInterfaceXml(self, devicePath, interface):
print "Generando grafica (interface)..."
xml = self.test.generaLinksGraficasInterfaceXml(devicePath, interface)
print 'Terminado'
def generaListaDeGraficasXml(self, deviceList):
print "Generando lista de graficas..."
xml = self.test.generaListaDeGraficasXml(deviceList)
print 'Terminado'
def diagnosticaDeviceListXml(self, deviceList):
print "Diagnosticando deviceList..."
xml = self.test.diagnosticaDeviceListXml(deviceList)
print 'Terminado'
def generaCsv(self, deviceList, start, end):
print "Generando graficas en CSV..."
xml = self.test.generaCsv(deviceList, start, end)
print xml
print 'Terminado'
if __name__ == "__main__":
try:
logginLevel = logging.DEBUG
logging.basicConfig(
level = logginLevel,
filename = "InspectorDevice.log",
format = "%(asctime)-15s %(levelname)-8s %(name)s - %(message)s"
)
tester = InspectorDeviceTester(logginLevel)
start = '1262304001' #2010-01-01
end = '1272931199' #2010-05-03
# devicePath = "Server/Linux/devices/monitor.reddominionmexico.com.mx"
# interface = "eth0"
#
# #devicePath = "Network/Router/Cisco/devices/RRCONAC-MEX01A-00000001X"
# #interface = "Voice Over IP Peer_ 999"
# #interface = "GigabitEthernet0_1"
#
devicePath = "Server/Linux/devices/m1.tilatina.com"
#devicePath = "Network/Router/Cisco/NOC/devices/NOC-INFOTEC-Principal"
#interface = "Serial0_0_0_0"
# Prueba de los generadores de XML originales
tester.generaXml(devicePath, start, end)
#tester.generaGraficasInterfaceXml(devicePath, interface, start, end)
# Prueba de los generadores de LINKS que incluyen las URLs de graficacion
tester.generaLinksXml(devicePath)
#tester.generaLinksGraficasInterfaceXml(devicePath, interface)
#
# # deviceList = [
# # "Server/Linux/devices/monitor.reddominionmexico.com.mx",
# # "Devices/Network/Router/Cisco/NOC/Dominion/devices/E1-Dominion",
# # "Network/Router/Firewall/devices/Packetshaper_Dominion",
# # "Network/Router/Firewall/devices/lbDominion",
# # "Network/Router/Firewall/devices/Sonicwalk",
# # "Devices/Network/Switch/devices/S1-RA-RED%20MONI",
# # "Dominion/UPS/devices/APC%20Symmetra%2040K",
# # "Dominion/PBX%20TELDAT/devices/10.36.0.150",
# # ]
# #
# # deviceList = [
# # "Server/Linux/devices/monitor.reddominionmexico.com.mx",
# # "Network/Router/Cisco/devices/RRCONAC-MEX01A-00000001X",
# # "Network/Router/Cisco/VILLACERO/devices/RRVILLAC-DFVALLEJO_0174X",
# # "Dominion/PBX%20TELDAT/devices/10.36.0.150"
# # ]
# #
deviceList = [
"Server/Linux/devices/m1.tilatina.com"
]
# # Estos son todos los devices de INFOTEC
# deviceList = [
# "Network/Router/Cisco/INFOTEC/devices/RRINFO-AGSAGS-030X",
# "Network/Router/Cisco/INFOTEC/devices/RRINFO-CAMCAM-033X",
# "Network/Router/Cisco/INFOTEC/devices/RRINFO-CHIATUXG-036X",
# "Network/Router/Cisco/INFOTEC/devices/RRINFO-CHIHCHIH-037X",
# "Network/Router/Cisco/INFOTEC/devices/RRINFO-COLCOL-035X",
# "Network/Router/Cisco/INFOTEC/devices/RRINFO-SLPSLP-052X",
# "Network/Router/Cisco/INFOTEC/devices/RRINFO-DGODGO-038X",
# "Network/Router/Cisco/INFOTEC/devices/RRINFO-GTOGTO-039X",
# "Network/Router/Cisco/INFOTEC/devices/RRINFO-QROOCHET-051X",
# "Network/Router/Cisco/INFOTEC/devices/RRINFO-GROCHIL-040X",
# "Network/Router/Cisco/INFOTEC/devices/RRINFO-OAXOAX-048X",
# "Network/Router/Cisco/INFOTEC/devices/RRINFO-HGOPACH-041",
# "Network/Router/Cisco/INFOTEC/devices/RRINFO-VERJAL-058X",
# "Network/Router/Cisco/INFOTEC/devices/RRINFO-SINCUL-053X",
# "Network/Router/Cisco/INFOTEC/devices/RRINFO-MORCUER-045X",
# "Network/Router/Cisco/INFOTEC/devices/RRINFO-NLMTY-047X",
# "Network/Router/Cisco/INFOTEC/devices/RRINFO-MICHMOR-044X",
# "Network/Router/Cisco/INFOTEC/devices/RRINFO-BCNMEX-031X",
# "Network/Router/Cisco/INFOTEC/devices/RRINFO-SONHER-054X",
# "Network/Router/Cisco/INFOTEC/devices/RRINFO-YUCMER-059X",
# "Network/Router/Cisco/INFOTEC/devices/RRINFO-TAMCDVIC-056X",
# "Network/Router/Cisco/INFOTEC/devices/RRINFO-BCSLAP-032X",
# "Network/Router/Cisco/INFOTEC/devices/RRINFO-NAYTEP-046X",
# "Network/Router/Cisco/INFOTEC/devices/RRINFO-EDOMEXTOL-043X",
# "Network/Router/Cisco/INFOTEC/devices/RRINFO-JALGDL-042X",
# "Network/Router/Cisco/INFOTEC/devices/RRINFO-DFPRINCIPAL-01X",
# "Network/Router/Cisco/INFOTEC/devices/NOC-INFOTEC-Principal",
# "Network/Router/Cisco/INFOTEC/devices/NOC-INFOTEC-Secundario"
# ]
# #
# # Estos son todos los devices de CONACYT
# deviceList = [
# "Network/Router/Cisco/devices/RRCONAC-MEX01A-00000001X",
# "Network/Router/Cisco/devices/RRCONAC-MEX01A-00000002X",
# "Network/Router/Cisco/devices/RRCONAC-NVL01A-00000003X",
# "Network/Router/Cisco/devices/RRCONAC-JAL01A-00000004X",
# "Network/Router/Cisco/devices/RRCONAC-PUE01A-00000005X",
# "Network/Router/Cisco/devices/RRCONAC-YUC01A-00000006X",
# "Network/Router/Cisco/devices/RRCONAC-QRO01A-00000007X",
# "Network/Router/Cisco/devices/RRCONAC-CHI01A-00000008X",
# "Network/Router/Cisco/devices/RRCONAC-BCN01A-00000009X",
# "Network/Router/Cisco/devices/RRCONAC-SIN01A-00000010X",
# "Network/Router/Cisco/devices/RRCONAC-SON01A-00000011X",
# "Network/Router/Cisco/devices/RRCONAC-VER01A-00000012X",
# "Network/Router/Cisco/devices/RRCONAC-MEX01A-00000013X"
# ]
#
# # Prueba de los generadores de listas de graficas
tester.generaListaDeGraficasXml(deviceList)
# tester.generaListaDeGraficasXml(None)
#
#
# # Estos se utilizan para probar los diagnosticos
# deviceList = [
# "Server/Linux/devices/monitor.reddominionmexico.com.mx",
# "Dominion/pruebas/devices/fallido1",
# "Devices/Network/Router/Cisco/NOC/Dominion/devices/E1-Dominion",
# "Network/Router/Firewall/devices/Packetshaper_Dominion",
# "Dominion/pruebas/devices/fallido2",
# "Network/Router/Firewall/devices/lbDominion",
# "Network/Router/Firewall/devices/Sonicwalk",
# "Devices/Network/Switch/devices/S1-RA-RED%20MONI",
# "Dominion/UPS/devices/APC%20Symmetra%2040K",
# "Dominion/PBX%20TELDAT/devices/10.36.0.150",
# "Dominion/pruebas/devices/fallido3"
# ]
#
# tester.diagnosticaDeviceListXml(deviceList)
# tester.diagnosticaDeviceListXml(None)
# # Estos se utilizan para probar el CVS
# deviceList = [
# "Server/Linux/devices/monitor.reddominionmexico.com.mx",
# "Network/Router/Cisco/devices/RRCONAC-MEX01A-00000001X",
# "Network/Router/Cisco/INFOTEC/devices/RRINFO-DFPRINCIPAL-01X"
# ]
#
# tester.generaCsv(deviceList, start, end)
# except Exception, ex:
# print "Exception: ", ex
finally:
print 'Testing Finalizado'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment