Home Page do Portal
Brasil, um país de todos

Changeset 445

Show
Ignorar:
Timestamp:
05/15/08 12:17:27
Autor:
rogeriolino@gmail.com
Mensagem:

--

Arquivos:

Legenda:

Não modificado
Adicionado
Removido
Modificado
Copiado
Movido
  • cacic/trunk/agente-linux/pycacic/src/README

    r425 r445  
    77#    |__|     /__/    \____/ |__|   \__\ \____/ |__|  \____/   # 
    88#                                                              # 
    9 #                                              VERSAO TESTE    # 
     9#                                    VERSAO DESENVOLVIMENTO    # 
    1010#                                                              # 
    1111################################################################ 
    1212 
    13  Primeiramente deve-se alterar, configurar, o arquivo /config/cacic.conf  
     13 Primeiramente deve-se alterar, configurar, o arquivo config/cacic.conf  
    1414 informando o endereco, usuario e senha do Gerente Web. 
    1515  
    16  Apos executar, como super usuario, o arquivo /cacic.py que ficara rodando em background. 
    17  Para utilizar a interface deve executar o arquivo /gui.py (como usuario normal),  
    18  e necessario ter instalado o GTK+, PyGTK e o Glade. Caso execute corretamente ira 
     16 Apos executar, como super-usuario, o arquivo cacic.py que ficara rodando em background. 
     17 Para utilizar a interface deve executar o arquivo gui.py (como usuario normal). 
     18 E necessario ter instalado o GTK+, PyGTK e o Glade. Caso execute corretamente ira 
    1919 aparecer um icone no systray. Ao clicar nesse icone abre a janela com a possibilidade 
    2020 de forcar uma coleta. 
    2121  
    22  obs: Ao clicar em "Forcar Coleta" observe no terminal que esta rodando o /cacic.py se apareceu 
     22 obs: Ao clicar em "Forcar Coleta" observe no terminal que esta rodando o cacic.py se apareceu 
    2323 a mensagem de "coleta forcada". 
    2424  
  • cacic/trunk/agente-linux/pycacic/src/cacic.py

    r437 r445  
    55import time 
    66import thread 
     7 
    78from socket import * 
    89from ger_cols import * 
    910from globals import Globals 
    1011 
     12import gc as garbage_collector 
     13 
    1114class Cacic: 
    1215     
    13     VERSION = '1.0.0
     16    VERSION = '0.0.1
    1417     
    1518    def __init__(self):        
    1619        try: 
    17             # adiciona o diretorio do pycacic ao sys.path 
    18             sys.path[0] = Globals.PATH 
     20            # somente executa se estiver como root 
     21            if not self.isRoot(): 
     22                raise Exception("Para executar o programa é necessário ser super-usuário (root).") 
    1923             
     24            # verifica se o pycacic esta instalado 
     25            # senao chama configurador do cacic.conf 
    2026            if not Globals.INSTALLED: 
    2127                Globals.install() 
    2228             
    23             if not self.isRoot(): 
    24                 raise Exception("Para executar o programa é necessário estar como super usuário (root).") 
    25              
     29            # Habilita o coletor de lixo do Python 
     30            garbage_collector.enable()                         
    2631            print "\n\tBem-Vindo ao PyCacic\n" 
    2732            # flags do Gerente de Coletas 
     
    3439            self.host, self.port, self.buf, self.addr = Globals.getSocketAttr() 
    3540            # criando socket 
    36             self.udp_sock = socket.socket(AF_INET, SOCK_DGRAM) 
    37             self.udp_sock.bind(self.addr) 
     41            self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
     42            self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 
     43            self.sock.bind(self.addr) 
    3844            # executa thread para escutar o socket 
    3945            thread.start_new_thread(self.checkSocket, ()) 
     
    4652                    self.conecta() 
    4753                    # com o coletor parado (dormindo) dispara timeout para iniciar a coleta 
    48                     # apos o intervalo de tempo definido pelo servidor  
     54                    # apos o intervalo de tempo definido pelo servidor 
    4955                    thread.start_new_thread(self.timeout, ()) 
    5056                    # intervalo 
    5157                    self.interval = self.gc.getInterval() 
    52                     print(" `---- Coleta iniciara daqui a %s minutos" % (self.interval/60)) 
    53                     #self.atualiza() 
     58                    print(" `---- Coleta iniciara em %s minutos" % (self.interval/60)) 
    5459                # se esta habilitado a executar ou e uma coleta forcada 
    5560                if self.gc_ok or len(self.isforcada) > 0: 
     
    6166                    # inicia coletas 
    6267                    self.gc.coletas_forcadas = self.isforcada 
    63                     self.start() 
     68                    self.start()                     
     69                    # Executa o coletor de lixo 
     70                    garbage_collector.collect() 
    6471                time.sleep(2) 
    65             # fechando conexao 
    66             self.udp_sock.close() 
     72            # sai 
     73            self.quit() 
     74        except socket.error, e:    
     75            print 'PyCacic already is running.' 
    6776        except Exception, e: 
    68             import traceback 
    69             traceback.print_exc() 
    70             print e 
     77            print e         
     78        # remover depois 
     79        import traceback 
     80        traceback.print_exc() 
    7181     
    7282    def isRoot(self): 
     
    101111        print(" Contato com o Gerente Web: %s" % strftime("%H:%M:%S")) 
    102112        self.gc.readXML(xml) 
     113        # verifica atualizacao 
     114        """ 
     115        if self.gc.hasNew(): 
     116            print ' Versao nova disponivel !!!' 
     117            print ' `--- Iniciando atualizacao...' 
     118            self.gc.atualiza() 
     119            print ' `--- Novo pacote salvo' 
     120            #chama atualizador e sai 
     121            os.system('python %s/update.py -pkg %s -tmp %s &' % (Globals.PATH, self.gc.pacote_disponivel, 'pycacic_temp')) 
     122            #self.quit() 
     123        """ 
    103124 
    104125    def checkSocket(self): 
    105126        """Verifica comunicacao com a interface""" 
    106         data, self.addr = self.udp_sock.recvfrom(self.buf) 
    107         self.isforcada.append(data
    108         self.checkSocket(
     127        while 1: 
     128            data, self.addr = self.sock.recvfrom(self.buf
     129            self.isforcada.append(data
    109130 
     131    def quit(self): 
     132        """Sai do programa fechando conexao do socket""" 
     133        self.sock.close() 
     134        print 'Bye' 
     135        sys.exit() 
    110136 
    111137if __name__ == '__main__': 
  • cacic/trunk/agente-linux/pycacic/src/chksis.py

    r417 r445  
    55        pass 
    66 
     7# ESCREVER CÓDIGO EM SHELL SCRIPT PARA MONITORAR DE HORA-EM-HORA (CRON) 
     8# SE O CACIC.PY ESTÁ EM EXECUÇÃO. 
  • cacic/trunk/agente-linux/pycacic/src/coletores/col_hard.py

    r437 r445  
    4343        inicio = strftime("%H:%M:%S") 
    4444        # CPUs 
    45         CPUs = '#CPU#'.join(['#FIELD#'.join(['te_cpu_desc###%s' % i.getDescricao(), 'te_cpu_fabricante###%s' % i.getFabricante(), 'te_cpu_serial###%s' % i.getSerial(), 'te_cpu_frequencia###%s' % i.getFrequencia()]) for i in self.computer.getCPU()]) 
     45        # removido frequencia CPUs = '#CPU#'.join(['#FIELD#'.join(['te_cpu_desc###%s' % i.getDescricao(), 'te_cpu_fabricante###%s' % i.getFabricante(), 'te_cpu_serial###%s' % i.getSerial(), 'te_cpu_frequencia###%s' % i.getFrequencia()]) for i in self.computer.getCPU()]) 
     46        CPUs = '#CPU#'.join(['#FIELD#'.join(['te_cpu_desc###%s' % i.getDescricao(), 'te_cpu_fabricante###%s' % i.getFabricante(), 'te_cpu_serial###%s' % i.getSerial()]) for i in self.computer.getCPU()]) 
    4647        self.addChave('te_Tripa_CPU', CPUs) 
    4748        # Placas/Configuracoes de Redes 
  • cacic/trunk/agente-linux/pycacic/src/coletores/lib/computador.py

    r434 r445  
    518518                        # modificando a permissao do arquivo 
    519519                        if stat.S_IMODE(os.lstat(lshw)[stat.ST_MODE]) < 448: 
    520                                 os.chmod(lshw, 777
     520                                os.chmod(lshw, 0755
    521521                        return commands.getoutput(lshw + " -xml") 
    522522                else: 
     
    647647                                        if a == 'id' and valor[0:3] == 'ide': 
    648648                                                self.getIDEInfo(filho) 
    649                                         if a == 'id' and valor in ('network', 'bridge'): 
     649                                        if a == 'id' and (valor[0:7] == 'network' or valor[0:6] == 'bridge'): 
    650650                                                self.getRedeInfo(filho) 
    651651                                        if a == 'id' and valor == 'communication': 
  • cacic/trunk/agente-linux/pycacic/src/coletores/lib/url.py

    r434 r445  
    2222import ftplib 
    2323from coletores.coletor import * 
     24from xml.dom import minidom, Node 
    2425 
    2526class URL : 
     
    6566    def isOK(self, xml): 
    6667        """Retorna se o XML gerado esta valido ou nao""" 
    67         status = xml.getElementsByTagName('STATUS')[0].firstChild.nodeValue 
    68         if status != "OK": 
    69             return 0 # False 
    70         return 1 # True 
     68        try: 
     69            xml = minidom.parseString(xml) 
     70            status = xml.getElementsByTagName('STATUS')[0].firstChild.nodeValue 
     71            if status != "OK": 
     72                return 0 # False 
     73            return 1 # True 
     74        except: 
     75            return 0 
    7176     
    7277    def ftpConecta(self, server, login, senha): 
  • cacic/trunk/agente-linux/pycacic/src/config/cacic.conf

    r434 r445  
    11<?xml version="1.0" encoding="iso-8859-1" ?> 
    22<config> 
    3         <status> 
    4                 <param id="installed" value="yes" /> 
    5                 <param id="test" value="no" /> 
    6         </status> 
     3        <pycacic id="agente_pycacic"> 
     4                <dir>/usr/share/pycacic</dir> 
     5                <hash>ZZZ</hash> 
     6                <password>PW_CACIC</password> 
     7                <status> 
     8                        <param id="installed" value="yes" /> 
     9                        <param id="test" value="no" /> 
     10                </status> 
     11        </pycacic> 
    712        <server id="gerente_web"> 
    8                 <address>http://10.71.0.121</address> 
     13                <address>http://127.0.0.1</address> 
    914                <ws>/cacic2/ws/</ws> 
    1015                <page>get_config.php</page> 
     
    1419                <description>Endereco (address) do servidor Gerente Web para buscar informacoes sobre quais coletas devem ser realizadas, intervalo de tempo entre elas, atualizao, etc. Senha (password) para acesso. E arquivo (file) que efetuara esta resposta.</description> 
    1520        </server> 
    16         <local> 
    17                 <dir>/usr/share/pycacic</dir> 
    18                 <sha1>XXXX</sha1> 
    19         </local> 
    2021        <socket> 
    2122                <host>localhost</host> 
  • cacic/trunk/agente-linux/pycacic/src/config/io.py

    r434 r445  
    1414import sys, os 
    1515from xml.dom import minidom, Node 
     16from globals import Globals 
    1617 
    1718class IOConfig: 
     
    2021         
    2122        Responsavel por guardar o caminho do arquivo de 
    22         configuracao do Cacic e efetuar a leitura dos nos principais 
     23        configuracao do PyCacic e efetuar a leitura dos nos principais 
    2324        dele.         
    2425    """ 
    2526 
    26     FILE = '%s/config/cacic.conf' % sys.path[0] 
     27    FILE = '%s/config/cacic.conf' % Globals.PATH 
    2728     
    2829    def exists(): 
     
    5960        return root.getElementsByTagName('coletores')[0] 
    6061     
    61     def getStatus(): 
     62    def getPycacic(): 
     63        """Retorna o node do Pycacic""" 
     64        root = IOConfig.getRoot() 
     65        return root.getElementsByTagName('pycacic')[0] 
     66     
     67    def getPycacicStatus(): 
    6268        """Retorna o node de status""" 
    63         root = IOConfig.getRoot() 
    64         return root.getElementsByTagName('status')[0]     
     69        pycacic = IOConfig.getPycacic() 
     70        for no in pycacic.childNodes: 
     71            if no.nodeType == Node.ELEMENT_NODE and no.nodeName == 'status': 
     72                return no 
    6573     
    6674    def getSocket(): 
     
    7482    getServer = staticmethod(getServer) 
    7583    getColetores = staticmethod(getColetores) 
    76     getStatus = staticmethod(getStatus) 
     84    getPycacic = staticmethod(getPycacic) 
     85    getPycacicStatus = staticmethod(getPycacicStatus) 
    7786    getSocket = staticmethod(getSocket) 
    7887 
     
    8291         
    8392        Responsavel por efetuar a leitura do arquivo de configuracao 
    84         do cacic. Informando dados como endereco do Gerente Web, 
     93        do PyCacic. Informando dados como endereco do Gerente Web, 
    8594        usuario e senha, etc. 
    8695         
     
    98107                server[no.nodeName] = no.firstChild.nodeValue                 
    99108        return server 
     109     
     110    def getPycacic(): 
     111        """Retorna um dicionario contendo as informacoes sobre o PyCacic""" 
     112        pycacic = {'dir' : '', 'hash' : '', 'password' : ''} 
     113        config = IOConfig.getPycacic() 
     114        for no in config.childNodes: 
     115            if no.nodeType == Node.ELEMENT_NODE: 
     116                pycacic[no.nodeName] = no.firstChild.nodeValue                 
     117        return pycacic 
    100118 
    101119    def getColetor(id): 
     
    113131                    return coletor 
    114132     
    115     def getStatus(id): 
     133    def getPycacicStatus(id): 
    116134        """ 
    117135            Retorna um dicionario contendo as informacoes de 
     
    119137        """ 
    120138        status = {'id' : '', 'value' : ''} 
    121         sts = IOConfig.getStatus() 
     139        sts = IOConfig.getPycacicStatus() 
    122140        for no in sts.childNodes: 
    123141            if no.nodeType == Node.ELEMENT_NODE: 
     
    138156     
    139157    getServer = staticmethod(getServer) 
     158    getPycacic = staticmethod(getPycacic) 
    140159    getColetor = staticmethod(getColetor) 
    141     getStatus = staticmethod(getStatus) 
    142     getSocket = staticmethod(getSocket) 
    143      
     160    getPycacicStatus = staticmethod(getPycacicStatus) 
     161    getSocket = staticmethod(getSocket)     
    144162     
    145163class Writer: 
     
    148166         
    149167        Responsavel por efetuar a escrita no arquivo de configuracao 
    150         do cacic. Alterando dados como se e instalacao, endereco do 
     168        do PyCacic. Alterando dados como se e instalacao, endereco do 
    151169        Gerente Web, usuario e senha, etc.         
    152170    """ 
     
    185203        Writer.saveXML(config.replace(sv, server)) 
    186204         
    187     def setStatus(s, v): 
    188         """Modifica o status""" 
     205    def setPycacicStatus(s, v): 
     206        """Modifica o status do Pycacic""" 
    189207        config = IOConfig.getFile() 
     208        re_pc = re.compile('<pycacic(?:.|\n)*</pycacic>') 
    190209        re_st = re.compile('<status(?:.|\n)*</status>') 
    191210        re_pr = re.compile('<param.*?id="'+s+'".*?/>') 
     211        pc = re_pc.findall(config)[0] 
    192212        st = re_st.findall(config)[0] 
    193213        pr = re_pr.findall(config)[0] 
    194214        status = st 
     215        pycacic = pc 
    195216        if (v): 
    196217            v = "yes" 
     
    198219            v = "no" 
    199220        status = status.replace(pr, Writer.setNodeAttrib(pr, "value", v)) 
    200         Writer.saveXML(config.replace(st, status)
    201          
     221        pycacic = pycacic.replace(st, status
     222        Writer.saveXML(config.replace(pc, pycacic)) 
    202223 
    203224    saveXML = staticmethod(saveXML) 
    204225    setServer = staticmethod(setServer) 
    205     setStatus = staticmethod(setStatus) 
     226    setPycacicStatus = staticmethod(setPycacicStatus) 
    206227    setNodeValue = staticmethod(setNodeValue) 
    207228    setNodeAttrib = staticmethod(setNodeAttrib) 
  • cacic/trunk/agente-linux/pycacic/src/ger_cols.py

    r437 r445  
    1414import os 
    1515import sys 
     16import commands 
    1617 
    1718from coletores.coletor import * 
     
    6364        # configuracoes gerais 
    6465        self.versao_atual = version 
    65         self.versao_disponivel = '' 
     66        self.hash_atual = Reader.getPycacic()['hash'] 
     67        self.hash_disponivel = 'ZZZ' 
     68        self.pacote_disponivel = '' 
    6669        self.exibe_bandeja = 'N' 
    6770        self.exibe_erros_criticos = 'N' 
     
    108111        }         
    109112        self.dicionario = { 
    110             'te_versao_cacic'    : version, 
    111             'te_versao_gercols'  : version, 
    112113            'in_chkcacic'        : self.coletor.encripta(''), 
    113114            'in_teste'           : self.coletor.encripta(''),                 
     
    116117            'id_ftp'             : self.coletor.encripta(''), 
    117118            'te_fila_ftp'        : self.coletor.encripta(''), 
    118             'te_versao_cacic'    : self.coletor.encripta(version), 
    119             'te_versao_gercols'  : self.coletor.encripta(version), 
     119            'te_versao_cacic'    : self.coletor.encripta(self.versao_atual), 
     120            'te_versao_gercols'  : self.coletor.encripta(self.versao_atual), 
    120121            'te_tripa_perfis'    : self.coletor.encripta(''), 
    121         }      
    122          
     122        }        
    123123        self.separador = '=CacicIsFree=' 
    124124         
     
    165165            return xml  
    166166        except Exception, e: 
    167             raise Exception(e.message
     167            raise Exception(e
    168168     
    169169    def addColeta(self, col, valor): 
     
    175175        """ Le o XML gerado pelo servidor WEB """ 
    176176        # returns void 
    177         #print "XML: "+xml 
    178         self.xml = minidom.parseString(xml) 
    179177        # se nao achar o status==OK, retorna 
    180         if not self.url.isOK(self.xml): 
     178        if not self.url.isOK(xml): 
    181179            raise Exception('Erro ao ler XML do servidor, status não disponível') 
     180        self.xml = minidom.parseString(xml)         
    182181        root = self.xml.getElementsByTagName('CONFIGS')[0] 
    183182        # Coletores 
     
    187186        for no in root.childNodes: 
    188187            if no.nodeType == Node.ELEMENT_NODE: 
    189                 if no.firstChild.nodeValue != '': 
     188                if no.firstChild.nodeValue != '':                    
    190189                    if no.nodeName == 'cs_auto_update': 
    191190                        self.update_auto = self.decode(no.firstChild.nodeValue) 
     
    207206                        pass 
    208207                    # VERSOES 
    209                     elif no.nodeName == 'TE_VERSAO_PYCACIC_DISPONIVEL': 
    210                         self.versao_disponivel = self.decode(no.firstChild.nodeValue) 
     208                    elif no.nodeName == 'TE_HASH_PYCACIC': 
     209                        self.hash_disponivel = self.decode(no.firstChild.nodeValue) 
     210                    elif no.nodeName == 'TE_PACOTE_PYCACIC_DISPONIVEL': 
     211                        self.pacote_disponivel = self.decode(no.firstChild.nodeValue) 
    211212                    elif no.nodeName == 'in_exibe_bandeja': 
    212213                        self.exibe_bandeja = self.decode(no.firstChild.nodeValue) 
     
    244245        return self.coletor.decripta(data).replace('\x00','') 
    245246 
    246     def isNew(self, current, new): 
     247    def hasNew(self, current='', new=''): 
    247248        """Compara as versoes, atual com a disponivel.""" 
    248         return (current.replace('.','') < new.replace('.','')) 
     249        if current == '' or new == '': 
     250            current, new = self.hash_atual, self.hash_disponivel 
     251        return (current != new)        
    249252     
    250253    def atualiza(self): 
    251         """Atualiza os modulos dos coletores""" 
    252         """ 
    253             TODO: definir como vai ficar a string de destino dos arquivos 
    254         """ 
     254        """Atualiza os modulos dos coletores caso tenha alguma versao nova.""" 
    255255        try: 
    256256            # se nao tem versao nova retorna 
    257             if not self.isNew(self.versao_atual, self.versao_disponivel): 
    258                 return 
     257            if not self.hasNew(): return '' 
    259258            # conecta ao servidor ftp para buscar atualizacao 
    260259            self.url.ftpConecta(self.update_server, self.update_user, self.update_pass) 
     260            # altera o diretorio do servidor para aonde esta o pacote 
    261261            self.url.ftpAlteraDir(self.update_path) 
    262             #self.url.getFile('vaca.exe', 'vaca.exe') 
     262            # pega o pacote e salva no temporario 
     263            self.url.getFile(self.pacote_disponivel, '/tmp/%s' % self.pacote_disponivel) 
    263264            self.url.ftpDesconecta() 
    264265        except Exception, e: 
     
    272273        for col in self.coletores.values(): 
    273274            col.start() 
    274             self.coletor.addChave(col.getUVCKey(), col.getChave('UVC'))             
    275             if self.all_forcada or (col.getName() in self.coletas_forcadas) or col.isReady(self.OUTPUT_DAT):                 
     275            self.coletor.addChave(col.getUVCKey(), col.getChave('UVC')) 
     276            if self.all_forcada or (col.getName() in self.coletas_forcadas) or col.isReady(self.OUTPUT_DAT): 
    276277                page = Reader.getColetor(col.getName())['page'] 
    277278                dict = col.getEncryptedDict() 
     
    287288            server = '%s%s%s' % (self.cacic_server, self.cacic_ws, self.coletas_enviar[col]['page']) 
    288289            xml = self.conecta(server, self.coletas_enviar[col]['dict']) 
    289             if self.url.isOK(minidom.parseString(xml)): 
     290            if self.url.isOK(xml): 
    290291                print(' `---- Envio OK') 
    291292            else: 
  • cacic/trunk/agente-linux/pycacic/src/globals.py

    r433 r445  
    1515import sys 
    1616import commands 
    17 from config.io import Reader 
    18 from config.io import Writer 
     17 
    1918 
    2019class Globals: 
     
    3029    def getSocketAttr(): 
    3130        """Retorna as informacoes do Socket""" 
     31        from config.io import Reader 
    3232        sock = Reader.getSocket() 
    3333        host = sock['host'] 
     
    3939    def install(): 
    4040        """Abre console para configuracao do PyCacic""" 
     41        from config.io import Writer 
    4142        print "\n\t--- Bem-Vindo a Configuracao do PyCacic ---" 
    4243        print "\n\tapos preencher as informacoes abaixo o programa ira iniciar\n" 
     
    5859            Globals.install() 
    5960            return 
    60         Writer.setStatus('installed', 1) 
     61        Writer.setPycacicStatus('installed', 1) 
    6162        if addr[len(addr)-1] == '/': addr = addr[:-1] 
    6263        Writer.setServer('address', addr) 
     
    8384 
    8485def isInstalled(): 
    85     return (Reader.getStatus('installed')['value'] == 'yes') 
     86    from config.io import Reader 
     87    return (Reader.getPycacicStatus('installed')['value'] == 'yes') 
    8688 
    8789 
  • cacic/trunk/agente-linux/pycacic/src/lang/language.py

    r434 r445  
    55import codecs 
    66from xml.dom import minidom, Node 
     7 
     8from globals import Globals 
    79 
    810class Language: 
     
    4244    def openXML(self): 
    4345        """Abre o arquivo XML contendo o idioma escolhido""" 
    44         xml_file = open(sys.path[0] + '/lang/' + self.langs[self.lang], 'r').read() 
     46        xml_file = open(Globals.PATH + '/lang/' + self.langs[self.lang], 'r').read() 
    4547        self.xml = minidom.parseString(xml_file) 
    4648