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
|
# File 'lib/lambda_convert/cli.rb', line 14
def self.lambda_convert
s3_region = ENV['CONVERT_S3_REGION'] || ENV['AWS_REGION']
lambda_region = ENV['CONVERT_LAMBDA_REGION'] || ENV['AWS_REGION']
aws_credentials = Aws::Credentials.new(
ENV['CONVERT_ACCESS_KEY'] || ENV['AWS_ACCESS_KEY_ID'],
ENV['CONVERT_SECRET_ACCESS_KEY'] || ENV['AWS_SECRET_ACCESS_KEY']
)
s3_bucket = ENV['CONVERT_S3_BUCKET']
s3_key_prefix = ENV['CONVERT_S3_KEY_PREFIX'] || '_convert_tmp/'
lambda_function = ENV['CONVERT_LAMBDA_FUNCTION'] || 'image-convert-prod'
s3 = Aws::S3::Client.new(
region: s3_region,
credentials: aws_credentials
)
aws_lambda = Aws::Lambda::Client.new(
region: lambda_region,
credentials: aws_credentials
)
input_file, input_selecting = LambdaConvert::Utils.parse_input_path(
ARGV[0]
)
output_file = ARGV[-1]
input_key = "#{s3_key_prefix}#{SecureRandom.uuid}"
output_key = "#{s3_key_prefix}#{SecureRandom.uuid}"
logger.info("Uploading file to s3://#{s3_bucket}/#{input_key}")
File.open(input_file, 'rb') do |file|
s3.put_object(bucket: s3_bucket, key: input_key, body: file)
end
source = '{source}'
source += "[#{input_selecting}]" unless input_selecting.nil?
instruction = {
schema: 'envoy-convert-instruction',
original: input_key,
bucket: s3_bucket,
write_options: {
acl: 'private'
},
key: output_key,
args: [source] + ARGV[1..-2] + ['{dest}']
}
logger.info("Invoking lambda with instruction #{instruction}")
resp = aws_lambda.invoke(
function_name: lambda_function,
invocation_type: 'RequestResponse',
payload: JSON.dump(instruction)
)
logger.info("Get response of invoke #{resp}")
raise 'Failed to run convert on Lambda' if resp.status_code != 200
logger.info(
"Downloading file from s3://#{s3_bucket}/#{output_key} to " \
"#{output_file}"
)
s3.get_object(
response_target: output_file,
bucket: s3_bucket,
key: output_key
)
logger.info('Done')
ensure
if !s3.nil? && !input_key.nil? && !output_key.nil?
logger.info(
"Delete files #{input_key} and #{output_key} from #{s3_bucket}"
)
s3.delete_objects(
bucket: s3_bucket,
delete: {
objects: [
{
key: input_key
},
{
key: output_key
}
],
quiet: true
}
)
end
end
|