33
31

More than 5 years have passed since last update.

GithubのWeb Hookを受け取るプロキシサーバー 「Octogate」

Last updated at Posted at 2014-03-03

JenkinsのGithubフックの受け口がどうにも不安定でしかも設定に柔軟性が無い。
せっかくGithubのフックが送ってくれるデータには色々な情報が含まれているのにイマイチ活用し切れない。

というわけで、間に噛ませるプロキシサーバーを作ってみた。

joker1007/octogate

特徴は以下のとおり。

  • Sinatra製でHerokuで簡単に動かせる
  • gemになっていて、コマンド一発で起動できる
  • どこに転送するかの定義をRubyのDSLで記述する

現在は、PushとPullRequestで発生するイベントにのみ対応してます。

フックの情報を元に送ったり送らなかったり、パラメーターにリポジトリやコミットの情報を利用したかったので、
設定ファイルの書式を柔軟にした方が良いだろう、ということでRubyで設定のためのDSLを定義しました。
一応、YAMLも考えたんですが、正規表現でリポジトリ名とマッチさせたりとか考えると無理がありそうなので止めました。

利用方法

起動時にコンフィグファイルやポートを指定して起動します。

設定ファイルの内容はこんな感じで書きます。

token "token_string"

target "jenkins" do
  hook_type [:push]
  url "http://targethost.dev/job/JobName"
  http_method :post

  parameter_type :query
  params key1: "value1", key2: "value2"

  match ->(event) {
    event.ref =~ /master/
  }
end
# if event type is push and event.ref contains "master",
# octogate requests "http://targethost.dev/job/JobName" via POST method, request body is {key1: "value1, key2: "value2"} params

target "json_params" do
  hook_type [:push, :pull_request]
  url "http://targethost.dev/job/JobName"
  http_method :post

  parameter_type :json
  params key1: "value1", key2: "value2"

  match ->(event) {
    case event
    when Octogate::Event::PullRequest
      event.try(:pull_request).try(:head).try(:ref) =~ /json_params/
    when Octogate::Event::Push
      event.ref =~ /json_params/
    end
  }
end
# if event type is push or pull_request, and ref name contains "json_params",
# octogate requests "http://targethost.dev/job/JobName" via POST method, body is {key1: "value1, key2: "value2"} as JSON FORMAT


% bundle exec octogate -h
Usage: octogate [options]
    -c config                        Set config file (default = ./config.rb)
    -p port                          Set port number (default = 4567)
    -o address                       Set address to bind (default = 0.0.0.0)

% bundle exec octogate -c config.rb
  # => Endpoint is http://hostname:4567/token_string

適当にアクセスされると少し困るので、エンドポイントには設定ファイルのトークン文字列を利用します。
充分に長いランダムな文字列を設定しておきます。

リポジトリにはもう少し設定例があります。
octogate/spec/config_sample.rb

Herokuでホストする時

適当にディレクトリを作りGemfileを用意します。

% bundle init
Gemfile
gem "octogate"
gem "thin"
bundle install --path .bundle

Procfileを書きます。

Procfile
web: bundle exec octogate -c ./config.rb -p $PORT

上記の例を参考にコンフィグファイルを書き、gitリポジトリを作ります。

% git init .
% echo ".bundle" > .gitignore
% git commit -am "init"

Herokuにアプリを作ってpushします。

% heroku create your-app-name
% git push heroku master

後は、githubのhookポイントにエンドポイントを設定すればOKです。

33
31
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
33
31