* Starts background task that updates configuration and pushes stats. * * Receives pushed Websocket messages on configuration updates, and * sends stat messages in response to API sollicitations. * * @param {string} url API endpoint * @param {string} token API authentication token * @param {f
(url, token, cb)
| 85 | * @returns {undefined} |
| 86 | */ |
| 87 | function startWSManagementClient(url, token, cb) { |
| 88 | logger.info('connecting to push server', { url }); |
| 89 | function _logError(error, errorMessage, method) { |
| 90 | if (error) { |
| 91 | logger.error(`management client error: ${errorMessage}`, |
| 92 | { error: reshapeExceptionError(error), method }); |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | const socketsByChannelId = []; |
| 97 | const headers = { |
| 98 | 'x-instance-authentication-token': token, |
| 99 | }; |
| 100 | const agent = createWSAgent(url, process.env, logger); |
| 101 | |
| 102 | const ws = new WebSocket(url, subprotocols, { headers, agent }); |
| 103 | let pingTimeout = null; |
| 104 | |
| 105 | function sendPing() { |
| 106 | if (ws.readyState === ws.OPEN) { |
| 107 | ws.ping(err => _logError(err, 'failed to send a ping', 'sendPing')); |
| 108 | } |
| 109 | pingTimeout = setTimeout(() => ws.terminate(), PING_INTERVAL_MS); |
| 110 | } |
| 111 | |
| 112 | function initiatePing() { |
| 113 | clearTimeout(pingTimeout); |
| 114 | setTimeout(sendPing, PING_INTERVAL_MS); |
| 115 | } |
| 116 | |
| 117 | function pushStats(options) { |
| 118 | if (process.env.PUSH_STATS === 'false') { |
| 119 | return; |
| 120 | } |
| 121 | const fromURL = `http://${cloudServerHost}:${cloudServerPort}/_/report`; |
| 122 | const fromOptions = { |
| 123 | json: true, |
| 124 | headers: { |
| 125 | 'x-scal-report-token': process.env.REPORT_TOKEN, |
| 126 | 'x-scal-report-skip-cache': Boolean(options && options.noCache), |
| 127 | }, |
| 128 | }; |
| 129 | request.get(fromURL, fromOptions, (err, response, body) => { |
| 130 | if (err) { |
| 131 | _logError(err, 'failed to get metrics report', 'pushStats'); |
| 132 | return; |
| 133 | } |
| 134 | ws.send(ChannelMessageV0.encodeMetricsReportMessage(body), |
| 135 | err => _logError(err, 'failed to send metrics report message', |
| 136 | 'pushStats')); |
| 137 | }); |
| 138 | } |
| 139 | |
| 140 | function closeChannel(channelId) { |
| 141 | const socket = socketsByChannelId[channelId]; |
| 142 | if (socket) { |
| 143 | socket.destroy(); |
| 144 | delete socketsByChannelId[channelId]; |
no test coverage detected