Repository navigation
Expand file tree
/
Copy pathapi.py
More file actions
516 lines (463 loc) · 18.1 KB
/
Copy pathapi.py
File metadata and controls
516 lines (463 loc) · 18.1 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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
import logging
import os
import textwrap
import time
from braintrust.logger import app_conn, login
from ...util import response_raise_for_status
from ._deprecation import add_deprecated_parser
_logger = logging.getLogger("braintrust.install.api")
PARAMS = {
"OrgName": "org_name",
"ProvisionedConcurrency": "provisioned_concurrency",
"EncryptDatabase": "encrypt_database",
"PostgresAlternativeHost": "postgres_alternative_host",
"APIHandlerMemorySize": "api_handler_memory_size",
"WhitelistedOrigins": "whitelisted_origins",
"PublicSubnet1AZ": "public_subnet_1_az",
"PrivateSubnet1AZ": "private_subnet_1_az",
"PrivateSubnet2AZ": "private_subnet_2_az",
"PrivateSubnet3AZ": "private_subnet_3_az",
"VPCCIDR": "vpc_cidr",
"PublicSubnet1CIDR": "public_subnet_1_cidr",
"PrivateSubnet1CIDR": "private_subnet_1_cidr",
"PrivateSubnet2CIDR": "private_subnet_2_cidr",
"PrivateSubnet3CIDR": "private_subnet_3_cidr",
"ManagedPostgres": "managed_postgres",
"PostgresVersion": "postgres_version",
"OutboundRateLimitWindowMinutes": "outbound_rate_limit_window_minutes",
"OutboundRateLimitMaxRequests": "outbound_rate_limit_max_requests",
"UseGlobalProxy": "use_global_proxy",
"EnableQuarantine": "enable_quarantine",
"EnableBrainstore": "enable_brainstore",
"BrainstoreInstanceKeyPairName": "brainstore_instance_key_pair_name",
"BrainstoreInstanceType": "brainstore_instance_type",
"BrainstoreInstanceCount": "brainstore_instance_count",
"BrainstoreMaxInstanceCount": "brainstore_max_instance_count",
"BrainstoreVersionOverride": "brainstore_version_override",
"BrainstoreLicenseKey": "brainstore_license_key",
}
REMOVED_PARAMS = ["ThirdAZIndex"]
DEFAULTS = {
"PrimaryOrgName": "",
"DwType": "Postgres",
"EncryptDatabase": "false",
"ProvisionedConcurrency": 0,
"APIHandlerMemorySize": 10240,
}
CAPABILITIES = ["CAPABILITY_IAM", "CAPABILITY_AUTO_EXPAND"]
LATEST_TEMPLATE = "https://braintrust-cf.s3.amazonaws.com/braintrust-latest.yaml"
def build_parser(subparsers, parents):
parser = add_deprecated_parser(subparsers, "api", "Install the Braintrust function API", parents, main)
parser.add_argument("name", help="Name of the CloudFormation stack to create or update")
parser.add_argument(
"--create",
help="Create the stack if it does not exist",
action="store_true",
default=False,
)
parser.add_argument(
"--vpc-connect",
help="Connect to an existing VPC",
action="store_true",
default=False,
)
parser.add_argument(
"--template",
help="A specific CloudFormation template URL to use",
default=None,
)
parser.add_argument(
"--update-template",
help="Update the CloudFormation to the latest version of the template",
action="store_true",
default=False,
)
# OrgName, ProvisionedConcurrency
parser.add_argument("--org-name", help="The name of your organization", default=None)
parser.add_argument(
"--provisioned-concurrency",
help="The amount of provisioned concurrency",
default=None,
type=int,
)
parser.add_argument(
"--api-handler-memory-size",
help="The amount of memory to allocate to the API handler",
default=None,
type=int,
)
parser.add_argument(
"--whitelisted-origins",
help="Comma-separated list of origins to whitelist",
default=None,
)
parser.add_argument(
"--public-subnet-1-az",
help="The availability zone for the public subnet",
default=None,
)
parser.add_argument(
"--private-subnet-1-az",
help="The availability zone for private subnet 1",
default=None,
)
parser.add_argument(
"--private-subnet-2-az",
help="The availability zone for private subnet 2",
default=None,
)
parser.add_argument(
"--private-subnet-3-az",
help="The availability zone for private subnet 3",
default=None,
)
parser.add_argument(
"--vpc-cidr",
help="The CIDR for the VPC",
default=None,
)
parser.add_argument(
"--public-subnet-1-cidr",
help="The CIDR for the public subnet",
default=None,
)
parser.add_argument(
"--private-subnet-1-cidr",
help="The CIDR for private subnet 1",
default=None,
)
parser.add_argument(
"--private-subnet-2-cidr",
help="The CIDR for private subnet 2",
default=None,
)
parser.add_argument(
"--private-subnet-3-cidr",
help="The CIDR for private subnet 3",
default=None,
)
# PostgresUrl
parser.add_argument(
"--managed-postgres",
help="Spin up an RDS instance to use as the datastore",
default=None,
choices=[None, "true", "false"],
)
parser.add_argument(
"--encrypt-database",
help="Whether to encrypt the database",
default="false",
choices=[None, "true", "false"],
)
parser.add_argument(
"--postgres-version",
help="The version of the postgres instance",
default=None,
)
parser.add_argument(
"--postgres-alternative-host",
help="Use an external host for postgres (but the same secrets)",
default=None,
)
# ElastiCacheClusterId
parser.add_argument("--elasticache-cluster-host", help="The ElastiCacheCluster host to use", default=None)
parser.add_argument(
"--elasticache-cluster-port", help="The ElastiCacheCluster host to use", default=None, type=int
)
# SecurityGroupId, SubnetIds
parser.add_argument("--security-group-id", help="The security group ID to use", default=None)
parser.add_argument("--subnet-ids", help="The subnet IDs to use", default=None)
# Rate limit configuration.
parser.add_argument(
"--outbound-rate-limit-window-minutes",
help="The time frame in minutes over which rate per-user rate limits are accumulated",
default=None,
type=int,
)
parser.add_argument(
"--outbound-rate-limit-max-requests",
help="The maximum number of requests per user allowed in the time frame specified by OutboundRateLimitMaxRequests. Setting to 0 will disable rate limits",
default=None,
type=int,
)
parser.add_argument(
"--use-global-proxy",
help="Use the global cloudflare proxy (https://braintrustproxy.com)",
default=None,
choices=[None, "true", "false"],
)
parser.add_argument(
"--enable-quarantine",
help="Enable the quarantine feature (running typescript and python functions)",
default=None,
choices=[None, "true", "false"],
)
# Advancd use only
parser.add_argument(
"--postgres-url",
help="[Advanced] The postgres URL to use (if you are connecting to another VPC)",
default=None,
)
# To configure your org
parser.add_argument(
"--api-key",
help="The API key to use to configure your org's API URL and Proxy URL",
default=os.environ.get("BRAINTRUST_API_KEY", None),
)
parser.add_argument(
"--update-stack-url",
help="Update the organization's API URL to match the stack's universal URL",
action="store_true",
default=False,
)
# Brainstore configuration
parser.add_argument(
"--enable-brainstore",
help="Enable Brainstore object-storage data backend",
choices=[None, "true", "false"],
default=None,
)
parser.add_argument(
"--brainstore-license-key",
help="The license key to use for Brainstore",
default=None,
)
parser.add_argument(
"--brainstore-instance-key-pair-name",
help="The EC2 Key Pair to allow SSH access to the Brainstore instance",
default=None,
)
parser.add_argument(
"--brainstore-instance-type",
help="EC2 instance type for Brainstore. Must be a Graviton instance type.",
default=None,
)
parser.add_argument(
"--brainstore-instance-count",
help="Number of Brainstore instances to run",
type=int,
default=None,
)
parser.add_argument(
"--brainstore-max-instance-count",
help="Max scaling size for Brainstore instances",
type=int,
default=None,
)
parser.add_argument(
"--brainstore-version-override",
help="Lock Brainstore to a specific docker tag",
default=None,
)
def main(args):
from botocore.exceptions import ClientError
# pylint: disable-next=no-name-in-module
from ...aws import cloudformation
template = args.template or LATEST_TEMPLATE
status = None
try:
statuses = cloudformation.describe_stacks(StackName=args.name)["Stacks"]
if len(statuses) == 1:
status = statuses[0]
_logger.debug(status)
except ClientError as e:
if "does not exist" not in str(e):
raise
vpc_connect = args.vpc_connect
if status and not vpc_connect:
vpc_connect = "SecurityGroupId" in set(x["ParameterKey"] for x in status["Parameters"])
if vpc_connect:
PARAMS["SecurityGroupId"] = "security_group_id"
PARAMS["SubnetIds"] = "subnet_ids"
PARAMS["ElastiCacheClusterHost"] = "elasticache_cluster_host"
PARAMS["ElastiCacheClusterPort"] = "elasticache_cluster_port"
PARAMS["PostgresUrl"] = "postgres_url"
PARAMS["EnableBrainstore"] = "enable_brainstore"
PARAMS["BrainstoreInstanceKeyPairName"] = "brainstore_instance_key_pair_name"
PARAMS["BrainstoreLicenseKey"] = "brainstore_license_key"
PARAMS["BrainstoreInstanceType"] = "brainstore_instance_type"
PARAMS["BrainstoreInstanceCount"] = "brainstore_instance_count"
PARAMS["BrainstoreMaxInstanceCount"] = "brainstore_max_instance_count"
PARAMS["BrainstoreVersionOverride"] = "brainstore_version_override"
if args.template is None:
template = "https://braintrust-cf.s3.amazonaws.com/braintrust-latest-vpc.yaml"
exists = status is not None
if exists and args.create:
_logger.error(
textwrap.dedent(
f"""\
Stack with name {args.name} already exists. Either delete it in the AWS console or
remove the --create flag."""
)
)
exit(1)
elif not exists and not args.create:
_logger.error(
textwrap.dedent(
f"""\
Stack with name {args.name} does not exist. Either create it manually by following
https://docs.braintrust.dev/admin/self-hosting/deploy or use the --create flag."""
)
)
exit(1)
if not exists:
_logger.info(f"Creating stack with name {args.name}")
params = [
{
"ParameterKey": k,
"ParameterValue": str(v),
}
for (k, v) in [
(param, args.__dict__[arg_name] or DEFAULTS.get(param, None)) for (param, arg_name) in PARAMS.items()
]
if v is not None
]
_logger.info("Using params:")
for param in params:
_logger.info(f" {param['ParameterKey']}: {param['ParameterValue']}")
_logger.info(f"Typical stack creation takes 10-15 minutes.")
cloudformation.create_stack(
StackName=args.name,
TemplateURL=template,
Parameters=params,
Capabilities=CAPABILITIES,
)
for _ in range(80):
status = cloudformation.describe_stacks(StackName=args.name)["Stacks"][0]
if status["StackStatus"] != "CREATE_IN_PROGRESS":
exists = True
break
_logger.info("Waiting for stack to be created...")
time.sleep(15)
else:
_logger.error(
textwrap.dedent(
"""\
Stack creation timed out. Please check the AWS console to see its status. You can also
re-run this command without --create to continue the setup process once it's done."""
)
)
exit(1)
_logger.info(f"Stack with name {args.name} has been created with status: {status['StackStatus']}")
exit(0)
_logger.info(f"Stack with name {args.name} has status: {status['StackStatus']}")
if not ("_COMPLETE" in status["StackStatus"] or "_FAILED" in status["StackStatus"]):
_logger.info(f"Please re-run this command once the stack has finished creating or updating")
exit(0)
# Update params that have changed
param_updates = {}
for param, arg_name in PARAMS.items():
if args.__dict__[arg_name] is not None:
param_updates[param] = args.__dict__[arg_name]
if len(param_updates) > 0 or args.update_template:
template_kwargs = {"TemplateURL": template} if args.update_template else {"UsePreviousTemplate": True}
_logger.info(f"Updating stack with name {args.name} with template: {template_kwargs}")
_logger.info("Using params:")
for param, value in param_updates.items():
_logger.info(f" {param}: {value}")
if args.template:
new_template = cloudformation.get_template_summary(TemplateURL=template)
new_params = set(x["ParameterKey"] for x in new_template["Parameters"])
else:
new_params = set(x["ParameterKey"] for x in status["Parameters"])
stack = cloudformation.describe_stacks(StackName=args.name)["Stacks"][0]
try:
final_params = [
{"ParameterKey": param, "ParameterValue": str(update)}
for (param, update) in param_updates.items()
if param in new_params and param not in REMOVED_PARAMS
] + [
{"ParameterKey": param["ParameterKey"], "UsePreviousValue": True}
for param in stack["Parameters"]
if param["ParameterKey"] not in param_updates
and param["ParameterKey"] not in REMOVED_PARAMS
and param["ParameterKey"] in new_params
]
cloudformation.update_stack(
StackName=args.name,
Parameters=final_params,
Capabilities=CAPABILITIES,
**template_kwargs,
)
except ClientError as e:
if "No updates are to be performed." in str(e):
_logger.warning("No updates are to be performed.")
else:
raise
for _ in range(120):
status = cloudformation.describe_stacks(StackName=args.name)["Stacks"][0]
if status["StackStatus"] != "UPDATE_IN_PROGRESS":
exists = True
break
_logger.info("Waiting for stack to be updated...")
time.sleep(5)
else:
_logger.error(
textwrap.dedent(
"""\
Stack update timed out. Please check the AWS console to see its status. You can also
re-run this command to try again."""
)
)
exit(1)
universal_url = [x for x in status["Outputs"] if x["OutputKey"] == "UniversalURL"]
if universal_url:
universal_url = universal_url[0]["OutputValue"]
else:
universal_url = None
org_name = [x for x in status["Parameters"] if x["ParameterKey"] == "OrgName"]
if org_name:
org_name = org_name[0]["ParameterValue"]
else:
org_name = None
_logger.info(f"Stack with name {args.name} has been updated with status: {status['StackStatus']}")
_logger.info(f"Universal URL: {universal_url}")
org_info = []
if args.api_key:
login(api_key=args.api_key)
resp = app_conn().post("api/apikey/login")
if resp.ok:
org_info = resp.json()["org_info"]
else:
_logger.error(f"Failed to login with API key: {resp.text}")
if len(org_info) > 0:
if org_name != "*":
org_info = [x for x in org_info if x["name"] == org_name]
if len(org_info) == 0:
_logger.error(f"Org with name {org_name} does not exist")
exit(1)
elif len(org_info) > 1:
names = ", ".join([x["name"] for x in org_info])
_logger.error(
f"You belong to multiple orgs: {names}. Please use an API key that's scoped to a single org."
)
org_info = []
if len(org_info) == 1:
org_info = org_info[0]
if org_info and (universal_url and org_info["api_url"] != universal_url):
if args.update_stack_url:
_logger.info(f"Will update org {org_info['name']}'s urls.")
_logger.info(f" They are currently set to:")
_logger.info(f" API URL: {org_info['api_url']}")
_logger.info(f" Proxy URL: {org_info['proxy_url']}")
_logger.info(f"And will update them to:")
patch_args = {"id": org_info["id"]}
if universal_url and org_info["api_url"] != universal_url:
patch_args["api_url"] = universal_url
patch_args["is_universal_api"] = True
_logger.info(f" API URL: {universal_url}")
_logger.warn(
f"\nNOTE: You can delete the proxy URL from your org settings now. It is no longer needed."
)
# Make the actual request
response_raise_for_status(
app_conn().post(
"api/organization/patch_id",
json=patch_args,
)
)
else:
_logger.info(f"Stack URL differs from organization API URL:")
_logger.info(f" Current API URL: {org_info['api_url']}")
_logger.info(f" Stack Universal URL: {universal_url}")
_logger.info(f"To update the organization's API URL, rerun with --update-stack-url flag")