-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathAWSLambda.jl
1016 lines (736 loc) · 26.4 KB
/
AWSLambda.jl
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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#==============================================================================#
# AWSLambda.jl
#
# AWS Lambda API.
#
# See http://docs.aws.amazon.com/lambda/latest/dg/API_Reference.html
#
# Copyright OC Technology Pty Ltd 2014 - All rights reserved
#==============================================================================#
#=
TODO
- Test on windows.
TODO later:
- can bindeps be deployed easily from BinaryBuilder/Linux??
- rename functions to shorter e.g. AWSLambda.create
=#
#FIXME https://github.com/awslabs/serverless-application-model
#FIXME https://github.com/awslabs/aws-sam-local
#FIXME DLQ
#FIXME tagging
#FIXME environment variables
__precompile__()
module AWSLambda
using AWSCore
using AWSIAM
using JSON
using InfoZIP
using Retry
using SymDict
using DataStructures
using Glob
using FNVHash
using Base.Pkg
using HTTP
import HTTP: @require, precondition_error
const jl_version = "JL_$(replace(string(VERSION), ".", "_"))"
const aws_lamabda_jl_version = "0.3.0"
#-------------------------------------------------------------------------------
# AWS Lambda REST API.
#-------------------------------------------------------------------------------
function lambda(aws::AWSConfig, verb; path="", query=[], headers=Dict())
aws = copy(aws)
aws[:ordered_json_dict] = false
resource = HTTP.escapepath("/2015-03-31/functions/$path")
query = @SymDict(headers, query...)
r = AWSCore.Services.lambda(aws, verb, resource, query)
if isa(r, Dict)
r = symboldict(r)
end
return r
end
list_lambdas(aws::AWSConfig) =
[symboldict(f) for f in lambda(aws, "GET")[:Functions]]
list_lambdas() = list_lambdas(default_aws_config())
function lambda_configuration(aws::AWSConfig, name)
@protected try
return lambda(aws, "GET", path="$name/configuration")
catch e
@ignore if ecode(e) == "404" end
end
return nothing
end
lambda_configuration(name) = lambda_configuration(default_aws_config(), name)
function lambda_update_configuration(aws::AWSConfig, name, options)
lambda(aws, "PUT", path="$name/configuration", query=options)
end
lambda_update_configuration(name, options) =
lambda_update_configuration(default_aws_config(), name, options)
lambda_exists(aws::AWSConfig, name) = lambda_configuration(aws, name) != nothing
lambda_exists(name) = lambda_exists(default_aws_config(), name)
function create_lambda(aws::AWSConfig, name;
ZipFile=nothing,
S3Key="$name.zip",
S3Bucket=get(aws, :lambda_bucket, nothing),
Handler="lambda_function.lambda_handler",
Role=role_arn(aws, "jl_lambda_eval_lambda_role"),
Runtime="python2.7",
MemorySize = 1536,
Timeout=300,
args...)
if ZipFile != nothing
ZipFile = base64encode(ZipFile)
Code = @SymDict(ZipFile)
else
Code = @SymDict(S3Key, S3Bucket)
end
query = @SymDict(FunctionName = name,
Code,
Handler,
Role,
Runtime,
MemorySize,
Timeout,
args...)
@repeat 5 try
lambda(aws, "POST", query=query)
catch e
# Retry in case Role was just created and is not yet active...
@delay_retry if ecode(e) == "400" end
end
end
create_lambda(name; kw...) = create_lambda(default_aws_config(), name; kw...)
function update_lambda(aws::AWSConfig, name;
ZipFile=nothing,
S3Key="$name.zip",
S3Bucket=get(aws, :lambda_bucket, nothing),
args...)
if ZipFile != nothing
ZipFile = base64encode(ZipFile)
query = @SymDict(ZipFile)
else
query = @SymDict(S3Key, S3Bucket)
end
lambda(aws, "PUT", path="$name/code", query=query)
if !isempty(args)
lambda(aws, "PUT", path="$name/configuration", query=@SymDict(args...))
end
end
update_lambda(name; kw...) = update_lambda(default_aws_config(), name; kw...)
function lambda_publish_version(aws::AWSConfig, name, alias)
r = lambda(aws, "POST", path="$name/versions")
@protected try
lambda_create_alias(aws, name, alias, FunctionVersion=r[:Version])
catch e
@ignore if ecode(e) == "409"
lambda_update_alias(aws, name, alias, FunctionVersion=r[:Version])
end
end
end
lambda_publish_version(name, alias) =
lambda_publish_version(default_aws_config(), name, alias)
function lambda_create_alias(aws::AWSConfig, name, alias;
FunctionVersion="\$LATEST")
lambda(aws, "POST", path="$name/aliases",
query=@SymDict(FunctionVersion, Name=alias))
end
lambda_create_alias(name, alias; kw...) =
lambda_create_alias(default_aws_config(), name, alias; kw...)
function lambda_update_alias(aws::AWSConfig, name, alias;
FunctionVersion="\$LATEST")
lambda(aws, "PUT", path="$name/aliases/$alias",
query=@SymDict(FunctionVersion))
end
lambda_update_alias(name, alias; kw...) =
lambda_update_alias(default_aws_config(), name, alias; kw...)
function lambda_add_permission(aws::AWSConfig, name, permission)
lambda(aws, "POST", path="$name/policy", query=permission)
end
lambda_add_permission(name, permission) =
lambda_add_permission(default_aws_config(), name, permission)
function lambda_delete_permission(aws::AWSConfig, name, id)
lambda(aws, "DELETE", path="$name/policy/$id")
end
lambda_delete_permission(name, id) =
lambda_delete_permission(default_aws_config(), name, id)
function lambda_delete_permissions(aws::AWSConfig, name)
for p in lambda_get_permissions(aws, name)
lambda_delete_permission(aws, name, p["Sid"])
end
end
lambda_delete_permissions(name) =
lambda_delete_permissions(default_aws_config(), name)
function lambda_get_permissions(aws::AWSConfig, name)
@protected try
r = lambda(aws, "GET", path="$name/policy")
return JSON.parse(r[:Policy])["Statement"]
catch e
@ignore if ecode(e) == "404"
return Dict[]
end
end
end
lambda_get_permissions(name) =
lambda_get_permissions(default_aws_config(), name)
function delete_lambda(aws::AWSConfig, name)
@protected try
lambda(aws, "DELETE", path=name)
catch e
@ignore if ecode(e) == "404" end
end
return
end
delete_lambda(name) = delete_lambda(default_aws_config(), name)
export AWSLambdaException
type AWSLambdaException <: Exception
name::String
message::String
end
function Base.show(io::IO, e::AWSLambdaException)
info = try
JSON.parse(e.message)
catch
Dict("message" => e.message)
end
println(io, string("AWSLambdaException \"", e.name, "\":\n",
info["message"], "\n"))
for (k, v) in info
if k != "message"
println(io, "$k: $v")
end
end
end
function invoke_lambda(aws::AWSConfig, name, args::Dict; async=false)
@protected try
r = lambda(aws, "POST",
path="$name/invocations",
headers=Dict("X-Amz-Invocation-Type" =>
async ? "Event" : "RequestResponse"),
#FIXME async not working?
query=args)
if isa(r, Dict) && haskey(r, :errorMessage)
throw(AWSLambdaException(string(name), r[:errorMessage]))
end
return r
catch e
if ecode(e) == "429"
e.message = e.message *
" See http://docs.aws.amazon.com/lambda/latest/dg/limits.html"
end
end
@assert false # Unreachable
end
invoke_lambda(name, args::Dict; kw...) = invoke_lambda(default_aws_config(),
name, args; kw...)
invoke_lambda(aws::AWSConfig, name; args...) =
invoke_lambda(aws, name, symboldict(args))
invoke_lambda(name; args...) =
invoke_lambda(default_aws_config(), name; args...)
async_lambda(aws::AWSConfig, name, args) =
invoke_lambda(aws, name, args; async=true)
async_lambda(name, args) = async_lambda(default_aws_config(), name, args)
function create_lambda_role(aws::AWSConfig, name, policy="")
name = "$(name)_lambda_role"
@protected try
r = AWSIAM.iam(aws, Action = "CreateRole",
Path = "/",
RoleName = name,
AssumeRolePolicyDocument = """{
"Version": "2012-10-17",
"Statement": [ {
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
} ]
}""")
catch e
@ignore if ecode(e) == "EntityAlreadyExists" end
end
AWSIAM.iam(aws, Action = "AttachRolePolicy",
RoleName = name,
PolicyArn = "arn:aws:iam::aws:policy" *
"/service-role/AWSLambdaBasicExecutionRole")
if policy != ""
AWSIAM.iam(aws, Action = "PutRolePolicy",
RoleName = name,
PolicyName = name,
PolicyDocument = policy)
end
return role_arn(aws, name)
end
#-------------------------------------------------------------------------------
# Python Code Support.
#-------------------------------------------------------------------------------
function create_py_lambda(aws::AWSConfig, name, py_code;
Role = create_lambda_role(aws, name))
options = @SymDict(Role, ZipFile = create_zip("lambda_function.py" => py_code))
old_config = lambda_configuration(aws, name)
if old_config == nothing
create_lambda(aws, name; options...)
else
update_lambda(aws, name; options...)
end
end
create_py_lambda(name, py_code; kw...) =
create_py_lambda(default_aws_config(), name, py_code; kw...)
#-------------------------------------------------------------------------------
# Julia Modules.
#-------------------------------------------------------------------------------
function local_module_cache()
# List of modules in local ".ji" cache.
r = [Symbol(splitext(f)[1]) for f in
[[readdir(p) for p in
filter(isdir, Base.LOAD_CACHE_PATH)]...;]]
# List of modules compiled in to sys image.
append!(r, filter(x->Main.eval(:(try isa($x, Module)
catch ex
if typeof(ex) != UndefVarError
rethrow(ex)
end
false
end)), names(Main)))
return unique(r)
end
function __init__()
global _lambda_module_cache = Symbol[]
end
global _lambda_module_cache = Symbol[]
global default_lambda_module_cache = [
:AWSCore,
:AWSIAM,
:AWSLambda,
:AWSS3,
:Base,
:Compat,
:Core,
:DataStructures,
:FNVHash,
:Glob,
:HTTP,
:InfoZIP,
:IniFile,
:IterTools,
:JSON,
:LightXML,
:Main,
:MbedTLS,
:Nullables,
:Retry,
:SymDict,
:XMLDict]
# List of modules in the Lambda sandbox ".ji" cache.
function lambda_module_cache(aws::AWSConfig = default_aws_config())
global _lambda_module_cache
if isempty(_lambda_module_cache)
@protected try
_lambda_module_cache = lambda_eval(aws, :(filter(x->Main.eval(:(
try
isa($x, Module) && !isfile(string("/tmp/julia/", $x, ".ji"))
catch ex
if typeof(ex) != UndefVarError
rethrow(ex)
end
false
end
)), names(Main))))
catch e
if ecode(e) == "404"
return default_lambda_module_cache
end
end
end
return _lambda_module_cache
end
# List of source files required by "modules".
function precompiled_module_files(aws::AWSConfig, modules::Vector{Symbol})
exclude = lambda_module_cache(aws)
modules = collect(filter(m->!(m in exclude), modules))
return unique([[_precompiled_module_files(i, exclude) for i in modules]...;])
end
function _precompiled_module_files(m, exclude_modules)
# Module must be precompiled...
if !(m in local_module_cache())
error("$m not precompiled. Do \"using $m\".")
end
r = Dict()
for p in Base.find_all_in_cache_path(m)
modules, files = Base.cache_dependencies(p)
for (f,t) in files
r[f] = nothing
end
for (m,t) in modules
if m in exclude_modules
continue
end
for f in _precompiled_module_files(m, exclude_modules)
r[f] = nothing
end
end
end
return collect(keys(r))
end
# Split paths from common prefix...
function path_prefix_split(paths::Vector)
if length(paths) == 0
return "", []
end
# Find longest common prefix...
i = 1
for i = 1:length(paths[1])
if any(f -> length(f) <= i || f[1:i] != paths[1][1:i], paths)
break
end
end
# Ensure prefix is a dir path...
while i > 0 && any(f->!isdirpath(f[1:i]), paths)
i -= 1
end
return paths[1][1:i], [p[i+1:end] for p in paths]
end
# Find load path and source files for "modules"...
function module_files(aws::AWSConfig, modules::Vector{Symbol})
if length(modules) == 0
return [], OrderedDict()
end
pkgd = realpath(Pkg.dir())
# Build a dict of files for each load path location...
d = Dict()
add_file = (p,f) -> (if !haskey(d, p); d[p] = [] end; push!(d[p], f))
for file in precompiled_module_files(aws, modules)
file = realpath(file)
if startswith(file, pkgd)
add_file(pkgd, file[length(pkgd)+2:end])
continue
end
for p in filter(isdir, LOAD_PATH)
p = realpath(abspath(p))
if joinpath(p, basename(file)) == file
add_file(p, basename(file))
break
end
end
end
if isempty(d)
return [], OrderedDict()
end
# Remove common prefix from load path locations...
load_path = collect(Base.Iterators.filter(p->p != pkgd, keys(d)))
prefix, short_load_path = path_prefix_split(load_path)
push!(short_load_path, basename(pkgd))
# Build archive of file content...
archive = OrderedDict()
for (p, s) in zip([load_path...; pkgd],
[short_load_path...; basename(pkgd)])
for f in get(d,p,[])
path = joinpath("julia", s, f)
path = replace(path, "\\", "/")
archive[path] = read(joinpath(p, f))
end
end
return short_load_path, archive
end
#-------------------------------------------------------------------------------
# Julia Code Support.
#-------------------------------------------------------------------------------
# Base64 representation of Julia objects...
function serialize64(x)
buf = IOBuffer()
b64 = Base64EncodePipe(buf)
serialize(b64, x)
close(b64)
String(take!(buf))
end
# Invoke a Julia AWS Lambda function.
# Serialise "args" and deserialise result.
function invoke_jl_lambda(aws::AWSConfig, name::String, args...)
r = invoke_lambda(aws, name, jl_data = serialize64(args))
try
println(r[:stdout])
end
try
return deserialize(Base64DecodePipe(IOBuffer(r[:jl_data])))
end
return r
end
invoke_jl_lambda(name::String, args...) =
invoke_jl_lambda(default_aws_config(), name, args...)
# Returns an anonymous function that calls "func" in the Lambda sandbox.
# e.g. lambda_function(println)("Hello")
# lambda_function(x -> x*x)(4)
# lambda_function(s -> JSON.parse(s))("{}")
lambda_function(aws, f) =
(a...) -> invoke_jl_lambda(aws, "jl_lambda_eval:$jl_version",
eval(Main,:(()->$f($a...))))
lambda_function(f) = lambda_function(default_aws_config(), f)
# Prepend `body` with expression to install `modules` under "/tmp"...
function embed_modules_in_body(aws, body, modules)
load_path, mod_files = module_files(aws, modules)
quote
for (path, code) in $([(k, v) for (k,v) in mod_files])
path = "/tmp/$path"
println("$path, $(length(code)) bytes")
mkpath(dirname(path))
write(path, code)
end
if !("/tmp/julia" in Base.LOAD_CACHE_PATH)
insert!(Base.LOAD_CACHE_PATH, 1, "/tmp/julia")
end
for dir in ["/tmp/julia/$p" for p in $load_path]
if !(dir in Base.LOAD_PATH)
push!(Base.LOAD_PATH, dir)
end
end
for u in $modules
eval(Main, :(using $u))
end
Base.invokelatest(()->$body)
end
end
"""
@lambda [using ...] function name(args...) body end [aws_config]
Define local `function` that executes `body` on AWS Lambda.
"""
macro lambda(args...)
@require 1 <= length(args) <= 3
@require all(x-> x isa Expr, args[1:end-1])
@require args[1].head in (:using, :toplevel, :function)
@require args[1].head != :toplevel || all(x->x.head == :using, args[1].args)
@require args[1].head == :function || length(args) > 1 &&
args[2].head == :function
# Optional last argument is AWSConfig.
if !(args[end] isa Expr) || args[end].head != :function
aws = args[end]
else
aws = :(Main.AWSCore.default_aws_config())
end
if args[1].head == :function
f = args[1]
body = f.args[2]
modules = Symbol[]
else
# Optional first argument is `using Foo, Bar, ...`
f = args[2]
modules = args[1]
if modules.head == :using
modules = Expr(:toplevel, modules)
end
@assert modules.head == :toplevel
modules = [x.args[1] for x in modules.args]
body = f.args[2]
body = embed_modules_in_body(eval(aws), body, modules)
end
# Replace function body with Lambda invocation.
args = f.args[1].args[2:end]
arg_names = [isa(a, Expr) ? a.args[1] : a for a in args]
l = Expr(:quote, Expr(:->, Expr(:tuple, args...), body))
f.args[2] = :(AWSLambda.lambda_function($aws, eval(Main, $l))($(arg_names...)))
return esc(f)
end
# Evaluate "expr" in the Lambda sandbox.
lambda_eval(aws, expr) =
invoke_jl_lambda(aws, "jl_lambda_eval:$jl_version", expr)
lambda_eval(expr) = lambda_eval(default_aws_config(), expr)
macro lambda_eval(expr)
if expr.head == :block
expr = [e for e in expr.args]
else
expr = QuoteNode(expr)
end
:(lambda_eval($expr))
end
# Evaluate "code" in the Lambda sandbox.
lambda_include_string(aws, code) = lambda_function(aws, include_string)(code)
lambda_include_string(code) = lambda_include_string(default_aws_config(), code)
# Evaluate "filename" in the Lambda sandbox.
function lambda_include(aws::AWSConfig, filename)
code = readstring(filename)
lambda_function(aws, include_string)(code, filename)
end
lambda_include(filename) = lambda_include(default_aws_config(), filename)
# For build_sysimg.jl
@static if isdefined(Base, :uv_eventloop)
# Create an AWS Lambda to run "jl_code".
function create_jl_lambda(name, jl_code, modules=Symbol[], options=SymbolDict())
options = Dict{Symbol,Any}(copy(options))
if !haskey(options, :aws)
aws = default_aws_config()
else
aws = options[:aws]
delete!(options, :aws)
end
# Find files and load path for required modules...
load_path, mod_files = module_files(aws, modules)
full_load_path = join([":/var/task/julia/$p" for p in load_path])
py_config = ["os.environ['JULIA_LOAD_PATH'] += '$full_load_path'\n"]
if AWSCore.debug_level > 0
println("create_jl_lambda($name)")
for f in keys(mod_files)
println(" $f")
end
end
# Get env vars from "aws" or "options"...
env = get(options, :env,
get(aws, :lambda_env, Dict()))
options[:env] = env
for (n,v) in env
push!(py_config, "os.environ['$n'] = '$v'\n")
end
# Start with ZipFile from options...
if !haskey(options, :ZipFile)
options[:ZipFile] = UInt8[]
end
if AWSCore.debug_level > 1
@show py_config
end
# Add lambda source and module files to zip...
open_zip(options[:ZipFile]) do z
merge!(z, mod_files)
z["lambda_config.py"] = join(py_config)
z["module_$name.jl"] = jl_code
end
# FNV hash of deployed Julia code is stored in the Description field.
old_config = lambda_configuration(aws, name)
new_code_hash = options[:ZipFile] |> open_zip |> Dict |>
serialize64 |> fnv32 |> hex
old_code_hash = old_config == nothing ? nothing :
get(old_config, :Description, nothing)
# Don't create a new lambda if one already exists with same code...
if new_code_hash == old_code_hash && !get(aws, :lambda_force_update, false)
return
end
options[:Description] = new_code_hash
deploy_lambda(aws, name, load_path, options, old_config == nothing)
end
@lambda using AWSLambda, AWSS3, InfoZIP function deploy_lambda(
aws, name, load_path, options, is_new)
println("Foo")
AWSCore.set_debug_level(1)
# Unzip lambda source and modules files to /tmp...
mktempdir() do tmpdir
for (n, v) in options[:env]
ENV[n] = replace(v, r"^/var/task", tmpdir)
end
if haskey(options, :ZipURL)
InfoZIP.unzip(Requests.get(options[:ZipURL]).data, tmpdir)
end
InfoZIP.unzip(options[:ZipFile], tmpdir)
# Create module precompilation directory under /tmp...
v = "v$(VERSION.major).$(VERSION.minor)"
ji_path = "$tmpdir/julia/lib/$v"
mkpath(ji_path)
# Run precompilation...
cmd = "push!(LOAD_PATH, \"$tmpdir\")\n"
for p in load_path
cmd *= "push!(LOAD_PATH, \"$tmpdir/julia/$p\")\n"
end
cmd *= "insert!(Base.LOAD_CACHE_PATH, 1, \"$ji_path\")\n"
cmd *= "using module_$name\n"
println(cmd)
run(`$JULIA_HOME/julia -e $cmd`)
run(`chmod -R a+r $ji_path`)
# Create new ZIP combining base image and new files from /tmp...
run(`rm -f /tmp/lambda.zip`)
run(Cmd(`zip -q --symlinks -r -9 /tmp/lambda.zip .`,
dir="/var/task"))
run(Cmd(`zip -q --symlinks -r -9 /tmp/lambda.zip .`,
dir=tmpdir))
options[:ZipFile] = read("/tmp/lambda.zip")
run(`rm -f /tmp/lambda.zip`)
end
# Deploy the lambda to AWS...
if is_new
r = AWSLambda.create_lambda(aws, name; options...)
else
r = AWSLambda.update_lambda(aws, name; options...)
end
end
# Create an AWS Lambda function.
#
# e.g.
#
# AWSLambda.@deploy function hello(a, b)
#
# message = "Hello $a$b"
#
# println("Log: $message")
#
# return message
# end aws
#
# hello("World", "!") # FIXME invoke lambda
# Hello World!
#
# @deploy deploys an AWS Lambda that contains the body of the Julia function.
"""
AWSLambda.@deploy [(option=value, ...)] [using ...] function name(args...)
function_body
end
Deploy `function` to AWS Lambda.
"""
macro deploy(options_ex, using_ex, function_ex)
deploy_ex(options_ex, using_ex, function_ex)
end
macro deploy(ex, function_ex)
if ex.head in (:toplevel, :using)
deploy_ex(:(Dict{Symbol,Any}()), ex, function_ex)
else
deploy_ex(ex, Expr(:toplevel), function_ex)
end
end
macro deploy(function_ex)
deploy_ex(:(Dict{Symbol,Any}()), Expr(:toplevel), function_ex)
end
function deploy_ex(options_ex, using_ex, function_ex)
# Wrap single-module using expression with :toplevel
if using_ex.head == :using
using_ex = Expr(:toplevel, using_ex)
end
@require using_ex.head == :toplevel
@require all(x->x.head == :using, using_ex.args)
@require function_ex.head == :function
modules = Symbol[x.args[1] for x in using_ex.args]
# Rewrite function name to be :lambda_function...
call, body = function_ex.args
name = call.args[1]
call.args[1] = :lambda_function
args = function_ex.args[1].args[2:end]
# Generate code to extract args from event Dict...
arg_names = [isa(a, Expr) ? a.args[1] : a for a in args]
get_args = Expr(:tuple, [:(event[$(string(a))]) for a in arg_names]...)
jl_code = """
__precompile__()
module $(Symbol("module_$name"))
$(join(["using $m" for m in modules], "; "))
$function_ex
function lambda_function_with_event(event::Dict{String,Any})
lambda_function$get_args
end
end
"""
:(create_jl_lambda($(string(name)), $jl_code, $modules, $(esc(options_ex))))
end
end # isdefined(Base, :uv_eventloop)
# For build_sysimg.jl
#-------------------------------------------------------------------------------
# Deploy pre-cooked Julia Base Lambda
#-------------------------------------------------------------------------------
function deploy_jl_lambda_eval(aws::AWSConfig = default_aws_config();
bucket = "octech.com.au.$(aws[:region]).awslambda.jl.deploy",
base_zip = "jl_lambda_eval_$(VERSION)_$(aws_lamabda_jl_version).zip")
old_config = lambda_configuration(aws, "jl_lambda_eval")
options = @SymDict(S3Key=base_zip,
S3Bucket=bucket,
Role = create_lambda_role(aws, "jl_lambda_eval"))
if old_config == nothing
create_lambda(aws, "jl_lambda_eval"; options...)