Class: Zillabyte::Runner::ComponentOperation

Inherits:
Object
  • Object
show all
Defined in:
lib/zillabyte/runner/component_operation.rb

Overview

Emulate Component Operations

Constant Summary collapse

NEXT_MESSAGE =
"{\"command\": \"next\"}\n"
DONE_MESSAGE =
"{\"command\": \"done\"}\n"
END_CYCLE_MESSAGE =
"{\"command\": \"end_cycle\"}\n"
ENDMARKER =
"\nend\n"

Class Method Summary collapse

Class Method Details

.build_tuple_json(tuple, meta = nil, column_aliases = nil) ⇒ Object

Build a tuple and format into JSON



534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
# File 'lib/zillabyte/runner/component_operation.rb', line 534

def self.build_tuple_json(tuple, meta = nil, column_aliases = nil)
  meta ||= {}
  column_aliases ||= {}
  values = {}
  tuple.each do |k, v|
   if(k == "id")
     nextx
   elsif(k == "confidence" or k == "since" or k == "source")
     meta[k] = v
   else  
    values[k] = v
   end
  end
  tuple_json = {"tuple" => values, "meta" => meta, "column_aliases" => column_aliases}.to_json
  return tuple_json
end

.cdisplay(msg) ⇒ Object

Display a colored, formatted message



579
580
581
582
# File 'lib/zillabyte/runner/component_operation.rb', line 579

def self.cdisplay(msg)

  @__tester.cdisplay(@__name, msg)
end

.command(arg, ignore_stderr = false) ⇒ Object

Construct a multilang command



553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
# File 'lib/zillabyte/runner/component_operation.rb', line 553

def self.command(arg, ignore_stderr=false)
  cdisplay("could not extract meta information. missing zillabyte.conf.yml?") if @__meta.nil?

  full_script = File.join(@__dir, @__meta["script"])
  stderr_opt = "2> /dev/null" if ignore_stderr

  case @__meta["language"]
  when "ruby"
    # Execute in the bundler context
    cmd = "cd \"#{@__dir}\"; unset BUNDLE_GEMFILE; ZILLABYTE_HARNESS=1 bundle exec ruby \"#{full_script}\" #{arg}  #{stderr_opt}"
  when "python"#{
    if(File.directory?("#{@__dir}/vEnv"))
      cmd = "cd \"#{@__dir}\"; PYTHONPATH=~/zb1/multilang/python/Zillabyte #{@__dir}/vEnv/bin/python \"#{full_script}\" #{arg}  #{stderr_opt}"
    else
      cmd = "cd \"#{@__dir}\"; PYTHONPATH=~/zb1/multilang/python/Zillabyte python \"#{full_script}\" #{arg}  #{stderr_opt}"
    end
  when "js"
    cmd = "cd \"#{@__dir}\"; NODE_PATH=~/zb1/multilang/js/src/lib #{Zillabyte::API::NODEJS_BIN}  \"#{full_script}\" #{arg} #{stderr_opt}"
  else
    cdisplay("no language specified")
  end
  return cmd
end

.emit_consumer_tuple(stream, consumer, tuple_json) ⇒ Object

Emit tuple_json to the consumer of a stream



520
521
522
523
524
525
526
527
528
529
530
# File 'lib/zillabyte/runner/component_operation.rb', line 520

def self.emit_consumer_tuple(stream, consumer, tuple_json)
  begin
    display_json = Hash[JSON.parse(tuple_json)["tuple"].map {|k,v| [truncate_message(k), truncate_message(v)]}].to_json
  rescue JSON::ParserError
    cdisplay "Error: invalid JSON"
  end
  write_stream = get_write_stream(stream, consumer)
  write_message(write_stream, tuple_json)
  @__emit_queues[stream][consumer][:ready] = false
  cdisplay "emitted tuple #{display_json} to #{consumer} "
end

.get_consumer_tuple(stream, consumer) ⇒ Object

Get tuple for sending to consumer of stream



514
515
516
# File 'lib/zillabyte/runner/component_operation.rb', line 514

def self.get_consumer_tuple(stream, consumer)
  @__emit_queues[stream][consumer][:write_queue].shift
end

.get_write_stream(stream, consumer) ⇒ Object

Get the write pipe of the stream consumer



508
509
510
# File 'lib/zillabyte/runner/component_operation.rb', line 508

def self.get_write_stream(stream, consumer)
   @__consumer_pipes[stream][consumer][:wr_parent]
end

.handshake(write_stream, read_stream) ⇒ Object

Handshake connection to multilang



485
486
487
488
489
490
491
492
493
494
# File 'lib/zillabyte/runner/component_operation.rb', line 485

def self.handshake(write_stream, read_stream)
  begin
    write_message write_stream, HANDSHAKE_MESSAGE
    msg = read_message(read_stream)
  rescue Exception => e
    cdisplay(e)
    cdisplay("Error handshaking node")
    raise e
  end
end

.read_message(read_stream) ⇒ Object

Read a JSON message



417
418
419
420
421
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
462
463
464
# File 'lib/zillabyte/runner/component_operation.rb', line 417

def self.read_message(read_stream)

  @__read_buffers[read_stream] ||= ""
  @__read_buffered_messages[read_stream] ||= []
  if !@__read_buffered_messages[read_stream].empty?
      obj = @__read_buffered_messages[read_stream].shift
    return obj
  end

  # read message from stream
  loop do

    while !@__read_buffers[read_stream].include? ENDMARKER
      segment = read_stream.sysread(BUFSIZE)
      @__read_buffers[read_stream] << segment
    end

    read_buffer = @__read_buffers[read_stream]
    if read_buffer.include? ENDMARKER
      objs = read_buffer.split(ENDMARKER)
      ends = read_buffer.scan(ENDMARKER)
      if objs.count == ends.count # We have a full number of messages
        objs.each do |obj|
          begin
            @__read_buffered_messages[read_stream] << JSON.parse(obj)
          rescue JSON::ParserError 
            cdisplay "READMESSAGE: invalid JSON #{obj}"
          end
        end
        @__read_buffers[read_stream] = ""
        return @__read_buffered_messages[read_stream].shift
      else

        (0..ends.count-1).each do |i|
          obj = objs[i] 
          begin
            @__read_buffered_messages[read_stream] << JSON.parse(obj)
          rescue JSON::ParserError 
            cdisplay "READMESSAGE: invalid JSON #{obj}" 
          end
        end

        @__read_buffers[read_stream] = objs[ends.count..-1].join(ENDMARKER)
        return @__read_buffered_messages[read_stream].shift
      end
    end
  end
end

.run(node, dir, consumee, consumer_pipes, tester, meta, options = {}) ⇒ Object

Run the operation



19
20
21
22
23
24
25
26
27
28
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
56
57
58
# File 'lib/zillabyte/runner/component_operation.rb', line 19

def self.run(node, dir, consumee, consumer_pipes, tester, meta, options = {})


  @__node = node
  @__name = node["name"]
  @__type = node["type"]
  @__dir = dir
  @__consumee = consumee
  @__consumer_pipes = consumer_pipes
  @__tester = tester

  @__meta = meta
  @__options = options
  @__output_type = options[:output_type]

  # Each consumer of a stream gets its own queue and message passing
  @__emit_queues = {}
  @__consumer_pipes.each_pair do |stream, consumers|
    consumers.each_key do |consumer|
      @__emit_queues[stream] ||= {}
      @__emit_queues[stream][consumer] = {:write_queue => [], :ready => true}
    end
  end
  begin
    case @__type
    when "source"
      self.run_input()
    when "component"
      self.run_rpc_component()

    # Component outputs act in same manner as sinks
    else
      Zillabyte::Runner::MultilangOperation.run(node, dir, consumee, consumer_pipes, tester, meta, options)
    end
  rescue => e
    cdisplay e.message
    cdisplay e.backtrace
  end

end

.run_input ⇒ Object

Run a component input



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
112
113
114
115
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
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
# File 'lib/zillabyte/runner/component_operation.rb', line 62

def self.run_input()
  input = @__options[:input]

  # Read input from file
  if input
    messages = []
    cdisplay "reading from file...."
    csv_rows = CSV.read("#{input}")
    fields = @__node["fields"].map {|f| f.keys[0]}
    csv_rows.each do |row|
      tuple = {}
      fields.each {|f| tuple[f] = row.shift}

      tuple_json = build_tuple_json(tuple)

      @__emit_queues.each_pair do |stream, consumers|
        consumers.each_pair do |consumer, emitter|
          emitter[:write_queue] << tuple_json
        end
      end

      # Index streams and consumers by their pipes for lookup
      consumer_hash = {}
      @__emit_queues.each_pair do |stream, consumers|
        consumers.each_key do |consumer|
          read_stream = @__consumer_pipes[stream][consumer][:rd_parent]
          consumer_hash[read_stream] = {:stream => stream, :consumer => consumer}
        end
      end


      # Send first tuple
      @__emit_queues.each_pair do |stream, consumers|
        consumers.each_key do |consumer|
          tuple_json = get_consumer_tuple(stream, consumer)
          emit_consumer_tuple(stream, consumer, tuple_json)
        end
      end

      # Sent tuples to consumers as appropriate
      loop do 

        # Retrieve messages from consumers
        rs, ws, es = IO.select(consumer_hash.keys, [], [])

        # Emit tuples to consumers
        emitted = false
        rs.each do |r|

          # Read from consumer
          msg = read_message(r)

          stream = consumer_hash[r][:stream]
          consumer = consumer_hash[r][:consumer]

          # Consumer is ready for next message
          if msg["command"] && msg["command"] == "next"

            @__emit_queues[stream][consumer][:ready] = true
            tuple_json = get_consumer_tuple(stream, consumer)

            # If all messages have been sent to consumer, end their cycle
            if tuple_json.nil?
              write_stream = get_write_stream(stream, consumer)
              cdisplay "ending cycle for #{consumer}"
              write_message(write_stream, END_CYCLE_MESSAGE)
              write_message(write_stream, DONE_MESSAGE)

            else
              # Emit tuple to consumer
              emit_consumer_tuple(stream, consumer, tuple_json)
              emitted = true
            end
          end
        end

        # Exit when done emitting
        if !emitted
          return
        end
      end
    end
    
  else
    stdin = @__consumee[:rd_child]
    loop do 

      msg = stdin.gets
      if msg == "end\n"
        @__consumer_pipes.each_pair do |stream, consumers|
          consumers.each_pair do |consumer, pipe| 
            write_stream = pipe[:wr_parent]
            write_message(write_stream, END_CYCLE_MESSAGE)
            write_message(write_stream, DONE_MESSAGE)
          end
        end

        break
      end

      # Build tuple
      begin

        tuple = JSON.parse(msg)
      rescue JSON::ParserError 
        cdisplay "Error: invalid JSON"           
        next
      end


      # Check input for correct fields
      has_fields = true
      fields = @__node['fields'].flat_map {|h| h.keys}
      tuple.each_key do |field|
        if !fields.include? field
          cdisplay "Error: invalid schema for node"
          next
        end
      end
      tuple_json = build_tuple_json(tuple)
      display_json = Hash[JSON.parse(tuple_json)["tuple"].map {|k,v| [truncate_message(k), truncate_message(v)]}].to_json
      send_to_consumers(tuple_json)   
    end

  end
 
end

.run_rpc_component ⇒ Object

Send to and manage an RPC component



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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
# File 'lib/zillabyte/runner/component_operation.rb', line 192

def self.run_rpc_component()

  # Index streams and consumers by their pipes for lookup
  consumer_hash = {}
  @__emit_queues.each_pair do |stream, consumers|
    consumers.each_key do |consumer|
      read_stream = @__consumer_pipes[stream][consumer][:rd_parent]
      consumer_hash[read_stream] = {:stream => stream, :consumer => consumer}
    end
  end
  
  # Keep track of how many consumers to handle before exiting
  consumers_running = consumer_hash.keys.length

  # Begin cycle
  end_cycle_received = false


  # TODO multiple inputs
  # The input component(singular at the moment)
  read_streams = consumer_hash.keys.concat [@__consumee[:rd_child]]

  # Start communication with API
  api = @__tester.session.api
  caller = Zillabyte::API::Components.new(api)
  component_id = @__node["id"]
  output_format = @__node["output_format"]
  component_info = api.request(
    :expects  => 200,
    :method   => :get,
    :path     => "/flows/#{component_id}"
  )
  component_schema = component_info.body["schema"]
  cdisplay("error: The requested component is not properly registered.") if component_info.nil?

  component_nodes = component_schema["nodes"]
  source_nodes = []
  component_nodes.each do |node|
    source_nodes << node if node["type"] == "source"
  end
  cdisplay("error: This component has multiple input streams. Currently we only support single input streams, sorry!") if source_nodes.size > 1

  fields = source_nodes[0]["fields"]

  # Receive and handle messages
  loop do

    # Read from a stream
    rs = select_read_streams(read_streams)
    rs.each do |r|
      # Read a message
      obj = read_message(r)

      # Handle tuple through RPC
      if obj['tuple']
        cdisplay("error: The number of inputs to the component does not match the declared number for stream #{source_nodes[0]["name"]}.") if obj['tuple'].size != fields.size
        rpc_inputs = []
        fields.each do |field|
          rpc_inputs << obj['tuple'][field.keys[0]]
        end

        display_json = Hash[obj['tuple'].map{|k, v| [truncate_message(k), truncate_message(v)]}].to_json
        

        # Send RPC call
        cdisplay "sending RPC call..."
        call_options = {
          :rpc_inputs => [rpc_inputs],
          :output_format => output_format
        }

        res = caller.rpc(component_id, call_options)
        cdisplay "received API response : #{res}"

        #TODO handle errors
        if res['error']
          cdisplay("error: #{res['error']}")
          next
        end
        run_ids = []
        res['execute_ids'].each do |q, qid|
          run_ids << qid
        end
        status = res['status']


        # Send result call
        loop do

          # If a call for results is not ready, save the execution ID for the next cycle
          ids_in_progress = []
          res = caller.get_rpc_results(component_id, {:execute_ids => run_ids})
          if res['error']
            cdisplay("error: #{res['error']}")
            next
          end

      
          # check results
          res['results'].each do |run_id, hash|
            
            # We have results
            if hash['status'] == "complete"

              # Handle Tuple in here
              data_streams = hash['data']

              # if stream_hash.nil?
              #   cdisplay("error : no results!")
              #   next
              # else
              #   stream_hash.each_pair
              # end

              # Handle each resulting tuple
              data_streams.each_pair do |stream, data_tuples|
                data_tuples.each do |data_tuple|
                  tuple_json = build_tuple_json(data_tuple)

                  #send or enqueue the tuple to all consumers of the stream
                  @__emit_queues.each_pair do |stream, consumers|
                    consumers.each_pair do |consumer, emitter|
                      if emitter[:ready]
                        emit_consumer_tuple(stream, consumer, tuple_json)
                      else
                        @__emit_queues[stream][consumer][:write_queue] << tuple_json
                      end
                    end
                  end

                end
              end

            else
              cdisplay "RPC #{run_id} has not completed... "
              ids_in_progress << run_id
            end
          end
          run_ids = ids_in_progress

          # If no more IDs to run, we are done
          if run_ids.empty?
            break
          end

          # Dont spam the API
          sleep(2)
        end

        # Ask for next tuple
        write_message(@__consumee[:wr_child], NEXT_MESSAGE)


      # End cycle
      elsif obj['command'] 
        case obj["command"]

        # Consumer is ready for a message
        when "next"
          stream = consumer_hash[r][:stream]
          consumer = consumer_hash[r][:consumer]

          @__emit_queues[stream][consumer][:ready] = true
          tuple_json = get_consumer_tuple(stream, consumer)

          # End cycle for consumer if it has processed all tuples
          if tuple_json.nil? && end_cycle_received
            write_stream = get_write_stream(stream, consumer)
            write_message(write_stream, END_CYCLE_MESSAGE)
            consumers_running -= 1
            if consumers_running == 0
              break
            end

            # TODO break if last consumer
          elsif !tuple_json.nil?
            # Emit tuple to consumer
            emit_consumer_tuple(stream, consumer, tuple_json)
            emitted = true
          end

        when "end_cycle"
          end_cycle_received = true
        end
      end

    end

    # Exit after ending consumer cycles
    if consumers_running == 0
      break
    end
  end

end

.select_read_streams(read_streams) ⇒ Object

Return availible reading streams



400
401
402
403
404
405
406
407
408
409
410
411
412
413
# File 'lib/zillabyte/runner/component_operation.rb', line 400

def self.select_read_streams(read_streams)

  rs = []
  read_streams.each do |read_stream|
    @__read_buffered_messages[read_stream] ||= []
    if !@__read_buffered_messages[read_stream].empty?
      rs << read_stream
    end
  end
  return rs unless rs.empty?

  rs, ws, es = IO.select(read_streams, [], [])
  return rs
end

.send_to_consumers(json_obj) ⇒ Object

Send object to every consumer of the operation, regardless of stream



497
498
499
500
501
502
503
504
# File 'lib/zillabyte/runner/component_operation.rb', line 497

def self.send_to_consumers(json_obj)
  @__consumer_pipes.each_pair do |stream, consumers|
    consumers.each_pair do |consumer, pipe| 
      write_message(pipe[:wr_parent], json_obj)
      cdisplay "emitted #{json_obj} to #{consumer}"
    end
  end
end

.truncate_message(msg) ⇒ Object

Format a message for display



475
476
477
478
479
480
481
# File 'lib/zillabyte/runner/component_operation.rb', line 475

def self.truncate_message(msg)
  return msg if(!msg.instance_of?(String))
  t_length = 50 # truncates entries to this length
  m_length = msg.length
  msg_out = m_length > t_length ? msg[0..t_length-3]+"..." : msg
  msg_out
end

.write_message(write_stream, msg) ⇒ Object

Write JSON message



468
469
470
471
472
# File 'lib/zillabyte/runner/component_operation.rb', line 468

def self.write_message(write_stream, msg)
  write_msg = msg.strip + ENDMARKER
  write_stream.write write_msg
  write_stream.flush
end