lib/ec2spec/client.rb in ec2spec-0.1.2 vs lib/ec2spec/client.rb in ec2spec-0.1.3

- old
+ new

@@ -1,8 +1,7 @@ -require 'ec2spec/json_formatter' -require 'ec2spec/plain_text_formatter' -require 'ec2spec/hash_formatter' +require 'ec2spec/formatter' +require 'ec2spec/price_calculator' module Ec2spec class UndefineFormatterError < StandardError; end class Client @@ -10,25 +9,38 @@ META_DATA_INSTANCE_TYPE_PATH = '/instance-type' META_DATA_INSTANCE_ID_PATH = '/instance-id' DEFAULT_REGION = 'ap-northeast-1' OUTPUT_FORMATTERS = { - plain_text: PlainTextFormatter, - json: JsonFormatter, - hash: HashFormatter, + plain_text: Formatter::PlainTextFormatter, + json: Formatter::JsonFormatter, + hash: Formatter::HashFormatter, + slack: Formatter::SlackFormatter, + markdown: Formatter::MarkdownFormatter, } + CONNECTION_ERROR_WITH_MESSAGES = { + Errno::ECONNREFUSED => 'Connection refused: %{host}', + Net::SSH::ConnectionTimeout => 'Connection timeout: %{host}', + StandardError => 'Unknown error: %{host}', + } + def initialize(hosts, days, format, region = DEFAULT_REGION) @hosts = hosts @days = days @format = format @region = region + Initializer.instance.do(region) + extend_formatter - OfferFile.instance.prepare(@region) end + def prepare_price_calculator(unit, rate, calc_type, app_id = nil) + PriceCalculator.instance.prepare(unit, rate, calc_type, app_id) + end + def run hosts = @hosts.map { |host| target(host) } threads = hosts.map do |host| Thread.start(host.backend) do |backend| exec_host_result(host, backend) @@ -49,20 +61,22 @@ raise UndefineFormatterError unless OUTPUT_FORMATTERS.key?(format_sym) extend OUTPUT_FORMATTERS[format_sym] end + def host_result(host, backend) + Ec2spec.logger.info("Finished: #{host.host}") + host.instance_type = instance_type(backend) + host.instance_id = instance_id(backend) + rescue *CONNECTION_ERROR_WITH_MESSAGES.keys => e + message = format(CONNECTION_ERROR_WITH_MESSAGES[e.class], host: host.host) + Ec2spec.logger.error(message) + host.na_values + end + def exec_host_result(host, backend) Ec2spec.logger.info("Started: #{host.host}") - - begin - host.instance_type = instance_type(backend) - host.instance_id = instance_id(backend) - rescue Errno::ECONNREFUSED - host.na_values - end - - Ec2spec.logger.info("Finished: #{host.host}") + host_result(host, backend) host end def instance_type(backend) cmd_result = backend.run_command(instance_type_cmd)