如何调试AWS Api Gateway和Lambda的" AWS/ApiGateway 5XXError"?

30
我有一个API网关资源,运行一个lambda函数。我正在使用来自我的API网关的AWS生成的SDK调用API网关资源。
这是从我的客户端中似乎相关的堆栈跟踪部分:
Caused by: com.amazonaws.mobileconnectors.apigateway.ApiClientException: {"message": "Internal server error"} (Service: DevnetcountableClient; Status Code: 500; Error Code: null; Request ID: 348e8f98-6f55-11e6-97f6-098c2caf220f)
at com.amazonaws.mobileconnectors.apigateway.ApiClientHandler.handleResponse(ApiClientHandler.java:255) at com.amazonaws.mobileconnectors.apigateway.ApiClientHandler.invoke(ApiClientHandler.java:88)
    at java.lang.reflect.Proxy.invoke(Proxy.java:393)
    at $Proxy1.accountCreatePost(Unknown Source)

现在看到AWS控制台,在我的Api Gateway仪表板中,我看到请求进来并导致“AWS/ApiGateway 5XXError”。但是没有日志(我找不到)。我的lambda函数似乎没有被调用,并且没有显示任何lambda日志。

现在我的lambda函数看起来像这样:

module.exports.createAccount = function(event, context, cb) {
    console.log('createAccount');
    console.log(event);
    console.log(context);
    console.log(cb);
    cb(null, {status: 'SUCCESS', message: 'I ran!'});
};

我该怎么调试这个问题?

编辑:好的,下面是将所有内容组合在一起的CloudFormation脚本。

{
   "AWSTemplateFormatVersion":"2010-09-09",
   "Description":"The AWS CloudFormation template for this Serverless application",
   "Resources":{
      "ServerlessDeploymentBucket":{
         "Type":"AWS::S3::Bucket"
      },
      "IamRoleLambda":{
         "Type":"AWS::IAM::Role",
         "Properties":{
            "AssumeRolePolicyDocument":{
               "Version":"2012-10-17",
               "Statement":[
                  {
                     "Effect":"Allow",
                     "Principal":{
                        "Service":[
                           "lambda.amazonaws.com"
                        ]
                     },
                     "Action":[
                        "sts:AssumeRole"
                     ]
                  }
               ]
            },
            "Path":"/"
         }
      },
      "IamPolicyLambda":{
         "Type":"AWS::IAM::Policy",
         "Properties":{
            "PolicyName":"dev-coolsoftware-lambda",
            "PolicyDocument":{
               "Version":"2012-10-17",
               "Statement":[
                  {
                     "Effect":"Allow",
                     "Action":[
                        "logs:CreateLogGroup",
                        "logs:CreateLogStream",
                        "logs:PutLogEvents"
                     ],
                     "Resource":"arn:aws:logs:us-west-2:*:*"
                  }
               ]
            },
            "Roles":[
               {
                  "Ref":"IamRoleLambda"
               }
            ]
         }
      },
      "createAccount":{
         "Type":"AWS::Lambda::Function",
         "Properties":{
            "Code":{
               "S3Bucket":{
                  "Ref":"ServerlessDeploymentBucket"
               },
               "S3Key":"coolsoftware-1472853507538.zip"
            },
            "FunctionName":"coolsoftware-dev-createAccount",
            "Handler":"handler.createAccount",
            "MemorySize":128,
            "Role":{
               "Fn::GetAtt":[
                  "IamRoleLambda",
                  "Arn"
               ]
            },
            "Runtime":"nodejs4.3",
            "Timeout":30
         }
      },
      "RestApiApigEvent":{
         "Type":"AWS::ApiGateway::RestApi",
         "Properties":{
            "Name":"dev-coolsoftware"
         }
      },
      "ResourceApigEventCreateaccountAccount":{
         "Type":"AWS::ApiGateway::Resource",
         "Properties":{
            "ParentId":{
               "Fn::GetAtt":[
                  "RestApiApigEvent",
                  "RootResourceId"
               ]
            },
            "PathPart":"account",
            "RestApiId":{
               "Ref":"RestApiApigEvent"
            }
         }
      },
      "PutMethodApigEventCreateaccountAccount":{
         "Type":"AWS::ApiGateway::Method",
         "Properties":{
            "AuthorizationType":"AWS_IAM",
            "HttpMethod":"PUT",
            "MethodResponses":[
               {
                  "ResponseModels":{
                     "application/json":"AccountCreationResponseModel"
                  },
                  "ResponseParameters":{

                  },
                  "StatusCode":"200"
               }
            ],
            "RequestParameters":{

            },
            "Integration":{
               "IntegrationHttpMethod":"POST",
               "Type":"AWS",
               "Uri":{
                  "Fn::Join":[
                     "",
                     [
                        "arn:aws:apigateway:",
                        {
                           "Ref":"AWS::Region"
                        },
                        ":lambda:path/2015-03-31/functions/",
                        {
                           "Fn::GetAtt":[
                              "createAccount",
                              "Arn"
                           ]
                        },
                        "/invocations"
                     ]
                  ]
               },
               "RequestTemplates":{
                  "application/json":"\n            #define( $loop )\n              {\n              #foreach($key in $map.keySet())\n                  \"$util.escapeJavaScript($key)\":\n                    \"$util.escapeJavaScript($map.get($key))\"\n                    #if( $foreach.hasNext ) , #end\n              #end\n              }\n            #end\n            {\n              \"body\": $input.json(\"$\"),\n              \"method\": \"$context.httpMethod\",\n              \"principalId\": \"$context.authorizer.principalId\",\n              \"stage\": \"$context.stage\",\n\n              #set( $map = $input.params().header )\n              \"headers\": $loop,\n\n              #set( $map = $input.params().querystring )\n              \"query\": $loop,\n\n              #set( $map = $input.params().path )\n              \"path\": $loop,\n\n              #set( $map = $context.identity )\n              \"identity\": $loop,\n\n              #set( $map = $stageVariables )\n              \"stageVariables\": $loop\n            }\n          "
               },
               "IntegrationResponses":[
                  {
                     "StatusCode":"200",
                     "ResponseParameters":{

                     },
                     "ResponseTemplates":{
                        "application/json":""
                     }
                  }
               ]
            },
            "ResourceId":{
               "Ref":"ResourceApigEventCreateaccountAccount"
            },
            "RestApiId":{
               "Ref":"RestApiApigEvent"
            },
            "RequestModels":{
               "application/json":"AccountCreationRequestModel"
            }
         }
      },
      "DeploymentApigEvent1472853508283":{
         "Type":"AWS::ApiGateway::Deployment",
         "Properties":{
            "RestApiId":{
               "Ref":"RestApiApigEvent"
            },
            "StageName":"dev"
         },
         "DependsOn":[
            "PutMethodApigEventCreateaccountAccount"
         ]
      },
      "createAccountApigPermission":{
         "Type":"AWS::Lambda::Permission",
         "Properties":{
            "FunctionName":{
               "Fn::GetAtt":[
                  "createAccount",
                  "Arn"
               ]
            },
            "Action":"lambda:InvokeFunction",
            "Principal":"apigateway.amazonaws.com"
         }
      },
      "DynamoDBTableAccounts":{
         "Type":"AWS::DynamoDB::Table",
         "DeletionPolicy":"Retain",
         "Properties":{
            "TableName":"dev-coolsoftware-accounts",
            "ProvisionedThroughput":{
               "ReadCapacityUnits":1,
               "WriteCapacityUnits":1
            },
            "AttributeDefinitions":[
               {
                  "AttributeName":"accountid",
                  "AttributeType":"S"
               }
            ],
            "KeySchema":[
               {
                  "AttributeName":"accountid",
                  "KeyType":"HASH"
               }
            ]
         }
      },
      "AccountCreationRequestModel":{
         "Type":"AWS::ApiGateway::Model",
         "Properties":{
            "RestApiId":{
               "Ref":"RestApiApigEvent"
            },
            "ContentType":"application/json",
            "Description":"Schema for AccountCreationRequestModel",
            "Name":"AccountCreationRequestModel",
            "Schema":{
               "$schema":"http://json-schema.org/draft-04/schema#",
               "title":"AccountCreationRequestModel",
               "type":"object",
               "properties":{
                  "publickey":{
                     "type":"string"
                  },
                  "deviceid":{
                     "type":"string"
                  }
               }
            }
         }
      },
      "AccountCreationResponseModel":{
         "Type":"AWS::ApiGateway::Model",
         "Properties":{
            "RestApiId":{
               "Ref":"RestApiApigEvent"
            },
            "ContentType":"application/json",
            "Description":"Schema for AccountCreationResponseModel",
            "Name":"AccountCreationResponseModel",
            "Schema":{
               "$schema":"http://json-schema.org/draft-04/schema#",
               "title":"AccountCreationResponseModel",
               "type":"object",
               "properties":{
                  "status":{
                     "type":"string"
                  },
                  "message":{
                     "type":"string"
                  }
               }
            }
         }
      },
      "FailureResponseModel":{
         "Type":"AWS::ApiGateway::Model",
         "Properties":{
            "RestApiId":{
               "Ref":"RestApiApigEvent"
            },
            "ContentType":"application/json",
            "Description":"Schema for FailureResponseModel",
            "Name":"FailureResponseModel",
            "Schema":{
               "$schema":"http://json-schema.org/draft-04/schema#",
               "title":"FailureResponseModel",
               "type":"object",
               "properties":{
                  "status":{
                     "type":"string"
                  },
                  "message":{
                     "type":"string"
                  }
               }
            }
         }
      }
   },
   "Outputs":{
      "ServerlessDeploymentBucketName":{
         "Value":{
            "Ref":"ServerlessDeploymentBucket"
         }
      },
      "Function1Arn":{
         "Description":"Lambda function info",
         "Value":{
            "Fn::GetAtt":[
               "createAccount",
               "Arn"
            ]
         }
      },
      "ServiceEndpoint":{
         "Description":"URL of the service endpoint",
         "Value":{
            "Fn::Join":[
               "",
               [
                  "https://",
                  {
                     "Ref":"RestApiApigEvent"
                  },
                  ".execute-api.us-west-2.amazonaws.com/dev"
               ]
            ]
         }
      }
   }
}

编辑2:当我在AWS控制台中使用API Gateway的测试功能测试端点时,一切都很顺利:/

编辑3:再次更新了CloudFormation脚本-仍然无法正常工作。


1
我因为缺少集成而遇到了这些错误。但是如果没有看到您如何创建网关/lambda,很难弄清楚。 - Rhythmic Fistman
嗯,可能是这个问题。我使用Serverless框架生成了它,但我试图通过CloudFormation脚本包括请求/响应模型、身份验证,并启用“使用调用者凭证调用”。也许这就是导致问题的原因。Serverless框架通过CloudFormation完成所有操作。我会查看模板。谢谢。 - CamHart
@RhythmicFistman,我已经添加了我的CloudFormation脚本,你介意看一下吗? - CamHart
3个回答

30

如何进行调试:

  1. 创建一个IAM角色,允许API Gateway将日志推送到CloudWatch。该角色必须附加以下策略:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:DescribeLogGroups",
                "logs:DescribeLogStreams",
                "logs:PutLogEvents",
                "logs:GetLogEvents",
                "logs:FilterLogEvents"
            ],
            "Resource": "*"
        }
    ]
}

使用以下信任策略:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Service": "apigateway.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
  1. 在API Gateway控制台中,前往设置 >>> 输入API Gateway-CloudWatch日志角色的ARN >>> 点击“保存”

  2. 进入您的API阶段。在“CloudWatch设置”下,选择“启用CloudWatch日志记录”。将“日志级别”设置为“INFO”。选择“记录完整请求/响应数据”。

enabling cloudwatch logs

  1. 重新部署到该阶段:进入API的“资源”选项卡。选择操作 >>> 部署API。

  2. 发出请求,等待几分钟,查看日志(在CloudWatch中)。

错误:

The error

原因:

启用“以调用者身份验证”后,使用Credentials: 'arn:aws:iam::*:user/*',调用者的IAM角色没有权限调用Lambda函数,导致500错误。给予调用者的IAM角色访问权限后,一切正常工作。


5
现在有一个管理策略可供使用,而不是创建自己的策略。它被称为 AmazonAPIGatewayPushToCloudWatchLogs - Lane Rettig
你能否提供更多关于如何解决500错误的细节,特别是调用者IAM角色访问权限内部的内容?谢谢。 - matteoh
我想知道在我的代码运行在AWS Api网关的同时,如何在本地机器上触发断点?这是可能的吗? - ATHER

1
API网关日志显示什么?它是否显示“Lambda函数权限无效”?我认为您需要在CloudFormation模板中包含权限创建(资源)。这是我的其中一个示例:
"PERMISSIONGET": {
        "Type": "AWS::Lambda::Permission",
        "Properties": {
            "FunctionName": "createCabinet",
            "Action": "lambda:InvokeFunction",
            "Principal": "apigateway.amazonaws.com",
            "SourceArn": {
                "Fn::Join": [
                    "",
                    [
                        "arn:aws:execute-api:us-east-1:87875636623:",
                        {
                            "Ref": "APIGATEWAY"
                        },
                        "/*/GET/*"
                    ]
                ]
            }
        },
        "DependsOn": "APIDEPLOYMENT"
    }

我已经解决了这个问题(请参见下面的答案)。这是因为调用者凭据需要权限来调用 Lambda 函数,因为在 API 网关中我启用了“使用调用者凭据调用”的选项。 - CamHart

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接