Class: Awful::DynamoDB

Inherits:
Cli show all
Defined in:
lib/awful/dynamodb.rb

Constant Summary collapse

COLORS =
{
  CREATING: :yellow,
  UPDATING: :yellow,
  DELETING: :red,
  ACTIVE:   :green,
}

Instance Method Summary collapse

Methods inherited from Cli

#initialize

Constructor Details

This class inherits a constructor from Awful::Cli

Instance Method Details

#batch_write(name) ⇒ Object



372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
# File 'lib/awful/dynamodb.rb', line 372

def batch_write(name)
  items = (1..25).map do |n|
    {
      put_request: {
        item: {
          "store_id"     => "store#{n}",
          "object_id"    => "object#{n}",
          "object_value" => "value#{n}"
        }
      }
    }
  end
  p items
  r = dynamodb.batch_write_item(request_items: {name => items})
  p r
end

#copy(src, dst) ⇒ Object



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
# File 'lib/awful/dynamodb.rb', line 232

def copy(src, dst)
  src_table, src_region = src.split('/').reverse # parse region/table into [table, region]
  dst_table, dst_region = dst.split('/').reverse

  ## clients are potentially for different regions
  src_client = Aws::DynamoDB::Client.new({region: src_region}.reject{|_,v| v.nil?})
  dst_client = Aws::DynamoDB::Client.new({region: dst_region}.reject{|_,v| v.nil?})

  ## params for put_item call
  params = {table_name: dst_table}

  ## add condition not to overwrite existing primary keys (hash or composite hash AND range)
  if options[:no_clobber]
    keys = dst_client.describe_table(table_name: dst_table).table.key_schema.map(&:attribute_name)
    params.merge!(condition_expression: keys.map{|key| "attribute_not_exists(#{key})"}.join(' AND '))
  end

  ## lame progress indicator, pass true for put, false for skip
  dots = options[:dots] ? ->(x){print x ? '.' : 'x'} : ->(_){}

  ## loop on each batch of scanned items
  exclusive_start_key = nil
  loop do
    r = src_client.scan(table_name: src_table, exclusive_start_key: exclusive_start_key, return_consumed_capacity: 'INDEXES')
    puts "[#{Time.now}] [#{src_table}] scanned:#{r.count} key:#{r.last_evaluated_key || 'nil'}"

    ## loop items and put to destination
    put = skipped = 0
    r.items.each do |item|
      begin
        dst_client.put_item(params.merge(item: item))
        put += 1
        dots.call(true)
      rescue Aws::DynamoDB::Errors::ConditionalCheckFailedException #item key exists
        skipped += 1
        dots.call(false)
      end
    end

    print "\n" if options[:dots]
    puts "[#{Time.now}] [#{dst_table}] put:#{put} skipped:#{skipped}"

    ## loop if there are more keys to scan
    exclusive_start_key = r.last_evaluated_key
    break unless exclusive_start_key
  end
end

#create_table(name, file = nil) ⇒ Object



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
# File 'lib/awful/dynamodb.rb', line 87

def create_table(name, file = nil)
  opt = load_cfg(options, file)
  params = only_keys_matching(opt, %i[attribute_definitions key_schema])
  params[:table_name] = name
  params[:provisioned_throughput] = only_keys_matching(opt[:provisioned_throughput], %i[read_capacity_units write_capacity_units])

  ## scrub unwanted keys from LSIs
  if opt.has_key?(:local_secondary_indexes)
    params[:local_secondary_indexes] = opt[:local_secondary_indexes].map do |lsi|
      only_keys_matching(lsi, %i[index_name key_schema projection])
    end
  end

  ## scrub unwanted keys from GSIs
  if opt.has_key?(:global_secondary_indexes)
    params[:global_secondary_indexes] = opt[:global_secondary_indexes].map do |gsi|
      only_keys_matching(gsi, %i[index_name key_schema projection]).output do |g|
        if gsi[:provisioned_throughput]
          g[:provisioned_throughput] = only_keys_matching(gsi[:provisioned_throughput], %i[read_capacity_units write_capacity_units])
        end
      end
    end
  end

  dynamodb.create_table(params)
end

#delete_table(name) ⇒ Object



219
220
221
222
223
224
225
226
227
# File 'lib/awful/dynamodb.rb', line 219

def delete_table(name)
  confirmation = ask("to delete #{name} and all its data, type the name of table to delete:", :yellow)
  if confirmation == name
    say("deleting table #{name}")
    dynamodb.delete_table(table_name: name)
  else
    say("confirmation failed for #{name}", :red)
  end
end

#dump(name) ⇒ Object



66
67
68
69
70
71
72
# File 'lib/awful/dynamodb.rb', line 66

def dump(name)
  all_matching_tables(name).map do |table_name|
    dynamodb.describe_table(table_name: table_name).table.to_hash.output do |table|
      puts YAML.dump(stringify_keys(table))
    end
  end
end

#enable_streams(name) ⇒ Object



212
213
214
215
216
# File 'lib/awful/dynamodb.rb', line 212

def enable_streams(name)
  stream_specification = {stream_enabled: !options[:disable]}
  stream_specification.merge!(stream_view_type: options[:stream_view_type].upcase) unless options[:disable]
  dynamodb.update_table(table_name: name, stream_specification: stream_specification)
end

#gsi(name) ⇒ Object



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/awful/dynamodb.rb', line 117

def gsi(name)
  (dynamodb.describe_table(table_name: name).table.global_secondary_indexes || []).output do |list|
    if options[:long]
      print_table list.map { |i|
        hash  = i.key_schema.find{ |k| k.key_type == 'HASH' }&.attribute_name
        range = i.key_schema.find{ |k| k.key_type == 'RANGE' }&.attribute_name
        [i.index_name, color(i.index_status), hash, range, i.projection.projection_type,
         i.provisioned_throughput.read_capacity_units, i.provisioned_throughput.write_capacity_units,
         i.index_size_bytes, i.item_count]
      }.sort
    elsif options[:arn]
      puts list.map(&:index_arn).sort
    else
      puts list.map(&:index_name).sort
    end
  end
end

#keys(name) ⇒ Object



80
81
82
83
84
# File 'lib/awful/dynamodb.rb', line 80

def keys(name)
  dynamodb.describe_table(table_name: name).table.key_schema.each_with_object({}) do |schema, h|
    h[schema.key_type.downcase.to_sym] = schema.attribute_name
  end.output(&method(:print_table))
end

#ls(name = /./) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/awful/dynamodb.rb', line 51

def ls(name = /./)
  tables = all_matching_tables(name)

  if options[:long]
    tables.map do |table|
      dynamodb.describe_table(table_name: table).table
    end.output do |list|
      print_table list.map { |t| [ t.table_name, color(t.table_status), t.item_count, t.table_size_bytes, t.creation_date_time ] }
    end
  else
    tables.output(&method(:puts))
  end
end

#lsi(name) ⇒ Object



138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/awful/dynamodb.rb', line 138

def lsi(name)
  (dynamodb.describe_table(table_name: name).table.local_secondary_indexes || []).output do |list|
    if options[:long]
      print_table list.map { |i|
        hash  = i.key_schema.find{ |k| k.key_type == 'HASH' }&.attribute_name
        range = i.key_schema.find{ |k| k.key_type == 'RANGE' }&.attribute_name
        [i.index_name, hash, range, i.projection.projection_type, i.index_size_bytes, i.item_count]
      }.sort
    elsif options[:arn]
      puts list.map(&:index_arn).sort
    else
      puts list.map(&:index_name).sort
    end
  end
end

#put_items(name, file = nil) ⇒ Object



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
# File 'lib/awful/dynamodb.rb', line 342

def put_items(name, file = nil)
  params = {'TableName' => name}

  ## set a condition not to overwrite items with existing primary key(s)
  if options[:no_clobber]
    keys = dynamodb.describe_table(table_name: name).table.key_schema.map(&:attribute_name)
    params.merge!('ConditionExpression' => keys.map{|key| "attribute_not_exists(#{key})"}.join(' AND '))
  end

  ## input data
  io = (file and File.open(file)) || ((not $stdin.tty?) and $stdin)

  put_count = 0
  skip_count = 0
  io.each_line do |line|
    begin
      dynamodb_simple.put_item(params.merge('Item' => JSON.parse(line)))
      put_count += 1
    rescue Aws::DynamoDB::Errors::ConditionalCheckFailedException #item key exists
      skip_count += 1
    end
  end

  ## return counts
  [put_count, skip_count].output do |put, skip|
    puts "put #{put} items, skipped #{skip} items"
  end
end

#query(name, exclusive_start_key = nil) ⇒ Object



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
# File 'lib/awful/dynamodb.rb', line 311

def query(name, exclusive_start_key = nil)
  fd = options[:output] ? File.open(options[:output], 'w') : $stdout.dup # open output file or stdout
  exclusive_start_key = nil
  count = 0
  condition = "#{options[:hash_key]} = :hash_key_value"
  condition += " and #{options[:range_key]} = :range_key_value" if options[:range_key]
  attributes = {
    ':hash_key_value'  => { S: options[:hash_key_value] },
    ':range_key_value' => { S: options[:range_key_value] },
  }.reject { |_,v| v[:S].nil? }
  loop do
    r = dynamodb_simple.query(
      'TableName'                 => name,
      'ExclusiveStartKey'         => exclusive_start_key,
      'Select'                    => options[:count] ? 'COUNT' : 'ALL_ATTRIBUTES',
      'KeyConditionExpression'    => condition,
      'ExpressionAttributeValues' => attributes,
    )
    count += r.fetch('Count', 0)
    r.fetch('Items', []).each do |item|
      fd.puts JSON.generate(item)
    end
    exclusive_start_key = r['LastEvaluatedKey']
    break unless exclusive_start_key
  end
  fd.close
  puts count if options[:count]
end

#scan(name, exclusive_start_key = nil) ⇒ Object



283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
# File 'lib/awful/dynamodb.rb', line 283

def scan(name, exclusive_start_key = nil)
  fd = options[:output] ? File.open(options[:output], 'w') : $stdout.dup # open output file or stdout
  exclusive_start_key = nil
  count = 0
  loop do
    r = dynamodb_simple.scan(
      'TableName'         => name,
      'Select'            => options[:count] ? 'COUNT' : 'ALL_ATTRIBUTES',
      'ExclusiveStartKey' => exclusive_start_key
    )
    count += r.fetch('Count', 0)
    r.fetch('Items', []).each do |item|
      fd.puts JSON.generate(item)
    end
    exclusive_start_key = r['LastEvaluatedKey']
    break unless exclusive_start_key
  end
  fd.close
  puts count if options[:count]
end

#status(name) ⇒ Object



75
76
77
# File 'lib/awful/dynamodb.rb', line 75

def status(name)
  dynamodb.describe_table(table_name: name).table.table_status.output(&method(:puts))
end

#tag(name, *tags) ⇒ Object



399
400
401
402
403
404
405
406
407
# File 'lib/awful/dynamodb.rb', line 399

def tag(name, *tags)
  dynamodb.tag_resource(
    resource_arn: get_arn(name),
    tags: tags.map { |t|
      k, v = t.split(/[=:]/)
      {key: k, value: v}
    }
  )
end

#tags(name) ⇒ Object



390
391
392
393
394
395
396
# File 'lib/awful/dynamodb.rb', line 390

def tags(name)
  paginate(:tags) do |token|
    dynamodb.list_tags_of_resource(resource_arn: get_arn(name), next_token: token)
  end.output do |tags|
    print_table tags.map { |t| [t.key, t.value] }
  end
end

#throughput(name) ⇒ Object



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
# File 'lib/awful/dynamodb.rb', line 160

def throughput(name)
  table = dynamodb.describe_table(table_name: name).table

  ## current is hash of current provisioned throughput
  current = table.provisioned_throughput.to_h

  ## loop-safe version of GSIs (in case nil)
  global_secondary_indexes = table.global_secondary_indexes || []

  ## get throughput for each GSI
  global_secondary_indexes.each do |gsi|
    current[gsi.index_name] = gsi.provisioned_throughput.to_h
  end

  ## if no updates requested, just print throughput and return table details
  unless options[:read_capacity_units] or options[:write_capacity_units]
    puts YAML.dump(stringify_keys(current))
    return table
  end

  ## parameters for update request
  params = { table_name: name }

  ## add table throughput unless told not to
  params[:provisioned_throughput] = {
    read_capacity_units:  options[:read_capacity_units]  || current[:read_capacity_units],
    write_capacity_units: options[:write_capacity_units] || current[:write_capacity_units]
  } if options[:table]

  ## list of requested GSIs, or all for this table
  gsis = options[:gsi]
  gsis = global_secondary_indexes.map(&:index_name) if options[:all]
  params[:global_secondary_index_updates] = gsis.map do |gsi|
    {
      update: {
        index_name: gsi,
        provisioned_throughput: {
          read_capacity_units:  options[:read_capacity_units]  || current[gsi][:read_capacity_units],
          write_capacity_units: options[:write_capacity_units] || current[gsi][:write_capacity_units]
        }
      }
    }
  end

  ## make the update request
  params.reject! { |_,v| v.empty? } # sdk hates empty global_secondary_index_updates
  dynamodb.update_table(params)
end

#ttl(name, attribute = nil) ⇒ Object



411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
# File 'lib/awful/dynamodb.rb', line 411

def ttl(name, attribute = nil)
  if attribute
    dynamodb.update_time_to_live(
      table_name: name,
      time_to_live_specification: {
        enabled: !options[:disable],
        attribute_name: attribute,
      }
    )
  else
    dynamodb.describe_time_to_live(table_name: name).time_to_live_description.output do |t|
      puts YAML.dump(stringify_keys(t.to_hash))
    end
  end
end