cloudwatch.rb 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # frozen_string_literal: true
  2. require 'fog-aws'
  3. require 'neoinfra/cloudwatch'
  4. # NeoInfra Account information
  5. module NeoInfra
  6. # Provide informations about the accounts available
  7. class Cloudwatch
  8. def get_instance_cpu(key, secret, region, instance_id)
  9. begin
  10. stats = {:cpu_avg => -1, :cpu_max => -1}
  11. cwstats = Fog::AWS::CloudWatch.new(
  12. {
  13. :region => region,
  14. :aws_access_key_id => key,
  15. :aws_secret_access_key => secret,
  16. }
  17. )
  18. cpu_stats=cwstats.get_metric_statistics(
  19. { 'Dimensions' => [ {'Name' => 'InstanceId', 'Value' => instance_id} ],
  20. 'Namespace' => 'AWS/EC2',
  21. 'MetricName' => 'CPUUtilization',
  22. 'Statistics' => ['Average'],
  23. 'EndTime' => DateTime.now,
  24. 'StartTime' => DateTime.now-7,
  25. 'Period' => 3600
  26. }).data[:body]['GetMetricStatisticsResult']['Datapoints'].collect{|r| r['Average']}
  27. if cpu_stats.size > 0
  28. stats[:cpu_max] = cpu_stats.max
  29. stats[:cpu_avg] = cpu_stats.inject(0.0) { |sum, el| sum + el } / cpu_stats.size
  30. else
  31. stats[:cpu_max] = 0
  32. stats[:cpu_avg] = 0
  33. end
  34. return stats
  35. rescue Exception => e
  36. puts "ERR: #{e.message}: #{account[:name]},#{region} #{base_conf.inspect}"
  37. return stats
  38. end
  39. end
  40. def get_bucket_size(key, secret, region, bucket)
  41. conf = {
  42. aws_access_key_id: key,
  43. aws_secret_access_key: secret,
  44. region: region
  45. }
  46. cwstats = Fog::AWS::CloudWatch.new(conf)
  47. begin
  48. cwstats.get_metric_statistics('Statistics' => ['Maximum'],
  49. 'StartTime' => DateTime.now - 7,
  50. 'EndTime' => DateTime.now,
  51. 'Period' => 3600,
  52. 'MetricName' => 'BucketSizeBytes',
  53. 'Namespace' => 'AWS/S3',
  54. 'Dimensions' => [
  55. { 'Name' => 'BucketName', 'Value' => bucket },
  56. { 'Name' => 'StorageType', 'Value' => 'StandardStorage' }
  57. ]).data[:body]['GetMetricStatisticsResult']['Datapoints'].last['Maximum']
  58. rescue StandardError
  59. puts "Unable to get stats for #{bucket} returning -1"
  60. return -1
  61. end
  62. end
  63. end
  64. end