Project

General

Profile

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

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

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 ActivationKeysCommand < BaseCommand
33

    
34
    ORGANIZATION = 'Organization'
35
    DESCRIPTION = 'Description'
36
    LIMIT = 'Limit'
37
    ENVIRONMENT = 'Environment'
38
    CONTENTVIEW = 'Content View'
39
    SYSTEMGROUPS = 'System Groups'
40
    SUBSCRIPTIONS = 'Subscriptions'
41

    
42
    def export
43
      CSV.open(option_csv_file || '/dev/stdout', 'wb', {:force_quotes => false}) do |csv|
44
        csv << [NAME, COUNT, ORGANIZATION, DESCRIPTION, LIMIT, ENVIRONMENT, CONTENTVIEW,
45
                SYSTEMGROUPS, SUBSCRIPTIONS]
46
        @api.resource(:organizations).call(:index, {:per_page => 999999})['results'].each do |organization|
47
          @api.resource(:activation_keys).call(:index, {'per_page' => 999999,
48
                                       'organization_id' => organization['label']
49
                                     })['results'].each do |activationkey|
50
            puts "Writing activation key '#{activationkey['name']}'" if option_verbose?
51
            name = namify(activationkey['name'])
52
            count = 1
53
            description = activationkey['description']
54
            limit = activationkey['usage_limit'].to_i < 0 ? 'Unlimited' : sytemgroup['usage_limit']
55
            environment = activationkey['environment']['label']
56
            contentview = activationkey['content_view']['name']
57
            systemgroups = CSV.generate do |column|
58
              column << activationkey['systemGroups'].collect do |systemgroup|
59
                systemgroup['name']
60
              end
61
            end.delete!("\n") if activationkey['systemGroups']
62
            subscriptions = CSV.generate do |column|
63
              column << @api.resource(:subscriptions).call(:index, {
64
                                                    'activation_key_id' => activationkey['id']
65
                                                  })['results'].collect do |subscription|
66
                amount = subscription['amount'] == 0 ? 'Automatic' : subscription['amount']
67
                "#{amount}|#{subscription['product_name']}"
68
              end
69
            end.delete!("\n")
70
            csv << [name, count, organization['label'], description, limit, environment, contentview,
71
                    systemgroups, 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' => katello_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' => katello_environment(line[ORGANIZATION],
104
                                                                              :name => line[ENVIRONMENT]),
105
                                      'content_view_id' => katello_contentview(line[ORGANIZATION],
106
                                                                               :name => line[CONTENTVIEW]),
107
                                      'description' => line[DESCRIPTION]
108
                                    })
109
          @existing[line[ORGANIZATION]][activationkey['name']] = activationkey['id']
110
        else
111
          print "Updating activation key '#{name}'..." if option_verbose?
112
          activationkey = @api.resource(:activation_keys).call(:update, {
113
                                        'id' => @existing[line[ORGANIZATION]][name],
114
                                        'name' => name,
115
                                        'environment_id' => katello_environment(line[ORGANIZATION],
116
                                                                                :name => line[ENVIRONMENT]),
117
                                        'content_view_id' => katello_contentview(line[ORGANIZATION],
118
                                                                                 :name => line[CONTENTVIEW]),
119
                                        'description' => line[DESCRIPTION]
120
                                      })
121
        end
122

    
123
        update_subscriptions(activationkey, line)
124
        update_groups(activationkey, line)
125

    
126
        puts "done" if option_verbose?
127
      end
128
    end
129

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

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

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

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

    
173
  end
174

    
175
  HammerCLI::MainCommand.subcommand("csv:activationkeys", "import/export activation keys", HammerCLICsv::ActivationKeysCommand)
176
end