Project

General

Profile

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

hammer-cli-csv / lib / hammer_cli_csv / puppet_reports.rb @ 561a8ac9

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)\
60
            .call(:index, {
61
                    :per_page => 999999
62
                  })['results'].each do |organization|
63
            @api.resource(:systems)\
64
              .call(:index, {
65
                      'per_page' => 999999,
66
                      'organization_id' => organization['id']
67
                    })['results'].each do |system|
68
              system = @api.resource(:systems)\
69
                .call(:show, {
70
                        'id' => system['uuid'],
71
                        'fields' => 'full'
72
                      })
73

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

    
116
      def import
117
        @existing = {}
118
        @host_guests = {}
119

    
120
        thread_import do |line|
121
          create_systems_from_csv(line)
122
        end
123

    
124
        print 'Updating host and guest associations...' if option_verbose?
125
        @host_guests.each do |host_id, guest_ids|
126
          @api.resource(:systems)\
127
            .call(:update, {
128
                    'id' => host_id,
129
                    'guest_ids' => guest_ids
130
                  })
131
        end
132
        puts 'done' if option_verbose?
133
      end
134

    
135
      def create_systems_from_csv(line)
136
        if !@existing[line[ORGANIZATION]]
137
          @existing[line[ORGANIZATION]] = {}
138
          @api.resource(:systems)\
139
            .call(:index, {
140
                    'organization_id' => line[ORGANIZATION],
141
                    'per_page' => 999999
142
                  })['results'].each do |system|
143
            @existing[line[ORGANIZATION]][system['name']] = system['uuid'] if system
144
          end
145
        end
146

    
147
        line[COUNT].to_i.times do |number|
148
          name = namify(line[NAME], number)
149

    
150
          # TODO: w/ @daviddavis p-r
151
          #subscriptions(line).each do |subscription|
152
          #  katello_subscription(line[ORGANIZATION], :name => subscription[:number])
153
          #end
154

    
155
          if !@existing[line[ORGANIZATION]].include? name
156
            print "Creating system '#{name}'..." if option_verbose?
157
            system_id = @api.resource(:systems)\
158
              .call(:create, {
159
                      'name' => name,
160
                      'organization_id' => line[ORGANIZATION],
161
                      'environment_id' => lifecycle_environment(line[ORGANIZATION], :name => line[ENVIRONMENT]),
162
                      'content_view_id' => lifecycle_contentview(line[ORGANIZATION], :name => line[CONTENTVIEW]),
163
                      'facts' => facts(line),
164
                      'installed_products' => products(line),
165
                      'type' => 'system'
166
                    })['uuid']
167
            @existing[line[ORGANIZATION]][name] = system_id
168
          else
169
            print "Updating system '#{name}'..." if option_verbose?
170
            puts line
171
            system_id = @api.resource(:systems)\
172
              .call(:update, {
173
                      'id' => @existing[line[ORGANIZATION]][name],
174
                      'name' => name,
175
                      'environment_id' => katello_environment(line[ORGANIZATION], :name => line[ENVIRONMENT]),
176
                      'content_view_id' => katello_contentview(line[ORGANIZATION], :name => line[CONTENTVIEW]),
177
                      'facts' => facts(line),
178
                      'installed_products' => products(line)
179
                    })['uuid']
180
          end
181

    
182
          if line[VIRTUAL] == 'Yes' && line[HOST]
183
            raise "Host system '#{line[HOST]}' not found" if !@existing[line[ORGANIZATION]][line[HOST]]
184
            @host_guests[@existing[line[ORGANIZATION]][line[HOST]]] ||= []
185
            @host_guests[@existing[line[ORGANIZATION]][line[HOST]]] << system_id
186
          end
187

    
188
          set_host_collections(system_id, line)
189

    
190
          puts 'done' if option_verbose?
191
        end
192
      rescue RuntimeError => e
193
        raise "#{e}\n       #{line}"
194
      end
195

    
196
      private
197

    
198
      def facts(line)
199
        facts = {}
200
        facts['cpu.core(s)_per_socket'] = line[CORES]
201
        facts['cpu.cpu_socket(s)'] = line[SOCKETS]
202
        facts['memory.memtotal'] = line[RAM]
203
        facts['uname.machine'] = line[ARCHITECTURE]
204
        if line[OPERATINGSYSTEM].index(' ')
205
          (facts['distribution.name'], facts['distribution.version']) = line[OPERATINGSYSTEM].split(' ')
206
        else
207
          (facts['distribution.name'], facts['distribution.version']) = ['RHEL', line[OPERATINGSYSTEM]]
208
        end
209
        facts['virt.is_guest'] = line[VIRTUAL] == 'Yes' ? true : false
210
        facts
211
      end
212

    
213
      def set_host_collections(system_id, line)
214
        CSV.parse_line(line[SYSTEMGROUPS]).each do |hostcollection_name|
215
          @api.resource(:hostcollections)\
216
            .call(:add_systems, {
217
                    'id' => katello_hostcollection(line[ORGANIZATION], :name => hostcollection_name),
218
                    'system_ids' => [system_id]
219
                  })
220
        end
221
      end
222

    
223
      def products(line)
224
        products = CSV.parse_line(line[PRODUCTS]).collect do |product_details|
225
          product = {}
226
          # TODO: these get passed straight through to candlepin; probably would be better to process in server
227
          #       to allow underscore product_id here
228
          (product['productId'], product['productName']) = product_details.split('|')
229
          product
230
        end
231
        products
232
      end
233

    
234
      def subscriptions(line)
235
        subscriptions = CSV.parse_line(line[SUBSCRIPTIONS]).collect do |subscription_details|
236
          subscription = {}
237
          (subscription[:number], subscription[:name]) = subscription_details.split('|')
238
          subscription
239
        end
240
        subscriptions
241
      end
242
    end
243
  end
244
end