Class: Zillabyte::Command::Flows

Inherits:
Base
  • Object
show all
Defined in:
lib/zillabyte/cli/flows.rb

Overview

HIDDEN: superclass for components and apps

Direct Known Subclasses

Apps, Components

Constant Summary collapse

MAX_POLL_SECONDS =
60 * 15
POLL_SLEEP =
2.0

Constants inherited from Base

Base::META_COLUMNS

Instance Attribute Summary

Attributes inherited from Base

#args, #options

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

alias_command, #api, extract_banner, extract_description, extract_help, extract_help_from_caller, extract_options, extract_summary, inherited, #initialize, method_added, namespace

Methods included from Helpers

#add_git_remote, #app, #ask, #create_git_remote, #display, #error, #extract_app_from_git_config, #extract_app_in_dir, #format_with_bang, #get_flow_name, #git, #handle_downloading_manifest, #has_git?, #longest, #read_multiline, #with_tty

Constructor Details

This class inherits a constructor from Zillabyte::Command::Base

Class Method Details

.get_info(cmd, info_file, dir, options = {}) ⇒ Object



422
423
424
425
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
453
454
455
456
457
458
459
460
461
# File 'lib/zillabyte/cli/flows.rb', line 422

def self.get_info(cmd, info_file, dir, options = {})
  type = options[:output_type]

  response = `#{cmd}`
  if($?.exitstatus == 1)

    File.delete("#{info_file}") if File.exists?(info_file)

    if options[:output_type].nil?
      exit(1)
    else
      Zillabyte::Helpers.error("error: #{response}", type)
    end
  end

  flow_info = {}
  File.open("#{info_file}", "r+").each do |line|
    line = JSON.parse(line)
    if(line["class"] == "node")
      flow_info["nodes"] << line["info"]
    elsif(line["class"] == "arc")
      flow_info["arcs"] << line["info"]
    else
      flow_info = line
      flow_info["nodes"] = []
      flow_info["arcs"] = []
    end
  end
  File.delete("#{info_file}")

  flow_info = flow_info.to_json
  if(File.exists?("#{dir}/info_to_java.in"))
    java_pipe = open("#{dir}/info_to_java.in","w+")
    java_pipe.puts(flow_info+"\n")
    java_pipe.flush
    java_pipe.close()
  end

  flow_info
end

Instance Method Details

#color_for(operation_name) ⇒ Object



625
626
627
628
# File 'lib/zillabyte/cli/flows.rb', line 625

def color_for(operation_name)
  @color_map[operation_name] ||= @all_colors[ @color_map.size % @all_colors.size ]
  @color_map[operation_name]
end

#delete ⇒ Object

flows:delete ID

Deletes a flow. If the flow is running, this command will kill it.

-f, --force # Don't ask for confirmation --output_type OUTPUT_TYPE # Specify an output type i.e. json #HIDDEN



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
372
373
374
375
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
414
415
416
417
418
419
# File 'lib/zillabyte/cli/flows.rb', line 345

def delete
  id = options[:id] || shift_argument

  if id.nil?
    id = read_name_from_conf(options)
    options[:is_name] = true
  elsif !(id =~ /^\d*$/)
    options[:is_name] = true
  end
  forced = options[:force]
  type = options[:output_type]

  if not forced

    if !type.nil?
      error("specify -f, --force to confirm deletion", type)
    end

    while true
      display "This operation cannot be undone. Are you sure you want to delete this flow? (yes/no):", false
      confirm = ask
      break if confirm == "yes" || confirm == "no"
      display "Please enter 'yes' to delete the flow or 'no' to exit"
    end

  end

  confirmed = forced || confirm == "yes"

  if confirmed
    display "Destroying flow ##{id}...please wait..." if type.nil?
    response = api.flows.create_delete(id, options)

    if response["job_id"]
      options[:job_id] = response["job_id"]
      flow_id = response["flow_id"]
      options.delete :is_name

      start = Time.now.utc
      display "Destroy request sent. Please wait..." if type.nil?

      while(Time.now.utc < start + MAX_POLL_SECONDS) do

      # Poll
        res = self.api.flows.poll_delete(flow_id, options)

        case res['status']
        when 'completed'
          if res['return']
            if type == "json"
              display "{}"
            else
              display "Flow ##{id} destroyed"
            end
          else
            throw "something is wrong: #{res}"
          end
          # success! continue below
          break
        when 'running'
          sleep(POLL_SLEEP)
        else
          throw "unknown status: #{res}"
        end

      end
    elsif response["error"]
      error(response["error"], type)
    else
      error("remote server error (f413)", type)
    end

  end

end

#errors ⇒ Object

flows:errors ID

Show recent errors generated by the flow.

--output_type OUTPUT_TYPE # Specify an output type i.e. json #HIDDEN



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
# File 'lib/zillabyte/cli/flows.rb', line 206

def errors

  # Init
  flow_id = options[:id] || shift_argument

  # No name?
  if flow_id.nil?
    flow_id = read_name_from_conf(options)
    options[:is_name] = true
  elsif !(flow_id =~ /^\d*$/)
    options[:is_name] = true
  end

  type = options[:output_type]

  # Make the request
  res = api.request(
    :expects => 200,
    :method => :get,
    :body    => options.to_json,
    :path => "/flows/#{CGI.escape(flow_id)}/errors"
  )

  # Render
  display "Recent errors:" if type.nil?
  headings = ["operation", "date", "error"]
  rows = (res.body["recent_errors"] || []).map do |row|
    if row['date']
      d = Time.at(row['date']/1000)
    else
      d = nil
    end
    [row['name'], d, row['message']]
  end
  rows.sort! do |a,b|
    a[1] <=> b[1]
  end
  color_map = {}
  colors = LogFormatter::COLORS.clone
  rows.each do |row|
    name = row[0]
    time = row[1]
    message = row[2].strip
    color_map[name] ||= colors.shift
    if time
      display "#{"* #{name} - #{time_ago_in_words(time)} ago".colorize(color_map[name])}:" if type.nil?
    else
      display "#{"* #{name}".colorize(color_map[name])}:" if type.nil?
    end
    message.split('\n').each do |sub_line|
      display "    #{sub_line}" if type.nil?
    end
  end

end

#info ⇒ Object

flows:info [DIR]

Outputs the info for the flow in the dir.

--pretty # Pretty prints the info output --directory DIR # Flow directory --output_type OUTPUT_TYPE # Specify an output type i.e. json #HIDDEN



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
# File 'lib/zillabyte/cli/flows.rb', line 308

def info

  dir = options[:directory] || shift_argument
  if dir.nil?
    dir = Dir.pwd
  else
    dir = File.expand_path(dir)
  end
  options[:directory] = dir

  info_file = "#{dir}/#{SecureRandom.uuid}"
  type = options[:output_type]

  cmd = command("--info --file #{info_file}", type, dir)
  flow_info = Zillabyte::Command::Apps.get_info(cmd, info_file, dir, options)

  if type == "json"
    puts flow_info
  else
    if options[:pretty]
      puts JSON.pretty_generate(JSON.parse(flow_info))
    else
      puts flow_info
    end
  end

  exit
end

#kill ⇒ Object

flows:kill ID

Kills the given flow.

--config CONFIG_FILE # Use the given config file --output_type OUTPUT_TYPE # Specify an output type i.e. json #HIDDEN



524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
# File 'lib/zillabyte/cli/flows.rb', line 524

def kill
  id = options[:id] || shift_argument
  type = options[:output_type]

  if id.nil?
    id = read_name_from_conf(options)
    options[:is_name] = true
  elsif !(id =~ /^\d*$/)
    options[:is_name] = true
  end

  display "Killing flow ##{id}...please wait..." if type.nil?
  response = api.flows.create_kill(id, options)

  if response["job_id"]
    options[:job_id] = response["job_id"]
    flow_id = response["flow_id"]
    options.delete :is_name

    start = Time.now.utc
    display "Kill request sent. Please wait..." if type.nil?

    while(Time.now.utc < start + MAX_POLL_SECONDS) do

      # Poll
      res = self.api.flows.poll_kill(flow_id, options)

      case res['status']
      when 'completed'
        if res['return']
          if type == "json"
            display "{}"
          else
            display "Flow ##{id} killed"
          end
        else
          throw "something is wrong: #{res}"
        end
        # success! continue below
        break
      when 'running'
        sleep(POLL_SLEEP)
     #   display ".", false
      else
        throw "unknown status: #{res}"
      end

    end
  elsif response["error"]
    error(response["error"], type)
  else
    error("remote server error (f569)", type)
  end

end

#live_run ⇒ Object

flows:live_run [OPERATION_NAME] [PIPE_NAME] [DIR]

Runs a local flow with live data.

--config CONFIG_FILE # Use the given config file --directory DIR # Flow directory --output_type OUTPUT_TYPE # Specify an output type i.e. json #HIDDEN



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
# File 'lib/zillabyte/cli/flows.rb', line 272

def live_run

  name = options[:name] || shift_argument
  type = options[:output_type]

  thread_id = options[:thread] || shift_argument || ""
  dir = options[:directory] || shift_argument
  if dir.nil?
    dir = Dir.pwd
  else
    dir = File.expand_path(dir)
  end
  options[:directory] = dir

  meta = Zillabyte::CLI::Config.get_config_info(dir, options)

  if meta.nil?
    error("could not find meta information for: #{dir}", type)
  end
 
  if(thread_id == "")
    exec(command("--execute_live --name #{name.to_s}",type, dir))
  else 
    exec(command("--execute_live --name #{name.to_s} --pipe #{dir}/#{thread_id}",type, dir))
  end
end

#logs ⇒ Object

flows:logs ID [OPERATION_NAME]

Streams logs for the flow from our cluster.

--operation OPERATION_NAME # Specify the operation to show logs for -v, --verbose LEVEL # Sets the verbosity (error, info, debug) [default: info] --output_type OUTPUT_TYPE # Specify an output type i.e. json #HIDDEN



173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# File 'lib/zillabyte/cli/flows.rb', line 173

def logs

  flow_id = options[:id] || shift_argument
  if flow_id.nil?
    flow_id = read_name_from_conf(options)
    options[:is_name] = true
  elsif !(flow_id =~ /^\d*$/)
    options[:is_name] = true
  end

  operation_id = options[:operation] || shift_argument || '_ALL_'
  category = options[:verbose] || '_ALL_'
  type = options[:output_type]

  carry_settings = {
    :category => category
  }

  display "Retrieving logs for flow ##{flow_id}...please wait..." if type.nil?
  hash = self.api.logs.get(flow_id, operation_id, options)

  fetch_logs(hash, operation_id)

end

#prep ⇒ Object

flows:prep [DIR]

Performs any necessary initialization for the flow.

--directory DIR # Flow directory --output_type OUTPUT_TYPE # Specify an output type i.e. json #HIDDEN --mode MODE # Specify development or production mode for dependencies #HIDDEN



116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/zillabyte/cli/flows.rb', line 116

def prep()
  mode, bundle_flags = case options[:mode]
  when nil, "development"
    [:development, ""]
  when "production"
    [:production, "--deployment"]
  else
    error("Unsupported mode #{options[:mode].inspect()}.  Zillabyte currently supports development and production.")
  end
  type = options[:output_type]
  dir = options[:directory] || shift_argument
  if dir.nil?
    dir = Dir.pwd
  else
    dir = File.expand_path(dir)
  end
  options[:directory] = dir
  meta = Zillabyte::CLI::Config.get_config_info(dir)

  if meta.nil?
    error("The specified directory (#{dir}) does not appear to contain a valid Zillabyte configuration file.", type)
  end

  case meta["language"]
  when "ruby"
    # Execute in the bundler context
    full_script = File.join(dir, meta["script"])
    cmd = "cd \"#{meta['home_dir']}\"; unset BUNDLE_GEMFILE; unset RUBYOPT; bundle install #{bundle_flags}"
    exec(cmd)
  when "python"
    vDir = "#{meta['home_dir']}/vEnv"
    lock_file = meta['home_dir']+"/zillabyte_thread_lock_file"
    if File.exists?(lock_file)
      sleep(1) while File.exists?(lock_file)
    else
      begin
        cmd = "touch #{lock_file}; virtualenv --clear --system-site-packages #{vDir}; PYTHONPATH=~/zb1/multilang/python/Zillabyte #{vDir}/bin/pip install -r #{meta['home_dir']}/requirements.txt"
        system cmd, :out => :out
      ensure
        File.delete(lock_file)
      end
    end
    
  when "js"
  end
  
end

#pull ⇒ Object

flows:pull ID DIR

Pulls a flow source to a directory.

--force # Pulls even if the directory exists --directory DIR # Flow directory --output_type OUTPUT_TYPE # Specify an output type i.e. json #HIDDEN

Examples:

$ zillabyte flows:pull .



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
# File 'lib/zillabyte/cli/flows.rb', line 69

def pull

  flow_id = options[:id] || shift_argument
  type = options[:output_type]

  if !(flow_id =~ /^\d*$/)
    options[:is_name] = true
  end

  dir = options[:directory] || shift_argument
  error("no directory given", type) if dir.nil?
  dir = File.expand_path(dir)
  
  error("no id given", type) if flow_id.nil?
  
  # Create if not exists..
  if File.exists?(dir)
    if Dir.entries(dir).size != 2 and options[:force].nil?
      error("target directory not empty. use --force to override", type)
    end
  else
    FileUtils.mkdir_p(dir)
  end
  
  res = api.flows.pull_to_directory flow_id, dir, session, options
  
  if res['error']
    error("error: #{res['error_message']}", type)
  else
    if type == "json"
      display "{}"
    else
      display "Flow ##{res['id']} pulled to #{dir}"
    end
  end
  
end

#status ⇒ Object

flows:status [DIR]

Fetches detailed status of the flow.

--directory DIR # Flow directory --output_type OUTPUT_TYPE # Specify an output type i.e. json #HIDDEN



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/zillabyte/cli/flows.rb', line 29

def status

  id = options[:id] || shift_argument
  type = options[:output_type]

  if id.nil?
    id = read_name_from_conf(options)
    options[:is_name] = true
  elsif !(id =~ /^\d*$/)
    options[:is_name] = true
  end

  res = api.request(
    :expects => 200,
    :method  => :get,
    :path    => "/flows/#{id}"
  )

  res.body
  if type == "json"
    display res.body.to_json
  else
    # TODO
    display res.body.to_json
  end

end

#test ⇒ Object

flows:test

Tests a local flow with sample data.

--config CONFIG_FILE # Use the given config file --input INPUT_FILE # Uses a CSV for component input (only applicable for components) --output OUTPUT_FILE # Writes sink output to a file --cycles CYCLES # Number of cycles to emit [default 1] (only applicable for apps) --directory DIR # Flow directory -i, --interactive # Interactively control input and read output (only applicable for apps)



475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
# File 'lib/zillabyte/cli/flows.rb', line 475

def test
   dir = options[:directory]
  if dir.nil?
    dir = Dir.pwd
  else
    dir = File.expand_path(dir)
  end
  options[:directory] = dir
  
  # Get the flow_type
  meta = Zillabyte::API::Flows.get_rich_meta_info_from_script(dir, session, {:test => true})
  if meta.nil? || meta["nodes"].nil?
    error "this is not a valid zillabyte app directory"
    exit
  end

  # Check that multilang version is atleast 0.1.0
  version = meta["multilang_version"] || "0.0.0"
  version_arr = version.split('.').map {|v| v.to_i}
  if version_arr.empty? || (version_arr[0] == 0 && version_arr[1] < 1)
    display "The version of zillabyte used in your application is outdated."
    display "Please use upgrade your zillabyte gem via 'bundle update zillabyte; gem cleanup zillabyte'"
    return
  end

  case meta["flow_type"]
  when "component"
    runner = Zillabyte::Runner::ComponentRunner.new()
  when "app"
    runner = Zillabyte::Runner::AppRunner.new()
  else
    # Default to App
    runner = Zillabyte::Runner::AppRunner.new()
  end

  # Start Runner
  runner.run(meta, dir, self, options)

end