'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.AgentMetrics = undefined;

var _promise = require('babel-runtime/core-js/promise');

var _promise2 = _interopRequireDefault(_promise);

var _stringify = require('babel-runtime/core-js/json/stringify');

var _stringify2 = _interopRequireDefault(_stringify);

var _keys = require('babel-runtime/core-js/object/keys');

var _keys2 = _interopRequireDefault(_keys);

var _regenerator = require('babel-runtime/regenerator');

var _regenerator2 = _interopRequireDefault(_regenerator);

var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');

var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require('babel-runtime/helpers/createClass');

var _createClass3 = _interopRequireDefault(_createClass2);

require('source-map-support/register');

var _expressSse = require('express-sse');

var _expressSse2 = _interopRequireDefault(_expressSse);

var _awsSdk = require('aws-sdk');

var _awsSdk2 = _interopRequireDefault(_awsSdk);

var _AgentLogger = require('./AgentLogger');

var _AgentLogger2 = _interopRequireDefault(_AgentLogger);

var _formatJson = require('format-json');

var _formatJson2 = _interopRequireDefault(_formatJson);

var _dynamodbStream = require('dynamodb-stream');

var _dynamodbStream2 = _interopRequireDefault(_dynamodbStream);

var _elasticsearch = require('elasticsearch');

var _elasticsearch2 = _interopRequireDefault(_elasticsearch);

var _tempusFugit = require('tempus-fugit');

var _AgentUtils = require('./AgentUtils');

var _requestPromiseNative = require('request-promise-native');

var _requestPromiseNative2 = _interopRequireDefault(_requestPromiseNative);

var _package = require('../../../package.json');

var _proxyAgent = require('proxy-agent');

var _proxyAgent2 = _interopRequireDefault(_proxyAgent);

var _os = require('os');

var _os2 = _interopRequireDefault(_os);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var agentGroup = process.env.GTM_AGENT_GROUP || 'default';

_awsSdk2.default.config.update({ region: process.env.GTM_AWS_REGION });

var log = _AgentLogger2.default.log();
var EVENTS_TABLE = process.env.GTM_DYNAMO_TABLE_EVENTS;
var AGENTS_TABLE = process.env.GTM_DYNAMO_TABLE_AGENTS;
var INITIAL_DATA = [];
INITIAL_DATA[EVENTS_TABLE] = [];
INITIAL_DATA[AGENTS_TABLE] = [];

var elastic = void 0;
if (process.env.GTM_ELASTIC_HOST && process.env.GTM_ELASTIC_PORT) {
    elastic = new _elasticsearch2.default.Client({
        host: process.env.GTM_ELASTIC_HOST + ':' + process.env.GTM_ELASTIC_PORT,
        log: 'info'
    });
}

if (process.env.IAM_ENABLED) {
    _awsSdk2.default.config.update({
        httpOptions: {
            agent: (0, _proxyAgent2.default)(process.env.HTTP_PROXY)
        }
    });
}

var sns = new _awsSdk2.default.SNS({ apiVersion: '2010-03-31' });

var AgentMetrics = exports.AgentMetrics = function () {
    function AgentMetrics() {
        (0, _classCallCheck3.default)(this, AgentMetrics);
    }

    (0, _createClass3.default)(AgentMetrics, null, [{
        key: 'configureRoutes',
        value: function () {
            var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee7(app) {
                var _this = this;

                var ddb;
                return _regenerator2.default.wrap(function _callee7$(_context7) {
                    while (1) {
                        switch (_context7.prev = _context7.next) {
                            case 0:
                                ddb = _AgentUtils.AgentUtils.getDynamoDB();
                                _context7.next = 3;
                                return this.bridgeStreams(app, ddb, EVENTS_TABLE, '/metrics/stream');

                            case 3:
                                _context7.next = 5;
                                return this.bridgeStreams(app, ddb, AGENTS_TABLE, '/metrics/agents/stream');

                            case 5:

                                app.get('/metrics', function (req, res) {
                                    res.render('metrics.html');
                                });

                                app.get('/metrics/log/gtm-:ghEventId.txt', function () {
                                    var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(req, res) {
                                        var ghEventId, logs;
                                        return _regenerator2.default.wrap(function _callee$(_context) {
                                            while (1) {
                                                switch (_context.prev = _context.next) {
                                                    case 0:
                                                        if (elastic) {
                                                            _context.next = 4;
                                                            break;
                                                        }

                                                        res.write('elasticsearch is not configured');
                                                        res.end();
                                                        return _context.abrupt('return');

                                                    case 4:
                                                        ghEventId = req.params.ghEventId;
                                                        _context.next = 7;
                                                        return _this.getEventLogs(ghEventId);

                                                    case 7:
                                                        logs = _context.sent;


                                                        logs.forEach(function (log) {
                                                            res.write(log._source['@timestamp'] + ' ' + log._source.message + ' \n');
                                                        });

                                                        res.end();

                                                    case 10:
                                                    case 'end':
                                                        return _context.stop();
                                                }
                                            }
                                        }, _callee, _this);
                                    }));

                                    return function (_x2, _x3) {
                                        return _ref2.apply(this, arguments);
                                    };
                                }());

                                app.get('/metrics/log/gtm-:ghEventId.json', function () {
                                    var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(req, res) {
                                        var ghEventId, logs;
                                        return _regenerator2.default.wrap(function _callee2$(_context2) {
                                            while (1) {
                                                switch (_context2.prev = _context2.next) {
                                                    case 0:
                                                        if (elastic) {
                                                            _context2.next = 4;
                                                            break;
                                                        }

                                                        res.json({ error: 'elasticsearch is not configured' });
                                                        res.end();
                                                        return _context2.abrupt('return');

                                                    case 4:
                                                        ghEventId = req.params.ghEventId;
                                                        _context2.next = 7;
                                                        return _this.getEventLogs(ghEventId);

                                                    case 7:
                                                        logs = _context2.sent;

                                                        res.json(logs);

                                                    case 9:
                                                    case 'end':
                                                        return _context2.stop();
                                                }
                                            }
                                        }, _callee2, _this);
                                    }));

                                    return function (_x4, _x5) {
                                        return _ref3.apply(this, arguments);
                                    };
                                }());

                                app.get('/metrics/health', function () {
                                    var _ref4 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(req, res) {
                                        var includeDetail, result;
                                        return _regenerator2.default.wrap(function _callee3$(_context3) {
                                            while (1) {
                                                switch (_context3.prev = _context3.next) {
                                                    case 0:
                                                        includeDetail = false;
                                                        _context3.next = 3;
                                                        return _this.getHealth(ddb, includeDetail);

                                                    case 3:
                                                        result = _context3.sent;

                                                        res.json(result);
                                                        res.end();

                                                    case 6:
                                                    case 'end':
                                                        return _context3.stop();
                                                }
                                            }
                                        }, _callee3, _this);
                                    }));

                                    return function (_x6, _x7) {
                                        return _ref4.apply(this, arguments);
                                    };
                                }());

                                app.get('/metrics/health/detail', function () {
                                    var _ref5 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee4(req, res) {
                                        var includeDetail, result;
                                        return _regenerator2.default.wrap(function _callee4$(_context4) {
                                            while (1) {
                                                switch (_context4.prev = _context4.next) {
                                                    case 0:
                                                        includeDetail = true;
                                                        _context4.next = 3;
                                                        return _this.getHealth(ddb, includeDetail);

                                                    case 3:
                                                        result = _context4.sent;

                                                        res.json(result);
                                                        res.end();

                                                    case 6:
                                                    case 'end':
                                                        return _context4.stop();
                                                }
                                            }
                                        }, _callee4, _this);
                                    }));

                                    return function (_x8, _x9) {
                                        return _ref5.apply(this, arguments);
                                    };
                                }());

                                app.get('/metrics/agent/kill/:agentId', function () {
                                    var _ref6 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee5(req, res) {
                                        var agentId, result;
                                        return _regenerator2.default.wrap(function _callee5$(_context5) {
                                            while (1) {
                                                switch (_context5.prev = _context5.next) {
                                                    case 0:
                                                        agentId = req.params.agentId;

                                                        log.info('sending kill code for agent: ' + agentId);
                                                        _context5.next = 4;
                                                        return _this.broadcastKill(agentId);

                                                    case 4:
                                                        result = _context5.sent;

                                                        res.json(result);
                                                        res.end();

                                                    case 7:
                                                    case 'end':
                                                        return _context5.stop();
                                                }
                                            }
                                        }, _callee5, _this);
                                    }));

                                    return function (_x10, _x11) {
                                        return _ref6.apply(this, arguments);
                                    };
                                }());

                                app.get('/metrics/agent/info/:agentId', function () {
                                    var _ref7 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee6(req, res) {
                                        var agentId, result;
                                        return _regenerator2.default.wrap(function _callee6$(_context6) {
                                            while (1) {
                                                switch (_context6.prev = _context6.next) {
                                                    case 0:
                                                        agentId = req.params.agentId || '*';

                                                        log.info('sending info request to all agents');
                                                        _context6.next = 4;
                                                        return _this.broadcastInfoRequest(agentId);

                                                    case 4:
                                                        result = _context6.sent;

                                                        res.json(result);
                                                        res.end();

                                                    case 7:
                                                    case 'end':
                                                        return _context6.stop();
                                                }
                                            }
                                        }, _callee6, _this);
                                    }));

                                    return function (_x12, _x13) {
                                        return _ref7.apply(this, arguments);
                                    };
                                }());

                            case 12:
                            case 'end':
                                return _context7.stop();
                        }
                    }
                }, _callee7, this);
            }));

            function configureRoutes(_x) {
                return _ref.apply(this, arguments);
            }

            return configureRoutes;
        }()
    }, {
        key: 'bridgeStreams',
        value: function () {
            var _ref8 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee9(app, ddb, tableName, uri) {
                var _this2 = this;

                var ddbStream;
                return _regenerator2.default.wrap(function _callee9$(_context9) {
                    while (1) {
                        switch (_context9.prev = _context9.next) {
                            case 0:
                                _context9.next = 2;
                                return this.getDDBStream(ddb, tableName);

                            case 2:
                                ddbStream = _context9.sent;


                                // fetch stream state initially
                                ddbStream.fetchStreamState(function () {
                                    var _ref9 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee8(err) {
                                        var ddbDocClient, data, sseStream;
                                        return _regenerator2.default.wrap(function _callee8$(_context8) {
                                            while (1) {
                                                switch (_context8.prev = _context8.next) {
                                                    case 0:
                                                        if (!err) {
                                                            _context8.next = 3;
                                                            break;
                                                        }

                                                        log.error(err);
                                                        return _context8.abrupt('return');

                                                    case 3:
                                                        ddbDocClient = new _awsSdk2.default.DynamoDB.DocumentClient({
                                                            convertEmptyValues: true,
                                                            service: ddb
                                                        });

                                                        // fetch initial data

                                                        _context8.next = 6;
                                                        return ddbDocClient.scan({ TableName: tableName }).promise();

                                                    case 6:
                                                        data = _context8.sent;

                                                        INITIAL_DATA[tableName] = data.Items;
                                                        log.debug('Initial data for ' + tableName + ': ' + _formatJson2.default.plain(INITIAL_DATA[tableName]));

                                                        // poll
                                                        (0, _tempusFugit.schedule)({ second: 10 }, function (job) {
                                                            ddbStream.fetchStreamState(job.callback());
                                                        });

                                                        sseStream = new _expressSse2.default(INITIAL_DATA[tableName]);

                                                        app.get(uri, sseStream.init);

                                                        ddbStream.on('insert record', function (object) {
                                                            log.debug('inserted ' + _formatJson2.default.plain(object));
                                                            INITIAL_DATA[tableName].push(object);
                                                            sseStream.updateInit(INITIAL_DATA[tableName]);
                                                            sseStream.send(object);
                                                        });

                                                        ddbStream.on('modify record', function (object) {
                                                            log.debug('updated ' + _formatJson2.default.plain(object));
                                                            INITIAL_DATA[tableName].push(object);
                                                            sseStream.updateInit(INITIAL_DATA[tableName]);
                                                            sseStream.send(object);
                                                        });

                                                    case 14:
                                                    case 'end':
                                                        return _context8.stop();
                                                }
                                            }
                                        }, _callee8, _this2);
                                    }));

                                    return function (_x18) {
                                        return _ref9.apply(this, arguments);
                                    };
                                }());

                            case 4:
                            case 'end':
                                return _context9.stop();
                        }
                    }
                }, _callee9, this);
            }));

            function bridgeStreams(_x14, _x15, _x16, _x17) {
                return _ref8.apply(this, arguments);
            }

            return bridgeStreams;
        }()
    }, {
        key: 'getDDBStream',
        value: function () {
            var _ref10 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee10(ddb, tableName) {
                var tableDetails, tableStreamArn, ddbStream;
                return _regenerator2.default.wrap(function _callee10$(_context10) {
                    while (1) {
                        switch (_context10.prev = _context10.next) {
                            case 0:
                                _context10.next = 2;
                                return ddb.describeTable({ TableName: tableName }).promise();

                            case 2:
                                tableDetails = _context10.sent;

                                log.debug(_formatJson2.default.plain(tableDetails));
                                tableStreamArn = tableDetails.Table.LatestStreamArn;
                                ddbStream = new _dynamodbStream2.default(new _awsSdk2.default.DynamoDBStreams(), tableStreamArn);

                                ddbStream.on('error', function (err) {
                                    log.error(err);
                                });

                                ddbStream.on('end', function () {
                                    log.info('stream closed');
                                });
                                return _context10.abrupt('return', ddbStream);

                            case 9:
                            case 'end':
                                return _context10.stop();
                        }
                    }
                }, _callee10, this);
            }));

            function getDDBStream(_x19, _x20) {
                return _ref10.apply(this, arguments);
            }

            return getDDBStream;
        }()
    }, {
        key: 'getEventLogs',
        value: function () {
            var _ref11 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee11(ghEventId) {
                var results;
                return _regenerator2.default.wrap(function _callee11$(_context11) {
                    while (1) {
                        switch (_context11.prev = _context11.next) {
                            case 0:
                                _context11.next = 2;
                                return elastic.search({
                                    index: 'logstash*',
                                    size: 10000,
                                    body: {
                                        query: {
                                            match: {
                                                ghEventId: ghEventId
                                            }
                                        }
                                    },
                                    sort: '@timestamp:asc'
                                });

                            case 2:
                                results = _context11.sent;
                                return _context11.abrupt('return', results.hits.hits);

                            case 4:
                            case 'end':
                                return _context11.stop();
                        }
                    }
                }, _callee11, this);
            }));

            function getEventLogs(_x21) {
                return _ref11.apply(this, arguments);
            }

            return getEventLogs;
        }()
    }, {
        key: 'getHealth',
        value: function () {
            var _ref12 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee12(ddb, includeDetails) {
                return _regenerator2.default.wrap(function _callee12$(_context12) {
                    while (1) {
                        switch (_context12.prev = _context12.next) {
                            case 0:
                                _context12.next = 2;
                                return this.getAgentInfo(includeDetails);

                            case 2:
                                _context12.t0 = _context12.sent;
                                _context12.next = 5;
                                return this.getProcessInfo(includeDetails);

                            case 5:
                                _context12.t1 = _context12.sent;
                                _context12.next = 8;
                                return this.getElasticInfo(includeDetails);

                            case 8:
                                _context12.t2 = _context12.sent;
                                _context12.next = 11;
                                return this.getDynamoInfo(ddb, includeDetails);

                            case 11:
                                _context12.t3 = _context12.sent;
                                _context12.next = 14;
                                return this.getSQSInfo(includeDetails);

                            case 14:
                                _context12.t4 = _context12.sent;
                                _context12.next = 17;
                                return this.getOSInfo(includeDetails);

                            case 17:
                                _context12.t5 = _context12.sent;
                                return _context12.abrupt('return', {
                                    agent: _context12.t0,
                                    node: _context12.t1,
                                    elastic: _context12.t2,
                                    dynamodb: _context12.t3,
                                    sqs: _context12.t4,
                                    os: _context12.t5
                                });

                            case 19:
                            case 'end':
                                return _context12.stop();
                        }
                    }
                }, _callee12, this);
            }));

            function getHealth(_x22, _x23) {
                return _ref12.apply(this, arguments);
            }

            return getHealth;
        }()
    }, {
        key: 'getOSInfo',
        value: function () {
            var _ref13 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee13(includeDetails) {
                return _regenerator2.default.wrap(function _callee13$(_context13) {
                    while (1) {
                        switch (_context13.prev = _context13.next) {
                            case 0:
                                if (includeDetails) {
                                    _context13.next = 4;
                                    break;
                                }

                                return _context13.abrupt('return', {
                                    hostname: _os2.default.hostname()
                                });

                            case 4:
                                return _context13.abrupt('return', {
                                    hostname: _os2.default.hostname(),
                                    type: _os2.default.type(),
                                    platform: _os2.default.platform(),
                                    arch: _os2.default.arch(),
                                    release: _os2.default.release(),
                                    uptime: _os2.default.uptime(),
                                    loadavg: _os2.default.loadavg(),
                                    totalmem: _os2.default.totalmem(),
                                    freemem: _os2.default.freemem(),
                                    cpus: _os2.default.cpus(),
                                    networkInterfaces: _os2.default.networkInterfaces()
                                });

                            case 5:
                            case 'end':
                                return _context13.stop();
                        }
                    }
                }, _callee13, this);
            }));

            function getOSInfo(_x24) {
                return _ref13.apply(this, arguments);
            }

            return getOSInfo;
        }()
    }, {
        key: 'getAgentInfo',
        value: function () {
            var _ref14 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee14(includeDetails) {
                var result;
                return _regenerator2.default.wrap(function _callee14$(_context14) {
                    while (1) {
                        switch (_context14.prev = _context14.next) {
                            case 0:
                                result = {
                                    id: _AgentUtils.AgentUtils.agentId(),
                                    version: _package.version,
                                    group: agentGroup
                                };

                                if (includeDetails) {
                                    result.env = this.getEnvParams();
                                }
                                return _context14.abrupt('return', result);

                            case 3:
                            case 'end':
                                return _context14.stop();
                        }
                    }
                }, _callee14, this);
            }));

            function getAgentInfo(_x25) {
                return _ref14.apply(this, arguments);
            }

            return getAgentInfo;
        }()
    }, {
        key: 'getElasticInfo',
        value: function () {
            var _ref15 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee15(includeDetails) {
                var result;
                return _regenerator2.default.wrap(function _callee15$(_context15) {
                    while (1) {
                        switch (_context15.prev = _context15.next) {
                            case 0:
                                result = 'not configured';

                                if (!(process.env.GTM_ELASTIC_HOST && process.env.GTM_ELASTIC_PORT)) {
                                    _context15.next = 6;
                                    break;
                                }

                                _context15.next = 4;
                                return (0, _requestPromiseNative2.default)({
                                    json: true,
                                    uri: 'http://' + process.env.GTM_ELASTIC_HOST + ':' + process.env.GTM_ELASTIC_PORT
                                });

                            case 4:
                                result = _context15.sent;

                                if (!includeDetails) {
                                    result = 'found';
                                }

                            case 6:
                                return _context15.abrupt('return', result);

                            case 7:
                            case 'end':
                                return _context15.stop();
                        }
                    }
                }, _callee15, this);
            }));

            function getElasticInfo(_x26) {
                return _ref15.apply(this, arguments);
            }

            return getElasticInfo;
        }()
    }, {
        key: 'getSQSInfo',
        value: function () {
            var _ref16 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee16(includeDetails) {
                var sqsPendingStats, sqsResultsStats;
                return _regenerator2.default.wrap(function _callee16$(_context16) {
                    while (1) {
                        switch (_context16.prev = _context16.next) {
                            case 0:
                                _context16.next = 2;
                                return this.describeQueue(process.env.GTM_SQS_PENDING_QUEUE, ['All'], true);

                            case 2:
                                sqsPendingStats = _context16.sent;
                                _context16.next = 5;
                                return this.describeQueue(process.env.GTM_SQS_RESULTS_QUEUE, ['All'], true);

                            case 5:
                                sqsResultsStats = _context16.sent;

                                if (!includeDetails) {
                                    sqsPendingStats = 'found';
                                    sqsResultsStats = 'found';
                                }
                                return _context16.abrupt('return', {
                                    pending: sqsPendingStats,
                                    results: sqsResultsStats
                                });

                            case 8:
                            case 'end':
                                return _context16.stop();
                        }
                    }
                }, _callee16, this);
            }));

            function getSQSInfo(_x27) {
                return _ref16.apply(this, arguments);
            }

            return getSQSInfo;
        }()
    }, {
        key: 'getDynamoInfo',
        value: function () {
            var _ref17 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee17(ddb, includeDetails) {
                var eventsTableStatus, agentsTableStatus;
                return _regenerator2.default.wrap(function _callee17$(_context17) {
                    while (1) {
                        switch (_context17.prev = _context17.next) {
                            case 0:
                                _context17.next = 2;
                                return ddb.describeTable({ TableName: EVENTS_TABLE }).promise();

                            case 2:
                                eventsTableStatus = _context17.sent;
                                _context17.next = 5;
                                return ddb.describeTable({ TableName: AGENTS_TABLE }).promise();

                            case 5:
                                agentsTableStatus = _context17.sent;


                                if (!includeDetails) {
                                    eventsTableStatus = 'found';
                                    agentsTableStatus = 'found';
                                }

                                return _context17.abrupt('return', {
                                    events: eventsTableStatus,
                                    agents: agentsTableStatus
                                });

                            case 8:
                            case 'end':
                                return _context17.stop();
                        }
                    }
                }, _callee17, this);
            }));

            function getDynamoInfo(_x28, _x29) {
                return _ref17.apply(this, arguments);
            }

            return getDynamoInfo;
        }()
    }, {
        key: 'getProcessInfo',
        value: function getProcessInfo() {
            return {
                version: process.version,
                pid: process.pid,
                uptime: process.uptime(),
                cpuUsage: process.cpuUsage(),
                memoryUsage: process.memoryUsage()
            };
        }
    }, {
        key: 'getEnvParams',
        value: function getEnvParams() {
            var env = {};
            (0, _keys2.default)(process.env).sort().forEach(function (key) {
                if (key.startsWith('GTM')) {
                    env[key] = _AgentUtils.AgentUtils.varMask(key, process.env[key]);
                }
            });
            return env;
        }
    }, {
        key: 'describeQueue',
        value: function () {
            var _ref18 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee18(queueName, attributeNameArray, includeDetails) {
                var sqs, queueUrl, sqsQueueParams, queueDetails, result;
                return _regenerator2.default.wrap(function _callee18$(_context18) {
                    while (1) {
                        switch (_context18.prev = _context18.next) {
                            case 0:
                                sqs = new _awsSdk2.default.SQS();

                                if (includeDetails) {
                                    _context18.next = 3;
                                    break;
                                }

                                return _context18.abrupt('return', 'found');

                            case 3:
                                _context18.next = 5;
                                return sqs.getQueueUrl({ QueueName: queueName }).promise();

                            case 5:
                                queueUrl = _context18.sent;

                                log.debug('sqs queue url ' + queueName + ': ' + _formatJson2.default.plain(queueUrl));
                                if (!attributeNameArray) attributeNameArray = ['All'];
                                sqsQueueParams = {
                                    QueueUrl: queueUrl.QueueUrl,
                                    AttributeNames: attributeNameArray
                                };
                                _context18.next = 11;
                                return sqs.getQueueAttributes(sqsQueueParams).promise();

                            case 11:
                                queueDetails = _context18.sent;
                                result = {};

                                result.name = queueName;
                                result.url = queueUrl.QueueUrl;
                                result.attributes = queueDetails.Attributes;
                                log.debug('sqs queue details: ' + result);
                                return _context18.abrupt('return', result);

                            case 18:
                            case 'end':
                                return _context18.stop();
                        }
                    }
                }, _callee18, this);
            }));

            function describeQueue(_x30, _x31, _x32) {
                return _ref18.apply(this, arguments);
            }

            return describeQueue;
        }()
    }, {
        key: 'broadcast',
        value: function () {
            var _ref19 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee19(message) {
                return _regenerator2.default.wrap(function _callee19$(_context19) {
                    while (1) {
                        switch (_context19.prev = _context19.next) {
                            case 0:
                                return _context19.abrupt('return', sns.createTopic({
                                    Name: process.env.GTM_SNS_AGENTS_TOPIC
                                }).promise().then(function (data) {
                                    var topicArn = data.TopicArn;
                                    var params = {
                                        Message: (0, _stringify2.default)(message),
                                        TopicArn: topicArn
                                    };
                                    return _promise2.default.resolve(params);
                                }).then(function (params) {
                                    return sns.publish(params).promise();
                                }));

                            case 1:
                            case 'end':
                                return _context19.stop();
                        }
                    }
                }, _callee19, this);
            }));

            function broadcast(_x33) {
                return _ref19.apply(this, arguments);
            }

            return broadcast;
        }()
    }, {
        key: 'broadcastKill',
        value: function () {
            var _ref20 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee20(agentId) {
                var msg;
                return _regenerator2.default.wrap(function _callee20$(_context20) {
                    while (1) {
                        switch (_context20.prev = _context20.next) {
                            case 0:
                                msg = {
                                    action: 'KILL',
                                    agentId: agentId
                                };
                                _context20.next = 3;
                                return this.broadcast(msg);

                            case 3:
                                return _context20.abrupt('return', _context20.sent);

                            case 4:
                            case 'end':
                                return _context20.stop();
                        }
                    }
                }, _callee20, this);
            }));

            function broadcastKill(_x34) {
                return _ref20.apply(this, arguments);
            }

            return broadcastKill;
        }()
    }, {
        key: 'broadcastInfoRequest',
        value: function () {
            var _ref21 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee21(agentId) {
                var msg;
                return _regenerator2.default.wrap(function _callee21$(_context21) {
                    while (1) {
                        switch (_context21.prev = _context21.next) {
                            case 0:
                                msg = {
                                    action: 'INFO',
                                    agentId: agentId
                                };
                                _context21.next = 3;
                                return this.broadcast(msg);

                            case 3:
                                return _context21.abrupt('return', _context21.sent);

                            case 4:
                            case 'end':
                                return _context21.stop();
                        }
                    }
                }, _callee21, this);
            }));

            function broadcastInfoRequest(_x35) {
                return _ref21.apply(this, arguments);
            }

            return broadcastInfoRequest;
        }()
    }]);
    return AgentMetrics;
}();