Class: Cf::Line

Inherits:
Thor
  • Object
show all
Includes:
Config, LineYamlValidator
Defined in:
lib/cf/cli/line.rb

Overview

:nodoc: all

Instance Method Summary collapse

Methods included from LineYamlValidator

#validate

Methods included from Config

#config_file, #find_home, #get_api_key, #load_config, #save_config, #set_api_key, #set_target_uri

Instance Method Details

#createObject



147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
# File 'lib/cf/cli/line.rb', line 147

def create
  line_source = Dir.pwd
  yaml_source = "#{line_source}/line.yml"

  unless File.exist?(yaml_source)
    say "The line.yml file does not exist in this directory", :red
    return
  end
  errors = validate(yaml_source)

  if errors.present?
    say("Invalid line.yml file. Correct its structure as per the errors shown below.", :red)
    errors.each {|error| say("  #{error}", :cyan)}
    exit(1)
  end

  set_target_uri(false)
  set_api_key(yaml_source)

  CF. = CF::Account.info['name']

  line_dump = YAML::load(File.read(yaml_source).strip)
  line_title = line_dump['title'].parameterize
  line_description = line_dump['description']
  line_department = line_dump['department']
  line_public = line_dump['public']
  line_priority = line_dump['priority']
  line_worker_pool = line_dump['worker_pool']
  line_prefetch_task = line_dump['prefetch_task']
  line = CF::Line.info(line_title)
  if line['error'].blank? && options.force?
    rollback(line.title)
  elsif line['error'].blank?
    say("This line already exist.", :yellow)
    override = agree("Do you want to override? [y/n] ")
    if override
      self.delete
      say("Deleting the line forcefuly..", :yellow)
      rollback(line['title'])
    else
      say("Line creation aborted!!", :yellow) and exit(1)
    end
  end
  line = CF::Line.new(line_title, line_department, {:description => line_description, :public => line_public, :priority => line_priority, :worker_pool => line_worker_pool, :prefetch_task => line_prefetch_task})
  say "Creating new assembly line: #{line.title}", :green
  say("Error: #{line.errors}", :red) and exit(1) if line.errors.present?

  say "Adding InputFormats", :green

  # Creation of InputFormat from yaml file
  input_formats = line_dump['input_formats']
  input_formats.each_with_index do |input_format, index|
    if input_format['valid_type']
      @attrs = {
        :name => input_format['name'],
        :required => input_format['required'],
        :valid_type => input_format['valid_type']
      }
    elsif input_format['valid_type'].nil?
      @attrs = {
        :name => input_format['name'],
        :required => input_format['required'],
        :valid_type => input_format['valid_type']
      }
    end
    input_format_for_line = CF::InputFormat.new(@attrs)
    input_format = line.input_formats input_format_for_line
    say_status "input", "#{@attrs[:name]}"
    display_error(line_title, "#{line.input_formats[index].errors}") if line.input_formats[index].errors.present?
  end

  # Creation of Station
  stations = line_dump['stations']
  stations.each_with_index do |station_file, s_index|
    type = station_file['station']['station_type']
    index = station_file['station']['station_index']
    input_formats_for_station = station_file['station']['input_formats']
    batch_size = station_file['station']['batch_size']
    gold_fields = station_file['station']['gold_fields']
    if type == "tournament"
      jury_worker = station_file['station']['jury_worker']
      auto_judge = station_file['station']['auto_judge']
      acceptance_ratio = station_file['station']['acceptance_ratio']
      station_params = {:line => line, :type => type, :jury_worker => jury_worker, :auto_judge => auto_judge, :input_formats => input_formats_for_station, :batch_size => batch_size, :acceptance_ratio => acceptance_ratio, :gold_fields => gold_fields}
    else
      station_params = {:line => line, :type => type, :input_formats => input_formats_for_station, :batch_size => batch_size, :gold_fields => gold_fields}
    end
    station = CF::Station.create(station_params) do |s|
      say "Adding Station #{index}: #{s.type}", :green
      display_error(line_title, "#{s.errors}") if s.errors.present?

      # For Worker
      worker = station_file['station']['worker']
      number = worker['num_workers']
      reward = worker['reward']
      worker_type = worker['worker_type']

      ##### Add badge to the station ########

      if worker_type == "human"
        badges = station_file['station']['badges']
        stat_badge = worker['stat_badge']

        human_worker =  CF::HumanWorker.new({:station => s, :number => number, :reward => reward, :badge => badges, :stat_badge => stat_badge})

        say_status "worker", "#{number} Cloud #{pluralize(number, "Worker")} with reward of #{reward} #{pluralize(reward, "cent")}"
        display_error(line_title, "#{human_worker.errors}") if human_worker.errors.present?
      elsif worker_type =~ /robot/
        settings = worker['settings']
        robot_worker = CF::RobotWorker.create({:station => s, :type => worker_type, :settings => settings})

        say_status "robot", "Robot worker: #{worker_type}"
        display_error(line_title, "#{robot_worker.errors}") if robot_worker.errors.present?
      else
        display_error(line_title, "Invalid worker type: #{worker_type}")
      end


      # Creation of Form
      # Creation of TaskForm
      if station_file['station']['task_form'].present?
        title = station_file['station']['task_form']['form_title']
        instruction = station_file['station']['task_form']['instruction']
        form = CF::TaskForm.create({:station => s, :title => title, :instruction => instruction}) do |f|

          # Creation of FormFields
          say_status "form", "TaskForm '#{f.title}'"
          display_error(line_title, "#{f.errors}") if f.errors.present?

          station_file['station']['task_form']['form_fields'].each do |form_field|
            form_field_params = form_field.merge(:form => f)
            field = CF::FormField.new(form_field_params.symbolize_keys)
            say_status "form_field", "FormField '#{field.form_field_params}'"
            display_error(line_title, field.errors) if field.errors.present?
          end

        end

      elsif station_file['station']['custom_task_form'].present?
        # Creation of CustomTaskForm
        title = station_file['station']['custom_task_form']['form_title']
        instruction = station_file['station']['custom_task_form']['instruction']

        html_file = station_file['station']['custom_task_form']['html']
        html = File.read("#{line_source}/station#{station_file['station']['station_index']}.html")
        form = CF::CustomTaskForm.create({:station => s, :title => title, :instruction => instruction, :raw_html => html})
        say_status "form", "CustomTaskForm '#{form.title}'"
        display_error(line_title, "#{form.errors}") if form.errors.present?
      end

      # print if the badge for the station exist NOTE: addition of the badge is done above.
      # it is printed here for better UI
      if badges
        say "Adding Badges For Station#{index}", :green
        badges.each do |name|
          say_status "-", "#{name}"
        end
      end

      #check the presence of gold standard and create goldstandards for the station
      gold_standards = station_file['station']['gold_standards']
      if gold_standards
        say "Adding Gold Standards to stations", :green
        if gold_standards.class == Hash
          if gold_standards["template_file"]
            gold_template_source = gold_standards["template_file"]
            if File.exist?(gold_template_source)
              gold_template = YAML::load(File.read(gold_template_source).strip)
              gold_standards.merge!("template" => gold_template)
            end
          end
        end
        if gold_standards.class == Hash#gold_standards["file"]
          gold_standard = CF::GoldStandard.new(gold_standards.merge!({:line => line,:station => s }))
          say_status "GoldStandard from file", "'#{gold_standards[:file]}'"
          display_error(line_title, "#{gold_standard.errors}") if gold_standard.errors.present?
        else
          gold_standards.each do |gold_options|
            gold_standard = CF::GoldStandard.new(gold_options.merge({:line => line,:station => s }))
            say_status "GoldStandard", "'#{gold_options["name"]}'"
            display_error(line_title, "#{gold_standard.errors}") if gold_standard.errors.present?
          end
        end
      end
    end
  end

  output_formats = line_dump['output_formats'].presence
  if output_formats
    output_format = CF::OutputFormat.new(output_formats.merge(:line => line))
    say "Adding Output Format #{output_formats}", :green
    display_error(line_title, "#{output_format.errors}") if output_format.errors.present?
  end

  #check the presence of gold standard and create goldstandards for the line
  gold_standards = line_dump['gold_standards'].presence
  if gold_standards
    say "Adding GoldStandards to Line", :green
    if gold_standards.class == Hash
      if gold_standards["template_file"]
        gold_template_source = gold_standards["template_file"]
        if File.exist?(gold_template_source)
          gold_template = YAML::load(File.read(gold_template_source).strip)
          gold_standards.merge!("template" => gold_template)
        end
      end
    end
    if gold_standards.class == Hash#gold_standards["file"]
      gold_standard = CF::GoldStandard.new(gold_standards.merge!({:line => line}))
      say_status "GoldStandard from file", "'#{gold_standards[:file]}'"
      display_error(line_title, "#{gold_standard.errors}") if gold_standard.errors.present?
    else
      gold_standards.each do |gold_options|
        gold_standard = CF::GoldStandard.new(gold_options.merge(:line => line))
        say_status "GoldStandard", "'#{gold_options["name"]}'"
        display_error(line_title, "#{gold_standard.errors}") if gold_standard.errors.present?
      end
    end
  end

  say " ☁ ☁ ☁ ☁ ☁ ☁ ☁ ☁ ☁ ☁ ☁ ☁ ☁ ☁ ☁ ☁ ☁ ☁ ☁ ☁ ☁ ☁ ☁ ☁ ☁ ☁ ☁ ☁ ☁ ☁ ☁ ☁ ☁ ☁ ☁ ☁ ☁ ☁ ☁ ☁", :white
  say "Line was successfully created.", :green
  say "View your line at http://#{CF.}.#{CF.api_url.split("/")[-2]}/lines/#{CF.}/#{line.title}", :yellow
  say "\nNow you can do production runs with: cf production start <your-run-title>", :green
end

#deleteObject



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/cf/cli/line.rb', line 54

def delete
  if options['line'].blank?
    line_source = Dir.pwd
    yaml_source = "#{line_source}/line.yml"
    say("The line.yml file does not exist in this directory", :red) and exit(1) unless File.exist?(yaml_source)
    set_target_uri(false)
    set_api_key(yaml_source)
    CF. = CF::Account.info['name']
    line_dump = YAML::load(File.read(yaml_source).strip)
    line_title = line_dump['title'].parameterize
  else
    set_target_uri(false)
    set_api_key
    CF. = CF::Account.info['name']
    line_title = options['line'].parameterize
  end

  resp_line = CF::Line.find(line_title)
  if resp_line.nil?
    say("Line does not exist entitled #{line_title} !!!", :red) and exit(1)
  else
    line = Hashie::Mash.new(resp_line)
  end
  if line.title == line_title && !resp_line.nil?
    if options.force
      CF::Line.destroy(line_title, :forced => true)
      say("The line #{line_title} deleted forcefully!", :yellow)
    else

      # Check whether this line has existing runs or not
      resp_runs = CF::Run.all({:line_title => line_title})
      if resp_runs.has_key?('total_runs') && (resp_runs['runs'] || resp_runs['test_runs'])
        say("!!! Warning !!!\nThe following are the existing production runs based on this line.", :yellow)
        existing_runs = Cf::Production.new([],{'line' => line_title, 'all' => true})
        existing_runs.list

        say("\n!!! Warning !!!\nDeleting this line will also delete all the existing production runs based on this line.\n", :yellow)
        delete_forcefully = agree("Do you still want to delete this line? [y/n] ")
        say("\n")
        if delete_forcefully
          resp = CF::Line.destroy(line_title, :forced => true)
          if resp['code'] != 200
            say("Error: #{resp.error.message}\n", :red)
          else
            say("The line #{line_title} deleted successfully!\n", :yellow)
          end
        else
          say("Line deletion aborted!\n", :cyan)
        end
      else
        CF::Line.destroy(line_title)
        say("The line #{line_title} deleted successfully!\n", :yellow)
      end
    end
  else
    say("The line #{line_title} doesn't exist!\n", :yellow)
  end
end

#detailsObject

method_option :verbose, :type => :boolean, :aliases => “-v”, :desc => “gives the detailed structure of the line”



426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
# File 'lib/cf/cli/line.rb', line 426

def details
  if options['line'].blank?
    line_source = Dir.pwd
    yaml_source = "#{line_source}/line.yml"
    say("The line.yml file does not exist in this directory", :red) and exit(1) unless File.exist?(yaml_source)
    set_target_uri(false)
    set_api_key(yaml_source)
    CF. = CF::Account.info['name']

    line_dump = YAML::load(File.read(yaml_source).strip)
    line_title = line_dump['title'].parameterize
  else
    set_target_uri(false)
    set_api_key
    CF. = CF::Account.info['name']
    line_title = options['line'].parameterize
  end

  line = CF::Line.inspect(line_title)
  line = Hashie::Mash.new(line)
  if line.error.blank?
    say("\nThe following is the structure of the line: #{line_title}\n", :green)
    ap line
  else
    say("Error: #{line.error.message}\n", :red)
  end
end

#generate(title = nil) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/cf/cli/line.rb', line 33

def generate(title=nil)
  if title.present?
    line_destination = "#{title.parameterize}"
    yaml_destination = "#{line_destination}/line.yml"
    FileUtils.rm_rf(line_destination, :verbose => true) if options.force? && File.exist?(line_destination)
    if File.exist?(line_destination)
      say "Skipping #{yaml_destination} because it already exists.\nUse the -f flag to force it to overwrite or check and delete it manually.", :red
    else
      say "Generating #{yaml_destination}", :green
      Cf::Newline.start([title, yaml_destination])
      say "A new line named #{line_destination} generated.", :green
      say "Modify the #{yaml_destination} file and you can create this line with: cf line create", :yellow
    end
  else
    say "Title for the line is required.", :red
  end
end

#listObject



376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
# File 'lib/cf/cli/line.rb', line 376

def list
  line_source = Dir.pwd
  yaml_source = "#{line_source}/line.yml"

  set_target_uri(false)
  set_api_key(yaml_source)
  CF. = CF::Account.info['name']

  if options.all
    resp_lines = CF::Line.all(:page => 'all')
    current_page = 1
  else
    if page = options['page'].presence
      resp_lines = CF::Line.all(:page => page)
      current_page = page
    else
      resp_lines = CF::Line.all
      current_page = 1
    end
  end

  lines = resp_lines['lines'].presence
  say "\n"
  say("You don't have any lines to list", :yellow) and return if lines.blank?

  if resp_lines['total_pages']
    say("Showing page #{current_page} of #{resp_lines['total_pages']}\tTotal lines: #{resp_lines['total_lines']}")
  end
  lines.sort! { |a, b| a['title'] <=> b['title'] }
  lines_table = table do |t|
    t.headings = ["Line Title", 'URL']
    lines.each do |line|
      line = Hashie::Mash.new(line)
      t << [line.title, "http://#{CF.}.cloudfactory.com/lines/#{CF.}/#{line.title.parameterize}"]
    end
  end
  say(lines_table)
end