<commit_before>require File.join(File.dirname(__FILE__), 'config')

require 'sinatra/async'
require 'redis'

require File.join(File.dirname(__FILE__), 'helpers', 'redis')

module Sensu
  class API < Sinatra::Base
    register Sinatra::Async

    def self.run(options={})
      EM::run do
        self.setup(options)
        self.run!(:port => $settings.api.port)

        %w[INT TERM].each do |signal|
          Signal.trap(signal) do
            self.stop(signal)
          end
        end
      end
    end

    def self.setup(options={})
      config = Sensu::Config.new(options)
      $settings = config.settings
      $logger = config.logger || config.open_log
      if options[:daemonize]
        Process.daemonize
      end
      if options[:pid_file]
        Process.write_pid(options[:pid_file])
      end
      $logger.debug('[setup] -- connecting to redis')
      $redis = Redis.connect($settings.redis.to_hash.symbolize_keys)
      $logger.debug('[setup] -- connecting to rabbitmq')
      rabbitmq = AMQP.connect($settings.rabbitmq.to_hash.symbolize_keys)
      $amq = AMQP::Channel.new(rabbitmq)
    end

    def self.stop(signal)
      $logger.warn('[stop] -- stopping sensu api -- ' + signal)
      EM::Timer.new(1) do
        EM::stop_event_loop
      end
    end

    before do
      content_type 'application/json'
    end

    aget '/clients' do
      $logger.debug('[clients] -- ' + request.ip + ' -- GET -- request for client list')
      response = Array.new
      $redis.smembers('clients').callback do |clients|
        unless clients.empty?
          clients.each_with_index do |client, index|
            $redis.get('client:' + client).callback do |client_json|
              response.push(JSON.parse(client_json))
              body response.to_json if index == clients.size - 1
            end
          end
        else
          body response.to_json
        end
      end
    end

    aget '/client/:name' do |client|
      $logger.debug('[client] -- ' + request.ip + ' -- GET -- request for client -- ' + client)
      $redis.get('client:' + client).callback do |client_json|
        status 404 if client_json.nil?
        body client_json
      end
    end

    adelete '/client/:name' do |client|
      $logger.debug('[client] -- ' + request.ip + ' -- DELETE -- request for client -- ' + client)
      $redis.sismember('clients', client).callback do |client_exists|
        if client_exists
          $redis.hgetall('events:' + client).callback do |events|
            events.keys.each do |check_name|
              check = {
                :name => check_name,
                :issued => Time.now.to_i,
                :status => 0,
                :output => 'Client is being removed on request of the API',
                :force_resolve => true
              }
              $amq.queue('results').publish({:client => client, :check => check}.to_json)
            end
            EM::Timer.new(8) do
              $redis.srem('clients', client)
              $redis.del('events:' + client)
              $redis.del('client:' + client)
              $settings.checks.each_key do |check_name|
                $redis.del('history:' + client + ':' + check_name)
              end
            end
            status 204
            body nil
          end
        else
          status 404<commit_msg>[api-delete-client] reduce client deletion delay to 5 seconds, enough time to resolve events<commit_after>require File.join(File.dirname(__FILE__), 'config')

require 'sinatra/async'
require 'redis'

require File.join(File.dirname(__FILE__), 'helpers', 'redis')

module Sensu
  class API < Sinatra::Base
    register Sinatra::Async

    def self.run(options={})
      EM::run do
        self.setup(options)
        self.run!(:port => $settings.api.port)

        %w[INT TERM].each do |signal|
          Signal.trap(signal) do
            self.stop(signal)
          end
        end
      end
    end

    def self.setup(options={})
      config = Sensu::Config.new(options)
      $settings = config.settings
      $logger = config.logger || config.open_log
      if options[:daemonize]
        Process.daemonize
      end
      if options[:pid_file]
        Process.write_pid(options[:pid_file])
      end
      $logger.debug('[setup] -- connecting to redis')
      $redis = Redis.connect($settings.redis.to_hash.symbolize_keys)
      $logger.debug('[setup] -- connecting to rabbitmq')
      rabbitmq = AMQP.connect($settings.rabbitmq.to_hash.symbolize_keys)
      $amq = AMQP::Channel.new(rabbitmq)
    end

    def self.stop(signal)
      $logger.warn('[stop] -- stopping sensu api -- ' + signal)
      EM::Timer.new(1) do
        EM::stop_event_loop
      end
    end

    before do
      content_type 'application/json'
    end

    aget '/clients' do
      $logger.debug('[clients] -- ' + request.ip + ' -- GET -- request for client list')
      response = Array.new
      $redis.smembers('clients').callback do |clients|
        unless clients.empty?
          clients.each_with_index do |client, index|
            $redis.get('client:' + client).callback do |client_json|
              response.push(JSON.parse(client_json))
              body response.to_json if index == clients.size - 1
            end
          end
        else
          body response.to_json
        end
      end
    end

    aget '/client/:name' do |client|
      $logger.debug('[client] -- ' + request.ip + ' -- GET -- request for client -- ' + client)
      $redis.get('client:' + client).callback do |client_json|
        status 404 if client_json.nil?
        body client_json
      end
    end

    adelete '/client/:name' do |client|
      $logger.debug('[client] -- ' + request.ip + ' -- DELETE -- request for client -- ' + client)
      $redis.sismember('clients', client).callback do |client_exists|
        if client_exists
          $redis.hgetall('events:' + client).callback do |events|
            events.keys.each do |check_name|
              check = {
                :name => check_name,
                :issued => Time.now.to_i,
                :status => 0,
                :output => 'Client is being removed on request of the API',
                :force_resolve => true
              }
              $amq.queue('results').publish({:client => client, :check => check}.to_json)
            end
            EM::Timer.new(5) do
              $redis.srem('clients', client)
              $redis.del('events:' + client)
              $redis.del('client:' + client)
              $settings.checks.each_key do |check_name|
                $redis.del('history:' + client + ':' + check_name)
              end
            end
            status 204
            body nil
          end
        else
          status 404
{'fraction_non_alphanumeric': 0.12527798369162343, 'fraction_numerical': 0.004002965159377317, 'mean_word_length': 1.8890792291220557, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5676260', 'n_tokens_mistral': 2048, 'n_tokens_neox': 1982, 'n_words': 451}