Commit de48e465 authored by Samir Noir's avatar Samir Noir 🧀
Browse files

Add rubocop

parent 35ca0253
AllCops:
Exclude:
- 'db/**/*'
- 'config/**/*'
- 'script/**/*'
- 'bin/**/*'
- 'Vagrantfile'
- 'config.ru'
- 'debian/**/*'
- 'vendor/**/*'
Rails:
Enabled: true
#FIXME A lot of useless assignement in spec
Lint/UselessAssignment:
Exclude:
- 'spec/**/*'
Lint/RescueException:
Enabled: false
Style/Encoding:
Enabled: false
#FIXME Use simple quote when no interpolation is needed
Style/StringLiterals:
Enabled: false
#FIXME Usage of {a: 1} instead of {:a => 1}
Style/HashSyntax:
EnforcedStyle: 'no_mixed_keys'
#FIXME A bunch of style error related to space
Layout/SpaceAroundOperators:
Enabled: false
#FIXME Up the value of complexity metrics
Metrics/PerceivedComplexity:
Enabled: false
Metrics/CyclomaticComplexity:
Enabled: false
Style/Documentation:
Enabled: false
Layout/SpaceInsideHashLiteralBraces:
Enabled: false
Layout/SpaceInsideBlockBraces:
Enabled: false
Layout/SpaceAfterComma:
Enabled: false
Layout/IndentationStyle:
Enabled: false
Layout/LeadingCommentSpace:
Enabled: false
Layout/TrailingWhitespace:
Enabled: false
Layout/SpaceBeforeBlockBraces:
Enabled: false
Layout/HashAlignment:
Enabled: false
#FIXME simpler method ?
Metrics/BlockLength:
Exclude:
- 'spec/**/*'
- 'lib/tasks/**/*'
Metrics/MethodLength:
Max: 40
Exclude:
- 'spec/**/*'
- 'lib/tasks/**/*'
Metrics/ClassLength:
Max: 200
Exclude:
- 'spec/**/*'
- 'lib/tasks/**/*'
Layout/LineLength:
Max: 200
Metrics/AbcSize:
Enabled: false
......@@ -28,7 +28,6 @@ group :development do
# for ruby scripts written to replicate
# bugs
gem 'ruby-cute'
gem 'byebug'
end
group :test do
......@@ -40,6 +39,10 @@ group :test do
gem 'simplecov'
gem 'net-ssh', "< 5.0.0" #version as from 5.0.0 require ruby > 2.2.6
gem 'net-ssh-multi'
gem 'byebug'
end
group :development, :test do
gem 'byebug'
gem 'rubocop'
gem 'rubocop-rails'
end
......@@ -58,6 +58,7 @@ GEM
zeitwerk (~> 2.2, >= 2.2.2)
addressable (2.7.0)
public_suffix (>= 2.0.2, < 5.0)
ast (2.4.1)
bootsnap (1.4.6)
msgpack (~> 1.0)
builder (3.2.4)
......@@ -132,6 +133,9 @@ GEM
nio4r (2.5.2)
nokogiri (1.10.10)
mini_portile2 (~> 2.4.0)
parallel (1.19.2)
parser (2.7.1.4)
ast (~> 2.4.1)
pg (1.2.3)
public_suffix (4.0.5)
rack (2.2.3)
......@@ -166,12 +170,15 @@ GEM
method_source
rake (>= 0.8.7)
thor (>= 0.20.3, < 2.0)
rainbow (3.0.0)
rake (13.0.1)
regexp_parser (1.7.1)
rest-client (2.1.0)
http-accept (>= 1.7.0, < 2.0)
http-cookie (>= 1.0.2, < 2.0)
mime-types (>= 1.16, < 4.0)
netrc (~> 0.8)
rexml (3.2.4)
rspec (3.9.0)
rspec-core (~> 3.9.0)
rspec-expectations (~> 3.9.0)
......@@ -195,12 +202,28 @@ GEM
rspec-support (3.9.3)
rspec_junit_formatter (0.3.0)
rspec-core (>= 2, < 4, != 2.12.0)
rubocop (0.88.0)
parallel (~> 1.10)
parser (>= 2.7.1.1)
rainbow (>= 2.2.2, < 4.0)
regexp_parser (>= 1.7)
rexml
rubocop-ast (>= 0.1.0, < 1.0)
ruby-progressbar (~> 1.7)
unicode-display_width (>= 1.4.0, < 2.0)
rubocop-ast (0.1.0)
parser (>= 2.7.0.1)
rubocop-rails (2.6.0)
activesupport (>= 4.2.0)
rack (>= 1.1)
rubocop (>= 0.82.0)
ruby-cute (0.13)
ipaddress (>= 0.8)
json (>= 1.8)
net-ssh-multi (>= 1.2)
rest-client (>= 1.6)
ruby-mysql (2.9.14)
ruby-progressbar (1.10.1)
rugged (1.0.1)
safe_yaml (1.0.5)
sass-rails (6.0.0)
......@@ -247,6 +270,7 @@ GEM
unf (0.1.4)
unf_ext
unf_ext (0.0.7.7)
unicode-display_width (1.7.0)
webmock (3.8.3)
addressable (>= 2.3.6)
crack (>= 0.3.2)
......@@ -280,6 +304,8 @@ DEPENDENCIES
rspec
rspec-rails
rspec_junit_formatter (~> 0.3.0)
rubocop
rubocop-rails
ruby-cute
ruby-mysql
rugged
......
......@@ -55,13 +55,14 @@ class ApplicationController < ActionController::Base
rescue_from PreconditionFailed, :with => :precondition_failed # for 412
# exception-handlers for client-side exceptions
rescue_from UnsupportedMediaType, :with => :server_error # for 415
rescue_from UnsupportedMediaType, :with => :server_error # for 415
# agreed to send exception to server_error (instead of unsupported_media_type)
rescue_from ServerError, :with => :server_error # for 500
rescue_from BadGateway, :with => :bad_gateway # for 502
rescue_from ServerUnavailable, :with => :server_unavailable # for 503
protected
def set_default_format
params[:format] ||= begin
first_mime_type = (
......@@ -74,7 +75,7 @@ class ApplicationController < ActionController::Base
def lookup_credentials
invalid_values = ["", "unknown", "(unknown)"]
cn = request.env["HTTP_#{Rails.my_config(:header_user_cn).gsub("-","_").upcase}"] ||
ENV["HTTP_#{Rails.my_config(:header_user_cn).gsub("-","_").upcase}"]
ENV["HTTP_#{Rails.my_config(:header_user_cn).gsub("-","_").upcase}"]
if cn.nil? || invalid_values.include?(cn)
@credentials = {
:cn => nil,
......@@ -108,13 +109,13 @@ class ApplicationController < ActionController::Base
# Allow the list of "non-error" http codes
allowed_status = [options[:is] || (200..299).to_a].flatten
status = http.code.to_i # get the status from the http response
status = http.code.to_i # get the status from the http response
# hack to make rspec tests working, indeed for a unknown reason, http.uri is
# nil when running the specs suite
http.uri = http.header['Location'] if http.uri.nil?
if status.between?(400, 599) # error status
if status.between?(400, 599) # error status
# http.method always returns nil. Bug?
# msg = "#{http.method} #{http.uri} failed with status #{status}"
msg = "Request to #{http.uri} failed with status #{status}: #{http.body}"
......@@ -122,58 +123,57 @@ class ApplicationController < ActionController::Base
end
case status
when *allowed_status # Status codes (200, ..., 299)
true
when 400
raise BadRequest, msg
when 401
raise AuthorizationRequired, msg
when 403
raise Forbidden, msg
when 404
raise NotFound, msg
when 405
raise MethodNotAllowed, msg
when 406
raise NotAcceptable, msg
when 412
raise PreconditionFailed, msg
when 415
raise UnsupportedMediaType, msg
when 502
raise BadGateway, msg
when 503
raise ServerUnavailable, msg
else
raise ServerError, "Request to #{http.uri.to_s} failed with status #{status}: #{http.body}"
Rails.logger.error msg
when *allowed_status # Status codes (200, ..., 299)
true
when 400
raise BadRequest, msg
when 401
raise AuthorizationRequired, msg
when 403
raise Forbidden, msg
when 404
raise NotFound, msg
when 405
raise MethodNotAllowed, msg
when 406
raise NotAcceptable, msg
when 412
raise PreconditionFailed, msg
when 415
raise UnsupportedMediaType, msg
when 502
raise BadGateway, msg
when 503
raise ServerUnavailable, msg
else
raise ServerError, "Request to #{http.uri} failed with status #{status}: #{http.body}"
end
case status
when *allowed_status # Status codes (200, ..., 299)
true
when 400
raise BadRequest, msg
when 401
raise AuthorizationRequired, msg
when 403
raise Forbidden, msg
when 404
raise NotFound, msg
when 405
raise MethodNotAllowed, msg
when 406
raise NotAcceptable, msg
when 412
raise PreconditionFailed, msg
when 415
raise UnsupportedMediaType, msg
when 502
raise BadGateway, msg
when 503
raise ServerUnavailable, msg
else
raise ServerError, "Request to #{http.uri.to_s} failed with unexpected status #{status}: #{http.body} ; could be a TLS problem"
when *allowed_status # Status codes (200, ..., 299)
true
when 400
raise BadRequest, msg
when 401
raise AuthorizationRequired, msg
when 403
raise Forbidden, msg
when 404
raise NotFound, msg
when 405
raise MethodNotAllowed, msg
when 406
raise NotAcceptable, msg
when 412
raise PreconditionFailed, msg
when 415
raise UnsupportedMediaType, msg
when 502
raise BadGateway, msg
when 503
raise ServerUnavailable, msg
else
raise ServerError, "Request to #{http.uri} failed with unexpected status #{status}: #{http.body} ; could be a TLS problem"
end
end
......@@ -278,6 +278,7 @@ class ApplicationController < ActionController::Base
def allow(*args)
response.headers['Allow'] = args.flatten.map{|m| m.to_s.upcase}.join(",")
end
def vary_on(*args)
response.headers['Vary'] ||= ''
response.headers['Vary'] = [
......@@ -285,9 +286,11 @@ class ApplicationController < ActionController::Base
args
].flatten.join(",")
end
def etag(*args)
response.etag = args.join(".")
end
def last_modified(time)
response.last_modified = time.utc
end
......
......@@ -20,7 +20,6 @@ require 'resources_controller'
# the ClustersController is a special case of a SitesController,
# for specific clusters, insofar that this attribute is limited to the status function
class ClustersController < ResourcesController
# method to return status of a specific cluster - bug 5856
def status
result = {
......@@ -61,10 +60,10 @@ class ClustersController < ResourcesController
links = super(item)
links.push({
"rel" => "status",
"rel" => "status",
"type" => api_media_type(:g5kitemjson),
"href" => uri_to(File.join(resource_path(item["uid"]), "status"))
})
})
links
end
end
......@@ -72,12 +72,12 @@ class DeploymentsController < ApplicationController
dpl = find_item(params[:id])
authorize!(dpl.user_uid)
dpl.base_uri = api_path()
dpl.tls_options=tls_options_for(dpl.base_uri, :out)
dpl.tls_options=tls_options_for(:out)
dpl.user = @credentials[:cn]
begin
dpl.cancel! if dpl.can_cancel?
rescue Exception => e
rescue => e
raise ServerError, "Cannot cancel deployment: #{e.message}"
end
......@@ -106,10 +106,10 @@ class DeploymentsController < ApplicationController
dpl.site_uid = Rails.whoami
dpl.user = @credentials[:cn]
dpl.base_uri = api_path()
dpl.tls_options=tls_options_for(dpl.base_uri, :out)
dpl.tls_options=tls_options_for(:out)
Rails.logger.info "Received deployment = #{dpl.inspect}"
rescue Exception => e
rescue => e
raise BadRequest, "The deployment you are trying to submit is not valid: #{e.message}"
end
raise BadRequest, "The deployment you are trying to submit is not valid: #{dpl.errors.to_a.join("; ")}" unless dpl.valid?
......@@ -119,7 +119,7 @@ class DeploymentsController < ApplicationController
begin
dpl.launch || raise(ServerError,
"#{dpl.errors.full_messages.join("; ")}")
"#{dpl.errors.full_messages.join("; ")}")
rescue Exception => e
raise ServerError, "Cannot launch deployment: #{e.message}"
end
......@@ -148,12 +148,12 @@ class DeploymentsController < ApplicationController
def update
dpl = find_item(params[:id])
dpl.base_uri = api_path()
dpl.tls_options=tls_options_for(dpl.base_uri, :out)
dpl.tls_options=tls_options_for(:out)
dpl.user = 'root' # Ugly hack since no auth is needed for this method on theg5k API
begin
dpl.touch! if dpl.active?
rescue Exception => e
rescue => e
raise ServerError, e.message
end
......@@ -223,10 +223,11 @@ class DeploymentsController < ApplicationController
def find_item(id)
item = Grid5000::Deployment.find_by_uid(id)
raise NotFound, "Couldn't find #{Grid5000::Deployment} with ID=#{id}" if item.nil?
item
end
def api_path(path='')
def api_path(path = '')
uri_to(
File.join(
site_path(params[:site_id]),
......
......@@ -15,7 +15,6 @@
require 'resources_controller'
class EnvironmentsController < ResourcesController
protected
def collection_path
......
......@@ -56,7 +56,7 @@ class JobsController < ApplicationController
render_opts = {:methods => [:resources_by_type, :assigned_nodes]}
respond_to do |format|
format.g5kitemjson { render render_opts.merge(:json => job) }
format.json { render render_opts.merge(:json => job) }
format.json { render render_opts.merge(:json => job) }
end
end
......@@ -74,11 +74,10 @@ class JobsController < ApplicationController
)+"/internal/oarapi/jobs/#{params[:id]}.json",
:out
)
tls_options = tls_options_for(uri, :out)
tls_options = tls_options_for(:out)
headers = { 'Accept' => api_media_type(:json),
'X-Remote-Ident' => @credentials[:cn],
'X-Api-User-Cn' => @credentials[:cn],
}
'X-Api-User-Cn' => @credentials[:cn] }
http = http_request(:delete, uri, tls_options, 10, headers)
continue_if!(http, :is => [200,202,204,404])
......@@ -111,18 +110,18 @@ class JobsController < ApplicationController
job = Grid5000::Job.new(job_params)
Rails.logger.info "Received job = #{job.inspect}"
raise BadRequest, "The job you are trying to submit is not valid: #{job.errors.join("; ")}" unless job.valid?
job_to_send = job.to_hash(:destination => "oar-2.4-submission")
Rails.logger.info "Submitting #{job_to_send.inspect}"
uri = uri_to(
site_path(params[:site_id])+"/internal/oarapi/jobs.json", :out
)
tls_options = tls_options_for(uri, :out)
tls_options = tls_options_for(:out)
headers = { 'X-Remote-Ident' => @credentials[:cn],
'X-Api-User-Cn' => @credentials[:cn],
'Content-Type' => api_media_type(:json),
'Accept' => api_media_type(:json)
}
'Accept' => api_media_type(:json)}
http = http_request(:post, uri, tls_options, 20, headers, job_to_send.to_json)
......
......@@ -15,7 +15,6 @@
require 'resources_controller'
class NetworkEquipmentsController < ResourcesController
protected
def collection_path
......
......@@ -15,7 +15,6 @@
require 'resources_controller'
class NodesController < ResourcesController
protected
def collection_path
......
......@@ -15,7 +15,6 @@
require 'resources_controller'
class PdusController < ResourcesController
protected
def collection_path
......
......@@ -13,7 +13,6 @@
# limitations under the License.
class ResourcesController < ApplicationController
MAX_AGE = 60.seconds
# Return a collection of resources
......@@ -26,6 +25,7 @@ class ResourcesController < ApplicationController
end
protected
def fetch(path)
allow :get; vary_on :accept
Rails.logger.info "Fetching #{path}"
......@@ -37,7 +37,7 @@ class ResourcesController < ApplicationController
raise NotFound, "Cannot find resource #{path}" if object.nil?
if object.has_key?('items')
object['links'] = links_for_collection(object)
object['links'] = links_for_collection
object['items'].each{|item|
item['links'] = links_for_item(item)
}
......@@ -148,49 +148,48 @@ class ResourcesController < ApplicationController
(item.delete('subresources') || []).each do |subresource|
href = uri_to(resource_path(item["uid"]) + "/" + subresource[:name])
links.push({
"rel" => subresource[:name],
"rel" => subresource[:name],
"href" => href,
"type" => api_media_type(:g5kcollectionjson)
})
})
end
links.push({
"rel" => "self",
"rel" => "self",
"type" => api_media_type(:g5kitemjson),
"href" => uri_to(resource_path(item["uid"]))
})
})
links.push({
"rel" => "parent",
"rel" => "parent",
"type" => api_media_type(:g5kitemjson),
"href" => uri_to(parent_path)
})
})
links.push({
"rel" => "version",
"rel" => "version",
"type" => api_media_type(:g5kitemjson),
"href" => uri_to(File.join(resource_path(item["uid"]), "versions", item["version"]))
})
})
links.push({
"rel" => "versions",
"rel" => "versions",
"type" => api_media_type(:g5kcollectionjson),
"href" => uri_to(File.join(resource_path(item["uid"]), "versions"))
})
})
links
end
# Should be overwritten
def links_for_collection(collection)
def links_for_collection
links = []
links.push({
"rel" => "self",
"rel" => "self",
"type" => api_media_type(:g5kcollectionjson),
"href" => uri_to(collection_path)
})
})
links.push({
"rel" => "parent",
"rel" => "parent",
"type" => api_media_type(:g5kitemjson),
"href" => uri_to(parent_path)
}) unless parent_path.blank?
}) unless parent_path.blank?
links
end
end
......@@ -13,14 +13,13 @@
# limitations under the License.
class RootController < ResourcesController
protected
def collection_path
"/"
end