gce_helper.rb 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. require 'ostruct'
  2. module OpenShift
  3. module Ops
  4. class GceHelper
  5. MYDIR = File.expand_path(File.dirname(__FILE__))
  6. def self.get_list()
  7. cmd = "#{MYDIR}/../inventory/gce/gce.py --list"
  8. hosts = %x[#{cmd} 2>&1]
  9. raise "Error: failed to list hosts\n#{hosts}" unless $?.exitstatus == 0
  10. return JSON.parse(hosts)
  11. end
  12. def self.get_tag(tags, selector)
  13. tags.each do |tag|
  14. return $1 if tag =~ selector
  15. end
  16. return nil
  17. end
  18. def self.get_hosts()
  19. hosts = get_list()
  20. retval = []
  21. hosts['_meta']['hostvars'].each do |host, info|
  22. retval << OpenStruct.new({
  23. :name => info['gce_name'],
  24. :env => get_tag(info['gce_tags'], /^env-(\w+)$/) || 'UNSET',
  25. :public_ip => info['gce_public_ip'],
  26. :state => info['gce_status'],
  27. :created_by => get_tag(info['gce_tags'], /^created-by-(\w+)$/) || 'UNSET',
  28. })
  29. end
  30. retval.sort_by! { |h| [h.env, h.state, h.name] }
  31. return retval
  32. end
  33. def self.get_host_details(host)
  34. cmd = "#{MYDIR}/../inventory/gce/gce.py --host #{host}"
  35. details = %x[#{cmd} 2>&1]
  36. raise "Error: failed to get host details\n#{details}" unless $?.exitstatus == 0
  37. retval = JSON.parse(details)
  38. raise "Error: host not found [#{host}]" if retval.empty?
  39. # Convert OpenShift specific tags to entries
  40. retval['gce_tags'].each do |tag|
  41. if tag =~ /\Ahost-type-([\w\d-]+)\z/
  42. retval['host-type'] = $1
  43. end
  44. if tag =~ /\Aenv-([\w\d]+)\z/
  45. retval['env'] = $1
  46. end
  47. end
  48. return retval
  49. end
  50. def self.generate_env_tag(env)
  51. return "env-#{env}"
  52. end
  53. def self.generate_env_tag_name(env)
  54. return "tag_#{generate_env_tag(env)}"
  55. end
  56. def self.generate_host_type_tag(host_type)
  57. return "host-type-#{host_type}"
  58. end
  59. def self.generate_host_type_tag_name(host_type)
  60. return "tag_#{generate_host_type_tag(host_type)}"
  61. end
  62. def self.generate_env_host_type_tag(env, host_type)
  63. return "env-host-type-#{env}-#{host_type}"
  64. end
  65. def self.generate_env_host_type_tag_name(env, host_type)
  66. return "tag_#{generate_env_host_type_tag(env, host_type)}"
  67. end
  68. end
  69. end
  70. end