Project

General

Profile

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

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

1
# Copyright (c) 2013-2014 Red Hat
2
#
3
# MIT License
4
#
5
# Permission is hereby granted, free of charge, to any person obtaining
6
# a copy of this software and associated documentation files (the
7
# "Software"), to deal in the Software without restriction, including
8
# without limitation the rights to use, copy, modify, merge, publish,
9
# distribute, sublicense, and/or sell copies of the Software, and to
10
# permit persons to whom the Software is furnished to do so, subject to
11
# the following conditions:
12
#
13
# The above copyright notice and this permission notice shall be
14
# included in all copies or substantial portions of the Software.
15
#
16
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23
#
24
#
25
# -= Activation Key CSV =-
26
#
27
# Columns
28
#   Name
29
#     - Activation key name
30
#     - May contain '%d' which will be replaced with current iteration number of Count
31
#     - eg. "group%d" -> "group1"
32
#   Count
33
#     - Number of times to iterate on this line of the CSV file
34
#   Org Label
35
#   Limit
36
#   Description
37
#
38

    
39
require 'hammer_cli'
40
require 'katello_api'
41
require 'json'
42
require 'csv'
43

    
44
module HammerCLICsv
45
  class ActivationKeysCommand < BaseCommand
46

    
47
    ORGANIZATION = 'Organization'
48
    DESCRIPTION = 'Description'
49
    LIMIT = 'Limit'
50
    ENVIRONMENT = 'Environment'
51
    CONTENTVIEW = 'Content View'
52
    SYSTEMGROUPS = 'System Groups'
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, DESCRIPTION, LIMIT, ENVIRONMENT, CONTENTVIEW,
58
                SYSTEMGROUPS, SUBSCRIPTIONS]
59
        @k_organization_api.index({:per_page => 999999})[0]['results'].each do |organization|
60
          @k_activationkey_api.index({'per_page' => 999999,
61
                                       'organization_id' => organization['label']
62
                                     })[0]['results'].each do |activationkey|
63
            puts "Writing activation key '#{activationkey['name']}'" if option_verbose?
64
            name = namify(activationkey['name'])
65
            count = 1
66
            description = activationkey['description']
67
            limit = activationkey['usage_limit'].to_i < 0 ? 'Unlimited' : sytemgroup['usage_limit']
68
            environment = activationkey['environment']['label']
69
            contentview = activationkey['content_view']['name']
70
            systemgroups = CSV.generate do |column|
71
              column << activationkey['systemGroups'].collect do |systemgroup|
72
                systemgroup['name']
73
              end
74
            end.delete!("\n") if activationkey['systemGroups']
75
            subscriptions = CSV.generate do |column|
76
              column << @k_subscription_api.index({
77
                                                    'activation_key_id' => activationkey['id']
78
                                                  })[0]['results'].collect do |subscription|
79
                amount = subscription['amount'] == 0 ? 'Automatic' : subscription['amount']
80
                "#{amount}|#{subscription['product_name']}"
81
              end
82
            end.delete!("\n")
83
            csv << [name, count, organization['label'], description, limit, environment, contentview,
84
                    systemgroups, subscriptions]
85
          end
86
        end
87
      end
88
    end
89

    
90
    def import
91
      @existing = {}
92

    
93
      thread_import do |line|
94
        create_activationkeys_from_csv(line)
95
      end
96
    end
97

    
98
    def create_activationkeys_from_csv(line)
99
      if !@existing[line[ORGANIZATION]]
100
        @existing[line[ORGANIZATION]] = {}
101
        @k_activationkey_api.index({
102
                                     'per_page' => 999999,
103
                                     'organization_id' => katello_organization(:name => line[ORGANIZATION])
104
                                   })[0]['results'].each do |activationkey|
105
          @existing[line[ORGANIZATION]][activationkey['name']] = activationkey['id'] if activationkey
106
        end
107
      end
108

    
109
      line[COUNT].to_i.times do |number|
110
        name = namify(line[NAME], number)
111

    
112
        if !@existing[line[ORGANIZATION]].include? name
113
          print "Creating activation key '#{name}'..." if option_verbose?
114
          activationkey = @k_activationkey_api.create({
115
                                      'name' => name,
116
                                      'environment_id' => katello_environment(line[ORGANIZATION],
117
                                                                              :name => line[ENVIRONMENT]),
118
                                      'content_view_id' => katello_contentview(line[ORGANIZATION],
119
                                                                               :name => line[CONTENTVIEW]),
120
                                      'description' => line[DESCRIPTION]
121
                                    })[0]
122
          @existing[line[ORGANIZATION]][activationkey['name']] = activationkey['id']
123
        else
124
          print "Updating activation key '#{name}'..." if option_verbose?
125
          activationkey = @k_activationkey_api.update({
126
                                        'id' => @existing[line[ORGANIZATION]][name],
127
                                        'name' => name,
128
                                        'environment_id' => katello_environment(line[ORGANIZATION],
129
                                                                                :name => line[ENVIRONMENT]),
130
                                        'content_view_id' => katello_contentview(line[ORGANIZATION],
131
                                                                                 :name => line[CONTENTVIEW]),
132
                                        'description' => line[DESCRIPTION]
133
                                      })[0]
134
        end
135

    
136
        update_subscriptions(activationkey, line)
137
        update_groups(activationkey, line)
138

    
139
        puts "done" if option_verbose?
140
      end
141
    end
142

    
143
    def update_groups(activationkey, line)
144
      if line[SYSTEMGROUPS] && line[SYSTEMGROUPS] != ''
145
        # TODO: note that existing system groups are not removed
146
        CSV.parse_line(line[SYSTEMGROUPS], {:skip_blanks => true}).each do |name|
147
          @k_systemgroup_api.add_activation_keys({
148
                                                   'id' => katello_systemgroup(line[ORGANIZATION], :name => name),
149
                                                   'activation_key_ids' => [activationkey['id']]
150
                                                 })
151
        end
152
      end
153
    end
154

    
155
    def update_subscriptions(activationkey, line)
156
      if line[SUBSCRIPTIONS] && line[SUBSCRIPTIONS] != ''
157
        subscriptions = CSV.parse_line(line[SUBSCRIPTIONS], {:skip_blanks => true}).collect do |subscription_details|
158
          subscription = {}
159
          (amount, name) = subscription_details.split('|')
160
          {
161
            :subscription => {
162
              :id => katello_subscription(line[ORGANIZATION], :name => name),
163
              :quantity => amount
164
            }
165
          }
166
        end
167

    
168
        # TODO: should there be a destroy_all similar to systems?
169
        @k_subscription_api.index({
170
                                  'per_page' => 999999,
171
                                  'activation_key_id' => activationkey['id']
172
                                })[0]['results'].each do |subscription|
173
          @k_subscription_api.destroy({
174
                                        'id' => subscription['id'],
175
                                        'activation_key_id' => activationkey['id']
176
                                      })
177
        end
178

    
179
        @k_subscription_api.create({
180
                                     'activation_key_id' => activationkey['id'],
181
                                     'subscriptions' => subscriptions
182
                                   })
183
      end
184
    end
185

    
186
  end
187

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