Project

General

Profile

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

hammer-cli-csv / lib / hammer_cli_csv / activation_keys.rb @ d0d41780

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

    
35
      command_name "activation-keys"
36
      desc         "import or export activation keys"
37

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

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

    
81
      def import
82
        @existing = {}
83

    
84
        thread_import do |line|
85
          create_activationkeys_from_csv(line)
86
        end
87
      end
88

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

    
100
        line[COUNT].to_i.times do |number|
101
          name = namify(line[NAME], number)
102

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

    
129
          update_subscriptions(activationkey, line)
130
          update_groups(activationkey, line)
131

    
132
          puts "done" if option_verbose?
133
        end
134
      end
135

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

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

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

    
170
          @api.resource(:subscriptions).call(:create, {
171
                                               'activation_key_id' => activationkey['id'],
172
                                               'subscriptions' => subscriptions
173
                                             })
174
        end
175
      end
176

    
177
      def usage_limit(limit)
178
        Integer(limit) rescue -1
179
      end
180
    end
181
  end
182
end