Class: Aly::App

Inherits:
Object
  • Object
show all
Defined in:
lib/aly/app.rb

Instance Method Summary collapse

Instance Method Details

#ecs(*args, **options) ⇒ Object



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
# File 'lib/aly/app.rb', line 24

def ecs(*args, **options)
  raw_out = exec('ecs', 'DescribeInstances', '--pager', **options)
  selected = (raw_out['Instances']['Instance'] || []).each do |item|
    item['PrivateIP'] = (item['NetworkInterfaces']['NetworkInterface'] || []).map { |ni| ni['PrimaryIpAddress'] }.join(',')
    item['PublicIP'] = item['EipAddress']['IpAddress'] || ''
    item['PublicIP'] = item['PublicIpAddress']['IpAddress'].join(',') if item['PublicIP'] == ''
  end

  if query = args.first&.split(',')
    selected = selected.select do |item|
      item.values_at('InstanceId', 'InstanceName', 'PrivateIP', 'PublicIP').compact.any? { |e| query.any? { |q| e.include?(q) } }
    end
  end

  if options[:full]
    selected = selected.map do |row|
      {
        Id: row['InstanceId'],
        Name: row['InstanceName'],
        PrivateIP: row['PrivateIP'],
        PublicIP: row['PublicIP'],
        CPU: row['Cpu'],
        RAM: "#{row['Memory'] / 1024.0} GB",
        WEB: "https://ecs.console.aliyun.com/#/server/#{row['InstanceId']}/monitor?regionId=#{row['RegionId']}"
      }
    end
    puts selected.table&.to_s
  elsif options[:detail]
    puts JSON.pretty_generate(selected)
  else
    selected = selected.map do |row|
      {
        Id: row['InstanceId'],
        Name: row['InstanceName'],
        PrivateIP: row['PrivateIP'],
        PublicIP: row['PublicIP'],
        CPU: row['Cpu'],
        RAM: "#{row['Memory'] / 1024.0} GB"
      }
    end
    puts selected.table&.to_s
  end
end

#ecs_contains_host?(host) ⇒ Boolean

Returns:

  • (Boolean)


318
319
320
# File 'lib/aly/app.rb', line 318

def ecs_contains_host?(host)
  @ecs.any? { |item| item['AllIPs'].include?(host) }
end

#eip(*args, **options) ⇒ Object



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
# File 'lib/aly/app.rb', line 68

def eip(*args, **options)
  puts 'EIPs:'
  raw_out = exec('vpc', 'DescribeEipAddresses', '--PageSize=100', **options)
  selected = raw_out['EipAddresses']['EipAddress']

  if query = args.first&.split(',')
    selected = selected.select do |item|
      item.values_at('AllocationId', 'InstanceId', 'InstanceType', 'IpAddress').compact.any? { |e| query.any? { |q| e.include?(q) } }
    end
  end


  if options[:detail]
    puts JSON.pretty_generate(selected)
  else
    net_intefraces = exec('ecs', 'DescribeNetworkInterfaces', '--pager', **options)['NetworkInterfaceSets']['NetworkInterfaceSet'].each_with_object({}) do |item, result|
      result[item['NetworkInterfaceId']] = item
    end
    selected = selected.map do |row|
      result = {
        Id: row['AllocationId'],
        InstanceId: row['InstanceId'],
        InstanceType: row['InstanceType'],
        IP: row['IpAddress'],
        EcsId: '',
        PrivateIP: ''
      }

      if row['InstanceType'] == 'NetworkInterface' && interface = net_intefraces[row['InstanceId']]
        result[:EcsId] = interface['InstanceId']
        result[:PrivateIP] = interface['PrivateIpAddress']
      end

      result
    end
    puts selected.table&.to_s
  end
end

#eip_contains_host?(host) ⇒ Boolean

Returns:

  • (Boolean)


456
457
458
# File 'lib/aly/app.rb', line 456

def eip_contains_host?(host)
  @eip.any? { |eip| eip['IpAddress'] == host }
end

#exec(command, sub_command, *args, **options) ⇒ Object



501
502
503
504
505
# File 'lib/aly/app.rb', line 501

def exec(command, sub_command, *args, **options)
  command = "aliyun #{command} #{sub_command} #{args.join(' ')}"
  command += " -p #{options[:profile]}" if options[:profile]
  JSON.parse(`#{command}`)
end

#full_slb(lbs, eips, **options) ⇒ Object



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
# File 'lib/aly/app.rb', line 107

def full_slb(lbs, eips, **options)
  lbs.each do |lb|
    puts "\nLoanBalancer Id: %s, Name: %s" % [lb['LoadBalancerId'], lb['LoadBalancerName']]
    puts "==============================================================\n\n"
    listeners = lb['Listeners']
    background_servers = exec('slb', 'DescribeLoadBalancerAttribute', "--LoadBalancerId=#{lb['LoadBalancerId']}", **options)['BackendServers']['BackendServer'] || []

    puts '    LoadBalancer Basic Information:'
    puts([{
            Id: lb['LoadBalancerId'],
            Name: lb['LoadBalancerName'],
            Address: lb['Address'],
            Eip: lb['Eip'],
            Listeners: listeners.size,
            WEB: "https://slb.console.aliyun.com/slb/#{lb['RegionId']}/slbs/#{lb['LoadBalancerId']}/listeners"
          }].table.to_s.gsub(/^/, '    '))
    puts

    if background_servers && background_servers.size > 0
      puts '    Default Backend Servers:'
      puts

      ecss = @ecs.select { |e| background_servers.map{|ee| ee['ServerId']}.include?(e['InstanceId']) }

      puts ecss.map { |row|
        {
          Id: row['InstanceId'],
          Name: row['InstanceName'],
          PrivateIP: row['PrivateIP'].join(','),
          PublicIP: row['PublicIP'].join(','),
          CPU: row['Cpu'],
          RAM: "#{row['Memory'] / 1024.0} GB"
        }
      }.table.to_s.gsub(/^/, '    ')
      puts
    end

    vserver_groups = exec('slb', 'DescribeVServerGroups', '--pager', "--LoadBalancerId=#{lb['LoadBalancerId']}", **options)["VServerGroups"]["VServerGroup"] || []
    vserver_group_servers = vserver_groups.flat_map do |vg|
      vg_attr = exec('slb', 'DescribeVServerGroupAttribute', "--VServerGroupId=#{vg['VServerGroupId']}", **options)["BackendServers"]["BackendServer"]
      vg_attr.each_with_index.map do |attr, idx|
        ecs = @ecs.find {|e| e['InstanceId'] == attr['ServerId'] }
        {
          VGroupId: (idx.zero? ? vg['VServerGroupId'] : ''),
          VGroupName: (idx.zero? ? vg['VServerGroupName'] : ''),
          Weight: attr['Weight'],
          Port: attr['Port'],
          Type: attr['Type'],
          EcsId: attr['ServerId'],
          EcsName: ecs['InstanceName'],
          PrivateIP: ecs['PrivateIP'].join(','),
          PublicIP: ecs['PublicIP'].join(','),
          CPU: ecs['Cpu'],
          RAM: "#{ecs['Memory'] / 1024.0} GB"
        }
      end + [nil]
    end
    puts '    VServer Groups:'
    puts vserver_group_servers[0..-2].table.to_s.gsub(/^/, '    ')
    puts

    listeners.each do |listener|
      listener_type = ['HTTP', 'HTTPS', 'TCP', 'TCPS', 'UDP'].find { |e| !listener["#{e}ListenerConfig"].empty? }
      listener['ListenerType'] = listener_type
    end

    listeners_info = listeners.map do |listener|
      {
        Description: listener['Description'],
        Port: listener['ListenerPort'],
        Protocol: listener['ListenerProtocol'],
        Status: listener['Status'],
        HeathCheck: (listener["#{listener['ListenerType']}ListenerConfig"] || {}).dig("HealthCheck") || 'off',
        BackendServerPort: listener['BackendServerPort'],
        ForwardPort: listener.dig('HTTPListenerConfig', 'ForwardPort'),
        VServerGroup: listener['VServerGroupId'],
        AclStatus: listener['AclStatus'] || 'off',
        AclType: listener['AclType'],
        AclIds: (listener['AclIds'] || []).join(','),
      }
    end

    puts '    Configured Listeners:'
    puts listeners_info.table.to_s.gsub(/^/, '    ')
    puts

    listener_rules = listeners.flat_map do |listener|
      listener_type = listener['ListenerType']
      next [] unless listener_type
      rules = exec('slb', "DescribeLoadBalancer#{listener_type}ListenerAttribute", "--LoadBalancerId=#{lb['LoadBalancerId']}", "--ListenerPort=#{listener['ListenerPort']}", **options).dig('Rules', 'Rule') || []
      rules.map do |rule|
        {'Listener' => listener['Description']}.merge(rule)
      end
    end

    puts '    Listener Rules:'
    puts listener_rules.table.to_s.gsub(/^/, '    ')
    puts

    if options[:acl]
      acl_ids = listeners.flat_map { |listener| listener['AclIds'] || [] }.uniq
      unless acl_ids.empty?
        alc_entries = acl_ids.flat_map do |acl_id|
          attr = exec('slb', 'DescribeAccessControlListAttribute', "--AclId=#{acl_id}", **options)
          (attr.dig('AclEntrys', 'AclEntry') || []).each_with_index.map do |e, idx|
            {
              AclId: (idx.zero? ? attr['AclId'] : ''),
              AclName: (idx.zero? ? attr['AclName'] : ''),
              AclEntryIP: e['AclEntryIP'],
              AclEntryComment: e['AclEntryComment']
            }
          end + [nil]
        end
        puts '    Access Control Lists:'
        puts alc_entries[0..-2].table.to_s.gsub(/^/, '    ')
        puts
      end

    end

  end
end

#show(*args, **options) ⇒ Object



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
# File 'lib/aly/app.rb', line 460

def show(*args, **options)
  @slb ||= exec('slb', 'DescribeLoadBalancers', '--pager', **options)['LoadBalancers']['LoadBalancer'] || []

  @eip ||= exec('vpc', 'DescribeEipAddresses', '--PageSize=100', **options)['EipAddresses']['EipAddress'] || []

  eip_map = @eip.each_with_object({}) { |eip, h| h[eip['InstanceId']] = eip['IpAddress'] }
  @slb.each do |slb|
    slb['Eip'] = eip_map[slb['LoadBalancerId']]
  end

  unless @ecs
    @ecs = exec('ecs', 'DescribeInstances', '--pager', **options)['Instances']['Instance'] || []
    @ecs.each do |item|
      item['PrivateIP'] = (item['NetworkInterfaces']['NetworkInterface'] || []).map { |ni| ni['PrimaryIpAddress'] }
      item['PublicIP'] = []
      if ip = item['EipAddress']['IpAddress']
        item['PublicIP'] << ip
      end
      if ips = item['PublicIpAddress']['IpAddress']
        item['PublicIP'] += ips
      end
      item['AllIPs'] = item['PrivateIP'] + item['PublicIP']
    end
  end

  host = IPSocket::getaddress(args.first)

  puts "Host: #{args.first} resolves to #{host}" if host != args.first
  puts

  if slb_contains_host?(host)
    show_slb(host, **options)
  elsif ecs_contains_host?(host)
    show_ecs(host)
  elsif eip_contains_host?(host)
    eip(host, **options)
  else
    puts "Not found: #{host}"
  end
end

#show_ecs(host) ⇒ Object



441
442
443
444
445
446
447
448
449
450
451
452
453
454
# File 'lib/aly/app.rb', line 441

def show_ecs(host)
  selected = @ecs.select { |e| e['AllIPs'].include?(host) }.map do |row|
    {
      Id: row['InstanceId'],
      Name: row['InstanceName'],
      PrivateIP: row['PrivateIP'].join(','),
      PublicIP: row['PublicIP'].join(','),
      CPU: row['Cpu'],
      RAM: "#{row['Memory'] / 1024.0} GB"
    }
  end
  puts 'ECS Instances:'
  puts selected.table&.to_s
end

#show_slb(host, **options) ⇒ Object



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
# File 'lib/aly/app.rb', line 322

def show_slb(host, **options)
  @listeners ||= exec('slb', 'DescribeLoadBalancerListeners', '--pager', 'path=Listeners', **options)['Listeners'] || []
  lb = @slb.find { |e| e['Address'] == host || e['Eip'] == host }
  listeners = @listeners.select { |e| e['LoadBalancerId'] == lb['LoadBalancerId'] }

  puts "\nLoanBalancer Id: %s, Name: %s" % [lb['LoadBalancerId'], lb['LoadBalancerName']]
  puts "==============================================================\n\n"
  background_servers = exec('slb', 'DescribeLoadBalancerAttribute', "--LoadBalancerId=#{lb['LoadBalancerId']}", **options)['BackendServers']['BackendServer'] || []

  puts '    LoadBalancer Basic Information:'
  puts([{
          Id: lb['LoadBalancerId'],
          Name: lb['LoadBalancerName'],
          Address: lb['Address'],
          Eip: lb['Eip'],
          Listeners: listeners.size
        }].table.to_s.gsub(/^/, '    '))
  puts

  if background_servers && background_servers.size > 0
    puts '    Default Backend Servers:'
    puts

    ecss = @ecs.select { |e| background_servers.map{|ee| ee['ServerId']}.include?(e['InstanceId']) }

    puts ecss.map { |row|
      {
        Id: row['InstanceId'],
        Name: row['InstanceName'],
        PrivateIP: row['PrivateIP'].join(','),
        PublicIP: row['PublicIP'].join(','),
        CPU: row['Cpu'],
        RAM: "#{row['Memory'] / 1024.0} GB"
      }
    }.table.to_s.gsub(/^/, '    ')
    puts
  end

  vserver_groups = exec('slb', 'DescribeVServerGroups', '--pager', "--LoadBalancerId=#{lb['LoadBalancerId']}", **options)["VServerGroups"]["VServerGroup"] || []
  vserver_group_servers = vserver_groups.flat_map do |vg|
    vg_attr = exec('slb', 'DescribeVServerGroupAttribute', "--VServerGroupId=#{vg['VServerGroupId']}", **options)["BackendServers"]["BackendServer"]
    vg_attr.each_with_index.map do |attr, idx|
      ecs = @ecs.find {|e| e['InstanceId'] == attr['ServerId'] }
      {
        VGroupId: (idx.zero? ? vg['VServerGroupId'] : ''),
        VGroupName: (idx.zero? ? vg['VServerGroupName'] : ''),
        Weight: attr['Weight'],
        Port: attr['Port'],
        Type: attr['Type'],
        EcsId: attr['ServerId'],
        EcsName: ecs['InstanceName'],
        PrivateIP: ecs['PrivateIP'].join(','),
        PublicIP: ecs['PublicIP'].join(','),
        CPU: ecs['Cpu'],
        RAM: "#{ecs['Memory'] / 1024.0} GB"
      }
    end + [nil]
  end
  puts '    VServer Groups:'
  puts vserver_group_servers[0..-2].table.to_s.gsub(/^/, '    ')
  puts

  listeners.each do |listener|
    listener_type = ['HTTP', 'HTTPS', 'TCP', 'TCPS', 'UDP'].find { |e| !listener["#{e}ListenerConfig"].empty? }
    listener['ListenerType'] = listener_type
  end

  listeners_info = listeners.map do |listener|
    {
      Description: listener['Description'],
      Port: listener['ListenerPort'],
      Protocol: listener['ListenerProtocol'],
      Status: listener['Status'],
      HeathCheck: (listener["#{listener['ListenerType']}ListenerConfig"] || {}).dig("HealthCheck") || 'off',
      BackendServerPort: listener['BackendServerPort'],
      ForwardPort: listener.dig('HTTPListenerConfig', 'ForwardPort'),
      VServerGroup: listener['VServerGroupId'],
      AclStatus: listener['AclStatus'] || 'off',
      AclType: listener['AclType'],
      AclIds: (listener['AclIds'] || []).join(','),
    }
  end

  puts '    Configured Listeners:'
  puts listeners_info.table.to_s.gsub(/^/, '    ')
  puts

  listener_rules = listeners.flat_map do |listener|
    listener_type = listener['ListenerType']
    next [] unless listener_type
    rules = exec('slb', "DescribeLoadBalancer#{listener_type}ListenerAttribute", "--LoadBalancerId=#{lb['LoadBalancerId']}", "--ListenerPort=#{listener['ListenerPort']}", **options).dig('Rules', 'Rule') || []
    rules.map do |rule|
      {'Listener' => listener['Description']}.merge(rule)
    end
  end

  puts '    Listener Rules:'
  puts listener_rules.table.to_s.gsub(/^/, '    ')
  puts

  acl_ids = listeners.flat_map { |listener| listener['AclIds'] || [] }.uniq
  unless acl_ids.empty?
    alc_entries = acl_ids.flat_map do |acl_id|
      attr = exec('slb', 'DescribeAccessControlListAttribute', "--AclId=#{acl_id}", **options)
      (attr.dig('AclEntrys', 'AclEntry') || []).each_with_index.map do |e, idx|
        {
          AclId: (idx.zero? ? attr['AclId'] : ''),
          AclName: (idx.zero? ? attr['AclName'] : ''),
          AclEntryIP: e['AclEntryIP'],
          AclEntryComment: e['AclEntryComment']
        }
      end + [nil]
    end
    puts '    Access Control Lists:'
    puts alc_entries[0..-2].table.to_s.gsub(/^/, '    ')
    puts
  end
end

#slb(*args, **options) ⇒ 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
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
# File 'lib/aly/app.rb', line 230

def slb(*args, **options)
  raw_out = exec('slb', 'DescribeLoadBalancers', '--pager', **options)
  selected = raw_out['LoadBalancers']['LoadBalancer'] || []

  eips = exec('vpc', 'DescribeEipAddresses', "--PageSize=#{selected.size}", **options)['EipAddresses']['EipAddress'].each_with_object({}) do |item, result|
    result[item['InstanceId']] = item['IpAddress']
  end

  listeners = (exec('slb', 'DescribeLoadBalancerListeners', '--pager', 'path=Listeners', **options)['Listeners'] || []).each_with_object({}) do |listener, result|
    instance_id = listener['LoadBalancerId']
    result[instance_id] ||= []
    result[instance_id] << listener
  end

  selected.each do |lb|
    lb['Listeners'] = listeners[lb['LoadBalancerId']] || []
  end

  if query = args.first&.split(',')
    selected = selected.select do |lb|
      lb.values_at('LoadBalancerId', 'LoadBalancerName', 'Address').compact.any? { |e| query.any? { |q| e.include?(q) } }
    end
  end

  @eip ||= exec('vpc', 'DescribeEipAddresses', '--PageSize=100', **options)['EipAddresses']['EipAddress'] || []

  eip_map = @eip.each_with_object({}) { |eip, h| h[eip['InstanceId']] = eip['IpAddress'] }
  selected.each do |slb|
    slb['Eip'] = eip_map[slb['LoadBalancerId']]
  end

  @ecs = exec('ecs', 'DescribeInstances', '--pager', **options)['Instances']['Instance'] || []
  @ecs.each do |item|
    item['PrivateIP'] = (item['NetworkInterfaces']['NetworkInterface'] || []).map { |ni| ni['PrimaryIpAddress'] }
    item['PublicIP'] = []
    if ip = item['EipAddress']['IpAddress']
      item['PublicIP'] << ip
    end
    if ips = item['PublicIpAddress']['IpAddress']
      item['PublicIP'] += ips
    end
    item['AllIPs'] = item['PrivateIP'] + item['PublicIP']
  end

  if options[:full]
    full_slb(selected, eips, **options)
  elsif options[:detail]
    selected.each do |row|
      described_load_balancer_attributes = exec('slb', 'DescribeLoadBalancerAttribute', "--LoadBalancerId=#{row['LoadBalancerId']}", **options)
      row['BackendServers'] = described_load_balancer_attributes['BackendServers']['BackendServer']

      row['Listeners'].select { |e| e['VServerGroupId'] }.each do |listener|
        vserver_group = exec('slb', 'DescribeVServerGroupAttribute', "--VServerGroupId=#{listener['VServerGroupId']}", **options)
        listener['VServerGroup'] = vserver_group
      end
    end

    puts JSON.pretty_generate(selected)
  else
    selected = selected.map do |row|
      listeners = (row['Listeners'] || []).map do |listener|
        listener_port = listener['ListenerPort']
        backend_port = listener['BackendServerPort']
        if backend_port
          "#{listener_port}:#{backend_port}"
        elsif forward_port = listener.dig('HTTPListenerConfig', 'ForwardPort')
          "#{listener_port}->#{forward_port}"
        elsif vserver_group_id = listener['VServerGroupId']
          "#{listener_port}->#{vserver_group_id}"
        end
      end.compact.join(', ')

      {
        Id: row['LoadBalancerId'],
        Name: row['LoadBalancerName'],
        Address: row['Address'],
        Eip: eips[row['LoadBalancerId']] || '',
        Listeners: listeners
      }
    end
    puts selected.table&.to_s
  end
end

#slb_contains_host?(host) ⇒ Boolean

Returns:

  • (Boolean)


314
315
316
# File 'lib/aly/app.rb', line 314

def slb_contains_host?(host)
  @slb.any? { |lb| lb['Address'] == host || lb['Eip'] == host }
end

#start(options) ⇒ Object



20
21
22
# File 'lib/aly/app.rb', line 20

def start(options)
  send(options[:command], *options[:args], **(options[:options].transform_keys(&:to_sym)))
end