Skip to content

Commit

Permalink
Merge pull request #1 from Goodluckhf/develop
Browse files Browse the repository at this point in the history
Error handling and docs fixes
  • Loading branch information
Goodluckhf authored Jul 26, 2018
2 parents 201914d + 78018ee commit 45c7e22
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 52 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
[![NPM](https://nodei.co/npm/pm2-service-discovery-prom.png?downloads=true&downloadRank=true)](https://nodei.co/npm/pm2-service-discovery-prom/)

This pm2 module will help you to expose product's metrics from pm2 instances.
It will automatically listen for all your commands like:
It will automatically listen to all your commands like:
```bash
$ pm2 scale <pm2_id|name> <number>
$ pm2 stop <pm2_id|name>
Expand All @@ -40,7 +40,7 @@ $ pm2 set pm2-service-discovery:target_base_port <your port>
```
The result port value for each instance will be (`base_port` + `pm2_id`)
For example if you set `target_host = localhost` and `target_base_port = 9300`
And if you have instances with `pm2_id = 1` and `pm2_id = 11` Prometheus will came for metrics to:
And if you have instances with `pm2_id = 1` and `pm2_id = 11` Prometheus will come for metrics to:
* `localhost:9301/metrics`
* `localhost:9311/metrics`

Expand All @@ -61,5 +61,5 @@ Then all you need is add several lines to `prometheus.yml` config and restart pr
scrape_interval: "5s"
consul_sd_configs:
- server: '<pm2 service discovery host>:<pm2_service_discovery_port>'
- services: ['pm2_service_discovery'] # it can should be the same as config value service_name
- services: ['pm2_service_discovery'] # it should be the same as config value service_name
```
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
},
"repository": {
"type": "git",
"url": "git+https://github.com/Goodluckhf/Pm2PrometheusConfGenerator.git"
"url": "git+https://github.com/Goodluckhf/pm2ServiceDiscovery.git"
},
"engines": {
"node": ">=6.10.0"
Expand Down
12 changes: 5 additions & 7 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,6 @@ app.use(morgan('dev'));
app.use(bodyParser.json({ limit: '5mb' }));
const router = express.Router();

//eslint-disable-next-line
router.use((error, req, res, next) => {
logger.error({ error });
res.status(500).send('Internal server error');
});

router.get('/v1/catalog/services', makeServicesRoute(config));
router.get('/v1/catalog/service/:service', makeServiceRoute(config, serviceDiscovery));

Expand All @@ -65,8 +59,12 @@ router.get('/v1/agent/self', (req, res) => {
});
});


app.use('/', router);
//eslint-disable-next-line
app.use((error, req, res, next) => {
logger.error({ error });
res.status(500).send('Internal server error');
});
app.get('*', (req, res) => {
res.status(404).send('Not Found');
});
Expand Down
86 changes: 45 additions & 41 deletions src/routes/service.js
Original file line number Diff line number Diff line change
@@ -1,52 +1,56 @@
export default (config, serviceDiscovery) => {
let oldConfig = null;

return async (req, res) => {
const actualConfig = serviceDiscovery.getActualConfig();

// Если модуль только стартанул,
// надо сразу сгенерировать и отдать конфиг
if (!actualConfig) {
const generatedConfig = await serviceDiscovery.generateConfig();
res.json(generatedConfig.getRawObject());
return;
}

// Если индекса нет
// Значит запроси пришел либо в ручную
// Либо это первый запрос
const { index } = req.query;
if (!index) {
res.json(actualConfig.getRawObject());
return;
}

// Сам long polling
// По таймауту, если конфиг не изменился
// Отдаем текущий актуальный
let responseSent = false;
let interval = null;
const timeout = setTimeout(() => {
clearInterval(interval);
if (responseSent) {
return async (req, res, next) => {
try {
const actualConfig = serviceDiscovery.getActualConfig();

// Если модуль только стартанул,
// надо сразу сгенерировать и отдать конфиг
if (!actualConfig) {
const generatedConfig = await serviceDiscovery.generateConfig();
res.json(generatedConfig.getRawObject());
return;
}

responseSent = true;
res.json(actualConfig.getRawObject());
}, config.polling_interval);

interval = setInterval(() => {
const actualConfigForIteration = serviceDiscovery.getActualConfig();
if (actualConfigForIteration.equals(oldConfig)) {
// Если индекса нет
// Значит запроси пришел либо в ручную
// Либо это первый запрос
const { index } = req.query;
if (!index) {
res.json(actualConfig.getRawObject());
return;
}

clearTimeout(timeout);
clearInterval(interval);
oldConfig = actualConfigForIteration;
const newConfig = serviceDiscovery.getActualConfig();
res.json(newConfig.getRawObject());
}, 1000);
// Сам long polling
// По таймауту, если конфиг не изменился
// Отдаем текущий актуальный
let responseSent = false;
let interval = null;
const timeout = setTimeout(() => {
clearInterval(interval);
if (responseSent) {
return;
}

responseSent = true;
res.json(actualConfig.getRawObject());
}, config.polling_interval);

interval = setInterval(() => {
const actualConfigForIteration = serviceDiscovery.getActualConfig();
if (actualConfigForIteration.equals(oldConfig)) {
return;
}

clearTimeout(timeout);
clearInterval(interval);
oldConfig = actualConfigForIteration;
const newConfig = serviceDiscovery.getActualConfig();
res.json(newConfig.getRawObject());
}, 1000);
} catch (error) {
next(error);
}
};
};

0 comments on commit 45c7e22

Please sign in to comment.