diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/LICENSE diff --git a/development.ini b/development.ini new file mode 100644 index 0000000..ce5a3d3 --- /dev/null +++ b/development.ini @@ -0,0 +1,29 @@ +[WSCBot] +###Url de acesso ao modulo wscserver (terminar com '/') +url_wscserver: http://http://10.209.8.39/wscserver/ + +###Url de acesso ao Super Gerente +ip_superg: http://10.209.8.39/lbbulk/reg + +###Local do disco onde o arquivo será salvo temporariamente +filepath: /tmp/extract/ + +###Nome de usuário +username: rest + +###senha do usuário +senha: rest + +###data da coleta +data: 01-01-1970 + +###Tempo entre as leituras em busca de registros (em segundos) +sleep_time: 86400 + +[Daemon] +stdin_path = /dev/null +stdout_path = /dev/tty +stderr_path = /dev/tty +pidfile_path = /var/run/wscbot.pid +logfile_path = /var/log/wscbot.log +pidfile_timeout = 5 diff --git a/production.ini b/production.ini new file mode 100644 index 0000000..029a400 --- /dev/null +++ b/production.ini @@ -0,0 +1,29 @@ +[WSCBot] +###Url de acesso ao modulo wscserver (terminar com '/') +url_wscserver: http://10.209.8.39/wscserver/ + +###Url de acesso ao Super Gerente +ip_superg: http://10.209.8.39/lbbulk/reg + +###Local do disco onde o arquivo será salvo temporariamente +filepath: /tmp/extract/ + +###Nome de usuário +username: rest + +###senha do usuário +senha: rest + +###data da coleta +data: 01-01-1970 + +###Tempo entre as leituras em busca de registros (em segundos) +sleep_time: 3600 + +[Daemon] +stdin_path = /dev/null +stdout_path = /dev/tty +stderr_path = /dev/tty +pidfile_path = /var/run/wscbot.pid +logfile_path = /var/log/wscbot.log +pidfile_timeout = 5 diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..677691d --- /dev/null +++ b/setup.py @@ -0,0 +1,31 @@ +from setuptools import setup, find_packages + + +requires = [ + 'ConfigParser', + 'requests', + 'lockfile', + 'python-daemon', + 'simplejson' + ] + +setup( + name = "WSCBot", + version = "0.1.3", + author = "Lightbase", + author_email = "breno.brito@lightbase.com.br", + url = "https://pypi.python.org/pypi/LBConverter", + description = "Daemon Converter for the neo-lightbase service", + license = "GPLv2", + keywords = "Converter extractor lightbase daemon", + install_requires=requires, + packages=find_packages(), + classifiers=[ + "Development Status :: 2 - Pre-Alpha", + "Environment :: No Input/Output (Daemon)", + "License :: OSI Approved :: GNU General Public License v2 (GPLv2)", + "Natural Language :: Portuguese (Brazilian)", + "Programming Language :: Python :: 3.2", + "Topic :: Database :: Database Engines/Servers", + ] +) diff --git a/wscbot/__init__.py b/wscbot/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/wscbot/__init__.py diff --git a/wscbot/__main__.py b/wscbot/__main__.py new file mode 100644 index 0000000..e3474be --- /dev/null +++ b/wscbot/__main__.py @@ -0,0 +1,102 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +import logging +import time +import os +import ConfigParser + +from daemon import runner + + +from app import main + +#exceptions +from requests.exceptions import * +import zipfile +import lockfile + +ini_path='/srv/bot-super-gerente/WSCBot/production.ini' +#absolute path to .ini file + + + +def setconfig(config_file): + """Função que conecta o modulo ao arquivo de configurações""" + + config_file = os.path.abspath(config_file) + config = ConfigParser.ConfigParser() + config.read(config_file) + user = {} + user['url_wscserver'] = config.get('WSCBot', 'url_wscserver') + user['filepath'] = config.get('WSCBot', 'filepath') + user['username'] = config.get('WSCBot', 'username') + user['senha'] = config.get('WSCBot', 'senha') + user['data'] = config.get('WSCBot', 'data') + user['ip_superg'] = config.get('WSCBot', 'ip_superg') + user['sleep_time'] = int(config.get('WSCBot', 'sleep_time')) + user['stdin_path'] = config.get('Daemon', 'stdin_path') + user['stdout_path'] = config.get('Daemon', 'stdout_path') + user['stderr_path'] = config.get('Daemon', 'stderr_path') + user['pidfile_path'] = config.get('Daemon', 'pidfile_path') + user['logfile_path'] = config.get('Daemon', 'logfile_path') + user['pidfile_timeout'] = int(config.get('Daemon', 'pidfile_timeout')) + return user + +class App(): + + def __init__(self): + self.stdin_path = user['stdin_path'] + self.stdout_path = user['stdout_path'] + self.stderr_path = user['stderr_path'] + self.pidfile_path = user['pidfile_path'] + self.pidfile_timeout = user['pidfile_timeout'] + + def run(self): + logger.info ('Iniciando modulo WSCBot') + while True: + timeron = time.time() + logger.info ('Iniciando execução') + try: + main(ip_servidor,username,senha,ip_superg,filepath,data) + except (ConnectionError, Timeout): + logger.error ('Não foi possivel estabelecer conexão com o servidor! ' + domain) + except zipfile.BadZipfile: + logger.error ('Arquivo zip gerado pelo WSCServer invalido ou corrompido') + except Exception as erro: + logger.error (erro) + timeronff = time.time() + tempo = (timeronff - timeron) + m, s = divmod(sleep_time, 60) + h, m = divmod(m, 60) + next = "%d:%02d:%02d" % (h, m, s) + logger.debug ('Execução durou ' + str(tempo) + ' segundos.') + logger.info ('Proxima execução em: ' + next) + time.sleep(sleep_time) + +user = setconfig(ini_path) +ip_servidor = user['url_wscserver'] +senha = user['senha'] +ip_superg = user['ip_superg'] +sleep_time = user['sleep_time'] +username = user['username'] +filepath = user['filepath'] +data = user['data'] +app = App() +logger = logging.getLogger("WSCBot") +logger.setLevel(logging.INFO) # Alterar para logging.INFO em produção +formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') +handler = logging.FileHandler(user['logfile_path']) +handler.setFormatter(formatter) +logger.addHandler(handler) + +daemon_runner = runner.DaemonRunner(app) +#This ensures that the logger file handle does not get closed during daemonization +daemon_runner.daemon_context.files_preserve=[handler.stream] +try: + daemon_runner.do_action() +except (KeyboardInterrupt, SystemExit): + raise +except lockfile.LockTimeout: + print "\nErro: Já existe uma instância desse modulo em execução\n" +except runner.DaemonRunnerStopFailureError: + print "\nErro: Não existe nenhuma instância desse módulo em execução\n" diff --git a/wscbot/app.py b/wscbot/app.py new file mode 100644 index 0000000..f3dabad --- /dev/null +++ b/wscbot/app.py @@ -0,0 +1,37 @@ + # -*- coding: utf-8 -*- +"""Autor: Breno Rodrigues Brito""" +import json + +from requests import put, post +import logging + +from wscbot.scripts import req +from wscbot.scripts import pegachave +from wscbot.scripts import erro +from wscbot.scripts import rotinas +from wscbot.scripts.zipparser import ziphandler + +def main(ip_servidor,username,senha,ip_superg,filepath,data): + """ + Envia uma requisição GET HTTP para o endereço cadastrado, + fornecendo como parâmetros da requisição o usuário e senha informados; + Pega a resposta da requisição e escreve num arquivo; + Criptografa o conteúdo do arquivo com base em uma chave compartilhada com o Super Gerente; + Envia o arquivo criptografado para o Super Gerente; + Registra a data do envio e o resultado da comunicação. + """ + + # Faz a requisição do arquivo zip + zip_path = req.req(ip_servidor, filepath) + + dicionario = ziphandler(zip_path) + for arquivo in dicionario: + logger.debug('Inicio do envio de dados') + coleta = json.loads(dicionario[arquivo])['results'] + for registro in coleta: + registro = json.dumps(registro) + + f = post(ip_superg,data={'json_reg':registro}) + erro.is_error_p(f) + +logger = logging.getLogger("WSCBot") diff --git a/wscbot/model/__init__.py b/wscbot/model/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/wscbot/model/__init__.py diff --git a/wscbot/scripts/__init__.py b/wscbot/scripts/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/wscbot/scripts/__init__.py diff --git a/wscbot/scripts/erro.py b/wscbot/scripts/erro.py new file mode 100644 index 0000000..319913f --- /dev/null +++ b/wscbot/scripts/erro.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +"""Autor: Breno Rodrigues Brito""" +import logging +import simplejson # for exception + +def is_error_p(resp): + """verifica erros do post""" + try: + json = resp.json() + except simplejson.decoder.JSONDecodeError: + msg = 'not found' + n_err = str(resp.status_code) + logger.error(n_err + ': ' + msg) + else: + try: + a = len(json) + except TypeError: + id_reg = str(json) + logger.info('Escrito com sucesso id_reg: ' + id_reg) + else: + msg = json['_error_message'] + n_err = str(json['_status']) + logger.error(n_err + ': ' + msg) + + +def is_error_g(recebe): + """Verifica erros do GET""" + + num_er = recebe.__dict__['status_code'] + msg = recebe.__dict__['reason'] + + if num_er > 199 and num_er < 300: + logger.debug('Recebido com sucesso.') + else: + logger.error(str(num_err) + ': ' + msg) + + +logger = logging.getLogger("WSCBot") \ No newline at end of file diff --git a/wscbot/scripts/pegachave.py b/wscbot/scripts/pegachave.py new file mode 100644 index 0000000..1655333 --- /dev/null +++ b/wscbot/scripts/pegachave.py @@ -0,0 +1,19 @@ +# -*- coding: utf-8 -*- +"""Autor: Breno Rodrigues Brito""" +from requests import get + +def pegachave(domain,username,senha): + """Envia uma requisição GET HTTP para o endereço cadastrado, + fornecendo como parâmetros da requisição o usuário e senha informados;""" + + payload = {'user' : 'username', + 'pass' : 'senha'} + + recebe = get(domain, data=payload) + # jsonfull = recebe.json() + # bases = jsonfull["results"] + chave = t_dados(recebe) + + + return chave + diff --git a/wscbot/scripts/req.py b/wscbot/scripts/req.py new file mode 100644 index 0000000..69009aa --- /dev/null +++ b/wscbot/scripts/req.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +"""Autor: Breno Rodrigues Brito""" +# from requests import get +import urllib +import logging +import os + +from wscbot.scripts.erro import is_error_g +from wscbot.scripts.tratamento import t_dados + + +def download_file(url, filepath): + """Baixa o arquivo de coleta na url indicada""" + + if not os.path.isdir(filepath): + os.mkdir(filepath) + local_filename = filepath + "coleta.zip" + urllib.urlretrieve(url, local_filename) + return local_filename + + +def req(domain,filepath): #Recebia domain e data + """Envia uma requisição GET HTTP para o endereço cadastrado, + fornecendo como parâmetros da requisição o usuário e senha informados;""" + + # payload = {'user' : 'username', + # 'pass' : 'senha'} + logger.debug('Mandando requisição') + url = domain + 'zip/coleta' + + # values = {'data_coleta':data} + + arquivo_coleta = download_file(url,filepath) # , param=values + arquivo_coleta = os.path.abspath(arquivo_coleta) + + # ATENCAO!!! + # tem de se testar se o data precisa de encoding!! + + # funcionava para o módulo requests + # Não sei como fazer para o urllib + # is_error_g(arquivo_coleta) + + return arquivo_coleta + +logger = logging.getLogger("WSCBot") + +# zip para baixar e testar: +# http://10.0.0.149/api/doc/arquivos/29/download \ No newline at end of file diff --git a/wscbot/scripts/rotinas.py b/wscbot/scripts/rotinas.py new file mode 100644 index 0000000..3aa306c --- /dev/null +++ b/wscbot/scripts/rotinas.py @@ -0,0 +1,27 @@ +# -*- coding: utf-8 -*- +"""Autor: Breno Rodrigues Brito""" +import logging + +def so(): + """SO""" + logger.debug('Iniciando a rotina SO') + pass + +def software(): + """software""" + logger.debug('Iniciando a rotina software') + pass + +def hardware(): + """hardware""" + logger.debug('Iniciando a rotina hardware') + pass + +def software_basico(): + """software_basico""" + logger.debug('Iniciando a rotina software_basico') + pass + + + +logger = logging.getLogger("WSCBot") \ No newline at end of file diff --git a/wscbot/scripts/tratamento.py b/wscbot/scripts/tratamento.py new file mode 100644 index 0000000..891c32b --- /dev/null +++ b/wscbot/scripts/tratamento.py @@ -0,0 +1,6 @@ +import json + +def t_dados(algo): + """Trata os dados recebidos""" + tratado = json.dumps(algo) + return tratado \ No newline at end of file diff --git a/wscbot/scripts/xmlparser.py b/wscbot/scripts/xmlparser.py new file mode 100644 index 0000000..9093f99 --- /dev/null +++ b/wscbot/scripts/xmlparser.py @@ -0,0 +1,19 @@ +# -*- coding: utf-8 -*- + +""" +Faz o parse do arquivo XML + +""" +"""Autor: Breno Rodrigues Brito""" +import xml.etree.ElementTree as ET +# from xml.dom import minidom + +tree = ET.parse(pathtofile) +root = tree.getroot() + +# xmldoc = minidom.parse('items.xml') +# itemlist = xmldoc.getElementsByTagName('item') +# print len(itemlist) +# print itemlist[0].attributes['name'].value +# for s in itemlist : +# print s.attributes['name'].value diff --git a/wscbot/scripts/zipparser.py b/wscbot/scripts/zipparser.py new file mode 100644 index 0000000..ab34b4b --- /dev/null +++ b/wscbot/scripts/zipparser.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +"""Autor: Breno Rodrigues Brito""" + +import zipfile +import logging +import tempfile +import json +import os + +from wscbot.scripts.tratamento import t_dados + +def ziphandler(filename): + """ + Receive a zip file and parse one file at a time, returning a collection of parsed files. + """ + # Create the zipfile object + z_root = zipfile.ZipFile(filename) + + # Create a temp dir and unzip file contents + tmp_dir = tempfile.mkdtemp() + + # registros = { + # 'import_error' : [], + # 'registros' : [] + # } + + + # cria um dicionario + for arquivo in z_root.namelist(): + # This should be a list with a all the zip files + #print('00000000000000000000000000000 %s' % arquivo) + z_root.extract(arquivo,tmp_dir) + + # This is the file object for this registro + # z = zipfile.ZipFile(os.path.join(tmp_dir,arquivo)) + filepath = (os.path.join(tmp_dir,arquivo)) + + # Lê o arquivo string que vai conter o json + with open(filepath) as f: + string_json = f.read() + + # carrega o Json + jsonfull = json.loads(string_json) + jsonfull = t_dados(jsonfull) + # cria um dicionario + dicionario = {arquivo:jsonfull} + + return dicionario + # lista de arquivos + +logger = logging.getLogger("WSCBot") -- libgit2 0.21.2