Project

General

Profile

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

hammer-cli-csv / lib / hammer_cli_csv / activation_keys.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
# -= Activation Key CSV =-
14
#
15
# Columns
16
#   Name
17
#     - Activation key name
18
#     - May contain '%d' which will be replaced with current iteration number of Count
19
#     - eg. "group%d" -> "group1"
20
#   Count
21
#     - Number of times to iterate on this line of the CSV file
22
#   Org Label
23
#   Limit
24
#   Description
25
#
26

    
27
require 'hammer_cli'
28
require 'json'
29
require 'csv'
30

    
31
module HammerCLICsv
32
  class CsvCommand
33
    class ActivationKeysCommand < BaseCommand
34
      command_name 'activation-keys'
35
      desc         'import or export activation keys'
36

    
37
      ORGANIZATION = 'Organization'
38
      DESCRIPTION = 'Description'
39
      LIMIT = 'Limit'
40
      ENVIRONMENT = 'Environment'
41
      CONTENTVIEW = 'Content View'
42
      SYSTEMGROUPS = 'System Groups'
43
      SUBSCRIPTIONS = 'Subscriptions'
44

    
45
      def export
46
        CSV.open(option_csv_file || '/dev/stdout', 'wb', {:force_quotes => false}) do |csv|
47
          csv << [NAME, COUNT, ORGANIZATION, DESCRIPTION, LIMIT, ENVIRONMENT, CONTENTVIEW,
48
                  SYSTEMGROUPS, SUBSCRIPTIONS]
49
          @api.resource(:organizations).call(:index, {:per_page => 999999})['results'].each do |organization|
50
            @api.resource(:activation_keys).call(:index, {'per_page' => 999999,
51
                                                   'organization_id' => organization['id']
52
                                                 })['results'].each do |activationkey|
53
              puts "Writing activation key '#{activationkey['name']}'" if option_verbose?
54
              name = namify(activationkey['name'])
55
              count = 1
56
              description = activationkey['description']
57
              limit = activationkey['usage_limit'].to_i < 0 ? 'Unlimited' : sytemgroup['usage_limit']
58
              environment = activationkey['environment']['label']
59
              contentview = activationkey['content_view']['name']
60
              hostcollections = export_column(activationkey, 'systemGroups', 'name')
61
              subscriptions = CSV.generate do |column|
62
                column << @api.resource(:subscriptions).call(:index, {
63
                                                      'activation_key_id' => activationkey['id']
64
                                                    })['results'].collect do |subscription|
65
                  amount = subscription['amount'] == 0 ? 'Automatic' : subscription['amount']
66
                  "#{amount}|#{subscription['product_name']}"
67
                end
68
              end
69
              subscriptions.delete!("\n")
70
              csv << [name, count, organization['label'], description, limit, environment, contentview,
71
                      hostcollections, subscriptions]
72
            end
73
          end
74
        end
75
      end
76

    
77
      def import
78
        @existing = {}
79

    
80
        thread_import do |line|
81
          create_activationkeys_from_csv(line)
82
        end
83
      end
84

    
85
      def create_activationkeys_from_csv(line)
86
        if !@existing[line[ORGANIZATION]]
87
          @existing[line[ORGANIZATION]] = {}
88
          @api.resource(:activation_keys).call(:index, {
89
                                       'per_page' => 999999,
90
                                       'organization_id' => foreman_organization(:name => line[ORGANIZATION])
91
                                     })['results'].each do |activationkey|
92
            @existing[line[ORGANIZATION]][activationkey['name']] = activationkey['id'] if activationkey
93
          end
94
        end
95

    
96
        line[COUNT].to_i.times do |number|
97
          name = namify(line[NAME], number)
98

    
99
          if !@existing[line[ORGANIZATION]].include? name
100
            print "Creating activation key '#{name}'..." if option_verbose?
101
            activationkey = @api.resource(:activation_keys).call(:create, {
102
                                        'name' => name,
103
                                        'environment_id' => lifecycle_environment(line[ORGANIZATION],
104
                                                                                :name => line[ENVIRONMENT]),
105
                                        'content_view_id' => katello_contentview(line[ORGANIZATION],
106
                                                                                 :name => line[CONTENTVIEW]),
107
                                        'description' => line[DESCRIPTION],
108
                                        'usage_limit' => usage_limit(line[LIMIT])
109
                                      })
110
            @existing[line[ORGANIZATION]][activationkey['name']] = activationkey['id']
111
          else
112
            print "Updating activation key '#{name}'..." if option_verbose?
113
            activationkey = @api.resource(:activation_keys).call(:update, {
114
                                          'id' => @existing[line[ORGANIZATION]][name],
115
                                          'name' => name,
116
                                          'environment_id' => lifecycle_environment(line[ORGANIZATION],
117
                                                                                  :name => line[ENVIRONMENT]),
118
                                          'content_view_id' => katello_contentview(line[ORGANIZATION],
119
                                                                                   :name => line[CONTENTVIEW]),
120
                                          'description' => line[DESCRIPTION],
121
                                          'usage_limit' => usage_limit(line[LIMIT])
122
                                        })
123
          end
124

    
125
          update_subscriptions(activationkey, line)
126
          update_groups(activationkey, line)
127

    
128
          puts 'done' if option_verbose?
129
        end
130
      end
131

    
132
      def update_groups(activationkey, line)
133
        if line[SYSTEMGROUPS] && line[SYSTEMGROUPS] != ''
134
          # TODO: note that existing system groups are not removed
135
          CSV.parse_line(line[SYSTEMGROUPS], {:skip_blanks => true}).each do |name|
136
            @api.resource(:host_collections).call(:add_activation_keys, {
137
                                                     'id' => katello_hostcollection(line[ORGANIZATION], :name => name),
138
                                                     'activation_key_ids' => [activationkey['id']]
139
                                                   })
140
          end
141
        end
142
      end
143

    
144
      def update_subscriptions(activationkey, line)
145
        if line[SUBSCRIPTIONS] && line[SUBSCRIPTIONS] != ''
146
          subscriptions = CSV.parse_line(line[SUBSCRIPTIONS], {:skip_blanks => true}).collect do |subscription_details|
147
            (amount, name) = subscription_details.split('|')
148
            {
149
              :id => katello_subscription(line[ORGANIZATION], :name => name),
150
              :quantity => amount
151
            }
152
          end
153

    
154
          # TODO: should there be a destroy_all similar to systems?
155
          @api.resource(:subscriptions).call(:index, {
156
                                               'per_page' => 999999,
157
                                               'activation_key_id' => activationkey['id']
158
                                             })['results'].each do |subscription|
159
            @api.resource(:subscriptions).call(:destroy, {
160
                                                 'id' => subscription['id'],
161
                                                 'activation_key_id' => activationkey['id']
162
                                               })
163
          end
164

    
165
          @api.resource(:subscriptions).call(:create, {
166
                                               'activation_key_id' => activationkey['id'],
167
                                               'subscriptions' => subscriptions
168
                                             })
169
        end
170
      end
171

    
172
      def usage_limit(limit)
173
        Integer(limit) rescue -1
174
      end
175
    end
176
  end
177
end