Project

General

Profile

Revision 400832c6

Added by Thomas McKay over 5 years ago

fixes #16493 - create manifest in portal

View differences:

lib/hammer_cli_csv/subscriptions.rb
1
require 'rest_client'
2

  
1 3
module HammerCLICsv
2 4
  class CsvCommand
3 5
    class SubscriptionsCommand < BaseCommand
......
8 10
        true
9 11
      end
10 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

  
11 25
      ORGANIZATION = 'Organization'
12 26
      MANIFEST = 'Manifest File'
13 27
      SUBSCRIPTION = 'Subscription Name'
......
30 44
        info = organization['owner_details']['upstreamConsumer']
31 45
        return if info.nil?
32 46

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

  
37 51
      def export_subscriptions(csv, organization)
......
40 54
            'organization_id' => organization['id']
41 55
        })['results'].each do |subscription|
42 56
          next if subscription['product_id'].to_i != 0  # Red Hat subs do not have number SKU
43
          name = subscription['host'].nil? ? "# Subscription" : "# Guest Subscription for Host '#{subscription['host']['name']}'"
57
          name = subscription['host'].nil? ? "Subscription" : "Guest Subscription for Host '#{subscription['host']['name']}'"
44 58
          quantity = subscription['quantity'] < 0 ? "Unlimited" : subscription['quantity']
45 59
          csv << [name, organization['name'], nil, subscription['name'],
46 60
                  quantity, subscription['product_id'], subscription['contract_number'],
......
50 64
      end
51 65

  
52 66
      def import
53
        thread_import do |line|
54
          if line[MANIFEST] && !line[MANIFEST].empty?
55
            import_manifest(line)
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
56 74
          end
57 75
        end
58 76
      end
......
65 83
          --organization-id #{ foreman_organization(:name => line[ORGANIZATION]) }
66 84
        }
67 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
        }
68 231

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

Also available in: Unified diff