Class: Utils

Inherits:
Object
  • Object
show all
Defined in:
lib/vmfloaty/utils.rb

Class Method Summary collapse

Class Method Details

.format_host_output(hosts) ⇒ Object



51
52
53
54
55
# File 'lib/vmfloaty/utils.rb', line 51

def self.format_host_output(hosts)
  hosts.flat_map do |os, names|
    names.map { |name| "- #{name} (#{os})" }
  end.join("\n")
end

.generate_os_hash(os_args) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/vmfloaty/utils.rb', line 57

def self.generate_os_hash(os_args)
  # expects args to look like:
  # ["centos", "debian=5", "windows=1"]

  # Build vm hash where
  #
  #  [operating_system_type1 -> total,
  #   operating_system_type2 -> total,
  #   ...]
  os_types = {}
  os_args.each do |arg|
    os_arr = arg.split("=")
    if os_arr.size == 1
      # assume they didn't specify an = sign if split returns 1 size
      os_types[os_arr[0]] = 1
    else
      os_types[os_arr[0]] = os_arr[1].to_i
    end
  end
  os_types
end

.get_service_config(config, options) ⇒ Object



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
# File 'lib/vmfloaty/utils.rb', line 176

def self.get_service_config(config, options)
  # The top-level url, user, and token values in the config file are treated as defaults
  service_config = {
      'url' => config['url'],
      'user' => config['user'],
      'token' => config['token'],
      'type' => config['type'] || 'vmpooler'
  }

  if config['services']
    if options.service.nil?
      # If the user did not specify a service name at the command line, but configured services do exist,
      # use the first configured service in the list by default.
      _, values = config['services'].first
      service_config.merge! values
    else
      # If the user provided a service name at the command line, use that service if posible, or fail
      if config['services'][options.service]
        # If the service is configured but some values are missing, use the top-level defaults to fill them in
        service_config.merge! config['services'][options.service]
      else
        raise ArgumentError, "Could not find a configured service named '#{options.service}' in ~/.vmfloaty.yml"
      end
    end
  end

  # Prioritize an explicitly specified url, user, or token if the user provided one
  service_config['url'] = options.url unless options.url.nil?
  service_config['token'] = options.token unless options.token.nil?
  service_config['user'] = options.user unless options.user.nil?

  service_config
end

.get_service_object(type = '') ⇒ Object



167
168
169
170
171
172
173
174
# File 'lib/vmfloaty/utils.rb', line 167

def self.get_service_object(type = '')
  nspooler_strings = ['ns', 'nspooler', 'nonstandard', 'nonstandard_pooler']
  if nspooler_strings.include? type.downcase
    NonstandardPooler
  else
    Pooler
  end
end

.pretty_print_hosts(verbose, service, hostnames = []) ⇒ Object



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
# File 'lib/vmfloaty/utils.rb', line 79

def self.pretty_print_hosts(verbose, service, hostnames = [])
  hostnames = [hostnames] unless hostnames.is_a? Array
  hostnames.each do |hostname|
    begin
      response = service.query(verbose, hostname)
      host_data = response[hostname]

      case service.type
        when 'Pooler'
          tag_pairs = []
          unless host_data['tags'].nil?
            tag_pairs = host_data['tags'].map {|key, value| "#{key}: #{value}"}
          end
          duration = "#{host_data['running']}/#{host_data['lifetime']} hours"
           = [host_data['template'], duration, *tag_pairs]
          puts "- #{hostname}.#{host_data['domain']} (#{.join(", ")})"
        when 'NonstandardPooler'
          line = "- #{host_data['fqdn']} (#{host_data['os_triple']}"
          line += ", #{host_data['hours_left_on_reservation']}h remaining"
          unless host_data['reserved_for_reason'].empty?
            line += ", reason: #{host_data['reserved_for_reason']}"
          end
          line += ')'
          puts line
        else
          raise "Invalid service type #{service.type}"
      end
    rescue => e
      STDERR.puts("Something went wrong while trying to gather information on #{hostname}:")
      STDERR.puts(e)
    end
  end
end

.pretty_print_status(verbose, service) ⇒ Object



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
# File 'lib/vmfloaty/utils.rb', line 113

def self.pretty_print_status(verbose, service)
  status_response = service.status(verbose)

  case service.type
    when 'Pooler'
      message = status_response['status']['message']
      pools = status_response['pools']
      pools.select! {|_, pool| pool['ready'] < pool['max']} unless verbose

      width = pools.keys.map(&:length).max
      pools.each do |name, pool|
        begin
          max = pool['max']
          ready = pool['ready']
          pending = pool['pending']
          missing = max - ready - pending
          char = 'o'
          puts "#{name.ljust(width)} #{(char*ready).green}#{(char*pending).yellow}#{(char*missing).red}"
        rescue => e
          puts "#{name.ljust(width)} #{e.red}"
        end
      end
      puts message.colorize(status_response['status']['ok'] ? :default : :red)
    when 'NonstandardPooler'
      pools = status_response
      pools.delete 'ok'
      pools.select! {|_, pool| pool['available_hosts'] < pool['total_hosts']} unless verbose

      width = pools.keys.map(&:length).max
      pools.each do |name, pool|
        begin
          max = pool['total_hosts']
          ready = pool['available_hosts']
          pending = pool['pending'] || 0 # not available for nspooler
          missing = max - ready - pending
          char = 'o'
          puts "#{name.ljust(width)} #{(char*ready).green}#{(char*pending).yellow}#{(char*missing).red}"
        rescue => e
          puts "#{name.ljust(width)} #{e.red}"
        end
      end
    else
      raise "Invalid service type #{service.type}"
  end
end

.standardize_hostnames(response_body) ⇒ Object

TODO: Takes the json response body from an HTTP GET request and “pretty prints” it



7
8
9
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
40
41
42
43
44
45
46
47
48
49
# File 'lib/vmfloaty/utils.rb', line 7

def self.standardize_hostnames(response_body)
  # vmpooler response body example when `floaty get` arguments are `ubuntu-1610-x86_64=2 centos-7-x86_64`:
  # {
  #   "ok": true,
  #   "domain": "delivery.mycompany.net",
  #   "ubuntu-1610-x86_64": {
  #     "hostname": ["gdoy8q3nckuob0i", "ctnktsd0u11p9tm"]
  #   },
  #   "centos-7-x86_64": {
  #     "hostname": "dlgietfmgeegry2"
  #   }
  # }

  # nonstandard pooler response body example when `floaty get` arguments are `solaris-11-sparc=2 ubuntu-16.04-power8`:
  # {
  #   "ok": true,
  #   "solaris-10-sparc": {
  #     "hostname": ["sol10-10.delivery.mycompany.net", "sol10-11.delivery.mycompany.net"]
  #   },
  #   "ubuntu-16.04-power8": {
  #     "hostname": "power8-ubuntu1604-6.delivery.mycompany.net"
  #   }
  # }

  unless response_body.delete('ok')
    raise ArgumentError, "Bad GET response passed to format_hosts: #{response_body.to_json}"
  end

  # vmpooler reports the domain separately from the hostname
  domain = response_body.delete('domain')

  result = {}

  response_body.each do |os, value|
    hostnames = Array(value['hostname'])
    if domain
      hostnames.map! {|host| "#{host}.#{domain}"}
    end
    result[os] = hostnames
  end

  result
end

.strip_heredoc(str) ⇒ Object

Adapted from ActiveSupport



160
161
162
163
164
165
# File 'lib/vmfloaty/utils.rb', line 160

def self.strip_heredoc(str)
  min_indent = str.scan(/^[ \t]*(?=\S)/).min
  min_indent_size = min_indent.nil? ? 0 : min_indent.size

  str.gsub(/^[ \t]{#{min_indent_size}}/, '')
end