Repository URL to install this package:
|
Version:
0.7.0 ▾
|
// (c) Copyright 2023 Supertenant Ltd. - all rights reserved.
// See LICENSE file in project root for license terms.
"use strict";const atMostOnce=require("@supertenant/core").util["atMostOnce"],exec=require("child_process")["exec"],http=require("@supertenant/core").uninstrumentedHttp["http"],agentOpts=require("../agent/opts"),EXPECTED_SERVER_HEADER="Instana Agent";let logger;logger=require("../logger").getLogger("announceCycle/agentHostLookup",newLogger=>{logger=newLogger});const retryTimeoutMillis=6e4;function enter(ctx){const agentHost=agentOpts.host;checkHost(agentHost,function(localhostCheckErr){localhostCheckErr?(logger.debug("%s:%s is not running the agent. Trying default gateway...",agentHost,agentOpts.port,{error:localhostCheckErr}),getDefaultGateway(function(getDefaultGatewayErr,defaultGateway){getDefaultGatewayErr?(logger.debug("Error while trying to determine default gateway.",{error:getDefaultGatewayErr}),logger.warn("Agent cannot be contacted via %s:%s and default gateway cannot be determined. Scheduling reattempt of agent host lookup in %s millis.",agentHost,agentOpts.port,retryTimeoutMillis),setTimeout(enter,retryTimeoutMillis,ctx).unref()):checkHost(defaultGateway,function(defaultGatewayCheckErr){defaultGatewayCheckErr?(logger.debug("Failed to contact agent via default gateway %s",defaultGateway,{error:defaultGatewayCheckErr}),logger.warn("Agent cannot be contacted via %s:%s nor via default gateway %s:%s. Scheduling reattempt of agent host lookup in %s millis.",agentHost,agentOpts.port,defaultGateway,agentOpts.port,retryTimeoutMillis),setTimeout(enter,retryTimeoutMillis,ctx).unref()):(setAgentHost(defaultGateway),ctx.transitionTo("unannounced"))})})):(setAgentHost(agentHost),ctx.transitionTo("unannounced"))})}function getDefaultGateway(cb){exec("/sbin/ip route | awk '/default/ { print $3 }'",(error,stdout,stderr)=>{null!==error||0<stderr.length?cb(new Error("Failed to retrieve default gateway: "+stderr)):cb(null,stdout.trim())})}function checkHost(host,cb){cb=atMostOnce("callback for checkHost: "+host,cb);let req;try{req=http.request({host:host,port:agentOpts.port,path:"/",agent:http.agent,method:"GET"},res=>{res.headers.server===EXPECTED_SERVER_HEADER?cb(null):cb(new Error(`Host ${host}:${agentOpts.port} did not respond with expected agent header. Got: `+res.headers.server)),res.resume()})}catch(e){return void cb(new Error("Host lookup failed due to: "+e.message))}req.setTimeout(5e3,function(){cb(new Error("Host check timed out"))}),req.on("error",err=>{cb(new Error("Host check failed: "+err.message))}),req.end()}function setAgentHost(host){logger.info("Attempting agent communication via %s:%s",host,agentOpts.port),agentOpts.host=host}module.exports={enter:enter,leave:function(){}};