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

More rubocop

parent 6914efd6
Pipeline #163170 waiting for manual action with stages
in 20 minutes and 39 seconds
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/**/*'
TargetRubyVersion: 2.5
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
source 'https://rubygems.org'
gem 'rake'
gem 'rails', '~> 6.0.2'
gem 'bootsnap', require: false
gem 'rails', '~> 6.0.2'
gem 'rake'
# jQuery is the default JavaScript library as from Rails 3.1
gem 'jquery-rails'
gem 'rack-fiber_pool', '~> 0.9'
gem "mysql2", '~> 0.5.3'
gem "ruby-mysql", :require => "mysql"
gem 'addressable', '~> 2.2'
gem 'thin', '~> 1.7.0'
gem 'state_machines-activerecord'
gem 'syslogger'
gem 'haml', '~> 5.1.2'
gem 'rack-jsonp'
gem 'pg'
gem 'mysql2', '~> 0.5.3'
gem 'nokogiri'
gem 'pg'
gem 'rack-fiber_pool', '~> 0.9'
gem 'rack-jsonp'
gem 'ruby-mysql', require: 'mysql'
gem 'rugged'
gem 'state_machines-activerecord'
gem 'syslogger'
gem 'thin', '~> 1.7.0'
gem 'sass-rails'
gem 'coffee-rails'
gem 'uglifier'
gem 'erubis', '~> 2.7'
gem 'sass-rails'
gem 'uglifier'
group :development do
# for ruby scripts written to replicate
......@@ -31,14 +31,14 @@ group :development do
end
group :test do
gem 'webmock'
gem 'factory_bot_rails'
gem 'net-ssh', '< 5.0.0' # version as from 5.0.0 require ruby > 2.2.6
gem 'net-ssh-multi'
gem 'rspec'
gem 'rspec_junit_formatter', '~> 0.3.0' # for tests generated for Jenkins
gem 'rspec-rails'
gem 'rspec_junit_formatter', '~> 0.3.0' #for tests generated for Jenkins
gem 'factory_bot_rails'
gem 'simplecov'
gem 'net-ssh', "< 5.0.0" #version as from 5.0.0 require ruby > 2.2.6
gem 'net-ssh-multi'
gem 'webmock'
end
group :development, :test do
......
# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
require File.expand_path('../config/application', __FILE__)
require File.expand_path('config/application', __dir__)
require 'rake'
Api::Application.load_tasks
......@@ -2,10 +2,10 @@
# vi: set ft=ruby :
#
Vagrant.require_version ">= 1.8.0"
Vagrant.require_version '>= 1.8.0'
# Vagrantfile API/syntax version. Don't touch unless you know what you're doing!
VAGRANTFILE_API_VERSION = "2"
VAGRANTFILE_API_VERSION = '2'.freeze
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
# All Vagrant configuration is done here. The most common configuration
......@@ -13,21 +13,21 @@ Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
# please see the online documentation at vagrantup.com.
# Every Vagrant virtual environment requires a box to build off of.
config.vm.box = "debian/contrib-buster64"
config.vm.hostname = "g5k-local"
config.vm.box = 'debian/contrib-buster64'
config.vm.hostname = 'g5k-local'
# Create a forwarded port mapping which allows access to a specific port
# within the machine from a port on the host machine. In the example below,
# accessing "localhost:8080" will access port 80 on the guest machine.
# config.vm.network :forwarded_port, guest: 80, host: 8080
config.vm.network :forwarded_port, guest: 3306, host: 13306
config.vm.network :forwarded_port, guest: 5432, host: 15432
config.vm.network :forwarded_port, guest: 3306, host: 13_306
config.vm.network :forwarded_port, guest: 5432, host: 15_432
config.vm.network :forwarded_port, guest: 8000, host: 8000
config.vm.network :forwarded_port, guest: 8080, host: 8080
# Create a private network, which allows host-only access to the machine
# using a specific IP.
config.vm.network :private_network, ip: "192.168.2.10"
config.vm.network :private_network, ip: '192.168.2.10'
# Create a public network, which generally matched to bridged network.
# Bridged networks make the machine appear as another physical device on
......@@ -42,11 +42,11 @@ Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
# the path on the host to the actual folder. The second argument is
# the path on the guest to mount the folder. And the optional third
# argument is a set of non-required options.
if File.exist? "../reference-repository"
if File.exist? '../reference-repository'
# not required for tests
config.vm.synced_folder "../reference-repository", "/home/vagrant/reference-repository"
config.vm.synced_folder '../reference-repository', '/home/vagrant/reference-repository'
end
# Provider-specific configuration so you can fine-tune various
# backing providers for Vagrant. These expose provider-specific options.
# Example for VirtualBox:
......@@ -63,10 +63,10 @@ Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
# information on available options.
#
config.vm.provider :virtualbox do |vb|
#make sure DNS will resolve
vb.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
# make sure DNS will resolve
vb.customize ['modifyvm', :id, '--natdnshostresolver1', 'on']
# disable host IO cache (speeds things up in tests with virtual box 5.2 and debian 8)
vb.customize ["storagectl", :id, "--name", "SATA Controller","--hostiocache", "off"]
vb.customize ['storagectl', :id, '--name', 'SATA Controller', '--hostiocache', 'off']
vb.memory = 2048
vb.cpus = 2
end
......@@ -74,13 +74,11 @@ Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
# Ease access to stats.g5kadmin
config.ssh.forward_agent = true
#Configure git for within the file
if File.exists?("#{Dir.home}/.gitconfig")
config.vm.provision "file", source: "~/.gitconfig", destination: ".gitconfig"
end
# Configure git for within the file
config.vm.provision 'file', source: '~/.gitconfig', destination: '.gitconfig' if File.exist?("#{Dir.home}/.gitconfig")
# Provisioning with shell commands on the VM
config.vm.provision "shell", inline: <<-SHELL
config.vm.provision 'shell', inline: <<-SHELL
#!/bin/bash -x
if ! which pupppet > /dev/null ; then
sed -i s/httpredir/deb/ /etc/apt/sources.list # faster mirror
......@@ -111,12 +109,12 @@ Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
#
config.vm.provision :puppet do |puppet|
puppet.environment = 'development'
puppet.environment_path = "puppet"
puppet.environment_path = 'puppet'
puppet.facter = {
"owner" => ENV['OWNER']||'vagrant',
"workspace" => ENV['WORKSPACE']||'/vagrant',
"developer" => ENV['DEVELOPER']||'ajenkins',
"oardbsite" => ENV['OAR_DB_SITE']||'rennes'
'owner' => ENV['OWNER'] || 'vagrant',
'workspace' => ENV['WORKSPACE'] || '/vagrant',
'developer' => ENV['DEVELOPER'] || 'ajenkins',
'oardbsite' => ENV['OAR_DB_SITE'] || 'rennes'
}
end
......@@ -164,4 +162,3 @@ Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
#
# chef.validation_client_name = "ORGNAME-validator"
end
......@@ -20,7 +20,7 @@ class ApplicationController < ActionController::Base
protect_from_forgery unless: -> { request.format.json? }
before_action :lookup_credentials
before_action :parse_json_payload, :only => [:create, :update, :destroy]
before_action :parse_json_payload, only: %i[create update destroy]
before_action :set_default_format
# additional classes introduced to handle all possible exceptions
......@@ -42,24 +42,24 @@ class ApplicationController < ActionController::Base
class ServerUnavailable < ServerError; end # Error code 503
# This thing must alway come first, or it will override other rescue_from.
rescue_from Exception, :with => :server_error
rescue_from Exception, with: :server_error
# exception-handlers for client-side exceptions
rescue_from BadRequest, :with => :bad_request # for 400
rescue_from AuthorizationRequired, :with => :authorization_required # for 401
rescue_from Forbidden, :with => :forbidden # for 403
rescue_from NotFound, :with => :not_found # for 404
rescue_from ActiveRecord::RecordNotFound, :with => :not_found # for 404
rescue_from MethodNotAllowed, :with => :method_not_allowed # for 405
rescue_from NotAcceptable, :with => :not_acceptable # for 406
rescue_from PreconditionFailed, :with => :precondition_failed # for 412
rescue_from BadRequest, with: :bad_request # for 400
rescue_from AuthorizationRequired, with: :authorization_required # for 401
rescue_from Forbidden, with: :forbidden # for 403
rescue_from NotFound, with: :not_found # for 404
rescue_from ActiveRecord::RecordNotFound, with: :not_found # for 404
rescue_from MethodNotAllowed, with: :method_not_allowed # for 405
rescue_from NotAcceptable, with: :not_acceptable # for 406
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
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
......@@ -68,28 +68,28 @@ class ApplicationController < ActionController::Base
end
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}"]
if cn.nil? || invalid_values.include?(cn)
@credentials = {
:cn => nil,
:privileges => []
}
else
@credentials = {
:cn => cn.downcase,
:privileges => []
}
end
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}"]
@credentials = if cn.nil? || invalid_values.include?(cn)
{
cn: nil,
privileges: []
}
else
{
cn: cn.downcase,
privileges: []
}
end
end
def is_anonymous?
@credentials[:cn]=="anonymous"
@credentials[:cn] == 'anonymous'
end
def ensure_authenticated!
(@credentials[:cn] && @credentials[:cn] != "anonymous") || raise(Forbidden)
(@credentials[:cn] && @credentials[:cn] != 'anonymous') || raise(Forbidden)
end
def authorize!(user_id)
......@@ -106,7 +106,7 @@ class ApplicationController < ActionController::Base
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
# 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?
......@@ -174,7 +174,7 @@ class ApplicationController < ActionController::Base
# Automatically parse JSON payload when request content type is JSON
def parse_json_payload
if request.content_type =~ /application\/.*json/i
if request.content_type =~ %r{application/.*json}i
json = JSON.parse(request.body.read)
params.merge!(json)
end
......@@ -185,13 +185,13 @@ class ApplicationController < ActionController::Base
def render_error(exception, options = {})
log_exception(exception)
message = options[:message] || exception.message
render :plain => message,
:status => options[:status]
render plain: message,
status: options[:status]
end
def log_exception(exception)
Rails.logger.warn exception.message
Rails.logger.debug exception.backtrace.join(";")
Rails.logger.debug exception.backtrace.join(';')
end
# ===============
......@@ -202,68 +202,68 @@ class ApplicationController < ActionController::Base
# If such error conditions become prominent in the the future,
# they should be overloaded in subclasses.
def bad_request(exception)
opts = {:status => 400}
opts[:message] = "Bad Request" if exception.message == exception.class.name
opts = { status: 400 }
opts[:message] = 'Bad Request' if exception.message == exception.class.name
render_error(exception, opts)
end
def authorization_required(exception)
opts = {:status => 401}
opts[:message] = "Authorization Required" if exception.message == exception.class.name
opts = { status: 401 }
opts[:message] = 'Authorization Required' if exception.message == exception.class.name
render_error(exception, opts)
end
def forbidden(exception)
opts = {:status => 403}
opts[:message] = "You are not authorized to access this resource" if exception.message == exception.class.name
opts = { status: 403 }
opts[:message] = 'You are not authorized to access this resource' if exception.message == exception.class.name
render_error(exception, opts)
end
def not_found(exception)
opts = {:status => 404}
opts[:message] = "Not Found" if exception.message == exception.class.name
opts = { status: 404 }
opts[:message] = 'Not Found' if exception.message == exception.class.name
render_error(exception, opts)
end
def method_not_allowed(exception)
opts = {:status => 405}
opts[:message] = "Method Not Allowed" if exception.message == exception.class.name
opts = { status: 405 }
opts[:message] = 'Method Not Allowed' if exception.message == exception.class.name
render_error(exception, opts)
end
def not_acceptable(exception)
opts = {:status => 406}
opts[:message] = "Not Acceptable" if exception.message == exception.class.name
opts = { status: 406 }
opts[:message] = 'Not Acceptable' if exception.message == exception.class.name
render_error(exception, opts)
end
def precondition_failed(exception)
opts = {:status => 412}
opts[:message] = "Precondition Failed" if exception.message == exception.class.name
opts = { status: 412 }
opts[:message] = 'Precondition Failed' if exception.message == exception.class.name
render_error(exception, opts)
end
def unsupported_media_type(exception)
opts = {:status => 415}
opts[:message] = "Unsupported Media Type" if exception.message == exception.class.name
opts = { status: 415 }
opts[:message] = 'Unsupported Media Type' if exception.message == exception.class.name
render_error(exception, opts)
end
def server_error(exception)
opts = {:status => 500}
opts[:message] = "Internal Server Error" if exception.message == exception.class.name
opts = { status: 500 }
opts[:message] = 'Internal Server Error' if exception.message == exception.class.name
render_error(exception, opts)
end
def bad_gateway(exception)
opts = {:status => 502}
opts[:message] = "Bad Gateway" if exception.message == exception.class.name
opts = { status: 502 }
opts[:message] = 'Bad Gateway' if exception.message == exception.class.name
render_error(exception, opts)
end
def server_unavailable(exception)
opts = {:status => 503}
opts[:message] = "Server Unavailable" if exception.message == exception.class.name
opts = { status: 503 }
opts[:message] = 'Server Unavailable' if exception.message == exception.class.name
render_error(exception, opts)
end
......@@ -271,19 +271,19 @@ class ApplicationController < ActionController::Base
# = HTTP Headers =
# ================
def allow(*args)
response.headers['Allow'] = args.flatten.map{|m| m.to_s.upcase}.join(",")
response.headers['Allow'] = args.flatten.map { |m| m.to_s.upcase }.join(',')
end
def vary_on(*args)
response.headers['Vary'] ||= ''
response.headers['Vary'] = [
response.headers['Vary'].split(","),
response.headers['Vary'].split(','),
args
].flatten.join(",")
].flatten.join(',')
end
def etag(*args)
response.etag = args.join(".")
response.etag = args.join('.')
end
def last_modified(time)
......
......@@ -23,28 +23,28 @@ class ClustersController < ResourcesController
# method to return status of a specific cluster - bug 5856
def status
result = {
"uid" => Time.now.to_i,
"links" => [
'uid' => Time.now.to_i,
'links' => [
{
"rel" => "self",
"href" => uri_to(status_site_cluster_path(params[:site_id],params[:id])),
"type" => api_media_type(:g5kitemjson)
'rel' => 'self',
'href' => uri_to(status_site_cluster_path(params[:site_id], params[:id])),
'type' => api_media_type(:g5kitemjson)
},
{
"rel" => "parent",
"href" => uri_to(site_cluster_path(params[:site_id],params[:id])),
"type" => api_media_type(:g5kitemjson)
'rel' => 'parent',
'href' => uri_to(site_cluster_path(params[:site_id], params[:id])),
'type' => api_media_type(:g5kitemjson)
}
]
}
expected_rtypes=['node']
expected_rtypes.push('disk') if params[:disks] != "no"
result.merge!(OAR::Resource.status(:clusters => params[:id], :network_address => params[:network_address], :job_details => params[:job_details], :waiting => params[:waiting], :types => expected_rtypes))
expected_rtypes = ['node']
expected_rtypes.push('disk') if params[:disks] != 'no'
result.merge!(OAR::Resource.status(clusters: params[:id], network_address: params[:network_address], job_details: params[:job_details], waiting: params[:waiting], types: expected_rtypes))
respond_to do |format|
format.g5kitemjson { render :json => result }
format.json { render :json => result }
format.g5kitemjson { render json: result }
format.json { render json: result }
end
end
......@@ -60,9 +60,9 @@ class ClustersController < ResourcesController
links = super(item)
links.push({
"rel" => "status",
"type" => api_media_type(:g5kitemjson),
"href" => uri_to(File.join(resource_path(item["uid"]), "status"))
'rel' => 'status',
'type' => api_media_type(:g5kitemjson),
'href' => uri_to(File.join(resource_path(item['uid']), 'status'))
})
links
end
......
......@@ -22,31 +22,31 @@ class DeploymentsController < ApplicationController
offset = [(params[:offset] || 0).to_i, 0].max
limit = [(params[:limit] || LIMIT).to_i, LIMIT_MAX].min
order = "DESC"
order = "ASC" if params[:reverse] && params[:reverse].to_s == "true"
order = 'DESC'
order = 'ASC' if params[:reverse] && params[:reverse].to_s == 'true'
items = Grid5000::Deployment.order("created_at #{order}")
items = items.where(:user_uid => params[:user]) if params[:user]
items = items.where(:status => params[:status]) if params[:status]
items = items.where(user_uid: params[:user]) if params[:user]
items = items.where(status: params[:status]) if params[:status]
total = items.count
items = items.offset(offset).limit(limit)
items.each{|item|
items.each do |item|
item.links = links_for_item(item)
}
end
result = {
"total" => total,
"offset" => offset,
"items" => items,
"links" => links_for_collection