Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require 'sinatra'
- require 'sequel'
- require 'yaml'
- require 'rufus-scheduler'
- require 'json'
- # fetch data from the database on a schedule
- class DataFetcher
- def initialize(db)
- @db = db
- @current_status = fetch_current_status
- @historical_status_last_30_min = fetch_historical_status_last_30_min
- setup_scheduler
- end
- attr_reader :current_status, :historical_status_last_30_min
- private
- def setup_scheduler
- scheduler = Rufus::Scheduler.new
- scheduler.every '15s' do
- @current_status = fetch_current_status
- end
- scheduler.every '60s' do
- @historical_status_last_30_min = fetch_historical_status_last_30_min
- end
- end
- def fetch_current_status
- puts 'Fetching current status...'
- result = @db[:current_status].all
- puts "Current status: #{result.inspect}"
- result
- end
- def fetch_historical_status_last_30_min
- puts 'Fetching historical status for the last 30 minutes...'
- result = @db[:historical_status]
- .where { recorded_at > Time.now - (30 * 60) }
- .order(Sequel.desc(:recorded_at))
- .all
- puts "Historical status: #{result.inspect}"
- result
- end
- end
- # Load database configuration and initialize DataFetcher
- config = YAML.load_file('config.yml')['api']
- DB = Sequel.connect(adapter: config['adapter'], host: config['host'], database: config['database'], user: config['user'], password: config['password'], port: config['port'])
- data_fetcher = DataFetcher.new(DB)
- # Sinatra routes
- get '/' do
- current_status = data_fetcher.current_status
- historical_status = data_fetcher.historical_status_last_30_min
- puts "Current status: #{current_status.inspect}"
- puts "Historical status: #{historical_status.inspect}"
- erb :_overall_network_status, locals: {
- active_partial: 'overall_network_status',
- current_status: current_status,
- historical_status: historical_status
- }
- end
- get '/by-server-status' do
- erb :_by_server_status, locals: {
- active_partial: 'by_server_status',
- current_status: data_fetcher.current_status
- }
- end
- get '/status-charts' do
- erb :_status_charts, locals: {
- active_partial: 'status_charts',
- historical_status: data_fetcher.historical_status_last_30_min
- }
- end
- get '/current-status' do
- content_type :json
- data = data_fetcher.current_status.to_json
- puts "Current status JSON: #{data}"
- data
- end
- get '/network-data-last-30-minutes' do
- content_type :json
- data = data_fetcher.historical_status_last_30_min.to_json
- puts "Network data JSON: #{data}"
- data
- end
Advertisement
Add Comment
Please, Sign In to add comment