Skip to content
Snippets Groups Projects
Commit 94216ab7 authored by Luiz Vasconcellos's avatar Luiz Vasconcellos
Browse files

Merge branch 'minor-adjustments' into 'developer'

Minor adjustments

See merge request !7
parents 450e55bb 45815864
No related branches found
No related tags found
1 merge request!7Minor adjustments
# Webservice PInSIS # Webservice PInSIS
Webservice para disponibilizar os dados coletados pelos agentes do projeto PInSIS Webservice that provide the data collected by agents of project PInSIS
## Dependencies:
## Dependências: - Use npm install to install the dependencies of nodejs
- postgres >=9.0 (not necessarily in the same computer)
- Use npm install para instalar as dependências do nodejs - Must be created a Database and User
- postgres >=9.0 (não necessariamente na mesma máquina)
- Deve-se criar usuário e banco de dados
- npm >=5.7.1 - npm >=5.7.1
- nodejs >=v6.11.4 - nodejs >=v6.11.4
## Uso ## Use
### Instale os módulos ### Install modules
```bash ```bash
npm install #Instala as dependências do node npm install #Install node dependencies
``` ```
### Crie as relações ### Create the relatios
No diretório db/ há a documentação detalhada de como se deve criar/migrar as relações do banco de dados There is a detailed documentation in the directory `db/` about how can be created/migrated the relations of the database
### Crie e altere o arquivo de configuração para acesso ao DB ### Create and alter the file of configuration to access database
```bash ```bash
cp config.js.example config.js cp config.js.example config.js
...@@ -35,10 +34,10 @@ vim config.js ...@@ -35,10 +34,10 @@ vim config.js
```bash ```bash
npm start #Executa o arquivo ./src/server.js com parâmetros defaults npm start #Execute the file ./src/server.js with default parameters
``` ```
Os parâmetros possíveis para executar o server.js são: The possible parameters to execute `server.js` are:
- [-c, --config] alternative configuration file (default: config.js) - [-c, --config] alternative configuration file (default: config.js)
- [-p, --port] port where the server will listen to - [-p, --port] port where the server will listen to
- [--insecure] allows session cookies to be passed around in insecure connections - [--insecure] allows session cookies to be passed around in insecure connections
...@@ -47,14 +46,14 @@ Os parâmetros possíveis para executar o server.js são: ...@@ -47,14 +46,14 @@ Os parâmetros possíveis para executar o server.js são:
- [-d, --daemon] start the server as a daemon - [-d, --daemon] start the server as a daemon
- [--pid-file] path for the pid file when running as a daemon - [--pid-file] path for the pid file when running as a daemon
## Possíveis erros ## Possible errors
- Os principais problemas encontrados estão relacionados à conexão com o DB - The main problems verified are relationed to the database connection.
Em caso de erros verifique se é possível fazer conexão com o DB com o In case of errors, verify if is possible do the connection with database
psql por exemplo (no mesmo usuário em que está se executando os comandos) by `psql`command (in the same user that is in configuration file).
- Outro caso comum é tentar executar o serviço numa mesma porta em que outro - Another commum case is to try execute the service in a port that another
processo já está executando. Nesse caso um erro semelhante a process is alredy executing. In this case a error similar to
*Error: bind EADDRINUSE null:3000* será notificado. `Error: bind EADDRINUSE null:3000` will be notified.
Nesse caso tente alterar a porta em que o serviço será provido ou encerre In this case, try alter the port that the service is provided or stop
o outro processo. the other process.
var config = module.exports = {}; var config = module.exports = {};
config.db_config = { config.db_config = {
user: 'user', user: DB_USER,
password: 'password', password: DB_PASS,
database: 'dbname', database: DB_DBNAME,
host: 'localhost', host: DB_HOST,
port: 5432 port: DB_PORT
}; };
config.mail = { config.agentVersion = 0.0;
port: 25
, host: 'localhost'
, ignoreTLS: true
, secure: false
, from: 'noreply@simmc.c3sl.ufpr.br'
};
config.report_config = {
imagesPath: './reports/reports/images/'
, outputPath: './tmp/reports'
};
config.alert_config = {
alertsPath: '/home/simmc/simmc/scripts/alerts/'
};
config.fqdn = 'simmc.c3sl.ufpr.br';
config.agentVersion = 1.0;
config.secret = '123mudar';
// Uncomment to enable memcached
//
// config.memcached = {
// server: 'localhost:11211',
// options: { retries: 1, timeout: 1000, poolSize: 1 },
// lifetime: 3600 // 1 hour in seconds
// };
# Create/Migrate DB PInSIS # Create/Migrate DB PInSIS
Módulo para criar/migrar as relações do banco de dados do projeto PInSIS Module to create/migrate the relations of the database of project PInSIS
Este projeto utiliza o [node-pg-migrate](https://github.com/salsita/node-pg-migrate). This subproject utilize the [node-pg-migrate](https://github.com/salsita/node-pg-migrate).
## Exemplo de uso: ## Use example:
```bash ```bash
DATABASE_URL='postgresql://logindb:password@localhost/dbtest' npm run migrate up # Cria todos os schemas DATABASE_URL='postgresql://logindb:password@localhost/dbtest' npm run migrate up # Create all schemas
DATABASE_URL='postgresql://logindb:password@localhost/dbtest' npm run migrate down # Cria o banco de dados DATABASE_URL='postgresql://logindb:password@localhost/dbtest' npm run migrate down # Undo the last migration
``` ```
Observe que é necessário definir uma variável de ambiente ao executar os comandos acima. Observe that is necessary to define a env variable by the executation of the above commands.
Para uma documentação mais completa e métodos alternativos de utilizar os comandos consule [node-pg-migrate CLI Usage](https://github.com/salsita/node-pg-migrate/blob/master/docs/cli.md) There is a documentation more complete and alternative methods to utilize the library in [node-pg-migrate CLI Usage](https://github.com/salsita/node-pg-migrate/blob/master/docs/cli.md).
## Camadas
Observe que quando os migrates ups executados no exemplo anterior passarão por todas as migrações existentes em ./migrations e criarão os modelos na ordem cronológica. ## Layers
No caso dos migrates downs, cada execução irá "descer uma camada" em relação às migrações.
Consulte a documentação original para ver métodos alternativos para simplificar o uso. Observe that when the `migrates up`commands are executed in the previous example, all the migrations in `./migrations` will be used to create the database in cronologic order.
In case of `migrate down`commands, each execution will "down one layer" in relation of the migrations.
## Migrar o banco You can find in the original documentation alternative methods to simplify the use.
## Migrate the database
```bash ```bash
# Esses comandos criarão modelos no diretório /migrations # This commands will create models in the directory ./migrations
# Por questões de padronização, adotou-se que os nomes das migrações # Because of standartion, the migrations name will use _ instead of space
# teriam espacamento substituido por _ # by instance: add_table_1
# por exemplo: add_table_1
# alter_colum_x_from_table2 # alter_colum_x_from_table2
npm run migrate create nome da migracao Examples
npm run migrate create migration4
npm run migrate create migration5 npm run migrate create add_table_agent
npm run migrate create add_views_agentuses
``` ```
## Possíveis erros ## Possible errors
- Os principais problemas encontrados estão relacionados à conexão com o DB - The main problems verified are relationed to the database connection.
Em caso de erros verifique se é possível fazer conexão com o DB com o In case of errors, verify if is possible do the connection with database
psql por exemplo (no mesmo usuário em que está se executando os comandos) by `psql`command (in the same user that is in configuration file).
...@@ -4,8 +4,11 @@ ...@@ -4,8 +4,11 @@
"description": "", "description": "",
"main": "", "main": "",
"dependencies": { "dependencies": {
"node-pg-migrate": "^3.0.0", "migration": "^0.3.0",
"pg": "^7.4.1" "node-pg-migrate": "^3.1.1",
"npm": "^6.0.1",
"pg": "^7.4.1",
"runner": "^1.0.4"
}, },
"devDependencies": {}, "devDependencies": {},
"scripts": { "scripts": {
......
...@@ -60,13 +60,17 @@ function querie_db(req, q, callback){ ...@@ -60,13 +60,17 @@ function querie_db(req, q, callback){
conn.query(q.toParam().text,q.toParam().values, function(err,data,fields){ conn.query(q.toParam().text,q.toParam().values, function(err,data,fields){
done(); done();
if (err) callback(err, null); if (err){
callback(err, null);
return;
}
callback(null, data) callback(null, data)
}); });
}); });
} }
catch(err){ catch(err){
callback(err,null); done();
callback(err,null);
} }
} }
...@@ -112,19 +116,9 @@ module.exports = function(agentVersion) { ...@@ -112,19 +116,9 @@ module.exports = function(agentVersion) {
//Access the correct view //Access the correct view
//Group entries that was considered executed and count the total uses //Group entries that was considered executed and count the total uses
if(req.query['executed'] != null) table+="ByStatus"; if(req.query['executed'] != null) table+="bystatus";
q = qb.select_between(table,parameters); q = qb.select_between(table,parameters);
if(req.query['fk_agent']){
q = qb.filter_query(q,{"fk_agent": parseInt(req.query['fk_agent'])});
}
break; break;
case 'Agent': case 'Agent':
...@@ -134,50 +128,53 @@ module.exports = function(agentVersion) { ...@@ -134,50 +128,53 @@ module.exports = function(agentVersion) {
q = qb.select(table,parameters); q = qb.select(table,parameters);
break; break;
} }
if(req.query['id']){
q = qb.filter_query(q,{"id": parseInt(req.query['id'])});
}
} }
catch(err){ catch(err){
console.log(err); console.log(err);
return res.status(500).json({error: 'Invalid fields'}); return res.status(500).json({error: 'Invalid fields'});
} }
querie_db(req, q, function(err, data) {
if (err || !data) {
querie_db(req, q, function(err, data) { req.log.error(err);
if (err) { return res.status(500).json({error: 'db_connection_failed'});
req.log.error(err); }
return res.status(500).json({error: 'db_connection_failed'});
}
// Create two class of uses in json: sus and not_sus // Create two class of uses in json: sus and not_sus
if(table in tables_uses){ if(table in tables_uses){
data.rows = data.rows.sort(function(a,b){ data.rows = data.rows.sort(function(a,b){
return new Date(a.date) - new Date(b.date); return new Date(a.date) - new Date(b.date);
}); });
var sus = data.rows.filter(function(x){ var sus = data.rows.filter(function(x){
return x.is_sus; return x.is_sus;
}); });
var not_sus = data.rows.filter(function(x){ var not_sus = data.rows.filter(function(x){
return !x.is_sus; return !x.is_sus;
}); });
return res.status(200).json( return res.status(200).json(
{ {
"sus": sus, "sus": sus,
"not_sus": not_sus "not_sus": not_sus
} }
); );
} }
else{ else{
return res.status(200).json(data.rows); return res.status(200).json(data.rows);
} }
}); });
}
}
}; };
} }
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment