Class: Zillabyte::Runner::MultilangOperation

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

Overview

Emulate a multilang operation

Constant Summary collapse

HANDSHAKE_MESSAGE =
"{\"pidDir\": \"/tmp\"}\n"
DONE_MESSAGE =
"{\"command\": \"done\"}\n"
NEXT_MESSAGE =
"{\"command\": \"next\"}\n"
BEGIN_CYCLE_MESSAGE =
"{\"command\": \"begin_cycle\"}\n"
END_CYCLE_MESSAGE =
"{\"command\": \"end_cycle\"}\n"
PONG_PREFIX =
"{\"pong\": \""
PONG_SUFFIX =
"\"}\n"
ENDMARKER =
"\nend\n"

Class Method Summary collapse

Class Method Details

.begin_cycle(write_stream, read_stream) ⇒ Object

Instruct multilang to begin cycle



1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
# File 'lib/zillabyte/runner/multilang_operation.rb', line 1038

def self.begin_cycle(write_stream, read_stream)
  begin
    write_message(write_stream, BEGIN_CYCLE_MESSAGE)
    msg = read_message(read_stream)
    obj = Hash[msg]
    if obj["command"] != "done"
      raise "Invalid response from multilang #{msg}"
    end
  rescue Exception => e
    cdisplay(e)
  end
end

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

Build a tuple and format into JSON



1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
# File 'lib/zillabyte/runner/multilang_operation.rb', line 1090

def self.build_tuple_json(tuple, meta = nil, column_aliases = nil)
  meta ||= {}
  column_aliases ||= {}
  values = {}
  tuple.each do |k, v|
   if(k == "id")
     next
   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



1135
1136
1137
# File 'lib/zillabyte/runner/multilang_operation.rb', line 1135

def self.cdisplay(msg)
  @__tester.cdisplay(@__name, msg)
end

.command(arg, ignore_stderr = false) ⇒ Object

Construct a multilang command



1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
# File 'lib/zillabyte/runner/multilang_operation.rb', line 1109

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



1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
# File 'lib/zillabyte/runner/multilang_operation.rb', line 1076

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



1070
1071
1072
# File 'lib/zillabyte/runner/multilang_operation.rb', line 1070

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



1064
1065
1066
# File 'lib/zillabyte/runner/multilang_operation.rb', line 1064

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

.handshake(write_stream, read_stream) ⇒ Object

Handshake connection to multilang



1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
# File 'lib/zillabyte/runner/multilang_operation.rb', line 1025

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



952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
# File 'lib/zillabyte/runner/multilang_operation.rb', line 952

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

    # cdisplay "READMESSAGE: read #{segment.length} bytes, read buffer length : #{@__read_buffer.length}"
    # TODO this include is redundant
    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)
            # cdisplay "READMESSAGE: got hash #{hash}"
          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

       # cdisplay "adding leftovers : \n  #{objs[ends.count..-1]}"
        @__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



18
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
59
60
61
62
# File 'lib/zillabyte/runner/multilang_operation.rb', line 18

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_source()
    when "group_by"
      self.run_group_by()
    when "each"
      self.run_each()
    when "filter"
      self.run_filter()
    when "component"
      Zillabyte::Runner::ComponentOperation.run(node, dir, consumee, consumer_pipes, tester, meta, options = {})
    when "sink"
      self.run_sink()
    else
      cdisplay("invalid operation type #{@__type}")
    end
  rescue => e
    cdisplay e.message
    cdisplay e.backtrace
  end
end

.run_each ⇒ Object



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
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
465
466
467
468
469
470
471
472
473
474
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
514
515
516
517
518
519
520
521
522
523
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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
# File 'lib/zillabyte/runner/multilang_operation.rb', line 394

def self.run_each()

  # 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

  # Setup multilang pipe
  ml_pipe = "#{@__name}_pipe"
  if File.exists?("#{ml_pipe}.in")
    File.delete("#{ml_pipe}.in")
  end
  File.mkfifo("#{ml_pipe}.in")

  cmd = command("--execute_live --name #{@__name} --pipe #{ml_pipe}")
  begin
    # Start the operation... 
    Open3.popen3(cmd) do |ml_input, stdout, stderr, wait_thread|
      begin

        # Multilang output tuples
        ml_output = File.open("#{ml_pipe}.in", "r+")

        # Setup streams from consumers, multilang, and the consumee
        read_streams = consumer_hash.keys.concat [@__consumee[:rd_child], ml_output, stdout]

        # Handshake
        handshake(ml_input, ml_output)

        # Begin cycle
        multilang_queue = []
        mutlilang_count = 0
        end_cycle_received = false


        # Receive and handle messages
        loop do

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

            # Read STDOUT from program straight to user
            if r == stdout
              msg = r.gets
              msg = msg.sub(/\n/, "")
              cdisplay("LOG: #{msg}")
              next
            end

            # Receive an object
            obj = read_message(r)

            if obj["command"] 
              case obj["command"]

              # Multilang emitted a tuple
              when "emit"

                stream = obj["stream"]
               
                # Send or enqueue tuple for each consumer
                tuple_json = build_tuple_json(obj['tuple'], obj['meta'], obj['column_aliases'])

                @__emit_queues[stream].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

              # 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

              # Multilang is done emitting a group of tuples
              when "done" 
                mutlilang_count -= 1                  

                # Send the next tuple to multilang
                if !multilang_queue.empty?
                  write_message(ml_input, multilang_queue.shift)

                # Request next tuple from consumee
                elsif !end_cycle_received
                  write_message(@__consumee[:wr_child], NEXT_MESSAGE)
                  

                # If there are no more messages to send, we are done
                elsif end_cycle_received && mutlilang_count == 0
                  finished = true

                 # End cycle for ready consumers
                  @__emit_queues.each_pair do |stream, consumers|
                    consumers.each_pair do |consumer, emitter|
                      if emitter[:ready]
                        write_stream = get_write_stream(stream, consumer)
                        write_message(write_stream, END_CYCLE_MESSAGE)
                        consumers_running -= 1
                        if consumers_running == 0
                          break
                        end
                      end
                    end
                  end
                end

              # Multilang sent an error message
              when "fail"
                cdisplay("ERROR : #{obj['msg']}")
              
              # Multilang sent a log message
              when "log"
                cdisplay "LOG: #{obj['msg']}"

              # Consumee operation sent signal to end_cycle
              when "end_cycle"
                end_cycle_received = true

                if mutlilang_count == 0
                  @__emit_queues.each_pair do |stream, consumers|
                    consumers.each_pair do |consumer, emitter|                      
                      if emitter[:ready]
                        write_stream = get_write_stream(stream, consumer)
                        write_message(write_stream, END_CYCLE_MESSAGE)
                        consumers_running -= 1
                        if consumers_running == 0
                          break
                        end
                      end
                    end
                  end

                end

              end

            # Received a tuple from consumee
            elsif obj['tuple']
            
              # Send or enqueue to multilang
              mutlilang_count += 1
              if multilang_queue.empty?
                write_message(ml_input, obj.to_json)
              else
                multilang_queue << obj.to_json
              end
            
            # Multilang sent a ping
            elsif obj['ping']
              write_message(ml_input, PONG_PREFIX + "#{Time.now.utc.to_f}" + PONG_SUFFIX)
            end
          end

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

        end
      rescue Errno::EIO
         cdisplay("Errno:EIO error")
      ensure
        # cleanup
        pid = wait_thread[:pid] 
        ml_input.close  
        ml_output.close
        File.delete("#{ml_pipe}.in")
        stdout.close
        stderr.close
        Process.kill('INT', pid)
      end
    end
  rescue PTY::ChildExited
    cdisplay("The child process exited!")
  end
end

.run_filter ⇒ Object



842
843
844
# File 'lib/zillabyte/runner/multilang_operation.rb', line 842

def self.run_filter()
  self.run_each()
end

.run_group_by ⇒ Object



604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
# File 'lib/zillabyte/runner/multilang_operation.rb', line 604

def self.run_group_by()

  # 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

  # Setup groups
  group_by = @__node['group_by']
  group_tuples = {}
  emit_count = 0    # used to track how many emits are expected once groups are sent to multilang
  emitted_tuples = [] # used to send to consumers after once groupings are emitted
  tuple_queue = []

  # Setup multilang pipe
  ml_pipe = "#{@__name}_pipe"
  if File.exists?("#{ml_pipe}.in")
    File.delete("#{ml_pipe}.in")
  end
  File.mkfifo("#{ml_pipe}.in")
  
  cmd = command("--execute_live --name #{@__name} --pipe #{ml_pipe}")
  begin
    # Start the operation... 
    Open3.popen3(cmd) do |ml_input, stdout, stderr, wait_thread|
      begin

        # Multilang output tuples
        ml_output = File.open("#{ml_pipe}.in", "r+")
        # Setup streams from consumers, multilang, and the consumee
        read_streams = consumer_hash.keys.concat [stdout, ml_output, @__consumee[:rd_child]]

        # Handshake
        handshake(ml_input, ml_output)

        # Begin cycle
        end_cycle_received = false
        finished_emitting = false

        # select a stream
        loop do

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

            # Read STDOUT from program straight to user
            if r == stdout
              msg = r.gets
              msg = msg.sub(/\n/, "")
              cdisplay("log: #{msg}")
              next
            end


            # Receive an object
            obj = read_message(r)
          
            if obj["command"] 
              case obj["command"]

              when "done"

                if end_cycle_received
                  tuple_json = tuple_queue.shift
                  if !tuple_json.nil?
                    write_message(ml_input, tuple_json)
                  end
                end

                next

              # Begin aggregation
              when "end_cycle"
                end_cycle_received = true
                read_streams = [ml_output]

                group_tuples.each do |group_tuple, tuples|
                  tuple_queue << "{\"command\": \"begin_group\", \"tuple\": #{group_tuple.to_json}, \"meta\":{}}\n"
                  tuples.each do |t|
                    tuple_queue << "{\"command\": \"aggregate\", #{t}}\n"
                  end
                 tuple_queue << "{\"command\": \"end_group\"}\n"

                  # keep track of how many emits are expected
                  emit_count += 1
                end

                tuple_json = tuple_queue.shift
                if !tuple_json.nil?
                  write_message(ml_input, tuple_json)
                end

              # Multilang has emitted a grouped tuple
              when "emit"
                stream = obj['stream']
                emit_count -= 1
                # Enqueue for consumers
                tuple_json = build_tuple_json(obj['tuple'], obj['meta'], obj['column_aliases'])
                @__emit_queues.each_pair do |stream, consumers|
                  consumers.each_key do |consumer|
                    @__emit_queues[stream][consumer][:write_queue] << tuple_json  
                  end
                end

                # End cycle when done emitting
                if end_cycle_received && emit_count == 0
                  finished_emitting = true
                  break      
                elsif end_cycle_received
                  tuple_json = tuple_queue.shift
                  if !tuple_json.nil?
                    write_message(ml_input, tuple_json)
                  end
                end

              end

            # Received a tuple from operation
            elsif obj["tuple"]
              tuple = obj["tuple"].to_json
              meta = obj["meta"].to_json
              column_aliases = obj["column_aliases"] || {}
              aliases = Hash[column_aliases.map{|h| [h["alias"],h["concrete_name"]]}]
              gt = {}

              # Get the column names to group on
              group_by.each do |field|
                field_name = aliases[field] || field
                gt[field] = obj["tuple"][field_name]
              end

              msg_no_brackets = "\"tuple\": #{tuple}, \"meta\": #{meta}, \"column_aliases\": #{column_aliases.to_json}"

              # Group tuple into existing group or create new group
              if group_tuples[gt]
                group_tuples[gt] << msg_no_brackets
              else
                group_tuples[gt] = [msg_no_brackets]
              end

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

            # Multilang sent a ping
            elsif obj['ping']
              write_message(ml_input, PONG_PREFIX + "#{Time.now.utc.to_f}" + PONG_SUFFIX)
            end
          end

          # Send tuples to consumers
          if finished_emitting && consumers_running > 0

            # 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)
                consumer = consumer_hash[r][:consumer]
                stream = consumer_hash[r][:stream]

                # 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 a consumer, end its cycle
                  if tuple_json.nil?
                    write_stream = get_write_stream(stream, consumer)
                    write_message(write_stream, END_CYCLE_MESSAGE)
                    consumers_running -= 1
                    if consumers_running == 0
                      break
                    end
                  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
            break

          # Exit after ending all consumer cycles
          elsif consumers_running == 0
            break
          end

          
        end
      rescue Errno::EIO
         cdisplay("Errno:EIO error")
      ensure
        # cleanup
        pid = wait_thread[:pid]  
        ml_input.close 
        ml_output.close
        File.delete("#{ml_pipe}.in")
        stdout.close
        stderr.close
        Process.kill('INT', pid)
      end  
    end
  rescue PTY::ChildExited
    cdisplay("The child process exited!")
  end
end

.run_sink ⇒ Object

Send a message to all consumers of the operation



848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
# File 'lib/zillabyte/runner/multilang_operation.rb', line 848

def self.run_sink()
  output = @__options[:output]
  messages = []
  loop do
    # Read messages
    msg = read_message(@__consumee[:rd_child])
    obj = msg

    # Add row
    if obj['tuple']
      messages << msg
      display_json = Hash[obj['tuple'].map{|k, v| [truncate_message(k), truncate_message(v)]}].to_json
      if @__options[:interactive]
        cdisplay "received #{display_json}"
      end
      write_message(@__consumee[:wr_child], NEXT_MESSAGE)

    # End cycle
    elsif obj['command'] && obj['command'] == "end_cycle"
      break
    end
  end

  if messages.empty?
    cdisplay "empty relation"
    cdisplay "use Ctrl-C to exit"
    return
  end

  # Build table
  table = Terminal::Table.new :title => @__name
  csv_str = CSV.generate do |csv|
    header_written = false;
    messages.each do |obj|
      begin

        t = obj['tuple']
        m = obj['meta'] || {}

         if t
          if header_written == false
            keys = [t.keys, m.keys].flatten
            csv << keys
            table << keys
            table << :separator
            header_written = true
          end

          vals = [t.values, m.values].flatten
          csv << vals
          table << vals.flat_map{|v| "#{v}"[0..100]}
        end
      rescue JSON::ParserError
        cdisplay("invalid JSON")
        next
      rescue Exception => e
        cdisplay e
      end
    end
  end

  # Output table
  cdisplay("\n#{table.to_s}")
  cdisplay ""
    
  # Write file
  if output
    filename = "#{output}.csv"
    f = File.open(filename, "w")
    f.write(csv_str)
    f.close()
    cdisplay("output written to #{filename}")
  end
  cdisplay "\n \nPress Ctrl-C to exit"
end

.run_source ⇒ Object



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
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
# File 'lib/zillabyte/runner/multilang_operation.rb', line 65

def self.run_source()

  end_cycle_policy = @__node["end_cycle_policy"]

  # Interactive source
  if @__options[:interactive]
    loop do 

      msg = @__consumee[:rd_child].gets

        # Build tuple
        begin
          tuple = JSON.parse(msg)
        rescue JSON::ParserError 
          cdisplay "Error: invalid JSON"           
          next
        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

  # Source from relation
  elsif @__node['matches'] or @__node["relation"]

    # Query API for rows  
    matches = @__node['matches'] || (@__node["relation"]["query"])
    cdisplay("Fetching remote data...")
    res = @__tester.query_agnostic(matches)
    rows = res["rows"]
    if(rows.nil? or rows.length == 0)
      cdisplay("Could not find data that matches your 'matches' clause")
      exit(-1)
    end
    cdisplay("Received #{rows.length} rows!")

    # Enqueue rows for sending to consumers
    column_aliases = res["column_aliases"]
    rows.each do |tuple|
      tuple_json = build_tuple_json(tuple, nil, column_aliases)

      @__emit_queues.each_pair do |stream, consumers|
        consumers.each_pair do |consumer, emitter|
          emitter[:write_queue] << tuple_json
        end
      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
    
  # Custom source
  else

    # 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

    # Setup multilang pipe
    ml_pipe = "#{@__name}_pipe"
    if File.exists?("#{ml_pipe}.in")
      File.delete("#{ml_pipe}.in")
    end
    File.mkfifo("#{ml_pipe}.in")


    # Spawn multilang process
    cmd = command("--execute_live --name #{@__name} --pipe #{ml_pipe}")
    begin

      Open3.popen3(cmd) do |ml_input, stdout, stderr, wait_thread|
        begin

          # Multilang output tuples
          ml_output = File.open("#{ml_pipe}.in", "r")

          # Setup streams from consumers and multilang
          read_streams = consumer_hash.keys.concat [stdout, ml_output]

          # Handshake
          handshake(ml_input, ml_output)

          # Begin cycle
          begin_cycle(ml_input, ml_output)
          emitted = false
          write_message(ml_input, NEXT_MESSAGE)
          multilang_queue = []
          end_cycle_policy = @__options[:end_cycle_policy]
          end_cycle_received = false

          # Receive and handle messages
          loop do
           
            # Read from a stream
            rs = select_read_streams(read_streams)
            rs.each do |r|

              # Read stdout straight to user
              if r == stdout && consumers_running > 0
                msg = r.gets
                msg = msg.sub(/\n/, "")
                cdisplay("log: #{msg}")
                next
              end

              obj = read_message(r)

              if obj.nil?
                next
              end

              if obj["command"] 
                case obj["command"]

                # Multilang emitted a tuple
                when "emit"

                  stream = obj['stream']
                  # Check for null emit
                  if end_cycle_policy != "explicit"

                    if obj['tuple'].nil?
                      end_cycle_received = true
                    else
                      nil_values = false
                      obj['tuple'].each_value do |v|
                        if v.nil?
                          nil_values = true
                          break       
                        end                     
                      end
                      end_cycle_received = nil_values
                      next unless !end_cycle_received
                    end
                  end

                  # Valid emit
                  emitted = true

                  # Send or enqueue tuple for each consumer
                  tuple_json = build_tuple_json(obj['tuple'], obj['meta'], obj['column_aliases'])

 
                  @__emit_queues[stream].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

                # 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

                # Multilang is done emitting a group of tuples
                when "done"
                  # End cycle if no tuples were emitted
                  if !emitted && end_cycle_policy == "null_emit"
                    end_cycle_received = true
                  else
                    emitted = false
                  end
                
                  # Send the next tuple to multilang
                  if !multilang_queue.empty?
                    write_message(ml_input, multilang_queue.shift)

                  # Request next tuple from mutilang
                  elsif !end_cycle_received
                    write_message(ml_input, NEXT_MESSAGE)

                  # If there are no more messages to send, we are done
                  else end_cycle_received
                    finished = true
                     # End cycle for ready consumers
                    @__emit_queues.each_pair do |stream, consumers|
                      consumers.each_pair do |consumer, emitter|
                        if emitter[:ready]
                          write_stream = get_write_stream(stream, consumer)
                          write_message(write_stream, END_CYCLE_MESSAGE)
                          consumers_running -= 1
                          if consumers_running == 0
                            break
                          end
                        end
                      end

                    end
                  end

                # Multilang sent an error message
                when "fail"
                  cdisplay("ERROR : #{obj['msg']}")
                
                # Multilang sent a log message
                when "log"
                  cdisplay "LOG: #{obj['msg']}"

                # Multilang sent signal to end the cycle
                when "end_cycle"
                  if end_cycle_policy != "explicit"
                    cdisplay "received end_cycle command for non explicit policy"
                    next
                  end
                  end_cycle_received = true

                end
              
              # Multilang sent a ping
              elsif obj['ping']
                write_message(ml_input, PONG_PREFIX + "#{Time.now.utc.to_f}" + PONG_SUFFIX)
              end
            end

            # Exit after ending consumer cycles
            if consumers_running == 0
              return
            end
            
          end
        rescue Errno::EIO
           cdisplay("Errno:EIO error")
        ensure
          # cleanup
          pid = wait_thread[:pid] 
          ml_input.close
          ml_output.close
          File.delete("#{ml_pipe}.in")
          stdout.close
          stderr.close
          Process.kill('INT', pid)
        end
      end
    rescue PTY::ChildExited
      cdisplay("The child process exited!")
    end
  end
end

.select_read_streams(read_streams) ⇒ Object

Return availible reading streams



935
936
937
938
939
940
941
942
943
944
945
946
947
948
# File 'lib/zillabyte/runner/multilang_operation.rb', line 935

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



1053
1054
1055
1056
1057
1058
1059
1060
# File 'lib/zillabyte/runner/multilang_operation.rb', line 1053

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



1015
1016
1017
1018
1019
1020
1021
# File 'lib/zillabyte/runner/multilang_operation.rb', line 1015

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



1008
1009
1010
1011
1012
# File 'lib/zillabyte/runner/multilang_operation.rb', line 1008

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