-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathcli.py
More file actions
302 lines (284 loc) · 9.87 KB
/
Copy pathcli.py
File metadata and controls
302 lines (284 loc) · 9.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
"""
CLI command for "local start-api" command
"""
import logging
from ssl import SSLError
import click
from samcli.cli.cli_config_file import ConfigProvider, configuration_option, save_params_option
from samcli.cli.main import aws_creds_options, pass_context, print_cmdline_args
from samcli.cli.main import common_options as cli_framework_options
from samcli.commands._utils.click_mutex import ClickMutex
from samcli.commands._utils.option_value_processor import process_image_options
from samcli.commands._utils.options import (
generate_next_command_recommendation,
hook_name_click_option,
skip_prepare_infra_option,
terraform_plan_file_option,
)
from samcli.commands.local.cli_common.options import (
invoke_common_options,
local_common_options,
service_common_options,
warm_containers_common_options,
)
from samcli.commands.local.lib.exceptions import InvalidIntermediateImageError
from samcli.commands.local.start_api.core.command import InvokeAPICommand
from samcli.lib.telemetry.metric import track_command
from samcli.lib.utils.version_checker import check_newer_version
from samcli.local.docker.exceptions import ContainerNotStartableException, PortAlreadyInUse, ProcessSigTermException
LOG = logging.getLogger(__name__)
HELP_TEXT = """
Run & test AWS serverless functions locally as a HTTP API.
"""
DESCRIPTION = """
Allows one to run their Serverless application locally for quick development & testing.
When run in a directory that contains Serverless functions and an AWS SAM template, it will create a local HTTP
server hosting all of template's functions. When accessed (via browser, cli etc), it will launch a Docker container
locally to invoke the function.
It will read the CodeUri property of AWS::Serverless::Function resource to find the path in the file system
containing the Lambda Function code. This could be the project's root directory for interpreted
languages like Node & Python, or a build directory that stores your compiled artifacts or a JAR file. If one uses
a interpreted language, local changes will be available immediately in Docker container on every invoke. For more
compiled languages or projects requiring complex packing support, it is recommended to run custom building solution
and point AWS SAM CLI to the directory or file containing build artifacts.
For testing multi-tenant functions, pass tenant-id via X-Amz-Tenant-Id header. By default, each request uses a new
container providing tenant isolation. When using --warm-containers, containers are reused and do not
provide tenant isolation like production Lambda.
"""
@click.command(
"start-api",
cls=InvokeAPICommand,
help=HELP_TEXT,
short_help=HELP_TEXT,
description=DESCRIPTION,
requires_credentials=False,
context_settings={"max_content_width": 120},
)
@configuration_option(provider=ConfigProvider(section="parameters"))
@terraform_plan_file_option
@hook_name_click_option(
force_prepare=False, invalid_coexist_options=["t", "template-file", "template", "parameter-overrides"]
)
@skip_prepare_infra_option
@service_common_options(3000)
@click.option(
"--static-dir",
"-s",
default="public",
help="Any static assets (e.g. CSS/Javascript/HTML) files located in this directory " "will be presented at /",
)
@click.option(
"--disable-authorizer",
is_flag=True,
default=False,
help="Disable custom Lambda Authorizers from being parsed and invoked.",
)
@click.option(
"--ssl-cert-file",
default=None,
type=click.Path(exists=True),
cls=ClickMutex,
required_param_lists=[["ssl_key_file"]],
help="Path to SSL certificate file (default: None)",
)
@click.option(
"--ssl-key-file",
default=None,
type=click.Path(exists=True),
cls=ClickMutex,
required_param_lists=[["ssl_cert_file"]],
help="Path to SSL key file (default: None)",
)
@invoke_common_options
@warm_containers_common_options
@local_common_options
@cli_framework_options
@aws_creds_options # pylint: disable=R0914
@save_params_option
@pass_context
@track_command
@check_newer_version
@print_cmdline_args
def cli(
ctx,
# start-api Specific Options
host,
port,
static_dir,
disable_authorizer,
# Common Options for Lambda Invoke
template_file,
env_vars,
debug_port,
debug_args,
debugger_path,
container_env_vars,
docker_volume_basedir,
docker_network,
log_file,
layer_cache_basedir,
skip_pull_image,
force_image_build,
parameter_overrides,
save_params,
config_file,
config_env,
warm_containers,
shutdown,
debug_function,
container_host,
container_host_interface,
add_host,
invoke_image,
hook_name,
skip_prepare_infra,
terraform_plan_file,
ssl_cert_file,
ssl_key_file,
no_memory_limit,
):
"""
`sam local start-api` command entry point
"""
# All logic must be implemented in the ``do_cli`` method. This helps with easy unit testing
do_cli(
ctx,
host,
port,
disable_authorizer,
static_dir,
template_file,
env_vars,
debug_port,
debug_args,
debugger_path,
container_env_vars,
docker_volume_basedir,
docker_network,
log_file,
layer_cache_basedir,
skip_pull_image,
force_image_build,
parameter_overrides,
warm_containers,
shutdown,
debug_function,
container_host,
container_host_interface,
add_host,
invoke_image,
hook_name,
ssl_cert_file,
ssl_key_file,
no_memory_limit,
) # pragma: no cover
def do_cli( # pylint: disable=R0914
ctx,
host,
port,
disable_authorizer,
static_dir,
template,
env_vars,
debug_port,
debug_args,
debugger_path,
container_env_vars,
docker_volume_basedir,
docker_network,
log_file,
layer_cache_basedir,
skip_pull_image,
force_image_build,
parameter_overrides,
warm_containers,
shutdown,
debug_function,
container_host,
container_host_interface,
add_host,
invoke_image,
hook_name,
ssl_cert_file,
ssl_key_file,
no_mem_limit,
):
"""
Implementation of the ``cli`` method, just separated out for unit testing purposes
"""
from samcli.commands.exceptions import UserException
from samcli.commands.local.cli_common.invoke_context import InvokeContext
from samcli.commands.local.lib.exceptions import NoApisDefined, OverridesNotWellDefinedError
from samcli.commands.local.lib.local_api_service import LocalApiService
from samcli.commands.validate.lib.exceptions import InvalidSamDocumentException
from samcli.lib.providers.exceptions import InvalidLayerReference
from samcli.local.docker.lambda_debug_settings import DebuggingNotSupported
LOG.debug("local start-api command is called")
processed_invoke_images = process_image_options(invoke_image)
# Pass all inputs to setup necessary context to invoke function locally.
# Handler exception raised by the processor for invalid args and print errors
try:
with InvokeContext(
template_file=template,
function_identifier=None, # Don't scope to one particular function
env_vars_file=env_vars,
docker_volume_basedir=docker_volume_basedir,
docker_network=docker_network,
log_file=log_file,
skip_pull_image=skip_pull_image,
debug_ports=debug_port,
debug_args=debug_args,
debugger_path=debugger_path,
container_env_vars_file=container_env_vars,
parameter_overrides=parameter_overrides,
layer_cache_basedir=layer_cache_basedir,
force_image_build=force_image_build,
aws_region=ctx.region,
aws_profile=ctx.profile,
warm_container_initialization_mode=warm_containers,
debug_function=debug_function,
shutdown=shutdown,
container_host=container_host,
container_host_interface=container_host_interface,
invoke_images=processed_invoke_images,
add_host=add_host,
no_mem_limit=no_mem_limit,
) as invoke_context:
ssl_context = (ssl_cert_file, ssl_key_file) if ssl_cert_file else None
service = LocalApiService(
lambda_invoke_context=invoke_context,
port=port,
host=host,
static_dir=static_dir,
disable_authorizer=disable_authorizer,
ssl_context=ssl_context,
)
service.start()
if not hook_name:
command_suggestions = generate_next_command_recommendation(
[
("Validate SAM template", "sam validate"),
("Test Function in the Cloud", "sam sync --stack-name {{stack-name}} --watch"),
("Deploy", "sam deploy --guided"),
]
)
click.secho(command_suggestions, fg="yellow")
except SSLError as ex:
raise UserException(f"SSL Error: {ex.strerror}", wrapped_from=ex.__class__.__name__) from ex
except NoApisDefined as ex:
raise UserException(
"Template does not have any APIs connected to Lambda functions", wrapped_from=ex.__class__.__name__
) from ex
except (
InvalidSamDocumentException,
OverridesNotWellDefinedError,
InvalidLayerReference,
InvalidIntermediateImageError,
DebuggingNotSupported,
PortAlreadyInUse,
) as ex:
raise UserException(str(ex), wrapped_from=ex.__class__.__name__) from ex
except ContainerNotStartableException as ex:
raise UserException(str(ex), wrapped_from=ex.__class__.__name__) from ex
except ProcessSigTermException:
LOG.debug("Successfully exited SIGTERM terminated process")