I want to achieve a problem, where we manually go and check a webapp/server if it is up/down. I want to build a rails app which can automate this task.
Consider my app url is: HostName:PORT/Route?Params (may or may not have port in url)
I checked 'net/http'
def check_status()
#url='host'
uri = URI(#url)
http = Net::HTTP.new(#url,port)
response = http.request_get('/<route>?<params>')
if response == Net::HTTPSuccess
#result='Running'
else
#result='Not Running'
end
end
I am facing error at ,
response = http.request_get('/<route>?<params>')
when the app is down throwing 'Failed to open TCP connection to URL' which is correct.
Can you guys help me find some new solution or how can I improve the above implementation?
Since it's working as intended and you just need to handle the error that's returned when the app is down, wrap it in a rescue block.
def check_status()
#url='host'
uri = URI(#url)
http = Net::HTTP.new(#url,port)
begin
response = http.request_get('/<route>?<params>')
rescue TheClassNameOfThisErrorWhenSiteIsDown
#result = 'Not Running'
end
if response == Net::HTTPSuccess
#result='Running'
else
#result='Not Running'
end
end
end
Just came across this old question. Net::HTTP methods get and head don't raise an exception. So use one of these instead.
def up?(site)
Net::HTTP.new(site).head('/').kind_of? Net::HTTPOK
end
up? 'www.google.com' #=> true
Related
I am using RestClient gem to build an API client and the calls to the API are processed by this method here
def call(api_name,api_endpoint,token = nil,*extra_params)
endpoint = fetch_endpoint(api_name,api_endpoint)
params = {}
endpoint['params'].each_with_index { |p,i| params[p] = endpoint['values'][i] }
puts params
if token.nil? then
response = RestClient::Request.execute(method: endpoint['method'], url: endpoint['url'], params: params.to_json)
else
response = RestClient::Request.execute(method: endpoint['method'], url: endpoint['url'], headers: {"Authorization" => "Bearer #{token}"}, params: params.to_json)
end
response
end
As you may see, all I do is mounting a hash with parameters/values for the call and invoking RestClient::Request#execute to get a response.
It happens that some of my tests, like this one
it 'request_autorization' do
obj = SpotifyIntegration.new
response = obj.call('spotify','request_authorization',nil,state: obj.random_state_string)
myjson = JSON.parse(response.body)
expect(myjson).to eq({})
end
are returning a 400 Bad request error, and I really don't know why. Other tests, like this one
it 'my_playlists (with no authorization token)' do
obj = SpotifyIntegration.new
expect {
response = obj.call('spotify','my_playlists')
}.to raise_error(RestClient::Unauthorized,'401 Unauthorized')
end
processed by the same method, run perfectly fine.
Is there any way to see the request sent? I mean, see how RestClient is mount/sending my request to the corresponding API? May be this way I could understand what is happening.
By "see the request" I mean something like
puts RestClient::Request.prepared_request
or
puts RestClient::Request.prepared_url
I've searched the RestClient documentation and found nothing similar, but maybe some of you know how to do this.
You might try using RestClient.log to get more information. Something like:
RestClient.log = STDOUT
WebMock is also a great test framework for HTTP requests. The tests for rest-client itself make a lot of use of WebMock.
I am sending attachments from Redmine to JIRA. This is the code I'm using for it:
if attachments.present?
begin
curl = SynchCurl.get_jira_curl_instance "jira_url"
curl.multipart_form_post = true
curl.headers["X-Atlassian-Token"] = "no-check"
attachments.each do |sa|
curl.http_post(Curl::PostField.file('file', sa.disk_filename, remote_file_name = sa.filename))
end
rescue Exception => e
CommonSynch.manage_jira_errors e
end
end
Now I want to check if the attachments are being saved on JIRA via Easy Callbacks to show the user an error message. I tried with:
curl.on_failure {|easy| puts "Error message"}
And some modifications under the post request, but the callback is always getting a nil value (I modified my code to provoke a 500 response code).
How can I do this?
Sorry if this is a dumb question, im pretty new in RoR. Thanks in advance.
I want to update model via PUT request in Rails app. What would be the best way to do that?
Basically I have:
def method
...
#relation = Relation.find(34)
#relation.name = "new_name"
#relation.save
end
This gives me errors in SQLite ("cannot start a transaction within a transaction").
Switching to put/post should I guess save the problem.. What would be the right way to do it?
So after some time, I actually found the solution. Here is the code for the Resque worker, that updates the Relation model via PUT. Using this method I don't get SQLite busy exception errors.
class VideoCollector
def self.perform(rel_id)
#relation = Relation.find_by_id(rel_id)
#url = Rails.application.routes.url_helpers.relation_url(#relation)
#uri = URI(#url)
#body ={"collected" => "true"}.to_json
request = Net::HTTP::Put.new(#uri.path, initheader = {'Content-Type' =>'application/json'})
request.body = #body
response = Net::HTTP.new(#uri.host, #uri.port).start {|http| http.request(request) }
end
end
Maybe that will be useful to someone.
Just today I've found my fbgraph implementation has started returning a 400 Bad Request error which is causing an internal server error.
The controller looks like:
def fb
fbclient = FBGraph::Client.new(:client_id => 'ID', :secret_id => 'SECRET')
#fbname = fbclient.selection.user('129220333799040').feed.info!['data'][0].from.name
#fbmessage = fbclient.selection.user('129220333799040').feed.info!['data'][0].message
end
How can I check before calling #fbname in my view that I've received a 200 status?
Thanks.
Update: following Devin M's suggestion, I've switched the above action to
def fb
fbclient = FBGraph::Client.new(:client_id => 'ID', :secret_id => 'SECRET')
begin
#fbname = fbclient.selection.user('129220333799040').feed.info!['data'][0].from.name
#fbmessage = fbclient.selection.user('129220333799040').feed.info!['data'][0].message
rescue
#fbname = "Facebook Account"
#fbmessage = "Facebook's API is a nightmare"
end
end
I think that you should write some tests for this, Its hard to work with Facebooks nightmare of an API.
Although if you wanted to catch this error try using that way you can catch the specific error and take some action on it in the rescue portion.
begin
rescue
end
If you want me to take a look at the docs and see what you should catch let me know.
i'm trying to see if a url exists. here is my code for doing so:
validate :registered_domain_name_exists
private
def registered_domain_name_exists
if url and url.match(URI::regexp(%w(http https))) then
begin # check header response
case Net::HTTP.get_response(URI.parse(url))
when Net::HTTPSuccess then true
else errors.add(:url, "URL does not exist") and false
end
rescue # DNS failures
errors.add(:url, "URL does not exist") and false
end
end
end
however, this code is failing. it says http://www.biorad.com is not a valid website. this is absolutely incorrect. Also, knowing that http://www.biorad.com just redirects you to http://www.bio-rad.com/evportal/evolutionPortal.portal i tried this url too, and that also failed. again, i know this can't be possible. what's wrong with my code??
Each of the example urls you gave is a redirect (http status code 301 or 302). Your code is only considering http status code 2xx to be success. Add another case:
when Net::HTTPRedirection then true
UPDATE: Note that using HTTP HEAD instead of GET will transmit less data across the network.
uri = URI.parse(url)
response = Net::HTTP.start(uri.host, uri.port) {|http|
http.head('/')
}