Commit 039dbfd9 authored by Albin PETIT's avatar Albin PETIT
Browse files

Fix rubocop errors

parent 49eff74d
Pipeline #160967 passed with stages
in 20 minutes and 7 seconds
Lint/RescueException:
Enabled: false
load 'config/deploy' # remove this line to skip loading any of the default tasks
\ No newline at end of file
load 'config/deploy' # remove this line to skip loading any of the default tasks
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
# bugs
gem 'ruby-cute'
gem 'byebug'
gem 'ruby-cute'
end
group :test do
gem 'webmock'
gem 'byebug'
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 'byebug'
gem 'webmock'
end
# 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
# abasu : additional classes introduced to handle all possible exceptions - 02.04.2015
......@@ -42,58 +42,59 @@ 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
# abasu : exception-handlers for client-side exceptions - 02.04.2015
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
# abasu : exception-handlers for client-side exceptions - 02.04.2015
rescue_from UnsupportedMediaType, :with => :server_error # for 415
rescue_from UnsupportedMediaType, with: :server_error # for 415
# abasu : 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
def set_default_format
params[:format] ||= begin
first_mime_type = (
(request.accept || "").split(",")[0] || ""
).split(";")[0]
(request.accept || '').split(',')[0] || ''
).split(';')[0]
Mime::Type.lookup(first_mime_type).to_sym || :g5kjson
end
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)
......@@ -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
# 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,64 +123,63 @@ 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
# 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
......@@ -190,13 +190,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
# ===============
......@@ -207,68 +207,68 @@ class ApplicationController < ActionController::Base
# abasu : If such error conditions become prominent in the the future,
# abasu : 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
......@@ -276,18 +276,21 @@ 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)
response.last_modified = time.utc
end
......
......@@ -17,42 +17,41 @@ require 'resources_controller'
# abasu : changed inheritance of class ClustersController - bug ref 5856 -- 2015.3.19
# from ResourcesController to SitesController
# Logic for changing inheritance : From the perspective of a controller,
# the ClustersController is a special case of a SitesController,
# 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
# abasu : method to return status of a specific cluster - bug ref 5856 -- 2015.03.19
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))