Module: AwsStackBuilder

Defined in:
lib/modulator/lambda/aws_stack_builder.rb,
lib/modulator/lambda/aws_stack_uploader.rb

Constant Summary collapse

RUBY_VERSION =
'ruby2.5'
GEM_PATH =
'/opt/ruby/2.5.0'
LAMBDA_HANDLER_FILE_NAME =
'lambda-handler'
S3Client =
Aws::S3::Client.new

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.api_gateway_deploymentObject

Returns the value of attribute api_gateway_deployment.



12
13
14
# File 'lib/modulator/lambda/aws_stack_builder.rb', line 12

def api_gateway_deployment
  @api_gateway_deployment
end

.app_dirObject

Returns the value of attribute app_dir.



13
14
15
# File 'lib/modulator/lambda/aws_stack_builder.rb', line 13

def app_dir
  @app_dir
end

.app_nameObject

Returns the value of attribute app_name.



12
13
14
# File 'lib/modulator/lambda/aws_stack_builder.rb', line 12

def app_name
  @app_name
end

.app_pathObject

Returns the value of attribute app_path.



13
14
15
# File 'lib/modulator/lambda/aws_stack_builder.rb', line 13

def app_path
  @app_path
end

.bucketObject

Returns the value of attribute bucket.



13
14
15
# File 'lib/modulator/lambda/aws_stack_builder.rb', line 13

def bucket
  @bucket
end

.gateway_idObject

Returns the value of attribute gateway_id.



12
13
14
# File 'lib/modulator/lambda/aws_stack_builder.rb', line 12

def gateway_id
  @gateway_id
end

.hidden_dirObject

Returns the value of attribute hidden_dir.



13
14
15
# File 'lib/modulator/lambda/aws_stack_builder.rb', line 13

def hidden_dir
  @hidden_dir
end

.stackObject

Returns the value of attribute stack.



12
13
14
# File 'lib/modulator/lambda/aws_stack_builder.rb', line 12

def stack
  @stack
end

.stack_optsObject

Returns the value of attribute stack_opts.



13
14
15
# File 'lib/modulator/lambda/aws_stack_builder.rb', line 13

def stack_opts
  @stack_opts
end

Class Method Details

.add_api_gatewayObject

gateway



58
59
60
61
# File 'lib/modulator/lambda/aws_stack_builder.rb', line 58

def add_api_gateway
  @gateway_id = 'ApiGateway'
  @stack.add(gateway_id, Humidifier::ApiGateway::RestApi.new(name: app_name, description: app_name + ' API'))
end

.add_api_gateway_deploymentObject

gateway deployment



64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/modulator/lambda/aws_stack_builder.rb', line 64

def add_api_gateway_deployment
  @api_gateway_deployment = Humidifier::ApiGateway::Deployment.new(
    rest_api_id: Humidifier.ref(gateway_id),
    stage_name: Humidifier.ref("ApiGatewayStageName")
  )
  @stack.add('ApiGatewayDeployment', @api_gateway_deployment)
  @stack.add_output('ApiGatewayInvokeURL',
      value: Humidifier.fn.sub("https://${#{gateway_id}}.execute-api.${AWS::Region}.amazonaws.com/${ApiGatewayStageName}"),
      description: 'API root url',
      export_name: app_name + 'RootUrl'
  )
  @api_gateway_deployment.depends_on = []
end

.add_api_gateway_resources(gateway:, lambda:) ⇒ Object

gateway method



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
# File 'lib/modulator/lambda/aws_stack_builder.rb', line 131

def add_api_gateway_resources(gateway:, lambda:)

  # example: calculator/algebra/:x/:y/sum -> module name, args, method name
  path = gateway[:path].split('/')

  # root resource
  root_resource = path.shift
  @stack.add(root_resource.camelize, Humidifier::ApiGateway::Resource.new(
      rest_api_id: Humidifier.ref(AwsStackBuilder.gateway_id),
      parent_id: Humidifier.fn.get_att(["ApiGateway", "RootResourceId"]),
      path_part: root_resource
    )
  )

  # args and method name are nested resources
  parent_resource = root_resource.camelize
  path.each do |fragment|
    if fragment.start_with?(':')
      fragment = fragment[1..-1]
      dynamic_fragment = "{#{fragment}}"
    end
    @stack.add(parent_resource + fragment.camelize, Humidifier::ApiGateway::Resource.new(
        rest_api_id: Humidifier.ref(AwsStackBuilder.gateway_id),
        parent_id: Humidifier.ref(parent_resource),
        path_part: dynamic_fragment || fragment
      )
    )
    parent_resource = parent_resource + fragment.camelize
  end

  # attach lambda to last resource
  id = 'EndpointFor' + (gateway[:path].gsub(':', '').gsub('/', '_')).camelize
  @stack.add(id, Humidifier::ApiGateway::Method.new(
      authorization_type: 'NONE',
      http_method: gateway[:verb].to_s.upcase,
      integration: {
        integration_http_method: 'POST',
        type: "AWS_PROXY",
        uri: Humidifier.fn.sub([
          "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${lambdaArn}/invocations",
          'lambdaArn' => Humidifier.fn.get_att([lambda, 'Arn'])
        ])
      },
      rest_api_id: Humidifier.ref(gateway_id),
      resource_id: Humidifier.ref(parent_resource) # last evaluated resource
    )
  )

  # deployment depends on the method
  @api_gateway_deployment.depends_on << id
end

.add_lambda(gateway:, mod:, wrapper: {}, env: {}, settings: {}) ⇒ Object

lambda function



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
# File 'lib/modulator/lambda/aws_stack_builder.rb', line 79

def add_lambda(gateway:, mod:, wrapper: {}, env: {}, settings: {})
  lambda_config = {}
  name_parts = mod[:name].split('::')
  {gateway: gateway, module: mod, wrapper: wrapper}.each do |env_group_prefix, env_group|
    env_group.each{|env_key, env_value| lambda_config["#{env_group_prefix}_#{env_key}"] = env_value}
  end

  lambda_function = Humidifier::Lambda::Function.new(
    description: "Lambda for #{mod[:name]}.#{mod[:method]}",
    function_name: [app_name.dasherize, name_parts, mod[:method]].flatten.map(&:downcase).join('-'),
    handler: "#{LAMBDA_HANDLER_FILE_NAME}.AwsLambdaHandler.call",
    environment: {
      variables: env
        .reduce({}){|env_as_string, (k, v)| env_as_string.update(k.to_s => v.to_s)}
        .merge(lambda_config)
        .merge('GEM_PATH' => GEM_PATH, 'app_dir' => app_dir)
    },
    role: Humidifier.fn.get_att(['LambdaRole', 'Arn']),
    timeout: settings[:timeout] || stack_opts[:timeout] || 15,
    memory_size: settings[:memory_size] || stack_opts[:memory_size] || 128,
    runtime: RUBY_VERSION,
    code: {
      s3_bucket: bucket,
      s3_key: LAMBDA_HANDLER_FILE_NAME + '.rb.zip'
    },
    layers: [
      Humidifier.ref(app_name + 'Layer'),
      Humidifier.ref(app_name + 'GemsLayer')
    ]
  )
  id = ['Lambda', name_parts, mod[:method].capitalize].join
  @stack.add(id, lambda_function)
  add_lambda_invoke_permission(id: id, gateway: gateway)
  id
end

.add_lambda_iam_role(function_name: nil) ⇒ Object



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
# File 'lib/modulator/lambda/aws_stack_builder.rb', line 183

def add_lambda_iam_role(function_name: nil)
  @stack.add('LambdaRole', Humidifier::IAM::Role.new(
      assume_role_policy_document: {
        'Version' => "2012-10-17",
        'Statement' => [
          {
            'Action' => ["sts:AssumeRole"],
            'Effect' => "Allow",
            'Principal' => {
              'Service' => ["lambda.amazonaws.com"]
            }
          }
        ]
      },
      policies: [
        {
          'policy_document' => {
            'Version' => "2012-10-17",
            'Statement' => [
              {
                'Action' => [
                  "logs:CreateLogStream",
                  "logs:PutLogEvents",
                ],
                'Effect' => "Allow",
                'Resource' => Humidifier.fn.sub("arn:aws:logs:${AWS::Region}:${AWS::AccountId}:*")
              },
              {
                'Action' => [
                  "logs:CreateLogGroup",
                ],
                'Effect' => "Allow",
                'Resource' => "*"
              }
            ]
          },
          'policy_name' => "cloud-watch-access"
        }
      ]
    )
  )
end

.add_lambda_invoke_permission(id:, gateway:) ⇒ Object

invoke permission



116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/modulator/lambda/aws_stack_builder.rb', line 116

def add_lambda_invoke_permission(id:, gateway:)
  arn_path_matcher = gateway[:path].split('/').each_with_object([]) do |fragment, matcher|
    fragment = '*' if fragment.start_with?(':')
    matcher << fragment
  end.join('/')
  @stack.add('LambdaPermission', Humidifier::Lambda::Permission.new(
      action: "lambda:InvokeFunction",
      function_name: Humidifier.fn.get_att([id, 'Arn']),
      principal: "apigateway.amazonaws.com",
      source_arn: Humidifier.fn.sub("arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${#{gateway_id}}/*/#{gateway[:verb]}/#{arn_path_matcher}")
    )
  )
end

.add_layer(name:, description:, s3_key:, s3_object_version:) ⇒ Object

add layer



135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/modulator/lambda/aws_stack_uploader.rb', line 135

def add_layer(name:, description:, s3_key:, s3_object_version:)
  stack.add(name + 'Layer', Humidifier::Lambda::LayerVersion.new(
      compatible_runtimes: [RUBY_VERSION],
      layer_name: name,
      description: description,
      content: {
        s3_bucket: bucket,
        s3_key: s3_key,
        s3_object_version: s3_object_version
      }
    )
  )
end

.checksum(dir) ⇒ Object



149
150
151
152
153
# File 'lib/modulator/lambda/aws_stack_uploader.rb', line 149

def checksum(dir)
  files = Dir["#{dir}/**/*"].reject{|f| File.directory?(f)}
  content = files.map{|f| File.read(f)}.join
  Digest::MD5.hexdigest(content)
end

.extend_stack_instance(stack) ⇒ Object

helpers



46
47
48
49
50
51
52
53
54
55
# File 'lib/modulator/lambda/aws_stack_builder.rb', line 46

def extend_stack_instance(stack)
  stack.instance_eval do
    def add_lambda_endpoint(**opts) # gateway:, mod:, wrapper: {}, env: {}, settings: {}
      # add lambda
      lambda = AwsStackBuilder.add_lambda(opts)
      # add api resources
      AwsStackBuilder.add_api_gateway_resources(gateway: opts[:gateway], lambda: lambda)
    end
  end
end

.init(app_name:, bucket:, **stack_opts) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/modulator/lambda/aws_stack_builder.rb', line 16

def init(app_name:, bucket:, **stack_opts)
  puts 'Initializing stack'
  @app_name   = app_name.camelize
  @bucket     = bucket
  @app_path   = Pathname.getwd
  @app_dir    = app_path.basename.to_s
  @hidden_dir = '.modulator'
  @stack_opts = stack_opts
  @stack      = Humidifier::Stack.new(name: @app_name, aws_template_format_version: '2010-09-09')

  # api stage
  @stack.add_parameter('ApiGatewayStageName', description: 'Gateway deployment stage', type: 'String', default: 'v1')

  add_api_gateway
  add_api_gateway_deployment
  add_lambda_iam_role
  upload_files
  extend_stack_instance(@stack)
  @stack
end

.upload_app_layerObject



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
# File 'lib/modulator/lambda/aws_stack_uploader.rb', line 90

def upload_app_layer
  zip_file_name = app_dir + '.zip'
  app_zip_path  = app_path.join(hidden_dir, zip_file_name)

  # copy app code to ruby/lib in use outside temp dir
  temp_dir_name = '.modulator_temp'
  ruby_lib_dirs = 'ruby/lib'
  temp_path     = app_path.parent.join(temp_dir_name)
  temp_path.join(ruby_lib_dirs).mkpath
  FileUtils.copy_entry app_path, temp_path.join(ruby_lib_dirs)

  # calculate checksum for app folder
  checksum_path = app_path.join(hidden_dir, 'app_checksum')
  old_checksum  = (checksum_path.read rescue nil)
  new_checksum  = checksum(app_path)

  if old_checksum != new_checksum
    puts '- uploading app layer'
    checksum_path.write(new_checksum)
    ZipFileGenerator.new(temp_path, app_zip_path).write
    # upload zipped file
    app_layer = S3Client.put_object(
      bucket: bucket,
      key: zip_file_name,
      body: app_zip_path.read
    )
    # delete zipped file
    app_zip_path.delete
  else
    puts '- using existing app layer'
    app_layer = S3Client.get_object(bucket: bucket, key: zip_file_name)
  end

  # delete temp dir
  FileUtils.remove_dir(temp_path)

  add_layer(
    name: app_name,
    description: "App source. MD5: #{new_checksum}",
    s3_key: zip_file_name,
    s3_object_version: app_layer.version_id
  )
end

.upload_filesObject



37
38
39
40
41
42
43
# File 'lib/modulator/lambda/aws_stack_builder.rb', line 37

def upload_files
  upload_lambda_handler
  puts 'Generating layers'
  app_path.join(hidden_dir).mkpath
  upload_gems_layer
  upload_app_layer
end

.upload_gems_layerObject



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
# File 'lib/modulator/lambda/aws_stack_uploader.rb', line 41

def upload_gems_layer
  if !app_path.join('Gemfile').exist?
    puts '- no Gemfile detected'
    return
  end

  # calculate Gemfile checksum
  checksum_path = app_path.join(hidden_dir, 'gemfile_checksum')
  old_checksum  = (checksum_path.read rescue nil)
  new_checksum  = Digest::MD5.hexdigest(File.read(app_path.join('Gemfile.lock')))

  zip_file_name = app_dir + '_gems.zip'
  gems_path = app_path.join(hidden_dir, 'gems')
  gems_zip_path = app_path.join(hidden_dir, zip_file_name)

  if old_checksum != new_checksum
    puts '- uploading gems layer'
    checksum_path.write(new_checksum)

    # bundle gems
    Bundler.with_clean_env do
      Dir.chdir(app_path) do
        `bundle install --path=./#{hidden_dir}/gems --clean`
      end
    end
    ZipFileGenerator.new(gems_path, gems_zip_path).write

    # upload zipped file
    gem_layer = S3Client.put_object(
      bucket: bucket,
      key: zip_file_name,
      body: gems_zip_path.read
    )
    # delete zipped file
    FileUtils.remove_dir(gems_path)
    gems_zip_path.delete
  else
    puts '- using existing gems layer'
    gem_layer = S3Client.get_object(bucket: bucket, key: zip_file_name)
  end

  add_layer(
    name: app_name + 'Gems',
    description: "App gems",
    s3_key: zip_file_name,
    s3_object_version: gem_layer.version_id
  )
end

.upload_lambda_handlerObject



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
# File 'lib/modulator/lambda/aws_stack_uploader.rb', line 10

def upload_lambda_handler
  bucket_name = Humidifier.ref("S3Bucket").reference
  lambda_handler_key = LAMBDA_HANDLER_FILE_NAME + '.rb.zip'
  source = <<~SOURCE
    require 'modulator/lambda/aws_lambda_handler'
  SOURCE

  existing_handler = S3Client.get_object(
    bucket: bucket,
    key: lambda_handler_key
  ) rescue false # not found

  existing_source = Zip::InputStream.open(existing_handler.body) do |zip_file|
    zip_file.get_next_entry
    zip_file.read
  end if existing_handler

  if existing_source != source
    puts '- uploading generic lambda handler'
    source_zip_file = Zip::OutputStream.write_buffer do |zip|
      zip.put_next_entry LAMBDA_HANDLER_FILE_NAME + '.rb'
      zip.print source
    end
    S3Client.put_object(
      bucket: bucket,
      key: lambda_handler_key,
      body: source_zip_file.tap(&:rewind).read
    )
  end
end