aws / aws-xray-sdk-node

The official AWS X-Ray SDK for Node.js.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Missing AWS Lambda trace data for X-Ray TypeScript

login21 opened this issue · comments

Hi ,

I need support to resolve this issue when I use xray tracing with my serverless lambda function which has an Init() function.

2022-08-12T02:16:10.373Z	undefined	ERROR	Error: Missing AWS Lambda trace data for X-Ray. Ensure Active Tracing is enabled and no subsegments are created outside the function handler.
    at Object.contextMissingLogError [as contextMissing] (/var/task/node_modules/aws-xray-sdk-core/dist/lib/context_utils.js:22:27)
    at Segment.resolveLambdaTraceData (/var/task/node_modules/aws-xray-sdk-core/dist/lib/env/aws_lambda.js:86:49)
    at Object.getSegment (/var/task/node_modules/aws-xray-sdk-core/dist/lib/context_utils.js:92:25)
    at Object.resolveSegment (/var/task/node_modules/aws-xray-sdk-core/dist/lib/context_utils.js:71:25)
    at captureOutgoingHTTPs (/var/task/node_modules/aws-xray-sdk-core/dist/lib/patchers/http_p.js:84:37)
    at Object.captureHTTPsRequest [as request] (/var/task/node_modules/aws-xray-sdk-core/dist/lib/patchers/http_p.js:175:16)
    at RedirectableRequest._performRequest (/var/task/node_modules/follow-redirects/index.js:279:24)
    at new RedirectableRequest (/var/task/node_modules/follow-redirects/index.js:61:8)
    at Object.request (/var/task/node_modules/follow-redirects/index.js:487:14)
    at dispatchHttpRequest (/var/task/node_modules/axios/lib/adapters/http.js:242:25)
	
2022-08-12T02:16:10.340Z	undefined	ERROR	Error: Missing AWS Lambda trace data for X-Ray. Ensure Active Tracing is enabled and no subsegments are created outside the function handler.
    at Object.contextMissingLogError [as contextMissing] (/var/task/node_modules/aws-xray-sdk-core/dist/lib/context_utils.js:22:27)
    at Segment.resolveLambdaTraceData (/var/task/node_modules/aws-xray-sdk-core/dist/lib/env/aws_lambda.js:86:49)
    at Object.getSegment (/var/task/node_modules/aws-xray-sdk-core/dist/lib/context_utils.js:92:25)
    at Object.resolveSegment (/var/task/node_modules/aws-xray-sdk-core/dist/lib/context_utils.js:71:25)
    at captureOutgoingHTTPs (/var/task/node_modules/aws-xray-sdk-core/dist/lib/patchers/http_p.js:84:37)
    at TunnelingAgent.captureHTTPsRequest [as request] (/var/task/node_modules/aws-xray-sdk-core/dist/lib/patchers/http_p.js:175:16)
    at TunnelingAgent.createSocket (/var/task/node_modules/tunnel/lib/tunnel.js:126:25)
    at TunnelingAgent.createSecureSocket [as createSocket] (/var/task/node_modules/tunnel/lib/tunnel.js:207:41)
    at TunnelingAgent.addRequest (/var/task/node_modules/tunnel/lib/tunnel.js:84:8)
    at new ClientRequest (_http_client.js:305:16)
	
2022-08-12T02:16:10.339Z	undefined	ERROR	Error: Missing AWS Lambda trace data for X-Ray. Ensure Active Tracing is enabled and no subsegments are created outside the function handler.
    at Object.contextMissingLogError [as contextMissing] (/var/task/node_modules/aws-xray-sdk-core/dist/lib/context_utils.js:22:27)
    at Segment.resolveLambdaTraceData (/var/task/node_modules/aws-xray-sdk-core/dist/lib/env/aws_lambda.js:86:49)
    at Object.getSegment (/var/task/node_modules/aws-xray-sdk-core/dist/lib/context_utils.js:92:25)
    at Object.resolveSegment (/var/task/node_modules/aws-xray-sdk-core/dist/lib/context_utils.js:71:25)
    at captureOutgoingHTTPs (/var/task/node_modules/aws-xray-sdk-core/dist/lib/patchers/http_p.js:84:37)
    at Object.captureHTTPsRequest [as request] (/var/task/node_modules/aws-xray-sdk-core/dist/lib/patchers/http_p.js:175:16)
    at RedirectableRequest._performRequest (/var/task/node_modules/follow-redirects/index.js:279:24)
    at new RedirectableRequest (/var/task/node_modules/follow-redirects/index.js:61:8)
    at Object.request (/var/task/node_modules/follow-redirects/index.js:487:14)
    at dispatchHttpRequest (/var/task/node_modules/axios/lib/adapters/http.js:242:25)	

app.js file -

import express from 'express';
import * as OpenApiValidator from 'express-openapi-validator';
import multer from 'multer';
import ProxyAgent from 'proxy-agent';
import AWS from 'aws-sdk';
import { productsRouter } from './routes/products.js';
import config from './config/config.js';
import { providerRouter } from './routes/provider.js';
import { apisRouter } from './routes/apis.js';
import { errorHandler } from './middleware/errorHandler.js';
import { initExecutionContext, setExecutionContextLogAttributes } from './middleware/executionContext.js';
import { multipartOpenAPIValidatorAdaptor } from './middleware/multipartOpenAPIValidatorAdaptor.js';
import { multipartFileValidator } from './middleware/multipartFileValidator.js';
import {
  retrieveSsmParameters,
  initialiseTokenVerifier,
  fetchAndCacheJwks,
  fetchAndCacheCsgPublicKey
} from './authorization/authorizationConfig.js';
import { globalsSingleton } from './globals/globals.js';
import { logger } from './utils/logger.js';
import { getCorsOptions } from './utils/cors.js';
import cors from 'cors';
import { Request } from 'express';
import AWSXRay from 'aws-xray-sdk';

const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
AWSXRay.setContextMissingStrategy("LOG_ERROR");
const XRayExpress = AWSXRay.express;

AWS.config.update({
  region: 'ap-southeast-2'
});

logger.info(`Instantiate Express Application`);
const app = express();
logger.info(`Starting Xray tracing`);
app.use(XRayExpress.openSegment('ManagementService'));

const networkProxy = config['NETWORK_PROXY'];
logger.info('networkProxy: ', { data: { networkProxy: networkProxy } });

const globals = globalsSingleton.getInstance();
let publicKey: any;
let idTokenVerifier: any;

const init = async () => {
  logger.info('Init function triggered.');
  await retrieveSsmParameters();
  if (networkProxy) {
    idTokenVerifier = await initialiseTokenVerifier(globals.getAuthorizationConfig()?.PORTAL_CLIENT_ID as string);
    await fetchAndCacheJwks(idTokenVerifier);
  } else {
    logger.error(`authorization configuration could not be setup as no network proxy configured.`);
    throw new Error(`authorization configuration could not be setup as no network proxy configured.`);
  }
  publicKey = await fetchAndCacheCsgPublicKey();
};

await init();
globals.setPublicKey(publicKey);
globals.setTokenVerifier(idTokenVerifier);
logger.info('Init function finished: ', {
  data: {
    publicKey: globals.getPublicKey(),
    idTokenVerifier: globals.getTokenVerifier()
  }
});

const corsOptions = function (req: Request, callback: (err: Error | null, options?: cors.CorsOptions) => void) {
  const requestOrigin = req.header('Origin') || req.header('origin');
  const opts = getCorsOptions(config.CORS_WHITELIST, requestOrigin as string) ; 

  logger.info('options =', opts);
  callback(null, opts);
};
app.use(cors(corsOptions));
app.use(express.urlencoded({ limit: '10mb', extended: true }));
app.use(express.json({ limit: '10mb' }));
app.use(upload.any());
app.use(initExecutionContext);
app.use(setExecutionContextLogAttributes);
app.use(multipartFileValidator);
app.use(multipartOpenAPIValidatorAdaptor);
app.use(
  OpenApiValidator.middleware({
    apiSpec: './api-spec/management-service-api-spec.yml',
    fileUploader: false
  })
);
app.use(`${config.BASE_PATH_V1}/providers`, providerRouter);
app.use(`${config.BASE_PATH_V1}/apis`, apisRouter);
app.use(`${config.BASE_PATH_V1}/products`, productsRouter);
app.use(`${config.BASE_PATH_V1}/test-auth`, testAuthRouter);
app.use(errorHandler);
app.use(XRayExpress.closeSegment());

export { app };

My ssm call code looks like this -

export const getSsmParameters = async (keys: string[]) => {
  logger.debug('SSM client key: ', { data: { key: keys } });
  const params: GetParametersRequest = {
    Names: keys
  };
  try {
    const param = await ssm.getParameters(params).promise();
    return param.Parameters;
  } catch (err) {
    logger.error('SSM client failed retrieving parameters: ', { data: { error: err } });
    throw err;
  }
};

I am using captureAWSClient() function like this

import AWS from 'aws-sdk';
const ssm = AWSXRay.captureAWSClient(new AWS.SSM());

Can anyone please help me fix this issue.

Few point about this issue -

  • Active tracing in enabled in my lambda.
  • Able to see the trace with other services like S3, Lambda, StepFunction etc.
  • Have a init() function in my lambda code where I am calling the above ssm function to get values from parameter store.

There is a portion of the error message that says: Ensure Active Tracing is enabled and no subsegments are created outside the function handler. Are you creating any subsegments outside of this function handler by any chance?

Hi @carolabadeer thank you for your response.

I am not creating any segment or subsegment anywhere.. Its just that I have a init() function to fetch some values from AWS SSM and then to do some other task to get some third party token. While my init() function executes I see these errors. I am not sure if init() function is not getting traced and throwing that error or something else.

I have added full error log and also my app.js file where I have my init() function which throws error.