aws_lambda_ric 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: cf1124bbf50d67d952fa22fcd35345899f5f8051e4c3d2be9ba87f0cc701cabb
4
+ data.tar.gz: e32410af6693b00bb5ed60e6f7c1ff99d7dec53d4484982c18c338920ed401ce
5
+ SHA512:
6
+ metadata.gz: '005869f4ece8cdd2a5c93e771d377c8d4107121f0916259ecdf62bd57d5e4bc695dabad4f7695d70155c22bce0d5f13ec0be9db396f7dad86c8d364595d4d81c'
7
+ data.tar.gz: fa08b30481f6ead00ab458515b8f4eef8ce8c4190432f879408329031383bb190cde4dcc7bd8691709d1220c98d80ff98d7561d984822b075f040ee2fb74982d
data/Gemfile ADDED
@@ -0,0 +1,10 @@
1
+ # Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+
3
+ # frozen_string_literal: true
4
+
5
+ source 'https://rubygems.org'
6
+
7
+ git_source(:github) { |repo_name| "https://github.com/#{repo_name}" }
8
+
9
+ # Specify your gem's dependencies in aws_lambda_ric.gemspec
10
+ gemspec
@@ -0,0 +1,22 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ aws_lambda_ric (1.0.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ minitest (5.14.2)
10
+ rake (10.5.0)
11
+
12
+ PLATFORMS
13
+ ruby
14
+
15
+ DEPENDENCIES
16
+ aws_lambda_ric!
17
+ bundler (>= 2.0)
18
+ minitest (~> 5.0)
19
+ rake (~> 10.0)
20
+
21
+ BUNDLED WITH
22
+ 2.2.0.rc.2
data/LICENSE ADDED
@@ -0,0 +1,229 @@
1
+ Apache License
2
+
3
+ Version 2.0, January 2004
4
+
5
+ http://www.apache.org/licenses/ TERMS
6
+ AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+
11
+
12
+
13
+ "License" shall mean the terms and conditions for use, reproduction, and
14
+ distribution as defined by Sections 1 through 9 of this document.
15
+
16
+
17
+
18
+
19
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright
20
+ owner that is granting the License.
21
+
22
+
23
+
24
+ "Legal Entity" shall mean the
25
+ union of the acting entity and all other entities that control, are controlled
26
+ by, or are under common control with that entity. For the purposes of this
27
+ definition, "control" means (i) the power, direct or indirect, to cause the
28
+ direction or management of such entity, whether by contract or otherwise, or (ii)
29
+ ownership of fifty percent (50%) or more of the outstanding shares, or (iii)
30
+ beneficial ownership of such entity.
31
+
32
+
33
+
34
+ "You" (or "Your") shall mean
35
+ an individual or Legal Entity exercising permissions granted by this License.
36
+
37
+
38
+
39
+
40
+ "Source" form shall mean the preferred form for making modifications,
41
+ including but not limited to software source code, documentation source, and
42
+ configuration files.
43
+
44
+
45
+
46
+ "Object" form shall mean any form resulting
47
+ from mechanical transformation or translation of a Source form, including but not
48
+ limited to compiled object code, generated documentation, and conversions to
49
+ other media types.
50
+
51
+
52
+
53
+ "Work" shall mean the work of authorship,
54
+ whether in Source or Object form, made available under the License, as indicated
55
+ by a copyright notice that is included in or attached to the work (an example is
56
+ provided in the Appendix below).
57
+
58
+
59
+
60
+ "Derivative Works" shall mean any
61
+ work, whether in Source or Object form, that is based on (or derived from) the
62
+ Work and for which the editorial revisions, annotations, elaborations, or other
63
+ modifications represent, as a whole, an original work of authorship. For the
64
+ purposes of this License, Derivative Works shall not include works that remain
65
+ separable from, or merely link (or bind by name) to the interfaces of, the Work
66
+ and Derivative Works thereof.
67
+
68
+
69
+
70
+ "Contribution" shall mean any work
71
+ of authorship, including the original version of the Work and any modifications
72
+ or additions to that Work or Derivative Works thereof, that is intentionally
73
+ submitted to Licensor for inclusion in the Work by the copyright owner or by an
74
+ individual or Legal Entity authorized to submit on behalf of the copyright owner.
75
+ For the purposes of this definition, "submitted" means any form of electronic,
76
+ verbal, or written communication sent to the Licensor or its representatives,
77
+ including but not limited to communication on electronic mailing lists, source
78
+ code control systems, and issue tracking systems that are managed by, or on
79
+ behalf of, the Licensor for the purpose of discussing and improving the Work, but
80
+ excluding communication that is conspicuously marked or otherwise designated in
81
+ writing by the copyright owner as "Not a Contribution."
82
+
83
+
84
+
85
+
86
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of
87
+ whom a Contribution has been received by Licensor and subsequently incorporated
88
+ within the Work.
89
+
90
+ 2. Grant of Copyright License. Subject to the terms and
91
+ conditions of this License, each Contributor hereby grants to You a perpetual,
92
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license
93
+ to reproduce, prepare Derivative Works of, publicly display, publicly perform,
94
+ sublicense, and distribute the Work and such Derivative Works in Source or Object
95
+ form.
96
+
97
+ 3. Grant of Patent License. Subject to the terms and conditions of this
98
+ License, each Contributor hereby grants to You a perpetual, worldwide,
99
+ non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this
100
+ section) patent license to make, have made, use, offer to sell, sell, import, and
101
+ otherwise transfer the Work, where such license applies only to those patent
102
+ claims licensable by such Contributor that are necessarily infringed by their
103
+ Contribution(s) alone or by combination of their Contribution(s) with the Work to
104
+ which such Contribution(s) was submitted. If You institute patent litigation
105
+ against any entity (including a cross-claim or counterclaim in a lawsuit)
106
+ alleging that the Work or a Contribution incorporated within the Work constitutes
107
+ direct or contributory patent infringement, then any patent licenses granted to
108
+ You under this License for that Work shall terminate as of the date such
109
+ litigation is filed.
110
+
111
+ 4. Redistribution. You may reproduce and distribute
112
+ copies of the Work or Derivative Works thereof in any medium, with or without
113
+ modifications, and in Source or Object form, provided that You meet the following
114
+ conditions:
115
+
116
+ (a) You must give any other recipients of the Work or
117
+ Derivative Works a copy of this License; and
118
+
119
+ (b) You must cause any
120
+ modified files to carry prominent notices stating that You changed the files;
121
+ and
122
+
123
+ (c) You must retain, in the Source form of any Derivative Works that
124
+ You distribute, all copyright, patent, trademark, and attribution notices from
125
+ the Source form of the Work, excluding those notices that do not pertain to any
126
+ part of the Derivative Works; and
127
+
128
+ (d) If the Work includes a "NOTICE" text
129
+ file as part of its distribution, then any Derivative Works that You distribute
130
+ must include a readable copy of the attribution notices contained within such
131
+ NOTICE file, excluding those notices that do not pertain to any part of the
132
+ Derivative Works, in at least one of the following places: within a NOTICE text
133
+ file distributed as part of the Derivative Works; within the Source form or
134
+ documentation, if provided along with the Derivative Works; or, within a display
135
+ generated by the Derivative Works, if and wherever such third-party notices
136
+ normally appear. The contents of the NOTICE file are for informational purposes
137
+ only and do not modify the License. You may add Your own attribution notices
138
+ within Derivative Works that You distribute, alongside or as an addendum to the
139
+ NOTICE text from the Work, provided that such additional attribution notices
140
+ cannot be construed as modifying the License.
141
+
142
+ You may add Your own
143
+ copyright statement to Your modifications and may provide additional or different
144
+ license terms and conditions for use, reproduction, or distribution of Your
145
+ modifications, or for any such Derivative Works as a whole, provided Your use,
146
+ reproduction, and distribution of the Work otherwise complies with the conditions
147
+ stated in this License.
148
+
149
+ 5. Submission of Contributions. Unless You explicitly
150
+ state otherwise, any Contribution intentionally submitted for inclusion in the
151
+ Work by You to the Licensor shall be under the terms and conditions of this
152
+ License, without any additional terms or conditions. Notwithstanding the above,
153
+ nothing herein shall supersede or modify the terms of any separate license
154
+ agreement you may have executed with Licensor regarding such Contributions.
155
+
156
+
157
+ 6. Trademarks. This License does not grant permission to use the trade names,
158
+ trademarks, service marks, or product names of the Licensor, except as required
159
+ for reasonable and customary use in describing the origin of the Work and
160
+ reproducing the content of the NOTICE file.
161
+
162
+ 7. Disclaimer of Warranty. Unless
163
+ required by applicable law or agreed to in writing, Licensor provides the Work
164
+ (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT
165
+ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including,
166
+ without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT,
167
+ MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible
168
+ for determining the appropriateness of using or redistributing the Work and
169
+ assume any risks associated with Your exercise of permissions under this
170
+ License.
171
+
172
+ 8. Limitation of Liability. In no event and under no legal theory,
173
+ whether in tort (including negligence), contract, or otherwise, unless required
174
+ by applicable law (such as deliberate and grossly negligent acts) or agreed to in
175
+ writing, shall any Contributor be liable to You for damages, including any
176
+ direct, indirect, special, incidental, or consequential damages of any character
177
+ arising as a result of this License or out of the use or inability to use the
178
+ Work (including but not limited to damages for loss of goodwill, work stoppage,
179
+ computer failure or malfunction, or any and all other commercial damages or
180
+ losses), even if such Contributor has been advised of the possibility of such
181
+ damages.
182
+
183
+ 9. Accepting Warranty or Additional Liability. While redistributing
184
+ the Work or Derivative Works thereof, You may choose to offer, and charge a fee
185
+ for, acceptance of support, warranty, indemnity, or other liability obligations
186
+ and/or rights consistent with this License. However, in accepting such
187
+ obligations, You may act only on Your own behalf and on Your sole responsibility,
188
+ not on behalf of any other Contributor, and only if You agree to indemnify,
189
+ defend, and hold each Contributor harmless for any liability incurred by, or
190
+ claims asserted against, such Contributor by reason of your accepting any such
191
+ warranty or additional liability. END OF TERMS AND CONDITIONS
192
+
193
+ APPENDIX: How to
194
+ apply the Apache License to your work.
195
+
196
+ To apply the Apache License to your work,
197
+ attach the following boilerplate notice, with the fields enclosed by brackets
198
+ "[]" replaced with your own identifying information. (Don't include the
199
+ brackets!) The text should be enclosed in the appropriate comment syntax for the
200
+ file format. We also recommend that a file or class name and description of
201
+ purpose be included on the same "printed page" as the copyright notice for easier
202
+ identification within third-party archives.
203
+
204
+ Copyright [yyyy] Edgar
205
+ Hernandez
206
+
207
+ Licensed under the Apache License, Version 2.0 (the "License");
208
+
209
+ you
210
+ may not use this file except in compliance with the License.
211
+
212
+ You may obtain a
213
+ copy of the License at
214
+
215
+ http://www.apache.org/licenses/LICENSE-2.0
216
+
217
+ Unless
218
+ required by applicable law or agreed to in writing, software
219
+
220
+ distributed under
221
+ the License is distributed on an "AS IS" BASIS,
222
+
223
+ WITHOUT WARRANTIES OR CONDITIONS
224
+ OF ANY KIND, either express or implied.
225
+
226
+ See the License for the specific
227
+ language governing permissions and
228
+
229
+ limitations under the License.
data/NOTICE ADDED
@@ -0,0 +1 @@
1
+ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
@@ -0,0 +1,102 @@
1
+ ## AWS Lambda Ruby Runtime Interface Client
2
+
3
+ We have open-sourced a set of software packages, Runtime Interface Clients (RIC), that implement the Lambda
4
+ [Runtime API](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-api.html), allowing you to seamlessly extend your preferred
5
+ base images to be Lambda compatible.
6
+ The Lambda Runtime Interface Client is a lightweight interface that allows your runtime to receive requests from and send requests to the Lambda service.
7
+
8
+ The Lambda Ruby Runtime Interface Client is vended through [rubygems](https://rubygems.org/gems/aws_lambda_ric).
9
+ You can include this package in your preferred base image to make that base image Lambda compatible.
10
+
11
+ ## Requirements
12
+ The Ruby Runtime Interface Client package currently supports Ruby versions:
13
+ - 2.5.x up to and including 2.7.x
14
+
15
+ ## Usage
16
+
17
+ ### Creating a Docker Image for Lambda with the Runtime Interface Client
18
+ First step is to choose the base image to be used. The supported Linux OS distributions are:
19
+
20
+ - Amazon Linux 2
21
+ - Alpine
22
+ - CentOS
23
+ - Debian
24
+ - Ubuntu
25
+
26
+ In order to install the Runtime Interface Client, either add this line to your application's Gemfile:
27
+
28
+ ```ruby
29
+ gem 'aws_lambda_ric'
30
+ ```
31
+
32
+ And then execute:
33
+
34
+ $ bundle
35
+
36
+ Or install it manually as:
37
+
38
+ $ gem install aws_lambda_ric
39
+
40
+
41
+ Next step would be to copy your Lambda function code into the image's working directory.
42
+ ```Docker
43
+ # Create function directory
44
+ RUN mkdir -p ${FUNCTION_DIR}
45
+
46
+ # Copy handler function
47
+ COPY app.rb ${FUNCTION_DIR}/app.rb
48
+
49
+ WORKDIR ${FUNCTION_DIR}
50
+ ```
51
+
52
+ The next step would be to set the `ENTRYPOINT` property of the Docker image to invoke the Runtime Interface Client and then set the `CMD` argument to specify the desired handler.
53
+
54
+ Example Dockerfile:
55
+ ```Docker
56
+ FROM amazonlinux:latest
57
+
58
+ # Define custom function directory
59
+ ARG FUNCTION_DIR="/function"
60
+
61
+ # Install ruby
62
+ RUN amazon-linux-extras install -y ruby2.6
63
+
64
+ # Install the Runtime Interface Client
65
+ RUN gem install aws_lambda_ric
66
+
67
+ # Create function directory
68
+ RUN mkdir -p ${FUNCTION_DIR}
69
+
70
+ # Copy handler function
71
+ COPY app.rb ${FUNCTION_DIR}/app.rb
72
+
73
+ WORKDIR ${FUNCTION_DIR}
74
+
75
+ ENTRYPOINT ["aws_lambda_ric"]
76
+ CMD ["app.App::Handler.process"]
77
+ ```
78
+
79
+ Example Ruby handler `app.rb`:
80
+ ```rb
81
+ module App
82
+ class Handler
83
+ def self.process(event:, context:)
84
+ message = "Hello World!"
85
+ { statusCode: 200, body: { 'message': message } }
86
+ end
87
+ end
88
+ end
89
+ ```
90
+
91
+ ### Local Testing
92
+
93
+ For testing locally you will need to set up a local Runtime Interface Emulator against which the Runtime Interface Client will make API calls. You will need to post data to the endpoint it creates in order to invoke your function. For more information check out the [Runtime Interface Emulator](https://github.com/aws/aws-lambda-runtime-interface-emulator).
94
+
95
+
96
+ ## Security
97
+
98
+ If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue.
99
+
100
+ ## License
101
+
102
+ This project is licensed under the Apache-2.0 License.
@@ -0,0 +1,37 @@
1
+ # Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+
3
+ # frozen_string_literal: true
4
+
5
+ lib = File.expand_path('lib', __dir__)
6
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
7
+ require './lib/aws_lambda_ric/version'
8
+
9
+ Gem::Specification.new do |spec|
10
+ spec.name = 'aws_lambda_ric'
11
+ spec.version = AwsLambdaRuntimeInterfaceClient::VERSION
12
+ spec.authors = ['AWS Lambda']
13
+
14
+ spec.summary = 'AWS Lambda Runtime Interface Client for Ruby'
15
+ spec.description = 'The AWS Lambda Ruby Runtime Interface Client implements the Lambda programming model for Ruby.'
16
+ spec.homepage = 'https://github.com/aws/aws-lambda-ruby-runtime-interface-client'
17
+
18
+ # Specify which files should be added to the gem when it is released.
19
+ spec.files = %w[
20
+ LICENSE
21
+ README.md
22
+ Gemfile
23
+ NOTICE
24
+ Gemfile.lock
25
+ aws_lambda_ric.gemspec
26
+ bin/aws_lambda_ric
27
+ ] + Dir['lib/**/*']
28
+
29
+ spec.bindir = 'bin'
30
+ # all application-style files are expected to be found in bindir
31
+ spec.executables = 'aws_lambda_ric'
32
+ spec.require_paths = ['lib']
33
+
34
+ spec.add_development_dependency 'bundler', '>= 2.0'
35
+ spec.add_development_dependency 'minitest', '~> 5.0'
36
+ spec.add_development_dependency 'rake', '~> 10.0'
37
+ end
@@ -0,0 +1,10 @@
1
+ #! /usr/bin/env ruby
2
+
3
+ # Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
4
+
5
+ # frozen_string_literal: true
6
+
7
+ require 'bundler/setup'
8
+ require_relative '../lib/aws_lambda_ric/bootstrap'
9
+
10
+ Bootstrap.start
@@ -0,0 +1,194 @@
1
+ # Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+
3
+ # frozen_string_literal: true
4
+
5
+ require_relative 'aws_lambda_ric/lambda_errors'
6
+ require_relative 'aws_lambda_ric/lambda_server'
7
+ require_relative 'aws_lambda_ric/lambda_handler'
8
+ require_relative 'aws_lambda_ric/lambda_context'
9
+ require_relative 'aws_lambda_ric/lambda_logger'
10
+ require_relative 'aws_lambda_ric/lambda_log_formatter'
11
+ require_relative 'aws_lambda_ric/telemetry_log_sink'
12
+ require_relative 'aws_lambda_ric/aws_lambda_marshaller'
13
+ require_relative 'aws_lambda_ric/xray_cause'
14
+ require_relative 'aws_lambda_ric/version'
15
+ require 'logger'
16
+
17
+ $stdout.sync = true # Ensures that logs are flushed promptly.
18
+
19
+ module AwsLambdaRuntimeInterfaceClient
20
+
21
+ class Error < StandardError; end
22
+
23
+ # Loads the user code and runs it upon invocation
24
+ class LambdaRunner
25
+
26
+ ENV_VAR_RUNTIME_API = 'AWS_LAMBDA_RUNTIME_API'
27
+
28
+ def initialize(runtime_server_addr)
29
+ @lambda_server = LambdaServer.new(runtime_server_addr)
30
+ @runtime_loop_active = true # if false, we will exit the program
31
+ @exit_code = 0
32
+ end
33
+
34
+ def run(app_root, handler)
35
+
36
+ $LOAD_PATH.unshift(app_root) unless $LOAD_PATH.include?(app_root)
37
+
38
+ begin
39
+ @lambda_handler = LambdaHandler.new(env_handler: handler)
40
+ require @lambda_handler.handler_file_name
41
+ start_runtime_loop
42
+ rescue Exception => e # which includes LoadError or any exception within static user code
43
+ @runtime_loop_active = false
44
+ @exit_code = -4
45
+ send_init_error_to_server(e)
46
+ ensure
47
+ TelemetryLoggingHelper.close
48
+ end
49
+
50
+ exit(@exit_code)
51
+ end
52
+
53
+ private
54
+
55
+ def start_runtime_loop
56
+ while @runtime_loop_active
57
+ lambda_invocation_request = wait_for_invocation
58
+ run_user_code(lambda_invocation_request)
59
+ end
60
+ end
61
+
62
+ def wait_for_invocation
63
+ request_id, raw_request = @lambda_server.next_invocation
64
+ $_global_aws_request_id = request_id
65
+ if (trace_id = raw_request['Lambda-Runtime-Trace-Id'])
66
+ ENV['_X_AMZN_TRACE_ID'] = trace_id
67
+ end
68
+ request = AwsLambda::Marshaller.marshall_request(raw_request)
69
+
70
+ LambdaInvocationRequest.new(request_id, raw_request, request, trace_id)
71
+ rescue LambdaErrors::InvocationError => e
72
+ @runtime_loop_active = false # ends the loop
73
+ raise e # ends the process
74
+ end
75
+
76
+ def run_user_code(lambda_invocation_request)
77
+ context = LambdaContext.new(lambda_invocation_request.raw_request) # pass in opts
78
+
79
+ # start of user code
80
+ handler_response, content_type = @lambda_handler.call_handler(
81
+ request: lambda_invocation_request.request,
82
+ context: context
83
+ )
84
+ # end of user code
85
+
86
+ @lambda_server.send_response(
87
+ request_id: lambda_invocation_request.request_id,
88
+ response_object: handler_response,
89
+ content_type: content_type
90
+ )
91
+
92
+ rescue LambdaErrors::LambdaHandlerError => e
93
+ LambdaLogger.log_error(exception: e, message: 'Error raised from handler method')
94
+ send_error_response(lambda_invocation_request, e)
95
+ rescue LambdaErrors::LambdaHandlerCriticalException => e
96
+ LambdaLogger.log_error(exception: e, message: 'Critical exception from handler')
97
+ send_error_response(lambda_invocation_request, e, -1, false)
98
+ rescue LambdaErrors::LambdaRuntimeError => e
99
+ send_error_response(lambda_invocation_request, e, -2, false)
100
+ end
101
+
102
+ def send_init_error_to_server(err)
103
+ ex = LambdaErrors::LambdaRuntimeInitError.new(err)
104
+ LambdaLogger.log_error(exception: ex, message: "Init error when loading handler #{@env_handler}")
105
+ @lambda_server.send_init_error(error_object: ex.to_lambda_response, error: ex)
106
+ end
107
+
108
+ def send_error_response(lambda_invocation, err, exit_code = nil, runtime_loop_active: true)
109
+ error_object = err.to_lambda_response
110
+ @lambda_server.send_error_response(
111
+ request_id: lambda_invocation.request_id,
112
+ error_object: error_object,
113
+ error: err,
114
+ xray_cause: XRayCause.new(error_object).as_json
115
+ )
116
+
117
+ @exit_code = exit_code unless exit_code.nil?
118
+ @runtime_loop_active = runtime_loop_active
119
+ end
120
+ end
121
+
122
+ # Helper class to for mutating std logger with TelemetryLog
123
+ class TelemetryLoggingHelper
124
+
125
+ ENV_VAR_TELEMETRY_LOG_FD = '_LAMBDA_TELEMETRY_LOG_FD'
126
+
127
+ class << self
128
+ attr_accessor :telemetry_log_fd_file, :telemetry_log_sink
129
+
130
+ def close
131
+ telemetry_log_fd_file&.close
132
+ end
133
+ end
134
+
135
+ def initialize(telemetry_log_fd, path_to_fd='/proc/self/fd/')
136
+ fd = "#{path_to_fd}#{telemetry_log_fd}"
137
+ AwsLambdaRuntimeInterfaceClient::TelemetryLoggingHelper.telemetry_log_fd_file = File.open(fd, 'wb')
138
+ AwsLambdaRuntimeInterfaceClient::TelemetryLoggingHelper.telemetry_log_fd_file.sync = true
139
+
140
+ AwsLambdaRuntimeInterfaceClient::TelemetryLoggingHelper.telemetry_log_sink = TelemetryLogSink.new(file: AwsLambdaRuntimeInterfaceClient::TelemetryLoggingHelper.telemetry_log_fd_file)
141
+
142
+ mutate_std_logger
143
+ mutate_kernel_puts
144
+ rescue Errno::ENOENT
145
+ # If File.open() fails, then the mutation won't happen and the default behaviour (print to stdout) will prevail
146
+ end
147
+
148
+ private
149
+
150
+ def mutate_std_logger
151
+ Logger.class_eval do
152
+ alias_method :orig_initialize, :initialize
153
+ def initialize(logdev, shift_age = 0, shift_size = 1048576, level: 'debug',
154
+ progname: nil, formatter: nil, datetime_format: nil,
155
+ binmode: false, shift_period_suffix: '%Y%m%d')
156
+ # use unpatched constructor if logdev is a filename or an IO Object other than $stdout or $stderr
157
+ if logdev && logdev != $stdout && logdev != $stderr
158
+ orig_initialize(logdev, shift_age, shift_size, level, progname,
159
+ formatter, datetime_format, binmode, shift_period_suffix)
160
+ else
161
+ self.level = level
162
+ self.progname = progname
163
+ @default_formatter = LambdaLogFormatter.new
164
+ self.datetime_format = datetime_format
165
+ self.formatter = formatter
166
+ @logdev = AwsLambdaRuntimeInterfaceClient::TelemetryLoggingHelper.telemetry_log_sink
167
+ end
168
+ end
169
+ end
170
+ end
171
+
172
+ def mutate_kernel_puts
173
+ Kernel.module_eval do
174
+ def puts(*arg)
175
+ msg = arg.flatten.collect { |a| a.to_s.encode('UTF-8') }.join("\n")
176
+ AwsLambdaRuntimeInterfaceClient::TelemetryLoggingHelper.telemetry_log_sink.write(msg)
177
+ end
178
+ end
179
+ end
180
+ end
181
+
182
+ # Represents a single Lambda Invocation Request
183
+ class LambdaInvocationRequest
184
+
185
+ attr_accessor :request_id, :raw_request, :request, :trace_id
186
+
187
+ def initialize(request_id, raw_request, request, trace_id)
188
+ @request_id = request_id
189
+ @raw_request = raw_request
190
+ @request = request
191
+ @trace_id = trace_id
192
+ end
193
+ end
194
+ end
@@ -0,0 +1,35 @@
1
+ # Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+
3
+ # frozen_string_literal: true
4
+
5
+ module AwsLambda
6
+ class Marshaller
7
+ class << self
8
+ # By default, JSON-parses the raw request body. This can be overwritten
9
+ # by users who know what they are doing.
10
+ def marshall_request(raw_request)
11
+ content_type = raw_request['Content-Type']
12
+ if content_type == 'application/json'
13
+ JSON.parse(raw_request.body)
14
+ else
15
+ raw_request.body # return it unaltered
16
+ end
17
+ end
18
+
19
+ # By default, just runs #to_json on the method's response value.
20
+ # This can be overwritten by users who know what they are doing.
21
+ # The response is an array of response, content-type.
22
+ # If returned without a content-type, it is assumed to be application/json
23
+ # Finally, StringIO/IO is used to signal a response that shouldn't be
24
+ # formatted as JSON, and should get a different content-type header.
25
+ def marshall_response(method_response)
26
+ case method_response
27
+ when StringIO, IO
28
+ [method_response, 'application/unknown']
29
+ else
30
+ method_response.to_json # application/json is assumed
31
+ end
32
+ end
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,38 @@
1
+ require_relative '../aws_lambda_ric'
2
+
3
+ # Bootstrap runtime
4
+ module Bootstrap
5
+
6
+ def self.start
7
+ bootstrap_telemetry_log_sink
8
+ bootstrap_handler
9
+ end
10
+
11
+ def self.fetch_runtime_server
12
+ ENV.fetch(AwsLambdaRuntimeInterfaceClient::LambdaRunner::ENV_VAR_RUNTIME_API)
13
+ rescue KeyError
14
+ puts 'Failed to get runtime server address from AWS_LAMBDA_RUNTIME_API env variable'
15
+ exit(-2)
16
+ end
17
+
18
+ def self.bootstrap_telemetry_log_sink(path_to_fd='/proc/self/fd/')
19
+ fd = ENV.fetch(AwsLambdaRuntimeInterfaceClient::TelemetryLoggingHelper::ENV_VAR_TELEMETRY_LOG_FD)
20
+ ENV.delete(AwsLambdaRuntimeInterfaceClient::TelemetryLoggingHelper::ENV_VAR_TELEMETRY_LOG_FD)
21
+ AwsLambdaRuntimeInterfaceClient::TelemetryLoggingHelper.new(fd, path_to_fd)
22
+ rescue KeyError
23
+ puts 'Skipped bootstraping TelemetryLog'
24
+ end
25
+
26
+ def self.bootstrap_handler
27
+ if ARGV.empty?
28
+ puts 'No handler specified, exiting Runtime Interface Client.'
29
+ exit
30
+ end
31
+ app_root = Dir.pwd
32
+ handler = ARGV[0]
33
+ lambda_runner = AwsLambdaRuntimeInterfaceClient::LambdaRunner.new(fetch_runtime_server)
34
+ puts "Executing '#{handler}' in function directory '#{app_root}'"
35
+ lambda_runner.run(app_root, handler)
36
+ end
37
+
38
+ end
@@ -0,0 +1,29 @@
1
+ # Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+
3
+ # frozen_string_literal: true
4
+
5
+ class LambdaContext
6
+ attr_reader :aws_request_id, :invoked_function_arn, :log_group_name,
7
+ :log_stream_name, :function_name, :memory_limit_in_mb, :function_version,
8
+ :identity, :client_context, :deadline_ms
9
+
10
+ def initialize(request)
11
+ @clock_diff = Process.clock_gettime(Process::CLOCK_REALTIME, :millisecond) - Process.clock_gettime(Process::CLOCK_MONOTONIC, :millisecond)
12
+ @deadline_ms = request['Lambda-Runtime-Deadline-Ms'].to_i
13
+ @aws_request_id = request['Lambda-Runtime-Aws-Request-Id']
14
+ @invoked_function_arn = request['Lambda-Runtime-Invoked-Function-Arn']
15
+ @log_group_name = ENV['AWS_LAMBDA_LOG_GROUP_NAME']
16
+ @log_stream_name = ENV['AWS_LAMBDA_LOG_STREAM_NAME']
17
+ @function_name = ENV['AWS_LAMBDA_FUNCTION_NAME']
18
+ @memory_limit_in_mb = ENV['AWS_LAMBDA_FUNCTION_MEMORY_SIZE']
19
+ @function_version = ENV['AWS_LAMBDA_FUNCTION_VERSION']
20
+ @identity = JSON.parse(request['Lambda-Runtime-Cognito-Identity']) if request['Lambda-Runtime-Cognito-Identity']
21
+ @client_context = JSON.parse(request['Lambda-Runtime-Client-Context']) if request['Lambda-Runtime-Client-Context']
22
+ end
23
+
24
+ def get_remaining_time_in_millis
25
+ now = Process.clock_gettime(Process::CLOCK_MONOTONIC, :millisecond) + @clock_diff
26
+ remaining = @deadline_ms - now
27
+ remaining.positive? ? remaining : 0
28
+ end
29
+ end
@@ -0,0 +1,85 @@
1
+ # Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+
3
+ # frozen_string_literal: true
4
+ module LambdaErrors
5
+
6
+ class LambdaErrors::InvocationError < StandardError;
7
+ end
8
+
9
+ class LambdaError < StandardError
10
+ def initialize(original_error, classification = 'Function')
11
+ @error_class = original_error.class.to_s
12
+ @error_type = "#{classification}<#{original_error.class}>"
13
+ @error_message = original_error.message
14
+ @stack_trace = _sanitize_stacktrace(original_error.backtrace_locations)
15
+ super(original_error)
16
+ end
17
+
18
+ def runtime_error_type
19
+ if _allowed_error?
20
+ @error_type
21
+ else
22
+ 'Function<UserException>'
23
+ end
24
+ end
25
+
26
+ def to_lambda_response
27
+ {
28
+ :errorMessage => @error_message,
29
+ :errorType => @error_type,
30
+ :stackTrace => @stack_trace
31
+ }
32
+ end
33
+
34
+ private
35
+
36
+ def _sanitize_stacktrace(stacktrace)
37
+ ret = []
38
+ safe_trace = true
39
+ if stacktrace
40
+ stacktrace.first(100).each do |line|
41
+ if safe_trace
42
+ if line.to_s.match(%r{^lib})
43
+ safe_trace = false
44
+ else
45
+ ret << line
46
+ end
47
+ end # else skip
48
+ end
49
+ end
50
+ ret
51
+ end
52
+
53
+ def _allowed_error?
54
+ # _aws_sdk_pattern? || _standard_error?
55
+ _standard_error?
56
+ end
57
+
58
+ # Currently unused, may be activated later.
59
+ def _aws_sdk_pattern?
60
+ @error_class.match(/Aws(::\w+)*::Errors/)
61
+ end
62
+
63
+ def _standard_error?
64
+ %w[ArgumentError NoMethodError Exception StandardError NameError LoadError SystemExit SystemStackError].include?(@error_class)
65
+ end
66
+ end
67
+
68
+ class LambdaHandlerError < LambdaError
69
+ end
70
+
71
+ class LambdaHandlerCriticalException < LambdaError
72
+ end
73
+
74
+ class LambdaRuntimeError < LambdaError
75
+ def initialize(original_error)
76
+ super(original_error, 'Runtime')
77
+ end
78
+ end
79
+
80
+ class LambdaRuntimeInitError < LambdaError
81
+ def initialize(original_error)
82
+ super(original_error, 'Init')
83
+ end
84
+ end
85
+ end
@@ -0,0 +1,43 @@
1
+ # Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+
3
+ require_relative 'aws_lambda_marshaller'
4
+
5
+ # frozen_string_literal: true
6
+ class LambdaHandler
7
+ attr_reader :handler_file_name, :handler_method_name
8
+
9
+ def initialize(env_handler:)
10
+ handler_split = env_handler.split('.')
11
+ if handler_split.size == 2
12
+ @handler_file_name, @handler_method_name = handler_split
13
+ elsif handler_split.size == 3
14
+ @handler_file_name, @handler_class, @handler_method_name = handler_split
15
+ else
16
+ raise ArgumentError.new("Invalid handler #{handler_split}, must be of form FILENAME.METHOD or FILENAME.CLASS.METHOD where FILENAME corresponds with an existing Ruby source file FILENAME.rb, CLASS is an optional module/class namespace and METHOD is a callable method. If using CLASS, METHOD must be a class-level method.")
17
+ end
18
+ end
19
+
20
+ def call_handler(request:, context:)
21
+ opts = {
22
+ event: request,
23
+ context: context
24
+ }
25
+ if @handler_class
26
+ response = Kernel.const_get(@handler_class).send(@handler_method_name, **opts)
27
+ else
28
+ response = __send__(@handler_method_name, **opts)
29
+ end
30
+ # serialization can be a part of user code
31
+ AwsLambda::Marshaller.marshall_response(response)
32
+ rescue NoMethodError => e
33
+ # This is a special case of standard error that we want to hard-fail for
34
+ raise LambdaErrors::LambdaHandlerCriticalException.new(e)
35
+ rescue NameError => e
36
+ # This is a special case error that we want to wrap
37
+ raise LambdaErrors::LambdaHandlerCriticalException.new(e)
38
+ rescue StandardError => e
39
+ raise LambdaErrors::LambdaHandlerError.new(e)
40
+ rescue Exception => e
41
+ raise LambdaErrors::LambdaHandlerCriticalException.new(e)
42
+ end
43
+ end
@@ -0,0 +1,14 @@
1
+ # Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+
3
+ # frozen_string_literal: true
4
+
5
+ require 'logger'
6
+
7
+ class LambdaLogFormatter < Logger::Formatter
8
+ FORMAT = '%<sev>s, [%<datetime>s#%<process>d] %<severity>5s %<request_id>s -- %<progname>s: %<msg>s'
9
+
10
+ def call(severity, time, progname, msg)
11
+ (FORMAT % {sev: severity[0..0], datetime: format_datetime(time), process: $$, severity: severity,
12
+ request_id: $_global_aws_request_id, progname: progname, msg: msg2str(msg)}).encode!('UTF-8')
13
+ end
14
+ end
@@ -0,0 +1,10 @@
1
+ # Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+
3
+ class LambdaLogger
4
+ class << self
5
+ def log_error(exception:, message: nil)
6
+ puts message if message
7
+ puts JSON.pretty_unparse(exception.to_lambda_response)
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,88 @@
1
+ # Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+
3
+ # frozen_string_literal: true
4
+
5
+ require 'net/http'
6
+ require 'json'
7
+ require_relative 'lambda_errors'
8
+
9
+ class LambdaServer
10
+ LAMBDA_DEFAULT_SERVER_ADDRESS = '127.0.0.1:9001'
11
+ LAMBDA_RUNTIME_API_VERSION = '2018-06-01'
12
+
13
+ MAX_HEADER_SIZE = 1024 * 1024
14
+ LONG_TIMEOUT = 1_000_000
15
+
16
+ def initialize(server_address)
17
+ server_address ||= LAMBDA_DEFAULT_SERVER_ADDRESS
18
+ @server_address = 'http://' + server_address + '/' + LAMBDA_RUNTIME_API_VERSION
19
+ end
20
+
21
+ def next_invocation
22
+ next_invocation_uri = URI(@server_address + '/runtime/invocation/next')
23
+ begin
24
+ http = Net::HTTP.new(next_invocation_uri.host, next_invocation_uri.port)
25
+ http.read_timeout = LONG_TIMEOUT
26
+ resp = http.start do |connection|
27
+ connection.get(next_invocation_uri.path)
28
+ end
29
+ if resp.is_a?(Net::HTTPSuccess)
30
+ request_id = resp['Lambda-Runtime-Aws-Request-Id']
31
+ [request_id, resp]
32
+ else
33
+ raise LambdaErrors::InvocationError.new(
34
+ "Received #{resp.code} when waiting for next invocation."
35
+ )
36
+ end
37
+ rescue LambdaErrors::InvocationError => e
38
+ raise e
39
+ rescue StandardError => e
40
+ raise LambdaErrors::InvocationError.new(e)
41
+ end
42
+ end
43
+
44
+ def send_response(request_id:, response_object:, content_type: 'application/json')
45
+ response_uri = URI(@server_address + "/runtime/invocation/#{request_id}/response")
46
+ begin
47
+ # unpack IO at this point
48
+ if content_type == 'application/unknown'
49
+ response_object = response_object.read
50
+ end
51
+ Net::HTTP.post(
52
+ response_uri,
53
+ response_object,
54
+ { 'Content-Type' => content_type }
55
+ )
56
+ rescue StandardError => e
57
+ raise LambdaErrors::LambdaRuntimeError.new(e)
58
+ end
59
+ end
60
+
61
+ def send_error_response(request_id:, error_object:, error:, xray_cause:)
62
+ response_uri = URI(@server_address + "/runtime/invocation/#{request_id}/error")
63
+ begin
64
+ headers = { 'Lambda-Runtime-Function-Error-Type' => error.runtime_error_type }
65
+ headers['Lambda-Runtime-Function-XRay-Error-Cause'] = xray_cause if xray_cause.bytesize < MAX_HEADER_SIZE
66
+ Net::HTTP.post(
67
+ response_uri,
68
+ error_object.to_json,
69
+ headers
70
+ )
71
+ rescue StandardError => e
72
+ raise LambdaErrors::LambdaRuntimeError.new(e)
73
+ end
74
+ end
75
+
76
+ def send_init_error(error_object:, error:)
77
+ uri = URI("#{@server_address}/runtime/init/error")
78
+ begin
79
+ Net::HTTP.post(
80
+ uri,
81
+ error_object.to_json,
82
+ { 'Lambda-Runtime-Function-Error-Type' => error.runtime_error_type }
83
+ )
84
+ rescue StandardError => e
85
+ raise LambdaErrors::LambdaRuntimeInitError.new(e)
86
+ end
87
+ end
88
+ end
@@ -0,0 +1,43 @@
1
+ # Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+
3
+ # frozen_string_literal: true
4
+
5
+ require 'logger'
6
+
7
+ class TelemetryLogSink < Logger::LogDevice
8
+
9
+ # TelemetryLogSink implements the logging contract between runtimes and the platform. It implements a simple
10
+ # framing protocol so message boundaries can be determined. Each frame can be visualized as follows:
11
+ #
12
+ # +----------------------+------------------------+-----------------------+
13
+ # | Frame Type - 4 bytes | Length (len) - 4 bytes | Message - \'len\' bytes |
14
+ # +----------------------+------------------------+-----------------------+
15
+ #
16
+ # The first 4 bytes indicate the type of the frame - log frames have a type defined as the hex value 0xa55a0001. The
17
+ # second 4 bytes should indicate the message\'s length. The next \'len\' bytes contain the message. The byte order is
18
+ # big-endian.
19
+
20
+ def initialize(file:)
21
+ @file = file
22
+ end
23
+
24
+ FRAME_BYTES = [0xa55a0001].pack('L>')
25
+
26
+ def write(msg)
27
+ if @file.nil? || @file.closed?
28
+ $stdout.write(msg)
29
+ else
30
+ @file.write(FRAME_BYTES)
31
+ @file.write([msg.bytesize].pack('L>'))
32
+ @file.write(msg)
33
+ end
34
+ end
35
+
36
+ def reopen(log = nil)
37
+ # do nothing
38
+ end
39
+
40
+ def close
41
+ # do nothing
42
+ end
43
+ end
@@ -0,0 +1,7 @@
1
+ # Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+
3
+ # frozen_string_literal: true
4
+
5
+ module AwsLambdaRuntimeInterfaceClient
6
+ VERSION = '1.0.0'
7
+ end
@@ -0,0 +1,42 @@
1
+ # Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+
3
+ require_relative 'lambda_errors'
4
+
5
+ class XRayCause
6
+ MAX_DEPTH = 15
7
+
8
+ def initialize(lambda_error)
9
+ @cause = {
10
+ working_directory: Dir.pwd,
11
+ paths: Gem.paths.path,
12
+ exceptions: lambda_error ? normalize(err: lambda_error) : lambda_error
13
+ }
14
+ end
15
+
16
+ def as_json
17
+ @as_json ||= begin
18
+ JSON.dump(@cause)
19
+ end
20
+ end
21
+
22
+ private
23
+
24
+ def normalize(err:)
25
+ exception = {
26
+ message: err[:errorMessage],
27
+ type: err[:errorType]
28
+ }
29
+
30
+ backtrace = err[:stackTrace]
31
+ if backtrace
32
+ exception[:stack] = backtrace.first(MAX_DEPTH).collect do |t|
33
+ {
34
+ path: t.path,
35
+ line: t.lineno,
36
+ label: t.label
37
+ }
38
+ end
39
+ end
40
+ [exception]
41
+ end
42
+ end
metadata ADDED
@@ -0,0 +1,104 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: aws_lambda_ric
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - AWS Lambda
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2020-12-01 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '2.0'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '2.0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: minitest
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '5.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '5.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rake
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '10.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '10.0'
55
+ description: The AWS Lambda Ruby Runtime Interface Client implements the Lambda programming
56
+ model for Ruby.
57
+ email:
58
+ executables:
59
+ - aws_lambda_ric
60
+ extensions: []
61
+ extra_rdoc_files: []
62
+ files:
63
+ - Gemfile
64
+ - Gemfile.lock
65
+ - LICENSE
66
+ - NOTICE
67
+ - README.md
68
+ - aws_lambda_ric.gemspec
69
+ - bin/aws_lambda_ric
70
+ - lib/aws_lambda_ric.rb
71
+ - lib/aws_lambda_ric/aws_lambda_marshaller.rb
72
+ - lib/aws_lambda_ric/bootstrap.rb
73
+ - lib/aws_lambda_ric/lambda_context.rb
74
+ - lib/aws_lambda_ric/lambda_errors.rb
75
+ - lib/aws_lambda_ric/lambda_handler.rb
76
+ - lib/aws_lambda_ric/lambda_log_formatter.rb
77
+ - lib/aws_lambda_ric/lambda_logger.rb
78
+ - lib/aws_lambda_ric/lambda_server.rb
79
+ - lib/aws_lambda_ric/telemetry_log_sink.rb
80
+ - lib/aws_lambda_ric/version.rb
81
+ - lib/aws_lambda_ric/xray_cause.rb
82
+ homepage: https://github.com/aws/aws-lambda-ruby-runtime-interface-client
83
+ licenses: []
84
+ metadata: {}
85
+ post_install_message:
86
+ rdoc_options: []
87
+ require_paths:
88
+ - lib
89
+ required_ruby_version: !ruby/object:Gem::Requirement
90
+ requirements:
91
+ - - ">="
92
+ - !ruby/object:Gem::Version
93
+ version: '0'
94
+ required_rubygems_version: !ruby/object:Gem::Requirement
95
+ requirements:
96
+ - - ">="
97
+ - !ruby/object:Gem::Version
98
+ version: '0'
99
+ requirements: []
100
+ rubygems_version: 3.0.3
101
+ signing_key:
102
+ specification_version: 4
103
+ summary: AWS Lambda Runtime Interface Client for Ruby
104
+ test_files: []