Class: Lsaws::Lister

Inherits:
Object
  • Object
show all
Includes:
Utils
Defined in:
lib/lsaws/lister.rb

Constant Summary collapse

NEXT_PAGE_FIELDS =
%i[next_token next_marker next_page_token page_token].freeze

Instance Method Summary collapse

Methods included from Utils

#_deep_transform_keys_in_object, #_deep_transform_keys_in_object!, #from_iso8601, #to_iso8601

Constructor Details

#initialize(options) ⇒ Lister

Returns a new instance of Lister.



13
14
15
16
# File 'lib/lsaws/lister.rb', line 13

def initialize(options)
  @options = options
  @options[:max_width] = nil if @options[:max_width].to_i.zero?
end

Instance Method Details

#_abort_with_list(sdk, type) ⇒ Object



18
19
20
21
22
23
24
25
26
27
# File 'lib/lsaws/lister.rb', line 18

def _abort_with_list(sdk, type)
  if type == "default"
    warn "[!] no default entity type set for #{sdk.inspect} SDK"
  else
    warn "[!] #{sdk.inspect} SDK does not have #{type.inspect} entity type"
  end
  puts "Known entity types are:"
  list_entity_types(sdk)
  exit 1
end

#_convert_tags_procObject

only for table/text view



183
184
185
# File 'lib/lsaws/lister.rb', line 183

def _convert_tags_proc
  proc { |entity| entity.tags.map { |tag| "#{tag.key}=#{tag.value}" }.join(", ") }
end

#_get_cols(row) ⇒ Object

elasticache:global_replication_groups has ‘members’ as a column, so cannot just use ‘rows.members` assuming row is always subclass of Struct here



208
209
210
211
212
213
214
# File 'lib/lsaws/lister.rb', line 208

def _get_cols(row)
  if row.is_a?(Struct)
    Struct.instance_method(:members).bind_call(row)
  else
    row.members
  end
end

#_list_array(a) ⇒ Object



191
192
193
194
195
196
197
198
199
200
# File 'lib/lsaws/lister.rb', line 191

def _list_array(a)
  case @options[:format]
  when :json
    puts a.to_json
  when :yaml
    puts a.to_yaml
  else
    puts a.join("\n")
  end
end

#_prepare_entities(sdk, type, &block) ⇒ Object



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
# File 'lib/lsaws/lister.rb', line 29

def _prepare_entities(sdk, type, &block)
  edef = Lsaws.config.dig(sdk, type)
  return _prepare_entities(sdk, edef, &block) if edef.is_a?(String) # redirect like 'default' -> 'instances'

  edef ||= {}
  require(edef["require"] || "aws-sdk-#{sdk}")

  params = edef["default_params"] || {}
  if @options[:filters].any?
    params[:filters] = @options[:filters].map { |k, v| { name: k, values: [v] } }
  elsif edef["default_filter"]
    params[:filters] = [edef["default_filter"]]
  end
  params[:max_results] = @options[:max_results] if @options[:max_results]

  ctor_params = {}
  ctor_params[:endpoint] = @options[:endpoint] if @options[:endpoint]

  sdkp = SDKParser.new(sdk)
  client_class = edef["client_class"] || sdkp.client_class_name
  client = Kernel.const_get(client_class).new(ctor_params)

  method_name = edef["method"] || sdkp.etype2method(type)
  _abort_with_list(sdk, type) unless method_name
  warn "[d] #{method_name} #{params}" if @options[:debug]
  results = client.send(method_name, params)

  warn "[d] #{File.basename(__FILE__)}:#{__LINE__} results:\n#{results.pretty_inspect}" if @options[:debug]

  if !edef["result_keys"] && results.any?
    r = results.first
    r = r.last if r.is_a?(Array)
    edef["result_keys"] =
      if r.respond_to?(type)
        [type]
      elsif NEXT_PAGE_FIELDS.any? { |t| r.respond_to?(t) }
        data_members = r.members - NEXT_PAGE_FIELDS
        if data_members.size == 1
          [data_members[0]]
        else
          # XXX what if there's more than one array?
          [data_members.find { |key| r[key].is_a?(Array) }].compact
        end
      else
        []
      end
  end

  edef["result_keys"].each do |key|
    results = if results.is_a?(Array)
                results.map(&key.to_sym).flatten # TODO: is flatten necessary?
              else
                results[key]
              end
  end

  warn "[d] #{File.basename(__FILE__)}:#{__LINE__} results:\n#{results.pretty_inspect}" if @options[:debug]
  edef["cols"] = @options[:show_cols] if @options[:show_cols].any?
  warn "[d] edef: #{edef}" if @options[:debug]

  col_defs = {}
  Array(edef["cols"]).each do |r|
    case r
    when String, Symbol
      col_defs[r] = proc { |entity| entity.send(r) }
    when Hash
      col_defs.merge!(r)
    else
      raise Error, "unexpected #{r.inspect}"
    end
  end
  # TODO: check with all types
  col_defs["tags"] = _convert_tags_proc if @options[:show_tags] || col_defs["tags"]

  results ||= []
  warn "[d] #{results.inspect}" if @options[:debug]
  if results.respond_to?(:any?) && results.any? && !results.first.respond_to?(:name) && results.first.respond_to?(:tags)
    results.first.class.class_eval do
      def name
        tags.find { |tag| tag.key == "Name" }&.value
      end
    end
  end

  case results
  when Hash
    col_defs = {
      key: :first,
      value: :last
    }
  when Array
    # ok
  else
    # ec2 instance_event_notification_attributes
    # 'Array(results)' doesn't work here
    results = [results]
  end

  if block_given?
    results.map do |entity|
      yield entity, col_defs
    end
  else
    [results, col_defs]
  end
end

#_tabulo_guess_max_cols(rows, _cols) ⇒ Object



216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'lib/lsaws/lister.rb', line 216

def _tabulo_guess_max_cols(rows, _cols)
  all_cols = _get_cols(rows[0])
  max_cols = all_cols.size
  return max_cols if max_cols < 4 || !@options[:max_width]

  4.upto(max_cols) do |ncols|
    tbl = Tabulo::Table.new(rows[0, 100], *all_cols[0, ncols])
    tbl.autosize_columns
    tbl_width = tbl.column_registry.values.map { |c| c.padded_width + 1 }.inject(:+) + 1
    return ncols - 1 if tbl_width >= @options[:max_width]
  end
  max_cols
end

#entities2hashes(sdk, type) ⇒ Object



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
# File 'lib/lsaws/lister.rb', line 150

def entities2hashes(sdk, type)
  rows =
    if @options[:show_cols].any?
      # show cols specified on cmdline
      _prepare_entities(sdk, type) do |entity, _col_defs|
        case entity
        when String
          { value: entity } # might conflict with show_cols, let's always display for now
        else
          @options[:show_cols].map { |c| [c, entity.send(c)] }.to_h
        end
      end
    else
      # either predefined cols from YAML or automatic ones
      _prepare_entities(sdk, type) do |entity, _col_defs|
        case entity
        when String
          { value: entity }
        else
          # ec2 instance_event_notification_attributes
          entity.to_h
        end
      end
    end
  if rows&.first&.key?("tags")
    rows.each do |row|
      row["tags"] = row["tags"].map { |tag| [tag.key, tag.value] }.to_h
    end
  end
  rows
end

#entities2records(sdk, type) ⇒ Object



136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/lsaws/lister.rb', line 136

def entities2records(sdk, type)
  rows, cols = _prepare_entities(sdk, type)
  if rows.is_a?(Array) && rows[0].is_a?(String)
    # sqs
    cols = { value: proc { |entity| entity } }
  elsif rows.is_a?(Array) && rows[0].is_a?(Hash)
    # securitylake:log_sources
    cols = { value: proc { |entity| entity } }
  elsif rows.respond_to?(:members)
    rows = [rows]
  end
  [rows, cols]
end

#list_entity_types(sdk) ⇒ Object



202
203
204
# File 'lib/lsaws/lister.rb', line 202

def list_entity_types(sdk)
  _list_array SDKParser.new(sdk).entity_types
end

#list_sdksObject



187
188
189
# File 'lib/lsaws/lister.rb', line 187

def list_sdks
  _list_array SDKParser.get_sdks
end

#process_command(sdk, type = "default") ⇒ Object



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
# File 'lib/lsaws/lister.rb', line 230

def process_command(sdk, type = "default")
  if sdk == :list
    return list_sdks
  elsif type == :list
    return list_entity_types(sdk)
  elsif type == :all
    SDKParser.new(sdk).entity_types.each do |etype|
      puts "#{etype}:"
      process_command(sdk, etype)
    end
    return
  end

  case @options[:format]
  when :text, :table
    @options[:max_width] ||= ($stdout.tty? ? TTY::Screen.width : nil)

    rows, cols = entities2records(sdk, type)
    return unless rows.any?

    style = @options[:format] == :text ? :blank : :modern

    tbl = Tabulo::Table.new(rows, border: style, align_header: :left, header_frequency: @options[:header])
    if cols.any?
      cols.each { |name, func| tbl.add_column(name, &func) }
    else
      max_cols = _tabulo_guess_max_cols(rows, cols)
      _get_cols(rows[0])[0, max_cols].each { |col| tbl.add_column(col) }
    end
    puts tbl.pack(max_table_width: @options[:max_width])
  when :json
    rows = entities2hashes(sdk, type)
    puts rows.to_json
  when :'json-stream', :js
    rows = entities2hashes(sdk, type)
    rows.each do |row|
      puts row.to_json
    end
  when :yaml
    rows = entities2hashes(sdk, type)
    puts rows.map { |row| _deep_transform_keys_in_object(row, &:to_s) }.to_yaml
  else
    warn "[!] unknown format: #{@options[:format]}"
    exit 1
  end
rescue Aws::Errors::ServiceError => e
  warn "[!] #{e}"
end