Skip to content

Instantly share code, notes, and snippets.

@namutaka
Created October 13, 2017 04:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save namutaka/6c062d17d9d5df7015819fd2a10ed615 to your computer and use it in GitHub Desktop.
Save namutaka/6c062d17d9d5df7015819fd2a10ed615 to your computer and use it in GitHub Desktop.
swaggerからAPI定義を読み取ってelastic searchの検索filter条件式を作成する
#!/bin/env ruby
# encoding: utf-8
#
# SwaggerからURLとmethodの定義を取得して
# Elastic Serch(kibana)の検索条件式のJSONを出力します
#
require 'json'
require 'open-uri'
class SwaggerUrlDetector
def initialize(swagger_url)
@swagger_url = swagger_url
end
def setup
@url_spec = open(@swagger_url, 'r:utf-8:utf-8') {|f| JSON.load(f)}
@url_details = {}
@url_spec['apis'].each do |spec|
path = spec['path']
detail = open(@swagger_url + path, 'r:utf-8:utf-8') {|f| JSON.load(f)}
@url_details[spec] = detail
detail['apis'].each {|api|
api_path = api['path']
path_ptn = api_path.gsub(/\{[^\}]+\}/, "[A-z0-9]*").sub(/\/$/, "/?")
api['path_ptn'] = /\/api#{path_ptn}(\?.*)?/
}
end
end
def output_kibana_filters
filters = {}
@url_details.each do |spec, detail|
detail['apis'].each do |api|
api['operations'].each do |ope|
filters["#{spec['description']}-#{ope['nickname']}"] = {
"query" => {
"query_string" => {
"query" => "uri:#{api['path_ptn'].inspect} AND method:#{ope["method"]}",
"analyze_wildcard" => true
}
}
}
end
end
end
puts ({"filters" => filters}).to_json
end
def output_kibana_category_filters
filters = {}
@url_details.each do |spec, detail|
querys = []
detail['apis'].each do |api|
api['operations'].each do |ope|
querys << {
"query_string" => {
"query" => "uri:#{api['path_ptn'].inspect} AND method:#{ope["method"]}",
"analyze_wildcard" => true
}
}
end
end
filters["#{spec['description']}"] = {
"query" => {
"bool" => {
"should" => querys,
"minimum_should_match" => 1
}
}
}
end
puts ({"filters" => filters}).to_json
end
def detect(path, method)
@url_details.each do |spec, detail|
api =
detail['apis'].find {|api|
path =~ api['path_ptn']
}
next if detail_spec.nil?
ope = api['operations'].find {|ope|
method == ope['method']
}
next if ope.nil?
return {spec: spec, detail: api, operation: ope}
end
puts "unknown", path, method
return {spec: {}, detail: {}, operation: {}}
end
end
if $0 == __FILE__
swagger_url = ARGV[0]
u = SwaggerUrlDetector.new(ARGV[swagger_url)
u.setup
puts "APIs filter"
u.output_kibana_filters
puts
puts "Categories filter"
u.output_kibana_category_filters
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment