Project

General

Profile

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

hammer-cli-csv / lib / hammer_cli_csv / base.rb @ 90d0b5c8

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
require 'apipie-bindings'
13
require 'hammer_cli'
14
require 'json'
15
require 'csv'
16
require 'hammer_cli_csv/csv'
17

    
18
module HammerCLICsv
19
  class BaseCommand < HammerCLI::Apipie::Command
20
    option %w(-v --verbose), :flag, 'be verbose'
21
    option %w(--threads), 'THREAD_COUNT', 'Number of threads to hammer with', :default => 1
22
    option %w(--csv-export), :flag, 'Export current data instead of importing'
23
    option %w(--csv-file), 'FILE_NAME', 'CSV file (default to /dev/stdout with --csv-export, otherwise required)'
24
    option %w(--prefix), 'PREFIX', 'Prefix for all name columns'
25
    option %w(--server), 'SERVER', 'Server URL'
26
    option %w(-u --username), 'USERNAME', 'Username to access server'
27
    option %w(-p --password), 'PASSWORD', 'Password to access server'
28

    
29
    NAME = 'Name'
30
    COUNT = 'Count'
31

    
32
    def execute
33
      if !option_csv_file
34
        if option_csv_export?
35
          # rubocop:disable UselessAssignment
36
          option_csv_file = '/dev/stdout'
37
        else
38
          # rubocop:disable UselessAssignment
39
          option_csv_file = '/dev/stdin'
40
        end
41
      end
42

    
43
      server = option_server ||
44
        HammerCLI::Settings.get(:csv, :host) ||
45
        HammerCLI::Settings.get(:katello, :host) ||
46
        HammerCLI::Settings.get(:foreman, :host)
47
      username = option_username ||
48
        HammerCLI::Settings.get(:csv, :username) ||
49
        HammerCLI::Settings.get(:katello, :username) ||
50
        HammerCLI::Settings.get(:foreman, :username)
51
      password = option_password ||
52
        HammerCLI::Settings.get(:csv, :password) ||
53
        HammerCLI::Settings.get(:katello, :password) ||
54
        HammerCLI::Settings.get(:foreman, :password)
55
      @api = ApipieBindings::API.new({
56
                                       :uri => server,
57
                                       :username => username,
58
                                       :password => password,
59
                                       :api_version => 2
60
                                     })
61

    
62
      option_csv_export? ? export : import
63
      HammerCLI::EX_OK
64
    end
65

    
66
    def namify(name_format, number = 0)
67
      if name_format.index('%')
68
        name = name_format % number
69
      else
70
        name = name_format
71
      end
72
      name = "#{option_prefix}#{name}" if option_prefix
73
      name
74
    end
75

    
76
    def labelize(name)
77
      name.gsub(/[^a-z0-9\-_]/i, '_')
78
    end
79

    
80
    def thread_import(return_headers = false)
81
      csv = []
82
      CSV.foreach(option_csv_file || '/dev/stdin', {
83
                                                     :skip_blanks => true,
84
                                                     :headers => :first_row,
85
                                                     :return_headers => return_headers
86
                                                   }) do |line|
87
        csv << line
88
      end
89
      lines_per_thread = csv.length / option_threads.to_i + 1
90
      splits = []
91

    
92
      option_threads.to_i.times do |current_thread|
93
        start_index = ((current_thread) * lines_per_thread).to_i
94
        finish_index = ((current_thread + 1) * lines_per_thread).to_i
95
        finish_index = csv.length if finish_index > csv.length
96
        if start_index <= finish_index
97
          lines = csv[start_index...finish_index].clone
98
          splits << Thread.new do
99
            lines.each do |line|
100
              if line[NAME][0] != '#'
101
                yield line
102
              end
103
            end
104
          end
105
        end
106
      end
107

    
108
      splits.each do |thread|
109
        thread.join
110
      end
111
    end
112

    
113
    def hammer_context
114
      {
115
        :interactive => false,
116
        :username => 'admin', # TODO: this needs to come from config/settings
117
        :password => 'changeme' # TODO: this needs to come from config/settings
118
      }
119
    end
120

    
121
    def hammer(context = nil)
122
      HammerCLI::MainCommand.new('', context || hammer_context)
123
    end
124

    
125
    def foreman_organization(options = {})
126
      @organizations ||= {}
127

    
128
      if options[:name]
129
        return nil if options[:name].nil? || options[:name].empty?
130
        options[:id] = @organizations[options[:name]]
131
        if !options[:id]
132
          organization = @api.resource(:organizations).call(:index, {
133
                                                              :per_page => 999999,
134
                                                              'search' => "name=\"#{options[:name]}\""
135
                                                            })['results']
136
          raise "Organization '#{options[:name]}' not found" if !organization || organization.empty?
137
          options[:id] = organization[0]['id']
138
          @organizations[options[:name]] = options[:id]
139
        end
140
        result = options[:id]
141
      else
142
        return nil if options[:id].nil?
143
        options[:name] = @organizations.key(options[:id])
144
        if !options[:name]
145
          organization = @api.resource(:organizations).call(:show, {'id' => options[:id]})
146
          raise "Organization 'id=#{options[:id]}' not found" if !organization || organization.empty?
147
          options[:name] = organization['name']
148
          @organizations[options[:name]] = options[:id]
149
        end
150
        result = options[:name]
151
      end
152

    
153
      result
154
    end
155

    
156
    def foreman_location(options = {})
157
      @locations ||= {}
158

    
159
      if options[:name]
160
        return nil if options[:name].nil? || options[:name].empty?
161
        options[:id] = @locations[options[:name]]
162
        if !options[:id]
163
          location = @api.resource(:locations).call(:index, {
164
                                                      :per_page => 999999,
165
                                                      'search' => "name=\"#{options[:name]}\""
166
                                                    })['results']
167
          raise "Location '#{options[:name]}' not found" if !location || location.empty?
168
          options[:id] = location[0]['id']
169
          @locations[options[:name]] = options[:id]
170
        end
171
        result = options[:id]
172
      else
173
        return nil if options[:id].nil?
174
        options[:name] = @locations.key(options[:id])
175
        if !options[:name]
176
          location = @api.resource(:locations).call(:show, {'id' => options[:id]})
177
          raise "Location 'id=#{options[:id]}' not found" if !location || location.empty?
178
          options[:name] = location['name']
179
          @locations[options[:name]] = options[:id]
180
        end
181
        result = options[:name]
182
      end
183

    
184
      result
185
    end
186

    
187
    def foreman_role(options = {})
188
      @roles ||= {}
189

    
190
      if options[:name]
191
        return nil if options[:name].nil? || options[:name].empty?
192
        options[:id] = @roles[options[:name]]
193
        if !options[:id]
194
          role = @api.resource(:roles).call(:index, {
195
                                              :per_page => 999999,
196
                                              'search' => "name=\"#{options[:name]}\""
197
                                            })['results']
198
          raise "Role '#{options[:name]}' not found" if !role || role.empty?
199
          options[:id] = role[0]['id']
200
          @roles[options[:name]] = options[:id]
201
        end
202
        result = options[:id]
203
      else
204
        return nil if options[:id].nil?
205
        options[:name] = @roles.key(options[:id])
206
        if !options[:name]
207
          role = @api.resource(:roles).call(:show, {'id' => options[:id]})
208
          raise "Role 'id=#{options[:id]}' not found" if !role || role.empty?
209
          options[:name] = role['name']
210
          @roles[options[:name]] = options[:id]
211
        end
212
        result = options[:name]
213
      end
214

    
215
      result
216
    end
217

    
218
    def foreman_permission(options = {})
219
      @permissions ||= {}
220

    
221
      if options[:name]
222
        return nil if options[:name].nil? || options[:name].empty?
223
        options[:id] = @permissions[options[:name]]
224
        if !options[:id]
225
          permission = @api.resource(:permissions).call(:index, {
226
                                                          :per_page => 999999,
227
                                                          'name' => options[:name]
228
                                                        })['results']
229
          raise "Permission '#{options[:name]}' not found" if !permission || permission.empty?
230
          options[:id] = permission[0]['id']
231
          @permissions[options[:name]] = options[:id]
232
        end
233
        result = options[:id]
234
      else
235
        return nil if options[:id].nil?
236
        options[:name] = @permissions.key(options[:id])
237
        if !options[:name]
238
          permission = @api.resource(:permissions).call(:show, {'id' => options[:id]})
239
          raise "Permission 'id=#{options[:id]}' not found" if !permission || permission.empty?
240
          options[:name] = permission['name']
241
          @permissions[options[:name]] = options[:id]
242
        end
243
        result = options[:name]
244
      end
245

    
246
      result
247
    end
248

    
249
    def foreman_filter(role, resource, search)
250
      search = nil if search && search.empty?
251
      filters = @api.resource(:filters).call(:index, {
252
                                               :per_page => 999999,
253
                                               'search' => "role=\"#{role}\""
254
                                             })['results']
255
      filters.each do |filter|
256
        resource_type = filter['resource_type'].split(':')[-1] # To remove "Katello::" when present
257
        return filter['id'] if resource_type == resource && filter['search'] == search
258
      end
259

    
260
      nil
261
    end
262

    
263
    def foreman_environment(options = {})
264
      @environments ||= {}
265

    
266
      if options[:name]
267
        return nil if options[:name].nil? || options[:name].empty?
268
        options[:id] = @environments[options[:name]]
269
        if !options[:id]
270
          environment = @api.resource(:environments).call(:index, {
271
                                                            :per_page => 999999,
272
                                                            'search' => "name=\"#{ options[:name] }\""
273
                                                          })['results']
274
          raise "Puppet environment '#{options[:name]}' not found" if !environment || environment.empty?
275
          options[:id] = environment[0]['id']
276
          @environments[options[:name]] = options[:id]
277
        end
278
        result = options[:id]
279
      else
280
        return nil if options[:id].nil?
281
        options[:name] = @environments.key(options[:id])
282
        if !options[:name]
283
          environment = @api.resource(:environments).call(:show, {'id' => options[:id]})
284
          raise "Puppet environment '#{options[:name]}' not found" if !environment || environment.empty?
285
          options[:name] = environment['name']
286
          @environments[options[:name]] = options[:id]
287
        end
288
        result = options[:name]
289
      end
290

    
291
      result
292
    end
293

    
294
    def foreman_template_kind(options = {})
295
      @template_kinds ||= {}
296

    
297
      if options[:name]
298
        return nil if options[:name].nil? || options[:name].empty?
299
        options[:id] = @template_kinds[options[:name]]
300
        if !options[:id]
301
          template_kind = @api.resource(:template_kinds).call(:index, {
302
                                              :per_page => 999999,
303
                                              'search' => "name=\"#{options[:name]}\""
304
                                            })['results']
305
          raise "Template kind '#{options[:name]}' not found" if !template_kind || template_kind.empty?
306
          options[:id] = template_kind[0]['id']
307
          @template_kinds[options[:name]] = options[:id]
308
        end
309
        result = options[:id]
310
      else
311
        return nil if options[:id].nil?
312
        options[:name] = @template_kinds.key(options[:id])
313
        if !options[:name]
314
          template_kind = @api.resource(:template_kinds).call(:show, {'id' => options[:id]})
315
          raise "Template kind 'id=#{options[:id]}' not found" if !template_kind || template_kind.empty?
316
          options[:name] = template_kind['name']
317
          @template_kinds[options[:name]] = options[:id]
318
        end
319
        result = options[:name]
320
      end
321

    
322
      result
323
    end
324

    
325
    def foreman_operatingsystem(options = {})
326
      @operatingsystems ||= {}
327

    
328
      if options[:name]
329
        return nil if options[:name].nil? || options[:name].empty?
330
        options[:id] = @operatingsystems[options[:name]]
331
        if !options[:id]
332
          (osname, major, minor) = split_os_name(options[:name])
333
          search = "name=\"#{osname}\" and major=\"#{major}\" and minor=\"#{minor}\""
334
          operatingsystems = @api.resource(:operatingsystems).call(:index, {
335
                                                                     :per_page => 999999,
336
                                                                     'search' => search
337
                                                                   })['results']
338
          operatingsystem = operatingsystems[0]
339
          raise "Operating system '#{options[:name]}' not found" if !operatingsystem || operatingsystem.empty?
340
          options[:id] = operatingsystem['id']
341
          @operatingsystems[options[:name]] = options[:id]
342
        end
343
        result = options[:id]
344
      else
345
        return nil if options[:id].nil?
346
        options[:name] = @operatingsystems.key(options[:id])
347
        if !options[:name]
348
          operatingsystem = @api.resource(:operatingsystems).call(:show, {'id' => options[:id]})
349
          raise "Operating system 'id=#{options[:id]}' not found" if !operatingsystem || operatingsystem.empty?
350
          options[:name] = build_os_name(operatingsystem['name'],
351
                                         operatingsystem['major'],
352
                                         operatingsystem['minor'])
353
          @operatingsystems[options[:name]] = options[:id]
354
        end
355
        result = options[:name]
356
      end
357

    
358
      result
359
    end
360

    
361
    def foreman_architecture(options = {})
362
      @architectures ||= {}
363

    
364
      if options[:name]
365
        return nil if options[:name].nil? || options[:name].empty?
366
        options[:id] = @architectures[options[:name]]
367
        if !options[:id]
368
          architecture = @api.resource(:architectures).call(:index, {
369
                                                              :per_page => 999999,
370
                                                              'search' => "name=\"#{options[:name]}\""
371
                                                            })['results']
372
          raise "Architecture '#{options[:name]}' not found" if !architecture || architecture.empty?
373
          options[:id] = architecture[0]['id']
374
          @architectures[options[:name]] = options[:id]
375
        end
376
        result = options[:id]
377
      else
378
        return nil if options[:id].nil?
379
        options[:name] = @architectures.key(options[:id])
380
        if !options[:name]
381
          architecture = @api.resource(:architectures).call(:show, {'id' => options[:id]})
382
          raise "Architecture 'id=#{options[:id]}' not found" if !architecture || architecture.empty?
383
          options[:name] = architecture['name']
384
          @architectures[options[:name]] = options[:id]
385
        end
386
        result = options[:name]
387
      end
388

    
389
      result
390
    end
391

    
392
    def foreman_domain(options = {})
393
      @domains ||= {}
394

    
395
      if options[:name]
396
        return nil if options[:name].nil? || options[:name].empty?
397
        options[:id] = @domains[options[:name]]
398
        if !options[:id]
399
          domain = @api.resource(:domains).call(:index, {
400
                                                  :per_page => 999999,
401
                                                  'search' => "name=\"#{options[:name]}\""
402
                                                })['results']
403
          raise "Domain '#{options[:name]}' not found" if !domain || domain.empty?
404
          options[:id] = domain[0]['id']
405
          @domains[options[:name]] = options[:id]
406
        end
407
        result = options[:id]
408
      else
409
        return nil if options[:id].nil?
410
        options[:name] = @domains.key(options[:id])
411
        if !options[:name]
412
          domain = @api.resource(:domains).call(:show, {'id' => options[:id]})
413
          raise "Domain 'id=#{options[:id]}' not found" if !domain || domain.empty?
414
          options[:name] = domain['name']
415
          @domains[options[:name]] = options[:id]
416
        end
417
        result = options[:name]
418
      end
419

    
420
      result
421
    end
422

    
423
    def foreman_partitiontable(options = {})
424
      @ptables ||= {}
425

    
426
      if options[:name]
427
        return nil if options[:name].nil? || options[:name].empty?
428
        options[:id] = @ptables[options[:name]]
429
        if !options[:id]
430
          ptable = @api.resource(:ptables).call(:index, {
431
                                                  :per_page => 999999,
432
                                                  'search' => "name=\"#{options[:name]}\""
433
                                                })['results']
434
          raise "Partition table '#{options[:name]}' not found" if !ptable || ptable.empty?
435
          options[:id] = ptable[0]['id']
436
          @ptables[options[:name]] = options[:id]
437
        end
438
        result = options[:id]
439
      elsif options[:id]
440
        return nil if options[:id].nil?
441
        options[:name] = @ptables.key(options[:id])
442
        if !options[:name]
443
          ptable = @api.resource(:ptables).call(:show, {'id' => options[:id]})
444
          options[:name] = ptable['name']
445
          @ptables[options[:name]] = options[:id]
446
        end
447
        result = options[:name]
448
      elsif !options[:name] && !options[:id]
449
        result = ''
450
      end
451

    
452
      result
453
    end
454

    
455
    def lifecycle_environment(organization, options = {})
456
      @lifecycle_environments ||= {}
457
      @lifecycle_environments[organization] ||= {
458
      }
459

    
460
      if options[:name]
461
        return nil if options[:name].nil? || options[:name].empty?
462
        options[:id] = @lifecycle_environments[organization][options[:name]]
463
        if !options[:id]
464
          @api.resource(:lifecycle_environments)\
465
            .call(:index, {
466
                    :per_page => 999999,
467
                    'organization_id' => foreman_organization(:name => organization)
468
                  })['results'].each do |environment|
469
            @lifecycle_environments[organization][environment['name']] = environment['id']
470
          end
471
          options[:id] = @lifecycle_environments[organization][options[:name]]
472
          raise "Lifecycle environment '#{options[:name]}' not found" if !options[:id]
473
        end
474
        result = options[:id]
475
      else
476
        return nil if options[:id].nil?
477
        options[:name] = @lifecycle_environments.key(options[:id])
478
        if !options[:name]
479
          environment = @api.resource(:lifecycle_environments).call(:show, {'id' => options[:id]})
480
          raise "Lifecycle environment '#{options[:name]}' not found" if !environment || environment.empty?
481
          options[:name] = environment['name']
482
          @lifecycle_environments[options[:name]] = options[:id]
483
        end
484
        result = options[:name]
485
      end
486

    
487
      result
488
    end
489

    
490
    def katello_contentview(organization, options = {})
491
      @contentviews ||= {}
492
      @contentviews[organization] ||= {}
493

    
494
      if options[:name]
495
        return nil if options[:name].nil? || options[:name].empty?
496
        options[:id] = @contentviews[organization][options[:name]]
497
        if !options[:id]
498
          @api.resource(:content_views).call(:index, {
499
                                               :per_page => 999999,
500
                                               'organization_id' => foreman_organization(:name => organization)
501
                                             })['results'].each do |contentview|
502
            @contentviews[organization][contentview['name']] = contentview['id']
503
          end
504
          options[:id] = @contentviews[organization][options[:name]]
505
          raise "Content view '#{options[:name]}' not found" if !options[:id]
506
        end
507
        result = options[:id]
508
      else
509
        return nil if options[:id].nil?
510
        options[:name] = @contentviews.key(options[:id])
511
        if !options[:name]
512
          contentview = @api.resource(:content_views).call(:show, {'id' => options[:id]})
513
          raise "Puppet contentview '#{options[:name]}' not found" if !contentview || contentview.empty?
514
          options[:name] = contentview['name']
515
          @contentviews[options[:name]] = options[:id]
516
        end
517
        result = options[:name]
518
      end
519

    
520
      result
521
    end
522

    
523
    def katello_repository(organization, options = {})
524
      @repositories ||= {}
525
      @repositories[organization] ||= {}
526

    
527
      if options[:name]
528
        return nil if options[:name].nil? || options[:name].empty?
529
        options[:id] = @repositories[organization][options[:name]]
530
        if !options[:id]
531
          @api.resource(:repositories)\
532
            .call(:index, {
533
                    :per_page => 999999,
534
                    'organization_id' => foreman_organization(:name => organization)
535
                  })['results'].each do |repository|
536
            @repositories[organization][repository['name']] = repository['id']
537
          end
538
          options[:id] = @repositories[organization][options[:name]]
539
          raise "Repository '#{options[:name]}' not found" if !options[:id]
540
        end
541
        result = options[:id]
542
      else
543
        return nil if options[:id].nil?
544
        options[:name] = @repositories.key(options[:id])
545
        if !options[:name]
546
          repository = @api.resource(:repositories).call(:show, {'id' => options[:id]})
547
          raise "Puppet repository '#{options[:name]}' not found" if !repository || repository.empty?
548
          options[:name] = repository['name']
549
          @repositoriesr[options[:name]] = options[:id]
550
        end
551
        result = options[:name]
552
      end
553

    
554
      result
555
    end
556

    
557
    def katello_subscription(organization, options = {})
558
      @subscriptions ||= {}
559
      @subscriptions[organization] ||= {}
560

    
561
      if options[:name]
562
        return nil if options[:name].nil? || options[:name].empty?
563
        options[:id] = @subscriptions[organization][options[:name]]
564
        if !options[:id]
565
          results = @api.resource(:subscriptions).call(:index, {
566
                                                         :per_page => 999999,
567
                                                         'organization_id' => foreman_organization(:name => organization),
568
                                                         'search' => "name:\"#{options[:name]}\""
569
                                                       })
570
          raise "No subscriptions match '#{options[:name]}'" if results['subtotal'] == 0
571
          raise "Too many subscriptions match '#{options[:name]}'" if results['subtotal'] > 1
572
          subscription = results['results'][0]
573
          @subscriptions[organization][options[:name]] = subscription['id']
574
          options[:id] = @subscriptions[organization][options[:name]]
575
          raise "Subscription '#{options[:name]}' not found" if !options[:id]
576
        end
577
        result = options[:id]
578
      else
579
        return nil if options[:id].nil?
580
        options[:name] = @subscriptions.key(options[:id])
581
        if !options[:name]
582
          subscription = @api.resource(:subscriptions).call(:show, {'id' => options[:id]})
583
          raise "Subscription '#{options[:name]}' not found" if !subscription || subscription.empty?
584
          options[:name] = subscription['name']
585
          @subscriptions[options[:name]] = options[:id]
586
        end
587
        result = options[:name]
588
      end
589

    
590
      result
591
    end
592

    
593
    def katello_hostcollection(organization, options = {})
594
      @hostcollections ||= {}
595
      @hostcollections[organization] ||= {}
596

    
597
      if options[:name]
598
        return nil if options[:name].nil? || options[:name].empty?
599
        options[:id] = @hostcollections[organization][options[:name]]
600
        if !options[:id]
601
          @api.resource(:host_collections).call(:index,
602
                  {
603
                    :per_page => 999999,
604
                    'organization_id' => foreman_organization(:name => organization),
605
                    'search' => "name:\"#{options[:name]}\""
606
                  })['results'].each do |hostcollection|
607
            @hostcollections[organization][hostcollection['name']] = hostcollection['id'] if hostcollection
608
          end
609
          options[:id] = @hostcollections[organization][options[:name]]
610
          raise "System group '#{options[:name]}' not found" if !options[:id]
611
        end
612
        result = options[:id]
613
      else
614
        return nil if options[:id].nil?
615
        options[:name] = @hostcollections.key(options[:id])
616
        if !options[:name]
617
          hostcollection = @api.resource(:host_collections).call(:show, {'id' => options[:id]})
618
          raise "System group '#{options[:name]}' not found" if !hostcollection || hostcollection.empty?
619
          options[:name] = hostcollection['name']
620
          @hostcollections[options[:name]] = options[:id]
621
        end
622
        result = options[:name]
623
      end
624

    
625
      result
626
    end
627

    
628
    def build_os_name(name, major, minor)
629
      name += " #{major}" if major && major != ''
630
      name += ".#{minor}" if minor && minor != ''
631
      name
632
    end
633

    
634
    # "Red Hat 6.4" => "Red Hat", "6", "4"
635
    # "Red Hat 6"   => "Red Hat", "6", ''
636
    def split_os_name(name)
637
      tokens = name.split(' ')
638
      is_number = Float(tokens[-1]) rescue false
639
      if is_number
640
        (major, minor) = tokens[-1].split('.').flatten
641
        name = tokens[0...-1].join(' ')
642
      else
643
        name = tokens.join(' ')
644
      end
645
      [name, major || '', minor || '']
646
    end
647

    
648
    def export_column(object, name, field)
649
      return '' unless object[name]
650
      values = CSV.generate do |column|
651
        column << object[name].collect do |fields|
652
          fields[field]
653
        end
654
      end
655
      values.delete!("\n")
656
    end
657

    
658
    def collect_column(column)
659
      return [] if column.nil? || column.empty?
660
      CSV.parse_line(column, {:skip_blanks => true}).collect do |value|
661
        yield value
662
      end
663
    end
664

    
665
    def pluralize(name)
666
      case name
667
      when /smart_proxy/
668
        'smart_proxies'
669
      else
670
        "#{name}s"
671
      end
672
    end
673

    
674
    def associate_organizations(id, organizations, name)
675
      return if organizations.nil?
676

    
677
      associations ||= {}
678
      CSV.parse_line(organizations).each do |organization|
679
        organization_id = foreman_organization(:name => organization)
680
        if associations[organization].nil?
681
          associations[organization] = @api.resource(:organizations).call(:show, {'id' => organization_id})[pluralize(name)].collect do |reference_object|
682
            reference_object['id']
683
          end
684
        end
685
        associations[organization] += [id] if !associations[organization].include? id
686
        @api.resource(:organizations)\
687
          .call(:update, {
688
                  'id' => organization_id,
689
                  'organization' => {
690
                    "#{name}_ids" => associations[organization]
691
                  }
692
                })
693
      end if organizations && !organizations.empty?
694
    end
695

    
696
    def associate_locations(id, locations, name)
697
      return if locations.nil?
698

    
699
      associations ||= {}
700
      CSV.parse_line(locations).each do |location|
701
        location_id = foreman_location(:name => location)
702
        if associations[location].nil?
703
          associations[location] = @api.resource(:locations).call(:show, {'id' => location_id})[pluralize(name)].collect do |reference_object|
704
            reference_object['id']
705
          end
706
        end
707
        associations[location] += [id] if !associations[location].include? id
708

    
709
        @api.resource(:locations)\
710
          .call(:update, {
711
                  'id' => location_id,
712
                  'location' => {
713
                    "#{name}_ids" => associations[location]
714
                  }
715
                })
716
      end if locations && !locations.empty?
717
    end
718
  end
719
end