self.listen

in tools/pubsub-ci-email.rb [39:123]


  def self.listen(url, creds, options={})
    debug = options[:debug]
    mtime = File.mtime(__FILE__)
    FileUtils.touch(ALIVE) 
    done = false
    except = nil
    ps_thread = Thread.new do
      begin
        uri = URI.parse(url)
        Net::HTTP.start(uri.host, uri.port,
          open_timeout: 20, read_timeout: 20, ssl_timeout: 20,
          use_ssl: uri.scheme == 'https') do |http|
          request = Net::HTTP::Get.new uri.request_uri
          request.basic_auth(*creds) if creds
          http.request request do |response|
            response.each_header do |h, v|
              puts stamp [h, v].inspect if h.start_with? 'x-' or h == 'server'
            end
            body = ''
            response.read_body do |chunk|
              
              lasttime = File.mtime(ALIVE)
              diff = (Time.now - lasttime).to_i
              if diff > 60
                puts stamp 'HUNG?', diff, lasttime
              end
              FileUtils.touch(ALIVE) 
              body += chunk
              
              
              if chunk.end_with? "\n"
                event = JSON.parse(body.chomp)
                body = ''
                if event['stillalive'] 
                  @restartable = true
                  puts stamp event if debug
                else
                  yield event 
                end
              else
                puts stamp 'Partial chunk' if debug
              end
              unless mtime == File.mtime(__FILE__)
                puts stamp 'File updated' if debug
                @updated = true
                done = true
              end
              break if done
            end 
            puts stamp 'Done reading chunks' if debug
            break if done
          end 
          puts stamp 'Done reading response' if debug
          break if done
        end 
        puts stamp 'Done with start' if debug
      rescue Errno::ECONNREFUSED => e
        @restartable = true
        except = e
        puts stamp e.inspect
        sleep 3
      rescue StandardError => e
        except = e
        puts stamp e.inspect
        puts stamp e.backtrace
      end
      puts stamp 'Done with thread' if debug
    end 
    puts stamp "Pubsub thread started #{url} ..."
    ps_thread.join
    subject = 'Pubsub thread finished %s...' % (@updated ? '(code updated) ' : '')
    puts stamp subject
    mail_notify subject, <<~EOD
    Restartable: 
    Exception: 
    EOD
    if @restartable and ! ARGV.include? '--prompt'
      puts stamp 'restarting'

      
      sleep 1
      exec RbConfig.ruby, __FILE__, *ARGV
    end
  end