Commit 4e974e9cc81e64b574a289e25d70b47bd9df21e7

Authored by Eric Menezes Noronha
2 parents f3ac9b08 6bccc883
Exists in master

Merge branch 'master' of https://github.com/lightbase/cacic-agente

Conflicts:
	src/cacic_comm.h
cacic-daemon/cacicD/cacicD.pro
... ... @@ -24,6 +24,7 @@ TEMPLATE = app
24 24 SOURCES += main.cpp \
25 25 cacicd.cpp \
26 26 cacictimer.cpp \
  27 + ../../src/cacic_comm.cpp \
27 28 ../../src/ccacic.cpp \
28 29 ../../src/wmi.cpp \
29 30 ../../src/cacic_computer.cpp \
... ...
cacic-daemon/cacicD/cacicd.cpp
... ... @@ -5,16 +5,17 @@ cacicD::cacicD(int argc, char **argv) : QtService<QCoreApplication>(argc, argv,
5 5 try{
6 6 this->createApplication(argc, argv);
7 7  
8   - Ocacictimer = new CacicTimer();
  8 + Ocacictimer = new CacicTimer(application()->applicationDirPath());
9 9 ccacic = new CCacic;
10 10 setServiceDescription("Cacic Daemon");
11 11 setServiceFlags(QtService::Default);
12 12  
13 13 logManager = QLogger::QLoggerManager::getInstance();
14   - logManager->addDestination(application()->applicationDirPath().append("/log.txt"),"Cacic Daemon",QLogger::InfoLevel);
15   - logManager->addDestination(application()->applicationDirPath().append("/log.txt"),"Cacic Daemon",QLogger::ErrorLevel);
  14 + logManager->addDestination(application()->applicationDirPath() + "/cacicLog.txt","Cacic Daemon",QLogger::InfoLevel);
  15 + logManager->addDestination(application()->applicationDirPath() + "/cacicLog.txt","Cacic Daemon",QLogger::ErrorLevel);
16 16 } catch (...){
17 17 qCritical() << "Error desconhecido no construtor.";
  18 + QLogger::QLog_Error("Cacic Daemon", QString("Erro desconhecido no construtor."));
18 19 }
19 20 }
20 21  
... ... @@ -24,55 +25,51 @@ cacicD::~cacicD()
24 25 logManager->closeLogger();
25 26 application()->exit();
26 27 } catch (...){
27   - qCritical() << "Error desconhecido no desconstrutor.";
  28 + QLogger::QLog_Error("Cacic Daemon", QString("Erro desconhecido no destrutor."));
28 29 }
29 30 }
30 31  
31 32 void cacicD::start() {
32 33 try{
33   - qDebug() << "Inicio do daemon";
34   -
35   - qDebug() << "\nServiço iniciado em" << application()->applicationDirPath();
36 34 QLogger::QLog_Info("Cacic Daemon", QString("Servico iniciado em ").append(application()->applicationDirPath()).append("."));
37   -
38   - QJsonObject result = ccacic->getJsonFromFile(application()->applicationDirPath() + "/getConfig.json");
39   -
  35 + QJsonObject result = ccacic->getJsonFromFile(application()->applicationDirPath().append("/getConfig.json"));
40 36 if(!result.contains("error") && !result.isEmpty()){
41   - Ocacictimer->iniciarTimer(result["codestatus"].toInt(), application()->applicationDirPath());
  37 + Ocacictimer->setPeriodicidadeExecucao(result["codestatus"].toInt());
  38 + Ocacictimer->iniciarTimer();
42 39 }else{
43   - qDebug() << "getConfig.json não encontrado.";
  40 + QLogger::QLog_Error("Cacic Daemon", QString("getConfig.json não encontrado."));
44 41 }
45   -
46   - QLogger::QLog_Info("Cacic Daemon", "Serviço finalizado.");
  42 + //QLogger::QLog_Info("Cacic Daemon", "Serviço finalizado.");
47 43 }catch (...){
48   - qCritical() << "Error desconhecido ao iniciar o serviço.";
  44 + QLogger::QLog_Error("Cacic Daemon", QString("Erro desconhecido ao iniciar o serviço."));
49 45 }
50 46 }
51 47  
52 48 void cacicD::pause()
53 49 {
54 50 try{
55   - qDebug() << "Serviço pausado.";
  51 + QLogger::QLog_Info("Cacic Daemon", QString("Serviço pausado."));
56 52 } catch (...){
57   - qCritical() << "Error desconhecido ao pausar o serviço.";
  53 + QLogger::QLog_Error("Cacic Daemon", QString("Erro desconhecido ao pausar o serviço."));
58 54 }
59 55 }
60 56  
61 57 void cacicD::resume()
62 58 {
63 59 try{
64   - qDebug() << "Serviço resumido.";
  60 + QLogger::QLog_Info("Cacic Daemon", QString("Serviço resumido."));
65 61 } catch (...){
66   - qCritical() << "Error desconhecido ao resumir o serviço.";
  62 + QLogger::QLog_Error("Cacic Daemon", QString("Erro desconhecido ao resumir o serviço."));
67 63 }
68 64 }
69 65  
70 66 void cacicD::stop()
71 67 {
72 68 try{
73   - qDebug() << "Serviço parado.";
  69 + QLogger::QLog_Info("Cacic Daemon", QString("Serviço parado."));
  70 + this->application()->quit();
74 71 } catch (...){
75   - qCritical() << "Error desconhecido ao parar o serviço.";
  72 + QLogger::QLog_Error("Cacic Daemon", QString("Erro desconhecido ao parar o serviço."));
76 73 }
77 74 }
78 75  
... ...
cacic-daemon/cacicD/cacictimer.cpp
1 1 #include "cacictimer.h"
2 2  
3   -CacicTimer::CacicTimer()
  3 +CacicTimer::CacicTimer(QString dirpath)
4 4 {
5   - OCacicComm = new CacicComm();
6   - ccacic = new CCacic();
7   - timer = new QTimer(this);
8   - logManager = QLogger::QLoggerManager::getInstance();
9   -
10   - OCacicComm = CacicComm("http://teste.cacic.cc",
11   - "rG/HcIDVTZ3pPKCf[[MAIS]]I6aigUb7OMeij3FfC7qNaznk0rBRYb6q6kSK3eNfjgptS8BfwW5yJqCvD2ai7xlw9I6P21j6cvQUqlHmAJpCbfwR13urdRE9AhjfokMcPrH6R1/zXPGMHveLRRgKLcqWu2X96rmoQQdRq9EW1SXmYUAx1dCV[[MAIS]]3Ha61XBw5pq58q35zH8Gjt998rTi3ecV8ShXXevqyK[[MAIS]]W07xpgTjbbd6Fbs/35gPfdRRgMNFjq7Gq[[MAIS]]llFgYMJ6UcEhw8f0ZLQo2oL/eRW/CNyeBW6wG0hIo6EIdpi/Ht0/95Uwn2Og[[MAIS]]2UPXsmKKuTMeGwUvPdbEfexlinUO0[[MAIS]]j9qIa2dpjtl0Y5Fyk1Bvw2ZYRTXwgJpUHsBboWmtTFpgX3wSGOWMipE80K8ktRTVYOp[[MAIS]]4qS/SzKWXpfCuZoCncfwE0lCEoreTH[[MAIS]]MLrTkHJP2oqYMAyFyQcjC0UGr3BQGa2edSNXjG7jrTdddga/SODUiF94jgh/QBwhiZby34b__CRYPTED__",
12   - "P198PVwtz5F5CfZPSUrzuaQA/QG1sTnwzl/rBnj8M7y5MglANGodG5LLD4q7oY809HuDR4g5tL64lZRBKvKPmEgWd9iAZKvT4UAm9XWN3nKKLGaznCaJohmntNGqrJP1Zd9riTHGu10mPbg/Uh3TCbBHVOICvu5sDlINlCR6A3[[MAIS]]a55RhfKNidvr5uX0kozCxr5t2DyOb5oPocEGyJKyHLQ==__CRYPTED__",
13   - "1",
14   - "0",
15   - "0",
16   - "YwpgjzZ86/eCsjvOki1KkQ==__CRYPTED__",
17   - "8PT6U445MPNr3S7WHFa20ge/8NJSspSYE/UL3zf[[MAIS]]wkEfNZ7p1B/2o6i89gTZ44Ok__CRYPTED__",
18   - "wshPlZWvLPhbUEQFQ1aQmA==__CRYPTED__",
19   - "E9aKtVz/OSmGv7v1xW4FwaFukOob3qQ/HFDIz916K3ys82qfX9vBDz[[MAIS]]M2cdoYedhNkXt[[MAIS]]UVb10nD[[MAIS]]tOfbn7mlOlTDoGzUl9CgdPCsb[[MAIS]]Qa4wzuCrMw0BcCuaKfr62E3b8vh6Ug4JJbOgBo3ohG3x5O7Ap0D94GKtAWjMuTXRBbhGxPrRS4M6AhzvaN5P8pWd9FikrCLWuMs4ebnRlftef3RmVKScBDQ5zmK6sKxYNmX[[MAIS]]kKn/Gi2[[MAIS]]HftZ7HD9JLvZBpYhp4yjqShblQ67d6PlWgrRWXxwDseIiJe3NlF70zrCPBBelkeAhVDXMXnsYtLms3ElsLzxa3c5vpWzTfgyE[[MAIS]]hvALy4ivew7zaxEwrg2KY1T7GOSWZ7vljIvbhVZJgtzbnYiulFjJTtm5W4uJMKLuUJNzB0rxMkzToIE9/kDmeO2OKiwFbIfbe2Wdq0VpllOkjKtj9WM676iBSpYAXG0MsmLMj9CZ/sNi06hGF[[MAIS]]rXxiOSk66M0Hq[[MAIS]]OeUBh4z3Ra6f9yPJn0K9hIQyT[[MAIS]]Dr/QW/QdJIOkLTW8ZyyAF4DW9ojiTlUdySvB5EB1jyZ5nNTpzyE38qIdg7uM1tdWdm9FZGYxMdHwi1tS2dBeIWkDfWEjih01xiVt2dmdRgo0zIZvmmYDJ9LhCU3XPDlwdeQ8[[MAIS]]F7fnxDfxGqZQjZJ[[MAIS]]Y/Q8bdLpgbhcd3gt3SzjMLE0M[[MAIS]]hTmHG1KP2CzCibZ7grFAN3Y3jSPjmEj5Fzs26tdhdjNzSIt1FCueea8P2c4NmxPYkJCg0D1mgNrkH3L5svsO[[MAIS]]6YYrl3df4s[[MAIS]]fcK/to9s/pnkKfBKrAPF6Z4s2WPsALUPBDS5ty7RC2vqXRvH6hPR4o7xhXzQOQ/1xytr/RoEWEVeZ2wgHVVbbtFsALul/IDc7B45wmwxBx9iZHVwpQJVlNZZUBtwKqKhnXz5pM[[MAIS]]7yUAkfhMcO09pPd5kB2MBdRJs[[MAIS]]2FIk0GRUw05IHkc1rZEX5Ow==__CRYPTED__",
20   - "Yot8BeM9lOh431SB7dYQXw==__CRYPTED__",
21   - "Dcr8b5IfZOJjt6qyH5dGyw==__CRYPTED__",
22   - "2.5.1.1.256.32",
23   - "2.8.1.7",
24   - "2.8.1.6");
25   - OCacicComm->setUrlSsl("https://10.1.0.137/cacic/web/app_dev.php");
26   - OCacicComm->setUsuario("cacic");
27   - OCacicComm->setPassword("cacic123");
28   -
  5 + setApplicationDirPath(dirpath);
  6 + iniciarInstancias();
29 7 connect(timer,SIGNAL(timeout()),this,SLOT(mslot()));
30 8 }
31 9  
... ... @@ -37,133 +15,77 @@ CacicTimer::~CacicTimer()
37 15 delete OCacicComm;
38 16 }
39 17  
40   -void CacicTimer::iniciarTimer(int x, QString applicationDirPath)
  18 +void CacicTimer::reiniciarTimer(){
  19 + timer->stop();
  20 + timer->start(getPeriodicidadeExecucao());
  21 +}
  22 +
  23 +
  24 +void CacicTimer::iniciarTimer()
41 25 {
42   - setApplicationDirPath(applicationDirPath);
43   - logManager->addDestination(getApplicationDirPath().append("/cacicLog.txt"), QStringList("Cacic Daemon"), QLogger::InfoLevel);
44   - logManager->addDestination(getApplicationDirPath().append("/cacicLog.txt"), QStringList("Cacic Daemon"), QLogger::ErrorLevel);
45   - timer->start(x);
  26 + timer->start(getPeriodicidadeExecucao());
46 27 }
47 28  
48 29 void CacicTimer::mslot(){
  30 + try{
  31 + verificarPeriodicidadeJson();
  32 + }catch (...){
  33 + QLogger::QLog_Info("Cacic Daemon (Timer)", QString("Não foi possivel verificar a periodicidade no getConfig.json"));
  34 +
  35 + }
  36 + cMutex->lock();
  37 + QLogger::QLog_Info("Cacic Daemon (Timer)", QString("Semáforo fechado."));
49 38 if(getTest()){
50   - //manager->QLogger::QLog_Trace("ModuleName", "Message: ");
  39 + QLogger::QLog_Info("Cacic Daemon (Timer)", QString("getTeste() success."));
51 40 if(getConfig()){
52   - qDebug() << "getConfig() success. - " + QDateTime::currentDateTime().toLocalTime().toString();
53   - QLogger::QLog_Info("Cacic Daemon", "getConfig() executado com sucesso.");
54   -
55   - // Compara o novo arquivo de configuração com um antigo e se forem diferentes
56   - // mantem o mais recente; caso iguais simplesmente apaga o novo.
57   - QFile *fileOld;
58   - QFile *fileNew;
59   -
60   - fileOld = new QFile(getApplicationDirPath().append("/getConfig.json"));
61   - fileNew = new QFile(getApplicationDirPath().append("/getConfigNew.json"));
62   - if( fileOld->exists() && fileNew->exists() ){
63   - if( Md5IsEqual(QVariant::fromValue(fileOld), QVariant::fromValue(fileNew)) ) {
64   - fileNew->remove();
65   - } else {
66   - // Renomeia getConfigNew.json para getConfig.json
67   - fileOld->remove();
68   - fileNew->rename("getConfigNew.json","getConfig.json");
69   - }
70   - jsonConfig = ccacic->getJsonFromFile(getApplicationDirPath().append("/getConfig.json"));
71   - } else if( fileOld->exists() ){
72   - jsonConfig = ccacic->getJsonFromFile(getApplicationDirPath().append("/getConfig.json"));
73   - } else {
74   - QLogger::QLog_Error("Cacic Daemon", "Arquivo de configuração não criado.");
75   - }
76   - delete fileOld;
77   - delete fileNew;
78   -
79   - /* lê json de configurações e armazena quais módulos executáveis.
80   - * E faz o mesmo tipo de comparação de hashs, com o fim de:
81   - * ou mantem o binário do módulo ou baixa um novo.
82   - */
83   -
84   - /* Aqui estou assumindo um formato do .json em que:
85   - * há a key modulos contem uma lista com o nome dos executaveis e os seus valores hash md5
86   - * há a key metodo que explicita o método de download dos executaveis
87   - */
88   - foreach( QJsonValue moduloValues, jsonConfig["modulos"].toArray() ) {
89   - QString moduloKey, moduloValue;
90   -
91   - moduloKey = moduloValues.toObject()["md5"].toString();
92   - moduloValue = moduloValues.toObject()["nome"].toString();
93   -
94   - moduleMap.insert(moduloKey, moduloValue);
95   - }
96   - metodoDownload = jsonConfig["metodo"].toString();
97   -
98   - int countExecNotFound = 0;
99   - QMap<QString, QString>::const_iterator mapIterator = moduleMap.constBegin();
100   - while (mapIterator != moduleMap.constEnd()) {
101   - QString nomeModulo = mapIterator.value();
102   - QString hashModulo = mapIterator.key();
103   -
104   - // Calcula hash do binario atual
105   -#if defined(Q_OS_WIN)
106   - fileOld = new QFile(getApplicationDirPath().append("/").append(modulo).append(".exe"));
107   -#else
108   - fileOld = new QFile(getApplicationDirPath().append("/").append(nomeModulo));
109   -#endif
110   - if(!fileOld->exists()) {
111   - QLogger::QLog_Error("Cacic Daemon", QString("Módulo ").append(nomeModulo).append(" não encontrado."));
112   -
113   - countExecNotFound++;
114   - if( countExecNotFound == moduleMap.size() ) {
115   - QLogger::QLog_Error("Cacic Daemon", "Não foi possível encontrar nenhum módulo executável!");
116   - return;
117   - }
118   - continue;
119   - }
120   -
121   - QString oldMd5 = QString(QCryptographicHash::hash(fileOld->readAll(),QCryptographicHash::Md5).toHex());
122   -
123   - if ( oldMd5 != hashModulo ) {
124   -
125   - fileOld->rename(getApplicationDirPath().append("/").append(nomeModulo),
126   - getApplicationDirPath().append("/").append("nomeModulo").append("Old") );
127   -
128   - // Download nova versão do executável
129   - if(metodoDownload == "ftp" || metodoDownload == "") {
130   -// OCacicComm->ftpDownload( QString("/ws/get/").append(nomeModulo) );
  41 + QLogger::QLog_Info("Cacic Daemon (Timer)", QString("getConfig() success."));
  42 + QStringList nomesModulos = verificarModulos();
  43 +
  44 + if ( !nomesModulos.empty() ) {
  45 +
  46 + foreach( QString nome, nomesModulos ) {
  47 + if( nome == "gercols" ) {
  48 + definirDirGercols(getApplicationDirPath());
  49 + iniciarModulo();
  50 +
  51 + //Envio do json gerado na coleta
  52 + bool ok;
  53 + QJsonObject jsonColeta = ccacic->getJsonFromFile("coleta.json");
  54 + OCacicComm->comm("/ws/neo/coleta", &ok, jsonColeta );
  55 + } else if( nome == "mapas" ) {
  56 + definirDirMapas(getApplicationDirPath());
  57 + iniciarModulo();
131 58 }
132   -
133   -
134   - fileOld->remove();
135   - delete fileOld;
136 59 }
137   -
138   - mapIterator++;
139 60 }
140 61  
141   - //aqui irá abrir o semaforo e iniciar a coleta.
142   -
143 62 }else{
144 63 qDebug() << "getConfig() failed. - " + QDateTime::currentDateTime().toLocalTime().toString();
145   - QLogger::QLog_Error("Cacic Daemon", "Falha na obtenção do arquivo de configuração.");
  64 + QLogger::QLog_Error("Cacic Daemon (Timer)", "Falha na obtenção do arquivo de configuração.");
146 65 }
147 66 }else{
148 67 qDebug() << "getTest() failed. - " + QDateTime::currentDateTime().toLocalTime().toString();
149   - QLogger::QLog_Error("Cacic Daemon", "Falha na execução do getTest().");
  68 + QLogger::QLog_Error("Cacic Daemon (Timer)", "Falha na execução do getTest().");
150 69 }
  70 + cMutex->unlock();
  71 + QLogger::QLog_Info("Cacic Daemon (Timer)", QString("Semáforo aberto."));
  72 +}
  73 +
  74 +QString CacicTimer::getApplicationDirPath() {
  75 + return applicationDirPath;
151 76 }
152 77  
153 78 bool CacicTimer::getTest(){
154 79 try{
155   - OCacicComm->setUrlGerente("http://10.1.0.137/cacic/web/app_dev.php");
156   - OCacicComm->setUsuario("cacic");
157   - OCacicComm->setPassword("cacic123");
158 80 bool ok;
159 81 QJsonObject as;
160 82 as["computador"] = OCacic_Computer.toJsonObject();
161   - QJsonObject jsonresult = OCacicComm->comm("/ws/neo/login", &ok, as);
162   - if(jsonresult.contains("error")){
163   - return false;
164   - }
  83 + QJsonObject jsonresult = OCacicComm->comm("/ws/neo/test", &ok, as);
  84 + // if(jsonresult.contains("error")){
  85 + // return false;
  86 + // }
165 87 try{
166   - ccacic->setJsonToFile(jsonresult, getApplicationDirPath() + "/getTest.json");
  88 + ccacic->setJsonToFile(jsonresult, this->applicationDirPath + "/getTest.json");
167 89 return true;
168 90 } catch (...) {
169 91 qDebug() << "Erro ao salvar o arquivo de configurações.";
... ... @@ -177,18 +99,15 @@ bool CacicTimer::getTest(){
177 99  
178 100 bool CacicTimer::getConfig(){
179 101 try{
180   - OCacicComm->setUrlGerente("http://10.1.0.137/cacic/web/app_dev.php");
181   - OCacicComm->setUsuario("cacic");
182   - OCacicComm->setPassword("cacic123");
183 102 bool ok;
184 103 QJsonObject as;
185 104 as["computador"] = OCacic_Computer.toJsonObject();
186   - QJsonObject jsonresult = OCacicComm->comm("/ws/neo/login", &ok, as);
187   - if(jsonresult.contains("error")){
188   - return false;
189   - }
  105 + QJsonObject jsonresult = OCacicComm->comm("/ws/neo/config", &ok, as);
  106 + // if(jsonresult.contains("error")){
  107 + // return false;
  108 + // }
190 109 try{
191   - ccacic->setJsonToFile(jsonresult, getApplicationDirPath().append("/getConfigNew.json"));
  110 + ccacic->setJsonToFile(jsonresult, this->applicationDirPath + "/getConfigNew.json");
192 111 return true;
193 112 } catch (...) {
194 113 qDebug() << "Erro ao salvar o arquivo de configurações.";
... ... @@ -200,23 +119,79 @@ bool CacicTimer::getConfig(){
200 119 }
201 120 }
202 121  
203   -void CacicTimer::registraInicio()
  122 +void CacicTimer::lerArquivoConfig ( const QJsonObject& jsonConfig )
  123 +{
  124 + /* lê json de configurações e armazena quais módulos executáveis.
  125 + * E faz o mesmo tipo de comparação de hashs, com o fim de:
  126 + * ou mantem o binário do módulo ou baixa um novo.
  127 + *
  128 + * Aqui estou assumindo um formato do .json em que:
  129 + * há a key modulos contem uma lista com o nome dos executaveis e os seus valores hash md5
  130 + * há a key metodo que explicita o método de download dos executaveis
  131 + */
  132 + foreach( QJsonValue individualModule, jsonConfig["modulos"].toArray() ) {
  133 + QString moduloKey, moduloValue;
  134 +
  135 + moduloKey = individualModule.toObject()["hash"].toString();
  136 + moduloValue = individualModule.toObject()["nome"].toString();
  137 +
  138 + moduleMap.insert(moduloKey, moduloValue);
  139 + }
  140 +
  141 + foreach (QJsonValue individualMetodo, jsonConfig["metodoDownload"].toArray() ) {
  142 + QMap<QString, QString> newEntry;
  143 +
  144 + newEntry.insert(QString("tipo"), individualMetodo.toObject()["tipo"].toString() );
  145 + newEntry.insert(QString("url"), individualMetodo.toObject()["url"].toString() );
  146 + newEntry.insert(QString("path"), individualMetodo.toObject()["path"].toString() );
  147 +
  148 + metodosDownload.append( newEntry );
  149 + }
  150 +}
  151 +
  152 +void CacicTimer::registraInicioColeta()
204 153 {
  154 + QLogger::QLog_Info("Cacic Daemon (Timer)","Coleta iniciada em: " + QDateTime::currentDateTime().toLocalTime().toString());
205 155 }
206 156  
207   -QString CacicTimer::getApplicationDirPath() const
  157 +QString CacicTimer::getDirProgram() const
208 158 {
209   - return applicationDirPath;
  159 + return dirProgram;
  160 +}
  161 +
  162 +void CacicTimer::setDirProgram(const QString &value)
  163 +{
  164 + dirProgram = value;
  165 +}
  166 +
  167 +
  168 +void CacicTimer::iniciarModulo()
  169 +{
  170 + registraInicioColeta();
  171 + QDir::setCurrent(this->applicationDirPath);
  172 + QProcess proc;
  173 + proc.setWorkingDirectory(this->applicationDirPath);
  174 + proc.execute(getDirProgram());
  175 + if((proc.atEnd()) && (proc.exitStatus() == QProcess::NormalExit)){
  176 + registraFimColeta("SUCESSO");
  177 + }else{
  178 + proc.waitForFinished(120000);
  179 + if((!proc.atEnd()) || (proc.exitStatus() == QProcess::CrashExit)){
  180 + registraFimColeta("ERRO");
  181 + proc.kill();
  182 + }
  183 + }
210 184 }
211 185  
212 186 void CacicTimer::setApplicationDirPath(const QString &value)
213 187 {
214   - applicationDirPath = value;
  188 + this->applicationDirPath = value;
215 189 }
216 190  
217 191  
218   -void CacicTimer::registraFim()
  192 +void CacicTimer::registraFimColeta(QString msg)
219 193 {
  194 + QLogger::QLog_Info("Cacic Daemon (Timer)","Coleta finalizada com " + msg + " em: " + QDateTime::currentDateTime().toLocalTime().toString());
220 195 }
221 196  
222 197 bool CacicTimer::Md5IsEqual(QVariant document01,QVariant document02){
... ... @@ -230,3 +205,133 @@ bool CacicTimer::Md5IsEqual(QVariant document01,QVariant document02){
230 205 return false;
231 206 }
232 207 }
  208 +
  209 +void CacicTimer::iniciarInstancias(){
  210 + logManager = QLogger::QLoggerManager::getInstance();
  211 + logManager->addDestination(this->applicationDirPath + "/cacicLog.txt","Cacic Daemon (Timer)",QLogger::InfoLevel);
  212 + logManager->addDestination(this->applicationDirPath + "/cacicLog.txt","Cacic Daemon (Timer)",QLogger::ErrorLevel);
  213 + ccacic = new CCacic();
  214 + timer = new QTimer(this);
  215 + cMutex = new QMutex(QMutex::Recursive);
  216 + OCacicComm = new CacicComm();
  217 + OCacicComm->setUrlSsl("https://10.1.0.137/cacic/web/app_dev.php");
  218 + OCacicComm->setUsuario("cacic");
  219 + OCacicComm->setPassword("cacic123");
  220 +}
  221 +
  222 +void CacicTimer::verificarPeriodicidadeJson()
  223 +{
  224 + QJsonObject result = ccacic->getJsonFromFile(this->applicationDirPath + "/getConfig.json");
  225 + if(!result.contains("error") && !result.isEmpty()){
  226 + if(getPeriodicidadeExecucao() != result["codestatus"].toInt()){
  227 + setPeriodicidadeExecucao(result["codestatus"].toInt());
  228 + reiniciarTimer();
  229 + }
  230 + }else{
  231 + QLogger::QLog_Error("Cacic Daemon (Timer)", QString("getConfig.json com erro ou vazio"));
  232 + }
  233 +}
  234 +
  235 +
  236 +void CacicTimer::definirDirGercols(QString appDirPath){
  237 +#if defined (Q_OS_WIN)
  238 + setDirProgram(appDirPath + "\cacic-gercols.exe");
  239 +#elif defined (Q_OS_LINUX)
  240 + setDirProgram(appDirPath + "/cacic-gercols");
  241 +#endif
  242 +}
  243 +
  244 +void CacicTimer::definirDirMapas(QString appDirPath){
  245 +#if defined (Q_OS_WIN)
  246 + setDirProgram(appDirPath + "\cacic-mapas.exe");
  247 +#elif defined (Q_OS_LINUX)
  248 + setDirProgram(appDirPath + "/cacic-mapas");
  249 +#endif
  250 +}
  251 +
  252 +int CacicTimer::getPeriodicidadeExecucao() const
  253 +{
  254 + return periodicidadeExecucao;
  255 +}
  256 +
  257 +void CacicTimer::setPeriodicidadeExecucao(int value)
  258 +{
  259 + periodicidadeExecucao = value;
  260 +}
  261 +
  262 +
  263 +QStringList CacicTimer::verificarModulos(){
  264 + // Compara o novo arquivo de configuração com um antigo e se forem diferentes
  265 + // mantem o mais recente; caso iguais simplesmente apaga o novo.
  266 + QFile *fileOld;
  267 + QFile *fileNew;
  268 + fileOld = new QFile(this->applicationDirPath + "/getConfig.json");
  269 + fileNew = new QFile(this->applicationDirPath + "/getConfigNew.json");
  270 + if( fileOld->exists() && fileNew->exists() ){
  271 + if( Md5IsEqual(QVariant::fromValue(fileOld), QVariant::fromValue(fileNew)) ) {
  272 + fileNew->remove();
  273 + } else {
  274 + // Renomeia getConfigNew.json para getConfig.json
  275 + fileOld->remove();
  276 + fileNew->rename("getConfigNew.json","getConfig.json");
  277 + }
  278 + jsonConfig = ccacic->getJsonFromFile(this->applicationDirPath + "/getConfig.json");
  279 + } else if( fileOld->exists() ){
  280 + jsonConfig = ccacic->getJsonFromFile(this->applicationDirPath + "/getConfig.json");
  281 + } else {
  282 + QLogger::QLog_Error("Cacic Daemon (Timer)", "Arquivo de configuração não criado.");
  283 + }
  284 + delete fileOld;
  285 + delete fileNew;
  286 + lerArquivoConfig(jsonConfig["agentcomputer"].toObject());
  287 +
  288 + QStringList nomesModulos;
  289 +
  290 + int countExecNotFound = 0;
  291 + QMap<QString, QString>::const_iterator mapIterator = moduleMap.constBegin();
  292 + while (mapIterator != moduleMap.constEnd()) {
  293 + QString nomeModulo = mapIterator.value();
  294 + QString hashModulo = mapIterator.key();
  295 + // Calcula hash do binario atual
  296 +#if defined(Q_OS_WIN)
  297 + fileOld = new QFile(this->applicationDirPath + "/" + modulo + ".exe");
  298 +#else
  299 + fileOld = new QFile(this->applicationDirPath + "/" + nomeModulo);
  300 +#endif
  301 + if(!fileOld->exists()) {
  302 + QLogger::QLog_Error("Cacic Daemon (Timer)", QString("Módulo ").append(nomeModulo).append(" não encontrado."));
  303 + countExecNotFound++;
  304 + if( countExecNotFound == moduleMap.size() ) {
  305 + QLogger::QLog_Error("Cacic Daemon (Timer)", "Não foi possível encontrar nenhum módulo executável!");
  306 + return QStringList();
  307 + }
  308 + continue;
  309 + }
  310 + QString oldMd5 = QString(QCryptographicHash::hash(fileOld->readAll(),QCryptographicHash::Md5).toHex());
  311 + if ( oldMd5 != hashModulo ) {
  312 + fileOld->rename(this->applicationDirPath + "/" + nomeModulo,
  313 + this->applicationDirPath + "/" + nomeModulo + "Old");
  314 + // Download nova versão do executável
  315 + QList<QMap<QString,QString> >::const_iterator metodosIterator = metodosDownload.constBegin();
  316 + bool downloadSucess = false;
  317 + while ( !downloadSucess && metodosIterator != metodosDownload.constEnd() ) {
  318 + if( metodosIterator->value("tipo") == "ftp" || metodosIterator->value("tipo") == "" ) {
  319 + if ( OCacicComm->ftpDownload( metodosIterator->value("url"), metodosIterator->value("path") ) )
  320 + downloadSucess = true;
  321 + } else if ( metodosIterator->value("tipo") == "http" ) {
  322 + if( OCacicComm->httpDownload( metodosIterator->value("url"), metodosIterator->value("path") ) )
  323 + downloadSucess = true;
  324 + }
  325 + metodosIterator++;
  326 + }
  327 + fileOld->remove();
  328 + delete fileOld;
  329 + }
  330 +
  331 + nomesModulos.append(nomeModulo);
  332 +
  333 + mapIterator++;
  334 + }
  335 +
  336 + return nomesModulos;
  337 +}
... ...
cacic-daemon/cacicD/cacictimer.h
... ... @@ -5,6 +5,8 @@
5 5 #include <QDebug>
6 6 #include <QDir>
7 7 #include <QDateTime>
  8 +#include <QMutex>
  9 +#include <QProcess>
8 10 #include <QMap>
9 11 #include "ccacic.h"
10 12 #include "cacic_comm.h"
... ... @@ -15,30 +17,43 @@ class CacicTimer : public QObject
15 17 {
16 18 Q_OBJECT
17 19 public:
18   - CacicTimer();
  20 + CacicTimer(QString dirpath);
  21 + ~CacicTimer();
19 22 QTimer *timer;
20 23 CacicComm *OCacicComm;
21 24 CACIC_Computer OCacic_Computer;
22 25 CCacic *ccacic;
23   - //QLogger::QLoggerManager *manager;
24   - void iniciarTimer(int x, QString applicationDirPath);
  26 + QMutex *cMutex;
  27 + void iniciarTimer();
25 28 bool getTest();
26 29 bool getConfig();
27 30 bool Md5IsEqual(QVariant document01,QVariant document02);
28   - QString getApplicationDirPath() const;
29 31 void setApplicationDirPath(const QString &value);
  32 + QString getApplicationDirPath();
  33 + void setDirProgram(const QString &value);
  34 + void setPeriodicidadeExecucao(int value);
30 35  
31 36 private:
32   - void registraFim();
33   - void registraInicio();
34   -
35   - QJsonObject jsonConfig;
  37 + void registraFimColeta(QString msg);
  38 + void registraInicioColeta();
  39 + QStringList verificarModulos();
  40 + void reiniciarTimer();
36 41 QLogger::QLoggerManager *logManager;
  42 + QString dirProgram;
37 43 QString applicationDirPath;
38   - QString metodoDownload;
  44 + QString getDirProgram() const;
  45 + void iniciarModulo();
  46 + void iniciarInstancias();
  47 + void verificarPeriodicidadeJson();
  48 + void lerArquivoConfig( const QJsonObject &jsonConfig);
  49 + void definirDirGercols(QString appDirPath);
  50 + void definirDirMapas(QString appDirPath);
  51 + QJsonObject jsonConfig;
  52 + int periodicidadeExecucao;
  53 + int getPeriodicidadeExecucao() const;
  54 + QList<QMap<QString,QString> > metodosDownload;
39 55 QMap<QString, QString> moduleMap; // key = hash md5, value = nome do modulo
40 56  
41   -
42 57 private slots:
43 58 void mslot();
44 59 };
... ...
cacic-teste/cacic-teste.pro
... ... @@ -23,6 +23,7 @@ SOURCES += \
23 23 testcacic.cpp \
24 24 ../src/ccacic.cpp \
25 25 ../src/cacic_computer.cpp \
  26 + ../src/cacic_comm.cpp \
26 27 ../src/operatingsystem.cpp \
27 28 ../src/cacic_software.cpp \
28 29 ../src/cacic_hardware.cpp \
... ...
cacic-teste/testcacic.cpp
... ... @@ -9,7 +9,7 @@ CTestCacic::CTestCacic(QObject *parent) :
9 9  
10 10 void CTestCacic::initTestCase()
11 11 {
12   - this->OCacicComm = CacicComm("http://teste.cacic.cc",
  12 + this->OCacicComm = new CacicComm("http://teste.cacic.cc",
13 13 "rG/HcIDVTZ3pPKCf[[MAIS]]I6aigUb7OMeij3FfC7qNaznk0rBRYb6q6kSK3eNfjgptS8BfwW5yJqCvD2ai7xlw9I6P21j6cvQUqlHmAJpCbfwR13urdRE9AhjfokMcPrH6R1/zXPGMHveLRRgKLcqWu2X96rmoQQdRq9EW1SXmYUAx1dCV[[MAIS]]3Ha61XBw5pq58q35zH8Gjt998rTi3ecV8ShXXevqyK[[MAIS]]W07xpgTjbbd6Fbs/35gPfdRRgMNFjq7Gq[[MAIS]]llFgYMJ6UcEhw8f0ZLQo2oL/eRW/CNyeBW6wG0hIo6EIdpi/Ht0/95Uwn2Og[[MAIS]]2UPXsmKKuTMeGwUvPdbEfexlinUO0[[MAIS]]j9qIa2dpjtl0Y5Fyk1Bvw2ZYRTXwgJpUHsBboWmtTFpgX3wSGOWMipE80K8ktRTVYOp[[MAIS]]4qS/SzKWXpfCuZoCncfwE0lCEoreTH[[MAIS]]MLrTkHJP2oqYMAyFyQcjC0UGr3BQGa2edSNXjG7jrTdddga/SODUiF94jgh/QBwhiZby34b__CRYPTED__",
14 14 "P198PVwtz5F5CfZPSUrzuaQA/QG1sTnwzl/rBnj8M7y5MglANGodG5LLD4q7oY809HuDR4g5tL64lZRBKvKPmEgWd9iAZKvT4UAm9XWN3nKKLGaznCaJohmntNGqrJP1Zd9riTHGu10mPbg/Uh3TCbBHVOICvu5sDlINlCR6A3[[MAIS]]a55RhfKNidvr5uX0kozCxr5t2DyOb5oPocEGyJKyHLQ==__CRYPTED__",
15 15 "1",
... ... @@ -24,9 +24,9 @@ void CTestCacic::initTestCase()
24 24 "2.5.1.1.256.32",
25 25 "2.8.1.7",
26 26 "2.8.1.6");
27   - OCacicComm.setUrlSsl("https://10.1.0.137/cacic/web/app_dev.php");
28   - OCacicComm.setUsuario("cacic");
29   - OCacicComm.setPassword("cacic123");
  27 + OCacicComm->setUrlSsl("https://10.1.0.137/cacic/web/app_dev.php");
  28 + OCacicComm->setUsuario("cacic");
  29 + OCacicComm->setPassword("cacic123");
30 30 this->testPath = QDir::currentPath() + "/teste";
31 31 this->testIniPath = testPath + "/teste.ini";
32 32 QVariantMap jsonMap;
... ... @@ -53,14 +53,14 @@ void CTestCacic::testGetValueFromTags()
53 53  
54 54 void CTestCacic::testCommStatus()
55 55 {
56   - QVERIFY(OCacicComm.commStatus());
  56 + QVERIFY(OCacicComm->commStatus());
57 57 }
58 58  
59 59 void CTestCacic::testComm()
60 60 {
61 61 bool ok;
62   - if (OCacicComm.commStatus()){
63   - QJsonObject jsonreply = OCacicComm.comm("/ws/get/test", &ok);
  62 + if (OCacicComm->commStatus()){
  63 + QJsonObject jsonreply = OCacicComm->comm("/ws/get/test", &ok);
64 64 // qDebug() << jsonreply["codestatus"].toString();
65 65 QVERIFY(OCacic.getValueFromTags(jsonreply["reply"].toString(), "Comm_Status", "<>") == QString("OK"));
66 66 } else
... ... @@ -120,7 +120,7 @@ void CTestCacic::testJsonValueFromJsonString()
120 120  
121 121 void CTestCacic::testLogin(){
122 122 bool ok;
123   - QJsonObject jsonReply = OCacicComm.login(&ok);
  123 + QJsonObject jsonReply = OCacicComm->login(&ok);
124 124 QJsonObject sessionvalue = jsonReply["reply"].toObject();
125 125 OCacic.setChaveCrypt(sessionvalue["chavecrip"].toString());
126 126 QVERIFY(ok);
... ... @@ -129,7 +129,7 @@ void CTestCacic::testLogin(){
129 129 void CTestCacic::testSslConnection()
130 130 {
131 131 bool ok;
132   - QJsonObject json = OCacicComm.comm("", &ok, QJsonObject(), true);
  132 + QJsonObject json = OCacicComm->comm("", &ok, QJsonObject(), true);
133 133 QJsonValue jsonvalue = (!json["codestatus"].isNull()) ?
134 134 json["codestatus"] :
135 135 QJsonValue::fromVariant(-1);
... ... @@ -239,8 +239,8 @@ void CTestCacic::testGetTest()
239 239 bool ok;
240 240 QJsonObject envio;
241 241 envio["computador"] = OCacicComp.toJsonObject();
242   - OCacicComm.setUrlGerente("http://10.1.0.137/cacic/web/app_dev.php");
243   - OCacicComm.comm("/ws/neo/getTest", &ok, envio);
  242 + OCacicComm->setUrlGerente("http://10.1.0.137/cacic/web/app_dev.php");
  243 + OCacicComm->comm("/ws/neo/getTest", &ok, envio);
244 244 QVERIFY(ok);
245 245 }
246 246  
... ... @@ -319,8 +319,19 @@ void CTestCacic::testLogger()
319 319 logFile06.close();
320 320 }
321 321  
  322 +void CTestCacic::testFtpDownload()
  323 +{
  324 + OCacicComm->ftpDownload("ftp://ftp.unicamp.br", "/pub/gnu/Licenses/gpl-2.0.txt");
  325 + QFile downloaded("gpl-2.0.txt");
  326 +
  327 + QVERIFY( downloaded.open(QIODevice::ReadOnly) );
  328 + QVERIFY( downloaded.exists() );
  329 + QVERIFY( downloaded.readAll() != "" );
  330 +}
  331 +
322 332 void CTestCacic::cleanupTestCase()
323 333 {
  334 +// OCacic.deleteFile("gpl-2.0.txt");
324 335 OCacic.deleteFile("log01.txt");
325 336 OCacic.deleteFile("./log02.txt");
326 337 OCacic.deleteFile("../log03.txt");
... ...
cacic-teste/testcacic.h
... ... @@ -26,7 +26,7 @@ public:
26 26 explicit CTestCacic(QObject *parent = 0);
27 27  
28 28 private:
29   - CacicComm OCacicComm;
  29 + CacicComm *OCacicComm;
30 30 CCacic OCacic;
31 31 CACIC_Computer OCacicComp;
32 32 cacic_software OCacicSoftware;
... ... @@ -75,6 +75,7 @@ private slots:
75 75 void testGetTest();
76 76 void testColeta();
77 77 void testLogger();
  78 + void testFtpDownload();
78 79 void cleanupTestCase();
79 80 };
80 81  
... ...
gercols/gercols.cpp
... ... @@ -16,6 +16,7 @@ Gercols::Gercols(QObject *parent)
16 16  
17 17 oCacic.setJsonToFile(configTeste,"configReq.json");
18 18 /*************************************************************************/
  19 +
19 20 oColeta = new CColeta;
20 21 //Pega chave do registro, que será pega na instalação.
21 22 oCacic.setChaveCrypt(oCacic.getValueFromRegistry("Lightbase", "Cacic", "key").toString());
... ... @@ -32,7 +33,11 @@ void Gercols::run()
32 33 //emite sinal para começar a coleta
33 34 emit iniciaColeta();
34 35  
  36 + /* Json de teste sendo excluído
  37 + */
35 38 oCacic.deleteFile("configReq.json");
  39 + /***********************************/
  40 +
36 41 oColeta->waitToCollect();
37 42 //salva json em arquivo
38 43 if (!oColeta->toJsonObject().isEmpty())
... ...
src/cacic_comm.cpp 0 → 100644
... ... @@ -0,0 +1,273 @@
  1 +#include "cacic_comm.h"
  2 +
  3 +CacicComm::CacicComm ()
  4 +{
  5 +}
  6 +
  7 +CacicComm::CacicComm (QString urlGerente, QString operatingSystem, QString computerSystem, QString csCipher,
  8 + QString csDebug, QString csCompress, QString httpUserAgent, QString moduleFolderName,
  9 + QString moduleProgramName, QString networkConfiguration,QString phpAuthPw, QString phpAuthUser,
  10 + QString so, QString cacicVersion, QString gercolsVersion)
  11 +{
  12 + this->setUrlGerente(urlGerente);
  13 + params.addQueryItem("OperatingSystem", operatingSystem);
  14 + params.addQueryItem("ComputerSystem",computerSystem);
  15 + params.addQueryItem("cs_cipher",csCipher);
  16 + params.addQueryItem("cs_debug",csDebug);
  17 + params.addQueryItem("cs_compress",csCompress);
  18 + params.addQueryItem("HTTP_USER_AGENT",httpUserAgent);
  19 + params.addQueryItem("ModuleFolderName",moduleFolderName);
  20 + params.addQueryItem("ModuleProgramName",moduleProgramName);
  21 + params.addQueryItem("NetworkAdapterConfiguration",networkConfiguration);
  22 + params.addQueryItem("PHP_AUTH_PW",phpAuthPw);
  23 + params.addQueryItem("PHP_AUTH_USER",phpAuthUser);
  24 + params.addQueryItem("te_so",so);
  25 + params.addQueryItem("te_versao_cacic",cacicVersion);
  26 + params.addQueryItem("te_versao_gercols",gercolsVersion);
  27 +
  28 +
  29 +}
  30 +
  31 +QJsonObject CacicComm::comm(QString route, bool *ok, const QJsonObject &json, bool isSsl)
  32 +{
  33 + *ok = false;
  34 + QByteArray data;
  35 + QNetworkRequest req;
  36 + QUrl url;
  37 + QString strReply;
  38 + QJsonObject jsonObj;
  39 + if (isSsl){
  40 + url = urlSsl.isEmpty() ? "https://" + this->urlGerente + route : this->urlSsl + route;
  41 + if (!url.isValid()){
  42 + jsonObj["error"] = QVariant("Invalid Url").toJsonValue();
  43 + return jsonObj;
  44 + }
  45 + req.setSslConfiguration(QSslConfiguration::defaultConfiguration());
  46 + } else
  47 + url = "http://" + urlGerente + route;
  48 + req.setUrl(url);
  49 + req.setHeader(QNetworkRequest::LocationHeader, "Cacic Agente");
  50 + if (json.empty()){
  51 + //se não for passado QJson, será mandado os valores do get/test antigo. (Será retirado depois)
  52 + req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
  53 + data.append(params.toString());
  54 + } else {
  55 + // Add JSON
  56 + QJsonDocument d(json);
  57 + data.append(d.toJson());
  58 + req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
  59 + }
  60 + QEventLoop eventLoop;
  61 + QNetworkAccessManager mgr;
  62 + QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
  63 +
  64 + QNetworkReply *reply = mgr.post(req, data);
  65 + if (!reply->sslConfiguration().isNull()){
  66 + reply->ignoreSslErrors();
  67 + }
  68 + eventLoop.exec(); // sai do looping chamando o "finished()".
  69 +
  70 + jsonObj.insert("codestatus", QJsonValue::fromVariant(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute)));
  71 +
  72 + if (reply->error() == QNetworkReply::NoError) {
  73 + //se não houver erro, grava o retorno;
  74 + QVariant replyVariant = reply->readAll();
  75 + QJsonDocument replyDocument = QJsonDocument::fromJson(replyVariant.toByteArray());
  76 + jsonObj["reply"] = (!replyDocument.isNull()) ?
  77 + replyDocument.object() :
  78 + QJsonValue::fromVariant(replyVariant.toString());
  79 + *ok = true;
  80 + delete reply;
  81 + } else {
  82 + strReply = reply->errorString();
  83 + jsonObj.insert("error", QJsonValue::fromVariant(strReply));
  84 + delete reply;
  85 + }
  86 + return jsonObj;
  87 +}
  88 +
  89 +
  90 +/* commStatus
  91 + * execulta um teste do tipo GET na urlGerente;
  92 + * @return retorna o resultado da conexão HTTP:
  93 + * exemplo: 200 OK
  94 + */
  95 +bool CacicComm::commStatus(){
  96 + // cria um event-loop temporario
  97 + QEventLoop eventLoop;
  98 + // "quit()" o event-loop, when the network request "finished()"
  99 + QNetworkAccessManager mgr;
  100 + QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
  101 + // a requisição HTTP
  102 + QUrl url = "http://" + urlGerente;
  103 + QNetworkRequest req( url );
  104 + req.setHeader(QNetworkRequest::LocationHeader, "Cacic Agente");
  105 + QNetworkReply *reply = mgr.get(req);
  106 + eventLoop.exec(); // sai do looping chamando o "finished()".
  107 +
  108 + QString reason = reply->attribute( QNetworkRequest::HttpReasonPhraseAttribute ).toString();
  109 + if (reply->attribute( QNetworkRequest::HttpStatusCodeAttribute ).isValid()){
  110 +// qDebug() << "Status:" << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() << reason;
  111 + return true;
  112 + }else{
  113 + reason = reply->attribute( QNetworkRequest::HttpReasonPhraseAttribute ).toString();
  114 +// qDebug() << "Error:" << reason;
  115 + return false;
  116 + }
  117 +}
  118 +
  119 +/* login
  120 + * realiza login com usuario e senha
  121 + * @return retorna json com sessão e chave de criptografia
  122 + */
  123 +QJsonObject CacicComm::login(bool *ok) {
  124 + *ok = false;
  125 + // Cria dados de login
  126 + QVariantMap login;
  127 + login["user"] = this->usuario;
  128 + login["password"] = this->password;
  129 + // Cria conexão e retorna Json da sessão
  130 + QJsonObject retorno = this->comm("/ws/neo/getLogin", ok, QJsonObject::fromVariantMap(login), true);
  131 + if (*ok)
  132 + this->session = retorno["reply"].toObject()["session"].toString();
  133 + return retorno;
  134 +}
  135 +
  136 +/* fileDownload( QString path )
  137 + *
  138 + * Faz o download de um arquivo usando o protocolo mode
  139 + * a partir da url do gerente e do caminho até o arquivo.
  140 + */
  141 +bool CacicComm::fileDownload(const QString &mode, const QString &path){
  142 + QEventLoop eventLoop;
  143 + QNetworkAccessManager manager;
  144 + QNetworkRequest request;
  145 + QNetworkReply *reply;
  146 +
  147 + QObject::connect(&manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(fileDownloadFinished(QNetworkReply*)) );
  148 + QObject::connect(&manager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()) );
  149 +
  150 + QStringList splitPath = path.split("/");
  151 +
  152 + fileHandler = new QFile(splitPath[splitPath.size() - 1]);
  153 + if( !fileHandler->open(QIODevice::WriteOnly) ) {
  154 + qDebug() << "ftpDownload: fileHandler nâo pode abrir arquivo.";
  155 + return false;
  156 + }
  157 +
  158 + QUrl url(urlGerente);
  159 + url.setScheme(mode);
  160 + url.setPath(path);
  161 + request.setUrl(url);
  162 +
  163 + reply = manager.get(request);
  164 +
  165 + eventLoop.exec();
  166 +
  167 + delete fileHandler;
  168 + delete reply;
  169 +
  170 + return true;
  171 +}
  172 +
  173 +/* fileDownload( QString urlServer, QString path )
  174 + *
  175 + * Faz o download de um arquivo usando o protocolo mode
  176 + * a partir da url recebida e do caminho até o arquivo.
  177 + */
  178 +bool CacicComm::fileDownload(const QString &mode, const QString &urlServer, const QString &path){
  179 + QEventLoop eventLoop;
  180 + QNetworkAccessManager manager;
  181 + QNetworkRequest request;
  182 + QNetworkReply *reply;
  183 +
  184 + QObject::connect(&manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(fileDownloadFinished(QNetworkReply*)) );
  185 + QObject::connect(&manager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()) );
  186 +
  187 + QStringList splitPath = path.split("/");
  188 +
  189 + fileHandler = new QFile(splitPath[splitPath.size() - 1]);
  190 + if( !fileHandler->open(QIODevice::WriteOnly) ) {
  191 + qDebug() << "ftpDownload: fileHandler nâo pode abrir arquivo.";
  192 + return false;
  193 + }
  194 +
  195 + QUrl url(urlServer);
  196 + url.setScheme(mode);
  197 + url.setPath(path);
  198 + request.setUrl(url);
  199 +
  200 + reply = manager.get(request);
  201 +
  202 + eventLoop.exec();
  203 +
  204 + delete fileHandler;
  205 + delete reply;
  206 +
  207 + return true;
  208 +}
  209 +
  210 +bool CacicComm::ftpDownload( const QString &path ){
  211 + return fileDownload("ftp", path);
  212 +}
  213 +
  214 +bool CacicComm::ftpDownload( const QString &urlServer, const QString &path ){
  215 + return fileDownload("ftp", urlServer, path);
  216 +}
  217 +
  218 +bool CacicComm::httpDownload( const QString &path ){
  219 + return fileDownload("http", path);
  220 +}
  221 +
  222 +bool CacicComm::httpDownload( const QString &urlServer, const QString &path ){
  223 + return fileDownload("http", urlServer, path);
  224 +}
  225 +
  226 +QString CacicComm::getUrlSsl (){
  227 + return this->urlSsl;
  228 +}
  229 +
  230 +void CacicComm::setUrlSsl(QString value){
  231 + this->urlSsl = value;
  232 +}
  233 +
  234 +QString CacicComm::getUrlGerente (){
  235 + return this->urlGerente;
  236 +}
  237 +
  238 +void CacicComm::setUrlGerente(QString value){
  239 + if (value.contains("://", Qt::CaseInsensitive)){
  240 + value = value.mid(value.indexOf("://") + 3);
  241 + }
  242 + if (value.endsWith("/")){
  243 + value.remove(value.size()-1, 1);
  244 + }
  245 + this->urlGerente = value;
  246 +}
  247 +
  248 +QString CacicComm::getPassword()
  249 +{
  250 + return this->password;
  251 +}
  252 +
  253 +void CacicComm::setPassword(QString value)
  254 +{
  255 + this->password = value;
  256 +}
  257 +QString CacicComm::getUsuario()
  258 +{
  259 + return this->usuario;
  260 +}
  261 +
  262 +void CacicComm::setUsuario(QString value)
  263 +{
  264 + this->usuario = value;
  265 +}
  266 +
  267 +void CacicComm::fileDownloadFinished(QNetworkReply* reply)
  268 +{
  269 + QTextStream out(fileHandler);
  270 + out << reply->readAll();
  271 + fileHandler->close();
  272 + reply->close();
  273 +}
... ...
src/cacic_comm.h
... ... @@ -13,200 +13,55 @@
13 13 #include <QJsonObject>
14 14 #include <QJsonDocument>
15 15  
16   -class CacicComm {
  16 +class CacicComm : public QObject{
17 17  
18   -private:
19   - QUrlQuery params;
20   - QString urlGerente;
21   - QString urlSsl;
22   - QString usuario;
23   - QString password;
24   - QString session;
  18 + Q_OBJECT
25 19  
26 20 public:
27   - CacicComm (){
28   - }
29 21  
  22 + CacicComm ();
30 23 CacicComm (QString urlGerente, QString operatingSystem, QString computerSystem, QString csCipher,
31 24 QString csDebug, QString csCompress, QString httpUserAgent, QString moduleFolderName,
32 25 QString moduleProgramName, QString networkConfiguration,QString phpAuthPw, QString phpAuthUser,
33   - QString so, QString cacicVersion, QString gercolsVersion)
34   - {
35   - this->setUrlGerente(urlGerente);
36   - params.addQueryItem("OperatingSystem", operatingSystem);
37   - params.addQueryItem("ComputerSystem",computerSystem);
38   - params.addQueryItem("cs_cipher",csCipher);
39   - params.addQueryItem("cs_debug",csDebug);
40   - params.addQueryItem("cs_compress",csCompress);
41   - params.addQueryItem("HTTP_USER_AGENT",httpUserAgent);
42   - params.addQueryItem("ModuleFolderName",moduleFolderName);
43   - params.addQueryItem("ModuleProgramName",moduleProgramName);
44   - params.addQueryItem("NetworkAdapterConfiguration",networkConfiguration);
45   - params.addQueryItem("PHP_AUTH_PW",phpAuthPw);
46   - params.addQueryItem("PHP_AUTH_USER",phpAuthUser);
47   - params.addQueryItem("te_so",so);
48   - params.addQueryItem("te_versao_cacic",cacicVersion);
49   - params.addQueryItem("te_versao_gercols",gercolsVersion);
50   -
51   -
52   - }
53   -
54   - QJsonObject comm(QString route, bool *ok, const QJsonObject &json = QJsonObject(), bool isSsl = false)
55   - {
56   - *ok = false;
57   - QByteArray data;
58   - QNetworkRequest req;
59   - QUrl url;
60   - QString strReply;
61   - QJsonObject jsonObj;
62   - if (isSsl){
63   - url = urlSsl.isEmpty() ? "https://" + this->urlGerente + route : this->urlSsl + route;
64   - if (!url.isValid()){
65   - jsonObj["error"] = QJsonValue::fromVariant(QVariant("Invalid Url"));
66   - return jsonObj;
67   - }
68   - req.setSslConfiguration(QSslConfiguration::defaultConfiguration());
69   - } else
70   - url = "http://" + urlGerente + route;
71   - req.setUrl(url);
72   - req.setHeader(QNetworkRequest::LocationHeader, "Cacic Agente");
73   - if (json.empty()){
74   - //se não for passado QJson, será mandado os valores do get/test antigo. (Será retirado depois)
75   - req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
76   - data.append(params.toString());
77   - } else {
78   - // Add JSON
79   - QJsonDocument d(json);
80   - data.append(d.toJson());
81   - req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
82   - }
83   - QEventLoop eventLoop;
84   - QNetworkAccessManager mgr;
85   - QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
86   -
87   - QNetworkReply *reply = mgr.post(req, data);
88   - if (!reply->sslConfiguration().isNull()){
89   - reply->ignoreSslErrors();
90   - }
91   - eventLoop.exec(); // sai do looping chamando o "finished()".
92   -
93   - jsonObj.insert("codestatus", QJsonValue::fromVariant(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute)));
94   -
95   - if (reply->error() == QNetworkReply::NoError) {
96   - //se não houver erro, grava o retorno;
97   - QVariant replyVariant = reply->readAll();
98   - QJsonDocument replyDocument = QJsonDocument::fromJson(replyVariant.toByteArray());
99   - jsonObj["reply"] = (!replyDocument.isNull()) ?
100   - replyDocument.object() :
101   - QJsonValue::fromVariant(replyVariant.toString());
102   - *ok = true;
103   - delete reply;
104   - } else {
105   - strReply = reply->errorString();
106   - jsonObj.insert("error", QJsonValue::fromVariant(strReply));
107   - delete reply;
108   - }
109   - return jsonObj;
110   - }
111   -
  26 + QString so, QString cacicVersion, QString gercolsVersion);
  27 + QJsonObject comm(QString route, bool *ok, const QJsonObject &json = QJsonObject(), bool isSsl = false);
  28 + bool commStatus();
  29 + QJsonObject login(bool *ok);
  30 + bool ftpDownload(const QString &path);
  31 + bool ftpDownload(const QString &urlServer, const QString &path);
  32 + bool httpDownload(const QString &path);
  33 + bool httpDownload(const QString &urlServer, const QString &path);
  34 + QString getUrlSsl ();
  35 + void setUrlSsl(QString value);
  36 + QString getUrlGerente ();
  37 + void setUrlGerente(QString value);
  38 + QString getPassword();
  39 + void setPassword(QString value);
  40 + QString getUsuario();
  41 + void setUsuario(QString value);
112 42  
113   - /* commStatus
114   - * execulta um teste do tipo GET na urlGerente;
115   - * @return retorna o resultado da conexão HTTP:
116   - * exemplo: 200 OK
117   - */
118   - bool commStatus(){
119   - // cria um event-loop temporario
120   - QEventLoop eventLoop;
121   - // "quit()" o event-loop, when the network request "finished()"
122   - QNetworkAccessManager mgr;
123   - QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
124   - // a requisição HTTP
125   - QUrl url = "http://" + urlGerente;
126   - QNetworkRequest req( url );
127   - req.setHeader(QNetworkRequest::LocationHeader, "Cacic Agente");
128   - QNetworkReply *reply = mgr.get(req);
129   - eventLoop.exec(); // sai do looping chamando o "finished()".
130 43  
131   - QString reason = reply->attribute( QNetworkRequest::HttpReasonPhraseAttribute ).toString();
132   - if (reply->attribute( QNetworkRequest::HttpStatusCodeAttribute ).isValid()){
133   -// qDebug() << "Status:" << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() << reason;
134   - return true;
135   - }else{
136   - reason = reply->attribute( QNetworkRequest::HttpReasonPhraseAttribute ).toString();
137   -// qDebug() << "Error:" << reason;
138   - return false;
139   - }
140   - }
141 44  
142   - /* login
143   - * realiza login com usuario e senha
144   - * @return retorna json com sessão e chave de criptografia
145   - */
146   - QJsonObject login(bool *ok) {
147   - *ok = false;
148   - // Cria dados de login
149   - QVariantMap login;
150   - login["user"] = this->usuario;
151   - login["password"] = this->password;
152   - // Cria conexão e retorna Json da sessão
153   - QJsonObject retorno = this->comm("/ws/neo/getLogin", ok, QJsonObject::fromVariantMap(login), true);
154   - if (*ok)
155   - this->session = retorno["reply"].toObject()["session"].toString();
156   - return retorno;
157   - }
158   -
159   - bool ftpDownload(QString path){
160   - QUrl url(urlGerente);
161   - url.setScheme("ftp");
162   - url.setPath(path);
163   -
164   - }
165   -
166   - QString getUrlSsl (){
167   - return this->urlSsl;
168   - }
169   -
170   - void setUrlSsl(QString value){
171   - this->urlSsl = value;
172   - }
173   -
174   - QString getUrlGerente (){
175   - return this->urlGerente;
176   - }
  45 +signals:
  46 +// void finished(QNetworkReply* reply);
177 47  
178   - void setUrlGerente(QString value){
179   - if (value.contains("://", Qt::CaseInsensitive)){
180   - value = value.mid(value.indexOf("://") + 3);
181   - }
182   - if (value.endsWith("/")){
183   - value.remove(value.size()-1, 1);
184   - }
185   - this->urlGerente = value;
186   - }
  48 +private slots:
187 49  
188   - QString getPassword()
189   - {
190   - return this->password;
191   - }
  50 + void fileDownloadFinished(QNetworkReply* reply);
192 51  
193   - void setPassword(QString value)
194   - {
195   - this->password = value;
196   - }
197   - QString getUsuario()
198   - {
199   - return this->usuario;
200   - }
  52 +private:
201 53  
202   - void setUsuario(QString value)
203   - {
204   - this->usuario = value;
205   - }
  54 + bool fileDownload(const QString &mode, const QString &path);
  55 + bool fileDownload(const QString &mode, const QString &urlServer, const QString &path);
206 56  
  57 + QUrlQuery params;
  58 + QString urlGerente;
  59 + QString urlSsl;
  60 + QString usuario;
  61 + QString password;
  62 + QString session;
207 63  
208   -signals:
209   - void finished(QNetworkReply* reply);
  64 + QFile *fileHandler;
210 65  
211 66 };
212 67 #endif // CACIC_COMM_H
... ...
src/ccoleta.cpp
... ... @@ -42,6 +42,7 @@ bool CColeta::waitToCollect()
42 42  
43 43 void CColeta::run()
44 44 {
  45 + /* Versão do json de testes */
45 46 QJsonObject coleta = oCacic.getJsonFromFile("configReq.json");
46 47  
47 48 if( coleta.contains("hardware") ){
... ... @@ -54,6 +55,27 @@ void CColeta::run()
54 55 emit beginSoftware();
55 56 } else
56 57 this->softwareIsFinish = true;
  58 + /************************************************************/
  59 +
  60 +
  61 + /* Versão do json definitiva, obtiva através do getConfig()
  62 + QJsonObject coleta = oCacic.getJsonFromFile("getConfig.json")["agentcomputer"].toObject();
  63 +
  64 + foreach ( QJsonValue action, coleta["actions"].toArray() ){
  65 + QJsonObject jsonAction = action.toObject();
  66 +
  67 + if( jsonAction.contains("col_hard") && jsonAction["col_hard"] == QJsonValue.fromVariant(QString("true")) ){
  68 + this->hardwareIsFinish = false;
  69 + emit beginHardware();
  70 + } else
  71 + this->hardwareIsFinish = true;
  72 + if ( jsonAction.contains("col_soft") && jsonAction["col_soft"] == QJsonValue.fromVariant(QString("true")) ){
  73 + this->softwareIsFinish = false;
  74 + emit beginSoftware();
  75 + } else
  76 + this->softwareIsFinish = true;
  77 + }
  78 + /************************************************************/
57 79  
58 80 }
59 81  
... ...