Project

General

Profile

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

hammer-cli-csv / lib / hammer_cli_csv / subscriptions.rb @ f92e695a

1
require 'rest_client'
2

    
3
module HammerCLICsv
4
  class CsvCommand
5
    class SubscriptionsCommand < BaseCommand
6
      include ::HammerCLICsv::Utils::Subscriptions
7

    
8
      command_name 'subscriptions'
9
      desc         'import or export subscriptions'
10

    
11
      def self.supported?
12
        true
13
      end
14

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

    
27
      ORGANIZATION = 'Organization'
28
      MANIFEST = 'Manifest File'
29

    
30
      def export(csv)
31
        csv << [NAME, ORGANIZATION, MANIFEST, SUBS_NAME, SUBS_QUANTITY, SUBS_SKU, SUBS_CONTRACT, SUBS_ACCOUNT, SUBS_START, SUBS_END]
32
        @api.resource(:organizations).call(:index, {:per_page => 999999})['results'].each do |organization|
33
          next if option_organization && organization['name'] != option_organization
34
          organization = @api.resource(:organizations).call(:show, {'id' => organization['id']})
35
          export_manifest(csv, organization)
36
          export_subscriptions(csv, organization)
37
        end
38
      end
39

    
40
      def export_manifest(csv, organization)
41
        info = organization['owner_details']['upstreamConsumer']
42
        return if info.nil?
43

    
44
        csv << ["Manifest Name", organization['name'], info['name']]
45
        csv << ["Manifest URL", organization['name'], "https://#{info['webUrl']}#{info['uuid']}"]
46
      end
47

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

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

    
76
      def import_manifest(organization_name, filename)
77
        return if option_organization && organization_name != option_organization
78
        print(_("Importing manifest '%{filename}' into organization '%{organization}'...") % {:filename => filename, :organization => organization_name}) if option_verbose?
79
        args = %W{
80
          --server #{ @server } --username #{ @username } --password #{ @password }
81
          subscription upload --file #{ filename }
82
          --organization-id #{ foreman_organization(:name => organization_name) }
83
        }
84
        hammer.run(args)
85
        puts(_("done")) if option_verbose?
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
          import_manifest(organization, filename)
113
        end
114
      end
115

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

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

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

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

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

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

    
205
      def get_existing_manifest(line)
206
        return @manifests[line[ORGANIZATION]][:manifest] if @manifests[line[ORGANIZATION]][:manifest]
207

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

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

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

    
235
        RestClient::Resource.new(option_portal + path, options)
236
      end
237
    end
238
  end
239
end