Project

General

Profile

Download (9.54 KB) Statistics
| Branch: | Tag: | Revision:

hammer-cli-csv / lib / hammer_cli_csv / puppet_reports.rb @ 8c7ba4af

1
# Copyright 2013-2014 Red Hat, Inc.
2
#
3
# This software is licensed to you under the GNU General Public
4
# License as published by the Free Software Foundation; either version
5
# 2 of the License (GPLv2) or (at your option) any later version.
6
# There is NO WARRANTY for this software, express or implied,
7
# including the implied warranties of MERCHANTABILITY,
8
# NON-INFRINGEMENT, or FITNESS FOR A PARTICULAR PURPOSE. You should
9
# have received a copy of GPLv2 along with this software; if not, see
10
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
11

    
12
#
13
# -= Systems CSV =-
14
#
15
# Columns
16
#   Name
17
#     - System name
18
#     - May contain '%d' which will be replaced with current iteration number of Count
19
#     - eg. "os%d" -> "os1"
20
#   Count
21
#     - Number of times to iterate on this line of the CSV file
22
#   MAC Address
23
#     - MAC address
24
#     - May contain '%d' which will be replaced with current iteration number of Count
25
#     - eg. "FF:FF:FF:FF:FF:%02x" -> "FF:FF:FF:FF:FF:0A"
26
#     - Warning: be sure to keep count below 255 or MAC hex will exceed limit
27
#
28

    
29
require 'hammer_cli'
30
require 'json'
31
require 'csv'
32
require 'uri'
33

    
34
module HammerCLICsv
35
  class CsvCommand
36
    class PuppetReportsCommand < BaseCommand
37
      command_name 'puppet-reports'
38
      desc         'import or export puppet reports'
39

    
40
      ORGANIZATION = 'Organization'
41
      ENVIRONMENT = 'Environment'
42
      CONTENTVIEW = 'Content View'
43
      SYSTEMGROUPS = 'System Groups'
44
      VIRTUAL = 'Virtual'
45
      HOST = 'Host'
46
      OPERATINGSYSTEM = 'OS'
47
      ARCHITECTURE = 'Arch'
48
      SOCKETS = 'Sockets'
49
      RAM = 'RAM'
50
      CORES = 'Cores'
51
      SLA = 'SLA'
52
      PRODUCTS = 'Products'
53
      SUBSCRIPTIONS = 'Subscriptions'
54

    
55
      def export
56
        CSV.open(option_csv_file || '/dev/stdout', 'wb', {:force_quotes => false}) do |csv|
57
          csv << [NAME, COUNT, ORGANIZATION, ENVIRONMENT, CONTENTVIEW, SYSTEMGROUPS, VIRTUAL, HOST,
58
                  OPERATINGSYSTEM, ARCHITECTURE, SOCKETS, RAM, CORES, SLA, PRODUCTS, SUBSCRIPTIONS]
59
          @api.resource(:organizations).call(:index, {:per_page => 999999})['results'].each do |organization|
60
            @api.resource(:systems).call(:index, {
61
                                  'per_page' => 999999,
62
                                  'organization_id' => organization['id']
63
                                 })['results'].each do |system|
64
              system = @api.resource(:systems).call(:show, {
65
                                            'id' => system['uuid'],
66
                                            'fields' => 'full'
67
                                          })
68

    
69
              name = system['name']
70
              count = 1
71
              organization_label = organization['label']
72
              environment = system['environment']['label']
73
              contentview = system['content_view']['name']
74
              hostcollections = CSV.generate do |column|
75
                column << system['systemGroups'].collect do |hostcollection|
76
                  hostcollection['name']
77
                end
78
              end.delete!("\n")
79
              virtual = system['facts']['virt.is_guest'] == 'true' ? 'Yes' : 'No'
80
              host = system['host']
81
              operatingsystem = "#{system['facts']['distribution.name']} " if system['facts']['distribution.name']
82
              operatingsystem += system['facts']['distribution.version'] if system['facts']['distribution.version']
83
              architecture = system['facts']['uname.machine']
84
              sockets = system['facts']['cpu.cpu_socket(s)']
85
              ram = system['facts']['memory.memtotal']
86
              cores = system['facts']['cpu.core(s)_per_socket']
87
              sla = ''
88
              products = CSV.generate do |column|
89
                column << system['installedProducts'].collect do |product|
90
                  "#{product['productId']}|#{product['productName']}"
91
                end
92
              end.delete!("\n")
93
              subscriptions = CSV.generate do |column|
94
                column << @api.resource(:subscriptions).call(:index, {
95
                                                      'system_id' => system['uuid']
96
                                                    })['results'].collect do |subscription|
97
                  "#{subscription['product_id']}|#{subscription['product_name']}"
98
                end
99
              end.delete!("\n")
100
              csv << [name, count, organization_label, environment, contentview, hostcollections, virtual, host,
101
                      operatingsystem, architecture, sockets, ram, cores, sla, products, subscriptions]
102
            end
103
          end
104
        end
105
      end
106

    
107
      def import
108
        @existing = {}
109
        @host_guests = {}
110

    
111
        thread_import do |line|
112
          create_systems_from_csv(line)
113
        end
114

    
115
        print 'Updating host and guest associations...' if option_verbose?
116
        @host_guests.each do |host_id, guest_ids|
117
          @api.resource(:systems).call(:update, {
118
                                 'id' => host_id,
119
                                 'guest_ids' => guest_ids
120
                               })
121
        end
122
        puts 'done' if option_verbose?
123
      end
124

    
125
      def create_systems_from_csv(line)
126
        if !@existing[line[ORGANIZATION]]
127
          @existing[line[ORGANIZATION]] = {}
128
          @api.resource(:systems).call(:index, {'organization_id' => line[ORGANIZATION], 'page_size' => 999999})['results'].each do |system|
129
            @existing[line[ORGANIZATION]][system['name']] = system['uuid'] if system
130
          end
131
        end
132

    
133
        line[COUNT].to_i.times do |number|
134
          name = namify(line[NAME], number)
135

    
136
          # TODO w/ @daviddavis p-r
137
          #subscriptions(line).each do |subscription|
138
          #  katello_subscription(line[ORGANIZATION], :name => subscription[:number])
139
          #end
140

    
141
          if !@existing[line[ORGANIZATION]].include? name
142
            print "Creating system '#{name}'..." if option_verbose?
143
            system_id = @api.resource(:systems).call(:create, {
144
                                   'name' => name,
145
                                   'organization_id' => line[ORGANIZATION],
146
                                   'environment_id' => lifecycle_environment(line[ORGANIZATION], :name => line[ENVIRONMENT]),
147
                                   'content_view_id' => lifecycle_contentview(line[ORGANIZATION], :name => line[CONTENTVIEW]),
148
                                   'facts' => facts(line),
149
                                   'installed_products' => products(line),
150
                                   'type' => 'system'
151
                                 })['uuid']
152
            @existing[line[ORGANIZATION]][name] = system_id
153
          else
154
            print "Updating system '#{name}'..." if option_verbose?
155
            puts line
156
            system_id = @api.resource(:systems).call(:update, {
157
                                   'id' => @existing[line[ORGANIZATION]][name],
158
                                   'name' => name,
159
                                   'environment_id' => katello_environment(line[ORGANIZATION], :name => line[ENVIRONMENT]),
160
                                   'content_view_id' => katello_contentview(line[ORGANIZATION], :name => line[CONTENTVIEW]),
161
                                   'facts' => facts(line),
162
                                   'installed_products' => products(line)
163
                                 })['uuid']
164
          end
165

    
166
          if line[VIRTUAL] == 'Yes' && line[HOST]
167
            raise "Host system '#{line[HOST]}' not found" if !@existing[line[ORGANIZATION]][line[HOST]]
168
            @host_guests[@existing[line[ORGANIZATION]][line[HOST]]] ||= []
169
            @host_guests[@existing[line[ORGANIZATION]][line[HOST]]] << system_id
170
          end
171

    
172
          set_host_collections(system_id, line)
173

    
174
          puts 'done' if option_verbose?
175
        end
176
      rescue RuntimeError => e
177
        raise "#{e}\n       #{line}"
178
      end
179

    
180
      private
181

    
182
      def facts(line)
183
        facts = {}
184
        facts['cpu.core(s)_per_socket'] = line[CORES]
185
        facts['cpu.cpu_socket(s)'] = line[SOCKETS]
186
        facts['memory.memtotal'] = line[RAM]
187
        facts['uname.machine'] = line[ARCHITECTURE]
188
        if line[OPERATINGSYSTEM].index(' ')
189
          (facts['distribution.name'], facts['distribution.version']) = line[OPERATINGSYSTEM].split(' ')
190
        else
191
          (facts['distribution.name'], facts['distribution.version']) = ['RHEL', line[OPERATINGSYSTEM]]
192
        end
193
        facts['virt.is_guest'] = line[VIRTUAL] == 'Yes' ? true : false
194
        facts
195
      end
196

    
197
      def set_host_collections(system_id, line)
198
        CSV.parse_line(line[SYSTEMGROUPS]).each do |hostcollection_name|
199
          @api.resource(:hostcollections).call(:add_systems, {
200
                                           'id' => katello_hostcollection(line[ORGANIZATION], :name => hostcollection_name),
201
                                           'system_ids' => [system_id]
202
                                         })
203
        end
204
      end
205

    
206
      def products(line)
207
        products = CSV.parse_line(line[PRODUCTS]).collect do |product_details|
208
          product = {}
209
          # TODO: these get passed straight through to candlepin; probably would be better to process in server
210
          #       to allow underscore product_id here
211
          (product['productId'], product['productName']) = product_details.split('|')
212
          product
213
        end
214
        products
215
      end
216

    
217
      def subscriptions(line)
218
        subscriptions = CSV.parse_line(line[SUBSCRIPTIONS]).collect do |subscription_details|
219
          subscription = {}
220
          (subscription[:number], subscription[:name]) = subscription_details.split('|')
221
          subscription
222
        end
223
        subscriptions
224
      end
225
    end
226
  end
227
end