Consume API event-stream

Hi,

I finally solve it using Node.js, below I post the solution.
Packages needed:

  • https
  • agentkeepalive

Code:

const https = require('https');
const Agent = require('agentkeepalive').HttpsAgent;

const keepaliveAgent = new Agent({
  maxSockets: 100,
  maxFreeSockets: 10,
  freeSocketTimeout: 30000, // free socket keepalive for 30 seconds
});

const options = {
  host: 'icinga_server',
  port: 5665,
  auth: 'username:password',
  path: '/v1/events?queue=cr&types=StateChange',
  method: 'POST',
  agent: keepaliveAgent,
  headers: {
        'Accept': 'application/json'
  }
};

makeRequest();

function makeRequest(){
  const req = https.request(options, res => {
    console.log('STATUS: ' + res.statusCode);
    console.log('HEADERS: ' + JSON.stringify(res.headers));
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
      console.log('BODY: ' + chunk);
    });
  });
  req.on('error', e => {
    console.log('problem with request: ' + e.message);
    makeRequest();
  });
  req.end();

  }

setInterval(() => {
  if (keepaliveAgent.statusChanged) {
    if(keepaliveAgent.getCurrentStatus().resetStatus != 0){
            keepaliveAgent.setCurrentStatus();
            makeRequest();
    }
  }
}, 2000);

Custom modifications:
Each time the icinga2 restarts, the connections close the socket and it not reconnects. To handle that I modified the node_modules/agentkeepalive/lib/agent.js and added a new value called resetStatus and a new function setCurrentStatus, so each time the connection closes, the count reset to 0 and call the makeRequest function again.

1 Like