# frozen_string_literal: true # Realiza el deploy de un sitio class DeployJob < ApplicationJob class DeployException < StandardError; end class DeployTimedOutException < DeployException; end # rubocop:disable Metrics/MethodLength def perform(site, notify = true, time = Time.now) ActiveRecord::Base.connection_pool.with_connection do @site = Site.find(site) # Si ya hay una tarea corriendo, aplazar esta. Si estuvo # esperando más de 10 minutos, recuperar el estado anterior. # # Como el trabajo actual se aplaza al siguiente, arrastrar la # hora original para poder ir haciendo timeouts. if @site.building? if 10.minutes.ago >= time notify = false raise DeployTimedOutException, "#{@site.name} la tarea estuvo más de 10 minutos esperando, volviendo al estado original" end DeployJob.perform_in(60, site, notify, time) return end @site.update status: 'building' # Asegurarse que DeployLocal sea el primero! @deployed = { deploy_local: deploy_locally } # No es opcional unless @deployed[:deploy_local][:status] # Hacer fallar la tarea raise DeployException, 'Falló la compilación' end deploy_others rescue DeployException => e notify_exception e ensure @site&.update status: 'waiting' notify_usuaries if notify end end # rubocop:enable Metrics/MethodLength private # @param :exception [StandardError] # @param :deploy [Deploy] def notify_exception(exception, deploy = nil) data = { site: @site.id, deploy: deploy&.type, log: deploy&.build_stats&.last&.log } ExceptionNotifier.notify_exception(exception, data: data) end def deploy_local @deploy_local ||= @site.deploys.find_by(type: 'DeployLocal') end def deploy_locally deploy_local.deploy end def deploy_others @site.deploys.where.not(type: 'DeployLocal').find_each do |d| @deployed[d.type.underscore.to_sym] = d.deploy rescue StandardError => e @deployed[d.type.underscore.to_sym] = false ExceptionNotifier.notify_exception(e, data: { site: site.id, deploy: d.type }) end end def notify_usuaries @site.roles.where(rol: 'usuarie', temporal: false).pluck(:usuarie_id).each do |usuarie| DeployMailer.with(usuarie: usuarie, site: @site.id) .deployed(@deployed) .deliver_now end end end