module Sqreen::Worker

Public Instance Methods

start(framework) click to toggle source
# File lib/sqreen/worker.rb, line 12
def start(framework)
  Sqreen.log.debug('Starting Sqreen worker thread')

  Thread.new do
    begin
      runner = nil
      Sqreen.log.debug("Reading configuration")
      configuration = Sqreen.config_init(framework)
      framework.sqreen_configuration = configuration
      Sqreen.log.debug("Initializing logs")
      Sqreen.log_init
      Sqreen.log.debug("Starting Sqreen #{Sqreen::VERSION}")
      prevent_startup = Sqreen.framework.prevent_startup
      if !prevent_startup
        logger = Sqreen.log.instance_eval { @logger }
        log_level = logger.send(:format_severity, logger.level)
        log_filename = logger.instance_eval { @logdev.filename }
        warn "process.pid:#{Process.pid} sqreen.log.level:#{log_level} sqreen.log.location:#{log_filename.inspect}"
        runner = Sqreen::Runner.new(configuration, framework)
        runner.run_watcher
        Sqreen.log.info("process.pid:#{Process.pid} sqreen.start:true")
      else
        Sqreen.log.info("process.pid:#{Process.pid} sqreen.start:false cause:#{prevent_startup}")
      end
    rescue Sqreen::TokenNotFoundException
      Sqreen.log.error "Sorry but we couldn't find your Sqreen token.\nYour application is NOT currently protected by Sqreen.\n\nHave you filled your config/sqreen.yml?\n\n"
    rescue Sqreen::TokenInvalidException
      Sqreen.log.error "Sorry but your Sqreen token appears to be invalid.\nYour application is NOT currently protected by Sqreen.\n\nHave you correctly filled your config/sqreen.yml?\n\n"
    rescue Exception => e # rubocop:disable Lint/RescueException
      Sqreen.log.debug("General exception caught: #{e.inspect}")
      Sqreen.log.debug e.backtrace
      if runner
        unless e.is_a?(Sqreen::Unauthorized)
          Sqreen.log.debug("Immediately posting exception for runner #{runner.inspect}")
          runner.session.post_sqreen_exception(Sqreen::RemoteException.new(e))
        end
        begin
          runner.remove_instrumentation
        rescue StandardError => e
          Sqreen.log.debug("Unexpected exception when removing instrumentation: #{e.inspect}")
          Sqreen.log.debug e.backtrace
          Sqreen.log.error("Terminating Sqreen thread")
          return nil
        end
        begin
          runner.logout(false)
        rescue StandardError => e
          Sqreen.log.debug("Unexpected exception when logging out: #{remove_exception.inspect}")
          Sqreen.log.debug(e.backtrace)
          nil
        end
      end
      # Wait a few seconds before retrying
      delay = rand(120)
      Sqreen.log.debug("Sleeping #{delay} seconds before restarting Sqreen thread")
      sleep(delay)
      retry
    end
    Sqreen.log.debug("Shutting down Sqreen #{Sqreen::VERSION}")
  end
end