-
Notifications
You must be signed in to change notification settings - Fork 0
/
ui_app.rb
232 lines (211 loc) · 6.99 KB
/
ui_app.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
require 'sinatra'
require 'sinatra/reloader'
require 'json/ext'
require 'haml'
require 'uri'
require 'prometheus/client'
require 'rufus-scheduler'
require 'logger'
require 'faraday'
require 'zipkin-tracer'
require_relative 'helpers'
# Dependent services
POST_SERVICE_HOST ||= ENV['POST_SERVICE_HOST'] || '127.0.0.1'
POST_SERVICE_PORT ||= ENV['POST_SERVICE_PORT'] || '4567'
COMMENT_SERVICE_HOST ||= ENV['COMMENT_SERVICE_HOST'] || '127.0.0.1'
COMMENT_SERVICE_PORT ||= ENV['COMMENT_SERVICE_PORT'] || '4567'
ZIPKIN_ENABLED ||= ENV['ZIPKIN_ENABLED'] || false
POST_URL ||= "http://#{POST_SERVICE_HOST}:#{POST_SERVICE_PORT}"
COMMENT_URL ||= "http://#{COMMENT_SERVICE_HOST}:#{COMMENT_SERVICE_PORT}"
# App version and build info
if File.exist?('VERSION')
VERSION ||= File.read('VERSION').strip
else
VERSION ||= "version_missing"
end
if File.exist?('build_info.txt')
BUILD_INFO = File.readlines('build_info.txt')
else
BUILD_INFO = Array.new(2, "build_info_missing")
end
@@host_info=ENV['HOSTNAME']
@@env_info=ENV['ENV']
# Zipkin opts
set :zipkin_enabled, ZIPKIN_ENABLED
zipkin_config = {
service_name: 'ui_app',
service_port: 9292,
sample_rate: 1,
sampled_as_boolean: false,
log_tracing: true,
json_api_host: 'http://zipkin:9411/api/v1/spans'
}
configure do
# https://github.com/openzipkin/zipkin-ruby#sending-traces-on-incoming-requests
http_client = Faraday.new do |faraday|
faraday.use ZipkinTracer::FaradayHandler
faraday.request :url_encoded # form-encode POST params
# faraday.response :logger
faraday.adapter Faraday.default_adapter # make requests with Net::HTTP
end
set :http_client, http_client
set :bind, '0.0.0.0'
set :server, :puma
set :logging, false
set :mylogger, Logger.new(STDOUT)
enable :sessions
end
if settings.zipkin_enabled?
use ZipkinTracer::RackHandler, zipkin_config
end
# create and register metrics
prometheus = Prometheus::Client.registry
ui_health_gauge = Prometheus::Client::Gauge.new(
:ui_health,
'Health status of UI service'
)
ui_health_post_gauge = Prometheus::Client::Gauge.new(
:ui_health_post_availability,
'Check if Post service is available to UI'
)
ui_health_comment_gauge = Prometheus::Client::Gauge.new(
:ui_health_comment_availability,
'Check if Comment service is available to UI'
)
prometheus.register(ui_health_gauge)
prometheus.register(ui_health_post_gauge)
prometheus.register(ui_health_comment_gauge)
# Schedule health check function
scheduler = Rufus::Scheduler.new
scheduler.every '5s' do
check = JSON.parse(http_healthcheck_handler(POST_URL, COMMENT_URL, VERSION))
set_health_gauge(ui_health_gauge, check['status'])
set_health_gauge(ui_health_post_gauge, check['dependent_services']['post'])
set_health_gauge(ui_health_comment_gauge, check['dependent_services']['comment'])
end
# before each request
before do
session[:flashes] = [] if session[:flashes].class != Array
env['rack.logger'] = settings.mylogger # set custom logger
end
# after each request
after do
request_id = env['REQUEST_ID'] || 'null'
logger.info("service=ui | event=request | path=#{env['REQUEST_PATH']} | " \
"request_id=#{request_id} | " \
"remote_addr=#{env['REMOTE_ADDR']} | " \
"method= #{env['REQUEST_METHOD']} | " \
"response_status=#{response.status}")
end
# show all posts
get '/' do
@title = 'All posts'
begin
@posts = http_request('get', "#{POST_URL}/posts")
rescue StandardError => e
flash_danger('Can\'t show blog posts, some problems with the post ' \
'service. <a href="." class="alert-link">Refresh?</a>')
log_event('error', 'show_all_posts',
"Failed to read from Post service. Reason: #{e.message}")
else
log_event('info', 'show_all_posts',
'Successfully showed the home page with posts')
end
@flashes = session[:flashes]
session[:flashes] = nil
haml :index
end
# show a form for creating a new post
get '/new' do
@title = 'New post'
@flashes = session[:flashes]
session[:flashes] = nil
haml :create
end
# talk to Post service in order to creat a new post
post '/new/?' do
if params['link'] =~ URI::DEFAULT_PARSER.regexp[:ABS_URI]
begin
http_request('post', "#{POST_URL}/add_post", title: params['title'],
link: params['link'],
created_at: Time.now.to_i)
rescue StandardError => e
flash_danger("Can't save your post, some problems with the post service")
log_event('error', 'post_create',
"Failed to create a post. Reason: #{e.message}", params)
else
flash_success('Post successuly published')
log_event('info', 'post_create', 'Successfully created a post', params)
end
redirect '/'
else
flash_danger('Invalid URL')
log_event('warning', 'post_create', 'Invalid URL', params)
redirect back
end
end
# talk to Post service in order to vote on a post
post '/post/:id/vote/:type' do
begin
http_request('post', "#{POST_URL}/vote", id: params[:id],
type: params[:type])
rescue StandardError => e
flash_danger('Can\'t vote, some problems with the post service')
log_event('error', 'vote',
"Failed to vote. Reason: #{e.message}", params)
else
log_event('info', 'vote', 'Successful vote', params)
end
redirect back
end
# show a specific post
get '/post/:id' do
begin
@post = http_request('get', "#{POST_URL}/post/#{params[:id]}")
rescue StandardError => e
log_event('error', 'show_post',
"Counldn't show the post. Reason: #{e.message}", params)
halt 404, 'Not found'
end
begin
@comments = http_request('get', "#{COMMENT_URL}/#{params[:id]}/comments")
rescue StandardError => e
log_event('error', 'show_post',
"Counldn't show the comments. Reason: #{e.message}", params)
flash_danger("Can't show comments, some problems with the comment service")
else
log_event('info', 'show_post',
'Successfully showed the post', params)
end
@flashes = session[:flashes]
session[:flashes] = nil
haml :show
end
# talk to Comment service in order to comment on a post
post '/post/:id/comment' do
begin
http_request('post', "#{COMMENT_URL}/add_comment",
post_id: params[:id],
name: params[:name],
email: params[:email],
created_at: Time.now.to_i,
body: params[:body])
rescue StandardError => e
log_event('error', 'create_comment',
"Counldn't create a comment. Reason: #{e.message}", params)
flash_danger("Can\'t save the comment,
some problems with the comment service")
else
log_event('info', 'create_comment',
'Successfully created a new post', params)
flash_success('Comment successuly published')
end
redirect back
end
# health check endpoint
get '/healthcheck' do
http_healthcheck_handler(POST_URL, COMMENT_URL, VERSION)
end
get '/*' do
halt 404, 'Page not found'
end