LoginSignup
1
1

More than 5 years have passed since last update.

HRForecastで歯抜けたデータを補充した

Last updated at Posted at 2014-06-29

なりゆき

  • おいら: DBの接続エラーが累積してHRForecastがデータベースに接続できていない!
  • お嬢: HRForecastのデータ歯抜けてるから補充して
  • おいら: ラジャー!

概要

おいらの所ではcrontab (コード末尾参照) でmysql -eにて値を取得してcurlでHRForecastに記録しています。このcrontabを入力として、任意の期間の値を補充しました。かなり限定された用途にしか使えないと思うのですが、ご参考まで。

上記の状況を想定してWHERE句で期間を限定して値を取得し投げています。また私たちの所では前日との差分も必要となっていたので、そちらのデータも以下のスクリプトで記録するようにしています。

コード

# -*- encoding: utf-8 -*-
require 'pp'
require 'net/http'
require 'uri'
require 'active_support'
require 'active_support/all'

HR_URL = 'http://hf-forecast.awesome-admin.com'
AUTH = ['hogehoge', 'hagehage']

Time.zone = 'UTC'
ENV['TZ'] = 'UTC'

def hr_post(path, data={})
  url = URI(HR_URL)
  http = Net::HTTP.new(url.host, url.port)
  request = Net::HTTP::Post.new(url.path + path)
  request.basic_auth(*AUTH)
  request.set_form_data(data)
  response = http.request(request)
end

begin_date = Date.parse '2014-05-04'
end_date = Date.parse '2014-05-07'

DATA.each_line do |line|
  post_cmd = line.split(' ')[6..-1].join(' ')
  (post_prefix, get_cmd, post_suffix) = post_cmd.split('`')
  (sql_prefix, base_sql_query, sql_suffix) = get_cmd.split('\'')
  next unless base_sql_query
  graph_path = post_suffix.split(' ')[0].split('/')[4..-1].join('/')

  base_sql_query += base_sql_query.index('WHERE') ? ' AND ' : ' WHERE '

  dailies = []
  ((begin_date - 1) .. (end_date + 1)).each do |date|
    filter_query = "created_at <= \"#{date.to_s}\""
    sql_query = base_sql_query + filter_query
    sql_cmd = [sql_prefix, sql_query, sql_suffix].join('\'')
    dailies.push([date, `#{sql_cmd}`.to_i])
  end

  dailies.each do |date, num|
    options = { number: num.to_i , datetime: date.to_s(:db) }
    hr_post("/api/#{graph_path}", options)
  end

  dailies.each_with_index do |value, i|
    date, num = *value
    next if i < 1
    options = { number: num.to_i - dailies[i-1][1].to_i, datetime: date.to_s(:db) }
    hr_post("/api/#{graph_path}-subtract", options)
  end
end
__END__
* * * * * nobody curl -F number=`mysql -hawesome-db.com -uhogehoge -phagehage awesome_db -BN -e 'SELECT COUNT(id) FROM access_log'` http://hf-forecast.awesome-admin.com/api/awesome_service/pv/all 2>&1 | logger -t post_gf -p local0.info
* * * * * nobody curl -F number=`mysql -hawesome-db.com -uhogehoge -phagehage awesome_db -BN -e 'SELECT COUNT(DISTINCT member_id) FROM acess_log'` http://hf-forecast.awesome-admin.com/api/awesome_service/pv/unique 2>&1 | logger -t post_gf -p local0.info

おわりに

もっと汎用的なスクリプト書きたい・・・!crontabのパースとかかなり苦しい感じになってます。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1