Project

General

Profile

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

hammer-cli-csv / lib / hammer_cli_csv / subscriptions.rb @ 400832c6

1
require 'rest_client'
2

    
3
module HammerCLICsv
4
  class CsvCommand
5
    class SubscriptionsCommand < BaseCommand
6
      command_name 'subscriptions'
7
      desc         'import or export subscriptions'
8

    
9
      def self.supported?
10
        true
11
      end
12

    
13
      option %w(--in-portal), :flag, _('Import subscription comment lines into portal'),
14
             :hidden => true
15
      option %w(--portal-username), 'PORTAL_USERNAME', 'Portal username',
16
             :hidden => true
17
      option %w(--portal-password), 'PORTAL_PASSWORD', 'Portal password',
18
             :hidden => true
19
      option %w(--portal-hock), 'PORTAL_HOCK', 'Portal subscription creation address',
20
             :hidden => true
21
      option %w(--portal), 'PORTAL', 'Portal subscription access address',
22
             :default => "https://subscription.rhn.redhat.com:443",
23
             :hidden => true
24

    
25
      ORGANIZATION = 'Organization'
26
      MANIFEST = 'Manifest File'
27
      SUBSCRIPTION = 'Subscription Name'
28
      QUANTITY = 'Quantity'
29
      SKU = 'Product SKU'
30
      CONTRACT = 'Contract Number'
31
      ACCOUNT = 'Account Number'
32

    
33
      def export(csv)
34
        csv << [NAME, ORGANIZATION, MANIFEST, SUBSCRIPTION, QUANTITY, SKU, CONTRACT, ACCOUNT]
35
        @api.resource(:organizations).call(:index, {:per_page => 999999})['results'].each do |organization|
36
          next if option_organization && organization['name'] != option_organization
37
          organization = @api.resource(:organizations).call(:show, {'id' => organization['id']})
38
          export_manifest(csv, organization)
39
          export_subscriptions(csv, organization)
40
        end
41
      end
42

    
43
      def export_manifest(csv, organization)
44
        info = organization['owner_details']['upstreamConsumer']
45
        return if info.nil?
46

    
47
        csv << ["Manifest Name", organization['name'], info['name']]
48
        csv << ["Manifest URL", organization['name'], "https://#{info['webUrl']}#{info['uuid']}"]
49
      end
50

    
51
      def export_subscriptions(csv, organization)
52
        @api.resource(:subscriptions).call(:index, {
53
            'per_page' => 999999,
54
            'organization_id' => organization['id']
55
        })['results'].each do |subscription|
56
          next if subscription['product_id'].to_i != 0  # Red Hat subs do not have number SKU
57
          name = subscription['host'].nil? ? "Subscription" : "Guest Subscription for Host '#{subscription['host']['name']}'"
58
          quantity = subscription['quantity'] < 0 ? "Unlimited" : subscription['quantity']
59
          csv << [name, organization['name'], nil, subscription['name'],
60
                  quantity, subscription['product_id'], subscription['contract_number'],
61
                  subscription['account_number'],
62
                  subscription['start_date'], subscription['end_date']]
63
        end
64
      end
65

    
66
      def import
67
        if option_in_portal?
68
          import_into_portal
69
        else
70
          thread_import do |line|
71
            if line[NAME] == 'Manifest' && line[MANIFEST] && !line[MANIFEST].empty?
72
              import_manifest(line)
73
            end
74
          end
75
        end
76
      end
77

    
78
      def import_manifest(line)
79
        return if option_organization && line[ORGANIZATION] != option_organization
80
        args = %W{
81
          --server #{ @server } --username #{ @username } --password #{ @password }
82
          subscription upload --file #{ line[MANIFEST] }
83
          --organization-id #{ foreman_organization(:name => line[ORGANIZATION]) }
84
        }
85
        hammer.run(args)
86
      end
87

    
88
      def import_into_portal
89
        raise _("--portal-username and --portal-password required") unless option_portal_username && option_portal_password
90
        raise _("--portal required") unless option_portal
91

    
92
        @manifests = {}
93

    
94
        thread_import do |line|
95
          return if option_organization && line[ORGANIZATION] != option_organization
96

    
97
          @manifests[line[ORGANIZATION]] ||= {}
98
          import_subscription(line)
99
        end
100

    
101
        @manifests.each do |organization, manifest|
102
          print _("Downloading manifest for organization '%{organization}...") % {:organization => organization} if option_verbose?
103
          api = rest_client("/subscription/consumers/#{manifest[:manifest]['uuid']}/export")
104
          data = api.get({'accept' => 'application/zip'})
105
          filename = manifest[:file] || "#{manifest[:name]}.zip"
106
          print _("writing to file '%{filename}'...") % {:filename => filename} if option_verbose?
107
          File.open(filename, 'w') do |f|
108
            f.binmode
109
            f.write data
110
          end
111
          puts _("done") if option_verbose?
112
        end
113
      end
114

    
115
      def import_subscription(line)
116
        case line[NAME]
117
        when "Manifest Name"
118
          print _("Checking manifest '%{name}'...") % {:name => line[MANIFEST]} if option_verbose?
119
          @manifests[line[ORGANIZATION]][:name] = line[MANIFEST]
120
          @manifests[line[ORGANIZATION]][:manifest] = get_or_create_manifest(line)
121
          puts _("done") if option_verbose?
122
        when "Manifest URL"
123
          # ignore
124
        when "Manifest"
125
          @manifests[line[ORGANIZATION]][:file] = line[MANIFEST]
126
        when "Subscription"
127
          manifest = @manifests[line[ORGANIZATION]][:manifest]
128
          raise _('Manifest Name row is required before updating from Subscription rows') unless manifest
129
          line[QUANTITY] = line[QUANTITY].to_i  #guarantee integer for future calculations
130
          add_subscription(line, manifest)
131
        else
132
          # ignore
133
        end
134
      end
135

    
136
      def add_subscription(line, manifest)
137
        if find_existing_subscription(line, manifest)
138
          puts _("'%{name}' of quantity %{quantity} already attached") %
139
                  {:name => line[SUBSCRIPTION], :quantity => line[QUANTITY]} if option_verbose?
140
          return
141
        end
142
        print _("Attaching '%{name}' of quantity %{quantity}...") %
143
                {:name => line[SUBSCRIPTION], :quantity => line[QUANTITY]} if option_verbose?
144
        manifest['available_subscriptions'] ||= get_available_subscriptions(manifest)
145
        attach_subscription(line, manifest)
146
        puts _('done')
147
      end
148

    
149
      def attach_subscription(line, manifest)
150
        manifest['available_subscriptions'].each do |subscription|
151
          if subscription['productId'] == line[SKU] && subscription['quantity'] >= line[QUANTITY]
152
            api = rest_client("/subscription/consumers/#{manifest['uuid']}/entitlements?pool=#{subscription['id']}&quantity=#{line[QUANTITY]}")
153
            results = api.post({}.to_json)
154
            subscription['quantity'] -= line[QUANTITY]
155
            break
156
          end
157
        end
158
      end
159

    
160
      def get_available_subscriptions(manifest)
161
        api = rest_client("/subscription/pools/?consumer=#{manifest['uuid']}&listall=false")
162
        JSON.parse(api.get)
163
      end
164

    
165
      def find_existing_subscription(line, manifest)
166
        manifest['subscriptions'].each do |subscription|
167
          if !subscription['csv_matched'] && subscription['pool']['productId'] == line[SKU] && subscription['quantity'] == line[QUANTITY]
168
            subscription['csv_matched'] = true
169
            return true
170
          end
171
        end
172
        false
173
      end
174

    
175
      def get_or_create_manifest(line)
176
        manifest = get_existing_manifest(line)
177
        if manifest
178
          if manifest['subscriptions'].nil?
179
            api = rest_client("/subscription/consumers/#{manifest['uuid']}/entitlements")
180
            results = JSON.parse(api.get)
181
            manifest['subscriptions'] = results
182
          end
183
        else
184
          api = rest_client("/subscription/consumers?owner=#{@manifests[line[ORGANIZATION]][:owner]}")
185
          body = {
186
            'name' => line[MANIFEST],
187
            'type' => 'satellite',
188
            'facts' => {
189
              'distributor_version' => 'sat-6.0',
190
              'system.certificate_version' => '3.2'
191
            }
192
          }
193
          manifest = api.post(body.to_json,
194
              {'accept' => 'json', 'content_type' => 'application/json'}
195
          )
196
          manifest['subscriptions'] = []
197
          @manifests[line[ORGANIZATION]][:manifest] = manifest
198
        end
199
        manifest
200
      end
201

    
202
      def get_existing_manifest(line)
203
        return @manifests[line[ORGANIZATION]][:manifest] if @manifests[line[ORGANIZATION]][:manifest]
204

    
205
        unless @manifests[line[ORGANIZATION]][:owner]
206
          api = rest_client("/subscription/users/#{option_portal_username}/owners")
207
          @manifests[line[ORGANIZATION]][:owner] = JSON.parse(api.get)[0]['key']
208
        end
209

    
210
        api = rest_client("/subscription/owners/#{@manifests[line[ORGANIZATION]][:owner]}/consumers?type=satellite")
211
        response = JSON.parse(api.get).each do |manifest|
212
          if manifest['name'] == @manifests[line[ORGANIZATION]][:name]
213
            @manifests[line[ORGANIZATION]][:manifest] = manifest
214
            break
215
          end
216
        end
217
        @manifests[line[ORGANIZATION]][:manifest]
218
      end
219

    
220
      def rest_client(path)
221
        options = {
222
          :headers => {
223
            'accept' => 'application/json',
224
            'accept-language' => HammerCLI::I18n.locale,
225
            'content-type' => 'application/json'
226
          },
227
          :user => option_portal_username,
228
          :password => option_portal_password,
229
          :verify_ssl => OpenSSL::SSL::VERIFY_NONE
230
        }
231

    
232
        RestClient::Resource.new(option_portal + path, options)
233
      end
234
    end
235
  end
236
end